From 874ccf0708d0be16aa4c67ed6c05633ff99ce03f Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 5 Nov 2014 10:57:06 -0800 Subject: [PATCH 001/258] add FindLibcuckoo module and instructions for dropping in libcuckoo --- .gitignore | 4 +++ cmake/modules/FindLibcuckoo.cmake | 29 +++++++++++++++++++ libraries/networking/CMakeLists.txt | 5 +++- .../networking/externals/libcuckoo/readme.txt | 14 +++++++++ 4 files changed, 51 insertions(+), 1 deletion(-) create mode 100644 cmake/modules/FindLibcuckoo.cmake create mode 100644 libraries/networking/externals/libcuckoo/readme.txt diff --git a/.gitignore b/.gitignore index 6e6b69cb66..74a5748b85 100644 --- a/.gitignore +++ b/.gitignore @@ -32,5 +32,9 @@ DerivedData interface/external/*/* !interface/external/*/readme.txt +# ignore libraries externals +libraries/*/externals/*/* +!libraries/*/externals/*/readme.txt + # Ignore interfaceCache for Linux users interface/interfaceCache/ diff --git a/cmake/modules/FindLibcuckoo.cmake b/cmake/modules/FindLibcuckoo.cmake new file mode 100644 index 0000000000..d997f25449 --- /dev/null +++ b/cmake/modules/FindLibcuckoo.cmake @@ -0,0 +1,29 @@ +# FindLibCuckoo.cmake +# +# Try to find libcuckoo. +# +# You can provide a LIBCUCKOO_ROOT_DIR which contains src and include directories +# +# Once done this will define +# +# LIBCUCKOO_FOUND - system found libcuckoo +# LIBCUCKOO_INCLUDE_DIRS - the libcuckoo include directory +# +# Created on 5/11/2014 by Stephen Birarda +# Copyright 2014 High Fidelity, Inc. +# +# Distributed under the Apache License, Version 2.0. +# See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +# + +include("${MACRO_DIR}/HifiLibrarySearchHints.cmake") +hifi_library_search_hints("libcuckoo") + +find_path(LIBCUCKOO_INCLUDE_DIRS cuckoohash_map.hh PATH_SUFFIXES libcuckoo HINTS ${LIBCUCKOO_SEARCH_DIRS}) + +include(FindPackageHandleStandardArgs) +find_package_handle_standard_args( + libcuckoo + "Could NOT find libcuckoo. Read libraries/networking/externals/libcuckoo/readme.txt" + LIBCUCKOO_INCLUDE_DIRS +) \ No newline at end of file diff --git a/libraries/networking/CMakeLists.txt b/libraries/networking/CMakeLists.txt index 50f41fe643..cf68bc464a 100644 --- a/libraries/networking/CMakeLists.txt +++ b/libraries/networking/CMakeLists.txt @@ -10,9 +10,12 @@ if (WIN32) target_link_libraries(${TARGET_NAME} ws2_32.lib) endif () -# find OpenSSL +# find required dependencies find_package(OpenSSL REQUIRED) +list(APPEND LIBCUCKOO_ROOT_DIR "${CMAKE_CURRENT_SOURCE_DIR}/externals/libcuckoo") +find_package(libcuckoo REQUIRED) + if (APPLE AND ${OPENSSL_INCLUDE_DIR} STREQUAL "/usr/include") # this is a user on OS X using system OpenSSL, which is going to throw warnings since they're deprecating for their common crypto message(WARNING "The found version of OpenSSL is the OS X system version. This will produce deprecation warnings." diff --git a/libraries/networking/externals/libcuckoo/readme.txt b/libraries/networking/externals/libcuckoo/readme.txt new file mode 100644 index 0000000000..b86f8bc609 --- /dev/null +++ b/libraries/networking/externals/libcuckoo/readme.txt @@ -0,0 +1,14 @@ + +Instructions for adding the libcuckoo library to Interface +Stephen Birarda, November 5, 2014 + +1. Download the libcuckoo ZIP from the High Fidelity libcuckoo fork on Github. + https://github.com/highfidelity/libcuckoo/archive/master.zip + +2. Copy the libcuckoo folder from inside the ZIP to libraries/networking/externals/libcuckoo/. + + You should have the following structure: + + libraries/networking/externals/libcuckoo/libcuckoo/cuckoohash_map.hh + +3. Delete your build directory, run cmake and build, and you should be all set. From c8aeab53ba5022e062a8237ee8e303e99e345a2b Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 5 Nov 2014 11:42:18 -0800 Subject: [PATCH 002/258] changes for C++11 support --- CMakeLists.txt | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index b421040a50..938375ebc1 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -34,6 +34,23 @@ elseif (CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_GNUCXX) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -fno-strict-aliasing") endif(WIN32) +include(CheckCXXCompilerFlag) +CHECK_CXX_COMPILER_FLAG("-std=c++11" COMPILER_SUPPORTS_CXX11) +CHECK_CXX_COMPILER_FLAG("-std=c++0x" COMPILER_SUPPORTS_CXX0X) + +if (COMPILER_SUPPORTS_CXX11) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11") +elseif(COMPILER_SUPPORTS_CXX0X) + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++0x") +else() + message(STATUS "The compiler ${CMAKE_CXX_COMPILER} has no C++11 support. Please use a different C++ compiler.") +endif() + +if (APPLE) + set(CMAKE_XCODE_ATTRIBUTE_CLANG_CXX_LANGUAGE_STANDARD "c++0x") + set(CMAKE_XCODE_ATTRIBUTE_CLANG_CXX_LIBRARY "libc++") +endif () + if (NOT QT_CMAKE_PREFIX_PATH) set(QT_CMAKE_PREFIX_PATH $ENV{QT_CMAKE_PREFIX_PATH}) endif () From 3f442039845a7b30fcf554c9820aab2ef3db5e7c Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 5 Nov 2014 11:42:40 -0800 Subject: [PATCH 003/258] remove getpid usage and replace with Qt solution --- libraries/shared/src/LogHandler.cpp | 18 ++---------------- 1 file changed, 2 insertions(+), 16 deletions(-) diff --git a/libraries/shared/src/LogHandler.cpp b/libraries/shared/src/LogHandler.cpp index a13f3a9dad..6abfd9e787 100644 --- a/libraries/shared/src/LogHandler.cpp +++ b/libraries/shared/src/LogHandler.cpp @@ -12,15 +12,7 @@ #include -#ifdef _WIN32 -#include -#define getpid _getpid -#define getppid _getpid // hack to build -#define pid_t int // hack to build -#elif __linux__ -#include // for getpid() on linux -#endif - +#include #include #include @@ -122,14 +114,8 @@ QString LogHandler::printMessage(LogMsgType type, const QMessageLogContext& cont prefixString.append(QString(" [%1]").arg(dateString)); if (_shouldOutputPID) { - prefixString.append(QString(" [%1").arg(getpid())); + prefixString.append(QString(" [%1]").arg(QCoreApplication::instance()->applicationPid())); - pid_t parentProcessID = getppid(); - if (parentProcessID != 0) { - prefixString.append(QString(":%1]").arg(parentProcessID)); - } else { - prefixString.append("]"); - } } if (!_targetName.isEmpty()) { From 161b3b83d71d6dfb6ff73400dd1196fff1f54d87 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 5 Nov 2014 11:44:56 -0800 Subject: [PATCH 004/258] find an installed version of libcuckoo --- cmake/modules/FindLibcuckoo.cmake | 2 +- libraries/networking/CMakeLists.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/cmake/modules/FindLibcuckoo.cmake b/cmake/modules/FindLibcuckoo.cmake index d997f25449..dad3d8513e 100644 --- a/cmake/modules/FindLibcuckoo.cmake +++ b/cmake/modules/FindLibcuckoo.cmake @@ -19,7 +19,7 @@ include("${MACRO_DIR}/HifiLibrarySearchHints.cmake") hifi_library_search_hints("libcuckoo") -find_path(LIBCUCKOO_INCLUDE_DIRS cuckoohash_map.hh PATH_SUFFIXES libcuckoo HINTS ${LIBCUCKOO_SEARCH_DIRS}) +find_path(LIBCUCKOO_INCLUDE_DIRS libcuckoo/cuckoohash_map.hh PATH_SUFFIXES include HINTS ${LIBCUCKOO_SEARCH_DIRS}) include(FindPackageHandleStandardArgs) find_package_handle_standard_args( diff --git a/libraries/networking/CMakeLists.txt b/libraries/networking/CMakeLists.txt index cf68bc464a..f10b7b2402 100644 --- a/libraries/networking/CMakeLists.txt +++ b/libraries/networking/CMakeLists.txt @@ -22,7 +22,7 @@ if (APPLE AND ${OPENSSL_INCLUDE_DIR} STREQUAL "/usr/include") "\nWe recommend you install a newer version (at least 1.0.1h) in a different directory and set OPENSSL_ROOT_DIR in your env so Cmake can find it.") endif () -include_directories(SYSTEM "${OPENSSL_INCLUDE_DIR}") +include_directories(SYSTEM "${OPENSSL_INCLUDE_DIR}" "${LIBCUCKOO_INCLUDE_DIRS}") # append OpenSSL to our list of libraries to link list(APPEND ${TARGET_NAME}_LIBRARIES_TO_LINK "${OPENSSL_LIBRARIES}") From 118b3133c564a64a547ebcbe2762edee6bc18d68 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 5 Nov 2014 11:45:14 -0800 Subject: [PATCH 005/258] change call to std::abs to abs in SequenceNumberStats --- libraries/networking/src/SequenceNumberStats.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/networking/src/SequenceNumberStats.cpp b/libraries/networking/src/SequenceNumberStats.cpp index f472159164..58c684e16b 100644 --- a/libraries/networking/src/SequenceNumberStats.cpp +++ b/libraries/networking/src/SequenceNumberStats.cpp @@ -68,7 +68,7 @@ SequenceNumberStats::ArrivalInfo SequenceNumberStats::sequenceNumberReceived(qui int expectedInt = (int)expected; // check if the gap between incoming and expected is reasonable, taking possible rollover into consideration - int absGap = std::abs(incomingInt - expectedInt); + int absGap = abs(incomingInt - expectedInt); if (absGap >= UINT16_RANGE - MAX_REASONABLE_SEQUENCE_GAP) { // rollover likely occurred between incoming and expected. // correct the larger of the two so that it's within [-UINT16_RANGE, -1] while the other remains within [0, UINT16_RANGE-1] From bff67077153fc18426b20c62bbc6b5a9c4c88966 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 5 Nov 2014 12:02:05 -0800 Subject: [PATCH 006/258] repair implicit cast of ints into unsigned colorBuffer --- interface/src/ui/TextRenderer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interface/src/ui/TextRenderer.cpp b/interface/src/ui/TextRenderer.cpp index 0db1ab5f00..71f10a8603 100644 --- a/interface/src/ui/TextRenderer.cpp +++ b/interface/src/ui/TextRenderer.cpp @@ -128,7 +128,7 @@ int TextRenderer::draw(int x, int y, const char* str) { leftBottom.x, rightTop.y, ls, tt, }; const int NUM_COLOR_SCALARS_PER_GLYPH = 4; - unsigned int colorBuffer[NUM_COLOR_SCALARS_PER_GLYPH] = { compactColor, compactColor, compactColor, compactColor }; + int colorBuffer[NUM_COLOR_SCALARS_PER_GLYPH] = { compactColor, compactColor, compactColor, compactColor }; gpu::Buffer::Size offset = sizeof(vertexBuffer) * _numGlyphsBatched; gpu::Buffer::Size colorOffset = sizeof(colorBuffer) * _numGlyphsBatched; From b8d0bd5d6bb527c0b560c3d3aa9564b433bbf793 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 5 Nov 2014 13:25:32 -0800 Subject: [PATCH 007/258] allow a target to bubble up required includes --- cmake/macros/LinkHifiLibraries.cmake | 4 ++++ cmake/macros/LinkSharedDependencies.cmake | 10 +++++++++- libraries/networking/CMakeLists.txt | 5 ++++- libraries/networking/src/LimitedNodeList.h | 2 ++ 4 files changed, 19 insertions(+), 2 deletions(-) diff --git a/cmake/macros/LinkHifiLibraries.cmake b/cmake/macros/LinkHifiLibraries.cmake index 9d73963fea..a46023fe9a 100644 --- a/cmake/macros/LinkHifiLibraries.cmake +++ b/cmake/macros/LinkHifiLibraries.cmake @@ -29,6 +29,10 @@ macro(LINK_HIFI_LIBRARIES) get_target_property(LINKED_TARGET_DEPENDENCY_LIBRARIES ${HIFI_LIBRARY} DEPENDENCY_LIBRARIES) list(APPEND ${TARGET_NAME}_LIBRARIES_TO_LINK ${LINKED_TARGET_DEPENDENCY_LIBRARIES}) + # ask the library what its include dependencies are and link them + get_target_property(LINKED_TARGET_DEPENDENCY_INCLUDES ${HIFI_LIBRARY} DEPENDENCY_INCLUDES) + list(APPEND ${TARGET_NAME}_DEPENDENCY_INCLUDES ${LINKED_TARGET_DEPENDENCY_INCLUDES}) + endforeach() endmacro(LINK_HIFI_LIBRARIES) \ No newline at end of file diff --git a/cmake/macros/LinkSharedDependencies.cmake b/cmake/macros/LinkSharedDependencies.cmake index ae478ca530..a73f57dc1d 100644 --- a/cmake/macros/LinkSharedDependencies.cmake +++ b/cmake/macros/LinkSharedDependencies.cmake @@ -17,9 +17,17 @@ macro(LINK_SHARED_DEPENDENCIES) target_link_libraries(${TARGET_NAME} ${${TARGET_NAME}_LIBRARIES_TO_LINK}) endif () + if (${TARGET_NAME}_DEPENDENCY_INCLUDES) + list(REMOVE_DUPLICATES ${TARGET_NAME}_DEPENDENCY_INCLUDES) + + # include those in our own target + include_directories(SYSTEM ${${TARGET_NAME}_DEPENDENCY_INCLUDES}) + endif () + # we've already linked our Qt modules, but we need to bubble them up to parents list(APPEND ${TARGET_NAME}_LIBRARIES_TO_LINK "${${TARGET}_QT_MODULES_TO_LINK}") # set the property on this target so it can be retreived by targets linking to us - set_target_properties(${TARGET_NAME} PROPERTIES DEPENDENCY_LIBRARIES "${${TARGET}_LIBRARIES_TO_LINK}") + set_target_properties(${TARGET_NAME} PROPERTIES DEPENDENCY_LIBRARIES "${${TARGET_NAME}_LIBRARIES_TO_LINK}") + set_target_properties(${TARGET_NAME} PROPERTIES DEPENDENCY_INCLUDES "${${TARGET_NAME}_DEPENDENCY_INCLUDES}") endmacro(LINK_SHARED_DEPENDENCIES) \ No newline at end of file diff --git a/libraries/networking/CMakeLists.txt b/libraries/networking/CMakeLists.txt index f10b7b2402..021401853f 100644 --- a/libraries/networking/CMakeLists.txt +++ b/libraries/networking/CMakeLists.txt @@ -22,10 +22,13 @@ if (APPLE AND ${OPENSSL_INCLUDE_DIR} STREQUAL "/usr/include") "\nWe recommend you install a newer version (at least 1.0.1h) in a different directory and set OPENSSL_ROOT_DIR in your env so Cmake can find it.") endif () -include_directories(SYSTEM "${OPENSSL_INCLUDE_DIR}" "${LIBCUCKOO_INCLUDE_DIRS}") +include_directories(SYSTEM "${OPENSSL_INCLUDE_DIR}") # append OpenSSL to our list of libraries to link list(APPEND ${TARGET_NAME}_LIBRARIES_TO_LINK "${OPENSSL_LIBRARIES}") +# append libcuckoo includes to our list of includes to bubble +list(APPEND ${TARGET_NAME}_DEPENDENCY_INCLUDES "${LIBCUCKOO_INCLUDE_DIRS}") + # call macro to link our dependencies and bubble them up via a property on our target link_shared_dependencies() \ No newline at end of file diff --git a/libraries/networking/src/LimitedNodeList.h b/libraries/networking/src/LimitedNodeList.h index 64495fbd34..9e5610ba4e 100644 --- a/libraries/networking/src/LimitedNodeList.h +++ b/libraries/networking/src/LimitedNodeList.h @@ -28,6 +28,8 @@ #include #include +#include + #include "DomainHandler.h" #include "Node.h" From 35d0d31350a0ade1641e2b9d55df2ed697b5c650 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 5 Nov 2014 13:54:38 -0800 Subject: [PATCH 008/258] change the NodeHash to a cuckoohash_map with CityHash --- cmake/modules/FindLibcuckoo.cmake | 9 +++++++ libraries/networking/CMakeLists.txt | 2 +- libraries/networking/src/LimitedNodeList.h | 8 ++++--- libraries/networking/src/UUIDCityHasher.cpp | 12 ++++++++++ libraries/networking/src/UUIDCityHasher.h | 26 +++++++++++++++++++++ 5 files changed, 53 insertions(+), 4 deletions(-) create mode 100644 libraries/networking/src/UUIDCityHasher.cpp create mode 100644 libraries/networking/src/UUIDCityHasher.h diff --git a/cmake/modules/FindLibcuckoo.cmake b/cmake/modules/FindLibcuckoo.cmake index dad3d8513e..4e87c650c2 100644 --- a/cmake/modules/FindLibcuckoo.cmake +++ b/cmake/modules/FindLibcuckoo.cmake @@ -21,9 +21,18 @@ hifi_library_search_hints("libcuckoo") find_path(LIBCUCKOO_INCLUDE_DIRS libcuckoo/cuckoohash_map.hh PATH_SUFFIXES include HINTS ${LIBCUCKOO_SEARCH_DIRS}) +find_library(CITYHASH_LIBRARY_RELEASE NAME cityhash PATH_SUFFIXES lib HINTS ${LIBCUCKOO_SEARCH_DIRS}) +find_library(CITYHASH_LIBRARY_DEBUG NAME cityhash PATH_SUFFIXES lib HINTS ${LIBCUCKOO_SEARCH_DIRS}) + +include(SelectLibraryConfigurations) +select_library_configurations(CITYHASH) + +set(LIBCUCKOO_LIBRARIES ${CITYHASH_LIBRARY}) + include(FindPackageHandleStandardArgs) find_package_handle_standard_args( libcuckoo "Could NOT find libcuckoo. Read libraries/networking/externals/libcuckoo/readme.txt" LIBCUCKOO_INCLUDE_DIRS + LIBCUCKOO_LIBRARIES ) \ No newline at end of file diff --git a/libraries/networking/CMakeLists.txt b/libraries/networking/CMakeLists.txt index 021401853f..b650c0942c 100644 --- a/libraries/networking/CMakeLists.txt +++ b/libraries/networking/CMakeLists.txt @@ -25,7 +25,7 @@ endif () include_directories(SYSTEM "${OPENSSL_INCLUDE_DIR}") # append OpenSSL to our list of libraries to link -list(APPEND ${TARGET_NAME}_LIBRARIES_TO_LINK "${OPENSSL_LIBRARIES}") +list(APPEND ${TARGET_NAME}_LIBRARIES_TO_LINK "${OPENSSL_LIBRARIES}" "${LIBCUCKOO_LIBRARIES}") # append libcuckoo includes to our list of includes to bubble list(APPEND ${TARGET_NAME}_DEPENDENCY_INCLUDES "${LIBCUCKOO_INCLUDE_DIRS}") diff --git a/libraries/networking/src/LimitedNodeList.h b/libraries/networking/src/LimitedNodeList.h index 9e5610ba4e..100e3a53ea 100644 --- a/libraries/networking/src/LimitedNodeList.h +++ b/libraries/networking/src/LimitedNodeList.h @@ -26,12 +26,13 @@ #include #include #include -#include +#include #include #include "DomainHandler.h" #include "Node.h" +#include "UUIDCityHasher.h" const int MAX_PACKET_SIZE = 1500; @@ -51,9 +52,10 @@ class HifiSockAddr; typedef QSet NodeSet; typedef QSharedPointer SharedNodePointer; -typedef QHash NodeHash; Q_DECLARE_METATYPE(SharedNodePointer) +typedef cuckoohash_map NodeHash; + typedef quint8 PingType_t; namespace PingType { const PingType_t Agnostic = 0; @@ -159,7 +161,7 @@ protected: void changeSocketBufferSizes(int numBytes); QUuid _sessionUUID; - NodeHash _nodeHash; + cuckoohash_map _nodeHash; QMutex _nodeHashMutex; QUdpSocket _nodeSocket; QUdpSocket* _dtlsSocket; diff --git a/libraries/networking/src/UUIDCityHasher.cpp b/libraries/networking/src/UUIDCityHasher.cpp new file mode 100644 index 0000000000..731e287fc0 --- /dev/null +++ b/libraries/networking/src/UUIDCityHasher.cpp @@ -0,0 +1,12 @@ +// +// UUIDCityHasher.cpp +// libraries/networking/src +// +// Created by Stephen Birarda on 2014-11-05. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "UUIDCityHasher.h" diff --git a/libraries/networking/src/UUIDCityHasher.h b/libraries/networking/src/UUIDCityHasher.h new file mode 100644 index 0000000000..e27e3bdf1b --- /dev/null +++ b/libraries/networking/src/UUIDCityHasher.h @@ -0,0 +1,26 @@ +// +// UUIDCityHasher.h +// libraries/networking/src +// +// Created by Stephen Birarda on 2014-11-05. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef hifi_UUIDCityHasher_h +#define hifi_UUIDCityHasher_h + +#include + +#include "UUID.h" + +class UUIDCityHasher { +public: + size_t operator()(const QUuid& key) const { + return CityHash64(key.toRfc4122().constData(), NUM_BYTES_RFC4122_UUID); + } +}; + +#endif // hifi_UUIDCityHasher_h \ No newline at end of file From a492abc3a1410e5eaab76e72a203976c925b69ef Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 5 Nov 2014 14:40:56 -0800 Subject: [PATCH 009/258] complete LimitedNodeList changes for new cuckoo hash --- libraries/networking/src/LimitedNodeList.cpp | 133 ++++++------------- libraries/networking/src/LimitedNodeList.h | 9 +- libraries/networking/src/Node.cpp | 48 ++++--- libraries/networking/src/Node.h | 2 + libraries/networking/src/NodeList.cpp | 6 +- 5 files changed, 79 insertions(+), 119 deletions(-) diff --git a/libraries/networking/src/LimitedNodeList.cpp b/libraries/networking/src/LimitedNodeList.cpp index 043f0621bb..0f86719761 100644 --- a/libraries/networking/src/LimitedNodeList.cpp +++ b/libraries/networking/src/LimitedNodeList.cpp @@ -68,7 +68,6 @@ LimitedNodeList* LimitedNodeList::getInstance() { LimitedNodeList::LimitedNodeList(unsigned short socketListenPort, unsigned short dtlsListenPort) : _sessionUUID(), _nodeHash(), - _nodeHashMutex(QMutex::Recursive), _nodeSocket(this), _dtlsSocket(NULL), _localSockAddr(), @@ -344,18 +343,11 @@ int LimitedNodeList::findNodeAndUpdateWithDataFromPacket(const QByteArray& packe } SharedNodePointer LimitedNodeList::nodeWithUUID(const QUuid& nodeUUID, bool blockingLock) { - const int WAIT_TIME = 10; // wait up to 10ms in the try lock case - SharedNodePointer node; - // if caller wants us to block and guarantee the correct answer, then honor that request - if (blockingLock) { - // this will block till we can get access - QMutexLocker locker(&_nodeHashMutex); - node = _nodeHash.value(nodeUUID); - } else if (_nodeHashMutex.tryLock(WAIT_TIME)) { // some callers are willing to get wrong answers but not block - node = _nodeHash.value(nodeUUID); - _nodeHashMutex.unlock(); + try { + return _nodeHash[nodeUUID]; + } catch (std::out_of_range) { + return SharedNodePointer(); } - return node; } SharedNodePointer LimitedNodeList::sendingNodeForPacket(const QByteArray& packet) { @@ -365,22 +357,15 @@ SharedNodePointer LimitedNodeList::sendingNodeForPacket(const QByteArray& packet return nodeWithUUID(nodeUUID); } -NodeHash LimitedNodeList::getNodeHash() { - QMutexLocker locker(&_nodeHashMutex); - return NodeHash(_nodeHash); -} - void LimitedNodeList::eraseAllNodes() { qDebug() << "Clearing the NodeList. Deleting all nodes in list."; - QMutexLocker locker(&_nodeHashMutex); - - NodeHash::iterator nodeItem = _nodeHash.begin(); - - // iterate the nodes in the list - while (nodeItem != _nodeHash.end()) { - nodeItem = killNodeAtHashIterator(nodeItem); + // iterate the current nodes and note that they are going down + for (auto it = _nodeHash.cbegin(); !it.is_end(); it++) { + emit nodeKilled(it->second); } + + _nodeHash.clear(); } void LimitedNodeList::reset() { @@ -388,20 +373,13 @@ void LimitedNodeList::reset() { } void LimitedNodeList::killNodeWithUUID(const QUuid& nodeUUID) { - QMutexLocker locker(&_nodeHashMutex); - - NodeHash::iterator nodeItemToKill = _nodeHash.find(nodeUUID); - if (nodeItemToKill != _nodeHash.end()) { - killNodeAtHashIterator(nodeItemToKill); + SharedNodePointer matchingNode = nodeWithUUID(nodeUUID); + if (matchingNode) { + emit nodeKilled(matchingNode); + _nodeHash.erase(nodeUUID); } } -NodeHash::iterator LimitedNodeList::killNodeAtHashIterator(NodeHash::iterator& nodeItemToKill) { - qDebug() << "Killed" << *nodeItemToKill.value(); - emit nodeKilled(nodeItemToKill.value()); - return _nodeHash.erase(nodeItemToKill); -} - void LimitedNodeList::processKillNode(const QByteArray& dataByteArray) { // read the node id QUuid nodeUUID = QUuid::fromRfc4122(dataByteArray.mid(numBytesForPacketHeader(dataByteArray), NUM_BYTES_RFC4122_UUID)); @@ -411,62 +389,33 @@ void LimitedNodeList::processKillNode(const QByteArray& dataByteArray) { } SharedNodePointer LimitedNodeList::addOrUpdateNode(const QUuid& uuid, NodeType_t nodeType, - const HifiSockAddr& publicSocket, const HifiSockAddr& localSocket) { - _nodeHashMutex.lock(); - - if (!_nodeHash.contains(uuid)) { - + const HifiSockAddr& publicSocket, const HifiSockAddr& localSocket) { + try { + SharedNodePointer matchingNode = _nodeHash[uuid]; + matchingNode->updateSockets(publicSocket, localSocket); + return matchingNode; + } catch (std::out_of_range) { // we didn't have this node, so add them Node* newNode = new Node(uuid, nodeType, publicSocket, localSocket); SharedNodePointer newNodeSharedPointer(newNode, &QObject::deleteLater); _nodeHash.insert(newNode->getUUID(), newNodeSharedPointer); - _nodeHashMutex.unlock(); - qDebug() << "Added" << *newNode; - + emit nodeAdded(newNodeSharedPointer); - + return newNodeSharedPointer; - } else { - _nodeHashMutex.unlock(); - - return updateSocketsForNode(uuid, publicSocket, localSocket); } } -SharedNodePointer LimitedNodeList::updateSocketsForNode(const QUuid& uuid, - const HifiSockAddr& publicSocket, const HifiSockAddr& localSocket) { - - SharedNodePointer matchingNode = nodeWithUUID(uuid); - - if (matchingNode) { - // perform appropriate updates to this node - QMutexLocker locker(&matchingNode->getMutex()); - - // check if we need to change this node's public or local sockets - if (publicSocket != matchingNode->getPublicSocket()) { - matchingNode->setPublicSocket(publicSocket); - qDebug() << "Public socket change for node" << *matchingNode; - } - - if (localSocket != matchingNode->getLocalSocket()) { - matchingNode->setLocalSocket(localSocket); - qDebug() << "Local socket change for node" << *matchingNode; - } - } - - return matchingNode; -} - unsigned LimitedNodeList::broadcastToNodes(const QByteArray& packet, const NodeSet& destinationNodeTypes) { unsigned n = 0; - - foreach (const SharedNodePointer& node, getNodeHash()) { - // only send to the NodeTypes we are asked to send to. - if (destinationNodeTypes.contains(node->getType())) { - writeDatagram(packet, node); + + SnapshotNodeHash snapshotHash = _nodeHash.snapshot_table(); + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + if (destinationNodeTypes.contains(it->second->getType())) { + writeDatagram(packet, it->second); ++n; } } @@ -510,9 +459,11 @@ QByteArray LimitedNodeList::constructPingReplyPacket(const QByteArray& pingPacke SharedNodePointer LimitedNodeList::soloNodeOfType(char nodeType) { if (memchr(SOLO_NODE_TYPES, nodeType, sizeof(SOLO_NODE_TYPES))) { - foreach (const SharedNodePointer& node, getNodeHash()) { - if (node->getType() == nodeType) { - return node; + SnapshotNodeHash snapshotHash = _nodeHash.snapshot_table(); + + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + if (it->second->getType() == nodeType) { + return it->second; } } } @@ -531,28 +482,20 @@ void LimitedNodeList::resetPacketStats() { } void LimitedNodeList::removeSilentNodes() { - - _nodeHashMutex.lock(); - NodeHash::iterator nodeItem = _nodeHash.begin(); - - while (nodeItem != _nodeHash.end()) { - SharedNodePointer node = nodeItem.value(); - + SnapshotNodeHash snapshotHash = _nodeHash.snapshot_table(); + + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + SharedNodePointer node = it->second; node->getMutex().lock(); - + if ((usecTimestampNow() - node->getLastHeardMicrostamp()) > (NODE_SILENCE_THRESHOLD_MSECS * 1000)) { - // call our private method to kill this node (removes it and emits the right signal) - nodeItem = killNodeAtHashIterator(nodeItem); - } else { - // we didn't kill this node, push the iterator forwards - ++nodeItem; + // call the NodeHash erase to get rid of this node + _nodeHash.erase(it->first); } node->getMutex().unlock(); } - - _nodeHashMutex.unlock(); } const uint32_t RFC_5389_MAGIC_COOKIE = 0x2112A442; diff --git a/libraries/networking/src/LimitedNodeList.h b/libraries/networking/src/LimitedNodeList.h index 100e3a53ea..81daa7ace8 100644 --- a/libraries/networking/src/LimitedNodeList.h +++ b/libraries/networking/src/LimitedNodeList.h @@ -55,6 +55,7 @@ typedef QSharedPointer SharedNodePointer; Q_DECLARE_METATYPE(SharedNodePointer) typedef cuckoohash_map NodeHash; +typedef std::vector > SnapshotNodeHash; typedef quint8 PingType_t; namespace PingType { @@ -95,7 +96,7 @@ public: void(*linkedDataCreateCallback)(Node *); - NodeHash getNodeHash(); + const NodeHash& getNodeHash() { return _nodeHash; } int size() const { return _nodeHash.size(); } SharedNodePointer nodeWithUUID(const QUuid& nodeUUID, bool blockingLock = true); @@ -154,15 +155,11 @@ protected: qint64 writeDatagram(const QByteArray& datagram, const HifiSockAddr& destinationSockAddr, const QUuid& connectionSecret); - - NodeHash::iterator killNodeAtHashIterator(NodeHash::iterator& nodeItemToKill); - void changeSocketBufferSizes(int numBytes); QUuid _sessionUUID; - cuckoohash_map _nodeHash; - QMutex _nodeHashMutex; + NodeHash _nodeHash; QUdpSocket _nodeSocket; QUdpSocket* _dtlsSocket; HifiSockAddr _localSockAddr; diff --git a/libraries/networking/src/Node.cpp b/libraries/networking/src/Node.cpp index c2b35d3b7d..de82dde7f0 100644 --- a/libraries/networking/src/Node.cpp +++ b/libraries/networking/src/Node.cpp @@ -94,30 +94,48 @@ void Node::updateClockSkewUsec(int clockSkewSample) { } void Node::setPublicSocket(const HifiSockAddr& publicSocket) { - if (_activeSocket == &_publicSocket) { - // if the active socket was the public socket then reset it to NULL - _activeSocket = NULL; + if (publicSocket != _publicSocket) { + if (_activeSocket == &_publicSocket) { + // if the active socket was the public socket then reset it to NULL + _activeSocket = NULL; + } + + if (!_publicSocket.isNull()) { + qDebug() << "Public socket change for node" << *this; + } + + _publicSocket = publicSocket; } - - _publicSocket = publicSocket; } void Node::setLocalSocket(const HifiSockAddr& localSocket) { - if (_activeSocket == &_localSocket) { - // if the active socket was the local socket then reset it to NULL - _activeSocket = NULL; + if (localSocket != _localSocket) { + if (_activeSocket == &_localSocket) { + // if the active socket was the local socket then reset it to NULL + _activeSocket = NULL; + } + + if (!_localSocket.isNull()) { + qDebug() << "Local socket change for node" << *this; + } + + _localSocket = localSocket; } - - _localSocket = localSocket; } void Node::setSymmetricSocket(const HifiSockAddr& symmetricSocket) { - if (_activeSocket == &_symmetricSocket) { - // if the active socket was the symmetric socket then reset it to NULL - _activeSocket = NULL; + if (symmetricSocket != _symmetricSocket) { + if (_activeSocket == &_symmetricSocket) { + // if the active socket was the symmetric socket then reset it to NULL + _activeSocket = NULL; + } + + if (!_symmetricSocket.isNull()) { + qDebug() << "Symmetric socket change for node" << *this; + } + + _symmetricSocket = symmetricSocket; } - - _symmetricSocket = symmetricSocket; } void Node::activateLocalSocket() { diff --git a/libraries/networking/src/Node.h b/libraries/networking/src/Node.h index acb6c6f453..05b32d0528 100644 --- a/libraries/networking/src/Node.h +++ b/libraries/networking/src/Node.h @@ -81,6 +81,8 @@ public: const HifiSockAddr& getSymmetricSocket() const { return _symmetricSocket; } virtual void setSymmetricSocket(const HifiSockAddr& symmetricSocket); + void updateSockets(const HifiSockAddr& publicSocket, const HifiSockAddr& localSocket); + const HifiSockAddr* getActiveSocket() const { return _activeSocket; } void activatePublicSocket(); diff --git a/libraries/networking/src/NodeList.cpp b/libraries/networking/src/NodeList.cpp index ff3b86880d..6621a6d2e2 100644 --- a/libraries/networking/src/NodeList.cpp +++ b/libraries/networking/src/NodeList.cpp @@ -449,10 +449,10 @@ void NodeList::pingPunchForInactiveNode(const SharedNodePointer& node) { } void NodeList::pingInactiveNodes() { - foreach (const SharedNodePointer& node, getNodeHash()) { - if (!node->getActiveSocket()) { + for (auto it = _nodeHash.cbegin(); !it.is_end(); it++) { + if (!it->second->getActiveSocket()) { // we don't have an active link to this node, ping it to set that up - pingPunchForInactiveNode(node); + pingPunchForInactiveNode(it->second); } } } From 8a72cdd59d581c8455c7a0d76c494137a3fca10f Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 5 Nov 2014 15:09:54 -0800 Subject: [PATCH 010/258] leverage new libcuckoo hash outside LimitedNodeList --- assignment-client/src/audio/AudioMixer.cpp | 35 ++++++++++++---- assignment-client/src/avatars/AvatarMixer.cpp | 8 +++- .../src/entities/EntityServer.cpp | 11 +++-- .../octree/OctreeInboundPacketProcessor.cpp | 2 +- assignment-client/src/octree/OctreeServer.cpp | 9 ++-- domain-server/src/DomainServer.cpp | 42 ++++++++++++++----- interface/src/Application.cpp | 20 ++++++--- interface/src/MetavoxelSystem.cpp | 13 +++++- .../metavoxels/src/MetavoxelClientManager.cpp | 12 +++++- libraries/networking/src/LimitedNodeList.cpp | 11 +++-- libraries/networking/src/LimitedNodeList.h | 4 +- libraries/networking/src/Node.h | 2 - libraries/octree/src/JurisdictionListener.cpp | 8 ++-- .../octree/src/OctreeEditPacketSender.cpp | 28 ++++++++----- libraries/octree/src/OctreeHeadlessViewer.cpp | 10 +++-- libraries/script-engine/src/ScriptEngine.cpp | 6 ++- 16 files changed, 157 insertions(+), 64 deletions(-) diff --git a/assignment-client/src/audio/AudioMixer.cpp b/assignment-client/src/audio/AudioMixer.cpp index 6ca93a7b11..39011b8083 100644 --- a/assignment-client/src/audio/AudioMixer.cpp +++ b/assignment-client/src/audio/AudioMixer.cpp @@ -437,7 +437,12 @@ int AudioMixer::prepareMixForListeningNode(Node* node) { // loop through all other nodes that have sufficient audio to mix int streamsMixed = 0; - foreach (const SharedNodePointer& otherNode, NodeList::getInstance()->getNodeHash()) { + + NodeHashSnapshot snapshotHash = NodeList::getInstance()->getNodeHash().snapshot_table(); + + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + SharedNodePointer otherNode = it->second; + if (otherNode->getLinkedData()) { AudioMixerClientData* otherNodeClientData = (AudioMixerClientData*) otherNode->getLinkedData(); @@ -480,7 +485,11 @@ void AudioMixer::readPendingDatagram(const QByteArray& receivedPacket, const Hif QByteArray packet = receivedPacket; populatePacketHeader(packet, PacketTypeMuteEnvironment); - foreach (const SharedNodePointer& node, nodeList->getNodeHash()) { + NodeHashSnapshot snapshotHash = nodeList->getNodeHash().snapshot_table(); + + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + SharedNodePointer node = it->second; + if (node->getType() == NodeType::Agent && node->getActiveSocket() && node->getLinkedData() && node != nodeList->sendingNodeForPacket(receivedPacket)) { nodeList->writeDatagram(packet, packet.size(), node); } @@ -548,8 +557,10 @@ void AudioMixer::sendStatsPacket() { NodeList* nodeList = NodeList::getInstance(); int clientNumber = 0; - foreach (const SharedNodePointer& node, nodeList->getNodeHash()) { - + + NodeHashSnapshot snapshotHash = nodeList->getNodeHash().snapshot_table(); + + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { // if we're too large, send the packet if (sizeOfStats > TOO_BIG_FOR_MTU) { nodeList->sendStatsToDomainServer(statsObject2); @@ -559,9 +570,9 @@ void AudioMixer::sendStatsPacket() { } clientNumber++; - AudioMixerClientData* clientData = static_cast(node->getLinkedData()); + AudioMixerClientData* clientData = static_cast(it->second->getLinkedData()); if (clientData) { - QString property = "jitterStats." + node->getUUID().toString(); + QString property = "jitterStats." + it->first.toString(); QString value = clientData->getAudioStreamStatsString(); statsObject2[qPrintable(property)] = value; somethingToSend = true; @@ -706,7 +717,11 @@ void AudioMixer::run() { _lastPerSecondCallbackTime = now; } - foreach (const SharedNodePointer& node, nodeList->getNodeHash()) { + NodeHashSnapshot snapshotHash = nodeList->getNodeHash().snapshot_table(); + + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + SharedNodePointer node = it->second; + if (node->getLinkedData()) { AudioMixerClientData* nodeData = (AudioMixerClientData*)node->getLinkedData(); @@ -873,7 +888,11 @@ void AudioMixer::perSecondActions() { _timeSpentPerHashMatchCallStats.getWindowSum() / WINDOW_LENGTH_USECS * 100.0, _timeSpentPerHashMatchCallStats.getCurrentIntervalSum() / USECS_PER_SECOND * 100.0); - foreach(const SharedNodePointer& node, NodeList::getInstance()->getNodeHash()) { + NodeHashSnapshot snapshotHash = NodeList::getInstance()->getNodeHash().snapshot_table(); + + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + SharedNodePointer node = it->second; + if (node->getLinkedData()) { AudioMixerClientData* nodeData = (AudioMixerClientData*)node->getLinkedData(); diff --git a/assignment-client/src/avatars/AvatarMixer.cpp b/assignment-client/src/avatars/AvatarMixer.cpp index 3ec7c5cfbf..3c2fa92c7c 100644 --- a/assignment-client/src/avatars/AvatarMixer.cpp +++ b/assignment-client/src/avatars/AvatarMixer.cpp @@ -122,7 +122,9 @@ void AvatarMixer::broadcastAvatarData() { AvatarMixerClientData* nodeData = NULL; AvatarMixerClientData* otherNodeData = NULL; - foreach (const SharedNodePointer& node, nodeList->getNodeHash()) { + NodeHashSnapshot snapshotHash = nodeList->getNodeHash().snapshot_table(); + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + SharedNodePointer node = it->second; if (node->getLinkedData() && node->getType() == NodeType::Agent && node->getActiveSocket() && (nodeData = reinterpret_cast(node->getLinkedData()))->getMutex().tryLock()) { ++_sumListeners; @@ -135,7 +137,9 @@ void AvatarMixer::broadcastAvatarData() { // this is an AGENT we have received head data from // send back a packet with other active node data to this node - foreach (const SharedNodePointer& otherNode, nodeList->getNodeHash()) { + NodeHashSnapshot snapshotHash = nodeList->getNodeHash().snapshot_table(); + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + SharedNodePointer otherNode = it->second; if (otherNode->getLinkedData() && otherNode->getUUID() != node->getUUID() && (otherNodeData = reinterpret_cast(otherNode->getLinkedData()))->getMutex().tryLock()) { diff --git a/assignment-client/src/entities/EntityServer.cpp b/assignment-client/src/entities/EntityServer.cpp index 2b7d6873cc..31999f91f7 100644 --- a/assignment-client/src/entities/EntityServer.cpp +++ b/assignment-client/src/entities/EntityServer.cpp @@ -123,9 +123,14 @@ void EntityServer::pruneDeletedEntities() { if (tree->hasAnyDeletedEntities()) { quint64 earliestLastDeletedEntitiesSent = usecTimestampNow() + 1; // in the future - foreach (const SharedNodePointer& otherNode, NodeList::getInstance()->getNodeHash()) { - if (otherNode->getLinkedData()) { - EntityNodeData* nodeData = static_cast(otherNode->getLinkedData()); + + NodeHashSnapshot snapshotHash = NodeList::getInstance()->getNodeHash().snapshot_table(); + + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + SharedNodePointer node = it->second; + + if (node->getLinkedData()) { + EntityNodeData* nodeData = static_cast(node->getLinkedData()); quint64 nodeLastDeletedEntitiesSentAt = nodeData->getLastDeletedEntitiesSentAt(); if (nodeLastDeletedEntitiesSentAt < earliestLastDeletedEntitiesSent) { earliestLastDeletedEntitiesSent = nodeLastDeletedEntitiesSentAt; diff --git a/assignment-client/src/octree/OctreeInboundPacketProcessor.cpp b/assignment-client/src/octree/OctreeInboundPacketProcessor.cpp index bd3a7ceee5..b85eb46ebc 100644 --- a/assignment-client/src/octree/OctreeInboundPacketProcessor.cpp +++ b/assignment-client/src/octree/OctreeInboundPacketProcessor.cpp @@ -248,7 +248,7 @@ int OctreeInboundPacketProcessor::sendNackPackets() { continue; } - const SharedNodePointer& destinationNode = NodeList::getInstance()->getNodeHash().value(nodeUUID); + const SharedNodePointer& destinationNode = NodeList::getInstance()->nodeWithUUID(nodeUUID); // retrieve sequence number stats of node, prune its missing set SequenceNumberStats& sequenceNumberStats = nodeStats.getIncomingEditSequenceNumberStats(); diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index 121cac0273..2b38ce3cdd 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -1137,9 +1137,12 @@ void OctreeServer::aboutToFinish() { qDebug() << qPrintable(_safeServerName) << "server STARTING about to finish..."; qDebug() << qPrintable(_safeServerName) << "inform Octree Inbound Packet Processor that we are shutting down..."; _octreeInboundPacketProcessor->shuttingDown(); - foreach (const SharedNodePointer& node, NodeList::getInstance()->getNodeHash()) { - qDebug() << qPrintable(_safeServerName) << "server about to finish while node still connected node:" << *node; - forceNodeShutdown(node); + + NodeHashSnapshot snapshotHash = NodeList::getInstance()->getNodeHash().snapshot_table(); + + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + qDebug() << qPrintable(_safeServerName) << "server about to finish while node still connected node:" << *it->second; + forceNodeShutdown(it->second); } qDebug() << qPrintable(_safeServerName) << "server ENDING about to finish..."; } diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index dbaaca43fa..5dddfd70dd 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -821,7 +821,10 @@ void DomainServer::sendDomainListToNode(const SharedNodePointer& node, const Hif if (nodeData->isAuthenticated()) { // if this authenticated node has any interest types, send back those nodes as well - foreach (const SharedNodePointer& otherNode, nodeList->getNodeHash()) { + NodeHashSnapshot snapshotHash = nodeList->getNodeHash().snapshot_table(); + + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + SharedNodePointer otherNode = it->second; // reset our nodeByteArray and nodeDataStream QByteArray nodeByteArray; @@ -960,7 +963,10 @@ void DomainServer::readAvailableDatagrams() { void DomainServer::setupPendingAssignmentCredits() { // enumerate the NodeList to find the assigned nodes - foreach (const SharedNodePointer& node, LimitedNodeList::getInstance()->getNodeHash()) { + NodeHashSnapshot snapshotHash = NodeList::getInstance()->getNodeHash().snapshot_table(); + + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + SharedNodePointer node = it->second; DomainServerNodeData* nodeData = reinterpret_cast(node->getLinkedData()); if (!nodeData->getAssignmentUUID().isNull() && !nodeData->getWalletUUID().isNull()) { @@ -1119,7 +1125,13 @@ void DomainServer::sendHeartbeatToDataServer(const QString& networkAddress) { // add the number of currently connected agent users int numConnectedAuthedUsers = 0; - foreach(const SharedNodePointer& node, LimitedNodeList::getInstance()->getNodeHash()) { + + NodeHashSnapshot snapshotHash = NodeList::getInstance()->getNodeHash().snapshot_table(); + + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + + SharedNodePointer node = it->second; + if (node->getLinkedData() && !static_cast(node->getLinkedData())->getUsername().isEmpty()) { ++numConnectedAuthedUsers; } @@ -1242,8 +1254,9 @@ void DomainServer::processDatagram(const QByteArray& receivedPacket, const HifiS parseNodeDataFromByteArray(packetStream, throwawayNodeType, nodePublicAddress, nodeLocalAddress, senderSockAddr); - SharedNodePointer checkInNode = nodeList->updateSocketsForNode(nodeUUID, - nodePublicAddress, nodeLocalAddress); + SharedNodePointer checkInNode = nodeList->nodeWithUUID(nodeUUID); + checkInNode->setPublicSocket(nodePublicAddress); + checkInNode->setLocalSocket(nodeLocalAddress); // update last receive to now quint64 timeNow = usecTimestampNow(); @@ -1425,7 +1438,12 @@ bool DomainServer::handleHTTPRequest(HTTPConnection* connection, const QUrl& url QJsonObject assignedNodesJSON; // enumerate the NodeList to find the assigned nodes - foreach (const SharedNodePointer& node, LimitedNodeList::getInstance()->getNodeHash()) { + NodeHashSnapshot snapshotHash = NodeList::getInstance()->getNodeHash().snapshot_table(); + + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + + SharedNodePointer node = it->second; + DomainServerNodeData* nodeData = reinterpret_cast(node->getLinkedData()); if (!nodeData->getAssignmentUUID().isNull()) { @@ -1489,9 +1507,11 @@ bool DomainServer::handleHTTPRequest(HTTPConnection* connection, const QUrl& url // enumerate the NodeList to find the assigned nodes LimitedNodeList* nodeList = LimitedNodeList::getInstance(); - foreach (const SharedNodePointer& node, nodeList->getNodeHash()) { + NodeHashSnapshot snapshotHash = nodeList->getNodeHash().snapshot_table(); + + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { // add the node using the UUID as the key - nodesJSONArray.append(jsonObjectForNode(node)); + nodesJSONArray.append(jsonObjectForNode(it->second)); } rootJSON["nodes"] = nodesJSONArray; @@ -2023,8 +2043,10 @@ void DomainServer::addStaticAssignmentsToQueue() { bool foundMatchingAssignment = false; // enumerate the nodes and check if there is one with an attached assignment with matching UUID - foreach (const SharedNodePointer& node, LimitedNodeList::getInstance()->getNodeHash()) { - if (node->getUUID() == staticAssignment->data()->getUUID()) { + NodeHashSnapshot snapshotHash = NodeList::getInstance()->getNodeHash().snapshot_table(); + + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + if (it->first == staticAssignment->data()->getUUID()) { foundMatchingAssignment = true; } } diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 6d8b612bc3..f5842ed4c3 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -2405,7 +2405,10 @@ int Application::sendNackPackets() { char packet[MAX_PACKET_SIZE]; // iterates thru all nodes in NodeList - foreach(const SharedNodePointer& node, NodeList::getInstance()->getNodeHash()) { + NodeHashSnapshot snapshotHash = NodeList::getInstance()->getNodeHash().snapshot_table(); + + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + SharedNodePointer node = it->second; if (node->getActiveSocket() && ( node->getType() == NodeType::VoxelServer @@ -2503,7 +2506,13 @@ void Application::queryOctree(NodeType_t serverType, PacketType packetType, Node int inViewServers = 0; int unknownJurisdictionServers = 0; - foreach (const SharedNodePointer& node, NodeList::getInstance()->getNodeHash()) { + NodeList* nodeList = NodeList::getInstance(); + NodeHashSnapshot snapshotHash = nodeList->getNodeHash().snapshot_table(); + + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + + SharedNodePointer node = it->second; + // only send to the NodeTypes that are serverType if (node->getActiveSocket() && node->getType() == serverType) { totalServers++; @@ -2560,10 +2569,9 @@ void Application::queryOctree(NodeType_t serverType, PacketType packetType, Node if (wantExtraDebugging) { qDebug("perServerPPS: %d perUnknownServer: %d", perServerPPS, perUnknownServer); } - - NodeList* nodeList = NodeList::getInstance(); - - foreach (const SharedNodePointer& node, nodeList->getNodeHash()) { + + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + SharedNodePointer node = it->second; // only send to the NodeTypes that are serverType if (node->getActiveSocket() && node->getType() == serverType) { diff --git a/interface/src/MetavoxelSystem.cpp b/interface/src/MetavoxelSystem.cpp index 4c0acc553a..20a7bc906f 100644 --- a/interface/src/MetavoxelSystem.cpp +++ b/interface/src/MetavoxelSystem.cpp @@ -163,7 +163,12 @@ void MetavoxelSystem::render() { } void MetavoxelSystem::refreshVoxelData() { - foreach (const SharedNodePointer& node, NodeList::getInstance()->getNodeHash()) { + NodeHashSnapshot snapshotHash = NodeList::getInstance()->getNodeHash().snapshot_table(); + + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + + SharedNodePointer node = it->second; + if (node->getType() == NodeType::MetavoxelServer) { QMutexLocker locker(&node->getMutex()); MetavoxelSystemClient* client = static_cast(node->getLinkedData()); @@ -685,7 +690,11 @@ MetavoxelClient* MetavoxelSystem::createClient(const SharedNodePointer& node) { } void MetavoxelSystem::guideToAugmented(MetavoxelVisitor& visitor, bool render) { - foreach (const SharedNodePointer& node, NodeList::getInstance()->getNodeHash()) { + NodeHashSnapshot snapshotHash = NodeList::getInstance()->getNodeHash().snapshot_table(); + + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + SharedNodePointer node = it->second; + if (node->getType() == NodeType::MetavoxelServer) { QMutexLocker locker(&node->getMutex()); MetavoxelSystemClient* client = static_cast(node->getLinkedData()); diff --git a/libraries/metavoxels/src/MetavoxelClientManager.cpp b/libraries/metavoxels/src/MetavoxelClientManager.cpp index f1c086da67..7765b8cda2 100644 --- a/libraries/metavoxels/src/MetavoxelClientManager.cpp +++ b/libraries/metavoxels/src/MetavoxelClientManager.cpp @@ -42,7 +42,11 @@ SharedObjectPointer MetavoxelClientManager::findFirstRaySpannerIntersection(cons const glm::vec3& direction, const AttributePointer& attribute, float& distance) { SharedObjectPointer closestSpanner; float closestDistance = FLT_MAX; - foreach (const SharedNodePointer& node, NodeList::getInstance()->getNodeHash()) { + + NodeHashSnapshot snapshotHash = NodeList::getInstance()->getNodeHash().snapshot_table(); + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + SharedNodePointer node = it->second; + if (node->getType() == NodeType::MetavoxelServer) { QMutexLocker locker(&node->getMutex()); MetavoxelClient* client = static_cast(node->getLinkedData()); @@ -115,7 +119,11 @@ MetavoxelClient* MetavoxelClientManager::createClient(const SharedNodePointer& n } void MetavoxelClientManager::guide(MetavoxelVisitor& visitor) { - foreach (const SharedNodePointer& node, NodeList::getInstance()->getNodeHash()) { + NodeHashSnapshot snapshotHash = NodeList::getInstance()->getNodeHash().snapshot_table(); + + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + SharedNodePointer node = it->second; + if (node->getType() == NodeType::MetavoxelServer) { QMutexLocker locker(&node->getMutex()); MetavoxelClient* client = static_cast(node->getLinkedData()); diff --git a/libraries/networking/src/LimitedNodeList.cpp b/libraries/networking/src/LimitedNodeList.cpp index 0f86719761..5a103076b6 100644 --- a/libraries/networking/src/LimitedNodeList.cpp +++ b/libraries/networking/src/LimitedNodeList.cpp @@ -392,7 +392,10 @@ SharedNodePointer LimitedNodeList::addOrUpdateNode(const QUuid& uuid, NodeType_t const HifiSockAddr& publicSocket, const HifiSockAddr& localSocket) { try { SharedNodePointer matchingNode = _nodeHash[uuid]; - matchingNode->updateSockets(publicSocket, localSocket); + + matchingNode->setPublicSocket(publicSocket); + matchingNode->setLocalSocket(localSocket); + return matchingNode; } catch (std::out_of_range) { // we didn't have this node, so add them @@ -412,7 +415,7 @@ SharedNodePointer LimitedNodeList::addOrUpdateNode(const QUuid& uuid, NodeType_t unsigned LimitedNodeList::broadcastToNodes(const QByteArray& packet, const NodeSet& destinationNodeTypes) { unsigned n = 0; - SnapshotNodeHash snapshotHash = _nodeHash.snapshot_table(); + NodeHashSnapshot snapshotHash = _nodeHash.snapshot_table(); for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { if (destinationNodeTypes.contains(it->second->getType())) { writeDatagram(packet, it->second); @@ -459,7 +462,7 @@ QByteArray LimitedNodeList::constructPingReplyPacket(const QByteArray& pingPacke SharedNodePointer LimitedNodeList::soloNodeOfType(char nodeType) { if (memchr(SOLO_NODE_TYPES, nodeType, sizeof(SOLO_NODE_TYPES))) { - SnapshotNodeHash snapshotHash = _nodeHash.snapshot_table(); + NodeHashSnapshot snapshotHash = _nodeHash.snapshot_table(); for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { if (it->second->getType() == nodeType) { @@ -483,7 +486,7 @@ void LimitedNodeList::resetPacketStats() { void LimitedNodeList::removeSilentNodes() { - SnapshotNodeHash snapshotHash = _nodeHash.snapshot_table(); + NodeHashSnapshot snapshotHash = _nodeHash.snapshot_table(); for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { SharedNodePointer node = it->second; diff --git a/libraries/networking/src/LimitedNodeList.h b/libraries/networking/src/LimitedNodeList.h index 81daa7ace8..63f93458f3 100644 --- a/libraries/networking/src/LimitedNodeList.h +++ b/libraries/networking/src/LimitedNodeList.h @@ -55,7 +55,7 @@ typedef QSharedPointer SharedNodePointer; Q_DECLARE_METATYPE(SharedNodePointer) typedef cuckoohash_map NodeHash; -typedef std::vector > SnapshotNodeHash; +typedef std::vector > NodeHashSnapshot; typedef quint8 PingType_t; namespace PingType { @@ -104,8 +104,6 @@ public: SharedNodePointer addOrUpdateNode(const QUuid& uuid, NodeType_t nodeType, const HifiSockAddr& publicSocket, const HifiSockAddr& localSocket); - SharedNodePointer updateSocketsForNode(const QUuid& uuid, - const HifiSockAddr& publicSocket, const HifiSockAddr& localSocket); const HifiSockAddr& getLocalSockAddr() const { return _localSockAddr; } diff --git a/libraries/networking/src/Node.h b/libraries/networking/src/Node.h index 05b32d0528..acb6c6f453 100644 --- a/libraries/networking/src/Node.h +++ b/libraries/networking/src/Node.h @@ -81,8 +81,6 @@ public: const HifiSockAddr& getSymmetricSocket() const { return _symmetricSocket; } virtual void setSymmetricSocket(const HifiSockAddr& symmetricSocket); - void updateSockets(const HifiSockAddr& publicSocket, const HifiSockAddr& localSocket); - const HifiSockAddr* getActiveSocket() const { return _activeSocket; } void activatePublicSocket(); diff --git a/libraries/octree/src/JurisdictionListener.cpp b/libraries/octree/src/JurisdictionListener.cpp index f3d9e31acc..606a6c13f2 100644 --- a/libraries/octree/src/JurisdictionListener.cpp +++ b/libraries/octree/src/JurisdictionListener.cpp @@ -40,9 +40,11 @@ bool JurisdictionListener::queueJurisdictionRequest() { NodeList* nodeList = NodeList::getInstance(); - foreach (const SharedNodePointer& node, nodeList->getNodeHash()) { - if (node->getType() == getNodeType() && node->getActiveSocket()) { - _packetSender.queuePacketForSending(node, QByteArray(reinterpret_cast(bufferOut), sizeOut)); + NodeHashSnapshot nodeHashSnapshot = nodeList->getNodeHash().snapshot_table(); + + for (auto it = nodeHashSnapshot.begin(); it != nodeHashSnapshot.end(); it++) { + if (it->second->getType() == getNodeType() && it->second->getActiveSocket()) { + _packetSender.queuePacketForSending(it->second, QByteArray(reinterpret_cast(bufferOut), sizeOut)); nodeCount++; } } diff --git a/libraries/octree/src/OctreeEditPacketSender.cpp b/libraries/octree/src/OctreeEditPacketSender.cpp index 65308f906f..19de2e37e9 100644 --- a/libraries/octree/src/OctreeEditPacketSender.cpp +++ b/libraries/octree/src/OctreeEditPacketSender.cpp @@ -52,12 +52,13 @@ bool OctreeEditPacketSender::serversExist() const { bool hasServers = false; bool atLeastOneJurisdictionMissing = false; // assume the best NodeList* nodeList = NodeList::getInstance(); - - foreach (const SharedNodePointer& node, nodeList->getNodeHash()) { - + + NodeHashSnapshot snapshotHash = nodeList->getNodeHash().snapshot_table(); + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { // only send to the NodeTypes that are getMyNodeType() + SharedNodePointer node = it->second; if (node->getType() == getMyNodeType() && node->getActiveSocket()) { - + QUuid nodeUUID = node->getUUID(); // If we've got Jurisdictions set, then check to see if we know the jurisdiction for this server if (_serverJurisdictions) { @@ -86,8 +87,11 @@ void OctreeEditPacketSender::queuePacketToNode(const QUuid& nodeUUID, unsigned c bool wantDebug = false; NodeList* nodeList = NodeList::getInstance(); - - foreach (const SharedNodePointer& node, nodeList->getNodeHash()) { + + NodeHashSnapshot snapshotHash = nodeList->getNodeHash().snapshot_table(); + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + SharedNodePointer node = it->second; + // only send to the NodeTypes that are getMyNodeType() if (node->getType() == getMyNodeType() && ((node->getUUID() == nodeUUID) || (nodeUUID.isNull()))) { @@ -194,8 +198,10 @@ void OctreeEditPacketSender::queuePacketToNodes(unsigned char* buffer, size_t le // But we can't really do that with a packed message, since each edit message could be destined // for a different server... So we need to actually manage multiple queued packets... one // for each server - - foreach (const SharedNodePointer& node, NodeList::getInstance()->getNodeHash()) { + + NodeHashSnapshot snapshotHash = NodeList::getInstance()->getNodeHash().snapshot_table(); + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + SharedNodePointer node = it->second; // only send to the NodeTypes that are getMyNodeType() if (node->getActiveSocket() && node->getType() == getMyNodeType()) { QUuid nodeUUID = node->getUUID(); @@ -249,7 +255,9 @@ void OctreeEditPacketSender::queueOctreeEditMessage(PacketType type, unsigned ch _packetsQueueLock.lock(); - foreach (const SharedNodePointer& node, NodeList::getInstance()->getNodeHash()) { + NodeHashSnapshot snapshotHash = NodeList::getInstance()->getNodeHash().snapshot_table(); + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + SharedNodePointer node = it->second; // only send to the NodeTypes that are getMyNodeType() if (node->getActiveSocket() && node->getType() == getMyNodeType()) { QUuid nodeUUID = node->getUUID(); @@ -384,7 +392,7 @@ void OctreeEditPacketSender::processNackPacket(const QByteArray& packet) { // retrieve packet from history const QByteArray* packet = sentPacketHistory.getPacket(sequenceNumber); if (packet) { - const SharedNodePointer& node = NodeList::getInstance()->getNodeHash().value(sendingNodeUUID); + const SharedNodePointer& node = NodeList::getInstance()->nodeWithUUID(sendingNodeUUID); queuePacketForSending(node, *packet); } } diff --git a/libraries/octree/src/OctreeHeadlessViewer.cpp b/libraries/octree/src/OctreeHeadlessViewer.cpp index 2f21c7a899..b363c654c1 100644 --- a/libraries/octree/src/OctreeHeadlessViewer.cpp +++ b/libraries/octree/src/OctreeHeadlessViewer.cpp @@ -76,8 +76,10 @@ void OctreeHeadlessViewer::queryOctree() { int totalServers = 0; int inViewServers = 0; int unknownJurisdictionServers = 0; - - foreach (const SharedNodePointer& node, NodeList::getInstance()->getNodeHash()) { + + NodeHashSnapshot snapshotHash = NodeList::getInstance()->getNodeHash().snapshot_table(); + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + SharedNodePointer node = it->second; // only send to the NodeTypes that are serverType if (node->getActiveSocket() && node->getType() == serverType) { totalServers++; @@ -142,11 +144,11 @@ void OctreeHeadlessViewer::queryOctree() { NodeList* nodeList = NodeList::getInstance(); - foreach (const SharedNodePointer& node, nodeList->getNodeHash()) { + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + SharedNodePointer node = it->second; // only send to the NodeTypes that are serverType if (node->getActiveSocket() && node->getType() == serverType) { - // get the server bounds for this server QUuid nodeUUID = node->getUUID(); diff --git a/libraries/script-engine/src/ScriptEngine.cpp b/libraries/script-engine/src/ScriptEngine.cpp index fb98124fc9..340d5b3e20 100644 --- a/libraries/script-engine/src/ScriptEngine.cpp +++ b/libraries/script-engine/src/ScriptEngine.cpp @@ -520,7 +520,11 @@ void ScriptEngine::run() { // write audio packet to AudioMixer nodes NodeList* nodeList = NodeList::getInstance(); - foreach(const SharedNodePointer& node, nodeList->getNodeHash()) { + NodeHashSnapshot snapshotHash = nodeList->getNodeHash().snapshot_table(); + + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + SharedNodePointer node = it->second; + // only send to nodes of type AudioMixer if (node->getType() == NodeType::AudioMixer) { // pack sequence number From 63c5dacdd07a93cbb3455c453746aee09a5b5aa7 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 5 Nov 2014 15:12:42 -0800 Subject: [PATCH 011/258] final changes to use new hash from LimitedNodeList --- interface/src/ui/NodeBounds.cpp | 7 +++++-- interface/src/ui/OctreeStatsDialog.cpp | 6 ++++-- interface/src/ui/Stats.cpp | 7 +++++-- 3 files changed, 14 insertions(+), 6 deletions(-) diff --git a/interface/src/ui/NodeBounds.cpp b/interface/src/ui/NodeBounds.cpp index 49509cc9cf..6298385c90 100644 --- a/interface/src/ui/NodeBounds.cpp +++ b/interface/src/ui/NodeBounds.cpp @@ -53,8 +53,11 @@ void NodeBounds::draw() { float selectedScale = 0; NodeList* nodeList = NodeList::getInstance(); - - foreach (const SharedNodePointer& node, nodeList->getNodeHash()) { + NodeHashSnapshot snapshotHash = nodeList->getNodeHash().snapshot_table(); + + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + SharedNodePointer node = it->second; + NodeType_t nodeType = node->getType(); if (nodeType == NodeType::VoxelServer && _showVoxelNodes) { diff --git a/interface/src/ui/OctreeStatsDialog.cpp b/interface/src/ui/OctreeStatsDialog.cpp index e51b9b1f42..8a6d6442f5 100644 --- a/interface/src/ui/OctreeStatsDialog.cpp +++ b/interface/src/ui/OctreeStatsDialog.cpp @@ -248,8 +248,10 @@ void OctreeStatsDialog::showOctreeServersOfType(int& serverCount, NodeType_t ser QLocale locale(QLocale::English); NodeList* nodeList = NodeList::getInstance(); - - foreach (const SharedNodePointer& node, nodeList->getNodeHash()) { + NodeHashSnapshot snapshotHash = nodeList->getNodeHash().snapshot_table(); + + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + SharedNodePointer node = it->second; // only send to the NodeTypes that are NodeType_t_VOXEL_SERVER if (node->getType() == serverType) { serverCount++; diff --git a/interface/src/ui/Stats.cpp b/interface/src/ui/Stats.cpp index 9bad475838..8e4b900180 100644 --- a/interface/src/ui/Stats.cpp +++ b/interface/src/ui/Stats.cpp @@ -328,8 +328,11 @@ void Stats::display( // Now handle voxel servers, since there could be more than one, we average their ping times unsigned long totalPingVoxel = 0; int voxelServerCount = 0; - - foreach (const SharedNodePointer& node, nodeList->getNodeHash()) { + + NodeHashSnapshot snapshotHash = nodeList->getNodeHash().snapshot_table(); + + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + SharedNodePointer node = it->second; // TODO: this should also support entities if (node->getType() == NodeType::VoxelServer) { totalPingVoxel += node->getPingMs(); From a39ed798aea41f9407bfee66869e77845f659573 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 5 Nov 2014 15:45:51 -0800 Subject: [PATCH 012/258] replace libcuckoo requirement with tbb --- cmake/modules/FindLibcuckoo.cmake | 38 ---- cmake/modules/FindTBB.cmake | 283 ++++++++++++++++++++++++++ libraries/networking/CMakeLists.txt | 8 +- libraries/networking/src/NodeList.cpp | 3 +- 4 files changed, 288 insertions(+), 44 deletions(-) delete mode 100644 cmake/modules/FindLibcuckoo.cmake create mode 100644 cmake/modules/FindTBB.cmake diff --git a/cmake/modules/FindLibcuckoo.cmake b/cmake/modules/FindLibcuckoo.cmake deleted file mode 100644 index 4e87c650c2..0000000000 --- a/cmake/modules/FindLibcuckoo.cmake +++ /dev/null @@ -1,38 +0,0 @@ -# FindLibCuckoo.cmake -# -# Try to find libcuckoo. -# -# You can provide a LIBCUCKOO_ROOT_DIR which contains src and include directories -# -# Once done this will define -# -# LIBCUCKOO_FOUND - system found libcuckoo -# LIBCUCKOO_INCLUDE_DIRS - the libcuckoo include directory -# -# Created on 5/11/2014 by Stephen Birarda -# Copyright 2014 High Fidelity, Inc. -# -# Distributed under the Apache License, Version 2.0. -# See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -# - -include("${MACRO_DIR}/HifiLibrarySearchHints.cmake") -hifi_library_search_hints("libcuckoo") - -find_path(LIBCUCKOO_INCLUDE_DIRS libcuckoo/cuckoohash_map.hh PATH_SUFFIXES include HINTS ${LIBCUCKOO_SEARCH_DIRS}) - -find_library(CITYHASH_LIBRARY_RELEASE NAME cityhash PATH_SUFFIXES lib HINTS ${LIBCUCKOO_SEARCH_DIRS}) -find_library(CITYHASH_LIBRARY_DEBUG NAME cityhash PATH_SUFFIXES lib HINTS ${LIBCUCKOO_SEARCH_DIRS}) - -include(SelectLibraryConfigurations) -select_library_configurations(CITYHASH) - -set(LIBCUCKOO_LIBRARIES ${CITYHASH_LIBRARY}) - -include(FindPackageHandleStandardArgs) -find_package_handle_standard_args( - libcuckoo - "Could NOT find libcuckoo. Read libraries/networking/externals/libcuckoo/readme.txt" - LIBCUCKOO_INCLUDE_DIRS - LIBCUCKOO_LIBRARIES -) \ No newline at end of file diff --git a/cmake/modules/FindTBB.cmake b/cmake/modules/FindTBB.cmake new file mode 100644 index 0000000000..e5ca100391 --- /dev/null +++ b/cmake/modules/FindTBB.cmake @@ -0,0 +1,283 @@ +# Locate Intel Threading Building Blocks include paths and libraries +# FindTBB.cmake can be found at https://code.google.com/p/findtbb/ +# Written by Hannes Hofmann +# Improvements by Gino van den Bergen , +# Florian Uhlig , +# Jiri Marsik + +# The MIT License +# +# Copyright (c) 2011 Hannes Hofmann +# +# 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. + +# GvdB: This module uses the environment variable TBB_ARCH_PLATFORM which defines architecture and compiler. +# e.g. "ia32/vc8" or "em64t/cc4.1.0_libc2.4_kernel2.6.16.21" +# TBB_ARCH_PLATFORM is set by the build script tbbvars[.bat|.sh|.csh], which can be found +# in the TBB installation directory (TBB_INSTALL_DIR). +# +# GvdB: Mac OS X distribution places libraries directly in lib directory. +# +# For backwards compatibility, you may explicitely set the CMake variables TBB_ARCHITECTURE and TBB_COMPILER. +# TBB_ARCHITECTURE [ ia32 | em64t | itanium ] +# which architecture to use +# TBB_COMPILER e.g. vc9 or cc3.2.3_libc2.3.2_kernel2.4.21 or cc4.0.1_os10.4.9 +# which compiler to use (detected automatically on Windows) + +# This module respects +# TBB_INSTALL_DIR or $ENV{TBB21_INSTALL_DIR} or $ENV{TBB_INSTALL_DIR} + +# This module defines +# TBB_INCLUDE_DIRS, where to find task_scheduler_init.h, etc. +# TBB_LIBRARY_DIRS, where to find libtbb, libtbbmalloc +# TBB_DEBUG_LIBRARY_DIRS, where to find libtbb_debug, libtbbmalloc_debug +# TBB_INSTALL_DIR, the base TBB install directory +# TBB_LIBRARIES, the libraries to link against to use TBB. +# TBB_DEBUG_LIBRARIES, the libraries to link against to use TBB with debug symbols. +# TBB_FOUND, If false, don't try to use TBB. +# TBB_INTERFACE_VERSION, as defined in tbb/tbb_stddef.h + + +if (WIN32) + # has em64t/vc8 em64t/vc9 + # has ia32/vc7.1 ia32/vc8 ia32/vc9 + set(_TBB_DEFAULT_INSTALL_DIR "C:/Program Files/Intel/TBB" "C:/Program Files (x86)/Intel/TBB") + set(_TBB_LIB_NAME "tbb") + set(_TBB_LIB_MALLOC_NAME "${_TBB_LIB_NAME}malloc") + set(_TBB_LIB_DEBUG_NAME "${_TBB_LIB_NAME}_debug") + set(_TBB_LIB_MALLOC_DEBUG_NAME "${_TBB_LIB_MALLOC_NAME}_debug") + if (MSVC71) + set (_TBB_COMPILER "vc7.1") + endif(MSVC71) + if (MSVC80) + set(_TBB_COMPILER "vc8") + endif(MSVC80) + if (MSVC90) + set(_TBB_COMPILER "vc9") + endif(MSVC90) + if(MSVC10) + set(_TBB_COMPILER "vc10") + endif(MSVC10) + # Todo: add other Windows compilers such as ICL. + set(_TBB_ARCHITECTURE ${TBB_ARCHITECTURE}) +endif (WIN32) + +if (UNIX) + if (APPLE) + # MAC + set(_TBB_DEFAULT_INSTALL_DIR "/Library/Frameworks/Intel_TBB.framework/Versions") + # libs: libtbb.dylib, libtbbmalloc.dylib, *_debug + set(_TBB_LIB_NAME "tbb") + set(_TBB_LIB_MALLOC_NAME "${_TBB_LIB_NAME}malloc") + set(_TBB_LIB_DEBUG_NAME "${_TBB_LIB_NAME}_debug") + set(_TBB_LIB_MALLOC_DEBUG_NAME "${_TBB_LIB_MALLOC_NAME}_debug") + # default flavor on apple: ia32/cc4.0.1_os10.4.9 + # Jiri: There is no reason to presume there is only one flavor and + # that user's setting of variables should be ignored. + if(NOT TBB_COMPILER) + set(_TBB_COMPILER "cc4.0.1_os10.4.9") + elseif (NOT TBB_COMPILER) + set(_TBB_COMPILER ${TBB_COMPILER}) + endif(NOT TBB_COMPILER) + if(NOT TBB_ARCHITECTURE) + set(_TBB_ARCHITECTURE "ia32") + elseif(NOT TBB_ARCHITECTURE) + set(_TBB_ARCHITECTURE ${TBB_ARCHITECTURE}) + endif(NOT TBB_ARCHITECTURE) + else (APPLE) + # LINUX + set(_TBB_DEFAULT_INSTALL_DIR "/opt/intel/tbb" "/usr/local/include" "/usr/include") + set(_TBB_LIB_NAME "tbb") + set(_TBB_LIB_MALLOC_NAME "${_TBB_LIB_NAME}malloc") + set(_TBB_LIB_DEBUG_NAME "${_TBB_LIB_NAME}_debug") + set(_TBB_LIB_MALLOC_DEBUG_NAME "${_TBB_LIB_MALLOC_NAME}_debug") + # has em64t/cc3.2.3_libc2.3.2_kernel2.4.21 em64t/cc3.3.3_libc2.3.3_kernel2.6.5 em64t/cc3.4.3_libc2.3.4_kernel2.6.9 em64t/cc4.1.0_libc2.4_kernel2.6.16.21 + # has ia32/* + # has itanium/* + set(_TBB_COMPILER ${TBB_COMPILER}) + set(_TBB_ARCHITECTURE ${TBB_ARCHITECTURE}) + endif (APPLE) +endif (UNIX) + +if (CMAKE_SYSTEM MATCHES "SunOS.*") +# SUN +# not yet supported +# has em64t/cc3.4.3_kernel5.10 +# has ia32/* +endif (CMAKE_SYSTEM MATCHES "SunOS.*") + + +#-- Clear the public variables +set (TBB_FOUND "NO") + + +#-- Find TBB install dir and set ${_TBB_INSTALL_DIR} and cached ${TBB_INSTALL_DIR} +# first: use CMake variable TBB_INSTALL_DIR +if (TBB_INSTALL_DIR) + set (_TBB_INSTALL_DIR ${TBB_INSTALL_DIR}) +endif (TBB_INSTALL_DIR) +# second: use environment variable +if (NOT _TBB_INSTALL_DIR) + if (NOT "$ENV{TBB_INSTALL_DIR}" STREQUAL "") + set (_TBB_INSTALL_DIR $ENV{TBB_INSTALL_DIR}) + endif (NOT "$ENV{TBB_INSTALL_DIR}" STREQUAL "") + # Intel recommends setting TBB21_INSTALL_DIR + if (NOT "$ENV{TBB21_INSTALL_DIR}" STREQUAL "") + set (_TBB_INSTALL_DIR $ENV{TBB21_INSTALL_DIR}) + endif (NOT "$ENV{TBB21_INSTALL_DIR}" STREQUAL "") + if (NOT "$ENV{TBB22_INSTALL_DIR}" STREQUAL "") + set (_TBB_INSTALL_DIR $ENV{TBB22_INSTALL_DIR}) + endif (NOT "$ENV{TBB22_INSTALL_DIR}" STREQUAL "") + if (NOT "$ENV{TBB30_INSTALL_DIR}" STREQUAL "") + set (_TBB_INSTALL_DIR $ENV{TBB30_INSTALL_DIR}) + endif (NOT "$ENV{TBB30_INSTALL_DIR}" STREQUAL "") +endif (NOT _TBB_INSTALL_DIR) +# third: try to find path automatically +if (NOT _TBB_INSTALL_DIR) + if (_TBB_DEFAULT_INSTALL_DIR) + set (_TBB_INSTALL_DIR ${_TBB_DEFAULT_INSTALL_DIR}) + endif (_TBB_DEFAULT_INSTALL_DIR) +endif (NOT _TBB_INSTALL_DIR) +# sanity check +if (NOT _TBB_INSTALL_DIR) + message ("ERROR: Unable to find Intel TBB install directory. ${_TBB_INSTALL_DIR}") +else (NOT _TBB_INSTALL_DIR) +# finally: set the cached CMake variable TBB_INSTALL_DIR +if (NOT TBB_INSTALL_DIR) + set (TBB_INSTALL_DIR ${_TBB_INSTALL_DIR} CACHE PATH "Intel TBB install directory") + mark_as_advanced(TBB_INSTALL_DIR) +endif (NOT TBB_INSTALL_DIR) + + +#-- A macro to rewrite the paths of the library. This is necessary, because +# find_library() always found the em64t/vc9 version of the TBB libs +macro(TBB_CORRECT_LIB_DIR var_name) +# if (NOT "${_TBB_ARCHITECTURE}" STREQUAL "em64t") + string(REPLACE em64t "${_TBB_ARCHITECTURE}" ${var_name} ${${var_name}}) +# endif (NOT "${_TBB_ARCHITECTURE}" STREQUAL "em64t") + string(REPLACE ia32 "${_TBB_ARCHITECTURE}" ${var_name} ${${var_name}}) + string(REPLACE vc7.1 "${_TBB_COMPILER}" ${var_name} ${${var_name}}) + string(REPLACE vc8 "${_TBB_COMPILER}" ${var_name} ${${var_name}}) + string(REPLACE vc9 "${_TBB_COMPILER}" ${var_name} ${${var_name}}) + string(REPLACE vc10 "${_TBB_COMPILER}" ${var_name} ${${var_name}}) +endmacro(TBB_CORRECT_LIB_DIR var_content) + + +#-- Look for include directory and set ${TBB_INCLUDE_DIR} +set (TBB_INC_SEARCH_DIR ${_TBB_INSTALL_DIR}/include) +# Jiri: tbbvars now sets the CPATH environment variable to the directory +# containing the headers. +find_path(TBB_INCLUDE_DIR + tbb/task_scheduler_init.h + PATHS ${TBB_INC_SEARCH_DIR} ENV CPATH +) +mark_as_advanced(TBB_INCLUDE_DIR) + + +#-- Look for libraries +# GvdB: $ENV{TBB_ARCH_PLATFORM} is set by the build script tbbvars[.bat|.sh|.csh] +if (NOT $ENV{TBB_ARCH_PLATFORM} STREQUAL "") + set (_TBB_LIBRARY_DIR + ${_TBB_INSTALL_DIR}/lib/$ENV{TBB_ARCH_PLATFORM} + ${_TBB_INSTALL_DIR}/$ENV{TBB_ARCH_PLATFORM}/lib + ) +endif (NOT $ENV{TBB_ARCH_PLATFORM} STREQUAL "") +# Jiri: This block isn't mutually exclusive with the previous one +# (hence no else), instead I test if the user really specified +# the variables in question. +if ((NOT ${TBB_ARCHITECTURE} STREQUAL "") AND (NOT ${TBB_COMPILER} STREQUAL "")) + # HH: deprecated + message(STATUS "[Warning] FindTBB.cmake: The use of TBB_ARCHITECTURE and TBB_COMPILER is deprecated and may not be supported in future versions. Please set \$ENV{TBB_ARCH_PLATFORM} (using tbbvars.[bat|csh|sh]).") + # Jiri: It doesn't hurt to look in more places, so I store the hints from + # ENV{TBB_ARCH_PLATFORM} and the TBB_ARCHITECTURE and TBB_COMPILER + # variables and search them both. + set (_TBB_LIBRARY_DIR "${_TBB_INSTALL_DIR}/${_TBB_ARCHITECTURE}/${_TBB_COMPILER}/lib" ${_TBB_LIBRARY_DIR}) +endif ((NOT ${TBB_ARCHITECTURE} STREQUAL "") AND (NOT ${TBB_COMPILER} STREQUAL "")) + +# GvdB: Mac OS X distribution places libraries directly in lib directory. +list(APPEND _TBB_LIBRARY_DIR ${_TBB_INSTALL_DIR}/lib) + +# Jiri: No reason not to check the default paths. From recent versions, +# tbbvars has started exporting the LIBRARY_PATH and LD_LIBRARY_PATH +# variables, which now point to the directories of the lib files. +# It all makes more sense to use the ${_TBB_LIBRARY_DIR} as a HINTS +# argument instead of the implicit PATHS as it isn't hard-coded +# but computed by system introspection. Searching the LIBRARY_PATH +# and LD_LIBRARY_PATH environment variables is now even more important +# that tbbvars doesn't export TBB_ARCH_PLATFORM and it facilitates +# the use of TBB built from sources. +find_library(TBB_LIBRARY ${_TBB_LIB_NAME} HINTS ${_TBB_LIBRARY_DIR} + PATHS ENV LIBRARY_PATH ENV LD_LIBRARY_PATH) +find_library(TBB_MALLOC_LIBRARY ${_TBB_LIB_MALLOC_NAME} HINTS ${_TBB_LIBRARY_DIR} + PATHS ENV LIBRARY_PATH ENV LD_LIBRARY_PATH) + +#Extract path from TBB_LIBRARY name +get_filename_component(TBB_LIBRARY_DIR ${TBB_LIBRARY} PATH) + +#TBB_CORRECT_LIB_DIR(TBB_LIBRARY) +#TBB_CORRECT_LIB_DIR(TBB_MALLOC_LIBRARY) +mark_as_advanced(TBB_LIBRARY TBB_MALLOC_LIBRARY) + +#-- Look for debug libraries +# Jiri: Changed the same way as for the release libraries. +find_library(TBB_LIBRARY_DEBUG ${_TBB_LIB_DEBUG_NAME} HINTS ${_TBB_LIBRARY_DIR} + PATHS ENV LIBRARY_PATH ENV LD_LIBRARY_PATH) +find_library(TBB_MALLOC_LIBRARY_DEBUG ${_TBB_LIB_MALLOC_DEBUG_NAME} HINTS ${_TBB_LIBRARY_DIR} + PATHS ENV LIBRARY_PATH ENV LD_LIBRARY_PATH) + +# Jiri: Self-built TBB stores the debug libraries in a separate directory. +# Extract path from TBB_LIBRARY_DEBUG name +get_filename_component(TBB_LIBRARY_DEBUG_DIR ${TBB_LIBRARY_DEBUG} PATH) + +#TBB_CORRECT_LIB_DIR(TBB_LIBRARY_DEBUG) +#TBB_CORRECT_LIB_DIR(TBB_MALLOC_LIBRARY_DEBUG) +mark_as_advanced(TBB_LIBRARY_DEBUG TBB_MALLOC_LIBRARY_DEBUG) + + +if (TBB_INCLUDE_DIR) + if (TBB_LIBRARY) + set (TBB_FOUND "YES") + set (TBB_LIBRARIES ${TBB_LIBRARY} ${TBB_MALLOC_LIBRARY} ${TBB_LIBRARIES}) + set (TBB_DEBUG_LIBRARIES ${TBB_LIBRARY_DEBUG} ${TBB_MALLOC_LIBRARY_DEBUG} ${TBB_DEBUG_LIBRARIES}) + set (TBB_INCLUDE_DIRS ${TBB_INCLUDE_DIR} CACHE PATH "TBB include directory" FORCE) + set (TBB_LIBRARY_DIRS ${TBB_LIBRARY_DIR} CACHE PATH "TBB library directory" FORCE) + # Jiri: Self-built TBB stores the debug libraries in a separate directory. + set (TBB_DEBUG_LIBRARY_DIRS ${TBB_LIBRARY_DEBUG_DIR} CACHE PATH "TBB debug library directory" FORCE) + mark_as_advanced(TBB_INCLUDE_DIRS TBB_LIBRARY_DIRS TBB_DEBUG_LIBRARY_DIRS TBB_LIBRARIES TBB_DEBUG_LIBRARIES) + message(STATUS "Found Intel TBB") + endif (TBB_LIBRARY) +endif (TBB_INCLUDE_DIR) + +if (NOT TBB_FOUND) + message("ERROR: Intel TBB NOT found!") + message(STATUS "Looked for Threading Building Blocks in ${_TBB_INSTALL_DIR}") + # do only throw fatal, if this pkg is REQUIRED + if (TBB_FIND_REQUIRED) + message(FATAL_ERROR "Could NOT find TBB library.") + endif (TBB_FIND_REQUIRED) +endif (NOT TBB_FOUND) + +endif (NOT _TBB_INSTALL_DIR) + +if (TBB_FOUND) + set(TBB_INTERFACE_VERSION 0) + FILE(READ "${TBB_INCLUDE_DIRS}/tbb/tbb_stddef.h" _TBB_VERSION_CONTENTS) + STRING(REGEX REPLACE ".*#define TBB_INTERFACE_VERSION ([0-9]+).*" "\\1" TBB_INTERFACE_VERSION "${_TBB_VERSION_CONTENTS}") + set(TBB_INTERFACE_VERSION "${TBB_INTERFACE_VERSION}") +endif (TBB_FOUND) diff --git a/libraries/networking/CMakeLists.txt b/libraries/networking/CMakeLists.txt index b650c0942c..7c8b628183 100644 --- a/libraries/networking/CMakeLists.txt +++ b/libraries/networking/CMakeLists.txt @@ -12,9 +12,7 @@ endif () # find required dependencies find_package(OpenSSL REQUIRED) - -list(APPEND LIBCUCKOO_ROOT_DIR "${CMAKE_CURRENT_SOURCE_DIR}/externals/libcuckoo") -find_package(libcuckoo REQUIRED) +find_package(TBB REQUIRED) if (APPLE AND ${OPENSSL_INCLUDE_DIR} STREQUAL "/usr/include") # this is a user on OS X using system OpenSSL, which is going to throw warnings since they're deprecating for their common crypto @@ -25,10 +23,10 @@ endif () include_directories(SYSTEM "${OPENSSL_INCLUDE_DIR}") # append OpenSSL to our list of libraries to link -list(APPEND ${TARGET_NAME}_LIBRARIES_TO_LINK "${OPENSSL_LIBRARIES}" "${LIBCUCKOO_LIBRARIES}") +list(APPEND ${TARGET_NAME}_LIBRARIES_TO_LINK "${OPENSSL_LIBRARIES}" "${TBB_LIBRARIES}") # append libcuckoo includes to our list of includes to bubble -list(APPEND ${TARGET_NAME}_DEPENDENCY_INCLUDES "${LIBCUCKOO_INCLUDE_DIRS}") +list(APPEND ${TARGET_NAME}_DEPENDENCY_INCLUDES "${TBB_INCLUDE_DIRS}") # call macro to link our dependencies and bubble them up via a property on our target link_shared_dependencies() \ No newline at end of file diff --git a/libraries/networking/src/NodeList.cpp b/libraries/networking/src/NodeList.cpp index 6621a6d2e2..fe8efe42c4 100644 --- a/libraries/networking/src/NodeList.cpp +++ b/libraries/networking/src/NodeList.cpp @@ -449,7 +449,8 @@ void NodeList::pingPunchForInactiveNode(const SharedNodePointer& node) { } void NodeList::pingInactiveNodes() { - for (auto it = _nodeHash.cbegin(); !it.is_end(); it++) { + NodeHashSnapshot snapshotHash = _nodeHash.snapshot_table(); + for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { if (!it->second->getActiveSocket()) { // we don't have an active link to this node, ping it to set that up pingPunchForInactiveNode(it->second); From e0c4f14c8163f55c4c28abca1fa9df461b256440 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 6 Nov 2014 11:19:16 -0800 Subject: [PATCH 013/258] move networking lib to TBB concurrent_unordered_map --- libraries/networking/src/LimitedNodeList.cpp | 63 ++++++++++---------- libraries/networking/src/LimitedNodeList.h | 63 +++++++++++++++----- libraries/networking/src/NodeList.cpp | 9 ++- libraries/networking/src/UUIDCityHasher.cpp | 12 ---- libraries/networking/src/UUIDCityHasher.h | 26 -------- libraries/networking/src/UUIDHasher.h | 26 ++++++++ 6 files changed, 108 insertions(+), 91 deletions(-) delete mode 100644 libraries/networking/src/UUIDCityHasher.cpp delete mode 100644 libraries/networking/src/UUIDCityHasher.h create mode 100644 libraries/networking/src/UUIDHasher.h diff --git a/libraries/networking/src/LimitedNodeList.cpp b/libraries/networking/src/LimitedNodeList.cpp index 5a103076b6..818d35c0e5 100644 --- a/libraries/networking/src/LimitedNodeList.cpp +++ b/libraries/networking/src/LimitedNodeList.cpp @@ -21,6 +21,8 @@ #include +#include + #include "AccountManager.h" #include "Assignment.h" #include "HifiSockAddr.h" @@ -342,9 +344,9 @@ int LimitedNodeList::findNodeAndUpdateWithDataFromPacket(const QByteArray& packe return 0; } -SharedNodePointer LimitedNodeList::nodeWithUUID(const QUuid& nodeUUID, bool blockingLock) { +SharedNodePointer LimitedNodeList::nodeWithUUID(const QUuid& nodeUUID) { try { - return _nodeHash[nodeUUID]; + return _nodeHash.at(nodeUUID); } catch (std::out_of_range) { return SharedNodePointer(); } @@ -360,12 +362,12 @@ SharedNodePointer LimitedNodeList::sendingNodeForPacket(const QByteArray& packet void LimitedNodeList::eraseAllNodes() { qDebug() << "Clearing the NodeList. Deleting all nodes in list."; - // iterate the current nodes and note that they are going down - for (auto it = _nodeHash.cbegin(); !it.is_end(); it++) { + // iterate the current nodes, emit that they are dying and remove them from the hash + QWriteLocker writeLock(&_nodeMutex); + for (NodeHash::iterator it = _nodeHash.begin(); it != _nodeHash.end(); ++it) { emit nodeKilled(it->second); + it = _nodeHash.unsafe_erase(it); } - - _nodeHash.clear(); } void LimitedNodeList::reset() { @@ -373,10 +375,13 @@ void LimitedNodeList::reset() { } void LimitedNodeList::killNodeWithUUID(const QUuid& nodeUUID) { - SharedNodePointer matchingNode = nodeWithUUID(nodeUUID); - if (matchingNode) { + NodeHash::iterator it = _nodeHash.find(nodeUUID); + if (it != _nodeHash.end()) { + SharedNodePointer matchingNode = it->second; + + QWriteLocker writeLocker(&_nodeMutex); + _nodeHash.unsafe_erase(it); emit nodeKilled(matchingNode); - _nodeHash.erase(nodeUUID); } } @@ -391,7 +396,7 @@ void LimitedNodeList::processKillNode(const QByteArray& dataByteArray) { SharedNodePointer LimitedNodeList::addOrUpdateNode(const QUuid& uuid, NodeType_t nodeType, const HifiSockAddr& publicSocket, const HifiSockAddr& localSocket) { try { - SharedNodePointer matchingNode = _nodeHash[uuid]; + SharedNodePointer matchingNode = _nodeHash.at(uuid); matchingNode->setPublicSocket(publicSocket); matchingNode->setLocalSocket(localSocket); @@ -402,7 +407,7 @@ SharedNodePointer LimitedNodeList::addOrUpdateNode(const QUuid& uuid, NodeType_t Node* newNode = new Node(uuid, nodeType, publicSocket, localSocket); SharedNodePointer newNodeSharedPointer(newNode, &QObject::deleteLater); - _nodeHash.insert(newNode->getUUID(), newNodeSharedPointer); + _nodeHash.insert(UUIDNodePair(newNode->getUUID(), newNodeSharedPointer)); qDebug() << "Added" << *newNode; @@ -415,13 +420,12 @@ SharedNodePointer LimitedNodeList::addOrUpdateNode(const QUuid& uuid, NodeType_t unsigned LimitedNodeList::broadcastToNodes(const QByteArray& packet, const NodeSet& destinationNodeTypes) { unsigned n = 0; - NodeHashSnapshot snapshotHash = _nodeHash.snapshot_table(); - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { - if (destinationNodeTypes.contains(it->second->getType())) { - writeDatagram(packet, it->second); + eachNode([&](const SharedNodePointer& node){ + if (destinationNodeTypes.contains(node->getType())) { + writeDatagram(packet, node); ++n; } - } + }); return n; } @@ -460,17 +464,9 @@ QByteArray LimitedNodeList::constructPingReplyPacket(const QByteArray& pingPacke } SharedNodePointer LimitedNodeList::soloNodeOfType(char nodeType) { - - if (memchr(SOLO_NODE_TYPES, nodeType, sizeof(SOLO_NODE_TYPES))) { - NodeHashSnapshot snapshotHash = _nodeHash.snapshot_table(); - - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { - if (it->second->getType() == nodeType) { - return it->second; - } - } - } - return SharedNodePointer(); + return nodeMatchingPredicate([&](const SharedNodePointer& node){ + return node->getType() == nodeType; + }); } void LimitedNodeList::getPacketStats(float& packetsPerSecond, float& bytesPerSecond) { @@ -485,20 +481,21 @@ void LimitedNodeList::resetPacketStats() { } void LimitedNodeList::removeSilentNodes() { - - NodeHashSnapshot snapshotHash = _nodeHash.snapshot_table(); - - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + eachNodeHashIterator([this](NodeHash::iterator& it){ SharedNodePointer node = it->second; node->getMutex().lock(); if ((usecTimestampNow() - node->getLastHeardMicrostamp()) > (NODE_SILENCE_THRESHOLD_MSECS * 1000)) { // call the NodeHash erase to get rid of this node - _nodeHash.erase(it->first); + it = _nodeHash.unsafe_erase(it); + emit nodeKilled(node); + } else { + // we didn't erase this node, push the iterator forwards + ++it; } node->getMutex().unlock(); - } + }); } const uint32_t RFC_5389_MAGIC_COOKIE = 0x2112A442; diff --git a/libraries/networking/src/LimitedNodeList.h b/libraries/networking/src/LimitedNodeList.h index 63f93458f3..c7a8ccecf5 100644 --- a/libraries/networking/src/LimitedNodeList.h +++ b/libraries/networking/src/LimitedNodeList.h @@ -20,19 +20,18 @@ #include // not on windows, not needed for mac or windows #endif -#include -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include -#include +#include #include "DomainHandler.h" #include "Node.h" -#include "UUIDCityHasher.h" +#include "UUIDHasher.h" const int MAX_PACKET_SIZE = 1500; @@ -54,8 +53,9 @@ typedef QSet NodeSet; typedef QSharedPointer SharedNodePointer; Q_DECLARE_METATYPE(SharedNodePointer) -typedef cuckoohash_map NodeHash; -typedef std::vector > NodeHashSnapshot; +using namespace tbb; +typedef std::pair UUIDNodePair; +typedef concurrent_unordered_map NodeHash; typedef quint8 PingType_t; namespace PingType { @@ -74,7 +74,6 @@ public: const QUuid& getSessionUUID() const { return _sessionUUID; } void setSessionUUID(const QUuid& sessionUUID); - void rebindNodeSocket(); QUdpSocket& getNodeSocket() { return _nodeSocket; } QUdpSocket& getDTLSSocket(); @@ -95,11 +94,10 @@ public: const HifiSockAddr& overridenSockAddr = HifiSockAddr()); void(*linkedDataCreateCallback)(Node *); - - const NodeHash& getNodeHash() { return _nodeHash; } + int size() const { return _nodeHash.size(); } - SharedNodePointer nodeWithUUID(const QUuid& nodeUUID, bool blockingLock = true); + SharedNodePointer nodeWithUUID(const QUuid& nodeUUID); SharedNodePointer sendingNodeForPacket(const QByteArray& packet); SharedNodePointer addOrUpdateNode(const QUuid& uuid, NodeType_t nodeType, @@ -128,6 +126,29 @@ public: void sendHeartbeatToIceServer(const HifiSockAddr& iceServerSockAddr, QUuid headerID = QUuid(), const QUuid& connectRequestID = QUuid()); + + template + void eachNode(NodeLambda functor) { + QReadLocker readLock(&_nodeMutex); + + for (NodeHash::const_iterator it = _nodeHash.cbegin(); it != _nodeHash.cend(); ++it) { + functor(it->second); + } + } + + template + SharedNodePointer nodeMatchingPredicate(const PredLambda predicate) { + QReadLocker readLock(&_nodeMutex); + + for (NodeHash::const_iterator it = _nodeHash.cbegin(); it != _nodeHash.cend(); ++it) { + if (predicate(it->second)) { + return it->second; + } + } + + return SharedNodePointer(); + } + public slots: void reset(); void eraseAllNodes(); @@ -158,6 +179,7 @@ protected: QUuid _sessionUUID; NodeHash _nodeHash; + QReadWriteLock _nodeMutex; QUdpSocket _nodeSocket; QUdpSocket* _dtlsSocket; HifiSockAddr _localSockAddr; @@ -166,6 +188,17 @@ protected: int _numCollectedPackets; int _numCollectedBytes; QElapsedTimer _packetStatTimer; + + template + void eachNodeHashIterator(IteratorLambda functor) { + QWriteLocker writeLock(&_nodeMutex); + NodeHash::iterator it = _nodeHash.begin(); + + while (it != _nodeHash.end()) { + functor(it); + } + } + }; #endif // hifi_LimitedNodeList_h diff --git a/libraries/networking/src/NodeList.cpp b/libraries/networking/src/NodeList.cpp index fe8efe42c4..bf992e7b88 100644 --- a/libraries/networking/src/NodeList.cpp +++ b/libraries/networking/src/NodeList.cpp @@ -449,13 +449,12 @@ void NodeList::pingPunchForInactiveNode(const SharedNodePointer& node) { } void NodeList::pingInactiveNodes() { - NodeHashSnapshot snapshotHash = _nodeHash.snapshot_table(); - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { - if (!it->second->getActiveSocket()) { + eachNode([this](const SharedNodePointer& node){ + if (!node->getActiveSocket()) { // we don't have an active link to this node, ping it to set that up - pingPunchForInactiveNode(it->second); + pingPunchForInactiveNode(node); } - } + }); } void NodeList::activateSocketFromNodeCommunication(const QByteArray& packet, const SharedNodePointer& sendingNode) { diff --git a/libraries/networking/src/UUIDCityHasher.cpp b/libraries/networking/src/UUIDCityHasher.cpp deleted file mode 100644 index 731e287fc0..0000000000 --- a/libraries/networking/src/UUIDCityHasher.cpp +++ /dev/null @@ -1,12 +0,0 @@ -// -// UUIDCityHasher.cpp -// libraries/networking/src -// -// Created by Stephen Birarda on 2014-11-05. -// Copyright 2014 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -#include "UUIDCityHasher.h" diff --git a/libraries/networking/src/UUIDCityHasher.h b/libraries/networking/src/UUIDCityHasher.h deleted file mode 100644 index e27e3bdf1b..0000000000 --- a/libraries/networking/src/UUIDCityHasher.h +++ /dev/null @@ -1,26 +0,0 @@ -// -// UUIDCityHasher.h -// libraries/networking/src -// -// Created by Stephen Birarda on 2014-11-05. -// Copyright 2014 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -#ifndef hifi_UUIDCityHasher_h -#define hifi_UUIDCityHasher_h - -#include - -#include "UUID.h" - -class UUIDCityHasher { -public: - size_t operator()(const QUuid& key) const { - return CityHash64(key.toRfc4122().constData(), NUM_BYTES_RFC4122_UUID); - } -}; - -#endif // hifi_UUIDCityHasher_h \ No newline at end of file diff --git a/libraries/networking/src/UUIDHasher.h b/libraries/networking/src/UUIDHasher.h new file mode 100644 index 0000000000..d5d16e21e9 --- /dev/null +++ b/libraries/networking/src/UUIDHasher.h @@ -0,0 +1,26 @@ +// +// UUIDHasher.h +// libraries/networking/src +// +// Created by Stephen Birarda on 2014-11-05. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef hifi_UUIDHasher_h +#define hifi_UUIDHasher_h + +#include "UUID.h" + +class UUIDHasher { +public: + size_t operator()(const QUuid& uuid) const { + return uuid.data1 ^ uuid.data2 ^ (uuid.data3 << 16) + ^ ((uuid.data4[0] << 24) | (uuid.data4[1] << 16) | (uuid.data4[2] << 8) | uuid.data4[3]) + ^ ((uuid.data4[4] << 24) | (uuid.data4[5] << 16) | (uuid.data4[6] << 8) | uuid.data4[7]); + } +}; + +#endif // hifi_UUIDHasher_h \ No newline at end of file From c80633499fbfc67f87cbb2e363e9771630b36044 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 6 Nov 2014 11:35:07 -0800 Subject: [PATCH 014/258] make eachNode callers return bool to say if iteration should continue --- libraries/networking/src/LimitedNodeList.cpp | 2 ++ libraries/networking/src/LimitedNodeList.h | 4 +++- libraries/networking/src/NodeList.cpp | 2 ++ libraries/octree/src/JurisdictionListener.cpp | 14 ++++++-------- libraries/octree/src/OctreeEditPacketSender.cpp | 13 ++++++------- 5 files changed, 19 insertions(+), 16 deletions(-) diff --git a/libraries/networking/src/LimitedNodeList.cpp b/libraries/networking/src/LimitedNodeList.cpp index 818d35c0e5..2661c83b5c 100644 --- a/libraries/networking/src/LimitedNodeList.cpp +++ b/libraries/networking/src/LimitedNodeList.cpp @@ -425,6 +425,8 @@ unsigned LimitedNodeList::broadcastToNodes(const QByteArray& packet, const NodeS writeDatagram(packet, node); ++n; } + + return true; }); return n; diff --git a/libraries/networking/src/LimitedNodeList.h b/libraries/networking/src/LimitedNodeList.h index c7a8ccecf5..750e5b8688 100644 --- a/libraries/networking/src/LimitedNodeList.h +++ b/libraries/networking/src/LimitedNodeList.h @@ -132,7 +132,9 @@ public: QReadLocker readLock(&_nodeMutex); for (NodeHash::const_iterator it = _nodeHash.cbegin(); it != _nodeHash.cend(); ++it) { - functor(it->second); + if (!functor(it->second)) { + break; + } } } diff --git a/libraries/networking/src/NodeList.cpp b/libraries/networking/src/NodeList.cpp index bf992e7b88..7271dfe446 100644 --- a/libraries/networking/src/NodeList.cpp +++ b/libraries/networking/src/NodeList.cpp @@ -454,6 +454,8 @@ void NodeList::pingInactiveNodes() { // we don't have an active link to this node, ping it to set that up pingPunchForInactiveNode(node); } + + return true; }); } diff --git a/libraries/octree/src/JurisdictionListener.cpp b/libraries/octree/src/JurisdictionListener.cpp index 606a6c13f2..f16daf9f0d 100644 --- a/libraries/octree/src/JurisdictionListener.cpp +++ b/libraries/octree/src/JurisdictionListener.cpp @@ -38,16 +38,14 @@ bool JurisdictionListener::queueJurisdictionRequest() { int sizeOut = populatePacketHeader(reinterpret_cast(bufferOut), PacketTypeJurisdictionRequest); int nodeCount = 0; - NodeList* nodeList = NodeList::getInstance(); - - NodeHashSnapshot nodeHashSnapshot = nodeList->getNodeHash().snapshot_table(); - - for (auto it = nodeHashSnapshot.begin(); it != nodeHashSnapshot.end(); it++) { - if (it->second->getType() == getNodeType() && it->second->getActiveSocket()) { - _packetSender.queuePacketForSending(it->second, QByteArray(reinterpret_cast(bufferOut), sizeOut)); + NodeList::getInstance()->eachNode([&](const SharedNodePointer& node) { + if (node->getType() == getNodeType() && node->getActiveSocket()) { + _packetSender.queuePacketForSending(node, QByteArray(reinterpret_cast(bufferOut), sizeOut)); nodeCount++; } - } + + return true; + }); if (nodeCount > 0){ _packetSender.setPacketsPerSecond(nodeCount); diff --git a/libraries/octree/src/OctreeEditPacketSender.cpp b/libraries/octree/src/OctreeEditPacketSender.cpp index 19de2e37e9..1a126576d3 100644 --- a/libraries/octree/src/OctreeEditPacketSender.cpp +++ b/libraries/octree/src/OctreeEditPacketSender.cpp @@ -51,12 +51,8 @@ OctreeEditPacketSender::~OctreeEditPacketSender() { bool OctreeEditPacketSender::serversExist() const { bool hasServers = false; bool atLeastOneJurisdictionMissing = false; // assume the best - NodeList* nodeList = NodeList::getInstance(); - NodeHashSnapshot snapshotHash = nodeList->getNodeHash().snapshot_table(); - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { - // only send to the NodeTypes that are getMyNodeType() - SharedNodePointer node = it->second; + NodeList::getInstance()->eachNode([&](const SharedNodePointer& node){ if (node->getType() == getMyNodeType() && node->getActiveSocket()) { QUuid nodeUUID = node->getUUID(); @@ -72,10 +68,13 @@ bool OctreeEditPacketSender::serversExist() const { } hasServers = true; } + if (atLeastOneJurisdictionMissing) { - break; // no point in looking further... + return false; // no point in looking further - return false from anonymous function + } else { + return true; } - } + }); return (hasServers && !atLeastOneJurisdictionMissing); } From da8fc5d5c578efb0dcc29c599c45cc00c15dd886 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 6 Nov 2014 11:43:20 -0800 Subject: [PATCH 015/258] migrate octree library to tbb concurrent map --- .../octree/src/OctreeEditPacketSender.cpp | 108 +++++++++--------- libraries/octree/src/OctreeHeadlessViewer.cpp | 54 ++++----- 2 files changed, 79 insertions(+), 83 deletions(-) diff --git a/libraries/octree/src/OctreeEditPacketSender.cpp b/libraries/octree/src/OctreeEditPacketSender.cpp index 1a126576d3..c0866a981e 100644 --- a/libraries/octree/src/OctreeEditPacketSender.cpp +++ b/libraries/octree/src/OctreeEditPacketSender.cpp @@ -85,54 +85,50 @@ void OctreeEditPacketSender::queuePacketToNode(const QUuid& nodeUUID, unsigned c size_t length, qint64 satoshiCost) { bool wantDebug = false; - NodeList* nodeList = NodeList::getInstance(); - - NodeHashSnapshot snapshotHash = nodeList->getNodeHash().snapshot_table(); - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { - SharedNodePointer node = it->second; - + NodeList::getInstance()->eachNode([&](const SharedNodePointer& node){ // only send to the NodeTypes that are getMyNodeType() - if (node->getType() == getMyNodeType() && - ((node->getUUID() == nodeUUID) || (nodeUUID.isNull()))) { - if (node->getActiveSocket()) { - - // pack sequence number - int numBytesPacketHeader = numBytesForPacketHeader(reinterpret_cast(buffer)); - unsigned char* sequenceAt = buffer + numBytesPacketHeader; - quint16 sequence = _outgoingSequenceNumbers[nodeUUID]++; - memcpy(sequenceAt, &sequence, sizeof(quint16)); + if (node->getType() == getMyNodeType() + && ((node->getUUID() == nodeUUID) || (nodeUUID.isNull())) + && node->getActiveSocket()) { + + // pack sequence number + int numBytesPacketHeader = numBytesForPacketHeader(reinterpret_cast(buffer)); + unsigned char* sequenceAt = buffer + numBytesPacketHeader; + quint16 sequence = _outgoingSequenceNumbers[nodeUUID]++; + memcpy(sequenceAt, &sequence, sizeof(quint16)); + + // send packet + QByteArray packet(reinterpret_cast(buffer), length); + + queuePacketForSending(node, packet); + + if (hasDestinationWalletUUID() && satoshiCost > 0) { + // if we have a destination wallet UUID and a cost associated with this packet, signal that it + // needs to be sent + emit octreePaymentRequired(satoshiCost, nodeUUID, _destinationWalletUUID); + } + + // add packet to history + _sentPacketHistories[nodeUUID].packetSent(sequence, packet); + + // debugging output... + if (wantDebug) { + int numBytesPacketHeader = numBytesForPacketHeader(reinterpret_cast(buffer)); + unsigned short int sequence = (*((unsigned short int*)(buffer + numBytesPacketHeader))); + quint64 createdAt = (*((quint64*)(buffer + numBytesPacketHeader + sizeof(sequence)))); + quint64 queuedAt = usecTimestampNow(); + quint64 transitTime = queuedAt - createdAt; - // send packet - QByteArray packet(reinterpret_cast(buffer), length); - - queuePacketForSending(node, packet); - - if (hasDestinationWalletUUID() && satoshiCost > 0) { - // if we have a destination wallet UUID and a cost associated with this packet, signal that it - // needs to be sent - emit octreePaymentRequired(satoshiCost, nodeUUID, _destinationWalletUUID); - } - - // add packet to history - _sentPacketHistories[nodeUUID].packetSent(sequence, packet); - - // debugging output... - if (wantDebug) { - int numBytesPacketHeader = numBytesForPacketHeader(reinterpret_cast(buffer)); - unsigned short int sequence = (*((unsigned short int*)(buffer + numBytesPacketHeader))); - quint64 createdAt = (*((quint64*)(buffer + numBytesPacketHeader + sizeof(sequence)))); - quint64 queuedAt = usecTimestampNow(); - quint64 transitTime = queuedAt - createdAt; - - qDebug() << "OctreeEditPacketSender::queuePacketToNode() queued " << buffer[0] << - " - command to node bytes=" << length << - " satoshiCost=" << satoshiCost << - " sequence=" << sequence << - " transitTimeSoFar=" << transitTime << " usecs"; - } + qDebug() << "OctreeEditPacketSender::queuePacketToNode() queued " << buffer[0] << + " - command to node bytes=" << length << + " satoshiCost=" << satoshiCost << + " sequence=" << sequence << + " transitTimeSoFar=" << transitTime << " usecs"; } } - } + + return true; + }); } void OctreeEditPacketSender::processPreServerExistsPackets() { @@ -198,9 +194,7 @@ void OctreeEditPacketSender::queuePacketToNodes(unsigned char* buffer, size_t le // for a different server... So we need to actually manage multiple queued packets... one // for each server - NodeHashSnapshot snapshotHash = NodeList::getInstance()->getNodeHash().snapshot_table(); - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { - SharedNodePointer node = it->second; + NodeList::getInstance()->eachNode([&](const SharedNodePointer& node){ // only send to the NodeTypes that are getMyNodeType() if (node->getActiveSocket() && node->getType() == getMyNodeType()) { QUuid nodeUUID = node->getUUID(); @@ -215,7 +209,9 @@ void OctreeEditPacketSender::queuePacketToNodes(unsigned char* buffer, size_t le queuePacketToNode(nodeUUID, buffer, length, satoshiCost); } } - } + + return true; + }); } @@ -254,9 +250,7 @@ void OctreeEditPacketSender::queueOctreeEditMessage(PacketType type, unsigned ch _packetsQueueLock.lock(); - NodeHashSnapshot snapshotHash = NodeList::getInstance()->getNodeHash().snapshot_table(); - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { - SharedNodePointer node = it->second; + NodeList::getInstance()->eachNode([&](const SharedNodePointer& node){ // only send to the NodeTypes that are getMyNodeType() if (node->getActiveSocket() && node->getType() == getMyNodeType()) { QUuid nodeUUID = node->getUUID(); @@ -279,19 +273,19 @@ void OctreeEditPacketSender::queueOctreeEditMessage(PacketType type, unsigned ch if (isMyJurisdiction) { EditPacketBuffer& packetBuffer = _pendingEditPackets[nodeUUID]; packetBuffer._nodeUUID = nodeUUID; - + // If we're switching type, then we send the last one and start over if ((type != packetBuffer._currentType && packetBuffer._currentSize > 0) || (packetBuffer._currentSize + length >= (size_t)_maxPacketSize)) { releaseQueuedPacket(packetBuffer); initializePacket(packetBuffer, type); } - + // If the buffer is empty and not correctly initialized for our type... if (type != packetBuffer._currentType && packetBuffer._currentSize == 0) { initializePacket(packetBuffer, type); } - + // This is really the first time we know which server/node this particular edit message // is going to, so we couldn't adjust for clock skew till now. But here's our chance. // We call this virtual function that allows our specific type of EditPacketSender to @@ -299,13 +293,15 @@ void OctreeEditPacketSender::queueOctreeEditMessage(PacketType type, unsigned ch if (node->getClockSkewUsec() != 0) { adjustEditPacketForClockSkew(type, editPacketBuffer, length, node->getClockSkewUsec()); } - + memcpy(&packetBuffer._currentBuffer[packetBuffer._currentSize], editPacketBuffer, length); packetBuffer._currentSize += length; packetBuffer._satoshiCost += satoshiCost; } } - } + + return true; + }); _packetsQueueLock.unlock(); diff --git a/libraries/octree/src/OctreeHeadlessViewer.cpp b/libraries/octree/src/OctreeHeadlessViewer.cpp index b363c654c1..e40ae712e9 100644 --- a/libraries/octree/src/OctreeHeadlessViewer.cpp +++ b/libraries/octree/src/OctreeHeadlessViewer.cpp @@ -77,16 +77,14 @@ void OctreeHeadlessViewer::queryOctree() { int inViewServers = 0; int unknownJurisdictionServers = 0; - NodeHashSnapshot snapshotHash = NodeList::getInstance()->getNodeHash().snapshot_table(); - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { - SharedNodePointer node = it->second; + NodeList::getInstance()->eachNode([&](const SharedNodePointer& node){ // only send to the NodeTypes that are serverType if (node->getActiveSocket() && node->getType() == serverType) { totalServers++; - + // get the server bounds for this server QUuid nodeUUID = node->getUUID(); - + // if we haven't heard from this voxel server, go ahead and send it a query, so we // can get the jurisdiction... jurisdictions.lockForRead(); @@ -95,18 +93,18 @@ void OctreeHeadlessViewer::queryOctree() { unknownJurisdictionServers++; } else { const JurisdictionMap& map = (jurisdictions)[nodeUUID]; - + unsigned char* rootCode = map.getRootOctalCode(); - + if (rootCode) { VoxelPositionSize rootDetails; voxelDetailsForCode(rootCode, rootDetails); jurisdictions.unlock(); AACube serverBounds(glm::vec3(rootDetails.x, rootDetails.y, rootDetails.z), rootDetails.s); serverBounds.scale(TREE_SCALE); - + ViewFrustum::location serverFrustumLocation = _viewFrustum.cubeInFrustum(serverBounds); - + if (serverFrustumLocation != ViewFrustum::OUTSIDE) { inViewServers++; } @@ -115,7 +113,9 @@ void OctreeHeadlessViewer::queryOctree() { } } } - } + + return true; + }); if (wantExtraDebugging) { qDebug("Servers: total %d, in view %d, unknown jurisdiction %d", @@ -143,18 +143,16 @@ void OctreeHeadlessViewer::queryOctree() { } NodeList* nodeList = NodeList::getInstance(); - - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { - SharedNodePointer node = it->second; + nodeList->eachNode([&](const SharedNodePointer& node){ // only send to the NodeTypes that are serverType if (node->getActiveSocket() && node->getType() == serverType) { - + // get the server bounds for this server QUuid nodeUUID = node->getUUID(); - + bool inView = false; bool unknownView = false; - + // if we haven't heard from this voxel server, go ahead and send it a query, so we // can get the jurisdiction... jurisdictions.lockForRead(); @@ -166,16 +164,16 @@ void OctreeHeadlessViewer::queryOctree() { } } else { const JurisdictionMap& map = (jurisdictions)[nodeUUID]; - + unsigned char* rootCode = map.getRootOctalCode(); - + if (rootCode) { VoxelPositionSize rootDetails; voxelDetailsForCode(rootCode, rootDetails); jurisdictions.unlock(); AACube serverBounds(glm::vec3(rootDetails.x, rootDetails.y, rootDetails.z), rootDetails.s); serverBounds.scale(TREE_SCALE); - + ViewFrustum::location serverFrustumLocation = _viewFrustum.cubeInFrustum(serverBounds); if (serverFrustumLocation != ViewFrustum::OUTSIDE) { inView = true; @@ -189,7 +187,7 @@ void OctreeHeadlessViewer::queryOctree() { } } } - + if (inView) { _octreeQuery.setMaxOctreePacketsPerSecond(perServerPPS); if (wantExtraDebugging) { @@ -198,9 +196,9 @@ void OctreeHeadlessViewer::queryOctree() { } else if (unknownView) { if (wantExtraDebugging) { qDebug() << "no known jurisdiction for node " << *node << ", give it budget of " - << perUnknownServer << " to send us jurisdiction."; + << perUnknownServer << " to send us jurisdiction."; } - + // set the query's position/orientation to be degenerate in a manner that will get the scene quickly // If there's only one server, then don't do this, and just let the normal voxel query pass through // as expected... this way, we will actually get a valid scene if there is one to be seen @@ -224,19 +222,21 @@ void OctreeHeadlessViewer::queryOctree() { } // set up the packet for sending... unsigned char* endOfQueryPacket = queryPacket; - + // insert packet type/version and node UUID endOfQueryPacket += populatePacketHeader(reinterpret_cast(endOfQueryPacket), packetType); - + // encode the query data... endOfQueryPacket += _octreeQuery.getBroadcastData(endOfQueryPacket); - + int packetLength = endOfQueryPacket - queryPacket; - + // make sure we still have an active socket nodeList->writeUnverifiedDatagram(reinterpret_cast(queryPacket), packetLength, node); } - } + + return true; + }); } From 270823be438184199866abb885a2c475a84e65cd Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 6 Nov 2014 13:39:15 -0800 Subject: [PATCH 016/258] update domain-server to leverage intel tbb hash --- domain-server/src/DomainServer.cpp | 100 ++++++++----------- libraries/networking/src/LimitedNodeList.cpp | 7 +- 2 files changed, 42 insertions(+), 65 deletions(-) diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index 5dddfd70dd..cbd70f9edc 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -821,52 +821,50 @@ void DomainServer::sendDomainListToNode(const SharedNodePointer& node, const Hif if (nodeData->isAuthenticated()) { // if this authenticated node has any interest types, send back those nodes as well - NodeHashSnapshot snapshotHash = nodeList->getNodeHash().snapshot_table(); - - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { - SharedNodePointer otherNode = it->second; - + nodeList->eachNode([&](const SharedNodePointer& otherNode){ // reset our nodeByteArray and nodeDataStream QByteArray nodeByteArray; QDataStream nodeDataStream(&nodeByteArray, QIODevice::Append); - + if (otherNode->getUUID() != node->getUUID() && nodeInterestList.contains(otherNode->getType())) { - + // don't send avatar nodes to other avatars, that will come from avatar mixer nodeDataStream << *otherNode.data(); - + // pack the secret that these two nodes will use to communicate with each other QUuid secretUUID = nodeData->getSessionSecretHash().value(otherNode->getUUID()); if (secretUUID.isNull()) { // generate a new secret UUID these two nodes can use secretUUID = QUuid::createUuid(); - + // set that on the current Node's sessionSecretHash nodeData->getSessionSecretHash().insert(otherNode->getUUID(), secretUUID); - + // set it on the other Node's sessionSecretHash reinterpret_cast(otherNode->getLinkedData()) ->getSessionSecretHash().insert(node->getUUID(), secretUUID); - + } - + nodeDataStream << secretUUID; - + if (broadcastPacket.size() + nodeByteArray.size() > dataMTU) { // we need to break here and start a new packet // so send the current one - + nodeList->writeDatagram(broadcastPacket, node, senderSockAddr); - + // reset the broadcastPacket structure broadcastPacket.resize(numBroadcastPacketLeadBytes); broadcastDataStream.device()->seek(numBroadcastPacketLeadBytes); } - + // append the nodeByteArray to the current state of broadcastDataStream broadcastPacket.append(nodeByteArray); } - } + + return true; + }); } // always write the last broadcastPacket @@ -963,17 +961,14 @@ void DomainServer::readAvailableDatagrams() { void DomainServer::setupPendingAssignmentCredits() { // enumerate the NodeList to find the assigned nodes - NodeHashSnapshot snapshotHash = NodeList::getInstance()->getNodeHash().snapshot_table(); - - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { - SharedNodePointer node = it->second; + NodeList::getInstance()->eachNode([&](const SharedNodePointer& node){ DomainServerNodeData* nodeData = reinterpret_cast(node->getLinkedData()); - + if (!nodeData->getAssignmentUUID().isNull() && !nodeData->getWalletUUID().isNull()) { // check if we have a non-finalized transaction for this node to add this amount to TransactionHash::iterator i = _pendingAssignmentCredits.find(nodeData->getWalletUUID()); WalletTransaction* existingTransaction = NULL; - + while (i != _pendingAssignmentCredits.end() && i.key() == nodeData->getWalletUUID()) { if (!i.value()->isFinalized()) { existingTransaction = i.value(); @@ -982,16 +977,16 @@ void DomainServer::setupPendingAssignmentCredits() { ++i; } } - + qint64 elapsedMsecsSinceLastPayment = nodeData->getPaymentIntervalTimer().elapsed(); nodeData->getPaymentIntervalTimer().restart(); - + const float CREDITS_PER_HOUR = 0.10f; const float CREDITS_PER_MSEC = CREDITS_PER_HOUR / (60 * 60 * 1000); const int SATOSHIS_PER_MSEC = CREDITS_PER_MSEC * SATOSHIS_PER_CREDIT; - + float pendingCredits = elapsedMsecsSinceLastPayment * SATOSHIS_PER_MSEC; - + if (existingTransaction) { existingTransaction->incrementAmount(pendingCredits); } else { @@ -1000,7 +995,9 @@ void DomainServer::setupPendingAssignmentCredits() { _pendingAssignmentCredits.insert(nodeData->getWalletUUID(), freshTransaction); } } - } + + return true; + }); } void DomainServer::sendPendingTransactionsToServer() { @@ -1126,16 +1123,13 @@ void DomainServer::sendHeartbeatToDataServer(const QString& networkAddress) { // add the number of currently connected agent users int numConnectedAuthedUsers = 0; - NodeHashSnapshot snapshotHash = NodeList::getInstance()->getNodeHash().snapshot_table(); - - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { - - SharedNodePointer node = it->second; - + NodeList::getInstance()->eachNode([&numConnectedAuthedUsers](const SharedNodePointer& node){ if (node->getLinkedData() && !static_cast(node->getLinkedData())->getUsername().isEmpty()) { ++numConnectedAuthedUsers; } - } + + return true; + }); const QString DOMAIN_HEARTBEAT_KEY = "heartbeat"; const QString HEARTBEAT_NUM_USERS_KEY = "num_users"; @@ -1438,20 +1432,17 @@ bool DomainServer::handleHTTPRequest(HTTPConnection* connection, const QUrl& url QJsonObject assignedNodesJSON; // enumerate the NodeList to find the assigned nodes - NodeHashSnapshot snapshotHash = NodeList::getInstance()->getNodeHash().snapshot_table(); - - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { - - SharedNodePointer node = it->second; - + NodeList::getInstance()->eachNode([this, &assignedNodesJSON](const SharedNodePointer& node){ DomainServerNodeData* nodeData = reinterpret_cast(node->getLinkedData()); - + if (!nodeData->getAssignmentUUID().isNull()) { // add the node using the UUID as the key QString uuidString = uuidStringWithoutCurlyBraces(nodeData->getAssignmentUUID()); assignedNodesJSON[uuidString] = jsonObjectForNode(node); } - } + + return true; + }); assignmentJSON["fulfilled"] = assignedNodesJSON; @@ -1505,14 +1496,12 @@ bool DomainServer::handleHTTPRequest(HTTPConnection* connection, const QUrl& url QJsonArray nodesJSONArray; // enumerate the NodeList to find the assigned nodes - LimitedNodeList* nodeList = LimitedNodeList::getInstance(); - - NodeHashSnapshot snapshotHash = nodeList->getNodeHash().snapshot_table(); - - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + LimitedNodeList::getInstance()->eachNode([this, &nodesJSONArray](const SharedNodePointer& node){ // add the node using the UUID as the key - nodesJSONArray.append(jsonObjectForNode(it->second)); - } + nodesJSONArray.append(jsonObjectForNode(node)); + + return true; + }); rootJSON["nodes"] = nodesJSONArray; @@ -2040,18 +2029,9 @@ void DomainServer::addStaticAssignmentsToQueue() { QHash::iterator staticAssignment = staticHashCopy.begin(); while (staticAssignment != staticHashCopy.end()) { // add any of the un-matched static assignments to the queue - bool foundMatchingAssignment = false; // enumerate the nodes and check if there is one with an attached assignment with matching UUID - NodeHashSnapshot snapshotHash = NodeList::getInstance()->getNodeHash().snapshot_table(); - - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { - if (it->first == staticAssignment->data()->getUUID()) { - foundMatchingAssignment = true; - } - } - - if (!foundMatchingAssignment) { + if (NodeList::getInstance()->nodeWithUUID(staticAssignment->data()->getUUID())) { // this assignment has not been fulfilled - reset the UUID and add it to the assignment queue refreshStaticAssignmentAndAddToQueue(*staticAssignment); } diff --git a/libraries/networking/src/LimitedNodeList.cpp b/libraries/networking/src/LimitedNodeList.cpp index 2661c83b5c..4202444749 100644 --- a/libraries/networking/src/LimitedNodeList.cpp +++ b/libraries/networking/src/LimitedNodeList.cpp @@ -345,11 +345,8 @@ int LimitedNodeList::findNodeAndUpdateWithDataFromPacket(const QByteArray& packe } SharedNodePointer LimitedNodeList::nodeWithUUID(const QUuid& nodeUUID) { - try { - return _nodeHash.at(nodeUUID); - } catch (std::out_of_range) { - return SharedNodePointer(); - } + NodeHash::const_iterator it = _nodeHash.find(nodeUUID); + return it == _nodeHash.cend() ? SharedNodePointer() : it->second; } SharedNodePointer LimitedNodeList::sendingNodeForPacket(const QByteArray& packet) { From e92376cf649192a5480d53332bcbb08c9749f41c Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 6 Nov 2014 13:41:55 -0800 Subject: [PATCH 017/258] distinguish between eachNode and eachNodeBreakable --- domain-server/src/DomainServer.cpp | 10 ---------- libraries/networking/src/LimitedNodeList.cpp | 2 -- libraries/networking/src/LimitedNodeList.h | 9 +++++++++ libraries/networking/src/NodeList.cpp | 2 -- libraries/octree/src/JurisdictionListener.cpp | 2 -- libraries/octree/src/OctreeEditPacketSender.cpp | 8 +------- libraries/octree/src/OctreeHeadlessViewer.cpp | 4 ---- 7 files changed, 10 insertions(+), 27 deletions(-) diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index cbd70f9edc..cb4b1c8026 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -862,8 +862,6 @@ void DomainServer::sendDomainListToNode(const SharedNodePointer& node, const Hif // append the nodeByteArray to the current state of broadcastDataStream broadcastPacket.append(nodeByteArray); } - - return true; }); } @@ -995,8 +993,6 @@ void DomainServer::setupPendingAssignmentCredits() { _pendingAssignmentCredits.insert(nodeData->getWalletUUID(), freshTransaction); } } - - return true; }); } @@ -1127,8 +1123,6 @@ void DomainServer::sendHeartbeatToDataServer(const QString& networkAddress) { if (node->getLinkedData() && !static_cast(node->getLinkedData())->getUsername().isEmpty()) { ++numConnectedAuthedUsers; } - - return true; }); const QString DOMAIN_HEARTBEAT_KEY = "heartbeat"; @@ -1440,8 +1434,6 @@ bool DomainServer::handleHTTPRequest(HTTPConnection* connection, const QUrl& url QString uuidString = uuidStringWithoutCurlyBraces(nodeData->getAssignmentUUID()); assignedNodesJSON[uuidString] = jsonObjectForNode(node); } - - return true; }); assignmentJSON["fulfilled"] = assignedNodesJSON; @@ -1499,8 +1491,6 @@ bool DomainServer::handleHTTPRequest(HTTPConnection* connection, const QUrl& url LimitedNodeList::getInstance()->eachNode([this, &nodesJSONArray](const SharedNodePointer& node){ // add the node using the UUID as the key nodesJSONArray.append(jsonObjectForNode(node)); - - return true; }); rootJSON["nodes"] = nodesJSONArray; diff --git a/libraries/networking/src/LimitedNodeList.cpp b/libraries/networking/src/LimitedNodeList.cpp index 4202444749..ac63941882 100644 --- a/libraries/networking/src/LimitedNodeList.cpp +++ b/libraries/networking/src/LimitedNodeList.cpp @@ -422,8 +422,6 @@ unsigned LimitedNodeList::broadcastToNodes(const QByteArray& packet, const NodeS writeDatagram(packet, node); ++n; } - - return true; }); return n; diff --git a/libraries/networking/src/LimitedNodeList.h b/libraries/networking/src/LimitedNodeList.h index 750e5b8688..25c560b2e2 100644 --- a/libraries/networking/src/LimitedNodeList.h +++ b/libraries/networking/src/LimitedNodeList.h @@ -131,6 +131,15 @@ public: void eachNode(NodeLambda functor) { QReadLocker readLock(&_nodeMutex); + for (NodeHash::const_iterator it = _nodeHash.cbegin(); it != _nodeHash.cend(); ++it) { + functor(it->second); + } + } + + template + void eachNodeBreakable(BreakableNodeLambda functor) { + QReadLocker readLock(&_nodeMutex); + for (NodeHash::const_iterator it = _nodeHash.cbegin(); it != _nodeHash.cend(); ++it) { if (!functor(it->second)) { break; diff --git a/libraries/networking/src/NodeList.cpp b/libraries/networking/src/NodeList.cpp index 7271dfe446..bf992e7b88 100644 --- a/libraries/networking/src/NodeList.cpp +++ b/libraries/networking/src/NodeList.cpp @@ -454,8 +454,6 @@ void NodeList::pingInactiveNodes() { // we don't have an active link to this node, ping it to set that up pingPunchForInactiveNode(node); } - - return true; }); } diff --git a/libraries/octree/src/JurisdictionListener.cpp b/libraries/octree/src/JurisdictionListener.cpp index f16daf9f0d..bcd5e9ac1c 100644 --- a/libraries/octree/src/JurisdictionListener.cpp +++ b/libraries/octree/src/JurisdictionListener.cpp @@ -43,8 +43,6 @@ bool JurisdictionListener::queueJurisdictionRequest() { _packetSender.queuePacketForSending(node, QByteArray(reinterpret_cast(bufferOut), sizeOut)); nodeCount++; } - - return true; }); if (nodeCount > 0){ diff --git a/libraries/octree/src/OctreeEditPacketSender.cpp b/libraries/octree/src/OctreeEditPacketSender.cpp index c0866a981e..8c94316d28 100644 --- a/libraries/octree/src/OctreeEditPacketSender.cpp +++ b/libraries/octree/src/OctreeEditPacketSender.cpp @@ -52,7 +52,7 @@ bool OctreeEditPacketSender::serversExist() const { bool hasServers = false; bool atLeastOneJurisdictionMissing = false; // assume the best - NodeList::getInstance()->eachNode([&](const SharedNodePointer& node){ + NodeList::getInstance()->eachNodeBreakable([&](const SharedNodePointer& node){ if (node->getType() == getMyNodeType() && node->getActiveSocket()) { QUuid nodeUUID = node->getUUID(); @@ -126,8 +126,6 @@ void OctreeEditPacketSender::queuePacketToNode(const QUuid& nodeUUID, unsigned c " transitTimeSoFar=" << transitTime << " usecs"; } } - - return true; }); } @@ -209,8 +207,6 @@ void OctreeEditPacketSender::queuePacketToNodes(unsigned char* buffer, size_t le queuePacketToNode(nodeUUID, buffer, length, satoshiCost); } } - - return true; }); } @@ -299,8 +295,6 @@ void OctreeEditPacketSender::queueOctreeEditMessage(PacketType type, unsigned ch packetBuffer._satoshiCost += satoshiCost; } } - - return true; }); _packetsQueueLock.unlock(); diff --git a/libraries/octree/src/OctreeHeadlessViewer.cpp b/libraries/octree/src/OctreeHeadlessViewer.cpp index e40ae712e9..e0ca22e4e8 100644 --- a/libraries/octree/src/OctreeHeadlessViewer.cpp +++ b/libraries/octree/src/OctreeHeadlessViewer.cpp @@ -113,8 +113,6 @@ void OctreeHeadlessViewer::queryOctree() { } } } - - return true; }); if (wantExtraDebugging) { @@ -234,8 +232,6 @@ void OctreeHeadlessViewer::queryOctree() { // make sure we still have an active socket nodeList->writeUnverifiedDatagram(reinterpret_cast(queryPacket), packetLength, node); } - - return true; }); } From 948615afe5dc90e1187e1a2fff7493f9e8f19118 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 6 Nov 2014 13:44:03 -0800 Subject: [PATCH 018/258] move metavoxels library to tbb concurrent map --- .../metavoxels/src/MetavoxelClientManager.cpp | 18 ++++++------------ 1 file changed, 6 insertions(+), 12 deletions(-) diff --git a/libraries/metavoxels/src/MetavoxelClientManager.cpp b/libraries/metavoxels/src/MetavoxelClientManager.cpp index 7765b8cda2..3148f870c2 100644 --- a/libraries/metavoxels/src/MetavoxelClientManager.cpp +++ b/libraries/metavoxels/src/MetavoxelClientManager.cpp @@ -43,24 +43,22 @@ SharedObjectPointer MetavoxelClientManager::findFirstRaySpannerIntersection(cons SharedObjectPointer closestSpanner; float closestDistance = FLT_MAX; - NodeHashSnapshot snapshotHash = NodeList::getInstance()->getNodeHash().snapshot_table(); - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { - SharedNodePointer node = it->second; - + NodeList::getInstance()->eachNode([&](const SharedNodePointer& node){ if (node->getType() == NodeType::MetavoxelServer) { QMutexLocker locker(&node->getMutex()); MetavoxelClient* client = static_cast(node->getLinkedData()); if (client) { float clientDistance; SharedObjectPointer clientSpanner = client->getDataCopy().findFirstRaySpannerIntersection( - origin, direction, attribute, clientDistance); + origin, direction, attribute, clientDistance); if (clientSpanner && clientDistance < closestDistance) { closestSpanner = clientSpanner; closestDistance = clientDistance; } } } - } + }); + if (closestSpanner) { distance = closestDistance; } @@ -119,11 +117,7 @@ MetavoxelClient* MetavoxelClientManager::createClient(const SharedNodePointer& n } void MetavoxelClientManager::guide(MetavoxelVisitor& visitor) { - NodeHashSnapshot snapshotHash = NodeList::getInstance()->getNodeHash().snapshot_table(); - - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { - SharedNodePointer node = it->second; - + NodeList::getInstance()->eachNode([&visitor](const SharedNodePointer& node){ if (node->getType() == NodeType::MetavoxelServer) { QMutexLocker locker(&node->getMutex()); MetavoxelClient* client = static_cast(node->getLinkedData()); @@ -131,7 +125,7 @@ void MetavoxelClientManager::guide(MetavoxelVisitor& visitor) { client->getDataCopy().guide(visitor); } } - } + }); } MetavoxelUpdater::MetavoxelUpdater(MetavoxelClientManager* clientManager) : From 51bc5d10b55de0654f471c2be8978d7b48de2edb Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 6 Nov 2014 13:46:26 -0800 Subject: [PATCH 019/258] fix network includes in LimitedNodeList --- libraries/networking/src/LimitedNodeList.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libraries/networking/src/LimitedNodeList.h b/libraries/networking/src/LimitedNodeList.h index 25c560b2e2..a29902a7c9 100644 --- a/libraries/networking/src/LimitedNodeList.h +++ b/libraries/networking/src/LimitedNodeList.h @@ -24,8 +24,8 @@ #include #include #include -#include -#include +#include +#include #include From 38f2b2ac6a841dafe5afc70de01df83f39060e92 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 6 Nov 2014 13:47:56 -0800 Subject: [PATCH 020/258] move script-engine library to intel tbb concurrent map --- libraries/script-engine/src/ScriptEngine.cpp | 10 +++------- 1 file changed, 3 insertions(+), 7 deletions(-) diff --git a/libraries/script-engine/src/ScriptEngine.cpp b/libraries/script-engine/src/ScriptEngine.cpp index 340d5b3e20..5b5dd6cd53 100644 --- a/libraries/script-engine/src/ScriptEngine.cpp +++ b/libraries/script-engine/src/ScriptEngine.cpp @@ -520,21 +520,17 @@ void ScriptEngine::run() { // write audio packet to AudioMixer nodes NodeList* nodeList = NodeList::getInstance(); - NodeHashSnapshot snapshotHash = nodeList->getNodeHash().snapshot_table(); - - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { - SharedNodePointer node = it->second; - + nodeList->eachNode([this, &nodeList, &audioPacket, &numPreSequenceNumberBytes](const SharedNodePointer& node){ // only send to nodes of type AudioMixer if (node->getType() == NodeType::AudioMixer) { // pack sequence number quint16 sequence = _outgoingScriptAudioSequenceNumbers[node->getUUID()]++; memcpy(audioPacket.data() + numPreSequenceNumberBytes, &sequence, sizeof(quint16)); - + // send audio packet nodeList->writeDatagram(audioPacket, node); } - } + }); } } From 1a953b5906a9da2b6b29fc6c609180328cabf2b0 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 6 Nov 2014 13:53:10 -0800 Subject: [PATCH 021/258] migrate node hash calls from AudioMixer to new tbb format --- assignment-client/src/audio/AudioMixer.cpp | 52 +++++++------------ assignment-client/src/avatars/AvatarMixer.cpp | 12 ++--- 2 files changed, 22 insertions(+), 42 deletions(-) diff --git a/assignment-client/src/audio/AudioMixer.cpp b/assignment-client/src/audio/AudioMixer.cpp index 39011b8083..4236072857 100644 --- a/assignment-client/src/audio/AudioMixer.cpp +++ b/assignment-client/src/audio/AudioMixer.cpp @@ -438,16 +438,12 @@ int AudioMixer::prepareMixForListeningNode(Node* node) { // loop through all other nodes that have sufficient audio to mix int streamsMixed = 0; - NodeHashSnapshot snapshotHash = NodeList::getInstance()->getNodeHash().snapshot_table(); - - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { - SharedNodePointer otherNode = it->second; - + NodeList::getInstance()->eachNode([&](const SharedNodePointer& otherNode){ if (otherNode->getLinkedData()) { AudioMixerClientData* otherNodeClientData = (AudioMixerClientData*) otherNode->getLinkedData(); - + // enumerate the ARBs attached to the otherNode and add all that should be added to mix - + const QHash& otherNodeAudioStreams = otherNodeClientData->getAudioStreams(); QHash::ConstIterator i; for (i = otherNodeAudioStreams.constBegin(); i != otherNodeAudioStreams.constEnd(); i++) { @@ -457,14 +453,15 @@ int AudioMixer::prepareMixForListeningNode(Node* node) { if (otherNodeStream->getType() == PositionalAudioStream::Microphone) { streamUUID = otherNode->getUUID(); } - + if (*otherNode != *node || otherNodeStream->shouldLoopbackForNode()) { - streamsMixed += addStreamToMixForListeningNodeWithStream(listenerNodeData, streamUUID, - otherNodeStream, nodeAudioStream); + streamsMixed += addStreamToMixForListeningNodeWithStream(listenerNodeData, streamUUID, + otherNodeStream, nodeAudioStream); } } } - } + }); + return streamsMixed; } @@ -485,16 +482,11 @@ void AudioMixer::readPendingDatagram(const QByteArray& receivedPacket, const Hif QByteArray packet = receivedPacket; populatePacketHeader(packet, PacketTypeMuteEnvironment); - NodeHashSnapshot snapshotHash = nodeList->getNodeHash().snapshot_table(); - - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { - SharedNodePointer node = it->second; - + nodeList->eachNode([&](const SharedNodePointer& node){ if (node->getType() == NodeType::Agent && node->getActiveSocket() && node->getLinkedData() && node != nodeList->sendingNodeForPacket(receivedPacket)) { nodeList->writeDatagram(packet, packet.size(), node); } - } - + }); } else { // let processNodeData handle it. nodeList->processNodeData(senderSockAddr, receivedPacket); @@ -558,9 +550,8 @@ void AudioMixer::sendStatsPacket() { NodeList* nodeList = NodeList::getInstance(); int clientNumber = 0; - NodeHashSnapshot snapshotHash = nodeList->getNodeHash().snapshot_table(); - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { + nodeList->eachNode([&](const SharedNodePointer& node) { // if we're too large, send the packet if (sizeOfStats > TOO_BIG_FOR_MTU) { nodeList->sendStatsToDomainServer(statsObject2); @@ -570,15 +561,15 @@ void AudioMixer::sendStatsPacket() { } clientNumber++; - AudioMixerClientData* clientData = static_cast(it->second->getLinkedData()); + AudioMixerClientData* clientData = static_cast(node->getLinkedData()); if (clientData) { - QString property = "jitterStats." + it->first.toString(); + QString property = "jitterStats." + node->getUUID().toString(); QString value = clientData->getAudioStreamStatsString(); statsObject2[qPrintable(property)] = value; somethingToSend = true; sizeOfStats += property.size() + value.size(); } - } + }); if (somethingToSend) { nodeList->sendStatsToDomainServer(statsObject2); @@ -717,10 +708,7 @@ void AudioMixer::run() { _lastPerSecondCallbackTime = now; } - NodeHashSnapshot snapshotHash = nodeList->getNodeHash().snapshot_table(); - - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { - SharedNodePointer node = it->second; + nodeList->eachNode([&](const SharedNodePointer& node) { if (node->getLinkedData()) { AudioMixerClientData* nodeData = (AudioMixerClientData*)node->getLinkedData(); @@ -830,7 +818,7 @@ void AudioMixer::run() { ++_sumListeners; } } - } + }); ++_numStatFrames; @@ -888,11 +876,7 @@ void AudioMixer::perSecondActions() { _timeSpentPerHashMatchCallStats.getWindowSum() / WINDOW_LENGTH_USECS * 100.0, _timeSpentPerHashMatchCallStats.getCurrentIntervalSum() / USECS_PER_SECOND * 100.0); - NodeHashSnapshot snapshotHash = NodeList::getInstance()->getNodeHash().snapshot_table(); - - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { - SharedNodePointer node = it->second; - + NodeList::getInstance()->eachNode([](const SharedNodePointer& node) { if (node->getLinkedData()) { AudioMixerClientData* nodeData = (AudioMixerClientData*)node->getLinkedData(); @@ -902,7 +886,7 @@ void AudioMixer::perSecondActions() { nodeData->printUpstreamDownstreamStats(); } } - } + }); } _datagramsReadPerCallStats.currentIntervalComplete(); diff --git a/assignment-client/src/avatars/AvatarMixer.cpp b/assignment-client/src/avatars/AvatarMixer.cpp index 3c2fa92c7c..107ce29ac9 100644 --- a/assignment-client/src/avatars/AvatarMixer.cpp +++ b/assignment-client/src/avatars/AvatarMixer.cpp @@ -122,9 +122,7 @@ void AvatarMixer::broadcastAvatarData() { AvatarMixerClientData* nodeData = NULL; AvatarMixerClientData* otherNodeData = NULL; - NodeHashSnapshot snapshotHash = nodeList->getNodeHash().snapshot_table(); - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { - SharedNodePointer node = it->second; + nodeList->eachNode([&](const SharedNodePointer& node) { if (node->getLinkedData() && node->getType() == NodeType::Agent && node->getActiveSocket() && (nodeData = reinterpret_cast(node->getLinkedData()))->getMutex().tryLock()) { ++_sumListeners; @@ -137,9 +135,7 @@ void AvatarMixer::broadcastAvatarData() { // this is an AGENT we have received head data from // send back a packet with other active node data to this node - NodeHashSnapshot snapshotHash = nodeList->getNodeHash().snapshot_table(); - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { - SharedNodePointer otherNode = it->second; + nodeList->eachNode([&](const SharedNodePointer& otherNode) { if (otherNode->getLinkedData() && otherNode->getUUID() != node->getUUID() && (otherNodeData = reinterpret_cast(otherNode->getLinkedData()))->getMutex().tryLock()) { @@ -207,13 +203,13 @@ void AvatarMixer::broadcastAvatarData() { otherNodeData->getMutex().unlock(); } - } + }); nodeList->writeDatagram(mixedAvatarByteArray, node); nodeData->getMutex().unlock(); } - } + }); _lastFrameTimestamp = QDateTime::currentMSecsSinceEpoch(); } From 881d03b11dd6060c0919d6006683ccbe256071bc Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 6 Nov 2014 13:54:40 -0800 Subject: [PATCH 022/258] migrate EntityServer and OctreeServer to tbb concurrent map --- assignment-client/src/entities/EntityServer.cpp | 9 +++------ assignment-client/src/octree/OctreeServer.cpp | 9 ++++----- 2 files changed, 7 insertions(+), 11 deletions(-) diff --git a/assignment-client/src/entities/EntityServer.cpp b/assignment-client/src/entities/EntityServer.cpp index 31999f91f7..a39e7acbf4 100644 --- a/assignment-client/src/entities/EntityServer.cpp +++ b/assignment-client/src/entities/EntityServer.cpp @@ -124,11 +124,7 @@ void EntityServer::pruneDeletedEntities() { quint64 earliestLastDeletedEntitiesSent = usecTimestampNow() + 1; // in the future - NodeHashSnapshot snapshotHash = NodeList::getInstance()->getNodeHash().snapshot_table(); - - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { - SharedNodePointer node = it->second; - + NodeList::getInstance()->eachNode([&earliestLastDeletedEntitiesSent](const SharedNodePointer& node) { if (node->getLinkedData()) { EntityNodeData* nodeData = static_cast(node->getLinkedData()); quint64 nodeLastDeletedEntitiesSentAt = nodeData->getLastDeletedEntitiesSentAt(); @@ -136,7 +132,8 @@ void EntityServer::pruneDeletedEntities() { earliestLastDeletedEntitiesSent = nodeLastDeletedEntitiesSentAt; } } - } + }); + tree->forgetEntitiesDeletedBefore(earliestLastDeletedEntitiesSent); } } diff --git a/assignment-client/src/octree/OctreeServer.cpp b/assignment-client/src/octree/OctreeServer.cpp index 2b38ce3cdd..e6211a046a 100644 --- a/assignment-client/src/octree/OctreeServer.cpp +++ b/assignment-client/src/octree/OctreeServer.cpp @@ -1138,12 +1138,11 @@ void OctreeServer::aboutToFinish() { qDebug() << qPrintable(_safeServerName) << "inform Octree Inbound Packet Processor that we are shutting down..."; _octreeInboundPacketProcessor->shuttingDown(); - NodeHashSnapshot snapshotHash = NodeList::getInstance()->getNodeHash().snapshot_table(); + NodeList::getInstance()->eachNode([this](const SharedNodePointer& node) { + qDebug() << qPrintable(_safeServerName) << "server about to finish while node still connected node:" << *node; + forceNodeShutdown(node); + }); - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { - qDebug() << qPrintable(_safeServerName) << "server about to finish while node still connected node:" << *it->second; - forceNodeShutdown(it->second); - } qDebug() << qPrintable(_safeServerName) << "server ENDING about to finish..."; } From 0e9e8a003692a4ac4b42005da026a53c22b015a1 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 6 Nov 2014 13:56:19 -0800 Subject: [PATCH 023/258] remove libcuckoo and readme --- .gitignore | 4 ---- .../networking/externals/libcuckoo/readme.txt | 14 -------------- 2 files changed, 18 deletions(-) delete mode 100644 libraries/networking/externals/libcuckoo/readme.txt diff --git a/.gitignore b/.gitignore index 74a5748b85..6e6b69cb66 100644 --- a/.gitignore +++ b/.gitignore @@ -32,9 +32,5 @@ DerivedData interface/external/*/* !interface/external/*/readme.txt -# ignore libraries externals -libraries/*/externals/*/* -!libraries/*/externals/*/readme.txt - # Ignore interfaceCache for Linux users interface/interfaceCache/ diff --git a/libraries/networking/externals/libcuckoo/readme.txt b/libraries/networking/externals/libcuckoo/readme.txt deleted file mode 100644 index b86f8bc609..0000000000 --- a/libraries/networking/externals/libcuckoo/readme.txt +++ /dev/null @@ -1,14 +0,0 @@ - -Instructions for adding the libcuckoo library to Interface -Stephen Birarda, November 5, 2014 - -1. Download the libcuckoo ZIP from the High Fidelity libcuckoo fork on Github. - https://github.com/highfidelity/libcuckoo/archive/master.zip - -2. Copy the libcuckoo folder from inside the ZIP to libraries/networking/externals/libcuckoo/. - - You should have the following structure: - - libraries/networking/externals/libcuckoo/libcuckoo/cuckoohash_map.hh - -3. Delete your build directory, run cmake and build, and you should be all set. From 455cbac8a5d4a5c8f2a8869a56e366a288cdcaea Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 6 Nov 2014 15:16:45 -0800 Subject: [PATCH 024/258] repairs to node hash iterations in Application --- interface/src/Application.cpp | 87 ++++++++++++++++------------------- 1 file changed, 40 insertions(+), 47 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index f5842ed4c3..516701d085 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -2405,75 +2405,73 @@ int Application::sendNackPackets() { char packet[MAX_PACKET_SIZE]; // iterates thru all nodes in NodeList - NodeHashSnapshot snapshotHash = NodeList::getInstance()->getNodeHash().snapshot_table(); + NodeList* nodeList = NodeList::getInstance(); - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { - SharedNodePointer node = it->second; + nodeList->eachNode([&](const SharedNodePointer& node){ - if (node->getActiveSocket() && - ( node->getType() == NodeType::VoxelServer - || node->getType() == NodeType::EntityServer) - ) { - + if (node->getActiveSocket() + && (node->getType() == NodeType::VoxelServer || node->getType() == NodeType::EntityServer)) { + QUuid nodeUUID = node->getUUID(); - + // if there are octree packets from this node that are waiting to be processed, // don't send a NACK since the missing packets may be among those waiting packets. if (_octreeProcessor.hasPacketsToProcessFrom(nodeUUID)) { - continue; + return; } _octreeSceneStatsLock.lockForRead(); - + // retreive octree scene stats of this node if (_octreeServerSceneStats.find(nodeUUID) == _octreeServerSceneStats.end()) { _octreeSceneStatsLock.unlock(); - continue; + return; } - + // get sequence number stats of node, prune its missing set, and make a copy of the missing set SequenceNumberStats& sequenceNumberStats = _octreeServerSceneStats[nodeUUID].getIncomingOctreeSequenceNumberStats(); sequenceNumberStats.pruneMissingSet(); const QSet missingSequenceNumbers = sequenceNumberStats.getMissingSet(); - + _octreeSceneStatsLock.unlock(); - + // construct nack packet(s) for this node int numSequenceNumbersAvailable = missingSequenceNumbers.size(); QSet::const_iterator missingSequenceNumbersIterator = missingSequenceNumbers.constBegin(); while (numSequenceNumbersAvailable > 0) { - + char* dataAt = packet; int bytesRemaining = MAX_PACKET_SIZE; - + // pack header int numBytesPacketHeader = populatePacketHeader(packet, PacketTypeOctreeDataNack); dataAt += numBytesPacketHeader; bytesRemaining -= numBytesPacketHeader; - + // calculate and pack the number of sequence numbers int numSequenceNumbersRoomFor = (bytesRemaining - sizeof(uint16_t)) / sizeof(OCTREE_PACKET_SEQUENCE); uint16_t numSequenceNumbers = min(numSequenceNumbersAvailable, numSequenceNumbersRoomFor); uint16_t* numSequenceNumbersAt = (uint16_t*)dataAt; *numSequenceNumbersAt = numSequenceNumbers; dataAt += sizeof(uint16_t); - + // pack sequence numbers for (int i = 0; i < numSequenceNumbers; i++) { OCTREE_PACKET_SEQUENCE* sequenceNumberAt = (OCTREE_PACKET_SEQUENCE*)dataAt; *sequenceNumberAt = *missingSequenceNumbersIterator; dataAt += sizeof(OCTREE_PACKET_SEQUENCE); - + missingSequenceNumbersIterator++; } numSequenceNumbersAvailable -= numSequenceNumbers; - + // send it - NodeList::getInstance()->writeUnverifiedDatagram(packet, dataAt - packet, node); + nodeList->writeUnverifiedDatagram(packet, dataAt - packet, node); packetsSent++; } } - } + }); + return packetsSent; } @@ -2507,12 +2505,8 @@ void Application::queryOctree(NodeType_t serverType, PacketType packetType, Node int unknownJurisdictionServers = 0; NodeList* nodeList = NodeList::getInstance(); - NodeHashSnapshot snapshotHash = nodeList->getNodeHash().snapshot_table(); - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { - - SharedNodePointer node = it->second; - + nodeList->eachNode([&](const SharedNodePointer& node) { // only send to the NodeTypes that are serverType if (node->getActiveSocket() && node->getType() == serverType) { totalServers++; @@ -2543,7 +2537,7 @@ void Application::queryOctree(NodeType_t serverType, PacketType packetType, Node } } } - } + }); if (wantExtraDebugging) { qDebug("Servers: total %d, in view %d, unknown jurisdiction %d", @@ -2570,18 +2564,17 @@ void Application::queryOctree(NodeType_t serverType, PacketType packetType, Node qDebug("perServerPPS: %d perUnknownServer: %d", perServerPPS, perUnknownServer); } - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { - SharedNodePointer node = it->second; + nodeList->eachNode([&](const SharedNodePointer& node){ // only send to the NodeTypes that are serverType if (node->getActiveSocket() && node->getType() == serverType) { - - + + // get the server bounds for this server QUuid nodeUUID = node->getUUID(); - + bool inView = false; bool unknownView = false; - + // if we haven't heard from this voxel server, go ahead and send it a query, so we // can get the jurisdiction... if (jurisdictions.find(nodeUUID) == jurisdictions.end()) { @@ -2591,15 +2584,15 @@ void Application::queryOctree(NodeType_t serverType, PacketType packetType, Node } } else { const JurisdictionMap& map = (jurisdictions)[nodeUUID]; - + unsigned char* rootCode = map.getRootOctalCode(); - + if (rootCode) { VoxelPositionSize rootDetails; voxelDetailsForCode(rootCode, rootDetails); AACube serverBounds(glm::vec3(rootDetails.x, rootDetails.y, rootDetails.z), rootDetails.s); serverBounds.scale(TREE_SCALE); - + ViewFrustum::location serverFrustumLocation = _viewFrustum.cubeInFrustum(serverBounds); if (serverFrustumLocation != ViewFrustum::OUTSIDE) { inView = true; @@ -2612,15 +2605,15 @@ void Application::queryOctree(NodeType_t serverType, PacketType packetType, Node } } } - + if (inView) { _octreeQuery.setMaxOctreePacketsPerSecond(perServerPPS); } else if (unknownView) { if (wantExtraDebugging) { qDebug() << "no known jurisdiction for node " << *node << ", give it budget of " - << perUnknownServer << " to send us jurisdiction."; + << perUnknownServer << " to send us jurisdiction."; } - + // set the query's position/orientation to be degenerate in a manner that will get the scene quickly // If there's only one server, then don't do this, and just let the normal voxel query pass through // as expected... this way, we will actually get a valid scene if there is one to be seen @@ -2644,22 +2637,22 @@ void Application::queryOctree(NodeType_t serverType, PacketType packetType, Node } // set up the packet for sending... unsigned char* endOfQueryPacket = queryPacket; - + // insert packet type/version and node UUID endOfQueryPacket += populatePacketHeader(reinterpret_cast(endOfQueryPacket), packetType); - + // encode the query data... endOfQueryPacket += _octreeQuery.getBroadcastData(endOfQueryPacket); - + int packetLength = endOfQueryPacket - queryPacket; - + // make sure we still have an active socket nodeList->writeUnverifiedDatagram(reinterpret_cast(queryPacket), packetLength, node); - + // Feed number of bytes to corresponding channel of the bandwidth meter _bandwidthMeter.outputStream(BandwidthMeter::VOXELS).updateValue(packetLength); } - } + }); } ///////////////////////////////////////////////////////////////////////////////////// From aa7e99567253708152e69a5aff0681d1174631f6 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 6 Nov 2014 15:18:56 -0800 Subject: [PATCH 025/258] update MetavoxelSystem.cpp to new tbb node iteration --- interface/src/MetavoxelSystem.cpp | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) diff --git a/interface/src/MetavoxelSystem.cpp b/interface/src/MetavoxelSystem.cpp index 20a7bc906f..2ca17e32c1 100644 --- a/interface/src/MetavoxelSystem.cpp +++ b/interface/src/MetavoxelSystem.cpp @@ -163,12 +163,7 @@ void MetavoxelSystem::render() { } void MetavoxelSystem::refreshVoxelData() { - NodeHashSnapshot snapshotHash = NodeList::getInstance()->getNodeHash().snapshot_table(); - - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { - - SharedNodePointer node = it->second; - + NodeList::getInstance()->eachNode([](const SharedNodePointer& node){ if (node->getType() == NodeType::MetavoxelServer) { QMutexLocker locker(&node->getMutex()); MetavoxelSystemClient* client = static_cast(node->getLinkedData()); @@ -176,7 +171,7 @@ void MetavoxelSystem::refreshVoxelData() { QMetaObject::invokeMethod(client, "refreshVoxelData"); } } - } + }); } class RayHeightfieldIntersectionVisitor : public RayIntersectionVisitor { @@ -690,11 +685,7 @@ MetavoxelClient* MetavoxelSystem::createClient(const SharedNodePointer& node) { } void MetavoxelSystem::guideToAugmented(MetavoxelVisitor& visitor, bool render) { - NodeHashSnapshot snapshotHash = NodeList::getInstance()->getNodeHash().snapshot_table(); - - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { - SharedNodePointer node = it->second; - + NodeList::getInstance()->eachNode([&visitor, &render](const SharedNodePointer& node) { if (node->getType() == NodeType::MetavoxelServer) { QMutexLocker locker(&node->getMutex()); MetavoxelSystemClient* client = static_cast(node->getLinkedData()); @@ -708,7 +699,7 @@ void MetavoxelSystem::guideToAugmented(MetavoxelVisitor& visitor, bool render) { } } } - } + }); } Throttle::Throttle() : From d82e2fb8f448c8b8a40658a71be377c458bb655b Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 6 Nov 2014 15:21:18 -0800 Subject: [PATCH 026/258] update NodeBounds.cpp to new tbb node iteration --- interface/src/ui/NodeBounds.cpp | 38 +++++++++++++++------------------ 1 file changed, 17 insertions(+), 21 deletions(-) diff --git a/interface/src/ui/NodeBounds.cpp b/interface/src/ui/NodeBounds.cpp index 6298385c90..dedc687cc2 100644 --- a/interface/src/ui/NodeBounds.cpp +++ b/interface/src/ui/NodeBounds.cpp @@ -53,65 +53,61 @@ void NodeBounds::draw() { float selectedScale = 0; NodeList* nodeList = NodeList::getInstance(); - NodeHashSnapshot snapshotHash = nodeList->getNodeHash().snapshot_table(); - - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { - SharedNodePointer node = it->second; - + nodeList->eachNode([&](const SharedNodePointer& node){ NodeType_t nodeType = node->getType(); - + if (nodeType == NodeType::VoxelServer && _showVoxelNodes) { serverJurisdictions = &voxelServerJurisdictions; } else if (nodeType == NodeType::EntityServer && _showEntityNodes) { serverJurisdictions = &entityServerJurisdictions; } else { - continue; + return; } - + QUuid nodeUUID = node->getUUID(); serverJurisdictions->lockForRead(); if (serverJurisdictions->find(nodeUUID) != serverJurisdictions->end()) { const JurisdictionMap& map = (*serverJurisdictions)[nodeUUID]; - + unsigned char* rootCode = map.getRootOctalCode(); - + if (rootCode) { VoxelPositionSize rootDetails; voxelDetailsForCode(rootCode, rootDetails); serverJurisdictions->unlock(); glm::vec3 location(rootDetails.x, rootDetails.y, rootDetails.z); location *= (float)TREE_SCALE; - + AACube serverBounds(location, rootDetails.s * TREE_SCALE); - + glm::vec3 center = serverBounds.getVertex(BOTTOM_RIGHT_NEAR) - + ((serverBounds.getVertex(TOP_LEFT_FAR) - serverBounds.getVertex(BOTTOM_RIGHT_NEAR)) / 2.0f); - + + ((serverBounds.getVertex(TOP_LEFT_FAR) - serverBounds.getVertex(BOTTOM_RIGHT_NEAR)) / 2.0f); + const float VOXEL_NODE_SCALE = 1.00f; const float ENTITY_NODE_SCALE = 0.99f; - + float scaleFactor = rootDetails.s * TREE_SCALE; - + // Scale by 0.92 - 1.00 depending on the scale of the node. This allows smaller nodes to scale in // a bit and not overlap larger nodes. scaleFactor *= 0.92 + (rootDetails.s * 0.08); - + // Scale different node types slightly differently because it's common for them to overlap. if (nodeType == NodeType::VoxelServer) { scaleFactor *= VOXEL_NODE_SCALE; } else if (nodeType == NodeType::EntityServer) { scaleFactor *= ENTITY_NODE_SCALE; } - + float red, green, blue; getColorForNodeType(nodeType, red, green, blue); drawNodeBorder(center, scaleFactor, red, green, blue); - + float distance; BoxFace face; bool inside = serverBounds.contains(mouseRayOrigin); bool colliding = serverBounds.findRayIntersection(mouseRayOrigin, mouseRayDirection, distance, face); - + // If the camera is inside a node it will be "selected" if you don't have your cursor over another node // that you aren't inside. if (colliding && (!selectedNode || (!inside && (distance < selectedDistance || selectedIsInside)))) { @@ -127,7 +123,7 @@ void NodeBounds::draw() { } else { serverJurisdictions->unlock(); } - } + }); if (selectedNode) { glPushMatrix(); From ce02d79d415e9ef4411ffc03fe971ccafb2d676c Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 6 Nov 2014 15:22:30 -0800 Subject: [PATCH 027/258] update OctreeStatsDialog to new tbb node iteration --- interface/src/ui/OctreeStatsDialog.cpp | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/interface/src/ui/OctreeStatsDialog.cpp b/interface/src/ui/OctreeStatsDialog.cpp index 8a6d6442f5..14da45e1d1 100644 --- a/interface/src/ui/OctreeStatsDialog.cpp +++ b/interface/src/ui/OctreeStatsDialog.cpp @@ -248,10 +248,8 @@ void OctreeStatsDialog::showOctreeServersOfType(int& serverCount, NodeType_t ser QLocale locale(QLocale::English); NodeList* nodeList = NodeList::getInstance(); - NodeHashSnapshot snapshotHash = nodeList->getNodeHash().snapshot_table(); - - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { - SharedNodePointer node = it->second; + nodeList->eachNode([&](const SharedNodePointer& node){ + // only send to the NodeTypes that are NodeType_t_VOXEL_SERVER if (node->getType() == serverType) { serverCount++; @@ -422,7 +420,7 @@ void OctreeStatsDialog::showOctreeServersOfType(int& serverCount, NodeType_t ser serverDetails << linkDetails.str(); _labels[_voxelServerLables[serverCount - 1]]->setText(serverDetails.str().c_str()); } // is VOXEL_SERVER - } + }); } void OctreeStatsDialog::reject() { From 2f66e56e46eb3f900f2b9385259e6b319b7c2821 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 6 Nov 2014 15:23:30 -0800 Subject: [PATCH 028/258] update Stats to new tbb node iteration --- interface/src/ui/Stats.cpp | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/interface/src/ui/Stats.cpp b/interface/src/ui/Stats.cpp index 8e4b900180..08eaac9334 100644 --- a/interface/src/ui/Stats.cpp +++ b/interface/src/ui/Stats.cpp @@ -329,10 +329,7 @@ void Stats::display( unsigned long totalPingVoxel = 0; int voxelServerCount = 0; - NodeHashSnapshot snapshotHash = nodeList->getNodeHash().snapshot_table(); - - for (auto it = snapshotHash.begin(); it != snapshotHash.end(); it++) { - SharedNodePointer node = it->second; + nodeList->eachNode([&totalPingVoxel, &pingVoxelMax, &voxelServerCount](const SharedNodePointer& node){ // TODO: this should also support entities if (node->getType() == NodeType::VoxelServer) { totalPingVoxel += node->getPingMs(); @@ -341,7 +338,7 @@ void Stats::display( pingVoxelMax = node->getPingMs(); } } - } + }); if (voxelServerCount) { pingVoxel = totalPingVoxel/voxelServerCount; From 996c76c723f4dd591707be56da8ad74ecbce06fb Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 6 Nov 2014 16:05:01 -0800 Subject: [PATCH 029/258] repairs for node teardown on domain dissappear or node disconnect --- domain-server/src/DomainServer.cpp | 4 +-- libraries/networking/src/LimitedNodeList.cpp | 34 ++++++++++++++++---- libraries/networking/src/LimitedNodeList.h | 2 ++ 3 files changed, 31 insertions(+), 9 deletions(-) diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index cb4b1c8026..153fbae0c9 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -2019,9 +2019,9 @@ void DomainServer::addStaticAssignmentsToQueue() { QHash::iterator staticAssignment = staticHashCopy.begin(); while (staticAssignment != staticHashCopy.end()) { // add any of the un-matched static assignments to the queue - + // enumerate the nodes and check if there is one with an attached assignment with matching UUID - if (NodeList::getInstance()->nodeWithUUID(staticAssignment->data()->getUUID())) { + if (!NodeList::getInstance()->nodeWithUUID(staticAssignment->data()->getUUID())) { // this assignment has not been fulfilled - reset the UUID and add it to the assignment queue refreshStaticAssignmentAndAddToQueue(*staticAssignment); } diff --git a/libraries/networking/src/LimitedNodeList.cpp b/libraries/networking/src/LimitedNodeList.cpp index ac63941882..767935bf3d 100644 --- a/libraries/networking/src/LimitedNodeList.cpp +++ b/libraries/networking/src/LimitedNodeList.cpp @@ -359,11 +359,18 @@ SharedNodePointer LimitedNodeList::sendingNodeForPacket(const QByteArray& packet void LimitedNodeList::eraseAllNodes() { qDebug() << "Clearing the NodeList. Deleting all nodes in list."; + QSet killedNodes; + eachNode([&killedNodes](const SharedNodePointer& node){ + killedNodes.insert(node); + }); + // iterate the current nodes, emit that they are dying and remove them from the hash - QWriteLocker writeLock(&_nodeMutex); - for (NodeHash::iterator it = _nodeHash.begin(); it != _nodeHash.end(); ++it) { - emit nodeKilled(it->second); - it = _nodeHash.unsafe_erase(it); + _nodeMutex.lockForWrite(); + _nodeHash.clear(); + _nodeMutex.unlock(); + + foreach(const SharedNodePointer& killedNode, killedNodes) { + handleNodeKill(killedNode); } } @@ -378,7 +385,8 @@ void LimitedNodeList::killNodeWithUUID(const QUuid& nodeUUID) { QWriteLocker writeLocker(&_nodeMutex); _nodeHash.unsafe_erase(it); - emit nodeKilled(matchingNode); + + handleNodeKill(matchingNode); } } @@ -390,6 +398,11 @@ void LimitedNodeList::processKillNode(const QByteArray& dataByteArray) { killNodeWithUUID(nodeUUID); } +void LimitedNodeList::handleNodeKill(const SharedNodePointer& node) { + qDebug() << "Killed" << *node; + emit nodeKilled(node); +} + SharedNodePointer LimitedNodeList::addOrUpdateNode(const QUuid& uuid, NodeType_t nodeType, const HifiSockAddr& publicSocket, const HifiSockAddr& localSocket) { try { @@ -478,14 +491,17 @@ void LimitedNodeList::resetPacketStats() { } void LimitedNodeList::removeSilentNodes() { - eachNodeHashIterator([this](NodeHash::iterator& it){ + QSet killedNodes; + + eachNodeHashIterator([&](NodeHash::iterator& it){ SharedNodePointer node = it->second; node->getMutex().lock(); if ((usecTimestampNow() - node->getLastHeardMicrostamp()) > (NODE_SILENCE_THRESHOLD_MSECS * 1000)) { // call the NodeHash erase to get rid of this node it = _nodeHash.unsafe_erase(it); - emit nodeKilled(node); + + killedNodes.insert(node); } else { // we didn't erase this node, push the iterator forwards ++it; @@ -493,6 +509,10 @@ void LimitedNodeList::removeSilentNodes() { node->getMutex().unlock(); }); + + foreach(const SharedNodePointer& killedNode, killedNodes) { + handleNodeKill(killedNode); + } } const uint32_t RFC_5389_MAGIC_COOKIE = 0x2112A442; diff --git a/libraries/networking/src/LimitedNodeList.h b/libraries/networking/src/LimitedNodeList.h index a29902a7c9..d713f69d29 100644 --- a/libraries/networking/src/LimitedNodeList.h +++ b/libraries/networking/src/LimitedNodeList.h @@ -187,6 +187,8 @@ protected: const QUuid& connectionSecret); void changeSocketBufferSizes(int numBytes); + + void handleNodeKill(const SharedNodePointer& node); QUuid _sessionUUID; NodeHash _nodeHash; From cd0ee0ff1db256882aacf2e5dc1654ecb19b237a Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Sun, 23 Nov 2014 14:58:29 -0800 Subject: [PATCH 030/258] better support for includes in entity scripts --- interface/src/entities/EntityTreeRenderer.cpp | 15 +++++++++++++-- interface/src/entities/EntityTreeRenderer.h | 2 +- libraries/script-engine/src/ScriptEngine.cpp | 11 ++++++++--- libraries/script-engine/src/ScriptEngine.h | 3 +++ 4 files changed, 25 insertions(+), 6 deletions(-) diff --git a/interface/src/entities/EntityTreeRenderer.cpp b/interface/src/entities/EntityTreeRenderer.cpp index 192b42c58b..dfe9505c02 100644 --- a/interface/src/entities/EntityTreeRenderer.cpp +++ b/interface/src/entities/EntityTreeRenderer.cpp @@ -99,13 +99,15 @@ QScriptValue EntityTreeRenderer::loadEntityScript(const EntityItemID& entityItem } -QString EntityTreeRenderer::loadScriptContents(const QString& scriptMaybeURLorText) { +QString EntityTreeRenderer::loadScriptContents(const QString& scriptMaybeURLorText, bool& isURL) { QUrl url(scriptMaybeURLorText); // If the url is not valid, this must be script text... if (!url.isValid()) { + isURL = false; return scriptMaybeURLorText; } + isURL = true; QString scriptContents; // assume empty @@ -168,7 +170,8 @@ QScriptValue EntityTreeRenderer::loadEntityScript(EntityItem* entity) { return QScriptValue(); // no script } - QString scriptContents = loadScriptContents(entity->getScript()); + bool isURL = false; // loadScriptContents() will tell us if this is a URL or just text. + QString scriptContents = loadScriptContents(entity->getScript(), isURL); QScriptSyntaxCheckResult syntaxCheck = QScriptEngine::checkSyntax(scriptContents); if (syntaxCheck.state() != QScriptSyntaxCheckResult::Valid) { @@ -179,6 +182,9 @@ QScriptValue EntityTreeRenderer::loadEntityScript(EntityItem* entity) { return QScriptValue(); // invalid script } + if (isURL) { + _entitiesScriptEngine->setParentURL(entity->getScript()); + } QScriptValue entityScriptConstructor = _entitiesScriptEngine->evaluate(scriptContents); if (!entityScriptConstructor.isFunction()) { @@ -189,9 +195,14 @@ QScriptValue EntityTreeRenderer::loadEntityScript(EntityItem* entity) { } QScriptValue entityScriptObject = entityScriptConstructor.construct(); + EntityScriptDetails newDetails = { entity->getScript(), entityScriptObject }; _entityScripts[entityID] = newDetails; + if (isURL) { + _entitiesScriptEngine->setParentURL(""); + } + return entityScriptObject; // newly constructed } diff --git a/interface/src/entities/EntityTreeRenderer.h b/interface/src/entities/EntityTreeRenderer.h index e5eba79e0d..8b2131691c 100644 --- a/interface/src/entities/EntityTreeRenderer.h +++ b/interface/src/entities/EntityTreeRenderer.h @@ -132,7 +132,7 @@ private: QScriptValue loadEntityScript(const EntityItemID& entityItemID); QScriptValue getPreviouslyLoadedEntityScript(const EntityItemID& entityItemID); QScriptValue getPreviouslyLoadedEntityScript(EntityItem* entity); - QString loadScriptContents(const QString& scriptMaybeURLorText); + QString loadScriptContents(const QString& scriptMaybeURLorText, bool& isURL); QScriptValueList createMouseEventArgs(const EntityItemID& entityID, QMouseEvent* event, unsigned int deviceID); QScriptValueList createMouseEventArgs(const EntityItemID& entityID, const MouseEvent& mouseEvent); diff --git a/libraries/script-engine/src/ScriptEngine.cpp b/libraries/script-engine/src/ScriptEngine.cpp index e6002d7c10..fc1e8ce8bc 100644 --- a/libraries/script-engine/src/ScriptEngine.cpp +++ b/libraries/script-engine/src/ScriptEngine.cpp @@ -618,16 +618,20 @@ void ScriptEngine::stopTimer(QTimer *timer) { } QUrl ScriptEngine::resolvePath(const QString& include) const { - // first lets check to see if it's already a full URL QUrl url(include); + // first lets check to see if it's already a full URL if (!url.scheme().isEmpty()) { return url; } // we apparently weren't a fully qualified url, so, let's assume we're relative // to the original URL of our script - QUrl parentURL(_fileNameString); - + QUrl parentURL; + if (_parentURL.isEmpty()) { + parentURL = QUrl(_fileNameString); + } else { + parentURL = QUrl(_parentURL); + } // if the parent URL's scheme is empty, then this is probably a local file... if (parentURL.scheme().isEmpty()) { parentURL = QUrl::fromLocalFile(_fileNameString); @@ -660,6 +664,7 @@ void ScriptEngine::include(const QString& includeFile) { #else QString fileName = url.toLocalFile(); #endif + QFile scriptFile(fileName); if (scriptFile.open(QFile::ReadOnly | QFile::Text)) { qDebug() << "Including file:" << fileName; diff --git a/libraries/script-engine/src/ScriptEngine.h b/libraries/script-engine/src/ScriptEngine.h index bb279b8887..289436aada 100644 --- a/libraries/script-engine/src/ScriptEngine.h +++ b/libraries/script-engine/src/ScriptEngine.h @@ -93,6 +93,8 @@ public: void setUserLoaded(bool isUserLoaded) { _isUserLoaded = isUserLoaded; } bool isUserLoaded() const { return _isUserLoaded; } + void setParentURL(const QString& parentURL) { _parentURL = parentURL; } + public slots: void stop(); @@ -121,6 +123,7 @@ signals: protected: QString _scriptContents; + QString _parentURL; bool _isFinished; bool _isRunning; bool _isInitialized; From 3ee6d6a6dbb1b661555a81bcff16e444cd9b464e Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Sun, 23 Nov 2014 20:12:52 -0800 Subject: [PATCH 031/258] work in making entity script mixable and inheritable --- examples/entityScripts/changeColorOnHover.js | 35 +- .../entityScripts/changeColorOnHoverClass.js | 55 +++ examples/entityScripts/movable.js | 410 +---------------- examples/entityScripts/movableClass.js | 426 ++++++++++++++++++ examples/entityScripts/sitOnEntity.js | 363 +-------------- examples/entityScripts/sittable.js | 15 + examples/entityScripts/sittableClass.js | 381 ++++++++++++++++ 7 files changed, 888 insertions(+), 797 deletions(-) create mode 100644 examples/entityScripts/changeColorOnHoverClass.js create mode 100644 examples/entityScripts/movableClass.js create mode 100644 examples/entityScripts/sittable.js create mode 100644 examples/entityScripts/sittableClass.js diff --git a/examples/entityScripts/changeColorOnHover.js b/examples/entityScripts/changeColorOnHover.js index 638c1bece4..0cf08adf1d 100644 --- a/examples/entityScripts/changeColorOnHover.js +++ b/examples/entityScripts/changeColorOnHover.js @@ -13,34 +13,7 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -(function(){ - this.oldColor = {}; - this.oldColorKnown = false; - this.storeOldColor = function(entityID) { - var oldProperties = Entities.getEntityProperties(entityID); - this.oldColor = oldProperties.color; - this.oldColorKnown = true; - print("storing old color... this.oldColor=" + this.oldColor.red + "," + this.oldColor.green + "," + this.oldColor.blue); - }; - - this.preload = function(entityID) { - print("preload"); - this.storeOldColor(entityID); - }; - - this.hoverEnterEntity = function(entityID, mouseEvent) { - print("hoverEnterEntity"); - if (!this.oldColorKnown) { - this.storeOldColor(entityID); - } - Entities.editEntity(entityID, { color: { red: 0, green: 255, blue: 255} }); - }; - this.hoverLeaveEntity = function(entityID, mouseEvent) { - print("hoverLeaveEntity"); - if (this.oldColorKnown) { - print("leave restoring old color... this.oldColor=" - + this.oldColor.red + "," + this.oldColor.green + "," + this.oldColor.blue); - Entities.editEntity(entityID, { color: this.oldColor }); - } - }; -}) \ No newline at end of file +(function() { + Script.include("changeColorOnHoverClass.js"); + return new ChangeColorOnHover(); +}) diff --git a/examples/entityScripts/changeColorOnHoverClass.js b/examples/entityScripts/changeColorOnHoverClass.js new file mode 100644 index 0000000000..231469f7e8 --- /dev/null +++ b/examples/entityScripts/changeColorOnHoverClass.js @@ -0,0 +1,55 @@ +// +// changeColorOnHover.js +// examples/entityScripts +// +// Created by Brad Hefta-Gaub on 11/1/14. +// Copyright 2014 High Fidelity, Inc. +// +// This is an example of an entity script which when assigned to a non-model entity like a box or sphere, will +// change the color of the entity when you hover over it. This script uses the JavaScript prototype/class functionality +// to construct an object that has methods for hoverEnterEntity and hoverLeaveEntity; +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + + +ChangeColorOnHover = function(){ + this.oldColor = {}; + this.oldColorKnown = false; +}; + +ChangeColorOnHover.prototype = { + + storeOldColor: function(entityID) { + var oldProperties = Entities.getEntityProperties(entityID); + this.oldColor = oldProperties.color; + this.oldColorKnown = true; + print("storing old color... this.oldColor=" + this.oldColor.red + "," + this.oldColor.green + "," + this.oldColor.blue); + }, + + preload: function(entityID) { + print("preload"); + this.storeOldColor(entityID); + }, + + hoverEnterEntity: function(entityID, mouseEvent) { + print("hoverEnterEntity"); + if (!this.oldColorKnown) { + this.storeOldColor(entityID); + } + Entities.editEntity(entityID, { color: { red: 0, green: 255, blue: 255} }); + }, + + + hoverLeaveEntity: function(entityID, mouseEvent) { + print("hoverLeaveEntity"); + if (this.oldColorKnown) { + print("leave restoring old color... this.oldColor=" + + this.oldColor.red + "," + this.oldColor.green + "," + this.oldColor.blue); + Entities.editEntity(entityID, { color: this.oldColor }); + } + } +}; + + diff --git a/examples/entityScripts/movable.js b/examples/entityScripts/movable.js index 21e6261179..0ea3641c6f 100644 --- a/examples/entityScripts/movable.js +++ b/examples/entityScripts/movable.js @@ -8,412 +8,8 @@ // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -(function(){ - - this.entityID = null; - this.properties = null; - this.graboffset = null; - this.clickedAt = null; - this.firstHolding = true; - this.clicked = { x: -1, y: -1}; - this.lastMovedPosition = { x: -1, y: -1}; - this.lastMovedTime = 0; - this.rotateOverlayTarget = null; - this.rotateOverlayInner = null; - this.rotateOverlayOuter = null; - this.rotateOverlayCurrent = null; - this.rotateMode = false; - this.originalRotation = null; - - this.moveSoundURLS = [ - "http://public.highfidelity.io/sounds/MovingFurniture/FurnitureMove1.wav", - "http://public.highfidelity.io/sounds/MovingFurniture/FurnitureMove2.wav", - "http://public.highfidelity.io/sounds/MovingFurniture/FurnitureMove3.wav" - ]; - - this.turnSoundURLS = [ - - "http://public.highfidelity.io/sounds/MovingFurniture/FurnitureMove1.wav", - "http://public.highfidelity.io/sounds/MovingFurniture/FurnitureMove2.wav", - "http://public.highfidelity.io/sounds/MovingFurniture/FurnitureMove3.wav" - - // TODO: determine if these or other turn sounds work better than move sounds. - //"http://public.highfidelity.io/sounds/MovingFurniture/FurnitureTurn1.wav", - //"http://public.highfidelity.io/sounds/MovingFurniture/FurnitureTurn2.wav", - //"http://public.highfidelity.io/sounds/MovingFurniture/FurnitureTurn3.wav" - ]; - - - this.moveSounds = new Array(); - this.turnSounds = new Array(); - this.moveSound = null; - this.turnSound = null; - this.injector = null; - - var debug = false; - var displayRotateTargets = true; // change to false if you don't want the rotate targets - var rotateOverlayTargetSize = 10000; // really big target - var innerSnapAngle = 22.5; // the angle which we snap to on the inner rotation tool - var innerRadius; - var outerRadius; - var yawCenter; - var yawZero; - var rotationNormal; - var yawNormal; - var stopSoundDelay = 100; // number of msecs of not moving to have sound stop - - this.getRandomInt = function(min, max) { - return Math.floor(Math.random() * (max - min + 1)) + min; - } - - this.downloadSounds = function() { - for (var i = 0; i < this.moveSoundURLS.length; i++) { - this.moveSounds[i] = SoundCache.getSound(this.moveSoundURLS[i]); - } - for (var i = 0; i < this.turnSoundURLS.length; i++) { - this.turnSounds[i] = SoundCache.getSound(this.turnSoundURLS[i]); - } - } - - this.pickRandomSounds = function() { - var moveIndex = this.getRandomInt(0, this.moveSounds.length - 1); - var turnIndex = this.getRandomInt(0, this.turnSounds.length - 1); - if (debug) { - print("Random sounds -- turn:" + turnIndex + " move:" + moveIndex); - } - this.moveSound = this.moveSounds[moveIndex]; - this.turnSound = this.turnSounds[turnIndex]; - } - - // Play move sound - this.playMoveSound = function() { - if (debug) { - print("playMoveSound()"); - } - if (this.moveSound && this.moveSound.downloaded) { - if (debug) { - print("playMoveSound() --- calling this.injector = Audio.playSound(this.moveSound...)"); - } - this.injector = Audio.playSound(this.moveSound, { position: this.properties.position, loop: true, volume: 0.1 }); - } - } - - // Play turn sound - this.playTurnSound = function() { - if (debug) { - print("playTurnSound()"); - } - if (this.turnSound && this.turnSound.downloaded) { - if (debug) { - print("playTurnSound() --- calling this.injector = Audio.playSound(this.turnSound...)"); - } - this.injector = Audio.playSound(this.turnSound, { position: this.properties.position, loop: true, volume: 0.1 }); - } - } - - // stop sound - this.stopSound = function() { - if (debug) { - print("stopSound()"); - } - if (this.injector) { - Audio.stopInjector(this.injector); - this.injector = null; - } - } - - // Pr, Vr are respectively the Ray's Point of origin and Vector director - // Pp, Np are respectively the Plane's Point of origin and Normal vector - this.rayPlaneIntersection = function(Pr, Vr, Pp, Np) { - var d = -Vec3.dot(Pp, Np); - var t = -(Vec3.dot(Pr, Np) + d) / Vec3.dot(Vr, Np); - return Vec3.sum(Pr, Vec3.multiply(t, Vr)); - }; - - // updates the piece position based on mouse input - this.updatePosition = function(mouseEvent) { - var pickRay = Camera.computePickRay(mouseEvent.x, mouseEvent.y) - var upVector = { x: 0, y: 1, z: 0 }; - var intersection = this.rayPlaneIntersection(pickRay.origin, pickRay.direction, - this.properties.position, upVector); - - var newPosition = Vec3.sum(intersection, this.graboffset); - Entities.editEntity(this.entityID, { position: newPosition }); - }; - - this.grab = function(mouseEvent) { - // first calculate the offset - var pickRay = Camera.computePickRay(mouseEvent.x, mouseEvent.y) - var upVector = { x: 0, y: 1, z: 0 }; - var intersection = this.rayPlaneIntersection(pickRay.origin, pickRay.direction, - this.properties.position, upVector); - this.graboffset = Vec3.subtract(this.properties.position, intersection); - }; - - this.stopSoundIfNotMoving = function(mouseEvent) { - var nowDate = new Date(); - var nowMSecs = nowDate.getTime(); - if(mouseEvent.x == this.lastMovedPosition.x && mouseEvent.y == this.lastMovedPosition.y) { - var elapsedSinceLastMove = nowMSecs - this.lastMovedMSecs; - if (debug) { - print("elapsedSinceLastMove:" + elapsedSinceLastMove); - } - if (elapsedSinceLastMove > stopSoundDelay) { - if (debug) { - print("calling stopSound()..."); - } - this.stopSound(); - } - } else { - // if we've moved, then track our last move position and time... - this.lastMovedMSecs = nowMSecs; - this.lastMovedPosition.x = mouseEvent.x; - this.lastMovedPosition.y = mouseEvent.y; - } - } - - this.move = function(mouseEvent) { - this.updatePosition(mouseEvent); - if (this.injector === null) { - this.playMoveSound(); - } - }; - - this.release = function(mouseEvent) { - this.updatePosition(mouseEvent); - }; - - this.rotate = function(mouseEvent) { - var pickRay = Camera.computePickRay(mouseEvent.x, mouseEvent.y) - var result = Overlays.findRayIntersection(pickRay); - - if (result.intersects) { - var center = yawCenter; - var zero = yawZero; - var centerToZero = Vec3.subtract(center, zero); - var centerToIntersect = Vec3.subtract(center, result.intersection); - var angleFromZero = Vec3.orientedAngle(centerToZero, centerToIntersect, rotationNormal); - - var distanceFromCenter = Vec3.distance(center, result.intersection); - var snapToInner = false; - // var innerRadius = (Vec3.length(selectionManager.worldDimensions) / 2) * 1.1; - if (distanceFromCenter < innerRadius) { - angleFromZero = Math.floor(angleFromZero/innerSnapAngle) * innerSnapAngle; - snapToInner = true; - } - - var yawChange = Quat.fromVec3Degrees({ x: 0, y: angleFromZero, z: 0 }); - Entities.editEntity(this.entityID, { rotation: Quat.multiply(yawChange, this.originalRotation) }); - - - // update the rotation display accordingly... - var startAtCurrent = 360-angleFromZero; - var endAtCurrent = 360; - var startAtRemainder = 0; - var endAtRemainder = 360-angleFromZero; - if (angleFromZero < 0) { - startAtCurrent = 0; - endAtCurrent = -angleFromZero; - startAtRemainder = -angleFromZero; - endAtRemainder = 360; - } - - if (snapToInner) { - Overlays.editOverlay(this.rotateOverlayOuter, { startAt: 0, endAt: 360 }); - Overlays.editOverlay(this.rotateOverlayInner, { startAt: startAtRemainder, endAt: endAtRemainder }); - Overlays.editOverlay(this.rotateOverlayCurrent, { startAt: startAtCurrent, endAt: endAtCurrent, size: innerRadius, - majorTickMarksAngle: innerSnapAngle, minorTickMarksAngle: 0, - majorTickMarksLength: -0.25, minorTickMarksLength: 0, }); - } else { - Overlays.editOverlay(this.rotateOverlayInner, { startAt: 0, endAt: 360 }); - Overlays.editOverlay(this.rotateOverlayOuter, { startAt: startAtRemainder, endAt: endAtRemainder }); - Overlays.editOverlay(this.rotateOverlayCurrent, { startAt: startAtCurrent, endAt: endAtCurrent, size: outerRadius, - majorTickMarksAngle: 45.0, minorTickMarksAngle: 5, - majorTickMarksLength: 0.25, minorTickMarksLength: 0.1, }); - } - } - - if (this.injector === null) { - this.playTurnSound(); - } - }; - // All callbacks start by updating the properties - this.updateProperties = function(entityID) { - if (this.entityID === null || !this.entityID.isKnownID) { - this.entityID = Entities.identifyEntity(entityID); - } - this.properties = Entities.getEntityProperties(this.entityID); - }; - - this.cleanupRotateOverlay = function() { - Overlays.deleteOverlay(this.rotateOverlayTarget); - Overlays.deleteOverlay(this.rotateOverlayInner); - Overlays.deleteOverlay(this.rotateOverlayOuter); - Overlays.deleteOverlay(this.rotateOverlayCurrent); - this.rotateOverlayTarget = null; - this.rotateOverlayInner = null; - this.rotateOverlayOuter = null; - this.rotateOverlayCurrent = null; - } - - this.displayRotateOverlay = function(mouseEvent) { - var yawOverlayAngles = { x: 90, y: 0, z: 0 }; - var yawOverlayRotation = Quat.fromVec3Degrees(yawOverlayAngles); - - yawNormal = { x: 0, y: 1, z: 0 }; - yawCenter = this.properties.position; - rotationNormal = yawNormal; - - // Size the overlays to the current selection size - var diagonal = (Vec3.length(this.properties.dimensions) / 2) * 1.1; - var halfDimensions = Vec3.multiply(this.properties.dimensions, 0.5); - innerRadius = diagonal; - outerRadius = diagonal * 1.15; - var innerAlpha = 0.2; - var outerAlpha = 0.2; - - this.rotateOverlayTarget = Overlays.addOverlay("circle3d", { - position: this.properties.position, - size: rotateOverlayTargetSize, - color: { red: 0, green: 0, blue: 0 }, - alpha: 0.0, - solid: true, - visible: true, - rotation: yawOverlayRotation, - ignoreRayIntersection: false - }); - - this.rotateOverlayInner = Overlays.addOverlay("circle3d", { - position: this.properties.position, - size: innerRadius, - innerRadius: 0.9, - alpha: innerAlpha, - color: { red: 51, green: 152, blue: 203 }, - solid: true, - visible: displayRotateTargets, - rotation: yawOverlayRotation, - hasTickMarks: true, - majorTickMarksAngle: innerSnapAngle, - minorTickMarksAngle: 0, - majorTickMarksLength: -0.25, - minorTickMarksLength: 0, - majorTickMarksColor: { red: 0, green: 0, blue: 0 }, - minorTickMarksColor: { red: 0, green: 0, blue: 0 }, - ignoreRayIntersection: true, // always ignore this - }); - - this.rotateOverlayOuter = Overlays.addOverlay("circle3d", { - position: this.properties.position, - size: outerRadius, - innerRadius: 0.9, - startAt: 0, - endAt: 360, - alpha: outerAlpha, - color: { red: 51, green: 152, blue: 203 }, - solid: true, - visible: displayRotateTargets, - rotation: yawOverlayRotation, - - hasTickMarks: true, - majorTickMarksAngle: 45.0, - minorTickMarksAngle: 5, - majorTickMarksLength: 0.25, - minorTickMarksLength: 0.1, - majorTickMarksColor: { red: 0, green: 0, blue: 0 }, - minorTickMarksColor: { red: 0, green: 0, blue: 0 }, - ignoreRayIntersection: true, // always ignore this - }); - - this.rotateOverlayCurrent = Overlays.addOverlay("circle3d", { - position: this.properties.position, - size: outerRadius, - startAt: 0, - endAt: 0, - innerRadius: 0.9, - color: { red: 224, green: 67, blue: 36}, - alpha: 0.8, - solid: true, - visible: displayRotateTargets, - rotation: yawOverlayRotation, - ignoreRayIntersection: true, // always ignore this - hasTickMarks: true, - majorTickMarksColor: { red: 0, green: 0, blue: 0 }, - minorTickMarksColor: { red: 0, green: 0, blue: 0 }, - }); - - var pickRay = Camera.computePickRay(mouseEvent.x, mouseEvent.y) - var result = Overlays.findRayIntersection(pickRay); - yawZero = result.intersection; - - }; - - this.preload = function(entityID) { - this.updateProperties(entityID); // All callbacks start by updating the properties - this.downloadSounds(); - }; - - this.clickDownOnEntity = function(entityID, mouseEvent) { - this.updateProperties(entityID); // All callbacks start by updating the properties - this.grab(mouseEvent); - - var nowDate = new Date(); - var nowMSecs = nowDate.getTime(); - this.clickedAt = nowMSecs; - this.firstHolding = true; - - this.clicked.x = mouseEvent.x; - this.clicked.y = mouseEvent.y; - this.lastMovedPosition.x = mouseEvent.x; - this.lastMovedPosition.y = mouseEvent.y; - this.lastMovedMSecs = nowMSecs; - - this.pickRandomSounds(); - }; - - this.holdingClickOnEntity = function(entityID, mouseEvent) { - - this.updateProperties(entityID); // All callbacks start by updating the properties - - if (this.firstHolding) { - // if we haven't moved yet... - if (this.clicked.x == mouseEvent.x && this.clicked.y == mouseEvent.y) { - var d = new Date(); - var now = d.getTime(); - - if (now - this.clickedAt > 500) { - this.displayRotateOverlay(mouseEvent); - this.firstHolding = false; - this.rotateMode = true; - this.originalRotation = this.properties.rotation; - } - } else { - this.firstHolding = false; - } - } - - if (this.rotateMode) { - this.rotate(mouseEvent); - } else { - this.move(mouseEvent); - } - - this.stopSoundIfNotMoving(mouseEvent); - }; - this.clickReleaseOnEntity = function(entityID, mouseEvent) { - this.updateProperties(entityID); // All callbacks start by updating the properties - if (this.rotateMode) { - this.rotate(mouseEvent); - } else { - this.release(mouseEvent); - } - - if (this.rotateOverlayTarget != null) { - this.cleanupRotateOverlay(); - this.rotateMode = false; - } - - this.firstHolding = false; - this.stopSound(); - }; +(function() { + Script.include("movableClass.js"); + return new Movable(); }) diff --git a/examples/entityScripts/movableClass.js b/examples/entityScripts/movableClass.js new file mode 100644 index 0000000000..26fb643826 --- /dev/null +++ b/examples/entityScripts/movableClass.js @@ -0,0 +1,426 @@ +// +// movableClass.js +// examples/entityScripts +// +// Created by Brad Hefta-Gaub on 11/17/14. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// +Movable = function() { + + this.entityID = null; + this.properties = null; + this.graboffset = null; + this.clickedAt = null; + this.firstHolding = true; + this.clicked = { x: -1, y: -1}; + this.lastMovedPosition = { x: -1, y: -1}; + this.lastMovedTime = 0; + this.rotateOverlayTarget = null; + this.rotateOverlayInner = null; + this.rotateOverlayOuter = null; + this.rotateOverlayCurrent = null; + this.rotateMode = false; + this.originalRotation = null; + + this.moveSoundURLS = [ + "http://public.highfidelity.io/sounds/MovingFurniture/FurnitureMove1.wav", + "http://public.highfidelity.io/sounds/MovingFurniture/FurnitureMove2.wav", + "http://public.highfidelity.io/sounds/MovingFurniture/FurnitureMove3.wav" + ]; + + this.turnSoundURLS = [ + + "http://public.highfidelity.io/sounds/MovingFurniture/FurnitureMove1.wav", + "http://public.highfidelity.io/sounds/MovingFurniture/FurnitureMove2.wav", + "http://public.highfidelity.io/sounds/MovingFurniture/FurnitureMove3.wav" + + // TODO: determine if these or other turn sounds work better than move sounds. + //"http://public.highfidelity.io/sounds/MovingFurniture/FurnitureTurn1.wav", + //"http://public.highfidelity.io/sounds/MovingFurniture/FurnitureTurn2.wav", + //"http://public.highfidelity.io/sounds/MovingFurniture/FurnitureTurn3.wav" + ]; + + + this.moveSounds = new Array(); + this.turnSounds = new Array(); + this.moveSound = null; + this.turnSound = null; + this.injector = null; + + var debug = false; + var displayRotateTargets = true; // change to false if you don't want the rotate targets + var rotateOverlayTargetSize = 10000; // really big target + var innerSnapAngle = 22.5; // the angle which we snap to on the inner rotation tool + var innerRadius; + var outerRadius; + var yawCenter; + var yawZero; + var rotationNormal; + var yawNormal; + var stopSoundDelay = 100; // number of msecs of not moving to have sound stop + + this.getRandomInt = function(min, max) { + return Math.floor(Math.random() * (max - min + 1)) + min; + } + + this.downloadSounds = function() { + for (var i = 0; i < this.moveSoundURLS.length; i++) { + this.moveSounds[i] = SoundCache.getSound(this.moveSoundURLS[i]); + } + for (var i = 0; i < this.turnSoundURLS.length; i++) { + this.turnSounds[i] = SoundCache.getSound(this.turnSoundURLS[i]); + } + } + + this.pickRandomSounds = function() { + var moveIndex = this.getRandomInt(0, this.moveSounds.length - 1); + var turnIndex = this.getRandomInt(0, this.turnSounds.length - 1); + if (debug) { + print("Random sounds -- turn:" + turnIndex + " move:" + moveIndex); + } + this.moveSound = this.moveSounds[moveIndex]; + this.turnSound = this.turnSounds[turnIndex]; + } + + // Play move sound + this.playMoveSound = function() { + if (debug) { + print("playMoveSound()"); + } + if (this.moveSound && this.moveSound.downloaded) { + if (debug) { + print("playMoveSound() --- calling this.injector = Audio.playSound(this.moveSound...)"); + } + this.injector = Audio.playSound(this.moveSound, { position: this.properties.position, loop: true, volume: 0.1 }); + } + } + + // Play turn sound + this.playTurnSound = function() { + if (debug) { + print("playTurnSound()"); + } + if (this.turnSound && this.turnSound.downloaded) { + if (debug) { + print("playTurnSound() --- calling this.injector = Audio.playSound(this.turnSound...)"); + } + this.injector = Audio.playSound(this.turnSound, { position: this.properties.position, loop: true, volume: 0.1 }); + } + } + + // stop sound + this.stopSound = function() { + if (debug) { + print("stopSound()"); + } + if (this.injector) { + Audio.stopInjector(this.injector); + this.injector = null; + } + } + + // Pr, Vr are respectively the Ray's Point of origin and Vector director + // Pp, Np are respectively the Plane's Point of origin and Normal vector + this.rayPlaneIntersection = function(Pr, Vr, Pp, Np) { + var d = -Vec3.dot(Pp, Np); + var t = -(Vec3.dot(Pr, Np) + d) / Vec3.dot(Vr, Np); + return Vec3.sum(Pr, Vec3.multiply(t, Vr)); + }; + + // updates the piece position based on mouse input + this.updatePosition = function(mouseEvent) { + var pickRay = Camera.computePickRay(mouseEvent.x, mouseEvent.y) + var upVector = { x: 0, y: 1, z: 0 }; + var intersection = this.rayPlaneIntersection(pickRay.origin, pickRay.direction, + this.properties.position, upVector); + + var newPosition = Vec3.sum(intersection, this.graboffset); + Entities.editEntity(this.entityID, { position: newPosition }); + }; + + this.grab = function(mouseEvent) { + // first calculate the offset + var pickRay = Camera.computePickRay(mouseEvent.x, mouseEvent.y) + var upVector = { x: 0, y: 1, z: 0 }; + var intersection = this.rayPlaneIntersection(pickRay.origin, pickRay.direction, + this.properties.position, upVector); + this.graboffset = Vec3.subtract(this.properties.position, intersection); + }; + + this.stopSoundIfNotMoving = function(mouseEvent) { + var nowDate = new Date(); + var nowMSecs = nowDate.getTime(); + if(mouseEvent.x == this.lastMovedPosition.x && mouseEvent.y == this.lastMovedPosition.y) { + var elapsedSinceLastMove = nowMSecs - this.lastMovedMSecs; + if (debug) { + print("elapsedSinceLastMove:" + elapsedSinceLastMove); + } + if (elapsedSinceLastMove > stopSoundDelay) { + if (debug) { + print("calling stopSound()..."); + } + this.stopSound(); + } + } else { + // if we've moved, then track our last move position and time... + this.lastMovedMSecs = nowMSecs; + this.lastMovedPosition.x = mouseEvent.x; + this.lastMovedPosition.y = mouseEvent.y; + } + } + + this.move = function(mouseEvent) { + this.updatePosition(mouseEvent); + if (this.injector === null) { + this.playMoveSound(); + } + }; + + this.release = function(mouseEvent) { + this.updatePosition(mouseEvent); + }; + + this.rotate = function(mouseEvent) { + var pickRay = Camera.computePickRay(mouseEvent.x, mouseEvent.y) + var result = Overlays.findRayIntersection(pickRay); + + if (result.intersects) { + var center = yawCenter; + var zero = yawZero; + var centerToZero = Vec3.subtract(center, zero); + var centerToIntersect = Vec3.subtract(center, result.intersection); + var angleFromZero = Vec3.orientedAngle(centerToZero, centerToIntersect, rotationNormal); + + var distanceFromCenter = Vec3.distance(center, result.intersection); + var snapToInner = false; + // var innerRadius = (Vec3.length(selectionManager.worldDimensions) / 2) * 1.1; + if (distanceFromCenter < innerRadius) { + angleFromZero = Math.floor(angleFromZero/innerSnapAngle) * innerSnapAngle; + snapToInner = true; + } + + var yawChange = Quat.fromVec3Degrees({ x: 0, y: angleFromZero, z: 0 }); + Entities.editEntity(this.entityID, { rotation: Quat.multiply(yawChange, this.originalRotation) }); + + + // update the rotation display accordingly... + var startAtCurrent = 360-angleFromZero; + var endAtCurrent = 360; + var startAtRemainder = 0; + var endAtRemainder = 360-angleFromZero; + if (angleFromZero < 0) { + startAtCurrent = 0; + endAtCurrent = -angleFromZero; + startAtRemainder = -angleFromZero; + endAtRemainder = 360; + } + + if (snapToInner) { + Overlays.editOverlay(this.rotateOverlayOuter, { startAt: 0, endAt: 360 }); + Overlays.editOverlay(this.rotateOverlayInner, { startAt: startAtRemainder, endAt: endAtRemainder }); + Overlays.editOverlay(this.rotateOverlayCurrent, { startAt: startAtCurrent, endAt: endAtCurrent, size: innerRadius, + majorTickMarksAngle: innerSnapAngle, minorTickMarksAngle: 0, + majorTickMarksLength: -0.25, minorTickMarksLength: 0, }); + } else { + Overlays.editOverlay(this.rotateOverlayInner, { startAt: 0, endAt: 360 }); + Overlays.editOverlay(this.rotateOverlayOuter, { startAt: startAtRemainder, endAt: endAtRemainder }); + Overlays.editOverlay(this.rotateOverlayCurrent, { startAt: startAtCurrent, endAt: endAtCurrent, size: outerRadius, + majorTickMarksAngle: 45.0, minorTickMarksAngle: 5, + majorTickMarksLength: 0.25, minorTickMarksLength: 0.1, }); + } + } + + if (this.injector === null) { + this.playTurnSound(); + } + }; + // All callbacks start by updating the properties + this.updateProperties = function(entityID) { + if (this.entityID === null || !this.entityID.isKnownID) { + this.entityID = Entities.identifyEntity(entityID); + } + this.properties = Entities.getEntityProperties(this.entityID); + }; + + this.cleanupRotateOverlay = function() { + Overlays.deleteOverlay(this.rotateOverlayTarget); + Overlays.deleteOverlay(this.rotateOverlayInner); + Overlays.deleteOverlay(this.rotateOverlayOuter); + Overlays.deleteOverlay(this.rotateOverlayCurrent); + this.rotateOverlayTarget = null; + this.rotateOverlayInner = null; + this.rotateOverlayOuter = null; + this.rotateOverlayCurrent = null; + } + + this.displayRotateOverlay = function(mouseEvent) { + var yawOverlayAngles = { x: 90, y: 0, z: 0 }; + var yawOverlayRotation = Quat.fromVec3Degrees(yawOverlayAngles); + + yawNormal = { x: 0, y: 1, z: 0 }; + yawCenter = this.properties.position; + rotationNormal = yawNormal; + + // Size the overlays to the current selection size + var diagonal = (Vec3.length(this.properties.dimensions) / 2) * 1.1; + var halfDimensions = Vec3.multiply(this.properties.dimensions, 0.5); + innerRadius = diagonal; + outerRadius = diagonal * 1.15; + var innerAlpha = 0.2; + var outerAlpha = 0.2; + + this.rotateOverlayTarget = Overlays.addOverlay("circle3d", { + position: this.properties.position, + size: rotateOverlayTargetSize, + color: { red: 0, green: 0, blue: 0 }, + alpha: 0.0, + solid: true, + visible: true, + rotation: yawOverlayRotation, + ignoreRayIntersection: false + }); + + this.rotateOverlayInner = Overlays.addOverlay("circle3d", { + position: this.properties.position, + size: innerRadius, + innerRadius: 0.9, + alpha: innerAlpha, + color: { red: 51, green: 152, blue: 203 }, + solid: true, + visible: displayRotateTargets, + rotation: yawOverlayRotation, + hasTickMarks: true, + majorTickMarksAngle: innerSnapAngle, + minorTickMarksAngle: 0, + majorTickMarksLength: -0.25, + minorTickMarksLength: 0, + majorTickMarksColor: { red: 0, green: 0, blue: 0 }, + minorTickMarksColor: { red: 0, green: 0, blue: 0 }, + ignoreRayIntersection: true, // always ignore this + }); + + this.rotateOverlayOuter = Overlays.addOverlay("circle3d", { + position: this.properties.position, + size: outerRadius, + innerRadius: 0.9, + startAt: 0, + endAt: 360, + alpha: outerAlpha, + color: { red: 51, green: 152, blue: 203 }, + solid: true, + visible: displayRotateTargets, + rotation: yawOverlayRotation, + + hasTickMarks: true, + majorTickMarksAngle: 45.0, + minorTickMarksAngle: 5, + majorTickMarksLength: 0.25, + minorTickMarksLength: 0.1, + majorTickMarksColor: { red: 0, green: 0, blue: 0 }, + minorTickMarksColor: { red: 0, green: 0, blue: 0 }, + ignoreRayIntersection: true, // always ignore this + }); + + this.rotateOverlayCurrent = Overlays.addOverlay("circle3d", { + position: this.properties.position, + size: outerRadius, + startAt: 0, + endAt: 0, + innerRadius: 0.9, + color: { red: 224, green: 67, blue: 36}, + alpha: 0.8, + solid: true, + visible: displayRotateTargets, + rotation: yawOverlayRotation, + ignoreRayIntersection: true, // always ignore this + hasTickMarks: true, + majorTickMarksColor: { red: 0, green: 0, blue: 0 }, + minorTickMarksColor: { red: 0, green: 0, blue: 0 }, + }); + + var pickRay = Camera.computePickRay(mouseEvent.x, mouseEvent.y) + var result = Overlays.findRayIntersection(pickRay); + yawZero = result.intersection; + + }; +}; + +Movable.prototype = { + preload : function(entityID) { + print("Movable.preload()"); + this.updateProperties(entityID); // All callbacks start by updating the properties + this.downloadSounds(); + }, + + clickDownOnEntity : function(entityID, mouseEvent) { + print("Movable.clickDownOnEntity()"); + + this.updateProperties(entityID); // All callbacks start by updating the properties + this.grab(mouseEvent); + + var nowDate = new Date(); + var nowMSecs = nowDate.getTime(); + this.clickedAt = nowMSecs; + this.firstHolding = true; + + this.clicked.x = mouseEvent.x; + this.clicked.y = mouseEvent.y; + this.lastMovedPosition.x = mouseEvent.x; + this.lastMovedPosition.y = mouseEvent.y; + this.lastMovedMSecs = nowMSecs; + + this.pickRandomSounds(); + }, + + holdingClickOnEntity : function(entityID, mouseEvent) { + print("Movable.holdingClickOnEntity()"); + + this.updateProperties(entityID); // All callbacks start by updating the properties + + if (this.firstHolding) { + // if we haven't moved yet... + if (this.clicked.x == mouseEvent.x && this.clicked.y == mouseEvent.y) { + var d = new Date(); + var now = d.getTime(); + + if (now - this.clickedAt > 500) { + this.displayRotateOverlay(mouseEvent); + this.firstHolding = false; + this.rotateMode = true; + this.originalRotation = this.properties.rotation; + } + } else { + this.firstHolding = false; + } + } + + if (this.rotateMode) { + this.rotate(mouseEvent); + } else { + this.move(mouseEvent); + } + + this.stopSoundIfNotMoving(mouseEvent); + }, + + clickReleaseOnEntity : function(entityID, mouseEvent) { + print("Movable.clickReleaseOnEntity()"); + this.updateProperties(entityID); // All callbacks start by updating the properties + if (this.rotateMode) { + this.rotate(mouseEvent); + } else { + this.release(mouseEvent); + } + + if (this.rotateOverlayTarget != null) { + this.cleanupRotateOverlay(); + this.rotateMode = false; + } + + this.firstHolding = false; + this.stopSound(); + }, +}; diff --git a/examples/entityScripts/sitOnEntity.js b/examples/entityScripts/sitOnEntity.js index d5c4fa9c52..080acf61a8 100644 --- a/examples/entityScripts/sitOnEntity.js +++ b/examples/entityScripts/sitOnEntity.js @@ -11,362 +11,7 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -(function(){ - - this.entityID = null; - this.properties = null; - this.standUpButton = null; - this.indicatorsAdded = false; - this.indicator = new Array(); - - - var buttonImageUrl = "https://worklist-prod.s3.amazonaws.com/attachment/0aca88e1-9bd8-5c1d.svg"; - var windowDimensions = Controller.getViewportDimensions(); - var buttonWidth = 37; - var buttonHeight = 46; - var buttonPadding = 50; // inside the normal toolbar position - var buttonPositionX = windowDimensions.x - buttonPadding - buttonWidth; - var buttonPositionY = (windowDimensions.y - buttonHeight) / 2 - (buttonHeight + buttonPadding); - - var passedTime = 0.0; - var startPosition = null; - var startRotation = null; - var animationLenght = 2.0; - - var avatarOldPosition = { x: 0, y: 0, z: 0 }; - - var sittingSettingsHandle = "SitJsSittingPosition"; - var sitting = Settings.getValue(sittingSettingsHandle, false) == "true"; - print("Original sitting status: " + sitting); - var frame = 0; - - var seat = new Object(); - var hiddingSeats = false; - - // This is the pose we would like to end up - var pose = [ - {joint:"RightUpLeg", rotation: {x:100.0, y:15.0, z:0.0}}, - {joint:"RightLeg", rotation: {x:-130.0, y:15.0, z:0.0}}, - {joint:"RightFoot", rotation: {x:30, y:15.0, z:0.0}}, - {joint:"LeftUpLeg", rotation: {x:100.0, y:-15.0, z:0.0}}, - {joint:"LeftLeg", rotation: {x:-130.0, y:-15.0, z:0.0}}, - {joint:"LeftFoot", rotation: {x:30, y:15.0, z:0.0}} - ]; - - var startPoseAndTransition = []; - - function storeStartPoseAndTransition() { - for (var i = 0; i < pose.length; i++){ - var startRotation = Quat.safeEulerAngles(MyAvatar.getJointRotation(pose[i].joint)); - var transitionVector = Vec3.subtract( pose[i].rotation, startRotation ); - startPoseAndTransition.push({joint: pose[i].joint, start: startRotation, transition: transitionVector}); - } - } - - function updateJoints(factor){ - for (var i = 0; i < startPoseAndTransition.length; i++){ - var scaledTransition = Vec3.multiply(startPoseAndTransition[i].transition, factor); - var rotation = Vec3.sum(startPoseAndTransition[i].start, scaledTransition); - MyAvatar.setJointData(startPoseAndTransition[i].joint, Quat.fromVec3Degrees( rotation )); - } - } - - var sittingDownAnimation = function(deltaTime) { - - passedTime += deltaTime; - var factor = passedTime/animationLenght; - - if ( passedTime <= animationLenght ) { - updateJoints(factor); - - var pos = { x: startPosition.x - 0.3 * factor, y: startPosition.y - 0.5 * factor, z: startPosition.z}; - MyAvatar.position = pos; - } else { - Script.update.disconnect(sittingDownAnimation); - if (seat.model) { - MyAvatar.setModelReferential(seat.model.id); - } - } - } - - var standingUpAnimation = function(deltaTime) { - - passedTime += deltaTime; - var factor = 1 - passedTime/animationLenght; - - if ( passedTime <= animationLenght ) { - - updateJoints(factor); - - var pos = { x: startPosition.x + 0.3 * (passedTime/animationLenght), y: startPosition.y + 0.5 * (passedTime/animationLenght), z: startPosition.z}; - MyAvatar.position = pos; - } else { - Script.update.disconnect(standingUpAnimation); - - } - } - - var externalThis = this; - - var goToSeatAnimation = function(deltaTime) { - passedTime += deltaTime; - var factor = passedTime/animationLenght; - - if (passedTime <= animationLenght) { - var targetPosition = Vec3.sum(seat.position, { x: 0.3, y: 0.5, z: 0 }); - MyAvatar.position = Vec3.sum(Vec3.multiply(startPosition, 1 - factor), Vec3.multiply(targetPosition, factor)); - } else if (passedTime <= 2 * animationLenght) { - //Quat.print("MyAvatar: ", MyAvatar.orientation); - //Quat.print("Seat: ", seat.rotation); - MyAvatar.orientation = Quat.mix(startRotation, seat.rotation, factor - 1); - } else { - Script.update.disconnect(goToSeatAnimation); - externalThis.sitDown(); - externalThis.showIndicators(false); - } - } - - var globalMouseClick = function(event) { - var clickedOverlay = Overlays.getOverlayAtPoint({x: event.x, y: event.y}); - if (clickedOverlay == externalThis.standUpButton) { - seat.model = null; - externalThis.standUp(); - Controller.mousePressEvent.disconnect(globalMouseClick); - } - }; - - this.sitDown = function() { - sitting = true; - Settings.setValue(sittingSettingsHandle, sitting); - print("sitDown sitting status: " + Settings.getValue(sittingSettingsHandle, false)); - passedTime = 0.0; - startPosition = MyAvatar.position; - storeStartPoseAndTransition(); - try { - Script.update.disconnect(standingUpAnimation); - } catch(e){ - // no need to handle. if it wasn't connected no harm done - } - Script.update.connect(sittingDownAnimation); - Overlays.editOverlay(this.standUpButton, { visible: true }); - Controller.mousePressEvent.connect(globalMouseClick); - } - - this.standUp = function() { - sitting = false; - Settings.setValue(sittingSettingsHandle, sitting); - print("standUp sitting status: " + Settings.getValue(sittingSettingsHandle, false)); - passedTime = 0.0; - startPosition = MyAvatar.position; - MyAvatar.clearReferential(); - try{ - Script.update.disconnect(sittingDownAnimation); - } catch (e){} - Script.update.connect(standingUpAnimation); - Overlays.editOverlay(this.standUpButton, { visible: false }); - Controller.mousePressEvent.disconnect(globalMouseClick); - } - - function SeatIndicator(modelProperties, seatIndex) { - var halfDiagonal = Vec3.length(modelProperties.dimensions) / 2.0; - - this.position = Vec3.sum(modelProperties.position, - Vec3.multiply(Vec3.multiplyQbyV(modelProperties.rotation, modelProperties.sittingPoints[seatIndex].position), - halfDiagonal)); // hack - - this.orientation = Quat.multiply(modelProperties.rotation, - modelProperties.sittingPoints[seatIndex].rotation); - this.scale = MyAvatar.scale / 3; - - this.sphere = Overlays.addOverlay("billboard", { - subImage: { x: 0, y: buttonHeight, width: buttonWidth, height: buttonHeight}, - url: buttonImageUrl, - position: this.position, - scale: this.scale, - size: this.scale, - solid: true, - color: { red: 255, green: 255, blue: 255 }, - alpha: 0.8, - visible: true, - isFacingAvatar: true - }); - - this.show = function(doShow) { - Overlays.editOverlay(this.sphere, { visible: doShow }); - } - - this.update = function() { - Overlays.editOverlay(this.sphere, { - position: this.position, - size: this.scale - }); - } - - this.cleanup = function() { - Overlays.deleteOverlay(this.sphere); - } - } - - function update(deltaTime){ - var newWindowDimensions = Controller.getViewportDimensions(); - if( newWindowDimensions.x != windowDimensions.x || newWindowDimensions.y != windowDimensions.y ){ - windowDimensions = newWindowDimensions; - var newX = windowDimensions.x - buttonPadding - buttonWidth; - var newY = (windowDimensions.y - buttonHeight) / 2 ; - Overlays.editOverlay( this.standUpButton, {x: newX, y: newY} ); - } - - // For a weird reason avatar joint don't update till the 10th frame - // Set the update frame to 20 to be safe - var UPDATE_FRAME = 20; - if (frame <= UPDATE_FRAME) { - if (frame == UPDATE_FRAME) { - if (sitting == true) { - print("Was seated: " + sitting); - storeStartPoseAndTransition(); - updateJoints(1.0); - } - } - frame++; - } - } - - this.addIndicators = function() { - if (!this.indicatorsAdded) { - if (this.properties.sittingPoints.length > 0) { - for (var i = 0; i < this.properties.sittingPoints.length; ++i) { - this.indicator[i] = new SeatIndicator(this.properties, i); - } - this.indicatorsAdded = true; - } - } - } - - this.removeIndicators = function() { - for (var i = 0; i < this.properties.sittingPoints.length; ++i) { - this.indicator[i].cleanup(); - } - } - - this.showIndicators = function(doShow) { - this.addIndicators(); - if (this.indicatorsAdded) { - for (var i = 0; i < this.properties.sittingPoints.length; ++i) { - this.indicator[i].show(doShow); - } - } - hiddingSeats = !doShow; - } - - function raySphereIntersection(origin, direction, center, radius) { - var A = origin; - var B = Vec3.normalize(direction); - var P = center; - - var x = Vec3.dot(Vec3.subtract(P, A), B); - var X = Vec3.sum(A, Vec3.multiply(B, x)); - var d = Vec3.length(Vec3.subtract(P, X)); - - return (x > 0 && d <= radius); - } - - this.cleanup = function() { - this.standUp(); - MyAvatar.clearReferential(); - for (var i = 0; i < pose.length; i++){ - MyAvatar.clearJointData(pose[i].joint); - } - Overlays.deleteOverlay(this.standUpButton); - for (var i = 0; i < this.indicator.length; ++i) { - this.indicator[i].cleanup(); - } - }; - - - this.createStandupButton = function() { - this.standUpButton = Overlays.addOverlay("image", { - x: buttonPositionX, y: buttonPositionY, width: buttonWidth, height: buttonHeight, - subImage: { x: buttonWidth, y: buttonHeight, width: buttonWidth, height: buttonHeight}, - imageURL: buttonImageUrl, - visible: false, - alpha: 1.0 - }); - }; - - this.handleClickEvent = function(event) { - var clickedOverlay = Overlays.getOverlayAtPoint({x: event.x, y: event.y}); - - if (clickedOverlay == this.standUpButton) { - seat.model = null; - this.standUp(); - } else { - this.addIndicators(); - if (this.indicatorsAdded) { - var pickRay = Camera.computePickRay(event.x, event.y); - - var clickedOnSeat = false; - - for (var i = 0; i < this.properties.sittingPoints.length; ++i) { - if (raySphereIntersection(pickRay.origin, - pickRay.direction, - this.indicator[i].position, - this.indicator[i].scale / 2)) { - clickedOnSeat = true; - seat.model = this.entityID; // ?? - seat.position = this.indicator[i].position; - seat.rotation = this.indicator[i].orientation; - } - } - - if (clickedOnSeat) { - passedTime = 0.0; - startPosition = MyAvatar.position; - startRotation = MyAvatar.orientation; - try{ Script.update.disconnect(standingUpAnimation); } catch(e){} - try{ Script.update.disconnect(sittingDownAnimation); } catch(e){} - Script.update.connect(goToSeatAnimation); - } - } - } - }; - - - // All callbacks start by updating the properties - this.updateProperties = function(entityID) { - if (this.entityID === null || !this.entityID.isKnownID) { - this.entityID = Entities.identifyEntity(entityID); - } - this.properties = Entities.getEntityProperties(this.entityID); - }; - - this.unload = function(entityID) { - this.cleanup(); - Script.update.disconnect(update); - }; - - this.preload = function(entityID) { - this.updateProperties(entityID); // All callbacks start by updating the properties - this.createStandupButton(); - Script.update.connect(update); - }; - - - this.hoverOverEntity = function(entityID, mouseEvent) { - this.updateProperties(entityID); // All callbacks start by updating the properties - this.showIndicators(true); - }; - this.hoverLeaveEntity = function(entityID, mouseEvent) { - this.updateProperties(entityID); // All callbacks start by updating the properties - this.showIndicators(false); - }; - - this.clickDownOnEntity = function(entityID, mouseEvent) { - this.updateProperties(entityID); // All callbacks start by updating the properties - this.handleClickEvent(mouseEvent); - }; - - this.clickReleaseOnEntity = function(entityID, mouseEvent) { - this.updateProperties(entityID); // All callbacks start by updating the properties - }; - -}) \ No newline at end of file +(function() { + Script.include("sittableClass.js"); + return new Sittable(); +}) diff --git a/examples/entityScripts/sittable.js b/examples/entityScripts/sittable.js new file mode 100644 index 0000000000..0753a46d2a --- /dev/null +++ b/examples/entityScripts/sittable.js @@ -0,0 +1,15 @@ +// +// sittable.js +// examples/entityScripts +// +// Created by Brad Hefta-Gaub on 11/17/14. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +(function() { + Script.include("sittableClass.js"); + return new Sittable(); +}) diff --git a/examples/entityScripts/sittableClass.js b/examples/entityScripts/sittableClass.js new file mode 100644 index 0000000000..c16e026f96 --- /dev/null +++ b/examples/entityScripts/sittableClass.js @@ -0,0 +1,381 @@ +// +// sitOnEntity.js +// examples/entityScripts +// +// Created by Brad Hefta-Gaub on 11/1/14. +// Copyright 2014 High Fidelity, Inc. +// +// This is an example of an entity script for sitting. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +Sittable = function() { + + this.entityID = null; + this.properties = null; + this.standUpButton = null; + this.indicatorsAdded = false; + this.indicator = new Array(); + + + var buttonImageUrl = "https://worklist-prod.s3.amazonaws.com/attachment/0aca88e1-9bd8-5c1d.svg"; + var windowDimensions = Controller.getViewportDimensions(); + var buttonWidth = 37; + var buttonHeight = 46; + var buttonPadding = 50; // inside the normal toolbar position + var buttonPositionX = windowDimensions.x - buttonPadding - buttonWidth; + var buttonPositionY = (windowDimensions.y - buttonHeight) / 2 - (buttonHeight + buttonPadding); + + var passedTime = 0.0; + var startPosition = null; + var startRotation = null; + var animationLenght = 2.0; + + var avatarOldPosition = { x: 0, y: 0, z: 0 }; + + var sittingSettingsHandle = "SitJsSittingPosition"; + var sitting = Settings.getValue(sittingSettingsHandle, false) == "true"; + print("Original sitting status: " + sitting); + var frame = 0; + + var seat = new Object(); + var hiddingSeats = false; + + // This is the pose we would like to end up + var pose = [ + {joint:"RightUpLeg", rotation: {x:100.0, y:15.0, z:0.0}}, + {joint:"RightLeg", rotation: {x:-130.0, y:15.0, z:0.0}}, + {joint:"RightFoot", rotation: {x:30, y:15.0, z:0.0}}, + {joint:"LeftUpLeg", rotation: {x:100.0, y:-15.0, z:0.0}}, + {joint:"LeftLeg", rotation: {x:-130.0, y:-15.0, z:0.0}}, + {joint:"LeftFoot", rotation: {x:30, y:15.0, z:0.0}} + ]; + + var startPoseAndTransition = []; + + function storeStartPoseAndTransition() { + for (var i = 0; i < pose.length; i++){ + var startRotation = Quat.safeEulerAngles(MyAvatar.getJointRotation(pose[i].joint)); + var transitionVector = Vec3.subtract( pose[i].rotation, startRotation ); + startPoseAndTransition.push({joint: pose[i].joint, start: startRotation, transition: transitionVector}); + } + } + + function updateJoints(factor){ + for (var i = 0; i < startPoseAndTransition.length; i++){ + var scaledTransition = Vec3.multiply(startPoseAndTransition[i].transition, factor); + var rotation = Vec3.sum(startPoseAndTransition[i].start, scaledTransition); + MyAvatar.setJointData(startPoseAndTransition[i].joint, Quat.fromVec3Degrees( rotation )); + } + } + + var sittingDownAnimation = function(deltaTime) { + + passedTime += deltaTime; + var factor = passedTime/animationLenght; + + if ( passedTime <= animationLenght ) { + updateJoints(factor); + + var pos = { x: startPosition.x - 0.3 * factor, y: startPosition.y - 0.5 * factor, z: startPosition.z}; + MyAvatar.position = pos; + } else { + Script.update.disconnect(sittingDownAnimation); + if (seat.model) { + MyAvatar.setModelReferential(seat.model.id); + } + } + } + + var standingUpAnimation = function(deltaTime) { + + passedTime += deltaTime; + var factor = 1 - passedTime/animationLenght; + + if ( passedTime <= animationLenght ) { + + updateJoints(factor); + + var pos = { x: startPosition.x + 0.3 * (passedTime/animationLenght), y: startPosition.y + 0.5 * (passedTime/animationLenght), z: startPosition.z}; + MyAvatar.position = pos; + } else { + Script.update.disconnect(standingUpAnimation); + + } + } + + var externalThis = this; + + var goToSeatAnimation = function(deltaTime) { + passedTime += deltaTime; + var factor = passedTime/animationLenght; + + if (passedTime <= animationLenght) { + var targetPosition = Vec3.sum(seat.position, { x: 0.3, y: 0.5, z: 0 }); + MyAvatar.position = Vec3.sum(Vec3.multiply(startPosition, 1 - factor), Vec3.multiply(targetPosition, factor)); + } else if (passedTime <= 2 * animationLenght) { + //Quat.print("MyAvatar: ", MyAvatar.orientation); + //Quat.print("Seat: ", seat.rotation); + MyAvatar.orientation = Quat.mix(startRotation, seat.rotation, factor - 1); + } else { + Script.update.disconnect(goToSeatAnimation); + externalThis.sitDown(); + externalThis.showIndicators(false); + } + } + + var globalMouseClick = function(event) { + var clickedOverlay = Overlays.getOverlayAtPoint({x: event.x, y: event.y}); + if (clickedOverlay == externalThis.standUpButton) { + seat.model = null; + externalThis.standUp(); + Controller.mousePressEvent.disconnect(globalMouseClick); + } + }; + + this.sitDown = function() { + sitting = true; + Settings.setValue(sittingSettingsHandle, sitting); + print("sitDown sitting status: " + Settings.getValue(sittingSettingsHandle, false)); + passedTime = 0.0; + startPosition = MyAvatar.position; + storeStartPoseAndTransition(); + try { + Script.update.disconnect(standingUpAnimation); + } catch(e){ + // no need to handle. if it wasn't connected no harm done + } + Script.update.connect(sittingDownAnimation); + Overlays.editOverlay(this.standUpButton, { visible: true }); + Controller.mousePressEvent.connect(globalMouseClick); + } + + this.standUp = function() { + sitting = false; + Settings.setValue(sittingSettingsHandle, sitting); + print("standUp sitting status: " + Settings.getValue(sittingSettingsHandle, false)); + passedTime = 0.0; + startPosition = MyAvatar.position; + MyAvatar.clearReferential(); + try{ + Script.update.disconnect(sittingDownAnimation); + } catch (e){} + Script.update.connect(standingUpAnimation); + Overlays.editOverlay(this.standUpButton, { visible: false }); + Controller.mousePressEvent.disconnect(globalMouseClick); + } + + function SeatIndicator(modelProperties, seatIndex) { + var halfDiagonal = Vec3.length(modelProperties.dimensions) / 2.0; + + this.position = Vec3.sum(modelProperties.position, + Vec3.multiply(Vec3.multiplyQbyV(modelProperties.rotation, modelProperties.sittingPoints[seatIndex].position), + halfDiagonal)); // hack + + this.orientation = Quat.multiply(modelProperties.rotation, + modelProperties.sittingPoints[seatIndex].rotation); + this.scale = MyAvatar.scale / 3; + + this.sphere = Overlays.addOverlay("billboard", { + subImage: { x: 0, y: buttonHeight, width: buttonWidth, height: buttonHeight}, + url: buttonImageUrl, + position: this.position, + scale: this.scale, + size: this.scale, + solid: true, + color: { red: 255, green: 255, blue: 255 }, + alpha: 0.8, + visible: true, + isFacingAvatar: true + }); + + this.show = function(doShow) { + Overlays.editOverlay(this.sphere, { visible: doShow }); + } + + this.update = function() { + Overlays.editOverlay(this.sphere, { + position: this.position, + size: this.scale + }); + } + + this.cleanup = function() { + Overlays.deleteOverlay(this.sphere); + } + } + + function update(deltaTime){ + var newWindowDimensions = Controller.getViewportDimensions(); + if( newWindowDimensions.x != windowDimensions.x || newWindowDimensions.y != windowDimensions.y ){ + windowDimensions = newWindowDimensions; + var newX = windowDimensions.x - buttonPadding - buttonWidth; + var newY = (windowDimensions.y - buttonHeight) / 2 ; + Overlays.editOverlay( this.standUpButton, {x: newX, y: newY} ); + } + + // For a weird reason avatar joint don't update till the 10th frame + // Set the update frame to 20 to be safe + var UPDATE_FRAME = 20; + if (frame <= UPDATE_FRAME) { + if (frame == UPDATE_FRAME) { + if (sitting == true) { + print("Was seated: " + sitting); + storeStartPoseAndTransition(); + updateJoints(1.0); + } + } + frame++; + } + } + + this.addIndicators = function() { + if (!this.indicatorsAdded) { + if (this.properties.sittingPoints.length > 0) { + for (var i = 0; i < this.properties.sittingPoints.length; ++i) { + this.indicator[i] = new SeatIndicator(this.properties, i); + } + this.indicatorsAdded = true; + } + } + } + + this.removeIndicators = function() { + for (var i = 0; i < this.properties.sittingPoints.length; ++i) { + this.indicator[i].cleanup(); + } + } + + this.showIndicators = function(doShow) { + this.addIndicators(); + if (this.indicatorsAdded) { + for (var i = 0; i < this.properties.sittingPoints.length; ++i) { + this.indicator[i].show(doShow); + } + } + hiddingSeats = !doShow; + } + + function raySphereIntersection(origin, direction, center, radius) { + var A = origin; + var B = Vec3.normalize(direction); + var P = center; + + var x = Vec3.dot(Vec3.subtract(P, A), B); + var X = Vec3.sum(A, Vec3.multiply(B, x)); + var d = Vec3.length(Vec3.subtract(P, X)); + + return (x > 0 && d <= radius); + } + + this.cleanup = function() { + this.standUp(); + MyAvatar.clearReferential(); + for (var i = 0; i < pose.length; i++){ + MyAvatar.clearJointData(pose[i].joint); + } + Overlays.deleteOverlay(this.standUpButton); + for (var i = 0; i < this.indicator.length; ++i) { + this.indicator[i].cleanup(); + } + }; + + + this.createStandupButton = function() { + this.standUpButton = Overlays.addOverlay("image", { + x: buttonPositionX, y: buttonPositionY, width: buttonWidth, height: buttonHeight, + subImage: { x: buttonWidth, y: buttonHeight, width: buttonWidth, height: buttonHeight}, + imageURL: buttonImageUrl, + visible: false, + alpha: 1.0 + }); + }; + + this.handleClickEvent = function(event) { + var clickedOverlay = Overlays.getOverlayAtPoint({x: event.x, y: event.y}); + + if (clickedOverlay == this.standUpButton) { + seat.model = null; + this.standUp(); + } else { + this.addIndicators(); + if (this.indicatorsAdded) { + var pickRay = Camera.computePickRay(event.x, event.y); + + var clickedOnSeat = false; + + for (var i = 0; i < this.properties.sittingPoints.length; ++i) { + if (raySphereIntersection(pickRay.origin, + pickRay.direction, + this.indicator[i].position, + this.indicator[i].scale / 2)) { + clickedOnSeat = true; + seat.model = this.entityID; // ?? + seat.position = this.indicator[i].position; + seat.rotation = this.indicator[i].orientation; + } + } + + if (clickedOnSeat) { + passedTime = 0.0; + startPosition = MyAvatar.position; + startRotation = MyAvatar.orientation; + try{ Script.update.disconnect(standingUpAnimation); } catch(e){} + try{ Script.update.disconnect(sittingDownAnimation); } catch(e){} + Script.update.connect(goToSeatAnimation); + } + } + } + }; + + + // All callbacks start by updating the properties + this.updateProperties = function(entityID) { + if (this.entityID === null || !this.entityID.isKnownID) { + this.entityID = Entities.identifyEntity(entityID); + } + this.properties = Entities.getEntityProperties(this.entityID); + }; +}; + +Sittable.prototype = { + + unload : function(entityID) { + print("Sittable.unload()"); + this.cleanup(); + //Script.update.disconnect(update); + }, + + preload : function(entityID) { + print("Sittable.preload()"); + this.updateProperties(entityID); // All callbacks start by updating the properties + this.createStandupButton(); + //Script.update.connect(update); + }, + + + hoverOverEntity : function(entityID, mouseEvent) { + print("Sittable.hoverOverEntity()"); + this.updateProperties(entityID); // All callbacks start by updating the properties + this.showIndicators(true); + }, + + hoverLeaveEntity : function(entityID, mouseEvent) { + print("Sittable.hoverLeaveEntity()"); + this.updateProperties(entityID); // All callbacks start by updating the properties + this.showIndicators(false); + }, + + clickDownOnEntity : function(entityID, mouseEvent) { + print("Sittable.clickDownOnEntity()"); + this.updateProperties(entityID); // All callbacks start by updating the properties + this.handleClickEvent(mouseEvent); + }, + + clickReleaseOnEntity : function(entityID, mouseEvent) { + print("Sittable.clickReleaseOnEntity()"); + this.updateProperties(entityID); // All callbacks start by updating the properties + } +}; \ No newline at end of file From a95b6dbabd904b220b57cca5ec24b775929fa07d Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Sun, 23 Nov 2014 20:36:33 -0800 Subject: [PATCH 032/258] hacking on global functions --- examples/entityScripts/sittableClass.js | 62 ++++++++++++++----------- 1 file changed, 36 insertions(+), 26 deletions(-) diff --git a/examples/entityScripts/sittableClass.js b/examples/entityScripts/sittableClass.js index c16e026f96..591b7515cb 100644 --- a/examples/entityScripts/sittableClass.js +++ b/examples/entityScripts/sittableClass.js @@ -11,6 +11,40 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +var activeSittable = null; +function SittableUpdate(deltaTime){ + + // This keeps the standup button in a reasonable place. + var newWindowDimensions = Controller.getViewportDimensions(); + if( newWindowDimensions.x != windowDimensions.x || newWindowDimensions.y != windowDimensions.y ){ + windowDimensions = newWindowDimensions; + var newX = windowDimensions.x - buttonPadding - buttonWidth; + var newY = (windowDimensions.y - buttonHeight) / 2 ; + Overlays.editOverlay( activeSittable.standUpButton, {x: newX, y: newY} ); + } + + + // this appears to be some logic related to storing the original position + /* + + // For a weird reason avatar joint don't update till the 10th frame + // Set the update frame to 20 to be safe + var UPDATE_FRAME = 20; + if (frame <= UPDATE_FRAME) { + if (frame == UPDATE_FRAME) { + if (sitting == true) { + print("Was seated: " + sitting); + activeSittable.storeStartPoseAndTransition(); + activeSittable.updateJoints(1.0); + } + } + frame++; + } + */ +} + + + Sittable = function() { this.entityID = null; @@ -207,30 +241,6 @@ Sittable = function() { } } - function update(deltaTime){ - var newWindowDimensions = Controller.getViewportDimensions(); - if( newWindowDimensions.x != windowDimensions.x || newWindowDimensions.y != windowDimensions.y ){ - windowDimensions = newWindowDimensions; - var newX = windowDimensions.x - buttonPadding - buttonWidth; - var newY = (windowDimensions.y - buttonHeight) / 2 ; - Overlays.editOverlay( this.standUpButton, {x: newX, y: newY} ); - } - - // For a weird reason avatar joint don't update till the 10th frame - // Set the update frame to 20 to be safe - var UPDATE_FRAME = 20; - if (frame <= UPDATE_FRAME) { - if (frame == UPDATE_FRAME) { - if (sitting == true) { - print("Was seated: " + sitting); - storeStartPoseAndTransition(); - updateJoints(1.0); - } - } - frame++; - } - } - this.addIndicators = function() { if (!this.indicatorsAdded) { if (this.properties.sittingPoints.length > 0) { @@ -345,14 +355,14 @@ Sittable.prototype = { unload : function(entityID) { print("Sittable.unload()"); this.cleanup(); - //Script.update.disconnect(update); + //Script.update.disconnect(SittableUpdate); }, preload : function(entityID) { print("Sittable.preload()"); this.updateProperties(entityID); // All callbacks start by updating the properties this.createStandupButton(); - //Script.update.connect(update); + //Script.update.connect(SittableUpdate); }, From 345735fa8c33df7c437638426eb1e578b7504b14 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Sun, 23 Nov 2014 20:50:39 -0800 Subject: [PATCH 033/258] tweaks --- examples/entityScripts/sittableClass.js | 100 ++++++++++++------------ 1 file changed, 51 insertions(+), 49 deletions(-) diff --git a/examples/entityScripts/sittableClass.js b/examples/entityScripts/sittableClass.js index 591b7515cb..1a7b1df25a 100644 --- a/examples/entityScripts/sittableClass.js +++ b/examples/entityScripts/sittableClass.js @@ -43,7 +43,49 @@ function SittableUpdate(deltaTime){ */ } +SeatIndicator = function(modelProperties, seatIndex) { + var buttonImageUrl = "https://worklist-prod.s3.amazonaws.com/attachment/0aca88e1-9bd8-5c1d.svg"; + var buttonWidth = 37; + var buttonHeight = 46; + var halfDiagonal = Vec3.length(modelProperties.dimensions) / 2.0; + + this.position = Vec3.sum(modelProperties.position, + Vec3.multiply(Vec3.multiplyQbyV(modelProperties.rotation, modelProperties.sittingPoints[seatIndex].position), + halfDiagonal)); // hack + + this.orientation = Quat.multiply(modelProperties.rotation, + modelProperties.sittingPoints[seatIndex].rotation); + this.scale = MyAvatar.scale / 3; + + this.sphere = Overlays.addOverlay("billboard", { + subImage: { x: 0, y: buttonHeight, width: buttonWidth, height: buttonHeight}, + url: buttonImageUrl, + position: this.position, + scale: this.scale, + size: this.scale, + solid: true, + color: { red: 255, green: 255, blue: 255 }, + alpha: 0.8, + visible: true, + isFacingAvatar: true + }); + + this.show = function(doShow) { + Overlays.editOverlay(this.sphere, { visible: doShow }); + } + + this.update = function() { + Overlays.editOverlay(this.sphere, { + position: this.position, + size: this.scale + }); + } + + this.cleanup = function() { + Overlays.deleteOverlay(this.sphere); + } +}; Sittable = function() { @@ -65,7 +107,7 @@ Sittable = function() { var passedTime = 0.0; var startPosition = null; var startRotation = null; - var animationLenght = 2.0; + var animationLength = 2.0; var avatarOldPosition = { x: 0, y: 0, z: 0 }; @@ -108,9 +150,9 @@ Sittable = function() { var sittingDownAnimation = function(deltaTime) { passedTime += deltaTime; - var factor = passedTime/animationLenght; + var factor = passedTime/animationLength; - if ( passedTime <= animationLenght ) { + if ( passedTime <= animationLength ) { updateJoints(factor); var pos = { x: startPosition.x - 0.3 * factor, y: startPosition.y - 0.5 * factor, z: startPosition.z}; @@ -126,13 +168,13 @@ Sittable = function() { var standingUpAnimation = function(deltaTime) { passedTime += deltaTime; - var factor = 1 - passedTime/animationLenght; + var factor = 1 - passedTime/animationLength; - if ( passedTime <= animationLenght ) { + if ( passedTime <= animationLength ) { updateJoints(factor); - var pos = { x: startPosition.x + 0.3 * (passedTime/animationLenght), y: startPosition.y + 0.5 * (passedTime/animationLenght), z: startPosition.z}; + var pos = { x: startPosition.x + 0.3 * (passedTime/animationLength), y: startPosition.y + 0.5 * (passedTime/animationLength), z: startPosition.z}; MyAvatar.position = pos; } else { Script.update.disconnect(standingUpAnimation); @@ -144,12 +186,12 @@ Sittable = function() { var goToSeatAnimation = function(deltaTime) { passedTime += deltaTime; - var factor = passedTime/animationLenght; + var factor = passedTime/animationLength; - if (passedTime <= animationLenght) { + if (passedTime <= animationLength) { var targetPosition = Vec3.sum(seat.position, { x: 0.3, y: 0.5, z: 0 }); MyAvatar.position = Vec3.sum(Vec3.multiply(startPosition, 1 - factor), Vec3.multiply(targetPosition, factor)); - } else if (passedTime <= 2 * animationLenght) { + } else if (passedTime <= 2 * animationLength) { //Quat.print("MyAvatar: ", MyAvatar.orientation); //Quat.print("Seat: ", seat.rotation); MyAvatar.orientation = Quat.mix(startRotation, seat.rotation, factor - 1); @@ -201,46 +243,6 @@ Sittable = function() { Controller.mousePressEvent.disconnect(globalMouseClick); } - function SeatIndicator(modelProperties, seatIndex) { - var halfDiagonal = Vec3.length(modelProperties.dimensions) / 2.0; - - this.position = Vec3.sum(modelProperties.position, - Vec3.multiply(Vec3.multiplyQbyV(modelProperties.rotation, modelProperties.sittingPoints[seatIndex].position), - halfDiagonal)); // hack - - this.orientation = Quat.multiply(modelProperties.rotation, - modelProperties.sittingPoints[seatIndex].rotation); - this.scale = MyAvatar.scale / 3; - - this.sphere = Overlays.addOverlay("billboard", { - subImage: { x: 0, y: buttonHeight, width: buttonWidth, height: buttonHeight}, - url: buttonImageUrl, - position: this.position, - scale: this.scale, - size: this.scale, - solid: true, - color: { red: 255, green: 255, blue: 255 }, - alpha: 0.8, - visible: true, - isFacingAvatar: true - }); - - this.show = function(doShow) { - Overlays.editOverlay(this.sphere, { visible: doShow }); - } - - this.update = function() { - Overlays.editOverlay(this.sphere, { - position: this.position, - size: this.scale - }); - } - - this.cleanup = function() { - Overlays.deleteOverlay(this.sphere); - } - } - this.addIndicators = function() { if (!this.indicatorsAdded) { if (this.properties.sittingPoints.length > 0) { From 136c3a2cce423a0dd7b90b5255da531a084626b2 Mon Sep 17 00:00:00 2001 From: David Rowe Date: Tue, 9 Dec 2014 18:32:53 -0800 Subject: [PATCH 034/258] Replace 2D and 3D text overlay textWidth() method with textSize() --- interface/src/ui/overlays/Overlays.cpp | 8 ++++---- interface/src/ui/overlays/Overlays.h | 4 ++-- interface/src/ui/overlays/Text3DOverlay.cpp | 20 ++++++++++++++++---- interface/src/ui/overlays/Text3DOverlay.h | 2 +- interface/src/ui/overlays/TextOverlay.cpp | 16 ++++++++++++++-- interface/src/ui/overlays/TextOverlay.h | 2 +- libraries/shared/src/RegisteredMetaTypes.cpp | 12 ++++++++++++ libraries/shared/src/RegisteredMetaTypes.h | 4 ++++ 8 files changed, 54 insertions(+), 14 deletions(-) diff --git a/interface/src/ui/overlays/Overlays.cpp b/interface/src/ui/overlays/Overlays.cpp index 25e667e56c..ace4ecf353 100644 --- a/interface/src/ui/overlays/Overlays.cpp +++ b/interface/src/ui/overlays/Overlays.cpp @@ -432,19 +432,19 @@ bool Overlays::isLoaded(unsigned int id) { return thisOverlay->isLoaded(); } -float Overlays::textWidth(unsigned int id, const QString& text) const { +QSizeF Overlays::textSize(unsigned int id, const QString& text) const { Overlay* thisOverlay = _overlays2D[id]; if (thisOverlay) { if (typeid(*thisOverlay) == typeid(TextOverlay)) { - return static_cast(thisOverlay)->textWidth(text); + return static_cast(thisOverlay)->textSize(text); } } else { thisOverlay = _overlays3D[id]; if (thisOverlay) { if (typeid(*thisOverlay) == typeid(Text3DOverlay)) { - return static_cast(thisOverlay)->textWidth(text); + return static_cast(thisOverlay)->textSize(text); } } } - return 0.0f; + return QSizeF(0.0f, 0.0f); } diff --git a/interface/src/ui/overlays/Overlays.h b/interface/src/ui/overlays/Overlays.h index 7acc2c7878..fb2c936a64 100644 --- a/interface/src/ui/overlays/Overlays.h +++ b/interface/src/ui/overlays/Overlays.h @@ -85,9 +85,9 @@ public slots: /// returns whether the overlay's assets are loaded or not bool isLoaded(unsigned int id); - /// returns the width of the given text in the specified overlay if it is a text overlay: in pixels if it is a 2D text + /// returns the size of the given text in the specified overlay if it is a text overlay: in pixels if it is a 2D text /// overlay; in meters if it is a 3D text overlay - float textWidth(unsigned int id, const QString& text) const; + QSizeF textSize(unsigned int id, const QString& text) const; private: QMap _overlays2D; diff --git a/interface/src/ui/overlays/Text3DOverlay.cpp b/interface/src/ui/overlays/Text3DOverlay.cpp index 2e80fae8a0..7db73dda8c 100644 --- a/interface/src/ui/overlays/Text3DOverlay.cpp +++ b/interface/src/ui/overlays/Text3DOverlay.cpp @@ -236,11 +236,23 @@ Text3DOverlay* Text3DOverlay::createClone() const { return new Text3DOverlay(this);; } -float Text3DOverlay::textWidth(const QString& text) const { +QSizeF Text3DOverlay::textSize(const QString& text) const { + QFont font(SANS_FONT_FAMILY, FIXED_FONT_POINT_SIZE); // Same font properties as render() QFontMetrics fontMetrics(font); - float scaleFactor = _lineHeight * LINE_SCALE_RATIO / (float)FIXED_FONT_POINT_SIZE; - return scaleFactor * (float)fontMetrics.width(qPrintable(text)); + const float TEXT_SCALE_ADJUST = 1.02f; // Experimentally detemined for the specified font + const int TEXT_HEIGHT_ADJUST = -6; + float scaleFactor = _lineHeight * TEXT_SCALE_ADJUST * LINE_SCALE_RATIO / (float)FIXED_FONT_POINT_SIZE; + + QStringList lines = text.split(QRegExp("\r\n|\r|\n")); + + float width = 0.0f; + for (int i = 0; i < lines.count(); i += 1) { + width = std::max(width, scaleFactor * (float)fontMetrics.width(qPrintable(lines[i]))); + } + + float height = lines.count() * scaleFactor * (float)(fontMetrics.height() + TEXT_HEIGHT_ADJUST); + + return QSizeF(width, height); } - diff --git a/interface/src/ui/overlays/Text3DOverlay.h b/interface/src/ui/overlays/Text3DOverlay.h index d74131391a..aefda852db 100644 --- a/interface/src/ui/overlays/Text3DOverlay.h +++ b/interface/src/ui/overlays/Text3DOverlay.h @@ -51,7 +51,7 @@ public: virtual void setProperties(const QScriptValue& properties); virtual QScriptValue getProperty(const QString& property); - float textWidth(const QString& text) const; // Meters + QSizeF textSize(const QString& test) const; // Meters virtual Text3DOverlay* createClone() const; diff --git a/interface/src/ui/overlays/TextOverlay.cpp b/interface/src/ui/overlays/TextOverlay.cpp index 272c9bc916..b603e1f3bf 100644 --- a/interface/src/ui/overlays/TextOverlay.cpp +++ b/interface/src/ui/overlays/TextOverlay.cpp @@ -169,8 +169,20 @@ QScriptValue TextOverlay::getProperty(const QString& property) { return Overlay2D::getProperty(property); } -float TextOverlay::textWidth(const QString& text) const { +QSizeF TextOverlay::textSize(const QString& text) const { + QFont font(SANS_FONT_FAMILY, _fontSize, DEFAULT_FONT_WEIGHT); // Same font properties as render() QFontMetrics fontMetrics(font); - return fontMetrics.width(qPrintable(text)); + const int TEXT_HEIGHT_ADJUST = -2; // Experimentally determined for the specified font + + QStringList lines = text.split(QRegExp("\r\n|\r|\n")); + + int width = 0; + for (int i = 0; i < lines.count(); i += 1) { + width = std::max(width, fontMetrics.width(qPrintable(lines[i]))); + } + + int height = lines.count() * (fontMetrics.height() + TEXT_HEIGHT_ADJUST); + + return QSizeF(width, height); } diff --git a/interface/src/ui/overlays/TextOverlay.h b/interface/src/ui/overlays/TextOverlay.h index 754faea2bc..793d705d3c 100644 --- a/interface/src/ui/overlays/TextOverlay.h +++ b/interface/src/ui/overlays/TextOverlay.h @@ -59,7 +59,7 @@ public: virtual TextOverlay* createClone() const; virtual QScriptValue getProperty(const QString& property); - float textWidth(const QString& text) const; // Pixels + QSizeF textSize(const QString& test) const; // Pixels private: QString _text; diff --git a/libraries/shared/src/RegisteredMetaTypes.cpp b/libraries/shared/src/RegisteredMetaTypes.cpp index cc8db8783f..4099384aea 100644 --- a/libraries/shared/src/RegisteredMetaTypes.cpp +++ b/libraries/shared/src/RegisteredMetaTypes.cpp @@ -39,6 +39,7 @@ void registerMetaTypes(QScriptEngine* engine) { qScriptRegisterMetaType(engine, pickRayToScriptValue, pickRayFromScriptValue); qScriptRegisterMetaType(engine, collisionToScriptValue, collisionFromScriptValue); qScriptRegisterMetaType(engine, quuidToScriptValue, quuidFromScriptValue); + qScriptRegisterMetaType(engine, qSizeFToScriptValue, qSizeFFromScriptValue); } QScriptValue vec4toScriptValue(QScriptEngine* engine, const glm::vec4& vec4) { @@ -206,3 +207,14 @@ void quuidFromScriptValue(const QScriptValue& object, QUuid& uuid) { uuid = fromString; } +QScriptValue qSizeFToScriptValue(QScriptEngine* engine, const QSizeF& qSizeF) { + QScriptValue obj = engine->newObject(); + obj.setProperty("width", qSizeF.width()); + obj.setProperty("height", qSizeF.height()); + return obj; +} + +void qSizeFFromScriptValue(const QScriptValue& object, QSizeF& qSizeF) { + qSizeF.setWidth(object.property("width").toVariant().toFloat()); + qSizeF.setHeight(object.property("height").toVariant().toFloat()); +} diff --git a/libraries/shared/src/RegisteredMetaTypes.h b/libraries/shared/src/RegisteredMetaTypes.h index b9278c9f2d..ca4898b65c 100644 --- a/libraries/shared/src/RegisteredMetaTypes.h +++ b/libraries/shared/src/RegisteredMetaTypes.h @@ -81,4 +81,8 @@ void collisionFromScriptValue(const QScriptValue &object, Collision& collision); QScriptValue quuidToScriptValue(QScriptEngine* engine, const QUuid& uuid); void quuidFromScriptValue(const QScriptValue& object, QUuid& uuid); +//Q_DECLARE_METATYPE(QSizeF) // Don't need to to this becase it's arleady a meta type +QScriptValue qSizeFToScriptValue(QScriptEngine* engine, const QSizeF& qSizeF); +void qSizeFFromScriptValue(const QScriptValue& object, QSizeF& qSizeF); + #endif // hifi_RegisteredMetaTypes_h From 3ea3a497c64396bef3444a00fa2bca447797e964 Mon Sep 17 00:00:00 2001 From: David Rowe Date: Tue, 9 Dec 2014 18:33:29 -0800 Subject: [PATCH 035/258] Update scripts to use new textSize() method --- examples/editModels.js | 4 ++-- examples/lobby.js | 2 +- examples/newEditEntities.js | 4 ++-- examples/virtualKeyboard.js | 10 +++++----- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/examples/editModels.js b/examples/editModels.js index c961d55bed..e0ade3b6a3 100644 --- a/examples/editModels.js +++ b/examples/editModels.js @@ -1191,8 +1191,8 @@ var toolBar = (function () { visible: false }); - menuItemWidth = Math.max(Overlays.textWidth(loadURLMenuItem, "Model URL"), - Overlays.textWidth(loadFileMenuItem, "Model File")) + 20; + menuItemWidth = Math.max(Overlays.textSize(loadURLMenuItem, "Model URL").width, + Overlays.textSize(loadFileMenuItem, "Model File").width) + 20; Overlays.editOverlay(loadURLMenuItem, { width: menuItemWidth }); Overlays.editOverlay(loadFileMenuItem, { width: menuItemWidth }); diff --git a/examples/lobby.js b/examples/lobby.js index dd011d08a4..a1f161d8a5 100644 --- a/examples/lobby.js +++ b/examples/lobby.js @@ -331,7 +331,7 @@ function handleLookAt(pickRay) { } else { currentTestLine = allWords[currentTestWord]; } - var lineLength = Overlays.textWidth(descriptionText, currentTestLine); + var lineLength = Overlays.textSize(descriptionText, currentTestLine).width; if (lineLength < textWidth || wordsOnLine == 0) { wordsFormated++; currentTestWord++; diff --git a/examples/newEditEntities.js b/examples/newEditEntities.js index 43e304a76d..e9f42bf74c 100644 --- a/examples/newEditEntities.js +++ b/examples/newEditEntities.js @@ -159,8 +159,8 @@ var toolBar = (function () { visible: false }); - menuItemWidth = Math.max(Overlays.textWidth(loadURLMenuItem, "Model URL"), - Overlays.textWidth(loadFileMenuItem, "Model File")) + 20; + menuItemWidth = Math.max(Overlays.textSize(loadURLMenuItem, "Model URL").width, + Overlays.textSize(loadFileMenuItem, "Model File").width) + 20; Overlays.editOverlay(loadURLMenuItem, { width: menuItemWidth }); Overlays.editOverlay(loadFileMenuItem, { width: menuItemWidth }); diff --git a/examples/virtualKeyboard.js b/examples/virtualKeyboard.js index c89dc6fb04..ce793c6ea0 100644 --- a/examples/virtualKeyboard.js +++ b/examples/virtualKeyboard.js @@ -80,7 +80,7 @@ function updateTextOverlay() { var textLines = textText.split("\n"); var maxLineWidth = 0; for (textLine in textLines) { - var lineWidth = Overlays.textWidth(text, textLines[textLine]); + var lineWidth = Overlays.textSize(text, textLines[textLine]).width; if (lineWidth > maxLineWidth) { maxLineWidth = lineWidth; } @@ -92,7 +92,7 @@ function updateTextOverlay() { Overlays.editOverlay(text, {text: textText, font: {size: textFontSize}, topMargin: topMargin}); var maxLineWidth = 0; for (textLine in textLines) { - var lineWidth = Overlays.textWidth(text, textLines[textLine]); + var lineWidth = Overlays.textSize(text, textLines[textLine]).width; if (lineWidth > maxLineWidth) { maxLineWidth = lineWidth; } @@ -122,18 +122,18 @@ keyboard.onKeyRelease = function(event) { var textLines = textText.split("\n"); var maxLineWidth = 0; for (textLine in textLines) { - var lineWidth = Overlays.textWidth(textSizeMeasureOverlay, textLines[textLine]); + var lineWidth = Overlays.textSize(textSizeMeasureOverlay, textLines[textLine]).width; if (lineWidth > maxLineWidth) { maxLineWidth = lineWidth; } } var usernameLine = "--" + GlobalServices.myUsername; - var usernameWidth = Overlays.textWidth(textSizeMeasureOverlay, usernameLine); + var usernameWidth = Overlays.textSize(textSizeMeasureOverlay, usernameLine).width; if (maxLineWidth < usernameWidth) { maxLineWidth = usernameWidth; } else { var spaceableWidth = maxLineWidth - usernameWidth; - var spaceWidth = Overlays.textWidth(textSizeMeasureOverlay, " "); + var spaceWidth = Overlays.textSize(textSizeMeasureOverlay, " ").width; var numberOfSpaces = Math.floor(spaceableWidth / spaceWidth); for (var i = 0; i < numberOfSpaces; i++) { usernameLine = " " + usernameLine; From 8cf50b71eaa086e50c28a9606ddb2914c67b6694 Mon Sep 17 00:00:00 2001 From: David Rowe Date: Tue, 9 Dec 2014 19:18:37 -0800 Subject: [PATCH 036/258] Update some comments to reflect changes --- interface/src/entities/RenderableTextEntityItem.cpp | 2 +- interface/src/ui/overlays/Text3DOverlay.cpp | 2 +- interface/src/ui/overlays/TextOverlay.cpp | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/interface/src/entities/RenderableTextEntityItem.cpp b/interface/src/entities/RenderableTextEntityItem.cpp index f790f6fa35..4059ee5751 100644 --- a/interface/src/entities/RenderableTextEntityItem.cpp +++ b/interface/src/entities/RenderableTextEntityItem.cpp @@ -63,7 +63,7 @@ void RenderableTextEntityItem::render(RenderArgs* args) { const int FIXED_FONT_SCALING_RATIO = FIXED_FONT_POINT_SIZE * 40.0f; // this is a ratio determined through experimentation - // Same font properties as textWidth() + // Same font properties as textSize() TextRenderer* textRenderer = TextRenderer::getInstance(SANS_FONT_FAMILY, FIXED_FONT_POINT_SIZE); float maxHeight = (float)textRenderer->calculateHeight("Xy") * LINE_SCALE_RATIO; diff --git a/interface/src/ui/overlays/Text3DOverlay.cpp b/interface/src/ui/overlays/Text3DOverlay.cpp index 7db73dda8c..41e36cb396 100644 --- a/interface/src/ui/overlays/Text3DOverlay.cpp +++ b/interface/src/ui/overlays/Text3DOverlay.cpp @@ -108,7 +108,7 @@ void Text3DOverlay::render(RenderArgs* args) { const int FIXED_FONT_SCALING_RATIO = FIXED_FONT_POINT_SIZE * 40.0f; // this is a ratio determined through experimentation - // Same font properties as textWidth() + // Same font properties as textSize() TextRenderer* textRenderer = TextRenderer::getInstance(SANS_FONT_FAMILY, FIXED_FONT_POINT_SIZE); float maxHeight = (float)textRenderer->calculateHeight("Xy") * LINE_SCALE_RATIO; diff --git a/interface/src/ui/overlays/TextOverlay.cpp b/interface/src/ui/overlays/TextOverlay.cpp index b603e1f3bf..ae8a7cbcfe 100644 --- a/interface/src/ui/overlays/TextOverlay.cpp +++ b/interface/src/ui/overlays/TextOverlay.cpp @@ -77,7 +77,7 @@ void TextOverlay::render(RenderArgs* args) { glVertex2f(_bounds.left(), _bounds.bottom()); glEnd(); - // Same font properties as textWidth() + // Same font properties as textSize() TextRenderer* textRenderer = TextRenderer::getInstance(SANS_FONT_FAMILY, _fontSize, DEFAULT_FONT_WEIGHT); const int leftAdjust = -1; // required to make text render relative to left edge of bounds From c9bc95580d9d6be8f76a37c349802f5997b59d21 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Thu, 11 Dec 2014 12:30:17 -0800 Subject: [PATCH 037/258] add support for generic windowWatcher that keeps dialogs from being moved to HMD display --- interface/src/Application.cpp | 2 + interface/src/Application.h | 1 + interface/src/Menu.cpp | 13 +++ interface/src/ui/HMDToolsDialog.cpp | 155 +++++++++++++++++----------- interface/src/ui/HMDToolsDialog.h | 27 ++++- 5 files changed, 135 insertions(+), 63 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index cb3acc88f1..19055ab61b 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -142,6 +142,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) : QApplication(argc, argv), _window(new MainWindow(desktop())), _glWidget(new GLCanvas()), + _toolWindow(NULL), _nodeThread(new QThread(this)), _datagramProcessor(), _undoStack(), @@ -371,6 +372,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) : _glWidget->setMouseTracking(true); _toolWindow = new ToolWindow(); + qDebug() << "_toolWindow:" << _toolWindow; _toolWindow->setWindowFlags(_toolWindow->windowFlags() | Qt::WindowStaysOnTopHint); _toolWindow->setWindowTitle("Tools"); diff --git a/interface/src/Application.h b/interface/src/Application.h index 217d547c89..57b0cd2c2c 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -329,6 +329,7 @@ public: bool isHMDMode() const; QRect getDesirableApplicationGeometry(); + RunningScriptsWidget* getRunningScriptsWidget() { return _runningScriptsWidget; } signals: diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index ae12b5ff26..5e35f08e95 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -1303,6 +1303,10 @@ void Menu::bandwidthDetails() { connect(_bandwidthDialog, SIGNAL(closed()), SLOT(bandwidthDetailsClosed())); _bandwidthDialog->show(); + + if (_hmdToolsDialog) { + _hmdToolsDialog->watchWindow(_bandwidthDialog->windowHandle()); + } } _bandwidthDialog->raise(); } @@ -1384,6 +1388,9 @@ void Menu::toggleConsole() { void Menu::toggleToolWindow() { QMainWindow* toolWindow = Application::getInstance()->getToolWindow(); toolWindow->setVisible(!toolWindow->isVisible()); + if (_hmdToolsDialog) { + _hmdToolsDialog->watchWindow(toolWindow->windowHandle()); + } } void Menu::audioMuteToggled() { @@ -1406,6 +1413,9 @@ void Menu::octreeStatsDetails() { Application::getInstance()->getOcteeSceneStats()); connect(_octreeStatsDialog, SIGNAL(closed()), SLOT(octreeStatsDetailsClosed())); _octreeStatsDialog->show(); + if (_hmdToolsDialog) { + _hmdToolsDialog->watchWindow(_octreeStatsDialog->windowHandle()); + } } _octreeStatsDialog->raise(); } @@ -1586,6 +1596,9 @@ void Menu::lodTools() { _lodToolsDialog = new LodToolsDialog(Application::getInstance()->getGLWidget()); connect(_lodToolsDialog, SIGNAL(closed()), SLOT(lodToolsClosed())); _lodToolsDialog->show(); + if (_hmdToolsDialog) { + _hmdToolsDialog->watchWindow(_lodToolsDialog->windowHandle()); + } } _lodToolsDialog->raise(); } diff --git a/interface/src/ui/HMDToolsDialog.cpp b/interface/src/ui/HMDToolsDialog.cpp index 580490f83b..ab84980d80 100644 --- a/interface/src/ui/HMDToolsDialog.cpp +++ b/interface/src/ui/HMDToolsDialog.cpp @@ -67,12 +67,22 @@ HMDToolsDialog::HMDToolsDialog(QWidget* parent) : // watch for our dialog window moving screens. If it does we want to enforce our rules about // what screens we're allowed on - QWindow* dialogWindow = windowHandle(); - connect(dialogWindow, &QWindow::screenChanged, this, &HMDToolsDialog::dialogWindowScreenChanged); - connect(dialogWindow, &QWindow::xChanged, this, &HMDToolsDialog::dialogWindowGeometryChanged); - connect(dialogWindow, &QWindow::yChanged, this, &HMDToolsDialog::dialogWindowGeometryChanged); - connect(dialogWindow, &QWindow::widthChanged, this, &HMDToolsDialog::dialogWindowGeometryChanged); - connect(dialogWindow, &QWindow::heightChanged, this, &HMDToolsDialog::dialogWindowGeometryChanged); + watchWindow(windowHandle()); + if (Application::getInstance()->getRunningScriptsWidget()) { + watchWindow(Application::getInstance()->getRunningScriptsWidget()->windowHandle()); + } + if (Application::getInstance()->getToolWindow()) { + watchWindow(Application::getInstance()->getToolWindow()->windowHandle()); + } + if (Menu::getInstance()->getBandwidthDialog()) { + watchWindow(Menu::getInstance()->getBandwidthDialog()->windowHandle()); + } + if (Menu::getInstance()->getOctreeStatsDialog()) { + watchWindow(Menu::getInstance()->getOctreeStatsDialog()->windowHandle()); + } + if (Menu::getInstance()->getLodToolsDialog()) { + watchWindow(Menu::getInstance()->getLodToolsDialog()->windowHandle()); + } // when the application is about to quit, leave HDM mode connect(Application::getInstance(), SIGNAL(aboutToQuit()), this, SLOT(aboutToQuit())); @@ -82,67 +92,16 @@ HMDToolsDialog::HMDToolsDialog(QWidget* parent) : } HMDToolsDialog::~HMDToolsDialog() { + foreach(HMDWindowWatcher* watcher, _windowWatchers) { + delete watcher; + } + _windowWatchers.clear(); } void HMDToolsDialog::applicationWindowScreenChanged(QScreen* screen) { _debugDetails->setText(getDebugDetails()); } -void HMDToolsDialog::dialogWindowGeometryChanged(int arg) { - QWindow* dialogWindow = windowHandle(); - _previousDialogRect = rect(); - _previousDialogRect = QRect(dialogWindow->mapToGlobal(_previousDialogRect.topLeft()), - dialogWindow->mapToGlobal(_previousDialogRect.bottomRight())); - _previousDialogScreen = dialogWindow->screen(); -} - -void HMDToolsDialog::dialogWindowScreenChanged(QScreen* screen) { - _debugDetails->setText(getDebugDetails()); - - // if we have more than one screen, and a known hmdScreen then try to - // keep our dialog off of the hmdScreen - if (QApplication::desktop()->screenCount() > 1) { - - // we want to use a local variable here because we are not necesarily in HMD mode - int hmdScreenNumber = OculusManager::getHMDScreen(); - if (_hmdScreenNumber >= 0) { - QScreen* hmdScreen = QGuiApplication::screens()[hmdScreenNumber]; - if (screen == hmdScreen) { - qDebug() << "HMD Tools: Whoa! What are you doing? You don't want to move me to the HMD Screen!"; - QWindow* dialogWindow = windowHandle(); - - // try to pick a better screen - QScreen* betterScreen = NULL; - - QWindow* appWindow = Application::getInstance()->getWindow()->windowHandle(); - QScreen* appScreen = appWindow->screen(); - - if (_previousDialogScreen && _previousDialogScreen != hmdScreen) { - // first, if the previous dialog screen is not the HMD screen, then move it there. - betterScreen = appScreen; - } else if (appScreen != hmdScreen) { - // second, if the application screen is not the HMD screen, then move it there. - betterScreen = appScreen; - } else if (_previousScreen && _previousScreen != hmdScreen) { - // third, if the application screen is the HMD screen, we want to move it to - // the previous screen - betterScreen = _previousScreen; - } else { - // last, if we can't use the previous screen the use the primary desktop screen - int desktopPrimaryScreenNumber = QApplication::desktop()->primaryScreen(); - QScreen* desktopPrimaryScreen = QGuiApplication::screens()[desktopPrimaryScreenNumber]; - betterScreen = desktopPrimaryScreen; - } - - if (betterScreen) { - dialogWindow->setScreen(betterScreen); - dialogWindow->setGeometry(_previousDialogRect); - } - } - } - } -} - QString HMDToolsDialog::getDebugDetails() const { QString results; @@ -304,5 +263,79 @@ void HMDToolsDialog::screenCountChanged(int newCount) { _debugDetails->setText(getDebugDetails()); } +void HMDToolsDialog::watchWindow(QWindow* window) { + qDebug() << "HMDToolsDialog::watchWindow() window:" << window; + if (window && !_windowWatchers.contains(window)) { + HMDWindowWatcher* watcher = new HMDWindowWatcher(window, this); + _windowWatchers[window] = watcher; + } +} + + +HMDWindowWatcher::HMDWindowWatcher(QWindow* window, HMDToolsDialog* hmdTools) : + _window(window), + _hmdTools(hmdTools), + _previousScreen(NULL) +{ + connect(window, &QWindow::screenChanged, this, &HMDWindowWatcher::windowScreenChanged); + connect(window, &QWindow::xChanged, this, &HMDWindowWatcher::windowGeometryChanged); + connect(window, &QWindow::yChanged, this, &HMDWindowWatcher::windowGeometryChanged); + connect(window, &QWindow::widthChanged, this, &HMDWindowWatcher::windowGeometryChanged); + connect(window, &QWindow::heightChanged, this, &HMDWindowWatcher::windowGeometryChanged); +} + +HMDWindowWatcher::~HMDWindowWatcher() { +} + + +void HMDWindowWatcher::windowGeometryChanged(int arg) { + _previousRect = _window->geometry(); + _previousScreen = _window->screen(); +} + +void HMDWindowWatcher::windowScreenChanged(QScreen* screen) { + // if we have more than one screen, and a known hmdScreen then try to + // keep our dialog off of the hmdScreen + if (QApplication::desktop()->screenCount() > 1) { + + // we want to use a local variable here because we are not necesarily in HMD mode + int hmdScreenNumber = OculusManager::getHMDScreen(); + if (hmdScreenNumber >= 0) { + QScreen* hmdScreen = QGuiApplication::screens()[hmdScreenNumber]; + if (screen == hmdScreen) { + qDebug() << "HMD Tools: Whoa! What are you doing? You don't want to move me to the HMD Screen!"; + + // try to pick a better screen + QScreen* betterScreen = NULL; + + QScreen* lastApplicationScreen = _hmdTools->getLastApplicationScreen(); + QWindow* appWindow = Application::getInstance()->getWindow()->windowHandle(); + QScreen* appScreen = appWindow->screen(); + + if (_previousScreen && _previousScreen != hmdScreen) { + // first, if the previous dialog screen is not the HMD screen, then move it there. + betterScreen = _previousScreen; + } else if (appScreen != hmdScreen) { + // second, if the application screen is not the HMD screen, then move it there. + betterScreen = appScreen; + } else if (lastApplicationScreen && lastApplicationScreen != hmdScreen) { + // third, if the application screen is the HMD screen, we want to move it to + // the previous screen + betterScreen = lastApplicationScreen; + } else { + // last, if we can't use the previous screen the use the primary desktop screen + int desktopPrimaryScreenNumber = QApplication::desktop()->primaryScreen(); + QScreen* desktopPrimaryScreen = QGuiApplication::screens()[desktopPrimaryScreenNumber]; + betterScreen = desktopPrimaryScreen; + } + + if (betterScreen) { + _window->setScreen(betterScreen); + _window->setGeometry(_previousRect); + } + } + } + } +} diff --git a/interface/src/ui/HMDToolsDialog.h b/interface/src/ui/HMDToolsDialog.h index d539b58d04..10dc1c5c80 100644 --- a/interface/src/ui/HMDToolsDialog.h +++ b/interface/src/ui/HMDToolsDialog.h @@ -14,6 +14,8 @@ #include +class HMDWindowWatcher; + class HMDToolsDialog : public QDialog { Q_OBJECT public: @@ -23,7 +25,9 @@ public: QString getDebugDetails() const; QScreen* getHMDScreen() const { return _hmdScreen; } + QScreen* getLastApplicationScreen() const { return _previousScreen; } bool hasHMDScreen() const { return _hmdScreenNumber >= -1; } + void watchWindow(QWindow* window); signals: void closed(); @@ -34,8 +38,6 @@ public slots: void activateWindowAfterEnterMode(); void moveWindowAfterLeaveMode(); void applicationWindowScreenChanged(QScreen* screen); - void dialogWindowScreenChanged(QScreen* screen); - void dialogWindowGeometryChanged(int arg); void aboutToQuit(); void screenCountChanged(int newCount); @@ -60,6 +62,27 @@ private: QRect _previousDialogRect; QScreen* _previousDialogScreen; bool _inHDMMode; + + QHash _windowWatchers; +}; + + +class HMDWindowWatcher : public QObject { + Q_OBJECT +public: + // Sets up the UI + HMDWindowWatcher(QWindow* window, HMDToolsDialog* hmdTools); + ~HMDWindowWatcher(); + +public slots: + void windowScreenChanged(QScreen* screen); + void windowGeometryChanged(int arg); + +private: + QWindow* _window; + HMDToolsDialog* _hmdTools; + QRect _previousRect; + QScreen* _previousScreen; }; #endif // hifi_HMDToolsDialog_h From 29672aec096f86932371b22b5c7b3fb9fb3fceea Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Thu, 11 Dec 2014 13:55:10 -0800 Subject: [PATCH 038/258] removing VoxelShader and PointShader which were both disabled --- interface/src/Application.cpp | 4 - interface/src/Application.h | 6 - interface/src/Menu.h | 2 - interface/src/renderer/PointShader.cpp | 80 ----- interface/src/renderer/PointShader.h | 48 --- interface/src/renderer/VoxelShader.cpp | 73 ----- interface/src/renderer/VoxelShader.h | 49 --- interface/src/voxels/VoxelSystem.cpp | 425 ++++++------------------- interface/src/voxels/VoxelSystem.h | 17 - 9 files changed, 99 insertions(+), 605 deletions(-) delete mode 100644 interface/src/renderer/PointShader.cpp delete mode 100644 interface/src/renderer/PointShader.h delete mode 100644 interface/src/renderer/VoxelShader.cpp delete mode 100644 interface/src/renderer/VoxelShader.h diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 32d4557c66..a57b157e64 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1915,8 +1915,6 @@ void Application::init() { _deferredLightingEffect.init(); _glowEffect.init(); _ambientOcclusionEffect.init(); - _voxelShader.init(); - _pointShader.init(); // TODO: move _myAvatar out of Application. Move relevant code to MyAvataar or AvatarManager _avatarManager.init(); @@ -1987,8 +1985,6 @@ void Application::init() { // Set up VoxelSystem after loading preferences so we can get the desired max voxel count _voxels.setMaxVoxels(Menu::getInstance()->getMaxVoxels()); - _voxels.setUseVoxelShader(false); - _voxels.setVoxelsAsPoints(false); _voxels.setDisableFastVoxelPipeline(false); _voxels.init(); diff --git a/interface/src/Application.h b/interface/src/Application.h index 5700b7fb87..96858a6c73 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -64,9 +64,7 @@ #include "renderer/DeferredLightingEffect.h" #include "renderer/GeometryCache.h" #include "renderer/GlowEffect.h" -#include "renderer/PointShader.h" #include "renderer/TextureCache.h" -#include "renderer/VoxelShader.h" #include "scripting/ControllerScriptingInterface.h" #include "ui/BandwidthDialog.h" #include "ui/BandwidthMeter.h" @@ -295,8 +293,6 @@ public: NodeBounds& getNodeBoundsDisplay() { return _nodeBoundsDisplay; } - VoxelShader& getVoxelShader() { return _voxelShader; } - PointShader& getPointShader() { return _pointShader; } FileLogger* getLogger() { return _logger; } glm::vec2 getViewportDimensions() const { return glm::vec2(_glWidget->getDeviceWidth(), _glWidget->getDeviceHeight()); } @@ -588,8 +584,6 @@ private: DeferredLightingEffect _deferredLightingEffect; GlowEffect _glowEffect; AmbientOcclusionEffect _ambientOcclusionEffect; - VoxelShader _voxelShader; - PointShader _pointShader; Audio _audio; diff --git a/interface/src/Menu.h b/interface/src/Menu.h index 138828d3e8..e2c687fff1 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -123,7 +123,6 @@ public: LodToolsDialog* getLodToolsDialog() const { return _lodToolsDialog; } HMDToolsDialog* getHMDToolsDialog() const { return _hmdToolsDialog; } int getMaxVoxels() const { return _maxVoxels; } - QAction* getUseVoxelShader() const { return _useVoxelShader; } bool getShadowsEnabled() const; @@ -304,7 +303,6 @@ private: float _avatarLODIncreaseFPS; float _avatarLODDistanceMultiplier; int _boundaryLevelAdjust; - QAction* _useVoxelShader; int _maxVoxelPacketsPerSecond; QString replaceLastOccurrence(QChar search, QChar replace, QString string); quint64 _lastAdjust; diff --git a/interface/src/renderer/PointShader.cpp b/interface/src/renderer/PointShader.cpp deleted file mode 100644 index 68df69f284..0000000000 --- a/interface/src/renderer/PointShader.cpp +++ /dev/null @@ -1,80 +0,0 @@ -// -// PointShader.cpp -// interface/src/renderer -// -// Created by Brad Hefta-Gaub on 10/30/13. -// Copyright 2013 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -// include this before QOpenGLFramebufferObject, which includes an earlier version of OpenGL -#include "InterfaceConfig.h" - -#include - -#include "Application.h" -#include "PointShader.h" -#include "ProgramObject.h" -#include "RenderUtil.h" - -PointShader::PointShader() - : _initialized(false) -{ - _program = NULL; -} - -PointShader::~PointShader() { - if (_initialized) { - delete _program; - } -} - -ProgramObject* PointShader::createPointShaderProgram(const QString& name) { - ProgramObject* program = new ProgramObject(); - program->addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + "shaders/" + name + ".vert" ); - program->link(); - return program; -} - -void PointShader::init() { - if (_initialized) { - qDebug("[ERROR] PointShader is already initialized."); - return; - } - _program = createPointShaderProgram("point_size"); - _initialized = true; -} - -void PointShader::begin() { - _program->bind(); -} - -void PointShader::end() { - _program->release(); -} - -int PointShader::attributeLocation(const char* name) const { - if (_program) { - return _program->attributeLocation(name); - } else { - return -1; - } -} - -int PointShader::uniformLocation(const char* name) const { - if (_program) { - return _program->uniformLocation(name); - } else { - return -1; - } -} - -void PointShader::setUniformValue(int uniformLocation, float value) { - _program->setUniformValue(uniformLocation, value); -} - -void PointShader::setUniformValue(int uniformLocation, const glm::vec3& value) { - _program->setUniformValue(uniformLocation, value.x, value.y, value.z); -} diff --git a/interface/src/renderer/PointShader.h b/interface/src/renderer/PointShader.h deleted file mode 100644 index 1db4f1b201..0000000000 --- a/interface/src/renderer/PointShader.h +++ /dev/null @@ -1,48 +0,0 @@ -// -// PointShader.h -// interface/src/renderer -// -// Created by Brad Hefta-Gaub on 10/30/13. -// Copyright 2013 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -#ifndef hifi_PointShader_h -#define hifi_PointShader_h - -#include - -class ProgramObject; - -/// A shader program that draws voxels as points with variable sizes -class PointShader : public QObject { - Q_OBJECT - -public: - PointShader(); - ~PointShader(); - - void init(); - - /// Starts using the voxel point shader program. - void begin(); - - /// Stops using the voxel point shader program. - void end(); - - /// Gets access to attributes from the shader program - int attributeLocation(const char* name) const; - int uniformLocation(const char* name) const; - void setUniformValue(int uniformLocation, float value); - void setUniformValue(int uniformLocation, const glm::vec3& value); - - static ProgramObject* createPointShaderProgram(const QString& name); - -private: - bool _initialized; - ProgramObject* _program; -}; - -#endif // hifi_PointShader_h diff --git a/interface/src/renderer/VoxelShader.cpp b/interface/src/renderer/VoxelShader.cpp deleted file mode 100644 index 0982304adf..0000000000 --- a/interface/src/renderer/VoxelShader.cpp +++ /dev/null @@ -1,73 +0,0 @@ -// -// VoxelShader.cpp -// interface/src/renderer -// -// Created by Brad Hefta-Gaub on 9/22/13. -// Copyright 2013 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -// include this before QOpenGLFramebufferObject, which includes an earlier version of OpenGL -#include "InterfaceConfig.h" - -#include - -#include "Application.h" -#include "VoxelShader.h" -#include "ProgramObject.h" -#include "RenderUtil.h" - -VoxelShader::VoxelShader() - : _initialized(false) -{ - _program = NULL; -} - -VoxelShader::~VoxelShader() { - if (_initialized) { - delete _program; - } -} - -ProgramObject* VoxelShader::createGeometryShaderProgram(const QString& name) { - ProgramObject* program = new ProgramObject(); - program->addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + "shaders/passthrough.vert" ); - program->addShaderFromSourceFile(QGLShader::Geometry, Application::resourcesPath() + "shaders/" + name + ".geom" ); - program->setGeometryInputType(GL_POINTS); - program->setGeometryOutputType(GL_TRIANGLE_STRIP); - const int VERTICES_PER_FACE = 4; - const int FACES_PER_VOXEL = 6; - const int VERTICES_PER_VOXEL = VERTICES_PER_FACE * FACES_PER_VOXEL; - program->setGeometryOutputVertexCount(VERTICES_PER_VOXEL); - program->link(); - return program; -} - -void VoxelShader::init() { - if (_initialized) { - qDebug("[ERROR] TestProgram is already initialized."); - return; - } - - _program = createGeometryShaderProgram("voxel"); - _initialized = true; -} - -void VoxelShader::begin() { - _program->bind(); -} - -void VoxelShader::end() { - _program->release(); -} - -int VoxelShader::attributeLocation(const char * name) const { - if (_program) { - return _program->attributeLocation(name); - } else { - return -1; - } -} - diff --git a/interface/src/renderer/VoxelShader.h b/interface/src/renderer/VoxelShader.h deleted file mode 100644 index cfcd27bba7..0000000000 --- a/interface/src/renderer/VoxelShader.h +++ /dev/null @@ -1,49 +0,0 @@ -// -// VoxelShader.h -// interface/src/renderer -// -// Created by Brad Hefta-Gaub on 9/23/13. -// Copyright 2013 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -#ifndef hifi_VoxelShader_h -#define hifi_VoxelShader_h - -#include - -class ProgramObject; - -/// A generic full screen glow effect. -class VoxelShader : public QObject { - Q_OBJECT - -public: - VoxelShader(); - ~VoxelShader(); - - void init(); - - /// Starts using the voxel geometry shader effect. - void begin(); - - /// Stops using the voxel geometry shader effect. - void end(); - - /// Gets access to attributes from the shader program - int attributeLocation(const char * name) const; - - static ProgramObject* createGeometryShaderProgram(const QString& name); - -public slots: - -private: - - bool _initialized; - - ProgramObject* _program; -}; - -#endif // hifi_VoxelShader_h diff --git a/interface/src/voxels/VoxelSystem.cpp b/interface/src/voxels/VoxelSystem.cpp index 8d16245962..8fbaf65f37 100644 --- a/interface/src/voxels/VoxelSystem.cpp +++ b/interface/src/voxels/VoxelSystem.cpp @@ -92,13 +92,6 @@ VoxelSystem::VoxelSystem(float treeScale, int maxVoxels, VoxelTree* tree) _viewFrustum = Application::getInstance()->getViewFrustum(); - _useVoxelShader = false; - _voxelsAsPoints = false; - _voxelShaderModeWhenVoxelsAsPointsEnabled = false; - - _writeVoxelShaderData = NULL; - _readVoxelShaderData = NULL; - _readVerticesArray = NULL; _writeVerticesArray = NULL; _readColorsArray = NULL; @@ -270,106 +263,30 @@ void VoxelSystem::setMaxVoxels(unsigned long maxVoxels) { } } -// This is called by the main application thread on both the initialization of the application and when -// the use voxel shader menu item is chosen -void VoxelSystem::setUseVoxelShader(bool useVoxelShader) { - if (_useVoxelShader == useVoxelShader) { - return; - } - - bool wasInitialized = _initialized; - if (wasInitialized) { - clearAllNodesBufferIndex(); - cleanupVoxelMemory(); - } - _useVoxelShader = useVoxelShader; - _usePrimitiveRenderer = false; - if (wasInitialized) { - initVoxelMemory(); - } - - if (wasInitialized) { - forceRedrawEntireTree(); - } -} - -void VoxelSystem::setVoxelsAsPoints(bool voxelsAsPoints) { - if (_voxelsAsPoints == voxelsAsPoints) { - return; - } - - bool wasInitialized = _initialized; - - // If we're "turning on" Voxels as points, we need to double check that we're in voxel shader mode. - // Voxels as points uses the VoxelShader memory model, so if we're not in voxel shader mode, - // then set it to voxel shader mode. - if (voxelsAsPoints) { - Menu::getInstance()->getUseVoxelShader()->setEnabled(false); - - // If enabling this... then do it before checking voxel shader status, that way, if voxel - // shader is already enabled, we just start drawing as points. - _voxelsAsPoints = true; - - if (!_useVoxelShader) { - setUseVoxelShader(true); - _voxelShaderModeWhenVoxelsAsPointsEnabled = false; - } else { - _voxelShaderModeWhenVoxelsAsPointsEnabled = true; - } - } else { - Menu::getInstance()->getUseVoxelShader()->setEnabled(true); - // if we're turning OFF voxels as point mode, then we check what the state of voxel shader was when we enabled - // voxels as points, if it was OFF, then we return it to that value. - if (_voxelShaderModeWhenVoxelsAsPointsEnabled == false) { - setUseVoxelShader(false); - } - // If disabling this... then do it AFTER checking previous voxel shader status, that way, if voxel - // shader is was not enabled, we switch back to normal mode before turning off points. - _voxelsAsPoints = false; - } - - // Set our voxels as points - if (wasInitialized) { - forceRedrawEntireTree(); - } -} - void VoxelSystem::cleanupVoxelMemory() { if (_initialized) { _readArraysLock.lockForWrite(); _initialized = false; // no longer initialized - if (_useVoxelShader) { - // these are used when in VoxelShader mode. - glDeleteBuffers(1, &_vboVoxelsID); - glDeleteBuffers(1, &_vboVoxelsIndicesID); + // Destroy glBuffers + glDeleteBuffers(1, &_vboVerticesID); + glDeleteBuffers(1, &_vboColorsID); - delete[] _writeVoxelShaderData; - delete[] _readVoxelShaderData; + glDeleteBuffers(1, &_vboIndicesTop); + glDeleteBuffers(1, &_vboIndicesBottom); + glDeleteBuffers(1, &_vboIndicesLeft); + glDeleteBuffers(1, &_vboIndicesRight); + glDeleteBuffers(1, &_vboIndicesFront); + glDeleteBuffers(1, &_vboIndicesBack); - _writeVoxelShaderData = _readVoxelShaderData = NULL; + delete[] _readVerticesArray; + delete[] _writeVerticesArray; + delete[] _readColorsArray; + delete[] _writeColorsArray; - } else { - // Destroy glBuffers - glDeleteBuffers(1, &_vboVerticesID); - glDeleteBuffers(1, &_vboColorsID); - - glDeleteBuffers(1, &_vboIndicesTop); - glDeleteBuffers(1, &_vboIndicesBottom); - glDeleteBuffers(1, &_vboIndicesLeft); - glDeleteBuffers(1, &_vboIndicesRight); - glDeleteBuffers(1, &_vboIndicesFront); - glDeleteBuffers(1, &_vboIndicesBack); - - delete[] _readVerticesArray; - delete[] _writeVerticesArray; - delete[] _readColorsArray; - delete[] _writeColorsArray; - - _readVerticesArray = NULL; - _writeVerticesArray = NULL; - _readColorsArray = NULL; - _writeColorsArray = NULL; - } + _readVerticesArray = NULL; + _writeVerticesArray = NULL; + _readColorsArray = NULL; + _writeColorsArray = NULL; delete _renderer; _renderer = 0; @@ -417,102 +334,55 @@ void VoxelSystem::initVoxelMemory() { _memoryUsageRAM = 0; _memoryUsageVBO = 0; // our VBO allocations as we know them - // if _voxelsAsPoints then we must have _useVoxelShader - if (_voxelsAsPoints && !_useVoxelShader) { - _useVoxelShader = true; - } + // Global Normals mode uses a technique of not including normals on any voxel vertices, and instead + // rendering the voxel faces in 6 passes that use a global call to glNormal3f() + setupFaceIndices(_vboIndicesTop, identityIndicesTop); + setupFaceIndices(_vboIndicesBottom, identityIndicesBottom); + setupFaceIndices(_vboIndicesLeft, identityIndicesLeft); + setupFaceIndices(_vboIndicesRight, identityIndicesRight); + setupFaceIndices(_vboIndicesFront, identityIndicesFront); + setupFaceIndices(_vboIndicesBack, identityIndicesBack); - if (_useVoxelShader) { - GLuint* indicesArray = new GLuint[_maxVoxels]; + // Depending on if we're using per vertex normals, we will need more or less vertex points per voxel + int vertexPointsPerVoxel = GLOBAL_NORMALS_VERTEX_POINTS_PER_VOXEL; + glGenBuffers(1, &_vboVerticesID); + glBindBuffer(GL_ARRAY_BUFFER, _vboVerticesID); + glBufferData(GL_ARRAY_BUFFER, vertexPointsPerVoxel * sizeof(GLfloat) * _maxVoxels, NULL, GL_DYNAMIC_DRAW); + _memoryUsageVBO += vertexPointsPerVoxel * sizeof(GLfloat) * _maxVoxels; - // populate the indicesArray - // this will not change given new voxels, so we can set it all up now - for (unsigned long n = 0; n < _maxVoxels; n++) { - indicesArray[n] = n; - } + // VBO for colorsArray + glGenBuffers(1, &_vboColorsID); + glBindBuffer(GL_ARRAY_BUFFER, _vboColorsID); + glBufferData(GL_ARRAY_BUFFER, vertexPointsPerVoxel * sizeof(GLubyte) * _maxVoxels, NULL, GL_DYNAMIC_DRAW); + _memoryUsageVBO += vertexPointsPerVoxel * sizeof(GLubyte) * _maxVoxels; - // bind the indices VBO to the actual indices array - glGenBuffers(1, &_vboVoxelsIndicesID); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _vboVoxelsIndicesID); - glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint) * _maxVoxels, indicesArray, GL_STATIC_DRAW); - _memoryUsageVBO += sizeof(GLuint) * _maxVoxels; + // we will track individual dirty sections with these arrays of bools + _writeVoxelDirtyArray = new bool[_maxVoxels]; + memset(_writeVoxelDirtyArray, false, _maxVoxels * sizeof(bool)); + _memoryUsageRAM += (sizeof(bool) * _maxVoxels); - glGenBuffers(1, &_vboVoxelsID); - glBindBuffer(GL_ARRAY_BUFFER, _vboVoxelsID); - glBufferData(GL_ARRAY_BUFFER, _maxVoxels * sizeof(VoxelShaderVBOData), NULL, GL_DYNAMIC_DRAW); - _memoryUsageVBO += _maxVoxels * sizeof(VoxelShaderVBOData); + _readVoxelDirtyArray = new bool[_maxVoxels]; + memset(_readVoxelDirtyArray, false, _maxVoxels * sizeof(bool)); + _memoryUsageRAM += (sizeof(bool) * _maxVoxels); - // delete the indices and normals arrays that are no longer needed - delete[] indicesArray; + // prep the data structures for incoming voxel data + _writeVerticesArray = new GLfloat[vertexPointsPerVoxel * _maxVoxels]; + _memoryUsageRAM += (sizeof(GLfloat) * vertexPointsPerVoxel * _maxVoxels); + _readVerticesArray = new GLfloat[vertexPointsPerVoxel * _maxVoxels]; + _memoryUsageRAM += (sizeof(GLfloat) * vertexPointsPerVoxel * _maxVoxels); - // we will track individual dirty sections with these arrays of bools - _writeVoxelDirtyArray = new bool[_maxVoxels]; - memset(_writeVoxelDirtyArray, false, _maxVoxels * sizeof(bool)); - _memoryUsageRAM += (_maxVoxels * sizeof(bool)); + _writeColorsArray = new GLubyte[vertexPointsPerVoxel * _maxVoxels]; + _memoryUsageRAM += (sizeof(GLubyte) * vertexPointsPerVoxel * _maxVoxels); + _readColorsArray = new GLubyte[vertexPointsPerVoxel * _maxVoxels]; + _memoryUsageRAM += (sizeof(GLubyte) * vertexPointsPerVoxel * _maxVoxels); - _readVoxelDirtyArray = new bool[_maxVoxels]; - memset(_readVoxelDirtyArray, false, _maxVoxels * sizeof(bool)); - _memoryUsageRAM += (_maxVoxels * sizeof(bool)); - - // prep the data structures for incoming voxel data - _writeVoxelShaderData = new VoxelShaderVBOData[_maxVoxels]; - _memoryUsageRAM += (sizeof(VoxelShaderVBOData) * _maxVoxels); - - _readVoxelShaderData = new VoxelShaderVBOData[_maxVoxels]; - _memoryUsageRAM += (sizeof(VoxelShaderVBOData) * _maxVoxels); - - } else { - - // Global Normals mode uses a technique of not including normals on any voxel vertices, and instead - // rendering the voxel faces in 6 passes that use a global call to glNormal3f() - setupFaceIndices(_vboIndicesTop, identityIndicesTop); - setupFaceIndices(_vboIndicesBottom, identityIndicesBottom); - setupFaceIndices(_vboIndicesLeft, identityIndicesLeft); - setupFaceIndices(_vboIndicesRight, identityIndicesRight); - setupFaceIndices(_vboIndicesFront, identityIndicesFront); - setupFaceIndices(_vboIndicesBack, identityIndicesBack); - - // Depending on if we're using per vertex normals, we will need more or less vertex points per voxel - int vertexPointsPerVoxel = GLOBAL_NORMALS_VERTEX_POINTS_PER_VOXEL; - glGenBuffers(1, &_vboVerticesID); - glBindBuffer(GL_ARRAY_BUFFER, _vboVerticesID); - glBufferData(GL_ARRAY_BUFFER, vertexPointsPerVoxel * sizeof(GLfloat) * _maxVoxels, NULL, GL_DYNAMIC_DRAW); - _memoryUsageVBO += vertexPointsPerVoxel * sizeof(GLfloat) * _maxVoxels; - - // VBO for colorsArray - glGenBuffers(1, &_vboColorsID); - glBindBuffer(GL_ARRAY_BUFFER, _vboColorsID); - glBufferData(GL_ARRAY_BUFFER, vertexPointsPerVoxel * sizeof(GLubyte) * _maxVoxels, NULL, GL_DYNAMIC_DRAW); - _memoryUsageVBO += vertexPointsPerVoxel * sizeof(GLubyte) * _maxVoxels; - - // we will track individual dirty sections with these arrays of bools - _writeVoxelDirtyArray = new bool[_maxVoxels]; - memset(_writeVoxelDirtyArray, false, _maxVoxels * sizeof(bool)); - _memoryUsageRAM += (sizeof(bool) * _maxVoxels); - - _readVoxelDirtyArray = new bool[_maxVoxels]; - memset(_readVoxelDirtyArray, false, _maxVoxels * sizeof(bool)); - _memoryUsageRAM += (sizeof(bool) * _maxVoxels); - - // prep the data structures for incoming voxel data - _writeVerticesArray = new GLfloat[vertexPointsPerVoxel * _maxVoxels]; - _memoryUsageRAM += (sizeof(GLfloat) * vertexPointsPerVoxel * _maxVoxels); - _readVerticesArray = new GLfloat[vertexPointsPerVoxel * _maxVoxels]; - _memoryUsageRAM += (sizeof(GLfloat) * vertexPointsPerVoxel * _maxVoxels); - - _writeColorsArray = new GLubyte[vertexPointsPerVoxel * _maxVoxels]; - _memoryUsageRAM += (sizeof(GLubyte) * vertexPointsPerVoxel * _maxVoxels); - _readColorsArray = new GLubyte[vertexPointsPerVoxel * _maxVoxels]; - _memoryUsageRAM += (sizeof(GLubyte) * vertexPointsPerVoxel * _maxVoxels); - - // create our simple fragment shader if we're the first system to init - if (!_program.isLinked()) { - _program.addShaderFromSourceFile(QGLShader::Vertex, - Application::resourcesPath() + "shaders/voxel.vert"); - _program.addShaderFromSourceFile(QGLShader::Fragment, - Application::resourcesPath() + "shaders/voxel.frag"); - _program.link(); - } + // create our simple fragment shader if we're the first system to init + if (!_program.isLinked()) { + _program.addShaderFromSourceFile(QGLShader::Vertex, + Application::resourcesPath() + "shaders/voxel.vert"); + _program.addShaderFromSourceFile(QGLShader::Fragment, + Application::resourcesPath() + "shaders/voxel.frag"); + _program.link(); } _renderer = new PrimitiveRenderer(_maxVoxels); @@ -882,25 +752,18 @@ void VoxelSystem::copyWrittenDataToReadArraysPartialVBOs() { void VoxelSystem::copyWrittenDataSegmentToReadArrays(glBufferIndex segmentStart, glBufferIndex segmentEnd) { int segmentLength = (segmentEnd - segmentStart) + 1; - if (_useVoxelShader) { - GLsizeiptr segmentSizeBytes = segmentLength * sizeof(VoxelShaderVBOData); - void* readDataAt = &_readVoxelShaderData[segmentStart]; - void* writeDataAt = &_writeVoxelShaderData[segmentStart]; - memcpy(readDataAt, writeDataAt, segmentSizeBytes); - } else { - // Depending on if we're using per vertex normals, we will need more or less vertex points per voxel - int vertexPointsPerVoxel = GLOBAL_NORMALS_VERTEX_POINTS_PER_VOXEL; + // Depending on if we're using per vertex normals, we will need more or less vertex points per voxel + int vertexPointsPerVoxel = GLOBAL_NORMALS_VERTEX_POINTS_PER_VOXEL; - GLsizeiptr segmentSizeBytes = segmentLength * vertexPointsPerVoxel * sizeof(GLfloat); - GLfloat* readVerticesAt = _readVerticesArray + (segmentStart * vertexPointsPerVoxel); - GLfloat* writeVerticesAt = _writeVerticesArray + (segmentStart * vertexPointsPerVoxel); - memcpy(readVerticesAt, writeVerticesAt, segmentSizeBytes); + GLsizeiptr segmentSizeBytes = segmentLength * vertexPointsPerVoxel * sizeof(GLfloat); + GLfloat* readVerticesAt = _readVerticesArray + (segmentStart * vertexPointsPerVoxel); + GLfloat* writeVerticesAt = _writeVerticesArray + (segmentStart * vertexPointsPerVoxel); + memcpy(readVerticesAt, writeVerticesAt, segmentSizeBytes); - segmentSizeBytes = segmentLength * vertexPointsPerVoxel * sizeof(GLubyte); - GLubyte* readColorsAt = _readColorsArray + (segmentStart * vertexPointsPerVoxel); - GLubyte* writeColorsAt = _writeColorsArray + (segmentStart * vertexPointsPerVoxel); - memcpy(readColorsAt, writeColorsAt, segmentSizeBytes); - } + segmentSizeBytes = segmentLength * vertexPointsPerVoxel * sizeof(GLubyte); + GLubyte* readColorsAt = _readColorsArray + (segmentStart * vertexPointsPerVoxel); + GLubyte* writeColorsAt = _writeColorsArray + (segmentStart * vertexPointsPerVoxel); + memcpy(readColorsAt, writeColorsAt, segmentSizeBytes); } void VoxelSystem::copyWrittenDataToReadArrays(bool fullVBOs) { @@ -1101,31 +964,15 @@ void VoxelSystem::updateArraysDetails(glBufferIndex nodeIndex, const glm::vec3& if (_initialized && nodeIndex <= _maxVoxels) { _writeVoxelDirtyArray[nodeIndex] = true; - if (_useVoxelShader) { - // write in position, scale, and color for the voxel - - if (_writeVoxelShaderData) { - VoxelShaderVBOData* writeVerticesAt = &_writeVoxelShaderData[nodeIndex]; - writeVerticesAt->x = startVertex.x * TREE_SCALE; - writeVerticesAt->y = startVertex.y * TREE_SCALE; - writeVerticesAt->z = startVertex.z * TREE_SCALE; - writeVerticesAt->s = voxelScale * TREE_SCALE; - writeVerticesAt->r = color[RED_INDEX]; - writeVerticesAt->g = color[GREEN_INDEX]; - writeVerticesAt->b = color[BLUE_INDEX]; - } - } else { - if (_writeVerticesArray && _writeColorsArray) { - int vertexPointsPerVoxel = GLOBAL_NORMALS_VERTEX_POINTS_PER_VOXEL; - for (int j = 0; j < vertexPointsPerVoxel; j++ ) { - GLfloat* writeVerticesAt = _writeVerticesArray + (nodeIndex * vertexPointsPerVoxel); - GLubyte* writeColorsAt = _writeColorsArray + (nodeIndex * vertexPointsPerVoxel); - *(writeVerticesAt+j) = startVertex[j % 3] + (identityVerticesGlobalNormals[j] * voxelScale); - *(writeColorsAt +j) = color[j % 3]; - } + if (_writeVerticesArray && _writeColorsArray) { + int vertexPointsPerVoxel = GLOBAL_NORMALS_VERTEX_POINTS_PER_VOXEL; + for (int j = 0; j < vertexPointsPerVoxel; j++ ) { + GLfloat* writeVerticesAt = _writeVerticesArray + (nodeIndex * vertexPointsPerVoxel); + GLubyte* writeColorsAt = _writeColorsArray + (nodeIndex * vertexPointsPerVoxel); + *(writeVerticesAt+j) = startVertex[j % 3] + (identityVerticesGlobalNormals[j] * voxelScale); + *(writeColorsAt +j) = color[j % 3]; } } - } } @@ -1253,44 +1100,34 @@ void VoxelSystem::updateVBOSegment(glBufferIndex segmentStart, glBufferIndex seg bool showWarning = Menu::getInstance()->isOptionChecked(MenuOption::PipelineWarnings); PerformanceWarning warn(showWarning, "updateVBOSegment()"); - if (_useVoxelShader) { - int segmentLength = (segmentEnd - segmentStart) + 1; - GLintptr segmentStartAt = segmentStart * sizeof(VoxelShaderVBOData); - GLsizeiptr segmentSizeBytes = segmentLength * sizeof(VoxelShaderVBOData); - void* readVerticesFrom = &_readVoxelShaderData[segmentStart]; + int vertexPointsPerVoxel = GLOBAL_NORMALS_VERTEX_POINTS_PER_VOXEL; + int segmentLength = (segmentEnd - segmentStart) + 1; + GLintptr segmentStartAt = segmentStart * vertexPointsPerVoxel * sizeof(GLfloat); + GLsizeiptr segmentSizeBytes = segmentLength * vertexPointsPerVoxel * sizeof(GLfloat); + GLfloat* readVerticesFrom = _readVerticesArray + (segmentStart * vertexPointsPerVoxel); - glBindBuffer(GL_ARRAY_BUFFER, _vboVoxelsID); + { + PerformanceWarning warn(showWarning, "updateVBOSegment() : glBindBuffer(GL_ARRAY_BUFFER, _vboVerticesID);"); + glBindBuffer(GL_ARRAY_BUFFER, _vboVerticesID); + } + + { + PerformanceWarning warn(showWarning, "updateVBOSegment() : glBufferSubData() _vboVerticesID);"); glBufferSubData(GL_ARRAY_BUFFER, segmentStartAt, segmentSizeBytes, readVerticesFrom); - } else { - int vertexPointsPerVoxel = GLOBAL_NORMALS_VERTEX_POINTS_PER_VOXEL; - int segmentLength = (segmentEnd - segmentStart) + 1; - GLintptr segmentStartAt = segmentStart * vertexPointsPerVoxel * sizeof(GLfloat); - GLsizeiptr segmentSizeBytes = segmentLength * vertexPointsPerVoxel * sizeof(GLfloat); - GLfloat* readVerticesFrom = _readVerticesArray + (segmentStart * vertexPointsPerVoxel); + } - { - PerformanceWarning warn(showWarning, "updateVBOSegment() : glBindBuffer(GL_ARRAY_BUFFER, _vboVerticesID);"); - glBindBuffer(GL_ARRAY_BUFFER, _vboVerticesID); - } + segmentStartAt = segmentStart * vertexPointsPerVoxel * sizeof(GLubyte); + segmentSizeBytes = segmentLength * vertexPointsPerVoxel * sizeof(GLubyte); + GLubyte* readColorsFrom = _readColorsArray + (segmentStart * vertexPointsPerVoxel); - { - PerformanceWarning warn(showWarning, "updateVBOSegment() : glBufferSubData() _vboVerticesID);"); - glBufferSubData(GL_ARRAY_BUFFER, segmentStartAt, segmentSizeBytes, readVerticesFrom); - } + { + PerformanceWarning warn(showWarning, "updateVBOSegment() : glBindBuffer(GL_ARRAY_BUFFER, _vboColorsID);"); + glBindBuffer(GL_ARRAY_BUFFER, _vboColorsID); + } - segmentStartAt = segmentStart * vertexPointsPerVoxel * sizeof(GLubyte); - segmentSizeBytes = segmentLength * vertexPointsPerVoxel * sizeof(GLubyte); - GLubyte* readColorsFrom = _readColorsArray + (segmentStart * vertexPointsPerVoxel); - - { - PerformanceWarning warn(showWarning, "updateVBOSegment() : glBindBuffer(GL_ARRAY_BUFFER, _vboColorsID);"); - glBindBuffer(GL_ARRAY_BUFFER, _vboColorsID); - } - - { - PerformanceWarning warn(showWarning, "updateVBOSegment() : glBufferSubData() _vboColorsID);"); - glBufferSubData(GL_ARRAY_BUFFER, segmentStartAt, segmentSizeBytes, readColorsFrom); - } + { + PerformanceWarning warn(showWarning, "updateVBOSegment() : glBufferSubData() _vboColorsID);"); + glBufferSubData(GL_ARRAY_BUFFER, segmentStartAt, segmentSizeBytes, readColorsFrom); } } @@ -1306,70 +1143,6 @@ void VoxelSystem::render() { updateVBOs(); - // if not don't... then do... - if (_useVoxelShader) { - PerformanceWarning warn(showWarnings,"render().. _useVoxelShader openGL.."); - - - //Define this somewhere in your header file - #define BUFFER_OFFSET(i) ((void*)(i)) - - glBindBuffer(GL_ARRAY_BUFFER, _vboVoxelsID); - glEnableClientState(GL_VERTEX_ARRAY); - glVertexPointer(3, GL_FLOAT, sizeof(VoxelShaderVBOData), BUFFER_OFFSET(0)); //The starting point of the VBO, for the vertices - - int attributeLocation; - - if (!_voxelsAsPoints) { - Application::getInstance()->getVoxelShader().begin(); - attributeLocation = Application::getInstance()->getVoxelShader().attributeLocation("voxelSizeIn"); - glEnableVertexAttribArray(attributeLocation); - glVertexAttribPointer(attributeLocation, 1, GL_FLOAT, false, sizeof(VoxelShaderVBOData), BUFFER_OFFSET(3*sizeof(float))); - } else { - glEnable(GL_VERTEX_PROGRAM_POINT_SIZE); - - glm::vec2 viewDimensions = Application::getInstance()->getViewportDimensions(); - float viewportWidth = viewDimensions.x; - float viewportHeight = viewDimensions.y; - glm::vec3 cameraPosition = Application::getInstance()->getViewFrustum()->getPosition(); - PointShader& pointShader = Application::getInstance()->getPointShader(); - - pointShader.begin(); - - pointShader.setUniformValue(pointShader.uniformLocation("viewportWidth"), viewportWidth); - pointShader.setUniformValue(pointShader.uniformLocation("viewportHeight"), viewportHeight); - pointShader.setUniformValue(pointShader.uniformLocation("cameraPosition"), cameraPosition); - - attributeLocation = pointShader.attributeLocation("voxelSizeIn"); - glEnableVertexAttribArray(attributeLocation); - glVertexAttribPointer(attributeLocation, 1, GL_FLOAT, false, sizeof(VoxelShaderVBOData), BUFFER_OFFSET(3*sizeof(float))); - } - - - glEnableClientState(GL_COLOR_ARRAY); - glColorPointer(3, GL_UNSIGNED_BYTE, sizeof(VoxelShaderVBOData), BUFFER_OFFSET(4*sizeof(float)));//The starting point of colors - - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _vboVoxelsIndicesID); - - glDrawElements(GL_POINTS, _voxelsInReadArrays, GL_UNSIGNED_INT, BUFFER_OFFSET(0)); //The starting point of the IBO - - // deactivate vertex and color arrays after drawing - glDisableClientState(GL_VERTEX_ARRAY); - glDisableClientState(GL_COLOR_ARRAY); - - // bind with 0 to switch back to normal operation - glBindBuffer(GL_ARRAY_BUFFER, 0); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); - - if (!_voxelsAsPoints) { - Application::getInstance()->getVoxelShader().end(); - glDisableVertexAttribArray(attributeLocation); - } else { - Application::getInstance()->getPointShader().end(); - glDisableVertexAttribArray(attributeLocation); - glDisable(GL_VERTEX_PROGRAM_POINT_SIZE); - } - } else if (!_usePrimitiveRenderer) { if (_drawHaze) { glEnable(GL_FOG); diff --git a/interface/src/voxels/VoxelSystem.h b/interface/src/voxels/VoxelSystem.h index 8e60cbe073..4f4c624e15 100644 --- a/interface/src/voxels/VoxelSystem.h +++ b/interface/src/voxels/VoxelSystem.h @@ -25,7 +25,6 @@ #include "Camera.h" #include "Util.h" #include "world.h" -#include "renderer/VoxelShader.h" #include "PrimitiveRenderer.h" class ProgramObject; @@ -33,14 +32,6 @@ class ProgramObject; const int NUM_CHILDREN = 8; -struct VoxelShaderVBOData -{ - float x, y, z; // position - float s; // size - unsigned char r,g,b; // color -}; - - class VoxelSystem : public NodeData, public OctreeElementDeleteHook, public OctreeElementUpdateHook { Q_OBJECT @@ -97,8 +88,6 @@ public slots: void clearAllNodesBufferIndex(); void setDisableFastVoxelPipeline(bool disableFastVoxelPipeline); - void setUseVoxelShader(bool useVoxelShader); - void setVoxelsAsPoints(bool voxelsAsPoints); protected: float _treeScale; @@ -191,14 +180,8 @@ private: void initVoxelMemory(); void cleanupVoxelMemory(); - bool _useVoxelShader; - bool _voxelsAsPoints; - bool _voxelShaderModeWhenVoxelsAsPointsEnabled; - GLuint _vboVoxelsID; /// when using voxel shader, we'll use this VBO GLuint _vboVoxelsIndicesID; /// when using voxel shader, we'll use this VBO for our indexes - VoxelShaderVBOData* _writeVoxelShaderData; - VoxelShaderVBOData* _readVoxelShaderData; GLuint _vboVerticesID; GLuint _vboColorsID; From 208d3c8413579611e1b6f01a39d046ab82d451cb Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Thu, 11 Dec 2014 13:59:21 -0800 Subject: [PATCH 039/258] remove old unused shaders --- interface/resources/shaders/passthrough.vert | 21 --- interface/resources/shaders/point_size.vert | 174 ------------------- interface/resources/shaders/voxel.geom | 87 ---------- 3 files changed, 282 deletions(-) delete mode 100644 interface/resources/shaders/passthrough.vert delete mode 100644 interface/resources/shaders/point_size.vert delete mode 100644 interface/resources/shaders/voxel.geom diff --git a/interface/resources/shaders/passthrough.vert b/interface/resources/shaders/passthrough.vert deleted file mode 100644 index bb0a18eefa..0000000000 --- a/interface/resources/shaders/passthrough.vert +++ /dev/null @@ -1,21 +0,0 @@ -#version 120 - -// -// passthrough.vert -// vertex shader -// -// Copyright 2013 High Fidelity, Inc. -// -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -attribute float voxelSizeIn; -varying float voxelSize; - -void main(void) { - gl_FrontColor = gl_Color; - gl_Position = gl_Vertex; // don't call ftransform(), because we do projection in geometry shader - voxelSize = voxelSizeIn; -} \ No newline at end of file diff --git a/interface/resources/shaders/point_size.vert b/interface/resources/shaders/point_size.vert deleted file mode 100644 index 88c56bf0c4..0000000000 --- a/interface/resources/shaders/point_size.vert +++ /dev/null @@ -1,174 +0,0 @@ -#version 120 - -// -// point_size.vert -// vertex shader -// -// Copyright 2013 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -attribute float voxelSizeIn; -varying float voxelSize; - -uniform float viewportWidth; -uniform float viewportHeight; -uniform vec3 cameraPosition; - -// Bit codes for faces -const int NONE = 0; -const int RIGHT = 1; -const int LEFT = 2; -const int BOTTOM = 4; -const int BOTTOM_RIGHT = BOTTOM + RIGHT; -const int BOTTOM_LEFT = BOTTOM + LEFT; -const int TOP = 8; -const int TOP_RIGHT = TOP + RIGHT; -const int TOP_LEFT = TOP + LEFT; -const int NEAR = 16; -const int NEAR_RIGHT = NEAR + RIGHT; -const int NEAR_LEFT = NEAR + LEFT; -const int NEAR_BOTTOM = NEAR + BOTTOM; -const int NEAR_BOTTOM_RIGHT = NEAR + BOTTOM + RIGHT; -const int NEAR_BOTTOM_LEFT = NEAR + BOTTOM + LEFT; -const int NEAR_TOP = NEAR + TOP; -const int NEAR_TOP_RIGHT = NEAR + TOP + RIGHT; -const int NEAR_TOP_LEFT = NEAR + TOP + LEFT; -const int FAR = 32; -const int FAR_RIGHT = FAR + RIGHT; -const int FAR_LEFT = FAR + LEFT; -const int FAR_BOTTOM = FAR + BOTTOM; -const int FAR_BOTTOM_RIGHT = FAR + BOTTOM + RIGHT; -const int FAR_BOTTOM_LEFT = FAR + BOTTOM + LEFT; -const int FAR_TOP = FAR + TOP; -const int FAR_TOP_RIGHT = FAR + TOP + RIGHT; -const int FAR_TOP_LEFT = FAR + TOP + LEFT; - -// If we know the position of the camera relative to the voxel, we can a priori know the vertices that make the visible hull -// polygon. This also tells us which two vertices are known to make the longest possible distance between any pair of these -// vertices for the projected polygon. This is a visibleFaces table based on this knowledge. - -void main(void) { - // Note: the gl_Vertex in this case are in "world coordinates" meaning they've already been scaled to TREE_SCALE - // this is also true for voxelSizeIn. - vec4 bottomNearRight = gl_Vertex; - vec4 topFarLeft = (gl_Vertex + vec4(voxelSizeIn, voxelSizeIn, voxelSizeIn, 0.0)); - - int visibleFaces = NONE; - - // In order to use our visibleFaces "table" (implemented as if statements) below, we need to encode the 6-bit code to - // orient camera relative to the 6 defining faces of the voxel. Based on camera position relative to the bottomNearRight - // corner and the topFarLeft corner, we can calculate which hull and therefore which two vertices are furthest apart - // linearly once projected - if (cameraPosition.x < bottomNearRight.x) { - visibleFaces += RIGHT; - } - if (cameraPosition.x > topFarLeft.x) { - visibleFaces += LEFT; - } - if (cameraPosition.y < bottomNearRight.y) { - visibleFaces += BOTTOM; - } - if (cameraPosition.y > topFarLeft.y) { - visibleFaces += TOP; - } - if (cameraPosition.z < bottomNearRight.z) { - visibleFaces += NEAR; - } - if (cameraPosition.z > topFarLeft.z) { - visibleFaces += FAR; - } - - vec4 cornerAdjustOne; - vec4 cornerAdjustTwo; - - if (visibleFaces == RIGHT) { - cornerAdjustOne = vec4(0,0,0,0) * voxelSizeIn; - cornerAdjustTwo = vec4(0,1,1,0) * voxelSizeIn; - } else if (visibleFaces == LEFT) { - cornerAdjustOne = vec4(1,0,0,0) * voxelSizeIn; - cornerAdjustTwo = vec4(1,1,1,0) * voxelSizeIn; - } else if (visibleFaces == BOTTOM) { - cornerAdjustOne = vec4(0,0,0,0) * voxelSizeIn; - cornerAdjustTwo = vec4(1,0,1,0) * voxelSizeIn; - } else if (visibleFaces == TOP) { - cornerAdjustOne = vec4(0,1,0,0) * voxelSizeIn; - cornerAdjustTwo = vec4(1,1,1,0) * voxelSizeIn; - } else if (visibleFaces == NEAR) { - cornerAdjustOne = vec4(0,0,0,0) * voxelSizeIn; - cornerAdjustTwo = vec4(1,1,0,0) * voxelSizeIn; - } else if (visibleFaces == FAR) { - cornerAdjustOne = vec4(0,0,1,0) * voxelSizeIn; - cornerAdjustTwo = vec4(1,1,1,0) * voxelSizeIn; - } else if (visibleFaces == NEAR_BOTTOM_LEFT || - visibleFaces == FAR_TOP || - visibleFaces == FAR_TOP_RIGHT) { - cornerAdjustOne = vec4(0,1,0,0) * voxelSizeIn; - cornerAdjustTwo = vec4(1,0,1,0) * voxelSizeIn; - } else if (visibleFaces == FAR_TOP_LEFT || - visibleFaces == NEAR_RIGHT || - visibleFaces == NEAR_BOTTOM || - visibleFaces == NEAR_BOTTOM_RIGHT) { - cornerAdjustOne = vec4(0,0,1,0) * voxelSizeIn; - cornerAdjustTwo = vec4(1,1,0,0) * voxelSizeIn; - } else if (visibleFaces == NEAR_TOP_RIGHT || - visibleFaces == FAR_LEFT || - visibleFaces == FAR_BOTTOM_LEFT || - visibleFaces == BOTTOM_RIGHT || - visibleFaces == TOP_LEFT) { - cornerAdjustOne = vec4(1,0,0,0) * voxelSizeIn; - cornerAdjustTwo = vec4(0,1,1,0) * voxelSizeIn; - - // Everything else... - //} else if (visibleFaces == BOTTOM_LEFT || - // visibleFaces == TOP_RIGHT || - // visibleFaces == NEAR_LEFT || - // visibleFaces == FAR_RIGHT || - // visibleFaces == NEAR_TOP || - // visibleFaces == NEAR_TOP_LEFT || - // visibleFaces == FAR_BOTTOM || - // visibleFaces == FAR_BOTTOM_RIGHT) { - } else { - cornerAdjustOne = vec4(0,0,0,0) * voxelSizeIn; - cornerAdjustTwo = vec4(1,1,1,0) * voxelSizeIn; - } - - // Determine our corners - vec4 cornerOne = gl_Vertex + cornerAdjustOne; - vec4 cornerTwo = gl_Vertex + cornerAdjustTwo; - - // Find their model view projections - vec4 cornerOneMVP = gl_ModelViewProjectionMatrix * cornerOne; - vec4 cornerTwoMVP = gl_ModelViewProjectionMatrix * cornerTwo; - - // Map to x, y screen coordinates - vec2 cornerOneScreen = vec2(cornerOneMVP.x / cornerOneMVP.w, cornerOneMVP.y / cornerOneMVP.w); - if (cornerOneMVP.w < 0) { - cornerOneScreen.x = -cornerOneScreen.x; - cornerOneScreen.y = -cornerOneScreen.y; - } - - vec2 cornerTwoScreen = vec2(cornerTwoMVP.x / cornerTwoMVP.w, cornerTwoMVP.y / cornerTwoMVP.w); - if (cornerTwoMVP.w < 0) { - cornerTwoScreen.x = -cornerTwoScreen.x; - cornerTwoScreen.y = -cornerTwoScreen.y; - } - - // Find the distance between them in pixels - float voxelScreenWidth = abs(cornerOneScreen.x - cornerTwoScreen.x) * viewportWidth / 2.0; - float voxelScreenHeight = abs(cornerOneScreen.y - cornerTwoScreen.y) * viewportHeight / 2.0; - float voxelScreenLength = sqrt(voxelScreenHeight * voxelScreenHeight + voxelScreenWidth * voxelScreenWidth); - - // Find the center of the voxel - vec4 centerVertex = gl_Vertex; - float halfSizeIn = voxelSizeIn / 2; - centerVertex += vec4(halfSizeIn, halfSizeIn, halfSizeIn, 0.0); - vec4 center = gl_ModelViewProjectionMatrix * centerVertex; - - // Finally place the point at the center of the voxel, with a size equal to the maximum screen length - gl_Position = center; - gl_PointSize = voxelScreenLength; - gl_FrontColor = gl_Color; -} \ No newline at end of file diff --git a/interface/resources/shaders/voxel.geom b/interface/resources/shaders/voxel.geom deleted file mode 100644 index 4c850ed608..0000000000 --- a/interface/resources/shaders/voxel.geom +++ /dev/null @@ -1,87 +0,0 @@ -#version 120 -#extension GL_ARB_geometry_shader4 : enable - -// -// voxel.geom -// geometry shader -// -// Copyright 2013 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -// -// VOXEL GEOMETRY SHADER -// -// Input: gl_VerticesIn/gl_PositionIn -// GL_POINTS -// Assumes vertex shader has not transformed coordinates -// Each gl_PositionIn is the corner of voxel -// varying voxelSize - which is the voxel size -// -// Note: In vertex shader doesn't do any transform. Therefore passing the 3D world coordinates xyz to us -// -// Output: GL_TRIANGLE_STRIP -// -// Issues: -// how do we need to handle lighting of these colors?? -// how do we handle normals? -// check for size=0 and don't output the primitive -// - -varying in float voxelSize[1]; - -const int VERTICES_PER_FACE = 4; -const int COORD_PER_VERTEX = 3; -const int COORD_PER_FACE = COORD_PER_VERTEX * VERTICES_PER_FACE; - -void faceOfVoxel(vec4 corner, float scale, float[COORD_PER_FACE] facePoints, vec4 color, vec4 normal) { - for (int v = 0; v < VERTICES_PER_FACE; v++ ) { - vec4 vertex = corner; - for (int c = 0; c < COORD_PER_VERTEX; c++ ) { - int cIndex = c + (v * COORD_PER_VERTEX); - vertex[c] += (facePoints[cIndex] * scale); - } - - gl_FrontColor = color * (gl_LightModel.ambient + gl_LightSource[0].ambient + - gl_LightSource[0].diffuse * max(0.0, dot(normal, gl_LightSource[0].position))); - - gl_Position = gl_ModelViewProjectionMatrix * vertex; - EmitVertex(); - } - EndPrimitive(); -} - - -void main() { - //increment variable - int i; - vec4 corner; - float scale; - - float bottomFace[COORD_PER_FACE] = float[COORD_PER_FACE]( 0, 0, 0, 1, 0, 0, 0, 0, 1, 1, 0, 1 ); - float topFace[COORD_PER_FACE] = float[COORD_PER_FACE]( 1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1 ); - float rightFace[COORD_PER_FACE] = float[COORD_PER_FACE]( 0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1 ); - float leftFace[COORD_PER_FACE] = float[COORD_PER_FACE]( 1, 0, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1 ); - float frontFace[COORD_PER_FACE] = float[COORD_PER_FACE]( 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0 ); - float backFace[COORD_PER_FACE] = float[COORD_PER_FACE]( 1, 0, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1 ); - - vec4 bottomNormal = vec4(0.0, -1, 0.0, 0.0); - vec4 topNormal = vec4(0.0, 1, 0.0, 0.0); - vec4 rightNormal = vec4( -1, 0.0, 0.0, 0.0); - vec4 leftNormal = vec4( 1, 0.0, 0.0, 0.0); - vec4 frontNormal = vec4(0.0, 0.0, -1, 0.0); - vec4 backNormal = vec4(0.0, 0.0, 1, 0.0); - - for(i = 0; i < gl_VerticesIn; i++) { - corner = gl_PositionIn[i]; - scale = voxelSize[i]; - faceOfVoxel(corner, scale, bottomFace, gl_FrontColorIn[i], bottomNormal); - faceOfVoxel(corner, scale, topFace, gl_FrontColorIn[i], topNormal ); - faceOfVoxel(corner, scale, rightFace, gl_FrontColorIn[i], rightNormal ); - faceOfVoxel(corner, scale, leftFace, gl_FrontColorIn[i], leftNormal ); - faceOfVoxel(corner, scale, frontFace, gl_FrontColorIn[i], frontNormal ); - faceOfVoxel(corner, scale, backFace, gl_FrontColorIn[i], backNormal ); - } -} \ No newline at end of file From 3eb7314c98684c00a18e16a3fe16f82ebd82e0cc Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Thu, 11 Dec 2014 14:13:44 -0800 Subject: [PATCH 040/258] remove PrimitiveRenderer --- interface/src/voxels/PrimitiveRenderer.cpp | 742 --------------------- interface/src/voxels/PrimitiveRenderer.h | 503 -------------- interface/src/voxels/VoxelSystem.cpp | 534 ++------------- interface/src/voxels/VoxelSystem.h | 15 - 4 files changed, 61 insertions(+), 1733 deletions(-) delete mode 100644 interface/src/voxels/PrimitiveRenderer.cpp delete mode 100644 interface/src/voxels/PrimitiveRenderer.h diff --git a/interface/src/voxels/PrimitiveRenderer.cpp b/interface/src/voxels/PrimitiveRenderer.cpp deleted file mode 100644 index a212245289..0000000000 --- a/interface/src/voxels/PrimitiveRenderer.cpp +++ /dev/null @@ -1,742 +0,0 @@ -// -// PrimitiveRenderer.cpp -// interface/src/voxels -// -// Copyright 2014 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -#include - -#include "InterfaceConfig.h" -#include "OctreeElement.h" -#include "PrimitiveRenderer.h" - -Primitive::Primitive() { -} - -Primitive::~Primitive() { -} - -// Simple dispatch between API and SPI - -const VertexElementList& Primitive::vertexElements() const { - return vVertexElements(); -} - -VertexElementIndexList& Primitive::vertexElementIndices() { - return vVertexElementIndices(); -} - -TriElementList& Primitive::triElements() { - return vTriElements(); -} - -void Primitive::releaseVertexElements() { - vReleaseVertexElements(); -} - -unsigned long Primitive::getMemoryUsage() { - return vGetMemoryUsage(); -} - - -Cube::Cube( - float x, - float y, - float z, - float s, - unsigned char r, - unsigned char g, - unsigned char b, - unsigned char faceExclusions - ) : - _cpuMemoryUsage(0) { - init(x, y, z, s, r, g, b, faceExclusions); -} - -Cube::~Cube() { - terminate(); -} - -void Cube::init( - float x, - float y, - float z, - float s, - unsigned char r, - unsigned char g, - unsigned char b, - unsigned char faceExclusions - ) { - - initializeVertices(x, y, z, s, r, g, b, faceExclusions); - initializeTris(faceExclusions); -} - -void Cube::terminate() { - - terminateTris(); - terminateVertices(); -} - -void Cube::initializeVertices( - float x, - float y, - float z, - float s, - unsigned char r, - unsigned char g, - unsigned char b, - unsigned char faceExclusions - ) { - - for (int i = 0; i < _sNumVerticesPerCube; i++) { - // Check whether the vertex is necessary for the faces indicated by faceExclusions bit mask. - // uncomment this line to load all faces: if (~0x00 & _sFaceIndexToHalfSpaceMask[i >> 2]) { - // uncomment this line to include shared faces: if (faceExclusions & _sFaceIndexToHalfSpaceMask[i >> 2]) { - // uncomment this line to exclude shared faces: - if (~faceExclusions & _sFaceIndexToHalfSpaceMask[i >> 2]) { - - VertexElement* v = new VertexElement(); - if (v) { - // Construct vertex position - v->position.x = x + s * _sVertexIndexToConstructionVector[i][0]; - v->position.y = y + s * _sVertexIndexToConstructionVector[i][1]; - v->position.z = z + s * _sVertexIndexToConstructionVector[i][2]; - - // Construct vertex normal - v->normal.x = _sVertexIndexToNormalVector[i >> 2][0]; - v->normal.y = _sVertexIndexToNormalVector[i >> 2][1]; - v->normal.z = _sVertexIndexToNormalVector[i >> 2][2]; - - // Construct vertex color -//#define FALSE_COLOR -#ifndef FALSE_COLOR - v->color.r = r; - v->color.g = g; - v->color.b = b; - v->color.a = 255; -#else - static unsigned char falseColor[6][3] = { - 192, 0, 0, // Bot - 0, 192, 0, // Top - 0, 0, 192, // Right - 192, 0, 192, // Left - 192, 192, 0, // Near - 192, 192, 192 // Far - }; - v->color.r = falseColor[i >> 2][0]; - v->color.g = falseColor[i >> 2][1]; - v->color.b = falseColor[i >> 2][2]; - v->color.a = 255; -#endif - - // Add vertex element to list - _vertices.push_back(v); - _cpuMemoryUsage += sizeof(VertexElement); - _cpuMemoryUsage += sizeof(VertexElement*); - } - } - } -} - -void Cube::terminateVertices() { - - for (VertexElementList::iterator it = _vertices.begin(); it != _vertices.end(); ++it) { - delete *it; - } - _cpuMemoryUsage -= _vertices.size() * (sizeof(VertexElement) + sizeof(VertexElement*)); - _vertices.clear(); -} - -void Cube::initializeTris( - unsigned char faceExclusions - ) { - - int index = 0; - for (int i = 0; i < _sNumFacesPerCube; i++) { - // Check whether the vertex is necessary for the faces indicated by faceExclusions bit mask. - // uncomment this line to load all faces: if (~0x00 & _sFaceIndexToHalfSpaceMask[i]) { - // uncomment this line to include shared faces: if (faceExclusions & _sFaceIndexToHalfSpaceMask[i]) { - // uncomment this line to exclude shared faces: - if (~faceExclusions & _sFaceIndexToHalfSpaceMask[i]) { - - int start = index; - // Create the triangulated face, two tris, six indices referencing four vertices, both - // with cw winding order, such that: - - // A-B - // |\| - // D-C - - // Store triangle ABC - - TriElement* tri = new TriElement(); - if (tri) { - tri->indices[0] = index++; - tri->indices[1] = index++; - tri->indices[2] = index; - - // Add tri element to list - _tris.push_back(tri); - _cpuMemoryUsage += sizeof(TriElement); - _cpuMemoryUsage += sizeof(TriElement*); - } - - // Now store triangle ACD - tri = new TriElement(); - if (tri) { - tri->indices[0] = start; - tri->indices[1] = index++; - tri->indices[2] = index++; - - // Add tri element to list - _tris.push_back(tri); - _cpuMemoryUsage += sizeof(TriElement); - _cpuMemoryUsage += sizeof(TriElement*); - } - } - } -} - -void Cube::terminateTris() { - - for (TriElementList::iterator it = _tris.begin(); it != _tris.end(); ++it) { - delete *it; - } - _cpuMemoryUsage -= _tris.size() * (sizeof(TriElement) + sizeof(TriElement*)); - _tris.clear(); -} - -const VertexElementList& Cube::vVertexElements() const { - return _vertices; -} - -VertexElementIndexList& Cube::vVertexElementIndices() { - return _vertexIndices; -} - -TriElementList& Cube::vTriElements() { - return _tris; -} - -void Cube::vReleaseVertexElements() { - terminateVertices(); -} - -unsigned long Cube::vGetMemoryUsage() { - return _cpuMemoryUsage; -} - -unsigned char Cube::_sFaceIndexToHalfSpaceMask[6] = { - OctreeElement::HalfSpace::Bottom, - OctreeElement::HalfSpace::Top, - OctreeElement::HalfSpace::Right, - OctreeElement::HalfSpace::Left, - OctreeElement::HalfSpace::Near, - OctreeElement::HalfSpace::Far, -}; - -// Construction vectors ordered such that the vertices of each face are -// clockwise in a right-handed coordinate system with B-L-N at 0,0,0. -float Cube::_sVertexIndexToConstructionVector[24][3] = { - // Bottom - { 0,0,0 }, - { 1,0,0 }, - { 1,0,1 }, - { 0,0,1 }, - // Top - { 0,1,0 }, - { 0,1,1 }, - { 1,1,1 }, - { 1,1,0 }, - // Right - { 1,0,0 }, - { 1,1,0 }, - { 1,1,1 }, - { 1,0,1 }, - // Left - { 0,0,0 }, - { 0,0,1 }, - { 0,1,1 }, - { 0,1,0 }, - // Near - { 0,0,0 }, - { 0,1,0 }, - { 1,1,0 }, - { 1,0,0 }, - // Far - { 0,0,1 }, - { 1,0,1 }, - { 1,1,1 }, - { 0,1,1 }, -}; - -// Normals for a right-handed coordinate system -float Cube::_sVertexIndexToNormalVector[6][3] = { - { 0,-1, 0 }, // Bottom - { 0, 1, 0 }, // Top - { 1, 0, 0 }, // Right - { -1, 0, 0 }, // Left - { 0, 0,-1 }, // Near - { 0, 0, 1 }, // Far -}; - -Renderer::Renderer() { -} - -Renderer::~Renderer() { -} - -// Simple dispatch between API and SPI -int Renderer::add( - Primitive* primitive - ) { - return vAdd(primitive); -} - -void Renderer::remove( - int id - ) { - vRemove(id); -} - -void Renderer::release() { - vRelease(); -} - -void Renderer::render() { - vRender(); -} - -unsigned long Renderer::getMemoryUsage() { - return vGetMemoryUsage(); -} - -unsigned long Renderer::getMemoryUsageGPU() { - return vGetMemoryUsageGPU(); -} - -PrimitiveRenderer::PrimitiveRenderer( - int maxCount - ) : - _maxCount(maxCount), - _triBufferId(0), - _vertexBufferId(0), - - _vertexElementCount(0), - _maxVertexElementCount(0), - - _triElementCount(0), - _maxTriElementCount(0), - - _primitives(), - _primitiveCount(0), - - _gpuMemoryUsage(0), - _cpuMemoryUsage(0) - -{ - init(); -} - -PrimitiveRenderer::~PrimitiveRenderer() { - - terminate(); -} - -void PrimitiveRenderer::init() { - - initializeGL(); - initializeBookkeeping(); -} - -void PrimitiveRenderer::initializeGL() { - - glGenBuffers(1, &_triBufferId); - glGenBuffers(1, &_vertexBufferId); - - // Set up the element array buffer containing the index ids - _maxTriElementCount = _maxCount * 2; - int size = _maxTriElementCount * _sIndicesPerTri * sizeof(GLint); - _gpuMemoryUsage += size; - - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _triBufferId); - glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, 0, GL_DYNAMIC_DRAW); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); - - // Set up the array buffer in the form of array of structures - // I chose AOS because it maximizes the amount of data tranferred - // by a single glBufferSubData call. - _maxVertexElementCount = _maxCount * 8; - size = _maxVertexElementCount * sizeof(VertexElement); - _gpuMemoryUsage += size; - - glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferId); - glBufferData(GL_ARRAY_BUFFER, size, 0, GL_DYNAMIC_DRAW); - glBindBuffer(GL_ARRAY_BUFFER, 0); - - // Initialize the first tri element in the buffer to all zeros, the - // degenerate case - deconstructTriElement(0); - - // Initialize the first vertex element in the buffer to all zeros, the - // degenerate case - deconstructVertexElement(0); -} - -void PrimitiveRenderer::initializeBookkeeping() { - - // Start primitive count at one, because zero is reserved for the degenerate triangle - _primitives.resize(_maxCount + 1); - - // Set the counters - _primitiveCount = 1; - _vertexElementCount = 1; - _triElementCount = 1; - - // Guesstimate the memory consumption - _cpuMemoryUsage = sizeof(PrimitiveRenderer); - _cpuMemoryUsage += _availablePrimitiveIndex.capacity() * sizeof(int); - _cpuMemoryUsage += _availableVertexElementIndex.capacity() * sizeof(int); - _cpuMemoryUsage += _availableTriElementIndex.capacity() * sizeof(int); - _cpuMemoryUsage += _deconstructTriElementIndex.capacity() * sizeof(int); - _cpuMemoryUsage += _constructPrimitiveIndex.capacity() * sizeof(int); -} - -void PrimitiveRenderer::terminate() { - - terminateBookkeeping(); - terminateGL(); -} - -void PrimitiveRenderer::terminateGL() { - - if (_vertexBufferId) { - glDeleteBuffers(1, &_vertexBufferId); - _vertexBufferId = 0; - } - - if (_triBufferId) { - glDeleteBuffers(1, &_triBufferId); - _triBufferId = 0; - } -} - -void PrimitiveRenderer::terminateBookkeeping() { - - // Delete all of the primitives - for (int i = _primitiveCount + 1; --i > 0; ) { - Primitive* primitive = _primitives[i]; - if (primitive) { - _cpuMemoryUsage -= primitive->getMemoryUsage(); - _primitives[i] = 0; - delete primitive; - } - } - - // Drain the queues - _availablePrimitiveIndex.clear(); - _availableVertexElementIndex.clear(); - _availableTriElementIndex.clear(); - _deconstructTriElementIndex.clear(); - _constructPrimitiveIndex.clear(); - - _cpuMemoryUsage = sizeof(PrimitiveRenderer) + _primitives.size() * sizeof(Primitive *); -} - -void PrimitiveRenderer::constructElements( - Primitive* primitive - ) { - - // Load vertex elements - VertexElementIndexList& vertexElementIndexList = primitive->vertexElementIndices(); - const VertexElementList& vertices = primitive->vertexElements(); - { - for (VertexElementList::const_iterator it = vertices.begin(); it != vertices.end(); ++it ) { - int index = getAvailableVertexElementIndex(); - if (index != 0) { - // Store the vertex element index in the primitive's - // vertex element index list - vertexElementIndexList.push_back(index); - - VertexElement* vertex = *it; - transferVertexElement(index, vertex); - } else { - break; - } - } - } - - // Load tri elements - if (vertexElementIndexList.size() == vertices.size()) { - TriElementList& tris = primitive->triElements(); - - for (TriElementList::iterator it = tris.begin(); it != tris.end(); ++it) { - TriElement* tri = *it; - int index = getAvailableTriElementIndex(); - if (index != 0) { - int k; - k = tri->indices[0]; - tri->indices[0] = vertexElementIndexList[k]; - - k = tri->indices[1]; - tri->indices[1] = vertexElementIndexList[k]; - - k = tri->indices[2]; - tri->indices[2] = vertexElementIndexList[k]; - - tri->id = index; - transferTriElement(index, tri->indices); - } else { - break; - } - } - } else { - // TODO: failure mode - } -} - -void PrimitiveRenderer::deconstructElements( - Primitive* primitive - ) { - - // Schedule the tri elements of the face for deconstruction - { - TriElementList& tris = primitive->triElements(); - - for (TriElementList::const_iterator it = tris.begin(); it != tris.end(); ++it) { - const TriElement* tri = *it; - - if (tri->id) { - // Put the tri element index into decon queue - _deconstructTriElementIndex.push(tri->id); - } - } - } - - // Return the vertex element index to the available queue, it is not necessary - // to zero the data - { - VertexElementIndexList& vertexIndexList = primitive->vertexElementIndices(); - - for (VertexElementIndexList::const_iterator it = vertexIndexList.begin(); it != vertexIndexList.end(); ++it) { - int index = *it; - - if (index) { - // Put the vertex element index into the available queue - _availableVertexElementIndex.push(index); - } - } - } - - delete primitive; -} - -int PrimitiveRenderer::getAvailablePrimitiveIndex() { - - int index; - - // Check the available primitive index queue first for an available index. - if (!_availablePrimitiveIndex.isEmpty()) { - index = _availablePrimitiveIndex.pop(); - } else if (_primitiveCount < _maxCount) { - // There are no primitive indices available from the queue, - // make one up - index = _primitiveCount++; - } else { - index = 0; - } - return index; -} - -int PrimitiveRenderer::getAvailableVertexElementIndex() { - - int index; - - // Check the available vertex element queue first for an available index. - if (!_availableVertexElementIndex.isEmpty()) { - index = _availableVertexElementIndex.pop(); - } else if (_vertexElementCount < _maxVertexElementCount) { - // There are no vertex elements available from the queue, - // grab one from the end of the list - index = _vertexElementCount++; - } else { - index = 0; - } - return index; -} - -int PrimitiveRenderer::getAvailableTriElementIndex() { - - int index; - - // Check the tri elements scheduled for deconstruction queue first to - // intercept and reuse an index without it having to be destroyed - if (!_deconstructTriElementIndex.isEmpty()) { - index = _deconstructTriElementIndex.pop(); - } else if (!_availableTriElementIndex.isEmpty()) { - // Nothing available in the deconstruction queue, now - // check the available tri element queue for an available index. - index = _availableTriElementIndex.pop(); - } else if (_triElementCount < _maxTriElementCount) { - // There are no reusable tri elements available from the queue, - // grab one from the end of the list - index = _triElementCount++; - } else { - index = 0; - } - return index; -} - -void PrimitiveRenderer::deconstructTriElement( - int idx - ) { - - // Set the tri element to the degenerate case. - static int degenerate[3] = { 0, 0, 0 }; - transferTriElement(idx, degenerate); - -} - -void PrimitiveRenderer::deconstructVertexElement( - int idx - ) { - - // Set the vertex element to the degenerate case. - VertexElement degenerate; - memset(°enerate, 0, sizeof(degenerate)); - - transferVertexElement(idx, °enerate); - -} - -void PrimitiveRenderer::transferVertexElement( - int idx, - VertexElement* vertex - ) { - - glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferId); - glBufferSubData(GL_ARRAY_BUFFER, idx * sizeof(VertexElement), sizeof(VertexElement), vertex); - glBindBuffer(GL_ARRAY_BUFFER, 0); -} - -void PrimitiveRenderer::transferTriElement( - int idx, - int tri[3] - ) { - - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _triBufferId); - glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, idx * _sBytesPerTriElement, _sBytesPerTriElement, tri); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); -} - -int PrimitiveRenderer::vAdd( - Primitive* primitive - ) { - - QMutexLocker lock(&_guard); - int id = getAvailablePrimitiveIndex(); - if (id != 0) { - // Take ownership of primitive, including responsibility - // for destruction - _primitives[id] = primitive; - _constructPrimitiveIndex.push(id); - _cpuMemoryUsage += primitive->getMemoryUsage(); - } - return id; -} - -void PrimitiveRenderer::vRemove( - int id - ) { - - if (id != 0) { - QMutexLocker lock(&_guard); - - // Locate and remove the primitive by id in the vector map - Primitive* primitive = _primitives[id]; - if (primitive) { - _primitives[id] = 0; - _cpuMemoryUsage -= primitive->getMemoryUsage(); - deconstructElements(primitive); - - // Queue the index onto the available primitive stack. - _availablePrimitiveIndex.push(id); - } - } -} - -void PrimitiveRenderer::vRelease() { - - QMutexLocker lock(&_guard); - - terminateBookkeeping(); - initializeBookkeeping(); -} - -void PrimitiveRenderer::vRender() { - - int id; - QMutexLocker lock(&_guard); - - // Iterate over the set of triangle element array buffer ids scheduled for - // destruction. Set the triangle element to the degenerate case. Queue the id - // onto the available tri element stack. - while (!_deconstructTriElementIndex.isEmpty()) { - id = _deconstructTriElementIndex.pop(); - deconstructTriElement(id); - _availableTriElementIndex.push(id); - } - - // Iterate over the set of primitive ids scheduled for construction. Transfer - // primitive data to the GPU. - while (!_constructPrimitiveIndex.isEmpty()) { - id = _constructPrimitiveIndex.pop(); - Primitive* primitive = _primitives[id]; - if (primitive) { - constructElements(primitive); - - // No need to keep an extra copy of the vertices - _cpuMemoryUsage -= primitive->getMemoryUsage(); - primitive->releaseVertexElements(); - _cpuMemoryUsage += primitive->getMemoryUsage(); - } - } - - // The application uses clockwise winding for the definition of front face, this renderer - // aalso uses clockwise (that is the gl default) to construct the triangulation - // so... - //glFrontFace(GL_CW); - glEnable(GL_CULL_FACE); - - glBindBuffer(GL_ARRAY_BUFFER, _vertexBufferId); - - glEnableClientState(GL_VERTEX_ARRAY); - glVertexPointer(3, GL_FLOAT, sizeof(VertexElement), 0); - - glEnableClientState(GL_NORMAL_ARRAY); - glNormalPointer(GL_FLOAT, sizeof(VertexElement), (const GLvoid*)12); - - glEnableClientState(GL_COLOR_ARRAY); - glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(VertexElement), (const GLvoid*)24); - - glBindBuffer(GL_ARRAY_BUFFER, 0); - - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, _triBufferId); - glDrawElements(GL_TRIANGLES, 3 * _triElementCount, GL_UNSIGNED_INT, 0); - glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); - - glDisable(GL_CULL_FACE); -} - -unsigned long PrimitiveRenderer::vGetMemoryUsage() { - return _cpuMemoryUsage; -} - -unsigned long PrimitiveRenderer::vGetMemoryUsageGPU() { - return _gpuMemoryUsage; -} diff --git a/interface/src/voxels/PrimitiveRenderer.h b/interface/src/voxels/PrimitiveRenderer.h deleted file mode 100644 index 06dac119b0..0000000000 --- a/interface/src/voxels/PrimitiveRenderer.h +++ /dev/null @@ -1,503 +0,0 @@ -// -// PrimitiveRenderer.h -// interface/src/voxels -// -// Created by Norman Craft. -// Copyright 2014 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -#ifndef hifi_PrimitiveRenderer_h -#define hifi_PrimitiveRenderer_h - -#include -#include -#include - -/// Vertex element structure. -/// Using the array of structures approach to specifying -/// vertex data to GL cuts down on the calls to glBufferSubData -/// -typedef - struct __VertexElement { - struct __position { - float x; - float y; - float z; - } position; - struct __normal { - float x; - float y; - float z; - } normal; - struct __color { - unsigned char r; - unsigned char g; - unsigned char b; - unsigned char a; - } color; - } VertexElement; - -/// Triangle element index structure. -/// Specify the vertex indices of the triangle and its element index. -/// -typedef - struct __TriElement { - int indices[3]; - int id; - - } TriElement; - -/// Vertex element list container. -/// -typedef QVector VertexElementList; - -/// Vertex element index list container. -/// -typedef QVector VertexElementIndexList; - -/// Triangle element list container -/// -typedef QVector TriElementList; - -/// -/// @class Primitive -/// Primitive Interface class. -/// Abstract class for accessing vertex and tri elements of geometric primitives -/// -/// -class Primitive { -public: - virtual ~Primitive(); - - // API methods go here - - /// Vertex element accessor. - /// @return A list of vertex elements of the primitive - /// - const VertexElementList& vertexElements() const; - - /// Vertex element index accessor. - /// @return A list of vertex element indices of the primitive - /// - VertexElementIndexList& vertexElementIndices(); - - /// Tri element accessor. - /// @return A list of tri elements of the primitive - /// - TriElementList& triElements(); - - /// Release vertex elements. - /// - void releaseVertexElements(); - - /// Get memory usage. - /// - unsigned long getMemoryUsage(); - -protected: - /// Default constructor prohibited to API user, restricted to service implementer. - /// - Primitive(); - -private: - /// Copy constructor prohibited. - /// - Primitive( - const Primitive& copy - ); - - // SPI methods are defined here - - /// Vertex element accessor. - /// Service implementer to provide private override for this method - /// in derived class - /// - virtual const VertexElementList& vVertexElements() const = 0; - - /// Vertex element index accessor. - /// Service implementer to provide private override for this method - /// in derived class - /// - virtual VertexElementIndexList& vVertexElementIndices() = 0; - - /// Tri element accessor. - /// Service implementer to provide private override for this method - /// in derived class - /// - virtual TriElementList& vTriElements() = 0; - - /// Release vertex elements. - /// Service implementer to provide private override for this method - /// in derived class - /// - virtual void vReleaseVertexElements() = 0; - - /// Get memory usage. - /// Service implementer to provide private override for this method - /// in derived class - /// - virtual unsigned long vGetMemoryUsage() = 0; - -}; - - -/// -/// @class Cube -/// Class for accessing the vertex and triangle elements of a cube -/// -class Cube: public Primitive { -public: - /// Configuration dependency injection constructor. - /// - Cube( - float x, ///< Cube location on X-axis - float y, ///< Cube location on Y-axis - float z, ///< Cube location on Z-axis - float s, ///< Cube size - unsigned char r, ///< Cube red color component - unsigned char g, ///< Cube green color component - unsigned char b, ///< Cube blue color component - unsigned char faces ///< Bitmask of faces of cube excluded from construction - ); - - ~Cube(); - -private: - /// Copy constructor prohibited. - /// - Cube ( - const Cube& cube - ); - - /// Cube initialization - /// - void init( - float x, ///< Cube location on X-axis - float y, ///< Cube location on Y-axis - float z, ///< Cube location on Z-axis - float s, ///< Cube size - unsigned char r, ///< Cube red color component - unsigned char g, ///< Cube green color component - unsigned char b, ///< Cube blue color component - unsigned char faceExclusions ///< Bitmask of faces of cube excluded from construction - ); - - /// Cube termination - /// - void terminate(); - - /// Initialize cube's vertex list - /// - void initializeVertices( - float x, ///< Cube location on X-axis - float y, ///< Cube location on Y-axis - float z, ///< Cube location on Z-axis - float s, ///< Cube size - unsigned char r, ///< Cube red color component - unsigned char g, ///< Cube green color component - unsigned char b, ///< Cube blue color component - unsigned char faceExclusions ///< Bitmask of faces of cube excluded from construction - ); - - /// Terminate cube's vertex list - /// - void terminateVertices(); - - /// Initialize cube's triangle list - /// - void initializeTris( - unsigned char faceExclusions - ); - - /// Terminate cube's triangle list - /// - void terminateTris(); - - // SPI virtual override methods go here - - const VertexElementList& vVertexElements() const; - VertexElementIndexList& vVertexElementIndices(); - TriElementList& vTriElements(); - void vReleaseVertexElements(); - unsigned long vGetMemoryUsage(); - -private: - VertexElementList _vertices; ///< Vertex element list - VertexElementIndexList _vertexIndices; ///< Vertex element index list - TriElementList _tris; ///< Tri element list - - unsigned long _cpuMemoryUsage; ///< Memory allocation of object - - static const int _sNumFacesPerCube = 6; ///< Number of faces per cube - static const int _sNumVerticesPerCube = 24; ///< Number of vertices per cube - static unsigned char _sFaceIndexToHalfSpaceMask[6]; ///< index to bitmask map - static float _sVertexIndexToConstructionVector[24][3]; ///< Vertex index to construction vector map - static float _sVertexIndexToNormalVector[6][3]; ///< Vertex index to normal vector map - -}; - - -/// -/// @class Renderer -/// GL renderer interface class. -/// Abstract class for rendering geometric primitives in GL -/// -class Renderer { -public: - virtual ~Renderer(); - - // API methods go here - - /// Add primitive to renderer database. - /// - int add( - Primitive* primitive ///< Primitive instance to be added - ); - - /// Remove primitive from renderer database. - /// - void remove( - int id ///< Primitive id to be removed - ); - - /// Clear all primitives from renderer database - /// - void release(); - - /// Render primitive database. - /// The render method assumes appropriate GL context and state has - /// already been provided for - /// - void render(); - - /// Get memory usage. - /// - unsigned long getMemoryUsage(); - - /// Get GPU memory usage. - /// - unsigned long getMemoryUsageGPU(); - -protected: - /// Default constructor prohibited to API user, restricted to service implementer. - /// - Renderer(); - -private: - /// Copy constructor prohibited. - /// - Renderer( - const Renderer& copy - ); - - // SPI methods are defined here - - /// Add primitive to renderer database. - /// Service implementer to provide private override for this method - /// in derived class - /// @return Primitive id - /// - virtual int vAdd( - Primitive* primitive ///< Primitive instance to be added - ) = 0; - - /// Remove primitive from renderer database. - /// Service implementer to provide private override for this method - /// in derived class - /// - virtual void vRemove( - int id ///< Primitive id - ) = 0; - - /// Clear all primitives from renderer database - /// Service implementer to provide private override for this method - /// in derived class - /// - virtual void vRelease() = 0; - - /// Render primitive database. - /// Service implementer to provide private virtual override for this method - /// in derived class - /// - virtual void vRender() = 0; - - /// Get memory usage. - /// - virtual unsigned long vGetMemoryUsage() = 0; - - /// Get GPU memory usage. - /// - virtual unsigned long vGetMemoryUsageGPU() = 0; - -}; - -/// -/// @class PrimitiveRenderer -/// Renderer implementation class for the rendering of geometric primitives -/// using GL element array and GL array buffers -/// -class PrimitiveRenderer : public Renderer { -public: - /// Configuration dependency injection constructor. - /// - PrimitiveRenderer( - int maxCount ///< Max count - ); - - ~PrimitiveRenderer(); - -private: - /// Default constructor prohibited. - /// - PrimitiveRenderer(); - - /// Copy constructor prohibited. - /// - PrimitiveRenderer( - const PrimitiveRenderer& renderer - ); - - void init(); - void terminate(); - - /// Allocate and initialize GL buffers. - /// - void initializeGL(); - - /// Terminate and deallocate GL buffers. - /// - void terminateGL(); - - void initializeBookkeeping(); - void terminateBookkeeping(); - - /// Construct the elements of the faces of the primitive. - /// - void constructElements( - Primitive* primitive ///< Primitive instance - ); - - /// Deconstruct the elements of the faces of the primitive. - /// - void deconstructElements( - Primitive* primitive ///< Primitive instance - ); - - /// Deconstruct the triangle element from the GL buffer. - /// - void deconstructTriElement( - int idx ///< Triangle element index - ); - - /// Deconstruct the vertex element from the GL buffer. - /// - void deconstructVertexElement( - int idx ///< Vertex element index - ); - - /// Transfer the vertex element to the GL buffer. - /// - void transferVertexElement( - int idx, ///< Vertex element index - VertexElement *vertex ///< Vertex element instance - ); - - /// Transfer the triangle element to the GL buffer. - /// - void transferTriElement( - int idx, ///< Triangle element index - int tri[3] ///< Triangle element data - ); - - /// Get available primitive index. - /// Get an available primitive index from either the recycling - /// queue or incrementing the counter - /// - int getAvailablePrimitiveIndex(); - - /// Get available vertex element index. - /// Get an available vertex element index from either the recycling - /// queue or incrementing the counter - /// - int getAvailableVertexElementIndex(); - - /// Get available triangle element index. - /// Get an available triangle element index from either the elements - /// scheduled for deconstruction queue, the recycling - /// queue or incrementing the counter - /// - int getAvailableTriElementIndex(); - - // SPI virtual override methods go here - - /// Add primitive to renderer database. - /// - int vAdd( - Primitive* primitive ///< Primitive instance to be added - ); - - /// Remove primitive from renderer database. - /// - void vRemove( - int id ///< Primitive id to be removed - ); - - /// Clear all primitives from renderer database - /// - void vRelease(); - - /// Render triangle database. - /// - void vRender(); - - /// Get memory usage. - /// - unsigned long vGetMemoryUsage(); - - /// Get gpu memory usage. - /// - unsigned long vGetMemoryUsageGPU(); - -private: - - int _maxCount; ///< Maximum count of tris - - // GL related parameters - - GLuint _triBufferId; ///< GL element array buffer id - GLuint _vertexBufferId; ///< GL vertex array buffer id - - // Book keeping parameters - - int _vertexElementCount; ///< Count of vertices - int _maxVertexElementCount; ///< Max count of vertices - - int _triElementCount; ///< Count of triangles - int _maxTriElementCount; ///< Max count of triangles - - QVector _primitives; ///< Vector of primitive - int _primitiveCount; ///< Count of primitives - - QStack _availablePrimitiveIndex; ///< Queue of primitive indices available - QStack _availableVertexElementIndex; ///< Queue of vertex element indices available - QStack _availableTriElementIndex; ///< Queue of triangle element indices available - QStack _deconstructTriElementIndex; ///< Queue of triangle element indices requiring deletion from GL - QStack _constructPrimitiveIndex; ///< Queue of primitives requiring addition to GL - - QMutex _guard; - - // Statistics parameters, not necessary for proper operation - - unsigned long _gpuMemoryUsage; ///< GPU memory used by this instance - unsigned long _cpuMemoryUsage; ///< CPU memory used by this instance - - - static const int _sIndicesPerTri = 3; - static const int _sBytesPerTriElement = sizeof(GLint) * _sIndicesPerTri; -}; - - -#endif // hifi_PrimitiveRenderer_h diff --git a/interface/src/voxels/VoxelSystem.cpp b/interface/src/voxels/VoxelSystem.cpp index 8fbaf65f37..2f4fd3f0fa 100644 --- a/interface/src/voxels/VoxelSystem.cpp +++ b/interface/src/voxels/VoxelSystem.cpp @@ -68,10 +68,6 @@ VoxelSystem::VoxelSystem(float treeScale, int maxVoxels, VoxelTree* tree) _initialized(false), _writeArraysLock(QReadWriteLock::Recursive), _readArraysLock(QReadWriteLock::Recursive), - _inOcclusions(false), - _showCulledSharedFaces(false), - _usePrimitiveRenderer(false), - _renderer(0), _drawHaze(false), _farHazeDistance(300.0f), _hazeColor(grayColor) @@ -112,7 +108,7 @@ VoxelSystem::VoxelSystem(float treeScale, int maxVoxels, VoxelTree* tree) void VoxelSystem::elementDeleted(OctreeElement* element) { VoxelTreeElement* voxel = (VoxelTreeElement*)element; if (voxel->getVoxelSystem() == this) { - if ((_voxelsInWriteArrays != 0) || _usePrimitiveRenderer) { + if ((_voxelsInWriteArrays != 0)) { forceRemoveNodeFromArrays(voxel); } else { if (Menu::getInstance()->isOptionChecked(MenuOption::PipelineWarnings)) { @@ -288,9 +284,6 @@ void VoxelSystem::cleanupVoxelMemory() { _readColorsArray = NULL; _writeColorsArray = NULL; - delete _renderer; - _renderer = 0; - delete[] _writeVoxelDirtyArray; delete[] _readVoxelDirtyArray; _writeVoxelDirtyArray = _readVoxelDirtyArray = NULL; @@ -384,8 +377,6 @@ void VoxelSystem::initVoxelMemory() { Application::resourcesPath() + "shaders/voxel.frag"); _program.link(); } - _renderer = new PrimitiveRenderer(_maxVoxels); - _initialized = true; _writeArraysLock.unlock(); @@ -511,10 +502,6 @@ void VoxelSystem::setupNewVoxelsForDrawing() { _callsToTreesToArrays++; if (_writeRenderFullVBO) { - if (_usePrimitiveRenderer) { - _renderer->release(); - clearAllNodesBufferIndex(); - } clearFreeBufferIndexes(); } _voxelsUpdated = newTreeToArrays(_tree->getRoot()); @@ -525,24 +512,17 @@ void VoxelSystem::setupNewVoxelsForDrawing() { _voxelsUpdated = 0; } - if (_usePrimitiveRenderer) { - if (_voxelsUpdated) { - _voxelsDirty=true; - } - } else { - // lock on the buffer write lock so we can't modify the data when the GPU is reading it - _readArraysLock.lockForWrite(); - - if (_voxelsUpdated) { - _voxelsDirty=true; - } - - // copy the newly written data to the arrays designated for reading, only does something if _voxelsDirty && _voxelsUpdated - copyWrittenDataToReadArrays(didWriteFullVBO); - _readArraysLock.unlock(); + // lock on the buffer write lock so we can't modify the data when the GPU is reading it + _readArraysLock.lockForWrite(); + if (_voxelsUpdated) { + _voxelsDirty=true; } + // copy the newly written data to the arrays designated for reading, only does something if _voxelsDirty && _voxelsUpdated + copyWrittenDataToReadArrays(didWriteFullVBO); + _readArraysLock.unlock(); + quint64 end = usecTimestampNow(); int elapsedmsec = (end - start) / 1000; _setupNewVoxelsForDrawingLastFinished = end; @@ -569,26 +549,22 @@ void VoxelSystem::setupNewVoxelsForDrawingSingleNode(bool allowBailEarly) { return; // bail early, it hasn't been long enough since the last time we ran } - if (_usePrimitiveRenderer) { - _voxelsDirty = true; // if we got this far, then we can assume some voxels are dirty - _voxelsUpdated = 0; - } else { - // lock on the buffer write lock so we can't modify the data when the GPU is reading it - { - PerformanceWarning warn(Menu::getInstance()->isOptionChecked(MenuOption::PipelineWarnings), - "setupNewVoxelsForDrawingSingleNode()... _bufferWriteLock.lock();" ); - _readArraysLock.lockForWrite(); - } - - _voxelsDirty = true; // if we got this far, then we can assume some voxels are dirty - - // copy the newly written data to the arrays designated for reading, only does something if _voxelsDirty && _voxelsUpdated - copyWrittenDataToReadArrays(_writeRenderFullVBO); - - // after... - _voxelsUpdated = 0; - _readArraysLock.unlock(); + // lock on the buffer write lock so we can't modify the data when the GPU is reading it + { + PerformanceWarning warn(Menu::getInstance()->isOptionChecked(MenuOption::PipelineWarnings), + "setupNewVoxelsForDrawingSingleNode()... _bufferWriteLock.lock();" ); + _readArraysLock.lockForWrite(); } + + _voxelsDirty = true; // if we got this far, then we can assume some voxels are dirty + + // copy the newly written data to the arrays designated for reading, only does something if _voxelsDirty && _voxelsUpdated + copyWrittenDataToReadArrays(_writeRenderFullVBO); + + // after... + _voxelsUpdated = 0; + _readArraysLock.unlock(); + quint64 end = usecTimestampNow(); int elapsedmsec = (end - start) / 1000; _setupNewVoxelsForDrawingLastFinished = end; @@ -862,22 +838,13 @@ int VoxelSystem::forceRemoveNodeFromArrays(VoxelTreeElement* node) { return 0; } - if (_usePrimitiveRenderer) { - if (node->isKnownBufferIndex()) { - int primitiveIndex = node->getBufferIndex(); - _renderer->remove(primitiveIndex); - node->setBufferIndex(GLBUFFER_INDEX_UNKNOWN); - return 1; - } - } else { - // if the node is not in the VBOs then we have nothing to do! - if (node->isKnownBufferIndex()) { - // If this node has not yet been written to the array, then add it to the end of the array. - glBufferIndex nodeIndex = node->getBufferIndex(); - node->setBufferIndex(GLBUFFER_INDEX_UNKNOWN); - freeBufferIndex(nodeIndex); // NOTE: This will make the node invisible! - return 1; // updated! - } + // if the node is not in the VBOs then we have nothing to do! + if (node->isKnownBufferIndex()) { + // If this node has not yet been written to the array, then add it to the end of the array. + glBufferIndex nodeIndex = node->getBufferIndex(); + node->setBufferIndex(GLBUFFER_INDEX_UNKNOWN); + freeBufferIndex(nodeIndex); // NOTE: This will make the node invisible! + return 1; // updated! } return 0; // not-updated } @@ -909,43 +876,17 @@ int VoxelSystem::updateNodeInArrays(VoxelTreeElement* node, bool reuseIndex, boo float voxelScale = node->getScale(); nodeColor const & color = node->getColor(); - if (_usePrimitiveRenderer) { - if (node->isKnownBufferIndex()) { - int primitiveIndex = node->getBufferIndex(); - _renderer->remove(primitiveIndex); - node->setBufferIndex(GLBUFFER_INDEX_UNKNOWN); - } else { - node->setVoxelSystem(this); - } - unsigned char occlusions; - if (_showCulledSharedFaces) { - occlusions = ~node->getInteriorOcclusions(); - } else { - occlusions = node->getInteriorOcclusions(); - } - if (occlusions != OctreeElement::HalfSpace::All) { - Cube* cube = new Cube( - startVertex.x, startVertex.y, startVertex.z, voxelScale, - color[RED_INDEX], color[GREEN_INDEX], color[BLUE_INDEX], - occlusions); - if (cube) { - int primitiveIndex = _renderer->add(cube); - node->setBufferIndex(primitiveIndex); - } - } + glBufferIndex nodeIndex = GLBUFFER_INDEX_UNKNOWN; + if (reuseIndex && node->isKnownBufferIndex()) { + nodeIndex = node->getBufferIndex(); } else { - glBufferIndex nodeIndex = GLBUFFER_INDEX_UNKNOWN; - if (reuseIndex && node->isKnownBufferIndex()) { - nodeIndex = node->getBufferIndex(); - } else { - nodeIndex = getNextBufferIndex(); - node->setBufferIndex(nodeIndex); - node->setVoxelSystem(this); - } - - // populate the array with points for the 8 vertices and RGB color for each added vertex - updateArraysDetails(nodeIndex, startVertex, voxelScale, node->getColor()); + nodeIndex = getNextBufferIndex(); + node->setBufferIndex(nodeIndex); + node->setVoxelSystem(this); } + + // populate the array with points for the 8 vertices and RGB color for each added vertex + updateArraysDetails(nodeIndex, startVertex, voxelScale, node->getColor()); return 1; // updated! } else { // If we shouldn't render, and we're in reuseIndex mode, then free our index, this only operates @@ -1072,24 +1013,22 @@ void VoxelSystem::updateVBOs() { }; // would like to include _callsToTreesToArrays PerformanceWarning warn(Menu::getInstance()->isOptionChecked(MenuOption::PipelineWarnings), buffer); - if (! _usePrimitiveRenderer) { - if (_voxelsDirty) { - - // attempt to lock the read arrays, to for copying from them to the actual GPU VBOs. - // if we fail to get the lock, that's ok, our VBOs will update on the next frame... - const int WAIT_FOR_LOCK_IN_MS = 5; - if (_readArraysLock.tryLockForRead(WAIT_FOR_LOCK_IN_MS)) { - if (_readRenderFullVBO) { - updateFullVBOs(); - } else { - updatePartialVBOs(); - } - _voxelsDirty = false; - _readRenderFullVBO = false; - _readArraysLock.unlock(); + if (_voxelsDirty) { + + // attempt to lock the read arrays, to for copying from them to the actual GPU VBOs. + // if we fail to get the lock, that's ok, our VBOs will update on the next frame... + const int WAIT_FOR_LOCK_IN_MS = 5; + if (_readArraysLock.tryLockForRead(WAIT_FOR_LOCK_IN_MS)) { + if (_readRenderFullVBO) { + updateFullVBOs(); } else { - qDebug() << "updateVBOs().... couldn't get _readArraysLock.tryLockForRead()"; + updatePartialVBOs(); } + _voxelsDirty = false; + _readRenderFullVBO = false; + _readArraysLock.unlock(); + } else { + qDebug() << "updateVBOs().... couldn't get _readArraysLock.tryLockForRead()"; } } _callsToTreesToArrays = 0; // clear it @@ -1143,11 +1082,11 @@ void VoxelSystem::render() { updateVBOs(); - if (!_usePrimitiveRenderer) { - if (_drawHaze) { - glEnable(GL_FOG); - } + if (_drawHaze) { + glEnable(GL_FOG); + } + { PerformanceWarning warn(showWarnings, "render().. TRIANGLES..."); { @@ -1223,16 +1162,10 @@ void VoxelSystem::render() { glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } - - if (_drawHaze) { - glDisable(GL_FOG); - } } - else { - applyScaleAndBindProgram(texture); - _renderer->render(); - removeScaleAndReleaseProgram(texture); - + + if (_drawHaze) { + glDisable(GL_FOG); } } @@ -1275,12 +1208,6 @@ void VoxelSystem::killLocalVoxels() { _tree->getRoot()->setVoxelSystem(voxelSystem); _tree->unlock(); clearFreeBufferIndexes(); - if (_usePrimitiveRenderer) { - if (_renderer) { - _renderer->release(); - } - clearAllNodesBufferIndex(); - } _voxelsInReadArrays = 0; // do we need to do this? setupNewVoxelsForDrawing(); } @@ -1308,178 +1235,6 @@ void VoxelSystem::clearAllNodesBufferIndex() { } } -bool VoxelSystem::inspectForInteriorOcclusionsOperation(OctreeElement* element, void* extraData) { - _nodeCount++; - VoxelTreeElement* voxel = (VoxelTreeElement*)element; - - // Nothing to do at the leaf level - if (voxel->isLeaf()) { - return false; - } - - // Bit mask of occluded shared faces indexed by child - unsigned char occludedSharedFace[NUMBER_OF_CHILDREN] = { 0, 0, 0, 0, 0, 0, 0, 0 }; - - // Traverse all pair combinations of children - for (int i = NUMBER_OF_CHILDREN; --i >= 0; ) { - - VoxelTreeElement* childA = voxel->getChildAtIndex(i); - if (childA) { - - // Get the child A's occluding faces, for a leaf that will be - // all six voxel faces, and for a non leaf, that will be - // all faces which are completely covered by four child octants. - unsigned char exteriorOcclusionsA = childA->getExteriorOcclusions(); - - for (int j = i; --j >= 0; ) { - - VoxelTreeElement* childB = voxel->getChildAtIndex(j); - if (childB) { - - // Get child B's occluding faces - unsigned char exteriorOcclusionsB = childB->getExteriorOcclusions(); - - // Determine the shared halfspace partition between siblings A and B, - // i.e., near/far, left/right, or top/bottom - unsigned char partitionA = _sOctantIndexToSharedBitMask[i][j] & - exteriorOcclusionsA; - unsigned char partitionB = _sOctantIndexToSharedBitMask[i][j] & - exteriorOcclusionsB; - - // Determine which face of each sibling is occluded. - - // The _sOctantIndexToBitMask is a partition occupancy mask. For - // example, if the near-left-top (NLT) and near-left-bottom (NLB) child voxels - // exist, the shared partition is top-bottom (TB), and thus the occluded - // shared face of the NLT voxel is its bottom face. - occludedSharedFace[i] |= (partitionB & _sOctantIndexToBitMask[i]); - occludedSharedFace[j] |= (partitionA & _sOctantIndexToBitMask[j]); - } - } - // Exchange bit pairs, left to right, vice versa, etc. - occludedSharedFace[i] = _sSwizzledOcclusionBits[occludedSharedFace[i]]; - // Combine this voxel's interior excluded shared face only to those children which are coincident - // with the excluded face. - occludedSharedFace[i] |= (voxel->getInteriorOcclusions() & _sOctantIndexToBitMask[i]); - - // Inform the child - childA->setInteriorOcclusions(occludedSharedFace[i]); - if (occludedSharedFace[i] != OctreeElement::HalfSpace::None) { - //const glm::vec3& v = voxel->getCorner(); - //float s = voxel->getScale(); - - //qDebug("Child %d of voxel at %f %f %f size: %f has %02x occlusions", i, v.x, v.y, v.z, s, occludedSharedFace[i]); - } - } - } - return true; -} - -bool VoxelSystem::inspectForExteriorOcclusionsOperation(OctreeElement* element, void* extraData) { - _nodeCount++; - VoxelTreeElement* voxel = (VoxelTreeElement*)element; - - // Nothing to do at the leaf level - if (voxel->isLeaf()) { - // By definition the the exterior faces of a leaf voxel are - // always occluders. - voxel->setExteriorOcclusions(OctreeElement::HalfSpace::All); - // And the sibling occluders - voxel->setInteriorOcclusions(OctreeElement::HalfSpace::None); - return false; - } else { - voxel->setExteriorOcclusions(OctreeElement::HalfSpace::None); - voxel->setInteriorOcclusions(OctreeElement::HalfSpace::None); - } - - // Count of exterior occluding faces of this voxel element indexed - // by half space partition - unsigned int exteriorOcclusionsCt[6] = { 0, 0, 0, 0, 0, 0 }; - - // Traverse all children - for (int i = NUMBER_OF_CHILDREN; --i >= 0; ) { - - VoxelTreeElement* child = voxel->getChildAtIndex(i); - if (child) { - - // Get the child's occluding faces, for a leaf, that will be - // all six voxel faces, and for a non leaf, that will be - // all faces which are completely covered by four child octants. - unsigned char exteriorOcclusionsOfChild = child->getExteriorOcclusions(); - exteriorOcclusionsOfChild &= _sOctantIndexToBitMask[i]; - - for (int j = 6; --j >= 0; ) { - - // Determine if the halfspace partition indexed by 1 << j is - // present in the exterior occlusions of the child. - unsigned char partition = exteriorOcclusionsOfChild & (1 << j); - - if (partition) { - exteriorOcclusionsCt[j]++; - } - } - } - } - { - // Derive the exterior occlusions of the voxel elements from the exclusions - // of its children - unsigned char exteriorOcclusions = OctreeElement::HalfSpace::None; - for (int i = 6; --i >= 0; ) { - if (exteriorOcclusionsCt[i] == _sNumOctantsPerHemiVoxel) { - - // Exactly four octants qualify for full exterior occlusion - exteriorOcclusions |= (1 << i); - } - } - - // Inform the voxel element - voxel->setExteriorOcclusions(exteriorOcclusions); - - if (exteriorOcclusions == OctreeElement::HalfSpace::All) { - //const glm::vec3& v = voxel->getCorner(); - //float s = voxel->getScale(); - - //qDebug("Completely occupied voxel at %f %f %f size: %f", v.x, v.y, v.z, s); - - // All of the exterior faces of this voxel element are - // occluders, which means that this element is completely - // occupied. Hence, the subtree from this node could be - // pruned and replaced by a leaf voxel, if the visible - // properties of the children are the same - - } else if (exteriorOcclusions != OctreeElement::HalfSpace::None) { - //const glm::vec3& v = voxel->getCorner(); - //float s = voxel->getScale(); - - //qDebug("Partially occupied voxel at %f %f %f size: %f with %02x", v.x, v.y, v.z, s, exteriorOcclusions); - } - } - return true; -} - -void VoxelSystem::inspectForOcclusions() { - - if (_inOcclusions) { - return; - } - _inOcclusions = true; - _nodeCount = 0; - - bool showDebugDetails = Menu::getInstance()->isOptionChecked(MenuOption::PipelineWarnings); - PerformanceWarning warn(showDebugDetails, "inspectForOcclusions()"); - - _tree->lockForRead(); - _tree->recurseTreeWithPostOperation(inspectForExteriorOcclusionsOperation); - _nodeCount = 0; - _tree->recurseTreeWithOperation(inspectForInteriorOcclusionsOperation); - _tree->unlock(); - - if (showDebugDetails) { - qDebug("inspecting all occlusions of %d nodes", _nodeCount); - } - _inOcclusions = false; -} - bool VoxelSystem::forceRedrawEntireTreeOperation(OctreeElement* element, void* extraData) { _nodeCount++; element->setDirtyBit(); @@ -1904,170 +1659,3 @@ void VoxelSystem::bindPerlinModulateProgram() { } } -// Swizzle value of bit pairs of the value of index -unsigned short VoxelSystem::_sSwizzledOcclusionBits[64] = { - 0x0000, // 00000000 - 0x0002, // 00000001 - 0x0001, // 00000010 - 0x0003, // 00000011 - 0x0008, // 00000100 - 0x000a, // 00000101 - 0x0009, // 00000110 - 0x000b, // 00000111 - 0x0004, // 00001000 - 0x0006, // 00001001 - 0x0005, // 00001010 - 0x0007, // 00001011 - 0x000c, // 00001100 - 0x000e, // 00001101 - 0x000d, // 00001110 - 0x000f, // 00001111 - 0x0020, // 00010000 - 0x0022, // 00010001 - 0x0021, // 00010010 - 0x0023, // 00010011 - 0x0028, // 00010100 - 0x002a, // 00010101 - 0x0029, // 00010110 - 0x002b, // 00010111 - 0x0024, // 00011000 - 0x0026, // 00011001 - 0x0025, // 00011010 - 0x0027, // 00011011 - 0x002c, // 00011100 - 0x002e, // 00011101 - 0x002d, // 00011110 - 0x002f, // 00011111 - 0x0010, // 00100000 - 0x0012, // 00100001 - 0x0011, // 00100010 - 0x0013, // 00100011 - 0x0018, // 00100100 - 0x001a, // 00100101 - 0x0019, // 00100110 - 0x001b, // 00100111 - 0x0014, // 00101000 - 0x0016, // 00101001 - 0x0015, // 00101010 - 0x0017, // 00101011 - 0x001c, // 00101100 - 0x001e, // 00101101 - 0x001d, // 00101110 - 0x001f, // 00101111 - 0x0030, // 00110000 - 0x0032, // 00110001 - 0x0031, // 00110010 - 0x0033, // 00110011 - 0x0038, // 00110100 - 0x003a, // 00110101 - 0x0039, // 00110110 - 0x003b, // 00110111 - 0x0034, // 00111000 - 0x0036, // 00111001 - 0x0035, // 00111010 - 0x0037, // 00111011 - 0x003c, // 00111100 - 0x003e, // 00111101 - 0x003d, // 00111110 - 0x003f, // 00111111 -}; - -// Octant bitmask array indexed by octant. The mask value indicates the octant's halfspace partitioning. The index -// value corresponds to the voxel's octal code derived in "pointToVoxel" in SharedUtil.cpp, which, BTW, does *not* -// correspond to the "ChildIndex" enum value in OctreeElement.h -unsigned char VoxelSystem::_sOctantIndexToBitMask[8] = { - OctreeElement::HalfSpace::Bottom | OctreeElement::HalfSpace::Left | OctreeElement::HalfSpace::Near, - OctreeElement::HalfSpace::Bottom | OctreeElement::HalfSpace::Left | OctreeElement::HalfSpace::Far, - OctreeElement::HalfSpace::Top | OctreeElement::HalfSpace::Left | OctreeElement::HalfSpace::Near, - OctreeElement::HalfSpace::Top | OctreeElement::HalfSpace::Left | OctreeElement::HalfSpace::Far, - OctreeElement::HalfSpace::Bottom | OctreeElement::HalfSpace::Right | OctreeElement::HalfSpace::Near, - OctreeElement::HalfSpace::Bottom | OctreeElement::HalfSpace::Right | OctreeElement::HalfSpace::Far, - OctreeElement::HalfSpace::Top | OctreeElement::HalfSpace::Right | OctreeElement::HalfSpace::Near, - OctreeElement::HalfSpace::Top | OctreeElement::HalfSpace::Right | OctreeElement::HalfSpace::Far, -}; - -// Two dimensional array map indexed by octant row and column. The mask value -// indicates the two faces shared by the octants -unsigned char VoxelSystem::_sOctantIndexToSharedBitMask[8][8] = { - { // Index 0: Bottom-Left-Near - 0, // Bottom-Left-Near - OctreeElement::HalfSpace::Near | OctreeElement::HalfSpace::Far, // Bottom-Left-Far - OctreeElement::HalfSpace::Bottom | OctreeElement::HalfSpace::Top, // Top-Left-Near - 0, // Top-Left-Far - OctreeElement::HalfSpace::Right | OctreeElement::HalfSpace::Left, // Bottom-Right-Near - 0, // Bottom-Right-Far - 0, // Top-Right-Near - 0, // Top-Right-Far - }, - { // Index 1: Bottom-Left-Far - OctreeElement::HalfSpace::Near | OctreeElement::HalfSpace::Far, // Bottom-Left-Near - 0, // Bottom-Left-Far - 0, // Top-Left-Near - OctreeElement::HalfSpace::Bottom | OctreeElement::HalfSpace::Top, // Top-Left-Far - 0, // Bottom-Right-Near - OctreeElement::HalfSpace::Right | OctreeElement::HalfSpace::Left, // Bottom-Right-Far - 0, // Top-Right-Near - 0, // Top-Right-Far - }, - { // Index 2: Top-Left-Near - OctreeElement::HalfSpace::Bottom | OctreeElement::HalfSpace::Top, // Bottom-Left-Near - 0, // Bottom-Left-Far - 0, // Top-Left-Near - OctreeElement::HalfSpace::Near | OctreeElement::HalfSpace::Far, // Top-Left-Far - 0, // Bottom-Right-Near - 0, // Bottom-Right-Far - OctreeElement::HalfSpace::Right | OctreeElement::HalfSpace::Left, // Top-Right-Near - 0, // Top-Right-Far - }, - { // Index 3: Top-Left-Far - 0, // Bottom-Left-Near - OctreeElement::HalfSpace::Bottom | OctreeElement::HalfSpace::Top, // Bottom-Left-Far - OctreeElement::HalfSpace::Near | OctreeElement::HalfSpace::Far, // Top-Left-Near - 0, // Top-Left-Far - 0, // Bottom-Right-Near - 0, // Bottom-Right-Far - 0, // Top-Right-Near - OctreeElement::HalfSpace::Right | OctreeElement::HalfSpace::Left, // Top-Right-Far - }, - { // Index 4: Bottom-Right-Near - OctreeElement::HalfSpace::Right | OctreeElement::HalfSpace::Left, // Bottom-Left-Near - 0, // Bottom-Left-Far - 0, // Top-Left-Near - 0, // Top-Left-Far - 0, // Bottom-Right-Near - OctreeElement::HalfSpace::Near | OctreeElement::HalfSpace::Far, // Bottom-Right-Far - OctreeElement::HalfSpace::Bottom | OctreeElement::HalfSpace::Top, // Top-Right-Near - 0, // Top-Right-Far - }, - { // Index 5: Bottom-Right-Far - 0, // Bottom-Left-Near - OctreeElement::HalfSpace::Right | OctreeElement::HalfSpace::Left, // Bottom-Left-Far - 0, // Top-Left-Near - 0, // Top-Left-Far - OctreeElement::HalfSpace::Near | OctreeElement::HalfSpace::Far, // Bottom-Right-Near - 0, // Bottom-Right-Far - 0, // Top-Right-Near - OctreeElement::HalfSpace::Bottom | OctreeElement::HalfSpace::Top, // Top-Right-Far - }, - { // Index 6: Top-Right-Near - 0, // Bottom-Left-Near - 0, // Bottom-Left-Far - OctreeElement::HalfSpace::Right | OctreeElement::HalfSpace::Left, // Top-Left-Near - 0, // Top-Left-Far - OctreeElement::HalfSpace::Bottom | OctreeElement::HalfSpace::Top, // Bottom-Right-Near - 0, // Bottom-Right-Far - 0, // Top-Right-Near - OctreeElement::HalfSpace::Near | OctreeElement::HalfSpace::Far, // Top-Right-Far - }, - { // Index 7: Top-Right-Far - 0, // Bottom-Left-Near - 0, // Bottom-Left-Far - 0, // Top-Left-Near - OctreeElement::HalfSpace::Right | OctreeElement::HalfSpace::Left, // Top-Left-Far - 0, // Bottom-Right-Near - OctreeElement::HalfSpace::Bottom | OctreeElement::HalfSpace::Top, // Bottom-Right-Far - OctreeElement::HalfSpace::Near | OctreeElement::HalfSpace::Far, // Top-Right-Near - 0, // Top-Right-Far - }, -}; - diff --git a/interface/src/voxels/VoxelSystem.h b/interface/src/voxels/VoxelSystem.h index 4f4c624e15..b6413a0f68 100644 --- a/interface/src/voxels/VoxelSystem.h +++ b/interface/src/voxels/VoxelSystem.h @@ -25,7 +25,6 @@ #include "Camera.h" #include "Util.h" #include "world.h" -#include "PrimitiveRenderer.h" class ProgramObject; @@ -71,7 +70,6 @@ public: void killLocalVoxels(); virtual void hideOutOfView(bool forceFullFrustum = false); - void inspectForOcclusions(); bool hasViewChanged(); bool isViewChanging(); @@ -129,8 +127,6 @@ private: static bool killSourceVoxelsOperation(OctreeElement* element, void* extraData); static bool forceRedrawEntireTreeOperation(OctreeElement* element, void* extraData); static bool clearAllNodesBufferIndexOperation(OctreeElement* element, void* extraData); - static bool inspectForExteriorOcclusionsOperation(OctreeElement* element, void* extraData); - static bool inspectForInteriorOcclusionsOperation(OctreeElement* element, void* extraData); static bool hideOutOfViewOperation(OctreeElement* element, void* extraData); static bool hideAllSubTreeOperation(OctreeElement* element, void* extraData); static bool showAllSubTreeOperation(OctreeElement* element, void* extraData); @@ -241,17 +237,6 @@ private: float _lastKnownVoxelSizeScale; int _lastKnownBoundaryLevelAdjust; - bool _inOcclusions; - bool _showCulledSharedFaces; ///< Flag visibility of culled faces - bool _usePrimitiveRenderer; ///< Flag primitive renderer for use - PrimitiveRenderer* _renderer; ///< Voxel renderer - - static const unsigned int _sNumOctantsPerHemiVoxel = 4; - static int _sCorrectedChildIndex[8]; - static unsigned short _sSwizzledOcclusionBits[64]; ///< Swizzle value of bit pairs of the value of index - static unsigned char _sOctantIndexToBitMask[8]; ///< Map octant index to partition mask - static unsigned char _sOctantIndexToSharedBitMask[8][8]; ///< Map octant indices to shared partition mask - // haze bool _drawHaze; float _farHazeDistance; From 7611354df67ce4bed4f164c24687a2cef50c526f Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Thu, 11 Dec 2014 14:43:58 -0800 Subject: [PATCH 041/258] Fix for normal maps on skinned models. --- interface/src/renderer/Model.cpp | 133 ++++++++----------------------- interface/src/renderer/Model.h | 4 +- 2 files changed, 35 insertions(+), 102 deletions(-) diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index 71f5129a1e..fd54f67377 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -134,38 +134,21 @@ void Model::setOffset(const glm::vec3& offset) { _snappedToRegistrationPoint = false; } -void Model::initProgram(ProgramObject& program, Model::Locations& locations, int specularTextureUnit) { +void Model::initProgram(ProgramObject& program, Model::Locations& locations, bool link) { + if (link) { + program.bindAttributeLocation("tangent", gpu::Stream::TANGENT); + program.bindAttributeLocation("texcoord1", gpu::Stream::TEXCOORD1); + program.link(); + } program.bind(); -#ifdef Q_OS_MAC - - // HACK: Assign explicitely the attribute channel to avoid a bug on Yosemite - - glBindAttribLocation(program.programId(), 4, "tangent"); - - glLinkProgram(program.programId()); - -#endif - - - - glBindAttribLocation(program.programId(), gpu::Stream::TANGENT, "tangent"); - - glBindAttribLocation(program.programId(), gpu::Stream::TEXCOORD1, "texcoord1"); - - glLinkProgram(program.programId()); - locations.tangent = program.attributeLocation("tangent"); locations.alphaThreshold = program.uniformLocation("alphaThreshold"); - locations.texcoordMatrices = program.uniformLocation("texcoordMatrices"); - locations.emissiveParams = program.uniformLocation("emissiveParams"); - program.setUniformValue("diffuseMap", 0); - program.setUniformValue("normalMap", 1); int loc = program.uniformLocation("specularMap"); @@ -184,50 +167,22 @@ void Model::initProgram(ProgramObject& program, Model::Locations& locations, int locations.emissiveTextureUnit = -1; } - if (!program.isLinked()) { - program.release(); - } - program.release(); - } - - -void Model::initSkinProgram(ProgramObject& program, Model::SkinLocations& locations, int specularTextureUnit) { - - initProgram(program, locations, specularTextureUnit); - - - -#ifdef Q_OS_MAC - - // HACK: Assign explicitely the attribute channel to avoid a bug on Yosemite - - glBindAttribLocation(program.programId(), 5, "clusterIndices"); - - glBindAttribLocation(program.programId(), 6, "clusterWeights"); - - glLinkProgram(program.programId()); - -#endif - - // HACK: Assign explicitely the attribute channel to avoid a bug on Yosemite - - glBindAttribLocation(program.programId(), gpu::Stream::SKIN_CLUSTER_INDEX, "clusterIndices"); - - glBindAttribLocation(program.programId(), gpu::Stream::SKIN_CLUSTER_WEIGHT, "clusterWeights"); - - glLinkProgram(program.programId()); +void Model::initSkinProgram(ProgramObject& program, Model::SkinLocations& locations) { + program.bindAttributeLocation("tangent", gpu::Stream::TANGENT); + program.bindAttributeLocation("texcoord1", gpu::Stream::TEXCOORD1); + program.bindAttributeLocation("clusterIndices", gpu::Stream::SKIN_CLUSTER_INDEX); + program.bindAttributeLocation("clusterWeights", gpu::Stream::SKIN_CLUSTER_WEIGHT); + program.link(); + + initProgram(program, locations, false); program.bind(); - locations.clusterMatrices = program.uniformLocation("clusterMatrices"); - - - + locations.clusterMatrices = program.uniformLocation("clusterMatrices"); locations.clusterIndices = program.attributeLocation("clusterIndices"); - locations.clusterWeights = program.attributeLocation("clusterWeights"); program.release(); @@ -269,7 +224,6 @@ void Model::init() { if (!_program.isLinked()) { _program.addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + "shaders/model.vert"); _program.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + "shaders/model.frag"); - _program.link(); initProgram(_program, _locations); @@ -277,116 +231,101 @@ void Model::init() { Application::resourcesPath() + "shaders/model_normal_map.vert"); _normalMapProgram.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + "shaders/model_normal_map.frag"); - _normalMapProgram.link(); - + initProgram(_normalMapProgram, _normalMapLocations); _specularMapProgram.addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + "shaders/model.vert"); _specularMapProgram.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + "shaders/model_specular_map.frag"); - _specularMapProgram.link(); - + initProgram(_specularMapProgram, _specularMapLocations); _normalSpecularMapProgram.addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + "shaders/model_normal_map.vert"); _normalSpecularMapProgram.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + "shaders/model_normal_specular_map.frag"); - _normalSpecularMapProgram.link(); - - initProgram(_normalSpecularMapProgram, _normalSpecularMapLocations, 2); + + initProgram(_normalSpecularMapProgram, _normalSpecularMapLocations); _translucentProgram.addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + "shaders/model.vert"); _translucentProgram.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + "shaders/model_translucent.frag"); - _translucentProgram.link(); - + initProgram(_translucentProgram, _translucentLocations); // Lightmap _lightmapProgram.addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + "shaders/model_lightmap.vert"); _lightmapProgram.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + "shaders/model_lightmap.frag"); - _lightmapProgram.link(); - + initProgram(_lightmapProgram, _lightmapLocations); _lightmapNormalMapProgram.addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + "shaders/model_lightmap_normal_map.vert"); _lightmapNormalMapProgram.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + "shaders/model_lightmap_normal_map.frag"); - _lightmapNormalMapProgram.link(); - + initProgram(_lightmapNormalMapProgram, _lightmapNormalMapLocations); _lightmapSpecularMapProgram.addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + "shaders/model_lightmap.vert"); _lightmapSpecularMapProgram.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + "shaders/model_lightmap_specular_map.frag"); - _lightmapSpecularMapProgram.link(); - + initProgram(_lightmapSpecularMapProgram, _lightmapSpecularMapLocations); _lightmapNormalSpecularMapProgram.addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + "shaders/model_lightmap_normal_map.vert"); _lightmapNormalSpecularMapProgram.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + "shaders/model_lightmap_normal_specular_map.frag"); - _lightmapNormalSpecularMapProgram.link(); - - initProgram(_lightmapNormalSpecularMapProgram, _lightmapNormalSpecularMapLocations, 2); + + initProgram(_lightmapNormalSpecularMapProgram, _lightmapNormalSpecularMapLocations); // end lightmap _shadowProgram.addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + "shaders/model_shadow.vert"); _shadowProgram.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + "shaders/model_shadow.frag"); - _shadowProgram.link(); - + _skinProgram.addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + "shaders/skin_model.vert"); _skinProgram.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + "shaders/model.frag"); - _skinProgram.link(); - + initSkinProgram(_skinProgram, _skinLocations); _skinNormalMapProgram.addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + "shaders/skin_model_normal_map.vert"); _skinNormalMapProgram.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + "shaders/model_normal_map.frag"); - _skinNormalMapProgram.link(); - + initSkinProgram(_skinNormalMapProgram, _skinNormalMapLocations); _skinSpecularMapProgram.addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + "shaders/skin_model.vert"); _skinSpecularMapProgram.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + "shaders/model_specular_map.frag"); - _skinSpecularMapProgram.link(); - + initSkinProgram(_skinSpecularMapProgram, _skinSpecularMapLocations); _skinNormalSpecularMapProgram.addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + "shaders/skin_model_normal_map.vert"); _skinNormalSpecularMapProgram.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + "shaders/model_normal_specular_map.frag"); - _skinNormalSpecularMapProgram.link(); - - initSkinProgram(_skinNormalSpecularMapProgram, _skinNormalSpecularMapLocations, 2); + + initSkinProgram(_skinNormalSpecularMapProgram, _skinNormalSpecularMapLocations); _skinShadowProgram.addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + "shaders/skin_model_shadow.vert"); _skinShadowProgram.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + "shaders/model_shadow.frag"); - _skinShadowProgram.link(); - + initSkinProgram(_skinShadowProgram, _skinShadowLocations); _skinTranslucentProgram.addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + "shaders/skin_model.vert"); _skinTranslucentProgram.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + "shaders/model_translucent.frag"); - _skinTranslucentProgram.link(); - + initSkinProgram(_skinTranslucentProgram, _skinTranslucentLocations); } } @@ -600,8 +539,6 @@ bool Model::findRayIntersectionAgainstSubMeshes(const glm::vec3& origin, const g if (modelFrameBox.findRayIntersection(modelFrameOrigin, modelFrameDirection, distance, face)) { float bestDistance = std::numeric_limits::max(); - float bestTriangleDistance = std::numeric_limits::max(); - bool someTriangleHit = false; float distanceToSubMesh; BoxFace subMeshFace; @@ -615,7 +552,6 @@ bool Model::findRayIntersectionAgainstSubMeshes(const glm::vec3& origin, const g if (subMeshBox.findRayIntersection(origin, direction, distanceToSubMesh, subMeshFace)) { if (distanceToSubMesh < bestDistance) { if (pickAgainstTriangles) { - someTriangleHit = false; if (!_calculatedMeshTrianglesValid) { recalculateMeshBoxes(pickAgainstTriangles); } @@ -628,9 +564,6 @@ bool Model::findRayIntersectionAgainstSubMeshes(const glm::vec3& origin, const g float thisTriangleDistance; if (findRayTriangleIntersection(origin, direction, triangle, thisTriangleDistance)) { if (thisTriangleDistance < bestDistance) { - bestTriangleDistance = thisTriangleDistance; - someTriangleHit = true; - bestDistance = thisTriangleDistance; intersectedSomething = true; face = subMeshFace; diff --git a/interface/src/renderer/Model.h b/interface/src/renderer/Model.h index 43b04b7a46..e875c8f06c 100644 --- a/interface/src/renderer/Model.h +++ b/interface/src/renderer/Model.h @@ -347,7 +347,7 @@ private: static Locations _lightmapSpecularMapLocations; static Locations _lightmapNormalSpecularMapLocations; - static void initProgram(ProgramObject& program, Locations& locations, int specularTextureUnit = 1); + static void initProgram(ProgramObject& program, Locations& locations, bool link = true); class SkinLocations : public Locations { public: @@ -363,7 +363,7 @@ private: static SkinLocations _skinShadowLocations; static SkinLocations _skinTranslucentLocations; - static void initSkinProgram(ProgramObject& program, SkinLocations& locations, int specularTextureUnit = 1); + static void initSkinProgram(ProgramObject& program, SkinLocations& locations); QVector _calculatedMeshBoxes; // world coordinate AABoxes for all sub mesh boxes bool _calculatedMeshBoxesValid; From 0813d53bee3433367b83680c33d0262bea351fee Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Thu, 11 Dec 2014 15:17:22 -0800 Subject: [PATCH 042/258] CR feedback --- interface/src/Application.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 19055ab61b..9b65469243 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -372,7 +372,6 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) : _glWidget->setMouseTracking(true); _toolWindow = new ToolWindow(); - qDebug() << "_toolWindow:" << _toolWindow; _toolWindow->setWindowFlags(_toolWindow->windowFlags() | Qt::WindowStaysOnTopHint); _toolWindow->setWindowTitle("Tools"); From df66a0049bbbd302e4190ff1411ef3017d68f952 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Thu, 11 Dec 2014 15:33:46 -0800 Subject: [PATCH 043/258] Don't hide mouse when over a widget --- interface/src/Application.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 32d4557c66..7f10e83b02 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -2284,13 +2284,14 @@ void Application::updateCursor(float deltaTime) { PerformanceWarning warn(showWarnings, "Application::updateCursor()"); bool hideMouse = false; - bool underMouse = _glWidget->underMouse(); + bool underMouse = QGuiApplication::topLevelAt(QCursor::pos()) == + Application::getInstance()->getWindow()->windowHandle(); static const int HIDE_CURSOR_TIMEOUT = 3 * USECS_PER_SECOND; // 3 second int elapsed = usecTimestampNow() - _lastMouseMove; - if ((elapsed > HIDE_CURSOR_TIMEOUT && underMouse) || + if ((elapsed > HIDE_CURSOR_TIMEOUT) || (OculusManager::isConnected() && Menu::getInstance()->isOptionChecked(MenuOption::EnableVRMode))) { - hideMouse = true; + hideMouse = underMouse; } setCursorVisible(!hideMouse); From fe8937e37ed762802cfaa3b9933682b52ffa92ba Mon Sep 17 00:00:00 2001 From: David Rowe Date: Thu, 11 Dec 2014 21:31:08 -0800 Subject: [PATCH 044/258] Make lasers able to emanate from index finger tips --- interface/src/avatar/Avatar.cpp | 93 +++++++++++++++++----------- interface/src/avatar/MyAvatar.h | 9 --- libraries/avatars/src/AvatarData.cpp | 11 +++- libraries/avatars/src/AvatarData.h | 6 ++ 4 files changed, 71 insertions(+), 48 deletions(-) diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index c680c75056..74043b2339 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -277,43 +277,64 @@ void Avatar::render(const glm::vec3& cameraPosition, RenderMode renderMode, bool // render pointing lasers glm::vec3 laserColor = glm::vec3(1.0f, 0.0f, 1.0f); float laserLength = 50.0f; - if (_handState == HAND_STATE_LEFT_POINTING || - _handState == HAND_STATE_BOTH_POINTING) { - int leftIndex = _skeletonModel.getLeftHandJointIndex(); - glm::vec3 leftPosition; - glm::quat leftRotation; - _skeletonModel.getJointPositionInWorldFrame(leftIndex, leftPosition); - _skeletonModel.getJointRotationInWorldFrame(leftIndex, leftRotation); - glPushMatrix(); { - glTranslatef(leftPosition.x, leftPosition.y, leftPosition.z); - float angle = glm::degrees(glm::angle(leftRotation)); - glm::vec3 axis = glm::axis(leftRotation); - glRotatef(angle, axis.x, axis.y, axis.z); - glBegin(GL_LINES); - glColor3f(laserColor.x, laserColor.y, laserColor.z); - glVertex3f(0.0f, 0.0f, 0.0f); - glVertex3f(0.0f, laserLength, 0.0f); - glEnd(); - } glPopMatrix(); + glm::vec3 position; + glm::quat rotation; + bool havePosition, haveRotation; + + if (_handState & LEFT_HAND_POINTING_FLAG) { + + if (_handState & IS_FINGER_POINTING_FLAG) { + int leftIndexTip = getJointIndex("LeftHandIndex4"); + int leftIndexTipJoint = getJointIndex("LeftHandIndex3"); + havePosition = _skeletonModel.getJointPositionInWorldFrame(leftIndexTip, position); + haveRotation = _skeletonModel.getJointRotationInWorldFrame(leftIndexTipJoint, rotation); + } else { + int leftHand = _skeletonModel.getLeftHandJointIndex(); + havePosition = _skeletonModel.getJointPositionInWorldFrame(leftHand, position); + haveRotation = _skeletonModel.getJointRotationInWorldFrame(leftHand, rotation); + } + + if (havePosition && haveRotation) { + glPushMatrix(); { + glTranslatef(position.x, position.y, position.z); + float angle = glm::degrees(glm::angle(rotation)); + glm::vec3 axis = glm::axis(rotation); + glRotatef(angle, axis.x, axis.y, axis.z); + glBegin(GL_LINES); + glColor3f(laserColor.x, laserColor.y, laserColor.z); + glVertex3f(0.0f, 0.0f, 0.0f); + glVertex3f(0.0f, laserLength, 0.0f); + glEnd(); + } glPopMatrix(); + } } - if (_handState == HAND_STATE_RIGHT_POINTING || - _handState == HAND_STATE_BOTH_POINTING) { - int rightIndex = _skeletonModel.getRightHandJointIndex(); - glm::vec3 rightPosition; - glm::quat rightRotation; - _skeletonModel.getJointPositionInWorldFrame(rightIndex, rightPosition); - _skeletonModel.getJointRotationInWorldFrame(rightIndex, rightRotation); - glPushMatrix(); { - glTranslatef(rightPosition.x, rightPosition.y, rightPosition.z); - float angle = glm::degrees(glm::angle(rightRotation)); - glm::vec3 axis = glm::axis(rightRotation); - glRotatef(angle, axis.x, axis.y, axis.z); - glBegin(GL_LINES); - glColor3f(laserColor.x, laserColor.y, laserColor.z); - glVertex3f(0.0f, 0.0f, 0.0f); - glVertex3f(0.0f, laserLength, 0.0f); - glEnd(); - } glPopMatrix(); + + if (_handState & RIGHT_HAND_POINTING_FLAG) { + + if (_handState & IS_FINGER_POINTING_FLAG) { + int rightIndexTip = getJointIndex("RightHandIndex4"); + int rightIndexTipJoint = getJointIndex("RightHandIndex3"); + havePosition = _skeletonModel.getJointPositionInWorldFrame(rightIndexTip, position); + haveRotation = _skeletonModel.getJointRotationInWorldFrame(rightIndexTipJoint, rotation); + } else { + int rightHand = _skeletonModel.getRightHandJointIndex(); + havePosition = _skeletonModel.getJointPositionInWorldFrame(rightHand, position); + haveRotation = _skeletonModel.getJointRotationInWorldFrame(rightHand, rotation); + } + + if (havePosition && haveRotation) { + glPushMatrix(); { + glTranslatef(position.x, position.y, position.z); + float angle = glm::degrees(glm::angle(rotation)); + glm::vec3 axis = glm::axis(rotation); + glRotatef(angle, axis.x, axis.y, axis.z); + glBegin(GL_LINES); + glColor3f(laserColor.x, laserColor.y, laserColor.z); + glVertex3f(0.0f, 0.0f, 0.0f); + glVertex3f(0.0f, laserLength, 0.0f); + glEnd(); + } glPopMatrix(); + } } } diff --git a/interface/src/avatar/MyAvatar.h b/interface/src/avatar/MyAvatar.h index 12ad4474c9..7bf6d057da 100644 --- a/interface/src/avatar/MyAvatar.h +++ b/interface/src/avatar/MyAvatar.h @@ -21,15 +21,6 @@ class ModelItemID; -enum AvatarHandState -{ - HAND_STATE_NULL = 0, - HAND_STATE_LEFT_POINTING, - HAND_STATE_RIGHT_POINTING, - HAND_STATE_BOTH_POINTING, - NUM_HAND_STATES -}; - class MyAvatar : public Avatar { Q_OBJECT Q_PROPERTY(bool shouldRenderLocally READ getShouldRenderLocally WRITE setShouldRenderLocally) diff --git a/libraries/avatars/src/AvatarData.cpp b/libraries/avatars/src/AvatarData.cpp index 95432bc81a..d22d1c5a0a 100644 --- a/libraries/avatars/src/AvatarData.cpp +++ b/libraries/avatars/src/AvatarData.cpp @@ -188,7 +188,11 @@ QByteArray AvatarData::toByteArray() { // key state setSemiNibbleAt(bitItems,KEY_STATE_START_BIT,_keyState); // hand state - setSemiNibbleAt(bitItems,HAND_STATE_START_BIT,_handState); + bool isFingerPointing = _handState & IS_FINGER_POINTING_FLAG; + setSemiNibbleAt(bitItems, HAND_STATE_START_BIT, _handState & ~IS_FINGER_POINTING_FLAG); + if (isFingerPointing) { + setAtBit(bitItems, HAND_STATE_FINGER_POINTING_BIT); + } // faceshift state if (_headData->_isFaceshiftConnected) { setAtBit(bitItems, IS_FACESHIFT_CONNECTED); @@ -439,8 +443,9 @@ int AvatarData::parseDataAtOffset(const QByteArray& packet, int offset) { // key state, stored as a semi-nibble in the bitItems _keyState = (KeyState)getSemiNibbleAt(bitItems,KEY_STATE_START_BIT); - // hand state, stored as a semi-nibble in the bitItems - _handState = getSemiNibbleAt(bitItems,HAND_STATE_START_BIT); + // hand state, stored as a semi-nibble plus a bit in the bitItems + _handState = getSemiNibbleAt(bitItems, HAND_STATE_START_BIT) + + oneAtBit(bitItems, HAND_STATE_FINGER_POINTING_BIT) ? IS_FINGER_POINTING_FLAG : 0; _headData->_isFaceshiftConnected = oneAtBit(bitItems, IS_FACESHIFT_CONNECTED); _isChatCirclingEnabled = oneAtBit(bitItems, IS_CHAT_CIRCLING_ENABLED); diff --git a/libraries/avatars/src/AvatarData.h b/libraries/avatars/src/AvatarData.h index d590f95bfd..55b35377c0 100644 --- a/libraries/avatars/src/AvatarData.h +++ b/libraries/avatars/src/AvatarData.h @@ -82,6 +82,12 @@ const int HAND_STATE_START_BIT = 2; // 3rd and 4th bits const int IS_FACESHIFT_CONNECTED = 4; // 5th bit const int IS_CHAT_CIRCLING_ENABLED = 5; // 6th bit const int HAS_REFERENTIAL = 6; // 7th bit +const int HAND_STATE_FINGER_POINTING_BIT = 7; // 8th bit + +const char HAND_STATE_NULL = 0; +const char LEFT_HAND_POINTING_FLAG = 1; +const char RIGHT_HAND_POINTING_FLAG = 2; +const char IS_FINGER_POINTING_FLAG = 4; static const float MAX_AVATAR_SCALE = 1000.0f; static const float MIN_AVATAR_SCALE = .005f; From 1ab91296162bceab354ace56bf76cf5099015d5f Mon Sep 17 00:00:00 2001 From: David Rowe Date: Thu, 11 Dec 2014 21:31:23 -0800 Subject: [PATCH 045/258] Update laserPointer.js to detect pointing with Leap Motion or similar --- examples/laserPointer.js | 90 +++++++++++++++++++++++++++++++++++----- 1 file changed, 80 insertions(+), 10 deletions(-) diff --git a/examples/laserPointer.js b/examples/laserPointer.js index bedafe6a18..156e9ba298 100644 --- a/examples/laserPointer.js +++ b/examples/laserPointer.js @@ -5,19 +5,89 @@ // Created by Clément Brisset on 7/18/14. // Copyright 2014 High Fidelity, Inc. // +// If using Hydra controllers, pulling the triggers makes laser pointers emanate from the respective hands. +// If using a Leap Motion or similar to control your avatar's hands and fingers, pointing with your index fingers makes +// laser pointers emanate from the respective index fingers. +// // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -var LEFT = 0; -var RIGHT = 1; -var LEFT_HAND_FLAG = 1; -var RIGHT_HAND_FLAG = 2; +var laserPointer = (function () { -function update() { - var state = ((Controller.getTriggerValue(LEFT) > 0.9) ? LEFT_HAND_FLAG : 0) + - ((Controller.getTriggerValue(RIGHT) > 0.9) ? RIGHT_HAND_FLAG : 0); - MyAvatar.setHandState(state); -} + var NUM_FINGERs = 4, // Excluding thumb + fingers = [ + [ "LeftHandIndex", "LeftHandMiddle", "LeftHandRing", "LeftHandPinky" ], + [ "RightHandIndex", "RightHandMiddle", "RightHandRing", "RightHandPinky" ] + ]; -Script.update.connect(update); \ No newline at end of file + function isHandPointing(hand) { + var MINIMUM_TRIGGER_PULL = 0.9; + return Controller.getTriggerValue(hand) > MINIMUM_TRIGGER_PULL; + } + + function isFingerPointing(hand) { + // Index finger is pointing if final two bones of middle, ring, and pinky fingers are > 90 degrees w.r.t. index finger + + var pointing, + indexDirection, + otherDirection, + f; + + pointing = true; + + indexDirection = Vec3.subtract( + MyAvatar.getJointPosition(fingers[hand][0] + "4"), + MyAvatar.getJointPosition(fingers[hand][0] + "2") + ); + + for (f = 1; f < NUM_FINGERs; f += 1) { + otherDirection = Vec3.subtract( + MyAvatar.getJointPosition(fingers[hand][f] + "4"), + MyAvatar.getJointPosition(fingers[hand][f] + "2") + ); + pointing = pointing && Vec3.dot(indexDirection, otherDirection) < 0; + } + + return pointing; + } + + function update() { + var LEFT_HAND = 0, + RIGHT_HAND = 1, + LEFT_HAND_POINTING_FLAG = 1, + RIGHT_HAND_POINTING_FLAG = 2, + FINGER_POINTING_FLAG = 4, + handState; + + handState = 0; + + if (isHandPointing(LEFT_HAND)) { + handState += LEFT_HAND_POINTING_FLAG; + } + if (isHandPointing(RIGHT_HAND)) { + handState += RIGHT_HAND_POINTING_FLAG; + } + + if (handState === 0) { + if (isFingerPointing(LEFT_HAND)) { + handState += LEFT_HAND_POINTING_FLAG; + } + if (isFingerPointing(RIGHT_HAND)) { + handState += RIGHT_HAND_POINTING_FLAG; + } + if (handState !== 0) { + handState += FINGER_POINTING_FLAG; + } + } + + MyAvatar.setHandState(handState); + } + + return { + update: update + }; + +}()); + +Script.update.connect(laserPointer.update); From 20b880ca09833a60f13172207d0587524b47e821 Mon Sep 17 00:00:00 2001 From: David Rowe Date: Thu, 11 Dec 2014 23:07:05 -0800 Subject: [PATCH 046/258] Fix avatar hand state decoding for finger laser --- libraries/avatars/src/AvatarData.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/avatars/src/AvatarData.cpp b/libraries/avatars/src/AvatarData.cpp index d22d1c5a0a..01f84ca246 100644 --- a/libraries/avatars/src/AvatarData.cpp +++ b/libraries/avatars/src/AvatarData.cpp @@ -445,7 +445,7 @@ int AvatarData::parseDataAtOffset(const QByteArray& packet, int offset) { _keyState = (KeyState)getSemiNibbleAt(bitItems,KEY_STATE_START_BIT); // hand state, stored as a semi-nibble plus a bit in the bitItems _handState = getSemiNibbleAt(bitItems, HAND_STATE_START_BIT) - + oneAtBit(bitItems, HAND_STATE_FINGER_POINTING_BIT) ? IS_FINGER_POINTING_FLAG : 0; + + (oneAtBit(bitItems, HAND_STATE_FINGER_POINTING_BIT) ? IS_FINGER_POINTING_FLAG : 0); _headData->_isFaceshiftConnected = oneAtBit(bitItems, IS_FACESHIFT_CONNECTED); _isChatCirclingEnabled = oneAtBit(bitItems, IS_CHAT_CIRCLING_ENABLED); From 687072f19cf716305842151540d9aaa26f50a8ad Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 12 Dec 2014 09:47:15 -0800 Subject: [PATCH 047/258] fix for domain failed reconnect after disconnect --- libraries/networking/src/DomainHandler.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/libraries/networking/src/DomainHandler.cpp b/libraries/networking/src/DomainHandler.cpp index d64752dce0..6091b0cdd2 100644 --- a/libraries/networking/src/DomainHandler.cpp +++ b/libraries/networking/src/DomainHandler.cpp @@ -73,6 +73,7 @@ void DomainHandler::hardReset() { qDebug() << "Hard reset in NodeList DomainHandler."; _iceDomainID = QUuid(); + _iceServerSockAddr = HifiSockAddr(); _hostname = QString(); _sockAddr.setAddress(QHostAddress::Null); } From c1c5991ac50032a2429f57488bbe09b0c445d4ce Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Fri, 12 Dec 2014 12:07:48 -0800 Subject: [PATCH 048/258] Fix for distorted replaced textures. --- interface/src/MetavoxelSystem.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/interface/src/MetavoxelSystem.cpp b/interface/src/MetavoxelSystem.cpp index 87060d7dfa..002acec9ed 100644 --- a/interface/src/MetavoxelSystem.cpp +++ b/interface/src/MetavoxelSystem.cpp @@ -2188,13 +2188,15 @@ void HeightfieldNodeRenderer::render(const HeightfieldNodePointer& node, const g bufferPair.second.release(); } if (_heightTextureID == 0) { + // we use non-aligned data for the various layers + glPixelStorei(GL_UNPACK_ALIGNMENT, 1); + glGenTextures(1, &_heightTextureID); glBindTexture(GL_TEXTURE_2D, _heightTextureID); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); - glPixelStorei(GL_UNPACK_ALIGNMENT, 1); const QVector& heightContents = node->getHeight()->getContents(); glTexImage2D(GL_TEXTURE_2D, 0, GL_R16, width, height, 0, GL_RED, GL_UNSIGNED_SHORT, heightContents.constData()); @@ -2241,6 +2243,9 @@ void HeightfieldNodeRenderer::render(const HeightfieldNodePointer& node, const g glTexImage2D(GL_TEXTURE_2D, 0, GL_R8, 1, 1, 0, GL_RED, GL_UNSIGNED_BYTE, &ZERO_VALUE); } glBindTexture(GL_TEXTURE_2D, 0); + + // restore the default alignment; it's what Qt uses for image storage + glPixelStorei(GL_UNPACK_ALIGNMENT, 4); } if (cursor) { From b8737ad5257058b6edea3f1fa17514b6a0bec2a4 Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Fri, 12 Dec 2014 15:26:07 -0800 Subject: [PATCH 049/258] Update 'f' focus to only work when something is selected --- examples/editEntities.js | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/examples/editEntities.js b/examples/editEntities.js index e9f42bf74c..fc48cf22b5 100644 --- a/examples/editEntities.js +++ b/examples/editEntities.js @@ -839,9 +839,11 @@ Controller.keyReleaseEvent.connect(function (event) { selectionDisplay.toggleSpaceMode(); } else if (event.text == "f") { if (isActive) { - cameraManager.focus(selectionManager.worldPosition, - selectionManager.worldDimensions, - Menu.isOptionChecked(MENU_EASE_ON_FOCUS)); + if (selectionManager.hasSelection()) { + cameraManager.focus(selectionManager.worldPosition, + selectionManager.worldDimensions, + Menu.isOptionChecked(MENU_EASE_ON_FOCUS)); + } } } else if (event.text == '[') { if (isActive) { From d1f5bf2e3cdf9c68229dded470df12adc90140e9 Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Fri, 12 Dec 2014 15:27:30 -0800 Subject: [PATCH 050/258] Add rotation to properties window --- examples/editEntities.js | 5 +++++ examples/html/entityProperties.html | 23 +++++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/examples/editEntities.js b/examples/editEntities.js index fc48cf22b5..980f38f2cc 100644 --- a/examples/editEntities.js +++ b/examples/editEntities.js @@ -1004,6 +1004,7 @@ PropertiesTool = function(opts) { }; if (selectionManager.hasSelection()) { data.properties = Entities.getEntityProperties(selectionManager.selections[0]); + data.properties.rotation = Quat.safeEulerAngles(data.properties.rotation); } webView.eventBridge.emitScriptEvent(JSON.stringify(data)); }); @@ -1012,6 +1013,10 @@ PropertiesTool = function(opts) { print(data); data = JSON.parse(data); if (data.type == "update") { + if (data.properties.rotation !== undefined) { + var rotation = data.properties.rotation; + data.properties.rotation = Quat.fromPitchYawRollDegrees(rotation.x, rotation.y, rotation.z); + } Entities.editEntity(selectionManager.selections[0], data.properties); selectionManager._update(); } diff --git a/examples/html/entityProperties.html b/examples/html/entityProperties.html index 17eb0ad88f..d30aac72ee 100644 --- a/examples/html/entityProperties.html +++ b/examples/html/entityProperties.html @@ -85,6 +85,10 @@ var elRegistrationY = document.getElementById("property-reg-y"); var elRegistrationZ = document.getElementById("property-reg-z"); + var elRotationX = document.getElementById("property-rot-x"); + var elRotationY = document.getElementById("property-rot-y"); + var elRotationZ = document.getElementById("property-rot-z"); + var elLinearVelocityX = document.getElementById("property-lvel-x"); var elLinearVelocityY = document.getElementById("property-lvel-y"); var elLinearVelocityZ = document.getElementById("property-lvel-z"); @@ -181,6 +185,10 @@ elRegistrationY.value = properties.registrationPoint.y.toFixed(2); elRegistrationZ.value = properties.registrationPoint.z.toFixed(2); + elRotationX.value = properties.rotation.x.toFixed(2); + elRotationY.value = properties.rotation.y.toFixed(2); + elRotationZ.value = properties.rotation.z.toFixed(2); + elLinearVelocityX.value = properties.velocity.x.toFixed(2); elLinearVelocityY.value = properties.velocity.y.toFixed(2); elLinearVelocityZ.value = properties.velocity.z.toFixed(2); @@ -302,6 +310,12 @@ elRegistrationY.addEventListener('change', registrationChangeFunction); elRegistrationZ.addEventListener('change', registrationChangeFunction); + var rotationChangeFunction = createEmitVec3PropertyUpdateFunction( + 'rotation', elRotationX, elRotationY, elRotationZ); + elRotationX.addEventListener('change', rotationChangeFunction); + elRotationY.addEventListener('change', rotationChangeFunction); + elRotationZ.addEventListener('change', rotationChangeFunction); + var velocityChangeFunction = createEmitVec3PropertyUpdateFunction( 'velocity', elLinearVelocityX, elLinearVelocityY, elLinearVelocityZ); elLinearVelocityX.addEventListener('change', velocityChangeFunction); @@ -486,6 +500,15 @@ + + Rotation + +
Pitch
+
Yaw
+
Roll
+ + + Linear Velocity From 1a90a810379dd1ad196af9aeafa3792b89fa5d91 Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Fri, 12 Dec 2014 15:27:56 -0800 Subject: [PATCH 051/258] Add id to properties window --- examples/editEntities.js | 1 + examples/html/entityProperties.html | 11 +++++++++++ examples/html/style.css | 11 +++++++++++ 3 files changed, 23 insertions(+) diff --git a/examples/editEntities.js b/examples/editEntities.js index 980f38f2cc..ea6496d4f5 100644 --- a/examples/editEntities.js +++ b/examples/editEntities.js @@ -1003,6 +1003,7 @@ PropertiesTool = function(opts) { type: 'update', }; if (selectionManager.hasSelection()) { + data.id = selectionManager.selections[0].id; data.properties = Entities.getEntityProperties(selectionManager.selections[0]); data.properties.rotation = Quat.safeEulerAngles(data.properties.rotation); } diff --git a/examples/html/entityProperties.html b/examples/html/entityProperties.html index d30aac72ee..a34f7ce13f 100644 --- a/examples/html/entityProperties.html +++ b/examples/html/entityProperties.html @@ -70,6 +70,7 @@ }; function loaded() { + var elID = document.getElementById("property-id"); var elType = document.getElementById("property-type"); var elLocked = document.getElementById("property-locked"); var elVisible = document.getElementById("property-visible"); @@ -160,6 +161,8 @@ } else { var properties = data.properties; + elID.innerHTML = data.id; + elType.innerHTML = properties.type; elLocked.checked = properties.locked; @@ -451,6 +454,14 @@ + + + ID + + + + + Type diff --git a/examples/html/style.css b/examples/html/style.css index 424933e14e..aa23cf97ab 100644 --- a/examples/html/style.css +++ b/examples/html/style.css @@ -17,6 +17,17 @@ body { user-select: none; } +.selectable { + -webkit-touch-callout: text; + -webkit-user-select: text; + -khtml-user-select: text; + -moz-user-select: text; + -ms-user-select: text; + user-select: text; + + cursor: text; +} + .color-box { display: inline-block; width: 20px; From a5cbc9b3e2fa3aa8e3544d30dc66529c4cc785f3 Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Fri, 12 Dec 2014 15:28:22 -0800 Subject: [PATCH 052/258] Fix properties window to work with undo/redo --- examples/editEntities.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/examples/editEntities.js b/examples/editEntities.js index ea6496d4f5..b671e45d7c 100644 --- a/examples/editEntities.js +++ b/examples/editEntities.js @@ -1014,11 +1014,13 @@ PropertiesTool = function(opts) { print(data); data = JSON.parse(data); if (data.type == "update") { + selectionManager.saveProperties(); if (data.properties.rotation !== undefined) { var rotation = data.properties.rotation; data.properties.rotation = Quat.fromPitchYawRollDegrees(rotation.x, rotation.y, rotation.z); } Entities.editEntity(selectionManager.selections[0], data.properties); + pushCommandForSelections(); selectionManager._update(); } }); From 33b4c614eae17ad3ef7c54a821e929f2ffb0ee52 Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Fri, 12 Dec 2014 15:28:57 -0800 Subject: [PATCH 053/258] Add buttons for moving selection to grid and resetting to natural dimensions --- examples/editEntities.js | 48 +++++++++++++++++++++++++++++ examples/html/entityProperties.html | 29 +++++++++++++++++ 2 files changed, 77 insertions(+) diff --git a/examples/editEntities.js b/examples/editEntities.js index b671e45d7c..3f133ac0b2 100644 --- a/examples/editEntities.js +++ b/examples/editEntities.js @@ -1022,6 +1022,54 @@ PropertiesTool = function(opts) { Entities.editEntity(selectionManager.selections[0], data.properties); pushCommandForSelections(); selectionManager._update(); + } else if (data.type == "action") { + if (data.action == "moveSelectionToGrid") { + if (!selectionManager.hasSelection()) { + return; + } + selectionManager.saveProperties(); + var dY = grid.getOrigin().y - (selectionManager.worldPosition.y - selectionManager.worldDimensions.y / 2), + var diff = { x: 0, y: dY, z: 0 }; + for (var i = 0; i < SelectionManager.selections.length; i++) { + var properties = SelectionManager.savedProperties[SelectionManager.selections[i].id]; + var newPosition = Vec3.sum(properties.position, diff); + Entities.editEntity(SelectionManager.selections[i], { + position: newPosition, + }); + } + pushCommandForSelections(); + selectionManager._update(); + } else if (data.action == "moveAllToGrid") { + if (!selectionManager.hasSelection()) { + return; + } + selectionManager.saveProperties(); + for (var i = 0; i < SelectionManager.selections.length; i++) { + var properties = SelectionManager.savedProperties[SelectionManager.selections[i].id]; + var bottomY = properties.boundingBox.center.y - properties.boundingBox.dimensions.y / 2; + var dY = grid.getOrigin().y - bottomY; + var diff = { x: 0, y: dY, z: 0 }; + var newPosition = Vec3.sum(properties.position, diff); + Entities.editEntity(SelectionManager.selections[i], { + position: newPosition, + }); + } + pushCommandForSelections(); + selectionManager._update(); + } else if (data.action == "resetToNaturalDimensions") { + if (!selectionManager.hasSelection()) { + return; + } + selectionManager.saveProperties(); + for (var i = 0; i < SelectionManager.selections.length; i++) { + var properties = SelectionManager.savedProperties[SelectionManager.selections[i].id]; + Entities.editEntity(SelectionManager.selections[i], { + dimensions: properties.naturalDimensions, + }); + } + pushCommandForSelections(); + selectionManager._update(); + } } }); diff --git a/examples/html/entityProperties.html b/examples/html/entityProperties.html index a34f7ce13f..48804d475a 100644 --- a/examples/html/entityProperties.html +++ b/examples/html/entityProperties.html @@ -77,10 +77,13 @@ var elPositionX = document.getElementById("property-pos-x"); var elPositionY = document.getElementById("property-pos-y"); var elPositionZ = document.getElementById("property-pos-z"); + var elMoveSelectionToGrid = document.getElementById("move-selection-to-grid"); + var elMoveAllToGrid = document.getElementById("move-all-to-grid"); var elDimensionsX = document.getElementById("property-dim-x"); var elDimensionsY = document.getElementById("property-dim-y"); var elDimensionsZ = document.getElementById("property-dim-z"); + var elResetToNaturalDimensions = document.getElementById("reset-to-natural-dimensions"); var elRegistrationX = document.getElementById("property-reg-x"); var elRegistrationY = document.getElementById("property-reg-y"); @@ -398,6 +401,25 @@ elTextBackgroundColorGreen.addEventListener('change', textBackgroundColorChangeFunction); elTextBackgroundColorBlue.addEventListener('change', textBackgroundColorChangeFunction); + elMoveSelectionToGrid.addEventListener("click", function() { + EventBridge.emitWebEvent(JSON.stringify({ + type: "action", + action: "moveSelectionToGrid", + })); + }); + elMoveAllToGrid.addEventListener("click", function() { + EventBridge.emitWebEvent(JSON.stringify({ + type: "action", + action: "moveAllToGrid", + })); + }); + elResetToNaturalDimensions.addEventListener("click", function() { + EventBridge.emitWebEvent(JSON.stringify({ + type: "action", + action: "resetToNaturalDimensions", + })); + }); + var resizing = false; var startX = 0; @@ -490,6 +512,10 @@
X
Y
Z
+
+ + +
@@ -508,6 +534,9 @@
X
Y
Z
+
+ +
From dde9b92dbd4a02d630f171a7f1d72dea36236a88 Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Fri, 12 Dec 2014 15:31:54 -0800 Subject: [PATCH 054/258] Update SelectionManager -> selectionManager --- examples/editEntities.js | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/examples/editEntities.js b/examples/editEntities.js index 3f133ac0b2..c2f2ad4086 100644 --- a/examples/editEntities.js +++ b/examples/editEntities.js @@ -1030,10 +1030,10 @@ PropertiesTool = function(opts) { selectionManager.saveProperties(); var dY = grid.getOrigin().y - (selectionManager.worldPosition.y - selectionManager.worldDimensions.y / 2), var diff = { x: 0, y: dY, z: 0 }; - for (var i = 0; i < SelectionManager.selections.length; i++) { - var properties = SelectionManager.savedProperties[SelectionManager.selections[i].id]; + for (var i = 0; i < selectionManager.selections.length; i++) { + var properties = selectionManager.savedProperties[selectionManager.selections[i].id]; var newPosition = Vec3.sum(properties.position, diff); - Entities.editEntity(SelectionManager.selections[i], { + Entities.editEntity(selectionManager.selections[i], { position: newPosition, }); } @@ -1044,13 +1044,13 @@ PropertiesTool = function(opts) { return; } selectionManager.saveProperties(); - for (var i = 0; i < SelectionManager.selections.length; i++) { - var properties = SelectionManager.savedProperties[SelectionManager.selections[i].id]; + for (var i = 0; i < selectionManager.selections.length; i++) { + var properties = selectionManager.savedProperties[selectionManager.selections[i].id]; var bottomY = properties.boundingBox.center.y - properties.boundingBox.dimensions.y / 2; var dY = grid.getOrigin().y - bottomY; var diff = { x: 0, y: dY, z: 0 }; var newPosition = Vec3.sum(properties.position, diff); - Entities.editEntity(SelectionManager.selections[i], { + Entities.editEntity(selectionManager.selections[i], { position: newPosition, }); } @@ -1061,9 +1061,9 @@ PropertiesTool = function(opts) { return; } selectionManager.saveProperties(); - for (var i = 0; i < SelectionManager.selections.length; i++) { - var properties = SelectionManager.savedProperties[SelectionManager.selections[i].id]; - Entities.editEntity(SelectionManager.selections[i], { + for (var i = 0; i < selectionManager.selections.length; i++) { + var properties = selectionManager.savedProperties[selectionManager.selections[i].id]; + Entities.editEntity(selectionManager.selections[i], { dimensions: properties.naturalDimensions, }); } From 2fab404f7fee8c04a0fe3ce2e8a117cb00a57b37 Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Fri, 12 Dec 2014 15:35:39 -0800 Subject: [PATCH 055/258] Reorganize selectionManager selection checking --- examples/editEntities.js | 79 +++++++++++++++++++--------------------- 1 file changed, 38 insertions(+), 41 deletions(-) diff --git a/examples/editEntities.js b/examples/editEntities.js index c2f2ad4086..0b5c089c07 100644 --- a/examples/editEntities.js +++ b/examples/editEntities.js @@ -1024,51 +1024,48 @@ PropertiesTool = function(opts) { selectionManager._update(); } else if (data.type == "action") { if (data.action == "moveSelectionToGrid") { - if (!selectionManager.hasSelection()) { - return; - } - selectionManager.saveProperties(); - var dY = grid.getOrigin().y - (selectionManager.worldPosition.y - selectionManager.worldDimensions.y / 2), - var diff = { x: 0, y: dY, z: 0 }; - for (var i = 0; i < selectionManager.selections.length; i++) { - var properties = selectionManager.savedProperties[selectionManager.selections[i].id]; - var newPosition = Vec3.sum(properties.position, diff); - Entities.editEntity(selectionManager.selections[i], { - position: newPosition, - }); - } - pushCommandForSelections(); - selectionManager._update(); - } else if (data.action == "moveAllToGrid") { - if (!selectionManager.hasSelection()) { - return; - } - selectionManager.saveProperties(); - for (var i = 0; i < selectionManager.selections.length; i++) { - var properties = selectionManager.savedProperties[selectionManager.selections[i].id]; - var bottomY = properties.boundingBox.center.y - properties.boundingBox.dimensions.y / 2; - var dY = grid.getOrigin().y - bottomY; + if (selectionManager.hasSelection()) { + selectionManager.saveProperties(); + var dY = grid.getOrigin().y - (selectionManager.worldPosition.y - selectionManager.worldDimensions.y / 2), var diff = { x: 0, y: dY, z: 0 }; - var newPosition = Vec3.sum(properties.position, diff); - Entities.editEntity(selectionManager.selections[i], { - position: newPosition, - }); + for (var i = 0; i < selectionManager.selections.length; i++) { + var properties = selectionManager.savedProperties[selectionManager.selections[i].id]; + var newPosition = Vec3.sum(properties.position, diff); + Entities.editEntity(selectionManager.selections[i], { + position: newPosition, + }); + } + pushCommandForSelections(); + selectionManager._update(); + } + } else if (data.action == "moveAllToGrid") { + if (selectionManager.hasSelection()) { + selectionManager.saveProperties(); + for (var i = 0; i < selectionManager.selections.length; i++) { + var properties = selectionManager.savedProperties[selectionManager.selections[i].id]; + var bottomY = properties.boundingBox.center.y - properties.boundingBox.dimensions.y / 2; + var dY = grid.getOrigin().y - bottomY; + var diff = { x: 0, y: dY, z: 0 }; + var newPosition = Vec3.sum(properties.position, diff); + Entities.editEntity(selectionManager.selections[i], { + position: newPosition, + }); + } + pushCommandForSelections(); + selectionManager._update(); } - pushCommandForSelections(); - selectionManager._update(); } else if (data.action == "resetToNaturalDimensions") { - if (!selectionManager.hasSelection()) { - return; + if (selectionManager.hasSelection()) { + selectionManager.saveProperties(); + for (var i = 0; i < selectionManager.selections.length; i++) { + var properties = selectionManager.savedProperties[selectionManager.selections[i].id]; + Entities.editEntity(selectionManager.selections[i], { + dimensions: properties.naturalDimensions, + }); + } + pushCommandForSelections(); + selectionManager._update(); } - selectionManager.saveProperties(); - for (var i = 0; i < selectionManager.selections.length; i++) { - var properties = selectionManager.savedProperties[selectionManager.selections[i].id]; - Entities.editEntity(selectionManager.selections[i], { - dimensions: properties.naturalDimensions, - }); - } - pushCommandForSelections(); - selectionManager._update(); } } }); From a9223f58879f2afbb3cef72ffc4181b24a61dbb2 Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Fri, 12 Dec 2014 15:45:31 -0800 Subject: [PATCH 056/258] Remove text from label --- examples/html/entityProperties.html | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/html/entityProperties.html b/examples/html/entityProperties.html index 48804d475a..4e22637ad6 100644 --- a/examples/html/entityProperties.html +++ b/examples/html/entityProperties.html @@ -481,7 +481,7 @@ ID - + From 14cda00ebc46ba02f68bbbd3ae111059d1ccac9c Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Fri, 12 Dec 2014 20:52:41 -0800 Subject: [PATCH 057/258] First implementation of the DependencyManager --- libraries/shared/src/DependencyManager.cpp | 33 +++++++++++++ libraries/shared/src/DependencyManager.h | 55 ++++++++++++++++++++++ 2 files changed, 88 insertions(+) create mode 100644 libraries/shared/src/DependencyManager.cpp create mode 100644 libraries/shared/src/DependencyManager.h diff --git a/libraries/shared/src/DependencyManager.cpp b/libraries/shared/src/DependencyManager.cpp new file mode 100644 index 0000000000..b4b3061317 --- /dev/null +++ b/libraries/shared/src/DependencyManager.cpp @@ -0,0 +1,33 @@ +// +// DependencyManager.cpp +// +// +// Created by Clément Brisset on 12/10/14. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "DependencyManager.h" + +DependencyManager& DependencyManager::getInstance() { + static DependencyManager instance; + return instance; +} + +DependencyManager::DependencyManager() { + // Guard against request of ourself + // We could set the value to this, but since it doesn't make sense to access + // the DependencyManager instance from the outside let's set it to NULL + _instanceHash.insert(typeid(DependencyManager).name(), NULL); +} + +DependencyManager::~DependencyManager() { + foreach (Dependency* instance, _instanceHash) { + if (instance) { + instance->deleteInstance(); + } + } + _instanceHash.clear(); +} \ No newline at end of file diff --git a/libraries/shared/src/DependencyManager.h b/libraries/shared/src/DependencyManager.h new file mode 100644 index 0000000000..690058cab4 --- /dev/null +++ b/libraries/shared/src/DependencyManager.h @@ -0,0 +1,55 @@ +// +// DependencyManager.h +// +// +// Created by Clément Brisset on 12/10/14. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef hifi_DependencyManager_h +#define hifi_DependencyManager_h + +#include +#include + +#include + +class DependencyManager { +public: + template + static T* get(); + + class Dependency { + virtual void deleteInstance() = 0; + friend DependencyManager; + }; +private: + static DependencyManager& getInstance(); + DependencyManager(); + ~DependencyManager(); + + typedef QHash InstanceHash; + static InstanceHash& getInstanceHash() { return getInstance()._instanceHash; } + InstanceHash _instanceHash; +}; + +template +T* DependencyManager::get() { + const QString& typeId = typeid(T).name(); + + // Search the hash for global instance + Dependency* instance = getInstanceHash().value(typeId, NULL); + if (instance) { + return dynamic_cast(instance); + } + + // Found no instance in hash so we create one. + T* newInstance = new T(); + getInstanceHash().insert(typeId, dynamic_cast(newInstance)); + return newInstance; +} + +#endif // hifi_DependencyManager_h \ No newline at end of file From 50fd52377ff72e63c038a2b5aff908b855f7c026 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Fri, 12 Dec 2014 21:10:45 -0800 Subject: [PATCH 058/258] Couple improvements to the dependency manager --- libraries/shared/src/DependencyManager.cpp | 9 +-------- libraries/shared/src/DependencyManager.h | 14 +++++++++++--- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/libraries/shared/src/DependencyManager.cpp b/libraries/shared/src/DependencyManager.cpp index b4b3061317..41cb405ac7 100644 --- a/libraries/shared/src/DependencyManager.cpp +++ b/libraries/shared/src/DependencyManager.cpp @@ -16,17 +16,10 @@ DependencyManager& DependencyManager::getInstance() { return instance; } -DependencyManager::DependencyManager() { - // Guard against request of ourself - // We could set the value to this, but since it doesn't make sense to access - // the DependencyManager instance from the outside let's set it to NULL - _instanceHash.insert(typeid(DependencyManager).name(), NULL); -} - DependencyManager::~DependencyManager() { foreach (Dependency* instance, _instanceHash) { if (instance) { - instance->deleteInstance(); + delete instance; } } _instanceHash.clear(); diff --git a/libraries/shared/src/DependencyManager.h b/libraries/shared/src/DependencyManager.h index 690058cab4..2a81941b8a 100644 --- a/libraries/shared/src/DependencyManager.h +++ b/libraries/shared/src/DependencyManager.h @@ -19,16 +19,24 @@ class DependencyManager { public: + // Only accessible method. + // usage: T* instance = DependencyManager::get(); template static T* get(); + // Any class T in the DependencyManager needs to subclass Dependency + // They also need to have protected constructor(s) and virtual destructor + // As well as declare DependencyManager a friend class class Dependency { - virtual void deleteInstance() = 0; + protected: + Dependency() {} + virtual ~Dependency() {} // Ensure the proper destruction of the object friend DependencyManager; }; + private: static DependencyManager& getInstance(); - DependencyManager(); + DependencyManager() {} ~DependencyManager(); typedef QHash InstanceHash; @@ -52,4 +60,4 @@ T* DependencyManager::get() { return newInstance; } -#endif // hifi_DependencyManager_h \ No newline at end of file +#endif // hifi_DependencyManager_h From 9aea2843ac89fbeae4a0463bc8e7d4c3f23691c2 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Fri, 12 Dec 2014 21:20:26 -0800 Subject: [PATCH 059/258] Remove pointer check --- libraries/shared/src/DependencyManager.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/libraries/shared/src/DependencyManager.cpp b/libraries/shared/src/DependencyManager.cpp index 41cb405ac7..c858cb7059 100644 --- a/libraries/shared/src/DependencyManager.cpp +++ b/libraries/shared/src/DependencyManager.cpp @@ -18,9 +18,7 @@ DependencyManager& DependencyManager::getInstance() { DependencyManager::~DependencyManager() { foreach (Dependency* instance, _instanceHash) { - if (instance) { - delete instance; - } + delete instance; } _instanceHash.clear(); } \ No newline at end of file From d28e274876491a7e0f5f4c05254294e9179c5cf7 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Sat, 13 Dec 2014 07:43:40 -0800 Subject: [PATCH 060/258] fix warning --- interface/src/Application.h | 2 ++ interface/src/voxels/VoxelSystem.cpp | 1 - 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/interface/src/Application.h b/interface/src/Application.h index f82b14b47e..1b51b99e77 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -12,6 +12,8 @@ #ifndef hifi_Application_h #define hifi_Application_h +// testing + #include #include diff --git a/interface/src/voxels/VoxelSystem.cpp b/interface/src/voxels/VoxelSystem.cpp index 2f4fd3f0fa..67f3d585ea 100644 --- a/interface/src/voxels/VoxelSystem.cpp +++ b/interface/src/voxels/VoxelSystem.cpp @@ -874,7 +874,6 @@ int VoxelSystem::updateNodeInArrays(VoxelTreeElement* node, bool reuseIndex, boo if (node->getShouldRender()) { glm::vec3 startVertex = node->getCorner(); float voxelScale = node->getScale(); - nodeColor const & color = node->getColor(); glBufferIndex nodeIndex = GLBUFFER_INDEX_UNKNOWN; if (reuseIndex && node->isKnownBufferIndex()) { From 31db2188cb0f77060b070c0a485b05887dc84101 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Sat, 13 Dec 2014 07:58:13 -0800 Subject: [PATCH 061/258] remove test comment --- interface/src/Application.h | 2 -- 1 file changed, 2 deletions(-) diff --git a/interface/src/Application.h b/interface/src/Application.h index 1b51b99e77..f82b14b47e 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -12,8 +12,6 @@ #ifndef hifi_Application_h #define hifi_Application_h -// testing - #include #include From ad2dee5eaab5afa8e684d7e3274697a005567e8e Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Sun, 14 Dec 2014 16:26:08 -0800 Subject: [PATCH 062/258] Switched devices to DependencyManager for Faceshift --- interface/src/devices/FaceTracker.h | 2 +- interface/src/devices/Faceshift.h | 3 +++ interface/src/devices/Visage.cpp | 9 +++++---- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/interface/src/devices/FaceTracker.h b/interface/src/devices/FaceTracker.h index 459f38cafc..75954871e5 100644 --- a/interface/src/devices/FaceTracker.h +++ b/interface/src/devices/FaceTracker.h @@ -23,8 +23,8 @@ class FaceTracker : public QObject { Q_OBJECT public: - FaceTracker(); + virtual ~FaceTracker() {} const glm::vec3& getHeadTranslation() const { return _headTranslation; } const glm::quat& getHeadRotation() const { return _headRotation; } diff --git a/interface/src/devices/Faceshift.h b/interface/src/devices/Faceshift.h index 3b4092c099..618a8fb975 100644 --- a/interface/src/devices/Faceshift.h +++ b/interface/src/devices/Faceshift.h @@ -19,6 +19,8 @@ #include #endif +#include + #include "FaceTracker.h" /// Handles interaction with the Faceshift software, which provides head position/orientation and facial features. @@ -27,6 +29,7 @@ class Faceshift : public FaceTracker { public: Faceshift(); + virtual ~Faceshift() {} void init(); diff --git a/interface/src/devices/Visage.cpp b/interface/src/devices/Visage.cpp index 9c7416c219..38dcdb4ce6 100644 --- a/interface/src/devices/Visage.cpp +++ b/interface/src/devices/Visage.cpp @@ -11,11 +11,12 @@ #include + +#include +#include #include #include -#include - #include "Application.h" #include "Visage.h" @@ -119,7 +120,7 @@ static const QMultiHash >& getActionUnitNameMap() const float TRANSLATION_SCALE = 20.0f; void Visage::init() { - connect(Application::getInstance()->getFaceshift(), SIGNAL(connectionStateChanged()), SLOT(updateEnabled())); + connect(DependencyManager::get(), SIGNAL(connectionStateChanged()), SLOT(updateEnabled())); updateEnabled(); } @@ -171,7 +172,7 @@ void Visage::reset() { void Visage::updateEnabled() { setEnabled(Menu::getInstance()->isOptionChecked(MenuOption::Visage) && !(Menu::getInstance()->isOptionChecked(MenuOption::Faceshift) && - Application::getInstance()->getFaceshift()->isConnectedOrConnecting())); + DependencyManager::get()->isConnectedOrConnecting())); } void Visage::setEnabled(bool enabled) { From 1d9e53e227026dfe685e082be3e2262a81724585 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Sun, 14 Dec 2014 16:28:28 -0800 Subject: [PATCH 063/258] Switched avatar to DependencyManager for Faceshift --- interface/src/avatar/Head.cpp | 17 +++++++++-------- interface/src/avatar/MyAvatar.cpp | 4 ++-- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/interface/src/avatar/Head.cpp b/interface/src/avatar/Head.cpp index 660ebfcbb3..4b1e9e358c 100644 --- a/interface/src/avatar/Head.cpp +++ b/interface/src/avatar/Head.cpp @@ -10,6 +10,7 @@ #include +#include #include #include "Application.h" @@ -196,14 +197,14 @@ void Head::simulate(float deltaTime, bool isMine, bool billboard) { _mouth2 = glm::mix(_audioJawOpen * MMMM_POWER, _mouth2, MMMM_PERIOD + randFloat() * MMMM_RANDOM_PERIOD); _mouth4 = glm::mix(_audioJawOpen, _mouth4, SMILE_PERIOD + randFloat() * SMILE_RANDOM_PERIOD); - Application::getInstance()->getFaceshift()->updateFakeCoefficients(_leftEyeBlink, - _rightEyeBlink, - _browAudioLift, - _audioJawOpen, - _mouth2, - _mouth3, - _mouth4, - _blendshapeCoefficients); + DependencyManager::get()->updateFakeCoefficients(_leftEyeBlink, + _rightEyeBlink, + _browAudioLift, + _audioJawOpen, + _mouth2, + _mouth3, + _mouth4, + _blendshapeCoefficients); } else { _saccade = glm::vec3(); } diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 32053ea076..17cda19980 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -22,6 +22,7 @@ #include #include +#include #include #include #include @@ -421,8 +422,7 @@ void MyAvatar::render(const glm::vec3& cameraPosition, RenderMode renderMode, bo } void MyAvatar::renderHeadMouse(int screenWidth, int screenHeight) const { - - Faceshift* faceshift = Application::getInstance()->getFaceshift(); + Faceshift* faceshift = DependencyManager::get(); float pixelsPerDegree = screenHeight / Menu::getInstance()->getFieldOfView(); From 39a19a297ffd27fa92082ff389a6831c27e80cd5 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Sun, 14 Dec 2014 16:31:03 -0800 Subject: [PATCH 064/258] Switched menu to DependencyManager for Faceshift --- interface/src/Menu.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 5e35f08e95..ec9b93e072 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -31,9 +31,10 @@ #include #include -#include +#include #include #include +#include #include "Application.h" #include "AccountManager.h" @@ -432,7 +433,7 @@ Menu::Menu() : MenuOption::Faceshift, 0, true, - appInstance->getFaceshift(), + DependencyManager::get(), SLOT(setTCPEnabled(bool))); #endif #ifdef HAVE_VISAGE From 1db3592d4c593a595fe1a5905f94fb2c6c0b0271 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Sun, 14 Dec 2014 19:56:42 -0800 Subject: [PATCH 065/258] Switched meFaceshifto DependencyManager for Faceshift --- interface/src/Application.cpp | 17 ++++++++++------- interface/src/Application.h | 4 +--- interface/src/devices/Faceshift.h | 2 +- 3 files changed, 12 insertions(+), 11 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 7a0e61240a..8a13ef650d 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -55,6 +55,7 @@ #include #include #include +#include #include #include #include @@ -1690,8 +1691,10 @@ int Application::getMouseDragStartedY() const { } FaceTracker* Application::getActiveFaceTracker() { + Faceshift* faceshift = DependencyManager::get(); + return (_dde.isActive() ? static_cast(&_dde) : - (_faceshift.isActive() ? static_cast(&_faceshift) : + (faceshift->isActive() ? static_cast(faceshift) : (_visage.isActive() ? static_cast(&_visage) : NULL))); } @@ -1976,7 +1979,7 @@ void Application::init() { #endif // initialize our face trackers after loading the menu settings - _faceshift.init(); + DependencyManager::get()->init(); _visage.init(); Leapmotion::init(); @@ -2101,13 +2104,13 @@ void Application::updateMouseRay() { void Application::updateFaceshift() { bool showWarnings = Menu::getInstance()->isOptionChecked(MenuOption::PipelineWarnings); PerformanceWarning warn(showWarnings, "Application::updateFaceshift()"); - + Faceshift* faceshift = DependencyManager::get(); // Update faceshift - _faceshift.update(); + faceshift->update(); // Copy angular velocity if measured by faceshift, to the head - if (_faceshift.isActive()) { - _myAvatar->getHead()->setAngularVelocity(_faceshift.getHeadAngularVelocity()); + if (faceshift->isActive()) { + _myAvatar->getHead()->setAngularVelocity(faceshift->getHeadAngularVelocity()); } } @@ -3549,7 +3552,7 @@ void Application::deleteVoxelAt(const VoxelDetail& voxel) { } void Application::resetSensors() { - _faceshift.reset(); + DependencyManager::get()->reset(); _visage.reset(); _dde.reset(); diff --git a/interface/src/Application.h b/interface/src/Application.h index f82b14b47e..61ae317713 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -220,8 +220,7 @@ public: int getMouseDragStartedY() const; int getTrueMouseDragStartedX() const { return _mouseDragStartedX; } int getTrueMouseDragStartedY() const { return _mouseDragStartedY; } - bool getLastMouseMoveWasSimulated() const { return _lastMouseMoveWasSimulated;; } - Faceshift* getFaceshift() { return &_faceshift; } + bool getLastMouseMoveWasSimulated() const { return _lastMouseMoveWasSimulated; } Visage* getVisage() { return &_visage; } DdeFaceTracker* getDDE() { return &_dde; } FaceTracker* getActiveFaceTracker(); @@ -532,7 +531,6 @@ private: AvatarManager _avatarManager; MyAvatar* _myAvatar; // TODO: move this and relevant code to AvatarManager (or MyAvatar as the case may be) - Faceshift _faceshift; Visage _visage; DdeFaceTracker _dde; diff --git a/interface/src/devices/Faceshift.h b/interface/src/devices/Faceshift.h index 618a8fb975..83be51c7fa 100644 --- a/interface/src/devices/Faceshift.h +++ b/interface/src/devices/Faceshift.h @@ -24,7 +24,7 @@ #include "FaceTracker.h" /// Handles interaction with the Faceshift software, which provides head position/orientation and facial features. -class Faceshift : public FaceTracker { +class Faceshift : public FaceTracker, public DependencyManager::Dependency { Q_OBJECT public: From e40961df12f4edeee6c69250bfa9e9e8da09f37d Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Sun, 14 Dec 2014 21:34:27 -0800 Subject: [PATCH 066/258] Checking that T is in fact derived from Dependency --- libraries/shared/src/DependencyManager.h | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/libraries/shared/src/DependencyManager.h b/libraries/shared/src/DependencyManager.h index 2a81941b8a..87c7c7b4a6 100644 --- a/libraries/shared/src/DependencyManager.h +++ b/libraries/shared/src/DependencyManager.h @@ -16,6 +16,7 @@ #include #include +#include class DependencyManager { public: @@ -56,7 +57,9 @@ T* DependencyManager::get() { // Found no instance in hash so we create one. T* newInstance = new T(); - getInstanceHash().insert(typeId, dynamic_cast(newInstance)); + instance = dynamic_cast(newInstance); + assert(instance != NULL); // If this triggers, check that T is derived from Dependency + getInstanceHash().insert(typeId, instance); return newInstance; } From 65094f21654e1ddd78232c20d9c0e8ff1e0985dd Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Sun, 14 Dec 2014 21:47:08 -0800 Subject: [PATCH 067/258] Update headers --- interface/src/Application.cpp | 1 + interface/src/Application.h | 1 - interface/src/Menu.cpp | 1 + interface/src/avatar/Head.cpp | 1 + interface/src/devices/Faceshift.cpp | 1 - interface/src/devices/Visage.cpp | 1 + 6 files changed, 4 insertions(+), 2 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 8a13ef650d..3706206f1f 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -77,6 +77,7 @@ #include "ModelUploader.h" #include "Util.h" +#include "devices/Faceshift.h" #include "devices/Leapmotion.h" #include "devices/MIDIManager.h" #include "devices/OculusManager.h" diff --git a/interface/src/Application.h b/interface/src/Application.h index 61ae317713..d1d15d22a9 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -54,7 +54,6 @@ #include "avatar/Avatar.h" #include "avatar/AvatarManager.h" #include "avatar/MyAvatar.h" -#include "devices/Faceshift.h" #include "devices/PrioVR.h" #include "devices/SixenseManager.h" #include "devices/Visage.h" diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index ec9b93e072..c08df2b2c5 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -38,6 +38,7 @@ #include "Application.h" #include "AccountManager.h" +#include "devices/Faceshift.h" #include "Menu.h" #include "scripting/LocationScriptingInterface.h" #include "scripting/MenuScriptingInterface.h" diff --git a/interface/src/avatar/Head.cpp b/interface/src/avatar/Head.cpp index 4b1e9e358c..a16cdd9270 100644 --- a/interface/src/avatar/Head.cpp +++ b/interface/src/avatar/Head.cpp @@ -11,6 +11,7 @@ #include #include +#include #include #include "Application.h" diff --git a/interface/src/devices/Faceshift.cpp b/interface/src/devices/Faceshift.cpp index fb74f416a9..5c1bbfe709 100644 --- a/interface/src/devices/Faceshift.cpp +++ b/interface/src/devices/Faceshift.cpp @@ -14,7 +14,6 @@ #include #include -#include "Application.h" #include "Faceshift.h" #include "Menu.h" #include "Util.h" diff --git a/interface/src/devices/Visage.cpp b/interface/src/devices/Visage.cpp index 38dcdb4ce6..51b927df75 100644 --- a/interface/src/devices/Visage.cpp +++ b/interface/src/devices/Visage.cpp @@ -18,6 +18,7 @@ #include #include "Application.h" +#include "Faceshift.h" #include "Visage.h" // this has to go after our normal includes, because its definition of HANDLE conflicts with Qt's From 738f23f326a0e1d9ac353aeaef8c6c769d542166 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Sun, 14 Dec 2014 22:30:13 -0800 Subject: [PATCH 068/258] Moved visage and dde over to DependencyManager --- interface/src/Application.cpp | 18 +++++++++++------- interface/src/Application.h | 8 +------- interface/src/Menu.cpp | 5 +++-- interface/src/avatar/Head.cpp | 11 +++++++---- interface/src/devices/DdeFaceTracker.h | 13 ++++++++----- interface/src/devices/Faceshift.h | 6 +++--- interface/src/devices/Visage.h | 11 ++++++----- 7 files changed, 39 insertions(+), 33 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 3706206f1f..fbe55071e4 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -77,11 +77,13 @@ #include "ModelUploader.h" #include "Util.h" +#include "devices/DdeFaceTracker.h" #include "devices/Faceshift.h" #include "devices/Leapmotion.h" #include "devices/MIDIManager.h" #include "devices/OculusManager.h" #include "devices/TV3DManager.h" +#include "devices/Visage.h" #include "renderer/ProgramObject.h" #include "gpu/Batch.h" @@ -1693,10 +1695,12 @@ int Application::getMouseDragStartedY() const { FaceTracker* Application::getActiveFaceTracker() { Faceshift* faceshift = DependencyManager::get(); + Visage* visage = DependencyManager::get(); + DdeFaceTracker* dde = DependencyManager::get(); - return (_dde.isActive() ? static_cast(&_dde) : + return (dde->isActive() ? static_cast(dde) : (faceshift->isActive() ? static_cast(faceshift) : - (_visage.isActive() ? static_cast(&_visage) : NULL))); + (visage->isActive() ? static_cast(visage) : NULL))); } struct SendVoxelsOperationArgs { @@ -1981,7 +1985,7 @@ void Application::init() { // initialize our face trackers after loading the menu settings DependencyManager::get()->init(); - _visage.init(); + DependencyManager::get()->init(); Leapmotion::init(); @@ -2120,7 +2124,7 @@ void Application::updateVisage() { PerformanceWarning warn(showWarnings, "Application::updateVisage()"); // Update Visage - _visage.update(); + DependencyManager::get()->update(); } void Application::updateDDE() { @@ -2128,7 +2132,7 @@ void Application::updateDDE() { PerformanceWarning warn(showWarnings, "Application::updateDDE()"); // Update Cara - _dde.update(); + DependencyManager::get()->update(); } void Application::updateMyAvatarLookAtPosition() { @@ -3554,8 +3558,8 @@ void Application::deleteVoxelAt(const VoxelDetail& voxel) { void Application::resetSensors() { DependencyManager::get()->reset(); - _visage.reset(); - _dde.reset(); + DependencyManager::get()->reset(); + DependencyManager::get()->reset(); OculusManager::reset(); diff --git a/interface/src/Application.h b/interface/src/Application.h index d1d15d22a9..833f1374ce 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -56,8 +56,6 @@ #include "avatar/MyAvatar.h" #include "devices/PrioVR.h" #include "devices/SixenseManager.h" -#include "devices/Visage.h" -#include "devices/DdeFaceTracker.h" #include "entities/EntityTreeRenderer.h" #include "renderer/AmbientOcclusionEffect.h" #include "renderer/DeferredLightingEffect.h" @@ -99,6 +97,7 @@ class QMouseEvent; class QSettings; class QWheelEvent; +class FaceTracker; class Node; class ProgramObject; @@ -220,8 +219,6 @@ public: int getTrueMouseDragStartedX() const { return _mouseDragStartedX; } int getTrueMouseDragStartedY() const { return _mouseDragStartedY; } bool getLastMouseMoveWasSimulated() const { return _lastMouseMoveWasSimulated; } - Visage* getVisage() { return &_visage; } - DdeFaceTracker* getDDE() { return &_dde; } FaceTracker* getActiveFaceTracker(); PrioVR* getPrioVR() { return &_prioVR; } BandwidthMeter* getBandwidthMeter() { return &_bandwidthMeter; } @@ -530,9 +527,6 @@ private: AvatarManager _avatarManager; MyAvatar* _myAvatar; // TODO: move this and relevant code to AvatarManager (or MyAvatar as the case may be) - Visage _visage; - DdeFaceTracker _dde; - PrioVR _prioVR; Camera _myCamera; // My view onto the world diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index c08df2b2c5..6c2c3966fc 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -39,6 +39,8 @@ #include "Application.h" #include "AccountManager.h" #include "devices/Faceshift.h" +#include "devices/OculusManager.h" +#include "devices/Visage.h" #include "Menu.h" #include "scripting/LocationScriptingInterface.h" #include "scripting/MenuScriptingInterface.h" @@ -51,7 +53,6 @@ #include "ui/ModelsBrowser.h" #include "ui/LoginDialog.h" #include "ui/NodeBounds.h" -#include "devices/OculusManager.h" Menu* Menu::_instance = NULL; @@ -439,7 +440,7 @@ Menu::Menu() : #endif #ifdef HAVE_VISAGE addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::Visage, 0, false, - appInstance->getVisage(), SLOT(updateEnabled())); + DependencyManager::get(), SLOT(updateEnabled())); #endif addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::RenderSkeletonCollisionShapes); diff --git a/interface/src/avatar/Head.cpp b/interface/src/avatar/Head.cpp index a16cdd9270..42b3c968e1 100644 --- a/interface/src/avatar/Head.cpp +++ b/interface/src/avatar/Head.cpp @@ -12,6 +12,7 @@ #include #include +#include #include #include "Application.h" @@ -77,11 +78,13 @@ void Head::simulate(float deltaTime, bool isMine, bool billboard) { // Only use face trackers when not playing back a recording. if (!myAvatar->isPlaying()) { FaceTracker* faceTracker = Application::getInstance()->getActiveFaceTracker(); - if ((_isFaceshiftConnected = faceTracker)) { + DdeFaceTracker* dde = DependencyManager::get(); + Faceshift* faceshift = DependencyManager::get(); + + if ((_isFaceshiftConnected = (faceshift == faceTracker))) { _blendshapeCoefficients = faceTracker->getBlendshapeCoefficients(); - _isFaceshiftConnected = true; - } else if (Application::getInstance()->getDDE()->isActive()) { - faceTracker = Application::getInstance()->getDDE(); + } else if (dde->isActive()) { + faceTracker = dde; _blendshapeCoefficients = faceTracker->getBlendshapeCoefficients(); } } diff --git a/interface/src/devices/DdeFaceTracker.h b/interface/src/devices/DdeFaceTracker.h index 68d9e7d487..d80aa043e4 100644 --- a/interface/src/devices/DdeFaceTracker.h +++ b/interface/src/devices/DdeFaceTracker.h @@ -14,16 +14,14 @@ #include +#include + #include "FaceTracker.h" -class DdeFaceTracker : public FaceTracker { +class DdeFaceTracker : public FaceTracker, public DependencyManager::Dependency { Q_OBJECT public: - DdeFaceTracker(); - DdeFaceTracker(const QHostAddress& host, quint16 port); - ~DdeFaceTracker(); - //initialization void init(); void reset(); @@ -57,6 +55,11 @@ private slots: void socketStateChanged(QAbstractSocket::SocketState socketState); private: + DdeFaceTracker(); + DdeFaceTracker(const QHostAddress& host, quint16 port); + ~DdeFaceTracker(); + friend DependencyManager; + float getBlendshapeCoefficient(int index) const; void decodePacket(const QByteArray& buffer); diff --git a/interface/src/devices/Faceshift.h b/interface/src/devices/Faceshift.h index 83be51c7fa..3cca8f2bb1 100644 --- a/interface/src/devices/Faceshift.h +++ b/interface/src/devices/Faceshift.h @@ -28,9 +28,6 @@ class Faceshift : public FaceTracker, public DependencyManager::Dependency { Q_OBJECT public: - Faceshift(); - virtual ~Faceshift() {} - void init(); bool isConnectedOrConnecting() const; @@ -90,6 +87,9 @@ private slots: void readFromSocket(); private: + Faceshift(); + virtual ~Faceshift() {} + friend DependencyManager; float getBlendshapeCoefficient(int index) const; diff --git a/interface/src/devices/Visage.h b/interface/src/devices/Visage.h index 33e2f0a7e1..73edddc4d7 100644 --- a/interface/src/devices/Visage.h +++ b/interface/src/devices/Visage.h @@ -16,6 +16,8 @@ #include #include +#include + #include "FaceTracker.h" namespace VisageSDK { @@ -24,14 +26,10 @@ namespace VisageSDK { } /// Handles input from the Visage webcam feature tracking software. -class Visage : public FaceTracker { +class Visage : public FaceTracker, public DependencyManager::Dependency { Q_OBJECT public: - - Visage(); - virtual ~Visage(); - void init(); bool isActive() const { return _active; } @@ -44,6 +42,9 @@ public slots: void updateEnabled(); private: + Visage(); + virtual ~Visage(); + friend DependencyManager; #ifdef HAVE_VISAGE VisageSDK::VisageTracker2* _tracker; From e253b8afa4cd83ef5dd89ad38d6634ce742aa9ea Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Fri, 12 Dec 2014 14:18:23 -0800 Subject: [PATCH 069/258] move TextureCache out of interface and Application --- interface/CMakeLists.txt | 2 +- interface/src/Application.cpp | 15 ++++++++----- interface/src/Application.h | 11 ++++++---- interface/src/MetavoxelSystem.h | 2 +- interface/src/avatar/Avatar.cpp | 2 +- interface/src/renderer/GeometryCache.h | 2 +- interface/src/renderer/Model.h | 2 +- interface/src/ui/overlays/BillboardOverlay.h | 3 ++- .../render-utils/src}/TextureCache.cpp | 22 +++++++++++++++---- .../render-utils/src}/TextureCache.h | 8 ++++++- 10 files changed, 49 insertions(+), 20 deletions(-) rename {interface/src/renderer => libraries/render-utils/src}/TextureCache.cpp (98%) rename {interface/src/renderer => libraries/render-utils/src}/TextureCache.h (97%) diff --git a/interface/CMakeLists.txt b/interface/CMakeLists.txt index 38dd02c655..ffc401ba63 100644 --- a/interface/CMakeLists.txt +++ b/interface/CMakeLists.txt @@ -107,7 +107,7 @@ endif() add_executable(${TARGET_NAME} MACOSX_BUNDLE ${INTERFACE_SRCS} ${QM}) # link required hifi libraries -link_hifi_libraries(shared octree voxels gpu fbx metavoxels networking entities avatars audio animation script-engine physics) +link_hifi_libraries(shared octree voxels gpu fbx metavoxels networking entities avatars audio animation script-engine physics render-utils) # find any optional and required libraries find_package(ZLIB REQUIRED) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index fbe55071e4..0c1d2c3b9f 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -177,6 +177,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) : _touchAvgY(0.0f), _isTouchPressed(false), _mousePressed(false), + _textureCache(NULL), _audio(), _enableProcessVoxelsThread(true), _octreeProcessor(), @@ -194,6 +195,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) : _isVSyncOn(true), _aboutToQuit(false) { + _textureCache = TextureCache::getInstance(); // read the ApplicationInfo.ini file for Name/Version/Domain information QSettings applicationInfo(Application::resourcesPath() + "info/ApplicationInfo.ini", QSettings::IniFormat); @@ -621,10 +623,10 @@ void Application::paintGL() { // Set the desired FBO texture size. If it hasn't changed, this does nothing. // Otherwise, it must rebuild the FBOs if (OculusManager::isConnected()) { - _textureCache.setFrameBufferSize(OculusManager::getRenderTargetSize()); + _textureCache->setFrameBufferSize(OculusManager::getRenderTargetSize()); } else { QSize fbSize = _glWidget->getDeviceSize() * getRenderResolutionScale(); - _textureCache.setFrameBufferSize(fbSize); + _textureCache->setFrameBufferSize(fbSize); } glEnable(GL_LINE_SMOOTH); @@ -2042,6 +2044,9 @@ void Application::init() { // save settings when avatar changes connect(_myAvatar, &MyAvatar::transformChanged, this, &Application::bumpSettings); + + // make sure our texture cache knows about window size changes + _textureCache->associateWithWidget(getGLWidget()); } void Application::closeMirrorView() { @@ -2772,7 +2777,7 @@ glm::vec3 Application::getSunDirection() { void Application::updateShadowMap() { PerformanceTimer perfTimer("shadowMap"); - QOpenGLFramebufferObject* fbo = _textureCache.getShadowFramebufferObject(); + QOpenGLFramebufferObject* fbo = _textureCache->getShadowFramebufferObject(); fbo->bind(); glEnable(GL_DEPTH_TEST); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); @@ -2937,7 +2942,7 @@ void Application::setupWorldLight() { } QImage Application::renderAvatarBillboard() { - _textureCache.getPrimaryFramebufferObject()->bind(); + _textureCache->getPrimaryFramebufferObject()->bind(); // the "glow" here causes an alpha of one Glower glower; @@ -2948,7 +2953,7 @@ QImage Application::renderAvatarBillboard() { QImage image(BILLBOARD_SIZE, BILLBOARD_SIZE, QImage::Format_ARGB32); glReadPixels(0, 0, BILLBOARD_SIZE, BILLBOARD_SIZE, GL_BGRA, GL_UNSIGNED_BYTE, image.bits()); - _textureCache.getPrimaryFramebufferObject()->release(); + _textureCache->getPrimaryFramebufferObject()->release(); return image; } diff --git a/interface/src/Application.h b/interface/src/Application.h index 833f1374ce..99184e990d 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -12,6 +12,9 @@ #ifndef hifi_Application_h #define hifi_Application_h +// include this before QGLWidget, which includes an earlier version of OpenGL +#include "InterfaceConfig.h" + #include #include @@ -34,9 +37,10 @@ #include #include #include +#include #include #include -#include +#include #include #include @@ -61,7 +65,6 @@ #include "renderer/DeferredLightingEffect.h" #include "renderer/GeometryCache.h" #include "renderer/GlowEffect.h" -#include "renderer/TextureCache.h" #include "scripting/ControllerScriptingInterface.h" #include "ui/BandwidthDialog.h" #include "ui/BandwidthMeter.h" @@ -251,7 +254,7 @@ public: GeometryCache* getGeometryCache() { return &_geometryCache; } AnimationCache* getAnimationCache() { return &_animationCache; } - TextureCache* getTextureCache() { return &_textureCache; } + TextureCache* getTextureCache() { return _textureCache; } DeferredLightingEffect* getDeferredLightingEffect() { return &_deferredLightingEffect; } GlowEffect* getGlowEffect() { return &_glowEffect; } ControllerScriptingInterface* getControllerScriptingInterface() { return &_controllerScriptingInterface; } @@ -571,7 +574,7 @@ private: GeometryCache _geometryCache; AnimationCache _animationCache; - TextureCache _textureCache; + TextureCache* _textureCache; DeferredLightingEffect _deferredLightingEffect; GlowEffect _glowEffect; diff --git a/interface/src/MetavoxelSystem.h b/interface/src/MetavoxelSystem.h index 2ebf7e1146..0c0f9b49b7 100644 --- a/interface/src/MetavoxelSystem.h +++ b/interface/src/MetavoxelSystem.h @@ -20,9 +20,9 @@ #include #include +#include #include "renderer/ProgramObject.h" -#include "renderer/TextureCache.h" class HeightfieldBaseLayerBatch; class HeightfieldSplatBatch; diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index c680c75056..e4ea33a180 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #include "Application.h" #include "Avatar.h" @@ -36,7 +37,6 @@ #include "Recorder.h" #include "world.h" #include "devices/OculusManager.h" -#include "renderer/TextureCache.h" #include "ui/TextRenderer.h" using namespace std; diff --git a/interface/src/renderer/GeometryCache.h b/interface/src/renderer/GeometryCache.h index 6faad93fe4..2d06953eb5 100644 --- a/interface/src/renderer/GeometryCache.h +++ b/interface/src/renderer/GeometryCache.h @@ -13,7 +13,7 @@ #define hifi_GeometryCache_h // include this before QOpenGLBuffer, which includes an earlier version of OpenGL -#include "InterfaceConfig.h" +#include #include #include diff --git a/interface/src/renderer/Model.h b/interface/src/renderer/Model.h index e875c8f06c..74b227083f 100644 --- a/interface/src/renderer/Model.h +++ b/interface/src/renderer/Model.h @@ -21,13 +21,13 @@ #include #include #include +#include #include "AnimationHandle.h" #include "GeometryCache.h" #include "InterfaceConfig.h" #include "JointState.h" #include "ProgramObject.h" -#include "TextureCache.h" class QScriptEngine; diff --git a/interface/src/ui/overlays/BillboardOverlay.h b/interface/src/ui/overlays/BillboardOverlay.h index 03daef934d..dcb8ab8b0c 100644 --- a/interface/src/ui/overlays/BillboardOverlay.h +++ b/interface/src/ui/overlays/BillboardOverlay.h @@ -15,8 +15,9 @@ #include #include +#include + #include "Base3DOverlay.h" -#include "../../renderer/TextureCache.h" class BillboardOverlay : public Base3DOverlay { Q_OBJECT diff --git a/interface/src/renderer/TextureCache.cpp b/libraries/render-utils/src/TextureCache.cpp similarity index 98% rename from interface/src/renderer/TextureCache.cpp rename to libraries/render-utils/src/TextureCache.cpp index f40f0e3faf..11ccd4b797 100644 --- a/interface/src/renderer/TextureCache.cpp +++ b/libraries/render-utils/src/TextureCache.cpp @@ -10,20 +10,26 @@ // // include this before QGLWidget, which includes an earlier version of OpenGL -#include "InterfaceConfig.h" +#include #include #include #include +#include #include #include #include #include -#include "Application.h" #include "TextureCache.h" +TextureCache* TextureCache::getInstance() { + static TextureCache instance; + return &instance; +} + + TextureCache::TextureCache() : _permutationNormalTextureID(0), _whiteTextureID(0), @@ -35,7 +41,8 @@ TextureCache::TextureCache() : _secondaryFramebufferObject(NULL), _tertiaryFramebufferObject(NULL), _shadowFramebufferObject(NULL), - _frameBufferSize(100, 100) + _frameBufferSize(100, 100), + _associatedWidget(NULL) { } @@ -350,9 +357,16 @@ QSharedPointer TextureCache::createResource(const QUrl& url, &Resource::allReferencesCleared); } +void TextureCache::associateWithWidget(QGLWidget* widget) { + if (_associatedWidget) { + _associatedWidget->removeEventFilter(this); + } + _associatedWidget = widget; + _associatedWidget->installEventFilter(this); +} + QOpenGLFramebufferObject* TextureCache::createFramebufferObject() { QOpenGLFramebufferObject* fbo = new QOpenGLFramebufferObject(_frameBufferSize); - Application::getInstance()->getGLWidget()->installEventFilter(this); glBindTexture(GL_TEXTURE_2D, fbo->texture()); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); diff --git a/interface/src/renderer/TextureCache.h b/libraries/render-utils/src/TextureCache.h similarity index 97% rename from interface/src/renderer/TextureCache.h rename to libraries/render-utils/src/TextureCache.h index 66734da9cd..3808485135 100644 --- a/interface/src/renderer/TextureCache.h +++ b/libraries/render-utils/src/TextureCache.h @@ -14,10 +14,11 @@ #include #include +#include #include -#include "InterfaceConfig.h" +#include class QOpenGLFramebufferObject; @@ -32,10 +33,14 @@ class TextureCache : public ResourceCache { Q_OBJECT public: + + static TextureCache* getInstance(); TextureCache(); virtual ~TextureCache(); + void associateWithWidget(QGLWidget* widget); + /// Sets the desired texture resolution for the framebuffer objects. void setFrameBufferSize(QSize frameBufferSize); const QSize& getFrameBufferSize() const { return _frameBufferSize; } @@ -115,6 +120,7 @@ private: GLuint _shadowDepthTextureID; QSize _frameBufferSize; + QGLWidget* _associatedWidget; }; /// A simple object wrapper for an OpenGL texture. From 2df4c017f1083c54a2fa00e199456b4813192f27 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Fri, 12 Dec 2014 14:56:27 -0800 Subject: [PATCH 070/258] move GeometryCache out of application and remove dependency on Model --- interface/src/Application.h | 2 +- interface/src/renderer/Model.cpp | 44 ++++++++++++++- interface/src/renderer/Model.h | 25 ++++++++- .../render-utils/src}/GeometryCache.cpp | 55 +++++-------------- .../render-utils/src}/GeometryCache.h | 12 ---- 5 files changed, 81 insertions(+), 57 deletions(-) rename {interface/src/renderer => libraries/render-utils/src}/GeometryCache.cpp (95%) rename {interface/src/renderer => libraries/render-utils/src}/GeometryCache.h (92%) diff --git a/interface/src/Application.h b/interface/src/Application.h index 99184e990d..5b97c1301f 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -35,6 +35,7 @@ #include #include +#include #include #include #include @@ -63,7 +64,6 @@ #include "entities/EntityTreeRenderer.h" #include "renderer/AmbientOcclusionEffect.h" #include "renderer/DeferredLightingEffect.h" -#include "renderer/GeometryCache.h" #include "renderer/GlowEffect.h" #include "scripting/ControllerScriptingInterface.h" #include "ui/BandwidthDialog.h" diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index fd54f67377..c0295fd9b5 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -1149,7 +1149,7 @@ void Blender::run() { } } // post the result to the geometry cache, which will dispatch to the model if still alive - QMetaObject::invokeMethod(Application::getInstance()->getGeometryCache(), "setBlendedVertices", + QMetaObject::invokeMethod(ModelBlender::getInstance(), "setBlendedVertices", Q_ARG(const QPointer&, _model), Q_ARG(int, _blendNumber), Q_ARG(const QWeakPointer&, _geometry), Q_ARG(const QVector&, vertices), Q_ARG(const QVector&, normals)); @@ -1312,7 +1312,7 @@ void Model::simulateInternal(float deltaTime) { // post the blender if we're not currently waiting for one to finish if (geometry.hasBlendedMeshes() && _blendshapeCoefficients != _blendedBlendshapeCoefficients) { _blendedBlendshapeCoefficients = _blendshapeCoefficients; - Application::getInstance()->getGeometryCache()->noteRequiresBlend(this); + ModelBlender::getInstance()->noteRequiresBlend(this); } } @@ -2544,3 +2544,43 @@ int Model::renderMeshesFromList(QVector& list, gpu::Batch& batch, RenderMod return meshPartsRendered; } + +ModelBlender* ModelBlender::getInstance() { + static ModelBlender instance; + return &instance; +} + +ModelBlender::ModelBlender() : + _pendingBlenders(0) { +} + +ModelBlender::~ModelBlender() { +} + +void ModelBlender::noteRequiresBlend(Model* model) { + if (_pendingBlenders < QThread::idealThreadCount()) { + if (model->maybeStartBlender()) { + _pendingBlenders++; + } + return; + } + if (!_modelsRequiringBlends.contains(model)) { + _modelsRequiringBlends.append(model); + } +} + +void ModelBlender::setBlendedVertices(const QPointer& model, int blendNumber, + const QWeakPointer& geometry, const QVector& vertices, const QVector& normals) { + if (!model.isNull()) { + model->setBlendedVertices(blendNumber, geometry, vertices, normals); + } + _pendingBlenders--; + while (!_modelsRequiringBlends.isEmpty()) { + Model* nextModel = _modelsRequiringBlends.takeFirst(); + if (nextModel && nextModel->maybeStartBlender()) { + _pendingBlenders++; + return; + } + } +} + diff --git a/interface/src/renderer/Model.h b/interface/src/renderer/Model.h index 74b227083f..d74f95095d 100644 --- a/interface/src/renderer/Model.h +++ b/interface/src/renderer/Model.h @@ -453,12 +453,35 @@ private: static int renderMeshesForModelsInScene(gpu::Batch& batch, RenderMode mode, bool translucent, float alphaThreshold, bool hasLightmap, bool hasTangents, bool hasSpecular, bool isSkinned, RenderArgs* args); - }; Q_DECLARE_METATYPE(QPointer) Q_DECLARE_METATYPE(QWeakPointer) Q_DECLARE_METATYPE(QVector) +/// Handle management of pending models that need blending +class ModelBlender : public QObject { + Q_OBJECT + +public: + + static ModelBlender* getInstance(); + + ModelBlender(); + virtual ~ModelBlender(); + + + /// Adds the specified model to the list requiring vertex blends. + void noteRequiresBlend(Model* model); + +public slots: + void setBlendedVertices(const QPointer& model, int blendNumber, const QWeakPointer& geometry, + const QVector& vertices, const QVector& normals); + +private: + QList > _modelsRequiringBlends; + int _pendingBlenders; +}; + #endif // hifi_Model_h diff --git a/interface/src/renderer/GeometryCache.cpp b/libraries/render-utils/src/GeometryCache.cpp similarity index 95% rename from interface/src/renderer/GeometryCache.cpp rename to libraries/render-utils/src/GeometryCache.cpp index d753901243..6e0c40c28d 100644 --- a/interface/src/renderer/GeometryCache.cpp +++ b/libraries/render-utils/src/GeometryCache.cpp @@ -15,13 +15,13 @@ #include #include -#include "Application.h" -#include "GeometryCache.h" -#include "Model.h" -#include "world.h" +#include -GeometryCache::GeometryCache() : - _pendingBlenders(0) { +#include "TextureCache.h" + +#include "GeometryCache.h" + +GeometryCache::GeometryCache() { } GeometryCache::~GeometryCache() { @@ -505,33 +505,6 @@ QSharedPointer GeometryCache::getGeometry(const QUrl& url, cons return getResource(url, fallback, delayLoad).staticCast(); } -void GeometryCache::noteRequiresBlend(Model* model) { - if (_pendingBlenders < QThread::idealThreadCount()) { - if (model->maybeStartBlender()) { - _pendingBlenders++; - } - return; - } - if (!_modelsRequiringBlends.contains(model)) { - _modelsRequiringBlends.append(model); - } -} - -void GeometryCache::setBlendedVertices(const QPointer& model, int blendNumber, - const QWeakPointer& geometry, const QVector& vertices, const QVector& normals) { - if (!model.isNull()) { - model->setBlendedVertices(blendNumber, geometry, vertices, normals); - } - _pendingBlenders--; - while (!_modelsRequiringBlends.isEmpty()) { - Model* nextModel = _modelsRequiringBlends.takeFirst(); - if (nextModel && nextModel->maybeStartBlender()) { - _pendingBlenders++; - return; - } - } -} - QSharedPointer GeometryCache::createResource(const QUrl& url, const QSharedPointer& fallback, bool delayLoad, const void* extra) { QSharedPointer geometry(new NetworkGeometry(url, fallback.staticCast(), delayLoad), @@ -732,19 +705,19 @@ void NetworkGeometry::setTextureWithNameToURL(const QString& name, const QUrl& u QSharedPointer matchingTexture = QSharedPointer(); if (part.diffuseTextureName == name) { part.diffuseTexture = - Application::getInstance()->getTextureCache()->getTexture(url, DEFAULT_TEXTURE, + TextureCache::getInstance()->getTexture(url, DEFAULT_TEXTURE, _geometry.meshes[i].isEye, QByteArray()); part.diffuseTexture->setLoadPriorities(_loadPriorities); } else if (part.normalTextureName == name) { - part.normalTexture = Application::getInstance()->getTextureCache()->getTexture(url, DEFAULT_TEXTURE, + part.normalTexture = TextureCache::getInstance()->getTexture(url, DEFAULT_TEXTURE, false, QByteArray()); part.normalTexture->setLoadPriorities(_loadPriorities); } else if (part.specularTextureName == name) { - part.specularTexture = Application::getInstance()->getTextureCache()->getTexture(url, DEFAULT_TEXTURE, + part.specularTexture = TextureCache::getInstance()->getTexture(url, DEFAULT_TEXTURE, false, QByteArray()); part.specularTexture->setLoadPriorities(_loadPriorities); } else if (part.emissiveTextureName == name) { - part.emissiveTexture = Application::getInstance()->getTextureCache()->getTexture(url, DEFAULT_TEXTURE, + part.emissiveTexture = TextureCache::getInstance()->getTexture(url, DEFAULT_TEXTURE, false, QByteArray()); part.emissiveTexture->setLoadPriorities(_loadPriorities); } @@ -945,28 +918,28 @@ void NetworkGeometry::setGeometry(const FBXGeometry& geometry) { foreach (const FBXMeshPart& part, mesh.parts) { NetworkMeshPart networkPart; if (!part.diffuseTexture.filename.isEmpty()) { - networkPart.diffuseTexture = Application::getInstance()->getTextureCache()->getTexture( + networkPart.diffuseTexture = TextureCache::getInstance()->getTexture( _textureBase.resolved(QUrl(part.diffuseTexture.filename)), DEFAULT_TEXTURE, mesh.isEye, part.diffuseTexture.content); networkPart.diffuseTextureName = part.diffuseTexture.name; networkPart.diffuseTexture->setLoadPriorities(_loadPriorities); } if (!part.normalTexture.filename.isEmpty()) { - networkPart.normalTexture = Application::getInstance()->getTextureCache()->getTexture( + networkPart.normalTexture = TextureCache::getInstance()->getTexture( _textureBase.resolved(QUrl(part.normalTexture.filename)), NORMAL_TEXTURE, false, part.normalTexture.content); networkPart.normalTextureName = part.normalTexture.name; networkPart.normalTexture->setLoadPriorities(_loadPriorities); } if (!part.specularTexture.filename.isEmpty()) { - networkPart.specularTexture = Application::getInstance()->getTextureCache()->getTexture( + networkPart.specularTexture = TextureCache::getInstance()->getTexture( _textureBase.resolved(QUrl(part.specularTexture.filename)), SPECULAR_TEXTURE, false, part.specularTexture.content); networkPart.specularTextureName = part.specularTexture.name; networkPart.specularTexture->setLoadPriorities(_loadPriorities); } if (!part.emissiveTexture.filename.isEmpty()) { - networkPart.emissiveTexture = Application::getInstance()->getTextureCache()->getTexture( + networkPart.emissiveTexture = TextureCache::getInstance()->getTexture( _textureBase.resolved(QUrl(part.emissiveTexture.filename)), EMISSIVE_TEXTURE, false, part.emissiveTexture.content); networkPart.emissiveTextureName = part.emissiveTexture.name; diff --git a/interface/src/renderer/GeometryCache.h b/libraries/render-utils/src/GeometryCache.h similarity index 92% rename from interface/src/renderer/GeometryCache.h rename to libraries/render-utils/src/GeometryCache.h index 2d06953eb5..9fe6a7d5a2 100644 --- a/interface/src/renderer/GeometryCache.h +++ b/libraries/render-utils/src/GeometryCache.h @@ -26,7 +26,6 @@ #include "gpu/Stream.h" -class Model; class NetworkGeometry; class NetworkMesh; class NetworkTexture; @@ -52,14 +51,6 @@ public: /// \param delayLoad if true, don't load the geometry immediately; wait until load is first requested QSharedPointer getGeometry(const QUrl& url, const QUrl& fallback = QUrl(), bool delayLoad = false); - /// Adds the specified model to the list requiring vertex blends. - void noteRequiresBlend(Model* model); - -public slots: - - void setBlendedVertices(const QPointer& model, int blendNumber, const QWeakPointer& geometry, - const QVector& vertices, const QVector& normals); - protected: virtual QSharedPointer createResource(const QUrl& url, @@ -78,9 +69,6 @@ private: QHash _gridBuffers; QHash > _networkGeometry; - - QList > _modelsRequiringBlends; - int _pendingBlenders; }; /// Geometry loaded from the network. From e9ea6b20ce0bd5904af864da058a16d5ef7f7305 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Fri, 12 Dec 2014 15:29:42 -0800 Subject: [PATCH 071/258] use TextureCache::getInstance() instead of Application::getInstance()->getTextureCache() --- interface/src/Application.cpp | 2 +- interface/src/MetavoxelSystem.cpp | 18 +++++++-------- interface/src/ModelUploader.cpp | 2 +- interface/src/devices/OculusManager.cpp | 6 ++--- .../src/renderer/AmbientOcclusionEffect.cpp | 6 ++--- .../src/renderer/DeferredLightingEffect.cpp | 22 +++++++++---------- interface/src/renderer/GlowEffect.cpp | 14 ++++++------ interface/src/renderer/Model.cpp | 20 ++++++++--------- interface/src/ui/MetavoxelEditor.cpp | 2 +- interface/src/voxels/VoxelSystem.cpp | 6 ++--- 10 files changed, 49 insertions(+), 49 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 0c1d2c3b9f..eaaeb0534f 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -716,7 +716,7 @@ void Application::paintGL() { _glowEffect.prepare(); // Viewport is assigned to the size of the framebuffer - QSize size = Application::getInstance()->getTextureCache()->getPrimaryFramebufferObject()->size(); + QSize size = TextureCache::getInstance()->getPrimaryFramebufferObject()->size(); glViewport(0, 0, size.width(), size.height()); glMatrixMode(GL_MODELVIEW); diff --git a/interface/src/MetavoxelSystem.cpp b/interface/src/MetavoxelSystem.cpp index 002acec9ed..2e3e9796f3 100644 --- a/interface/src/MetavoxelSystem.cpp +++ b/interface/src/MetavoxelSystem.cpp @@ -205,7 +205,7 @@ void MetavoxelSystem::render() { glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); - Application::getInstance()->getTextureCache()->setPrimaryDrawBuffers(true, true); + TextureCache::getInstance()->setPrimaryDrawBuffers(true, true); glDisable(GL_BLEND); glEnable(GL_CULL_FACE); @@ -251,7 +251,7 @@ void MetavoxelSystem::render() { glPopMatrix(); } - Application::getInstance()->getTextureCache()->setPrimaryDrawBuffers(true, false); + TextureCache::getInstance()->setPrimaryDrawBuffers(true, false); _baseHeightfieldProgram.release(); @@ -348,7 +348,7 @@ void MetavoxelSystem::render() { } if (!_voxelBaseBatches.isEmpty()) { - Application::getInstance()->getTextureCache()->setPrimaryDrawBuffers(true, true); + TextureCache::getInstance()->setPrimaryDrawBuffers(true, true); glEnableClientState(GL_VERTEX_ARRAY); glDisable(GL_BLEND); @@ -383,7 +383,7 @@ void MetavoxelSystem::render() { glDisable(GL_ALPHA_TEST); glEnable(GL_BLEND); - Application::getInstance()->getTextureCache()->setPrimaryDrawBuffers(true, false); + TextureCache::getInstance()->setPrimaryDrawBuffers(true, false); if (!_voxelSplatBatches.isEmpty()) { glDepthFunc(GL_LEQUAL); @@ -463,7 +463,7 @@ void MetavoxelSystem::render() { } if (!_hermiteBatches.isEmpty() && Menu::getInstance()->isOptionChecked(MenuOption::DisplayHermiteData)) { - Application::getInstance()->getTextureCache()->setPrimaryDrawBuffers(true, true); + TextureCache::getInstance()->setPrimaryDrawBuffers(true, true); glEnableClientState(GL_VERTEX_ARRAY); @@ -486,7 +486,7 @@ void MetavoxelSystem::render() { glDisableClientState(GL_VERTEX_ARRAY); - Application::getInstance()->getTextureCache()->setPrimaryDrawBuffers(true, false); + TextureCache::getInstance()->setPrimaryDrawBuffers(true, false); } _hermiteBatches.clear(); @@ -797,7 +797,7 @@ void MetavoxelSystem::applyMaterialEdit(const MetavoxelEditMessage& message, boo Q_ARG(bool, reliable)); return; } - QSharedPointer texture = Application::getInstance()->getTextureCache()->getTexture( + QSharedPointer texture = TextureCache::getInstance()->getTexture( material->getDiffuse(), SPLAT_TEXTURE); if (texture->isLoaded()) { MetavoxelEditMessage newMessage = message; @@ -1180,7 +1180,7 @@ void VoxelBuffer::render(bool cursor) { for (int i = 0; i < _materials.size(); i++) { const SharedObjectPointer material = _materials.at(i); if (material) { - _networkTextures[i] = Application::getInstance()->getTextureCache()->getTexture( + _networkTextures[i] = TextureCache::getInstance()->getTexture( static_cast(material.data())->getDiffuse(), SPLAT_TEXTURE); } } @@ -2234,7 +2234,7 @@ void HeightfieldNodeRenderer::render(const HeightfieldNodePointer& node, const g for (int i = 0; i < materials.size(); i++) { const SharedObjectPointer& material = materials.at(i); if (material) { - _networkTextures[i] = Application::getInstance()->getTextureCache()->getTexture( + _networkTextures[i] = TextureCache::getInstance()->getTexture( static_cast(material.data())->getDiffuse(), SPLAT_TEXTURE); } } diff --git a/interface/src/ModelUploader.cpp b/interface/src/ModelUploader.cpp index d9e8ed0c40..6c167ca59a 100644 --- a/interface/src/ModelUploader.cpp +++ b/interface/src/ModelUploader.cpp @@ -473,7 +473,7 @@ void ModelUploader::processCheck() { QMessageBox::Ok); Application::getInstance()->getGeometryCache()->refresh(_url); foreach (const QByteArray& filename, _textureFilenames) { - Application::getInstance()->getTextureCache()->refresh(_textureBase + filename); + TextureCache::getInstance()->refresh(_textureBase + filename); } deleteLater(); break; diff --git a/interface/src/devices/OculusManager.cpp b/interface/src/devices/OculusManager.cpp index dfec98c358..0eb0c732c9 100644 --- a/interface/src/devices/OculusManager.cpp +++ b/interface/src/devices/OculusManager.cpp @@ -449,7 +449,7 @@ void OculusManager::display(const glm::quat &bodyOrientation, const glm::vec3 &p if (Menu::getInstance()->isOptionChecked(MenuOption::EnableGlowEffect)) { Application::getInstance()->getGlowEffect()->prepare(); } else { - Application::getInstance()->getTextureCache()->getPrimaryFramebufferObject()->bind(); + TextureCache::getInstance()->getPrimaryFramebufferObject()->bind(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } @@ -555,8 +555,8 @@ void OculusManager::display(const glm::quat &bodyOrientation, const glm::vec3 &p QOpenGLFramebufferObject* fbo = Application::getInstance()->getGlowEffect()->render(true); glBindTexture(GL_TEXTURE_2D, fbo->texture()); } else { - Application::getInstance()->getTextureCache()->getPrimaryFramebufferObject()->release(); - glBindTexture(GL_TEXTURE_2D, Application::getInstance()->getTextureCache()->getPrimaryFramebufferObject()->texture()); + TextureCache::getInstance()->getPrimaryFramebufferObject()->release(); + glBindTexture(GL_TEXTURE_2D, TextureCache::getInstance()->getPrimaryFramebufferObject()->texture()); } // restore our normal viewport diff --git a/interface/src/renderer/AmbientOcclusionEffect.cpp b/interface/src/renderer/AmbientOcclusionEffect.cpp index f75ed7e8c3..9ef0fa2d82 100644 --- a/interface/src/renderer/AmbientOcclusionEffect.cpp +++ b/interface/src/renderer/AmbientOcclusionEffect.cpp @@ -98,7 +98,7 @@ void AmbientOcclusionEffect::render() { glDisable(GL_DEPTH_TEST); glDepthMask(GL_FALSE); - glBindTexture(GL_TEXTURE_2D, Application::getInstance()->getTextureCache()->getPrimaryDepthTextureID()); + glBindTexture(GL_TEXTURE_2D, TextureCache::getInstance()->getPrimaryDepthTextureID()); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, _rotationTextureID); @@ -116,7 +116,7 @@ void AmbientOcclusionEffect::render() { glGetIntegerv(GL_VIEWPORT, viewport); const int VIEWPORT_X_INDEX = 0; const int VIEWPORT_WIDTH_INDEX = 2; - QOpenGLFramebufferObject* primaryFBO = Application::getInstance()->getTextureCache()->getPrimaryFramebufferObject(); + QOpenGLFramebufferObject* primaryFBO = TextureCache::getInstance()->getPrimaryFramebufferObject(); float sMin = viewport[VIEWPORT_X_INDEX] / (float)primaryFBO->width(); float sWidth = viewport[VIEWPORT_WIDTH_INDEX] / (float)primaryFBO->width(); @@ -141,7 +141,7 @@ void AmbientOcclusionEffect::render() { glActiveTexture(GL_TEXTURE0); // now render secondary to primary with 4x4 blur - Application::getInstance()->getTextureCache()->getPrimaryFramebufferObject()->bind(); + TextureCache::getInstance()->getPrimaryFramebufferObject()->bind(); glEnable(GL_BLEND); glBlendFuncSeparate(GL_ZERO, GL_SRC_COLOR, GL_ZERO, GL_ONE); diff --git a/interface/src/renderer/DeferredLightingEffect.cpp b/interface/src/renderer/DeferredLightingEffect.cpp index be4e457131..7c3436b2bc 100644 --- a/interface/src/renderer/DeferredLightingEffect.cpp +++ b/interface/src/renderer/DeferredLightingEffect.cpp @@ -37,7 +37,7 @@ void DeferredLightingEffect::init() { } void DeferredLightingEffect::bindSimpleProgram() { - Application::getInstance()->getTextureCache()->setPrimaryDrawBuffers(true, true, true); + TextureCache::getInstance()->setPrimaryDrawBuffers(true, true, true); _simpleProgram.bind(); _simpleProgram.setUniformValue(_glowIntensityLocation, Application::getInstance()->getGlowEffect()->getIntensity()); glDisable(GL_BLEND); @@ -46,7 +46,7 @@ void DeferredLightingEffect::bindSimpleProgram() { void DeferredLightingEffect::releaseSimpleProgram() { glEnable(GL_BLEND); _simpleProgram.release(); - Application::getInstance()->getTextureCache()->setPrimaryDrawBuffers(true, false, false); + TextureCache::getInstance()->setPrimaryDrawBuffers(true, false, false); } void DeferredLightingEffect::renderSolidSphere(float radius, int slices, int stacks) { @@ -117,15 +117,15 @@ void DeferredLightingEffect::addSpotLight(const glm::vec3& position, float radiu void DeferredLightingEffect::prepare() { // clear the normal and specular buffers - Application::getInstance()->getTextureCache()->setPrimaryDrawBuffers(false, true, false); + TextureCache::getInstance()->setPrimaryDrawBuffers(false, true, false); glClear(GL_COLOR_BUFFER_BIT); - Application::getInstance()->getTextureCache()->setPrimaryDrawBuffers(false, false, true); + TextureCache::getInstance()->setPrimaryDrawBuffers(false, false, true); // clearing to zero alpha for specular causes problems on my Nvidia card; clear to lowest non-zero value instead const float MAX_SPECULAR_EXPONENT = 128.0f; glClearColor(0.0f, 0.0f, 0.0f, 1.0f / MAX_SPECULAR_EXPONENT); glClear(GL_COLOR_BUFFER_BIT); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); - Application::getInstance()->getTextureCache()->setPrimaryDrawBuffers(true, false, false); + TextureCache::getInstance()->setPrimaryDrawBuffers(true, false, false); } void DeferredLightingEffect::render() { @@ -138,7 +138,7 @@ void DeferredLightingEffect::render() { glDisable(GL_COLOR_MATERIAL); glDepthMask(false); - QOpenGLFramebufferObject* primaryFBO = Application::getInstance()->getTextureCache()->getPrimaryFramebufferObject(); + QOpenGLFramebufferObject* primaryFBO = TextureCache::getInstance()->getPrimaryFramebufferObject(); primaryFBO->release(); QOpenGLFramebufferObject* freeFBO = Application::getInstance()->getGlowEffect()->getFreeFramebufferObject(); @@ -148,13 +148,13 @@ void DeferredLightingEffect::render() { glBindTexture(GL_TEXTURE_2D, primaryFBO->texture()); glActiveTexture(GL_TEXTURE1); - glBindTexture(GL_TEXTURE_2D, Application::getInstance()->getTextureCache()->getPrimaryNormalTextureID()); + glBindTexture(GL_TEXTURE_2D, TextureCache::getInstance()->getPrimaryNormalTextureID()); glActiveTexture(GL_TEXTURE2); - glBindTexture(GL_TEXTURE_2D, Application::getInstance()->getTextureCache()->getPrimarySpecularTextureID()); + glBindTexture(GL_TEXTURE_2D, TextureCache::getInstance()->getPrimarySpecularTextureID()); glActiveTexture(GL_TEXTURE3); - glBindTexture(GL_TEXTURE_2D, Application::getInstance()->getTextureCache()->getPrimaryDepthTextureID()); + glBindTexture(GL_TEXTURE_2D, TextureCache::getInstance()->getPrimaryDepthTextureID()); // get the viewport side (left, right, both) int viewport[4]; @@ -173,7 +173,7 @@ void DeferredLightingEffect::render() { bool shadowsEnabled = Menu::getInstance()->getShadowsEnabled(); if (shadowsEnabled) { glActiveTexture(GL_TEXTURE4); - glBindTexture(GL_TEXTURE_2D, Application::getInstance()->getTextureCache()->getShadowDepthTextureID()); + glBindTexture(GL_TEXTURE_2D, TextureCache::getInstance()->getShadowDepthTextureID()); program = &_directionalLightShadowMap; locations = &_directionalLightShadowMapLocations; @@ -188,7 +188,7 @@ void DeferredLightingEffect::render() { program->bind(); } program->setUniformValue(locations->shadowScale, - 1.0f / Application::getInstance()->getTextureCache()->getShadowFramebufferObject()->width()); + 1.0f / TextureCache::getInstance()->getShadowFramebufferObject()->width()); } else { program->bind(); diff --git a/interface/src/renderer/GlowEffect.cpp b/interface/src/renderer/GlowEffect.cpp index 9e9c1f2ed5..8a9d957234 100644 --- a/interface/src/renderer/GlowEffect.cpp +++ b/interface/src/renderer/GlowEffect.cpp @@ -41,8 +41,8 @@ GlowEffect::~GlowEffect() { QOpenGLFramebufferObject* GlowEffect::getFreeFramebufferObject() const { return (_isOddFrame ? - Application::getInstance()->getTextureCache()->getSecondaryFramebufferObject(): - Application::getInstance()->getTextureCache()->getTertiaryFramebufferObject()); + TextureCache::getInstance()->getSecondaryFramebufferObject(): + TextureCache::getInstance()->getTertiaryFramebufferObject()); } static ProgramObject* createProgram(const QString& name) { @@ -88,7 +88,7 @@ void GlowEffect::init() { } void GlowEffect::prepare() { - Application::getInstance()->getTextureCache()->getPrimaryFramebufferObject()->bind(); + TextureCache::getInstance()->getPrimaryFramebufferObject()->bind(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); _isEmpty = true; @@ -122,7 +122,7 @@ static void maybeRelease(QOpenGLFramebufferObject* fbo) { QOpenGLFramebufferObject* GlowEffect::render(bool toTexture) { PerformanceTimer perfTimer("glowEffect"); - QOpenGLFramebufferObject* primaryFBO = Application::getInstance()->getTextureCache()->getPrimaryFramebufferObject(); + QOpenGLFramebufferObject* primaryFBO = TextureCache::getInstance()->getPrimaryFramebufferObject(); primaryFBO->release(); glBindTexture(GL_TEXTURE_2D, primaryFBO->texture()); @@ -138,7 +138,7 @@ QOpenGLFramebufferObject* GlowEffect::render(bool toTexture) { glDepthMask(GL_FALSE); QOpenGLFramebufferObject* destFBO = toTexture ? - Application::getInstance()->getTextureCache()->getSecondaryFramebufferObject() : NULL; + TextureCache::getInstance()->getSecondaryFramebufferObject() : NULL; if (!Menu::getInstance()->isOptionChecked(MenuOption::EnableGlowEffect) || _isEmpty) { // copy the primary to the screen if (destFBO && QOpenGLFramebufferObject::hasOpenGLFramebufferBlit()) { @@ -160,9 +160,9 @@ QOpenGLFramebufferObject* GlowEffect::render(bool toTexture) { } else { // diffuse into the secondary/tertiary (alternating between frames) QOpenGLFramebufferObject* oldDiffusedFBO = - Application::getInstance()->getTextureCache()->getSecondaryFramebufferObject(); + TextureCache::getInstance()->getSecondaryFramebufferObject(); QOpenGLFramebufferObject* newDiffusedFBO = - Application::getInstance()->getTextureCache()->getTertiaryFramebufferObject(); + TextureCache::getInstance()->getTertiaryFramebufferObject(); if (_isOddFrame) { qSwap(oldDiffusedFBO, newDiffusedFBO); } diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index c0295fd9b5..bea94c019f 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -749,7 +749,7 @@ bool Model::renderCore(float alpha, RenderMode mode, RenderArgs* args) { } - /*Application::getInstance()->getTextureCache()->setPrimaryDrawBuffers( + /*TextureCache::getInstance()->setPrimaryDrawBuffers( mode == DEFAULT_RENDER_MODE || mode == DIFFUSE_RENDER_MODE, mode == DEFAULT_RENDER_MODE || mode == NORMAL_RENDER_MODE, mode == DEFAULT_RENDER_MODE); @@ -789,7 +789,7 @@ bool Model::renderCore(float alpha, RenderMode mode, RenderArgs* args) { opaqueMeshPartsRendered += renderMeshes(batch, mode, false, DEFAULT_ALPHA_THRESHOLD, true, true, true, false, args); // render translucent meshes afterwards - //Application::getInstance()->getTextureCache()->setPrimaryDrawBuffers(false, true, true); + //TextureCache::getInstance()->setPrimaryDrawBuffers(false, true, true); { GLenum buffers[2]; int bufferCount = 0; @@ -814,7 +814,7 @@ bool Model::renderCore(float alpha, RenderMode mode, RenderArgs* args) { GLBATCH(glDepthMask)(false); GLBATCH(glDepthFunc)(GL_LEQUAL); - //Application::getInstance()->getTextureCache()->setPrimaryDrawBuffers(true); + //TextureCache::getInstance()->setPrimaryDrawBuffers(true); { GLenum buffers[1]; int bufferCount = 0; @@ -1705,7 +1705,7 @@ void Model::endScene(RenderMode mode, RenderArgs* args) { } - /*Application::getInstance()->getTextureCache()->setPrimaryDrawBuffers( + /*TextureCache::getInstance()->setPrimaryDrawBuffers( mode == DEFAULT_RENDER_MODE || mode == DIFFUSE_RENDER_MODE, mode == DEFAULT_RENDER_MODE || mode == NORMAL_RENDER_MODE, mode == DEFAULT_RENDER_MODE); @@ -1745,7 +1745,7 @@ void Model::endScene(RenderMode mode, RenderArgs* args) { opaqueMeshPartsRendered += renderMeshesForModelsInScene(batch, mode, false, DEFAULT_ALPHA_THRESHOLD, true, true, true, false, args); // render translucent meshes afterwards - //Application::getInstance()->getTextureCache()->setPrimaryDrawBuffers(false, true, true); + //TextureCache::getInstance()->setPrimaryDrawBuffers(false, true, true); { GLenum buffers[2]; int bufferCount = 0; @@ -1770,7 +1770,7 @@ void Model::endScene(RenderMode mode, RenderArgs* args) { GLBATCH(glDepthMask)(false); GLBATCH(glDepthFunc)(GL_LEQUAL); - //Application::getInstance()->getTextureCache()->setPrimaryDrawBuffers(true); + //TextureCache::getInstance()->setPrimaryDrawBuffers(true); { GLenum buffers[1]; int bufferCount = 0; @@ -2446,7 +2446,7 @@ int Model::renderMeshesFromList(QVector& list, gpu::Batch& batch, RenderMod if (showDiffuse && diffuseMap) { GLBATCH(glBindTexture)(GL_TEXTURE_2D, diffuseMap->getID()); } else { - GLBATCH(glBindTexture)(GL_TEXTURE_2D, Application::getInstance()->getTextureCache()->getWhiteTextureID()); + GLBATCH(glBindTexture)(GL_TEXTURE_2D, TextureCache::getInstance()->getWhiteTextureID()); } if (locations->texcoordMatrices >= 0) { @@ -2464,7 +2464,7 @@ int Model::renderMeshesFromList(QVector& list, gpu::Batch& batch, RenderMod GLBATCH(glActiveTexture)(GL_TEXTURE1); Texture* normalMap = networkPart.normalTexture.data(); GLBATCH(glBindTexture)(GL_TEXTURE_2D, !normalMap ? - Application::getInstance()->getTextureCache()->getBlueTextureID() : normalMap->getID()); + TextureCache::getInstance()->getBlueTextureID() : normalMap->getID()); GLBATCH(glActiveTexture)(GL_TEXTURE0); } @@ -2472,7 +2472,7 @@ int Model::renderMeshesFromList(QVector& list, gpu::Batch& batch, RenderMod GLBATCH(glActiveTexture)(GL_TEXTURE0 + locations->specularTextureUnit); Texture* specularMap = networkPart.specularTexture.data(); GLBATCH(glBindTexture)(GL_TEXTURE_2D, !specularMap ? - Application::getInstance()->getTextureCache()->getWhiteTextureID() : specularMap->getID()); + TextureCache::getInstance()->getWhiteTextureID() : specularMap->getID()); GLBATCH(glActiveTexture)(GL_TEXTURE0); } @@ -2493,7 +2493,7 @@ int Model::renderMeshesFromList(QVector& list, gpu::Batch& batch, RenderMod GLBATCH(glActiveTexture)(GL_TEXTURE0 + locations->emissiveTextureUnit); Texture* emissiveMap = networkPart.emissiveTexture.data(); GLBATCH(glBindTexture)(GL_TEXTURE_2D, !emissiveMap ? - Application::getInstance()->getTextureCache()->getWhiteTextureID() : emissiveMap->getID()); + TextureCache::getInstance()->getWhiteTextureID() : emissiveMap->getID()); GLBATCH(glActiveTexture)(GL_TEXTURE0); } diff --git a/interface/src/ui/MetavoxelEditor.cpp b/interface/src/ui/MetavoxelEditor.cpp index 97c4c08b41..bc20def66f 100644 --- a/interface/src/ui/MetavoxelEditor.cpp +++ b/interface/src/ui/MetavoxelEditor.cpp @@ -916,7 +916,7 @@ void MaterialControl::updateTexture() { _texture.clear(); return; } - _texture = Application::getInstance()->getTextureCache()->getTexture(material->getDiffuse(), SPLAT_TEXTURE); + _texture = TextureCache::getInstance()->getTexture(material->getDiffuse(), SPLAT_TEXTURE); if (_texture) { if (_texture->isLoaded()) { textureLoaded(); diff --git a/interface/src/voxels/VoxelSystem.cpp b/interface/src/voxels/VoxelSystem.cpp index 67f3d585ea..3a50c07a71 100644 --- a/interface/src/voxels/VoxelSystem.cpp +++ b/interface/src/voxels/VoxelSystem.cpp @@ -1171,7 +1171,7 @@ void VoxelSystem::render() { void VoxelSystem::applyScaleAndBindProgram(bool texture) { if (texture) { bindPerlinModulateProgram(); - glBindTexture(GL_TEXTURE_2D, Application::getInstance()->getTextureCache()->getPermutationNormalTextureID()); + glBindTexture(GL_TEXTURE_2D, TextureCache::getInstance()->getPermutationNormalTextureID()); } else { _program.bind(); } @@ -1179,7 +1179,7 @@ void VoxelSystem::applyScaleAndBindProgram(bool texture) { glPushMatrix(); glScalef(_treeScale, _treeScale, _treeScale); - Application::getInstance()->getTextureCache()->setPrimaryDrawBuffers(true, true); + TextureCache::getInstance()->setPrimaryDrawBuffers(true, true); } void VoxelSystem::removeScaleAndReleaseProgram(bool texture) { @@ -1193,7 +1193,7 @@ void VoxelSystem::removeScaleAndReleaseProgram(bool texture) { _program.release(); } - Application::getInstance()->getTextureCache()->setPrimaryDrawBuffers(true, false); + TextureCache::getInstance()->setPrimaryDrawBuffers(true, false); } int VoxelSystem::_nodeCount = 0; From 4ac673fe63befe2f478ed6547decbf1bfb73126f Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Fri, 12 Dec 2014 15:44:54 -0800 Subject: [PATCH 072/258] more render util cleanup --- interface/src/Application.cpp | 6 +++--- interface/src/Application.h | 3 --- interface/src/Environment.cpp | 2 +- interface/src/ModelUploader.cpp | 2 +- interface/src/Util.cpp | 8 ++++---- interface/src/avatar/Avatar.cpp | 4 ++-- interface/src/avatar/Hand.cpp | 4 ++-- interface/src/avatar/MyAvatar.cpp | 4 ++-- interface/src/avatar/SkeletonModel.cpp | 14 +++++++------- interface/src/renderer/DeferredLightingEffect.cpp | 8 ++++---- interface/src/renderer/Model.cpp | 2 +- interface/src/ui/MetavoxelEditor.cpp | 2 +- interface/src/ui/overlays/Grid3DOverlay.cpp | 4 ++-- interface/src/ui/overlays/Sphere3DOverlay.cpp | 2 +- libraries/render-utils/src/GeometryCache.cpp | 5 +++++ libraries/render-utils/src/GeometryCache.h | 2 ++ 16 files changed, 38 insertions(+), 34 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index eaaeb0534f..c45267010b 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -3083,7 +3083,7 @@ void Application::displaySide(Camera& whichCamera, bool selfAvatarOnly, RenderAr // draw a red sphere float originSphereRadius = 0.05f; glColor3f(1,0,0); - _geometryCache.renderSphere(originSphereRadius, 15, 15); + GeometryCache::getInstance()->renderSphere(originSphereRadius, 15, 15); // Draw voxels if (Menu::getInstance()->isOptionChecked(MenuOption::Voxels)) { @@ -3304,12 +3304,12 @@ void Application::renderRearViewMirror(const QRect& region, bool billboard) { // set the bounds of rear mirror view if (billboard) { - QSize size = getTextureCache()->getFrameBufferSize(); + QSize size = TextureCache::getInstance()->getFrameBufferSize(); glViewport(region.x(), size.height() - region.y() - region.height(), region.width(), region.height()); glScissor(region.x(), size.height() - region.y() - region.height(), region.width(), region.height()); } else { // if not rendering the billboard, the region is in device independent coordinates; must convert to device - QSize size = getTextureCache()->getFrameBufferSize(); + QSize size = TextureCache::getInstance()->getFrameBufferSize(); float ratio = QApplication::desktop()->windowHandle()->devicePixelRatio() * getRenderResolutionScale(); int x = region.x() * ratio, y = region.y() * ratio, width = region.width() * ratio, height = region.height() * ratio; glViewport(x, size.height() - y - height, width, height); diff --git a/interface/src/Application.h b/interface/src/Application.h index 5b97c1301f..c3979086bc 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -252,9 +252,7 @@ public: ToolWindow* getToolWindow() { return _toolWindow ; } - GeometryCache* getGeometryCache() { return &_geometryCache; } AnimationCache* getAnimationCache() { return &_animationCache; } - TextureCache* getTextureCache() { return _textureCache; } DeferredLightingEffect* getDeferredLightingEffect() { return &_deferredLightingEffect; } GlowEffect* getGlowEffect() { return &_glowEffect; } ControllerScriptingInterface* getControllerScriptingInterface() { return &_controllerScriptingInterface; } @@ -572,7 +570,6 @@ private: QSet _keysPressed; - GeometryCache _geometryCache; AnimationCache _animationCache; TextureCache* _textureCache; diff --git a/interface/src/Environment.cpp b/interface/src/Environment.cpp index 0ce43ecdaa..a754b63eec 100644 --- a/interface/src/Environment.cpp +++ b/interface/src/Environment.cpp @@ -261,7 +261,7 @@ void Environment::renderAtmosphere(Camera& camera, const EnvironmentData& data) glDepthMask(GL_FALSE); glDisable(GL_DEPTH_TEST); - Application::getInstance()->getGeometryCache()->renderSphere(1.0f, 100, 50); //Draw a unit sphere + GeometryCache::getInstance()->renderSphere(1.0f, 100, 50); //Draw a unit sphere glDepthMask(GL_TRUE); program->release(); diff --git a/interface/src/ModelUploader.cpp b/interface/src/ModelUploader.cpp index 6c167ca59a..ee38a2c094 100644 --- a/interface/src/ModelUploader.cpp +++ b/interface/src/ModelUploader.cpp @@ -471,7 +471,7 @@ void ModelUploader::processCheck() { QString("ModelUploader::processCheck()"), QString("Your model is now available in the browser."), QMessageBox::Ok); - Application::getInstance()->getGeometryCache()->refresh(_url); + GeometryCache::getInstance()->refresh(_url); foreach (const QByteArray& filename, _textureFilenames) { TextureCache::getInstance()->refresh(_textureBase + filename); } diff --git a/interface/src/Util.cpp b/interface/src/Util.cpp index c4f2ec8468..256e437e21 100644 --- a/interface/src/Util.cpp +++ b/interface/src/Util.cpp @@ -71,22 +71,22 @@ void renderWorldBox() { glPushMatrix(); glTranslatef(MARKER_DISTANCE, 0, 0); glColor3fv(red); - Application::getInstance()->getGeometryCache()->renderSphere(MARKER_RADIUS, 10, 10); + GeometryCache::getInstance()->renderSphere(MARKER_RADIUS, 10, 10); glPopMatrix(); glPushMatrix(); glTranslatef(0, MARKER_DISTANCE, 0); glColor3fv(green); - Application::getInstance()->getGeometryCache()->renderSphere(MARKER_RADIUS, 10, 10); + GeometryCache::getInstance()->renderSphere(MARKER_RADIUS, 10, 10); glPopMatrix(); glPushMatrix(); glTranslatef(0, 0, MARKER_DISTANCE); glColor3fv(blue); - Application::getInstance()->getGeometryCache()->renderSphere(MARKER_RADIUS, 10, 10); + GeometryCache::getInstance()->renderSphere(MARKER_RADIUS, 10, 10); glPopMatrix(); glPushMatrix(); glColor3fv(gray); glTranslatef(MARKER_DISTANCE, 0, MARKER_DISTANCE); - Application::getInstance()->getGeometryCache()->renderSphere(MARKER_RADIUS, 10, 10); + GeometryCache::getInstance()->renderSphere(MARKER_RADIUS, 10, 10); glPopMatrix(); } diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index e4ea33a180..d4ec5ddb1f 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -394,7 +394,7 @@ void Avatar::render(const glm::vec3& cameraPosition, RenderMode renderMode, bool } else { glTranslatef(_position.x, getDisplayNamePosition().y + LOOK_AT_INDICATOR_OFFSET, _position.z); } - Application::getInstance()->getGeometryCache()->renderSphere(LOOK_AT_INDICATOR_RADIUS, 15, 15); + GeometryCache::getInstance()->renderSphere(LOOK_AT_INDICATOR_RADIUS, 15, 15); glPopMatrix(); } } @@ -422,7 +422,7 @@ void Avatar::render(const glm::vec3& cameraPosition, RenderMode renderMode, bool glPushMatrix(); glTranslatef(_position.x, _position.y, _position.z); glScalef(height, height, height); - Application::getInstance()->getGeometryCache()->renderSphere(sphereRadius, 15, 15); + GeometryCache::getInstance()->renderSphere(sphereRadius, 15, 15); glPopMatrix(); } diff --git a/interface/src/avatar/Hand.cpp b/interface/src/avatar/Hand.cpp index 148abc3546..fef4ac2fac 100644 --- a/interface/src/avatar/Hand.cpp +++ b/interface/src/avatar/Hand.cpp @@ -114,7 +114,7 @@ void Hand::render(bool isMine, Model::RenderMode renderMode) { glPushMatrix(); glTranslatef(position.x, position.y, position.z); glColor3f(0.0f, 1.0f, 0.0f); - Application::getInstance()->getGeometryCache()->renderSphere(PALM_COLLISION_RADIUS * _owningAvatar->getScale(), 10, 10); + GeometryCache::getInstance()->renderSphere(PALM_COLLISION_RADIUS * _owningAvatar->getScale(), 10, 10); glPopMatrix(); } } @@ -179,7 +179,7 @@ void Hand::renderHandTargets(bool isMine) { Avatar::renderJointConnectingCone(root, offsetFromPalm, PALM_DISK_RADIUS, 0.0f); glPushMatrix(); glTranslatef(root.x, root.y, root.z); - Application::getInstance()->getGeometryCache()->renderSphere(PALM_BALL_RADIUS, 20.0f, 20.0f); + GeometryCache::getInstance()->renderSphere(PALM_BALL_RADIUS, 20.0f, 20.0f); glPopMatrix(); } } diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 17cda19980..255e79ebcd 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -394,7 +394,7 @@ void MyAvatar::renderDebugBodyPoints() { glPushMatrix(); glColor4f(0, 1, 0, .5f); glTranslatef(position.x, position.y, position.z); - Application::getInstance()->getGeometryCache()->renderSphere(0.2f, 10.0f, 10.0f); + GeometryCache::getInstance()->renderSphere(0.2f, 10.0f, 10.0f); glPopMatrix(); // Head Sphere @@ -402,7 +402,7 @@ void MyAvatar::renderDebugBodyPoints() { glPushMatrix(); glColor4f(0, 1, 0, .5f); glTranslatef(position.x, position.y, position.z); - Application::getInstance()->getGeometryCache()->renderSphere(0.15f, 10.0f, 10.0f); + GeometryCache::getInstance()->renderSphere(0.15f, 10.0f, 10.0f); glPopMatrix(); } diff --git a/interface/src/avatar/SkeletonModel.cpp b/interface/src/avatar/SkeletonModel.cpp index 911ebb7412..9bc2b627be 100644 --- a/interface/src/avatar/SkeletonModel.cpp +++ b/interface/src/avatar/SkeletonModel.cpp @@ -561,9 +561,9 @@ void SkeletonModel::renderRagdoll() { glTranslatef(position.x, position.y, position.z); // draw each point as a yellow hexagon with black border glColor4f(0.0f, 0.0f, 0.0f, alpha); - Application::getInstance()->getGeometryCache()->renderSphere(radius2, BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); + GeometryCache::getInstance()->renderSphere(radius2, BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); glColor4f(1.0f, 1.0f, 0.0f, alpha); - Application::getInstance()->getGeometryCache()->renderSphere(radius1, BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); + GeometryCache::getInstance()->renderSphere(radius1, BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); glPopMatrix(); } glPopMatrix(); @@ -913,7 +913,7 @@ void SkeletonModel::renderBoundingCollisionShapes(float alpha) { endPoint = endPoint - _translation; glTranslatef(endPoint.x, endPoint.y, endPoint.z); glColor4f(0.6f, 0.6f, 0.8f, alpha); - Application::getInstance()->getGeometryCache()->renderSphere(_boundingShape.getRadius(), BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); + GeometryCache::getInstance()->renderSphere(_boundingShape.getRadius(), BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); // draw a yellow sphere at the capsule startpoint glm::vec3 startPoint; @@ -922,7 +922,7 @@ void SkeletonModel::renderBoundingCollisionShapes(float alpha) { glm::vec3 axis = endPoint - startPoint; glTranslatef(-axis.x, -axis.y, -axis.z); glColor4f(0.8f, 0.8f, 0.6f, alpha); - Application::getInstance()->getGeometryCache()->renderSphere(_boundingShape.getRadius(), BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); + GeometryCache::getInstance()->renderSphere(_boundingShape.getRadius(), BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); // draw a green cylinder between the two points glm::vec3 origin(0.0f); @@ -955,7 +955,7 @@ void SkeletonModel::renderJointCollisionShapes(float alpha) { glTranslatef(position.x, position.y, position.z); // draw a grey sphere at shape position glColor4f(0.75f, 0.75f, 0.75f, alpha); - Application::getInstance()->getGeometryCache()->renderSphere(shape->getBoundingRadius(), BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); + GeometryCache::getInstance()->renderSphere(shape->getBoundingRadius(), BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); } else if (shape->getType() == CAPSULE_SHAPE) { CapsuleShape* capsule = static_cast(shape); @@ -965,7 +965,7 @@ void SkeletonModel::renderJointCollisionShapes(float alpha) { endPoint = endPoint - simulationTranslation; glTranslatef(endPoint.x, endPoint.y, endPoint.z); glColor4f(0.6f, 0.6f, 0.8f, alpha); - Application::getInstance()->getGeometryCache()->renderSphere(capsule->getRadius(), BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); + GeometryCache::getInstance()->renderSphere(capsule->getRadius(), BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); // draw a yellow sphere at the capsule startpoint glm::vec3 startPoint; @@ -974,7 +974,7 @@ void SkeletonModel::renderJointCollisionShapes(float alpha) { glm::vec3 axis = endPoint - startPoint; glTranslatef(-axis.x, -axis.y, -axis.z); glColor4f(0.8f, 0.8f, 0.6f, alpha); - Application::getInstance()->getGeometryCache()->renderSphere(capsule->getRadius(), BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); + GeometryCache::getInstance()->renderSphere(capsule->getRadius(), BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); // draw a green cylinder between the two points glm::vec3 origin(0.0f); diff --git a/interface/src/renderer/DeferredLightingEffect.cpp b/interface/src/renderer/DeferredLightingEffect.cpp index 7c3436b2bc..42da3e0b08 100644 --- a/interface/src/renderer/DeferredLightingEffect.cpp +++ b/interface/src/renderer/DeferredLightingEffect.cpp @@ -51,7 +51,7 @@ void DeferredLightingEffect::releaseSimpleProgram() { void DeferredLightingEffect::renderSolidSphere(float radius, int slices, int stacks) { bindSimpleProgram(); - Application::getInstance()->getGeometryCache()->renderSphere(radius, slices, stacks); + GeometryCache::getInstance()->renderSphere(radius, slices, stacks); releaseSimpleProgram(); } @@ -75,7 +75,7 @@ void DeferredLightingEffect::renderWireCube(float size) { void DeferredLightingEffect::renderSolidCone(float base, float height, int slices, int stacks) { bindSimpleProgram(); - Application::getInstance()->getGeometryCache()->renderCone(base, height, slices, stacks); + GeometryCache::getInstance()->renderCone(base, height, slices, stacks); releaseSimpleProgram(); } @@ -270,7 +270,7 @@ void DeferredLightingEffect::render() { } else { glTranslatef(light.position.x, light.position.y, light.position.z); - Application::getInstance()->getGeometryCache()->renderSphere(expandedRadius, 32, 32); + GeometryCache::getInstance()->renderSphere(expandedRadius, 32, 32); } glPopMatrix(); @@ -323,7 +323,7 @@ void DeferredLightingEffect::render() { glm::vec3 axis = glm::axis(spotRotation); glRotatef(glm::degrees(glm::angle(spotRotation)), axis.x, axis.y, axis.z); glTranslatef(0.0f, 0.0f, -light.radius * (1.0f + SCALE_EXPANSION * 0.5f)); - Application::getInstance()->getGeometryCache()->renderCone(expandedRadius * glm::tan(light.cutoff), + GeometryCache::getInstance()->renderCone(expandedRadius * glm::tan(light.cutoff), expandedRadius, 32, 1); } diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index bea94c019f..45c80852ad 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -997,7 +997,7 @@ void Model::setURL(const QUrl& url, const QUrl& fallback, bool retainCurrent, bo _url = url; // if so instructed, keep the current geometry until the new one is loaded - _nextBaseGeometry = _nextGeometry = Application::getInstance()->getGeometryCache()->getGeometry(url, fallback, delayLoad); + _nextBaseGeometry = _nextGeometry = GeometryCache::getInstance()->getGeometry(url, fallback, delayLoad); _nextLODHysteresis = NetworkGeometry::NO_HYSTERESIS; if (!retainCurrent || !isActive() || _nextGeometry->isLoaded()) { applyNextGeometry(); diff --git a/interface/src/ui/MetavoxelEditor.cpp b/interface/src/ui/MetavoxelEditor.cpp index bc20def66f..dde181c571 100644 --- a/interface/src/ui/MetavoxelEditor.cpp +++ b/interface/src/ui/MetavoxelEditor.cpp @@ -353,7 +353,7 @@ void MetavoxelEditor::render() { _gridProgram.bind(); - Application::getInstance()->getGeometryCache()->renderGrid(GRID_DIVISIONS, GRID_DIVISIONS); + GeometryCache::getInstance()->renderGrid(GRID_DIVISIONS, GRID_DIVISIONS); _gridProgram.release(); diff --git a/interface/src/ui/overlays/Grid3DOverlay.cpp b/interface/src/ui/overlays/Grid3DOverlay.cpp index 4bf0d9ce93..67dd0b8e21 100644 --- a/interface/src/ui/overlays/Grid3DOverlay.cpp +++ b/interface/src/ui/overlays/Grid3DOverlay.cpp @@ -87,7 +87,7 @@ void Grid3DOverlay::render(RenderArgs* args) { float scale = MINOR_GRID_DIVISIONS * spacing; glScalef(scale, scale, scale); - Application::getInstance()->getGeometryCache()->renderGrid(MINOR_GRID_DIVISIONS, MINOR_GRID_DIVISIONS); + GeometryCache::getInstance()->renderGrid(MINOR_GRID_DIVISIONS, MINOR_GRID_DIVISIONS); } glPopMatrix(); @@ -102,7 +102,7 @@ void Grid3DOverlay::render(RenderArgs* args) { float scale = MAJOR_GRID_DIVISIONS * spacing; glScalef(scale, scale, scale); - Application::getInstance()->getGeometryCache()->renderGrid(MAJOR_GRID_DIVISIONS, MAJOR_GRID_DIVISIONS); + GeometryCache::getInstance()->renderGrid(MAJOR_GRID_DIVISIONS, MAJOR_GRID_DIVISIONS); } glPopMatrix(); diff --git a/interface/src/ui/overlays/Sphere3DOverlay.cpp b/interface/src/ui/overlays/Sphere3DOverlay.cpp index 34064675e5..b9aeb5145a 100644 --- a/interface/src/ui/overlays/Sphere3DOverlay.cpp +++ b/interface/src/ui/overlays/Sphere3DOverlay.cpp @@ -63,7 +63,7 @@ void Sphere3DOverlay::render(RenderArgs* args) { glScalef(dimensions.x, dimensions.y, dimensions.z); //Application::getInstance()->getDeferredLightingEffect()->renderSolidCube(1.0f); if (_isSolid) { - Application::getInstance()->getGeometryCache()->renderSphere(1.0f, SLICES, SLICES); + GeometryCache::getInstance()->renderSphere(1.0f, SLICES, SLICES); } else { glutWireSphere(1.0f, SLICES, SLICES); } diff --git a/libraries/render-utils/src/GeometryCache.cpp b/libraries/render-utils/src/GeometryCache.cpp index 6e0c40c28d..416148ab20 100644 --- a/libraries/render-utils/src/GeometryCache.cpp +++ b/libraries/render-utils/src/GeometryCache.cpp @@ -21,6 +21,11 @@ #include "GeometryCache.h" +GeometryCache* GeometryCache::getInstance() { + static GeometryCache instance; + return &instance; +} + GeometryCache::GeometryCache() { } diff --git a/libraries/render-utils/src/GeometryCache.h b/libraries/render-utils/src/GeometryCache.h index 9fe6a7d5a2..f50dc8ccd9 100644 --- a/libraries/render-utils/src/GeometryCache.h +++ b/libraries/render-utils/src/GeometryCache.h @@ -35,6 +35,8 @@ class GeometryCache : public ResourceCache { Q_OBJECT public: + + static GeometryCache* getInstance(); GeometryCache(); virtual ~GeometryCache(); From 3de3540ebea88247d5b9d5a32a89ff42e68425ac Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 08:37:33 -0800 Subject: [PATCH 073/258] move back into interface for now --- interface/CMakeLists.txt | 2 +- interface/src/Application.h | 4 ++-- interface/src/MetavoxelSystem.h | 2 +- interface/src/avatar/Avatar.cpp | 2 +- .../src => interface/src/renderer}/GeometryCache.cpp | 0 .../src => interface/src/renderer}/GeometryCache.h | 0 interface/src/renderer/Model.h | 2 +- .../src => interface/src/renderer}/TextureCache.cpp | 0 .../src => interface/src/renderer}/TextureCache.h | 0 interface/src/ui/overlays/BillboardOverlay.h | 3 +-- 10 files changed, 7 insertions(+), 8 deletions(-) rename {libraries/render-utils/src => interface/src/renderer}/GeometryCache.cpp (100%) rename {libraries/render-utils/src => interface/src/renderer}/GeometryCache.h (100%) rename {libraries/render-utils/src => interface/src/renderer}/TextureCache.cpp (100%) rename {libraries/render-utils/src => interface/src/renderer}/TextureCache.h (100%) diff --git a/interface/CMakeLists.txt b/interface/CMakeLists.txt index ffc401ba63..38dd02c655 100644 --- a/interface/CMakeLists.txt +++ b/interface/CMakeLists.txt @@ -107,7 +107,7 @@ endif() add_executable(${TARGET_NAME} MACOSX_BUNDLE ${INTERFACE_SRCS} ${QM}) # link required hifi libraries -link_hifi_libraries(shared octree voxels gpu fbx metavoxels networking entities avatars audio animation script-engine physics render-utils) +link_hifi_libraries(shared octree voxels gpu fbx metavoxels networking entities avatars audio animation script-engine physics) # find any optional and required libraries find_package(ZLIB REQUIRED) diff --git a/interface/src/Application.h b/interface/src/Application.h index c3979086bc..afb476ce97 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -35,13 +35,11 @@ #include #include -#include #include #include #include #include #include -#include #include #include @@ -64,7 +62,9 @@ #include "entities/EntityTreeRenderer.h" #include "renderer/AmbientOcclusionEffect.h" #include "renderer/DeferredLightingEffect.h" +#include "renderer/GeometryCache.h" #include "renderer/GlowEffect.h" +#include "renderer/TextureCache.h" #include "scripting/ControllerScriptingInterface.h" #include "ui/BandwidthDialog.h" #include "ui/BandwidthMeter.h" diff --git a/interface/src/MetavoxelSystem.h b/interface/src/MetavoxelSystem.h index 0c0f9b49b7..2ebf7e1146 100644 --- a/interface/src/MetavoxelSystem.h +++ b/interface/src/MetavoxelSystem.h @@ -20,9 +20,9 @@ #include #include -#include #include "renderer/ProgramObject.h" +#include "renderer/TextureCache.h" class HeightfieldBaseLayerBatch; class HeightfieldSplatBatch; diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index d4ec5ddb1f..0edf59290f 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -25,7 +25,6 @@ #include #include #include -#include #include "Application.h" #include "Avatar.h" @@ -37,6 +36,7 @@ #include "Recorder.h" #include "world.h" #include "devices/OculusManager.h" +#include "renderer/TextureCache.h" #include "ui/TextRenderer.h" using namespace std; diff --git a/libraries/render-utils/src/GeometryCache.cpp b/interface/src/renderer/GeometryCache.cpp similarity index 100% rename from libraries/render-utils/src/GeometryCache.cpp rename to interface/src/renderer/GeometryCache.cpp diff --git a/libraries/render-utils/src/GeometryCache.h b/interface/src/renderer/GeometryCache.h similarity index 100% rename from libraries/render-utils/src/GeometryCache.h rename to interface/src/renderer/GeometryCache.h diff --git a/interface/src/renderer/Model.h b/interface/src/renderer/Model.h index d74f95095d..e95b2472ba 100644 --- a/interface/src/renderer/Model.h +++ b/interface/src/renderer/Model.h @@ -21,13 +21,13 @@ #include #include #include -#include #include "AnimationHandle.h" #include "GeometryCache.h" #include "InterfaceConfig.h" #include "JointState.h" #include "ProgramObject.h" +#include "TextureCache.h" class QScriptEngine; diff --git a/libraries/render-utils/src/TextureCache.cpp b/interface/src/renderer/TextureCache.cpp similarity index 100% rename from libraries/render-utils/src/TextureCache.cpp rename to interface/src/renderer/TextureCache.cpp diff --git a/libraries/render-utils/src/TextureCache.h b/interface/src/renderer/TextureCache.h similarity index 100% rename from libraries/render-utils/src/TextureCache.h rename to interface/src/renderer/TextureCache.h diff --git a/interface/src/ui/overlays/BillboardOverlay.h b/interface/src/ui/overlays/BillboardOverlay.h index dcb8ab8b0c..c095a544b7 100644 --- a/interface/src/ui/overlays/BillboardOverlay.h +++ b/interface/src/ui/overlays/BillboardOverlay.h @@ -15,9 +15,8 @@ #include #include -#include - #include "Base3DOverlay.h" +#include "renderer/TextureCache.h" class BillboardOverlay : public Base3DOverlay { Q_OBJECT From ca39c79df45cd350656999a181e0ab22fb394721 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 08:50:36 -0800 Subject: [PATCH 074/258] unix compile --- interface/src/renderer/GeometryCache.cpp | 6 ++++-- interface/src/renderer/TextureCache.cpp | 1 + 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/interface/src/renderer/GeometryCache.cpp b/interface/src/renderer/GeometryCache.cpp index 416148ab20..5cb544135c 100644 --- a/interface/src/renderer/GeometryCache.cpp +++ b/interface/src/renderer/GeometryCache.cpp @@ -9,6 +9,9 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +// include this before QOpenGLBuffer, which includes an earlier version of OpenGL +#include + #include #include @@ -17,9 +20,8 @@ #include -#include "TextureCache.h" - #include "GeometryCache.h" +#include "TextureCache.h" GeometryCache* GeometryCache::getInstance() { static GeometryCache instance; diff --git a/interface/src/renderer/TextureCache.cpp b/interface/src/renderer/TextureCache.cpp index 11ccd4b797..e4c55db58b 100644 --- a/interface/src/renderer/TextureCache.cpp +++ b/interface/src/renderer/TextureCache.cpp @@ -10,6 +10,7 @@ // // include this before QGLWidget, which includes an earlier version of OpenGL +#include #include #include From 7d1081473eb0fdd69336b29c2856ca5a6bf6fe3c Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 09:42:35 -0800 Subject: [PATCH 075/258] remove _textureCache --- interface/src/Application.cpp | 15 ++++++--------- interface/src/Application.h | 1 - 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index c45267010b..1ec177163d 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -177,7 +177,6 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) : _touchAvgY(0.0f), _isTouchPressed(false), _mousePressed(false), - _textureCache(NULL), _audio(), _enableProcessVoxelsThread(true), _octreeProcessor(), @@ -195,8 +194,6 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) : _isVSyncOn(true), _aboutToQuit(false) { - _textureCache = TextureCache::getInstance(); - // read the ApplicationInfo.ini file for Name/Version/Domain information QSettings applicationInfo(Application::resourcesPath() + "info/ApplicationInfo.ini", QSettings::IniFormat); @@ -623,10 +620,10 @@ void Application::paintGL() { // Set the desired FBO texture size. If it hasn't changed, this does nothing. // Otherwise, it must rebuild the FBOs if (OculusManager::isConnected()) { - _textureCache->setFrameBufferSize(OculusManager::getRenderTargetSize()); + TextureCache::getInstance()->setFrameBufferSize(OculusManager::getRenderTargetSize()); } else { QSize fbSize = _glWidget->getDeviceSize() * getRenderResolutionScale(); - _textureCache->setFrameBufferSize(fbSize); + TextureCache::getInstance()->setFrameBufferSize(fbSize); } glEnable(GL_LINE_SMOOTH); @@ -2046,7 +2043,7 @@ void Application::init() { connect(_myAvatar, &MyAvatar::transformChanged, this, &Application::bumpSettings); // make sure our texture cache knows about window size changes - _textureCache->associateWithWidget(getGLWidget()); + TextureCache::getInstance()->associateWithWidget(getGLWidget()); } void Application::closeMirrorView() { @@ -2777,7 +2774,7 @@ glm::vec3 Application::getSunDirection() { void Application::updateShadowMap() { PerformanceTimer perfTimer("shadowMap"); - QOpenGLFramebufferObject* fbo = _textureCache->getShadowFramebufferObject(); + QOpenGLFramebufferObject* fbo = TextureCache::getInstance()->getShadowFramebufferObject(); fbo->bind(); glEnable(GL_DEPTH_TEST); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); @@ -2942,7 +2939,7 @@ void Application::setupWorldLight() { } QImage Application::renderAvatarBillboard() { - _textureCache->getPrimaryFramebufferObject()->bind(); + TextureCache::getInstance()->getPrimaryFramebufferObject()->bind(); // the "glow" here causes an alpha of one Glower glower; @@ -2953,7 +2950,7 @@ QImage Application::renderAvatarBillboard() { QImage image(BILLBOARD_SIZE, BILLBOARD_SIZE, QImage::Format_ARGB32); glReadPixels(0, 0, BILLBOARD_SIZE, BILLBOARD_SIZE, GL_BGRA, GL_UNSIGNED_BYTE, image.bits()); - _textureCache->getPrimaryFramebufferObject()->release(); + TextureCache::getInstance()->getPrimaryFramebufferObject()->release(); return image; } diff --git a/interface/src/Application.h b/interface/src/Application.h index afb476ce97..fe5c466e0e 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -571,7 +571,6 @@ private: AnimationCache _animationCache; - TextureCache* _textureCache; DeferredLightingEffect _deferredLightingEffect; GlowEffect _glowEffect; From a688f48bf7678f6e2563ccafa677465c8e3dd1f4 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 15 Dec 2014 10:02:01 -0800 Subject: [PATCH 076/258] indicate that user should run tbbvars for FindTBB --- BUILD.md | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/BUILD.md b/BUILD.md index e1d920b8df..f676c29a9d 100644 --- a/BUILD.md +++ b/BUILD.md @@ -5,6 +5,7 @@ Dependencies * [glm](http://glm.g-truc.net/0.9.5/index.html) ~> 0.9.5.2 * [OpenSSL](https://www.openssl.org/related/binaries.html) ~> 1.0.1g * IMPORTANT: OpenSSL 1.0.1g is critical to avoid a security vulnerability. +* [Intel Threading Building Blocks](https://www.threadingbuildingblocks.org/) ~> 4.3 #####Linux only * [freeglut](http://freeglut.sourceforge.net/) ~> 2.8.0 @@ -55,7 +56,7 @@ In the examples below the variable $NAME would be replaced by the name of the de UNIX === -In general, as long as external dependencies are placed in OS standard locations, CMake will successfully find them during its run. When possible, you may choose to install depencies from your package manager of choice, or from source. +In general, as long as external dependencies are placed in OS standard locations, CMake will successfully find them during its run. When possible, you may choose to install depencies from your package manager of choice, or from source. ####Linux Should you choose not to install Qt5 via a package manager that handles dependencies for you, you may be missing some Qt5 dependencies. On Ubuntu, for example, the following additional packages are required: @@ -67,7 +68,7 @@ Should you choose not to install Qt5 via a package manager that handles dependen [Homebrew](http://brew.sh/) is an excellent package manager for OS X. It makes install of all hifi dependencies very simple. brew tap highfidelity/homebrew-formulas - brew install cmake glm openssl + brew install cmake glm openssl tbb brew install highfidelity/formulas/qt5 brew link qt5 --force @@ -173,6 +174,9 @@ The recommended route for CMake to find the external dependencies is to place al -> bin -> include -> lib + -> tbb + -> include + -> lib -> zlib -> include -> lib @@ -202,6 +206,12 @@ To prevent these problems, install OpenSSL yourself. Download the following bina Install OpenSSL into the Windows system directory, to make sure that QT uses the version that you've just installed, and not some other version. +#### Intel Threading Building Blocks (TBB) + +Download the stable release for Windows from the [Intel Threading Building Blocks website](https://www.threadingbuildingblocks.org/). By default, TBB will install to Program Files. You may also choose to install it to %HIFI_LIB_DIR%\TBB. + +You must run `tbbvars.bat` so that the find module included with this project will be able to find TBB no matter where you installed it. `tbbvars.bat` is located in the 'bin' folder of your TBB install. For a default installation on a 64-bit architechture, tbbvars can be found at `C:/Program Files (x86)/Intel/TBB/bin/tbbvars.bat`. + #### Zlib Download the compiled DLL from the [zlib website](http://www.zlib.net/). Extract to %HIFI_LIB_DIR%\zlib. From ce6334535b3b0ce6206f80b05483aa8449398316 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 15 Dec 2014 10:08:48 -0800 Subject: [PATCH 077/258] add info for TBB to Linux section --- BUILD.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/BUILD.md b/BUILD.md index f676c29a9d..522e994ea4 100644 --- a/BUILD.md +++ b/BUILD.md @@ -63,6 +63,12 @@ Should you choose not to install Qt5 via a package manager that handles dependen libasound2 libxmu-dev libxi-dev freeglut3-dev libasound2-dev libjack-dev +##### Intel Threading Building Blocks (TBB) + +Install Intel TBB from your package manager of choice, or from source (available at the [TBB Website](https://www.threadingbuildingblocks.org/)). + +You must run `tbbvars` so that the find module included with this project will be able to find the correct version of TBB. `tbbvars` is located in the 'bin' folder of your TBB install. + ####OS X #####Package Managers [Homebrew](http://brew.sh/) is an excellent package manager for OS X. It makes install of all hifi dependencies very simple. From d65f435e2832bc044379266cdce5425e634732c4 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 15 Dec 2014 10:10:31 -0800 Subject: [PATCH 078/258] change Qt version referenced in build guide --- BUILD.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/BUILD.md b/BUILD.md index 522e994ea4..b884b5588e 100644 --- a/BUILD.md +++ b/BUILD.md @@ -1,7 +1,7 @@ Dependencies === * [cmake](http://www.cmake.org/cmake/resources/software.html) ~> 2.8.12.2 -* [Qt](http://qt-project.org/downloads) ~> 5.2.0 +* [Qt](http://qt-project.org/downloads) ~> 5.3.0 * [glm](http://glm.g-truc.net/0.9.5/index.html) ~> 0.9.5.2 * [OpenSSL](https://www.openssl.org/related/binaries.html) ~> 1.0.1g * IMPORTANT: OpenSSL 1.0.1g is critical to avoid a security vulnerability. @@ -80,7 +80,7 @@ You must run `tbbvars` so that the find module included with this project will b We have a [homebrew formulas repository](https://github.com/highfidelity/homebrew-formulas) that you can use/tap to install some of the dependencies. In the code block above qt5 is installed from a formula in this repository. -*Our [qt5 homebrew formula](https://raw.github.com/highfidelity/homebrew-formulas/master/qt5.rb) is for a patched version of Qt 5.2.0 stable that removes wireless network scanning that can reduce real-time audio performance. We recommended you use this formula to install Qt.* +*Our [qt5 homebrew formula](https://raw.github.com/highfidelity/homebrew-formulas/master/qt5.rb) is for a patched version of Qt 5.3.x stable that removes wireless network scanning that can reduce real-time audio performance. We recommended you use this formula to install Qt.* #####Xcode If Xcode is your editor of choice, you can ask CMake to generate Xcode project files instead of Unix Makefiles. From 6b39783de7ae579191d927e6ecf27542fb955a10 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 10:12:04 -0800 Subject: [PATCH 079/258] revert out the InterfaceConfig.h changes --- interface/src/Application.h | 3 --- interface/src/renderer/GeometryCache.h | 2 +- interface/src/renderer/TextureCache.cpp | 2 +- interface/src/renderer/TextureCache.h | 2 +- interface/src/voxels/VoxelSystem.cpp | 2 +- 5 files changed, 4 insertions(+), 7 deletions(-) diff --git a/interface/src/Application.h b/interface/src/Application.h index fe5c466e0e..d4a681f060 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -12,9 +12,6 @@ #ifndef hifi_Application_h #define hifi_Application_h -// include this before QGLWidget, which includes an earlier version of OpenGL -#include "InterfaceConfig.h" - #include #include diff --git a/interface/src/renderer/GeometryCache.h b/interface/src/renderer/GeometryCache.h index f50dc8ccd9..1eb9dcbc6a 100644 --- a/interface/src/renderer/GeometryCache.h +++ b/interface/src/renderer/GeometryCache.h @@ -13,7 +13,7 @@ #define hifi_GeometryCache_h // include this before QOpenGLBuffer, which includes an earlier version of OpenGL -#include +#include "InterfaceConfig.h" #include #include diff --git a/interface/src/renderer/TextureCache.cpp b/interface/src/renderer/TextureCache.cpp index e4c55db58b..4d246a4c9c 100644 --- a/interface/src/renderer/TextureCache.cpp +++ b/interface/src/renderer/TextureCache.cpp @@ -10,7 +10,7 @@ // // include this before QGLWidget, which includes an earlier version of OpenGL -#include +#include "InterfaceConfig.h" #include #include diff --git a/interface/src/renderer/TextureCache.h b/interface/src/renderer/TextureCache.h index 3808485135..3cbfaced49 100644 --- a/interface/src/renderer/TextureCache.h +++ b/interface/src/renderer/TextureCache.h @@ -18,7 +18,7 @@ #include -#include +#include "InterfaceConfig.h" class QOpenGLFramebufferObject; diff --git a/interface/src/voxels/VoxelSystem.cpp b/interface/src/voxels/VoxelSystem.cpp index 3a50c07a71..82384ce9a4 100644 --- a/interface/src/voxels/VoxelSystem.cpp +++ b/interface/src/voxels/VoxelSystem.cpp @@ -9,6 +9,7 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +#include // include this first #include #include @@ -24,7 +25,6 @@ #include #include "Application.h" -#include "InterfaceConfig.h" #include "Menu.h" #include "renderer/ProgramObject.h" #include "VoxelConstants.h" From c6b033fa0e5b4edc87afa4c367b9d1633299fea4 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 10:12:55 -0800 Subject: [PATCH 080/258] revert out the InterfaceConfig.h changes --- interface/src/voxels/VoxelSystem.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/interface/src/voxels/VoxelSystem.cpp b/interface/src/voxels/VoxelSystem.cpp index 82384ce9a4..6fd477d8f3 100644 --- a/interface/src/voxels/VoxelSystem.cpp +++ b/interface/src/voxels/VoxelSystem.cpp @@ -9,8 +9,6 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#include // include this first - #include #include #include // to load voxels from file @@ -25,6 +23,7 @@ #include #include "Application.h" +#include "InterfaceConfig.h" #include "Menu.h" #include "renderer/ProgramObject.h" #include "VoxelConstants.h" From 5ad4a57e3dedd7ab8a72c15827fd23944ed994be Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 15 Dec 2014 10:19:06 -0800 Subject: [PATCH 081/258] add OS specific build files --- BUILD.md | 240 ++----------------------------------------------- BUILD_LINUX.md | 18 ++++ BUILD_OSX.md | 22 +++++ BUILD_WIN.md | 180 +++++++++++++++++++++++++++++++++++++ 4 files changed, 228 insertions(+), 232 deletions(-) create mode 100644 BUILD_LINUX.md create mode 100644 BUILD_OSX.md create mode 100644 BUILD_WIN.md diff --git a/BUILD.md b/BUILD.md index b884b5588e..867e515209 100644 --- a/BUILD.md +++ b/BUILD.md @@ -1,5 +1,5 @@ -Dependencies -=== +###Dependencies + * [cmake](http://www.cmake.org/cmake/resources/software.html) ~> 2.8.12.2 * [Qt](http://qt-project.org/downloads) ~> 5.3.0 * [glm](http://glm.g-truc.net/0.9.5/index.html) ~> 0.9.5.2 @@ -7,28 +7,18 @@ Dependencies * IMPORTANT: OpenSSL 1.0.1g is critical to avoid a security vulnerability. * [Intel Threading Building Blocks](https://www.threadingbuildingblocks.org/) ~> 4.3 -#####Linux only -* [freeglut](http://freeglut.sourceforge.net/) ~> 2.8.0 -* [zLib](http://www.zlib.net/) ~> 1.2.8 - -#####Windows only -* [GLEW](http://glew.sourceforge.net/) ~> 1.10.0 -* [freeglut MSVC](http://www.transmissionzero.co.uk/software/freeglut-devel/) ~> 2.8.1 -* [zLib](http://www.zlib.net/) ~> 1.2.8 - -CMake -=== +###CMake Hifi uses CMake to generate build files and project files for your platform. ####Qt In order for CMake to find the Qt5 find modules, you will need to set an ENV variable pointing to your Qt installation. -For example, a Qt5 5.2.0 installation to /usr/local/qt5 would require that QT_CMAKE_PREFIX_PATH be set with the following command. This can either be entered directly into your shell session before you build or in your shell profile (e.g.: ~/.bash_profile, ~/.bashrc, ~/.zshrc - this depends on your shell and environment). +For example, a Qt5 5.3.2 installation to /usr/local/qt5 would require that QT_CMAKE_PREFIX_PATH be set with the following command. This can either be entered directly into your shell session before you build or in your shell profile (e.g.: ~/.bash_profile, ~/.bashrc, ~/.zshrc - this depends on your shell and environment). The path it needs to be set to will depend on where and how Qt5 was installed. e.g. - export QT_CMAKE_PREFIX_PATH=/usr/local/qt/5.2.0/clang_64/lib/cmake/ - export QT_CMAKE_PREFIX_PATH=/usr/local/Cellar/qt5/5.2.1/lib/cmake + export QT_CMAKE_PREFIX_PATH=/usr/local/qt/5.3.2/clang_64/lib/cmake/ + export QT_CMAKE_PREFIX_PATH=/usr/local/Cellar/qt5/5.3.2/lib/cmake export QT_CMAKE_PREFIX_PATH=/usr/local/opt/qt5/lib/cmake ####Generating build files @@ -54,221 +44,7 @@ In the examples below the variable $NAME would be replaced by the name of the de * $NAME_ROOT_DIR - set this variable in your ENV * HIFI_LIB_DIR - set this variable in your ENV to your High Fidelity lib folder, should contain a folder '$name' -UNIX -=== -In general, as long as external dependencies are placed in OS standard locations, CMake will successfully find them during its run. When possible, you may choose to install depencies from your package manager of choice, or from source. - -####Linux -Should you choose not to install Qt5 via a package manager that handles dependencies for you, you may be missing some Qt5 dependencies. On Ubuntu, for example, the following additional packages are required: - - libasound2 libxmu-dev libxi-dev freeglut3-dev libasound2-dev libjack-dev - -##### Intel Threading Building Blocks (TBB) - -Install Intel TBB from your package manager of choice, or from source (available at the [TBB Website](https://www.threadingbuildingblocks.org/)). - -You must run `tbbvars` so that the find module included with this project will be able to find the correct version of TBB. `tbbvars` is located in the 'bin' folder of your TBB install. - -####OS X -#####Package Managers -[Homebrew](http://brew.sh/) is an excellent package manager for OS X. It makes install of all hifi dependencies very simple. - - brew tap highfidelity/homebrew-formulas - brew install cmake glm openssl tbb - brew install highfidelity/formulas/qt5 - brew link qt5 --force - -We have a [homebrew formulas repository](https://github.com/highfidelity/homebrew-formulas) that you can use/tap to install some of the dependencies. In the code block above qt5 is installed from a formula in this repository. - -*Our [qt5 homebrew formula](https://raw.github.com/highfidelity/homebrew-formulas/master/qt5.rb) is for a patched version of Qt 5.3.x stable that removes wireless network scanning that can reduce real-time audio performance. We recommended you use this formula to install Qt.* - -#####Xcode -If Xcode is your editor of choice, you can ask CMake to generate Xcode project files instead of Unix Makefiles. - - cmake .. -GXcode - -After running cmake, you will have the make files or Xcode project file necessary to build all of the components. Open the hifi.xcodeproj file, choose ALL_BUILD from the Product > Scheme menu (or target drop down), and click Run. - -If the build completes successfully, you will have built targets for all components located in the `build/${target_name}/Debug` directories. - -Windows -=== -####Visual Studio - -Currently building on Windows has been tested using the following compilers: -* Visual Studio C++ 2010 Express -* Visual Studio 2013 - -(If anyone can test using Visual Studio 2013 Express then please update this document) - -#####Windows SDK 7.1 - -If using Visual Studio 2010, or using Visual Studio 2013 but building as a Visual Studio 2010 project, you need [Microsoft Windows SDK for Windows 7 and .NET Framework 4](http://www.microsoft.com/en-us/download/details.aspx?id=8279). - -NOTE: If using Visual Studio C++ 2010 Express, you need to follow a specific install order. See below before installing the Windows SDK. - -######Windows SDK 8.1 - -If using Visual Studio 2013 and building as a Visual Studio 2013 project you need the Windows 8 SDK which you should already have as part of installing Visual Studio 2013. You should be able to see it at `C:\Program Files (x86)\Windows Kits\8.1\Lib\winv6.3\um\x86`. - -#####Visual Studio C++ 2010 Express - -Visual Studio C++ 2010 Express can be downloaded [here](http://www.visualstudio.com/en-us/downloads#d-2010-express). - -The following patches/service packs are also required: -* [VS2010 SP1](http://www.microsoft.com/en-us/download/details.aspx?id=23691) -* [VS2010 SP1 Compiler Update](http://www.microsoft.com/en-us/download/details.aspx?id=4422) - -IMPORTANT: Use the following install order: -Visual Studio C++ 2010 Express -Windows SDK 7.1 -VS2010 SP1 -VS2010 SP1 Compiler Update - -If you get an error while installing the VS2010 SP1 Compiler update saying that you don't have the Windows SDK installed, then uninstall all of the above and start again in the correct order. - -Some of the build instructions will ask you to start a Visual Studio Command Prompt. You should have a shortcut in your Start menu called "Open Visual Studio Command Prompt (2010)" which will do so. - -#####Visual Studio 2013 - -You can use the Community or Professional editions of Visual Studio 2013. - -You can start a Visual Studio 2013 command prompt using the shortcut provided in the Visual Studio Tools folder installed as part of Visual Studio 2013. - -Or you can start a regular command prompt and then run: - - "%VS120COMNTOOLS%\vsvars32.bat" - -If you experience issues building interface on Visual Studio 2013, try generating the build files with Visual Studio 2010 instead. To do so, download Visual Studio 2010 and run `cmake .. -G "Visual Studio 10"` (Assuming running from %HIFI_DIR%\build). - -####Qt -You can use the online installer or the offline installer. If you use the offline installer, be sure to select the "OpenGL" version. - -NOTE: Qt does not support 64-bit builds on Windows 7, so you must use the 32-bit version of libraries for interface.exe to run. The 32-bit version of the static library is the one linked by our CMake find modules. - -* Download the online installer [here](http://qt-project.org/downloads) - * When it asks you to select components, ONLY select the following: - * Qt > Qt 5.2.0 > **msvc2010 32-bit OpenGL** - -* Download the offline installer [here](http://download.qt-project.org/official_releases/qt/5.2/5.2.0/qt-windows-opensource-5.2.0-msvc2010_opengl-x86-offline.exe) - -Once Qt is installed, you need to manually configure the following: -* Make sure the Qt runtime DLLs are loadable. You must do this before you attempt to build because some tools for the build depend on Qt. E.g., add to the PATH: `Qt\5.2.0\msvc2010_opengl\bin\`. -* Set the QT_CMAKE_PREFIX_PATH environment variable to your `Qt\5.2.0\msvc2010_opengl` directory. - -If building as a Visual Studio 2013 project, download and configure the msvc2013 version of Qt instead. - -####External Libraries - -CMake will need to know where the headers and libraries for required external dependencies are. - -The recommended route for CMake to find the external dependencies is to place all of the dependencies in one folder and set one ENV variable - HIFI_LIB_DIR. That ENV variable should point to a directory with the following structure: - - root_lib_dir - -> freeglut - -> bin - -> include - -> lib - -> glew - -> bin - -> include - -> lib - -> glm - -> glm - -> glm.hpp - -> openssl - -> bin - -> include - -> lib - -> tbb - -> include - -> lib - -> zlib - -> include - -> lib - -> test - -For many of the external libraries where precompiled binaries are readily available you should be able to simply copy the extracted folder that you get from the download links provided at the top of the guide. Otherwise you may need to build from source and install the built product to this directory. The `root_lib_dir` in the above example can be wherever you choose on your system - as long as the environment variable HIFI_LIB_DIR is set to it. From here on, whenever you see %HIFI_LIB_DIR% you should substitute the directory that you chose. - -As with the Qt libraries, you will need to make sure that directories containing DLL'S are in your path. Where possible, you can use static builds of the external dependencies to avoid this requirement. - -#### OpenSSL - -QT will use OpenSSL if it's available, but it doesn't install it, so you must install it separately. - -Your system may already have several versions of the OpenSSL DLL's (ssleay32.dll, libeay32.dll) lying around, but they may be the wrong version. If these DLL's are in the PATH then QT will try to use them, and if they're the wrong version then you will see the following errors in the console: - - QSslSocket: cannot resolve TLSv1_1_client_method - QSslSocket: cannot resolve TLSv1_2_client_method - QSslSocket: cannot resolve TLSv1_1_server_method - QSslSocket: cannot resolve TLSv1_2_server_method - QSslSocket: cannot resolve SSL_select_next_proto - QSslSocket: cannot resolve SSL_CTX_set_next_proto_select_cb - QSslSocket: cannot resolve SSL_get0_next_proto_negotiated - -To prevent these problems, install OpenSSL yourself. Download the following binary packages [from this website](http://slproweb.com/products/Win32OpenSSL.html): -* Visual C++ 2008 Redistributables -* Win32 OpenSSL v1.0.1h - -Install OpenSSL into the Windows system directory, to make sure that QT uses the version that you've just installed, and not some other version. - -#### Intel Threading Building Blocks (TBB) - -Download the stable release for Windows from the [Intel Threading Building Blocks website](https://www.threadingbuildingblocks.org/). By default, TBB will install to Program Files. You may also choose to install it to %HIFI_LIB_DIR%\TBB. - -You must run `tbbvars.bat` so that the find module included with this project will be able to find TBB no matter where you installed it. `tbbvars.bat` is located in the 'bin' folder of your TBB install. For a default installation on a 64-bit architechture, tbbvars can be found at `C:/Program Files (x86)/Intel/TBB/bin/tbbvars.bat`. - -#### Zlib - -Download the compiled DLL from the [zlib website](http://www.zlib.net/). Extract to %HIFI_LIB_DIR%\zlib. - -Add the following environment variables (remember to substitute your own directory for %HIFI_LIB_DIR%): - - ZLIB_LIBRARY=%HIFI_LIB_DIR%\zlib\lib\zdll.lib - ZLIB_INCLUDE_DIR=%HIFI_LIB_DIR%\zlib\include - -Add to the PATH: `%HIFI_LIB_DIR%\zlib` - -Important! This should be added at the beginning of the path, not the end. That's because your -system likely has many copies of zlib1.dll, and you want High Fidelity to use the correct version. If High Fidelity picks up the wrong zlib1.dll then it might be unable to use it, and that would cause it to fail to start, showing only the cryptic error "The application was unable to start correctly: 0xc0000022". - -#### freeglut - -Download the binary package: `freeglut-MSVC-2.8.1-1.mp.zip`. Extract to %HIFI_LIB_DIR%\freeglut. - -Add to the PATH: `%HIFI_LIB_DIR%\freeglut\bin` - -#### GLEW - -Download the binary package: `glew-1.10.0-win32.zip`. Extract to %HIFI_LIB_DIR%\glew (you'll need to rename the default directory name). - -Add to the PATH: `%HIFI_LIB_DIR%\glew\bin\Release\Win32` - -#### GLM - -This package contains only headers, so there's nothing to add to the PATH. - -Be careful with glm. For the folder other libraries would normally call 'include', the folder containing the headers, glm opts to use 'glm'. You will have a glm folder nested inside the top-level glm folder. - -#### Build High Fidelity using Visual Studio -Follow the same build steps from the CMake section, but pass a different generator to CMake. - - cmake .. -DZLIB_LIBRARY=%ZLIB_LIBRARY% -DZLIB_INCLUDE_DIR=%ZLIB_INCLUDE_DIR% -G "Visual Studio 10" - -If you're using Visual Studio 2013 then pass "Visual Studio 12" instead of "Visual Studio 10" (yes, 12, not 13). - -Open %HIFI_DIR%\build\hifi.sln and compile. - -####Running Interface -If you need to debug Interface, you can run interface from within Visual Studio (see the section below). You can also run Interface by launching it from command line or File Explorer from %HIFI_DIR%\build\interface\Debug\interface.exe - -####Debugging Interface -* In the Solution Explorer, right click interface and click Set as StartUp Project -* Set the "Working Directory" for the Interface debugging sessions to the Debug output directory so that your application can load resources. Do this: right click interface and click Properties, choose Debugging from Configuration Properties, set Working Directory to .\Debug -* Now you can run and debug interface through Visual Studio - -Optional Components -=== +###Optional Components ####QXmpp @@ -276,7 +52,7 @@ You can find QXmpp [here](https://github.com/qxmpp-project/qxmpp). The inclusion OS X users who tap our [homebrew formulas repository](https://github.com/highfidelity/homebrew-formulas) can install QXmpp via homebrew - `brew install highfidelity/formulas/qxmpp`. -#### Devices +####Devices You can support external input/output devices such as Leap Motion, Faceplus, Faceshift, PrioVR, MIDI, Razr Hydra and more by adding each individual SDK in the visible building path. Refer to the readme file available in each device folder in [interface/external/](interface/external) for the detailed explanation of the requirements to use the device. diff --git a/BUILD_LINUX.md b/BUILD_LINUX.md new file mode 100644 index 0000000000..17f7268131 --- /dev/null +++ b/BUILD_LINUX.md @@ -0,0 +1,18 @@ +Please read the [general build guide](BUILD.md) for information on dependencies required for all platforms. Only Linux specific instructions are found in this file. + +####Linux Specific Dependencies +* [freeglut](http://freeglut.sourceforge.net/) ~> 2.8.0 +* [zLib](http://www.zlib.net/) ~> 1.2.8 + +In general, as long as external dependencies are placed in OS standard locations, CMake will successfully find them during its run. When possible, you may choose to install depencies from your package manager of choice, or from source. + +####Qt5 Dependencies +Should you choose not to install Qt5 via a package manager that handles dependencies for you, you may be missing some Qt5 dependencies. On Ubuntu, for example, the following additional packages are required: + + libasound2 libxmu-dev libxi-dev freeglut3-dev libasound2-dev libjack-dev + +#### Intel Threading Building Blocks (TBB) + +Install Intel TBB from your package manager of choice, or from source (available at the [TBB Website](https://www.threadingbuildingblocks.org/)). + +You must run `tbbvars` so that the find module included with this project will be able to find the correct version of TBB. `tbbvars` is located in the 'bin' folder of your TBB install. \ No newline at end of file diff --git a/BUILD_OSX.md b/BUILD_OSX.md new file mode 100644 index 0000000000..977a27a781 --- /dev/null +++ b/BUILD_OSX.md @@ -0,0 +1,22 @@ +Please read the [general build guide](BUILD.md) for information on dependencies required for all platforms. Only OS X specific instructions are found in this file. + +####Homebrew +[Homebrew](http://brew.sh/) is an excellent package manager for OS X. It makes install of all hifi dependencies very simple. + + brew tap highfidelity/homebrew-formulas + brew install cmake glm openssl tbb + brew install highfidelity/formulas/qt5 + brew link qt5 --force + +We have a [homebrew formulas repository](https://github.com/highfidelity/homebrew-formulas) that you can use/tap to install some of the dependencies. In the code block above qt5 is installed from a formula in this repository. + +*Our [qt5 homebrew formula](https://raw.github.com/highfidelity/homebrew-formulas/master/qt5.rb) is for a patched version of Qt 5.3.x stable that removes wireless network scanning that can reduce real-time audio performance. We recommended you use this formula to install Qt.* + +####Xcode +If Xcode is your editor of choice, you can ask CMake to generate Xcode project files instead of Unix Makefiles. + + cmake .. -GXcode + +After running cmake, you will have the make files or Xcode project file necessary to build all of the components. Open the hifi.xcodeproj file, choose ALL_BUILD from the Product > Scheme menu (or target drop down), and click Run. + +If the build completes successfully, you will have built targets for all components located in the `build/${target_name}/Debug` directories. diff --git a/BUILD_WIN.md b/BUILD_WIN.md new file mode 100644 index 0000000000..458aeca53a --- /dev/null +++ b/BUILD_WIN.md @@ -0,0 +1,180 @@ +Please read the [general build guide](BUILD.md) for information on dependencies required for all platforms. Only Windows specific instructions are found in this file. + +####Windows Dependencies +* [GLEW](http://glew.sourceforge.net/) ~> 1.10.0 +* [freeglut MSVC](http://www.transmissionzero.co.uk/software/freeglut-devel/) ~> 2.8.1 +* [zLib](http://www.zlib.net/) ~> 1.2.8 + +####Visual Studio + +Currently building on Windows has been tested using the following compilers: +* Visual Studio C++ 2010 Express +* Visual Studio 2013 + +(If anyone can test using Visual Studio 2013 Express then please update this document) + +#####Windows SDK 7.1 + +If using Visual Studio 2010, or using Visual Studio 2013 but building as a Visual Studio 2010 project, you need [Microsoft Windows SDK for Windows 7 and .NET Framework 4](http://www.microsoft.com/en-us/download/details.aspx?id=8279). + +NOTE: If using Visual Studio C++ 2010 Express, you need to follow a specific install order. See below before installing the Windows SDK. + +######Windows SDK 8.1 + +If using Visual Studio 2013 and building as a Visual Studio 2013 project you need the Windows 8 SDK which you should already have as part of installing Visual Studio 2013. You should be able to see it at `C:\Program Files (x86)\Windows Kits\8.1\Lib\winv6.3\um\x86`. + +#####Visual Studio C++ 2010 Express + +Visual Studio C++ 2010 Express can be downloaded [here](http://www.visualstudio.com/en-us/downloads#d-2010-express). + +The following patches/service packs are also required: +* [VS2010 SP1](http://www.microsoft.com/en-us/download/details.aspx?id=23691) +* [VS2010 SP1 Compiler Update](http://www.microsoft.com/en-us/download/details.aspx?id=4422) + +IMPORTANT: Use the following install order: +Visual Studio C++ 2010 Express +Windows SDK 7.1 +VS2010 SP1 +VS2010 SP1 Compiler Update + +If you get an error while installing the VS2010 SP1 Compiler update saying that you don't have the Windows SDK installed, then uninstall all of the above and start again in the correct order. + +Some of the build instructions will ask you to start a Visual Studio Command Prompt. You should have a shortcut in your Start menu called "Open Visual Studio Command Prompt (2010)" which will do so. + +#####Visual Studio 2013 + +You can use the Community or Professional editions of Visual Studio 2013. + +You can start a Visual Studio 2013 command prompt using the shortcut provided in the Visual Studio Tools folder installed as part of Visual Studio 2013. + +Or you can start a regular command prompt and then run: + + "%VS120COMNTOOLS%\vsvars32.bat" + +If you experience issues building interface on Visual Studio 2013, try generating the build files with Visual Studio 2010 instead. To do so, download Visual Studio 2010 and run `cmake .. -G "Visual Studio 10"` (Assuming running from %HIFI_DIR%\build). + +####Qt +You can use the online installer or the offline installer. If you use the offline installer, be sure to select the "OpenGL" version. + +NOTE: Qt does not support 64-bit builds on Windows 7, so you must use the 32-bit version of libraries for interface.exe to run. The 32-bit version of the static library is the one linked by our CMake find modules. + +* Download the online installer [here](http://qt-project.org/downloads) + * When it asks you to select components, ONLY select the following: + * Qt > Qt 5.2.0 > **msvc2010 32-bit OpenGL** + +* Download the offline installer [here](http://download.qt-project.org/official_releases/qt/5.2/5.2.0/qt-windows-opensource-5.2.0-msvc2010_opengl-x86-offline.exe) + +Once Qt is installed, you need to manually configure the following: +* Make sure the Qt runtime DLLs are loadable. You must do this before you attempt to build because some tools for the build depend on Qt. E.g., add to the PATH: `Qt\5.2.0\msvc2010_opengl\bin\`. +* Set the QT_CMAKE_PREFIX_PATH environment variable to your `Qt\5.2.0\msvc2010_opengl` directory. + +If building as a Visual Studio 2013 project, download and configure the msvc2013 version of Qt instead. + +####External Libraries + +CMake will need to know where the headers and libraries for required external dependencies are. + +The recommended route for CMake to find the external dependencies is to place all of the dependencies in one folder and set one ENV variable - HIFI_LIB_DIR. That ENV variable should point to a directory with the following structure: + + root_lib_dir + -> freeglut + -> bin + -> include + -> lib + -> glew + -> bin + -> include + -> lib + -> glm + -> glm + -> glm.hpp + -> openssl + -> bin + -> include + -> lib + -> tbb + -> include + -> lib + -> zlib + -> include + -> lib + -> test + +For many of the external libraries where precompiled binaries are readily available you should be able to simply copy the extracted folder that you get from the download links provided at the top of the guide. Otherwise you may need to build from source and install the built product to this directory. The `root_lib_dir` in the above example can be wherever you choose on your system - as long as the environment variable HIFI_LIB_DIR is set to it. From here on, whenever you see %HIFI_LIB_DIR% you should substitute the directory that you chose. + +As with the Qt libraries, you will need to make sure that directories containing DLL'S are in your path. Where possible, you can use static builds of the external dependencies to avoid this requirement. + +#### OpenSSL + +QT will use OpenSSL if it's available, but it doesn't install it, so you must install it separately. + +Your system may already have several versions of the OpenSSL DLL's (ssleay32.dll, libeay32.dll) lying around, but they may be the wrong version. If these DLL's are in the PATH then QT will try to use them, and if they're the wrong version then you will see the following errors in the console: + + QSslSocket: cannot resolve TLSv1_1_client_method + QSslSocket: cannot resolve TLSv1_2_client_method + QSslSocket: cannot resolve TLSv1_1_server_method + QSslSocket: cannot resolve TLSv1_2_server_method + QSslSocket: cannot resolve SSL_select_next_proto + QSslSocket: cannot resolve SSL_CTX_set_next_proto_select_cb + QSslSocket: cannot resolve SSL_get0_next_proto_negotiated + +To prevent these problems, install OpenSSL yourself. Download the following binary packages [from this website](http://slproweb.com/products/Win32OpenSSL.html): +* Visual C++ 2008 Redistributables +* Win32 OpenSSL v1.0.1h + +Install OpenSSL into the Windows system directory, to make sure that QT uses the version that you've just installed, and not some other version. + +#### Intel Threading Building Blocks (TBB) + +Download the stable release for Windows from the [Intel Threading Building Blocks website](https://www.threadingbuildingblocks.org/). By default, TBB will install to Program Files. You may also choose to install it to %HIFI_LIB_DIR%\TBB. + +You must run `tbbvars.bat` so that the find module included with this project will be able to find TBB no matter where you installed it. `tbbvars.bat` is located in the 'bin' folder of your TBB install. For a default installation on a 64-bit architechture, tbbvars can be found at `C:/Program Files (x86)/Intel/TBB/bin/tbbvars.bat`. + +#### Zlib + +Download the compiled DLL from the [zlib website](http://www.zlib.net/). Extract to %HIFI_LIB_DIR%\zlib. + +Add the following environment variables (remember to substitute your own directory for %HIFI_LIB_DIR%): + + ZLIB_LIBRARY=%HIFI_LIB_DIR%\zlib\lib\zdll.lib + ZLIB_INCLUDE_DIR=%HIFI_LIB_DIR%\zlib\include + +Add to the PATH: `%HIFI_LIB_DIR%\zlib` + +Important! This should be added at the beginning of the path, not the end. That's because your +system likely has many copies of zlib1.dll, and you want High Fidelity to use the correct version. If High Fidelity picks up the wrong zlib1.dll then it might be unable to use it, and that would cause it to fail to start, showing only the cryptic error "The application was unable to start correctly: 0xc0000022". + +#### freeglut + +Download the binary package: `freeglut-MSVC-2.8.1-1.mp.zip`. Extract to %HIFI_LIB_DIR%\freeglut. + +Add to the PATH: `%HIFI_LIB_DIR%\freeglut\bin` + +#### GLEW + +Download the binary package: `glew-1.10.0-win32.zip`. Extract to %HIFI_LIB_DIR%\glew (you'll need to rename the default directory name). + +Add to the PATH: `%HIFI_LIB_DIR%\glew\bin\Release\Win32` + +#### GLM + +This package contains only headers, so there's nothing to add to the PATH. + +Be careful with glm. For the folder other libraries would normally call 'include', the folder containing the headers, glm opts to use 'glm'. You will have a glm folder nested inside the top-level glm folder. + +#### Build High Fidelity using Visual Studio +Follow the same build steps from the CMake section, but pass a different generator to CMake. + + cmake .. -DZLIB_LIBRARY=%ZLIB_LIBRARY% -DZLIB_INCLUDE_DIR=%ZLIB_INCLUDE_DIR% -G "Visual Studio 10" + +If you're using Visual Studio 2013 then pass "Visual Studio 12" instead of "Visual Studio 10" (yes, 12, not 13). + +Open %HIFI_DIR%\build\hifi.sln and compile. + +####Running Interface +If you need to debug Interface, you can run interface from within Visual Studio (see the section below). You can also run Interface by launching it from command line or File Explorer from %HIFI_DIR%\build\interface\Debug\interface.exe + +####Debugging Interface +* In the Solution Explorer, right click interface and click Set as StartUp Project +* Set the "Working Directory" for the Interface debugging sessions to the Debug output directory so that your application can load resources. Do this: right click interface and click Properties, choose Debugging from Configuration Properties, set Working Directory to .\Debug +* Now you can run and debug interface through Visual Studio From a87fb0fe5e4906c7581ed2947ee2679ab00b0c61 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 15 Dec 2014 10:21:31 -0800 Subject: [PATCH 082/258] link to OS build guides from main guide --- BUILD.md | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/BUILD.md b/BUILD.md index 867e515209..0a897aa193 100644 --- a/BUILD.md +++ b/BUILD.md @@ -7,6 +7,11 @@ * IMPORTANT: OpenSSL 1.0.1g is critical to avoid a security vulnerability. * [Intel Threading Building Blocks](https://www.threadingbuildingblocks.org/) ~> 4.3 +### OS Specific Build Guides +* [BUILD_OSX.md](BUILD_OSX.md) - additional instructions for OS X. +* [BUILD_LINUX.md](BUILD_LINUX.md) - additional instructions for Linux. +* [BUILD_WIN.md](BUILD_WIN.md) - additional instructions for Windows. + ###CMake Hifi uses CMake to generate build files and project files for your platform. From bba48a61f99671ae7372e0d2542e095dad787ec0 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 15 Dec 2014 10:22:58 -0800 Subject: [PATCH 083/258] cleanup formatting of build guides --- BUILD_LINUX.md | 6 +++--- BUILD_OSX.md | 4 ++-- BUILD_WIN.md | 34 +++++++++++++++++----------------- 3 files changed, 22 insertions(+), 22 deletions(-) diff --git a/BUILD_LINUX.md b/BUILD_LINUX.md index 17f7268131..eb4dcd9255 100644 --- a/BUILD_LINUX.md +++ b/BUILD_LINUX.md @@ -1,17 +1,17 @@ Please read the [general build guide](BUILD.md) for information on dependencies required for all platforms. Only Linux specific instructions are found in this file. -####Linux Specific Dependencies +###Linux Specific Dependencies * [freeglut](http://freeglut.sourceforge.net/) ~> 2.8.0 * [zLib](http://www.zlib.net/) ~> 1.2.8 In general, as long as external dependencies are placed in OS standard locations, CMake will successfully find them during its run. When possible, you may choose to install depencies from your package manager of choice, or from source. -####Qt5 Dependencies +###Qt5 Dependencies Should you choose not to install Qt5 via a package manager that handles dependencies for you, you may be missing some Qt5 dependencies. On Ubuntu, for example, the following additional packages are required: libasound2 libxmu-dev libxi-dev freeglut3-dev libasound2-dev libjack-dev -#### Intel Threading Building Blocks (TBB) +###Intel Threading Building Blocks (TBB) Install Intel TBB from your package manager of choice, or from source (available at the [TBB Website](https://www.threadingbuildingblocks.org/)). diff --git a/BUILD_OSX.md b/BUILD_OSX.md index 977a27a781..1eeaed1c13 100644 --- a/BUILD_OSX.md +++ b/BUILD_OSX.md @@ -1,6 +1,6 @@ Please read the [general build guide](BUILD.md) for information on dependencies required for all platforms. Only OS X specific instructions are found in this file. -####Homebrew +###Homebrew [Homebrew](http://brew.sh/) is an excellent package manager for OS X. It makes install of all hifi dependencies very simple. brew tap highfidelity/homebrew-formulas @@ -12,7 +12,7 @@ We have a [homebrew formulas repository](https://github.com/highfidelity/homebre *Our [qt5 homebrew formula](https://raw.github.com/highfidelity/homebrew-formulas/master/qt5.rb) is for a patched version of Qt 5.3.x stable that removes wireless network scanning that can reduce real-time audio performance. We recommended you use this formula to install Qt.* -####Xcode +###Xcode If Xcode is your editor of choice, you can ask CMake to generate Xcode project files instead of Unix Makefiles. cmake .. -GXcode diff --git a/BUILD_WIN.md b/BUILD_WIN.md index 458aeca53a..5685370dc3 100644 --- a/BUILD_WIN.md +++ b/BUILD_WIN.md @@ -1,11 +1,11 @@ Please read the [general build guide](BUILD.md) for information on dependencies required for all platforms. Only Windows specific instructions are found in this file. -####Windows Dependencies +###Windows Dependencies * [GLEW](http://glew.sourceforge.net/) ~> 1.10.0 * [freeglut MSVC](http://www.transmissionzero.co.uk/software/freeglut-devel/) ~> 2.8.1 * [zLib](http://www.zlib.net/) ~> 1.2.8 -####Visual Studio +###Visual Studio Currently building on Windows has been tested using the following compilers: * Visual Studio C++ 2010 Express @@ -13,17 +13,17 @@ Currently building on Windows has been tested using the following compilers: (If anyone can test using Visual Studio 2013 Express then please update this document) -#####Windows SDK 7.1 +####Windows SDK 7.1 If using Visual Studio 2010, or using Visual Studio 2013 but building as a Visual Studio 2010 project, you need [Microsoft Windows SDK for Windows 7 and .NET Framework 4](http://www.microsoft.com/en-us/download/details.aspx?id=8279). NOTE: If using Visual Studio C++ 2010 Express, you need to follow a specific install order. See below before installing the Windows SDK. -######Windows SDK 8.1 +#####Windows SDK 8.1 If using Visual Studio 2013 and building as a Visual Studio 2013 project you need the Windows 8 SDK which you should already have as part of installing Visual Studio 2013. You should be able to see it at `C:\Program Files (x86)\Windows Kits\8.1\Lib\winv6.3\um\x86`. -#####Visual Studio C++ 2010 Express +####Visual Studio C++ 2010 Express Visual Studio C++ 2010 Express can be downloaded [here](http://www.visualstudio.com/en-us/downloads#d-2010-express). @@ -41,7 +41,7 @@ If you get an error while installing the VS2010 SP1 Compiler update saying that Some of the build instructions will ask you to start a Visual Studio Command Prompt. You should have a shortcut in your Start menu called "Open Visual Studio Command Prompt (2010)" which will do so. -#####Visual Studio 2013 +####Visual Studio 2013 You can use the Community or Professional editions of Visual Studio 2013. @@ -53,7 +53,7 @@ Or you can start a regular command prompt and then run: If you experience issues building interface on Visual Studio 2013, try generating the build files with Visual Studio 2010 instead. To do so, download Visual Studio 2010 and run `cmake .. -G "Visual Studio 10"` (Assuming running from %HIFI_DIR%\build). -####Qt +###Qt You can use the online installer or the offline installer. If you use the offline installer, be sure to select the "OpenGL" version. NOTE: Qt does not support 64-bit builds on Windows 7, so you must use the 32-bit version of libraries for interface.exe to run. The 32-bit version of the static library is the one linked by our CMake find modules. @@ -70,7 +70,7 @@ Once Qt is installed, you need to manually configure the following: If building as a Visual Studio 2013 project, download and configure the msvc2013 version of Qt instead. -####External Libraries +###External Libraries CMake will need to know where the headers and libraries for required external dependencies are. @@ -104,7 +104,7 @@ For many of the external libraries where precompiled binaries are readily availa As with the Qt libraries, you will need to make sure that directories containing DLL'S are in your path. Where possible, you can use static builds of the external dependencies to avoid this requirement. -#### OpenSSL +###OpenSSL QT will use OpenSSL if it's available, but it doesn't install it, so you must install it separately. @@ -124,13 +124,13 @@ To prevent these problems, install OpenSSL yourself. Download the following bina Install OpenSSL into the Windows system directory, to make sure that QT uses the version that you've just installed, and not some other version. -#### Intel Threading Building Blocks (TBB) +###Intel Threading Building Blocks (TBB) Download the stable release for Windows from the [Intel Threading Building Blocks website](https://www.threadingbuildingblocks.org/). By default, TBB will install to Program Files. You may also choose to install it to %HIFI_LIB_DIR%\TBB. You must run `tbbvars.bat` so that the find module included with this project will be able to find TBB no matter where you installed it. `tbbvars.bat` is located in the 'bin' folder of your TBB install. For a default installation on a 64-bit architechture, tbbvars can be found at `C:/Program Files (x86)/Intel/TBB/bin/tbbvars.bat`. -#### Zlib +###Zlib Download the compiled DLL from the [zlib website](http://www.zlib.net/). Extract to %HIFI_LIB_DIR%\zlib. @@ -144,25 +144,25 @@ Add to the PATH: `%HIFI_LIB_DIR%\zlib` Important! This should be added at the beginning of the path, not the end. That's because your system likely has many copies of zlib1.dll, and you want High Fidelity to use the correct version. If High Fidelity picks up the wrong zlib1.dll then it might be unable to use it, and that would cause it to fail to start, showing only the cryptic error "The application was unable to start correctly: 0xc0000022". -#### freeglut +###freeglut Download the binary package: `freeglut-MSVC-2.8.1-1.mp.zip`. Extract to %HIFI_LIB_DIR%\freeglut. Add to the PATH: `%HIFI_LIB_DIR%\freeglut\bin` -#### GLEW +###GLEW Download the binary package: `glew-1.10.0-win32.zip`. Extract to %HIFI_LIB_DIR%\glew (you'll need to rename the default directory name). Add to the PATH: `%HIFI_LIB_DIR%\glew\bin\Release\Win32` -#### GLM +###GLM This package contains only headers, so there's nothing to add to the PATH. Be careful with glm. For the folder other libraries would normally call 'include', the folder containing the headers, glm opts to use 'glm'. You will have a glm folder nested inside the top-level glm folder. -#### Build High Fidelity using Visual Studio +###Build High Fidelity using Visual Studio Follow the same build steps from the CMake section, but pass a different generator to CMake. cmake .. -DZLIB_LIBRARY=%ZLIB_LIBRARY% -DZLIB_INCLUDE_DIR=%ZLIB_INCLUDE_DIR% -G "Visual Studio 10" @@ -171,10 +171,10 @@ If you're using Visual Studio 2013 then pass "Visual Studio 12" instead of "Visu Open %HIFI_DIR%\build\hifi.sln and compile. -####Running Interface +###Running Interface If you need to debug Interface, you can run interface from within Visual Studio (see the section below). You can also run Interface by launching it from command line or File Explorer from %HIFI_DIR%\build\interface\Debug\interface.exe -####Debugging Interface +###Debugging Interface * In the Solution Explorer, right click interface and click Set as StartUp Project * Set the "Working Directory" for the Interface debugging sessions to the Debug output directory so that your application can load resources. Do this: right click interface and click Properties, choose Debugging from Configuration Properties, set Working Directory to .\Debug * Now you can run and debug interface through Visual Studio From 7d75d2d1bfe76f46b0fa3685ca56461853ffa670 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 10:34:16 -0800 Subject: [PATCH 084/258] make TextureCache work with DependancyManager --- interface/src/Application.cpp | 18 +++++++-------- interface/src/MetavoxelSystem.cpp | 18 +++++++-------- interface/src/ModelUploader.cpp | 2 +- interface/src/devices/OculusManager.cpp | 6 ++--- .../src/renderer/AmbientOcclusionEffect.cpp | 6 ++--- .../src/renderer/DeferredLightingEffect.cpp | 22 +++++++++---------- interface/src/renderer/GeometryCache.cpp | 16 +++++++------- interface/src/renderer/GlowEffect.cpp | 14 ++++++------ interface/src/renderer/Model.cpp | 20 ++++++++--------- interface/src/renderer/TextureCache.cpp | 6 ----- interface/src/renderer/TextureCache.h | 12 +++++----- interface/src/ui/MetavoxelEditor.cpp | 2 +- interface/src/voxels/VoxelSystem.cpp | 6 ++--- 13 files changed, 70 insertions(+), 78 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 1ec177163d..105e3e087c 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -620,10 +620,10 @@ void Application::paintGL() { // Set the desired FBO texture size. If it hasn't changed, this does nothing. // Otherwise, it must rebuild the FBOs if (OculusManager::isConnected()) { - TextureCache::getInstance()->setFrameBufferSize(OculusManager::getRenderTargetSize()); + DependencyManager::get()->setFrameBufferSize(OculusManager::getRenderTargetSize()); } else { QSize fbSize = _glWidget->getDeviceSize() * getRenderResolutionScale(); - TextureCache::getInstance()->setFrameBufferSize(fbSize); + DependencyManager::get()->setFrameBufferSize(fbSize); } glEnable(GL_LINE_SMOOTH); @@ -713,7 +713,7 @@ void Application::paintGL() { _glowEffect.prepare(); // Viewport is assigned to the size of the framebuffer - QSize size = TextureCache::getInstance()->getPrimaryFramebufferObject()->size(); + QSize size = DependencyManager::get()->getPrimaryFramebufferObject()->size(); glViewport(0, 0, size.width(), size.height()); glMatrixMode(GL_MODELVIEW); @@ -2043,7 +2043,7 @@ void Application::init() { connect(_myAvatar, &MyAvatar::transformChanged, this, &Application::bumpSettings); // make sure our texture cache knows about window size changes - TextureCache::getInstance()->associateWithWidget(getGLWidget()); + DependencyManager::get()->associateWithWidget(getGLWidget()); } void Application::closeMirrorView() { @@ -2774,7 +2774,7 @@ glm::vec3 Application::getSunDirection() { void Application::updateShadowMap() { PerformanceTimer perfTimer("shadowMap"); - QOpenGLFramebufferObject* fbo = TextureCache::getInstance()->getShadowFramebufferObject(); + QOpenGLFramebufferObject* fbo = DependencyManager::get()->getShadowFramebufferObject(); fbo->bind(); glEnable(GL_DEPTH_TEST); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); @@ -2939,7 +2939,7 @@ void Application::setupWorldLight() { } QImage Application::renderAvatarBillboard() { - TextureCache::getInstance()->getPrimaryFramebufferObject()->bind(); + DependencyManager::get()->getPrimaryFramebufferObject()->bind(); // the "glow" here causes an alpha of one Glower glower; @@ -2950,7 +2950,7 @@ QImage Application::renderAvatarBillboard() { QImage image(BILLBOARD_SIZE, BILLBOARD_SIZE, QImage::Format_ARGB32); glReadPixels(0, 0, BILLBOARD_SIZE, BILLBOARD_SIZE, GL_BGRA, GL_UNSIGNED_BYTE, image.bits()); - TextureCache::getInstance()->getPrimaryFramebufferObject()->release(); + DependencyManager::get()->getPrimaryFramebufferObject()->release(); return image; } @@ -3301,12 +3301,12 @@ void Application::renderRearViewMirror(const QRect& region, bool billboard) { // set the bounds of rear mirror view if (billboard) { - QSize size = TextureCache::getInstance()->getFrameBufferSize(); + QSize size = DependencyManager::get()->getFrameBufferSize(); glViewport(region.x(), size.height() - region.y() - region.height(), region.width(), region.height()); glScissor(region.x(), size.height() - region.y() - region.height(), region.width(), region.height()); } else { // if not rendering the billboard, the region is in device independent coordinates; must convert to device - QSize size = TextureCache::getInstance()->getFrameBufferSize(); + QSize size = DependencyManager::get()->getFrameBufferSize(); float ratio = QApplication::desktop()->windowHandle()->devicePixelRatio() * getRenderResolutionScale(); int x = region.x() * ratio, y = region.y() * ratio, width = region.width() * ratio, height = region.height() * ratio; glViewport(x, size.height() - y - height, width, height); diff --git a/interface/src/MetavoxelSystem.cpp b/interface/src/MetavoxelSystem.cpp index 2e3e9796f3..a61f6e41d7 100644 --- a/interface/src/MetavoxelSystem.cpp +++ b/interface/src/MetavoxelSystem.cpp @@ -205,7 +205,7 @@ void MetavoxelSystem::render() { glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); - TextureCache::getInstance()->setPrimaryDrawBuffers(true, true); + DependencyManager::get()->setPrimaryDrawBuffers(true, true); glDisable(GL_BLEND); glEnable(GL_CULL_FACE); @@ -251,7 +251,7 @@ void MetavoxelSystem::render() { glPopMatrix(); } - TextureCache::getInstance()->setPrimaryDrawBuffers(true, false); + DependencyManager::get()->setPrimaryDrawBuffers(true, false); _baseHeightfieldProgram.release(); @@ -348,7 +348,7 @@ void MetavoxelSystem::render() { } if (!_voxelBaseBatches.isEmpty()) { - TextureCache::getInstance()->setPrimaryDrawBuffers(true, true); + DependencyManager::get()->setPrimaryDrawBuffers(true, true); glEnableClientState(GL_VERTEX_ARRAY); glDisable(GL_BLEND); @@ -383,7 +383,7 @@ void MetavoxelSystem::render() { glDisable(GL_ALPHA_TEST); glEnable(GL_BLEND); - TextureCache::getInstance()->setPrimaryDrawBuffers(true, false); + DependencyManager::get()->setPrimaryDrawBuffers(true, false); if (!_voxelSplatBatches.isEmpty()) { glDepthFunc(GL_LEQUAL); @@ -463,7 +463,7 @@ void MetavoxelSystem::render() { } if (!_hermiteBatches.isEmpty() && Menu::getInstance()->isOptionChecked(MenuOption::DisplayHermiteData)) { - TextureCache::getInstance()->setPrimaryDrawBuffers(true, true); + DependencyManager::get()->setPrimaryDrawBuffers(true, true); glEnableClientState(GL_VERTEX_ARRAY); @@ -486,7 +486,7 @@ void MetavoxelSystem::render() { glDisableClientState(GL_VERTEX_ARRAY); - TextureCache::getInstance()->setPrimaryDrawBuffers(true, false); + DependencyManager::get()->setPrimaryDrawBuffers(true, false); } _hermiteBatches.clear(); @@ -797,7 +797,7 @@ void MetavoxelSystem::applyMaterialEdit(const MetavoxelEditMessage& message, boo Q_ARG(bool, reliable)); return; } - QSharedPointer texture = TextureCache::getInstance()->getTexture( + QSharedPointer texture = DependencyManager::get()->getTexture( material->getDiffuse(), SPLAT_TEXTURE); if (texture->isLoaded()) { MetavoxelEditMessage newMessage = message; @@ -1180,7 +1180,7 @@ void VoxelBuffer::render(bool cursor) { for (int i = 0; i < _materials.size(); i++) { const SharedObjectPointer material = _materials.at(i); if (material) { - _networkTextures[i] = TextureCache::getInstance()->getTexture( + _networkTextures[i] = DependencyManager::get()->getTexture( static_cast(material.data())->getDiffuse(), SPLAT_TEXTURE); } } @@ -2234,7 +2234,7 @@ void HeightfieldNodeRenderer::render(const HeightfieldNodePointer& node, const g for (int i = 0; i < materials.size(); i++) { const SharedObjectPointer& material = materials.at(i); if (material) { - _networkTextures[i] = TextureCache::getInstance()->getTexture( + _networkTextures[i] = DependencyManager::get()->getTexture( static_cast(material.data())->getDiffuse(), SPLAT_TEXTURE); } } diff --git a/interface/src/ModelUploader.cpp b/interface/src/ModelUploader.cpp index ee38a2c094..c3b6ba74c3 100644 --- a/interface/src/ModelUploader.cpp +++ b/interface/src/ModelUploader.cpp @@ -473,7 +473,7 @@ void ModelUploader::processCheck() { QMessageBox::Ok); GeometryCache::getInstance()->refresh(_url); foreach (const QByteArray& filename, _textureFilenames) { - TextureCache::getInstance()->refresh(_textureBase + filename); + DependencyManager::get()->refresh(_textureBase + filename); } deleteLater(); break; diff --git a/interface/src/devices/OculusManager.cpp b/interface/src/devices/OculusManager.cpp index 0eb0c732c9..d27ab09876 100644 --- a/interface/src/devices/OculusManager.cpp +++ b/interface/src/devices/OculusManager.cpp @@ -449,7 +449,7 @@ void OculusManager::display(const glm::quat &bodyOrientation, const glm::vec3 &p if (Menu::getInstance()->isOptionChecked(MenuOption::EnableGlowEffect)) { Application::getInstance()->getGlowEffect()->prepare(); } else { - TextureCache::getInstance()->getPrimaryFramebufferObject()->bind(); + DependencyManager::get()->getPrimaryFramebufferObject()->bind(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); } @@ -555,8 +555,8 @@ void OculusManager::display(const glm::quat &bodyOrientation, const glm::vec3 &p QOpenGLFramebufferObject* fbo = Application::getInstance()->getGlowEffect()->render(true); glBindTexture(GL_TEXTURE_2D, fbo->texture()); } else { - TextureCache::getInstance()->getPrimaryFramebufferObject()->release(); - glBindTexture(GL_TEXTURE_2D, TextureCache::getInstance()->getPrimaryFramebufferObject()->texture()); + DependencyManager::get()->getPrimaryFramebufferObject()->release(); + glBindTexture(GL_TEXTURE_2D, DependencyManager::get()->getPrimaryFramebufferObject()->texture()); } // restore our normal viewport diff --git a/interface/src/renderer/AmbientOcclusionEffect.cpp b/interface/src/renderer/AmbientOcclusionEffect.cpp index 9ef0fa2d82..3354f715cb 100644 --- a/interface/src/renderer/AmbientOcclusionEffect.cpp +++ b/interface/src/renderer/AmbientOcclusionEffect.cpp @@ -98,7 +98,7 @@ void AmbientOcclusionEffect::render() { glDisable(GL_DEPTH_TEST); glDepthMask(GL_FALSE); - glBindTexture(GL_TEXTURE_2D, TextureCache::getInstance()->getPrimaryDepthTextureID()); + glBindTexture(GL_TEXTURE_2D, DependencyManager::get()->getPrimaryDepthTextureID()); glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, _rotationTextureID); @@ -116,7 +116,7 @@ void AmbientOcclusionEffect::render() { glGetIntegerv(GL_VIEWPORT, viewport); const int VIEWPORT_X_INDEX = 0; const int VIEWPORT_WIDTH_INDEX = 2; - QOpenGLFramebufferObject* primaryFBO = TextureCache::getInstance()->getPrimaryFramebufferObject(); + QOpenGLFramebufferObject* primaryFBO = DependencyManager::get()->getPrimaryFramebufferObject(); float sMin = viewport[VIEWPORT_X_INDEX] / (float)primaryFBO->width(); float sWidth = viewport[VIEWPORT_WIDTH_INDEX] / (float)primaryFBO->width(); @@ -141,7 +141,7 @@ void AmbientOcclusionEffect::render() { glActiveTexture(GL_TEXTURE0); // now render secondary to primary with 4x4 blur - TextureCache::getInstance()->getPrimaryFramebufferObject()->bind(); + DependencyManager::get()->getPrimaryFramebufferObject()->bind(); glEnable(GL_BLEND); glBlendFuncSeparate(GL_ZERO, GL_SRC_COLOR, GL_ZERO, GL_ONE); diff --git a/interface/src/renderer/DeferredLightingEffect.cpp b/interface/src/renderer/DeferredLightingEffect.cpp index 42da3e0b08..facec197a7 100644 --- a/interface/src/renderer/DeferredLightingEffect.cpp +++ b/interface/src/renderer/DeferredLightingEffect.cpp @@ -37,7 +37,7 @@ void DeferredLightingEffect::init() { } void DeferredLightingEffect::bindSimpleProgram() { - TextureCache::getInstance()->setPrimaryDrawBuffers(true, true, true); + DependencyManager::get()->setPrimaryDrawBuffers(true, true, true); _simpleProgram.bind(); _simpleProgram.setUniformValue(_glowIntensityLocation, Application::getInstance()->getGlowEffect()->getIntensity()); glDisable(GL_BLEND); @@ -46,7 +46,7 @@ void DeferredLightingEffect::bindSimpleProgram() { void DeferredLightingEffect::releaseSimpleProgram() { glEnable(GL_BLEND); _simpleProgram.release(); - TextureCache::getInstance()->setPrimaryDrawBuffers(true, false, false); + DependencyManager::get()->setPrimaryDrawBuffers(true, false, false); } void DeferredLightingEffect::renderSolidSphere(float radius, int slices, int stacks) { @@ -117,15 +117,15 @@ void DeferredLightingEffect::addSpotLight(const glm::vec3& position, float radiu void DeferredLightingEffect::prepare() { // clear the normal and specular buffers - TextureCache::getInstance()->setPrimaryDrawBuffers(false, true, false); + DependencyManager::get()->setPrimaryDrawBuffers(false, true, false); glClear(GL_COLOR_BUFFER_BIT); - TextureCache::getInstance()->setPrimaryDrawBuffers(false, false, true); + DependencyManager::get()->setPrimaryDrawBuffers(false, false, true); // clearing to zero alpha for specular causes problems on my Nvidia card; clear to lowest non-zero value instead const float MAX_SPECULAR_EXPONENT = 128.0f; glClearColor(0.0f, 0.0f, 0.0f, 1.0f / MAX_SPECULAR_EXPONENT); glClear(GL_COLOR_BUFFER_BIT); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); - TextureCache::getInstance()->setPrimaryDrawBuffers(true, false, false); + DependencyManager::get()->setPrimaryDrawBuffers(true, false, false); } void DeferredLightingEffect::render() { @@ -138,7 +138,7 @@ void DeferredLightingEffect::render() { glDisable(GL_COLOR_MATERIAL); glDepthMask(false); - QOpenGLFramebufferObject* primaryFBO = TextureCache::getInstance()->getPrimaryFramebufferObject(); + QOpenGLFramebufferObject* primaryFBO = DependencyManager::get()->getPrimaryFramebufferObject(); primaryFBO->release(); QOpenGLFramebufferObject* freeFBO = Application::getInstance()->getGlowEffect()->getFreeFramebufferObject(); @@ -148,13 +148,13 @@ void DeferredLightingEffect::render() { glBindTexture(GL_TEXTURE_2D, primaryFBO->texture()); glActiveTexture(GL_TEXTURE1); - glBindTexture(GL_TEXTURE_2D, TextureCache::getInstance()->getPrimaryNormalTextureID()); + glBindTexture(GL_TEXTURE_2D, DependencyManager::get()->getPrimaryNormalTextureID()); glActiveTexture(GL_TEXTURE2); - glBindTexture(GL_TEXTURE_2D, TextureCache::getInstance()->getPrimarySpecularTextureID()); + glBindTexture(GL_TEXTURE_2D, DependencyManager::get()->getPrimarySpecularTextureID()); glActiveTexture(GL_TEXTURE3); - glBindTexture(GL_TEXTURE_2D, TextureCache::getInstance()->getPrimaryDepthTextureID()); + glBindTexture(GL_TEXTURE_2D, DependencyManager::get()->getPrimaryDepthTextureID()); // get the viewport side (left, right, both) int viewport[4]; @@ -173,7 +173,7 @@ void DeferredLightingEffect::render() { bool shadowsEnabled = Menu::getInstance()->getShadowsEnabled(); if (shadowsEnabled) { glActiveTexture(GL_TEXTURE4); - glBindTexture(GL_TEXTURE_2D, TextureCache::getInstance()->getShadowDepthTextureID()); + glBindTexture(GL_TEXTURE_2D, DependencyManager::get()->getShadowDepthTextureID()); program = &_directionalLightShadowMap; locations = &_directionalLightShadowMapLocations; @@ -188,7 +188,7 @@ void DeferredLightingEffect::render() { program->bind(); } program->setUniformValue(locations->shadowScale, - 1.0f / TextureCache::getInstance()->getShadowFramebufferObject()->width()); + 1.0f / DependencyManager::get()->getShadowFramebufferObject()->width()); } else { program->bind(); diff --git a/interface/src/renderer/GeometryCache.cpp b/interface/src/renderer/GeometryCache.cpp index 5cb544135c..048d3d0444 100644 --- a/interface/src/renderer/GeometryCache.cpp +++ b/interface/src/renderer/GeometryCache.cpp @@ -712,19 +712,19 @@ void NetworkGeometry::setTextureWithNameToURL(const QString& name, const QUrl& u QSharedPointer matchingTexture = QSharedPointer(); if (part.diffuseTextureName == name) { part.diffuseTexture = - TextureCache::getInstance()->getTexture(url, DEFAULT_TEXTURE, + DependencyManager::get()->getTexture(url, DEFAULT_TEXTURE, _geometry.meshes[i].isEye, QByteArray()); part.diffuseTexture->setLoadPriorities(_loadPriorities); } else if (part.normalTextureName == name) { - part.normalTexture = TextureCache::getInstance()->getTexture(url, DEFAULT_TEXTURE, + part.normalTexture = DependencyManager::get()->getTexture(url, DEFAULT_TEXTURE, false, QByteArray()); part.normalTexture->setLoadPriorities(_loadPriorities); } else if (part.specularTextureName == name) { - part.specularTexture = TextureCache::getInstance()->getTexture(url, DEFAULT_TEXTURE, + part.specularTexture = DependencyManager::get()->getTexture(url, DEFAULT_TEXTURE, false, QByteArray()); part.specularTexture->setLoadPriorities(_loadPriorities); } else if (part.emissiveTextureName == name) { - part.emissiveTexture = TextureCache::getInstance()->getTexture(url, DEFAULT_TEXTURE, + part.emissiveTexture = DependencyManager::get()->getTexture(url, DEFAULT_TEXTURE, false, QByteArray()); part.emissiveTexture->setLoadPriorities(_loadPriorities); } @@ -925,28 +925,28 @@ void NetworkGeometry::setGeometry(const FBXGeometry& geometry) { foreach (const FBXMeshPart& part, mesh.parts) { NetworkMeshPart networkPart; if (!part.diffuseTexture.filename.isEmpty()) { - networkPart.diffuseTexture = TextureCache::getInstance()->getTexture( + networkPart.diffuseTexture = DependencyManager::get()->getTexture( _textureBase.resolved(QUrl(part.diffuseTexture.filename)), DEFAULT_TEXTURE, mesh.isEye, part.diffuseTexture.content); networkPart.diffuseTextureName = part.diffuseTexture.name; networkPart.diffuseTexture->setLoadPriorities(_loadPriorities); } if (!part.normalTexture.filename.isEmpty()) { - networkPart.normalTexture = TextureCache::getInstance()->getTexture( + networkPart.normalTexture = DependencyManager::get()->getTexture( _textureBase.resolved(QUrl(part.normalTexture.filename)), NORMAL_TEXTURE, false, part.normalTexture.content); networkPart.normalTextureName = part.normalTexture.name; networkPart.normalTexture->setLoadPriorities(_loadPriorities); } if (!part.specularTexture.filename.isEmpty()) { - networkPart.specularTexture = TextureCache::getInstance()->getTexture( + networkPart.specularTexture = DependencyManager::get()->getTexture( _textureBase.resolved(QUrl(part.specularTexture.filename)), SPECULAR_TEXTURE, false, part.specularTexture.content); networkPart.specularTextureName = part.specularTexture.name; networkPart.specularTexture->setLoadPriorities(_loadPriorities); } if (!part.emissiveTexture.filename.isEmpty()) { - networkPart.emissiveTexture = TextureCache::getInstance()->getTexture( + networkPart.emissiveTexture = DependencyManager::get()->getTexture( _textureBase.resolved(QUrl(part.emissiveTexture.filename)), EMISSIVE_TEXTURE, false, part.emissiveTexture.content); networkPart.emissiveTextureName = part.emissiveTexture.name; diff --git a/interface/src/renderer/GlowEffect.cpp b/interface/src/renderer/GlowEffect.cpp index 8a9d957234..e6bbdb2ba1 100644 --- a/interface/src/renderer/GlowEffect.cpp +++ b/interface/src/renderer/GlowEffect.cpp @@ -41,8 +41,8 @@ GlowEffect::~GlowEffect() { QOpenGLFramebufferObject* GlowEffect::getFreeFramebufferObject() const { return (_isOddFrame ? - TextureCache::getInstance()->getSecondaryFramebufferObject(): - TextureCache::getInstance()->getTertiaryFramebufferObject()); + DependencyManager::get()->getSecondaryFramebufferObject(): + DependencyManager::get()->getTertiaryFramebufferObject()); } static ProgramObject* createProgram(const QString& name) { @@ -88,7 +88,7 @@ void GlowEffect::init() { } void GlowEffect::prepare() { - TextureCache::getInstance()->getPrimaryFramebufferObject()->bind(); + DependencyManager::get()->getPrimaryFramebufferObject()->bind(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); _isEmpty = true; @@ -122,7 +122,7 @@ static void maybeRelease(QOpenGLFramebufferObject* fbo) { QOpenGLFramebufferObject* GlowEffect::render(bool toTexture) { PerformanceTimer perfTimer("glowEffect"); - QOpenGLFramebufferObject* primaryFBO = TextureCache::getInstance()->getPrimaryFramebufferObject(); + QOpenGLFramebufferObject* primaryFBO = DependencyManager::get()->getPrimaryFramebufferObject(); primaryFBO->release(); glBindTexture(GL_TEXTURE_2D, primaryFBO->texture()); @@ -138,7 +138,7 @@ QOpenGLFramebufferObject* GlowEffect::render(bool toTexture) { glDepthMask(GL_FALSE); QOpenGLFramebufferObject* destFBO = toTexture ? - TextureCache::getInstance()->getSecondaryFramebufferObject() : NULL; + DependencyManager::get()->getSecondaryFramebufferObject() : NULL; if (!Menu::getInstance()->isOptionChecked(MenuOption::EnableGlowEffect) || _isEmpty) { // copy the primary to the screen if (destFBO && QOpenGLFramebufferObject::hasOpenGLFramebufferBlit()) { @@ -160,9 +160,9 @@ QOpenGLFramebufferObject* GlowEffect::render(bool toTexture) { } else { // diffuse into the secondary/tertiary (alternating between frames) QOpenGLFramebufferObject* oldDiffusedFBO = - TextureCache::getInstance()->getSecondaryFramebufferObject(); + DependencyManager::get()->getSecondaryFramebufferObject(); QOpenGLFramebufferObject* newDiffusedFBO = - TextureCache::getInstance()->getTertiaryFramebufferObject(); + DependencyManager::get()->getTertiaryFramebufferObject(); if (_isOddFrame) { qSwap(oldDiffusedFBO, newDiffusedFBO); } diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index 45c80852ad..7004b277ca 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -749,7 +749,7 @@ bool Model::renderCore(float alpha, RenderMode mode, RenderArgs* args) { } - /*TextureCache::getInstance()->setPrimaryDrawBuffers( + /*DependencyManager::get()->setPrimaryDrawBuffers( mode == DEFAULT_RENDER_MODE || mode == DIFFUSE_RENDER_MODE, mode == DEFAULT_RENDER_MODE || mode == NORMAL_RENDER_MODE, mode == DEFAULT_RENDER_MODE); @@ -789,7 +789,7 @@ bool Model::renderCore(float alpha, RenderMode mode, RenderArgs* args) { opaqueMeshPartsRendered += renderMeshes(batch, mode, false, DEFAULT_ALPHA_THRESHOLD, true, true, true, false, args); // render translucent meshes afterwards - //TextureCache::getInstance()->setPrimaryDrawBuffers(false, true, true); + //DependencyManager::get()->setPrimaryDrawBuffers(false, true, true); { GLenum buffers[2]; int bufferCount = 0; @@ -814,7 +814,7 @@ bool Model::renderCore(float alpha, RenderMode mode, RenderArgs* args) { GLBATCH(glDepthMask)(false); GLBATCH(glDepthFunc)(GL_LEQUAL); - //TextureCache::getInstance()->setPrimaryDrawBuffers(true); + //DependencyManager::get()->setPrimaryDrawBuffers(true); { GLenum buffers[1]; int bufferCount = 0; @@ -1705,7 +1705,7 @@ void Model::endScene(RenderMode mode, RenderArgs* args) { } - /*TextureCache::getInstance()->setPrimaryDrawBuffers( + /*DependencyManager::get()->setPrimaryDrawBuffers( mode == DEFAULT_RENDER_MODE || mode == DIFFUSE_RENDER_MODE, mode == DEFAULT_RENDER_MODE || mode == NORMAL_RENDER_MODE, mode == DEFAULT_RENDER_MODE); @@ -1745,7 +1745,7 @@ void Model::endScene(RenderMode mode, RenderArgs* args) { opaqueMeshPartsRendered += renderMeshesForModelsInScene(batch, mode, false, DEFAULT_ALPHA_THRESHOLD, true, true, true, false, args); // render translucent meshes afterwards - //TextureCache::getInstance()->setPrimaryDrawBuffers(false, true, true); + //DependencyManager::get()->setPrimaryDrawBuffers(false, true, true); { GLenum buffers[2]; int bufferCount = 0; @@ -1770,7 +1770,7 @@ void Model::endScene(RenderMode mode, RenderArgs* args) { GLBATCH(glDepthMask)(false); GLBATCH(glDepthFunc)(GL_LEQUAL); - //TextureCache::getInstance()->setPrimaryDrawBuffers(true); + //DependencyManager::get()->setPrimaryDrawBuffers(true); { GLenum buffers[1]; int bufferCount = 0; @@ -2446,7 +2446,7 @@ int Model::renderMeshesFromList(QVector& list, gpu::Batch& batch, RenderMod if (showDiffuse && diffuseMap) { GLBATCH(glBindTexture)(GL_TEXTURE_2D, diffuseMap->getID()); } else { - GLBATCH(glBindTexture)(GL_TEXTURE_2D, TextureCache::getInstance()->getWhiteTextureID()); + GLBATCH(glBindTexture)(GL_TEXTURE_2D, DependencyManager::get()->getWhiteTextureID()); } if (locations->texcoordMatrices >= 0) { @@ -2464,7 +2464,7 @@ int Model::renderMeshesFromList(QVector& list, gpu::Batch& batch, RenderMod GLBATCH(glActiveTexture)(GL_TEXTURE1); Texture* normalMap = networkPart.normalTexture.data(); GLBATCH(glBindTexture)(GL_TEXTURE_2D, !normalMap ? - TextureCache::getInstance()->getBlueTextureID() : normalMap->getID()); + DependencyManager::get()->getBlueTextureID() : normalMap->getID()); GLBATCH(glActiveTexture)(GL_TEXTURE0); } @@ -2472,7 +2472,7 @@ int Model::renderMeshesFromList(QVector& list, gpu::Batch& batch, RenderMod GLBATCH(glActiveTexture)(GL_TEXTURE0 + locations->specularTextureUnit); Texture* specularMap = networkPart.specularTexture.data(); GLBATCH(glBindTexture)(GL_TEXTURE_2D, !specularMap ? - TextureCache::getInstance()->getWhiteTextureID() : specularMap->getID()); + DependencyManager::get()->getWhiteTextureID() : specularMap->getID()); GLBATCH(glActiveTexture)(GL_TEXTURE0); } @@ -2493,7 +2493,7 @@ int Model::renderMeshesFromList(QVector& list, gpu::Batch& batch, RenderMod GLBATCH(glActiveTexture)(GL_TEXTURE0 + locations->emissiveTextureUnit); Texture* emissiveMap = networkPart.emissiveTexture.data(); GLBATCH(glBindTexture)(GL_TEXTURE_2D, !emissiveMap ? - TextureCache::getInstance()->getWhiteTextureID() : emissiveMap->getID()); + DependencyManager::get()->getWhiteTextureID() : emissiveMap->getID()); GLBATCH(glActiveTexture)(GL_TEXTURE0); } diff --git a/interface/src/renderer/TextureCache.cpp b/interface/src/renderer/TextureCache.cpp index 4d246a4c9c..123a8a5384 100644 --- a/interface/src/renderer/TextureCache.cpp +++ b/interface/src/renderer/TextureCache.cpp @@ -25,12 +25,6 @@ #include "TextureCache.h" -TextureCache* TextureCache::getInstance() { - static TextureCache instance; - return &instance; -} - - TextureCache::TextureCache() : _permutationNormalTextureID(0), _whiteTextureID(0), diff --git a/interface/src/renderer/TextureCache.h b/interface/src/renderer/TextureCache.h index 3cbfaced49..2bdfda3217 100644 --- a/interface/src/renderer/TextureCache.h +++ b/interface/src/renderer/TextureCache.h @@ -16,6 +16,7 @@ #include #include +#include #include #include "InterfaceConfig.h" @@ -29,16 +30,11 @@ typedef QSharedPointer NetworkTexturePointer; enum TextureType { DEFAULT_TEXTURE, NORMAL_TEXTURE, SPECULAR_TEXTURE, EMISSIVE_TEXTURE, SPLAT_TEXTURE }; /// Stores cached textures, including render-to-texture targets. -class TextureCache : public ResourceCache { +class TextureCache : public ResourceCache, public DependencyManager::Dependency { Q_OBJECT public: - static TextureCache* getInstance(); - - TextureCache(); - virtual ~TextureCache(); - void associateWithWidget(QGLWidget* widget); /// Sets the desired texture resolution for the framebuffer objects. @@ -98,7 +94,9 @@ protected: const QSharedPointer& fallback, bool delayLoad, const void* extra); private: - + TextureCache(); + virtual ~TextureCache(); + friend class DependencyManager; friend class DilatableNetworkTexture; QOpenGLFramebufferObject* createFramebufferObject(); diff --git a/interface/src/ui/MetavoxelEditor.cpp b/interface/src/ui/MetavoxelEditor.cpp index dde181c571..1ca81f3d95 100644 --- a/interface/src/ui/MetavoxelEditor.cpp +++ b/interface/src/ui/MetavoxelEditor.cpp @@ -916,7 +916,7 @@ void MaterialControl::updateTexture() { _texture.clear(); return; } - _texture = TextureCache::getInstance()->getTexture(material->getDiffuse(), SPLAT_TEXTURE); + _texture = DependencyManager::get()->getTexture(material->getDiffuse(), SPLAT_TEXTURE); if (_texture) { if (_texture->isLoaded()) { textureLoaded(); diff --git a/interface/src/voxels/VoxelSystem.cpp b/interface/src/voxels/VoxelSystem.cpp index 6fd477d8f3..357bfe9c3e 100644 --- a/interface/src/voxels/VoxelSystem.cpp +++ b/interface/src/voxels/VoxelSystem.cpp @@ -1170,7 +1170,7 @@ void VoxelSystem::render() { void VoxelSystem::applyScaleAndBindProgram(bool texture) { if (texture) { bindPerlinModulateProgram(); - glBindTexture(GL_TEXTURE_2D, TextureCache::getInstance()->getPermutationNormalTextureID()); + glBindTexture(GL_TEXTURE_2D, DependencyManager::get()->getPermutationNormalTextureID()); } else { _program.bind(); } @@ -1178,7 +1178,7 @@ void VoxelSystem::applyScaleAndBindProgram(bool texture) { glPushMatrix(); glScalef(_treeScale, _treeScale, _treeScale); - TextureCache::getInstance()->setPrimaryDrawBuffers(true, true); + DependencyManager::get()->setPrimaryDrawBuffers(true, true); } void VoxelSystem::removeScaleAndReleaseProgram(bool texture) { @@ -1192,7 +1192,7 @@ void VoxelSystem::removeScaleAndReleaseProgram(bool texture) { _program.release(); } - TextureCache::getInstance()->setPrimaryDrawBuffers(true, false); + DependencyManager::get()->setPrimaryDrawBuffers(true, false); } int VoxelSystem::_nodeCount = 0; From e0a017e963fd290822b7bef9c8360e2d5ec1033f Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 10:49:34 -0800 Subject: [PATCH 085/258] make GeometryCache work with DependancyManager --- interface/src/Application.cpp | 2 +- interface/src/Environment.cpp | 2 +- interface/src/ModelUploader.cpp | 2 +- interface/src/Util.cpp | 8 ++++---- interface/src/avatar/Avatar.cpp | 4 ++-- interface/src/avatar/Hand.cpp | 4 ++-- interface/src/avatar/MyAvatar.cpp | 4 ++-- interface/src/avatar/SkeletonModel.cpp | 14 +++++++------- interface/src/renderer/DeferredLightingEffect.cpp | 8 ++++---- interface/src/renderer/GeometryCache.cpp | 5 ----- interface/src/renderer/GeometryCache.h | 12 +++++------- interface/src/renderer/Model.cpp | 2 +- interface/src/ui/MetavoxelEditor.cpp | 2 +- interface/src/ui/overlays/Grid3DOverlay.cpp | 4 ++-- interface/src/ui/overlays/Sphere3DOverlay.cpp | 2 +- 15 files changed, 34 insertions(+), 41 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 105e3e087c..766424ef4b 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -3080,7 +3080,7 @@ void Application::displaySide(Camera& whichCamera, bool selfAvatarOnly, RenderAr // draw a red sphere float originSphereRadius = 0.05f; glColor3f(1,0,0); - GeometryCache::getInstance()->renderSphere(originSphereRadius, 15, 15); + DependencyManager::get()->renderSphere(originSphereRadius, 15, 15); // Draw voxels if (Menu::getInstance()->isOptionChecked(MenuOption::Voxels)) { diff --git a/interface/src/Environment.cpp b/interface/src/Environment.cpp index a754b63eec..fa8f18ac3f 100644 --- a/interface/src/Environment.cpp +++ b/interface/src/Environment.cpp @@ -261,7 +261,7 @@ void Environment::renderAtmosphere(Camera& camera, const EnvironmentData& data) glDepthMask(GL_FALSE); glDisable(GL_DEPTH_TEST); - GeometryCache::getInstance()->renderSphere(1.0f, 100, 50); //Draw a unit sphere + DependencyManager::get()->renderSphere(1.0f, 100, 50); //Draw a unit sphere glDepthMask(GL_TRUE); program->release(); diff --git a/interface/src/ModelUploader.cpp b/interface/src/ModelUploader.cpp index c3b6ba74c3..b22457f847 100644 --- a/interface/src/ModelUploader.cpp +++ b/interface/src/ModelUploader.cpp @@ -471,7 +471,7 @@ void ModelUploader::processCheck() { QString("ModelUploader::processCheck()"), QString("Your model is now available in the browser."), QMessageBox::Ok); - GeometryCache::getInstance()->refresh(_url); + DependencyManager::get()->refresh(_url); foreach (const QByteArray& filename, _textureFilenames) { DependencyManager::get()->refresh(_textureBase + filename); } diff --git a/interface/src/Util.cpp b/interface/src/Util.cpp index 256e437e21..d93c8a26ad 100644 --- a/interface/src/Util.cpp +++ b/interface/src/Util.cpp @@ -71,22 +71,22 @@ void renderWorldBox() { glPushMatrix(); glTranslatef(MARKER_DISTANCE, 0, 0); glColor3fv(red); - GeometryCache::getInstance()->renderSphere(MARKER_RADIUS, 10, 10); + DependencyManager::get()->renderSphere(MARKER_RADIUS, 10, 10); glPopMatrix(); glPushMatrix(); glTranslatef(0, MARKER_DISTANCE, 0); glColor3fv(green); - GeometryCache::getInstance()->renderSphere(MARKER_RADIUS, 10, 10); + DependencyManager::get()->renderSphere(MARKER_RADIUS, 10, 10); glPopMatrix(); glPushMatrix(); glTranslatef(0, 0, MARKER_DISTANCE); glColor3fv(blue); - GeometryCache::getInstance()->renderSphere(MARKER_RADIUS, 10, 10); + DependencyManager::get()->renderSphere(MARKER_RADIUS, 10, 10); glPopMatrix(); glPushMatrix(); glColor3fv(gray); glTranslatef(MARKER_DISTANCE, 0, MARKER_DISTANCE); - GeometryCache::getInstance()->renderSphere(MARKER_RADIUS, 10, 10); + DependencyManager::get()->renderSphere(MARKER_RADIUS, 10, 10); glPopMatrix(); } diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index 0edf59290f..49a6f436df 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -394,7 +394,7 @@ void Avatar::render(const glm::vec3& cameraPosition, RenderMode renderMode, bool } else { glTranslatef(_position.x, getDisplayNamePosition().y + LOOK_AT_INDICATOR_OFFSET, _position.z); } - GeometryCache::getInstance()->renderSphere(LOOK_AT_INDICATOR_RADIUS, 15, 15); + DependencyManager::get()->renderSphere(LOOK_AT_INDICATOR_RADIUS, 15, 15); glPopMatrix(); } } @@ -422,7 +422,7 @@ void Avatar::render(const glm::vec3& cameraPosition, RenderMode renderMode, bool glPushMatrix(); glTranslatef(_position.x, _position.y, _position.z); glScalef(height, height, height); - GeometryCache::getInstance()->renderSphere(sphereRadius, 15, 15); + DependencyManager::get()->renderSphere(sphereRadius, 15, 15); glPopMatrix(); } diff --git a/interface/src/avatar/Hand.cpp b/interface/src/avatar/Hand.cpp index fef4ac2fac..9d1ee52fde 100644 --- a/interface/src/avatar/Hand.cpp +++ b/interface/src/avatar/Hand.cpp @@ -114,7 +114,7 @@ void Hand::render(bool isMine, Model::RenderMode renderMode) { glPushMatrix(); glTranslatef(position.x, position.y, position.z); glColor3f(0.0f, 1.0f, 0.0f); - GeometryCache::getInstance()->renderSphere(PALM_COLLISION_RADIUS * _owningAvatar->getScale(), 10, 10); + DependencyManager::get()->renderSphere(PALM_COLLISION_RADIUS * _owningAvatar->getScale(), 10, 10); glPopMatrix(); } } @@ -179,7 +179,7 @@ void Hand::renderHandTargets(bool isMine) { Avatar::renderJointConnectingCone(root, offsetFromPalm, PALM_DISK_RADIUS, 0.0f); glPushMatrix(); glTranslatef(root.x, root.y, root.z); - GeometryCache::getInstance()->renderSphere(PALM_BALL_RADIUS, 20.0f, 20.0f); + DependencyManager::get()->renderSphere(PALM_BALL_RADIUS, 20.0f, 20.0f); glPopMatrix(); } } diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 255e79ebcd..057b1f1fc6 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -394,7 +394,7 @@ void MyAvatar::renderDebugBodyPoints() { glPushMatrix(); glColor4f(0, 1, 0, .5f); glTranslatef(position.x, position.y, position.z); - GeometryCache::getInstance()->renderSphere(0.2f, 10.0f, 10.0f); + DependencyManager::get()->renderSphere(0.2f, 10.0f, 10.0f); glPopMatrix(); // Head Sphere @@ -402,7 +402,7 @@ void MyAvatar::renderDebugBodyPoints() { glPushMatrix(); glColor4f(0, 1, 0, .5f); glTranslatef(position.x, position.y, position.z); - GeometryCache::getInstance()->renderSphere(0.15f, 10.0f, 10.0f); + DependencyManager::get()->renderSphere(0.15f, 10.0f, 10.0f); glPopMatrix(); } diff --git a/interface/src/avatar/SkeletonModel.cpp b/interface/src/avatar/SkeletonModel.cpp index 9bc2b627be..f71c9318aa 100644 --- a/interface/src/avatar/SkeletonModel.cpp +++ b/interface/src/avatar/SkeletonModel.cpp @@ -561,9 +561,9 @@ void SkeletonModel::renderRagdoll() { glTranslatef(position.x, position.y, position.z); // draw each point as a yellow hexagon with black border glColor4f(0.0f, 0.0f, 0.0f, alpha); - GeometryCache::getInstance()->renderSphere(radius2, BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); + DependencyManager::get()->renderSphere(radius2, BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); glColor4f(1.0f, 1.0f, 0.0f, alpha); - GeometryCache::getInstance()->renderSphere(radius1, BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); + DependencyManager::get()->renderSphere(radius1, BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); glPopMatrix(); } glPopMatrix(); @@ -913,7 +913,7 @@ void SkeletonModel::renderBoundingCollisionShapes(float alpha) { endPoint = endPoint - _translation; glTranslatef(endPoint.x, endPoint.y, endPoint.z); glColor4f(0.6f, 0.6f, 0.8f, alpha); - GeometryCache::getInstance()->renderSphere(_boundingShape.getRadius(), BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); + DependencyManager::get()->renderSphere(_boundingShape.getRadius(), BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); // draw a yellow sphere at the capsule startpoint glm::vec3 startPoint; @@ -922,7 +922,7 @@ void SkeletonModel::renderBoundingCollisionShapes(float alpha) { glm::vec3 axis = endPoint - startPoint; glTranslatef(-axis.x, -axis.y, -axis.z); glColor4f(0.8f, 0.8f, 0.6f, alpha); - GeometryCache::getInstance()->renderSphere(_boundingShape.getRadius(), BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); + DependencyManager::get()->renderSphere(_boundingShape.getRadius(), BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); // draw a green cylinder between the two points glm::vec3 origin(0.0f); @@ -955,7 +955,7 @@ void SkeletonModel::renderJointCollisionShapes(float alpha) { glTranslatef(position.x, position.y, position.z); // draw a grey sphere at shape position glColor4f(0.75f, 0.75f, 0.75f, alpha); - GeometryCache::getInstance()->renderSphere(shape->getBoundingRadius(), BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); + DependencyManager::get()->renderSphere(shape->getBoundingRadius(), BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); } else if (shape->getType() == CAPSULE_SHAPE) { CapsuleShape* capsule = static_cast(shape); @@ -965,7 +965,7 @@ void SkeletonModel::renderJointCollisionShapes(float alpha) { endPoint = endPoint - simulationTranslation; glTranslatef(endPoint.x, endPoint.y, endPoint.z); glColor4f(0.6f, 0.6f, 0.8f, alpha); - GeometryCache::getInstance()->renderSphere(capsule->getRadius(), BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); + DependencyManager::get()->renderSphere(capsule->getRadius(), BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); // draw a yellow sphere at the capsule startpoint glm::vec3 startPoint; @@ -974,7 +974,7 @@ void SkeletonModel::renderJointCollisionShapes(float alpha) { glm::vec3 axis = endPoint - startPoint; glTranslatef(-axis.x, -axis.y, -axis.z); glColor4f(0.8f, 0.8f, 0.6f, alpha); - GeometryCache::getInstance()->renderSphere(capsule->getRadius(), BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); + DependencyManager::get()->renderSphere(capsule->getRadius(), BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); // draw a green cylinder between the two points glm::vec3 origin(0.0f); diff --git a/interface/src/renderer/DeferredLightingEffect.cpp b/interface/src/renderer/DeferredLightingEffect.cpp index facec197a7..75af4647e4 100644 --- a/interface/src/renderer/DeferredLightingEffect.cpp +++ b/interface/src/renderer/DeferredLightingEffect.cpp @@ -51,7 +51,7 @@ void DeferredLightingEffect::releaseSimpleProgram() { void DeferredLightingEffect::renderSolidSphere(float radius, int slices, int stacks) { bindSimpleProgram(); - GeometryCache::getInstance()->renderSphere(radius, slices, stacks); + DependencyManager::get()->renderSphere(radius, slices, stacks); releaseSimpleProgram(); } @@ -75,7 +75,7 @@ void DeferredLightingEffect::renderWireCube(float size) { void DeferredLightingEffect::renderSolidCone(float base, float height, int slices, int stacks) { bindSimpleProgram(); - GeometryCache::getInstance()->renderCone(base, height, slices, stacks); + DependencyManager::get()->renderCone(base, height, slices, stacks); releaseSimpleProgram(); } @@ -270,7 +270,7 @@ void DeferredLightingEffect::render() { } else { glTranslatef(light.position.x, light.position.y, light.position.z); - GeometryCache::getInstance()->renderSphere(expandedRadius, 32, 32); + DependencyManager::get()->renderSphere(expandedRadius, 32, 32); } glPopMatrix(); @@ -323,7 +323,7 @@ void DeferredLightingEffect::render() { glm::vec3 axis = glm::axis(spotRotation); glRotatef(glm::degrees(glm::angle(spotRotation)), axis.x, axis.y, axis.z); glTranslatef(0.0f, 0.0f, -light.radius * (1.0f + SCALE_EXPANSION * 0.5f)); - GeometryCache::getInstance()->renderCone(expandedRadius * glm::tan(light.cutoff), + DependencyManager::get()->renderCone(expandedRadius * glm::tan(light.cutoff), expandedRadius, 32, 1); } diff --git a/interface/src/renderer/GeometryCache.cpp b/interface/src/renderer/GeometryCache.cpp index 048d3d0444..534911ff46 100644 --- a/interface/src/renderer/GeometryCache.cpp +++ b/interface/src/renderer/GeometryCache.cpp @@ -23,11 +23,6 @@ #include "GeometryCache.h" #include "TextureCache.h" -GeometryCache* GeometryCache::getInstance() { - static GeometryCache instance; - return &instance; -} - GeometryCache::GeometryCache() { } diff --git a/interface/src/renderer/GeometryCache.h b/interface/src/renderer/GeometryCache.h index 1eb9dcbc6a..2d813ece09 100644 --- a/interface/src/renderer/GeometryCache.h +++ b/interface/src/renderer/GeometryCache.h @@ -18,6 +18,7 @@ #include #include +#include #include #include @@ -31,16 +32,10 @@ class NetworkMesh; class NetworkTexture; /// Stores cached geometry. -class GeometryCache : public ResourceCache { +class GeometryCache : public ResourceCache, public DependencyManager::Dependency { Q_OBJECT public: - - static GeometryCache* getInstance(); - - GeometryCache(); - virtual ~GeometryCache(); - void renderHemisphere(int slices, int stacks); void renderSphere(float radius, int slices, int stacks); void renderSquare(int xDivisions, int yDivisions); @@ -59,6 +54,9 @@ protected: const QSharedPointer& fallback, bool delayLoad, const void* extra); private: + GeometryCache(); + virtual ~GeometryCache(); + friend class DependencyManager; typedef QPair IntPair; typedef QPair VerticesIndices; diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index 7004b277ca..0ab3f82fda 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -997,7 +997,7 @@ void Model::setURL(const QUrl& url, const QUrl& fallback, bool retainCurrent, bo _url = url; // if so instructed, keep the current geometry until the new one is loaded - _nextBaseGeometry = _nextGeometry = GeometryCache::getInstance()->getGeometry(url, fallback, delayLoad); + _nextBaseGeometry = _nextGeometry = DependencyManager::get()->getGeometry(url, fallback, delayLoad); _nextLODHysteresis = NetworkGeometry::NO_HYSTERESIS; if (!retainCurrent || !isActive() || _nextGeometry->isLoaded()) { applyNextGeometry(); diff --git a/interface/src/ui/MetavoxelEditor.cpp b/interface/src/ui/MetavoxelEditor.cpp index 1ca81f3d95..158532e19a 100644 --- a/interface/src/ui/MetavoxelEditor.cpp +++ b/interface/src/ui/MetavoxelEditor.cpp @@ -353,7 +353,7 @@ void MetavoxelEditor::render() { _gridProgram.bind(); - GeometryCache::getInstance()->renderGrid(GRID_DIVISIONS, GRID_DIVISIONS); + DependencyManager::get()->renderGrid(GRID_DIVISIONS, GRID_DIVISIONS); _gridProgram.release(); diff --git a/interface/src/ui/overlays/Grid3DOverlay.cpp b/interface/src/ui/overlays/Grid3DOverlay.cpp index 67dd0b8e21..d1086ae534 100644 --- a/interface/src/ui/overlays/Grid3DOverlay.cpp +++ b/interface/src/ui/overlays/Grid3DOverlay.cpp @@ -87,7 +87,7 @@ void Grid3DOverlay::render(RenderArgs* args) { float scale = MINOR_GRID_DIVISIONS * spacing; glScalef(scale, scale, scale); - GeometryCache::getInstance()->renderGrid(MINOR_GRID_DIVISIONS, MINOR_GRID_DIVISIONS); + DependencyManager::get()->renderGrid(MINOR_GRID_DIVISIONS, MINOR_GRID_DIVISIONS); } glPopMatrix(); @@ -102,7 +102,7 @@ void Grid3DOverlay::render(RenderArgs* args) { float scale = MAJOR_GRID_DIVISIONS * spacing; glScalef(scale, scale, scale); - GeometryCache::getInstance()->renderGrid(MAJOR_GRID_DIVISIONS, MAJOR_GRID_DIVISIONS); + DependencyManager::get()->renderGrid(MAJOR_GRID_DIVISIONS, MAJOR_GRID_DIVISIONS); } glPopMatrix(); diff --git a/interface/src/ui/overlays/Sphere3DOverlay.cpp b/interface/src/ui/overlays/Sphere3DOverlay.cpp index b9aeb5145a..ded1b3917c 100644 --- a/interface/src/ui/overlays/Sphere3DOverlay.cpp +++ b/interface/src/ui/overlays/Sphere3DOverlay.cpp @@ -63,7 +63,7 @@ void Sphere3DOverlay::render(RenderArgs* args) { glScalef(dimensions.x, dimensions.y, dimensions.z); //Application::getInstance()->getDeferredLightingEffect()->renderSolidCube(1.0f); if (_isSolid) { - GeometryCache::getInstance()->renderSphere(1.0f, SLICES, SLICES); + DependencyManager::get()->renderSphere(1.0f, SLICES, SLICES); } else { glutWireSphere(1.0f, SLICES, SLICES); } From 049cb25f07c3c4d52f5ef9238f5ae36956c9227e Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 10:56:29 -0800 Subject: [PATCH 086/258] make ModelBlender work with DependancyManager --- interface/src/renderer/Model.cpp | 9 ++------- interface/src/renderer/Model.h | 13 ++++++------- 2 files changed, 8 insertions(+), 14 deletions(-) diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index 0ab3f82fda..62170efeed 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -1149,7 +1149,7 @@ void Blender::run() { } } // post the result to the geometry cache, which will dispatch to the model if still alive - QMetaObject::invokeMethod(ModelBlender::getInstance(), "setBlendedVertices", + QMetaObject::invokeMethod(DependencyManager::get(), "setBlendedVertices", Q_ARG(const QPointer&, _model), Q_ARG(int, _blendNumber), Q_ARG(const QWeakPointer&, _geometry), Q_ARG(const QVector&, vertices), Q_ARG(const QVector&, normals)); @@ -1312,7 +1312,7 @@ void Model::simulateInternal(float deltaTime) { // post the blender if we're not currently waiting for one to finish if (geometry.hasBlendedMeshes() && _blendshapeCoefficients != _blendedBlendshapeCoefficients) { _blendedBlendshapeCoefficients = _blendshapeCoefficients; - ModelBlender::getInstance()->noteRequiresBlend(this); + DependencyManager::get()->noteRequiresBlend(this); } } @@ -2545,11 +2545,6 @@ int Model::renderMeshesFromList(QVector& list, gpu::Batch& batch, RenderMod return meshPartsRendered; } -ModelBlender* ModelBlender::getInstance() { - static ModelBlender instance; - return &instance; -} - ModelBlender::ModelBlender() : _pendingBlenders(0) { } diff --git a/interface/src/renderer/Model.h b/interface/src/renderer/Model.h index e95b2472ba..9b609de1d0 100644 --- a/interface/src/renderer/Model.h +++ b/interface/src/renderer/Model.h @@ -19,6 +19,7 @@ #include "Transform.h" #include #include +#include #include #include @@ -460,17 +461,11 @@ Q_DECLARE_METATYPE(QWeakPointer) Q_DECLARE_METATYPE(QVector) /// Handle management of pending models that need blending -class ModelBlender : public QObject { +class ModelBlender : public QObject, public DependencyManager::Dependency { Q_OBJECT public: - static ModelBlender* getInstance(); - - ModelBlender(); - virtual ~ModelBlender(); - - /// Adds the specified model to the list requiring vertex blends. void noteRequiresBlend(Model* model); @@ -479,6 +474,10 @@ public slots: const QVector& vertices, const QVector& normals); private: + ModelBlender(); + virtual ~ModelBlender(); + friend class DependencyManager; + QList > _modelsRequiringBlends; int _pendingBlenders; }; From 25df784f433c49c8c51df5c2e0b4f13c0470563d Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Mon, 15 Dec 2014 10:56:42 -0800 Subject: [PATCH 087/258] Headers cleanup --- interface/src/Application.cpp | 1 + interface/src/Application.h | 20 ++++--------------- interface/src/GLCanvas.cpp | 2 +- interface/src/Menu.cpp | 1 + interface/src/entities/EntityTreeRenderer.h | 3 +++ .../scripting/WindowScriptingInterface.cpp | 1 + interface/src/ui/AddressBarDialog.cpp | 1 + interface/src/ui/AnimationsDialog.cpp | 1 + interface/src/ui/AttachmentsDialog.cpp | 1 + interface/src/ui/ChatWindow.cpp | 4 +++- interface/src/ui/HMDToolsDialog.cpp | 1 + interface/src/ui/MetavoxelEditor.cpp | 1 + interface/src/ui/PreferencesDialog.cpp | 1 + interface/src/ui/ToolWindow.cpp | 1 + 14 files changed, 21 insertions(+), 18 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index fbe55071e4..d0abc47b85 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -61,6 +61,7 @@ #include #include #include +#include #include #include #include diff --git a/interface/src/Application.h b/interface/src/Application.h index 833f1374ce..c2136f1c57 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -12,35 +12,21 @@ #ifndef hifi_Application_h #define hifi_Application_h -#include -#include - #include -#include -#include #include #include -#include #include #include #include #include -#include -#include #include -#include #include #include -#include -#include -#include -#include #include #include #include -#include "MainWindow.h" #include "Audio.h" #include "Camera.h" #include "DatagramProcessor.h" @@ -89,17 +75,19 @@ #include "UndoStackScriptingInterface.h" -class QAction; -class QActionGroup; class QGLWidget; class QKeyEvent; class QMouseEvent; class QSettings; +class QSystemTrayIcon; +class QTouchEvent; class QWheelEvent; class FaceTracker; +class MainWindow; class Node; class ProgramObject; +class ScriptEngine; static const float NODE_ADDED_RED = 0.0f; static const float NODE_ADDED_GREEN = 1.0f; diff --git a/interface/src/GLCanvas.cpp b/interface/src/GLCanvas.cpp index cec3f62b7d..10090de51a 100644 --- a/interface/src/GLCanvas.cpp +++ b/interface/src/GLCanvas.cpp @@ -9,13 +9,13 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#include #include #include #include #include "Application.h" #include "GLCanvas.h" +#include "MainWindow.h" #include "devices/OculusManager.h" const int MSECS_PER_FRAME_WHEN_THROTTLED = 66; diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 6c2c3966fc..14327bd51a 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -32,6 +32,7 @@ #include #include #include +#include #include #include #include diff --git a/interface/src/entities/EntityTreeRenderer.h b/interface/src/entities/EntityTreeRenderer.h index a8695db36d..3d79358536 100644 --- a/interface/src/entities/EntityTreeRenderer.h +++ b/interface/src/entities/EntityTreeRenderer.h @@ -17,6 +17,7 @@ #include #include // for RayToEntityIntersectionResult +#include #include #include #include @@ -27,6 +28,8 @@ #include "renderer/Model.h" +class ScriptEngine; + class EntityScriptDetails { public: QString scriptText; diff --git a/interface/src/scripting/WindowScriptingInterface.cpp b/interface/src/scripting/WindowScriptingInterface.cpp index 591ae87560..d69b1d0ba1 100644 --- a/interface/src/scripting/WindowScriptingInterface.cpp +++ b/interface/src/scripting/WindowScriptingInterface.cpp @@ -17,6 +17,7 @@ #include #include "Application.h" +#include "MainWindow.h" #include "Menu.h" #include "ui/ModelsBrowser.h" diff --git a/interface/src/ui/AddressBarDialog.cpp b/interface/src/ui/AddressBarDialog.cpp index dbc29be71a..3fc915e073 100644 --- a/interface/src/ui/AddressBarDialog.cpp +++ b/interface/src/ui/AddressBarDialog.cpp @@ -12,6 +12,7 @@ #include "AddressBarDialog.h" #include "AddressManager.h" #include "Application.h" +#include "MainWindow.h" const QString ADDRESSBAR_GO_BUTTON_ICON = "images/address-bar-submit.svg"; const QString ADDRESSBAR_GO_BUTTON_ACTIVE_ICON = "images/address-bar-submit-active.svg"; diff --git a/interface/src/ui/AnimationsDialog.cpp b/interface/src/ui/AnimationsDialog.cpp index c5ab826ebb..65e7cadc77 100644 --- a/interface/src/ui/AnimationsDialog.cpp +++ b/interface/src/ui/AnimationsDialog.cpp @@ -22,6 +22,7 @@ #include "AnimationsDialog.h" #include "Application.h" +#include "MainWindow.h" AnimationsDialog::AnimationsDialog() : QDialog(Application::getInstance()->getWindow()) { diff --git a/interface/src/ui/AttachmentsDialog.cpp b/interface/src/ui/AttachmentsDialog.cpp index 44dd2452e6..1209af580d 100644 --- a/interface/src/ui/AttachmentsDialog.cpp +++ b/interface/src/ui/AttachmentsDialog.cpp @@ -20,6 +20,7 @@ #include "Application.h" #include "AttachmentsDialog.h" +#include "MainWindow.h" AttachmentsDialog::AttachmentsDialog() : QDialog(Application::getInstance()->getWindow()) { diff --git a/interface/src/ui/ChatWindow.cpp b/interface/src/ui/ChatWindow.cpp index 747b4ae68d..61ce9f88fc 100644 --- a/interface/src/ui/ChatWindow.cpp +++ b/interface/src/ui/ChatWindow.cpp @@ -16,6 +16,8 @@ #include #include #include +#include "qtimespan.h" + #include #include @@ -23,7 +25,7 @@ #include "Application.h" #include "ChatMessageArea.h" #include "FlowLayout.h" -#include "qtimespan.h" +#include "MainWindow.h" #include "UIUtil.h" #include "XmppClient.h" diff --git a/interface/src/ui/HMDToolsDialog.cpp b/interface/src/ui/HMDToolsDialog.cpp index ab84980d80..23d6d5df2f 100644 --- a/interface/src/ui/HMDToolsDialog.cpp +++ b/interface/src/ui/HMDToolsDialog.cpp @@ -21,6 +21,7 @@ #include +#include "MainWindow.h" #include "Menu.h" #include "devices/OculusManager.h" #include "ui/HMDToolsDialog.h" diff --git a/interface/src/ui/MetavoxelEditor.cpp b/interface/src/ui/MetavoxelEditor.cpp index 97c4c08b41..46f69b0452 100644 --- a/interface/src/ui/MetavoxelEditor.cpp +++ b/interface/src/ui/MetavoxelEditor.cpp @@ -37,6 +37,7 @@ #include #include "Application.h" +#include "MainWindow.h" #include "MetavoxelEditor.h" using namespace std; diff --git a/interface/src/ui/PreferencesDialog.cpp b/interface/src/ui/PreferencesDialog.cpp index 61cc9718b3..318dce977a 100644 --- a/interface/src/ui/PreferencesDialog.cpp +++ b/interface/src/ui/PreferencesDialog.cpp @@ -11,6 +11,7 @@ #include "Application.h" +#include "MainWindow.h" #include "Menu.h" #include "ModelsBrowser.h" #include "PreferencesDialog.h" diff --git a/interface/src/ui/ToolWindow.cpp b/interface/src/ui/ToolWindow.cpp index da1d2c68f4..8774bffc36 100644 --- a/interface/src/ui/ToolWindow.cpp +++ b/interface/src/ui/ToolWindow.cpp @@ -10,6 +10,7 @@ // #include "Application.h" +#include "MainWindow.h" #include "ToolWindow.h" #include "UIUtil.h" From 9b37967bedcfb6b9d714d6a5257b91dfb482c9d0 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 15 Dec 2014 11:23:25 -0800 Subject: [PATCH 088/258] changes to instructions for TBB, remove MSVC2010 --- BUILD_LINUX.md | 2 +- BUILD_WIN.md | 45 +++++++++------------------------------------ 2 files changed, 10 insertions(+), 37 deletions(-) diff --git a/BUILD_LINUX.md b/BUILD_LINUX.md index eb4dcd9255..7b6c8f2176 100644 --- a/BUILD_LINUX.md +++ b/BUILD_LINUX.md @@ -15,4 +15,4 @@ Should you choose not to install Qt5 via a package manager that handles dependen Install Intel TBB from your package manager of choice, or from source (available at the [TBB Website](https://www.threadingbuildingblocks.org/)). -You must run `tbbvars` so that the find module included with this project will be able to find the correct version of TBB. `tbbvars` is located in the 'bin' folder of your TBB install. \ No newline at end of file +You must run `tbbvars` before running cmake that the find module included with this project will be able to find the correct version of TBB. `tbbvars` is located in the 'bin' folder of your TBB install. \ No newline at end of file diff --git a/BUILD_WIN.md b/BUILD_WIN.md index 5685370dc3..4e773e3323 100644 --- a/BUILD_WIN.md +++ b/BUILD_WIN.md @@ -8,39 +8,10 @@ Please read the [general build guide](BUILD.md) for information on dependencies ###Visual Studio Currently building on Windows has been tested using the following compilers: -* Visual Studio C++ 2010 Express * Visual Studio 2013 (If anyone can test using Visual Studio 2013 Express then please update this document) -####Windows SDK 7.1 - -If using Visual Studio 2010, or using Visual Studio 2013 but building as a Visual Studio 2010 project, you need [Microsoft Windows SDK for Windows 7 and .NET Framework 4](http://www.microsoft.com/en-us/download/details.aspx?id=8279). - -NOTE: If using Visual Studio C++ 2010 Express, you need to follow a specific install order. See below before installing the Windows SDK. - -#####Windows SDK 8.1 - -If using Visual Studio 2013 and building as a Visual Studio 2013 project you need the Windows 8 SDK which you should already have as part of installing Visual Studio 2013. You should be able to see it at `C:\Program Files (x86)\Windows Kits\8.1\Lib\winv6.3\um\x86`. - -####Visual Studio C++ 2010 Express - -Visual Studio C++ 2010 Express can be downloaded [here](http://www.visualstudio.com/en-us/downloads#d-2010-express). - -The following patches/service packs are also required: -* [VS2010 SP1](http://www.microsoft.com/en-us/download/details.aspx?id=23691) -* [VS2010 SP1 Compiler Update](http://www.microsoft.com/en-us/download/details.aspx?id=4422) - -IMPORTANT: Use the following install order: -Visual Studio C++ 2010 Express -Windows SDK 7.1 -VS2010 SP1 -VS2010 SP1 Compiler Update - -If you get an error while installing the VS2010 SP1 Compiler update saying that you don't have the Windows SDK installed, then uninstall all of the above and start again in the correct order. - -Some of the build instructions will ask you to start a Visual Studio Command Prompt. You should have a shortcut in your Start menu called "Open Visual Studio Command Prompt (2010)" which will do so. - ####Visual Studio 2013 You can use the Community or Professional editions of Visual Studio 2013. @@ -53,6 +24,10 @@ Or you can start a regular command prompt and then run: If you experience issues building interface on Visual Studio 2013, try generating the build files with Visual Studio 2010 instead. To do so, download Visual Studio 2010 and run `cmake .. -G "Visual Studio 10"` (Assuming running from %HIFI_DIR%\build). +#####Windows SDK 8.1 + +If using Visual Studio 2013 and building as a Visual Studio 2013 project you need the Windows 8 SDK which you should already have as part of installing Visual Studio 2013. You should be able to see it at `C:\Program Files (x86)\Windows Kits\8.1\Lib\winv6.3\um\x86`. + ###Qt You can use the online installer or the offline installer. If you use the offline installer, be sure to select the "OpenGL" version. @@ -60,15 +35,13 @@ NOTE: Qt does not support 64-bit builds on Windows 7, so you must use the 32-bit * Download the online installer [here](http://qt-project.org/downloads) * When it asks you to select components, ONLY select the following: - * Qt > Qt 5.2.0 > **msvc2010 32-bit OpenGL** + * Qt > Qt 5.3.2 > **msvc2013 32-bit OpenGL** -* Download the offline installer [here](http://download.qt-project.org/official_releases/qt/5.2/5.2.0/qt-windows-opensource-5.2.0-msvc2010_opengl-x86-offline.exe) +* Download the offline installer [here](http://download.qt-project.org/official_releases/qt/5.3/5.3.2/qt-opensource-windows-x86-msvc2013_opengl-5.3.2.exe) Once Qt is installed, you need to manually configure the following: -* Make sure the Qt runtime DLLs are loadable. You must do this before you attempt to build because some tools for the build depend on Qt. E.g., add to the PATH: `Qt\5.2.0\msvc2010_opengl\bin\`. -* Set the QT_CMAKE_PREFIX_PATH environment variable to your `Qt\5.2.0\msvc2010_opengl` directory. - -If building as a Visual Studio 2013 project, download and configure the msvc2013 version of Qt instead. +* Make sure the Qt runtime DLLs are loadable. You must do this before you attempt to build because some tools for the build depend on Qt. E.g., add to the PATH: `Qt\5.3.2\msvc2013_opengl\bin\`. +* Set the QT_CMAKE_PREFIX_PATH environment variable to your `Qt\5.3.2\msvc2013_opengl` directory. ###External Libraries @@ -128,7 +101,7 @@ Install OpenSSL into the Windows system directory, to make sure that QT uses the Download the stable release for Windows from the [Intel Threading Building Blocks website](https://www.threadingbuildingblocks.org/). By default, TBB will install to Program Files. You may also choose to install it to %HIFI_LIB_DIR%\TBB. -You must run `tbbvars.bat` so that the find module included with this project will be able to find TBB no matter where you installed it. `tbbvars.bat` is located in the 'bin' folder of your TBB install. For a default installation on a 64-bit architechture, tbbvars can be found at `C:/Program Files (x86)/Intel/TBB/bin/tbbvars.bat`. +You must run `tbbvars.bat` before running cmake so that the find module included with this project will be able to find TBB no matter where you installed it. `tbbvars.bat` is located in the 'bin' folder of your TBB install. For a default installation on a 64-bit architechture, tbbvars can be found at `C:/Program Files (x86)/Intel/TBB/bin/tbbvars.bat`. ###Zlib From ee919643000130e573ed921a9f9c15f576687497 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 15 Dec 2014 11:25:17 -0800 Subject: [PATCH 089/258] clarify that TBB can be installed wherever --- BUILD_WIN.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BUILD_WIN.md b/BUILD_WIN.md index 4e773e3323..e84b2ad811 100644 --- a/BUILD_WIN.md +++ b/BUILD_WIN.md @@ -99,7 +99,7 @@ Install OpenSSL into the Windows system directory, to make sure that QT uses the ###Intel Threading Building Blocks (TBB) -Download the stable release for Windows from the [Intel Threading Building Blocks website](https://www.threadingbuildingblocks.org/). By default, TBB will install to Program Files. You may also choose to install it to %HIFI_LIB_DIR%\TBB. +Download the stable release for Windows from the [Intel Threading Building Blocks website](https://www.threadingbuildingblocks.org/). By default, TBB will install to Program Files. You can choose to install it wherever you like, including %HIFI_LIB_DIR%. You must run `tbbvars.bat` before running cmake so that the find module included with this project will be able to find TBB no matter where you installed it. `tbbvars.bat` is located in the 'bin' folder of your TBB install. For a default installation on a 64-bit architechture, tbbvars can be found at `C:/Program Files (x86)/Intel/TBB/bin/tbbvars.bat`. From 36f23fe4be78ad51a0fd41758ca8b9a9dac07501 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 15 Dec 2014 11:26:06 -0800 Subject: [PATCH 090/258] fix Qt path in Generating build files --- BUILD.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BUILD.md b/BUILD.md index 0a897aa193..0fdb822f25 100644 --- a/BUILD.md +++ b/BUILD.md @@ -38,7 +38,7 @@ Any variables that need to be set for CMake to find dependencies can be set as E For example, to pass the QT_CMAKE_PREFIX_PATH variable during build file generation: - cmake .. -DQT_CMAKE_PREFIX_PATH=/usr/local/qt/5.2.1/lib/cmake + cmake .. -DQT_CMAKE_PREFIX_PATH=/usr/local/qt/5.3.2/lib/cmake ####Finding Dependencies You can point our [Cmake find modules](cmake/modules/) to the correct version of dependencies by setting one of the three following variables to the location of the correct version of the dependency. From aac44953cbf0b3db0eb36509ccbcd17633f22369 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 15 Dec 2014 11:27:31 -0800 Subject: [PATCH 091/258] fix generator passed to cmake for windows build --- BUILD_WIN.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/BUILD_WIN.md b/BUILD_WIN.md index e84b2ad811..030c2f92a8 100644 --- a/BUILD_WIN.md +++ b/BUILD_WIN.md @@ -138,9 +138,7 @@ Be careful with glm. For the folder other libraries would normally call 'include ###Build High Fidelity using Visual Studio Follow the same build steps from the CMake section, but pass a different generator to CMake. - cmake .. -DZLIB_LIBRARY=%ZLIB_LIBRARY% -DZLIB_INCLUDE_DIR=%ZLIB_INCLUDE_DIR% -G "Visual Studio 10" - -If you're using Visual Studio 2013 then pass "Visual Studio 12" instead of "Visual Studio 10" (yes, 12, not 13). + cmake .. -DZLIB_LIBRARY=%ZLIB_LIBRARY% -DZLIB_INCLUDE_DIR=%ZLIB_INCLUDE_DIR% -G "Visual Studio 12" Open %HIFI_DIR%\build\hifi.sln and compile. From ea08d7bb2300560da764e1c53d6c659a5a775ccd Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 15 Dec 2014 11:28:43 -0800 Subject: [PATCH 092/258] remove block recommending VS2010 project file --- BUILD_WIN.md | 2 -- 1 file changed, 2 deletions(-) diff --git a/BUILD_WIN.md b/BUILD_WIN.md index 030c2f92a8..bf7d421715 100644 --- a/BUILD_WIN.md +++ b/BUILD_WIN.md @@ -22,8 +22,6 @@ Or you can start a regular command prompt and then run: "%VS120COMNTOOLS%\vsvars32.bat" -If you experience issues building interface on Visual Studio 2013, try generating the build files with Visual Studio 2010 instead. To do so, download Visual Studio 2010 and run `cmake .. -G "Visual Studio 10"` (Assuming running from %HIFI_DIR%\build). - #####Windows SDK 8.1 If using Visual Studio 2013 and building as a Visual Studio 2013 project you need the Windows 8 SDK which you should already have as part of installing Visual Studio 2013. You should be able to see it at `C:\Program Files (x86)\Windows Kits\8.1\Lib\winv6.3\um\x86`. From 90c1132dd553bb10e221cdb569efc005ca975f42 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 11:28:57 -0800 Subject: [PATCH 093/258] reduce calls to DependencyManager::get<> where possible --- interface/src/Util.cpp | 9 +++++---- interface/src/avatar/SkeletonModel.cpp | 18 +++++++++++------- .../src/renderer/DeferredLightingEffect.cpp | 8 +++++--- 3 files changed, 21 insertions(+), 14 deletions(-) diff --git a/interface/src/Util.cpp b/interface/src/Util.cpp index d93c8a26ad..6d40726f14 100644 --- a/interface/src/Util.cpp +++ b/interface/src/Util.cpp @@ -71,22 +71,23 @@ void renderWorldBox() { glPushMatrix(); glTranslatef(MARKER_DISTANCE, 0, 0); glColor3fv(red); - DependencyManager::get()->renderSphere(MARKER_RADIUS, 10, 10); + GeometryCache* geometryCache = DependencyManager::get(); + geometryCache->renderSphere(MARKER_RADIUS, 10, 10); glPopMatrix(); glPushMatrix(); glTranslatef(0, MARKER_DISTANCE, 0); glColor3fv(green); - DependencyManager::get()->renderSphere(MARKER_RADIUS, 10, 10); + geometryCache->renderSphere(MARKER_RADIUS, 10, 10); glPopMatrix(); glPushMatrix(); glTranslatef(0, 0, MARKER_DISTANCE); glColor3fv(blue); - DependencyManager::get()->renderSphere(MARKER_RADIUS, 10, 10); + geometryCache->renderSphere(MARKER_RADIUS, 10, 10); glPopMatrix(); glPushMatrix(); glColor3fv(gray); glTranslatef(MARKER_DISTANCE, 0, MARKER_DISTANCE); - DependencyManager::get()->renderSphere(MARKER_RADIUS, 10, 10); + geometryCache->renderSphere(MARKER_RADIUS, 10, 10); glPopMatrix(); } diff --git a/interface/src/avatar/SkeletonModel.cpp b/interface/src/avatar/SkeletonModel.cpp index f71c9318aa..42c74db143 100644 --- a/interface/src/avatar/SkeletonModel.cpp +++ b/interface/src/avatar/SkeletonModel.cpp @@ -554,6 +554,7 @@ void SkeletonModel::renderRagdoll() { float radius1 = 0.008f; float radius2 = 0.01f; glm::vec3 simulationTranslation = _ragdoll->getTranslationInSimulationFrame(); + GeometryCache* geometryCache = DependencyManager::get(); for (int i = 0; i < numPoints; ++i) { glPushMatrix(); // NOTE: ragdollPoints are in simulation-frame but we want them to be model-relative @@ -561,9 +562,9 @@ void SkeletonModel::renderRagdoll() { glTranslatef(position.x, position.y, position.z); // draw each point as a yellow hexagon with black border glColor4f(0.0f, 0.0f, 0.0f, alpha); - DependencyManager::get()->renderSphere(radius2, BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); + geometryCache->renderSphere(radius2, BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); glColor4f(1.0f, 1.0f, 0.0f, alpha); - DependencyManager::get()->renderSphere(radius1, BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); + geometryCache->renderSphere(radius1, BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); glPopMatrix(); } glPopMatrix(); @@ -913,7 +914,8 @@ void SkeletonModel::renderBoundingCollisionShapes(float alpha) { endPoint = endPoint - _translation; glTranslatef(endPoint.x, endPoint.y, endPoint.z); glColor4f(0.6f, 0.6f, 0.8f, alpha); - DependencyManager::get()->renderSphere(_boundingShape.getRadius(), BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); + GeometryCache* geometryCache = DependencyManager::get(); + geometryCache->renderSphere(_boundingShape.getRadius(), BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); // draw a yellow sphere at the capsule startpoint glm::vec3 startPoint; @@ -922,7 +924,7 @@ void SkeletonModel::renderBoundingCollisionShapes(float alpha) { glm::vec3 axis = endPoint - startPoint; glTranslatef(-axis.x, -axis.y, -axis.z); glColor4f(0.8f, 0.8f, 0.6f, alpha); - DependencyManager::get()->renderSphere(_boundingShape.getRadius(), BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); + geometryCache->renderSphere(_boundingShape.getRadius(), BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); // draw a green cylinder between the two points glm::vec3 origin(0.0f); @@ -948,6 +950,8 @@ void SkeletonModel::renderJointCollisionShapes(float alpha) { continue; } + GeometryCache* geometryCache = DependencyManager::get(); + glPushMatrix(); // shapes are stored in simulation-frame but we want position to be model-relative if (shape->getType() == SPHERE_SHAPE) { @@ -955,7 +959,7 @@ void SkeletonModel::renderJointCollisionShapes(float alpha) { glTranslatef(position.x, position.y, position.z); // draw a grey sphere at shape position glColor4f(0.75f, 0.75f, 0.75f, alpha); - DependencyManager::get()->renderSphere(shape->getBoundingRadius(), BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); + geometryCache->renderSphere(shape->getBoundingRadius(), BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); } else if (shape->getType() == CAPSULE_SHAPE) { CapsuleShape* capsule = static_cast(shape); @@ -965,7 +969,7 @@ void SkeletonModel::renderJointCollisionShapes(float alpha) { endPoint = endPoint - simulationTranslation; glTranslatef(endPoint.x, endPoint.y, endPoint.z); glColor4f(0.6f, 0.6f, 0.8f, alpha); - DependencyManager::get()->renderSphere(capsule->getRadius(), BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); + geometryCache->renderSphere(capsule->getRadius(), BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); // draw a yellow sphere at the capsule startpoint glm::vec3 startPoint; @@ -974,7 +978,7 @@ void SkeletonModel::renderJointCollisionShapes(float alpha) { glm::vec3 axis = endPoint - startPoint; glTranslatef(-axis.x, -axis.y, -axis.z); glColor4f(0.8f, 0.8f, 0.6f, alpha); - DependencyManager::get()->renderSphere(capsule->getRadius(), BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); + geometryCache->renderSphere(capsule->getRadius(), BALL_SUBDIVISIONS, BALL_SUBDIVISIONS); // draw a green cylinder between the two points glm::vec3 origin(0.0f); diff --git a/interface/src/renderer/DeferredLightingEffect.cpp b/interface/src/renderer/DeferredLightingEffect.cpp index 75af4647e4..e40193c8c3 100644 --- a/interface/src/renderer/DeferredLightingEffect.cpp +++ b/interface/src/renderer/DeferredLightingEffect.cpp @@ -234,6 +234,8 @@ void DeferredLightingEffect::render() { const glm::vec3& eyePoint = Application::getInstance()->getDisplayViewFrustum()->getPosition(); float nearRadius = glm::distance(eyePoint, Application::getInstance()->getDisplayViewFrustum()->getNearTopLeft()); + + GeometryCache* geometryCache = DependencyManager::get(); if (!_pointLights.isEmpty()) { _pointLight.bind(); @@ -241,7 +243,7 @@ void DeferredLightingEffect::render() { _pointLight.setUniformValue(_pointLightLocations.depthScale, depthScale); _pointLight.setUniformValue(_pointLightLocations.depthTexCoordOffset, depthTexCoordOffsetS, depthTexCoordOffsetT); _pointLight.setUniformValue(_pointLightLocations.depthTexCoordScale, depthTexCoordScaleS, depthTexCoordScaleT); - + foreach (const PointLight& light, _pointLights) { _pointLight.setUniformValue(_pointLightLocations.radius, light.radius); glLightfv(GL_LIGHT1, GL_AMBIENT, (const GLfloat*)&light.ambient); @@ -270,7 +272,7 @@ void DeferredLightingEffect::render() { } else { glTranslatef(light.position.x, light.position.y, light.position.z); - DependencyManager::get()->renderSphere(expandedRadius, 32, 32); + geometryCache->renderSphere(expandedRadius, 32, 32); } glPopMatrix(); @@ -323,7 +325,7 @@ void DeferredLightingEffect::render() { glm::vec3 axis = glm::axis(spotRotation); glRotatef(glm::degrees(glm::angle(spotRotation)), axis.x, axis.y, axis.z); glTranslatef(0.0f, 0.0f, -light.radius * (1.0f + SCALE_EXPANSION * 0.5f)); - DependencyManager::get()->renderCone(expandedRadius * glm::tan(light.cutoff), + geometryCache->renderCone(expandedRadius * glm::tan(light.cutoff), expandedRadius, 32, 1); } From c18c45a40152f5dd326a78323c8dfe7b1577dffb Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 15 Dec 2014 11:30:17 -0800 Subject: [PATCH 094/258] bump glm dependency version --- BUILD.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BUILD.md b/BUILD.md index 0fdb822f25..6613786903 100644 --- a/BUILD.md +++ b/BUILD.md @@ -2,7 +2,7 @@ * [cmake](http://www.cmake.org/cmake/resources/software.html) ~> 2.8.12.2 * [Qt](http://qt-project.org/downloads) ~> 5.3.0 -* [glm](http://glm.g-truc.net/0.9.5/index.html) ~> 0.9.5.2 +* [glm](http://glm.g-truc.net/0.9.5/index.html) ~> 0.9.5.4 * [OpenSSL](https://www.openssl.org/related/binaries.html) ~> 1.0.1g * IMPORTANT: OpenSSL 1.0.1g is critical to avoid a security vulnerability. * [Intel Threading Building Blocks](https://www.threadingbuildingblocks.org/) ~> 4.3 From 3bc132154906013d13e9f4e90e069afa68d738a0 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 11:40:17 -0800 Subject: [PATCH 095/258] reduce calls to DependencyManager::get<> where possible --- interface/src/MetavoxelSystem.cpp | 6 ++++-- .../src/renderer/DeferredLightingEffect.cpp | 21 +++++++++++-------- interface/src/renderer/GeometryCache.cpp | 19 ++++++++++------- interface/src/renderer/GlowEffect.cpp | 9 ++++---- interface/src/renderer/Model.cpp | 11 +++++----- 5 files changed, 38 insertions(+), 28 deletions(-) diff --git a/interface/src/MetavoxelSystem.cpp b/interface/src/MetavoxelSystem.cpp index a61f6e41d7..84ccf0f406 100644 --- a/interface/src/MetavoxelSystem.cpp +++ b/interface/src/MetavoxelSystem.cpp @@ -1177,10 +1177,11 @@ void VoxelBuffer::render(bool cursor) { if (!_materials.isEmpty()) { _networkTextures.resize(_materials.size()); + TextureCache* textureCache = DependencyManager::get(); for (int i = 0; i < _materials.size(); i++) { const SharedObjectPointer material = _materials.at(i); if (material) { - _networkTextures[i] = DependencyManager::get()->getTexture( + _networkTextures[i] = textureCache->getTexture( static_cast(material.data())->getDiffuse(), SPLAT_TEXTURE); } } @@ -2231,10 +2232,11 @@ void HeightfieldNodeRenderer::render(const HeightfieldNodePointer& node, const g const QVector& materials = node->getMaterial()->getMaterials(); _networkTextures.resize(materials.size()); + TextureCache* textureCache = DependencyManager::get(); for (int i = 0; i < materials.size(); i++) { const SharedObjectPointer& material = materials.at(i); if (material) { - _networkTextures[i] = DependencyManager::get()->getTexture( + _networkTextures[i] = textureCache->getTexture( static_cast(material.data())->getDiffuse(), SPLAT_TEXTURE); } } diff --git a/interface/src/renderer/DeferredLightingEffect.cpp b/interface/src/renderer/DeferredLightingEffect.cpp index e40193c8c3..22ac5d82b6 100644 --- a/interface/src/renderer/DeferredLightingEffect.cpp +++ b/interface/src/renderer/DeferredLightingEffect.cpp @@ -117,15 +117,16 @@ void DeferredLightingEffect::addSpotLight(const glm::vec3& position, float radiu void DeferredLightingEffect::prepare() { // clear the normal and specular buffers - DependencyManager::get()->setPrimaryDrawBuffers(false, true, false); + TextureCache* textureCache = DependencyManager::get(); + textureCache->setPrimaryDrawBuffers(false, true, false); glClear(GL_COLOR_BUFFER_BIT); - DependencyManager::get()->setPrimaryDrawBuffers(false, false, true); + textureCache->setPrimaryDrawBuffers(false, false, true); // clearing to zero alpha for specular causes problems on my Nvidia card; clear to lowest non-zero value instead const float MAX_SPECULAR_EXPONENT = 128.0f; glClearColor(0.0f, 0.0f, 0.0f, 1.0f / MAX_SPECULAR_EXPONENT); glClear(GL_COLOR_BUFFER_BIT); glClearColor(0.0f, 0.0f, 0.0f, 0.0f); - DependencyManager::get()->setPrimaryDrawBuffers(true, false, false); + textureCache->setPrimaryDrawBuffers(true, false, false); } void DeferredLightingEffect::render() { @@ -137,8 +138,10 @@ void DeferredLightingEffect::render() { glDisable(GL_DEPTH_TEST); glDisable(GL_COLOR_MATERIAL); glDepthMask(false); + + TextureCache* textureCache = DependencyManager::get(); - QOpenGLFramebufferObject* primaryFBO = DependencyManager::get()->getPrimaryFramebufferObject(); + QOpenGLFramebufferObject* primaryFBO = textureCache->getPrimaryFramebufferObject(); primaryFBO->release(); QOpenGLFramebufferObject* freeFBO = Application::getInstance()->getGlowEffect()->getFreeFramebufferObject(); @@ -148,13 +151,13 @@ void DeferredLightingEffect::render() { glBindTexture(GL_TEXTURE_2D, primaryFBO->texture()); glActiveTexture(GL_TEXTURE1); - glBindTexture(GL_TEXTURE_2D, DependencyManager::get()->getPrimaryNormalTextureID()); + glBindTexture(GL_TEXTURE_2D, textureCache->getPrimaryNormalTextureID()); glActiveTexture(GL_TEXTURE2); - glBindTexture(GL_TEXTURE_2D, DependencyManager::get()->getPrimarySpecularTextureID()); + glBindTexture(GL_TEXTURE_2D, textureCache->getPrimarySpecularTextureID()); glActiveTexture(GL_TEXTURE3); - glBindTexture(GL_TEXTURE_2D, DependencyManager::get()->getPrimaryDepthTextureID()); + glBindTexture(GL_TEXTURE_2D, textureCache->getPrimaryDepthTextureID()); // get the viewport side (left, right, both) int viewport[4]; @@ -173,7 +176,7 @@ void DeferredLightingEffect::render() { bool shadowsEnabled = Menu::getInstance()->getShadowsEnabled(); if (shadowsEnabled) { glActiveTexture(GL_TEXTURE4); - glBindTexture(GL_TEXTURE_2D, DependencyManager::get()->getShadowDepthTextureID()); + glBindTexture(GL_TEXTURE_2D, textureCache->getShadowDepthTextureID()); program = &_directionalLightShadowMap; locations = &_directionalLightShadowMapLocations; @@ -188,7 +191,7 @@ void DeferredLightingEffect::render() { program->bind(); } program->setUniformValue(locations->shadowScale, - 1.0f / DependencyManager::get()->getShadowFramebufferObject()->width()); + 1.0f / textureCache->getShadowFramebufferObject()->width()); } else { program->bind(); diff --git a/interface/src/renderer/GeometryCache.cpp b/interface/src/renderer/GeometryCache.cpp index 534911ff46..974a542b0e 100644 --- a/interface/src/renderer/GeometryCache.cpp +++ b/interface/src/renderer/GeometryCache.cpp @@ -699,6 +699,7 @@ void NetworkGeometry::clearLoadPriority(const QPointer& owner) { void NetworkGeometry::setTextureWithNameToURL(const QString& name, const QUrl& url) { if (_meshes.size() > 0) { + TextureCache* textureCache = DependencyManager::get(); for (int i = 0; i < _meshes.size(); i++) { NetworkMesh& mesh = _meshes[i]; for (int j = 0; j < mesh.parts.size(); j++) { @@ -707,19 +708,19 @@ void NetworkGeometry::setTextureWithNameToURL(const QString& name, const QUrl& u QSharedPointer matchingTexture = QSharedPointer(); if (part.diffuseTextureName == name) { part.diffuseTexture = - DependencyManager::get()->getTexture(url, DEFAULT_TEXTURE, + textureCache->getTexture(url, DEFAULT_TEXTURE, _geometry.meshes[i].isEye, QByteArray()); part.diffuseTexture->setLoadPriorities(_loadPriorities); } else if (part.normalTextureName == name) { - part.normalTexture = DependencyManager::get()->getTexture(url, DEFAULT_TEXTURE, + part.normalTexture = textureCache->getTexture(url, DEFAULT_TEXTURE, false, QByteArray()); part.normalTexture->setLoadPriorities(_loadPriorities); } else if (part.specularTextureName == name) { - part.specularTexture = DependencyManager::get()->getTexture(url, DEFAULT_TEXTURE, + part.specularTexture = textureCache->getTexture(url, DEFAULT_TEXTURE, false, QByteArray()); part.specularTexture->setLoadPriorities(_loadPriorities); } else if (part.emissiveTextureName == name) { - part.emissiveTexture = DependencyManager::get()->getTexture(url, DEFAULT_TEXTURE, + part.emissiveTexture = textureCache->getTexture(url, DEFAULT_TEXTURE, false, QByteArray()); part.emissiveTexture->setLoadPriorities(_loadPriorities); } @@ -912,6 +913,8 @@ void NetworkGeometry::reinsert() { void NetworkGeometry::setGeometry(const FBXGeometry& geometry) { _geometry = geometry; + + TextureCache* textureCache = DependencyManager::get(); foreach (const FBXMesh& mesh, _geometry.meshes) { NetworkMesh networkMesh; @@ -920,28 +923,28 @@ void NetworkGeometry::setGeometry(const FBXGeometry& geometry) { foreach (const FBXMeshPart& part, mesh.parts) { NetworkMeshPart networkPart; if (!part.diffuseTexture.filename.isEmpty()) { - networkPart.diffuseTexture = DependencyManager::get()->getTexture( + networkPart.diffuseTexture = textureCache->getTexture( _textureBase.resolved(QUrl(part.diffuseTexture.filename)), DEFAULT_TEXTURE, mesh.isEye, part.diffuseTexture.content); networkPart.diffuseTextureName = part.diffuseTexture.name; networkPart.diffuseTexture->setLoadPriorities(_loadPriorities); } if (!part.normalTexture.filename.isEmpty()) { - networkPart.normalTexture = DependencyManager::get()->getTexture( + networkPart.normalTexture = textureCache->getTexture( _textureBase.resolved(QUrl(part.normalTexture.filename)), NORMAL_TEXTURE, false, part.normalTexture.content); networkPart.normalTextureName = part.normalTexture.name; networkPart.normalTexture->setLoadPriorities(_loadPriorities); } if (!part.specularTexture.filename.isEmpty()) { - networkPart.specularTexture = DependencyManager::get()->getTexture( + networkPart.specularTexture = textureCache->getTexture( _textureBase.resolved(QUrl(part.specularTexture.filename)), SPECULAR_TEXTURE, false, part.specularTexture.content); networkPart.specularTextureName = part.specularTexture.name; networkPart.specularTexture->setLoadPriorities(_loadPriorities); } if (!part.emissiveTexture.filename.isEmpty()) { - networkPart.emissiveTexture = DependencyManager::get()->getTexture( + networkPart.emissiveTexture = textureCache->getTexture( _textureBase.resolved(QUrl(part.emissiveTexture.filename)), EMISSIVE_TEXTURE, false, part.emissiveTexture.content); networkPart.emissiveTextureName = part.emissiveTexture.name; diff --git a/interface/src/renderer/GlowEffect.cpp b/interface/src/renderer/GlowEffect.cpp index e6bbdb2ba1..b6896eeaad 100644 --- a/interface/src/renderer/GlowEffect.cpp +++ b/interface/src/renderer/GlowEffect.cpp @@ -122,7 +122,8 @@ static void maybeRelease(QOpenGLFramebufferObject* fbo) { QOpenGLFramebufferObject* GlowEffect::render(bool toTexture) { PerformanceTimer perfTimer("glowEffect"); - QOpenGLFramebufferObject* primaryFBO = DependencyManager::get()->getPrimaryFramebufferObject(); + TextureCache* textureCache = DependencyManager::get(); + QOpenGLFramebufferObject* primaryFBO = textureCache->getPrimaryFramebufferObject(); primaryFBO->release(); glBindTexture(GL_TEXTURE_2D, primaryFBO->texture()); @@ -138,7 +139,7 @@ QOpenGLFramebufferObject* GlowEffect::render(bool toTexture) { glDepthMask(GL_FALSE); QOpenGLFramebufferObject* destFBO = toTexture ? - DependencyManager::get()->getSecondaryFramebufferObject() : NULL; + textureCache->getSecondaryFramebufferObject() : NULL; if (!Menu::getInstance()->isOptionChecked(MenuOption::EnableGlowEffect) || _isEmpty) { // copy the primary to the screen if (destFBO && QOpenGLFramebufferObject::hasOpenGLFramebufferBlit()) { @@ -160,9 +161,9 @@ QOpenGLFramebufferObject* GlowEffect::render(bool toTexture) { } else { // diffuse into the secondary/tertiary (alternating between frames) QOpenGLFramebufferObject* oldDiffusedFBO = - DependencyManager::get()->getSecondaryFramebufferObject(); + textureCache->getSecondaryFramebufferObject(); QOpenGLFramebufferObject* newDiffusedFBO = - DependencyManager::get()->getTertiaryFramebufferObject(); + textureCache->getTertiaryFramebufferObject(); if (_isOddFrame) { qSwap(oldDiffusedFBO, newDiffusedFBO); } diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index 62170efeed..2a6988a984 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -2324,7 +2324,8 @@ int Model::renderMeshesFromList(QVector& list, gpu::Batch& batch, RenderMod bool dontCullOutOfViewMeshParts = Menu::getInstance()->isOptionChecked(MenuOption::DontCullOutOfViewMeshParts); bool cullTooSmallMeshParts = !Menu::getInstance()->isOptionChecked(MenuOption::DontCullTooSmallMeshParts); bool dontReduceMaterialSwitches = Menu::getInstance()->isOptionChecked(MenuOption::DontReduceMaterialSwitches); - + + TextureCache* textureCache = DependencyManager::get(); QString lastMaterialID; int meshPartsRendered = 0; updateVisibleJointStates(); @@ -2446,7 +2447,7 @@ int Model::renderMeshesFromList(QVector& list, gpu::Batch& batch, RenderMod if (showDiffuse && diffuseMap) { GLBATCH(glBindTexture)(GL_TEXTURE_2D, diffuseMap->getID()); } else { - GLBATCH(glBindTexture)(GL_TEXTURE_2D, DependencyManager::get()->getWhiteTextureID()); + GLBATCH(glBindTexture)(GL_TEXTURE_2D, textureCache->getWhiteTextureID()); } if (locations->texcoordMatrices >= 0) { @@ -2464,7 +2465,7 @@ int Model::renderMeshesFromList(QVector& list, gpu::Batch& batch, RenderMod GLBATCH(glActiveTexture)(GL_TEXTURE1); Texture* normalMap = networkPart.normalTexture.data(); GLBATCH(glBindTexture)(GL_TEXTURE_2D, !normalMap ? - DependencyManager::get()->getBlueTextureID() : normalMap->getID()); + textureCache->getBlueTextureID() : normalMap->getID()); GLBATCH(glActiveTexture)(GL_TEXTURE0); } @@ -2472,7 +2473,7 @@ int Model::renderMeshesFromList(QVector& list, gpu::Batch& batch, RenderMod GLBATCH(glActiveTexture)(GL_TEXTURE0 + locations->specularTextureUnit); Texture* specularMap = networkPart.specularTexture.data(); GLBATCH(glBindTexture)(GL_TEXTURE_2D, !specularMap ? - DependencyManager::get()->getWhiteTextureID() : specularMap->getID()); + textureCache->getWhiteTextureID() : specularMap->getID()); GLBATCH(glActiveTexture)(GL_TEXTURE0); } @@ -2493,7 +2494,7 @@ int Model::renderMeshesFromList(QVector& list, gpu::Batch& batch, RenderMod GLBATCH(glActiveTexture)(GL_TEXTURE0 + locations->emissiveTextureUnit); Texture* emissiveMap = networkPart.emissiveTexture.data(); GLBATCH(glBindTexture)(GL_TEXTURE_2D, !emissiveMap ? - DependencyManager::get()->getWhiteTextureID() : emissiveMap->getID()); + textureCache->getWhiteTextureID() : emissiveMap->getID()); GLBATCH(glActiveTexture)(GL_TEXTURE0); } From 94cf8b33841a6a9ffbaaf9b973d1bb803626600c Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 11:43:30 -0800 Subject: [PATCH 096/258] reduce calls to DependencyManager::get<> where possible --- interface/src/ModelUploader.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/interface/src/ModelUploader.cpp b/interface/src/ModelUploader.cpp index b22457f847..6f582d60eb 100644 --- a/interface/src/ModelUploader.cpp +++ b/interface/src/ModelUploader.cpp @@ -466,17 +466,19 @@ void ModelUploader::processCheck() { _timer.stop(); switch (reply->error()) { - case QNetworkReply::NoError: + case QNetworkReply::NoError: { QMessageBox::information(NULL, QString("ModelUploader::processCheck()"), QString("Your model is now available in the browser."), QMessageBox::Ok); DependencyManager::get()->refresh(_url); + TextureCache* textureCache = DependencyManager::get(); foreach (const QByteArray& filename, _textureFilenames) { - DependencyManager::get()->refresh(_textureBase + filename); + textureCache->refresh(_textureBase + filename); } deleteLater(); break; + } case QNetworkReply::ContentNotFoundError: if (--_numberOfChecks) { _timer.start(TIMEOUT); From 28f2dc62ea20806b99d2a172148ee75091b7f459 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 11:49:01 -0800 Subject: [PATCH 097/258] add windowshacks.h to GPUConfig.h and move it to shared --- libraries/gpu/src/gpu/GPUConfig.h | 1 + {interface => libraries/shared}/src/windowshacks.h | 0 2 files changed, 1 insertion(+) rename {interface => libraries/shared}/src/windowshacks.h (100%) diff --git a/libraries/gpu/src/gpu/GPUConfig.h b/libraries/gpu/src/gpu/GPUConfig.h index 393a476182..c399f51b66 100644 --- a/libraries/gpu/src/gpu/GPUConfig.h +++ b/libraries/gpu/src/gpu/GPUConfig.h @@ -19,6 +19,7 @@ #include #elif defined(WIN32) +#include #include #include diff --git a/interface/src/windowshacks.h b/libraries/shared/src/windowshacks.h similarity index 100% rename from interface/src/windowshacks.h rename to libraries/shared/src/windowshacks.h From fa8b7020b0ed48556a8cbc2100599c8326903e08 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 15 Dec 2014 11:48:24 -0800 Subject: [PATCH 098/258] repairs to MetavoxelSystem after reset to upstream --- interface/src/MetavoxelSystem.cpp | 349 +++++++++++++++--------------- 1 file changed, 175 insertions(+), 174 deletions(-) diff --git a/interface/src/MetavoxelSystem.cpp b/interface/src/MetavoxelSystem.cpp index c047b8591b..b15ea0b488 100644 --- a/interface/src/MetavoxelSystem.cpp +++ b/interface/src/MetavoxelSystem.cpp @@ -40,13 +40,13 @@ REGISTER_META_OBJECT(StaticModelRenderer) REGISTER_META_OBJECT(HeightfieldRenderer) MetavoxelSystem::NetworkSimulation::NetworkSimulation(float dropRate, float repeatRate, - int minimumDelay, int maximumDelay, int bandwidthLimit) : -dropRate(dropRate), -repeatRate(repeatRate), -minimumDelay(minimumDelay), -maximumDelay(maximumDelay), -bandwidthLimit(bandwidthLimit) { -} + int minimumDelay, int maximumDelay, int bandwidthLimit) : + dropRate(dropRate), + repeatRate(repeatRate), + minimumDelay(minimumDelay), + maximumDelay(maximumDelay), + bandwidthLimit(bandwidthLimit) { +} MetavoxelSystem::~MetavoxelSystem() { // kill the updater before we delete our network simulation objects @@ -59,14 +59,14 @@ void MetavoxelSystem::init() { MetavoxelClientManager::init(); _voxelBufferAttribute = AttributeRegistry::getInstance()->registerAttribute( - new BufferDataAttribute("voxelBuffer")); + new BufferDataAttribute("voxelBuffer")); _voxelBufferAttribute->setLODThresholdMultiplier( - AttributeRegistry::getInstance()->getVoxelColorAttribute()->getLODThresholdMultiplier()); - + AttributeRegistry::getInstance()->getVoxelColorAttribute()->getLODThresholdMultiplier()); + _baseHeightfieldProgram.addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + - "shaders/metavoxel_heightfield_base.vert"); + "shaders/metavoxel_heightfield_base.vert"); _baseHeightfieldProgram.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + - "shaders/metavoxel_heightfield_base.frag"); + "shaders/metavoxel_heightfield_base.frag"); _baseHeightfieldProgram.link(); _baseHeightfieldProgram.bind(); @@ -79,9 +79,9 @@ void MetavoxelSystem::init() { loadSplatProgram("heightfield", _splatHeightfieldProgram, _splatHeightfieldLocations); _heightfieldCursorProgram.addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + - "shaders/metavoxel_heightfield_cursor.vert"); + "shaders/metavoxel_heightfield_cursor.vert"); _heightfieldCursorProgram.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + - "shaders/metavoxel_cursor.frag"); + "shaders/metavoxel_cursor.frag"); _heightfieldCursorProgram.link(); _heightfieldCursorProgram.bind(); @@ -89,17 +89,17 @@ void MetavoxelSystem::init() { _heightfieldCursorProgram.release(); _baseVoxelProgram.addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + - "shaders/metavoxel_voxel_base.vert"); + "shaders/metavoxel_voxel_base.vert"); _baseVoxelProgram.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + - "shaders/metavoxel_voxel_base.frag"); + "shaders/metavoxel_voxel_base.frag"); _baseVoxelProgram.link(); loadSplatProgram("voxel", _splatVoxelProgram, _splatVoxelLocations); _voxelCursorProgram.addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + - "shaders/metavoxel_voxel_cursor.vert"); + "shaders/metavoxel_voxel_cursor.vert"); _voxelCursorProgram.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + - "shaders/metavoxel_cursor.frag"); + "shaders/metavoxel_cursor.frag"); _voxelCursorProgram.link(); } @@ -124,16 +124,16 @@ public: SimulateVisitor(float deltaTime, const MetavoxelLOD& lod); virtual int visit(MetavoxelInfo& info); - + private: float _deltaTime; }; SimulateVisitor::SimulateVisitor(float deltaTime, const MetavoxelLOD& lod) : -MetavoxelVisitor(QVector() << AttributeRegistry::getInstance()->getRendererAttribute(), - QVector(), lod), -_deltaTime(deltaTime) { + MetavoxelVisitor(QVector() << AttributeRegistry::getInstance()->getRendererAttribute(), + QVector(), lod), + _deltaTime(deltaTime) { } int SimulateVisitor::visit(MetavoxelInfo& info) { @@ -141,7 +141,7 @@ int SimulateVisitor::visit(MetavoxelInfo& info) { return DEFAULT_ORDER; } static_cast(info.inputValues.at(0).getInlineValue< - SharedObjectPointer>().data())->getImplementation()->simulate(*_data, _deltaTime, info, _lod); + SharedObjectPointer>().data())->getImplementation()->simulate(*_data, _deltaTime, info, _lod); return STOP_RECURSION; } @@ -152,7 +152,7 @@ void MetavoxelSystem::simulate(float deltaTime) { const float DEFAULT_LOD_THRESHOLD = 0.01f; _lod = MetavoxelLOD(Application::getInstance()->getCamera()->getPosition(), DEFAULT_LOD_THRESHOLD); } - + SimulateVisitor simulateVisitor(deltaTime, getLOD()); guideToAugmented(simulateVisitor); } @@ -166,8 +166,8 @@ public: }; RenderVisitor::RenderVisitor(const MetavoxelLOD& lod) : -MetavoxelVisitor(QVector() << AttributeRegistry::getInstance()->getRendererAttribute(), - QVector(), lod) { + MetavoxelVisitor(QVector() << AttributeRegistry::getInstance()->getRendererAttribute(), + QVector(), lod) { } int RenderVisitor::visit(MetavoxelInfo& info) { @@ -175,7 +175,7 @@ int RenderVisitor::visit(MetavoxelInfo& info) { return DEFAULT_ORDER; } static_cast(info.inputValues.at(0).getInlineValue< - SharedObjectPointer>().data())->getImplementation()->render(*_data, info, _lod); + SharedObjectPointer>().data())->getImplementation()->render(*_data, info, _lod); return STOP_RECURSION; } @@ -195,18 +195,18 @@ void MetavoxelSystem::render() { // update the frustum ViewFrustum* viewFrustum = Application::getInstance()->getDisplayViewFrustum(); _frustum.set(viewFrustum->getFarTopLeft(), viewFrustum->getFarTopRight(), viewFrustum->getFarBottomLeft(), - viewFrustum->getFarBottomRight(), viewFrustum->getNearTopLeft(), viewFrustum->getNearTopRight(), - viewFrustum->getNearBottomLeft(), viewFrustum->getNearBottomRight()); - + viewFrustum->getFarBottomRight(), viewFrustum->getNearTopLeft(), viewFrustum->getNearTopRight(), + viewFrustum->getNearBottomLeft(), viewFrustum->getNearBottomRight()); + RenderVisitor renderVisitor(getLOD()); guideToAugmented(renderVisitor, true); if (!_heightfieldBaseBatches.isEmpty()) { glEnableClientState(GL_VERTEX_ARRAY); glEnableClientState(GL_TEXTURE_COORD_ARRAY); - + Application::getInstance()->getTextureCache()->setPrimaryDrawBuffers(true, true); - + glDisable(GL_BLEND); glEnable(GL_CULL_FACE); glEnable(GL_ALPHA_TEST); @@ -225,7 +225,7 @@ void MetavoxelSystem::render() { batch.vertexBuffer->bind(); batch.indexBuffer->bind(); - + HeightfieldPoint* point = 0; glVertexPointer(3, GL_FLOAT, sizeof(HeightfieldPoint), &point->vertex); glTexCoordPointer(2, GL_FLOAT, sizeof(HeightfieldPoint), &point->textureCoord); @@ -234,7 +234,7 @@ void MetavoxelSystem::render() { _baseHeightfieldProgram.setUniform(_baseHeightScaleLocation, batch.heightScale); _baseHeightfieldProgram.setUniform(_baseColorScaleLocation, batch.colorScale); - + glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, batch.colorTextureID); @@ -244,10 +244,10 @@ void MetavoxelSystem::render() { glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, 0); - + batch.vertexBuffer->release(); batch.indexBuffer->release(); - + glPopMatrix(); } @@ -275,7 +275,7 @@ void MetavoxelSystem::render() { batch.vertexBuffer->bind(); batch.indexBuffer->bind(); - + HeightfieldPoint* point = 0; glVertexPointer(3, GL_FLOAT, sizeof(HeightfieldPoint), &point->vertex); glTexCoordPointer(2, GL_FLOAT, sizeof(HeightfieldPoint), &point->textureCoord); @@ -283,7 +283,7 @@ void MetavoxelSystem::render() { glBindTexture(GL_TEXTURE_2D, batch.heightTextureID); _splatHeightfieldProgram.setUniformValue(_splatHeightfieldLocations.heightScale, - batch.heightScale.x, batch.heightScale.y); + batch.heightScale.x, batch.heightScale.y); _splatHeightfieldProgram.setUniform(_splatHeightfieldLocations.textureScale, batch.textureScale); _splatHeightfieldProgram.setUniform(_splatHeightfieldLocations.splatTextureOffset, batch.splatTextureOffset); @@ -291,18 +291,18 @@ void MetavoxelSystem::render() { _splatHeightfieldProgram.setUniform(_splatHeightfieldLocations.splatTextureScalesS, batch.splatTextureScalesS); _splatHeightfieldProgram.setUniform(_splatHeightfieldLocations.splatTextureScalesT, batch.splatTextureScalesT); _splatHeightfieldProgram.setUniformValue( - _splatHeightfieldLocations.textureValueMinima, - (batch.materialIndex + 1) * EIGHT_BIT_MAXIMUM_RECIPROCAL - QUARTER_STEP, - (batch.materialIndex + 2) * EIGHT_BIT_MAXIMUM_RECIPROCAL - QUARTER_STEP, - (batch.materialIndex + 3) * EIGHT_BIT_MAXIMUM_RECIPROCAL - QUARTER_STEP, - (batch.materialIndex + 4) * EIGHT_BIT_MAXIMUM_RECIPROCAL - QUARTER_STEP); + _splatHeightfieldLocations.textureValueMinima, + (batch.materialIndex + 1) * EIGHT_BIT_MAXIMUM_RECIPROCAL - QUARTER_STEP, + (batch.materialIndex + 2) * EIGHT_BIT_MAXIMUM_RECIPROCAL - QUARTER_STEP, + (batch.materialIndex + 3) * EIGHT_BIT_MAXIMUM_RECIPROCAL - QUARTER_STEP, + (batch.materialIndex + 4) * EIGHT_BIT_MAXIMUM_RECIPROCAL - QUARTER_STEP); _splatHeightfieldProgram.setUniformValue( - _splatHeightfieldLocations.textureValueMaxima, - (batch.materialIndex + 1) * EIGHT_BIT_MAXIMUM_RECIPROCAL + QUARTER_STEP, - (batch.materialIndex + 2) * EIGHT_BIT_MAXIMUM_RECIPROCAL + QUARTER_STEP, - (batch.materialIndex + 3) * EIGHT_BIT_MAXIMUM_RECIPROCAL + QUARTER_STEP, - (batch.materialIndex + 4) * EIGHT_BIT_MAXIMUM_RECIPROCAL + QUARTER_STEP); - + _splatHeightfieldLocations.textureValueMaxima, + (batch.materialIndex + 1) * EIGHT_BIT_MAXIMUM_RECIPROCAL + QUARTER_STEP, + (batch.materialIndex + 2) * EIGHT_BIT_MAXIMUM_RECIPROCAL + QUARTER_STEP, + (batch.materialIndex + 3) * EIGHT_BIT_MAXIMUM_RECIPROCAL + QUARTER_STEP, + (batch.materialIndex + 4) * EIGHT_BIT_MAXIMUM_RECIPROCAL + QUARTER_STEP); + glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, batch.materialTextureID); @@ -312,22 +312,22 @@ void MetavoxelSystem::render() { } glDrawRangeElements(GL_TRIANGLES, 0, batch.vertexCount - 1, batch.indexCount, GL_UNSIGNED_INT, 0); - + for (int i = 0; i < SPLAT_COUNT; i++) { glActiveTexture(GL_TEXTURE0 + SPLAT_TEXTURE_UNITS[i]); glBindTexture(GL_TEXTURE_2D, 0); } - + glActiveTexture(GL_TEXTURE1); glBindTexture(GL_TEXTURE_2D, 0); - + glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, 0); - + batch.vertexBuffer->release(); batch.indexBuffer->release(); - glPopMatrix(); + glPopMatrix(); } _splatHeightfieldProgram.release(); @@ -341,15 +341,15 @@ void MetavoxelSystem::render() { glDisable(GL_CULL_FACE); - glDisableClientState(GL_TEXTURE_COORD_ARRAY); - glDisableClientState(GL_VERTEX_ARRAY); + glDisableClientState(GL_TEXTURE_COORD_ARRAY); + glDisableClientState(GL_VERTEX_ARRAY); _heightfieldBaseBatches.clear(); } if (!_voxelBaseBatches.isEmpty()) { Application::getInstance()->getTextureCache()->setPrimaryDrawBuffers(true, true); - + glEnableClientState(GL_VERTEX_ARRAY); glDisable(GL_BLEND); glEnable(GL_CULL_FACE); @@ -360,7 +360,7 @@ void MetavoxelSystem::render() { glEnableClientState(GL_COLOR_ARRAY); glEnableClientState(GL_NORMAL_ARRAY); - + _baseVoxelProgram.bind(); foreach (const VoxelBatch& batch, _voxelBaseBatches) { @@ -379,10 +379,10 @@ void MetavoxelSystem::render() { } _baseVoxelProgram.release(); - + glDisable(GL_ALPHA_TEST); glEnable(GL_BLEND); - + Application::getInstance()->getTextureCache()->setPrimaryDrawBuffers(true, false); if (!_voxelSplatBatches.isEmpty()) { @@ -406,25 +406,25 @@ void MetavoxelSystem::render() { glNormalPointer(GL_BYTE, sizeof(VoxelPoint), &point->normal); _splatVoxelProgram.setAttributeBuffer(_splatVoxelLocations.materials, - GL_UNSIGNED_BYTE, (qint64)&point->materials, SPLAT_COUNT, sizeof(VoxelPoint)); + GL_UNSIGNED_BYTE, (qint64)&point->materials, SPLAT_COUNT, sizeof(VoxelPoint)); _splatVoxelProgram.setAttributeBuffer(_splatVoxelLocations.materialWeights, - GL_UNSIGNED_BYTE, (qint64)&point->materialWeights, SPLAT_COUNT, sizeof(VoxelPoint)); + GL_UNSIGNED_BYTE, (qint64)&point->materialWeights, SPLAT_COUNT, sizeof(VoxelPoint)); const float QUARTER_STEP = 0.25f * EIGHT_BIT_MAXIMUM_RECIPROCAL; _splatVoxelProgram.setUniform(_splatVoxelLocations.splatTextureScalesS, batch.splatTextureScalesS); _splatVoxelProgram.setUniform(_splatVoxelLocations.splatTextureScalesT, batch.splatTextureScalesT); _splatVoxelProgram.setUniformValue( - _splatVoxelLocations.textureValueMinima, - (batch.materialIndex + 1) * EIGHT_BIT_MAXIMUM_RECIPROCAL - QUARTER_STEP, - (batch.materialIndex + 2) * EIGHT_BIT_MAXIMUM_RECIPROCAL - QUARTER_STEP, - (batch.materialIndex + 3) * EIGHT_BIT_MAXIMUM_RECIPROCAL - QUARTER_STEP, - (batch.materialIndex + 4) * EIGHT_BIT_MAXIMUM_RECIPROCAL - QUARTER_STEP); + _splatVoxelLocations.textureValueMinima, + (batch.materialIndex + 1) * EIGHT_BIT_MAXIMUM_RECIPROCAL - QUARTER_STEP, + (batch.materialIndex + 2) * EIGHT_BIT_MAXIMUM_RECIPROCAL - QUARTER_STEP, + (batch.materialIndex + 3) * EIGHT_BIT_MAXIMUM_RECIPROCAL - QUARTER_STEP, + (batch.materialIndex + 4) * EIGHT_BIT_MAXIMUM_RECIPROCAL - QUARTER_STEP); _splatVoxelProgram.setUniformValue( - _splatVoxelLocations.textureValueMaxima, - (batch.materialIndex + 1) * EIGHT_BIT_MAXIMUM_RECIPROCAL + QUARTER_STEP, - (batch.materialIndex + 2) * EIGHT_BIT_MAXIMUM_RECIPROCAL + QUARTER_STEP, - (batch.materialIndex + 3) * EIGHT_BIT_MAXIMUM_RECIPROCAL + QUARTER_STEP, - (batch.materialIndex + 4) * EIGHT_BIT_MAXIMUM_RECIPROCAL + QUARTER_STEP); + _splatVoxelLocations.textureValueMaxima, + (batch.materialIndex + 1) * EIGHT_BIT_MAXIMUM_RECIPROCAL + QUARTER_STEP, + (batch.materialIndex + 2) * EIGHT_BIT_MAXIMUM_RECIPROCAL + QUARTER_STEP, + (batch.materialIndex + 3) * EIGHT_BIT_MAXIMUM_RECIPROCAL + QUARTER_STEP, + (batch.materialIndex + 4) * EIGHT_BIT_MAXIMUM_RECIPROCAL + QUARTER_STEP); for (int i = 0; i < SPLAT_COUNT; i++) { glActiveTexture(GL_TEXTURE0 + SPLAT_TEXTURE_UNITS[i]); @@ -437,9 +437,9 @@ void MetavoxelSystem::render() { glActiveTexture(GL_TEXTURE0 + SPLAT_TEXTURE_UNITS[i]); glBindTexture(GL_TEXTURE_2D, 0); } - + glActiveTexture(GL_TEXTURE0); - + batch.vertexBuffer->release(); batch.indexBuffer->release(); } @@ -517,10 +517,10 @@ public: }; RayVoxelIntersectionVisitor::RayVoxelIntersectionVisitor(const glm::vec3& origin, - const glm::vec3& direction, const MetavoxelLOD& lod) : -RayIntersectionVisitor(origin, direction, QVector() << - Application::getInstance()->getMetavoxels()->getVoxelBufferAttribute(), QVector(), lod), -intersectionDistance(FLT_MAX) { + const glm::vec3& direction, const MetavoxelLOD& lod) : + RayIntersectionVisitor(origin, direction, QVector() << + Application::getInstance()->getMetavoxels()->getVoxelBufferAttribute(), QVector(), lod), + intersectionDistance(FLT_MAX) { } int RayVoxelIntersectionVisitor::visit(MetavoxelInfo& info, float distance) { @@ -528,7 +528,7 @@ int RayVoxelIntersectionVisitor::visit(MetavoxelInfo& info, float distance) { return _order; } const VoxelBuffer* buffer = static_cast( - info.inputValues.at(0).getInlineValue().data()); + info.inputValues.at(0).getInlineValue().data()); if (!buffer) { return STOP_RECURSION; } @@ -630,7 +630,7 @@ public: virtual bool visit(Spanner* spanner); virtual int visit(MetavoxelInfo& info); - + private: Box _bounds; @@ -693,17 +693,17 @@ class BufferCursorRenderVisitor : public MetavoxelVisitor { public: BufferCursorRenderVisitor(const AttributePointer& attribute, const Box& bounds); - + virtual int visit(MetavoxelInfo& info); - + private: Box _bounds; }; BufferCursorRenderVisitor::BufferCursorRenderVisitor(const AttributePointer& attribute, const Box& bounds) : -MetavoxelVisitor(QVector() << attribute), -_bounds(bounds) { + MetavoxelVisitor(QVector() << attribute), + _bounds(bounds) { } int BufferCursorRenderVisitor::visit(MetavoxelInfo& info) { @@ -766,11 +766,11 @@ void MetavoxelSystem::renderVoxelCursor(const glm::vec3& position, float radius) class MaterialEditApplier : public SignalHandler { public: - + MaterialEditApplier(const MetavoxelEditMessage& message, const QSharedPointer texture); virtual void handle(); - + protected: MetavoxelEditMessage _message; @@ -778,8 +778,8 @@ protected: }; MaterialEditApplier::MaterialEditApplier(const MetavoxelEditMessage& message, const QSharedPointer texture) : -_message(message), -_texture(texture) { + _message(message), + _texture(texture) { } void MaterialEditApplier::handle() { @@ -794,16 +794,16 @@ void MetavoxelSystem::applyMaterialEdit(const MetavoxelEditMessage& message, boo if (material && material->getDiffuse().isValid()) { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "applyMaterialEdit", Q_ARG(const MetavoxelEditMessage&, message), - Q_ARG(bool, reliable)); + Q_ARG(bool, reliable)); return; } QSharedPointer texture = Application::getInstance()->getTextureCache()->getTexture( - material->getDiffuse(), SPLAT_TEXTURE); + material->getDiffuse(), SPLAT_TEXTURE); if (texture->isLoaded()) { MetavoxelEditMessage newMessage = message; static_cast(newMessage.edit.data())->averageColor = texture->getAverageColor(); - applyEdit(newMessage, true); - + applyEdit(newMessage, true); + } else { MaterialEditApplier* applier = new MaterialEditApplier(message, texture); connect(texture.data(), &Resource::loaded, applier, &SignalHandler::handle); @@ -818,7 +818,7 @@ MetavoxelClient* MetavoxelSystem::createClient(const SharedNodePointer& node) { } void MetavoxelSystem::guideToAugmented(MetavoxelVisitor& visitor, bool render) { - NodeList::getInstance()->eachNode([&visitor, &render](const SharedNodePointer& node) { + NodeList::getInstance()->eachNode([&visitor, &render](const SharedNodePointer& node){ if (node->getType() == NodeType::MetavoxelServer) { QMutexLocker locker(&node->getMutex()); MetavoxelSystemClient* client = static_cast(node->getLinkedData()); @@ -837,9 +837,9 @@ void MetavoxelSystem::guideToAugmented(MetavoxelVisitor& visitor, bool render) { void MetavoxelSystem::loadSplatProgram(const char* type, ProgramObject& program, SplatLocations& locations) { program.addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + - "shaders/metavoxel_" + type + "_splat.vert"); + "shaders/metavoxel_" + type + "_splat.vert"); program.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + - "shaders/metavoxel_" + type + "_splat.frag"); + "shaders/metavoxel_" + type + "_splat.frag"); program.link(); program.bind(); @@ -859,8 +859,8 @@ void MetavoxelSystem::loadSplatProgram(const char* type, ProgramObject& program, } Throttle::Throttle() : -_limit(INT_MAX), -_total(0) { + _limit(INT_MAX), + _total(0) { } bool Throttle::shouldThrottle(int bytes) { @@ -881,7 +881,7 @@ bool Throttle::shouldThrottle(int bytes) { } MetavoxelSystemClient::MetavoxelSystemClient(const SharedNodePointer& node, MetavoxelUpdater* updater) : -MetavoxelClient(node, updater) { + MetavoxelClient(node, updater) { } void MetavoxelSystemClient::setAugmentedData(const MetavoxelData& data) { @@ -898,11 +898,11 @@ class ReceiveDelayer : public QObject { public: ReceiveDelayer(const SharedNodePointer& node, const QByteArray& packet); - + protected: - + virtual void timerEvent(QTimerEvent* event); - + private: SharedNodePointer _node; @@ -910,8 +910,8 @@ private: }; ReceiveDelayer::ReceiveDelayer(const SharedNodePointer& node, const QByteArray& packet) : -_node(node), -_packet(packet) { + _node(node), + _packet(packet) { } void ReceiveDelayer::timerEvent(QTimerEvent* event) { @@ -956,16 +956,16 @@ public: AugmentVisitor(const MetavoxelLOD& lod, const MetavoxelData& previousData); virtual int visit(MetavoxelInfo& info); - + private: const MetavoxelData& _previousData; }; AugmentVisitor::AugmentVisitor(const MetavoxelLOD& lod, const MetavoxelData& previousData) : -MetavoxelVisitor(QVector() << AttributeRegistry::getInstance()->getRendererAttribute(), - QVector(), lod), -_previousData(previousData) { + MetavoxelVisitor(QVector() << AttributeRegistry::getInstance()->getRendererAttribute(), + QVector(), lod), + _previousData(previousData) { } int AugmentVisitor::visit(MetavoxelInfo& info) { @@ -973,7 +973,7 @@ int AugmentVisitor::visit(MetavoxelInfo& info) { return DEFAULT_ORDER; } static_cast(info.inputValues.at(0).getInlineValue< - SharedObjectPointer>().data())->getImplementation()->augment(*_data, _previousData, info, _lod); + SharedObjectPointer>().data())->getImplementation()->augment(*_data, _previousData, info, _lod); return STOP_RECURSION; } @@ -981,10 +981,10 @@ class Augmenter : public QRunnable { public: Augmenter(const SharedNodePointer& node, const MetavoxelData& data, - const MetavoxelData& previousData, const MetavoxelLOD& lod); + const MetavoxelData& previousData, const MetavoxelLOD& lod); virtual void run(); - + private: QWeakPointer _node; @@ -994,11 +994,11 @@ private: }; Augmenter::Augmenter(const SharedNodePointer& node, const MetavoxelData& data, - const MetavoxelData& previousData, const MetavoxelLOD& lod) : -_node(node), -_data(data), -_previousData(previousData), -_lod(lod) { + const MetavoxelData& previousData, const MetavoxelLOD& lod) : + _node(node), + _data(data), + _previousData(previousData), + _lod(lod) { } void Augmenter::run() { @@ -1016,7 +1016,7 @@ void MetavoxelSystemClient::refreshVoxelData() { // make it look as if all the colors have changed MetavoxelData oldData = getAugmentedData(); oldData.touch(AttributeRegistry::getInstance()->getVoxelColorAttribute()); - + QThreadPool::globalInstance()->start(new Augmenter(_node, _data, oldData, _remoteDataLOD)); } @@ -1029,9 +1029,9 @@ class SendDelayer : public QObject { public: SendDelayer(const SharedNodePointer& node, const QByteArray& data); - + virtual void timerEvent(QTimerEvent* event); - + private: SharedNodePointer _node; @@ -1039,8 +1039,8 @@ private: }; SendDelayer::SendDelayer(const SharedNodePointer& node, const QByteArray& data) : -_node(node), -_data(data.constData(), data.size()) { + _node(node), + _data(data.constData(), data.size()) { } void SendDelayer::timerEvent(QTimerEvent* event) { @@ -1083,21 +1083,21 @@ void VoxelPoint::setNormal(const glm::vec3& normal) { } VoxelBuffer::VoxelBuffer(const QVector& vertices, const QVector& indices, const QVector& hermite, - const QMultiHash& quadIndices, int size, const QVector& materials) : -_vertices(vertices), -_indices(indices), -_hermite(hermite), -_quadIndices(quadIndices), -_size(size), -_vertexCount(vertices.size()), -_indexCount(indices.size()), -_hermiteCount(hermite.size()), -_indexBuffer(QOpenGLBuffer::IndexBuffer), -_materials(materials) { + const QMultiHash& quadIndices, int size, const QVector& materials) : + _vertices(vertices), + _indices(indices), + _hermite(hermite), + _quadIndices(quadIndices), + _size(size), + _vertexCount(vertices.size()), + _indexCount(indices.size()), + _hermiteCount(hermite.size()), + _indexBuffer(QOpenGLBuffer::IndexBuffer), + _materials(materials) { } bool VoxelBuffer::findFirstRayIntersection(const glm::vec3& entry, const glm::vec3& origin, - const glm::vec3& direction, float& distance) const { + const glm::vec3& direction, float& distance) const { float highest = _size - 1.0f; glm::vec3 position = entry * highest; glm::vec3 floors = glm::floor(position); @@ -1105,14 +1105,14 @@ bool VoxelBuffer::findFirstRayIntersection(const glm::vec3& entry, const glm::ve int x = qMin((int)floors.x, max), y = qMin((int)floors.y, max), z = qMin((int)floors.z, max); forever { for (QMultiHash::const_iterator it = _quadIndices.constFind(qRgb(x + 1, y + 1, z + 1)); - it != _quadIndices.constEnd(); it++) { + it != _quadIndices.constEnd(); it++) { const int* indices = _indices.constData() + *it; if (findRayTriangleIntersection(origin, direction, _vertices.at(indices[0]).vertex, - _vertices.at(indices[1]).vertex, _vertices.at(indices[2]).vertex, distance) || + _vertices.at(indices[1]).vertex, _vertices.at(indices[2]).vertex, distance) || findRayTriangleIntersection(origin, direction, _vertices.at(indices[0]).vertex, - _vertices.at(indices[2]).vertex, _vertices.at(indices[3]).vertex, distance)) { - return true; - } + _vertices.at(indices[2]).vertex, _vertices.at(indices[3]).vertex, distance)) { + return true; + } } float xDistance = FLT_MAX, yDistance = FLT_MAX, zDistance = FLT_MAX; if (direction.x > 0.0f) { @@ -1181,7 +1181,7 @@ void VoxelBuffer::render(bool cursor) { const SharedObjectPointer material = _materials.at(i); if (material) { _networkTextures[i] = Application::getInstance()->getTextureCache()->getTexture( - static_cast(material.data())->getDiffuse(), SPLAT_TEXTURE); + static_cast(material.data())->getDiffuse(), SPLAT_TEXTURE); } } } @@ -1216,7 +1216,7 @@ void VoxelBuffer::render(bool cursor) { splatBatch.indexBuffer = &_indexBuffer; splatBatch.vertexCount = _vertexCount; splatBatch.indexCount = _indexCount; - + for (int i = 0; i < _materials.size(); i += SPLAT_COUNT) { for (int j = 0; j < SPLAT_COUNT; j++) { int index = i + j; @@ -1227,7 +1227,7 @@ void VoxelBuffer::render(bool cursor) { splatBatch.splatTextureScalesS[j] = 1.0f / material->getScaleS(); splatBatch.splatTextureScalesT[j] = 1.0f / material->getScaleT(); splatBatch.splatTextureIDs[j] = texture->getID(); - + } else { splatBatch.splatTextureIDs[j] = 0; } @@ -1256,7 +1256,7 @@ void VoxelBuffer::render(bool cursor) { } BufferDataAttribute::BufferDataAttribute(const QString& name) : -InlineAttribute(name) { + InlineAttribute(name) { } bool BufferDataAttribute::merge(void*& parent, void* children[], bool postRead) const { @@ -1278,17 +1278,17 @@ DefaultMetavoxelRendererImplementation::DefaultMetavoxelRendererImplementation() class VoxelAugmentVisitor : public MetavoxelVisitor { public: - + VoxelAugmentVisitor(const MetavoxelLOD& lod); virtual int visit(MetavoxelInfo& info); }; VoxelAugmentVisitor::VoxelAugmentVisitor(const MetavoxelLOD& lod) : -MetavoxelVisitor(QVector() << AttributeRegistry::getInstance()->getVoxelColorAttribute() << - AttributeRegistry::getInstance()->getVoxelMaterialAttribute() << - AttributeRegistry::getInstance()->getVoxelHermiteAttribute(), QVector() << - Application::getInstance()->getMetavoxels()->getVoxelBufferAttribute(), lod) { + MetavoxelVisitor(QVector() << AttributeRegistry::getInstance()->getVoxelColorAttribute() << + AttributeRegistry::getInstance()->getVoxelMaterialAttribute() << + AttributeRegistry::getInstance()->getVoxelHermiteAttribute(), QVector() << + Application::getInstance()->getMetavoxels()->getVoxelBufferAttribute(), lod) { } class EdgeCrossing { @@ -1446,9 +1446,9 @@ int VoxelAugmentVisitor::visit(MetavoxelInfo& info) { // its properties (color, material, normal) if one is present; as before, boundary edges are excluded int clampedX = qMax(x - 1, 0), clampedY = qMax(y - 1, 0), clampedZ = qMax(z - 1, 0); const QRgb* hermiteBase = hermiteData + clampedZ * hermiteArea + clampedY * hermiteStride + - clampedX * VoxelHermiteData::EDGE_COUNT; + clampedX * VoxelHermiteData::EDGE_COUNT; const char* materialBase = materialData ? - (materialData + clampedZ * area + clampedY * size + clampedX) : NULL; + (materialData + clampedZ * area + clampedY * size + clampedX) : NULL; int crossingCount = 0; if (middleX) { if (alpha0 != alpha1) { @@ -1650,7 +1650,7 @@ int VoxelAugmentVisitor::visit(MetavoxelInfo& info) { if (displayHermite) { glm::vec3 start = info.minimum + (glm::vec3(clampedX, clampedY, clampedZ) + - crossing.point) * scale; + crossing.point) * scale; hermiteSegments.append(start); hermiteSegments.append(start + crossing.normal * scale); } @@ -1710,18 +1710,18 @@ int VoxelAugmentVisitor::visit(MetavoxelInfo& info) { for (int i = 0; i < MAX_ITERATIONS; i++) { glm::vec3 offDiagonals = glm::abs(glm::vec3(d[1][0], d[2][0], d[2][1])); int largestIndex = (offDiagonals[0] > offDiagonals[1]) ? (offDiagonals[0] > offDiagonals[2] ? 0 : 2) : - (offDiagonals[1] > offDiagonals[2] ? 1 : 2); + (offDiagonals[1] > offDiagonals[2] ? 1 : 2); const float DESIRED_PRECISION = 0.00001f; if (offDiagonals[largestIndex] < DESIRED_PRECISION) { break; } int largestJ = (largestIndex == 2) ? 1 : 0; - int largestI = (largestIndex == 0) ? 1 : 2; + int largestI = (largestIndex == 0) ? 1 : 2; float sjj = d[largestJ][largestJ]; float sii = d[largestI][largestI]; float angle = glm::atan(2.0f * d[largestJ][largestI], sjj - sii) / 2.0f; glm::quat rotation = glm::angleAxis(angle, largestIndex == 0 ? glm::vec3(0.0f, 0.0f, -1.0f) : - (largestIndex == 1 ? glm::vec3(0.0f, 1.0f, 0.0f) : glm::vec3(-1.0f, 0.0f, 0.0f))); + (largestIndex == 1 ? glm::vec3(0.0f, 1.0f, 0.0f) : glm::vec3(-1.0f, 0.0f, 0.0f))); combinedRotation = glm::normalize(rotation * combinedRotation); glm::mat3 matrix = glm::mat3_cast(combinedRotation); d = matrix * ata * glm::transpose(matrix); @@ -1735,7 +1735,7 @@ int VoxelAugmentVisitor::visit(MetavoxelInfo& info) { // compute the pseudo-inverse, ataplus, and use to find the minimizing solution glm::mat3 u = glm::mat3_cast(combinedRotation); - glm::mat3 ataplus = glm::transpose(u) * d * u; + glm::mat3 ataplus = glm::transpose(u) * d * u; glm::vec3 solution = (ataplus * atrans * b) + center; // make sure it doesn't fall beyond the cell boundaries @@ -1774,7 +1774,7 @@ int VoxelAugmentVisitor::visit(MetavoxelInfo& info) { const glm::vec3& first = vertices.at(index.indices[0]).vertex; glm::vec3 normal = glm::cross(vertices.at(index1.indices[0]).vertex - first, - vertices.at(index3.indices[0]).vertex - first); + vertices.at(index3.indices[0]).vertex - first); if (alpha0 == 0) { // quad faces negative x indices.append(index3.getClosestIndex(normal = -normal, vertices)); @@ -1800,7 +1800,7 @@ int VoxelAugmentVisitor::visit(MetavoxelInfo& info) { const glm::vec3& first = vertices.at(index.indices[0]).vertex; glm::vec3 normal = glm::cross(vertices.at(index3.indices[0]).vertex - first, - vertices.at(index1.indices[0]).vertex - first); + vertices.at(index1.indices[0]).vertex - first); if (alpha0 == 0) { // quad faces negative y indices.append(index1.getClosestIndex(normal = -normal, vertices)); @@ -1826,7 +1826,7 @@ int VoxelAugmentVisitor::visit(MetavoxelInfo& info) { const glm::vec3& first = vertices.at(index.indices[0]).vertex; glm::vec3 normal = glm::cross(vertices.at(index1.indices[0]).vertex - first, - vertices.at(index3.indices[0]).vertex - first); + vertices.at(index3.indices[0]).vertex - first); if (alpha0 == 0) { // quad faces negative z indices.append(index3.getClosestIndex(normal = -normal, vertices)); @@ -1861,7 +1861,7 @@ int VoxelAugmentVisitor::visit(MetavoxelInfo& info) { } } buffer = new VoxelBuffer(vertices, indices, hermiteSegments, quadIndices, size, - material ? material->getMaterials() : QVector()); + material ? material->getMaterials() : QVector()); } BufferDataPointer pointer(buffer); info.outputValues[0] = AttributeValue(_outputs.at(0), encodeInline(pointer)); @@ -1869,14 +1869,14 @@ int VoxelAugmentVisitor::visit(MetavoxelInfo& info) { } void DefaultMetavoxelRendererImplementation::augment(MetavoxelData& data, const MetavoxelData& previous, - MetavoxelInfo& info, const MetavoxelLOD& lod) { + MetavoxelInfo& info, const MetavoxelLOD& lod) { // copy the previous buffers MetavoxelData expandedPrevious = previous; while (expandedPrevious.getSize() < data.getSize()) { expandedPrevious.expand(); } const AttributePointer& voxelBufferAttribute = - Application::getInstance()->getMetavoxels()->getVoxelBufferAttribute(); + Application::getInstance()->getMetavoxels()->getVoxelBufferAttribute(); MetavoxelNode* root = expandedPrevious.getRoot(voxelBufferAttribute); if (root) { data.setRoot(voxelBufferAttribute, root); @@ -1892,16 +1892,16 @@ public: SpannerSimulateVisitor(float deltaTime, const MetavoxelLOD& lod); virtual bool visit(Spanner* spanner); - + private: float _deltaTime; }; SpannerSimulateVisitor::SpannerSimulateVisitor(float deltaTime, const MetavoxelLOD& lod) : -SpannerVisitor(QVector() << AttributeRegistry::getInstance()->getSpannersAttribute(), - QVector(), QVector(), lod), -_deltaTime(deltaTime) { + SpannerVisitor(QVector() << AttributeRegistry::getInstance()->getSpannersAttribute(), + QVector(), QVector(), lod), + _deltaTime(deltaTime) { } bool SpannerSimulateVisitor::visit(Spanner* spanner) { @@ -1910,7 +1910,7 @@ bool SpannerSimulateVisitor::visit(Spanner* spanner) { } void DefaultMetavoxelRendererImplementation::simulate(MetavoxelData& data, float deltaTime, - MetavoxelInfo& info, const MetavoxelLOD& lod) { + MetavoxelInfo& info, const MetavoxelLOD& lod) { SpannerSimulateVisitor spannerSimulateVisitor(deltaTime, lod); data.guide(spannerSimulateVisitor); } @@ -1921,7 +1921,7 @@ public: BufferRenderVisitor(const AttributePointer& attribute); virtual int visit(MetavoxelInfo& info); - + private: int _order; @@ -1929,15 +1929,15 @@ private: }; BufferRenderVisitor::BufferRenderVisitor(const AttributePointer& attribute) : -MetavoxelVisitor(QVector() << attribute), -_order(encodeOrder(Application::getInstance()->getDisplayViewFrustum()->getDirection())), -_containmentDepth(INT_MAX) { + MetavoxelVisitor(QVector() << attribute), + _order(encodeOrder(Application::getInstance()->getDisplayViewFrustum()->getDirection())), + _containmentDepth(INT_MAX) { } int BufferRenderVisitor::visit(MetavoxelInfo& info) { if (_containmentDepth >= _depth) { Frustum::IntersectionType intersection = Application::getInstance()->getMetavoxels()->getFrustum().getIntersectionType( - info.getBounds()); + info.getBounds()); if (intersection == Frustum::NO_INTERSECTION) { return STOP_RECURSION; } @@ -2007,12 +2007,12 @@ void CuboidRenderer::render(const MetavoxelLOD& lod, bool contained, bool cursor } StaticModelRenderer::StaticModelRenderer() : -_model(new Model(this)) { + _model(new Model(this)) { } void StaticModelRenderer::init(Spanner* spanner) { SpannerRenderer::init(spanner); - + _model->init(); StaticModel* staticModel = static_cast(spanner); @@ -2035,7 +2035,7 @@ void StaticModelRenderer::simulate(float deltaTime) { bounds = Box(extents.minimum, extents.maximum); } static_cast(_spanner)->setBounds(glm::translate(_model->getTranslation()) * - glm::mat4_cast(_model->getRotation()) * glm::scale(_model->getScale()) * bounds); + glm::mat4_cast(_model->getRotation()) * glm::scale(_model->getScale()) * bounds); _model->simulate(deltaTime); } @@ -2251,7 +2251,7 @@ void HeightfieldNodeRenderer::render(const HeightfieldNodePointer& node, const g if (cursor) { bufferPair.first.bind(); bufferPair.second.bind(); - + glPushMatrix(); glTranslatef(translation.x, translation.y, translation.z); glm::vec3 axis = glm::axis(rotation); @@ -2286,7 +2286,7 @@ void HeightfieldNodeRenderer::render(const HeightfieldNodePointer& node, const g baseBatch.heightScale = glm::vec4(1.0f / width, 1.0f / height, (innerWidth - 1) / -2.0f, (innerHeight - 1) / -2.0f); baseBatch.colorTextureID = _colorTextureID; baseBatch.colorScale = glm::vec2((float)width / innerWidth, (float)height / innerHeight); - Application::getInstance()->getMetavoxels()->addHeightfieldBaseBatch(baseBatch); + Application::getInstance()->getMetavoxels()->addHeightfieldBaseBatch(baseBatch); if (!_networkTextures.isEmpty()) { HeightfieldSplatBatch splatBatch; @@ -2331,3 +2331,4 @@ void HeightfieldNodeRenderer::render(const HeightfieldNodePointer& node, const g } QHash HeightfieldNodeRenderer::_bufferPairs; + From 68430e1346ea1f6014c19cff445b2984a1a697a7 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Mon, 15 Dec 2014 11:54:33 -0800 Subject: [PATCH 099/258] Moved GLCanvas to DependencyManager --- interface/src/Application.cpp | 76 ++++++++++++++++++++--------------- interface/src/Application.h | 31 +++++++------- interface/src/GLCanvas.h | 10 ++++- 3 files changed, 68 insertions(+), 49 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index d0abc47b85..eaafcd0eac 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -146,7 +146,6 @@ QString& Application::resourcesPath() { Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) : QApplication(argc, argv), _window(new MainWindow(desktop())), - _glWidget(new GLCanvas()), _toolWindow(NULL), _nodeThread(new QThread(this)), _datagramProcessor(), @@ -195,7 +194,8 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) : _isVSyncOn(true), _aboutToQuit(false) { - + GLCanvas* glCanvas = DependencyManager::get(); + // read the ApplicationInfo.ini file for Name/Version/Domain information QSettings applicationInfo(Application::resourcesPath() + "info/ApplicationInfo.ini", QSettings::IniFormat); @@ -365,16 +365,16 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) : ResourceCache::setRequestLimit(3); - _window->setCentralWidget(_glWidget); + _window->setCentralWidget(glCanvas); restoreSizeAndPosition(); _window->setVisible(true); - _glWidget->setFocusPolicy(Qt::StrongFocus); - _glWidget->setFocus(); + glCanvas->setFocusPolicy(Qt::StrongFocus); + glCanvas->setFocus(); // enable mouse tracking; otherwise, we only get drag events - _glWidget->setMouseTracking(true); + glCanvas->setMouseTracking(true); _toolWindow = new ToolWindow(); _toolWindow->setWindowFlags(_toolWindow->windowFlags() | Qt::WindowStaysOnTopHint); @@ -393,7 +393,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) : checkVersion(); - _overlays.init(_glWidget); // do this before scripts load + _overlays.init(glCanvas); // do this before scripts load LocalVoxelsList::getInstance()->addPersistantTree(DOMAIN_TREE_NAME, _voxels.getTree()); LocalVoxelsList::getInstance()->addPersistantTree(CLIPBOARD_TREE_NAME, &_clipboard); @@ -483,8 +483,6 @@ Application::~Application() { Menu::getInstance()->deleteLater(); _myAvatar = NULL; - - delete _glWidget; } void Application::saveSettings() { @@ -624,7 +622,7 @@ void Application::paintGL() { if (OculusManager::isConnected()) { _textureCache.setFrameBufferSize(OculusManager::getRenderTargetSize()); } else { - QSize fbSize = _glWidget->getDeviceSize() * getRenderResolutionScale(); + QSize fbSize = DependencyManager::get()->getDeviceSize() * getRenderResolutionScale(); _textureCache.setFrameBufferSize(fbSize); } @@ -1048,7 +1046,8 @@ void Application::keyPressEvent(QKeyEvent* event) { if (isShifted) { _viewFrustum.setFocalLength(_viewFrustum.getFocalLength() - 0.1f); if (TV3DManager::isConnected()) { - TV3DManager::configureCamera(_myCamera, _glWidget->getDeviceWidth(), _glWidget->getDeviceHeight()); + GLCanvas* glCanvas = DependencyManager::get(); + TV3DManager::configureCamera(_myCamera, glCanvas->getDeviceWidth(), glCanvas->getDeviceHeight()); } } else { _myCamera.setEyeOffsetPosition(_myCamera.getEyeOffsetPosition() + glm::vec3(-0.001, 0, 0)); @@ -1060,7 +1059,8 @@ void Application::keyPressEvent(QKeyEvent* event) { if (isShifted) { _viewFrustum.setFocalLength(_viewFrustum.getFocalLength() + 0.1f); if (TV3DManager::isConnected()) { - TV3DManager::configureCamera(_myCamera, _glWidget->getDeviceWidth(), _glWidget->getDeviceHeight()); + GLCanvas* glCanvas = DependencyManager::get(); + TV3DManager::configureCamera(_myCamera, glCanvas->getDeviceWidth(), glCanvas->getDeviceHeight()); } } else { @@ -1506,7 +1506,7 @@ void Application::idle() { { PerformanceTimer perfTimer("updateGL"); PerformanceWarning warn(showWarnings, "Application::idle()... updateGL()"); - _glWidget->updateGL(); + DependencyManager::get()->updateGL(); } { PerformanceTimer perfTimer("rest"); @@ -1532,13 +1532,14 @@ void Application::idle() { void Application::checkBandwidthMeterClick() { // ... to be called upon button release + GLCanvas* glCanvas = DependencyManager::get(); if (Menu::getInstance()->isOptionChecked(MenuOption::Bandwidth) && Menu::getInstance()->isOptionChecked(MenuOption::Stats) && Menu::getInstance()->isOptionChecked(MenuOption::UserInterface) && glm::compMax(glm::abs(glm::ivec2(getMouseX() - getMouseDragStartedX(), getMouseY() - getMouseDragStartedY()))) <= BANDWIDTH_METER_CLICK_MAX_DRAG_LENGTH - && _bandwidthMeter.isWithinArea(getMouseX(), getMouseY(), _glWidget->width(), _glWidget->height())) { + && _bandwidthMeter.isWithinArea(getMouseX(), getMouseY(), glCanvas->width(), glCanvas->height())) { // The bandwidth meter is visible, the click didn't get dragged too far and // we actually hit the bandwidth meter @@ -1567,7 +1568,8 @@ void Application::setFullscreen(bool fullscreen) { } void Application::setEnable3DTVMode(bool enable3DTVMode) { - resizeGL(_glWidget->getDeviceWidth(),_glWidget->getDeviceHeight()); + GLCanvas* glCanvas = DependencyManager::get(); + resizeGL(glCanvas->getDeviceWidth(), glCanvas->getDeviceHeight()); } void Application::setEnableVRMode(bool enableVRMode) { @@ -1592,7 +1594,8 @@ void Application::setEnableVRMode(bool enableVRMode) { _myCamera.setHmdRotation(glm::quat()); } - resizeGL(_glWidget->getDeviceWidth(), _glWidget->getDeviceHeight()); + GLCanvas* glCanvas = DependencyManager::get(); + resizeGL(glCanvas->getDeviceWidth(), glCanvas->getDeviceHeight()); } void Application::setRenderVoxels(bool voxelRender) { @@ -1654,8 +1657,9 @@ glm::vec3 Application::getMouseVoxelWorldCoordinates(const VoxelDetail& mouseVox bool Application::mouseOnScreen() const { if (OculusManager::isConnected()) { - return getMouseX() >= 0 && getMouseX() <= _glWidget->getDeviceWidth() && - getMouseY() >= 0 && getMouseY() <= _glWidget->getDeviceHeight(); + GLCanvas* glCanvas = DependencyManager::get(); + return getMouseX() >= 0 && getMouseX() <= glCanvas->getDeviceWidth() && + getMouseY() >= 0 && getMouseY() <= glCanvas->getDeviceHeight(); } return true; } @@ -1774,7 +1778,8 @@ void Application::exportVoxels(const VoxelDetail& sourceVoxel) { QString desktopLocation = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation); QString suggestedName = desktopLocation.append("/voxels.svo"); - QString fileNameString = QFileDialog::getSaveFileName(_glWidget, tr("Export Voxels"), suggestedName, + QString fileNameString = QFileDialog::getSaveFileName(DependencyManager::get(), + tr("Export Voxels"), suggestedName, tr("Sparse Voxel Octree Files (*.svo)")); QByteArray fileNameAscii = fileNameString.toLocal8Bit(); const char* fileName = fileNameAscii.data(); @@ -2029,9 +2034,9 @@ void Application::init() { _metavoxels.init(); - _audio.init(_glWidget); - - _rearMirrorTools = new RearMirrorTools(_glWidget, _mirrorViewRect, _settings); + GLCanvas* glCanvas = DependencyManager::get(); + _audio.init(glCanvas); + _rearMirrorTools = new RearMirrorTools(glCanvas, _mirrorViewRect, _settings); connect(_rearMirrorTools, SIGNAL(closeView()), SLOT(closeMirrorView())); connect(_rearMirrorTools, SIGNAL(restoreView()), SLOT(restoreMirrorView())); @@ -2913,8 +2918,9 @@ void Application::updateShadowMap() { } fbo->release(); - - glViewport(0, 0, _glWidget->getDeviceWidth(), _glWidget->getDeviceHeight()); + + GLCanvas* glCanvas = DependencyManager::get(); + glViewport(0, 0, glCanvas->getDeviceWidth(), glCanvas->getDeviceHeight()); } const GLfloat WORLD_AMBIENT_COLOR[] = { 0.525f, 0.525f, 0.6f }; @@ -2944,7 +2950,9 @@ QImage Application::renderAvatarBillboard() { Glower glower; const int BILLBOARD_SIZE = 64; - renderRearViewMirror(QRect(0, _glWidget->getDeviceHeight() - BILLBOARD_SIZE, BILLBOARD_SIZE, BILLBOARD_SIZE), true); + renderRearViewMirror(QRect(0, DependencyManager::get()->getDeviceHeight() - BILLBOARD_SIZE, + BILLBOARD_SIZE, BILLBOARD_SIZE), + true); QImage image(BILLBOARD_SIZE, BILLBOARD_SIZE, QImage::Format_ARGB32); glReadPixels(0, 0, BILLBOARD_SIZE, BILLBOARD_SIZE, GL_BGRA, GL_UNSIGNED_BYTE, image.bits()); @@ -3239,8 +3247,9 @@ void Application::computeOffAxisFrustum(float& left, float& right, float& bottom } glm::vec2 Application::getScaledScreenPoint(glm::vec2 projectedPoint) { - float horizontalScale = _glWidget->getDeviceWidth() / 2.0f; - float verticalScale = _glWidget->getDeviceHeight() / 2.0f; + GLCanvas* glCanvas = DependencyManager::get(); + float horizontalScale = glCanvas->getDeviceWidth() / 2.0f; + float verticalScale = glCanvas->getDeviceHeight() / 2.0f; // -1,-1 is 0,windowHeight // 1,1 is windowWidth,0 @@ -3259,7 +3268,7 @@ glm::vec2 Application::getScaledScreenPoint(glm::vec2 projectedPoint) { // -1,-1 1,-1 glm::vec2 screenPoint((projectedPoint.x + 1.0) * horizontalScale, - ((projectedPoint.y + 1.0) * -verticalScale) + _glWidget->getDeviceHeight()); + ((projectedPoint.y + 1.0) * -verticalScale) + glCanvas->getDeviceHeight()); return screenPoint; } @@ -3570,7 +3579,7 @@ void Application::resetSensors() { QScreen* currentScreen = _window->windowHandle()->screen(); QWindow* mainWindow = _window->windowHandle(); QPoint windowCenter = mainWindow->geometry().center(); - _glWidget->cursor().setPos(currentScreen, windowCenter); + DependencyManager::get()->cursor().setPos(currentScreen, windowCenter); _myAvatar->reset(); @@ -4251,7 +4260,8 @@ void Application::setPreviousScriptLocation(const QString& previousScriptLocatio void Application::loadDialog() { - QString fileNameString = QFileDialog::getOpenFileName(_glWidget, tr("Open Script"), + QString fileNameString = QFileDialog::getOpenFileName(DependencyManager::get(), + tr("Open Script"), getPreviousScriptLocation(), tr("JavaScript Files (*.js)")); if (!fileNameString.isEmpty()) { @@ -4287,7 +4297,7 @@ void Application::loadScriptURLDialog() { void Application::toggleLogDialog() { if (! _logDialog) { - _logDialog = new LogDialog(_glWidget, getLogger()); + _logDialog = new LogDialog(DependencyManager::get(), getLogger()); } if (_logDialog->isVisible()) { @@ -4347,7 +4357,7 @@ void Application::parseVersionXml() { } if (!shouldSkipVersion(latestVersion) && applicationVersion() != latestVersion) { - new UpdateDialog(_glWidget, releaseNotes, latestVersion, downloadUrl); + new UpdateDialog(DependencyManager::get(), releaseNotes, latestVersion, downloadUrl); } sender->deleteLater(); } @@ -4380,7 +4390,7 @@ void Application::takeSnapshot() { } if (!_snapshotShareDialog) { - _snapshotShareDialog = new SnapshotShareDialog(fileName, _glWidget); + _snapshotShareDialog = new SnapshotShareDialog(fileName, DependencyManager::get()); } _snapshotShareDialog->show(); } diff --git a/interface/src/Application.h b/interface/src/Application.h index c2136f1c57..cddaeaad15 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -171,46 +171,50 @@ public: void removeVoxel(glm::vec3 position, float scale); glm::vec3 getMouseVoxelWorldCoordinates(const VoxelDetail& mouseVoxel); + bool isThrottleRendering() const { return DependencyManager::get()->isThrottleRendering(); } - GLCanvas* getGLWidget() { return _glWidget; } - bool isThrottleRendering() const { return _glWidget->isThrottleRendering(); } + GLCanvas* getGLWidget() { return DependencyManager::get(); } // TODO: remove MyAvatar* getAvatar() { return _myAvatar; } Audio* getAudio() { return &_audio; } Camera* getCamera() { return &_myCamera; } ViewFrustum* getViewFrustum() { return &_viewFrustum; } ViewFrustum* getDisplayViewFrustum() { return &_displayViewFrustum; } ViewFrustum* getShadowViewFrustum() { return &_shadowViewFrustum; } - VoxelImporter* getVoxelImporter() { return &_voxelImporter; } VoxelSystem* getVoxels() { return &_voxels; } - VoxelTree* getVoxelTree() { return _voxels.getTree(); } const OctreePacketProcessor& getOctreePacketProcessor() const { return _octreeProcessor; } MetavoxelSystem* getMetavoxels() { return &_metavoxels; } EntityTreeRenderer* getEntities() { return &_entities; } - bool getImportSucceded() { return _importSucceded; } VoxelSystem* getSharedVoxelSystem() { return &_sharedVoxelSystem; } + Environment* getEnvironment() { return &_environment; } + PrioVR* getPrioVR() { return &_prioVR; } + QUndoStack* getUndoStack() { return &_undoStack; } + MainWindow* getWindow() { return _window; } + + VoxelImporter* getVoxelImporter() { return &_voxelImporter; } VoxelTree* getClipboard() { return &_clipboard; } EntityTree* getEntityClipboard() { return &_entityClipboard; } EntityTreeRenderer* getEntityClipboardRenderer() { return &_entityClipboardRenderer; } - Environment* getEnvironment() { return &_environment; } + VoxelTree* getVoxelTree() { return _voxels.getTree(); } + bool getImportSucceded() { return _importSucceded; } + bool isMousePressed() const { return _mousePressed; } - bool isMouseHidden() const { return _glWidget->cursor().shape() == Qt::BlankCursor; } + bool isMouseHidden() const { return DependencyManager::get()->cursor().shape() == Qt::BlankCursor; } void setCursorVisible(bool visible); const glm::vec3& getMouseRayOrigin() const { return _mouseRayOrigin; } const glm::vec3& getMouseRayDirection() const { return _mouseRayDirection; } bool mouseOnScreen() const; int getMouseX() const; int getMouseY() const; - int getTrueMouseX() const { return _glWidget->mapFromGlobal(QCursor::pos()).x(); } - int getTrueMouseY() const { return _glWidget->mapFromGlobal(QCursor::pos()).y(); } + int getTrueMouseX() const { return DependencyManager::get()->mapFromGlobal(QCursor::pos()).x(); } + int getTrueMouseY() const { return DependencyManager::get()->mapFromGlobal(QCursor::pos()).y(); } int getMouseDragStartedX() const; int getMouseDragStartedY() const; int getTrueMouseDragStartedX() const { return _mouseDragStartedX; } int getTrueMouseDragStartedY() const { return _mouseDragStartedY; } bool getLastMouseMoveWasSimulated() const { return _lastMouseMoveWasSimulated; } + FaceTracker* getActiveFaceTracker(); - PrioVR* getPrioVR() { return &_prioVR; } BandwidthMeter* getBandwidthMeter() { return &_bandwidthMeter; } - QUndoStack* getUndoStack() { return &_undoStack; } QSystemTrayIcon* getTrayIcon() { return _trayIcon; } ApplicationOverlay& getApplicationOverlay() { return _applicationOverlay; } Overlays& getOverlays() { return _overlays; } @@ -230,7 +234,6 @@ public: void saveSettings(); - MainWindow* getWindow() { return _window; } NodeToOctreeSceneStats* getOcteeSceneStats() { return &_octreeServerSceneStats; } void lockOctreeSceneStats() { _octreeSceneStatsLock.lockForRead(); } void unlockOctreeSceneStats() { _octreeSceneStatsLock.unlock(); } @@ -278,7 +281,8 @@ public: FileLogger* getLogger() { return _logger; } - glm::vec2 getViewportDimensions() const { return glm::vec2(_glWidget->getDeviceWidth(), _glWidget->getDeviceHeight()); } + glm::vec2 getViewportDimensions() const { return glm::vec2(DependencyManager::get()->getDeviceWidth(), + DependencyManager::get()->getDeviceHeight()); } NodeToJurisdictionMap& getVoxelServerJurisdictions() { return _voxelServerJurisdictions; } NodeToJurisdictionMap& getEntityServerJurisdictions() { return _entityServerJurisdictions; } void pasteVoxelsToOctalCode(const unsigned char* octalCodeDestination); @@ -456,7 +460,6 @@ private: int sendNackPackets(); MainWindow* _window; - GLCanvas* _glWidget; // our GLCanvas has a couple extra features ToolWindow* _toolWindow; diff --git a/interface/src/GLCanvas.h b/interface/src/GLCanvas.h index 0d381fa0bf..2b1cd3539d 100644 --- a/interface/src/GLCanvas.h +++ b/interface/src/GLCanvas.h @@ -15,11 +15,12 @@ #include #include +#include + /// customized canvas that simply forwards requests/events to the singleton application -class GLCanvas : public QGLWidget { +class GLCanvas : public QGLWidget, public DependencyManager::Dependency { Q_OBJECT public: - GLCanvas(); bool isThrottleRendering() const; int getDeviceWidth() const; @@ -56,6 +57,11 @@ private slots: void activeChanged(Qt::ApplicationState state); void throttleRender(); bool eventFilter(QObject*, QEvent* event); + +private: + GLCanvas(); + ~GLCanvas(); + friend class DependencyManager; }; #endif // hifi_GLCanvas_h From 4e7368b643a36f6bddc9ebcd3a7af93c895d6f2d Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 12:09:30 -0800 Subject: [PATCH 100/258] more windows hackery --- libraries/shared/src/windowshacks.h | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/libraries/shared/src/windowshacks.h b/libraries/shared/src/windowshacks.h index fcd2f5a7f2..3fd9d29fb3 100644 --- a/libraries/shared/src/windowshacks.h +++ b/libraries/shared/src/windowshacks.h @@ -15,6 +15,11 @@ #define hifi_windowshacks_h #ifdef WIN32 +// apparently needed to get M_PI and other defines from cmath/math.h +#define _USE_MATH_DEFINES +// needed to make sure windows doesn't go to crazy with its defines +#define WINDOWS_LEAN_AND_MEAN + #undef NOMINMAX #include From 95d820ee8b1265c50391a72f9f2110b407037218 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 12:16:01 -0800 Subject: [PATCH 101/258] more windows hackery --- libraries/shared/src/windowshacks.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/shared/src/windowshacks.h b/libraries/shared/src/windowshacks.h index 3fd9d29fb3..e7397b29ee 100644 --- a/libraries/shared/src/windowshacks.h +++ b/libraries/shared/src/windowshacks.h @@ -20,7 +20,7 @@ // needed to make sure windows doesn't go to crazy with its defines #define WINDOWS_LEAN_AND_MEAN -#undef NOMINMAX +//#undef NOMINMAX #include inline double roundf(double value) { From 0b95403949d86d27b217e4bd2facd0af9b06dee2 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 12:25:20 -0800 Subject: [PATCH 102/258] cleanup the windows hackery a little --- libraries/shared/src/windowshacks.h | 6 ------ 1 file changed, 6 deletions(-) diff --git a/libraries/shared/src/windowshacks.h b/libraries/shared/src/windowshacks.h index e7397b29ee..67c6f8be0c 100644 --- a/libraries/shared/src/windowshacks.h +++ b/libraries/shared/src/windowshacks.h @@ -15,12 +15,6 @@ #define hifi_windowshacks_h #ifdef WIN32 -// apparently needed to get M_PI and other defines from cmath/math.h -#define _USE_MATH_DEFINES -// needed to make sure windows doesn't go to crazy with its defines -#define WINDOWS_LEAN_AND_MEAN - -//#undef NOMINMAX #include inline double roundf(double value) { From a92b65b0e9d871d91b38a356b63890c27870bec7 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 12:42:04 -0800 Subject: [PATCH 103/258] now lets see if this works --- interface/src/renderer/GeometryCache.h | 2 +- interface/src/renderer/TextureCache.cpp | 2 +- interface/src/renderer/TextureCache.h | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/interface/src/renderer/GeometryCache.h b/interface/src/renderer/GeometryCache.h index 2d813ece09..22857125af 100644 --- a/interface/src/renderer/GeometryCache.h +++ b/interface/src/renderer/GeometryCache.h @@ -13,7 +13,7 @@ #define hifi_GeometryCache_h // include this before QOpenGLBuffer, which includes an earlier version of OpenGL -#include "InterfaceConfig.h" +#include #include #include diff --git a/interface/src/renderer/TextureCache.cpp b/interface/src/renderer/TextureCache.cpp index 123a8a5384..1591f5cb26 100644 --- a/interface/src/renderer/TextureCache.cpp +++ b/interface/src/renderer/TextureCache.cpp @@ -10,7 +10,7 @@ // // include this before QGLWidget, which includes an earlier version of OpenGL -#include "InterfaceConfig.h" +#include #include #include diff --git a/interface/src/renderer/TextureCache.h b/interface/src/renderer/TextureCache.h index 2bdfda3217..56e29bc5fb 100644 --- a/interface/src/renderer/TextureCache.h +++ b/interface/src/renderer/TextureCache.h @@ -12,6 +12,8 @@ #ifndef hifi_TextureCache_h #define hifi_TextureCache_h +#include + #include #include #include @@ -19,8 +21,6 @@ #include #include -#include "InterfaceConfig.h" - class QOpenGLFramebufferObject; class NetworkTexture; From bf5147cd918bb9392cd57452c8e52fb58ab4fc88 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 15 Dec 2014 12:56:32 -0800 Subject: [PATCH 104/258] fix qt modules to link in LinkSharedDependencies --- cmake/macros/LinkSharedDependencies.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/macros/LinkSharedDependencies.cmake b/cmake/macros/LinkSharedDependencies.cmake index a73f57dc1d..afd25db0d7 100644 --- a/cmake/macros/LinkSharedDependencies.cmake +++ b/cmake/macros/LinkSharedDependencies.cmake @@ -25,7 +25,7 @@ macro(LINK_SHARED_DEPENDENCIES) endif () # we've already linked our Qt modules, but we need to bubble them up to parents - list(APPEND ${TARGET_NAME}_LIBRARIES_TO_LINK "${${TARGET}_QT_MODULES_TO_LINK}") + list(APPEND ${TARGET_NAME}_LIBRARIES_TO_LINK "${${TARGET_NAME}_QT_MODULES_TO_LINK}") # set the property on this target so it can be retreived by targets linking to us set_target_properties(${TARGET_NAME} PROPERTIES DEPENDENCY_LIBRARIES "${${TARGET_NAME}_LIBRARIES_TO_LINK}") From 7b973453b42bab53ee0a2cef396f3f9a94a22de1 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 13:14:16 -0800 Subject: [PATCH 105/258] move TextureCache to library --- interface/CMakeLists.txt | 2 +- interface/src/Application.h | 4 +- interface/src/MetavoxelSystem.h | 2 +- interface/src/avatar/Avatar.cpp | 4 +- interface/src/renderer/GeometryCache.cpp | 2 +- interface/src/renderer/Model.h | 2 +- interface/src/ui/UpdateDialog.cpp | 2 +- interface/src/ui/overlays/BillboardOverlay.h | 3 +- libraries/render-utils/CMakeLists.txt | 46 +++++++++++++++++++ .../render-utils/src}/TextureCache.cpp | 0 .../render-utils/src}/TextureCache.h | 0 11 files changed, 59 insertions(+), 8 deletions(-) create mode 100644 libraries/render-utils/CMakeLists.txt rename {interface/src/renderer => libraries/render-utils/src}/TextureCache.cpp (100%) rename {interface/src/renderer => libraries/render-utils/src}/TextureCache.h (100%) diff --git a/interface/CMakeLists.txt b/interface/CMakeLists.txt index 38dd02c655..ffc401ba63 100644 --- a/interface/CMakeLists.txt +++ b/interface/CMakeLists.txt @@ -107,7 +107,7 @@ endif() add_executable(${TARGET_NAME} MACOSX_BUNDLE ${INTERFACE_SRCS} ${QM}) # link required hifi libraries -link_hifi_libraries(shared octree voxels gpu fbx metavoxels networking entities avatars audio animation script-engine physics) +link_hifi_libraries(shared octree voxels gpu fbx metavoxels networking entities avatars audio animation script-engine physics render-utils) # find any optional and required libraries find_package(ZLIB REQUIRED) diff --git a/interface/src/Application.h b/interface/src/Application.h index d4a681f060..5a693ac21e 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -15,6 +15,8 @@ #include #include +#include + #include #include #include @@ -37,6 +39,7 @@ #include #include #include +#include #include #include @@ -61,7 +64,6 @@ #include "renderer/DeferredLightingEffect.h" #include "renderer/GeometryCache.h" #include "renderer/GlowEffect.h" -#include "renderer/TextureCache.h" #include "scripting/ControllerScriptingInterface.h" #include "ui/BandwidthDialog.h" #include "ui/BandwidthMeter.h" diff --git a/interface/src/MetavoxelSystem.h b/interface/src/MetavoxelSystem.h index 2ebf7e1146..0c0f9b49b7 100644 --- a/interface/src/MetavoxelSystem.h +++ b/interface/src/MetavoxelSystem.h @@ -20,9 +20,9 @@ #include #include +#include #include "renderer/ProgramObject.h" -#include "renderer/TextureCache.h" class HeightfieldBaseLayerBatch; class HeightfieldSplatBatch; diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index 49a6f436df..39fc522852 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -11,6 +11,8 @@ #include +#include + #include #include @@ -25,6 +27,7 @@ #include #include #include +#include #include "Application.h" #include "Avatar.h" @@ -36,7 +39,6 @@ #include "Recorder.h" #include "world.h" #include "devices/OculusManager.h" -#include "renderer/TextureCache.h" #include "ui/TextRenderer.h" using namespace std; diff --git a/interface/src/renderer/GeometryCache.cpp b/interface/src/renderer/GeometryCache.cpp index 974a542b0e..4eae148259 100644 --- a/interface/src/renderer/GeometryCache.cpp +++ b/interface/src/renderer/GeometryCache.cpp @@ -19,9 +19,9 @@ #include #include +#include #include "GeometryCache.h" -#include "TextureCache.h" GeometryCache::GeometryCache() { } diff --git a/interface/src/renderer/Model.h b/interface/src/renderer/Model.h index 9b609de1d0..334730b23b 100644 --- a/interface/src/renderer/Model.h +++ b/interface/src/renderer/Model.h @@ -22,13 +22,13 @@ #include #include #include +#include #include "AnimationHandle.h" #include "GeometryCache.h" #include "InterfaceConfig.h" #include "JointState.h" #include "ProgramObject.h" -#include "TextureCache.h" class QScriptEngine; diff --git a/interface/src/ui/UpdateDialog.cpp b/interface/src/ui/UpdateDialog.cpp index 33024586be..bd02ca910a 100644 --- a/interface/src/ui/UpdateDialog.cpp +++ b/interface/src/ui/UpdateDialog.cpp @@ -8,10 +8,10 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#include "Application.h" // HACK ATTACK WARNING: for windows build to work, we need this ahead of QtGui #include #include "ui_updateDialog.h" +#include "Application.h" #include "UpdateDialog.h" diff --git a/interface/src/ui/overlays/BillboardOverlay.h b/interface/src/ui/overlays/BillboardOverlay.h index c095a544b7..dcb8ab8b0c 100644 --- a/interface/src/ui/overlays/BillboardOverlay.h +++ b/interface/src/ui/overlays/BillboardOverlay.h @@ -15,8 +15,9 @@ #include #include +#include + #include "Base3DOverlay.h" -#include "renderer/TextureCache.h" class BillboardOverlay : public Base3DOverlay { Q_OBJECT diff --git a/libraries/render-utils/CMakeLists.txt b/libraries/render-utils/CMakeLists.txt new file mode 100644 index 0000000000..dea83a12a4 --- /dev/null +++ b/libraries/render-utils/CMakeLists.txt @@ -0,0 +1,46 @@ +set(TARGET_NAME render-utils) + +# use setup_hifi_library macro to setup our project and link appropriate Qt modules +setup_hifi_library(Widgets OpenGL Network) + +include_glm() + +link_hifi_libraries(shared gpu) +if (APPLE) + # link in required OS X frameworks and include the right GL headers + find_library(OpenGL OpenGL) + + target_link_libraries(${TARGET_NAME} ${OpenGL}) + +else (APPLE) + find_package(OpenGL REQUIRED) + + if (${OPENGL_INCLUDE_DIR}) + include_directories(SYSTEM "${OPENGL_INCLUDE_DIR}") + endif () + + #target_link_libraries(${TARGET_NAME} "${OPENGL_LIBRARY}") + + # link target to external libraries + if (WIN32) + find_package(GLEW REQUIRED) + include_directories(${GLEW_INCLUDE_DIRS}) + + # we're using static GLEW, so define GLEW_STATIC + add_definitions(-DGLEW_STATIC) + + #target_link_libraries(${TARGET_NAME} "${GLEW_LIBRARIES}" "${NSIGHT_LIBRARIES}" opengl32.lib) + + # try to find the Nsight package and add it to the build if we find it + #find_package(NSIGHT) + #if (NSIGHT_FOUND) + # include_directories(${NSIGHT_INCLUDE_DIRS}) + # add_definitions(-DNSIGHT_FOUND) + # #target_link_libraries(${TARGET_NAME} "${NSIGHT_LIBRARIES}") + #endif () + + endif() +endif (APPLE) + +# call macro to link our dependencies and bubble them up via a property on our target +link_shared_dependencies() diff --git a/interface/src/renderer/TextureCache.cpp b/libraries/render-utils/src/TextureCache.cpp similarity index 100% rename from interface/src/renderer/TextureCache.cpp rename to libraries/render-utils/src/TextureCache.cpp diff --git a/interface/src/renderer/TextureCache.h b/libraries/render-utils/src/TextureCache.h similarity index 100% rename from interface/src/renderer/TextureCache.h rename to libraries/render-utils/src/TextureCache.h From ea6d6e9f7265048ec21376215869f87e11a71ddd Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 13:26:27 -0800 Subject: [PATCH 106/258] windows build hackery --- interface/src/ui/UpdateDialog.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/interface/src/ui/UpdateDialog.cpp b/interface/src/ui/UpdateDialog.cpp index bd02ca910a..4c75a10f1d 100644 --- a/interface/src/ui/UpdateDialog.cpp +++ b/interface/src/ui/UpdateDialog.cpp @@ -8,6 +8,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +#include + #include #include "ui_updateDialog.h" From dee8f69722587765f505965cb050b0ad8ee2f93b Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 13:33:47 -0800 Subject: [PATCH 107/258] windows build hackery --- interface/src/voxels/VoxelSystem.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/interface/src/voxels/VoxelSystem.cpp b/interface/src/voxels/VoxelSystem.cpp index 357bfe9c3e..61ec4d6e6c 100644 --- a/interface/src/voxels/VoxelSystem.cpp +++ b/interface/src/voxels/VoxelSystem.cpp @@ -14,6 +14,8 @@ #include // to load voxels from file #include // to load voxels from file +#include + #include #include #include @@ -23,7 +25,6 @@ #include #include "Application.h" -#include "InterfaceConfig.h" #include "Menu.h" #include "renderer/ProgramObject.h" #include "VoxelConstants.h" From 4d8d6d602a269679aae5bf73e41103f8986c58b4 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 15 Dec 2014 13:56:21 -0800 Subject: [PATCH 108/258] simplify the FindTBB module for set envs --- BUILD_LINUX.md | 8 +- BUILD_OSX.md | 2 +- BUILD_WIN.md | 6 - cmake/modules/FindTBB.cmake | 328 +++++++----------------------------- 4 files changed, 62 insertions(+), 282 deletions(-) diff --git a/BUILD_LINUX.md b/BUILD_LINUX.md index 7b6c8f2176..08945716ae 100644 --- a/BUILD_LINUX.md +++ b/BUILD_LINUX.md @@ -9,10 +9,4 @@ In general, as long as external dependencies are placed in OS standard locations ###Qt5 Dependencies Should you choose not to install Qt5 via a package manager that handles dependencies for you, you may be missing some Qt5 dependencies. On Ubuntu, for example, the following additional packages are required: - libasound2 libxmu-dev libxi-dev freeglut3-dev libasound2-dev libjack-dev - -###Intel Threading Building Blocks (TBB) - -Install Intel TBB from your package manager of choice, or from source (available at the [TBB Website](https://www.threadingbuildingblocks.org/)). - -You must run `tbbvars` before running cmake that the find module included with this project will be able to find the correct version of TBB. `tbbvars` is located in the 'bin' folder of your TBB install. \ No newline at end of file + libasound2 libxmu-dev libxi-dev freeglut3-dev libasound2-dev libjack-dev \ No newline at end of file diff --git a/BUILD_OSX.md b/BUILD_OSX.md index 1eeaed1c13..cd947f2af4 100644 --- a/BUILD_OSX.md +++ b/BUILD_OSX.md @@ -19,4 +19,4 @@ If Xcode is your editor of choice, you can ask CMake to generate Xcode project f After running cmake, you will have the make files or Xcode project file necessary to build all of the components. Open the hifi.xcodeproj file, choose ALL_BUILD from the Product > Scheme menu (or target drop down), and click Run. -If the build completes successfully, you will have built targets for all components located in the `build/${target_name}/Debug` directories. +If the build completes successfully, you will have built targets for all components located in the `build/${target_name}/Debug` directories. \ No newline at end of file diff --git a/BUILD_WIN.md b/BUILD_WIN.md index bf7d421715..b90396b757 100644 --- a/BUILD_WIN.md +++ b/BUILD_WIN.md @@ -95,12 +95,6 @@ To prevent these problems, install OpenSSL yourself. Download the following bina Install OpenSSL into the Windows system directory, to make sure that QT uses the version that you've just installed, and not some other version. -###Intel Threading Building Blocks (TBB) - -Download the stable release for Windows from the [Intel Threading Building Blocks website](https://www.threadingbuildingblocks.org/). By default, TBB will install to Program Files. You can choose to install it wherever you like, including %HIFI_LIB_DIR%. - -You must run `tbbvars.bat` before running cmake so that the find module included with this project will be able to find TBB no matter where you installed it. `tbbvars.bat` is located in the 'bin' folder of your TBB install. For a default installation on a 64-bit architechture, tbbvars can be found at `C:/Program Files (x86)/Intel/TBB/bin/tbbvars.bat`. - ###Zlib Download the compiled DLL from the [zlib website](http://www.zlib.net/). Extract to %HIFI_LIB_DIR%\zlib. diff --git a/cmake/modules/FindTBB.cmake b/cmake/modules/FindTBB.cmake index e5ca100391..c6c1890a09 100644 --- a/cmake/modules/FindTBB.cmake +++ b/cmake/modules/FindTBB.cmake @@ -1,283 +1,75 @@ -# Locate Intel Threading Building Blocks include paths and libraries -# FindTBB.cmake can be found at https://code.google.com/p/findtbb/ -# Written by Hannes Hofmann -# Improvements by Gino van den Bergen , -# Florian Uhlig , -# Jiri Marsik - -# The MIT License +# +# FindTBB.cmake +# +# Try to find the Intel Threading Building Blocks library # -# Copyright (c) 2011 Hannes Hofmann +# You can provide a TBB_ROOT_DIR which contains lib and include directories # -# 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: +# Once done this will define # -# The above copyright notice and this permission notice shall be included in -# all copies or substantial portions of the Software. +# TBB_FOUND - system was able to find TBB +# TBB_INCLUDE_DIRS - the TBB include directory +# TBB_LIBRARIES - link this to use TBB # -# 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. - -# GvdB: This module uses the environment variable TBB_ARCH_PLATFORM which defines architecture and compiler. -# e.g. "ia32/vc8" or "em64t/cc4.1.0_libc2.4_kernel2.6.16.21" -# TBB_ARCH_PLATFORM is set by the build script tbbvars[.bat|.sh|.csh], which can be found -# in the TBB installation directory (TBB_INSTALL_DIR). +# Created on 12/14/2014 by Stephen Birarda +# Copyright 2014 High Fidelity, Inc. # -# GvdB: Mac OS X distribution places libraries directly in lib directory. -# -# For backwards compatibility, you may explicitely set the CMake variables TBB_ARCHITECTURE and TBB_COMPILER. -# TBB_ARCHITECTURE [ ia32 | em64t | itanium ] -# which architecture to use -# TBB_COMPILER e.g. vc9 or cc3.2.3_libc2.3.2_kernel2.4.21 or cc4.0.1_os10.4.9 -# which compiler to use (detected automatically on Windows) +# Distributed under the Apache License, Version 2.0. +# See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +# -# This module respects -# TBB_INSTALL_DIR or $ENV{TBB21_INSTALL_DIR} or $ENV{TBB_INSTALL_DIR} +include("${MACRO_DIR}/HifiLibrarySearchHints.cmake") +hifi_library_search_hints("tbb") -# This module defines -# TBB_INCLUDE_DIRS, where to find task_scheduler_init.h, etc. -# TBB_LIBRARY_DIRS, where to find libtbb, libtbbmalloc -# TBB_DEBUG_LIBRARY_DIRS, where to find libtbb_debug, libtbbmalloc_debug -# TBB_INSTALL_DIR, the base TBB install directory -# TBB_LIBRARIES, the libraries to link against to use TBB. -# TBB_DEBUG_LIBRARIES, the libraries to link against to use TBB with debug symbols. -# TBB_FOUND, If false, don't try to use TBB. -# TBB_INTERFACE_VERSION, as defined in tbb/tbb_stddef.h +find_path(TBB_INCLUDE_DIRS tbb/tbb.h PATH_SUFFIXES include HINTS ${TBB_SEARCH_DIRS}) +set(_TBB_LIB_NAME "tbb") +set(_TBB_LIB_MALLOC_NAME "${_TBB_LIB_NAME}malloc") -if (WIN32) - # has em64t/vc8 em64t/vc9 - # has ia32/vc7.1 ia32/vc8 ia32/vc9 - set(_TBB_DEFAULT_INSTALL_DIR "C:/Program Files/Intel/TBB" "C:/Program Files (x86)/Intel/TBB") - set(_TBB_LIB_NAME "tbb") - set(_TBB_LIB_MALLOC_NAME "${_TBB_LIB_NAME}malloc") - set(_TBB_LIB_DEBUG_NAME "${_TBB_LIB_NAME}_debug") - set(_TBB_LIB_MALLOC_DEBUG_NAME "${_TBB_LIB_MALLOC_NAME}_debug") - if (MSVC71) - set (_TBB_COMPILER "vc7.1") - endif(MSVC71) - if (MSVC80) - set(_TBB_COMPILER "vc8") - endif(MSVC80) - if (MSVC90) - set(_TBB_COMPILER "vc9") - endif(MSVC90) - if(MSVC10) - set(_TBB_COMPILER "vc10") - endif(MSVC10) - # Todo: add other Windows compilers such as ICL. - set(_TBB_ARCHITECTURE ${TBB_ARCHITECTURE}) -endif (WIN32) +if (APPLE) + set(_TBB_LIB_DIR "lib/libc++") +elseif (UNIX) + if(CMAKE_SIZEOF_VOID_P EQUAL 8) + set(_TBB_ARCH_DIR "intel64") + else() + set(_TBB_ARCH_DIR "ia32") + endif() + + execute_process( + COMMAND ${CMAKE_C_COMPILER} -dumpversion + OUTPUT_VARIABLE GCC_VERSION + ) + + if (GCC_VERSION VERSION_GREATER 4.4 OR GCC_VERSION VERSION_EQUAL 4.4) + set(_TBB_LIB_DIR "${_TBB_ARCH_DIR}/gcc4.4") + elseif (GCC_VERSION VERSION_GREATER 4.1 OR GCC_VERSION VERSION_EQUAL 4.1) + set(_TBB_LIB_DIR "${_TBB_ARCH_DIR}/gcc4.1") + else () + message(FATAL_ERROR "Could not find a compatible version of Threading Building Blocks library for your compiler.") + endif () + +elseif (WIN32) + if (CMAKE_CL_64) + set(_TBB_ARCH_DIR "intel64") + else() + set(_TBB_ARCH_DIR "ia32") + endif() + + set(_TBB_LIB_DIR "${_TBB_ARCH_DIR}/vc12") +endif () -if (UNIX) - if (APPLE) - # MAC - set(_TBB_DEFAULT_INSTALL_DIR "/Library/Frameworks/Intel_TBB.framework/Versions") - # libs: libtbb.dylib, libtbbmalloc.dylib, *_debug - set(_TBB_LIB_NAME "tbb") - set(_TBB_LIB_MALLOC_NAME "${_TBB_LIB_NAME}malloc") - set(_TBB_LIB_DEBUG_NAME "${_TBB_LIB_NAME}_debug") - set(_TBB_LIB_MALLOC_DEBUG_NAME "${_TBB_LIB_MALLOC_NAME}_debug") - # default flavor on apple: ia32/cc4.0.1_os10.4.9 - # Jiri: There is no reason to presume there is only one flavor and - # that user's setting of variables should be ignored. - if(NOT TBB_COMPILER) - set(_TBB_COMPILER "cc4.0.1_os10.4.9") - elseif (NOT TBB_COMPILER) - set(_TBB_COMPILER ${TBB_COMPILER}) - endif(NOT TBB_COMPILER) - if(NOT TBB_ARCHITECTURE) - set(_TBB_ARCHITECTURE "ia32") - elseif(NOT TBB_ARCHITECTURE) - set(_TBB_ARCHITECTURE ${TBB_ARCHITECTURE}) - endif(NOT TBB_ARCHITECTURE) - else (APPLE) - # LINUX - set(_TBB_DEFAULT_INSTALL_DIR "/opt/intel/tbb" "/usr/local/include" "/usr/include") - set(_TBB_LIB_NAME "tbb") - set(_TBB_LIB_MALLOC_NAME "${_TBB_LIB_NAME}malloc") - set(_TBB_LIB_DEBUG_NAME "${_TBB_LIB_NAME}_debug") - set(_TBB_LIB_MALLOC_DEBUG_NAME "${_TBB_LIB_MALLOC_NAME}_debug") - # has em64t/cc3.2.3_libc2.3.2_kernel2.4.21 em64t/cc3.3.3_libc2.3.3_kernel2.6.5 em64t/cc3.4.3_libc2.3.4_kernel2.6.9 em64t/cc4.1.0_libc2.4_kernel2.6.16.21 - # has ia32/* - # has itanium/* - set(_TBB_COMPILER ${TBB_COMPILER}) - set(_TBB_ARCHITECTURE ${TBB_ARCHITECTURE}) - endif (APPLE) -endif (UNIX) +find_library(TBB_LIBRARY_DEBUG NAMES ${_TBB_LIB_NAME}_debug PATH_SUFFIXES ${_TBB_LIB_DIR} HINTS ${TBB_SEARCH_DIRS}) +find_library(TBB_LIBRARY_RELEASE NAMES ${_TBB_LIB_NAME} PATH_SUFFIXES ${_TBB_LIB_DIR} HINTS ${TBB_SEARCH_DIRS}) -if (CMAKE_SYSTEM MATCHES "SunOS.*") -# SUN -# not yet supported -# has em64t/cc3.4.3_kernel5.10 -# has ia32/* -endif (CMAKE_SYSTEM MATCHES "SunOS.*") +find_library(TBB_MALLOC_LIBRARY_DEBUG NAMES ${_TBB_LIB_MALLOC_NAME}_debug PATH_SUFFIXES ${_TBB_LIB_DIR} HINTS ${TBB_SEARCH_DIRS}) +find_library(TBB_MALLOC_LIBRARY_RELEASE NAMES ${_TBB_LIB_MALLOC_NAME} PATH_SUFFIXES ${_TBB_LIB_DIR} HINTS ${TBB_SEARCH_DIRS}) +include(SelectLibraryConfigurations) +include(FindPackageHandleStandardArgs) -#-- Clear the public variables -set (TBB_FOUND "NO") +select_library_configurations(TBB) +select_library_configurations(TBB_MALLOC) +find_package_handle_standard_args(TBB DEFAULT_MSG TBB_LIBRARY TBB_MALLOC_LIBRARY TBB_INCLUDE_DIRS) -#-- Find TBB install dir and set ${_TBB_INSTALL_DIR} and cached ${TBB_INSTALL_DIR} -# first: use CMake variable TBB_INSTALL_DIR -if (TBB_INSTALL_DIR) - set (_TBB_INSTALL_DIR ${TBB_INSTALL_DIR}) -endif (TBB_INSTALL_DIR) -# second: use environment variable -if (NOT _TBB_INSTALL_DIR) - if (NOT "$ENV{TBB_INSTALL_DIR}" STREQUAL "") - set (_TBB_INSTALL_DIR $ENV{TBB_INSTALL_DIR}) - endif (NOT "$ENV{TBB_INSTALL_DIR}" STREQUAL "") - # Intel recommends setting TBB21_INSTALL_DIR - if (NOT "$ENV{TBB21_INSTALL_DIR}" STREQUAL "") - set (_TBB_INSTALL_DIR $ENV{TBB21_INSTALL_DIR}) - endif (NOT "$ENV{TBB21_INSTALL_DIR}" STREQUAL "") - if (NOT "$ENV{TBB22_INSTALL_DIR}" STREQUAL "") - set (_TBB_INSTALL_DIR $ENV{TBB22_INSTALL_DIR}) - endif (NOT "$ENV{TBB22_INSTALL_DIR}" STREQUAL "") - if (NOT "$ENV{TBB30_INSTALL_DIR}" STREQUAL "") - set (_TBB_INSTALL_DIR $ENV{TBB30_INSTALL_DIR}) - endif (NOT "$ENV{TBB30_INSTALL_DIR}" STREQUAL "") -endif (NOT _TBB_INSTALL_DIR) -# third: try to find path automatically -if (NOT _TBB_INSTALL_DIR) - if (_TBB_DEFAULT_INSTALL_DIR) - set (_TBB_INSTALL_DIR ${_TBB_DEFAULT_INSTALL_DIR}) - endif (_TBB_DEFAULT_INSTALL_DIR) -endif (NOT _TBB_INSTALL_DIR) -# sanity check -if (NOT _TBB_INSTALL_DIR) - message ("ERROR: Unable to find Intel TBB install directory. ${_TBB_INSTALL_DIR}") -else (NOT _TBB_INSTALL_DIR) -# finally: set the cached CMake variable TBB_INSTALL_DIR -if (NOT TBB_INSTALL_DIR) - set (TBB_INSTALL_DIR ${_TBB_INSTALL_DIR} CACHE PATH "Intel TBB install directory") - mark_as_advanced(TBB_INSTALL_DIR) -endif (NOT TBB_INSTALL_DIR) - - -#-- A macro to rewrite the paths of the library. This is necessary, because -# find_library() always found the em64t/vc9 version of the TBB libs -macro(TBB_CORRECT_LIB_DIR var_name) -# if (NOT "${_TBB_ARCHITECTURE}" STREQUAL "em64t") - string(REPLACE em64t "${_TBB_ARCHITECTURE}" ${var_name} ${${var_name}}) -# endif (NOT "${_TBB_ARCHITECTURE}" STREQUAL "em64t") - string(REPLACE ia32 "${_TBB_ARCHITECTURE}" ${var_name} ${${var_name}}) - string(REPLACE vc7.1 "${_TBB_COMPILER}" ${var_name} ${${var_name}}) - string(REPLACE vc8 "${_TBB_COMPILER}" ${var_name} ${${var_name}}) - string(REPLACE vc9 "${_TBB_COMPILER}" ${var_name} ${${var_name}}) - string(REPLACE vc10 "${_TBB_COMPILER}" ${var_name} ${${var_name}}) -endmacro(TBB_CORRECT_LIB_DIR var_content) - - -#-- Look for include directory and set ${TBB_INCLUDE_DIR} -set (TBB_INC_SEARCH_DIR ${_TBB_INSTALL_DIR}/include) -# Jiri: tbbvars now sets the CPATH environment variable to the directory -# containing the headers. -find_path(TBB_INCLUDE_DIR - tbb/task_scheduler_init.h - PATHS ${TBB_INC_SEARCH_DIR} ENV CPATH -) -mark_as_advanced(TBB_INCLUDE_DIR) - - -#-- Look for libraries -# GvdB: $ENV{TBB_ARCH_PLATFORM} is set by the build script tbbvars[.bat|.sh|.csh] -if (NOT $ENV{TBB_ARCH_PLATFORM} STREQUAL "") - set (_TBB_LIBRARY_DIR - ${_TBB_INSTALL_DIR}/lib/$ENV{TBB_ARCH_PLATFORM} - ${_TBB_INSTALL_DIR}/$ENV{TBB_ARCH_PLATFORM}/lib - ) -endif (NOT $ENV{TBB_ARCH_PLATFORM} STREQUAL "") -# Jiri: This block isn't mutually exclusive with the previous one -# (hence no else), instead I test if the user really specified -# the variables in question. -if ((NOT ${TBB_ARCHITECTURE} STREQUAL "") AND (NOT ${TBB_COMPILER} STREQUAL "")) - # HH: deprecated - message(STATUS "[Warning] FindTBB.cmake: The use of TBB_ARCHITECTURE and TBB_COMPILER is deprecated and may not be supported in future versions. Please set \$ENV{TBB_ARCH_PLATFORM} (using tbbvars.[bat|csh|sh]).") - # Jiri: It doesn't hurt to look in more places, so I store the hints from - # ENV{TBB_ARCH_PLATFORM} and the TBB_ARCHITECTURE and TBB_COMPILER - # variables and search them both. - set (_TBB_LIBRARY_DIR "${_TBB_INSTALL_DIR}/${_TBB_ARCHITECTURE}/${_TBB_COMPILER}/lib" ${_TBB_LIBRARY_DIR}) -endif ((NOT ${TBB_ARCHITECTURE} STREQUAL "") AND (NOT ${TBB_COMPILER} STREQUAL "")) - -# GvdB: Mac OS X distribution places libraries directly in lib directory. -list(APPEND _TBB_LIBRARY_DIR ${_TBB_INSTALL_DIR}/lib) - -# Jiri: No reason not to check the default paths. From recent versions, -# tbbvars has started exporting the LIBRARY_PATH and LD_LIBRARY_PATH -# variables, which now point to the directories of the lib files. -# It all makes more sense to use the ${_TBB_LIBRARY_DIR} as a HINTS -# argument instead of the implicit PATHS as it isn't hard-coded -# but computed by system introspection. Searching the LIBRARY_PATH -# and LD_LIBRARY_PATH environment variables is now even more important -# that tbbvars doesn't export TBB_ARCH_PLATFORM and it facilitates -# the use of TBB built from sources. -find_library(TBB_LIBRARY ${_TBB_LIB_NAME} HINTS ${_TBB_LIBRARY_DIR} - PATHS ENV LIBRARY_PATH ENV LD_LIBRARY_PATH) -find_library(TBB_MALLOC_LIBRARY ${_TBB_LIB_MALLOC_NAME} HINTS ${_TBB_LIBRARY_DIR} - PATHS ENV LIBRARY_PATH ENV LD_LIBRARY_PATH) - -#Extract path from TBB_LIBRARY name -get_filename_component(TBB_LIBRARY_DIR ${TBB_LIBRARY} PATH) - -#TBB_CORRECT_LIB_DIR(TBB_LIBRARY) -#TBB_CORRECT_LIB_DIR(TBB_MALLOC_LIBRARY) -mark_as_advanced(TBB_LIBRARY TBB_MALLOC_LIBRARY) - -#-- Look for debug libraries -# Jiri: Changed the same way as for the release libraries. -find_library(TBB_LIBRARY_DEBUG ${_TBB_LIB_DEBUG_NAME} HINTS ${_TBB_LIBRARY_DIR} - PATHS ENV LIBRARY_PATH ENV LD_LIBRARY_PATH) -find_library(TBB_MALLOC_LIBRARY_DEBUG ${_TBB_LIB_MALLOC_DEBUG_NAME} HINTS ${_TBB_LIBRARY_DIR} - PATHS ENV LIBRARY_PATH ENV LD_LIBRARY_PATH) - -# Jiri: Self-built TBB stores the debug libraries in a separate directory. -# Extract path from TBB_LIBRARY_DEBUG name -get_filename_component(TBB_LIBRARY_DEBUG_DIR ${TBB_LIBRARY_DEBUG} PATH) - -#TBB_CORRECT_LIB_DIR(TBB_LIBRARY_DEBUG) -#TBB_CORRECT_LIB_DIR(TBB_MALLOC_LIBRARY_DEBUG) -mark_as_advanced(TBB_LIBRARY_DEBUG TBB_MALLOC_LIBRARY_DEBUG) - - -if (TBB_INCLUDE_DIR) - if (TBB_LIBRARY) - set (TBB_FOUND "YES") - set (TBB_LIBRARIES ${TBB_LIBRARY} ${TBB_MALLOC_LIBRARY} ${TBB_LIBRARIES}) - set (TBB_DEBUG_LIBRARIES ${TBB_LIBRARY_DEBUG} ${TBB_MALLOC_LIBRARY_DEBUG} ${TBB_DEBUG_LIBRARIES}) - set (TBB_INCLUDE_DIRS ${TBB_INCLUDE_DIR} CACHE PATH "TBB include directory" FORCE) - set (TBB_LIBRARY_DIRS ${TBB_LIBRARY_DIR} CACHE PATH "TBB library directory" FORCE) - # Jiri: Self-built TBB stores the debug libraries in a separate directory. - set (TBB_DEBUG_LIBRARY_DIRS ${TBB_LIBRARY_DEBUG_DIR} CACHE PATH "TBB debug library directory" FORCE) - mark_as_advanced(TBB_INCLUDE_DIRS TBB_LIBRARY_DIRS TBB_DEBUG_LIBRARY_DIRS TBB_LIBRARIES TBB_DEBUG_LIBRARIES) - message(STATUS "Found Intel TBB") - endif (TBB_LIBRARY) -endif (TBB_INCLUDE_DIR) - -if (NOT TBB_FOUND) - message("ERROR: Intel TBB NOT found!") - message(STATUS "Looked for Threading Building Blocks in ${_TBB_INSTALL_DIR}") - # do only throw fatal, if this pkg is REQUIRED - if (TBB_FIND_REQUIRED) - message(FATAL_ERROR "Could NOT find TBB library.") - endif (TBB_FIND_REQUIRED) -endif (NOT TBB_FOUND) - -endif (NOT _TBB_INSTALL_DIR) - -if (TBB_FOUND) - set(TBB_INTERFACE_VERSION 0) - FILE(READ "${TBB_INCLUDE_DIRS}/tbb/tbb_stddef.h" _TBB_VERSION_CONTENTS) - STRING(REGEX REPLACE ".*#define TBB_INTERFACE_VERSION ([0-9]+).*" "\\1" TBB_INTERFACE_VERSION "${_TBB_VERSION_CONTENTS}") - set(TBB_INTERFACE_VERSION "${TBB_INTERFACE_VERSION}") -endif (TBB_FOUND) +set(TBB_LIBRARIES ${TBB_LIBRARY} ${TBB_MALLOC_LIBRARY}) From e8ea45efdef2820f32c775a3b7caf3848a76639a Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 15 Dec 2014 13:59:51 -0800 Subject: [PATCH 109/258] clarify TBB find for windows --- BUILD_WIN.md | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/BUILD_WIN.md b/BUILD_WIN.md index b90396b757..ad143ef56a 100644 --- a/BUILD_WIN.md +++ b/BUILD_WIN.md @@ -95,6 +95,12 @@ To prevent these problems, install OpenSSL yourself. Download the following bina Install OpenSSL into the Windows system directory, to make sure that QT uses the version that you've just installed, and not some other version. +###Intel Threading Building Blocks (TBB) + +Download the zip from the [TBB website](https://www.threadingbuildingblocks.org/). + +We recommend you extract it to %HIFI_LIB_DIR%\tbb. This will help our FindTBB cmake module find what it needs. You can place it wherever you like on your machine if you specify TBB_ROOT_DIR as an environment variable or a variable passed when cmake is run. + ###Zlib Download the compiled DLL from the [zlib website](http://www.zlib.net/). Extract to %HIFI_LIB_DIR%\zlib. From 49cacd85bd3abdce2524027ad83382bfbc110bff Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 14:00:41 -0800 Subject: [PATCH 110/258] move GeometryCache to library --- interface/src/Application.h | 2 +- interface/src/renderer/Model.h | 4 ++-- libraries/render-utils/CMakeLists.txt | 2 +- .../renderer => libraries/render-utils/src}/GeometryCache.cpp | 2 +- .../renderer => libraries/render-utils/src}/GeometryCache.h | 0 5 files changed, 5 insertions(+), 5 deletions(-) rename {interface/src/renderer => libraries/render-utils/src}/GeometryCache.cpp (99%) rename {interface/src/renderer => libraries/render-utils/src}/GeometryCache.h (100%) diff --git a/interface/src/Application.h b/interface/src/Application.h index 5a693ac21e..64ef0970d7 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -34,6 +34,7 @@ #include #include +#include #include #include #include @@ -62,7 +63,6 @@ #include "entities/EntityTreeRenderer.h" #include "renderer/AmbientOcclusionEffect.h" #include "renderer/DeferredLightingEffect.h" -#include "renderer/GeometryCache.h" #include "renderer/GlowEffect.h" #include "scripting/ControllerScriptingInterface.h" #include "ui/BandwidthDialog.h" diff --git a/interface/src/renderer/Model.h b/interface/src/renderer/Model.h index 334730b23b..c061bd85ac 100644 --- a/interface/src/renderer/Model.h +++ b/interface/src/renderer/Model.h @@ -16,16 +16,16 @@ #include #include -#include "Transform.h" #include #include #include +#include #include #include #include +#include #include "AnimationHandle.h" -#include "GeometryCache.h" #include "InterfaceConfig.h" #include "JointState.h" #include "ProgramObject.h" diff --git a/libraries/render-utils/CMakeLists.txt b/libraries/render-utils/CMakeLists.txt index dea83a12a4..bde26ea5ca 100644 --- a/libraries/render-utils/CMakeLists.txt +++ b/libraries/render-utils/CMakeLists.txt @@ -1,7 +1,7 @@ set(TARGET_NAME render-utils) # use setup_hifi_library macro to setup our project and link appropriate Qt modules -setup_hifi_library(Widgets OpenGL Network) +setup_hifi_library(Widgets OpenGL Network Script) include_glm() diff --git a/interface/src/renderer/GeometryCache.cpp b/libraries/render-utils/src/GeometryCache.cpp similarity index 99% rename from interface/src/renderer/GeometryCache.cpp rename to libraries/render-utils/src/GeometryCache.cpp index 4eae148259..54239f1678 100644 --- a/interface/src/renderer/GeometryCache.cpp +++ b/libraries/render-utils/src/GeometryCache.cpp @@ -19,8 +19,8 @@ #include #include -#include +#include "TextureCache.h" #include "GeometryCache.h" GeometryCache::GeometryCache() { diff --git a/interface/src/renderer/GeometryCache.h b/libraries/render-utils/src/GeometryCache.h similarity index 100% rename from interface/src/renderer/GeometryCache.h rename to libraries/render-utils/src/GeometryCache.h From f63aa44d019ab38866192625a92fb4a2c952970c Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 15 Dec 2014 14:02:55 -0800 Subject: [PATCH 111/258] add lib to lib dirs for win and linux --- cmake/modules/FindTBB.cmake | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cmake/modules/FindTBB.cmake b/cmake/modules/FindTBB.cmake index c6c1890a09..bce667b7d4 100644 --- a/cmake/modules/FindTBB.cmake +++ b/cmake/modules/FindTBB.cmake @@ -41,9 +41,9 @@ elseif (UNIX) ) if (GCC_VERSION VERSION_GREATER 4.4 OR GCC_VERSION VERSION_EQUAL 4.4) - set(_TBB_LIB_DIR "${_TBB_ARCH_DIR}/gcc4.4") + set(_TBB_LIB_DIR "lib/${_TBB_ARCH_DIR}/gcc4.4") elseif (GCC_VERSION VERSION_GREATER 4.1 OR GCC_VERSION VERSION_EQUAL 4.1) - set(_TBB_LIB_DIR "${_TBB_ARCH_DIR}/gcc4.1") + set(_TBB_LIB_DIR "lib/${_TBB_ARCH_DIR}/gcc4.1") else () message(FATAL_ERROR "Could not find a compatible version of Threading Building Blocks library for your compiler.") endif () @@ -55,7 +55,7 @@ elseif (WIN32) set(_TBB_ARCH_DIR "ia32") endif() - set(_TBB_LIB_DIR "${_TBB_ARCH_DIR}/vc12") + set(_TBB_LIB_DIR "lib/${_TBB_ARCH_DIR}/vc12") endif () find_library(TBB_LIBRARY_DEBUG NAMES ${_TBB_LIB_NAME}_debug PATH_SUFFIXES ${_TBB_LIB_DIR} HINTS ${TBB_SEARCH_DIRS}) From a3cc578fd15cd752689aab985c8141c137e20220 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Mon, 15 Dec 2014 14:08:23 -0800 Subject: [PATCH 112/258] use libc++ for C++11 in APPLE builds --- CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index f6e3f5c42c..7a6118bb87 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -49,6 +49,7 @@ endif() if (APPLE) set(CMAKE_XCODE_ATTRIBUTE_CLANG_CXX_LANGUAGE_STANDARD "c++0x") set(CMAKE_XCODE_ATTRIBUTE_CLANG_CXX_LIBRARY "libc++") + set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --stdlib=libc++") endif () if (NOT QT_CMAKE_PREFIX_PATH) From df7e115556357717cf449fa37a91c97df54fb059 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 14:21:22 -0800 Subject: [PATCH 113/258] move ProgramObject to libraries --- interface/src/Application.cpp | 2 +- interface/src/Environment.cpp | 2 +- interface/src/MetavoxelSystem.h | 3 +-- interface/src/avatar/Hand.cpp | 2 +- interface/src/devices/OculusManager.h | 3 ++- interface/src/renderer/AmbientOcclusionEffect.cpp | 2 +- interface/src/renderer/DeferredLightingEffect.h | 3 +-- interface/src/renderer/GlowEffect.cpp | 2 +- interface/src/renderer/Model.h | 2 +- interface/src/starfield/Config.h | 3 ++- interface/src/ui/MetavoxelEditor.h | 3 ++- interface/src/ui/overlays/Grid3DOverlay.h | 4 ++-- interface/src/voxels/VoxelSystem.cpp | 2 +- .../renderer => libraries/render-utils/src}/ProgramObject.cpp | 3 ++- .../renderer => libraries/render-utils/src}/ProgramObject.h | 0 15 files changed, 19 insertions(+), 17 deletions(-) rename {interface/src/renderer => libraries/render-utils/src}/ProgramObject.cpp (99%) rename {interface/src/renderer => libraries/render-utils/src}/ProgramObject.h (100%) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 766424ef4b..990f05d0de 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -66,6 +66,7 @@ #include #include #include +#include #include #include #include @@ -85,7 +86,6 @@ #include "devices/TV3DManager.h" #include "devices/Visage.h" -#include "renderer/ProgramObject.h" #include "gpu/Batch.h" #include "gpu/GLBackend.h" diff --git a/interface/src/Environment.cpp b/interface/src/Environment.cpp index fa8f18ac3f..c482095494 100644 --- a/interface/src/Environment.cpp +++ b/interface/src/Environment.cpp @@ -17,11 +17,11 @@ #include #include +#include #include #include "Application.h" #include "Camera.h" -#include "renderer/ProgramObject.h" #include "world.h" #include "Environment.h" diff --git a/interface/src/MetavoxelSystem.h b/interface/src/MetavoxelSystem.h index 0c0f9b49b7..a21cd2c1a4 100644 --- a/interface/src/MetavoxelSystem.h +++ b/interface/src/MetavoxelSystem.h @@ -20,10 +20,9 @@ #include #include +#include #include -#include "renderer/ProgramObject.h" - class HeightfieldBaseLayerBatch; class HeightfieldSplatBatch; class HermiteBatch; diff --git a/interface/src/avatar/Hand.cpp b/interface/src/avatar/Hand.cpp index 9d1ee52fde..9d7626266d 100644 --- a/interface/src/avatar/Hand.cpp +++ b/interface/src/avatar/Hand.cpp @@ -13,13 +13,13 @@ #include #include +#include #include "Application.h" #include "Avatar.h" #include "Hand.h" #include "Menu.h" #include "Util.h" -#include "renderer/ProgramObject.h" using namespace std; diff --git a/interface/src/devices/OculusManager.h b/interface/src/devices/OculusManager.h index 2e0354f61a..d9700d9530 100644 --- a/interface/src/devices/OculusManager.h +++ b/interface/src/devices/OculusManager.h @@ -17,7 +17,8 @@ #include #endif -#include "renderer/ProgramObject.h" +#include + #include "ui/overlays/Text3DOverlay.h" const float DEFAULT_OCULUS_UI_ANGULAR_SIZE = 72.0f; diff --git a/interface/src/renderer/AmbientOcclusionEffect.cpp b/interface/src/renderer/AmbientOcclusionEffect.cpp index 3354f715cb..415b850abd 100644 --- a/interface/src/renderer/AmbientOcclusionEffect.cpp +++ b/interface/src/renderer/AmbientOcclusionEffect.cpp @@ -16,10 +16,10 @@ #include +#include #include #include "Application.h" -#include "ProgramObject.h" #include "RenderUtil.h" #include "AmbientOcclusionEffect.h" diff --git a/interface/src/renderer/DeferredLightingEffect.h b/interface/src/renderer/DeferredLightingEffect.h index ce8b2b9759..effcea27d2 100644 --- a/interface/src/renderer/DeferredLightingEffect.h +++ b/interface/src/renderer/DeferredLightingEffect.h @@ -14,10 +14,9 @@ #include +#include #include -#include "ProgramObject.h" - class PostLightingRenderable; /// Handles deferred lighting for the bits that require it (voxels, metavoxels...) diff --git a/interface/src/renderer/GlowEffect.cpp b/interface/src/renderer/GlowEffect.cpp index b6896eeaad..77d002dc89 100644 --- a/interface/src/renderer/GlowEffect.cpp +++ b/interface/src/renderer/GlowEffect.cpp @@ -15,10 +15,10 @@ #include #include +#include #include "Application.h" #include "GlowEffect.h" -#include "ProgramObject.h" #include "RenderUtil.h" GlowEffect::GlowEffect() diff --git a/interface/src/renderer/Model.h b/interface/src/renderer/Model.h index c061bd85ac..1f0a571872 100644 --- a/interface/src/renderer/Model.h +++ b/interface/src/renderer/Model.h @@ -22,13 +22,13 @@ #include #include #include +#include #include #include #include "AnimationHandle.h" #include "InterfaceConfig.h" #include "JointState.h" -#include "ProgramObject.h" class QScriptEngine; diff --git a/interface/src/starfield/Config.h b/interface/src/starfield/Config.h index 7777c5207b..00f827dad7 100644 --- a/interface/src/starfield/Config.h +++ b/interface/src/starfield/Config.h @@ -13,7 +13,6 @@ #define hifi_Config_h #include "InterfaceConfig.h" -#include "renderer/ProgramObject.h" #include #include @@ -35,6 +34,8 @@ #include #include +#include + #include "AngleUtil.h" #include "Radix2InplaceSort.h" #include "Radix2IntegerScanner.h" diff --git a/interface/src/ui/MetavoxelEditor.h b/interface/src/ui/MetavoxelEditor.h index c154d7bc59..391b01270a 100644 --- a/interface/src/ui/MetavoxelEditor.h +++ b/interface/src/ui/MetavoxelEditor.h @@ -15,8 +15,9 @@ #include #include +#include + #include "MetavoxelSystem.h" -#include "renderer/ProgramObject.h" class QColorEditor; class QComboBox; diff --git a/interface/src/ui/overlays/Grid3DOverlay.h b/interface/src/ui/overlays/Grid3DOverlay.h index b162ff3d74..d6c85a10ee 100644 --- a/interface/src/ui/overlays/Grid3DOverlay.h +++ b/interface/src/ui/overlays/Grid3DOverlay.h @@ -18,12 +18,12 @@ #include #include + +#include #include #include "Base3DOverlay.h" -#include "renderer/ProgramObject.h" - class Grid3DOverlay : public Base3DOverlay { Q_OBJECT diff --git a/interface/src/voxels/VoxelSystem.cpp b/interface/src/voxels/VoxelSystem.cpp index 61ec4d6e6c..064cead160 100644 --- a/interface/src/voxels/VoxelSystem.cpp +++ b/interface/src/voxels/VoxelSystem.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include #include @@ -26,7 +27,6 @@ #include "Application.h" #include "Menu.h" -#include "renderer/ProgramObject.h" #include "VoxelConstants.h" #include "VoxelSystem.h" diff --git a/interface/src/renderer/ProgramObject.cpp b/libraries/render-utils/src/ProgramObject.cpp similarity index 99% rename from interface/src/renderer/ProgramObject.cpp rename to libraries/render-utils/src/ProgramObject.cpp index ff2b1cc11e..56fd48bff7 100644 --- a/interface/src/renderer/ProgramObject.cpp +++ b/libraries/render-utils/src/ProgramObject.cpp @@ -9,9 +9,10 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#include "ProgramObject.h" #include +#include "ProgramObject.h" + ProgramObject::ProgramObject(QObject* parent) : QGLShaderProgram(parent) { } diff --git a/interface/src/renderer/ProgramObject.h b/libraries/render-utils/src/ProgramObject.h similarity index 100% rename from interface/src/renderer/ProgramObject.h rename to libraries/render-utils/src/ProgramObject.h From f802e99a24c89c34a5003caf7c90625019adff59 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 14:32:33 -0800 Subject: [PATCH 114/258] windows build hackery --- interface/src/renderer/Model.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/interface/src/renderer/Model.h b/interface/src/renderer/Model.h index 1f0a571872..c79a6c2efd 100644 --- a/interface/src/renderer/Model.h +++ b/interface/src/renderer/Model.h @@ -12,6 +12,8 @@ #ifndef hifi_Model_h #define hifi_Model_h +#include + #include #include #include @@ -27,7 +29,6 @@ #include #include "AnimationHandle.h" -#include "InterfaceConfig.h" #include "JointState.h" class QScriptEngine; From bc78beb05fcea9ce536a0fabc5c88078cbb12439 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 14:41:15 -0800 Subject: [PATCH 115/258] windows build hackery --- interface/src/avatar/ModelReferential.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/interface/src/avatar/ModelReferential.cpp b/interface/src/avatar/ModelReferential.cpp index df6e272da7..d37879c6e1 100644 --- a/interface/src/avatar/ModelReferential.cpp +++ b/interface/src/avatar/ModelReferential.cpp @@ -9,6 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +#include // hack to get windows to build + #include #include From 0c14b0f8fc9acfbc6ce68a139b149d9f6dbd8f1b Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 14:47:26 -0800 Subject: [PATCH 116/258] windows build hackery --- interface/src/avatar/Hand.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/interface/src/avatar/Hand.cpp b/interface/src/avatar/Hand.cpp index 9d7626266d..91d59ae2fa 100644 --- a/interface/src/avatar/Hand.cpp +++ b/interface/src/avatar/Hand.cpp @@ -8,6 +8,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +#include // hack to get windows to build + #include #include From 753dc07cdd61039ad2d87ef78002d95e9f3b605a Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 14:58:47 -0800 Subject: [PATCH 117/258] cleanup windows hackery --- interface/src/avatar/ModelReferential.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/interface/src/avatar/ModelReferential.cpp b/interface/src/avatar/ModelReferential.cpp index d37879c6e1..df6e272da7 100644 --- a/interface/src/avatar/ModelReferential.cpp +++ b/interface/src/avatar/ModelReferential.cpp @@ -9,8 +9,6 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#include // hack to get windows to build - #include #include From bfcc78c57d7fa4a9c19f514c079e5b05bcda6f06 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 15:20:18 -0800 Subject: [PATCH 118/258] replaced Application::resourcesPath() with PathUtils::resourcesPath() --- interface/src/Application.cpp | 16 ++--- interface/src/Application.h | 1 - interface/src/Audio.cpp | 7 +- interface/src/Environment.cpp | 3 +- interface/src/Menu.cpp | 3 +- interface/src/MetavoxelSystem.cpp | 21 +++--- interface/src/avatar/Avatar.cpp | 5 +- interface/src/devices/OculusManager.cpp | 5 +- interface/src/devices/Visage.cpp | 7 +- .../src/renderer/AmbientOcclusionEffect.cpp | 9 +-- .../src/renderer/DeferredLightingEffect.cpp | 10 +-- interface/src/renderer/GlowEffect.cpp | 3 +- interface/src/renderer/Model.cpp | 65 ++++++++++--------- interface/src/ui/AddressBarDialog.cpp | 10 +-- interface/src/ui/ApplicationOverlay.cpp | 6 +- interface/src/ui/ChatWindow.cpp | 7 +- interface/src/ui/FramelessDialog.cpp | 8 ++- interface/src/ui/InfoView.cpp | 9 ++- interface/src/ui/JSConsole.cpp | 9 +-- interface/src/ui/LogDialog.cpp | 6 +- interface/src/ui/LoginDialog.cpp | 7 +- interface/src/ui/MetavoxelEditor.cpp | 3 +- interface/src/ui/RearMirrorTools.cpp | 11 ++-- interface/src/ui/RunningScriptsWidget.cpp | 4 +- interface/src/ui/VoxelImportDialog.cpp | 22 ++++--- interface/src/ui/overlays/Grid3DOverlay.cpp | 5 +- interface/src/voxels/VoxelSystem.cpp | 9 +-- libraries/shared/src/PathUtils.cpp | 25 +++++++ libraries/shared/src/PathUtils.h | 22 +++++++ 29 files changed, 194 insertions(+), 124 deletions(-) create mode 100644 libraries/shared/src/PathUtils.cpp create mode 100644 libraries/shared/src/PathUtils.h diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 990f05d0de..76247d1d9d 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -65,6 +65,7 @@ #include #include #include +#include #include #include #include @@ -133,15 +134,6 @@ void messageHandler(QtMsgType type, const QMessageLogContext& context, const QSt } } -QString& Application::resourcesPath() { -#ifdef Q_OS_MAC - static QString staticResourcePath = QCoreApplication::applicationDirPath() + "/../Resources/"; -#else - static QString staticResourcePath = QCoreApplication::applicationDirPath() + "/resources/"; -#endif - return staticResourcePath; -} - Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) : QApplication(argc, argv), _window(new MainWindow(desktop())), @@ -195,7 +187,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) : _aboutToQuit(false) { // read the ApplicationInfo.ini file for Name/Version/Domain information - QSettings applicationInfo(Application::resourcesPath() + "info/ApplicationInfo.ini", QSettings::IniFormat); + QSettings applicationInfo(PathUtils::resourcesPath() + "info/ApplicationInfo.ini", QSettings::IniFormat); // set the associated application properties applicationInfo.beginGroup("INFO"); @@ -213,7 +205,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) : _applicationStartupTime = startup_time; - QFontDatabase::addApplicationFont(Application::resourcesPath() + "styles/Inconsolata.otf"); + QFontDatabase::addApplicationFont(PathUtils::resourcesPath() + "styles/Inconsolata.otf"); _window->setWindowTitle("Interface"); qInstallMessageHandler(messageHandler); @@ -4369,7 +4361,7 @@ void Application::skipVersion(QString latestVersion) { void Application::takeSnapshot() { QMediaPlayer* player = new QMediaPlayer(); - QFileInfo inf = QFileInfo(Application::resourcesPath() + "sounds/snap.wav"); + QFileInfo inf = QFileInfo(PathUtils::resourcesPath() + "sounds/snap.wav"); player->setMedia(QUrl::fromLocalFile(inf.absoluteFilePath())); player->play(); diff --git a/interface/src/Application.h b/interface/src/Application.h index 64ef0970d7..0e1feafb7e 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -138,7 +138,6 @@ class Application : public QApplication { public: static Application* getInstance() { return static_cast(QCoreApplication::instance()); } - static QString& resourcesPath(); static const glm::vec3& getPositionForPath() { return getInstance()->_myAvatar->getPosition(); } static glm::quat getOrientationForPath() { return getInstance()->_myAvatar->getOrientation(); } diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 101d16d3ba..74ee9736a7 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -37,6 +37,7 @@ #include #include #include +#include #include #include #include @@ -140,9 +141,9 @@ Audio::Audio(QObject* parent) : } void Audio::init(QGLWidget *parent) { - _micTextureId = parent->bindTexture(QImage(Application::resourcesPath() + "images/mic.svg")); - _muteTextureId = parent->bindTexture(QImage(Application::resourcesPath() + "images/mic-mute.svg")); - _boxTextureId = parent->bindTexture(QImage(Application::resourcesPath() + "images/audio-box.svg")); + _micTextureId = parent->bindTexture(QImage(PathUtils::resourcesPath() + "images/mic.svg")); + _muteTextureId = parent->bindTexture(QImage(PathUtils::resourcesPath() + "images/mic-mute.svg")); + _boxTextureId = parent->bindTexture(QImage(PathUtils::resourcesPath() + "images/audio-box.svg")); } void Audio::reset() { diff --git a/interface/src/Environment.cpp b/interface/src/Environment.cpp index c482095494..1fd3c7a73c 100644 --- a/interface/src/Environment.cpp +++ b/interface/src/Environment.cpp @@ -17,6 +17,7 @@ #include #include +#include #include #include @@ -188,7 +189,7 @@ int Environment::parseData(const HifiSockAddr& senderAddress, const QByteArray& ProgramObject* Environment::createSkyProgram(const char* from, int* locations) { ProgramObject* program = new ProgramObject(); - QByteArray prefix = QString(Application::resourcesPath() + "/shaders/SkyFrom" + from).toUtf8(); + QByteArray prefix = QString(PathUtils::resourcesPath() + "/shaders/SkyFrom" + from).toUtf8(); program->addShaderFromSourceFile(QGLShader::Vertex, prefix + ".vert"); program->addShaderFromSourceFile(QGLShader::Fragment, prefix + ".frag"); program->link(); diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 6c2c3966fc..fbb23504b0 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -32,6 +32,7 @@ #include #include #include +#include #include #include #include @@ -246,7 +247,7 @@ Menu::Menu() : connect(&xmppClient, &QXmppClient::connected, this, &Menu::toggleChat); connect(&xmppClient, &QXmppClient::disconnected, this, &Menu::toggleChat); - QDir::setCurrent(Application::resourcesPath()); + QDir::setCurrent(PathUtils::resourcesPath()); // init chat window to listen chat _chatWindow = new ChatWindow(Application::getInstance()->getWindow()); #endif diff --git a/interface/src/MetavoxelSystem.cpp b/interface/src/MetavoxelSystem.cpp index 84ccf0f406..372c5214f7 100644 --- a/interface/src/MetavoxelSystem.cpp +++ b/interface/src/MetavoxelSystem.cpp @@ -26,6 +26,7 @@ #include #include +#include #include #include "Application.h" @@ -63,9 +64,9 @@ void MetavoxelSystem::init() { _voxelBufferAttribute->setLODThresholdMultiplier( AttributeRegistry::getInstance()->getVoxelColorAttribute()->getLODThresholdMultiplier()); - _baseHeightfieldProgram.addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + + _baseHeightfieldProgram.addShaderFromSourceFile(QGLShader::Vertex, PathUtils::resourcesPath() + "shaders/metavoxel_heightfield_base.vert"); - _baseHeightfieldProgram.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + + _baseHeightfieldProgram.addShaderFromSourceFile(QGLShader::Fragment, PathUtils::resourcesPath() + "shaders/metavoxel_heightfield_base.frag"); _baseHeightfieldProgram.link(); @@ -78,9 +79,9 @@ void MetavoxelSystem::init() { loadSplatProgram("heightfield", _splatHeightfieldProgram, _splatHeightfieldLocations); - _heightfieldCursorProgram.addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + + _heightfieldCursorProgram.addShaderFromSourceFile(QGLShader::Vertex, PathUtils::resourcesPath() + "shaders/metavoxel_heightfield_cursor.vert"); - _heightfieldCursorProgram.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + + _heightfieldCursorProgram.addShaderFromSourceFile(QGLShader::Fragment, PathUtils::resourcesPath() + "shaders/metavoxel_cursor.frag"); _heightfieldCursorProgram.link(); @@ -88,17 +89,17 @@ void MetavoxelSystem::init() { _heightfieldCursorProgram.setUniformValue("heightMap", 0); _heightfieldCursorProgram.release(); - _baseVoxelProgram.addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + + _baseVoxelProgram.addShaderFromSourceFile(QGLShader::Vertex, PathUtils::resourcesPath() + "shaders/metavoxel_voxel_base.vert"); - _baseVoxelProgram.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + + _baseVoxelProgram.addShaderFromSourceFile(QGLShader::Fragment, PathUtils::resourcesPath() + "shaders/metavoxel_voxel_base.frag"); _baseVoxelProgram.link(); loadSplatProgram("voxel", _splatVoxelProgram, _splatVoxelLocations); - _voxelCursorProgram.addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + + _voxelCursorProgram.addShaderFromSourceFile(QGLShader::Vertex, PathUtils::resourcesPath() + "shaders/metavoxel_voxel_cursor.vert"); - _voxelCursorProgram.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + + _voxelCursorProgram.addShaderFromSourceFile(QGLShader::Fragment, PathUtils::resourcesPath() + "shaders/metavoxel_cursor.frag"); _voxelCursorProgram.link(); } @@ -836,9 +837,9 @@ void MetavoxelSystem::guideToAugmented(MetavoxelVisitor& visitor, bool render) { } void MetavoxelSystem::loadSplatProgram(const char* type, ProgramObject& program, SplatLocations& locations) { - program.addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + + program.addShaderFromSourceFile(QGLShader::Vertex, PathUtils::resourcesPath() + "shaders/metavoxel_" + type + "_splat.vert"); - program.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + + program.addShaderFromSourceFile(QGLShader::Fragment, PathUtils::resourcesPath() + "shaders/metavoxel_" + type + "_splat.frag"); program.link(); diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index 39fc522852..e0896364f6 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -25,6 +25,7 @@ #include #include #include +#include #include #include #include @@ -915,13 +916,13 @@ void Avatar::scaleVectorRelativeToPosition(glm::vec3 &positionToScale) const { void Avatar::setFaceModelURL(const QUrl& faceModelURL) { AvatarData::setFaceModelURL(faceModelURL); - const QUrl DEFAULT_FACE_MODEL_URL = QUrl::fromLocalFile(Application::resourcesPath() + "meshes/defaultAvatar_head.fst"); + const QUrl DEFAULT_FACE_MODEL_URL = QUrl::fromLocalFile(PathUtils::resourcesPath() + "meshes/defaultAvatar_head.fst"); getHead()->getFaceModel().setURL(_faceModelURL, DEFAULT_FACE_MODEL_URL, true, !isMyAvatar()); } void Avatar::setSkeletonModelURL(const QUrl& skeletonModelURL) { AvatarData::setSkeletonModelURL(skeletonModelURL); - const QUrl DEFAULT_SKELETON_MODEL_URL = QUrl::fromLocalFile(Application::resourcesPath() + "meshes/defaultAvatar_body.fst"); + const QUrl DEFAULT_SKELETON_MODEL_URL = QUrl::fromLocalFile(PathUtils::resourcesPath() + "meshes/defaultAvatar_body.fst"); _skeletonModel.setURL(_skeletonModelURL, DEFAULT_SKELETON_MODEL_URL, true, !isMyAvatar()); } diff --git a/interface/src/devices/OculusManager.cpp b/interface/src/devices/OculusManager.cpp index d27ab09876..7f5c2cd668 100644 --- a/interface/src/devices/OculusManager.cpp +++ b/interface/src/devices/OculusManager.cpp @@ -21,6 +21,7 @@ #include +#include #include #include @@ -136,8 +137,8 @@ void OculusManager::connect() { if (!_programInitialized) { // Shader program _programInitialized = true; - _program.addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + "shaders/oculus.vert"); - _program.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + "shaders/oculus.frag"); + _program.addShaderFromSourceFile(QGLShader::Vertex, PathUtils::resourcesPath() + "shaders/oculus.vert"); + _program.addShaderFromSourceFile(QGLShader::Fragment, PathUtils::resourcesPath() + "shaders/oculus.frag"); _program.link(); // Uniforms diff --git a/interface/src/devices/Visage.cpp b/interface/src/devices/Visage.cpp index 51b927df75..189ad90e12 100644 --- a/interface/src/devices/Visage.cpp +++ b/interface/src/devices/Visage.cpp @@ -14,6 +14,7 @@ #include #include +#include #include #include @@ -45,12 +46,12 @@ Visage::Visage() : #ifdef HAVE_VISAGE #ifdef WIN32 - QByteArray licensePath = Application::resourcesPath().toLatin1() + "visage"; + QByteArray licensePath = PathUtils::resourcesPath().toLatin1() + "visage"; #else - QByteArray licensePath = Application::resourcesPath().toLatin1() + "visage/license.vlc"; + QByteArray licensePath = PathUtils::resourcesPath().toLatin1() + "visage/license.vlc"; #endif initializeLicenseManager(licensePath.data()); - _tracker = new VisageTracker2(Application::resourcesPath().toLatin1() + "visage/tracker.cfg"); + _tracker = new VisageTracker2(PathUtils::resourcesPath().toLatin1() + "visage/tracker.cfg"); _data = new FaceData(); #endif } diff --git a/interface/src/renderer/AmbientOcclusionEffect.cpp b/interface/src/renderer/AmbientOcclusionEffect.cpp index 415b850abd..08ad6703e6 100644 --- a/interface/src/renderer/AmbientOcclusionEffect.cpp +++ b/interface/src/renderer/AmbientOcclusionEffect.cpp @@ -16,6 +16,7 @@ #include +#include #include #include @@ -30,9 +31,9 @@ const int ROTATION_HEIGHT = 4; void AmbientOcclusionEffect::init() { _occlusionProgram = new ProgramObject(); - _occlusionProgram->addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + _occlusionProgram->addShaderFromSourceFile(QGLShader::Vertex, PathUtils::resourcesPath() + "shaders/ambient_occlusion.vert"); - _occlusionProgram->addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + _occlusionProgram->addShaderFromSourceFile(QGLShader::Fragment, PathUtils::resourcesPath() + "shaders/ambient_occlusion.frag"); _occlusionProgram->link(); @@ -82,8 +83,8 @@ void AmbientOcclusionEffect::init() { glBindTexture(GL_TEXTURE_2D, 0); _blurProgram = new ProgramObject(); - _blurProgram->addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + "shaders/ambient_occlusion.vert"); - _blurProgram->addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + "shaders/occlusion_blur.frag"); + _blurProgram->addShaderFromSourceFile(QGLShader::Vertex, PathUtils::resourcesPath() + "shaders/ambient_occlusion.vert"); + _blurProgram->addShaderFromSourceFile(QGLShader::Fragment, PathUtils::resourcesPath() + "shaders/occlusion_blur.frag"); _blurProgram->link(); _blurProgram->bind(); diff --git a/interface/src/renderer/DeferredLightingEffect.cpp b/interface/src/renderer/DeferredLightingEffect.cpp index 22ac5d82b6..79b89d03f9 100644 --- a/interface/src/renderer/DeferredLightingEffect.cpp +++ b/interface/src/renderer/DeferredLightingEffect.cpp @@ -14,13 +14,15 @@ #include +#include + #include "Application.h" #include "DeferredLightingEffect.h" #include "RenderUtil.h" void DeferredLightingEffect::init() { - _simpleProgram.addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + "shaders/simple.vert"); - _simpleProgram.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + "shaders/simple.frag"); + _simpleProgram.addShaderFromSourceFile(QGLShader::Vertex, PathUtils::resourcesPath() + "shaders/simple.vert"); + _simpleProgram.addShaderFromSourceFile(QGLShader::Fragment, PathUtils::resourcesPath() + "shaders/simple.frag"); _simpleProgram.link(); _simpleProgram.bind(); @@ -394,9 +396,9 @@ void DeferredLightingEffect::render() { } void DeferredLightingEffect::loadLightProgram(const char* name, bool limited, ProgramObject& program, LightLocations& locations) { - program.addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + + program.addShaderFromSourceFile(QGLShader::Vertex, PathUtils::resourcesPath() + (limited ? "shaders/deferred_light_limited.vert" : "shaders/deferred_light.vert")); - program.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + name); + program.addShaderFromSourceFile(QGLShader::Fragment, PathUtils::resourcesPath() + name); program.link(); program.bind(); diff --git a/interface/src/renderer/GlowEffect.cpp b/interface/src/renderer/GlowEffect.cpp index 77d002dc89..a53c9f878b 100644 --- a/interface/src/renderer/GlowEffect.cpp +++ b/interface/src/renderer/GlowEffect.cpp @@ -14,6 +14,7 @@ #include +#include #include #include @@ -47,7 +48,7 @@ QOpenGLFramebufferObject* GlowEffect::getFreeFramebufferObject() const { static ProgramObject* createProgram(const QString& name) { ProgramObject* program = new ProgramObject(); - program->addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + "shaders/" + name + ".frag"); + program->addShaderFromSourceFile(QGLShader::Fragment, PathUtils::resourcesPath() + "shaders/" + name + ".frag"); program->link(); program->bind(); diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index 2a6988a984..71f0fb24f3 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -18,6 +18,7 @@ #include #include +#include #include #include #include @@ -222,109 +223,109 @@ void Model::initJointTransforms() { void Model::init() { if (!_program.isLinked()) { - _program.addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + "shaders/model.vert"); - _program.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + "shaders/model.frag"); + _program.addShaderFromSourceFile(QGLShader::Vertex, PathUtils::resourcesPath() + "shaders/model.vert"); + _program.addShaderFromSourceFile(QGLShader::Fragment, PathUtils::resourcesPath() + "shaders/model.frag"); initProgram(_program, _locations); _normalMapProgram.addShaderFromSourceFile(QGLShader::Vertex, - Application::resourcesPath() + "shaders/model_normal_map.vert"); + PathUtils::resourcesPath() + "shaders/model_normal_map.vert"); _normalMapProgram.addShaderFromSourceFile(QGLShader::Fragment, - Application::resourcesPath() + "shaders/model_normal_map.frag"); + PathUtils::resourcesPath() + "shaders/model_normal_map.frag"); initProgram(_normalMapProgram, _normalMapLocations); _specularMapProgram.addShaderFromSourceFile(QGLShader::Vertex, - Application::resourcesPath() + "shaders/model.vert"); + PathUtils::resourcesPath() + "shaders/model.vert"); _specularMapProgram.addShaderFromSourceFile(QGLShader::Fragment, - Application::resourcesPath() + "shaders/model_specular_map.frag"); + PathUtils::resourcesPath() + "shaders/model_specular_map.frag"); initProgram(_specularMapProgram, _specularMapLocations); _normalSpecularMapProgram.addShaderFromSourceFile(QGLShader::Vertex, - Application::resourcesPath() + "shaders/model_normal_map.vert"); + PathUtils::resourcesPath() + "shaders/model_normal_map.vert"); _normalSpecularMapProgram.addShaderFromSourceFile(QGLShader::Fragment, - Application::resourcesPath() + "shaders/model_normal_specular_map.frag"); + PathUtils::resourcesPath() + "shaders/model_normal_specular_map.frag"); initProgram(_normalSpecularMapProgram, _normalSpecularMapLocations); _translucentProgram.addShaderFromSourceFile(QGLShader::Vertex, - Application::resourcesPath() + "shaders/model.vert"); + PathUtils::resourcesPath() + "shaders/model.vert"); _translucentProgram.addShaderFromSourceFile(QGLShader::Fragment, - Application::resourcesPath() + "shaders/model_translucent.frag"); + PathUtils::resourcesPath() + "shaders/model_translucent.frag"); initProgram(_translucentProgram, _translucentLocations); // Lightmap - _lightmapProgram.addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + "shaders/model_lightmap.vert"); - _lightmapProgram.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + "shaders/model_lightmap.frag"); + _lightmapProgram.addShaderFromSourceFile(QGLShader::Vertex, PathUtils::resourcesPath() + "shaders/model_lightmap.vert"); + _lightmapProgram.addShaderFromSourceFile(QGLShader::Fragment, PathUtils::resourcesPath() + "shaders/model_lightmap.frag"); initProgram(_lightmapProgram, _lightmapLocations); _lightmapNormalMapProgram.addShaderFromSourceFile(QGLShader::Vertex, - Application::resourcesPath() + "shaders/model_lightmap_normal_map.vert"); + PathUtils::resourcesPath() + "shaders/model_lightmap_normal_map.vert"); _lightmapNormalMapProgram.addShaderFromSourceFile(QGLShader::Fragment, - Application::resourcesPath() + "shaders/model_lightmap_normal_map.frag"); + PathUtils::resourcesPath() + "shaders/model_lightmap_normal_map.frag"); initProgram(_lightmapNormalMapProgram, _lightmapNormalMapLocations); _lightmapSpecularMapProgram.addShaderFromSourceFile(QGLShader::Vertex, - Application::resourcesPath() + "shaders/model_lightmap.vert"); + PathUtils::resourcesPath() + "shaders/model_lightmap.vert"); _lightmapSpecularMapProgram.addShaderFromSourceFile(QGLShader::Fragment, - Application::resourcesPath() + "shaders/model_lightmap_specular_map.frag"); + PathUtils::resourcesPath() + "shaders/model_lightmap_specular_map.frag"); initProgram(_lightmapSpecularMapProgram, _lightmapSpecularMapLocations); _lightmapNormalSpecularMapProgram.addShaderFromSourceFile(QGLShader::Vertex, - Application::resourcesPath() + "shaders/model_lightmap_normal_map.vert"); + PathUtils::resourcesPath() + "shaders/model_lightmap_normal_map.vert"); _lightmapNormalSpecularMapProgram.addShaderFromSourceFile(QGLShader::Fragment, - Application::resourcesPath() + "shaders/model_lightmap_normal_specular_map.frag"); + PathUtils::resourcesPath() + "shaders/model_lightmap_normal_specular_map.frag"); initProgram(_lightmapNormalSpecularMapProgram, _lightmapNormalSpecularMapLocations); // end lightmap - _shadowProgram.addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + "shaders/model_shadow.vert"); + _shadowProgram.addShaderFromSourceFile(QGLShader::Vertex, PathUtils::resourcesPath() + "shaders/model_shadow.vert"); _shadowProgram.addShaderFromSourceFile(QGLShader::Fragment, - Application::resourcesPath() + "shaders/model_shadow.frag"); + PathUtils::resourcesPath() + "shaders/model_shadow.frag"); - _skinProgram.addShaderFromSourceFile(QGLShader::Vertex, Application::resourcesPath() + "shaders/skin_model.vert"); - _skinProgram.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + "shaders/model.frag"); + _skinProgram.addShaderFromSourceFile(QGLShader::Vertex, PathUtils::resourcesPath() + "shaders/skin_model.vert"); + _skinProgram.addShaderFromSourceFile(QGLShader::Fragment, PathUtils::resourcesPath() + "shaders/model.frag"); initSkinProgram(_skinProgram, _skinLocations); _skinNormalMapProgram.addShaderFromSourceFile(QGLShader::Vertex, - Application::resourcesPath() + "shaders/skin_model_normal_map.vert"); + PathUtils::resourcesPath() + "shaders/skin_model_normal_map.vert"); _skinNormalMapProgram.addShaderFromSourceFile(QGLShader::Fragment, - Application::resourcesPath() + "shaders/model_normal_map.frag"); + PathUtils::resourcesPath() + "shaders/model_normal_map.frag"); initSkinProgram(_skinNormalMapProgram, _skinNormalMapLocations); _skinSpecularMapProgram.addShaderFromSourceFile(QGLShader::Vertex, - Application::resourcesPath() + "shaders/skin_model.vert"); + PathUtils::resourcesPath() + "shaders/skin_model.vert"); _skinSpecularMapProgram.addShaderFromSourceFile(QGLShader::Fragment, - Application::resourcesPath() + "shaders/model_specular_map.frag"); + PathUtils::resourcesPath() + "shaders/model_specular_map.frag"); initSkinProgram(_skinSpecularMapProgram, _skinSpecularMapLocations); _skinNormalSpecularMapProgram.addShaderFromSourceFile(QGLShader::Vertex, - Application::resourcesPath() + "shaders/skin_model_normal_map.vert"); + PathUtils::resourcesPath() + "shaders/skin_model_normal_map.vert"); _skinNormalSpecularMapProgram.addShaderFromSourceFile(QGLShader::Fragment, - Application::resourcesPath() + "shaders/model_normal_specular_map.frag"); + PathUtils::resourcesPath() + "shaders/model_normal_specular_map.frag"); initSkinProgram(_skinNormalSpecularMapProgram, _skinNormalSpecularMapLocations); _skinShadowProgram.addShaderFromSourceFile(QGLShader::Vertex, - Application::resourcesPath() + "shaders/skin_model_shadow.vert"); + PathUtils::resourcesPath() + "shaders/skin_model_shadow.vert"); _skinShadowProgram.addShaderFromSourceFile(QGLShader::Fragment, - Application::resourcesPath() + "shaders/model_shadow.frag"); + PathUtils::resourcesPath() + "shaders/model_shadow.frag"); initSkinProgram(_skinShadowProgram, _skinShadowLocations); _skinTranslucentProgram.addShaderFromSourceFile(QGLShader::Vertex, - Application::resourcesPath() + "shaders/skin_model.vert"); + PathUtils::resourcesPath() + "shaders/skin_model.vert"); _skinTranslucentProgram.addShaderFromSourceFile(QGLShader::Fragment, - Application::resourcesPath() + "shaders/model_translucent.frag"); + PathUtils::resourcesPath() + "shaders/model_translucent.frag"); initSkinProgram(_skinTranslucentProgram, _skinTranslucentLocations); } diff --git a/interface/src/ui/AddressBarDialog.cpp b/interface/src/ui/AddressBarDialog.cpp index dbc29be71a..32161b018f 100644 --- a/interface/src/ui/AddressBarDialog.cpp +++ b/interface/src/ui/AddressBarDialog.cpp @@ -9,6 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +#include + #include "AddressBarDialog.h" #include "AddressManager.h" #include "Application.h" @@ -82,7 +84,7 @@ void AddressBarDialog::setupUI() { _goButton->setSizePolicy(sizePolicy); _goButton->setMinimumSize(QSize(GO_BUTTON_SIZE, GO_BUTTON_SIZE)); _goButton->setMaximumSize(QSize(GO_BUTTON_SIZE, GO_BUTTON_SIZE)); - _goButton->setIcon(QIcon(Application::resourcesPath() + ADDRESSBAR_GO_BUTTON_ICON)); + _goButton->setIcon(QIcon(PathUtils::resourcesPath() + ADDRESSBAR_GO_BUTTON_ICON)); _goButton->setIconSize(QSize(GO_BUTTON_SIZE, GO_BUTTON_SIZE)); _goButton->setDefault(true); _goButton->setFlat(true); @@ -99,7 +101,7 @@ void AddressBarDialog::setupUI() { _closeButton->setSizePolicy(sizePolicy); _closeButton->setMinimumSize(QSize(CLOSE_BUTTON_SIZE, CLOSE_BUTTON_SIZE)); _closeButton->setMaximumSize(QSize(CLOSE_BUTTON_SIZE, CLOSE_BUTTON_SIZE)); - QIcon icon(Application::resourcesPath() + CLOSE_BUTTON_ICON); + QIcon icon(PathUtils::resourcesPath() + CLOSE_BUTTON_ICON); _closeButton->setIcon(icon); _closeButton->setIconSize(QSize(CLOSE_BUTTON_SIZE, CLOSE_BUTTON_SIZE)); _closeButton->setFlat(true); @@ -112,7 +114,7 @@ void AddressBarDialog::setupUI() { } void AddressBarDialog::showEvent(QShowEvent* event) { - _goButton->setIcon(QIcon(Application::resourcesPath() + ADDRESSBAR_GO_BUTTON_ICON)); + _goButton->setIcon(QIcon(PathUtils::resourcesPath() + ADDRESSBAR_GO_BUTTON_ICON)); _addressLineEdit->setText(QString()); _addressLineEdit->setFocus(); FramelessDialog::showEvent(event); @@ -120,7 +122,7 @@ void AddressBarDialog::showEvent(QShowEvent* event) { void AddressBarDialog::accept() { if (!_addressLineEdit->text().isEmpty()) { - _goButton->setIcon(QIcon(Application::resourcesPath() + ADDRESSBAR_GO_BUTTON_ACTIVE_ICON)); + _goButton->setIcon(QIcon(PathUtils::resourcesPath() + ADDRESSBAR_GO_BUTTON_ACTIVE_ICON)); AddressManager& addressManager = AddressManager::getInstance(); connect(&addressManager, &AddressManager::lookupResultsFinished, this, &QDialog::hide); addressManager.handleLookupString(_addressLineEdit->text()); diff --git a/interface/src/ui/ApplicationOverlay.cpp b/interface/src/ui/ApplicationOverlay.cpp index f4e0c9769d..32fffd3d40 100644 --- a/interface/src/ui/ApplicationOverlay.cpp +++ b/interface/src/ui/ApplicationOverlay.cpp @@ -12,6 +12,8 @@ #include "InterfaceConfig.h" #include + +#include #include #include "Application.h" @@ -379,7 +381,7 @@ void ApplicationOverlay::displayOverlayTexture3DTV(Camera& whichCamera, float as glEnd(); if (_crosshairTexture == 0) { - _crosshairTexture = Application::getInstance()->getGLWidget()->bindTexture(QImage(Application::resourcesPath() + "images/sixense-reticle.png")); + _crosshairTexture = Application::getInstance()->getGLWidget()->bindTexture(QImage(PathUtils::resourcesPath() + "images/sixense-reticle.png")); } //draw the mouse pointer @@ -513,7 +515,7 @@ void ApplicationOverlay::renderPointers() { //lazily load crosshair texture if (_crosshairTexture == 0) { - _crosshairTexture = Application::getInstance()->getGLWidget()->bindTexture(QImage(Application::resourcesPath() + "images/sixense-reticle.png")); + _crosshairTexture = Application::getInstance()->getGLWidget()->bindTexture(QImage(PathUtils::resourcesPath() + "images/sixense-reticle.png")); } glEnable(GL_TEXTURE_2D); diff --git a/interface/src/ui/ChatWindow.cpp b/interface/src/ui/ChatWindow.cpp index 747b4ae68d..22ceb0d367 100644 --- a/interface/src/ui/ChatWindow.cpp +++ b/interface/src/ui/ChatWindow.cpp @@ -19,6 +19,7 @@ #include #include +#include #include "Application.h" #include "ChatMessageArea.h" @@ -92,9 +93,9 @@ ChatWindow::ChatWindow(QWidget* parent) : connect(&_trayIcon, SIGNAL(messageClicked()), this, SLOT(notificationClicked())); #endif // HAVE_QXMPP - QDir mentionSoundsDir(Application::resourcesPath() + mentionSoundsPath); + QDir mentionSoundsDir(PathUtils::resourcesPath() + mentionSoundsPath); _mentionSounds = mentionSoundsDir.entryList(QDir::Files); - _trayIcon.setIcon(QIcon( Application::resourcesPath() + "/images/hifi-logo.svg")); + _trayIcon.setIcon(QIcon( PathUtils::resourcesPath() + "/images/hifi-logo.svg")); } ChatWindow::~ChatWindow() { @@ -385,7 +386,7 @@ void ChatWindow::messageReceived(const QXmppMessage& message) { if (_effectPlayer.state() != QMediaPlayer::PlayingState) { // get random sound - QFileInfo inf = QFileInfo(Application::resourcesPath() + + QFileInfo inf = QFileInfo(PathUtils::resourcesPath() + mentionSoundsPath + _mentionSounds.at(rand() % _mentionSounds.size())); _effectPlayer.setMedia(QUrl::fromLocalFile(inf.absoluteFilePath())); diff --git a/interface/src/ui/FramelessDialog.cpp b/interface/src/ui/FramelessDialog.cpp index 280354d974..bae6217083 100644 --- a/interface/src/ui/FramelessDialog.cpp +++ b/interface/src/ui/FramelessDialog.cpp @@ -12,6 +12,8 @@ #include #include +#include + #include "Application.h" #include "FramelessDialog.h" #include "Menu.h" @@ -80,10 +82,10 @@ bool FramelessDialog::eventFilter(QObject* sender, QEvent* event) { } void FramelessDialog::setStyleSheetFile(const QString& fileName) { - QFile globalStyleSheet(Application::resourcesPath() + "styles/global.qss"); - QFile styleSheet(Application::resourcesPath() + fileName); + QFile globalStyleSheet(PathUtils::resourcesPath() + "styles/global.qss"); + QFile styleSheet(PathUtils::resourcesPath() + fileName); if (styleSheet.open(QIODevice::ReadOnly) && globalStyleSheet.open(QIODevice::ReadOnly) ) { - QDir::setCurrent(Application::resourcesPath()); + QDir::setCurrent(PathUtils::resourcesPath()); setStyleSheet(globalStyleSheet.readAll() + styleSheet.readAll()); } } diff --git a/interface/src/ui/InfoView.cpp b/interface/src/ui/InfoView.cpp index f306514e80..0c04e07841 100644 --- a/interface/src/ui/InfoView.cpp +++ b/interface/src/ui/InfoView.cpp @@ -9,14 +9,17 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#include "InfoView.h" #include -#include "Application.h" #include #include #include +#include + +#include "Application.h" +#include "InfoView.h" + #define SETTINGS_VERSION_KEY "info-version" #define MAX_DIALOG_HEIGHT_RATIO 0.9 @@ -25,7 +28,7 @@ InfoView::InfoView(bool forced, QString path) : { setWindowFlags(Qt::WindowStaysOnTopHint | Qt::CustomizeWindowHint | Qt::WindowCloseButtonHint); - QString absPath = QFileInfo(Application::resourcesPath() + path).absoluteFilePath(); + QString absPath = QFileInfo(PathUtils::resourcesPath() + path).absoluteFilePath(); QUrl url = QUrl::fromLocalFile(absPath); load(url); diff --git a/interface/src/ui/JSConsole.cpp b/interface/src/ui/JSConsole.cpp index 8dbece41f0..700781df69 100644 --- a/interface/src/ui/JSConsole.cpp +++ b/interface/src/ui/JSConsole.cpp @@ -13,10 +13,11 @@ #include #include -#include "Application.h" -#include "ScriptHighlighting.h" +#include +#include "Application.h" #include "JSConsole.h" +#include "ScriptHighlighting.h" const int NO_CURRENT_HISTORY_COMMAND = -1; const int MAX_HISTORY_SIZE = 64; @@ -41,9 +42,9 @@ JSConsole::JSConsole(QWidget* parent, ScriptEngine* scriptEngine) : _ui->promptTextEdit->setWordWrapMode(QTextOption::NoWrap); _ui->promptTextEdit->installEventFilter(this); - QFile styleSheet(Application::resourcesPath() + "styles/console.qss"); + QFile styleSheet(PathUtils::resourcesPath() + "styles/console.qss"); if (styleSheet.open(QIODevice::ReadOnly)) { - QDir::setCurrent(Application::resourcesPath()); + QDir::setCurrent(PathUtils::resourcesPath()); setStyleSheet(styleSheet.readAll()); } diff --git a/interface/src/ui/LogDialog.cpp b/interface/src/ui/LogDialog.cpp index 7136ed2d25..a1a52f1d77 100644 --- a/interface/src/ui/LogDialog.cpp +++ b/interface/src/ui/LogDialog.cpp @@ -15,10 +15,10 @@ #include #include +#include #include #include "Application.h" - #include "ui/LogDialog.h" const int TOP_BAR_HEIGHT = 46; @@ -44,9 +44,9 @@ LogDialog::LogDialog(QWidget* parent, AbstractLoggerInterface* logger) : QDialog setWindowTitle("Log"); setAttribute(Qt::WA_DeleteOnClose); - QFile styleSheet(Application::resourcesPath() + "styles/log_dialog.qss"); + QFile styleSheet(PathUtils::resourcesPath() + "styles/log_dialog.qss"); if (styleSheet.open(QIODevice::ReadOnly)) { - QDir::setCurrent(Application::resourcesPath()); + QDir::setCurrent(PathUtils::resourcesPath()); setStyleSheet(styleSheet.readAll()); } diff --git a/interface/src/ui/LoginDialog.cpp b/interface/src/ui/LoginDialog.cpp index b3d8cb1e53..298efa6b1a 100644 --- a/interface/src/ui/LoginDialog.cpp +++ b/interface/src/ui/LoginDialog.cpp @@ -14,11 +14,12 @@ #include #include +#include + #include "Application.h" #include "Menu.h" #include "AccountManager.h" #include "ui_loginDialog.h" - #include "LoginDialog.h" const QString FORGOT_PASSWORD_URL = "https://data.highfidelity.io/users/password/new"; @@ -30,8 +31,8 @@ LoginDialog::LoginDialog(QWidget* parent) : _ui->setupUi(this); _ui->errorLabel->hide(); _ui->emailLineEdit->setFocus(); - _ui->logoLabel->setPixmap(QPixmap(Application::resourcesPath() + "images/hifi-logo.svg")); - _ui->loginButton->setIcon(QIcon(Application::resourcesPath() + "images/login.svg")); + _ui->logoLabel->setPixmap(QPixmap(PathUtils::resourcesPath() + "images/hifi-logo.svg")); + _ui->loginButton->setIcon(QIcon(PathUtils::resourcesPath() + "images/login.svg")); _ui->infoLabel->setVisible(false); _ui->errorLabel->setVisible(false); diff --git a/interface/src/ui/MetavoxelEditor.cpp b/interface/src/ui/MetavoxelEditor.cpp index 158532e19a..1a85e84b72 100644 --- a/interface/src/ui/MetavoxelEditor.cpp +++ b/interface/src/ui/MetavoxelEditor.cpp @@ -35,6 +35,7 @@ #include #include #include +#include #include "Application.h" #include "MetavoxelEditor.h" @@ -145,7 +146,7 @@ MetavoxelEditor::MetavoxelEditor() : return; } - _gridProgram.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + "shaders/grid.frag"); + _gridProgram.addShaderFromSourceFile(QGLShader::Fragment, PathUtils::resourcesPath() + "shaders/grid.frag"); _gridProgram.link(); } diff --git a/interface/src/ui/RearMirrorTools.cpp b/interface/src/ui/RearMirrorTools.cpp index fb6ef63647..fd3fc34adb 100644 --- a/interface/src/ui/RearMirrorTools.cpp +++ b/interface/src/ui/RearMirrorTools.cpp @@ -13,12 +13,13 @@ #include +#include #include #include "Application.h" +#include "RearMirrorTools.h" #include "Util.h" -#include "RearMirrorTools.h" const char SETTINGS_GROUP_NAME[] = "Rear View Tools"; const char ZOOM_LEVEL_SETTINGS[] = "ZoomLevel"; @@ -32,13 +33,13 @@ RearMirrorTools::RearMirrorTools(QGLWidget* parent, QRect& bounds, QSettings* se _fullScreen(false) { _zoomLevel = HEAD; - _closeTextureId = _parent->bindTexture(QImage(Application::resourcesPath() + "images/close.svg")); + _closeTextureId = _parent->bindTexture(QImage(PathUtils::resourcesPath() + "images/close.svg")); // Disabled for now https://worklist.net/19548 - // _resetTextureId = _parent->bindTexture(QImage(Application::resourcesPath() + "images/reset.png")); + // _resetTextureId = _parent->bindTexture(QImage(PathUtils::resourcesPath() + "images/reset.png")); - _zoomHeadTextureId = _parent->bindTexture(QImage(Application::resourcesPath() + "images/plus.svg")); - _zoomBodyTextureId = _parent->bindTexture(QImage(Application::resourcesPath() + "images/minus.svg")); + _zoomHeadTextureId = _parent->bindTexture(QImage(PathUtils::resourcesPath() + "images/plus.svg")); + _zoomBodyTextureId = _parent->bindTexture(QImage(PathUtils::resourcesPath() + "images/minus.svg")); _shrinkIconRect = QRect(ICON_PADDING, ICON_PADDING, ICON_SIZE, ICON_SIZE); _closeIconRect = QRect(_bounds.left() + ICON_PADDING, _bounds.top() + ICON_PADDING, ICON_SIZE, ICON_SIZE); diff --git a/interface/src/ui/RunningScriptsWidget.cpp b/interface/src/ui/RunningScriptsWidget.cpp index cfd7428482..57c0532777 100644 --- a/interface/src/ui/RunningScriptsWidget.cpp +++ b/interface/src/ui/RunningScriptsWidget.cpp @@ -21,6 +21,8 @@ #include #include +#include + #include "Application.h" #include "Menu.h" #include "ScriptsModel.h" @@ -109,7 +111,7 @@ void RunningScriptsWidget::setRunningScripts(const QStringList& list) { QPushButton* closeButton = new QPushButton(row); closeButton->setFlat(true); closeButton->setIcon( - QIcon(QPixmap(Application::resourcesPath() + "images/kill-script.svg").scaledToHeight(CLOSE_ICON_HEIGHT))); + QIcon(QPixmap(PathUtils::resourcesPath() + "images/kill-script.svg").scaledToHeight(CLOSE_ICON_HEIGHT))); closeButton->setSizePolicy(QSizePolicy(QSizePolicy::Maximum, QSizePolicy::Preferred)); closeButton->setStyleSheet("border: 0;"); closeButton->setCursor(Qt::PointingHandCursor); diff --git a/interface/src/ui/VoxelImportDialog.cpp b/interface/src/ui/VoxelImportDialog.cpp index 2d1b71ba7f..930fed133d 100644 --- a/interface/src/ui/VoxelImportDialog.cpp +++ b/interface/src/ui/VoxelImportDialog.cpp @@ -18,6 +18,8 @@ #include #include +#include + #include "Application.h" #include "VoxelImportDialog.h" @@ -64,7 +66,7 @@ QIcon HiFiIconProvider::icon(QFileIconProvider::IconType type) const { break; } - return QIcon(Application::resourcesPath() + "icons/" + typeString + ".svg"); + return QIcon(PathUtils::resourcesPath() + "icons/" + typeString + ".svg"); } QIcon HiFiIconProvider::icon(const QFileInfo &info) const { @@ -72,21 +74,21 @@ QIcon HiFiIconProvider::icon(const QFileInfo &info) const { if (info.isDir()) { if (info.absoluteFilePath() == QDir::homePath()) { - return QIcon(Application::resourcesPath() + "icons/home.svg"); + return QIcon(PathUtils::resourcesPath() + "icons/home.svg"); } else if (info.absoluteFilePath() == QStandardPaths::writableLocation(QStandardPaths::DesktopLocation)) { - return QIcon(Application::resourcesPath() + "icons/desktop.svg"); + return QIcon(PathUtils::resourcesPath() + "icons/desktop.svg"); } else if (info.absoluteFilePath() == QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation)) { - return QIcon(Application::resourcesPath() + "icons/documents.svg"); + return QIcon(PathUtils::resourcesPath() + "icons/documents.svg"); } - return QIcon(Application::resourcesPath() + "icons/folder.svg"); + return QIcon(PathUtils::resourcesPath() + "icons/folder.svg"); } - QFileInfo iconFile(Application::resourcesPath() + "icons/" + iconsMap[ext]); + QFileInfo iconFile(PathUtils::resourcesPath() + "icons/" + iconsMap[ext]); if (iconFile.exists() && iconFile.isFile()) { return QIcon(iconFile.filePath()); } - return QIcon(Application::resourcesPath() + "icons/file.svg"); + return QIcon(PathUtils::resourcesPath() + "icons/file.svg"); } QString HiFiIconProvider::type(const QFileInfo &info) const { @@ -307,16 +309,16 @@ void VoxelImportDialog::setLayout() { widget = findChild("treeView"); widget->setAttribute(Qt::WA_MacShowFocusRect, false); - QFile styleSheet(Application::resourcesPath() + "styles/import_dialog.qss"); + QFile styleSheet(PathUtils::resourcesPath() + "styles/import_dialog.qss"); if (styleSheet.open(QIODevice::ReadOnly)) { - QDir::setCurrent(Application::resourcesPath()); + QDir::setCurrent(PathUtils::resourcesPath()); setStyleSheet(styleSheet.readAll()); } } void VoxelImportDialog::setImportTypes() { - QFile config(Application::resourcesPath() + "config/config.json"); + QFile config(PathUtils::resourcesPath() + "config/config.json"); config.open(QFile::ReadOnly | QFile::Text); QJsonDocument document = QJsonDocument::fromJson(config.readAll()); if (!document.isNull() && !document.isEmpty()) { diff --git a/interface/src/ui/overlays/Grid3DOverlay.cpp b/interface/src/ui/overlays/Grid3DOverlay.cpp index d1086ae534..953a288cb6 100644 --- a/interface/src/ui/overlays/Grid3DOverlay.cpp +++ b/interface/src/ui/overlays/Grid3DOverlay.cpp @@ -9,9 +9,10 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#include "Grid3DOverlay.h" +#include #include "Application.h" +#include "Grid3DOverlay.h" ProgramObject Grid3DOverlay::_gridProgram; @@ -36,7 +37,7 @@ void Grid3DOverlay::render(RenderArgs* args) { } if (!_gridProgram.isLinked()) { - if (!_gridProgram.addShaderFromSourceFile(QGLShader::Fragment, Application::resourcesPath() + "shaders/grid.frag")) { + if (!_gridProgram.addShaderFromSourceFile(QGLShader::Fragment, PathUtils::resourcesPath() + "shaders/grid.frag")) { qDebug() << "Failed to compile: " + _gridProgram.log(); return; } diff --git a/interface/src/voxels/VoxelSystem.cpp b/interface/src/voxels/VoxelSystem.cpp index 064cead160..114b6ba481 100644 --- a/interface/src/voxels/VoxelSystem.cpp +++ b/interface/src/voxels/VoxelSystem.cpp @@ -18,6 +18,7 @@ #include #include +#include #include #include #include @@ -372,9 +373,9 @@ void VoxelSystem::initVoxelMemory() { // create our simple fragment shader if we're the first system to init if (!_program.isLinked()) { _program.addShaderFromSourceFile(QGLShader::Vertex, - Application::resourcesPath() + "shaders/voxel.vert"); + PathUtils::resourcesPath() + "shaders/voxel.vert"); _program.addShaderFromSourceFile(QGLShader::Fragment, - Application::resourcesPath() + "shaders/voxel.frag"); + PathUtils::resourcesPath() + "shaders/voxel.frag"); _program.link(); } _initialized = true; @@ -1645,9 +1646,9 @@ unsigned long VoxelSystem::getVoxelMemoryUsageGPU() { void VoxelSystem::bindPerlinModulateProgram() { if (!_perlinModulateProgram.isLinked()) { _perlinModulateProgram.addShaderFromSourceFile(QGLShader::Vertex, - Application::resourcesPath() + "shaders/perlin_modulate.vert"); + PathUtils::resourcesPath() + "shaders/perlin_modulate.vert"); _perlinModulateProgram.addShaderFromSourceFile(QGLShader::Fragment, - Application::resourcesPath() + "shaders/perlin_modulate.frag"); + PathUtils::resourcesPath() + "shaders/perlin_modulate.frag"); _perlinModulateProgram.link(); _perlinModulateProgram.bind(); diff --git a/libraries/shared/src/PathUtils.cpp b/libraries/shared/src/PathUtils.cpp new file mode 100644 index 0000000000..0b99f22228 --- /dev/null +++ b/libraries/shared/src/PathUtils.cpp @@ -0,0 +1,25 @@ +// +// PathUtils.cpp +// libraries/shared/src +// +// Created by Brad Hefta-Gaub on 12/15/14. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include +#include + +#include "PathUtils.h" + + +QString& PathUtils::resourcesPath() { +#ifdef Q_OS_MAC + static QString staticResourcePath = QCoreApplication::applicationDirPath() + "/../Resources/"; +#else + static QString staticResourcePath = QCoreApplication::applicationDirPath() + "/resources/"; +#endif + return staticResourcePath; +} diff --git a/libraries/shared/src/PathUtils.h b/libraries/shared/src/PathUtils.h new file mode 100644 index 0000000000..71cabc727d --- /dev/null +++ b/libraries/shared/src/PathUtils.h @@ -0,0 +1,22 @@ +// +// PathUtils.h +// libraries/shared/src +// +// Created by Brad Hefta-Gaub on 12/15/14. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef hifi_PathUtils_h +#define hifi_PathUtils_h + + +#include + +namespace PathUtils { + QString& resourcesPath(); +} + +#endif // hifi_PathUtils_h \ No newline at end of file From 50c1e9fb4037cd9f225177ff9e6e5603c11c4776 Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Mon, 15 Dec 2014 22:41:35 -0800 Subject: [PATCH 119/258] Fixes for missing audio device. --- interface/src/Audio.cpp | 7 ++++++- libraries/audio/src/AudioRingBuffer.h | 2 +- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/interface/src/Audio.cpp b/interface/src/Audio.cpp index 101d16d3ba..bf176e0415 100644 --- a/interface/src/Audio.cpp +++ b/interface/src/Audio.cpp @@ -450,7 +450,9 @@ void Audio::start() { qDebug() << "Unable to set up audio output because of a problem with output format."; } - _inputFrameBuffer.initialize( _inputFormat.channelCount(), _audioInput->bufferSize() * 8 ); + if (_audioInput) { + _inputFrameBuffer.initialize( _inputFormat.channelCount(), _audioInput->bufferSize() * 8 ); + } _inputGain.initialize(); _sourceGain.initialize(); _noiseSource.initialize(); @@ -1935,6 +1937,9 @@ int Audio::calculateNumberOfFrameSamples(int numBytes) const { } float Audio::getAudioOutputMsecsUnplayed() const { + if (!_audioOutput) { + return 0.0f; + } int bytesAudioOutputUnplayed = _audioOutput->bufferSize() - _audioOutput->bytesFree(); float msecsAudioOutputUnplayed = bytesAudioOutputUnplayed / (float)_outputFormat.bytesForDuration(USECS_PER_MSEC); return msecsAudioOutputUnplayed; diff --git a/libraries/audio/src/AudioRingBuffer.h b/libraries/audio/src/AudioRingBuffer.h index f033ffa80f..9239527df3 100644 --- a/libraries/audio/src/AudioRingBuffer.h +++ b/libraries/audio/src/AudioRingBuffer.h @@ -62,7 +62,7 @@ public: float getNextOutputFrameLoudness() const; int samplesAvailable() const; - int framesAvailable() const { return samplesAvailable() / _numFrameSamples; } + int framesAvailable() const { return (_numFrameSamples == 0) ? 0 : samplesAvailable() / _numFrameSamples; } int getNumFrameSamples() const { return _numFrameSamples; } From b1d1cfee44420bc9f14a2749ca746a10389b3aaa Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 15:29:05 -0800 Subject: [PATCH 120/258] cmake cleanup --- libraries/render-utils/CMakeLists.txt | 15 +-------------- 1 file changed, 1 insertion(+), 14 deletions(-) diff --git a/libraries/render-utils/CMakeLists.txt b/libraries/render-utils/CMakeLists.txt index bde26ea5ca..eb96e7c5ec 100644 --- a/libraries/render-utils/CMakeLists.txt +++ b/libraries/render-utils/CMakeLists.txt @@ -10,7 +10,7 @@ if (APPLE) # link in required OS X frameworks and include the right GL headers find_library(OpenGL OpenGL) - target_link_libraries(${TARGET_NAME} ${OpenGL}) + #target_link_libraries(${TARGET_NAME} ${OpenGL}) else (APPLE) find_package(OpenGL REQUIRED) @@ -19,8 +19,6 @@ else (APPLE) include_directories(SYSTEM "${OPENGL_INCLUDE_DIR}") endif () - #target_link_libraries(${TARGET_NAME} "${OPENGL_LIBRARY}") - # link target to external libraries if (WIN32) find_package(GLEW REQUIRED) @@ -28,17 +26,6 @@ else (APPLE) # we're using static GLEW, so define GLEW_STATIC add_definitions(-DGLEW_STATIC) - - #target_link_libraries(${TARGET_NAME} "${GLEW_LIBRARIES}" "${NSIGHT_LIBRARIES}" opengl32.lib) - - # try to find the Nsight package and add it to the build if we find it - #find_package(NSIGHT) - #if (NSIGHT_FOUND) - # include_directories(${NSIGHT_INCLUDE_DIRS}) - # add_definitions(-DNSIGHT_FOUND) - # #target_link_libraries(${TARGET_NAME} "${NSIGHT_LIBRARIES}") - #endif () - endif() endif (APPLE) From e5e2eb4e8ae0adc3df0ed238596f30f126b442c1 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Mon, 15 Dec 2014 16:20:52 -0800 Subject: [PATCH 121/258] Moved GLCanvas in DM and DM to QSharedPointers --- interface/src/Application.cpp | 54 ++++++----- interface/src/Application.h | 1 - interface/src/Camera.cpp | 6 +- interface/src/Menu.cpp | 18 ++-- interface/src/avatar/Head.cpp | 7 +- interface/src/avatar/MyAvatar.cpp | 2 +- interface/src/devices/DdeFaceTracker.h | 4 +- interface/src/devices/Faceshift.h | 4 +- interface/src/devices/OculusManager.cpp | 8 +- interface/src/devices/PrioVR.cpp | 7 +- interface/src/devices/SixenseManager.cpp | 8 +- interface/src/devices/TV3DManager.cpp | 11 ++- interface/src/devices/Visage.cpp | 2 +- interface/src/devices/Visage.h | 4 +- interface/src/renderer/GlowEffect.cpp | 10 +- interface/src/renderer/TextureCache.cpp | 2 +- .../ControllerScriptingInterface.cpp | 6 +- .../scripting/WindowScriptingInterface.cpp | 2 +- interface/src/ui/ApplicationOverlay.cpp | 97 ++++++++++--------- interface/src/ui/MetavoxelEditor.cpp | 2 +- .../src/ui/MetavoxelNetworkSimulator.cpp | 2 +- interface/src/ui/PreferencesDialog.cpp | 7 +- interface/src/ui/Snapshot.cpp | 5 +- interface/src/ui/Stats.cpp | 20 ++-- 24 files changed, 143 insertions(+), 146 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index eaafcd0eac..4c9fdcaf0f 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -194,7 +194,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) : _isVSyncOn(true), _aboutToQuit(false) { - GLCanvas* glCanvas = DependencyManager::get(); + QSharedPointer glCanvas = DependencyManager::get(); // read the ApplicationInfo.ini file for Name/Version/Domain information QSettings applicationInfo(Application::resourcesPath() + "info/ApplicationInfo.ini", QSettings::IniFormat); @@ -365,7 +365,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) : ResourceCache::setRequestLimit(3); - _window->setCentralWidget(glCanvas); + _window->setCentralWidget(glCanvas.data()); restoreSizeAndPosition(); @@ -393,7 +393,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) : checkVersion(); - _overlays.init(glCanvas); // do this before scripts load + _overlays.init(glCanvas.data()); // do this before scripts load LocalVoxelsList::getInstance()->addPersistantTree(DOMAIN_TREE_NAME, _voxels.getTree()); LocalVoxelsList::getInstance()->addPersistantTree(CLIPBOARD_TREE_NAME, &_clipboard); @@ -442,6 +442,8 @@ void Application::aboutToQuit() { } Application::~Application() { + DependencyManager::get()->setParent(NULL); + _entities.getTree()->setSimulation(NULL); qInstallMessageHandler(NULL); @@ -1046,7 +1048,7 @@ void Application::keyPressEvent(QKeyEvent* event) { if (isShifted) { _viewFrustum.setFocalLength(_viewFrustum.getFocalLength() - 0.1f); if (TV3DManager::isConnected()) { - GLCanvas* glCanvas = DependencyManager::get(); + QSharedPointer glCanvas = DependencyManager::get(); TV3DManager::configureCamera(_myCamera, glCanvas->getDeviceWidth(), glCanvas->getDeviceHeight()); } } else { @@ -1059,7 +1061,7 @@ void Application::keyPressEvent(QKeyEvent* event) { if (isShifted) { _viewFrustum.setFocalLength(_viewFrustum.getFocalLength() + 0.1f); if (TV3DManager::isConnected()) { - GLCanvas* glCanvas = DependencyManager::get(); + QSharedPointer glCanvas = DependencyManager::get(); TV3DManager::configureCamera(_myCamera, glCanvas->getDeviceWidth(), glCanvas->getDeviceHeight()); } @@ -1532,7 +1534,7 @@ void Application::idle() { void Application::checkBandwidthMeterClick() { // ... to be called upon button release - GLCanvas* glCanvas = DependencyManager::get(); + QSharedPointer glCanvas = DependencyManager::get(); if (Menu::getInstance()->isOptionChecked(MenuOption::Bandwidth) && Menu::getInstance()->isOptionChecked(MenuOption::Stats) && Menu::getInstance()->isOptionChecked(MenuOption::UserInterface) && @@ -1568,7 +1570,7 @@ void Application::setFullscreen(bool fullscreen) { } void Application::setEnable3DTVMode(bool enable3DTVMode) { - GLCanvas* glCanvas = DependencyManager::get(); + QSharedPointer glCanvas = DependencyManager::get(); resizeGL(glCanvas->getDeviceWidth(), glCanvas->getDeviceHeight()); } @@ -1594,7 +1596,7 @@ void Application::setEnableVRMode(bool enableVRMode) { _myCamera.setHmdRotation(glm::quat()); } - GLCanvas* glCanvas = DependencyManager::get(); + QSharedPointer glCanvas = DependencyManager::get(); resizeGL(glCanvas->getDeviceWidth(), glCanvas->getDeviceHeight()); } @@ -1657,7 +1659,7 @@ glm::vec3 Application::getMouseVoxelWorldCoordinates(const VoxelDetail& mouseVox bool Application::mouseOnScreen() const { if (OculusManager::isConnected()) { - GLCanvas* glCanvas = DependencyManager::get(); + QSharedPointer glCanvas = DependencyManager::get(); return getMouseX() >= 0 && getMouseX() <= glCanvas->getDeviceWidth() && getMouseY() >= 0 && getMouseY() <= glCanvas->getDeviceHeight(); } @@ -1699,13 +1701,13 @@ int Application::getMouseDragStartedY() const { } FaceTracker* Application::getActiveFaceTracker() { - Faceshift* faceshift = DependencyManager::get(); - Visage* visage = DependencyManager::get(); - DdeFaceTracker* dde = DependencyManager::get(); + QSharedPointer faceshift = DependencyManager::get(); + QSharedPointer visage = DependencyManager::get(); + QSharedPointer dde = DependencyManager::get(); - return (dde->isActive() ? static_cast(dde) : - (faceshift->isActive() ? static_cast(faceshift) : - (visage->isActive() ? static_cast(visage) : NULL))); + return (dde->isActive() ? static_cast(dde.data()) : + (faceshift->isActive() ? static_cast(faceshift.data()) : + (visage->isActive() ? static_cast(visage.data()) : NULL))); } struct SendVoxelsOperationArgs { @@ -1778,7 +1780,7 @@ void Application::exportVoxels(const VoxelDetail& sourceVoxel) { QString desktopLocation = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation); QString suggestedName = desktopLocation.append("/voxels.svo"); - QString fileNameString = QFileDialog::getSaveFileName(DependencyManager::get(), + QString fileNameString = QFileDialog::getSaveFileName(DependencyManager::get().data(), tr("Export Voxels"), suggestedName, tr("Sparse Voxel Octree Files (*.svo)")); QByteArray fileNameAscii = fileNameString.toLocal8Bit(); @@ -2034,9 +2036,9 @@ void Application::init() { _metavoxels.init(); - GLCanvas* glCanvas = DependencyManager::get(); - _audio.init(glCanvas); - _rearMirrorTools = new RearMirrorTools(glCanvas, _mirrorViewRect, _settings); + QSharedPointer glCanvas = DependencyManager::get(); + _audio.init(glCanvas.data()); + _rearMirrorTools = new RearMirrorTools(glCanvas.data(), _mirrorViewRect, _settings); connect(_rearMirrorTools, SIGNAL(closeView()), SLOT(closeMirrorView())); connect(_rearMirrorTools, SIGNAL(restoreView()), SLOT(restoreMirrorView())); @@ -2115,7 +2117,7 @@ void Application::updateMouseRay() { void Application::updateFaceshift() { bool showWarnings = Menu::getInstance()->isOptionChecked(MenuOption::PipelineWarnings); PerformanceWarning warn(showWarnings, "Application::updateFaceshift()"); - Faceshift* faceshift = DependencyManager::get(); + Faceshift* faceshift = DependencyManager::get().data(); // Update faceshift faceshift->update(); @@ -2919,7 +2921,7 @@ void Application::updateShadowMap() { fbo->release(); - GLCanvas* glCanvas = DependencyManager::get(); + QSharedPointer glCanvas = DependencyManager::get(); glViewport(0, 0, glCanvas->getDeviceWidth(), glCanvas->getDeviceHeight()); } @@ -3247,7 +3249,7 @@ void Application::computeOffAxisFrustum(float& left, float& right, float& bottom } glm::vec2 Application::getScaledScreenPoint(glm::vec2 projectedPoint) { - GLCanvas* glCanvas = DependencyManager::get(); + QSharedPointer glCanvas = DependencyManager::get(); float horizontalScale = glCanvas->getDeviceWidth() / 2.0f; float verticalScale = glCanvas->getDeviceHeight() / 2.0f; @@ -4260,7 +4262,7 @@ void Application::setPreviousScriptLocation(const QString& previousScriptLocatio void Application::loadDialog() { - QString fileNameString = QFileDialog::getOpenFileName(DependencyManager::get(), + QString fileNameString = QFileDialog::getOpenFileName(DependencyManager::get().data(), tr("Open Script"), getPreviousScriptLocation(), tr("JavaScript Files (*.js)")); @@ -4297,7 +4299,7 @@ void Application::loadScriptURLDialog() { void Application::toggleLogDialog() { if (! _logDialog) { - _logDialog = new LogDialog(DependencyManager::get(), getLogger()); + _logDialog = new LogDialog(DependencyManager::get().data(), getLogger()); } if (_logDialog->isVisible()) { @@ -4357,7 +4359,7 @@ void Application::parseVersionXml() { } if (!shouldSkipVersion(latestVersion) && applicationVersion() != latestVersion) { - new UpdateDialog(DependencyManager::get(), releaseNotes, latestVersion, downloadUrl); + new UpdateDialog(DependencyManager::get().data(), releaseNotes, latestVersion, downloadUrl); } sender->deleteLater(); } @@ -4390,7 +4392,7 @@ void Application::takeSnapshot() { } if (!_snapshotShareDialog) { - _snapshotShareDialog = new SnapshotShareDialog(fileName, DependencyManager::get()); + _snapshotShareDialog = new SnapshotShareDialog(fileName, DependencyManager::get().data()); } _snapshotShareDialog->show(); } diff --git a/interface/src/Application.h b/interface/src/Application.h index cddaeaad15..31f6d7d50a 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -173,7 +173,6 @@ public: glm::vec3 getMouseVoxelWorldCoordinates(const VoxelDetail& mouseVoxel); bool isThrottleRendering() const { return DependencyManager::get()->isThrottleRendering(); } - GLCanvas* getGLWidget() { return DependencyManager::get(); } // TODO: remove MyAvatar* getAvatar() { return _myAvatar; } Audio* getAudio() { return &_audio; } Camera* getCamera() { return &_myCamera; } diff --git a/interface/src/Camera.cpp b/interface/src/Camera.cpp index d069afb96a..181f783af1 100644 --- a/interface/src/Camera.cpp +++ b/interface/src/Camera.cpp @@ -95,10 +95,8 @@ void Camera::setFarClip(float f) { } PickRay Camera::computePickRay(float x, float y) { - float screenWidth = Application::getInstance()->getGLWidget()->width(); - float screenHeight = Application::getInstance()->getGLWidget()->height(); - - return computeViewPickRay(x / screenWidth, y / screenHeight); + QSharedPointer glCanvas = DependencyManager::get(); + return computeViewPickRay(x / glCanvas->width(), y / glCanvas->height()); } PickRay Camera::computeViewPickRay(float xRatio, float yRatio) { diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 14327bd51a..501da725e4 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -436,12 +436,12 @@ Menu::Menu() : MenuOption::Faceshift, 0, true, - DependencyManager::get(), + DependencyManager::get().data(), SLOT(setTCPEnabled(bool))); #endif #ifdef HAVE_VISAGE addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::Visage, 0, false, - DependencyManager::get(), SLOT(updateEnabled())); + DependencyManager::get().data(), SLOT(updateEnabled())); #endif addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::RenderSkeletonCollisionShapes); @@ -1050,11 +1050,11 @@ void Menu::bumpSettings() { void sendFakeEnterEvent() { QPoint lastCursorPosition = QCursor::pos(); - QGLWidget* glWidget = Application::getInstance()->getGLWidget(); + QSharedPointer glCanvas = DependencyManager::get(); - QPoint windowPosition = glWidget->mapFromGlobal(lastCursorPosition); + QPoint windowPosition = glCanvas->mapFromGlobal(lastCursorPosition); QEnterEvent enterEvent = QEnterEvent(windowPosition, windowPosition, lastCursorPosition); - QCoreApplication::sendEvent(glWidget, &enterEvent); + QCoreApplication::sendEvent(glCanvas.data(), &enterEvent); } const float DIALOG_RATIO_OF_WINDOW = 0.30f; @@ -1302,7 +1302,7 @@ void Menu::toggleLoginMenuItem() { void Menu::bandwidthDetails() { if (! _bandwidthDialog) { - _bandwidthDialog = new BandwidthDialog(Application::getInstance()->getGLWidget(), + _bandwidthDialog = new BandwidthDialog(DependencyManager::get().data(), Application::getInstance()->getBandwidthMeter()); connect(_bandwidthDialog, SIGNAL(closed()), SLOT(bandwidthDetailsClosed())); @@ -1413,7 +1413,7 @@ void Menu::bandwidthDetailsClosed() { void Menu::octreeStatsDetails() { if (!_octreeStatsDialog) { - _octreeStatsDialog = new OctreeStatsDialog(Application::getInstance()->getGLWidget(), + _octreeStatsDialog = new OctreeStatsDialog(DependencyManager::get().data(), Application::getInstance()->getOcteeSceneStats()); connect(_octreeStatsDialog, SIGNAL(closed()), SLOT(octreeStatsDetailsClosed())); _octreeStatsDialog->show(); @@ -1597,7 +1597,7 @@ bool Menu::shouldRenderMesh(float largestDimension, float distanceToCamera) { void Menu::lodTools() { if (!_lodToolsDialog) { - _lodToolsDialog = new LodToolsDialog(Application::getInstance()->getGLWidget()); + _lodToolsDialog = new LodToolsDialog(DependencyManager::get().data()); connect(_lodToolsDialog, SIGNAL(closed()), SLOT(lodToolsClosed())); _lodToolsDialog->show(); if (_hmdToolsDialog) { @@ -1617,7 +1617,7 @@ void Menu::lodToolsClosed() { void Menu::hmdTools(bool showTools) { if (showTools) { if (!_hmdToolsDialog) { - _hmdToolsDialog = new HMDToolsDialog(Application::getInstance()->getGLWidget()); + _hmdToolsDialog = new HMDToolsDialog(DependencyManager::get().data()); connect(_hmdToolsDialog, SIGNAL(closed()), SLOT(hmdToolsClosed())); } _hmdToolsDialog->show(); diff --git a/interface/src/avatar/Head.cpp b/interface/src/avatar/Head.cpp index 42b3c968e1..150b67eb13 100644 --- a/interface/src/avatar/Head.cpp +++ b/interface/src/avatar/Head.cpp @@ -71,20 +71,19 @@ void Head::reset() { } void Head::simulate(float deltaTime, bool isMine, bool billboard) { - if (isMine) { MyAvatar* myAvatar = static_cast(_owningAvatar); // Only use face trackers when not playing back a recording. if (!myAvatar->isPlaying()) { FaceTracker* faceTracker = Application::getInstance()->getActiveFaceTracker(); - DdeFaceTracker* dde = DependencyManager::get(); - Faceshift* faceshift = DependencyManager::get(); + QSharedPointer dde = DependencyManager::get(); + QSharedPointer faceshift = DependencyManager::get(); if ((_isFaceshiftConnected = (faceshift == faceTracker))) { _blendshapeCoefficients = faceTracker->getBlendshapeCoefficients(); } else if (dde->isActive()) { - faceTracker = dde; + faceTracker = dde.data(); _blendshapeCoefficients = faceTracker->getBlendshapeCoefficients(); } } diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 17cda19980..a546560ffd 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -422,7 +422,7 @@ void MyAvatar::render(const glm::vec3& cameraPosition, RenderMode renderMode, bo } void MyAvatar::renderHeadMouse(int screenWidth, int screenHeight) const { - Faceshift* faceshift = DependencyManager::get(); + QSharedPointer faceshift = DependencyManager::get(); float pixelsPerDegree = screenHeight / Menu::getInstance()->getFieldOfView(); diff --git a/interface/src/devices/DdeFaceTracker.h b/interface/src/devices/DdeFaceTracker.h index d80aa043e4..5ae17729d4 100644 --- a/interface/src/devices/DdeFaceTracker.h +++ b/interface/src/devices/DdeFaceTracker.h @@ -18,8 +18,9 @@ #include "FaceTracker.h" -class DdeFaceTracker : public FaceTracker, public DependencyManager::Dependency { +class DdeFaceTracker : public FaceTracker { Q_OBJECT + SINGLETON_DEPENDENCY public: //initialization @@ -58,7 +59,6 @@ private: DdeFaceTracker(); DdeFaceTracker(const QHostAddress& host, quint16 port); ~DdeFaceTracker(); - friend DependencyManager; float getBlendshapeCoefficient(int index) const; void decodePacket(const QByteArray& buffer); diff --git a/interface/src/devices/Faceshift.h b/interface/src/devices/Faceshift.h index 3cca8f2bb1..73971db49d 100644 --- a/interface/src/devices/Faceshift.h +++ b/interface/src/devices/Faceshift.h @@ -24,8 +24,9 @@ #include "FaceTracker.h" /// Handles interaction with the Faceshift software, which provides head position/orientation and facial features. -class Faceshift : public FaceTracker, public DependencyManager::Dependency { +class Faceshift : public FaceTracker { Q_OBJECT + SINGLETON_DEPENDENCY public: void init(); @@ -89,7 +90,6 @@ private slots: private: Faceshift(); virtual ~Faceshift() {} - friend DependencyManager; float getBlendshapeCoefficient(int index) const; diff --git a/interface/src/devices/OculusManager.cpp b/interface/src/devices/OculusManager.cpp index dfec98c358..99515cb7a9 100644 --- a/interface/src/devices/OculusManager.cpp +++ b/interface/src/devices/OculusManager.cpp @@ -560,8 +560,8 @@ void OculusManager::display(const glm::quat &bodyOrientation, const glm::vec3 &p } // restore our normal viewport - glViewport(0, 0, Application::getInstance()->getGLWidget()->getDeviceWidth(), - Application::getInstance()->getGLWidget()->getDeviceHeight()); + QSharedPointer glCanvas = DependencyManager::get(); + glViewport(0, 0, glCanvas->getDeviceWidth(), glCanvas->getDeviceHeight()); glMatrixMode(GL_PROJECTION); glPopMatrix(); @@ -579,8 +579,8 @@ void OculusManager::display(const glm::quat &bodyOrientation, const glm::vec3 &p void OculusManager::renderDistortionMesh(ovrPosef eyeRenderPose[ovrEye_Count]) { glLoadIdentity(); - gluOrtho2D(0, Application::getInstance()->getGLWidget()->getDeviceWidth(), 0, - Application::getInstance()->getGLWidget()->getDeviceHeight()); + QSharedPointer glCanvas = DependencyManager::get(); + gluOrtho2D(0, glCanvas->getDeviceWidth(), 0, glCanvas->getDeviceHeight()); glDisable(GL_DEPTH_TEST); diff --git a/interface/src/devices/PrioVR.cpp b/interface/src/devices/PrioVR.cpp index d3e985d259..ab7c317c37 100644 --- a/interface/src/devices/PrioVR.cpp +++ b/interface/src/devices/PrioVR.cpp @@ -215,8 +215,9 @@ void PrioVR::renderCalibrationCountdown() { static TextRenderer* textRenderer = TextRenderer::getInstance(MONO_FONT_FAMILY, 18, QFont::Bold, false, TextRenderer::OUTLINE_EFFECT, 2); QByteArray text = "Assume T-Pose in " + QByteArray::number(secondsRemaining) + "..."; - textRenderer->draw((Application::getInstance()->getGLWidget()->width() - - textRenderer->computeWidth(text.constData())) / 2, Application::getInstance()->getGLWidget()->height() / 2, - text); + QSharedPointer glCanvas = DependencyManager::get(); + textRenderer->draw((glCanvas->width() - textRenderer->computeWidth(text.constData())) / 2, + glCanvas->height() / 2, + text); #endif } diff --git a/interface/src/devices/SixenseManager.cpp b/interface/src/devices/SixenseManager.cpp index 7a555eb902..73e4f53289 100644 --- a/interface/src/devices/SixenseManager.cpp +++ b/interface/src/devices/SixenseManager.cpp @@ -461,7 +461,7 @@ void SixenseManager::updateCalibration(const sixenseControllerData* controllers) void SixenseManager::emulateMouse(PalmData* palm, int index) { Application* application = Application::getInstance(); MyAvatar* avatar = application->getAvatar(); - GLCanvas* widget = application->getGLWidget(); + QSharedPointer glCanvas = DependencyManager::get(); QPoint pos; Qt::MouseButton bumperButton; @@ -489,10 +489,10 @@ void SixenseManager::emulateMouse(PalmData* palm, int index) { float yAngle = 0.5f - ((atan2(direction.z, direction.y) + M_PI_2)); // Get the pixel range over which the xAngle and yAngle are scaled - float cursorRange = widget->width() * getCursorPixelRangeMult(); + float cursorRange = glCanvas->width() * getCursorPixelRangeMult(); - pos.setX(widget->width() / 2.0f + cursorRange * xAngle); - pos.setY(widget->height() / 2.0f + cursorRange * yAngle); + pos.setX(glCanvas->width() / 2.0f + cursorRange * xAngle); + pos.setY(glCanvas->height() / 2.0f + cursorRange * yAngle); } diff --git a/interface/src/devices/TV3DManager.cpp b/interface/src/devices/TV3DManager.cpp index d7d7353b24..5c891224a8 100644 --- a/interface/src/devices/TV3DManager.cpp +++ b/interface/src/devices/TV3DManager.cpp @@ -33,10 +33,10 @@ bool TV3DManager::isConnected() { } void TV3DManager::connect() { - Application* app = Application::getInstance(); - int width = app->getGLWidget()->getDeviceWidth(); - int height = app->getGLWidget()->getDeviceHeight(); - Camera& camera = *app->getCamera(); + QSharedPointer glCanvas = DependencyManager::get(); + int width = glCanvas->getDeviceWidth(); + int height = glCanvas->getDeviceHeight(); + Camera& camera = *Application::getInstance()->getCamera(); configureCamera(camera, width, height); } @@ -91,7 +91,8 @@ void TV3DManager::display(Camera& whichCamera) { // left eye portal int portalX = 0; int portalY = 0; - QSize deviceSize = Application::getInstance()->getGLWidget()->getDeviceSize() * + QSharedPointer glCanvas = DependencyManager::get(); + QSize deviceSize = glCanvas->getDeviceSize() * Application::getInstance()->getRenderResolutionScale(); int portalW = deviceSize.width() / 2; int portalH = deviceSize.height(); diff --git a/interface/src/devices/Visage.cpp b/interface/src/devices/Visage.cpp index 51b927df75..a810b1a258 100644 --- a/interface/src/devices/Visage.cpp +++ b/interface/src/devices/Visage.cpp @@ -121,7 +121,7 @@ static const QMultiHash >& getActionUnitNameMap() const float TRANSLATION_SCALE = 20.0f; void Visage::init() { - connect(DependencyManager::get(), SIGNAL(connectionStateChanged()), SLOT(updateEnabled())); + connect(DependencyManager::get().data(), SIGNAL(connectionStateChanged()), SLOT(updateEnabled())); updateEnabled(); } diff --git a/interface/src/devices/Visage.h b/interface/src/devices/Visage.h index 73edddc4d7..38e337aada 100644 --- a/interface/src/devices/Visage.h +++ b/interface/src/devices/Visage.h @@ -26,8 +26,9 @@ namespace VisageSDK { } /// Handles input from the Visage webcam feature tracking software. -class Visage : public FaceTracker, public DependencyManager::Dependency { +class Visage : public FaceTracker { Q_OBJECT + SINGLETON_DEPENDENCY public: void init(); @@ -44,7 +45,6 @@ public slots: private: Visage(); virtual ~Visage(); - friend DependencyManager; #ifdef HAVE_VISAGE VisageSDK::VisageTracker2* _tracker; diff --git a/interface/src/renderer/GlowEffect.cpp b/interface/src/renderer/GlowEffect.cpp index 9e9c1f2ed5..a760889eff 100644 --- a/interface/src/renderer/GlowEffect.cpp +++ b/interface/src/renderer/GlowEffect.cpp @@ -139,15 +139,15 @@ QOpenGLFramebufferObject* GlowEffect::render(bool toTexture) { QOpenGLFramebufferObject* destFBO = toTexture ? Application::getInstance()->getTextureCache()->getSecondaryFramebufferObject() : NULL; + QSharedPointer glCanvas = DependencyManager::get(); if (!Menu::getInstance()->isOptionChecked(MenuOption::EnableGlowEffect) || _isEmpty) { // copy the primary to the screen if (destFBO && QOpenGLFramebufferObject::hasOpenGLFramebufferBlit()) { - QOpenGLFramebufferObject::blitFramebuffer(destFBO, primaryFBO); + QOpenGLFramebufferObject::blitFramebuffer(destFBO, primaryFBO); } else { maybeBind(destFBO); if (!destFBO) { - glViewport(0, 0, Application::getInstance()->getGLWidget()->getDeviceWidth(), - Application::getInstance()->getGLWidget()->getDeviceHeight()); + glViewport(0, 0, glCanvas->getDeviceWidth(), glCanvas->getDeviceHeight()); } glEnable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); @@ -194,9 +194,7 @@ QOpenGLFramebufferObject* GlowEffect::render(bool toTexture) { } maybeBind(destFBO); if (!destFBO) { - glViewport(0, 0, - Application::getInstance()->getGLWidget()->getDeviceWidth(), - Application::getInstance()->getGLWidget()->getDeviceHeight()); + glViewport(0, 0, glCanvas->getDeviceWidth(), glCanvas->getDeviceHeight()); } _addSeparateProgram->bind(); renderFullscreenQuad(); diff --git a/interface/src/renderer/TextureCache.cpp b/interface/src/renderer/TextureCache.cpp index f40f0e3faf..ec07d22647 100644 --- a/interface/src/renderer/TextureCache.cpp +++ b/interface/src/renderer/TextureCache.cpp @@ -352,7 +352,7 @@ QSharedPointer TextureCache::createResource(const QUrl& url, QOpenGLFramebufferObject* TextureCache::createFramebufferObject() { QOpenGLFramebufferObject* fbo = new QOpenGLFramebufferObject(_frameBufferSize); - Application::getInstance()->getGLWidget()->installEventFilter(this); + DependencyManager::get()->installEventFilter(this); glBindTexture(GL_TEXTURE_2D, fbo->texture()); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); diff --git a/interface/src/scripting/ControllerScriptingInterface.cpp b/interface/src/scripting/ControllerScriptingInterface.cpp index bcfe844668..a562236a92 100644 --- a/interface/src/scripting/ControllerScriptingInterface.cpp +++ b/interface/src/scripting/ControllerScriptingInterface.cpp @@ -267,9 +267,9 @@ void ControllerScriptingInterface::releaseJoystick(int joystickIndex) { } } -glm::vec2 ControllerScriptingInterface::getViewportDimensions() const { - GLCanvas* widget = Application::getInstance()->getGLWidget(); - return glm::vec2(widget->width(), widget->height()); +glm::vec2 ControllerScriptingInterface::getViewportDimensions() const { + QSharedPointer glCanvas = DependencyManager::get(); + return glm::vec2(glCanvas->width(), glCanvas->height()); } AbstractInputController* ControllerScriptingInterface::createInputController(const QString& deviceName, const QString& tracker) { diff --git a/interface/src/scripting/WindowScriptingInterface.cpp b/interface/src/scripting/WindowScriptingInterface.cpp index d69b1d0ba1..d84fc97cd8 100644 --- a/interface/src/scripting/WindowScriptingInterface.cpp +++ b/interface/src/scripting/WindowScriptingInterface.cpp @@ -40,7 +40,7 @@ WebWindowClass* WindowScriptingInterface::doCreateWebWindow(const QString& title } QScriptValue WindowScriptingInterface::hasFocus() { - return Application::getInstance()->getGLWidget()->hasFocus(); + return DependencyManager::get()->hasFocus(); } void WindowScriptingInterface::setCursorVisible(bool visible) { diff --git a/interface/src/ui/ApplicationOverlay.cpp b/interface/src/ui/ApplicationOverlay.cpp index f4e0c9769d..c95dc08e79 100644 --- a/interface/src/ui/ApplicationOverlay.cpp +++ b/interface/src/ui/ApplicationOverlay.cpp @@ -145,11 +145,11 @@ void ApplicationOverlay::renderOverlay(bool renderToTexture) { PerformanceWarning warn(Menu::getInstance()->isOptionChecked(MenuOption::PipelineWarnings), "ApplicationOverlay::displayOverlay()"); Application* application = Application::getInstance(); Overlays& overlays = application->getOverlays(); - GLCanvas* glWidget = application->getGLWidget(); + QSharedPointer glCanvas = DependencyManager::get(); MyAvatar* myAvatar = application->getAvatar(); _textureFov = glm::radians(Menu::getInstance()->getOculusUIAngularSize()); - _textureAspectRatio = (float)application->getGLWidget()->getDeviceWidth() / (float)application->getGLWidget()->getDeviceHeight(); + _textureAspectRatio = (float)glCanvas->getDeviceWidth() / (float)glCanvas->getDeviceHeight(); //Handle fading and deactivation/activation of UI if (Menu::getInstance()->isOptionChecked(MenuOption::UserInterface)) { @@ -178,12 +178,12 @@ void ApplicationOverlay::renderOverlay(bool renderToTexture) { glPushMatrix(); { glLoadIdentity(); - gluOrtho2D(0, glWidget->width(), glWidget->height(), 0); + gluOrtho2D(0, glCanvas->width(), glCanvas->height(), 0); renderAudioMeter(); if (Menu::getInstance()->isOptionChecked(MenuOption::HeadMouse)) { - myAvatar->renderHeadMouse(glWidget->width(), glWidget->height()); + myAvatar->renderHeadMouse(glCanvas->width(), glCanvas->height()); } renderStatsAndLogs(); @@ -213,7 +213,7 @@ void ApplicationOverlay::displayOverlayTexture() { if (_alpha == 0.0f) { return; } - GLCanvas* glWidget = Application::getInstance()->getGLWidget(); + QSharedPointer glCanvas = DependencyManager::get(); glEnable(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE0); @@ -222,16 +222,16 @@ void ApplicationOverlay::displayOverlayTexture() { glMatrixMode(GL_PROJECTION); glPushMatrix(); { glLoadIdentity(); - gluOrtho2D(0, glWidget->getDeviceWidth(), glWidget->getDeviceHeight(), 0); + gluOrtho2D(0, glCanvas->getDeviceWidth(), glCanvas->getDeviceHeight(), 0); glDisable(GL_DEPTH_TEST); glDisable(GL_LIGHTING); glEnable(GL_BLEND); glBegin(GL_QUADS); { glColor4f(1.0f, 1.0f, 1.0f, _alpha); - glTexCoord2f(0, 0); glVertex2i(0, glWidget->getDeviceHeight()); - glTexCoord2f(1, 0); glVertex2i(glWidget->getDeviceWidth(), glWidget->getDeviceHeight()); - glTexCoord2f(1, 1); glVertex2i(glWidget->getDeviceWidth(), 0); + glTexCoord2f(0, 0); glVertex2i(0, glCanvas->getDeviceHeight()); + glTexCoord2f(1, 0); glVertex2i(glCanvas->getDeviceWidth(), glCanvas->getDeviceHeight()); + glTexCoord2f(1, 1); glVertex2i(glCanvas->getDeviceWidth(), 0); glTexCoord2f(0, 1); glVertex2i(0, 0); } glEnd(); } glPopMatrix(); @@ -378,18 +378,19 @@ void ApplicationOverlay::displayOverlayTexture3DTV(Camera& whichCamera, float as glEnd(); + QSharedPointer glCanvas = DependencyManager::get(); if (_crosshairTexture == 0) { - _crosshairTexture = Application::getInstance()->getGLWidget()->bindTexture(QImage(Application::resourcesPath() + "images/sixense-reticle.png")); + _crosshairTexture = glCanvas->bindTexture(QImage(Application::resourcesPath() + "images/sixense-reticle.png")); } //draw the mouse pointer glBindTexture(GL_TEXTURE_2D, _crosshairTexture); - const float reticleSize = 40.0f / application->getGLWidget()->width() * quadWidth; + const float reticleSize = 40.0f / glCanvas->width() * quadWidth; x -= reticleSize / 2.0f; y += reticleSize / 2.0f; - const float mouseX = (application->getMouseX() / (float)application->getGLWidget()->width()) * quadWidth; - const float mouseY = (1.0 - (application->getMouseY() / (float)application->getGLWidget()->height())) * quadHeight; + const float mouseX = (application->getMouseX() / (float)glCanvas->width()) * quadWidth; + const float mouseY = (1.0 - (application->getMouseY() / (float)glCanvas->height())) * quadHeight; glBegin(GL_QUADS); @@ -431,7 +432,7 @@ void ApplicationOverlay::computeOculusPickRay(float x, float y, glm::vec3& origi //Caculate the click location using one of the sixense controllers. Scale is not applied QPoint ApplicationOverlay::getPalmClickLocation(const PalmData *palm) const { Application* application = Application::getInstance(); - GLCanvas* glWidget = application->getGLWidget(); + QSharedPointer glCanvas = DependencyManager::get(); MyAvatar* myAvatar = application->getAvatar(); glm::vec3 tip = myAvatar->getLaserPointerTipPosition(palm); @@ -462,8 +463,8 @@ QPoint ApplicationOverlay::getPalmClickLocation(const PalmData *palm) const { float u = asin(collisionPos.x) / (_textureFov)+0.5f; float v = 1.0 - (asin(collisionPos.y) / (_textureFov)+0.5f); - rv.setX(u * glWidget->width()); - rv.setY(v * glWidget->height()); + rv.setX(u * glCanvas->width()); + rv.setY(v * glCanvas->height()); } } else { //if they did not click on the overlay, just set the coords to INT_MAX @@ -480,8 +481,8 @@ QPoint ApplicationOverlay::getPalmClickLocation(const PalmData *palm) const { ndcSpacePos = glm::vec3(clipSpacePos) / clipSpacePos.w; } - rv.setX(((ndcSpacePos.x + 1.0) / 2.0) * glWidget->width()); - rv.setY((1.0 - ((ndcSpacePos.y + 1.0) / 2.0)) * glWidget->height()); + rv.setX(((ndcSpacePos.x + 1.0) / 2.0) * glCanvas->width()); + rv.setY((1.0 - ((ndcSpacePos.y + 1.0) / 2.0)) * glCanvas->height()); } return rv; } @@ -510,10 +511,11 @@ bool ApplicationOverlay::calculateRayUICollisionPoint(const glm::vec3& position, //Renders optional pointers void ApplicationOverlay::renderPointers() { Application* application = Application::getInstance(); + QSharedPointer glCanvas = DependencyManager::get(); //lazily load crosshair texture if (_crosshairTexture == 0) { - _crosshairTexture = Application::getInstance()->getGLWidget()->bindTexture(QImage(Application::resourcesPath() + "images/sixense-reticle.png")); + _crosshairTexture = glCanvas->bindTexture(QImage(Application::resourcesPath() + "images/sixense-reticle.png")); } glEnable(GL_TEXTURE_2D); @@ -536,7 +538,7 @@ void ApplicationOverlay::renderPointers() { glm::vec2 screenPos = sphericalToScreen(glm::vec2(yaw, -pitch)); position = QPoint(screenPos.x, screenPos.y); - application->getGLWidget()->cursor().setPos(application->getGLWidget()->mapToGlobal(position)); + glCanvas->cursor().setPos(glCanvas->mapToGlobal(position)); } _reticlePosition[MOUSE] = position; @@ -557,7 +559,7 @@ void ApplicationOverlay::renderPointers() { void ApplicationOverlay::renderControllerPointers() { Application* application = Application::getInstance(); - GLCanvas* glWidget = application->getGLWidget(); + QSharedPointer glCanvas = DependencyManager::get(); MyAvatar* myAvatar = application->getAvatar(); //Static variables used for storing controller state @@ -635,14 +637,14 @@ void ApplicationOverlay::renderControllerPointers() { float yAngle = 0.5f - ((atan2(direction.z, direction.y) + M_PI_2)); // Get the pixel range over which the xAngle and yAngle are scaled - float cursorRange = glWidget->width() * SixenseManager::getInstance().getCursorPixelRangeMult(); + float cursorRange = glCanvas->width() * SixenseManager::getInstance().getCursorPixelRangeMult(); - mouseX = (glWidget->width() / 2.0f + cursorRange * xAngle); - mouseY = (glWidget->height() / 2.0f + cursorRange * yAngle); + mouseX = (glCanvas->width() / 2.0f + cursorRange * xAngle); + mouseY = (glCanvas->height() / 2.0f + cursorRange * yAngle); } //If the cursor is out of the screen then don't render it - if (mouseX < 0 || mouseX >= glWidget->width() || mouseY < 0 || mouseY >= glWidget->height()) { + if (mouseX < 0 || mouseX >= glCanvas->width() || mouseY < 0 || mouseY >= glCanvas->height()) { _reticleActive[index] = false; continue; } @@ -702,11 +704,10 @@ void ApplicationOverlay::renderPointersOculus(const glm::vec3& eyePos) { //Renders a small magnification of the currently bound texture at the coordinates void ApplicationOverlay::renderMagnifier(glm::vec2 magPos, float sizeMult, bool showBorder) const { - Application* application = Application::getInstance(); - GLCanvas* glWidget = application->getGLWidget(); + QSharedPointer glCanvas = DependencyManager::get(); - const int widgetWidth = glWidget->width(); - const int widgetHeight = glWidget->height(); + const int widgetWidth = glCanvas->width(); + const int widgetHeight = glCanvas->height(); const float halfWidth = (MAGNIFY_WIDTH / _textureAspectRatio) * sizeMult / 2.0f; const float halfHeight = MAGNIFY_HEIGHT * sizeMult / 2.0f; @@ -760,8 +761,8 @@ void ApplicationOverlay::renderMagnifier(glm::vec2 magPos, float sizeMult, bool void ApplicationOverlay::renderAudioMeter() { Application* application = Application::getInstance(); - - GLCanvas* glWidget = application->getGLWidget(); + + QSharedPointer glCanvas = DependencyManager::get(); Audio* audio = application->getAudio(); // Display a single screen-size quad to create an alpha blended 'collision' flash @@ -769,7 +770,7 @@ void ApplicationOverlay::renderAudioMeter() { float collisionSoundMagnitude = audio->getCollisionSoundMagnitude(); const float VISIBLE_COLLISION_SOUND_MAGNITUDE = 0.5f; if (collisionSoundMagnitude > VISIBLE_COLLISION_SOUND_MAGNITUDE) { - renderCollisionOverlay(glWidget->width(), glWidget->height(), + renderCollisionOverlay(glCanvas->width(), glCanvas->height(), audio->getCollisionSoundMagnitude()); } } @@ -823,14 +824,14 @@ void ApplicationOverlay::renderAudioMeter() { if ((audio->getTimeSinceLastClip() > 0.0f) && (audio->getTimeSinceLastClip() < CLIPPING_INDICATOR_TIME)) { const float MAX_MAGNITUDE = 0.7f; float magnitude = MAX_MAGNITUDE * (1 - audio->getTimeSinceLastClip() / CLIPPING_INDICATOR_TIME); - renderCollisionOverlay(glWidget->width(), glWidget->height(), magnitude, 1.0f); + renderCollisionOverlay(glCanvas->width(), glCanvas->height(), magnitude, 1.0f); } audio->renderToolBox(MIRROR_VIEW_LEFT_PADDING + AUDIO_METER_GAP, audioMeterY, boxed); - audio->renderScope(glWidget->width(), glWidget->height()); + audio->renderScope(glCanvas->width(), glCanvas->height()); - audio->renderStats(WHITE_TEXT, glWidget->width(), glWidget->height()); + audio->renderStats(WHITE_TEXT, glCanvas->width(), glCanvas->height()); glBegin(GL_QUADS); if (isClipping) { @@ -891,8 +892,8 @@ void ApplicationOverlay::renderAudioMeter() { void ApplicationOverlay::renderStatsAndLogs() { Application* application = Application::getInstance(); - - GLCanvas* glWidget = application->getGLWidget(); + + QSharedPointer glCanvas = DependencyManager::get(); const OctreePacketProcessor& octreePacketProcessor = application->getOctreePacketProcessor(); BandwidthMeter* bandwidthMeter = application->getBandwidthMeter(); NodeBounds& nodeBoundsDisplay = application->getNodeBoundsDisplay(); @@ -910,8 +911,8 @@ void ApplicationOverlay::renderStatsAndLogs() { application->getPacketsPerSecond(), application->getBytesPerSecond(), voxelPacketsToProcess); // Bandwidth meter if (Menu::getInstance()->isOptionChecked(MenuOption::Bandwidth)) { - Stats::drawBackground(0x33333399, glWidget->width() - 296, glWidget->height() - 68, 296, 68); - bandwidthMeter->render(glWidget->width(), glWidget->height()); + Stats::drawBackground(0x33333399, glCanvas->width() - 296, glCanvas->height() - 68, 296, 68); + bandwidthMeter->render(glCanvas->width(), glCanvas->height()); } } @@ -924,7 +925,7 @@ void ApplicationOverlay::renderStatsAndLogs() { (Menu::getInstance()->isOptionChecked(MenuOption::Stats) && Menu::getInstance()->isOptionChecked(MenuOption::Bandwidth)) ? 80 : 20; - drawText(glWidget->width() - 100, glWidget->height() - timerBottom, + drawText(glCanvas->width() - 100, glCanvas->height() - timerBottom, 0.30f, 0.0f, 0, frameTimer, WHITE_TEXT); } nodeBoundsDisplay.drawOverlay(); @@ -934,9 +935,9 @@ void ApplicationOverlay::renderDomainConnectionStatusBorder() { NodeList* nodeList = NodeList::getInstance(); if (nodeList && !nodeList->getDomainHandler().isConnected()) { - GLCanvas* glWidget = Application::getInstance()->getGLWidget(); - int right = glWidget->width(); - int bottom = glWidget->height(); + QSharedPointer glCanvas = DependencyManager::get(); + int right = glCanvas->width(); + int bottom = glCanvas->height(); glColor3f(CONNECTION_STATUS_BORDER_COLOR[0], CONNECTION_STATUS_BORDER_COLOR[1], @@ -1071,7 +1072,7 @@ void ApplicationOverlay::TexturedHemisphere::cleanupVBO() { } void ApplicationOverlay::TexturedHemisphere::buildFramebufferObject() { - QSize size = Application::getInstance()->getGLWidget()->getDeviceSize(); + QSize size = DependencyManager::get()->getDeviceSize(); if (_framebufferObject != NULL && size == _framebufferObject->size()) { // Already build return; @@ -1122,7 +1123,7 @@ void ApplicationOverlay::TexturedHemisphere::render() { glm::vec2 ApplicationOverlay::screenToSpherical(glm::vec2 screenPos) const { - QSize screenSize = Application::getInstance()->getGLWidget()->getDeviceSize(); + QSize screenSize = DependencyManager::get()->getDeviceSize(); float yaw = -(screenPos.x / screenSize.width() - 0.5f) * MOUSE_YAW_RANGE; float pitch = (screenPos.y / screenSize.height() - 0.5f) * MOUSE_PITCH_RANGE; @@ -1130,7 +1131,7 @@ glm::vec2 ApplicationOverlay::screenToSpherical(glm::vec2 screenPos) const { } glm::vec2 ApplicationOverlay::sphericalToScreen(glm::vec2 sphericalPos) const { - QSize screenSize = Application::getInstance()->getGLWidget()->getDeviceSize(); + QSize screenSize = DependencyManager::get()->getDeviceSize(); float x = (-sphericalPos.x / MOUSE_YAW_RANGE + 0.5f) * screenSize.width(); float y = (sphericalPos.y / MOUSE_PITCH_RANGE + 0.5f) * screenSize.height(); @@ -1138,7 +1139,7 @@ glm::vec2 ApplicationOverlay::sphericalToScreen(glm::vec2 sphericalPos) const { } glm::vec2 ApplicationOverlay::sphericalToOverlay(glm::vec2 sphericalPos) const { - QSize screenSize = Application::getInstance()->getGLWidget()->getDeviceSize(); + QSize screenSize = DependencyManager::get()->getDeviceSize(); float x = (-sphericalPos.x / (_textureFov * _textureAspectRatio) + 0.5f) * screenSize.width(); float y = (sphericalPos.y / _textureFov + 0.5f) * screenSize.height(); @@ -1146,7 +1147,7 @@ glm::vec2 ApplicationOverlay::sphericalToOverlay(glm::vec2 sphericalPos) const { } glm::vec2 ApplicationOverlay::overlayToSpherical(glm::vec2 overlayPos) const { - QSize screenSize = Application::getInstance()->getGLWidget()->getDeviceSize(); + QSize screenSize = DependencyManager::get()->getDeviceSize(); float yaw = -(overlayPos.x / screenSize.width() - 0.5f) * _textureFov * _textureAspectRatio; float pitch = (overlayPos.y / screenSize.height() - 0.5f) * _textureFov; diff --git a/interface/src/ui/MetavoxelEditor.cpp b/interface/src/ui/MetavoxelEditor.cpp index 46f69b0452..75f2ebf97f 100644 --- a/interface/src/ui/MetavoxelEditor.cpp +++ b/interface/src/ui/MetavoxelEditor.cpp @@ -138,7 +138,7 @@ MetavoxelEditor::MetavoxelEditor() : connect(Application::getInstance()->getMetavoxels(), &MetavoxelSystem::rendering, this, &MetavoxelEditor::renderPreview); - Application::getInstance()->getGLWidget()->installEventFilter(this); + DependencyManager::get()->installEventFilter(this); show(); diff --git a/interface/src/ui/MetavoxelNetworkSimulator.cpp b/interface/src/ui/MetavoxelNetworkSimulator.cpp index aabee97636..7185524d6f 100644 --- a/interface/src/ui/MetavoxelNetworkSimulator.cpp +++ b/interface/src/ui/MetavoxelNetworkSimulator.cpp @@ -21,7 +21,7 @@ const int BYTES_PER_KILOBYTE = 1024; MetavoxelNetworkSimulator::MetavoxelNetworkSimulator() : - QWidget(Application::getInstance()->getGLWidget(), Qt::Dialog) { + QWidget(DependencyManager::get().data(), Qt::Dialog) { setWindowTitle("Metavoxel Network Simulator"); setAttribute(Qt::WA_DeleteOnClose); diff --git a/interface/src/ui/PreferencesDialog.cpp b/interface/src/ui/PreferencesDialog.cpp index 318dce977a..d39266e0fd 100644 --- a/interface/src/ui/PreferencesDialog.cpp +++ b/interface/src/ui/PreferencesDialog.cpp @@ -215,8 +215,8 @@ void PreferencesDialog::savePreferences() { myAvatar->setClampedTargetScale(ui.avatarScaleSpin->value()); Application::getInstance()->getVoxels()->setMaxVoxels(ui.maxVoxelsSpin->value()); - Application::getInstance()->resizeGL(Application::getInstance()->getGLWidget()->width(), - Application::getInstance()->getGLWidget()->height()); + QSharedPointer glCanvas = DependencyManager::get(); + Application::getInstance()->resizeGL(glCanvas->width(), glCanvas->height()); Menu::getInstance()->setRealWorldFieldOfView(ui.realWorldFieldOfViewSpin->value()); @@ -248,8 +248,7 @@ void PreferencesDialog::savePreferences() { Menu::getInstance()->setReceivedAudioStreamSettings(streamSettings); Application::getInstance()->getAudio()->setReceivedAudioStreamSettings(streamSettings); - Application::getInstance()->resizeGL(Application::getInstance()->getGLWidget()->width(), - Application::getInstance()->getGLWidget()->height()); + Application::getInstance()->resizeGL(glCanvas->width(), glCanvas->height()); Application::getInstance()->bumpSettings(); } diff --git a/interface/src/ui/Snapshot.cpp b/interface/src/ui/Snapshot.cpp index d68920a5f5..ddd2b93805 100644 --- a/interface/src/ui/Snapshot.cpp +++ b/interface/src/ui/Snapshot.cpp @@ -83,9 +83,8 @@ QTemporaryFile* Snapshot::saveTempSnapshot() { } QFile* Snapshot::savedFileForSnapshot(bool isTemporary) { - - QGLWidget* widget = Application::getInstance()->getGLWidget(); - QImage shot = widget->grabFrameBuffer(); + QSharedPointer glCanvas = DependencyManager::get(); + QImage shot = glCanvas->grabFrameBuffer(); Avatar* avatar = Application::getInstance()->getAvatar(); diff --git a/interface/src/ui/Stats.cpp b/interface/src/ui/Stats.cpp index 9abb3d1b78..2581866c70 100644 --- a/interface/src/ui/Stats.cpp +++ b/interface/src/ui/Stats.cpp @@ -56,8 +56,8 @@ Stats::Stats(): _metavoxelReceiveProgress(0), _metavoxelReceiveTotal(0) { - GLCanvas* glWidget = Application::getInstance()->getGLWidget(); - resetWidth(glWidget->width(), 0); + QSharedPointer glCanvas = DependencyManager::get(); + resetWidth(glCanvas->width(), 0); } void Stats::toggleExpanded() { @@ -67,7 +67,7 @@ void Stats::toggleExpanded() { // called on mouse click release // check for clicks over stats in order to expand or contract them void Stats::checkClick(int mouseX, int mouseY, int mouseDragStartedX, int mouseDragStartedY, int horizontalOffset) { - GLCanvas* glWidget = Application::getInstance()->getGLWidget(); + QSharedPointer glCanvas = DependencyManager::get(); if (0 != glm::compMax(glm::abs(glm::ivec2(mouseX - mouseDragStartedX, mouseY - mouseDragStartedY)))) { // not worried about dragging on stats @@ -114,7 +114,7 @@ void Stats::checkClick(int mouseX, int mouseY, int mouseDragStartedX, int mouseD // top-right stats click lines = _expanded ? 11 : 3; statsHeight = lines * STATS_PELS_PER_LINE + 10; - statsWidth = glWidget->width() - statsX; + statsWidth = glCanvas->width() - statsX; if (mouseX > statsX && mouseX < statsX + statsWidth && mouseY > statsY && mouseY < statsY + statsHeight) { toggleExpanded(); return; @@ -122,8 +122,8 @@ void Stats::checkClick(int mouseX, int mouseY, int mouseDragStartedX, int mouseD } void Stats::resetWidth(int width, int horizontalOffset) { - GLCanvas* glWidget = Application::getInstance()->getGLWidget(); - int extraSpace = glWidget->width() - horizontalOffset -2 + QSharedPointer glCanvas = DependencyManager::get(); + int extraSpace = glCanvas->width() - horizontalOffset -2 - STATS_GENERAL_MIN_WIDTH - (Menu::getInstance()->isOptionChecked(MenuOption::TestPing) ? STATS_PING_MIN_WIDTH -1 : 0) - STATS_GEO_MIN_WIDTH @@ -147,7 +147,7 @@ void Stats::resetWidth(int width, int horizontalOffset) { _pingStatsWidth += (int) extraSpace / panels; } _geoStatsWidth += (int) extraSpace / panels; - _voxelStatsWidth += glWidget->width() - (_generalStatsWidth + _pingStatsWidth + _geoStatsWidth + 3); + _voxelStatsWidth += glCanvas->width() - (_generalStatsWidth + _pingStatsWidth + _geoStatsWidth + 3); } } @@ -198,7 +198,7 @@ void Stats::display( int bytesPerSecond, int voxelPacketsToProcess) { - GLCanvas* glWidget = Application::getInstance()->getGLWidget(); + QSharedPointer glCanvas = DependencyManager::get(); unsigned int backgroundColor = 0x33333399; int verticalOffset = 0, lines = 0; @@ -210,7 +210,7 @@ void Stats::display( std::stringstream voxelStats; if (_lastHorizontalOffset != horizontalOffset) { - resetWidth(glWidget->width(), horizontalOffset); + resetWidth(glCanvas->width(), horizontalOffset); _lastHorizontalOffset = horizontalOffset; } @@ -478,7 +478,7 @@ void Stats::display( lines = _expanded ? 14 : 3; - drawBackground(backgroundColor, horizontalOffset, 0, glWidget->width() - horizontalOffset, + drawBackground(backgroundColor, horizontalOffset, 0, glCanvas->width() - horizontalOffset, lines * STATS_PELS_PER_LINE + 10); horizontalOffset += 5; From 892141fe14f485c55e3c17738eec5d66a197d39b Mon Sep 17 00:00:00 2001 From: Andrzej Kapolka Date: Mon, 15 Dec 2014 16:36:26 -0800 Subject: [PATCH 122/258] Fix for crash on exit due to cache references' not being cleared. --- libraries/networking/src/ResourceCache.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/libraries/networking/src/ResourceCache.cpp b/libraries/networking/src/ResourceCache.cpp index 097ede23d0..5bb327fe63 100644 --- a/libraries/networking/src/ResourceCache.cpp +++ b/libraries/networking/src/ResourceCache.cpp @@ -28,9 +28,13 @@ ResourceCache::ResourceCache(QObject* parent) : } ResourceCache::~ResourceCache() { - // make sure our unused resources know we're out of commission - foreach (const QSharedPointer& resource, _unusedResources) { - resource->setCache(NULL); + // the unused resources may themselves reference resources that will be added to the unused + // list on destruction, so keep clearing until there are no references left + while (!_unusedResources.isEmpty()) { + foreach (const QSharedPointer& resource, _unusedResources) { + resource->setCache(NULL); + } + _unusedResources.clear(); } } From e53833b3060fe5094ef8d0c2a066820026088602 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 17:29:48 -0800 Subject: [PATCH 123/258] make GlowEffect support DependencyManager --- interface/src/Application.cpp | 10 +++++--- interface/src/Application.h | 3 --- interface/src/avatar/Avatar.cpp | 1 + interface/src/avatar/AvatarManager.cpp | 3 ++- interface/src/avatar/Head.cpp | 5 ++-- interface/src/devices/OculusManager.cpp | 5 ++-- interface/src/devices/TV3DManager.cpp | 5 ++-- interface/src/entities/EntityTreeRenderer.cpp | 2 ++ .../src/renderer/AmbientOcclusionEffect.cpp | 3 ++- .../src/renderer/DeferredLightingEffect.cpp | 5 ++-- interface/src/renderer/GlowEffect.cpp | 24 ++++++++++++------- interface/src/renderer/GlowEffect.h | 17 +++++++++---- interface/src/renderer/Model.cpp | 5 +++- .../src/ui/overlays/LocalModelsOverlay.cpp | 1 + .../src/ui/overlays/LocalVoxelsOverlay.cpp | 1 + interface/src/ui/overlays/ModelOverlay.cpp | 1 + interface/src/voxels/VoxelFade.cpp | 5 ++-- 17 files changed, 64 insertions(+), 32 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 76247d1d9d..4bc4b0d339 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -90,6 +90,8 @@ #include "gpu/Batch.h" #include "gpu/GLBackend.h" +#include "renderer/GlowEffect.h" + #include "scripting/AccountScriptingInterface.h" #include "scripting/AudioDeviceScriptingInterface.h" #include "scripting/ClipboardScriptingInterface.h" @@ -702,7 +704,7 @@ void Application::paintGL() { TV3DManager::display(*whichCamera); } else { - _glowEffect.prepare(); + DependencyManager::get()->prepare(); // Viewport is assigned to the size of the framebuffer QSize size = DependencyManager::get()->getPrimaryFramebufferObject()->size(); @@ -721,7 +723,7 @@ void Application::paintGL() { renderRearViewMirror(_mirrorViewRect); } - _glowEffect.render(); + DependencyManager::get()->render(); { PerformanceTimer perfTimer("renderOverlay"); @@ -1913,7 +1915,6 @@ void Application::init() { _environment.init(); _deferredLightingEffect.init(); - _glowEffect.init(); _ambientOcclusionEffect.init(); // TODO: move _myAvatar out of Application. Move relevant code to MyAvataar or AvatarManager @@ -2036,6 +2037,9 @@ void Application::init() { // make sure our texture cache knows about window size changes DependencyManager::get()->associateWithWidget(getGLWidget()); + + // initialize the GlowEffect with our widget + DependencyManager::get()->init(getGLWidget()); } void Application::closeMirrorView() { diff --git a/interface/src/Application.h b/interface/src/Application.h index 0e1feafb7e..716d67c661 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -63,7 +63,6 @@ #include "entities/EntityTreeRenderer.h" #include "renderer/AmbientOcclusionEffect.h" #include "renderer/DeferredLightingEffect.h" -#include "renderer/GlowEffect.h" #include "scripting/ControllerScriptingInterface.h" #include "ui/BandwidthDialog.h" #include "ui/BandwidthMeter.h" @@ -252,7 +251,6 @@ public: AnimationCache* getAnimationCache() { return &_animationCache; } DeferredLightingEffect* getDeferredLightingEffect() { return &_deferredLightingEffect; } - GlowEffect* getGlowEffect() { return &_glowEffect; } ControllerScriptingInterface* getControllerScriptingInterface() { return &_controllerScriptingInterface; } AvatarManager& getAvatarManager() { return _avatarManager; } @@ -571,7 +569,6 @@ private: AnimationCache _animationCache; DeferredLightingEffect _deferredLightingEffect; - GlowEffect _glowEffect; AmbientOcclusionEffect _ambientOcclusionEffect; Audio _audio; diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index e0896364f6..83de09c4f5 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -40,6 +40,7 @@ #include "Recorder.h" #include "world.h" #include "devices/OculusManager.h" +#include "renderer/GlowEffect.h" #include "ui/TextRenderer.h" using namespace std; diff --git a/interface/src/avatar/AvatarManager.cpp b/interface/src/avatar/AvatarManager.cpp index ca6a6db4a7..2de272bb29 100644 --- a/interface/src/avatar/AvatarManager.cpp +++ b/interface/src/avatar/AvatarManager.cpp @@ -21,10 +21,11 @@ #include "Application.h" #include "Avatar.h" +#include "AvatarManager.h" #include "Menu.h" #include "MyAvatar.h" -#include "AvatarManager.h" +#include "renderer/GlowEffect.h" // We add _myAvatar into the hash with all the other AvatarData, and we use the default NULL QUid as the key. const QUuid MY_AVATAR_KEY; // NULL key diff --git a/interface/src/avatar/Head.cpp b/interface/src/avatar/Head.cpp index 42b3c968e1..fb20ccdbde 100644 --- a/interface/src/avatar/Head.cpp +++ b/interface/src/avatar/Head.cpp @@ -22,6 +22,7 @@ #include "Menu.h" #include "Util.h" #include "devices/OculusManager.h" +#include "renderer/GlowEffect.h" using namespace std; @@ -331,7 +332,7 @@ void Head::addLeanDeltas(float sideways, float forward) { void Head::renderLookatVectors(glm::vec3 leftEyePosition, glm::vec3 rightEyePosition, glm::vec3 lookatPosition) { - Application::getInstance()->getGlowEffect()->begin(); + DependencyManager::get()->begin(); glLineWidth(2.0); glBegin(GL_LINES); @@ -345,7 +346,7 @@ void Head::renderLookatVectors(glm::vec3 leftEyePosition, glm::vec3 rightEyePosi glVertex3f(lookatPosition.x, lookatPosition.y, lookatPosition.z); glEnd(); - Application::getInstance()->getGlowEffect()->end(); + DependencyManager::get()->end(); } diff --git a/interface/src/devices/OculusManager.cpp b/interface/src/devices/OculusManager.cpp index 7f5c2cd668..b000d6436b 100644 --- a/interface/src/devices/OculusManager.cpp +++ b/interface/src/devices/OculusManager.cpp @@ -26,6 +26,7 @@ #include #include "Application.h" +#include "renderer/GlowEffect.h" #ifdef HAVE_LIBOVR @@ -448,7 +449,7 @@ void OculusManager::display(const glm::quat &bodyOrientation, const glm::vec3 &p //Bind our framebuffer object. If we are rendering the glow effect, we let the glow effect shader take care of it if (Menu::getInstance()->isOptionChecked(MenuOption::EnableGlowEffect)) { - Application::getInstance()->getGlowEffect()->prepare(); + DependencyManager::get()->prepare(); } else { DependencyManager::get()->getPrimaryFramebufferObject()->bind(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); @@ -553,7 +554,7 @@ void OculusManager::display(const glm::quat &bodyOrientation, const glm::vec3 &p //Bind the output texture from the glow shader. If glow effect is disabled, we just grab the texture if (Menu::getInstance()->isOptionChecked(MenuOption::EnableGlowEffect)) { - QOpenGLFramebufferObject* fbo = Application::getInstance()->getGlowEffect()->render(true); + QOpenGLFramebufferObject* fbo = DependencyManager::get()->render(true); glBindTexture(GL_TEXTURE_2D, fbo->texture()); } else { DependencyManager::get()->getPrimaryFramebufferObject()->release(); diff --git a/interface/src/devices/TV3DManager.cpp b/interface/src/devices/TV3DManager.cpp index d7d7353b24..b756ccf41e 100644 --- a/interface/src/devices/TV3DManager.cpp +++ b/interface/src/devices/TV3DManager.cpp @@ -19,6 +19,7 @@ #include "TV3DManager.h" #include "Menu.h" +#include "renderer/GlowEffect.h" int TV3DManager::_screenWidth = 1; int TV3DManager::_screenHeight = 1; @@ -103,7 +104,7 @@ void TV3DManager::display(Camera& whichCamera) { applicationOverlay.renderOverlay(true); const bool displayOverlays = Menu::getInstance()->isOptionChecked(MenuOption::UserInterface); - Application::getInstance()->getGlowEffect()->prepare(); + DependencyManager::get()->prepare(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); @@ -169,7 +170,7 @@ void TV3DManager::display(Camera& whichCamera) { // reset the viewport to how we started glViewport(0, 0, deviceSize.width(), deviceSize.height()); - Application::getInstance()->getGlowEffect()->render(); + DependencyManager::get()->render(); } void TV3DManager::overrideOffAxisFrustum(float& left, float& right, float& bottom, float& top, float& nearVal, diff --git a/interface/src/entities/EntityTreeRenderer.cpp b/interface/src/entities/EntityTreeRenderer.cpp index 2c2b81fa3a..aca111e731 100644 --- a/interface/src/entities/EntityTreeRenderer.cpp +++ b/interface/src/entities/EntityTreeRenderer.cpp @@ -36,6 +36,8 @@ #include "RenderableSphereEntityItem.h" #include "RenderableTextEntityItem.h" +#include "renderer/GlowEffect.h" + QThread* EntityTreeRenderer::getMainThread() { return Application::getInstance()->getEntities()->thread(); diff --git a/interface/src/renderer/AmbientOcclusionEffect.cpp b/interface/src/renderer/AmbientOcclusionEffect.cpp index 08ad6703e6..c5aa193024 100644 --- a/interface/src/renderer/AmbientOcclusionEffect.cpp +++ b/interface/src/renderer/AmbientOcclusionEffect.cpp @@ -24,6 +24,7 @@ #include "RenderUtil.h" #include "AmbientOcclusionEffect.h" +#include "renderer/GlowEffect.h" const int ROTATION_WIDTH = 4; const int ROTATION_HEIGHT = 4; @@ -105,7 +106,7 @@ void AmbientOcclusionEffect::render() { glBindTexture(GL_TEXTURE_2D, _rotationTextureID); // render with the occlusion shader to the secondary/tertiary buffer - QOpenGLFramebufferObject* freeFBO = Application::getInstance()->getGlowEffect()->getFreeFramebufferObject(); + QOpenGLFramebufferObject* freeFBO = DependencyManager::get()->getFreeFramebufferObject(); freeFBO->bind(); float left, right, bottom, top, nearVal, farVal; diff --git a/interface/src/renderer/DeferredLightingEffect.cpp b/interface/src/renderer/DeferredLightingEffect.cpp index 79b89d03f9..b365307a44 100644 --- a/interface/src/renderer/DeferredLightingEffect.cpp +++ b/interface/src/renderer/DeferredLightingEffect.cpp @@ -19,6 +19,7 @@ #include "Application.h" #include "DeferredLightingEffect.h" #include "RenderUtil.h" +#include "renderer/GlowEffect.h" void DeferredLightingEffect::init() { _simpleProgram.addShaderFromSourceFile(QGLShader::Vertex, PathUtils::resourcesPath() + "shaders/simple.vert"); @@ -41,7 +42,7 @@ void DeferredLightingEffect::init() { void DeferredLightingEffect::bindSimpleProgram() { DependencyManager::get()->setPrimaryDrawBuffers(true, true, true); _simpleProgram.bind(); - _simpleProgram.setUniformValue(_glowIntensityLocation, Application::getInstance()->getGlowEffect()->getIntensity()); + _simpleProgram.setUniformValue(_glowIntensityLocation, DependencyManager::get()->getIntensity()); glDisable(GL_BLEND); } @@ -146,7 +147,7 @@ void DeferredLightingEffect::render() { QOpenGLFramebufferObject* primaryFBO = textureCache->getPrimaryFramebufferObject(); primaryFBO->release(); - QOpenGLFramebufferObject* freeFBO = Application::getInstance()->getGlowEffect()->getFreeFramebufferObject(); + QOpenGLFramebufferObject* freeFBO = DependencyManager::get()->getFreeFramebufferObject(); freeFBO->bind(); glClear(GL_COLOR_BUFFER_BIT); diff --git a/interface/src/renderer/GlowEffect.cpp b/interface/src/renderer/GlowEffect.cpp index a53c9f878b..4ec0a994b7 100644 --- a/interface/src/renderer/GlowEffect.cpp +++ b/interface/src/renderer/GlowEffect.cpp @@ -13,6 +13,7 @@ #include "InterfaceConfig.h" #include +#include #include #include @@ -58,7 +59,7 @@ static ProgramObject* createProgram(const QString& name) { return program; } -void GlowEffect::init() { +void GlowEffect::init(QGLWidget* widget) { if (_initialized) { qDebug("[ERROR] GlowEffeect is already initialized."); return; @@ -86,8 +87,18 @@ void GlowEffect::init() { _diffusionScaleLocation = _diffuseProgram->uniformLocation("diffusionScale"); _initialized = true; + _widget = widget; } +int GlowEffect::getDeviceWidth() const { + return _widget->width() * (_widget->windowHandle() ? _widget->windowHandle()->devicePixelRatio() : 1.0f); +} + +int GlowEffect::getDeviceHeight() const { + return _widget->height() * (_widget->windowHandle() ? _widget->windowHandle()->devicePixelRatio() : 1.0f); +} + + void GlowEffect::prepare() { DependencyManager::get()->getPrimaryFramebufferObject()->bind(); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); @@ -148,8 +159,7 @@ QOpenGLFramebufferObject* GlowEffect::render(bool toTexture) { } else { maybeBind(destFBO); if (!destFBO) { - glViewport(0, 0, Application::getInstance()->getGLWidget()->getDeviceWidth(), - Application::getInstance()->getGLWidget()->getDeviceHeight()); + glViewport(0, 0, getDeviceWidth(), getDeviceHeight()); } glEnable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); @@ -196,9 +206,7 @@ QOpenGLFramebufferObject* GlowEffect::render(bool toTexture) { } maybeBind(destFBO); if (!destFBO) { - glViewport(0, 0, - Application::getInstance()->getGLWidget()->getDeviceWidth(), - Application::getInstance()->getGLWidget()->getDeviceHeight()); + glViewport(0, 0, getDeviceWidth(), getDeviceHeight()); } _addSeparateProgram->bind(); renderFullscreenQuad(); @@ -226,10 +234,10 @@ QOpenGLFramebufferObject* GlowEffect::render(bool toTexture) { } Glower::Glower(float amount) { - Application::getInstance()->getGlowEffect()->begin(amount); + DependencyManager::get()->begin(amount); } Glower::~Glower() { - Application::getInstance()->getGlowEffect()->end(); + DependencyManager::get()->end(); } diff --git a/interface/src/renderer/GlowEffect.h b/interface/src/renderer/GlowEffect.h index f02774accc..42863019f3 100644 --- a/interface/src/renderer/GlowEffect.h +++ b/interface/src/renderer/GlowEffect.h @@ -15,23 +15,23 @@ #include #include +#include + class QOpenGLFramebufferObject; class ProgramObject; /// A generic full screen glow effect. -class GlowEffect : public QObject { +class GlowEffect : public QObject, public DependencyManager::Dependency { Q_OBJECT public: - GlowEffect(); - ~GlowEffect(); - + /// Returns a pointer to the framebuffer object that the glow effect is *not* using for persistent state /// (either the secondary or the tertiary). QOpenGLFramebufferObject* getFreeFramebufferObject() const; - void init(); + void init(QGLWidget* widget); /// Prepares the glow effect for rendering the current frame. To be called before rendering the scene. void prepare(); @@ -52,6 +52,12 @@ public: QOpenGLFramebufferObject* render(bool toTexture = false); private: + GlowEffect(); + virtual ~GlowEffect(); + friend class DependencyManager; + + int getDeviceWidth() const; + int getDeviceHeight() const; bool _initialized; @@ -69,6 +75,7 @@ private: float _intensity; QStack _intensityStack; + QGLWidget* _widget; }; /// RAII-style glow handler. Applies glow when in scope. diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index 71f0fb24f3..3e1784b680 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -33,6 +33,8 @@ #define GLBATCH( call ) batch._##call //#define GLBATCH( call ) call +#include "renderer/GlowEffect.h" + using namespace std; static int modelPointerTypeId = qRegisterMetaType >(); @@ -2327,6 +2329,7 @@ int Model::renderMeshesFromList(QVector& list, gpu::Batch& batch, RenderMod bool dontReduceMaterialSwitches = Menu::getInstance()->isOptionChecked(MenuOption::DontReduceMaterialSwitches); TextureCache* textureCache = DependencyManager::get(); + GlowEffect* glowEffect = DependencyManager::get(); QString lastMaterialID; int meshPartsRendered = 0; updateVisibleJointStates(); @@ -2431,7 +2434,7 @@ int Model::renderMeshesFromList(QVector& list, gpu::Batch& batch, RenderMod glm::vec4 diffuse = glm::vec4(part.diffuseColor, part.opacity); if (!(translucent && alphaThreshold == 0.0f)) { - GLBATCH(glAlphaFunc)(GL_EQUAL, diffuse.a = Application::getInstance()->getGlowEffect()->getIntensity()); + GLBATCH(glAlphaFunc)(GL_EQUAL, diffuse.a = glowEffect->getIntensity()); } glm::vec4 specular = glm::vec4(part.specularColor, 1.0f); GLBATCH(glMaterialfv)(GL_FRONT, GL_AMBIENT, (const float*)&diffuse); diff --git a/interface/src/ui/overlays/LocalModelsOverlay.cpp b/interface/src/ui/overlays/LocalModelsOverlay.cpp index d8555c85ba..d2af86e43b 100644 --- a/interface/src/ui/overlays/LocalModelsOverlay.cpp +++ b/interface/src/ui/overlays/LocalModelsOverlay.cpp @@ -12,6 +12,7 @@ #include "Application.h" #include "LocalModelsOverlay.h" +#include "renderer/GlowEffect.h" LocalModelsOverlay::LocalModelsOverlay(EntityTreeRenderer* entityTreeRenderer) : Volume3DOverlay(), diff --git a/interface/src/ui/overlays/LocalVoxelsOverlay.cpp b/interface/src/ui/overlays/LocalVoxelsOverlay.cpp index 9cb3df8bf3..b49320c087 100644 --- a/interface/src/ui/overlays/LocalVoxelsOverlay.cpp +++ b/interface/src/ui/overlays/LocalVoxelsOverlay.cpp @@ -18,6 +18,7 @@ #include #include "LocalVoxelsOverlay.h" +#include "renderer/GlowEffect.h" #include "voxels/VoxelSystem.h" QMap LocalVoxelsOverlay::_voxelSystemMap; diff --git a/interface/src/ui/overlays/ModelOverlay.cpp b/interface/src/ui/overlays/ModelOverlay.cpp index ecce137f4d..58fe0ec899 100644 --- a/interface/src/ui/overlays/ModelOverlay.cpp +++ b/interface/src/ui/overlays/ModelOverlay.cpp @@ -11,6 +11,7 @@ #include "../../Menu.h" #include "ModelOverlay.h" +#include "renderer/GlowEffect.h" ModelOverlay::ModelOverlay() : _model(), diff --git a/interface/src/voxels/VoxelFade.cpp b/interface/src/voxels/VoxelFade.cpp index c720717d7c..918cafe9c6 100644 --- a/interface/src/voxels/VoxelFade.cpp +++ b/interface/src/voxels/VoxelFade.cpp @@ -15,6 +15,7 @@ #include "Application.h" #include "VoxelFade.h" +#include "renderer/GlowEffect.h" const float VoxelFade::FADE_OUT_START = 0.5f; const float VoxelFade::FADE_OUT_END = 0.05f; @@ -36,7 +37,7 @@ VoxelFade::VoxelFade(FadeDirection direction, float red, float green, float blue } void VoxelFade::render() { - Application::getInstance()->getGlowEffect()->begin(); + DependencyManager::get()->begin(); glDisable(GL_LIGHTING); glPushMatrix(); @@ -52,7 +53,7 @@ void VoxelFade::render() { glEnable(GL_LIGHTING); - Application::getInstance()->getGlowEffect()->end(); + DependencyManager::get()->end(); opacity *= (direction == FADE_OUT) ? FADE_OUT_STEP : FADE_IN_STEP; } From 37abe8e89c48e7ffdfb23402721accedbe89e671 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 17:35:26 -0800 Subject: [PATCH 124/258] move RenderUtils.cpp/h to libraries --- interface/src/renderer/AmbientOcclusionEffect.cpp | 2 +- interface/src/renderer/DeferredLightingEffect.cpp | 2 +- interface/src/renderer/GlowEffect.cpp | 5 +++-- .../renderer => libraries/render-utils/src}/RenderUtil.cpp | 2 +- .../src/renderer => libraries/render-utils/src}/RenderUtil.h | 0 5 files changed, 6 insertions(+), 5 deletions(-) rename {interface/src/renderer => libraries/render-utils/src}/RenderUtil.cpp (95%) rename {interface/src/renderer => libraries/render-utils/src}/RenderUtil.h (100%) diff --git a/interface/src/renderer/AmbientOcclusionEffect.cpp b/interface/src/renderer/AmbientOcclusionEffect.cpp index c5aa193024..9c89eae75e 100644 --- a/interface/src/renderer/AmbientOcclusionEffect.cpp +++ b/interface/src/renderer/AmbientOcclusionEffect.cpp @@ -18,10 +18,10 @@ #include #include +#include #include #include "Application.h" -#include "RenderUtil.h" #include "AmbientOcclusionEffect.h" #include "renderer/GlowEffect.h" diff --git a/interface/src/renderer/DeferredLightingEffect.cpp b/interface/src/renderer/DeferredLightingEffect.cpp index b365307a44..ae0743e2a6 100644 --- a/interface/src/renderer/DeferredLightingEffect.cpp +++ b/interface/src/renderer/DeferredLightingEffect.cpp @@ -15,10 +15,10 @@ #include #include +#include #include "Application.h" #include "DeferredLightingEffect.h" -#include "RenderUtil.h" #include "renderer/GlowEffect.h" void DeferredLightingEffect::init() { diff --git a/interface/src/renderer/GlowEffect.cpp b/interface/src/renderer/GlowEffect.cpp index 4ec0a994b7..ee5642e654 100644 --- a/interface/src/renderer/GlowEffect.cpp +++ b/interface/src/renderer/GlowEffect.cpp @@ -18,10 +18,11 @@ #include #include #include +#include +#include -#include "Application.h" +#include "Menu.h" #include "GlowEffect.h" -#include "RenderUtil.h" GlowEffect::GlowEffect() : _initialized(false), diff --git a/interface/src/renderer/RenderUtil.cpp b/libraries/render-utils/src/RenderUtil.cpp similarity index 95% rename from interface/src/renderer/RenderUtil.cpp rename to libraries/render-utils/src/RenderUtil.cpp index c2f05d373e..d70c972c87 100644 --- a/interface/src/renderer/RenderUtil.cpp +++ b/libraries/render-utils/src/RenderUtil.cpp @@ -9,7 +9,7 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#include "InterfaceConfig.h" +#include #include "RenderUtil.h" void renderFullscreenQuad(float sMin, float sMax, float tMin, float tMax) { diff --git a/interface/src/renderer/RenderUtil.h b/libraries/render-utils/src/RenderUtil.h similarity index 100% rename from interface/src/renderer/RenderUtil.h rename to libraries/render-utils/src/RenderUtil.h From e52338d25c0cb9b9e046d106895026cf708f45f5 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 17:38:57 -0800 Subject: [PATCH 125/258] get rid of InterfaceConfig.h in GlowEffect --- interface/src/renderer/GlowEffect.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interface/src/renderer/GlowEffect.cpp b/interface/src/renderer/GlowEffect.cpp index ee5642e654..7ad553decf 100644 --- a/interface/src/renderer/GlowEffect.cpp +++ b/interface/src/renderer/GlowEffect.cpp @@ -10,7 +10,7 @@ // // include this before QOpenGLFramebufferObject, which includes an earlier version of OpenGL -#include "InterfaceConfig.h" +#include #include #include From 4eef4c2438ec0018b3fc01fdecaff248ac359089 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 18:52:40 -0800 Subject: [PATCH 126/258] move RenderUtils.cpp/h to libraries --- interface/src/MetavoxelSystem.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/interface/src/MetavoxelSystem.cpp b/interface/src/MetavoxelSystem.cpp index 372c5214f7..824f1e3313 100644 --- a/interface/src/MetavoxelSystem.cpp +++ b/interface/src/MetavoxelSystem.cpp @@ -32,7 +32,6 @@ #include "Application.h" #include "MetavoxelSystem.h" #include "renderer/Model.h" -#include "renderer/RenderUtil.h" REGISTER_META_OBJECT(DefaultMetavoxelRendererImplementation) REGISTER_META_OBJECT(SphereRenderer) From 8f3d23c5b32208581b8067ed34435b2fe214d969 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 19:06:54 -0800 Subject: [PATCH 127/258] remove Menu dependency from GlowEffect --- interface/src/Application.cpp | 2 +- interface/src/Menu.cpp | 4 +++- interface/src/renderer/GlowEffect.cpp | 14 ++++++++++---- interface/src/renderer/GlowEffect.h | 6 +++++- 4 files changed, 19 insertions(+), 7 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 4bc4b0d339..834587a26a 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -2039,7 +2039,7 @@ void Application::init() { DependencyManager::get()->associateWithWidget(getGLWidget()); // initialize the GlowEffect with our widget - DependencyManager::get()->init(getGLWidget()); + DependencyManager::get()->init(getGLWidget(), Menu::getInstance()->isOptionChecked(MenuOption::EnableGlowEffect)); } void Application::closeMirrorView() { diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index fbb23504b0..55a1254e3f 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -54,6 +54,7 @@ #include "ui/ModelsBrowser.h" #include "ui/LoginDialog.h" #include "ui/NodeBounds.h" +#include "renderer/GlowEffect.h" Menu* Menu::_instance = NULL; @@ -425,7 +426,8 @@ Menu::Menu() : true, appInstance, SLOT(setRenderVoxels(bool))); - addCheckableActionToQMenuAndActionHash(renderOptionsMenu, MenuOption::EnableGlowEffect, 0, true); + addCheckableActionToQMenuAndActionHash(renderOptionsMenu, MenuOption::EnableGlowEffect, 0, true, + DependencyManager::get(), SLOT(toggleGlowEffect(bool))); addCheckableActionToQMenuAndActionHash(renderOptionsMenu, MenuOption::Wireframe, Qt::ALT | Qt::Key_W, false); addActionToQMenuAndActionHash(renderOptionsMenu, MenuOption::LodTools, Qt::SHIFT | Qt::Key_L, this, SLOT(lodTools())); diff --git a/interface/src/renderer/GlowEffect.cpp b/interface/src/renderer/GlowEffect.cpp index 7ad553decf..13513c140b 100644 --- a/interface/src/renderer/GlowEffect.cpp +++ b/interface/src/renderer/GlowEffect.cpp @@ -21,14 +21,15 @@ #include #include -#include "Menu.h" #include "GlowEffect.h" GlowEffect::GlowEffect() : _initialized(false), _isOddFrame(false), _isFirstFrame(true), - _intensity(0.0f) { + _intensity(0.0f), + _widget(NULL), + _enabled(false) { } GlowEffect::~GlowEffect() { @@ -60,7 +61,7 @@ static ProgramObject* createProgram(const QString& name) { return program; } -void GlowEffect::init(QGLWidget* widget) { +void GlowEffect::init(QGLWidget* widget, bool enabled) { if (_initialized) { qDebug("[ERROR] GlowEffeect is already initialized."); return; @@ -89,6 +90,7 @@ void GlowEffect::init(QGLWidget* widget) { _initialized = true; _widget = widget; + _enabled = enabled; } int GlowEffect::getDeviceWidth() const { @@ -153,7 +155,7 @@ QOpenGLFramebufferObject* GlowEffect::render(bool toTexture) { QOpenGLFramebufferObject* destFBO = toTexture ? textureCache->getSecondaryFramebufferObject() : NULL; - if (!Menu::getInstance()->isOptionChecked(MenuOption::EnableGlowEffect) || _isEmpty) { + if (!_enabled || _isEmpty) { // copy the primary to the screen if (destFBO && QOpenGLFramebufferObject::hasOpenGLFramebufferBlit()) { QOpenGLFramebufferObject::blitFramebuffer(destFBO, primaryFBO); @@ -234,6 +236,10 @@ QOpenGLFramebufferObject* GlowEffect::render(bool toTexture) { return destFBO; } +void GlowEffect::toggleGlowEffect(bool enabled) { + _enabled = enabled; +} + Glower::Glower(float amount) { DependencyManager::get()->begin(amount); } diff --git a/interface/src/renderer/GlowEffect.h b/interface/src/renderer/GlowEffect.h index 42863019f3..d27f32c244 100644 --- a/interface/src/renderer/GlowEffect.h +++ b/interface/src/renderer/GlowEffect.h @@ -31,7 +31,7 @@ public: /// (either the secondary or the tertiary). QOpenGLFramebufferObject* getFreeFramebufferObject() const; - void init(QGLWidget* widget); + void init(QGLWidget* widget, bool enabled); /// Prepares the glow effect for rendering the current frame. To be called before rendering the scene. void prepare(); @@ -51,6 +51,9 @@ public: /// \return the framebuffer object to which we rendered, or NULL if to the frame buffer QOpenGLFramebufferObject* render(bool toTexture = false); +public slots: + void toggleGlowEffect(bool enabled); + private: GlowEffect(); virtual ~GlowEffect(); @@ -76,6 +79,7 @@ private: float _intensity; QStack _intensityStack; QGLWidget* _widget; + bool _enabled; }; /// RAII-style glow handler. Applies glow when in scope. From 41c135c4e5618cefc74ddc97382166d1a9123d99 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 19:19:21 -0800 Subject: [PATCH 128/258] move GlowEffect to libraries --- interface/src/Application.cpp | 2 +- interface/src/Menu.cpp | 3 +-- interface/src/avatar/Avatar.cpp | 2 +- interface/src/avatar/AvatarManager.cpp | 2 +- interface/src/avatar/Head.cpp | 6 +++--- interface/src/devices/OculusManager.cpp | 2 +- interface/src/devices/TV3DManager.cpp | 3 ++- interface/src/entities/EntityTreeRenderer.cpp | 5 +---- interface/src/renderer/AmbientOcclusionEffect.cpp | 2 +- interface/src/renderer/DeferredLightingEffect.cpp | 2 +- interface/src/renderer/Model.cpp | 3 +-- interface/src/ui/overlays/Circle3DOverlay.cpp | 2 +- interface/src/ui/overlays/Cube3DOverlay.cpp | 3 ++- interface/src/ui/overlays/Line3DOverlay.cpp | 3 ++- interface/src/ui/overlays/LocalModelsOverlay.cpp | 3 ++- interface/src/ui/overlays/LocalVoxelsOverlay.cpp | 4 ++-- interface/src/ui/overlays/ModelOverlay.cpp | 4 +++- interface/src/ui/overlays/Rectangle3DOverlay.cpp | 3 ++- interface/src/ui/overlays/Sphere3DOverlay.cpp | 3 ++- interface/src/voxels/VoxelFade.cpp | 2 +- .../render-utils/src}/GlowEffect.cpp | 8 +++++--- .../renderer => libraries/render-utils/src}/GlowEffect.h | 1 + 22 files changed, 37 insertions(+), 31 deletions(-) rename {interface/src/renderer => libraries/render-utils/src}/GlowEffect.cpp (98%) rename {interface/src/renderer => libraries/render-utils/src}/GlowEffect.h (99%) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 834587a26a..f3ac53c33b 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -57,6 +57,7 @@ #include #include #include +#include #include #include #include @@ -90,7 +91,6 @@ #include "gpu/Batch.h" #include "gpu/GLBackend.h" -#include "renderer/GlowEffect.h" #include "scripting/AccountScriptingInterface.h" #include "scripting/AudioDeviceScriptingInterface.h" diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 55a1254e3f..80fdec5202 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -32,6 +32,7 @@ #include #include #include +#include #include #include #include @@ -54,8 +55,6 @@ #include "ui/ModelsBrowser.h" #include "ui/LoginDialog.h" #include "ui/NodeBounds.h" -#include "renderer/GlowEffect.h" - Menu* Menu::_instance = NULL; diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index 83de09c4f5..4b7c5dfdf3 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -23,6 +23,7 @@ #include #include +#include #include #include #include @@ -40,7 +41,6 @@ #include "Recorder.h" #include "world.h" #include "devices/OculusManager.h" -#include "renderer/GlowEffect.h" #include "ui/TextRenderer.h" using namespace std; diff --git a/interface/src/avatar/AvatarManager.cpp b/interface/src/avatar/AvatarManager.cpp index 2de272bb29..8c13dd3c54 100644 --- a/interface/src/avatar/AvatarManager.cpp +++ b/interface/src/avatar/AvatarManager.cpp @@ -15,6 +15,7 @@ #include +#include #include #include #include @@ -25,7 +26,6 @@ #include "Menu.h" #include "MyAvatar.h" -#include "renderer/GlowEffect.h" // We add _myAvatar into the hash with all the other AvatarData, and we use the default NULL QUid as the key. const QUuid MY_AVATAR_KEY; // NULL key diff --git a/interface/src/avatar/Head.cpp b/interface/src/avatar/Head.cpp index fb20ccdbde..5d84c2d939 100644 --- a/interface/src/avatar/Head.cpp +++ b/interface/src/avatar/Head.cpp @@ -11,8 +11,7 @@ #include #include -#include -#include +#include #include #include "Application.h" @@ -21,8 +20,9 @@ #include "Head.h" #include "Menu.h" #include "Util.h" +#include "devices/DdeFaceTracker.h" +#include "devices/Faceshift.h" #include "devices/OculusManager.h" -#include "renderer/GlowEffect.h" using namespace std; diff --git a/interface/src/devices/OculusManager.cpp b/interface/src/devices/OculusManager.cpp index b000d6436b..96615112dd 100644 --- a/interface/src/devices/OculusManager.cpp +++ b/interface/src/devices/OculusManager.cpp @@ -21,12 +21,12 @@ #include +#include #include #include #include #include "Application.h" -#include "renderer/GlowEffect.h" #ifdef HAVE_LIBOVR diff --git a/interface/src/devices/TV3DManager.cpp b/interface/src/devices/TV3DManager.cpp index b756ccf41e..f665765d70 100644 --- a/interface/src/devices/TV3DManager.cpp +++ b/interface/src/devices/TV3DManager.cpp @@ -15,11 +15,12 @@ #include +#include + #include "Application.h" #include "TV3DManager.h" #include "Menu.h" -#include "renderer/GlowEffect.h" int TV3DManager::_screenWidth = 1; int TV3DManager::_screenHeight = 1; diff --git a/interface/src/entities/EntityTreeRenderer.cpp b/interface/src/entities/EntityTreeRenderer.cpp index aca111e731..59b3f697c8 100644 --- a/interface/src/entities/EntityTreeRenderer.cpp +++ b/interface/src/entities/EntityTreeRenderer.cpp @@ -18,6 +18,7 @@ #include "InterfaceConfig.h" #include +#include #include #include #include @@ -36,15 +37,11 @@ #include "RenderableSphereEntityItem.h" #include "RenderableTextEntityItem.h" -#include "renderer/GlowEffect.h" - QThread* EntityTreeRenderer::getMainThread() { return Application::getInstance()->getEntities()->thread(); } - - EntityTreeRenderer::EntityTreeRenderer(bool wantScripts) : OctreeRenderer(), _wantScripts(wantScripts), diff --git a/interface/src/renderer/AmbientOcclusionEffect.cpp b/interface/src/renderer/AmbientOcclusionEffect.cpp index 9c89eae75e..bcae662085 100644 --- a/interface/src/renderer/AmbientOcclusionEffect.cpp +++ b/interface/src/renderer/AmbientOcclusionEffect.cpp @@ -16,6 +16,7 @@ #include +#include #include #include #include @@ -24,7 +25,6 @@ #include "Application.h" #include "AmbientOcclusionEffect.h" -#include "renderer/GlowEffect.h" const int ROTATION_WIDTH = 4; const int ROTATION_HEIGHT = 4; diff --git a/interface/src/renderer/DeferredLightingEffect.cpp b/interface/src/renderer/DeferredLightingEffect.cpp index ae0743e2a6..18a93aa042 100644 --- a/interface/src/renderer/DeferredLightingEffect.cpp +++ b/interface/src/renderer/DeferredLightingEffect.cpp @@ -14,12 +14,12 @@ #include +#include #include #include #include "Application.h" #include "DeferredLightingEffect.h" -#include "renderer/GlowEffect.h" void DeferredLightingEffect::init() { _simpleProgram.addShaderFromSourceFile(QGLShader::Vertex, PathUtils::resourcesPath() + "shaders/simple.vert"); diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index 3e1784b680..877f43a563 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -18,6 +18,7 @@ #include #include +#include #include #include #include @@ -33,8 +34,6 @@ #define GLBATCH( call ) batch._##call //#define GLBATCH( call ) call -#include "renderer/GlowEffect.h" - using namespace std; static int modelPointerTypeId = qRegisterMetaType >(); diff --git a/interface/src/ui/overlays/Circle3DOverlay.cpp b/interface/src/ui/overlays/Circle3DOverlay.cpp index 68d589d20b..32ae7f0a07 100644 --- a/interface/src/ui/overlays/Circle3DOverlay.cpp +++ b/interface/src/ui/overlays/Circle3DOverlay.cpp @@ -12,11 +12,11 @@ #include "InterfaceConfig.h" #include +#include #include #include #include "Circle3DOverlay.h" -#include "renderer/GlowEffect.h" Circle3DOverlay::Circle3DOverlay() : _startAt(0.0f), diff --git a/interface/src/ui/overlays/Cube3DOverlay.cpp b/interface/src/ui/overlays/Cube3DOverlay.cpp index 8e37dedd77..f518c309a1 100644 --- a/interface/src/ui/overlays/Cube3DOverlay.cpp +++ b/interface/src/ui/overlays/Cube3DOverlay.cpp @@ -12,12 +12,13 @@ #include "InterfaceConfig.h" #include + +#include #include #include #include "Application.h" #include "Cube3DOverlay.h" -#include "renderer/GlowEffect.h" Cube3DOverlay::Cube3DOverlay() : _borderSize(0) { } diff --git a/interface/src/ui/overlays/Line3DOverlay.cpp b/interface/src/ui/overlays/Line3DOverlay.cpp index ae67bf9d92..4facd779de 100644 --- a/interface/src/ui/overlays/Line3DOverlay.cpp +++ b/interface/src/ui/overlays/Line3DOverlay.cpp @@ -11,8 +11,9 @@ // include this before QGLWidget, which includes an earlier version of OpenGL #include "InterfaceConfig.h" +#include + #include "Line3DOverlay.h" -#include "renderer/GlowEffect.h" Line3DOverlay::Line3DOverlay() { diff --git a/interface/src/ui/overlays/LocalModelsOverlay.cpp b/interface/src/ui/overlays/LocalModelsOverlay.cpp index d2af86e43b..e6fae4ff3d 100644 --- a/interface/src/ui/overlays/LocalModelsOverlay.cpp +++ b/interface/src/ui/overlays/LocalModelsOverlay.cpp @@ -9,10 +9,11 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +#include + #include "Application.h" #include "LocalModelsOverlay.h" -#include "renderer/GlowEffect.h" LocalModelsOverlay::LocalModelsOverlay(EntityTreeRenderer* entityTreeRenderer) : Volume3DOverlay(), diff --git a/interface/src/ui/overlays/LocalVoxelsOverlay.cpp b/interface/src/ui/overlays/LocalVoxelsOverlay.cpp index b49320c087..b3dac02468 100644 --- a/interface/src/ui/overlays/LocalVoxelsOverlay.cpp +++ b/interface/src/ui/overlays/LocalVoxelsOverlay.cpp @@ -15,10 +15,10 @@ #include #include -#include +#include +#include "Application.h" #include "LocalVoxelsOverlay.h" -#include "renderer/GlowEffect.h" #include "voxels/VoxelSystem.h" QMap LocalVoxelsOverlay::_voxelSystemMap; diff --git a/interface/src/ui/overlays/ModelOverlay.cpp b/interface/src/ui/overlays/ModelOverlay.cpp index 58fe0ec899..58d42598f2 100644 --- a/interface/src/ui/overlays/ModelOverlay.cpp +++ b/interface/src/ui/overlays/ModelOverlay.cpp @@ -8,10 +8,12 @@ // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // + +#include + #include "../../Menu.h" #include "ModelOverlay.h" -#include "renderer/GlowEffect.h" ModelOverlay::ModelOverlay() : _model(), diff --git a/interface/src/ui/overlays/Rectangle3DOverlay.cpp b/interface/src/ui/overlays/Rectangle3DOverlay.cpp index bcca759cd4..8e8c17743d 100644 --- a/interface/src/ui/overlays/Rectangle3DOverlay.cpp +++ b/interface/src/ui/overlays/Rectangle3DOverlay.cpp @@ -12,10 +12,11 @@ #include "InterfaceConfig.h" #include + +#include #include #include "Rectangle3DOverlay.h" -#include "renderer/GlowEffect.h" Rectangle3DOverlay::Rectangle3DOverlay() { } diff --git a/interface/src/ui/overlays/Sphere3DOverlay.cpp b/interface/src/ui/overlays/Sphere3DOverlay.cpp index ded1b3917c..eb95672399 100644 --- a/interface/src/ui/overlays/Sphere3DOverlay.cpp +++ b/interface/src/ui/overlays/Sphere3DOverlay.cpp @@ -12,11 +12,12 @@ #include "InterfaceConfig.h" #include + +#include #include #include "Sphere3DOverlay.h" #include "Application.h" -#include "renderer/GlowEffect.h" Sphere3DOverlay::Sphere3DOverlay() { } diff --git a/interface/src/voxels/VoxelFade.cpp b/interface/src/voxels/VoxelFade.cpp index 918cafe9c6..367090291c 100644 --- a/interface/src/voxels/VoxelFade.cpp +++ b/interface/src/voxels/VoxelFade.cpp @@ -11,11 +11,11 @@ #include "InterfaceConfig.h" +#include #include #include "Application.h" #include "VoxelFade.h" -#include "renderer/GlowEffect.h" const float VoxelFade::FADE_OUT_START = 0.5f; const float VoxelFade::FADE_OUT_END = 0.05f; diff --git a/interface/src/renderer/GlowEffect.cpp b/libraries/render-utils/src/GlowEffect.cpp similarity index 98% rename from interface/src/renderer/GlowEffect.cpp rename to libraries/render-utils/src/GlowEffect.cpp index 13513c140b..174436d155 100644 --- a/interface/src/renderer/GlowEffect.cpp +++ b/libraries/render-utils/src/GlowEffect.cpp @@ -12,16 +12,18 @@ // include this before QOpenGLFramebufferObject, which includes an earlier version of OpenGL #include +#include #include #include #include #include -#include -#include -#include #include "GlowEffect.h" +#include "ProgramObject.h" +#include "RenderUtil.h" +#include "TextureCache.h" + GlowEffect::GlowEffect() : _initialized(false), diff --git a/interface/src/renderer/GlowEffect.h b/libraries/render-utils/src/GlowEffect.h similarity index 99% rename from interface/src/renderer/GlowEffect.h rename to libraries/render-utils/src/GlowEffect.h index d27f32c244..3ad1577d14 100644 --- a/interface/src/renderer/GlowEffect.h +++ b/libraries/render-utils/src/GlowEffect.h @@ -13,6 +13,7 @@ #define hifi_GlowEffect_h #include +#include #include #include From fac6ff572ba3da1d53b39f2858be1c5153e3e8e7 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 19:29:53 -0800 Subject: [PATCH 129/258] see if this works --- libraries/render-utils/src/GlowEffect.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/libraries/render-utils/src/GlowEffect.h b/libraries/render-utils/src/GlowEffect.h index 3ad1577d14..cc3e6e5867 100644 --- a/libraries/render-utils/src/GlowEffect.h +++ b/libraries/render-utils/src/GlowEffect.h @@ -12,6 +12,8 @@ #ifndef hifi_GlowEffect_h #define hifi_GlowEffect_h +#include + #include #include #include From 02737a4ec402f8b97e07a08fca86b15c978996a0 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 19:38:30 -0800 Subject: [PATCH 130/258] move JointState to libraries --- interface/src/avatar/SkeletonRagdoll.h | 3 +- interface/src/renderer/Model.h | 2 +- libraries/render-utils/src/JointState.cpp | 281 ++++++++++++++++++++++ libraries/render-utils/src/JointState.h | 129 ++++++++++ 4 files changed, 412 insertions(+), 3 deletions(-) create mode 100644 libraries/render-utils/src/JointState.cpp create mode 100644 libraries/render-utils/src/JointState.h diff --git a/interface/src/avatar/SkeletonRagdoll.h b/interface/src/avatar/SkeletonRagdoll.h index ae9bec9116..2f8ce1f712 100644 --- a/interface/src/avatar/SkeletonRagdoll.h +++ b/interface/src/avatar/SkeletonRagdoll.h @@ -14,10 +14,9 @@ #include +#include #include -#include "../renderer/JointState.h" - class MuscleConstraint; class Model; diff --git a/interface/src/renderer/Model.h b/interface/src/renderer/Model.h index c79a6c2efd..8000e7385b 100644 --- a/interface/src/renderer/Model.h +++ b/interface/src/renderer/Model.h @@ -23,13 +23,13 @@ #include #include #include +#include #include #include #include #include #include "AnimationHandle.h" -#include "JointState.h" class QScriptEngine; diff --git a/libraries/render-utils/src/JointState.cpp b/libraries/render-utils/src/JointState.cpp new file mode 100644 index 0000000000..96561758da --- /dev/null +++ b/libraries/render-utils/src/JointState.cpp @@ -0,0 +1,281 @@ +// +// JointState.cpp +// interface/src/renderer +// +// Created by Andrzej Kapolka on 10/18/13. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include + +#include + +#include +#include + +#include "JointState.h" + +JointState::JointState() : + _animationPriority(0.0f), + _transformChanged(true), + _rotationIsValid(false), + _positionInParentFrame(0.0f), + _distanceToParent(0.0f), + _fbxJoint(NULL), + _constraint(NULL) { +} + +JointState::JointState(const JointState& other) : _constraint(NULL) { + _transformChanged = other._transformChanged; + _transform = other._transform; + _rotationIsValid = other._rotationIsValid; + _rotation = other._rotation; + _rotationInConstrainedFrame = other._rotationInConstrainedFrame; + _positionInParentFrame = other._positionInParentFrame; + _distanceToParent = other._distanceToParent; + _animationPriority = other._animationPriority; + _fbxJoint = other._fbxJoint; + // DO NOT copy _constraint +} + +JointState::~JointState() { + delete _constraint; + _constraint = NULL; + if (_constraint) { + delete _constraint; + _constraint = NULL; + } +} + +glm::quat JointState::getRotation() const { + if (!_rotationIsValid) { + const_cast(this)->_rotation = extractRotation(_transform); + const_cast(this)->_rotationIsValid = true; + } + + return _rotation; +} + +void JointState::setFBXJoint(const FBXJoint* joint) { + assert(joint != NULL); + _rotationInConstrainedFrame = joint->rotation; + _transformChanged = true; + _rotationIsValid = false; + + // NOTE: JointState does not own the FBXJoint to which it points. + _fbxJoint = joint; + if (_constraint) { + delete _constraint; + _constraint = NULL; + } +} + +void JointState::buildConstraint() { + if (_constraint) { + delete _constraint; + _constraint = NULL; + } + if (glm::distance2(glm::vec3(-PI), _fbxJoint->rotationMin) > EPSILON || + glm::distance2(glm::vec3(PI), _fbxJoint->rotationMax) > EPSILON ) { + // this joint has rotation constraints + _constraint = AngularConstraint::newAngularConstraint(_fbxJoint->rotationMin, _fbxJoint->rotationMax); + } +} + +void JointState::copyState(const JointState& state) { + _animationPriority = state._animationPriority; + _transformChanged = state._transformChanged; + _transform = state._transform; + _rotationIsValid = state._rotationIsValid; + _rotation = state._rotation; + _rotationInConstrainedFrame = state._rotationInConstrainedFrame; + _positionInParentFrame = state._positionInParentFrame; + _distanceToParent = state._distanceToParent; + + _visibleTransform = state._visibleTransform; + _visibleRotation = extractRotation(_visibleTransform); + _visibleRotationInConstrainedFrame = state._visibleRotationInConstrainedFrame; + // DO NOT copy _fbxJoint or _constraint +} + +void JointState::initTransform(const glm::mat4& parentTransform) { + computeTransform(parentTransform); + _positionInParentFrame = glm::inverse(extractRotation(parentTransform)) * (extractTranslation(_transform) - extractTranslation(parentTransform)); + _distanceToParent = glm::length(_positionInParentFrame); +} + +void JointState::computeTransform(const glm::mat4& parentTransform, bool parentTransformChanged, bool synchronousRotationCompute) { + if (!parentTransformChanged && !_transformChanged) { + return; + } + + glm::quat rotationInParentFrame = _fbxJoint->preRotation * _rotationInConstrainedFrame * _fbxJoint->postRotation; + glm::mat4 transformInParentFrame = _fbxJoint->preTransform * glm::mat4_cast(rotationInParentFrame) * _fbxJoint->postTransform; + glm::mat4 newTransform = parentTransform * glm::translate(_fbxJoint->translation) * transformInParentFrame; + + if (newTransform != _transform) { + _transform = newTransform; + _transformChanged = true; + _rotationIsValid = false; + } +} + +void JointState::computeVisibleTransform(const glm::mat4& parentTransform) { + glm::quat rotationInParentFrame = _fbxJoint->preRotation * _visibleRotationInConstrainedFrame * _fbxJoint->postRotation; + glm::mat4 transformInParentFrame = _fbxJoint->preTransform * glm::mat4_cast(rotationInParentFrame) * _fbxJoint->postTransform; + _visibleTransform = parentTransform * glm::translate(_fbxJoint->translation) * transformInParentFrame; + _visibleRotation = extractRotation(_visibleTransform); +} + +glm::quat JointState::getRotationInBindFrame() const { + return getRotation() * _fbxJoint->inverseBindRotation; +} + +glm::quat JointState::getRotationInParentFrame() const { + return _fbxJoint->preRotation * _rotationInConstrainedFrame * _fbxJoint->postRotation; +} + +glm::quat JointState::getVisibleRotationInParentFrame() const { + return _fbxJoint->preRotation * _visibleRotationInConstrainedFrame * _fbxJoint->postRotation; +} + +void JointState::restoreRotation(float fraction, float priority) { + assert(_fbxJoint != NULL); + if (priority == _animationPriority || _animationPriority == 0.0f) { + setRotationInConstrainedFrameInternal(safeMix(_rotationInConstrainedFrame, _fbxJoint->rotation, fraction)); + _animationPriority = 0.0f; + } +} + +void JointState::setRotationInBindFrame(const glm::quat& rotation, float priority, bool constrain) { + // rotation is from bind- to model-frame + assert(_fbxJoint != NULL); + if (priority >= _animationPriority) { + glm::quat targetRotation = _rotationInConstrainedFrame * glm::inverse(getRotation()) * rotation * glm::inverse(_fbxJoint->inverseBindRotation); + if (constrain && _constraint) { + _constraint->softClamp(targetRotation, _rotationInConstrainedFrame, 0.5f); + } + setRotationInConstrainedFrameInternal(targetRotation); + _animationPriority = priority; + } +} + +void JointState::clearTransformTranslation() { + _transform[3][0] = 0.0f; + _transform[3][1] = 0.0f; + _transform[3][2] = 0.0f; + _transformChanged = true; + _visibleTransform[3][0] = 0.0f; + _visibleTransform[3][1] = 0.0f; + _visibleTransform[3][2] = 0.0f; +} + +void JointState::applyRotationDelta(const glm::quat& delta, bool constrain, float priority) { + // NOTE: delta is in model-frame + assert(_fbxJoint != NULL); + if (priority < _animationPriority || delta.null) { + return; + } + _animationPriority = priority; + glm::quat targetRotation = _rotationInConstrainedFrame * glm::inverse(getRotation()) * delta * getRotation(); + if (!constrain || _constraint == NULL) { + // no constraints + _rotationInConstrainedFrame = targetRotation; + _transformChanged = true; + + _rotation = delta * getRotation(); + return; + } + setRotationInConstrainedFrameInternal(targetRotation); +} + +/// Applies delta rotation to joint but mixes a little bit of the default pose as well. +/// This helps keep an IK solution stable. +void JointState::mixRotationDelta(const glm::quat& delta, float mixFactor, float priority) { + // NOTE: delta is in model-frame + assert(_fbxJoint != NULL); + if (priority < _animationPriority) { + return; + } + _animationPriority = priority; + glm::quat targetRotation = _rotationInConstrainedFrame * glm::inverse(getRotation()) * delta * getRotation(); + if (mixFactor > 0.0f && mixFactor <= 1.0f) { + targetRotation = safeMix(targetRotation, _fbxJoint->rotation, mixFactor); + } + if (_constraint) { + _constraint->softClamp(targetRotation, _rotationInConstrainedFrame, 0.5f); + } + setRotationInConstrainedFrameInternal(targetRotation); +} + +void JointState::mixVisibleRotationDelta(const glm::quat& delta, float mixFactor) { + // NOTE: delta is in model-frame + assert(_fbxJoint != NULL); + glm::quat targetRotation = _visibleRotationInConstrainedFrame * glm::inverse(_visibleRotation) * delta * _visibleRotation; + if (mixFactor > 0.0f && mixFactor <= 1.0f) { + //targetRotation = safeMix(targetRotation, _fbxJoint->rotation, mixFactor); + targetRotation = safeMix(targetRotation, _rotationInConstrainedFrame, mixFactor); + } + setVisibleRotationInConstrainedFrame(targetRotation); +} + +glm::quat JointState::computeParentRotation() const { + // R = Rp * Rpre * r * Rpost + // Rp = R * (Rpre * r * Rpost)^ + return getRotation() * glm::inverse(_fbxJoint->preRotation * _rotationInConstrainedFrame * _fbxJoint->postRotation); +} + +glm::quat JointState::computeVisibleParentRotation() const { + return _visibleRotation * glm::inverse(_fbxJoint->preRotation * _visibleRotationInConstrainedFrame * _fbxJoint->postRotation); +} + +void JointState::setRotationInConstrainedFrame(glm::quat targetRotation, float priority, bool constrain) { + if (priority >= _animationPriority || _animationPriority == 0.0f) { + if (constrain && _constraint) { + _constraint->softClamp(targetRotation, _rotationInConstrainedFrame, 0.5f); + } + setRotationInConstrainedFrameInternal(targetRotation); + _animationPriority = priority; + } +} + +void JointState::setRotationInConstrainedFrameInternal(const glm::quat& targetRotation) { + glm::quat parentRotation = computeParentRotation(); + _rotationInConstrainedFrame = targetRotation; + _transformChanged = true; + // R' = Rp * Rpre * r' * Rpost + _rotation = parentRotation * _fbxJoint->preRotation * _rotationInConstrainedFrame * _fbxJoint->postRotation; +} + +void JointState::setVisibleRotationInConstrainedFrame(const glm::quat& targetRotation) { + glm::quat parentRotation = computeVisibleParentRotation(); + _visibleRotationInConstrainedFrame = targetRotation; + _visibleRotation = parentRotation * _fbxJoint->preRotation * _visibleRotationInConstrainedFrame * _fbxJoint->postRotation; +} + +const bool JointState::rotationIsDefault(const glm::quat& rotation, float tolerance) const { + glm::quat defaultRotation = _fbxJoint->rotation; + return glm::abs(rotation.x - defaultRotation.x) < tolerance && + glm::abs(rotation.y - defaultRotation.y) < tolerance && + glm::abs(rotation.z - defaultRotation.z) < tolerance && + glm::abs(rotation.w - defaultRotation.w) < tolerance; +} + +glm::quat JointState::getDefaultRotationInParentFrame() const { + // NOTE: the result is constant and could be cached in the FBXJoint + return _fbxJoint->preRotation * _fbxJoint->rotation * _fbxJoint->postRotation; +} + +const glm::vec3& JointState::getDefaultTranslationInConstrainedFrame() const { + assert(_fbxJoint != NULL); + return _fbxJoint->translation; +} + +void JointState::slaveVisibleTransform() { + _visibleTransform = _transform; + _visibleRotation = getRotation(); + _visibleRotationInConstrainedFrame = _rotationInConstrainedFrame; +} diff --git a/libraries/render-utils/src/JointState.h b/libraries/render-utils/src/JointState.h new file mode 100644 index 0000000000..b502083463 --- /dev/null +++ b/libraries/render-utils/src/JointState.h @@ -0,0 +1,129 @@ +// +// JointState.h +// interface/src/renderer +// +// Created by Andrzej Kapolka on 10/18/13. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef hifi_JointState_h +#define hifi_JointState_h + +#include +#include +#include + +#include +#include + +const float DEFAULT_PRIORITY = 3.0f; + +class AngularConstraint; + +class JointState { +public: + JointState(); + JointState(const JointState& other); + ~JointState(); + + void setFBXJoint(const FBXJoint* joint); + const FBXJoint& getFBXJoint() const { return *_fbxJoint; } + + void buildConstraint(); + void copyState(const JointState& state); + + void initTransform(const glm::mat4& parentTransform); + // if synchronousRotationCompute is true, then _transform is still computed synchronously, + // but _rotation will be asynchronously extracted + void computeTransform(const glm::mat4& parentTransform, bool parentTransformChanged = true, bool synchronousRotationCompute = false); + + void computeVisibleTransform(const glm::mat4& parentTransform); + const glm::mat4& getVisibleTransform() const { return _visibleTransform; } + glm::quat getVisibleRotation() const { return _visibleRotation; } + glm::vec3 getVisiblePosition() const { return extractTranslation(_visibleTransform); } + + const glm::mat4& getTransform() const { return _transform; } + void resetTransformChanged() { _transformChanged = false; } + bool getTransformChanged() const { return _transformChanged; } + + glm::quat getRotation() const; + glm::vec3 getPosition() const { return extractTranslation(_transform); } + + /// \return rotation from bind to model frame + glm::quat getRotationInBindFrame() const; + + glm::quat getRotationInParentFrame() const; + glm::quat getVisibleRotationInParentFrame() const; + const glm::vec3& getPositionInParentFrame() const { return _positionInParentFrame; } + float getDistanceToParent() const { return _distanceToParent; } + + int getParentIndex() const { return _fbxJoint->parentIndex; } + + /// \param delta is in the model-frame + void applyRotationDelta(const glm::quat& delta, bool constrain = true, float priority = 1.0f); + + /// Applies delta rotation to joint but mixes a little bit of the default pose as well. + /// This helps keep an IK solution stable. + /// \param delta rotation change in model-frame + /// \param mixFactor fraction in range [0,1] of how much default pose to blend in (0 is none, 1 is all) + /// \param priority priority level of this animation blend + void mixRotationDelta(const glm::quat& delta, float mixFactor, float priority = 1.0f); + void mixVisibleRotationDelta(const glm::quat& delta, float mixFactor); + + /// Blends a fraciton of default pose into joint rotation. + /// \param fraction fraction in range [0,1] of how much default pose to blend in (0 is none, 1 is all) + /// \param priority priority level of this animation blend + void restoreRotation(float fraction, float priority); + + /// \param rotation is from bind- to model-frame + /// computes and sets new _rotationInConstrainedFrame + /// NOTE: the JointState's model-frame transform/rotation are NOT updated! + void setRotationInBindFrame(const glm::quat& rotation, float priority, bool constrain = false); + + void setRotationInConstrainedFrame(glm::quat targetRotation, float priority, bool constrain = false); + void setVisibleRotationInConstrainedFrame(const glm::quat& targetRotation); + const glm::quat& getRotationInConstrainedFrame() const { return _rotationInConstrainedFrame; } + const glm::quat& getVisibleRotationInConstrainedFrame() const { return _visibleRotationInConstrainedFrame; } + + const bool rotationIsDefault(const glm::quat& rotation, float tolerance = EPSILON) const; + + glm::quat getDefaultRotationInParentFrame() const; + const glm::vec3& getDefaultTranslationInConstrainedFrame() const; + + + void clearTransformTranslation(); + + void slaveVisibleTransform(); + + float _animationPriority; // the priority of the animation affecting this joint + + /// \return parent model-frame rotation + // (used to keep _rotation consistent when modifying _rotationInWorldFrame directly) + glm::quat computeParentRotation() const; + glm::quat computeVisibleParentRotation() const; + +private: + void setRotationInConstrainedFrameInternal(const glm::quat& targetRotation); + /// debug helper function + void loadBindRotation(); + + bool _transformChanged; + glm::mat4 _transform; // joint- to model-frame + bool _rotationIsValid; + glm::quat _rotation; // joint- to model-frame + glm::quat _rotationInConstrainedFrame; // rotation in frame where angular constraints would be applied + glm::vec3 _positionInParentFrame; // only changes when the Model is scaled + float _distanceToParent; + + glm::mat4 _visibleTransform; + glm::quat _visibleRotation; + glm::quat _visibleRotationInConstrainedFrame; + + const FBXJoint* _fbxJoint; // JointState does NOT own its FBXJoint + AngularConstraint* _constraint; // JointState owns its AngularConstraint +}; + +#endif // hifi_JointState_h From 660bf2720e0ffbd6971e3699ef7fa7efd7293ee0 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 19:48:15 -0800 Subject: [PATCH 131/258] convert AnimationCache to DependencyManager --- .../src/avatars/ScriptableAvatar.cpp | 2 +- interface/src/Application.cpp | 2 +- interface/src/Application.h | 3 --- interface/src/renderer/AnimationHandle.cpp | 4 ++-- libraries/animation/src/AnimationCache.h | 17 +++++++++-------- libraries/entities/src/ModelEntityItem.cpp | 3 +-- libraries/script-engine/src/ScriptEngine.cpp | 3 +-- libraries/script-engine/src/ScriptEngine.h | 2 -- 8 files changed, 15 insertions(+), 21 deletions(-) diff --git a/assignment-client/src/avatars/ScriptableAvatar.cpp b/assignment-client/src/avatars/ScriptableAvatar.cpp index 0f721ac98c..e2f0449216 100644 --- a/assignment-client/src/avatars/ScriptableAvatar.cpp +++ b/assignment-client/src/avatars/ScriptableAvatar.cpp @@ -28,7 +28,7 @@ void ScriptableAvatar::startAnimation(const QString& url, float fps, float prior Q_ARG(float, lastFrame), Q_ARG(const QStringList&, maskedJoints)); return; } - _animation = _scriptEngine->getAnimationCache()->getAnimation(url); + _animation = DependencyManager::get()->getAnimation(url); _animationDetails = AnimationDetails("", QUrl(url), fps, 0, loop, hold, false, firstFrame, lastFrame, true, firstFrame); _maskedJoints = maskedJoints; } diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index f3ac53c33b..5f0f4a700a 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -4003,7 +4003,7 @@ void Application::registerScriptEngineWithApplicationServices(ScriptEngine* scri scriptEngine->registerGlobalObject("Menu", MenuScriptingInterface::getInstance()); scriptEngine->registerGlobalObject("Settings", SettingsScriptingInterface::getInstance()); scriptEngine->registerGlobalObject("AudioDevice", AudioDeviceScriptingInterface::getInstance()); - scriptEngine->registerGlobalObject("AnimationCache", &_animationCache); + scriptEngine->registerGlobalObject("AnimationCache", DependencyManager::get()); scriptEngine->registerGlobalObject("SoundCache", &SoundCache::getInstance()); scriptEngine->registerGlobalObject("Account", AccountScriptingInterface::getInstance()); scriptEngine->registerGlobalObject("Metavoxels", &_metavoxels); diff --git a/interface/src/Application.h b/interface/src/Application.h index 716d67c661..992d8d31d3 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -249,7 +249,6 @@ public: ToolWindow* getToolWindow() { return _toolWindow ; } - AnimationCache* getAnimationCache() { return &_animationCache; } DeferredLightingEffect* getDeferredLightingEffect() { return &_deferredLightingEffect; } ControllerScriptingInterface* getControllerScriptingInterface() { return &_controllerScriptingInterface; } @@ -566,8 +565,6 @@ private: QSet _keysPressed; - AnimationCache _animationCache; - DeferredLightingEffect _deferredLightingEffect; AmbientOcclusionEffect _ambientOcclusionEffect; diff --git a/interface/src/renderer/AnimationHandle.cpp b/interface/src/renderer/AnimationHandle.cpp index 89c265875b..30edf97a33 100644 --- a/interface/src/renderer/AnimationHandle.cpp +++ b/interface/src/renderer/AnimationHandle.cpp @@ -10,11 +10,11 @@ // #include "AnimationHandle.h" -#include "Application.h" +#include "Model.h" void AnimationHandle::setURL(const QUrl& url) { if (_url != url) { - _animation = Application::getInstance()->getAnimationCache()->getAnimation(_url = url); + _animation = DependencyManager::get()->getAnimation(_url = url); _jointMappings.clear(); } } diff --git a/libraries/animation/src/AnimationCache.h b/libraries/animation/src/AnimationCache.h index 8a9e371cb0..5f3f305461 100644 --- a/libraries/animation/src/AnimationCache.h +++ b/libraries/animation/src/AnimationCache.h @@ -15,30 +15,31 @@ #include #include -#include - +#include #include +#include class Animation; typedef QSharedPointer AnimationPointer; /// Scriptable interface for FBX animation loading. -class AnimationCache : public ResourceCache { +class AnimationCache : public ResourceCache, public DependencyManager::Dependency { Q_OBJECT public: - - AnimationCache(QObject* parent = NULL); - Q_INVOKABLE AnimationPointer getAnimation(const QString& url) { return getAnimation(QUrl(url)); } - Q_INVOKABLE AnimationPointer getAnimation(const QUrl& url); protected: virtual QSharedPointer createResource(const QUrl& url, - const QSharedPointer& fallback, bool delayLoad, const void* extra); + const QSharedPointer& fallback, bool delayLoad, const void* extra); +private: + AnimationCache(QObject* parent = NULL); + virtual ~AnimationCache() { } + friend class DependencyManager; + }; Q_DECLARE_METATYPE(AnimationPointer) diff --git a/libraries/entities/src/ModelEntityItem.cpp b/libraries/entities/src/ModelEntityItem.cpp index b9bf75178f..b14248b3bc 100644 --- a/libraries/entities/src/ModelEntityItem.cpp +++ b/libraries/entities/src/ModelEntityItem.cpp @@ -285,7 +285,6 @@ void ModelEntityItem::appendSubclassData(OctreePacketData* packetData, EncodeBit QMap ModelEntityItem::_loadedAnimations; // TODO: improve cleanup by leveraging the AnimationPointer(s) -AnimationCache ModelEntityItem::_animationCache; // This class/instance will cleanup the animations once unloaded. class EntityAnimationsBookkeeper { @@ -309,7 +308,7 @@ Animation* ModelEntityItem::getAnimation(const QString& url) { // if we don't already have this model then create it and initialize it if (_loadedAnimations.find(url) == _loadedAnimations.end()) { - animation = _animationCache.getAnimation(url); + animation = DependencyManager::get()->getAnimation(url); _loadedAnimations[url] = animation; } else { animation = _loadedAnimations[url]; diff --git a/libraries/script-engine/src/ScriptEngine.cpp b/libraries/script-engine/src/ScriptEngine.cpp index 70c536e116..ec5f2bc0e7 100644 --- a/libraries/script-engine/src/ScriptEngine.cpp +++ b/libraries/script-engine/src/ScriptEngine.cpp @@ -94,7 +94,6 @@ ScriptEngine::ScriptEngine(const QString& scriptContents, const QString& fileNam _quatLibrary(), _vec3Library(), _uuidLibrary(), - _animationCache(this), _isUserLoaded(false), _arrayBufferClass(new ArrayBufferClass(this)) { @@ -256,7 +255,7 @@ void ScriptEngine::init() { registerGlobalObject("Quat", &_quatLibrary); registerGlobalObject("Vec3", &_vec3Library); registerGlobalObject("Uuid", &_uuidLibrary); - registerGlobalObject("AnimationCache", &_animationCache); + registerGlobalObject("AnimationCache", DependencyManager::get()); registerGlobalObject("Voxels", &_voxelsScriptingInterface); diff --git a/libraries/script-engine/src/ScriptEngine.h b/libraries/script-engine/src/ScriptEngine.h index fd28e98cab..3b074d7c73 100644 --- a/libraries/script-engine/src/ScriptEngine.h +++ b/libraries/script-engine/src/ScriptEngine.h @@ -51,7 +51,6 @@ public: static EntityScriptingInterface* getEntityScriptingInterface() { return &_entityScriptingInterface; } ArrayBufferClass* getArrayBufferClass() { return _arrayBufferClass; } - AnimationCache* getAnimationCache() { return &_animationCache; } /// sets the script contents, will return false if failed, will fail if script is already running bool setScriptContents(const QString& scriptContents, const QString& fileNameString = QString("")); @@ -149,7 +148,6 @@ private: Quat _quatLibrary; Vec3 _vec3Library; ScriptUUID _uuidLibrary; - AnimationCache _animationCache; bool _isUserLoaded; ArrayBufferClass* _arrayBufferClass; From 5cba44fd5b3d52fc2774c410b605388c19a139e0 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Mon, 15 Dec 2014 19:49:16 -0800 Subject: [PATCH 132/258] moved JointState --- interface/src/renderer/JointState.cpp | 281 -------------------------- interface/src/renderer/JointState.h | 129 ------------ 2 files changed, 410 deletions(-) delete mode 100644 interface/src/renderer/JointState.cpp delete mode 100644 interface/src/renderer/JointState.h diff --git a/interface/src/renderer/JointState.cpp b/interface/src/renderer/JointState.cpp deleted file mode 100644 index 96561758da..0000000000 --- a/interface/src/renderer/JointState.cpp +++ /dev/null @@ -1,281 +0,0 @@ -// -// JointState.cpp -// interface/src/renderer -// -// Created by Andrzej Kapolka on 10/18/13. -// Copyright 2013 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -#include - -#include - -#include -#include - -#include "JointState.h" - -JointState::JointState() : - _animationPriority(0.0f), - _transformChanged(true), - _rotationIsValid(false), - _positionInParentFrame(0.0f), - _distanceToParent(0.0f), - _fbxJoint(NULL), - _constraint(NULL) { -} - -JointState::JointState(const JointState& other) : _constraint(NULL) { - _transformChanged = other._transformChanged; - _transform = other._transform; - _rotationIsValid = other._rotationIsValid; - _rotation = other._rotation; - _rotationInConstrainedFrame = other._rotationInConstrainedFrame; - _positionInParentFrame = other._positionInParentFrame; - _distanceToParent = other._distanceToParent; - _animationPriority = other._animationPriority; - _fbxJoint = other._fbxJoint; - // DO NOT copy _constraint -} - -JointState::~JointState() { - delete _constraint; - _constraint = NULL; - if (_constraint) { - delete _constraint; - _constraint = NULL; - } -} - -glm::quat JointState::getRotation() const { - if (!_rotationIsValid) { - const_cast(this)->_rotation = extractRotation(_transform); - const_cast(this)->_rotationIsValid = true; - } - - return _rotation; -} - -void JointState::setFBXJoint(const FBXJoint* joint) { - assert(joint != NULL); - _rotationInConstrainedFrame = joint->rotation; - _transformChanged = true; - _rotationIsValid = false; - - // NOTE: JointState does not own the FBXJoint to which it points. - _fbxJoint = joint; - if (_constraint) { - delete _constraint; - _constraint = NULL; - } -} - -void JointState::buildConstraint() { - if (_constraint) { - delete _constraint; - _constraint = NULL; - } - if (glm::distance2(glm::vec3(-PI), _fbxJoint->rotationMin) > EPSILON || - glm::distance2(glm::vec3(PI), _fbxJoint->rotationMax) > EPSILON ) { - // this joint has rotation constraints - _constraint = AngularConstraint::newAngularConstraint(_fbxJoint->rotationMin, _fbxJoint->rotationMax); - } -} - -void JointState::copyState(const JointState& state) { - _animationPriority = state._animationPriority; - _transformChanged = state._transformChanged; - _transform = state._transform; - _rotationIsValid = state._rotationIsValid; - _rotation = state._rotation; - _rotationInConstrainedFrame = state._rotationInConstrainedFrame; - _positionInParentFrame = state._positionInParentFrame; - _distanceToParent = state._distanceToParent; - - _visibleTransform = state._visibleTransform; - _visibleRotation = extractRotation(_visibleTransform); - _visibleRotationInConstrainedFrame = state._visibleRotationInConstrainedFrame; - // DO NOT copy _fbxJoint or _constraint -} - -void JointState::initTransform(const glm::mat4& parentTransform) { - computeTransform(parentTransform); - _positionInParentFrame = glm::inverse(extractRotation(parentTransform)) * (extractTranslation(_transform) - extractTranslation(parentTransform)); - _distanceToParent = glm::length(_positionInParentFrame); -} - -void JointState::computeTransform(const glm::mat4& parentTransform, bool parentTransformChanged, bool synchronousRotationCompute) { - if (!parentTransformChanged && !_transformChanged) { - return; - } - - glm::quat rotationInParentFrame = _fbxJoint->preRotation * _rotationInConstrainedFrame * _fbxJoint->postRotation; - glm::mat4 transformInParentFrame = _fbxJoint->preTransform * glm::mat4_cast(rotationInParentFrame) * _fbxJoint->postTransform; - glm::mat4 newTransform = parentTransform * glm::translate(_fbxJoint->translation) * transformInParentFrame; - - if (newTransform != _transform) { - _transform = newTransform; - _transformChanged = true; - _rotationIsValid = false; - } -} - -void JointState::computeVisibleTransform(const glm::mat4& parentTransform) { - glm::quat rotationInParentFrame = _fbxJoint->preRotation * _visibleRotationInConstrainedFrame * _fbxJoint->postRotation; - glm::mat4 transformInParentFrame = _fbxJoint->preTransform * glm::mat4_cast(rotationInParentFrame) * _fbxJoint->postTransform; - _visibleTransform = parentTransform * glm::translate(_fbxJoint->translation) * transformInParentFrame; - _visibleRotation = extractRotation(_visibleTransform); -} - -glm::quat JointState::getRotationInBindFrame() const { - return getRotation() * _fbxJoint->inverseBindRotation; -} - -glm::quat JointState::getRotationInParentFrame() const { - return _fbxJoint->preRotation * _rotationInConstrainedFrame * _fbxJoint->postRotation; -} - -glm::quat JointState::getVisibleRotationInParentFrame() const { - return _fbxJoint->preRotation * _visibleRotationInConstrainedFrame * _fbxJoint->postRotation; -} - -void JointState::restoreRotation(float fraction, float priority) { - assert(_fbxJoint != NULL); - if (priority == _animationPriority || _animationPriority == 0.0f) { - setRotationInConstrainedFrameInternal(safeMix(_rotationInConstrainedFrame, _fbxJoint->rotation, fraction)); - _animationPriority = 0.0f; - } -} - -void JointState::setRotationInBindFrame(const glm::quat& rotation, float priority, bool constrain) { - // rotation is from bind- to model-frame - assert(_fbxJoint != NULL); - if (priority >= _animationPriority) { - glm::quat targetRotation = _rotationInConstrainedFrame * glm::inverse(getRotation()) * rotation * glm::inverse(_fbxJoint->inverseBindRotation); - if (constrain && _constraint) { - _constraint->softClamp(targetRotation, _rotationInConstrainedFrame, 0.5f); - } - setRotationInConstrainedFrameInternal(targetRotation); - _animationPriority = priority; - } -} - -void JointState::clearTransformTranslation() { - _transform[3][0] = 0.0f; - _transform[3][1] = 0.0f; - _transform[3][2] = 0.0f; - _transformChanged = true; - _visibleTransform[3][0] = 0.0f; - _visibleTransform[3][1] = 0.0f; - _visibleTransform[3][2] = 0.0f; -} - -void JointState::applyRotationDelta(const glm::quat& delta, bool constrain, float priority) { - // NOTE: delta is in model-frame - assert(_fbxJoint != NULL); - if (priority < _animationPriority || delta.null) { - return; - } - _animationPriority = priority; - glm::quat targetRotation = _rotationInConstrainedFrame * glm::inverse(getRotation()) * delta * getRotation(); - if (!constrain || _constraint == NULL) { - // no constraints - _rotationInConstrainedFrame = targetRotation; - _transformChanged = true; - - _rotation = delta * getRotation(); - return; - } - setRotationInConstrainedFrameInternal(targetRotation); -} - -/// Applies delta rotation to joint but mixes a little bit of the default pose as well. -/// This helps keep an IK solution stable. -void JointState::mixRotationDelta(const glm::quat& delta, float mixFactor, float priority) { - // NOTE: delta is in model-frame - assert(_fbxJoint != NULL); - if (priority < _animationPriority) { - return; - } - _animationPriority = priority; - glm::quat targetRotation = _rotationInConstrainedFrame * glm::inverse(getRotation()) * delta * getRotation(); - if (mixFactor > 0.0f && mixFactor <= 1.0f) { - targetRotation = safeMix(targetRotation, _fbxJoint->rotation, mixFactor); - } - if (_constraint) { - _constraint->softClamp(targetRotation, _rotationInConstrainedFrame, 0.5f); - } - setRotationInConstrainedFrameInternal(targetRotation); -} - -void JointState::mixVisibleRotationDelta(const glm::quat& delta, float mixFactor) { - // NOTE: delta is in model-frame - assert(_fbxJoint != NULL); - glm::quat targetRotation = _visibleRotationInConstrainedFrame * glm::inverse(_visibleRotation) * delta * _visibleRotation; - if (mixFactor > 0.0f && mixFactor <= 1.0f) { - //targetRotation = safeMix(targetRotation, _fbxJoint->rotation, mixFactor); - targetRotation = safeMix(targetRotation, _rotationInConstrainedFrame, mixFactor); - } - setVisibleRotationInConstrainedFrame(targetRotation); -} - -glm::quat JointState::computeParentRotation() const { - // R = Rp * Rpre * r * Rpost - // Rp = R * (Rpre * r * Rpost)^ - return getRotation() * glm::inverse(_fbxJoint->preRotation * _rotationInConstrainedFrame * _fbxJoint->postRotation); -} - -glm::quat JointState::computeVisibleParentRotation() const { - return _visibleRotation * glm::inverse(_fbxJoint->preRotation * _visibleRotationInConstrainedFrame * _fbxJoint->postRotation); -} - -void JointState::setRotationInConstrainedFrame(glm::quat targetRotation, float priority, bool constrain) { - if (priority >= _animationPriority || _animationPriority == 0.0f) { - if (constrain && _constraint) { - _constraint->softClamp(targetRotation, _rotationInConstrainedFrame, 0.5f); - } - setRotationInConstrainedFrameInternal(targetRotation); - _animationPriority = priority; - } -} - -void JointState::setRotationInConstrainedFrameInternal(const glm::quat& targetRotation) { - glm::quat parentRotation = computeParentRotation(); - _rotationInConstrainedFrame = targetRotation; - _transformChanged = true; - // R' = Rp * Rpre * r' * Rpost - _rotation = parentRotation * _fbxJoint->preRotation * _rotationInConstrainedFrame * _fbxJoint->postRotation; -} - -void JointState::setVisibleRotationInConstrainedFrame(const glm::quat& targetRotation) { - glm::quat parentRotation = computeVisibleParentRotation(); - _visibleRotationInConstrainedFrame = targetRotation; - _visibleRotation = parentRotation * _fbxJoint->preRotation * _visibleRotationInConstrainedFrame * _fbxJoint->postRotation; -} - -const bool JointState::rotationIsDefault(const glm::quat& rotation, float tolerance) const { - glm::quat defaultRotation = _fbxJoint->rotation; - return glm::abs(rotation.x - defaultRotation.x) < tolerance && - glm::abs(rotation.y - defaultRotation.y) < tolerance && - glm::abs(rotation.z - defaultRotation.z) < tolerance && - glm::abs(rotation.w - defaultRotation.w) < tolerance; -} - -glm::quat JointState::getDefaultRotationInParentFrame() const { - // NOTE: the result is constant and could be cached in the FBXJoint - return _fbxJoint->preRotation * _fbxJoint->rotation * _fbxJoint->postRotation; -} - -const glm::vec3& JointState::getDefaultTranslationInConstrainedFrame() const { - assert(_fbxJoint != NULL); - return _fbxJoint->translation; -} - -void JointState::slaveVisibleTransform() { - _visibleTransform = _transform; - _visibleRotation = getRotation(); - _visibleRotationInConstrainedFrame = _rotationInConstrainedFrame; -} diff --git a/interface/src/renderer/JointState.h b/interface/src/renderer/JointState.h deleted file mode 100644 index b502083463..0000000000 --- a/interface/src/renderer/JointState.h +++ /dev/null @@ -1,129 +0,0 @@ -// -// JointState.h -// interface/src/renderer -// -// Created by Andrzej Kapolka on 10/18/13. -// Copyright 2013 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -#ifndef hifi_JointState_h -#define hifi_JointState_h - -#include -#include -#include - -#include -#include - -const float DEFAULT_PRIORITY = 3.0f; - -class AngularConstraint; - -class JointState { -public: - JointState(); - JointState(const JointState& other); - ~JointState(); - - void setFBXJoint(const FBXJoint* joint); - const FBXJoint& getFBXJoint() const { return *_fbxJoint; } - - void buildConstraint(); - void copyState(const JointState& state); - - void initTransform(const glm::mat4& parentTransform); - // if synchronousRotationCompute is true, then _transform is still computed synchronously, - // but _rotation will be asynchronously extracted - void computeTransform(const glm::mat4& parentTransform, bool parentTransformChanged = true, bool synchronousRotationCompute = false); - - void computeVisibleTransform(const glm::mat4& parentTransform); - const glm::mat4& getVisibleTransform() const { return _visibleTransform; } - glm::quat getVisibleRotation() const { return _visibleRotation; } - glm::vec3 getVisiblePosition() const { return extractTranslation(_visibleTransform); } - - const glm::mat4& getTransform() const { return _transform; } - void resetTransformChanged() { _transformChanged = false; } - bool getTransformChanged() const { return _transformChanged; } - - glm::quat getRotation() const; - glm::vec3 getPosition() const { return extractTranslation(_transform); } - - /// \return rotation from bind to model frame - glm::quat getRotationInBindFrame() const; - - glm::quat getRotationInParentFrame() const; - glm::quat getVisibleRotationInParentFrame() const; - const glm::vec3& getPositionInParentFrame() const { return _positionInParentFrame; } - float getDistanceToParent() const { return _distanceToParent; } - - int getParentIndex() const { return _fbxJoint->parentIndex; } - - /// \param delta is in the model-frame - void applyRotationDelta(const glm::quat& delta, bool constrain = true, float priority = 1.0f); - - /// Applies delta rotation to joint but mixes a little bit of the default pose as well. - /// This helps keep an IK solution stable. - /// \param delta rotation change in model-frame - /// \param mixFactor fraction in range [0,1] of how much default pose to blend in (0 is none, 1 is all) - /// \param priority priority level of this animation blend - void mixRotationDelta(const glm::quat& delta, float mixFactor, float priority = 1.0f); - void mixVisibleRotationDelta(const glm::quat& delta, float mixFactor); - - /// Blends a fraciton of default pose into joint rotation. - /// \param fraction fraction in range [0,1] of how much default pose to blend in (0 is none, 1 is all) - /// \param priority priority level of this animation blend - void restoreRotation(float fraction, float priority); - - /// \param rotation is from bind- to model-frame - /// computes and sets new _rotationInConstrainedFrame - /// NOTE: the JointState's model-frame transform/rotation are NOT updated! - void setRotationInBindFrame(const glm::quat& rotation, float priority, bool constrain = false); - - void setRotationInConstrainedFrame(glm::quat targetRotation, float priority, bool constrain = false); - void setVisibleRotationInConstrainedFrame(const glm::quat& targetRotation); - const glm::quat& getRotationInConstrainedFrame() const { return _rotationInConstrainedFrame; } - const glm::quat& getVisibleRotationInConstrainedFrame() const { return _visibleRotationInConstrainedFrame; } - - const bool rotationIsDefault(const glm::quat& rotation, float tolerance = EPSILON) const; - - glm::quat getDefaultRotationInParentFrame() const; - const glm::vec3& getDefaultTranslationInConstrainedFrame() const; - - - void clearTransformTranslation(); - - void slaveVisibleTransform(); - - float _animationPriority; // the priority of the animation affecting this joint - - /// \return parent model-frame rotation - // (used to keep _rotation consistent when modifying _rotationInWorldFrame directly) - glm::quat computeParentRotation() const; - glm::quat computeVisibleParentRotation() const; - -private: - void setRotationInConstrainedFrameInternal(const glm::quat& targetRotation); - /// debug helper function - void loadBindRotation(); - - bool _transformChanged; - glm::mat4 _transform; // joint- to model-frame - bool _rotationIsValid; - glm::quat _rotation; // joint- to model-frame - glm::quat _rotationInConstrainedFrame; // rotation in frame where angular constraints would be applied - glm::vec3 _positionInParentFrame; // only changes when the Model is scaled - float _distanceToParent; - - glm::mat4 _visibleTransform; - glm::quat _visibleRotation; - glm::quat _visibleRotationInConstrainedFrame; - - const FBXJoint* _fbxJoint; // JointState does NOT own its FBXJoint - AngularConstraint* _constraint; // JointState owns its AngularConstraint -}; - -#endif // hifi_JointState_h From cd95f7bd23a0d43088cbefdbd442ce63341bc185 Mon Sep 17 00:00:00 2001 From: DaveDubUK Date: Tue, 16 Dec 2014 13:20:11 +0000 Subject: [PATCH 133/258] Window.nonBlockingForm active status was not being tested correctly. Was causing unexpected fail on second attempt to show form --- interface/src/scripting/WindowScriptingInterface.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interface/src/scripting/WindowScriptingInterface.cpp b/interface/src/scripting/WindowScriptingInterface.cpp index 591ae87560..bbb4e695e7 100644 --- a/interface/src/scripting/WindowScriptingInterface.cpp +++ b/interface/src/scripting/WindowScriptingInterface.cpp @@ -200,7 +200,7 @@ void WindowScriptingInterface::showNonBlockingForm(const QString& title, QScript } // what should we do if someone calls us while we still think we have a dialog showing??? - if (_editDialog) { + if (_nonBlockingFormActive) { qDebug() << "Show Non-Blocking Form called when form already active."; return; } From 9493440d323f65b33f5c60d28fd9b75dd3a91959 Mon Sep 17 00:00:00 2001 From: DaveDubUK Date: Tue, 16 Dec 2014 13:33:10 +0000 Subject: [PATCH 134/258] Window.nonBlockingForm-fix --- interface/src/scripting/WindowScriptingInterface.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/interface/src/scripting/WindowScriptingInterface.cpp b/interface/src/scripting/WindowScriptingInterface.cpp index bbb4e695e7..fa6de82bfe 100644 --- a/interface/src/scripting/WindowScriptingInterface.cpp +++ b/interface/src/scripting/WindowScriptingInterface.cpp @@ -201,6 +201,7 @@ void WindowScriptingInterface::showNonBlockingForm(const QString& title, QScript // what should we do if someone calls us while we still think we have a dialog showing??? if (_nonBlockingFormActive) { + qDebug() << "Show Non-Blocking Form called when form already active."; return; } From 7ab9dfbfe1ab1cf8010cf50a4035d04c111e3e04 Mon Sep 17 00:00:00 2001 From: DaveDubUK Date: Tue, 16 Dec 2014 14:48:28 +0000 Subject: [PATCH 135/258] Window.nonBlockingForm-fix --- interface/src/scripting/WindowScriptingInterface.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/interface/src/scripting/WindowScriptingInterface.cpp b/interface/src/scripting/WindowScriptingInterface.cpp index fa6de82bfe..bbb4e695e7 100644 --- a/interface/src/scripting/WindowScriptingInterface.cpp +++ b/interface/src/scripting/WindowScriptingInterface.cpp @@ -201,7 +201,6 @@ void WindowScriptingInterface::showNonBlockingForm(const QString& title, QScript // what should we do if someone calls us while we still think we have a dialog showing??? if (_nonBlockingFormActive) { - qDebug() << "Show Non-Blocking Form called when form already active."; return; } From 4d79a08533534458491c110db6eadd21968c0397 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 16 Dec 2014 10:32:03 -0800 Subject: [PATCH 136/258] remove Application dependencies from AmbientOcclusion and DeferredLightingEffect --- interface/src/Application.cpp | 12 +++++-- interface/src/Application.h | 11 ++++-- .../src/renderer/AmbientOcclusionEffect.cpp | 9 +++-- .../src/renderer/AmbientOcclusionEffect.h | 6 ++-- .../src/renderer/DeferredLightingEffect.cpp | 23 ++++++------ .../src/renderer/DeferredLightingEffect.h | 5 ++- .../render-utils/src/ViewStateInterface.h | 36 +++++++++++++++++++ 7 files changed, 78 insertions(+), 24 deletions(-) create mode 100644 libraries/render-utils/src/ViewStateInterface.h diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 5f0f4a700a..57b3b57224 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1914,8 +1914,8 @@ void Application::init() { _environment.init(); - _deferredLightingEffect.init(); - _ambientOcclusionEffect.init(); + _deferredLightingEffect.init(this); + _ambientOcclusionEffect.init(this); // TODO: move _myAvatar out of Application. Move relevant code to MyAvataar or AvatarManager _avatarManager.init(); @@ -3235,6 +3235,14 @@ void Application::computeOffAxisFrustum(float& left, float& right, float& bottom } } +bool Application::getShadowsEnabled() { + return Menu::getInstance()->getShadowsEnabled(); +} + +bool Application::getCascadeShadowsEnabled() { + return Menu::getInstance()->isOptionChecked(MenuOption::CascadedShadows); +} + glm::vec2 Application::getScaledScreenPoint(glm::vec2 projectedPoint) { float horizontalScale = _glWidget->getDeviceWidth() / 2.0f; float verticalScale = _glWidget->getDeviceHeight() / 2.0f; diff --git a/interface/src/Application.h b/interface/src/Application.h index 992d8d31d3..9ca363254a 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -42,6 +42,7 @@ #include #include #include +#include #include #include "MainWindow.h" @@ -128,7 +129,7 @@ static const quint64 TOO_LONG_SINCE_LAST_SEND_DOWNSTREAM_AUDIO_STATS = 1 * USECS static const QString INFO_HELP_PATH = "html/interface-welcome-allsvg.html"; static const QString INFO_EDIT_ENTITIES_PATH = "html/edit-entities-commands.html"; -class Application : public QApplication { +class Application : public QApplication, public ViewStateInterface { Q_OBJECT friend class OctreePacketProcessor; @@ -276,12 +277,16 @@ public: void getModelViewMatrix(glm::dmat4* modelViewMatrix); void getProjectionMatrix(glm::dmat4* projectionMatrix); - const glm::vec3& getShadowDistances() const { return _shadowDistances; } + virtual const glm::vec3& getShadowDistances() const { return _shadowDistances; } /// Computes the off-axis frustum parameters for the view frustum, taking mirroring into account. - void computeOffAxisFrustum(float& left, float& right, float& bottom, float& top, float& nearVal, + virtual void computeOffAxisFrustum(float& left, float& right, float& bottom, float& top, float& nearVal, float& farVal, glm::vec4& nearClipPlane, glm::vec4& farClipPlane) const; + virtual ViewFrustum* getCurrentViewFrustum() { return getDisplayViewFrustum(); } + virtual bool getShadowsEnabled(); + virtual bool getCascadeShadowsEnabled(); + NodeBounds& getNodeBoundsDisplay() { return _nodeBoundsDisplay; } FileLogger* getLogger() { return _logger; } diff --git a/interface/src/renderer/AmbientOcclusionEffect.cpp b/interface/src/renderer/AmbientOcclusionEffect.cpp index bcae662085..4362d21645 100644 --- a/interface/src/renderer/AmbientOcclusionEffect.cpp +++ b/interface/src/renderer/AmbientOcclusionEffect.cpp @@ -21,15 +21,15 @@ #include #include #include - -#include "Application.h" +#include #include "AmbientOcclusionEffect.h" const int ROTATION_WIDTH = 4; const int ROTATION_HEIGHT = 4; -void AmbientOcclusionEffect::init() { +void AmbientOcclusionEffect::init(ViewStateInterface* viewState) { + _viewState = viewState; // we will use this for view state services _occlusionProgram = new ProgramObject(); _occlusionProgram->addShaderFromSourceFile(QGLShader::Vertex, PathUtils::resourcesPath() @@ -111,8 +111,7 @@ void AmbientOcclusionEffect::render() { float left, right, bottom, top, nearVal, farVal; glm::vec4 nearClipPlane, farClipPlane; - Application::getInstance()->computeOffAxisFrustum( - left, right, bottom, top, nearVal, farVal, nearClipPlane, farClipPlane); + _viewState->computeOffAxisFrustum(left, right, bottom, top, nearVal, farVal, nearClipPlane, farClipPlane); int viewport[4]; glGetIntegerv(GL_VIEWPORT, viewport); diff --git a/interface/src/renderer/AmbientOcclusionEffect.h b/interface/src/renderer/AmbientOcclusionEffect.h index 3b22c7629a..444b76a3c9 100644 --- a/interface/src/renderer/AmbientOcclusionEffect.h +++ b/interface/src/renderer/AmbientOcclusionEffect.h @@ -12,6 +12,8 @@ #ifndef hifi_AmbientOcclusionEffect_h #define hifi_AmbientOcclusionEffect_h +#include + class ProgramObject; /// A screen space ambient occlusion effect. See John Chapman's tutorial at @@ -19,8 +21,7 @@ class ProgramObject; class AmbientOcclusionEffect { public: - void init(); - + void init(ViewStateInterface* viewState); void render(); private: @@ -38,6 +39,7 @@ private: int _blurScaleLocation; GLuint _rotationTextureID; + ViewStateInterface* _viewState; }; #endif // hifi_AmbientOcclusionEffect_h diff --git a/interface/src/renderer/DeferredLightingEffect.cpp b/interface/src/renderer/DeferredLightingEffect.cpp index 18a93aa042..d3145b9d5d 100644 --- a/interface/src/renderer/DeferredLightingEffect.cpp +++ b/interface/src/renderer/DeferredLightingEffect.cpp @@ -14,14 +14,17 @@ #include +#include +#include #include #include #include +#include -#include "Application.h" #include "DeferredLightingEffect.h" -void DeferredLightingEffect::init() { +void DeferredLightingEffect::init(ViewStateInterface* viewState) { + _viewState = viewState; _simpleProgram.addShaderFromSourceFile(QGLShader::Vertex, PathUtils::resourcesPath() + "shaders/simple.vert"); _simpleProgram.addShaderFromSourceFile(QGLShader::Fragment, PathUtils::resourcesPath() + "shaders/simple.frag"); _simpleProgram.link(); @@ -176,19 +179,18 @@ void DeferredLightingEffect::render() { ProgramObject* program = &_directionalLight; const LightLocations* locations = &_directionalLightLocations; - bool shadowsEnabled = Menu::getInstance()->getShadowsEnabled(); - if (shadowsEnabled) { + bool shadowsEnabled = _viewState->getShadowsEnabled(); + if (shadowsEnabled) { glActiveTexture(GL_TEXTURE4); glBindTexture(GL_TEXTURE_2D, textureCache->getShadowDepthTextureID()); program = &_directionalLightShadowMap; locations = &_directionalLightShadowMapLocations; - if (Menu::getInstance()->isOptionChecked(MenuOption::CascadedShadows)) { + if (_viewState->getCascadeShadowsEnabled()) { program = &_directionalLightCascadedShadowMap; locations = &_directionalLightCascadedShadowMapLocations; _directionalLightCascadedShadowMap.bind(); - _directionalLightCascadedShadowMap.setUniform(locations->shadowDistances, - Application::getInstance()->getShadowDistances()); + _directionalLightCascadedShadowMap.setUniform(locations->shadowDistances, _viewState->getShadowDistances()); } else { program->bind(); @@ -202,8 +204,7 @@ void DeferredLightingEffect::render() { float left, right, bottom, top, nearVal, farVal; glm::vec4 nearClipPlane, farClipPlane; - Application::getInstance()->computeOffAxisFrustum( - left, right, bottom, top, nearVal, farVal, nearClipPlane, farClipPlane); + _viewState->computeOffAxisFrustum(left, right, bottom, top, nearVal, farVal, nearClipPlane, farClipPlane); program->setUniformValue(locations->nearLocation, nearVal); float depthScale = (farVal - nearVal) / farVal; program->setUniformValue(locations->depthScale, depthScale); @@ -238,8 +239,8 @@ void DeferredLightingEffect::render() { // enlarge the scales slightly to account for tesselation const float SCALE_EXPANSION = 0.05f; - const glm::vec3& eyePoint = Application::getInstance()->getDisplayViewFrustum()->getPosition(); - float nearRadius = glm::distance(eyePoint, Application::getInstance()->getDisplayViewFrustum()->getNearTopLeft()); + const glm::vec3& eyePoint = _viewState->getCurrentViewFrustum()->getPosition(); + float nearRadius = glm::distance(eyePoint, _viewState->getCurrentViewFrustum()->getNearTopLeft()); GeometryCache* geometryCache = DependencyManager::get(); diff --git a/interface/src/renderer/DeferredLightingEffect.h b/interface/src/renderer/DeferredLightingEffect.h index effcea27d2..40182e0917 100644 --- a/interface/src/renderer/DeferredLightingEffect.h +++ b/interface/src/renderer/DeferredLightingEffect.h @@ -16,6 +16,7 @@ #include #include +#include class PostLightingRenderable; @@ -23,7 +24,7 @@ class PostLightingRenderable; class DeferredLightingEffect { public: - void init(); + void init(ViewStateInterface* viewState); /// Returns a reference to a simple program suitable for rendering static /// untextured geometry (such as that generated by glutSolidSphere, etc.) @@ -118,6 +119,8 @@ private: QVector _pointLights; QVector _spotLights; QVector _postLightingRenderables; + + ViewStateInterface* _viewState; }; /// Simple interface for objects that require something to be rendered after deferred lighting. diff --git a/libraries/render-utils/src/ViewStateInterface.h b/libraries/render-utils/src/ViewStateInterface.h new file mode 100644 index 0000000000..decccdc401 --- /dev/null +++ b/libraries/render-utils/src/ViewStateInterface.h @@ -0,0 +1,36 @@ +// +// ViewStateInterface.h +// interface/src/renderer +// +// Created by Brad Hefta-Gaub on 12/16/14. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef hifi_ViewStateInterface_h +#define hifi_ViewStateInterface_h + +#include + +/// Interface provided by Application to other objects that need access to the current view state details +class ViewStateInterface { +public: + + /// Returns the shadow distances for the current view state + virtual const glm::vec3& getShadowDistances() const = 0; + + /// Computes the off-axis frustum parameters for the view frustum, taking mirroring into account. + virtual void computeOffAxisFrustum(float& left, float& right, float& bottom, float& top, float& nearVal, + float& farVal, glm::vec4& nearClipPlane, glm::vec4& farClipPlane) const = 0; + + /// gets the current view frustum for rendering the view state + virtual ViewFrustum* getCurrentViewFrustum() = 0; + + virtual bool getShadowsEnabled() = 0; + virtual bool getCascadeShadowsEnabled() = 0; +}; + + +#endif // hifi_ViewStateInterface_h From fc1e1ecfc04fdc3475fb990c3e19f29e343b978d Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 16 Dec 2014 11:27:44 -0800 Subject: [PATCH 137/258] move DeferredLightingEffect and AmbientOcclusionEffect to libraries, make them DependencyManager enabled --- interface/src/Application.cpp | 13 +++++--- interface/src/Application.h | 7 ---- interface/src/MetavoxelSystem.cpp | 9 ++--- interface/src/avatar/Avatar.cpp | 3 +- .../src/entities/RenderableBoxEntityItem.cpp | 7 ++-- .../entities/RenderableLightEntityItem.cpp | 33 ++++++++++--------- .../entities/RenderableModelEntityItem.cpp | 7 ++-- .../entities/RenderableSphereEntityItem.cpp | 5 +-- interface/src/renderer/Model.cpp | 3 +- interface/src/ui/overlays/Cube3DOverlay.cpp | 7 ++-- interface/src/ui/overlays/Sphere3DOverlay.cpp | 1 - .../src}/AmbientOcclusionEffect.cpp | 10 +++--- .../src}/AmbientOcclusionEffect.h | 9 +++-- .../src}/DeferredLightingEffect.cpp | 20 ++++++++--- .../src}/DeferredLightingEffect.h | 11 +++++-- 15 files changed, 84 insertions(+), 61 deletions(-) rename {interface/src/renderer => libraries/render-utils/src}/AmbientOcclusionEffect.cpp (98%) rename {interface/src/renderer => libraries/render-utils/src}/AmbientOcclusionEffect.h (81%) rename {interface/src/renderer => libraries/render-utils/src}/DeferredLightingEffect.cpp (98%) rename {interface/src/renderer => libraries/render-utils/src}/DeferredLightingEffect.h (94%) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 57b3b57224..c9309616ae 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -54,7 +54,9 @@ #include #include +#include #include +#include #include #include #include @@ -110,6 +112,7 @@ #include "ui/TextRenderer.h" + using namespace std; // Starfield information @@ -1914,8 +1917,8 @@ void Application::init() { _environment.init(); - _deferredLightingEffect.init(this); - _ambientOcclusionEffect.init(this); + DependencyManager::get()->init(this); + DependencyManager::get()->init(this); // TODO: move _myAvatar out of Application. Move relevant code to MyAvataar or AvatarManager _avatarManager.init(); @@ -3070,7 +3073,7 @@ void Application::displaySide(Camera& whichCamera, bool selfAvatarOnly, RenderAr glEnable(GL_LIGHTING); glEnable(GL_DEPTH_TEST); - _deferredLightingEffect.prepare(); + DependencyManager::get()->prepare(); if (!selfAvatarOnly) { // draw a red sphere @@ -3113,7 +3116,7 @@ void Application::displaySide(Camera& whichCamera, bool selfAvatarOnly, RenderAr PerformanceTimer perfTimer("ambientOcclusion"); PerformanceWarning warn(Menu::getInstance()->isOptionChecked(MenuOption::PipelineWarnings), "Application::displaySide() ... AmbientOcclusion..."); - _ambientOcclusionEffect.render(); + DependencyManager::get()->render(); } } @@ -3130,7 +3133,7 @@ void Application::displaySide(Camera& whichCamera, bool selfAvatarOnly, RenderAr { PROFILE_RANGE("DeferredLighting"); PerformanceTimer perfTimer("lighting"); - _deferredLightingEffect.render(); + DependencyManager::get()->render(); } { diff --git a/interface/src/Application.h b/interface/src/Application.h index 9ca363254a..6b5bcc0770 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -62,8 +62,6 @@ #include "devices/PrioVR.h" #include "devices/SixenseManager.h" #include "entities/EntityTreeRenderer.h" -#include "renderer/AmbientOcclusionEffect.h" -#include "renderer/DeferredLightingEffect.h" #include "scripting/ControllerScriptingInterface.h" #include "ui/BandwidthDialog.h" #include "ui/BandwidthMeter.h" @@ -250,7 +248,6 @@ public: ToolWindow* getToolWindow() { return _toolWindow ; } - DeferredLightingEffect* getDeferredLightingEffect() { return &_deferredLightingEffect; } ControllerScriptingInterface* getControllerScriptingInterface() { return &_controllerScriptingInterface; } AvatarManager& getAvatarManager() { return _avatarManager; } @@ -569,10 +566,6 @@ private: QSet _keysPressed; - - DeferredLightingEffect _deferredLightingEffect; - AmbientOcclusionEffect _ambientOcclusionEffect; - Audio _audio; bool _enableProcessVoxelsThread; diff --git a/interface/src/MetavoxelSystem.cpp b/interface/src/MetavoxelSystem.cpp index 824f1e3313..d34bc4a594 100644 --- a/interface/src/MetavoxelSystem.cpp +++ b/interface/src/MetavoxelSystem.cpp @@ -21,6 +21,7 @@ #include +#include #include #include @@ -470,7 +471,7 @@ void MetavoxelSystem::render() { glColor4f(1.0f, 1.0f, 1.0f, 1.0f); glNormal3f(0.0f, 1.0f, 0.0f); - Application::getInstance()->getDeferredLightingEffect()->bindSimpleProgram(); + DependencyManager::get()->bindSimpleProgram(); foreach (const HermiteBatch& batch, _hermiteBatches) { batch.vertexBuffer->bind(); @@ -482,7 +483,7 @@ void MetavoxelSystem::render() { batch.vertexBuffer->release(); } - Application::getInstance()->getDeferredLightingEffect()->releaseSimpleProgram(); + DependencyManager::get()->releaseSimpleProgram(); glDisableClientState(GL_VERTEX_ARRAY); @@ -1981,7 +1982,7 @@ void SphereRenderer::render(const MetavoxelLOD& lod, bool contained, bool cursor glm::vec3 axis = glm::axis(rotation); glRotatef(glm::degrees(glm::angle(rotation)), axis.x, axis.y, axis.z); - Application::getInstance()->getDeferredLightingEffect()->renderSolidSphere(sphere->getScale(), 32, 32); + DependencyManager::get()->renderSolidSphere(sphere->getScale(), 32, 32); glPopMatrix(); } @@ -2002,7 +2003,7 @@ void CuboidRenderer::render(const MetavoxelLOD& lod, bool contained, bool cursor glRotatef(glm::degrees(glm::angle(rotation)), axis.x, axis.y, axis.z); glScalef(1.0f, cuboid->getAspectY(), cuboid->getAspectZ()); - Application::getInstance()->getDeferredLightingEffect()->renderSolidCube(cuboid->getScale() * 2.0f); + DependencyManager::get()->renderSolidCube(cuboid->getScale() * 2.0f); glPopMatrix(); } diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index 4b7c5dfdf3..51fde3df43 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -22,6 +22,7 @@ #include #include +#include #include #include #include @@ -364,7 +365,7 @@ void Avatar::render(const glm::vec3& cameraPosition, RenderMode renderMode, bool glm::quat orientation = getOrientation(); foreach (const AvatarManager::LocalLight& light, Application::getInstance()->getAvatarManager().getLocalLights()) { glm::vec3 direction = orientation * light.direction; - Application::getInstance()->getDeferredLightingEffect()->addSpotLight(position - direction * distance, + DependencyManager::get()->addSpotLight(position - direction * distance, distance * 2.0f, glm::vec3(), light.color, light.color, 1.0f, 0.5f, 0.0f, direction, LIGHT_EXPONENT, LIGHT_CUTOFF); } diff --git a/interface/src/entities/RenderableBoxEntityItem.cpp b/interface/src/entities/RenderableBoxEntityItem.cpp index 1cc1f72e93..f7b403bff2 100644 --- a/interface/src/entities/RenderableBoxEntityItem.cpp +++ b/interface/src/entities/RenderableBoxEntityItem.cpp @@ -16,6 +16,7 @@ #include "InterfaceConfig.h" #include +#include #include #include @@ -53,7 +54,7 @@ void RenderableBoxEntityItem::render(RenderArgs* args) { glm::vec3 positionToCenter = center - position; glTranslatef(positionToCenter.x, positionToCenter.y, positionToCenter.z); glScalef(dimensions.x, dimensions.y, dimensions.z); - Application::getInstance()->getDeferredLightingEffect()->renderSolidCube(1.0f); + DependencyManager::get()->renderSolidCube(1.0f); glPopMatrix(); glPopMatrix(); } else { @@ -90,7 +91,7 @@ void RenderableBoxEntityItem::render(RenderArgs* args) { glColor4f(getColor()[RED_INDEX] / MAX_COLOR, getColor()[GREEN_INDEX] / MAX_COLOR, getColor()[BLUE_INDEX] / MAX_COLOR, getLocalRenderAlpha()); - Application::getInstance()->getDeferredLightingEffect()->bindSimpleProgram(); + DependencyManager::get()->bindSimpleProgram(); glPushMatrix(); glTranslatef(position.x, position.y, position.z); @@ -105,7 +106,7 @@ void RenderableBoxEntityItem::render(RenderArgs* args) { glPopMatrix(); glPopMatrix(); - Application::getInstance()->getDeferredLightingEffect()->releaseSimpleProgram(); + DependencyManager::get()->releaseSimpleProgram(); glDisableClientState(GL_VERTEX_ARRAY); // disable vertex arrays glDisableClientState(GL_NORMAL_ARRAY); diff --git a/interface/src/entities/RenderableLightEntityItem.cpp b/interface/src/entities/RenderableLightEntityItem.cpp index 77dbb5da0b..48996d5b4c 100644 --- a/interface/src/entities/RenderableLightEntityItem.cpp +++ b/interface/src/entities/RenderableLightEntityItem.cpp @@ -15,6 +15,7 @@ #include "InterfaceConfig.h" +#include #include #include @@ -65,30 +66,30 @@ void RenderableLightEntityItem::render(RenderArgs* args) { if (!disableLights) { if (_isSpotlight) { - Application::getInstance()->getDeferredLightingEffect()->addSpotLight(position, largestDiameter / 2.0f, + DependencyManager::get()->addSpotLight(position, largestDiameter / 2.0f, ambient, diffuse, specular, constantAttenuation, linearAttenuation, quadraticAttenuation, direction, exponent, cutoff); } else { - Application::getInstance()->getDeferredLightingEffect()->addPointLight(position, largestDiameter / 2.0f, + DependencyManager::get()->addPointLight(position, largestDiameter / 2.0f, ambient, diffuse, specular, constantAttenuation, linearAttenuation, quadraticAttenuation); } } - bool wantDebug = false; - if (wantDebug) { - glColor4f(diffuseR, diffuseG, diffuseB, 1.0f); - glPushMatrix(); - glTranslatef(position.x, position.y, position.z); - glm::vec3 axis = glm::axis(rotation); - glRotatef(glm::degrees(glm::angle(rotation)), axis.x, axis.y, axis.z); - glPushMatrix(); - glm::vec3 positionToCenter = center - position; - glTranslatef(positionToCenter.x, positionToCenter.y, positionToCenter.z); - glScalef(dimensions.x, dimensions.y, dimensions.z); - Application::getInstance()->getDeferredLightingEffect()->renderWireSphere(0.5f, 15, 15); - glPopMatrix(); +#ifdef WANT_DEBUG + glColor4f(diffuseR, diffuseG, diffuseB, 1.0f); + glPushMatrix(); + glTranslatef(position.x, position.y, position.z); + glm::vec3 axis = glm::axis(rotation); + glRotatef(glm::degrees(glm::angle(rotation)), axis.x, axis.y, axis.z); + glPushMatrix(); + glm::vec3 positionToCenter = center - position; + glTranslatef(positionToCenter.x, positionToCenter.y, positionToCenter.z); + + glScalef(dimensions.x, dimensions.y, dimensions.z); + DependencyManager::get()->renderWireSphere(0.5f, 15, 15); glPopMatrix(); - } + glPopMatrix(); +#endif }; bool RenderableLightEntityItem::findDetailedRayIntersection(const glm::vec3& origin, const glm::vec3& direction, diff --git a/interface/src/entities/RenderableModelEntityItem.cpp b/interface/src/entities/RenderableModelEntityItem.cpp index 080162dc16..13bc097f27 100644 --- a/interface/src/entities/RenderableModelEntityItem.cpp +++ b/interface/src/entities/RenderableModelEntityItem.cpp @@ -16,6 +16,7 @@ #include "InterfaceConfig.h" #include +#include #include #include @@ -191,7 +192,7 @@ void RenderableModelEntityItem::render(RenderArgs* args) { glColor3ub(getColor()[RED_INDEX],getColor()[GREEN_INDEX],getColor()[BLUE_INDEX]); glPushMatrix(); glTranslatef(position.x, position.y, position.z); - Application::getInstance()->getDeferredLightingEffect()->renderWireCube(size); + DependencyManager::get()->renderWireCube(size); glPopMatrix(); } } else { @@ -199,7 +200,7 @@ void RenderableModelEntityItem::render(RenderArgs* args) { glColor3ub(getColor()[RED_INDEX],getColor()[GREEN_INDEX],getColor()[BLUE_INDEX]); glPushMatrix(); glTranslatef(position.x, position.y, position.z); - Application::getInstance()->getDeferredLightingEffect()->renderWireCube(size); + DependencyManager::get()->renderWireCube(size); glPopMatrix(); } } @@ -208,7 +209,7 @@ void RenderableModelEntityItem::render(RenderArgs* args) { glColor3ub(getColor()[RED_INDEX],getColor()[GREEN_INDEX],getColor()[BLUE_INDEX]); glPushMatrix(); glTranslatef(position.x, position.y, position.z); - Application::getInstance()->getDeferredLightingEffect()->renderWireCube(size); + DependencyManager::get()->renderWireCube(size); glPopMatrix(); } } diff --git a/interface/src/entities/RenderableSphereEntityItem.cpp b/interface/src/entities/RenderableSphereEntityItem.cpp index d561670be8..db10edca73 100644 --- a/interface/src/entities/RenderableSphereEntityItem.cpp +++ b/interface/src/entities/RenderableSphereEntityItem.cpp @@ -15,6 +15,8 @@ #include "InterfaceConfig.h" +#include +#include #include #include @@ -23,7 +25,6 @@ #include "EntityTreeRenderer.h" #include "RenderableSphereEntityItem.h" - EntityItem* RenderableSphereEntityItem::factory(const EntityItemID& entityID, const EntityItemProperties& properties) { return new RenderableSphereEntityItem(entityID, properties); } @@ -51,7 +52,7 @@ void RenderableSphereEntityItem::render(RenderArgs* args) { glTranslatef(positionToCenter.x, positionToCenter.y, positionToCenter.z); glScalef(dimensions.x, dimensions.y, dimensions.z); - Application::getInstance()->getDeferredLightingEffect()->renderSolidSphere(0.5f, 15, 15); + DependencyManager::get()->renderSolidSphere(0.5f, 15, 15); glPopMatrix(); glPopMatrix(); }; diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index 877f43a563..15db8e4361 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -17,6 +17,7 @@ #include #include +#include #include #include #include @@ -493,7 +494,7 @@ bool Model::renderTriangleProxies() { glPushMatrix(); glTranslatef(center.x, center.y, center.z); glScalef(dimensions.x, dimensions.y, dimensions.z); - Application::getInstance()->getDeferredLightingEffect()->renderWireCube(1.0f); + DependencyManager::get()->renderWireCube(1.0f); glPopMatrix(); } diff --git a/interface/src/ui/overlays/Cube3DOverlay.cpp b/interface/src/ui/overlays/Cube3DOverlay.cpp index f518c309a1..c61d68f05d 100644 --- a/interface/src/ui/overlays/Cube3DOverlay.cpp +++ b/interface/src/ui/overlays/Cube3DOverlay.cpp @@ -13,6 +13,7 @@ #include +#include #include #include #include @@ -75,7 +76,7 @@ void Cube3DOverlay::render(RenderArgs* args) { glPushMatrix(); glColor4f(1.0f, 1.0f, 1.0f, alpha); glScalef(dimensions.x * _borderSize, dimensions.y * _borderSize, dimensions.z * _borderSize); - Application::getInstance()->getDeferredLightingEffect()->renderSolidCube(1.0f); + DependencyManager::get()->renderSolidCube(1.0f); glPopMatrix(); glDepthMask(GL_TRUE); } @@ -83,7 +84,7 @@ void Cube3DOverlay::render(RenderArgs* args) { glPushMatrix(); glColor4f(color.red / MAX_COLOR, color.green / MAX_COLOR, color.blue / MAX_COLOR, alpha); glScalef(dimensions.x, dimensions.y, dimensions.z); - Application::getInstance()->getDeferredLightingEffect()->renderSolidCube(1.0f); + DependencyManager::get()->renderSolidCube(1.0f); glPopMatrix(); } else { glLineWidth(_lineWidth); @@ -117,7 +118,7 @@ void Cube3DOverlay::render(RenderArgs* args) { } else { glScalef(dimensions.x, dimensions.y, dimensions.z); - Application::getInstance()->getDeferredLightingEffect()->renderWireCube(1.0f); + DependencyManager::get()->renderWireCube(1.0f); } } glPopMatrix(); diff --git a/interface/src/ui/overlays/Sphere3DOverlay.cpp b/interface/src/ui/overlays/Sphere3DOverlay.cpp index eb95672399..522902194f 100644 --- a/interface/src/ui/overlays/Sphere3DOverlay.cpp +++ b/interface/src/ui/overlays/Sphere3DOverlay.cpp @@ -62,7 +62,6 @@ void Sphere3DOverlay::render(RenderArgs* args) { glm::vec3 positionToCenter = center - position; glTranslatef(positionToCenter.x, positionToCenter.y, positionToCenter.z); glScalef(dimensions.x, dimensions.y, dimensions.z); - //Application::getInstance()->getDeferredLightingEffect()->renderSolidCube(1.0f); if (_isSolid) { DependencyManager::get()->renderSphere(1.0f, SLICES, SLICES); } else { diff --git a/interface/src/renderer/AmbientOcclusionEffect.cpp b/libraries/render-utils/src/AmbientOcclusionEffect.cpp similarity index 98% rename from interface/src/renderer/AmbientOcclusionEffect.cpp rename to libraries/render-utils/src/AmbientOcclusionEffect.cpp index 4362d21645..b9289204c7 100644 --- a/interface/src/renderer/AmbientOcclusionEffect.cpp +++ b/libraries/render-utils/src/AmbientOcclusionEffect.cpp @@ -10,20 +10,20 @@ // // include this before QOpenGLFramebufferObject, which includes an earlier version of OpenGL -#include "InterfaceConfig.h" +#include #include #include -#include #include -#include -#include #include -#include #include "AmbientOcclusionEffect.h" +#include "GlowEffect.h" +#include "ProgramObject.h" +#include "RenderUtil.h" +#include "TextureCache.h" const int ROTATION_WIDTH = 4; const int ROTATION_HEIGHT = 4; diff --git a/interface/src/renderer/AmbientOcclusionEffect.h b/libraries/render-utils/src/AmbientOcclusionEffect.h similarity index 81% rename from interface/src/renderer/AmbientOcclusionEffect.h rename to libraries/render-utils/src/AmbientOcclusionEffect.h index 444b76a3c9..1ee7269480 100644 --- a/interface/src/renderer/AmbientOcclusionEffect.h +++ b/libraries/render-utils/src/AmbientOcclusionEffect.h @@ -12,19 +12,24 @@ #ifndef hifi_AmbientOcclusionEffect_h #define hifi_AmbientOcclusionEffect_h -#include +#include + +#include "ViewStateInterface.h" class ProgramObject; /// A screen space ambient occlusion effect. See John Chapman's tutorial at /// http://john-chapman-graphics.blogspot.co.uk/2013/01/ssao-tutorial.html for reference. -class AmbientOcclusionEffect { +class AmbientOcclusionEffect: public DependencyManager::Dependency { public: void init(ViewStateInterface* viewState); void render(); private: + AmbientOcclusionEffect() {} + virtual ~AmbientOcclusionEffect() {} + friend class DependencyManager; ProgramObject* _occlusionProgram; int _nearLocation; diff --git a/interface/src/renderer/DeferredLightingEffect.cpp b/libraries/render-utils/src/DeferredLightingEffect.cpp similarity index 98% rename from interface/src/renderer/DeferredLightingEffect.cpp rename to libraries/render-utils/src/DeferredLightingEffect.cpp index d3145b9d5d..ff2df95746 100644 --- a/interface/src/renderer/DeferredLightingEffect.cpp +++ b/libraries/render-utils/src/DeferredLightingEffect.cpp @@ -10,18 +10,28 @@ // // include this before QOpenGLFramebufferObject, which includes an earlier version of OpenGL -#include "InterfaceConfig.h" +#include + + +// TODO: remove these once we migrate away from GLUT calls +#if defined(__APPLE__) +#include +#else +#include +#endif #include -#include #include -#include #include -#include -#include + #include "DeferredLightingEffect.h" +#include "GeometryCache.h" +#include "GlowEffect.h" +#include "RenderUtil.h" +#include "TextureCache.h" + void DeferredLightingEffect::init(ViewStateInterface* viewState) { _viewState = viewState; diff --git a/interface/src/renderer/DeferredLightingEffect.h b/libraries/render-utils/src/DeferredLightingEffect.h similarity index 94% rename from interface/src/renderer/DeferredLightingEffect.h rename to libraries/render-utils/src/DeferredLightingEffect.h index 40182e0917..5dcd7d35f4 100644 --- a/interface/src/renderer/DeferredLightingEffect.h +++ b/libraries/render-utils/src/DeferredLightingEffect.h @@ -14,14 +14,16 @@ #include -#include +#include #include -#include + +#include "ProgramObject.h" +#include "ViewStateInterface.h" class PostLightingRenderable; /// Handles deferred lighting for the bits that require it (voxels, metavoxels...) -class DeferredLightingEffect { +class DeferredLightingEffect: public DependencyManager::Dependency { public: void init(ViewStateInterface* viewState); @@ -69,6 +71,9 @@ public: void render(); private: + DeferredLightingEffect() { } + virtual ~DeferredLightingEffect() { } + friend class DependencyManager; class LightLocations { public: From a9b3fdd3ebb6360a589e69f312bf73f807d1904a Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 16 Dec 2014 11:44:15 -0800 Subject: [PATCH 138/258] try this --- libraries/render-utils/src/DeferredLightingEffect.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/libraries/render-utils/src/DeferredLightingEffect.cpp b/libraries/render-utils/src/DeferredLightingEffect.cpp index ff2df95746..f3bc0f9a22 100644 --- a/libraries/render-utils/src/DeferredLightingEffect.cpp +++ b/libraries/render-utils/src/DeferredLightingEffect.cpp @@ -16,6 +16,11 @@ // TODO: remove these once we migrate away from GLUT calls #if defined(__APPLE__) #include +#elif defined(WIN32) +#include +#include +#include +#include #else #include #endif From ec5c33feccf48c1071dbfef9027653ff86ab05cd Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 16 Dec 2014 11:57:06 -0800 Subject: [PATCH 139/258] try this --- libraries/render-utils/src/DeferredLightingEffect.cpp | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/libraries/render-utils/src/DeferredLightingEffect.cpp b/libraries/render-utils/src/DeferredLightingEffect.cpp index f3bc0f9a22..a93f9fc89f 100644 --- a/libraries/render-utils/src/DeferredLightingEffect.cpp +++ b/libraries/render-utils/src/DeferredLightingEffect.cpp @@ -17,10 +17,7 @@ #if defined(__APPLE__) #include #elif defined(WIN32) -#include -#include -#include -#include + // nothing? #else #include #endif From ee34dfffc11ac48e7462af14f8876335c014a82b Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 16 Dec 2014 12:05:23 -0800 Subject: [PATCH 140/258] try this --- libraries/render-utils/CMakeLists.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/libraries/render-utils/CMakeLists.txt b/libraries/render-utils/CMakeLists.txt index eb96e7c5ec..1a23f4c4f0 100644 --- a/libraries/render-utils/CMakeLists.txt +++ b/libraries/render-utils/CMakeLists.txt @@ -26,6 +26,7 @@ else (APPLE) # we're using static GLEW, so define GLEW_STATIC add_definitions(-DGLEW_STATIC) + target_link_libraries(${TARGET_NAME} "${GLEW_LIBRARIES}") endif() endif (APPLE) From 1ed2c62bbf7df6c9f5b5238138e2620e5f312ff5 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 16 Dec 2014 12:15:57 -0800 Subject: [PATCH 141/258] try this --- libraries/render-utils/CMakeLists.txt | 3 +++ libraries/render-utils/src/DeferredLightingEffect.cpp | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/libraries/render-utils/CMakeLists.txt b/libraries/render-utils/CMakeLists.txt index 1a23f4c4f0..0244fa91a6 100644 --- a/libraries/render-utils/CMakeLists.txt +++ b/libraries/render-utils/CMakeLists.txt @@ -24,6 +24,9 @@ else (APPLE) find_package(GLEW REQUIRED) include_directories(${GLEW_INCLUDE_DIRS}) + find_package(GLUT REQUIRED) + include_directories(SYSTEM "${GLUT_INCLUDE_DIRS}") + # we're using static GLEW, so define GLEW_STATIC add_definitions(-DGLEW_STATIC) target_link_libraries(${TARGET_NAME} "${GLEW_LIBRARIES}") diff --git a/libraries/render-utils/src/DeferredLightingEffect.cpp b/libraries/render-utils/src/DeferredLightingEffect.cpp index a93f9fc89f..9f54b25441 100644 --- a/libraries/render-utils/src/DeferredLightingEffect.cpp +++ b/libraries/render-utils/src/DeferredLightingEffect.cpp @@ -17,7 +17,7 @@ #if defined(__APPLE__) #include #elif defined(WIN32) - // nothing? +#include #else #include #endif From 58183515e6b33353f5125df90c8e9f83175c7938 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 16 Dec 2014 12:23:54 -0800 Subject: [PATCH 142/258] more windows shenanigans --- interface/src/renderer/Model.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index 15db8e4361..56d7d30def 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -9,6 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +#include + #include #include #include From 16c1e597f15f90cd15a837e85207c4944cfd06b6 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 16 Dec 2014 12:53:22 -0800 Subject: [PATCH 143/258] remove Application dependency from Model --- interface/src/Application.cpp | 2 ++ interface/src/Application.h | 5 +++-- interface/src/renderer/Model.cpp | 19 +++++++++++-------- interface/src/renderer/Model.h | 6 ++++++ .../render-utils/src/ViewStateInterface.h | 7 +++++++ 5 files changed, 29 insertions(+), 10 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index c9309616ae..02dae8e08e 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -429,6 +429,8 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) : #endif this->installEventFilter(this); + + Model::setViewStateInterface(this); // The model class will sometimes need to know view state details from us } void Application::aboutToQuit() { diff --git a/interface/src/Application.h b/interface/src/Application.h index 6b5bcc0770..dea7c80940 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -232,7 +232,7 @@ public: const glm::vec3& getViewMatrixTranslation() const { return _viewMatrixTranslation; } void setViewMatrixTranslation(const glm::vec3& translation) { _viewMatrixTranslation = translation; } - const Transform& getViewTransform() const { return _viewTransform; } + virtual const Transform& getViewTransform() const { return _viewTransform; } void setViewTransform(const Transform& view); /// if you need to access the application settings, use lockSettings()/unlockSettings() @@ -255,7 +255,7 @@ public: void controlledBroadcastToNodes(const QByteArray& packet, const NodeSet& destinationNodeTypes); - void setupWorldLight(); + virtual void setupWorldLight(); QImage renderAvatarBillboard(); @@ -283,6 +283,7 @@ public: virtual ViewFrustum* getCurrentViewFrustum() { return getDisplayViewFrustum(); } virtual bool getShadowsEnabled(); virtual bool getCascadeShadowsEnabled(); + virtual QThread* getMainThread() { return thread(); } NodeBounds& getNodeBoundsDisplay() { return _nodeBoundsDisplay; } diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index 56d7d30def..7fe024b8fe 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -22,6 +22,8 @@ #include #include #include +#include +#include #include #include #include @@ -29,11 +31,10 @@ #include #include "AnimationHandle.h" -#include "Application.h" +#include "Menu.h" #include "Model.h" -#include "gpu/Batch.h" -#include "gpu/GLBackend.h" + #define GLBATCH( call ) batch._##call //#define GLBATCH( call ) call @@ -63,7 +64,7 @@ Model::Model(QObject* parent) : _meshGroupsKnown(false) { // we may have been created in the network thread, but we live in the main thread - moveToThread(Application::getInstance()->thread()); + moveToThread(_viewState->getMainThread()); } Model::~Model() { @@ -109,6 +110,8 @@ Model::SkinLocations Model::_skinNormalSpecularMapLocations; Model::SkinLocations Model::_skinShadowLocations; Model::SkinLocations Model::_skinTranslucentLocations; +ViewStateInterface* Model::_viewState = NULL; + void Model::setScale(const glm::vec3& scale) { setScaleInternal(scale); // if anyone sets scale manually, then we are no longer scaled to fit @@ -727,7 +730,7 @@ bool Model::renderCore(float alpha, RenderMode mode, RenderArgs* args) { if (_transforms.empty()) { _transforms.push_back(Transform()); } - _transforms[0] = Application::getInstance()->getViewTransform(); + _transforms[0] = _viewState->getViewTransform(); // apply entity translation offset to the viewTransform in one go (it's a preTranslate because viewTransform goes from world to eye space) _transforms[0].preTranslate(-_translation); @@ -870,7 +873,7 @@ bool Model::renderCore(float alpha, RenderMode mode, RenderArgs* args) { } // restore all the default material settings - Application::getInstance()->setupWorldLight(); + _viewState->setupWorldLight(); if (args) { args->_translucentMeshPartsRendered = translucentMeshPartsRendered; @@ -1670,7 +1673,7 @@ void Model::setupBatchTransform(gpu::Batch& batch) { if (_transforms.empty()) { _transforms.push_back(Transform()); } - _transforms[0] = Application::getInstance()->getViewTransform(); + _transforms[0] = _viewState->getViewTransform(); _transforms[0].preTranslate(-_translation); batch.setViewTransform(_transforms[0]); } @@ -1830,7 +1833,7 @@ void Model::endScene(RenderMode mode, RenderArgs* args) { } // restore all the default material settings - Application::getInstance()->setupWorldLight(); + _viewState->setupWorldLight(); } diff --git a/interface/src/renderer/Model.h b/interface/src/renderer/Model.h index 8000e7385b..2c6b0bd6ae 100644 --- a/interface/src/renderer/Model.h +++ b/interface/src/renderer/Model.h @@ -28,6 +28,7 @@ #include #include #include +#include #include "AnimationHandle.h" @@ -46,6 +47,8 @@ class Model : public QObject, public PhysicsEntity { public: + static void setViewStateInterface(ViewStateInterface* viewState) { _viewState = viewState; } + Model(QObject* parent = NULL); virtual ~Model(); @@ -455,6 +458,9 @@ private: static int renderMeshesForModelsInScene(gpu::Batch& batch, RenderMode mode, bool translucent, float alphaThreshold, bool hasLightmap, bool hasTangents, bool hasSpecular, bool isSkinned, RenderArgs* args); + + static ViewStateInterface* _viewState; + }; Q_DECLARE_METATYPE(QPointer) diff --git a/libraries/render-utils/src/ViewStateInterface.h b/libraries/render-utils/src/ViewStateInterface.h index decccdc401..83501589d0 100644 --- a/libraries/render-utils/src/ViewStateInterface.h +++ b/libraries/render-utils/src/ViewStateInterface.h @@ -14,6 +14,9 @@ #include +class Transform; +class QThread; + /// Interface provided by Application to other objects that need access to the current view state details class ViewStateInterface { public: @@ -30,6 +33,10 @@ public: virtual bool getShadowsEnabled() = 0; virtual bool getCascadeShadowsEnabled() = 0; + + virtual QThread* getMainThread() = 0; + virtual const Transform& getViewTransform() const = 0; + virtual void setupWorldLight() = 0; }; From efa8a752f20fb9092df8279f4adbeabeb210f846 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 16 Dec 2014 13:14:57 -0800 Subject: [PATCH 144/258] remove dependency on Menu from Model --- interface/src/Application.cpp | 8 ++++++-- interface/src/Application.h | 1 + interface/src/renderer/Model.cpp | 16 ++++++++++------ libraries/render-utils/src/ViewStateInterface.h | 1 + 4 files changed, 18 insertions(+), 8 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 02dae8e08e..8b3c5a2fa1 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -191,6 +191,8 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) : _isVSyncOn(true), _aboutToQuit(false) { + Model::setViewStateInterface(this); // The model class will sometimes need to know view state details from us + // read the ApplicationInfo.ini file for Name/Version/Domain information QSettings applicationInfo(PathUtils::resourcesPath() + "info/ApplicationInfo.ini", QSettings::IniFormat); @@ -429,8 +431,6 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) : #endif this->installEventFilter(this); - - Model::setViewStateInterface(this); // The model class will sometimes need to know view state details from us } void Application::aboutToQuit() { @@ -2939,6 +2939,10 @@ void Application::setupWorldLight() { glMateriali(GL_FRONT, GL_SHININESS, 96); } +bool Application::shouldRenderMesh(float largestDimension, float distanceToCamera) { + return Menu::getInstance()->shouldRenderMesh(largestDimension, distanceToCamera); +} + QImage Application::renderAvatarBillboard() { DependencyManager::get()->getPrimaryFramebufferObject()->bind(); diff --git a/interface/src/Application.h b/interface/src/Application.h index dea7c80940..9aca90fac8 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -256,6 +256,7 @@ public: void controlledBroadcastToNodes(const QByteArray& packet, const NodeSet& destinationNodeTypes); virtual void setupWorldLight(); + virtual bool shouldRenderMesh(float largestDimension, float distanceToCamera); QImage renderAvatarBillboard(); diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index 7fe024b8fe..2faeeeea55 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -31,7 +31,6 @@ #include #include "AnimationHandle.h" -#include "Menu.h" #include "Model.h" @@ -64,7 +63,9 @@ Model::Model(QObject* parent) : _meshGroupsKnown(false) { // we may have been created in the network thread, but we live in the main thread - moveToThread(_viewState->getMainThread()); + if (_viewState) { + moveToThread(_viewState->getMainThread()); + } } Model::~Model() { @@ -720,6 +721,9 @@ bool Model::render(float alpha, RenderMode mode, RenderArgs* args) { bool Model::renderCore(float alpha, RenderMode mode, RenderArgs* args) { PROFILE_RANGE(__FUNCTION__); + if (!_viewState) { + return false; + } // Let's introduce a gpu::Batch to capture all the calls to the graphics api _renderBatch.clear(); @@ -2329,9 +2333,9 @@ int Model::renderMeshes(gpu::Batch& batch, RenderMode mode, bool translucent, fl int Model::renderMeshesFromList(QVector& list, gpu::Batch& batch, RenderMode mode, bool translucent, float alphaThreshold, RenderArgs* args, Locations* locations, SkinLocations* skinLocations) { PROFILE_RANGE(__FUNCTION__); - bool dontCullOutOfViewMeshParts = Menu::getInstance()->isOptionChecked(MenuOption::DontCullOutOfViewMeshParts); - bool cullTooSmallMeshParts = !Menu::getInstance()->isOptionChecked(MenuOption::DontCullTooSmallMeshParts); - bool dontReduceMaterialSwitches = Menu::getInstance()->isOptionChecked(MenuOption::DontReduceMaterialSwitches); + bool dontCullOutOfViewMeshParts = false; // Menu::getInstance()->isOptionChecked(MenuOption::DontCullOutOfViewMeshParts); + bool cullTooSmallMeshParts = true; // !Menu::getInstance()->isOptionChecked(MenuOption::DontCullTooSmallMeshParts); + bool dontReduceMaterialSwitches = false; // Menu::getInstance()->isOptionChecked(MenuOption::DontReduceMaterialSwitches); TextureCache* textureCache = DependencyManager::get(); GlowEffect* glowEffect = DependencyManager::get(); @@ -2373,7 +2377,7 @@ int Model::renderMeshesFromList(QVector& list, gpu::Batch& batch, RenderMod args->_viewFrustum->boxInFrustum(_calculatedMeshBoxes.at(i)) != ViewFrustum::OUTSIDE; if (shouldRender && cullTooSmallMeshParts) { float distance = args->_viewFrustum->distanceToCamera(_calculatedMeshBoxes.at(i).calcCenter()); - shouldRender = Menu::getInstance()->shouldRenderMesh(_calculatedMeshBoxes.at(i).getLargestDimension(), + shouldRender = !_viewState ? false : _viewState->shouldRenderMesh(_calculatedMeshBoxes.at(i).getLargestDimension(), distance); if (!shouldRender) { args->_meshesTooSmall++; diff --git a/libraries/render-utils/src/ViewStateInterface.h b/libraries/render-utils/src/ViewStateInterface.h index 83501589d0..9110eb8eb6 100644 --- a/libraries/render-utils/src/ViewStateInterface.h +++ b/libraries/render-utils/src/ViewStateInterface.h @@ -37,6 +37,7 @@ public: virtual QThread* getMainThread() = 0; virtual const Transform& getViewTransform() const = 0; virtual void setupWorldLight() = 0; + virtual bool shouldRenderMesh(float largestDimension, float distanceToCamera) = 0; }; From cf6aa563ac30635a11444e69215256446ecf8b6d Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Tue, 16 Dec 2014 13:54:24 -0800 Subject: [PATCH 145/258] DM returns shared pointer --- libraries/shared/src/DependencyManager.cpp | 4 -- libraries/shared/src/DependencyManager.h | 51 ++++++++++------------ 2 files changed, 22 insertions(+), 33 deletions(-) diff --git a/libraries/shared/src/DependencyManager.cpp b/libraries/shared/src/DependencyManager.cpp index c858cb7059..43bb92258e 100644 --- a/libraries/shared/src/DependencyManager.cpp +++ b/libraries/shared/src/DependencyManager.cpp @@ -17,8 +17,4 @@ DependencyManager& DependencyManager::getInstance() { } DependencyManager::~DependencyManager() { - foreach (Dependency* instance, _instanceHash) { - delete instance; - } - _instanceHash.clear(); } \ No newline at end of file diff --git a/libraries/shared/src/DependencyManager.h b/libraries/shared/src/DependencyManager.h index 87c7c7b4a6..455ec38bca 100644 --- a/libraries/shared/src/DependencyManager.h +++ b/libraries/shared/src/DependencyManager.h @@ -12,55 +12,48 @@ #ifndef hifi_DependencyManager_h #define hifi_DependencyManager_h -#include -#include +#include #include -#include + +#define SINGLETON_DEPENDENCY(T)\ +public:\ + typedef QSharedPointer SharedPointer;\ +private:\ + void customDeleter() { delete this; }\ + friend class DependencyManager; + +class QObject; class DependencyManager { public: // Only accessible method. // usage: T* instance = DependencyManager::get(); template - static T* get(); - - // Any class T in the DependencyManager needs to subclass Dependency - // They also need to have protected constructor(s) and virtual destructor - // As well as declare DependencyManager a friend class - class Dependency { - protected: - Dependency() {} - virtual ~Dependency() {} // Ensure the proper destruction of the object - friend DependencyManager; - }; + static QSharedPointer get(); private: static DependencyManager& getInstance(); DependencyManager() {} ~DependencyManager(); - typedef QHash InstanceHash; - static InstanceHash& getInstanceHash() { return getInstance()._instanceHash; } - InstanceHash _instanceHash; + static void noDelete(void*) {} }; template -T* DependencyManager::get() { - const QString& typeId = typeid(T).name(); +QSharedPointer DependencyManager::get() { + static QSharedPointer sharedPointer; + static T* instance = new T(); - // Search the hash for global instance - Dependency* instance = getInstanceHash().value(typeId, NULL); if (instance) { - return dynamic_cast(instance); + if (dynamic_cast(instance)) { // If this is a QOject, call deleteLater for destruction + sharedPointer = QSharedPointer(instance, &T::deleteLater); + } else { // Otherwise use custom deleter to avoid issues between private destructor and QSharedPointer + sharedPointer = QSharedPointer(instance, &T::customDeleter); + } + instance = NULL; } - - // Found no instance in hash so we create one. - T* newInstance = new T(); - instance = dynamic_cast(newInstance); - assert(instance != NULL); // If this triggers, check that T is derived from Dependency - getInstanceHash().insert(typeId, instance); - return newInstance; + return sharedPointer; } #endif // hifi_DependencyManager_h From e8a22f6f0f31d3f2adcc08751492b160490d47ae Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Tue, 16 Dec 2014 13:54:52 -0800 Subject: [PATCH 146/258] Switched to chared pointers and macros --- interface/src/Application.cpp | 3 +-- interface/src/GLCanvas.h | 9 ++++++--- interface/src/devices/DdeFaceTracker.h | 2 +- interface/src/devices/Faceshift.h | 2 +- interface/src/devices/Visage.h | 2 +- 5 files changed, 10 insertions(+), 8 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 4c9fdcaf0f..50275fcd1c 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -194,7 +194,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) : _isVSyncOn(true), _aboutToQuit(false) { - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); // read the ApplicationInfo.ini file for Name/Version/Domain information QSettings applicationInfo(Application::resourcesPath() + "info/ApplicationInfo.ini", QSettings::IniFormat); @@ -442,7 +442,6 @@ void Application::aboutToQuit() { } Application::~Application() { - DependencyManager::get()->setParent(NULL); _entities.getTree()->setSimulation(NULL); qInstallMessageHandler(NULL); diff --git a/interface/src/GLCanvas.h b/interface/src/GLCanvas.h index 2b1cd3539d..420bf77467 100644 --- a/interface/src/GLCanvas.h +++ b/interface/src/GLCanvas.h @@ -18,8 +18,10 @@ #include /// customized canvas that simply forwards requests/events to the singleton application -class GLCanvas : public QGLWidget, public DependencyManager::Dependency { +class GLCanvas : public QGLWidget { Q_OBJECT + SINGLETON_DEPENDENCY(GLCanvas) + public: bool isThrottleRendering() const; @@ -60,8 +62,9 @@ private slots: private: GLCanvas(); - ~GLCanvas(); - friend class DependencyManager; + ~GLCanvas() { + qDebug() << "Deleting GLCanvas"; + } }; #endif // hifi_GLCanvas_h diff --git a/interface/src/devices/DdeFaceTracker.h b/interface/src/devices/DdeFaceTracker.h index 5ae17729d4..23a5d1fcc8 100644 --- a/interface/src/devices/DdeFaceTracker.h +++ b/interface/src/devices/DdeFaceTracker.h @@ -20,7 +20,7 @@ class DdeFaceTracker : public FaceTracker { Q_OBJECT - SINGLETON_DEPENDENCY + SINGLETON_DEPENDENCY(DdeFaceTracker) public: //initialization diff --git a/interface/src/devices/Faceshift.h b/interface/src/devices/Faceshift.h index 73971db49d..b6b942dfee 100644 --- a/interface/src/devices/Faceshift.h +++ b/interface/src/devices/Faceshift.h @@ -26,7 +26,7 @@ /// Handles interaction with the Faceshift software, which provides head position/orientation and facial features. class Faceshift : public FaceTracker { Q_OBJECT - SINGLETON_DEPENDENCY + SINGLETON_DEPENDENCY(Faceshift) public: void init(); diff --git a/interface/src/devices/Visage.h b/interface/src/devices/Visage.h index 38e337aada..c12ce3aabd 100644 --- a/interface/src/devices/Visage.h +++ b/interface/src/devices/Visage.h @@ -28,7 +28,7 @@ namespace VisageSDK { /// Handles input from the Visage webcam feature tracking software. class Visage : public FaceTracker { Q_OBJECT - SINGLETON_DEPENDENCY + SINGLETON_DEPENDENCY(Visage) public: void init(); From 85c89517349790edd7510c00457bb21fb97d82fd Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 16 Dec 2014 13:57:22 -0800 Subject: [PATCH 147/258] really remove the debug settings from Model rendering --- examples/developerMenuItems.js | 4 ---- interface/src/Menu.h | 3 --- interface/src/renderer/Model.cpp | 10 +++------- 3 files changed, 3 insertions(+), 14 deletions(-) diff --git a/examples/developerMenuItems.js b/examples/developerMenuItems.js index 34bd3b3a75..3a274c7083 100644 --- a/examples/developerMenuItems.js +++ b/examples/developerMenuItems.js @@ -23,12 +23,8 @@ function setupMenus() { Menu.addMenuItem({ menuName: "Developer > Entities", menuItemName: "Display Model Element Bounds", isCheckable: true, isChecked: false }); Menu.addMenuItem({ menuName: "Developer > Entities", menuItemName: "Display Model Element Children", isCheckable: true, isChecked: false }); Menu.addMenuItem({ menuName: "Developer > Entities", menuItemName: "Don't Do Precision Picking", isCheckable: true, isChecked: false }); - Menu.addMenuItem({ menuName: "Developer > Entities", menuItemName: "Don't Attempt to Reduce Material Switches", isCheckable: true, isChecked: false }); Menu.addMenuItem({ menuName: "Developer > Entities", menuItemName: "Don't Attempt Render Entities as Scene", isCheckable: true, isChecked: false }); Menu.addMenuItem({ menuName: "Developer > Entities", menuItemName: "Don't Do Precision Picking", isCheckable: true, isChecked: false }); - Menu.addMenu("Developer > Entities > Culling"); - Menu.addMenuItem({ menuName: "Developer > Entities > Culling", menuItemName: "Don't Cull Out Of View Mesh Parts", isCheckable: true, isChecked: false }); - Menu.addMenuItem({ menuName: "Developer > Entities > Culling", menuItemName: "Don't Cull Too Small Mesh Parts", isCheckable: true, isChecked: false }); Menu.addMenuItem({ menuName: "Developer > Entities", menuItemName: "Disable Light Entities", isCheckable: true, isChecked: false }); } } diff --git a/interface/src/Menu.h b/interface/src/Menu.h index e2c687fff1..77936e7ac4 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -361,9 +361,6 @@ namespace MenuOption { const QString Collisions = "Collisions"; const QString Console = "Console..."; const QString ControlWithSpeech = "Control With Speech"; - const QString DontCullOutOfViewMeshParts = "Don't Cull Out Of View Mesh Parts"; - const QString DontCullTooSmallMeshParts = "Don't Cull Too Small Mesh Parts"; - const QString DontReduceMaterialSwitches = "Don't Attempt to Reduce Material Switches"; const QString DontRenderEntitiesAsScene = "Don't Render Entities as Scene"; const QString DontDoPrecisionPicking = "Don't Do Precision Picking"; const QString DecreaseAvatarSize = "Decrease Avatar Size"; diff --git a/interface/src/renderer/Model.cpp b/interface/src/renderer/Model.cpp index 2faeeeea55..5f160d2e8d 100644 --- a/interface/src/renderer/Model.cpp +++ b/interface/src/renderer/Model.cpp @@ -2333,9 +2333,6 @@ int Model::renderMeshes(gpu::Batch& batch, RenderMode mode, bool translucent, fl int Model::renderMeshesFromList(QVector& list, gpu::Batch& batch, RenderMode mode, bool translucent, float alphaThreshold, RenderArgs* args, Locations* locations, SkinLocations* skinLocations) { PROFILE_RANGE(__FUNCTION__); - bool dontCullOutOfViewMeshParts = false; // Menu::getInstance()->isOptionChecked(MenuOption::DontCullOutOfViewMeshParts); - bool cullTooSmallMeshParts = true; // !Menu::getInstance()->isOptionChecked(MenuOption::DontCullTooSmallMeshParts); - bool dontReduceMaterialSwitches = false; // Menu::getInstance()->isOptionChecked(MenuOption::DontReduceMaterialSwitches); TextureCache* textureCache = DependencyManager::get(); GlowEffect* glowEffect = DependencyManager::get(); @@ -2373,9 +2370,8 @@ int Model::renderMeshesFromList(QVector& list, gpu::Batch& batch, RenderMod args->_meshesConsidered++; if (args->_viewFrustum) { - shouldRender = dontCullOutOfViewMeshParts || - args->_viewFrustum->boxInFrustum(_calculatedMeshBoxes.at(i)) != ViewFrustum::OUTSIDE; - if (shouldRender && cullTooSmallMeshParts) { + shouldRender = args->_viewFrustum->boxInFrustum(_calculatedMeshBoxes.at(i)) != ViewFrustum::OUTSIDE; + if (shouldRender) { float distance = args->_viewFrustum->distanceToCamera(_calculatedMeshBoxes.at(i).calcCenter()); shouldRender = !_viewState ? false : _viewState->shouldRenderMesh(_calculatedMeshBoxes.at(i).getLargestDimension(), distance); @@ -2433,7 +2429,7 @@ int Model::renderMeshesFromList(QVector& list, gpu::Batch& batch, RenderMod GLBATCH(glBindTexture)(GL_TEXTURE_2D, 0); } else { - if (dontReduceMaterialSwitches || lastMaterialID != part.materialID) { + if (lastMaterialID != part.materialID) { const bool wantDebug = false; if (wantDebug) { qDebug() << "Material Changed ---------------------------------------------"; From 4d1529f77bc875a87c10b2006e449425a98bbdb7 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Tue, 16 Dec 2014 14:02:22 -0800 Subject: [PATCH 148/258] typedefs --- interface/src/Application.cpp | 26 +++++++++---------- interface/src/Camera.cpp | 2 +- interface/src/Menu.cpp | 2 +- interface/src/avatar/Head.cpp | 4 +-- interface/src/avatar/MyAvatar.cpp | 2 +- interface/src/devices/OculusManager.cpp | 4 +-- interface/src/devices/PrioVR.cpp | 2 +- interface/src/devices/SixenseManager.cpp | 2 +- interface/src/devices/TV3DManager.cpp | 4 +-- interface/src/renderer/GlowEffect.cpp | 2 +- .../ControllerScriptingInterface.cpp | 2 +- interface/src/ui/ApplicationOverlay.cpp | 20 +++++++------- interface/src/ui/PreferencesDialog.cpp | 2 +- interface/src/ui/Snapshot.cpp | 2 +- interface/src/ui/Stats.cpp | 8 +++--- 15 files changed, 42 insertions(+), 42 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 50275fcd1c..5746f1f670 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -1047,7 +1047,7 @@ void Application::keyPressEvent(QKeyEvent* event) { if (isShifted) { _viewFrustum.setFocalLength(_viewFrustum.getFocalLength() - 0.1f); if (TV3DManager::isConnected()) { - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); TV3DManager::configureCamera(_myCamera, glCanvas->getDeviceWidth(), glCanvas->getDeviceHeight()); } } else { @@ -1060,7 +1060,7 @@ void Application::keyPressEvent(QKeyEvent* event) { if (isShifted) { _viewFrustum.setFocalLength(_viewFrustum.getFocalLength() + 0.1f); if (TV3DManager::isConnected()) { - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); TV3DManager::configureCamera(_myCamera, glCanvas->getDeviceWidth(), glCanvas->getDeviceHeight()); } @@ -1533,7 +1533,7 @@ void Application::idle() { void Application::checkBandwidthMeterClick() { // ... to be called upon button release - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); if (Menu::getInstance()->isOptionChecked(MenuOption::Bandwidth) && Menu::getInstance()->isOptionChecked(MenuOption::Stats) && Menu::getInstance()->isOptionChecked(MenuOption::UserInterface) && @@ -1569,7 +1569,7 @@ void Application::setFullscreen(bool fullscreen) { } void Application::setEnable3DTVMode(bool enable3DTVMode) { - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); resizeGL(glCanvas->getDeviceWidth(), glCanvas->getDeviceHeight()); } @@ -1595,7 +1595,7 @@ void Application::setEnableVRMode(bool enableVRMode) { _myCamera.setHmdRotation(glm::quat()); } - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); resizeGL(glCanvas->getDeviceWidth(), glCanvas->getDeviceHeight()); } @@ -1658,7 +1658,7 @@ glm::vec3 Application::getMouseVoxelWorldCoordinates(const VoxelDetail& mouseVox bool Application::mouseOnScreen() const { if (OculusManager::isConnected()) { - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); return getMouseX() >= 0 && getMouseX() <= glCanvas->getDeviceWidth() && getMouseY() >= 0 && getMouseY() <= glCanvas->getDeviceHeight(); } @@ -1700,9 +1700,9 @@ int Application::getMouseDragStartedY() const { } FaceTracker* Application::getActiveFaceTracker() { - QSharedPointer faceshift = DependencyManager::get(); - QSharedPointer visage = DependencyManager::get(); - QSharedPointer dde = DependencyManager::get(); + Faceshift::SharedPointer faceshift = DependencyManager::get(); + Visage::SharedPointer visage = DependencyManager::get(); + DdeFaceTracker::SharedPointer dde = DependencyManager::get(); return (dde->isActive() ? static_cast(dde.data()) : (faceshift->isActive() ? static_cast(faceshift.data()) : @@ -2035,7 +2035,7 @@ void Application::init() { _metavoxels.init(); - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); _audio.init(glCanvas.data()); _rearMirrorTools = new RearMirrorTools(glCanvas.data(), _mirrorViewRect, _settings); @@ -2116,7 +2116,7 @@ void Application::updateMouseRay() { void Application::updateFaceshift() { bool showWarnings = Menu::getInstance()->isOptionChecked(MenuOption::PipelineWarnings); PerformanceWarning warn(showWarnings, "Application::updateFaceshift()"); - Faceshift* faceshift = DependencyManager::get().data(); + Faceshift::SharedPointer faceshift = DependencyManager::get(); // Update faceshift faceshift->update(); @@ -2920,7 +2920,7 @@ void Application::updateShadowMap() { fbo->release(); - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); glViewport(0, 0, glCanvas->getDeviceWidth(), glCanvas->getDeviceHeight()); } @@ -3248,7 +3248,7 @@ void Application::computeOffAxisFrustum(float& left, float& right, float& bottom } glm::vec2 Application::getScaledScreenPoint(glm::vec2 projectedPoint) { - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); float horizontalScale = glCanvas->getDeviceWidth() / 2.0f; float verticalScale = glCanvas->getDeviceHeight() / 2.0f; diff --git a/interface/src/Camera.cpp b/interface/src/Camera.cpp index 181f783af1..b2fd30a1a6 100644 --- a/interface/src/Camera.cpp +++ b/interface/src/Camera.cpp @@ -95,7 +95,7 @@ void Camera::setFarClip(float f) { } PickRay Camera::computePickRay(float x, float y) { - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); return computeViewPickRay(x / glCanvas->width(), y / glCanvas->height()); } diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 501da725e4..91f4460410 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -1050,7 +1050,7 @@ void Menu::bumpSettings() { void sendFakeEnterEvent() { QPoint lastCursorPosition = QCursor::pos(); - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); QPoint windowPosition = glCanvas->mapFromGlobal(lastCursorPosition); QEnterEvent enterEvent = QEnterEvent(windowPosition, windowPosition, lastCursorPosition); diff --git a/interface/src/avatar/Head.cpp b/interface/src/avatar/Head.cpp index 150b67eb13..9a228899c5 100644 --- a/interface/src/avatar/Head.cpp +++ b/interface/src/avatar/Head.cpp @@ -77,8 +77,8 @@ void Head::simulate(float deltaTime, bool isMine, bool billboard) { // Only use face trackers when not playing back a recording. if (!myAvatar->isPlaying()) { FaceTracker* faceTracker = Application::getInstance()->getActiveFaceTracker(); - QSharedPointer dde = DependencyManager::get(); - QSharedPointer faceshift = DependencyManager::get(); + DdeFaceTracker::SharedPointer dde = DependencyManager::get(); + Faceshift::SharedPointer faceshift = DependencyManager::get(); if ((_isFaceshiftConnected = (faceshift == faceTracker))) { _blendshapeCoefficients = faceTracker->getBlendshapeCoefficients(); diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index a546560ffd..8e40cb8b30 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -422,7 +422,7 @@ void MyAvatar::render(const glm::vec3& cameraPosition, RenderMode renderMode, bo } void MyAvatar::renderHeadMouse(int screenWidth, int screenHeight) const { - QSharedPointer faceshift = DependencyManager::get(); + Faceshift::SharedPointer faceshift = DependencyManager::get(); float pixelsPerDegree = screenHeight / Menu::getInstance()->getFieldOfView(); diff --git a/interface/src/devices/OculusManager.cpp b/interface/src/devices/OculusManager.cpp index 99515cb7a9..15aa129b93 100644 --- a/interface/src/devices/OculusManager.cpp +++ b/interface/src/devices/OculusManager.cpp @@ -560,7 +560,7 @@ void OculusManager::display(const glm::quat &bodyOrientation, const glm::vec3 &p } // restore our normal viewport - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); glViewport(0, 0, glCanvas->getDeviceWidth(), glCanvas->getDeviceHeight()); glMatrixMode(GL_PROJECTION); @@ -579,7 +579,7 @@ void OculusManager::display(const glm::quat &bodyOrientation, const glm::vec3 &p void OculusManager::renderDistortionMesh(ovrPosef eyeRenderPose[ovrEye_Count]) { glLoadIdentity(); - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); gluOrtho2D(0, glCanvas->getDeviceWidth(), 0, glCanvas->getDeviceHeight()); glDisable(GL_DEPTH_TEST); diff --git a/interface/src/devices/PrioVR.cpp b/interface/src/devices/PrioVR.cpp index ab7c317c37..5ef94339ae 100644 --- a/interface/src/devices/PrioVR.cpp +++ b/interface/src/devices/PrioVR.cpp @@ -215,7 +215,7 @@ void PrioVR::renderCalibrationCountdown() { static TextRenderer* textRenderer = TextRenderer::getInstance(MONO_FONT_FAMILY, 18, QFont::Bold, false, TextRenderer::OUTLINE_EFFECT, 2); QByteArray text = "Assume T-Pose in " + QByteArray::number(secondsRemaining) + "..."; - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); textRenderer->draw((glCanvas->width() - textRenderer->computeWidth(text.constData())) / 2, glCanvas->height() / 2, text); diff --git a/interface/src/devices/SixenseManager.cpp b/interface/src/devices/SixenseManager.cpp index 73e4f53289..e2b4fedd50 100644 --- a/interface/src/devices/SixenseManager.cpp +++ b/interface/src/devices/SixenseManager.cpp @@ -461,7 +461,7 @@ void SixenseManager::updateCalibration(const sixenseControllerData* controllers) void SixenseManager::emulateMouse(PalmData* palm, int index) { Application* application = Application::getInstance(); MyAvatar* avatar = application->getAvatar(); - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); QPoint pos; Qt::MouseButton bumperButton; diff --git a/interface/src/devices/TV3DManager.cpp b/interface/src/devices/TV3DManager.cpp index 5c891224a8..e4723d26a0 100644 --- a/interface/src/devices/TV3DManager.cpp +++ b/interface/src/devices/TV3DManager.cpp @@ -33,7 +33,7 @@ bool TV3DManager::isConnected() { } void TV3DManager::connect() { - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); int width = glCanvas->getDeviceWidth(); int height = glCanvas->getDeviceHeight(); Camera& camera = *Application::getInstance()->getCamera(); @@ -91,7 +91,7 @@ void TV3DManager::display(Camera& whichCamera) { // left eye portal int portalX = 0; int portalY = 0; - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); QSize deviceSize = glCanvas->getDeviceSize() * Application::getInstance()->getRenderResolutionScale(); int portalW = deviceSize.width() / 2; diff --git a/interface/src/renderer/GlowEffect.cpp b/interface/src/renderer/GlowEffect.cpp index a760889eff..9f953eed60 100644 --- a/interface/src/renderer/GlowEffect.cpp +++ b/interface/src/renderer/GlowEffect.cpp @@ -139,7 +139,7 @@ QOpenGLFramebufferObject* GlowEffect::render(bool toTexture) { QOpenGLFramebufferObject* destFBO = toTexture ? Application::getInstance()->getTextureCache()->getSecondaryFramebufferObject() : NULL; - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); if (!Menu::getInstance()->isOptionChecked(MenuOption::EnableGlowEffect) || _isEmpty) { // copy the primary to the screen if (destFBO && QOpenGLFramebufferObject::hasOpenGLFramebufferBlit()) { diff --git a/interface/src/scripting/ControllerScriptingInterface.cpp b/interface/src/scripting/ControllerScriptingInterface.cpp index a562236a92..545de00d7d 100644 --- a/interface/src/scripting/ControllerScriptingInterface.cpp +++ b/interface/src/scripting/ControllerScriptingInterface.cpp @@ -268,7 +268,7 @@ void ControllerScriptingInterface::releaseJoystick(int joystickIndex) { } glm::vec2 ControllerScriptingInterface::getViewportDimensions() const { - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); return glm::vec2(glCanvas->width(), glCanvas->height()); } diff --git a/interface/src/ui/ApplicationOverlay.cpp b/interface/src/ui/ApplicationOverlay.cpp index c95dc08e79..f16777a28d 100644 --- a/interface/src/ui/ApplicationOverlay.cpp +++ b/interface/src/ui/ApplicationOverlay.cpp @@ -145,7 +145,7 @@ void ApplicationOverlay::renderOverlay(bool renderToTexture) { PerformanceWarning warn(Menu::getInstance()->isOptionChecked(MenuOption::PipelineWarnings), "ApplicationOverlay::displayOverlay()"); Application* application = Application::getInstance(); Overlays& overlays = application->getOverlays(); - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); MyAvatar* myAvatar = application->getAvatar(); _textureFov = glm::radians(Menu::getInstance()->getOculusUIAngularSize()); @@ -213,7 +213,7 @@ void ApplicationOverlay::displayOverlayTexture() { if (_alpha == 0.0f) { return; } - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); glEnable(GL_TEXTURE_2D); glActiveTexture(GL_TEXTURE0); @@ -378,7 +378,7 @@ void ApplicationOverlay::displayOverlayTexture3DTV(Camera& whichCamera, float as glEnd(); - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); if (_crosshairTexture == 0) { _crosshairTexture = glCanvas->bindTexture(QImage(Application::resourcesPath() + "images/sixense-reticle.png")); } @@ -432,7 +432,7 @@ void ApplicationOverlay::computeOculusPickRay(float x, float y, glm::vec3& origi //Caculate the click location using one of the sixense controllers. Scale is not applied QPoint ApplicationOverlay::getPalmClickLocation(const PalmData *palm) const { Application* application = Application::getInstance(); - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); MyAvatar* myAvatar = application->getAvatar(); glm::vec3 tip = myAvatar->getLaserPointerTipPosition(palm); @@ -511,7 +511,7 @@ bool ApplicationOverlay::calculateRayUICollisionPoint(const glm::vec3& position, //Renders optional pointers void ApplicationOverlay::renderPointers() { Application* application = Application::getInstance(); - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); //lazily load crosshair texture if (_crosshairTexture == 0) { @@ -559,7 +559,7 @@ void ApplicationOverlay::renderPointers() { void ApplicationOverlay::renderControllerPointers() { Application* application = Application::getInstance(); - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); MyAvatar* myAvatar = application->getAvatar(); //Static variables used for storing controller state @@ -704,7 +704,7 @@ void ApplicationOverlay::renderPointersOculus(const glm::vec3& eyePos) { //Renders a small magnification of the currently bound texture at the coordinates void ApplicationOverlay::renderMagnifier(glm::vec2 magPos, float sizeMult, bool showBorder) const { - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); const int widgetWidth = glCanvas->width(); const int widgetHeight = glCanvas->height(); @@ -762,7 +762,7 @@ void ApplicationOverlay::renderAudioMeter() { Application* application = Application::getInstance(); - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); Audio* audio = application->getAudio(); // Display a single screen-size quad to create an alpha blended 'collision' flash @@ -893,7 +893,7 @@ void ApplicationOverlay::renderStatsAndLogs() { Application* application = Application::getInstance(); - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); const OctreePacketProcessor& octreePacketProcessor = application->getOctreePacketProcessor(); BandwidthMeter* bandwidthMeter = application->getBandwidthMeter(); NodeBounds& nodeBoundsDisplay = application->getNodeBoundsDisplay(); @@ -935,7 +935,7 @@ void ApplicationOverlay::renderDomainConnectionStatusBorder() { NodeList* nodeList = NodeList::getInstance(); if (nodeList && !nodeList->getDomainHandler().isConnected()) { - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); int right = glCanvas->width(); int bottom = glCanvas->height(); diff --git a/interface/src/ui/PreferencesDialog.cpp b/interface/src/ui/PreferencesDialog.cpp index d39266e0fd..7baacd3d5a 100644 --- a/interface/src/ui/PreferencesDialog.cpp +++ b/interface/src/ui/PreferencesDialog.cpp @@ -215,7 +215,7 @@ void PreferencesDialog::savePreferences() { myAvatar->setClampedTargetScale(ui.avatarScaleSpin->value()); Application::getInstance()->getVoxels()->setMaxVoxels(ui.maxVoxelsSpin->value()); - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); Application::getInstance()->resizeGL(glCanvas->width(), glCanvas->height()); Menu::getInstance()->setRealWorldFieldOfView(ui.realWorldFieldOfViewSpin->value()); diff --git a/interface/src/ui/Snapshot.cpp b/interface/src/ui/Snapshot.cpp index ddd2b93805..e3b512adcc 100644 --- a/interface/src/ui/Snapshot.cpp +++ b/interface/src/ui/Snapshot.cpp @@ -83,7 +83,7 @@ QTemporaryFile* Snapshot::saveTempSnapshot() { } QFile* Snapshot::savedFileForSnapshot(bool isTemporary) { - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); QImage shot = glCanvas->grabFrameBuffer(); Avatar* avatar = Application::getInstance()->getAvatar(); diff --git a/interface/src/ui/Stats.cpp b/interface/src/ui/Stats.cpp index 2581866c70..be1fd88445 100644 --- a/interface/src/ui/Stats.cpp +++ b/interface/src/ui/Stats.cpp @@ -56,7 +56,7 @@ Stats::Stats(): _metavoxelReceiveProgress(0), _metavoxelReceiveTotal(0) { - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); resetWidth(glCanvas->width(), 0); } @@ -67,7 +67,7 @@ void Stats::toggleExpanded() { // called on mouse click release // check for clicks over stats in order to expand or contract them void Stats::checkClick(int mouseX, int mouseY, int mouseDragStartedX, int mouseDragStartedY, int horizontalOffset) { - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); if (0 != glm::compMax(glm::abs(glm::ivec2(mouseX - mouseDragStartedX, mouseY - mouseDragStartedY)))) { // not worried about dragging on stats @@ -122,7 +122,7 @@ void Stats::checkClick(int mouseX, int mouseY, int mouseDragStartedX, int mouseD } void Stats::resetWidth(int width, int horizontalOffset) { - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); int extraSpace = glCanvas->width() - horizontalOffset -2 - STATS_GENERAL_MIN_WIDTH - (Menu::getInstance()->isOptionChecked(MenuOption::TestPing) ? STATS_PING_MIN_WIDTH -1 : 0) @@ -198,7 +198,7 @@ void Stats::display( int bytesPerSecond, int voxelPacketsToProcess) { - QSharedPointer glCanvas = DependencyManager::get(); + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); unsigned int backgroundColor = 0x33333399; int verticalOffset = 0, lines = 0; From 89101872bbc94998a92bd41a8da543963450a11b Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 16 Dec 2014 14:04:39 -0800 Subject: [PATCH 149/258] move Model and AnimationHandle to libraries --- interface/src/avatar/FaceModel.h | 2 +- interface/src/avatar/Hand.h | 5 +++-- interface/src/avatar/ModelReferential.cpp | 3 +-- interface/src/avatar/MyAvatar.cpp | 2 +- interface/src/avatar/SkeletonModel.h | 3 ++- interface/src/avatar/SkeletonRagdoll.cpp | 2 +- interface/src/entities/EntityTreeRenderer.h | 2 +- interface/src/ui/overlays/ModelOverlay.h | 4 ++-- .../render-utils/src}/AnimationHandle.cpp | 0 .../render-utils/src}/AnimationHandle.h | 0 .../render-utils/src}/Model.cpp | 4 ++-- .../render-utils/src}/Model.h | 14 +++++++------- 12 files changed, 21 insertions(+), 20 deletions(-) rename {interface/src/renderer => libraries/render-utils/src}/AnimationHandle.cpp (100%) rename {interface/src/renderer => libraries/render-utils/src}/AnimationHandle.h (100%) rename {interface/src/renderer => libraries/render-utils/src}/Model.cpp (99%) rename {interface/src/renderer => libraries/render-utils/src}/Model.h (99%) diff --git a/interface/src/avatar/FaceModel.h b/interface/src/avatar/FaceModel.h index eaaa07e635..6c14beb587 100644 --- a/interface/src/avatar/FaceModel.h +++ b/interface/src/avatar/FaceModel.h @@ -12,7 +12,7 @@ #ifndef hifi_FaceModel_h #define hifi_FaceModel_h -#include "renderer/Model.h" +#include class Head; diff --git a/interface/src/avatar/Hand.h b/interface/src/avatar/Hand.h index ed2fa3e1ab..688af151b4 100644 --- a/interface/src/avatar/Hand.h +++ b/interface/src/avatar/Hand.h @@ -11,6 +11,8 @@ #ifndef hifi_Hand_h #define hifi_Hand_h +#include "InterfaceConfig.h" + #include #include @@ -22,9 +24,8 @@ #include #include #include +#include -#include "InterfaceConfig.h" -#include "renderer/Model.h" #include "world.h" diff --git a/interface/src/avatar/ModelReferential.cpp b/interface/src/avatar/ModelReferential.cpp index df6e272da7..5b72fddae7 100644 --- a/interface/src/avatar/ModelReferential.cpp +++ b/interface/src/avatar/ModelReferential.cpp @@ -10,9 +10,8 @@ // #include - #include -#include "../renderer/Model.h" +#include #include "ModelReferential.h" diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 057b1f1fc6..6976e26e86 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -22,6 +22,7 @@ #include #include +#include #include #include #include @@ -40,7 +41,6 @@ #include "Recorder.h" #include "devices/Faceshift.h" #include "devices/OculusManager.h" -#include "renderer/AnimationHandle.h" #include "ui/TextRenderer.h" using namespace std; diff --git a/interface/src/avatar/SkeletonModel.h b/interface/src/avatar/SkeletonModel.h index ea732acfd5..0956d27b3f 100644 --- a/interface/src/avatar/SkeletonModel.h +++ b/interface/src/avatar/SkeletonModel.h @@ -12,9 +12,10 @@ #ifndef hifi_SkeletonModel_h #define hifi_SkeletonModel_h -#include "renderer/Model.h" #include +#include + #include "SkeletonRagdoll.h" class Avatar; diff --git a/interface/src/avatar/SkeletonRagdoll.cpp b/interface/src/avatar/SkeletonRagdoll.cpp index 7c0e056826..c944e0bd45 100644 --- a/interface/src/avatar/SkeletonRagdoll.cpp +++ b/interface/src/avatar/SkeletonRagdoll.cpp @@ -11,10 +11,10 @@ #include #include +#include #include "SkeletonRagdoll.h" #include "MuscleConstraint.h" -#include "../renderer/Model.h" SkeletonRagdoll::SkeletonRagdoll(Model* model) : Ragdoll(), _model(model) { assert(_model); diff --git a/interface/src/entities/EntityTreeRenderer.h b/interface/src/entities/EntityTreeRenderer.h index a8695db36d..87f45d5f56 100644 --- a/interface/src/entities/EntityTreeRenderer.h +++ b/interface/src/entities/EntityTreeRenderer.h @@ -17,6 +17,7 @@ #include #include // for RayToEntityIntersectionResult +#include #include #include #include @@ -25,7 +26,6 @@ #include #include -#include "renderer/Model.h" class EntityScriptDetails { public: diff --git a/interface/src/ui/overlays/ModelOverlay.h b/interface/src/ui/overlays/ModelOverlay.h index 567498feb5..8cd095f778 100644 --- a/interface/src/ui/overlays/ModelOverlay.h +++ b/interface/src/ui/overlays/ModelOverlay.h @@ -12,9 +12,9 @@ #ifndef hifi_ModelOverlay_h #define hifi_ModelOverlay_h -#include "Base3DOverlay.h" +#include -#include "../../renderer/Model.h" +#include "Base3DOverlay.h" class ModelOverlay : public Base3DOverlay { Q_OBJECT diff --git a/interface/src/renderer/AnimationHandle.cpp b/libraries/render-utils/src/AnimationHandle.cpp similarity index 100% rename from interface/src/renderer/AnimationHandle.cpp rename to libraries/render-utils/src/AnimationHandle.cpp diff --git a/interface/src/renderer/AnimationHandle.h b/libraries/render-utils/src/AnimationHandle.h similarity index 100% rename from interface/src/renderer/AnimationHandle.h rename to libraries/render-utils/src/AnimationHandle.h diff --git a/interface/src/renderer/Model.cpp b/libraries/render-utils/src/Model.cpp similarity index 99% rename from interface/src/renderer/Model.cpp rename to libraries/render-utils/src/Model.cpp index 5f160d2e8d..16e6b1bf02 100644 --- a/interface/src/renderer/Model.cpp +++ b/libraries/render-utils/src/Model.cpp @@ -19,9 +19,7 @@ #include #include -#include #include -#include #include #include #include @@ -31,6 +29,8 @@ #include #include "AnimationHandle.h" +#include "DeferredLightingEffect.h" +#include "GlowEffect.h" #include "Model.h" diff --git a/interface/src/renderer/Model.h b/libraries/render-utils/src/Model.h similarity index 99% rename from interface/src/renderer/Model.h rename to libraries/render-utils/src/Model.h index 2c6b0bd6ae..d24f349f81 100644 --- a/interface/src/renderer/Model.h +++ b/libraries/render-utils/src/Model.h @@ -21,16 +21,18 @@ #include #include #include -#include #include -#include +#include +#include #include -#include -#include #include -#include #include "AnimationHandle.h" +#include "GeometryCache.h" +#include "JointState.h" +#include "ProgramObject.h" +#include "TextureCache.h" +#include "ViewStateInterface.h" class QScriptEngine; @@ -38,8 +40,6 @@ class Shape; #include "RenderArgs.h" class ViewFrustum; -#include "gpu/Stream.h" -#include "gpu/Batch.h" /// A generic 3D model displaying geometry loaded from a URL. class Model : public QObject, public PhysicsEntity { From b449f650a0c4ac9bffef4511cf187be1fa13f2cd Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 16 Dec 2014 14:22:02 -0800 Subject: [PATCH 150/258] more Model cleanup --- interface/src/MetavoxelSystem.cpp | 2 +- interface/src/entities/RenderableLightEntityItem.cpp | 1 - interface/src/entities/RenderableModelEntityItem.h | 7 ++----- 3 files changed, 3 insertions(+), 7 deletions(-) diff --git a/interface/src/MetavoxelSystem.cpp b/interface/src/MetavoxelSystem.cpp index d34bc4a594..443c55359b 100644 --- a/interface/src/MetavoxelSystem.cpp +++ b/interface/src/MetavoxelSystem.cpp @@ -23,6 +23,7 @@ #include #include +#include #include #include @@ -32,7 +33,6 @@ #include "Application.h" #include "MetavoxelSystem.h" -#include "renderer/Model.h" REGISTER_META_OBJECT(DefaultMetavoxelRendererImplementation) REGISTER_META_OBJECT(SphereRenderer) diff --git a/interface/src/entities/RenderableLightEntityItem.cpp b/interface/src/entities/RenderableLightEntityItem.cpp index 48996d5b4c..58a3c3f18a 100644 --- a/interface/src/entities/RenderableLightEntityItem.cpp +++ b/interface/src/entities/RenderableLightEntityItem.cpp @@ -34,7 +34,6 @@ void RenderableLightEntityItem::render(RenderArgs* args) { PerformanceTimer perfTimer("RenderableLightEntityItem::render"); assert(getType() == EntityTypes::Light); glm::vec3 position = getPositionInMeters(); - glm::vec3 center = getCenterInMeters(); glm::vec3 dimensions = getDimensions() * (float)TREE_SCALE; glm::quat rotation = getRotation(); float largestDiameter = glm::max(dimensions.x, dimensions.y, dimensions.z); diff --git a/interface/src/entities/RenderableModelEntityItem.h b/interface/src/entities/RenderableModelEntityItem.h index 2401d0ea64..2c194467d2 100644 --- a/interface/src/entities/RenderableModelEntityItem.h +++ b/interface/src/entities/RenderableModelEntityItem.h @@ -16,6 +16,8 @@ #include #include +#include +#include #include #include #include @@ -23,11 +25,6 @@ #include #include -#include "renderer/Model.h" - -#include -#include - class RenderableModelEntityItem : public ModelEntityItem { public: static EntityItem* factory(const EntityItemID& entityID, const EntityItemProperties& properties); From ee2ce718b473edeb613be6d5e3330d1f61fcfc59 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 16 Dec 2014 15:14:14 -0800 Subject: [PATCH 151/258] header file cleanup --- interface/src/entities/EntityTreeRenderer.h | 3 +++ .../src/entities/RenderableModelEntityItem.cpp | 8 +------- .../src/entities/RenderableModelEntityItem.h | 15 +++++---------- .../src/entities/RenderableSphereEntityItem.cpp | 8 +------- .../src/entities/RenderableSphereEntityItem.h | 12 +----------- .../src/entities/RenderableTextEntityItem.cpp | 6 ++---- interface/src/entities/RenderableTextEntityItem.h | 12 +----------- 7 files changed, 14 insertions(+), 50 deletions(-) diff --git a/interface/src/entities/EntityTreeRenderer.h b/interface/src/entities/EntityTreeRenderer.h index 87f45d5f56..215a9df975 100644 --- a/interface/src/entities/EntityTreeRenderer.h +++ b/interface/src/entities/EntityTreeRenderer.h @@ -18,6 +18,7 @@ #include #include // for RayToEntityIntersectionResult #include +#include #include #include #include @@ -26,6 +27,8 @@ #include #include +class ScriptEngine; + class EntityScriptDetails { public: diff --git a/interface/src/entities/RenderableModelEntityItem.cpp b/interface/src/entities/RenderableModelEntityItem.cpp index 13bc097f27..c998570a27 100644 --- a/interface/src/entities/RenderableModelEntityItem.cpp +++ b/interface/src/entities/RenderableModelEntityItem.cpp @@ -11,18 +11,12 @@ #include -#include +#include -#include "InterfaceConfig.h" - -#include #include -#include #include - #include "Menu.h" -#include "EntityTreeRenderer.h" #include "RenderableModelEntityItem.h" EntityItem* RenderableModelEntityItem::factory(const EntityItemID& entityID, const EntityItemProperties& properties) { diff --git a/interface/src/entities/RenderableModelEntityItem.h b/interface/src/entities/RenderableModelEntityItem.h index 2c194467d2..b68723019f 100644 --- a/interface/src/entities/RenderableModelEntityItem.h +++ b/interface/src/entities/RenderableModelEntityItem.h @@ -12,18 +12,13 @@ #ifndef hifi_RenderableModelEntityItem_h #define hifi_RenderableModelEntityItem_h -#include -#include +#include +#include -#include -#include #include -#include -#include -#include -#include -#include -#include + +class Model; +class RenderArgs; class RenderableModelEntityItem : public ModelEntityItem { public: diff --git a/interface/src/entities/RenderableSphereEntityItem.cpp b/interface/src/entities/RenderableSphereEntityItem.cpp index db10edca73..97e3ee7869 100644 --- a/interface/src/entities/RenderableSphereEntityItem.cpp +++ b/interface/src/entities/RenderableSphereEntityItem.cpp @@ -11,18 +11,12 @@ #include -#include - -#include "InterfaceConfig.h" +#include #include #include #include -#include - -#include "Menu.h" -#include "EntityTreeRenderer.h" #include "RenderableSphereEntityItem.h" EntityItem* RenderableSphereEntityItem::factory(const EntityItemID& entityID, const EntityItemProperties& properties) { diff --git a/interface/src/entities/RenderableSphereEntityItem.h b/interface/src/entities/RenderableSphereEntityItem.h index 3c24889e79..0c8c6af7c2 100644 --- a/interface/src/entities/RenderableSphereEntityItem.h +++ b/interface/src/entities/RenderableSphereEntityItem.h @@ -12,18 +12,8 @@ #ifndef hifi_RenderableSphereEntityItem_h #define hifi_RenderableSphereEntityItem_h -#include -#include - -#include -#include -#include -#include -#include -#include -#include - #include +class RenderArgs; class RenderableSphereEntityItem : public SphereEntityItem { public: diff --git a/interface/src/entities/RenderableTextEntityItem.cpp b/interface/src/entities/RenderableTextEntityItem.cpp index 4059ee5751..1f680a8a0d 100644 --- a/interface/src/entities/RenderableTextEntityItem.cpp +++ b/interface/src/entities/RenderableTextEntityItem.cpp @@ -11,14 +11,12 @@ #include -#include "InterfaceConfig.h" - -#include +#include #include -#include "Menu.h" #include "EntityTreeRenderer.h" #include "RenderableTextEntityItem.h" +#include "ui/TextRenderer.h" const int FIXED_FONT_POINT_SIZE = 40; const float LINE_SCALE_RATIO = 1.2f; diff --git a/interface/src/entities/RenderableTextEntityItem.h b/interface/src/entities/RenderableTextEntityItem.h index 8760cb9df7..7fe85d9ef5 100644 --- a/interface/src/entities/RenderableTextEntityItem.h +++ b/interface/src/entities/RenderableTextEntityItem.h @@ -12,18 +12,8 @@ #ifndef hifi_RenderableTextEntityItem_h #define hifi_RenderableTextEntityItem_h -#include -#include - -#include -#include -#include -#include -#include -#include -#include - #include +class RenderArgs; class RenderableTextEntityItem : public TextEntityItem { public: From b2dac6f53fdb8c90f2197589cb5f083ccd5713df Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Tue, 16 Dec 2014 15:32:11 -0800 Subject: [PATCH 152/258] DM users update --- interface/src/Application.cpp | 4 ++-- interface/src/Menu.cpp | 2 +- libraries/animation/src/AnimationCache.h | 4 ++-- libraries/render-utils/src/AmbientOcclusionEffect.h | 5 +++-- libraries/render-utils/src/DeferredLightingEffect.h | 5 +++-- libraries/render-utils/src/GlowEffect.cpp | 9 ++++----- libraries/render-utils/src/GlowEffect.h | 4 ++-- libraries/script-engine/src/ScriptEngine.cpp | 2 +- libraries/shared/src/DependencyManager.h | 2 +- 9 files changed, 19 insertions(+), 18 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index f677c46269..e7455ef71e 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -2051,7 +2051,7 @@ void Application::init() { DependencyManager::get()->associateWithWidget(glCanvas.data()); // initialize the GlowEffect with our widget - DependencyManager::get()->init(glCanvas, + DependencyManager::get()->init(glCanvas.data(), Menu::getInstance()->isOptionChecked(MenuOption::EnableGlowEffect)); } @@ -4032,7 +4032,7 @@ void Application::registerScriptEngineWithApplicationServices(ScriptEngine* scri scriptEngine->registerGlobalObject("Menu", MenuScriptingInterface::getInstance()); scriptEngine->registerGlobalObject("Settings", SettingsScriptingInterface::getInstance()); scriptEngine->registerGlobalObject("AudioDevice", AudioDeviceScriptingInterface::getInstance()); - scriptEngine->registerGlobalObject("AnimationCache", DependencyManager::get()); + scriptEngine->registerGlobalObject("AnimationCache", DependencyManager::get().data()); scriptEngine->registerGlobalObject("SoundCache", &SoundCache::getInstance()); scriptEngine->registerGlobalObject("Account", AccountScriptingInterface::getInstance()); scriptEngine->registerGlobalObject("Metavoxels", &_metavoxels); diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index 0521615257..f0c2a687a4 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -427,7 +427,7 @@ Menu::Menu() : appInstance, SLOT(setRenderVoxels(bool))); addCheckableActionToQMenuAndActionHash(renderOptionsMenu, MenuOption::EnableGlowEffect, 0, true, - DependencyManager::get(), SLOT(toggleGlowEffect(bool))); + DependencyManager::get().data(), SLOT(toggleGlowEffect(bool))); addCheckableActionToQMenuAndActionHash(renderOptionsMenu, MenuOption::Wireframe, Qt::ALT | Qt::Key_W, false); addActionToQMenuAndActionHash(renderOptionsMenu, MenuOption::LodTools, Qt::SHIFT | Qt::Key_L, this, SLOT(lodTools())); diff --git a/libraries/animation/src/AnimationCache.h b/libraries/animation/src/AnimationCache.h index 5f3f305461..4e67014822 100644 --- a/libraries/animation/src/AnimationCache.h +++ b/libraries/animation/src/AnimationCache.h @@ -24,8 +24,9 @@ class Animation; typedef QSharedPointer AnimationPointer; /// Scriptable interface for FBX animation loading. -class AnimationCache : public ResourceCache, public DependencyManager::Dependency { +class AnimationCache : public ResourceCache { Q_OBJECT + SINGLETON_DEPENDENCY(AnimationCache) public: Q_INVOKABLE AnimationPointer getAnimation(const QString& url) { return getAnimation(QUrl(url)); } @@ -38,7 +39,6 @@ protected: private: AnimationCache(QObject* parent = NULL); virtual ~AnimationCache() { } - friend class DependencyManager; }; diff --git a/libraries/render-utils/src/AmbientOcclusionEffect.h b/libraries/render-utils/src/AmbientOcclusionEffect.h index 1ee7269480..421461860d 100644 --- a/libraries/render-utils/src/AmbientOcclusionEffect.h +++ b/libraries/render-utils/src/AmbientOcclusionEffect.h @@ -20,7 +20,9 @@ class ProgramObject; /// A screen space ambient occlusion effect. See John Chapman's tutorial at /// http://john-chapman-graphics.blogspot.co.uk/2013/01/ssao-tutorial.html for reference. -class AmbientOcclusionEffect: public DependencyManager::Dependency { +class AmbientOcclusionEffect { + SINGLETON_DEPENDENCY(AmbientOcclusionEffect) + public: void init(ViewStateInterface* viewState); @@ -29,7 +31,6 @@ public: private: AmbientOcclusionEffect() {} virtual ~AmbientOcclusionEffect() {} - friend class DependencyManager; ProgramObject* _occlusionProgram; int _nearLocation; diff --git a/libraries/render-utils/src/DeferredLightingEffect.h b/libraries/render-utils/src/DeferredLightingEffect.h index 5dcd7d35f4..904f9827ea 100644 --- a/libraries/render-utils/src/DeferredLightingEffect.h +++ b/libraries/render-utils/src/DeferredLightingEffect.h @@ -23,7 +23,9 @@ class PostLightingRenderable; /// Handles deferred lighting for the bits that require it (voxels, metavoxels...) -class DeferredLightingEffect: public DependencyManager::Dependency { +class DeferredLightingEffect { + SINGLETON_DEPENDENCY(DeferredLightingEffect) + public: void init(ViewStateInterface* viewState); @@ -73,7 +75,6 @@ public: private: DeferredLightingEffect() { } virtual ~DeferredLightingEffect() { } - friend class DependencyManager; class LightLocations { public: diff --git a/libraries/render-utils/src/GlowEffect.cpp b/libraries/render-utils/src/GlowEffect.cpp index 62e3a9d691..fb7189f61e 100644 --- a/libraries/render-utils/src/GlowEffect.cpp +++ b/libraries/render-utils/src/GlowEffect.cpp @@ -12,7 +12,6 @@ // include this before QOpenGLFramebufferObject, which includes an earlier version of OpenGL #include -#include #include #include @@ -157,7 +156,6 @@ QOpenGLFramebufferObject* GlowEffect::render(bool toTexture) { QOpenGLFramebufferObject* destFBO = toTexture ? textureCache->getSecondaryFramebufferObject() : NULL; - GLCanvas::SharedPointer glCanvas = DependencyManager::get(); if (!_enabled || _isEmpty) { // copy the primary to the screen if (destFBO && QOpenGLFramebufferObject::hasOpenGLFramebufferBlit()) { @@ -165,7 +163,7 @@ QOpenGLFramebufferObject* GlowEffect::render(bool toTexture) { } else { maybeBind(destFBO); if (!destFBO) { - glViewport(0, 0, glCanvas->getDeviceWidth(), glCanvas->getDeviceHeight()); + glViewport(0, 0, getDeviceWidth(), getDeviceHeight()); } glEnable(GL_TEXTURE_2D); glDisable(GL_LIGHTING); @@ -212,8 +210,9 @@ QOpenGLFramebufferObject* GlowEffect::render(bool toTexture) { } maybeBind(destFBO); if (!destFBO) { - glViewport(0, 0, glCanvas->getDeviceWidth(), glCanvas->getDeviceHeight()); - _addSeparateProgram->bind(); + glViewport(0, 0, getDeviceWidth(), getDeviceHeight()); + } + _addSeparateProgram->bind(); renderFullscreenQuad(); _addSeparateProgram->release(); maybeRelease(destFBO); diff --git a/libraries/render-utils/src/GlowEffect.h b/libraries/render-utils/src/GlowEffect.h index cc3e6e5867..37f29afb62 100644 --- a/libraries/render-utils/src/GlowEffect.h +++ b/libraries/render-utils/src/GlowEffect.h @@ -25,8 +25,9 @@ class QOpenGLFramebufferObject; class ProgramObject; /// A generic full screen glow effect. -class GlowEffect : public QObject, public DependencyManager::Dependency { +class GlowEffect : public QObject { Q_OBJECT + SINGLETON_DEPENDENCY(GlowEffect) public: @@ -60,7 +61,6 @@ public slots: private: GlowEffect(); virtual ~GlowEffect(); - friend class DependencyManager; int getDeviceWidth() const; int getDeviceHeight() const; diff --git a/libraries/script-engine/src/ScriptEngine.cpp b/libraries/script-engine/src/ScriptEngine.cpp index ec5f2bc0e7..6117da9d18 100644 --- a/libraries/script-engine/src/ScriptEngine.cpp +++ b/libraries/script-engine/src/ScriptEngine.cpp @@ -255,7 +255,7 @@ void ScriptEngine::init() { registerGlobalObject("Quat", &_quatLibrary); registerGlobalObject("Vec3", &_vec3Library); registerGlobalObject("Uuid", &_uuidLibrary); - registerGlobalObject("AnimationCache", DependencyManager::get()); + registerGlobalObject("AnimationCache", DependencyManager::get().data()); registerGlobalObject("Voxels", &_voxelsScriptingInterface); diff --git a/libraries/shared/src/DependencyManager.h b/libraries/shared/src/DependencyManager.h index 455ec38bca..d1a1896947 100644 --- a/libraries/shared/src/DependencyManager.h +++ b/libraries/shared/src/DependencyManager.h @@ -46,7 +46,7 @@ QSharedPointer DependencyManager::get() { static T* instance = new T(); if (instance) { - if (dynamic_cast(instance)) { // If this is a QOject, call deleteLater for destruction + if (dynamic_cast(instance) != NULL) { // If this is a QOject, call deleteLater for destruction sharedPointer = QSharedPointer(instance, &T::deleteLater); } else { // Otherwise use custom deleter to avoid issues between private destructor and QSharedPointer sharedPointer = QSharedPointer(instance, &T::customDeleter); From d385a7b8acb300061b40c42f7b3866dd62a7b7ee Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 16 Dec 2014 15:35:56 -0800 Subject: [PATCH 153/258] header file cleanup --- interface/src/entities/EntityTreeRenderer.cpp | 15 +++------------ interface/src/entities/EntityTreeRenderer.h | 12 +----------- .../src/entities/RenderableBoxEntityItem.cpp | 10 +--------- interface/src/entities/RenderableBoxEntityItem.h | 11 ----------- .../src/entities/RenderableLightEntityItem.cpp | 8 +------- .../src/entities/RenderableLightEntityItem.h | 11 ----------- .../src/entities/RenderableModelEntityItem.h | 1 - .../src/entities/RenderableSphereEntityItem.h | 1 - .../src/entities/RenderableTextEntityItem.cpp | 1 - interface/src/entities/RenderableTextEntityItem.h | 1 - interface/src/ui/overlays/LocalModelsOverlay.h | 4 ++-- 11 files changed, 8 insertions(+), 67 deletions(-) diff --git a/interface/src/entities/EntityTreeRenderer.cpp b/interface/src/entities/EntityTreeRenderer.cpp index 59b3f697c8..727a21c4c8 100644 --- a/interface/src/entities/EntityTreeRenderer.cpp +++ b/interface/src/entities/EntityTreeRenderer.cpp @@ -9,28 +9,19 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +#include + #include #include -#include - -#include "InterfaceConfig.h" - -#include #include -#include -#include +#include #include -#include - #include "Menu.h" -#include "NetworkAccessManager.h" #include "EntityTreeRenderer.h" -#include "devices/OculusManager.h" - #include "RenderableBoxEntityItem.h" #include "RenderableLightEntityItem.h" #include "RenderableModelEntityItem.h" diff --git a/interface/src/entities/EntityTreeRenderer.h b/interface/src/entities/EntityTreeRenderer.h index 215a9df975..1e0f4de125 100644 --- a/interface/src/entities/EntityTreeRenderer.h +++ b/interface/src/entities/EntityTreeRenderer.h @@ -12,24 +12,14 @@ #ifndef hifi_EntityTreeRenderer_h #define hifi_EntityTreeRenderer_h -#include -#include - #include #include // for RayToEntityIntersectionResult -#include #include -#include -#include #include -#include -#include -#include -#include +class Model; class ScriptEngine; - class EntityScriptDetails { public: QString scriptText; diff --git a/interface/src/entities/RenderableBoxEntityItem.cpp b/interface/src/entities/RenderableBoxEntityItem.cpp index f7b403bff2..bb0de0ce6d 100644 --- a/interface/src/entities/RenderableBoxEntityItem.cpp +++ b/interface/src/entities/RenderableBoxEntityItem.cpp @@ -11,21 +11,13 @@ #include -#include +#include -#include "InterfaceConfig.h" - -#include #include -#include #include - -#include "Menu.h" -#include "EntityTreeRenderer.h" #include "RenderableBoxEntityItem.h" - EntityItem* RenderableBoxEntityItem::factory(const EntityItemID& entityID, const EntityItemProperties& properties) { return new RenderableBoxEntityItem(entityID, properties); } diff --git a/interface/src/entities/RenderableBoxEntityItem.h b/interface/src/entities/RenderableBoxEntityItem.h index da4714f32b..c4495d2328 100644 --- a/interface/src/entities/RenderableBoxEntityItem.h +++ b/interface/src/entities/RenderableBoxEntityItem.h @@ -12,17 +12,6 @@ #ifndef hifi_RenderableBoxEntityItem_h #define hifi_RenderableBoxEntityItem_h -#include -#include - -#include -#include -#include -#include -#include -#include -#include - #include class RenderableBoxEntityItem : public BoxEntityItem { diff --git a/interface/src/entities/RenderableLightEntityItem.cpp b/interface/src/entities/RenderableLightEntityItem.cpp index 58a3c3f18a..be64fe7520 100644 --- a/interface/src/entities/RenderableLightEntityItem.cpp +++ b/interface/src/entities/RenderableLightEntityItem.cpp @@ -11,21 +11,15 @@ #include -#include - -#include "InterfaceConfig.h" +#include #include #include -#include - #include "Application.h" #include "Menu.h" -#include "EntityTreeRenderer.h" #include "RenderableLightEntityItem.h" - EntityItem* RenderableLightEntityItem::factory(const EntityItemID& entityID, const EntityItemProperties& properties) { return new RenderableLightEntityItem(entityID, properties); } diff --git a/interface/src/entities/RenderableLightEntityItem.h b/interface/src/entities/RenderableLightEntityItem.h index 2113f486cc..cfafb85983 100644 --- a/interface/src/entities/RenderableLightEntityItem.h +++ b/interface/src/entities/RenderableLightEntityItem.h @@ -12,17 +12,6 @@ #ifndef hifi_RenderableLightEntityItem_h #define hifi_RenderableLightEntityItem_h -#include -#include - -#include -#include -#include -#include -#include -#include -#include - #include class RenderableLightEntityItem : public LightEntityItem { diff --git a/interface/src/entities/RenderableModelEntityItem.h b/interface/src/entities/RenderableModelEntityItem.h index b68723019f..9e66e4ef40 100644 --- a/interface/src/entities/RenderableModelEntityItem.h +++ b/interface/src/entities/RenderableModelEntityItem.h @@ -18,7 +18,6 @@ #include class Model; -class RenderArgs; class RenderableModelEntityItem : public ModelEntityItem { public: diff --git a/interface/src/entities/RenderableSphereEntityItem.h b/interface/src/entities/RenderableSphereEntityItem.h index 0c8c6af7c2..3ed651b0ae 100644 --- a/interface/src/entities/RenderableSphereEntityItem.h +++ b/interface/src/entities/RenderableSphereEntityItem.h @@ -13,7 +13,6 @@ #define hifi_RenderableSphereEntityItem_h #include -class RenderArgs; class RenderableSphereEntityItem : public SphereEntityItem { public: diff --git a/interface/src/entities/RenderableTextEntityItem.cpp b/interface/src/entities/RenderableTextEntityItem.cpp index 1f680a8a0d..5a3d5df8f9 100644 --- a/interface/src/entities/RenderableTextEntityItem.cpp +++ b/interface/src/entities/RenderableTextEntityItem.cpp @@ -14,7 +14,6 @@ #include #include -#include "EntityTreeRenderer.h" #include "RenderableTextEntityItem.h" #include "ui/TextRenderer.h" diff --git a/interface/src/entities/RenderableTextEntityItem.h b/interface/src/entities/RenderableTextEntityItem.h index 7fe85d9ef5..e57ab0538a 100644 --- a/interface/src/entities/RenderableTextEntityItem.h +++ b/interface/src/entities/RenderableTextEntityItem.h @@ -13,7 +13,6 @@ #define hifi_RenderableTextEntityItem_h #include -class RenderArgs; class RenderableTextEntityItem : public TextEntityItem { public: diff --git a/interface/src/ui/overlays/LocalModelsOverlay.h b/interface/src/ui/overlays/LocalModelsOverlay.h index 39465de7f9..a82943a4a0 100644 --- a/interface/src/ui/overlays/LocalModelsOverlay.h +++ b/interface/src/ui/overlays/LocalModelsOverlay.h @@ -12,10 +12,10 @@ #ifndef hifi_LocalModelsOverlay_h #define hifi_LocalModelsOverlay_h -#include "entities/EntityTreeRenderer.h" - #include "Volume3DOverlay.h" +class EntityTreeRenderer; + class LocalModelsOverlay : public Volume3DOverlay { Q_OBJECT public: From 74a8f0059d0eb34a4fa1e20f0ddc6acf30a2931f Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 16 Dec 2014 15:43:24 -0800 Subject: [PATCH 154/258] some Application dependecy cleanup --- interface/src/entities/EntityTreeRenderer.cpp | 4 ---- interface/src/entities/EntityTreeRenderer.h | 2 -- 2 files changed, 6 deletions(-) diff --git a/interface/src/entities/EntityTreeRenderer.cpp b/interface/src/entities/EntityTreeRenderer.cpp index 727a21c4c8..951c214c44 100644 --- a/interface/src/entities/EntityTreeRenderer.cpp +++ b/interface/src/entities/EntityTreeRenderer.cpp @@ -29,10 +29,6 @@ #include "RenderableTextEntityItem.h" -QThread* EntityTreeRenderer::getMainThread() { - return Application::getInstance()->getEntities()->thread(); -} - EntityTreeRenderer::EntityTreeRenderer(bool wantScripts) : OctreeRenderer(), _wantScripts(wantScripts), diff --git a/interface/src/entities/EntityTreeRenderer.h b/interface/src/entities/EntityTreeRenderer.h index 1e0f4de125..b9fe516efd 100644 --- a/interface/src/entities/EntityTreeRenderer.h +++ b/interface/src/entities/EntityTreeRenderer.h @@ -57,8 +57,6 @@ public: /// clears the tree virtual void clear(); - static QThread* getMainThread(); - /// if a renderable entity item needs a model, we will allocate it for them Q_INVOKABLE Model* allocateModel(const QString& url); From 3f2b5aeca408f5fef82be452dd13c1182eed840e Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Tue, 16 Dec 2014 16:22:59 -0800 Subject: [PATCH 155/258] Cleaner destruction handling --- libraries/shared/src/DependencyManager.h | 21 +++++++++------------ 1 file changed, 9 insertions(+), 12 deletions(-) diff --git a/libraries/shared/src/DependencyManager.h b/libraries/shared/src/DependencyManager.h index d1a1896947..06a01058fd 100644 --- a/libraries/shared/src/DependencyManager.h +++ b/libraries/shared/src/DependencyManager.h @@ -20,7 +20,14 @@ public:\ typedef QSharedPointer SharedPointer;\ private:\ - void customDeleter() { delete this; }\ + void customDeleter() {\ + QObject* thisObject = dynamic_cast(this);\ + if (thisObject) {\ + thisObject->deleteLater();\ + } else {\ + delete this;\ + }\ + }\ friend class DependencyManager; class QObject; @@ -42,17 +49,7 @@ private: template QSharedPointer DependencyManager::get() { - static QSharedPointer sharedPointer; - static T* instance = new T(); - - if (instance) { - if (dynamic_cast(instance) != NULL) { // If this is a QOject, call deleteLater for destruction - sharedPointer = QSharedPointer(instance, &T::deleteLater); - } else { // Otherwise use custom deleter to avoid issues between private destructor and QSharedPointer - sharedPointer = QSharedPointer(instance, &T::customDeleter); - } - instance = NULL; - } + static QSharedPointer sharedPointer = QSharedPointer(new T(), &T::customDeleter); return sharedPointer; } From 3dfded89b8c172a4ad8f2a9b7a9f9ed58e91f725 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 16 Dec 2014 16:28:09 -0800 Subject: [PATCH 156/258] remove menu dependency from EntityTreeRenderer, some Application cleanup --- interface/src/Application.cpp | 16 ++- interface/src/Application.h | 3 + interface/src/entities/EntityTreeRenderer.cpp | 127 +++++++----------- interface/src/entities/EntityTreeRenderer.h | 15 ++- .../render-utils/src/ViewStateInterface.h | 3 + 5 files changed, 83 insertions(+), 81 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 8b3c5a2fa1..d8c7811b6a 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -155,9 +155,9 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) : _voxelImporter(), _importSucceded(false), _sharedVoxelSystem(TREE_SCALE, DEFAULT_MAX_VOXELS_PER_SYSTEM, &_clipboard), - _entities(true), + _entities(true, this), _entityCollisionSystem(), - _entityClipboardRenderer(false), + _entityClipboardRenderer(false, this), _entityClipboard(), _wantToKillLocalVoxels(false), _viewFrustum(), @@ -2943,6 +2943,18 @@ bool Application::shouldRenderMesh(float largestDimension, float distanceToCamer return Menu::getInstance()->shouldRenderMesh(largestDimension, distanceToCamera); } +float Application::getSizeScale() const { + return Menu::getInstance()->getVoxelSizeScale(); +} + +int Application::getBoundaryLevelAdjust() const { + return Menu::getInstance()->getBoundaryLevelAdjust(); +} + +PickRay Application::computePickRay(float x, float y) { + return getCamera()->computePickRay(x, y); +} + QImage Application::renderAvatarBillboard() { DependencyManager::get()->getPrimaryFramebufferObject()->bind(); diff --git a/interface/src/Application.h b/interface/src/Application.h index 9aca90fac8..86683a6608 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -285,6 +285,9 @@ public: virtual bool getShadowsEnabled(); virtual bool getCascadeShadowsEnabled(); virtual QThread* getMainThread() { return thread(); } + virtual float getSizeScale() const; + virtual int getBoundaryLevelAdjust() const; + virtual PickRay computePickRay(float x, float y); NodeBounds& getNodeBoundsDisplay() { return _nodeBoundsDisplay; } diff --git a/interface/src/entities/EntityTreeRenderer.cpp b/interface/src/entities/EntityTreeRenderer.cpp index 951c214c44..6684daf7e8 100644 --- a/interface/src/entities/EntityTreeRenderer.cpp +++ b/interface/src/entities/EntityTreeRenderer.cpp @@ -18,8 +18,9 @@ #include #include #include +#include -#include "Menu.h" +#include "Application.h" #include "EntityTreeRenderer.h" #include "RenderableBoxEntityItem.h" @@ -29,11 +30,16 @@ #include "RenderableTextEntityItem.h" -EntityTreeRenderer::EntityTreeRenderer(bool wantScripts) : +EntityTreeRenderer::EntityTreeRenderer(bool wantScripts, ViewStateInterface* viewState) : OctreeRenderer(), _wantScripts(wantScripts), _entitiesScriptEngine(NULL), - _lastMouseEventValid(false) + _lastMouseEventValid(false), + _viewState(viewState), + _displayElementChildProxies(false), + _displayModelBounds(false), + _displayModelElementProxy(false), + _dontDoPrecisionPicking(false) { REGISTER_ENTITY_TYPE_WITH_FACTORY(Model, RenderableModelEntityItem::factory) REGISTER_ENTITY_TYPE_WITH_FACTORY(Box, RenderableBoxEntityItem::factory) @@ -63,7 +69,7 @@ void EntityTreeRenderer::init() { entityTree->setFBXService(this); if (_wantScripts) { - _entitiesScriptEngine = new ScriptEngine(NO_SCRIPT, "Entities", + _entitiesScriptEngine = new ScriptEngine(NO_SCRIPT, "Entities", Application::getInstance()->getControllerScriptingInterface()); Application::getInstance()->registerScriptEngineWithApplicationServices(_entitiesScriptEngine); } @@ -276,44 +282,38 @@ void EntityTreeRenderer::checkEnterLeaveEntities() { } void EntityTreeRenderer::render(RenderArgs::RenderMode renderMode, RenderArgs::RenderSide renderSide) { - bool dontRenderAsScene = Menu::getInstance()->isOptionChecked(MenuOption::DontRenderEntitiesAsScene); + if (_tree) { + Model::startScene(renderSide); + RenderArgs args = { this, _viewFrustum, getSizeScale(), getBoundaryLevelAdjust(), renderMode, renderSide, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; + _tree->lockForRead(); + _tree->recurseTreeWithOperation(renderOperation, &args); + + Model::RenderMode modelRenderMode = renderMode == RenderArgs::SHADOW_RENDER_MODE + ? Model::SHADOW_RENDER_MODE : Model::DEFAULT_RENDER_MODE; + + // we must call endScene while we still have the tree locked so that no one deletes a model + // on us while rendering the scene + Model::endScene(modelRenderMode, &args); + _tree->unlock(); - if (dontRenderAsScene) { - OctreeRenderer::render(renderMode, renderSide); - } else { - if (_tree) { - Model::startScene(renderSide); - RenderArgs args = { this, _viewFrustum, getSizeScale(), getBoundaryLevelAdjust(), renderMode, renderSide, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; - _tree->lockForRead(); - _tree->recurseTreeWithOperation(renderOperation, &args); + // stats... + _meshesConsidered = args._meshesConsidered; + _meshesRendered = args._meshesRendered; + _meshesOutOfView = args._meshesOutOfView; + _meshesTooSmall = args._meshesTooSmall; - Model::RenderMode modelRenderMode = renderMode == RenderArgs::SHADOW_RENDER_MODE - ? Model::SHADOW_RENDER_MODE : Model::DEFAULT_RENDER_MODE; + _elementsTouched = args._elementsTouched; + _itemsRendered = args._itemsRendered; + _itemsOutOfView = args._itemsOutOfView; + _itemsTooSmall = args._itemsTooSmall; - // we must call endScene while we still have the tree locked so that no one deletes a model - // on us while rendering the scene - Model::endScene(modelRenderMode, &args); - _tree->unlock(); - - // stats... - _meshesConsidered = args._meshesConsidered; - _meshesRendered = args._meshesRendered; - _meshesOutOfView = args._meshesOutOfView; - _meshesTooSmall = args._meshesTooSmall; + _materialSwitches = args._materialSwitches; + _trianglesRendered = args._trianglesRendered; + _quadsRendered = args._quadsRendered; - _elementsTouched = args._elementsTouched; - _itemsRendered = args._itemsRendered; - _itemsOutOfView = args._itemsOutOfView; - _itemsTooSmall = args._itemsTooSmall; - - _materialSwitches = args._materialSwitches; - _trianglesRendered = args._trianglesRendered; - _quadsRendered = args._quadsRendered; - - _translucentMeshPartsRendered = args._translucentMeshPartsRendered; - _opaqueMeshPartsRendered = args._opaqueMeshPartsRendered; - } + _translucentMeshPartsRendered = args._translucentMeshPartsRendered; + _opaqueMeshPartsRendered = args._opaqueMeshPartsRendered; } deleteReleasedModels(); // seems like as good as any other place to do some memory cleanup } @@ -345,7 +345,7 @@ const Model* EntityTreeRenderer::getModelForEntityItem(const EntityItem* entityI return result; } -void renderElementProxy(EntityTreeElement* entityTreeElement) { +void EntityTreeRenderer::renderElementProxy(EntityTreeElement* entityTreeElement) { glm::vec3 elementCenter = entityTreeElement->getAACube().calcCenter() * (float) TREE_SCALE; float elementSize = entityTreeElement->getScale() * (float) TREE_SCALE; glColor3f(1.0f, 0.0f, 0.0f); @@ -354,9 +354,7 @@ void renderElementProxy(EntityTreeElement* entityTreeElement) { glutWireCube(elementSize); glPopMatrix(); - bool displayElementChildProxies = Menu::getInstance()->isOptionChecked(MenuOption::DisplayModelElementChildProxies); - - if (displayElementChildProxies) { + if (_displayElementChildProxies) { // draw the children float halfSize = elementSize / 2.0f; float quarterSize = elementSize / 4.0f; @@ -412,8 +410,7 @@ void renderElementProxy(EntityTreeElement* entityTreeElement) { void EntityTreeRenderer::renderProxies(const EntityItem* entity, RenderArgs* args) { bool isShadowMode = args->_renderMode == RenderArgs::SHADOW_RENDER_MODE; - bool displayModelBounds = Menu::getInstance()->isOptionChecked(MenuOption::DisplayModelBounds); - if (!isShadowMode && displayModelBounds) { + if (!isShadowMode && _displayModelBounds) { PerformanceTimer perfTimer("renderProxies"); AACube maxCube = entity->getMaximumAACube(); @@ -473,8 +470,6 @@ void EntityTreeRenderer::renderProxies(const EntityItem* entity, RenderArgs* arg } void EntityTreeRenderer::renderElement(OctreeElement* element, RenderArgs* args) { - bool wantDebug = false; - args->_elementsTouched++; // actually render it here... // we need to iterate the actual entityItems of the element @@ -486,11 +481,8 @@ void EntityTreeRenderer::renderElement(OctreeElement* element, RenderArgs* args) uint16_t numberOfEntities = entityItems.size(); bool isShadowMode = args->_renderMode == RenderArgs::SHADOW_RENDER_MODE; - bool displayElementProxy = Menu::getInstance()->isOptionChecked(MenuOption::DisplayModelElementProxy); - - - if (!isShadowMode && displayElementProxy && numberOfEntities > 0) { + if (!isShadowMode && _displayModelElementProxy && numberOfEntities > 0) { renderElementProxy(entityTreeElement); } @@ -507,23 +499,9 @@ void EntityTreeRenderer::renderElement(OctreeElement* element, RenderArgs* args) // when they are outside of the view frustum... float distance = args->_viewFrustum->distanceToCamera(entityBox.calcCenter()); - if (wantDebug) { - qDebug() << "------- renderElement() ----------"; - qDebug() << " type:" << EntityTypes::getEntityTypeName(entityItem->getType()); - if (entityItem->getType() == EntityTypes::Model) { - ModelEntityItem* modelEntity = static_cast(entityItem); - qDebug() << " url:" << modelEntity->getModelURL(); - } - qDebug() << " entityBox:" << entityItem->getAABox(); - qDebug() << " dimensions:" << entityItem->getDimensionsInMeters() << "in meters"; - qDebug() << " largestDimension:" << entityBox.getLargestDimension() << "in meters"; - qDebug() << " shouldRender:" << Menu::getInstance()->shouldRenderMesh(entityBox.getLargestDimension(), distance); - qDebug() << " in frustum:" << (args->_viewFrustum->boxInFrustum(entityBox) != ViewFrustum::OUTSIDE); - } - bool outOfView = args->_viewFrustum->boxInFrustum(entityBox) == ViewFrustum::OUTSIDE; if (!outOfView) { - bool bigEnoughToRender = Menu::getInstance()->shouldRenderMesh(entityBox.getLargestDimension(), distance); + bool bigEnoughToRender = _viewState->shouldRenderMesh(entityBox.getLargestDimension(), distance); if (bigEnoughToRender) { renderProxies(entityItem, args); @@ -548,11 +526,11 @@ void EntityTreeRenderer::renderElement(OctreeElement* element, RenderArgs* args) } float EntityTreeRenderer::getSizeScale() const { - return Menu::getInstance()->getVoxelSizeScale(); + return _viewState->getSizeScale(); } int EntityTreeRenderer::getBoundaryLevelAdjust() const { - return Menu::getInstance()->getBoundaryLevelAdjust(); + return _viewState->getBoundaryLevelAdjust(); } @@ -627,11 +605,6 @@ void EntityTreeRenderer::deleteReleasedModels() { } } -PickRay EntityTreeRenderer::computePickRay(float x, float y) { - return Application::getInstance()->getCamera()->computePickRay(x, y); -} - - RayToEntityIntersectionResult EntityTreeRenderer::findRayIntersectionWorker(const PickRay& ray, Octree::lockType lockType, bool precisionPicking) { RayToEntityIntersectionResult result; @@ -693,9 +666,9 @@ QScriptValueList EntityTreeRenderer::createEntityArgs(const EntityItemID& entity void EntityTreeRenderer::mousePressEvent(QMouseEvent* event, unsigned int deviceID) { PerformanceTimer perfTimer("EntityTreeRenderer::mousePressEvent"); - PickRay ray = computePickRay(event->x(), event->y()); + PickRay ray = _viewState->computePickRay(event->x(), event->y()); - bool precisionPicking = !Menu::getInstance()->isOptionChecked(MenuOption::DontDoPrecisionPicking); + bool precisionPicking = !_dontDoPrecisionPicking; RayToEntityIntersectionResult rayPickResult = findRayIntersectionWorker(ray, Octree::Lock, precisionPicking); if (rayPickResult.intersects) { //qDebug() << "mousePressEvent over entity:" << rayPickResult.entityID; @@ -719,8 +692,8 @@ void EntityTreeRenderer::mousePressEvent(QMouseEvent* event, unsigned int device void EntityTreeRenderer::mouseReleaseEvent(QMouseEvent* event, unsigned int deviceID) { PerformanceTimer perfTimer("EntityTreeRenderer::mouseReleaseEvent"); - PickRay ray = computePickRay(event->x(), event->y()); - bool precisionPicking = !Menu::getInstance()->isOptionChecked(MenuOption::DontDoPrecisionPicking); + PickRay ray = _viewState->computePickRay(event->x(), event->y()); + bool precisionPicking = !_dontDoPrecisionPicking; RayToEntityIntersectionResult rayPickResult = findRayIntersectionWorker(ray, Octree::Lock, precisionPicking); if (rayPickResult.intersects) { //qDebug() << "mouseReleaseEvent over entity:" << rayPickResult.entityID; @@ -754,7 +727,7 @@ void EntityTreeRenderer::mouseReleaseEvent(QMouseEvent* event, unsigned int devi void EntityTreeRenderer::mouseMoveEvent(QMouseEvent* event, unsigned int deviceID) { PerformanceTimer perfTimer("EntityTreeRenderer::mouseMoveEvent"); - PickRay ray = computePickRay(event->x(), event->y()); + PickRay ray = _viewState->computePickRay(event->x(), event->y()); bool precisionPicking = false; // for mouse moves we do not do precision picking RayToEntityIntersectionResult rayPickResult = findRayIntersectionWorker(ray, Octree::TryLock, precisionPicking); diff --git a/interface/src/entities/EntityTreeRenderer.h b/interface/src/entities/EntityTreeRenderer.h index b9fe516efd..c3bd77aba7 100644 --- a/interface/src/entities/EntityTreeRenderer.h +++ b/interface/src/entities/EntityTreeRenderer.h @@ -30,7 +30,7 @@ public: class EntityTreeRenderer : public OctreeRenderer, public EntityItemFBXService { Q_OBJECT public: - EntityTreeRenderer(bool wantScripts); + EntityTreeRenderer(bool wantScripts, ViewStateInterface* viewState); virtual ~EntityTreeRenderer(); virtual char getMyNodeType() const { return NodeType::EntityServer; } @@ -100,17 +100,22 @@ public slots: void entityCollisionWithVoxel(const EntityItemID& entityID, const VoxelDetail& voxel, const Collision& collision); void entityCollisionWithEntity(const EntityItemID& idA, const EntityItemID& idB, const Collision& collision); + // optional slots that can be wired to menu items + void setDisplayElementChildProxies(bool value) { _displayElementChildProxies = value; } + void setDisplayModelBounds(bool value) { _displayModelBounds = value; } + void setDisplayModelElementProxy(bool value) { _displayModelElementProxy = value; } + void setDontDoPrecisionPicking(bool value) { _dontDoPrecisionPicking = value; } protected: virtual Octree* createTree() { return new EntityTree(true); } private: + void renderElementProxy(EntityTreeElement* entityTreeElement); void checkAndCallPreload(const EntityItemID& entityID); void checkAndCallUnload(const EntityItemID& entityID); QList _releasedModels; void renderProxies(const EntityItem* entity, RenderArgs* args); - PickRay computePickRay(float x, float y); RayToEntityIntersectionResult findRayIntersectionWorker(const PickRay& ray, Octree::lockType lockType, bool precisionPicking); @@ -136,6 +141,12 @@ private: bool _lastMouseEventValid; MouseEvent _lastMouseEvent; + ViewStateInterface* _viewState; + bool _displayElementChildProxies; + bool _displayModelBounds; + bool _displayModelElementProxy; + bool _dontDoPrecisionPicking; + }; #endif // hifi_EntityTreeRenderer_h diff --git a/libraries/render-utils/src/ViewStateInterface.h b/libraries/render-utils/src/ViewStateInterface.h index 9110eb8eb6..5f85e998a4 100644 --- a/libraries/render-utils/src/ViewStateInterface.h +++ b/libraries/render-utils/src/ViewStateInterface.h @@ -38,6 +38,9 @@ public: virtual const Transform& getViewTransform() const = 0; virtual void setupWorldLight() = 0; virtual bool shouldRenderMesh(float largestDimension, float distanceToCamera) = 0; + virtual float getSizeScale() const = 0; + virtual int getBoundaryLevelAdjust() const = 0; + virtual PickRay computePickRay(float x, float y) = 0; }; From 6304a5e819e1cb06423f85b62e3ea3fa56d83f86 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Tue, 16 Dec 2014 16:50:15 -0800 Subject: [PATCH 157/258] Unused removed method --- libraries/shared/src/DependencyManager.h | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/libraries/shared/src/DependencyManager.h b/libraries/shared/src/DependencyManager.h index 06a01058fd..fdf8030199 100644 --- a/libraries/shared/src/DependencyManager.h +++ b/libraries/shared/src/DependencyManager.h @@ -42,9 +42,7 @@ public: private: static DependencyManager& getInstance(); DependencyManager() {} - ~DependencyManager(); - - static void noDelete(void*) {} + ~DependencyManager(); }; template From 77bc00e4105f0aae31d64abb817516d8375e0a94 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 16 Dec 2014 18:34:39 -0800 Subject: [PATCH 158/258] a simple model for persistent scripts in domain-server --- .../resources/describe-settings.json | 27 +++++++++ domain-server/resources/web/js/settings.js | 8 ++- domain-server/src/DomainServer.cpp | 59 ++++++++++--------- domain-server/src/DomainServer.h | 2 +- 4 files changed, 64 insertions(+), 32 deletions(-) diff --git a/domain-server/resources/describe-settings.json b/domain-server/resources/describe-settings.json index 50de26c518..ae6f116537 100644 --- a/domain-server/resources/describe-settings.json +++ b/domain-server/resources/describe-settings.json @@ -76,6 +76,33 @@ } ] }, + { + "name": "scripts", + "label": "Scripts", + "settings": [ + { + "name": "persistent_scripts", + "type": "table", + "label": "Persistent Scripts", + "help": "Add the URLs for scripts that you would like to ensure are always running in your domain.", + "columns": [ + { + "name": "url", + "label": "Script URL" + }, + { + "name": "num_instances", + "label": "# instances", + "default": 1 + }, + { + "name": "pool", + "label": "Pool" + } + ] + } + ] + }, { "name": "audio_env", "label": "Audio Environment", diff --git a/domain-server/resources/web/js/settings.js b/domain-server/resources/web/js/settings.js index a27965abce..141bd72a26 100644 --- a/domain-server/resources/web/js/settings.js +++ b/domain-server/resources/web/js/settings.js @@ -363,7 +363,8 @@ function makeTableInputs(setting) { _.each(setting.columns, function(col) { html += "\ - \ + \ " }) @@ -389,8 +390,9 @@ function badgeSidebarForDifferences(changedElement) { // badge for any settings we have that are not the same or are not present in initialValues for (var setting in panelJSON) { - if (!_.isEqual(panelJSON[setting], initialPanelJSON[setting]) - && (panelJSON[setting] !== "" || _.has(initialPanelJSON, setting))) { + if ((!_.has(initialPanelJSON, setting) && panelJSON[setting] !== "") || + (!_.isEqual(panelJSON[setting], initialPanelJSON[setting]) + && (panelJSON[setting] !== "" || _.has(initialPanelJSON, setting)))) { badgeValue += 1 } } diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index bf9505671b..470b69be01 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -233,6 +233,9 @@ void DomainServer::setupNodeListAndAssignments(const QUuid& sessionUUID) { parseAssignmentConfigs(parsedTypes); populateDefaultStaticAssignmentsExcludingTypes(parsedTypes); + + // check for scripts the user wants to persist from their domain-server config + populateStaticScriptedAssignmentsFromSettings(); LimitedNodeList* nodeList = LimitedNodeList::createInstance(domainServerPort, domainServerDTLSPort); @@ -451,8 +454,6 @@ void DomainServer::parseAssignmentConfigs(QSet& excludedTypes) if (assignmentType != Assignment::AgentType) { createStaticAssignmentsForType(assignmentType, assignmentList); - } else { - createScriptedAssignmentsFromList(assignmentList); } excludedTypes.insert(assignmentType); @@ -468,35 +469,37 @@ void DomainServer::addStaticAssignmentToAssignmentHash(Assignment* newAssignment _allAssignments.insert(newAssignment->getUUID(), SharedAssignmentPointer(newAssignment)); } -void DomainServer::createScriptedAssignmentsFromList(const QVariantList &configList) { - foreach(const QVariant& configVariant, configList) { - if (configVariant.canConvert(QMetaType::QVariantMap)) { - QVariantMap configMap = configVariant.toMap(); - - // make sure we were passed a URL, otherwise this is an invalid scripted assignment - const QString ASSIGNMENT_URL_KEY = "url"; - QString assignmentURL = configMap[ASSIGNMENT_URL_KEY].toString(); - - if (!assignmentURL.isEmpty()) { - // check the json for a pool - const QString ASSIGNMENT_POOL_KEY = "pool"; - QString assignmentPool = configMap[ASSIGNMENT_POOL_KEY].toString(); - - // check for a number of instances, if not passed then default is 1 - const QString ASSIGNMENT_INSTANCES_KEY = "instances"; - int numInstances = configMap[ASSIGNMENT_INSTANCES_KEY].toInt(); - numInstances = (numInstances == 0 ? 1 : numInstances); - - qDebug() << "Adding a static scripted assignment from" << assignmentURL; - - for (int i = 0; i < numInstances; i++) { +void DomainServer::populateStaticScriptedAssignmentsFromSettings() { + const QString PERSISTENT_SCRIPTS_KEY_PATH = "scripts.persistent_scripts"; + const QVariant* persistentScriptsVariant = valueForKeyPath(_settingsManager.getSettingsMap(), PERSISTENT_SCRIPTS_KEY_PATH); + + if (persistentScriptsVariant) { + QVariantList persistentScriptsList = persistentScriptsVariant->toList(); + foreach(const QVariant& persistentScriptVariant, persistentScriptsList) { + QVariantMap persistentScript = persistentScriptVariant.toMap(); + + const QString PERSISTENT_SCRIPT_URL_KEY = "url"; + const QString PERSISTENT_SCRIPT_NUM_INSTANCES_KEY = "num_instances"; + const QString PERSISTENT_SCRIPT_POOL_KEY = "pool"; + + if (persistentScript.contains(PERSISTENT_SCRIPT_URL_KEY)) { + // check how many instances of this script to add + + int numInstances = persistentScript[PERSISTENT_SCRIPT_NUM_INSTANCES_KEY].toInt(); + QString scriptURL = persistentScript[PERSISTENT_SCRIPT_URL_KEY].toString(); + + QString scriptPool = persistentScript.value(PERSISTENT_SCRIPT_POOL_KEY).toString(); + + qDebug() << "Adding" << numInstances << "of persistent script at URL" << scriptURL << "- pool" << scriptPool; + + for (int i = 0; i < numInstances; ++i) { // add a scripted assignment to the queue for this instance Assignment* scriptAssignment = new Assignment(Assignment::CreateCommand, Assignment::AgentType, - assignmentPool); - scriptAssignment->setPayload(assignmentURL.toUtf8()); - - // scripts passed on CL or via JSON are static - so they are added back to the queue if the node dies + scriptPool); + scriptAssignment->setPayload(scriptURL.toUtf8()); + + // add it to static hash so we know we have to keep giving it back out addStaticAssignmentToAssignmentHash(scriptAssignment); } } diff --git a/domain-server/src/DomainServer.h b/domain-server/src/DomainServer.h index 76ab562f74..f910534eb1 100644 --- a/domain-server/src/DomainServer.h +++ b/domain-server/src/DomainServer.h @@ -100,9 +100,9 @@ private: void parseAssignmentConfigs(QSet& excludedTypes); void addStaticAssignmentToAssignmentHash(Assignment* newAssignment); - void createScriptedAssignmentsFromList(const QVariantList& configList); void createStaticAssignmentsForType(Assignment::Type type, const QVariantList& configList); void populateDefaultStaticAssignmentsExcludingTypes(const QSet& excludedTypes); + void populateStaticScriptedAssignmentsFromSettings(); SharedAssignmentPointer matchingQueuedAssignmentForCheckIn(const QUuid& checkInUUID, NodeType_t nodeType); SharedAssignmentPointer deployableAssignmentForRequest(const Assignment& requestAssignment); From b95eac759e5550330d25474bd52237ab3e1f2b76 Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Wed, 17 Dec 2014 08:52:48 -0800 Subject: [PATCH 159/258] Fix minor grid spacing not updating --- examples/libraries/gridTool.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/libraries/gridTool.js b/examples/libraries/gridTool.js index 622822e108..b1c258dc31 100644 --- a/examples/libraries/gridTool.js +++ b/examples/libraries/gridTool.js @@ -195,7 +195,7 @@ Grid = function(opts) { Overlays.editOverlay(gridOverlay, { position: { x: origin.y, y: origin.y, z: -origin.y }, visible: that.visible && that.enabled, - minorGridSpacing: minorGridSpacing, + minorGridWidth: minorGridSpacing, majorGridEvery: majorGridEvery, color: gridColor, alpha: gridAlpha, From 2ee33cef9f1bbe53b2a8ed1f4bc8aa7f7c224463 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 17 Dec 2014 10:21:27 -0800 Subject: [PATCH 160/258] have targets bubble up their Qt modules --- cmake/macros/LinkHifiLibraries.cmake | 4 ++++ cmake/macros/LinkSharedDependencies.cmake | 15 +++++++++++++++ cmake/macros/SetupHifiLibrary.cmake | 13 ++----------- cmake/macros/SetupHifiProject.cmake | 15 ++------------- 4 files changed, 23 insertions(+), 24 deletions(-) diff --git a/cmake/macros/LinkHifiLibraries.cmake b/cmake/macros/LinkHifiLibraries.cmake index a46023fe9a..464af76553 100644 --- a/cmake/macros/LinkHifiLibraries.cmake +++ b/cmake/macros/LinkHifiLibraries.cmake @@ -33,6 +33,10 @@ macro(LINK_HIFI_LIBRARIES) get_target_property(LINKED_TARGET_DEPENDENCY_INCLUDES ${HIFI_LIBRARY} DEPENDENCY_INCLUDES) list(APPEND ${TARGET_NAME}_DEPENDENCY_INCLUDES ${LINKED_TARGET_DEPENDENCY_INCLUDES}) + # ask the library what its qt module dependencies are and link them + get_target_property(LINKED_TARGET_DEPENDENCY_QT_MODULES ${HIFI_LIBRARY} DEPENDENCY_QT_MODULES) + list(APPEND ${TARGET_NAME}_DEPENDENCY_QT_MODULES ${LINKED_TARGET_DEPENDENCY_QT_MODULES}) + endforeach() endmacro(LINK_HIFI_LIBRARIES) \ No newline at end of file diff --git a/cmake/macros/LinkSharedDependencies.cmake b/cmake/macros/LinkSharedDependencies.cmake index afd25db0d7..890736d806 100644 --- a/cmake/macros/LinkSharedDependencies.cmake +++ b/cmake/macros/LinkSharedDependencies.cmake @@ -24,10 +24,25 @@ macro(LINK_SHARED_DEPENDENCIES) include_directories(SYSTEM ${${TARGET_NAME}_DEPENDENCY_INCLUDES}) endif () + if (${TARGET_NAME}_DEPENDENCY_QT_MODULES) + list(REMOVE_DUPLICATES ${TARGET_NAME}_DEPENDENCY_QT_MODULES) + + message(${TARGET_NAME}) + message(${${TARGET_NAME}_DEPENDENCY_QT_MODULES}) + + # find these Qt modules and link them to our own target + find_package(Qt5 COMPONENTS ${${TARGET_NAME}_DEPENDENCY_QT_MODULES} REQUIRED) + + foreach(QT_MODULE ${QT_MODULES_TO_LINK}) + target_link_libraries(${TARGET_NAME} Qt5::${QT_MODULE}) + endforeach() + endif () + # we've already linked our Qt modules, but we need to bubble them up to parents list(APPEND ${TARGET_NAME}_LIBRARIES_TO_LINK "${${TARGET_NAME}_QT_MODULES_TO_LINK}") # set the property on this target so it can be retreived by targets linking to us set_target_properties(${TARGET_NAME} PROPERTIES DEPENDENCY_LIBRARIES "${${TARGET_NAME}_LIBRARIES_TO_LINK}") set_target_properties(${TARGET_NAME} PROPERTIES DEPENDENCY_INCLUDES "${${TARGET_NAME}_DEPENDENCY_INCLUDES}") + set_target_properties(${TARGET_NAME} PROPERTIES DEPENDENCY_QT_MODULES "${${TARGET_NAME}_DEPENDENCY_QT_MODULES}") endmacro(LINK_SHARED_DEPENDENCIES) \ No newline at end of file diff --git a/cmake/macros/SetupHifiLibrary.cmake b/cmake/macros/SetupHifiLibrary.cmake index 950286ce45..de9f9b9d1e 100644 --- a/cmake/macros/SetupHifiLibrary.cmake +++ b/cmake/macros/SetupHifiLibrary.cmake @@ -18,16 +18,7 @@ macro(SETUP_HIFI_LIBRARY) # create a library and set the property so it can be referenced later add_library(${TARGET_NAME} ${LIB_SRCS} ${AUTOMTC_SRC}) - set(QT_MODULES_TO_LINK ${ARGN}) - list(APPEND QT_MODULES_TO_LINK Core) + set(${TARGET_NAME}_DEPENDENCY_QT_MODULES ${ARGN}) + list(APPEND ${TARGET_NAME}_DEPENDENCY_QT_MODULES Core) - find_package(Qt5 COMPONENTS ${QT_MODULES_TO_LINK} REQUIRED) - - foreach(QT_MODULE ${QT_MODULES_TO_LINK}) - get_target_property(QT_LIBRARY_LOCATION Qt5::${QT_MODULE} LOCATION) - - # add the actual path to the Qt module to our LIBRARIES_TO_LINK variable - target_link_libraries(${TARGET_NAME} Qt5::${QT_MODULE}) - list(APPEND ${TARGET_NAME}_QT_MODULES_TO_LINK ${QT_LIBRARY_LOCATION}) - endforeach() endmacro(SETUP_HIFI_LIBRARY) \ No newline at end of file diff --git a/cmake/macros/SetupHifiProject.cmake b/cmake/macros/SetupHifiProject.cmake index d21e2c11bb..157c22ea79 100644 --- a/cmake/macros/SetupHifiProject.cmake +++ b/cmake/macros/SetupHifiProject.cmake @@ -25,17 +25,6 @@ macro(SETUP_HIFI_PROJECT) # add the executable, include additional optional sources add_executable(${TARGET_NAME} ${TARGET_SRCS} "${AUTOMTC_SRC}") - set(QT_MODULES_TO_LINK ${ARGN}) - list(APPEND QT_MODULES_TO_LINK Core) - - find_package(Qt5 COMPONENTS ${QT_MODULES_TO_LINK} REQUIRED) - - foreach(QT_MODULE ${QT_MODULES_TO_LINK}) - target_link_libraries(${TARGET_NAME} Qt5::${QT_MODULE}) - - # add the actual path to the Qt module to our LIBRARIES_TO_LINK variable - get_target_property(QT_LIBRARY_LOCATION Qt5::${QT_MODULE} LOCATION) - list(APPEND ${TARGET_NAME}_QT_MODULES_TO_LINK ${QT_LIBRARY_LOCATION}) - endforeach() - + set(${TARGET_NAME}_DEPENDENCY_QT_MODULES ${ARGN}) + list(APPEND ${TARGET_NAME}_DEPENDENCY_QT_MODULES Core) endmacro() \ No newline at end of file From 421680696756cf75bed30742d9514cdd3e13443c Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 17 Dec 2014 10:21:53 -0800 Subject: [PATCH 161/258] remove extra debugging in LinkSharedDependencies --- cmake/macros/LinkSharedDependencies.cmake | 3 --- 1 file changed, 3 deletions(-) diff --git a/cmake/macros/LinkSharedDependencies.cmake b/cmake/macros/LinkSharedDependencies.cmake index 890736d806..c5049cf842 100644 --- a/cmake/macros/LinkSharedDependencies.cmake +++ b/cmake/macros/LinkSharedDependencies.cmake @@ -27,9 +27,6 @@ macro(LINK_SHARED_DEPENDENCIES) if (${TARGET_NAME}_DEPENDENCY_QT_MODULES) list(REMOVE_DUPLICATES ${TARGET_NAME}_DEPENDENCY_QT_MODULES) - message(${TARGET_NAME}) - message(${${TARGET_NAME}_DEPENDENCY_QT_MODULES}) - # find these Qt modules and link them to our own target find_package(Qt5 COMPONENTS ${${TARGET_NAME}_DEPENDENCY_QT_MODULES} REQUIRED) From 33d50c6eb62beab46a52da27f1b3e4b2a8f15766 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 17 Dec 2014 10:26:51 -0800 Subject: [PATCH 162/258] fix dependency qt module linking in LinkSharedDependencies --- cmake/macros/LinkSharedDependencies.cmake | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cmake/macros/LinkSharedDependencies.cmake b/cmake/macros/LinkSharedDependencies.cmake index c5049cf842..fd5461c288 100644 --- a/cmake/macros/LinkSharedDependencies.cmake +++ b/cmake/macros/LinkSharedDependencies.cmake @@ -30,7 +30,7 @@ macro(LINK_SHARED_DEPENDENCIES) # find these Qt modules and link them to our own target find_package(Qt5 COMPONENTS ${${TARGET_NAME}_DEPENDENCY_QT_MODULES} REQUIRED) - foreach(QT_MODULE ${QT_MODULES_TO_LINK}) + foreach(QT_MODULE ${${TARGET_NAME}_DEPENDENCY_QT_MODULES}) target_link_libraries(${TARGET_NAME} Qt5::${QT_MODULE}) endforeach() endif () From d3bf28e87971ac8abbde30d68a61a82b62cda9b3 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 17 Dec 2014 11:10:24 -0800 Subject: [PATCH 163/258] more Application dependency cleanup --- libraries/gpu/src/gpu/GLUTConfig.h | 25 +++++++++++++ ...terface.h => AbstractViewStateInterface.h} | 0 .../src/AbstractScriptingServicesInterface.h | 35 +++++++++++++++++++ 3 files changed, 60 insertions(+) create mode 100644 libraries/gpu/src/gpu/GLUTConfig.h rename libraries/render-utils/src/{ViewStateInterface.h => AbstractViewStateInterface.h} (100%) create mode 100644 libraries/script-engine/src/AbstractScriptingServicesInterface.h diff --git a/libraries/gpu/src/gpu/GLUTConfig.h b/libraries/gpu/src/gpu/GLUTConfig.h new file mode 100644 index 0000000000..214f2bb2b0 --- /dev/null +++ b/libraries/gpu/src/gpu/GLUTConfig.h @@ -0,0 +1,25 @@ +// +// GPUConfig.h +// libraries/gpu/src/gpu +// +// Created by Brad Hefta-Gaub on 12/17/14. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef gpu__GLUTConfig__ +#define gpu__GLUTConfig__ + +// TODO: remove these once we migrate away from GLUT calls +#if defined(__APPLE__) +#include +#elif defined(WIN32) +#include +#else +#include +#endif + + +#endif // gpu__GLUTConfig__ diff --git a/libraries/render-utils/src/ViewStateInterface.h b/libraries/render-utils/src/AbstractViewStateInterface.h similarity index 100% rename from libraries/render-utils/src/ViewStateInterface.h rename to libraries/render-utils/src/AbstractViewStateInterface.h diff --git a/libraries/script-engine/src/AbstractScriptingServicesInterface.h b/libraries/script-engine/src/AbstractScriptingServicesInterface.h new file mode 100644 index 0000000000..5e7ad81f67 --- /dev/null +++ b/libraries/script-engine/src/AbstractScriptingServicesInterface.h @@ -0,0 +1,35 @@ +// +// AbstractScriptingServicesInterface.h +// interface/src/script-engine +// +// Created by Brad Hefta-Gaub on 12/16/14. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef hifi_AbstractScriptingServicesInterface_h +#define hifi_AbstractScriptingServicesInterface_h + +//#include + +class AbstractControllerScriptingInterface; +class Transform; +class ScriptEngine; +class QThread; + +/// Interface provided by Application to other objects that need access to scripting services of the application +class AbstractScriptingServicesInterface { +public: + + /// Returns the controller interface for the application + virtual AbstractControllerScriptingInterface* getControllerScriptingInterface() = 0; + + /// Registers application specific services with a script engine. + virtual void registerScriptEngineWithApplicationServices(ScriptEngine* scriptEngine) = 0; + +}; + + +#endif // hifi_AbstractScriptingServicesInterface_h From 5d636e21c64d8789f198bbdaf4cbf325372740cc Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 17 Dec 2014 11:10:45 -0800 Subject: [PATCH 164/258] more Application dependency cleanup --- interface/src/Application.cpp | 6 ++--- interface/src/Application.h | 14 ++++++----- interface/src/entities/EntityTreeRenderer.cpp | 23 ++++++++++++------- interface/src/entities/EntityTreeRenderer.h | 8 +++++-- .../src/AbstractViewStateInterface.h | 16 ++++++++----- .../src/AmbientOcclusionEffect.cpp | 3 ++- .../render-utils/src/AmbientOcclusionEffect.h | 7 +++--- .../src/DeferredLightingEffect.cpp | 15 ++++-------- .../render-utils/src/DeferredLightingEffect.h | 6 ++--- libraries/render-utils/src/Model.cpp | 4 +++- libraries/render-utils/src/Model.h | 6 ++--- 11 files changed, 60 insertions(+), 48 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index d8c7811b6a..1453cec53b 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -155,9 +155,9 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) : _voxelImporter(), _importSucceded(false), _sharedVoxelSystem(TREE_SCALE, DEFAULT_MAX_VOXELS_PER_SYSTEM, &_clipboard), - _entities(true, this), + _entities(true, this, this), _entityCollisionSystem(), - _entityClipboardRenderer(false, this), + _entityClipboardRenderer(false, this, this), _entityClipboard(), _wantToKillLocalVoxels(false), _viewFrustum(), @@ -191,7 +191,7 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) : _isVSyncOn(true), _aboutToQuit(false) { - Model::setViewStateInterface(this); // The model class will sometimes need to know view state details from us + Model::setAbstractViewStateInterface(this); // The model class will sometimes need to know view state details from us // read the ApplicationInfo.ini file for Name/Version/Domain information QSettings applicationInfo(PathUtils::resourcesPath() + "info/ApplicationInfo.ini", QSettings::IniFormat); diff --git a/interface/src/Application.h b/interface/src/Application.h index 86683a6608..d192a9abe6 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -32,6 +32,8 @@ #include #include +#include +#include #include #include #include @@ -42,7 +44,6 @@ #include #include #include -#include #include #include "MainWindow.h" @@ -127,7 +128,7 @@ static const quint64 TOO_LONG_SINCE_LAST_SEND_DOWNSTREAM_AUDIO_STATS = 1 * USECS static const QString INFO_HELP_PATH = "html/interface-welcome-allsvg.html"; static const QString INFO_EDIT_ENTITIES_PATH = "html/edit-entities-commands.html"; -class Application : public QApplication, public ViewStateInterface { +class Application : public QApplication, public AbstractViewStateInterface, AbstractScriptingServicesInterface { Q_OBJECT friend class OctreePacketProcessor; @@ -186,6 +187,7 @@ public: GLCanvas* getGLWidget() { return _glWidget; } bool isThrottleRendering() const { return _glWidget->isThrottleRendering(); } MyAvatar* getAvatar() { return _myAvatar; } + const MyAvatar* getAvatar() const { return _myAvatar; } Audio* getAudio() { return &_audio; } Camera* getCamera() { return &_myCamera; } ViewFrustum* getViewFrustum() { return &_viewFrustum; } @@ -248,7 +250,9 @@ public: ToolWindow* getToolWindow() { return _toolWindow ; } - ControllerScriptingInterface* getControllerScriptingInterface() { return &_controllerScriptingInterface; } + virtual AbstractControllerScriptingInterface* getControllerScriptingInterface() { return &_controllerScriptingInterface; } + virtual void registerScriptEngineWithApplicationServices(ScriptEngine* scriptEngine); + AvatarManager& getAvatarManager() { return _avatarManager; } void resetProfile(const QString& username); @@ -288,6 +292,7 @@ public: virtual float getSizeScale() const; virtual int getBoundaryLevelAdjust() const; virtual PickRay computePickRay(float x, float y); + virtual const glm::vec3& getAvatarPosition() const { return getAvatar()->getPosition(); } NodeBounds& getNodeBoundsDisplay() { return _nodeBoundsDisplay; } @@ -312,9 +317,6 @@ public: bool isVSyncEditable() const; bool isAboutToQuit() const { return _aboutToQuit; } - - void registerScriptEngineWithApplicationServices(ScriptEngine* scriptEngine); - // the isHMDmode is true whenever we use the interface from an HMD and not a standard flat display // rendering of several elements depend on that // TODO: carry that information on the Camera as a setting diff --git a/interface/src/entities/EntityTreeRenderer.cpp b/interface/src/entities/EntityTreeRenderer.cpp index 6684daf7e8..5654b416f1 100644 --- a/interface/src/entities/EntityTreeRenderer.cpp +++ b/interface/src/entities/EntityTreeRenderer.cpp @@ -11,16 +11,21 @@ #include +#include // TODO - we need to get rid of this ASAP + #include +#include #include - + +#include +#include #include +#include #include #include -#include +#include -#include "Application.h" #include "EntityTreeRenderer.h" #include "RenderableBoxEntityItem.h" @@ -30,12 +35,14 @@ #include "RenderableTextEntityItem.h" -EntityTreeRenderer::EntityTreeRenderer(bool wantScripts, ViewStateInterface* viewState) : +EntityTreeRenderer::EntityTreeRenderer(bool wantScripts, AbstractViewStateInterface* viewState, + AbstractScriptingServicesInterface* scriptingServices) : OctreeRenderer(), _wantScripts(wantScripts), _entitiesScriptEngine(NULL), _lastMouseEventValid(false), _viewState(viewState), + _scriptingServices(scriptingServices), _displayElementChildProxies(false), _displayModelBounds(false), _displayModelElementProxy(false), @@ -70,13 +77,13 @@ void EntityTreeRenderer::init() { if (_wantScripts) { _entitiesScriptEngine = new ScriptEngine(NO_SCRIPT, "Entities", - Application::getInstance()->getControllerScriptingInterface()); - Application::getInstance()->registerScriptEngineWithApplicationServices(_entitiesScriptEngine); + _scriptingServices->getControllerScriptingInterface()); + _scriptingServices->registerScriptEngineWithApplicationServices(_entitiesScriptEngine); } // make sure our "last avatar position" is something other than our current position, so that on our // first chance, we'll check for enter/leave entity events. - glm::vec3 avatarPosition = Application::getInstance()->getAvatar()->getPosition(); + glm::vec3 avatarPosition = _viewState->getAvatarPosition(); _lastAvatarPosition = avatarPosition + glm::vec3(1.0f, 1.0f, 1.0f); connect(entityTree, &EntityTree::deletingEntity, this, &EntityTreeRenderer::deletingEntity); @@ -233,7 +240,7 @@ void EntityTreeRenderer::update() { void EntityTreeRenderer::checkEnterLeaveEntities() { if (_tree) { _tree->lockForWrite(); // so that our scripts can do edits if they want - glm::vec3 avatarPosition = Application::getInstance()->getAvatar()->getPosition() / (float) TREE_SCALE; + glm::vec3 avatarPosition = _viewState->getAvatarPosition() / (float) TREE_SCALE; if (avatarPosition != _lastAvatarPosition) { float radius = 1.0f / (float) TREE_SCALE; // for now, assume 1 meter radius diff --git a/interface/src/entities/EntityTreeRenderer.h b/interface/src/entities/EntityTreeRenderer.h index c3bd77aba7..f827685409 100644 --- a/interface/src/entities/EntityTreeRenderer.h +++ b/interface/src/entities/EntityTreeRenderer.h @@ -19,6 +19,8 @@ class Model; class ScriptEngine; +class AbstractViewStateInterface; +class AbstractScriptingServicesInterface; class EntityScriptDetails { public: @@ -30,7 +32,8 @@ public: class EntityTreeRenderer : public OctreeRenderer, public EntityItemFBXService { Q_OBJECT public: - EntityTreeRenderer(bool wantScripts, ViewStateInterface* viewState); + EntityTreeRenderer(bool wantScripts, AbstractViewStateInterface* viewState, + AbstractScriptingServicesInterface* scriptingServices); virtual ~EntityTreeRenderer(); virtual char getMyNodeType() const { return NodeType::EntityServer; } @@ -141,7 +144,8 @@ private: bool _lastMouseEventValid; MouseEvent _lastMouseEvent; - ViewStateInterface* _viewState; + AbstractViewStateInterface* _viewState; + AbstractScriptingServicesInterface* _scriptingServices; bool _displayElementChildProxies; bool _displayModelBounds; bool _displayModelElementProxy; diff --git a/libraries/render-utils/src/AbstractViewStateInterface.h b/libraries/render-utils/src/AbstractViewStateInterface.h index 5f85e998a4..50a75c769a 100644 --- a/libraries/render-utils/src/AbstractViewStateInterface.h +++ b/libraries/render-utils/src/AbstractViewStateInterface.h @@ -1,5 +1,5 @@ // -// ViewStateInterface.h +// AbstractViewStateInterface.h // interface/src/renderer // // Created by Brad Hefta-Gaub on 12/16/14. @@ -9,16 +9,18 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -#ifndef hifi_ViewStateInterface_h -#define hifi_ViewStateInterface_h +#ifndef hifi_AbstractViewStateInterface_h +#define hifi_AbstractViewStateInterface_h -#include +#include class Transform; class QThread; +class ViewFrustum; +class PickRay; /// Interface provided by Application to other objects that need access to the current view state details -class ViewStateInterface { +class AbstractViewStateInterface { public: /// Returns the shadow distances for the current view state @@ -41,7 +43,9 @@ public: virtual float getSizeScale() const = 0; virtual int getBoundaryLevelAdjust() const = 0; virtual PickRay computePickRay(float x, float y) = 0; + + virtual const glm::vec3& getAvatarPosition() const = 0; }; -#endif // hifi_ViewStateInterface_h +#endif // hifi_AbstractViewStateInterface_h diff --git a/libraries/render-utils/src/AmbientOcclusionEffect.cpp b/libraries/render-utils/src/AmbientOcclusionEffect.cpp index b9289204c7..40a02a60a4 100644 --- a/libraries/render-utils/src/AmbientOcclusionEffect.cpp +++ b/libraries/render-utils/src/AmbientOcclusionEffect.cpp @@ -19,6 +19,7 @@ #include #include +#include "AbstractViewStateInterface.h" #include "AmbientOcclusionEffect.h" #include "GlowEffect.h" #include "ProgramObject.h" @@ -28,7 +29,7 @@ const int ROTATION_WIDTH = 4; const int ROTATION_HEIGHT = 4; -void AmbientOcclusionEffect::init(ViewStateInterface* viewState) { +void AmbientOcclusionEffect::init(AbstractViewStateInterface* viewState) { _viewState = viewState; // we will use this for view state services _occlusionProgram = new ProgramObject(); diff --git a/libraries/render-utils/src/AmbientOcclusionEffect.h b/libraries/render-utils/src/AmbientOcclusionEffect.h index 1ee7269480..59ab8b7c8b 100644 --- a/libraries/render-utils/src/AmbientOcclusionEffect.h +++ b/libraries/render-utils/src/AmbientOcclusionEffect.h @@ -14,8 +14,7 @@ #include -#include "ViewStateInterface.h" - +class AbstractViewStateInterface; class ProgramObject; /// A screen space ambient occlusion effect. See John Chapman's tutorial at @@ -23,7 +22,7 @@ class ProgramObject; class AmbientOcclusionEffect: public DependencyManager::Dependency { public: - void init(ViewStateInterface* viewState); + void init(AbstractViewStateInterface* viewState); void render(); private: @@ -44,7 +43,7 @@ private: int _blurScaleLocation; GLuint _rotationTextureID; - ViewStateInterface* _viewState; + AbstractViewStateInterface* _viewState; }; #endif // hifi_AmbientOcclusionEffect_h diff --git a/libraries/render-utils/src/DeferredLightingEffect.cpp b/libraries/render-utils/src/DeferredLightingEffect.cpp index 9f54b25441..5af14b6640 100644 --- a/libraries/render-utils/src/DeferredLightingEffect.cpp +++ b/libraries/render-utils/src/DeferredLightingEffect.cpp @@ -12,22 +12,15 @@ // include this before QOpenGLFramebufferObject, which includes an earlier version of OpenGL #include - -// TODO: remove these once we migrate away from GLUT calls -#if defined(__APPLE__) -#include -#elif defined(WIN32) -#include -#else -#include -#endif +#include // TODO - we need to get rid of this ASAP #include #include #include +#include - +#include "AbstractViewStateInterface.h" #include "DeferredLightingEffect.h" #include "GeometryCache.h" #include "GlowEffect.h" @@ -35,7 +28,7 @@ #include "TextureCache.h" -void DeferredLightingEffect::init(ViewStateInterface* viewState) { +void DeferredLightingEffect::init(AbstractViewStateInterface* viewState) { _viewState = viewState; _simpleProgram.addShaderFromSourceFile(QGLShader::Vertex, PathUtils::resourcesPath() + "shaders/simple.vert"); _simpleProgram.addShaderFromSourceFile(QGLShader::Fragment, PathUtils::resourcesPath() + "shaders/simple.frag"); diff --git a/libraries/render-utils/src/DeferredLightingEffect.h b/libraries/render-utils/src/DeferredLightingEffect.h index 5dcd7d35f4..955a289f6d 100644 --- a/libraries/render-utils/src/DeferredLightingEffect.h +++ b/libraries/render-utils/src/DeferredLightingEffect.h @@ -18,15 +18,15 @@ #include #include "ProgramObject.h" -#include "ViewStateInterface.h" +class AbstractViewStateInterface; class PostLightingRenderable; /// Handles deferred lighting for the bits that require it (voxels, metavoxels...) class DeferredLightingEffect: public DependencyManager::Dependency { public: - void init(ViewStateInterface* viewState); + void init(AbstractViewStateInterface* viewState); /// Returns a reference to a simple program suitable for rendering static /// untextured geometry (such as that generated by glutSolidSphere, etc.) @@ -125,7 +125,7 @@ private: QVector _spotLights; QVector _postLightingRenderables; - ViewStateInterface* _viewState; + AbstractViewStateInterface* _viewState; }; /// Simple interface for objects that require something to be rendered after deferred lighting. diff --git a/libraries/render-utils/src/Model.cpp b/libraries/render-utils/src/Model.cpp index 16e6b1bf02..b422a7f404 100644 --- a/libraries/render-utils/src/Model.cpp +++ b/libraries/render-utils/src/Model.cpp @@ -27,7 +27,9 @@ #include #include #include +#include +#include "AbstractViewStateInterface.h" #include "AnimationHandle.h" #include "DeferredLightingEffect.h" #include "GlowEffect.h" @@ -111,7 +113,7 @@ Model::SkinLocations Model::_skinNormalSpecularMapLocations; Model::SkinLocations Model::_skinShadowLocations; Model::SkinLocations Model::_skinTranslucentLocations; -ViewStateInterface* Model::_viewState = NULL; +AbstractViewStateInterface* Model::_viewState = NULL; void Model::setScale(const glm::vec3& scale) { setScaleInternal(scale); diff --git a/libraries/render-utils/src/Model.h b/libraries/render-utils/src/Model.h index d24f349f81..841389073e 100644 --- a/libraries/render-utils/src/Model.h +++ b/libraries/render-utils/src/Model.h @@ -32,8 +32,8 @@ #include "JointState.h" #include "ProgramObject.h" #include "TextureCache.h" -#include "ViewStateInterface.h" +class AbstractViewStateInterface; class QScriptEngine; class Shape; @@ -47,7 +47,7 @@ class Model : public QObject, public PhysicsEntity { public: - static void setViewStateInterface(ViewStateInterface* viewState) { _viewState = viewState; } + static void setAbstractViewStateInterface(AbstractViewStateInterface* viewState) { _viewState = viewState; } Model(QObject* parent = NULL); virtual ~Model(); @@ -459,7 +459,7 @@ private: bool hasLightmap, bool hasTangents, bool hasSpecular, bool isSkinned, RenderArgs* args); - static ViewStateInterface* _viewState; + static AbstractViewStateInterface* _viewState; }; From a465aa20ff5bb2b6a9b3ac396137fd74ab65c34d Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 17 Dec 2014 11:41:42 -0800 Subject: [PATCH 165/258] more Application and Menu dependency removal --- .../entities/RenderableLightEntityItem.cpp | 33 ++++++++----------- .../entities/RenderableModelEntityItem.cpp | 24 +++----------- .../src/entities/RenderableModelEntityItem.h | 1 + .../entities/src/EntityScriptingInterface.cpp | 10 ++---- libraries/entities/src/EntityTree.cpp | 1 - libraries/entities/src/EntityTree.h | 3 -- libraries/entities/src/LightEntityItem.cpp | 1 + libraries/entities/src/LightEntityItem.h | 5 +++ 8 files changed, 29 insertions(+), 49 deletions(-) diff --git a/interface/src/entities/RenderableLightEntityItem.cpp b/interface/src/entities/RenderableLightEntityItem.cpp index be64fe7520..9097956c88 100644 --- a/interface/src/entities/RenderableLightEntityItem.cpp +++ b/interface/src/entities/RenderableLightEntityItem.cpp @@ -16,8 +16,6 @@ #include #include -#include "Application.h" -#include "Menu.h" #include "RenderableLightEntityItem.h" EntityItem* RenderableLightEntityItem::factory(const EntityItemID& entityID, const EntityItemProperties& properties) { @@ -55,17 +53,13 @@ void RenderableLightEntityItem::render(RenderArgs* args) { float exponent = getExponent(); float cutoff = glm::radians(getCutoff()); - bool disableLights = Menu::getInstance()->isOptionChecked(MenuOption::DisableLightEntities); - - if (!disableLights) { - if (_isSpotlight) { - DependencyManager::get()->addSpotLight(position, largestDiameter / 2.0f, - ambient, diffuse, specular, constantAttenuation, linearAttenuation, quadraticAttenuation, - direction, exponent, cutoff); - } else { - DependencyManager::get()->addPointLight(position, largestDiameter / 2.0f, - ambient, diffuse, specular, constantAttenuation, linearAttenuation, quadraticAttenuation); - } + if (_isSpotlight) { + DependencyManager::get()->addSpotLight(position, largestDiameter / 2.0f, + ambient, diffuse, specular, constantAttenuation, linearAttenuation, quadraticAttenuation, + direction, exponent, cutoff); + } else { + DependencyManager::get()->addPointLight(position, largestDiameter / 2.0f, + ambient, diffuse, specular, constantAttenuation, linearAttenuation, quadraticAttenuation); } #ifdef WANT_DEBUG @@ -88,10 +82,11 @@ void RenderableLightEntityItem::render(RenderArgs* args) { bool RenderableLightEntityItem::findDetailedRayIntersection(const glm::vec3& origin, const glm::vec3& direction, bool& keepSearching, OctreeElement*& element, float& distance, BoxFace& face, void** intersectedObject, bool precisionPicking) const { - - // TODO: this isn't really correct because we don't know if we actually live in the main tree of the applications's - // EntityTreeRenderer. But we probably do. Technically we could be on the clipboard and someone might be trying to - // use the ray intersection API there. Anyway... if you ever try to do ray intersection testing off of trees other - // than the main tree of the main entity renderer, then you'll need to fix this mechanism. - return Application::getInstance()->getEntities()->getTree()->getLightsArePickable(); + + // TODO: consider if this is really what we want to do. We've made it so that "lights are pickable" is a global state + // this is probably reasonable since there's typically only one tree you'd be picking on at a time. Technically we could + // be on the clipboard and someone might be trying to use the ray intersection API there. Anyway... if you ever try to + // do ray intersection testing off of trees other than the main tree of the main entity renderer, then we'll need to + // fix this mechanism. + return _lightsArePickable; } diff --git a/interface/src/entities/RenderableModelEntityItem.cpp b/interface/src/entities/RenderableModelEntityItem.cpp index c998570a27..3e5118d203 100644 --- a/interface/src/entities/RenderableModelEntityItem.cpp +++ b/interface/src/entities/RenderableModelEntityItem.cpp @@ -13,10 +13,13 @@ #include +#include + #include +#include #include -#include "Menu.h" +#include "EntityTreeRenderer.h" #include "RenderableModelEntityItem.h" EntityItem* RenderableModelEntityItem::factory(const EntityItemID& entityID, const EntityItemProperties& properties) { @@ -159,28 +162,11 @@ void RenderableModelEntityItem::render(RenderArgs* args) { _needsInitialSimulation = false; } - // TODO: should we allow entityItems to have alpha on their models? - Model::RenderMode modelRenderMode = args->_renderMode == RenderArgs::SHADOW_RENDER_MODE - ? Model::SHADOW_RENDER_MODE : Model::DEFAULT_RENDER_MODE; - if (_model->isActive()) { // TODO: this is the majority of model render time. And rendering of a cube model vs the basic Box render // is significantly more expensive. Is there a way to call this that doesn't cost us as much? PerformanceTimer perfTimer("model->render"); - bool dontRenderAsScene = Menu::getInstance()->isOptionChecked(MenuOption::DontRenderEntitiesAsScene); - bool displayModelTriangles = Menu::getInstance()->isOptionChecked(MenuOption::DisplayModelTriangles); - bool rendered = false; - if (displayModelTriangles) { - rendered = _model->renderTriangleProxies(); - } - - if (!rendered) { - if (dontRenderAsScene) { - _model->render(alpha, modelRenderMode, args); - } else { - _model->renderInScene(alpha, args); - } - } + _model->renderInScene(alpha, args); } else { // if we couldn't get a model, then just draw a cube glColor3ub(getColor()[RED_INDEX],getColor()[GREEN_INDEX],getColor()[BLUE_INDEX]); diff --git a/interface/src/entities/RenderableModelEntityItem.h b/interface/src/entities/RenderableModelEntityItem.h index 9e66e4ef40..6f61a1b9db 100644 --- a/interface/src/entities/RenderableModelEntityItem.h +++ b/interface/src/entities/RenderableModelEntityItem.h @@ -18,6 +18,7 @@ #include class Model; +class EntityTreeRenderer; class RenderableModelEntityItem : public ModelEntityItem { public: diff --git a/libraries/entities/src/EntityScriptingInterface.cpp b/libraries/entities/src/EntityScriptingInterface.cpp index 26870ad9bb..6226012052 100644 --- a/libraries/entities/src/EntityScriptingInterface.cpp +++ b/libraries/entities/src/EntityScriptingInterface.cpp @@ -11,6 +11,7 @@ #include "EntityScriptingInterface.h" #include "EntityTree.h" +#include "LightEntityItem.h" #include "ModelEntityItem.h" EntityScriptingInterface::EntityScriptingInterface() : @@ -226,16 +227,11 @@ RayToEntityIntersectionResult EntityScriptingInterface::findRayIntersectionWorke } void EntityScriptingInterface::setLightsArePickable(bool value) { - if (_entityTree) { - _entityTree->setLightsArePickable(value); - } + LightEntityItem::setLightsArePickable(value); } bool EntityScriptingInterface::getLightsArePickable() const { - if (_entityTree) { - return _entityTree->getLightsArePickable(); - } - return false; + return LightEntityItem::getLightsArePickable(); } diff --git a/libraries/entities/src/EntityTree.cpp b/libraries/entities/src/EntityTree.cpp index 17178ccbed..fb8e4345f4 100644 --- a/libraries/entities/src/EntityTree.cpp +++ b/libraries/entities/src/EntityTree.cpp @@ -22,7 +22,6 @@ EntityTree::EntityTree(bool shouldReaverage) : Octree(shouldReaverage), _fbxService(NULL), - _lightsArePickable(true), _simulation(NULL) { _rootElement = createNewElement(); diff --git a/libraries/entities/src/EntityTree.h b/libraries/entities/src/EntityTree.h index 9a0fb43ecb..cfd08c3b5c 100644 --- a/libraries/entities/src/EntityTree.h +++ b/libraries/entities/src/EntityTree.h @@ -150,8 +150,6 @@ public: void emitEntityScriptChanging(const EntityItemID& entityItemID); - bool getLightsArePickable() const { return _lightsArePickable; } - void setLightsArePickable(bool value) { _lightsArePickable = value; } void setSimulation(EntitySimulation* simulation); signals: @@ -180,7 +178,6 @@ private: QHash _entityToElementMap; - bool _lightsArePickable; EntitySimulation* _simulation; }; diff --git a/libraries/entities/src/LightEntityItem.cpp b/libraries/entities/src/LightEntityItem.cpp index a24fe58c2a..44b83bc94e 100644 --- a/libraries/entities/src/LightEntityItem.cpp +++ b/libraries/entities/src/LightEntityItem.cpp @@ -18,6 +18,7 @@ #include "EntityTreeElement.h" #include "LightEntityItem.h" +bool LightEntityItem::_lightsArePickable = false; EntityItem* LightEntityItem::factory(const EntityItemID& entityID, const EntityItemProperties& properties) { return new LightEntityItem(entityID, properties); diff --git a/libraries/entities/src/LightEntityItem.h b/libraries/entities/src/LightEntityItem.h index eb9a2ed051..6ebb85beda 100644 --- a/libraries/entities/src/LightEntityItem.h +++ b/libraries/entities/src/LightEntityItem.h @@ -99,6 +99,9 @@ public: void setCutoff(float value) { _cutoff = value; } virtual const Shape& getCollisionShapeInMeters() const { return _emptyShape; } + + static bool getLightsArePickable() { return _lightsArePickable; } + static void setLightsArePickable(bool value) { _lightsArePickable = value; } protected: virtual void recalculateCollisionShape() { /* nothing to do */ } @@ -116,6 +119,8 @@ protected: // used for collision detection SphereShape _emptyShape; + + static bool _lightsArePickable; }; #endif // hifi_LightEntityItem_h From e36ee2a96130328ecddf1704edfc498905245e6c Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 17 Dec 2014 12:19:34 -0800 Subject: [PATCH 166/258] more correct creation and edit times for entities --- libraries/entities/src/EntityItem.cpp | 75 ++++++++++++------- libraries/entities/src/EntityItem.h | 5 +- libraries/entities/src/EntityItemProperties.h | 4 +- libraries/entities/src/EntityTypes.cpp | 8 +- 4 files changed, 55 insertions(+), 37 deletions(-) diff --git a/libraries/entities/src/EntityItem.cpp b/libraries/entities/src/EntityItem.cpp index b271439662..22cfeb3674 100644 --- a/libraries/entities/src/EntityItem.cpp +++ b/libraries/entities/src/EntityItem.cpp @@ -53,14 +53,13 @@ void EntityItem::initFromEntityItemID(const EntityItemID& entityItemID) { _creatorTokenID = entityItemID.creatorTokenID; // init values with defaults before calling setProperties - //uint64_t now = usecTimestampNow(); _lastEdited = 0; _lastEditedFromRemote = 0; _lastEditedFromRemoteInRemoteTime = 0; _lastSimulated = 0; _lastUpdated = 0; - _created = 0; // TODO: when do we actually want to make this "now" + _created = usecTimestampNow(); _changedOnServer = 0; _position = glm::vec3(0,0,0); @@ -99,16 +98,20 @@ EntityItem::EntityItem(const EntityItemID& entityItemID) { EntityItem::EntityItem(const EntityItemID& entityItemID, const EntityItemProperties& properties) { _type = EntityTypes::Unknown; - _lastEdited = 0; + quint64 now = usecTimestampNow(); + _created = properties.getCreated() < now ? properties.getCreated() : now; + _lastEdited = _lastEditedFromRemote = _lastSimulated = _lastUpdated = _lastEditedFromRemoteInRemoteTime = _created; _lastEditedFromRemote = 0; _lastEditedFromRemoteInRemoteTime = 0; _lastSimulated = 0; _lastUpdated = 0; - _created = properties.getCreated(); _dirtyFlags = 0; _changedOnServer = 0; initFromEntityItemID(entityItemID); setProperties(properties, true); // force copy + if (_lastEdited == 0) { + _lastEdited = _created; + } } EntityPropertyFlags EntityItem::getEntityProperties(EncodeBitstreamParams& params) const { @@ -367,7 +370,12 @@ int EntityItem::readEntityDataFromBuffer(const unsigned char* data, int bytesLef bytesRead += sizeof(createdFromBuffer); createdFromBuffer -= clockSkew; - _created = createdFromBuffer; // TODO: do we ever want to discard this??? + if (createdFromBuffer < _created) { + // the server claims that this entity has an older creation time + // so we accept it and clear _lastEdited + _created = createdFromBuffer; + _lastEdited = 0; + } if (wantDebug) { quint64 lastEdited = getLastEdited(); @@ -416,14 +424,14 @@ int EntityItem::readEntityDataFromBuffer(const unsigned char* data, int bytesLef if (fromSameServerEdit) { // If this is from the same sever packet, then check against any local changes since we got // the most recent packet from this server time - if (_lastEdited > _lastEditedFromRemote) { + if (_lastEdited >= _lastEditedFromRemote) { ignoreServerPacket = true; } } else { // If this isn't from the same sever packet, then honor our skew adjusted times... // If we've changed our local tree more recently than the new data from this packet // then we will not be changing our values, instead we just read and skip the data - if (_lastEdited > lastEditedFromBufferAdjusted) { + if (_lastEdited >= lastEditedFromBufferAdjusted) { ignoreServerPacket = true; } } @@ -439,7 +447,8 @@ int EntityItem::readEntityDataFromBuffer(const unsigned char* data, int bytesLef qDebug() << "USING NEW data from server!!! ****************"; } - _lastEdited = lastEditedFromBufferAdjusted; + // don't allow _lastEdited to be in the future + _lastEdited = lastEditedFromBufferAdjusted < now ? lastEditedFromBufferAdjusted : now; _lastEditedFromRemote = now; _lastEditedFromRemoteInRemoteTime = lastEditedFromBuffer; @@ -451,7 +460,8 @@ int EntityItem::readEntityDataFromBuffer(const unsigned char* data, int bytesLef ByteCountCoded updateDeltaCoder = encodedUpdateDelta; quint64 updateDelta = updateDeltaCoder; if (overwriteLocalData) { - _lastSimulated = _lastUpdated = lastEditedFromBufferAdjusted + updateDelta; // don't adjust for clock skew since we already did that for _lastEdited + _lastUpdated = lastEditedFromBufferAdjusted + updateDelta; // don't adjust for clock skew since we already did that for _lastEdited + _lastSimulated = now; if (wantDebug) { qDebug() << "_lastUpdated =" << _lastUpdated; qDebug() << "_lastEdited=" << _lastEdited; @@ -576,7 +586,7 @@ void EntityItem::simulate(const quint64& now) { float timeElapsed = (float)(now - _lastSimulated) / (float)(USECS_PER_SECOND); if (wantDebug) { - qDebug() << "********** EntityItem::update()"; + qDebug() << "********** EntityItem::simulate()"; qDebug() << " entity ID=" << getEntityItemID(); qDebug() << " now=" << now; qDebug() << " _lastSimulated=" << _lastSimulated; @@ -612,10 +622,8 @@ void EntityItem::simulate(const quint64& now) { } } - _lastSimulated = now; - if (wantDebug) { - qDebug() << " ********** EntityItem::update() .... SETTING _lastSimulated=" << _lastSimulated; + qDebug() << " ********** EntityItem::simulate() .... SETTING _lastSimulated=" << _lastSimulated; } if (hasAngularVelocity()) { @@ -645,13 +653,13 @@ void EntityItem::simulate(const quint64& now) { } } - if (hasVelocity() || hasGravity()) { + if (hasVelocity()) { glm::vec3 position = getPosition(); glm::vec3 velocity = getVelocity(); glm::vec3 newPosition = position + (velocity * timeElapsed); if (wantDebug) { - qDebug() << " EntityItem::update()...."; + qDebug() << " EntityItem::simulate()...."; qDebug() << " timeElapsed:" << timeElapsed; qDebug() << " old AACube:" << getMaximumAACube(); qDebug() << " old position:" << position; @@ -677,15 +685,15 @@ void EntityItem::simulate(const quint64& now) { } // handle gravity.... - if (hasGravity() && !isRestingOnSurface()) { - velocity += getGravity() * timeElapsed; - } - - // handle resting on surface case, this is definitely a bit of a hack, and it only works on the - // "ground" plane of the domain, but for now it - if (hasGravity() && isRestingOnSurface()) { - velocity.y = 0.0f; - position.y = getDistanceToBottomOfEntity(); + if (hasGravity()) { + // handle resting on surface case, this is definitely a bit of a hack, and it only works on the + // "ground" plane of the domain, but for now it what we've got + if (isRestingOnSurface()) { + velocity.y = 0.0f; + position.y = getDistanceToBottomOfEntity(); + } else { + velocity += getGravity() * timeElapsed; + } } // handle damping for velocity @@ -721,10 +729,12 @@ void EntityItem::simulate(const quint64& now) { qDebug() << " old getAABox:" << getAABox(); } } + + _lastSimulated = now; } bool EntityItem::isMoving() const { - return hasVelocity() || (hasGravity() && !isRestingOnSurface()) || hasAngularVelocity(); + return hasVelocity() || hasAngularVelocity(); } bool EntityItem::lifetimeHasExpired() const { @@ -773,10 +783,13 @@ bool EntityItem::setProperties(const EntityItemProperties& properties, bool forc // handle the setting of created timestamps for the basic new entity case if (forceCopy) { + quint64 now = usecTimestampNow(); if (properties.getCreated() == UNKNOWN_CREATED_TIME) { - _created = usecTimestampNow(); + _created = now; } else if (properties.getCreated() != USE_EXISTING_CREATED_TIME) { - _created = properties.getCreated(); + quint64 created = properties.getCreated(); + // don't allow _created to be in the future + _created = created < now ? created : now; } } @@ -803,13 +816,17 @@ bool EntityItem::setProperties(const EntityItemProperties& properties, bool forc if (somethingChanged) { somethingChangedNotification(); // notify derived classes that something has changed bool wantDebug = false; + uint64_t now = usecTimestampNow(); if (wantDebug) { - uint64_t now = usecTimestampNow(); int elapsed = now - getLastEdited(); qDebug() << "EntityItem::setProperties() AFTER update... edited AGO=" << elapsed << "now=" << now << " getLastEdited()=" << getLastEdited(); } - setLastEdited(properties._lastEdited); + // don't allow _lastEdited to be in the future + setLastEdited(properties._lastEdited < now ? properties._lastEdited : now); + if (getDirtyFlags() & EntityItem::DIRTY_POSITION) { + _lastSimulated = usecTimestampNow(); + } } return somethingChanged; diff --git a/libraries/entities/src/EntityItem.h b/libraries/entities/src/EntityItem.h index d5a4689657..7455b96f6b 100644 --- a/libraries/entities/src/EntityItem.h +++ b/libraries/entities/src/EntityItem.h @@ -85,7 +85,7 @@ public: /// Last edited time of this entity universal usecs quint64 getLastEdited() const { return _lastEdited; } void setLastEdited(quint64 lastEdited) - { _lastEdited = _lastSimulated = _lastUpdated = lastEdited; _changedOnServer = glm::max(lastEdited, _changedOnServer); } + { _lastEdited = _lastUpdated = lastEdited; _changedOnServer = glm::max(lastEdited, _changedOnServer); } float getEditedAgo() const /// Elapsed seconds since this entity was last edited { return (float)(usecTimestampNow() - getLastEdited()) / (float)USECS_PER_SECOND; } @@ -120,9 +120,6 @@ public: static int expectedBytes(); - static bool encodeEntityEditMessageDetails(PacketType command, EntityItemID id, const EntityItemProperties& details, - unsigned char* bufferOut, int sizeIn, int& sizeOut); - static void adjustEditPacketForClockSkew(unsigned char* codeColorBuffer, size_t length, int clockSkew); // perform update diff --git a/libraries/entities/src/EntityItemProperties.h b/libraries/entities/src/EntityItemProperties.h index 642e24beec..e5f78e8fc7 100644 --- a/libraries/entities/src/EntityItemProperties.h +++ b/libraries/entities/src/EntityItemProperties.h @@ -95,8 +95,8 @@ enum EntityPropertyList { typedef PropertyFlags EntityPropertyFlags; -const quint64 UNKNOWN_CREATED_TIME = (quint64)(-1); -const quint64 USE_EXISTING_CREATED_TIME = (quint64)(-2); +const quint64 UNKNOWN_CREATED_TIME = 0; +const quint64 USE_EXISTING_CREATED_TIME = 1; /// A collection of properties of an entity item used in the scripting API. Translates between the actual properties of an diff --git a/libraries/entities/src/EntityTypes.cpp b/libraries/entities/src/EntityTypes.cpp index 194df024e0..f7806445bc 100644 --- a/libraries/entities/src/EntityTypes.cpp +++ b/libraries/entities/src/EntityTypes.cpp @@ -71,7 +71,6 @@ bool EntityTypes::registerEntityType(EntityType entityType, const char* name, En EntityItem* EntityTypes::constructEntityItem(EntityType entityType, const EntityItemID& entityID, const EntityItemProperties& properties) { - EntityItem* newEntityItem = NULL; EntityTypeFactory factory = NULL; if (entityType >= 0 && entityType <= LAST) { @@ -129,7 +128,12 @@ EntityItem* EntityTypes::constructEntityItem(const unsigned char* data, int byte EntityItemID tempEntityID(actualID); EntityItemProperties tempProperties; - tempProperties.setCreated(usecTimestampNow()); // this is temporary... + + // we set the Creation and Edit times to 'now', but if the server submits an earlier Creation time + // then it will be accepted + quint64 now = usecTimestampNow(); + tempProperties.setCreated(now); + tempProperties.setLastEdited(now); return constructEntityItem(entityType, tempEntityID, tempProperties); } From 2be3b73e8c81da64f53fe10379f426d8c9fa9e91 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 17 Dec 2014 12:32:52 -0800 Subject: [PATCH 167/258] move TextRender to libraries/render-utils --- interface/src/Application.cpp | 2 +- interface/src/Util.cpp | 6 +++--- interface/src/avatar/Avatar.cpp | 2 +- interface/src/avatar/MyAvatar.cpp | 2 +- interface/src/devices/PrioVR.cpp | 2 +- interface/src/entities/RenderableTextEntityItem.cpp | 2 +- interface/src/ui/BandwidthMeter.h | 2 +- interface/src/ui/overlays/Text3DOverlay.cpp | 3 ++- interface/src/ui/overlays/TextOverlay.cpp | 2 +- .../src/ui => libraries/render-utils/src}/TextRenderer.cpp | 3 ++- .../src/ui => libraries/render-utils/src}/TextRenderer.h | 7 ++++--- 11 files changed, 18 insertions(+), 15 deletions(-) rename {interface/src/ui => libraries/render-utils/src}/TextRenderer.cpp (99%) rename {interface/src/ui => libraries/render-utils/src}/TextRenderer.h (97%) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 1453cec53b..62f06f81d5 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -73,6 +73,7 @@ #include #include #include +#include #include #include @@ -109,7 +110,6 @@ #include "ui/InfoView.h" #include "ui/Snapshot.h" #include "ui/Stats.h" -#include "ui/TextRenderer.h" diff --git a/interface/src/Util.cpp b/interface/src/Util.cpp index 6d40726f14..458640820b 100644 --- a/interface/src/Util.cpp +++ b/interface/src/Util.cpp @@ -19,12 +19,12 @@ #include #include -#include - #include +#include +#include + #include "InterfaceConfig.h" -#include "ui/TextRenderer.h" #include "VoxelConstants.h" #include "world.h" #include "Application.h" diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index 51fde3df43..81d7920783 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -30,6 +30,7 @@ #include #include #include +#include #include #include "Application.h" @@ -42,7 +43,6 @@ #include "Recorder.h" #include "world.h" #include "devices/OculusManager.h" -#include "ui/TextRenderer.h" using namespace std; diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 6976e26e86..37afd404dc 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -30,6 +30,7 @@ #include #include #include +#include #include "Application.h" #include "Audio.h" @@ -41,7 +42,6 @@ #include "Recorder.h" #include "devices/Faceshift.h" #include "devices/OculusManager.h" -#include "ui/TextRenderer.h" using namespace std; diff --git a/interface/src/devices/PrioVR.cpp b/interface/src/devices/PrioVR.cpp index d3e985d259..0417a50527 100644 --- a/interface/src/devices/PrioVR.cpp +++ b/interface/src/devices/PrioVR.cpp @@ -14,11 +14,11 @@ #include #include +#include #include "Application.h" #include "PrioVR.h" #include "scripting/JoystickScriptingInterface.h" -#include "ui/TextRenderer.h" #ifdef HAVE_PRIOVR const unsigned int SERIAL_LIST[] = { 0x00000001, 0x00000000, 0x00000008, 0x00000009, 0x0000000A, diff --git a/interface/src/entities/RenderableTextEntityItem.cpp b/interface/src/entities/RenderableTextEntityItem.cpp index 5a3d5df8f9..24f4a71295 100644 --- a/interface/src/entities/RenderableTextEntityItem.cpp +++ b/interface/src/entities/RenderableTextEntityItem.cpp @@ -13,9 +13,9 @@ #include #include +#include #include "RenderableTextEntityItem.h" -#include "ui/TextRenderer.h" const int FIXED_FONT_POINT_SIZE = 40; const float LINE_SCALE_RATIO = 1.2f; diff --git a/interface/src/ui/BandwidthMeter.h b/interface/src/ui/BandwidthMeter.h index 09353512d1..9931355f8e 100644 --- a/interface/src/ui/BandwidthMeter.h +++ b/interface/src/ui/BandwidthMeter.h @@ -16,7 +16,7 @@ #include -#include "ui/TextRenderer.h" +#include class BandwidthMeter { diff --git a/interface/src/ui/overlays/Text3DOverlay.cpp b/interface/src/ui/overlays/Text3DOverlay.cpp index 41e36cb396..9b80d873f9 100644 --- a/interface/src/ui/overlays/Text3DOverlay.cpp +++ b/interface/src/ui/overlays/Text3DOverlay.cpp @@ -11,9 +11,10 @@ // include this before QGLWidget, which includes an earlier version of OpenGL #include "InterfaceConfig.h" +#include + #include "Application.h" #include "Text3DOverlay.h" -#include "ui/TextRenderer.h" const xColor DEFAULT_BACKGROUND_COLOR = { 0, 0, 0 }; const float DEFAULT_BACKGROUND_ALPHA = 0.7f; diff --git a/interface/src/ui/overlays/TextOverlay.cpp b/interface/src/ui/overlays/TextOverlay.cpp index ae8a7cbcfe..97d910eb64 100644 --- a/interface/src/ui/overlays/TextOverlay.cpp +++ b/interface/src/ui/overlays/TextOverlay.cpp @@ -13,9 +13,9 @@ #include #include +#include #include "TextOverlay.h" -#include "ui/TextRenderer.h" TextOverlay::TextOverlay() : _backgroundColor(DEFAULT_BACKGROUND_COLOR), diff --git a/interface/src/ui/TextRenderer.cpp b/libraries/render-utils/src/TextRenderer.cpp similarity index 99% rename from interface/src/ui/TextRenderer.cpp rename to libraries/render-utils/src/TextRenderer.cpp index fce4c76c0d..34098c6862 100644 --- a/interface/src/ui/TextRenderer.cpp +++ b/libraries/render-utils/src/TextRenderer.cpp @@ -9,6 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +#include + #include #include #include @@ -18,7 +20,6 @@ #include #include -#include "InterfaceConfig.h" #include "TextRenderer.h" #include "glm/glm.hpp" diff --git a/interface/src/ui/TextRenderer.h b/libraries/render-utils/src/TextRenderer.h similarity index 97% rename from interface/src/ui/TextRenderer.h rename to libraries/render-utils/src/TextRenderer.h index 2ffd8b24b7..078efb0463 100644 --- a/interface/src/ui/TextRenderer.h +++ b/libraries/render-utils/src/TextRenderer.h @@ -12,6 +12,8 @@ #ifndef hifi_TextRenderer_h #define hifi_TextRenderer_h +#include + #include #include #include @@ -19,11 +21,10 @@ #include #include -#include "gpu/Resource.h" -#include "gpu/Stream.h" +#include +#include -#include "InterfaceConfig.h" // a special "character" that renders as a solid block const char SOLID_BLOCK_CHAR = 127; From cb7f5a5b45b072245d05c873d2b2f60a5e1c586e Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Wed, 17 Dec 2014 12:41:58 -0800 Subject: [PATCH 168/258] Roll gridTool.js back temporarily --- examples/libraries/gridTool.js | 74 +++++----------------------------- 1 file changed, 11 insertions(+), 63 deletions(-) diff --git a/examples/libraries/gridTool.js b/examples/libraries/gridTool.js index b1c258dc31..7d98befec8 100644 --- a/examples/libraries/gridTool.js +++ b/examples/libraries/gridTool.js @@ -1,9 +1,3 @@ -var SETTING_GRID_VISIBLE = 'gridVisible'; -var SETTING_GRID_SNAP_TO_GRID = 'gridSnapToGrid'; -var SETTING_GRID_MINOR_WIDTH= 'gridMinorWidth'; -var SETTING_GRID_MAJOR_EVERY = 'gridMajorEvery'; -var SETTING_GRID_COLOR = 'gridColor'; - Grid = function(opts) { var that = {}; @@ -18,6 +12,9 @@ Grid = function(opts) { var worldSize = 16384; + var minorGridWidth = 0.5; + var majorGridWidth = 1.5; + var snapToGrid = false; var gridOverlay = Overlays.addOverlay("grid", { @@ -26,7 +23,7 @@ Grid = function(opts) { color: { red: 0, green: 0, blue: 128 }, alpha: 1.0, rotation: Quat.fromPitchYawRollDegrees(90, 0, 0), - minorGridSpacing: 0.1, + minorGridWidth: 0.1, majorGridEvery: 2, }); @@ -43,37 +40,16 @@ Grid = function(opts) { that.getSnapToGrid = function() { return snapToGrid; }; that.setEnabled = function(enabled) { - if (that.enabled != enabled) { - that.enabled = enabled; - - if (enabled) { - if (selectionManager.hasSelection()) { - that.setPosition(selectionManager.getBottomPosition()); - } else { - that.setPosition(MyAvatar.position); - } - } - - updateGrid(); - } + that.enabled = enabled; + updateGrid(); } that.setVisible = function(visible, noUpdate) { - if (visible != that.visible) { - that.visible = visible; - updateGrid(); + that.visible = visible; + updateGrid(); - if (visible) { - if (selectionManager.hasSelection()) { - that.setPosition(selectionManager.getBottomPosition()); - } else { - that.setPosition(MyAvatar.position); - } - } - - if (!noUpdate) { - that.emitUpdate(); - } + if (!noUpdate) { + that.emitUpdate(); } } @@ -205,43 +181,15 @@ Grid = function(opts) { } function cleanup() { - saveSettings(); - Overlays.deleteOverlay(gridOverlay); } - function loadSettings() { - that.setVisible(Settings.getValue(SETTING_GRID_VISIBLE) == "true", true); - snapToGrid = Settings.getValue(SETTING_GRID_SNAP_TO_GRID) == "true"; - minorGridSpacing = parseFloat(Settings.getValue(SETTING_GRID_MINOR_WIDTH), 10); - majorGridEvery = parseInt(Settings.getValue(SETTING_GRID_MAJOR_EVERY), 10); - try { - var newColor = JSON.parse(Settings.getValue(SETTING_GRID_COLOR)); - if (newColor.red !== undefined && newColor.green !== undefined && newColor.blue !== undefined) { - gridColor.red = newColor.red; - gridColor.green = newColor.green; - gridColor.blue = newColor.blue; - } - } catch (e) { - } - updateGrid(); - } - - function saveSettings() { - Settings.setValue(SETTING_GRID_VISIBLE, that.visible); - Settings.setValue(SETTING_GRID_SNAP_TO_GRID, snapToGrid); - Settings.setValue(SETTING_GRID_MINOR_WIDTH, minorGridSpacing); - Settings.setValue(SETTING_GRID_MAJOR_EVERY, majorGridEvery); - Settings.setValue(SETTING_GRID_COLOR, JSON.stringify(gridColor)); - } - that.addListener = function(callback) { that.onUpdate = callback; } Script.scriptEnding.connect(cleanup); - - loadSettings(); + updateGrid(); that.onUpdate = null; From 9f9b8bcb68432c8a511f17d8f1f1b63b1c6d0d54 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 17 Dec 2014 12:54:41 -0800 Subject: [PATCH 169/258] move interface/entities to libraries/entities-renderer --- interface/CMakeLists.txt | 3 +- interface/src/Application.h | 2 +- libraries/entities-renderer/CMakeLists.txt | 37 +++++++++++++++++++ .../src}/EntityTreeRenderer.cpp | 0 .../src}/EntityTreeRenderer.h | 0 .../src}/RenderableBoxEntityItem.cpp | 0 .../src}/RenderableBoxEntityItem.h | 0 .../src}/RenderableLightEntityItem.cpp | 0 .../src}/RenderableLightEntityItem.h | 0 .../src}/RenderableModelEntityItem.cpp | 0 .../src}/RenderableModelEntityItem.h | 0 .../src}/RenderableSphereEntityItem.cpp | 0 .../src}/RenderableSphereEntityItem.h | 0 .../src}/RenderableTextEntityItem.cpp | 0 .../src}/RenderableTextEntityItem.h | 0 15 files changed, 40 insertions(+), 2 deletions(-) create mode 100644 libraries/entities-renderer/CMakeLists.txt rename {interface/src/entities => libraries/entities-renderer/src}/EntityTreeRenderer.cpp (100%) rename {interface/src/entities => libraries/entities-renderer/src}/EntityTreeRenderer.h (100%) rename {interface/src/entities => libraries/entities-renderer/src}/RenderableBoxEntityItem.cpp (100%) rename {interface/src/entities => libraries/entities-renderer/src}/RenderableBoxEntityItem.h (100%) rename {interface/src/entities => libraries/entities-renderer/src}/RenderableLightEntityItem.cpp (100%) rename {interface/src/entities => libraries/entities-renderer/src}/RenderableLightEntityItem.h (100%) rename {interface/src/entities => libraries/entities-renderer/src}/RenderableModelEntityItem.cpp (100%) rename {interface/src/entities => libraries/entities-renderer/src}/RenderableModelEntityItem.h (100%) rename {interface/src/entities => libraries/entities-renderer/src}/RenderableSphereEntityItem.cpp (100%) rename {interface/src/entities => libraries/entities-renderer/src}/RenderableSphereEntityItem.h (100%) rename {interface/src/entities => libraries/entities-renderer/src}/RenderableTextEntityItem.cpp (100%) rename {interface/src/entities => libraries/entities-renderer/src}/RenderableTextEntityItem.h (100%) diff --git a/interface/CMakeLists.txt b/interface/CMakeLists.txt index ffc401ba63..8c7b7b2211 100644 --- a/interface/CMakeLists.txt +++ b/interface/CMakeLists.txt @@ -107,7 +107,8 @@ endif() add_executable(${TARGET_NAME} MACOSX_BUNDLE ${INTERFACE_SRCS} ${QM}) # link required hifi libraries -link_hifi_libraries(shared octree voxels gpu fbx metavoxels networking entities avatars audio animation script-engine physics render-utils) +link_hifi_libraries(shared octree voxels gpu fbx metavoxels networking entities avatars audio animation script-engine physics + render-utils entities-renderer) # find any optional and required libraries find_package(ZLIB REQUIRED) diff --git a/interface/src/Application.h b/interface/src/Application.h index d192a9abe6..7a727d07b5 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -36,6 +36,7 @@ #include #include #include +#include #include #include #include @@ -62,7 +63,6 @@ #include "avatar/MyAvatar.h" #include "devices/PrioVR.h" #include "devices/SixenseManager.h" -#include "entities/EntityTreeRenderer.h" #include "scripting/ControllerScriptingInterface.h" #include "ui/BandwidthDialog.h" #include "ui/BandwidthMeter.h" diff --git a/libraries/entities-renderer/CMakeLists.txt b/libraries/entities-renderer/CMakeLists.txt new file mode 100644 index 0000000000..5744ea0b7b --- /dev/null +++ b/libraries/entities-renderer/CMakeLists.txt @@ -0,0 +1,37 @@ +set(TARGET_NAME entities-renderer) + +# use setup_hifi_library macro to setup our project and link appropriate Qt modules +setup_hifi_library(Widgets OpenGL Network Script) + +include_glm() + +link_hifi_libraries(shared gpu) +if (APPLE) + # link in required OS X frameworks and include the right GL headers + find_library(OpenGL OpenGL) + + #target_link_libraries(${TARGET_NAME} ${OpenGL}) + +else (APPLE) + find_package(OpenGL REQUIRED) + + if (${OPENGL_INCLUDE_DIR}) + include_directories(SYSTEM "${OPENGL_INCLUDE_DIR}") + endif () + + # link target to external libraries + if (WIN32) + find_package(GLEW REQUIRED) + include_directories(${GLEW_INCLUDE_DIRS}) + + find_package(GLUT REQUIRED) + include_directories(SYSTEM "${GLUT_INCLUDE_DIRS}") + + # we're using static GLEW, so define GLEW_STATIC + add_definitions(-DGLEW_STATIC) + target_link_libraries(${TARGET_NAME} "${GLEW_LIBRARIES}") + endif() +endif (APPLE) + +# call macro to link our dependencies and bubble them up via a property on our target +link_shared_dependencies() diff --git a/interface/src/entities/EntityTreeRenderer.cpp b/libraries/entities-renderer/src/EntityTreeRenderer.cpp similarity index 100% rename from interface/src/entities/EntityTreeRenderer.cpp rename to libraries/entities-renderer/src/EntityTreeRenderer.cpp diff --git a/interface/src/entities/EntityTreeRenderer.h b/libraries/entities-renderer/src/EntityTreeRenderer.h similarity index 100% rename from interface/src/entities/EntityTreeRenderer.h rename to libraries/entities-renderer/src/EntityTreeRenderer.h diff --git a/interface/src/entities/RenderableBoxEntityItem.cpp b/libraries/entities-renderer/src/RenderableBoxEntityItem.cpp similarity index 100% rename from interface/src/entities/RenderableBoxEntityItem.cpp rename to libraries/entities-renderer/src/RenderableBoxEntityItem.cpp diff --git a/interface/src/entities/RenderableBoxEntityItem.h b/libraries/entities-renderer/src/RenderableBoxEntityItem.h similarity index 100% rename from interface/src/entities/RenderableBoxEntityItem.h rename to libraries/entities-renderer/src/RenderableBoxEntityItem.h diff --git a/interface/src/entities/RenderableLightEntityItem.cpp b/libraries/entities-renderer/src/RenderableLightEntityItem.cpp similarity index 100% rename from interface/src/entities/RenderableLightEntityItem.cpp rename to libraries/entities-renderer/src/RenderableLightEntityItem.cpp diff --git a/interface/src/entities/RenderableLightEntityItem.h b/libraries/entities-renderer/src/RenderableLightEntityItem.h similarity index 100% rename from interface/src/entities/RenderableLightEntityItem.h rename to libraries/entities-renderer/src/RenderableLightEntityItem.h diff --git a/interface/src/entities/RenderableModelEntityItem.cpp b/libraries/entities-renderer/src/RenderableModelEntityItem.cpp similarity index 100% rename from interface/src/entities/RenderableModelEntityItem.cpp rename to libraries/entities-renderer/src/RenderableModelEntityItem.cpp diff --git a/interface/src/entities/RenderableModelEntityItem.h b/libraries/entities-renderer/src/RenderableModelEntityItem.h similarity index 100% rename from interface/src/entities/RenderableModelEntityItem.h rename to libraries/entities-renderer/src/RenderableModelEntityItem.h diff --git a/interface/src/entities/RenderableSphereEntityItem.cpp b/libraries/entities-renderer/src/RenderableSphereEntityItem.cpp similarity index 100% rename from interface/src/entities/RenderableSphereEntityItem.cpp rename to libraries/entities-renderer/src/RenderableSphereEntityItem.cpp diff --git a/interface/src/entities/RenderableSphereEntityItem.h b/libraries/entities-renderer/src/RenderableSphereEntityItem.h similarity index 100% rename from interface/src/entities/RenderableSphereEntityItem.h rename to libraries/entities-renderer/src/RenderableSphereEntityItem.h diff --git a/interface/src/entities/RenderableTextEntityItem.cpp b/libraries/entities-renderer/src/RenderableTextEntityItem.cpp similarity index 100% rename from interface/src/entities/RenderableTextEntityItem.cpp rename to libraries/entities-renderer/src/RenderableTextEntityItem.cpp diff --git a/interface/src/entities/RenderableTextEntityItem.h b/libraries/entities-renderer/src/RenderableTextEntityItem.h similarity index 100% rename from interface/src/entities/RenderableTextEntityItem.h rename to libraries/entities-renderer/src/RenderableTextEntityItem.h From 881119ebf3f87112db8c29a904fb216517d393bc Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 17 Dec 2014 13:23:12 -0800 Subject: [PATCH 170/258] removed dead code --- .../script-engine/src/AbstractScriptingServicesInterface.h | 2 -- 1 file changed, 2 deletions(-) diff --git a/libraries/script-engine/src/AbstractScriptingServicesInterface.h b/libraries/script-engine/src/AbstractScriptingServicesInterface.h index 5e7ad81f67..9d24531b60 100644 --- a/libraries/script-engine/src/AbstractScriptingServicesInterface.h +++ b/libraries/script-engine/src/AbstractScriptingServicesInterface.h @@ -12,8 +12,6 @@ #ifndef hifi_AbstractScriptingServicesInterface_h #define hifi_AbstractScriptingServicesInterface_h -//#include - class AbstractControllerScriptingInterface; class Transform; class ScriptEngine; From 7db350eac29057728fd28e5a415f62b7ec8758bb Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 17 Dec 2014 14:07:26 -0800 Subject: [PATCH 171/258] remove calls to glut in entities --- .../src/EntityTreeRenderer.cpp | 29 +++++++++---------- 1 file changed, 14 insertions(+), 15 deletions(-) diff --git a/libraries/entities-renderer/src/EntityTreeRenderer.cpp b/libraries/entities-renderer/src/EntityTreeRenderer.cpp index 5654b416f1..7253b96480 100644 --- a/libraries/entities-renderer/src/EntityTreeRenderer.cpp +++ b/libraries/entities-renderer/src/EntityTreeRenderer.cpp @@ -11,8 +11,6 @@ #include -#include // TODO - we need to get rid of this ASAP - #include #include @@ -20,6 +18,7 @@ #include #include +#include #include #include #include @@ -358,7 +357,7 @@ void EntityTreeRenderer::renderElementProxy(EntityTreeElement* entityTreeElement glColor3f(1.0f, 0.0f, 0.0f); glPushMatrix(); glTranslatef(elementCenter.x, elementCenter.y, elementCenter.z); - glutWireCube(elementSize); + DependencyManager::get()->renderWireCube(elementSize); glPopMatrix(); if (_displayElementChildProxies) { @@ -368,49 +367,49 @@ void EntityTreeRenderer::renderElementProxy(EntityTreeElement* entityTreeElement glColor3f(1.0f, 1.0f, 0.0f); glPushMatrix(); glTranslatef(elementCenter.x - quarterSize, elementCenter.y - quarterSize, elementCenter.z - quarterSize); - glutWireCube(halfSize); + DependencyManager::get()->renderWireCube(halfSize); glPopMatrix(); glColor3f(1.0f, 0.0f, 1.0f); glPushMatrix(); glTranslatef(elementCenter.x + quarterSize, elementCenter.y - quarterSize, elementCenter.z - quarterSize); - glutWireCube(halfSize); + DependencyManager::get()->renderWireCube(halfSize); glPopMatrix(); glColor3f(0.0f, 1.0f, 0.0f); glPushMatrix(); glTranslatef(elementCenter.x - quarterSize, elementCenter.y + quarterSize, elementCenter.z - quarterSize); - glutWireCube(halfSize); + DependencyManager::get()->renderWireCube(halfSize); glPopMatrix(); glColor3f(0.0f, 0.0f, 1.0f); glPushMatrix(); glTranslatef(elementCenter.x - quarterSize, elementCenter.y - quarterSize, elementCenter.z + quarterSize); - glutWireCube(halfSize); + DependencyManager::get()->renderWireCube(halfSize); glPopMatrix(); glColor3f(1.0f, 1.0f, 1.0f); glPushMatrix(); glTranslatef(elementCenter.x + quarterSize, elementCenter.y + quarterSize, elementCenter.z + quarterSize); - glutWireCube(halfSize); + DependencyManager::get()->renderWireCube(halfSize); glPopMatrix(); glColor3f(0.0f, 0.5f, 0.5f); glPushMatrix(); glTranslatef(elementCenter.x - quarterSize, elementCenter.y + quarterSize, elementCenter.z + quarterSize); - glutWireCube(halfSize); + DependencyManager::get()->renderWireCube(halfSize); glPopMatrix(); glColor3f(0.5f, 0.0f, 0.0f); glPushMatrix(); glTranslatef(elementCenter.x + quarterSize, elementCenter.y - quarterSize, elementCenter.z + quarterSize); - glutWireCube(halfSize); + DependencyManager::get()->renderWireCube(halfSize); glPopMatrix(); glColor3f(0.0f, 0.5f, 0.0f); glPushMatrix(); glTranslatef(elementCenter.x + quarterSize, elementCenter.y + quarterSize, elementCenter.z - quarterSize); - glutWireCube(halfSize); + DependencyManager::get()->renderWireCube(halfSize); glPopMatrix(); } } @@ -437,14 +436,14 @@ void EntityTreeRenderer::renderProxies(const EntityItem* entity, RenderArgs* arg glColor4f(1.0f, 1.0f, 0.0f, 1.0f); glPushMatrix(); glTranslatef(maxCenter.x, maxCenter.y, maxCenter.z); - glutWireCube(maxCube.getScale()); + DependencyManager::get()->renderWireCube(maxCube.getScale()); glPopMatrix(); // draw the min bounding cube glColor4f(0.0f, 1.0f, 0.0f, 1.0f); glPushMatrix(); glTranslatef(minCenter.x, minCenter.y, minCenter.z); - glutWireCube(minCube.getScale()); + DependencyManager::get()->renderWireCube(minCube.getScale()); glPopMatrix(); // draw the entityBox bounding box @@ -452,7 +451,7 @@ void EntityTreeRenderer::renderProxies(const EntityItem* entity, RenderArgs* arg glPushMatrix(); glTranslatef(entityBoxCenter.x, entityBoxCenter.y, entityBoxCenter.z); glScalef(entityBoxScale.x, entityBoxScale.y, entityBoxScale.z); - glutWireCube(1.0f); + DependencyManager::get()->renderWireCube(1.0f); glPopMatrix(); @@ -470,7 +469,7 @@ void EntityTreeRenderer::renderProxies(const EntityItem* entity, RenderArgs* arg glm::vec3 positionToCenter = center - position; glTranslatef(positionToCenter.x, positionToCenter.y, positionToCenter.z); glScalef(dimensions.x, dimensions.y, dimensions.z); - glutWireCube(1.0f); + DependencyManager::get()->renderWireCube(1.0f); glPopMatrix(); glPopMatrix(); } From 1e5c44f117c9d3ea47681feabaa86caa7e598bbf Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 17 Dec 2014 15:48:49 -0800 Subject: [PATCH 172/258] accept changes with the same Edit timestamp --- libraries/entities/src/EntityItem.cpp | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/libraries/entities/src/EntityItem.cpp b/libraries/entities/src/EntityItem.cpp index 22cfeb3674..f62cd278c8 100644 --- a/libraries/entities/src/EntityItem.cpp +++ b/libraries/entities/src/EntityItem.cpp @@ -109,9 +109,6 @@ EntityItem::EntityItem(const EntityItemID& entityItemID, const EntityItemPropert _changedOnServer = 0; initFromEntityItemID(entityItemID); setProperties(properties, true); // force copy - if (_lastEdited == 0) { - _lastEdited = _created; - } } EntityPropertyFlags EntityItem::getEntityProperties(EncodeBitstreamParams& params) const { @@ -424,14 +421,14 @@ int EntityItem::readEntityDataFromBuffer(const unsigned char* data, int bytesLef if (fromSameServerEdit) { // If this is from the same sever packet, then check against any local changes since we got // the most recent packet from this server time - if (_lastEdited >= _lastEditedFromRemote) { + if (_lastEdited > _lastEditedFromRemote) { ignoreServerPacket = true; } } else { // If this isn't from the same sever packet, then honor our skew adjusted times... // If we've changed our local tree more recently than the new data from this packet // then we will not be changing our values, instead we just read and skip the data - if (_lastEdited >= lastEditedFromBufferAdjusted) { + if (_lastEdited > lastEditedFromBufferAdjusted) { ignoreServerPacket = true; } } From 44ebf37510e971cc6c0410ebc6ee7b5b4e4cb052 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 17 Dec 2014 15:52:34 -0800 Subject: [PATCH 173/258] handle case where obj at rest but still falls --- libraries/entities/src/EntityItem.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libraries/entities/src/EntityItem.cpp b/libraries/entities/src/EntityItem.cpp index f62cd278c8..4ad2770d05 100644 --- a/libraries/entities/src/EntityItem.cpp +++ b/libraries/entities/src/EntityItem.cpp @@ -650,7 +650,7 @@ void EntityItem::simulate(const quint64& now) { } } - if (hasVelocity()) { + if (hasVelocity() || hasGravity()) { glm::vec3 position = getPosition(); glm::vec3 velocity = getVelocity(); glm::vec3 newPosition = position + (velocity * timeElapsed); @@ -731,7 +731,7 @@ void EntityItem::simulate(const quint64& now) { } bool EntityItem::isMoving() const { - return hasVelocity() || hasAngularVelocity(); + return hasVelocity() (hasGravity() && !isRestingOnSurface()) || hasAngularVelocity(); } bool EntityItem::lifetimeHasExpired() const { From ef42203481b67d9f368dee3484f84345bd2f8960 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Wed, 17 Dec 2014 15:58:52 -0800 Subject: [PATCH 174/258] add wire cube implementation to GeometryCache and DeferredLightingEffect --- libraries/render-utils/src/DeferredLightingEffect.cpp | 2 +- libraries/render-utils/src/GeometryCache.cpp | 8 ++++++-- libraries/render-utils/src/GeometryCache.h | 2 +- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/libraries/render-utils/src/DeferredLightingEffect.cpp b/libraries/render-utils/src/DeferredLightingEffect.cpp index 14d383418f..065ca3a741 100644 --- a/libraries/render-utils/src/DeferredLightingEffect.cpp +++ b/libraries/render-utils/src/DeferredLightingEffect.cpp @@ -68,7 +68,7 @@ void DeferredLightingEffect::renderSolidSphere(float radius, int slices, int sta void DeferredLightingEffect::renderWireSphere(float radius, int slices, int stacks) { bindSimpleProgram(); - glutWireSphere(radius, slices, stacks); + DependencyManager::get()->renderSphere(radius, slices, stacks, false); releaseSimpleProgram(); } diff --git a/libraries/render-utils/src/GeometryCache.cpp b/libraries/render-utils/src/GeometryCache.cpp index 56092945a2..a770d942fe 100644 --- a/libraries/render-utils/src/GeometryCache.cpp +++ b/libraries/render-utils/src/GeometryCache.cpp @@ -119,7 +119,7 @@ const int NUM_COORDS_PER_VERTEX = 3; const int NUM_BYTES_PER_VERTEX = NUM_COORDS_PER_VERTEX * sizeof(GLfloat); const int NUM_BYTES_PER_INDEX = sizeof(GLushort); -void GeometryCache::renderSphere(float radius, int slices, int stacks) { +void GeometryCache::renderSphere(float radius, int slices, int stacks, bool solid) { VerticesIndices& vbo = _sphereVBOs[IntPair(slices, stacks)]; int vertices = slices * (stacks - 1) + 2; int indices = slices * stacks * NUM_VERTICES_PER_TRIANGULATED_QUAD; @@ -211,7 +211,11 @@ void GeometryCache::renderSphere(float radius, int slices, int stacks) { glPushMatrix(); glScalef(radius, radius, radius); - glDrawRangeElementsEXT(GL_TRIANGLES, 0, vertices - 1, indices, GL_UNSIGNED_SHORT, 0); + if (solid) { + glDrawRangeElementsEXT(GL_TRIANGLES, 0, vertices - 1, indices, GL_UNSIGNED_SHORT, 0); + } else { + glDrawRangeElementsEXT(GL_LINES, 0, vertices - 1, indices, GL_UNSIGNED_SHORT, 0); + } glPopMatrix(); glDisableClientState(GL_VERTEX_ARRAY); diff --git a/libraries/render-utils/src/GeometryCache.h b/libraries/render-utils/src/GeometryCache.h index 97f24f94a3..f0045c10bf 100644 --- a/libraries/render-utils/src/GeometryCache.h +++ b/libraries/render-utils/src/GeometryCache.h @@ -38,7 +38,7 @@ class GeometryCache : public ResourceCache { public: void renderHemisphere(int slices, int stacks); - void renderSphere(float radius, int slices, int stacks); + void renderSphere(float radius, int slices, int stacks, bool solid = true); void renderSquare(int xDivisions, int yDivisions); void renderHalfCylinder(int slices, int stacks); void renderCone(float base, float height, int slices, int stacks); From 75d468da9e14f0f1a8b9a65bb9ab357e36f01ed9 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 17 Dec 2014 15:59:16 -0800 Subject: [PATCH 175/258] set _lastEdited to _created rather than to zero --- libraries/entities/src/EntityItem.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/libraries/entities/src/EntityItem.cpp b/libraries/entities/src/EntityItem.cpp index 4ad2770d05..a72eb86b0c 100644 --- a/libraries/entities/src/EntityItem.cpp +++ b/libraries/entities/src/EntityItem.cpp @@ -368,10 +368,9 @@ int EntityItem::readEntityDataFromBuffer(const unsigned char* data, int bytesLef createdFromBuffer -= clockSkew; if (createdFromBuffer < _created) { - // the server claims that this entity has an older creation time - // so we accept it and clear _lastEdited + // the server claims that this entity has an older creation time so we accept it _created = createdFromBuffer; - _lastEdited = 0; + _lastEdited = _created; } if (wantDebug) { From 756d09d895465452d27255565805cb3968b5f696 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Wed, 17 Dec 2014 16:06:15 -0800 Subject: [PATCH 176/258] fix typo that broke the build --- libraries/entities/src/EntityItem.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/entities/src/EntityItem.cpp b/libraries/entities/src/EntityItem.cpp index a72eb86b0c..cd34cd55c6 100644 --- a/libraries/entities/src/EntityItem.cpp +++ b/libraries/entities/src/EntityItem.cpp @@ -730,7 +730,7 @@ void EntityItem::simulate(const quint64& now) { } bool EntityItem::isMoving() const { - return hasVelocity() (hasGravity() && !isRestingOnSurface()) || hasAngularVelocity(); + return hasVelocity() || (hasGravity() && !isRestingOnSurface()) || hasAngularVelocity(); } bool EntityItem::lifetimeHasExpired() const { From adf51bfeb82df214c6b5e76899cbee63ec104e3a Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Wed, 17 Dec 2014 16:41:28 -0800 Subject: [PATCH 177/258] temp disable visage to get to C++11 support --- cmake/modules/FindVisage.cmake | 13 +++++++------ interface/CMakeLists.txt | 3 +-- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/cmake/modules/FindVisage.cmake b/cmake/modules/FindVisage.cmake index 96176a2648..2b288f4681 100644 --- a/cmake/modules/FindVisage.cmake +++ b/cmake/modules/FindVisage.cmake @@ -32,9 +32,10 @@ if (APPLE) find_library(VISAGE_VISION_LIBRARY NAME vsvision PATH_SUFFIXES lib HINTS ${VISAGE_SEARCH_DIRS}) find_library(VISAGE_OPENCV_LIBRARY NAME OpenCV PATH_SUFFIXES dependencies/OpenCV_MacOSX/lib HINTS ${VISAGE_SEARCH_DIRS}) - find_library(AppKit AppKit) - find_library(QuartzCore QuartzCore) + find_library(CoreVideo CoreVideo) find_library(QTKit QTKit) + find_library(IOKit IOKit) + elseif (WIN32) find_path(VISAGE_XML_INCLUDE_DIR libxml/xmlreader.h PATH_SUFFIXES dependencies/libxml2/include HINTS ${VISAGE_SEARCH_DIRS}) find_path(VISAGE_OPENCV_INCLUDE_DIR opencv/cv.h PATH_SUFFIXES dependencies/OpenCV/include HINTS ${VISAGE_SEARCH_DIRS}) @@ -49,19 +50,19 @@ include(FindPackageHandleStandardArgs) list(APPEND VISAGE_ARGS_LIST VISAGE_BASE_INCLUDE_DIR VISAGE_XML_INCLUDE_DIR VISAGE_OPENCV_INCLUDE_DIR VISAGE_OPENCV2_INCLUDE_DIR - VISAGE_CORE_LIBRARY VISAGE_VISION_LIBRARY VISAGE_OPENCV_LIBRARY) + VISAGE_CORE_LIBRARY VISAGE_VISION_LIBRARY) if (APPLE) - list(APPEND VISAGE_ARGS_LIST QuartzCore AppKit QTKit) + list(APPEND VISAGE_ARGS_LIST CoreVideo QTKit IOKit) endif () find_package_handle_standard_args(Visage DEFAULT_MSG ${VISAGE_ARGS_LIST}) set(VISAGE_INCLUDE_DIRS "${VISAGE_XML_INCLUDE_DIR}" "${VISAGE_OPENCV_INCLUDE_DIR}" "${VISAGE_OPENCV2_INCLUDE_DIR}" "${VISAGE_BASE_INCLUDE_DIR}") -set(VISAGE_LIBRARIES "${VISAGE_CORE_LIBRARY}" "${VISAGE_VISION_LIBRARY}" "${VISAGE_OPENCV_LIBRARY}") +set(VISAGE_LIBRARIES "${VISAGE_CORE_LIBRARY}" "${VISAGE_VISION_LIBRARY}") if (APPLE) - list(APPEND VISAGE_LIBRARIES ${QuartzCore} ${AppKit} ${QTKit}) + list(APPEND VISAGE_LIBRARIES "${CoreVideo}" "${QTKit}" "${IOKit}") endif () mark_as_advanced(VISAGE_INCLUDE_DIRS VISAGE_LIBRARIES) diff --git a/interface/CMakeLists.txt b/interface/CMakeLists.txt index ffc401ba63..78f4cbd6a6 100644 --- a/interface/CMakeLists.txt +++ b/interface/CMakeLists.txt @@ -2,7 +2,7 @@ set(TARGET_NAME interface) project(${TARGET_NAME}) # set a default root dir for each of our optional externals if it was not passed -set(OPTIONAL_EXTERNALS "Faceshift" "LibOVR" "PrioVR" "Sixense" "Visage" "LeapMotion" "RtMidi" "Qxmpp" "SDL2" "Gverb") +set(OPTIONAL_EXTERNALS "Faceshift" "LibOVR" "PrioVR" "Sixense" "LeapMotion" "RtMidi" "Qxmpp" "SDL2" "Gverb") foreach(EXTERNAL ${OPTIONAL_EXTERNALS}) string(TOUPPER ${EXTERNAL} ${EXTERNAL}_UPPERCASE) if (NOT ${${EXTERNAL}_UPPERCASE}_ROOT_DIR) @@ -156,7 +156,6 @@ if (VISAGE_FOUND AND NOT DISABLE_VISAGE AND APPLE) SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wno-comment") find_library(AVFoundation AVFoundation) find_library(CoreMedia CoreMedia) - find_library(NEW_STD_LIBRARY libc++.dylib /usr/lib/) target_link_libraries(${TARGET_NAME} ${AVFoundation} ${CoreMedia} ${NEW_STD_LIBRARY}) endif () From b202eb7dae01b9a878f3e7c87d349ac9b5db63b6 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 18 Dec 2014 09:14:44 -0800 Subject: [PATCH 178/258] DRY up gpu library/header linking --- libraries/entities-renderer/CMakeLists.txt | 28 +------------- libraries/gpu/CMakeLists.txt | 44 +++++++++++----------- libraries/render-utils/CMakeLists.txt | 26 ------------- 3 files changed, 24 insertions(+), 74 deletions(-) diff --git a/libraries/entities-renderer/CMakeLists.txt b/libraries/entities-renderer/CMakeLists.txt index 5744ea0b7b..1e77afe544 100644 --- a/libraries/entities-renderer/CMakeLists.txt +++ b/libraries/entities-renderer/CMakeLists.txt @@ -5,33 +5,7 @@ setup_hifi_library(Widgets OpenGL Network Script) include_glm() -link_hifi_libraries(shared gpu) -if (APPLE) - # link in required OS X frameworks and include the right GL headers - find_library(OpenGL OpenGL) - - #target_link_libraries(${TARGET_NAME} ${OpenGL}) - -else (APPLE) - find_package(OpenGL REQUIRED) - - if (${OPENGL_INCLUDE_DIR}) - include_directories(SYSTEM "${OPENGL_INCLUDE_DIR}") - endif () - - # link target to external libraries - if (WIN32) - find_package(GLEW REQUIRED) - include_directories(${GLEW_INCLUDE_DIRS}) - - find_package(GLUT REQUIRED) - include_directories(SYSTEM "${GLUT_INCLUDE_DIRS}") - - # we're using static GLEW, so define GLEW_STATIC - add_definitions(-DGLEW_STATIC) - target_link_libraries(${TARGET_NAME} "${GLEW_LIBRARIES}") - endif() -endif (APPLE) +link_hifi_libraries(shared gpu script-engine) # call macro to link our dependencies and bubble them up via a property on our target link_shared_dependencies() diff --git a/libraries/gpu/CMakeLists.txt b/libraries/gpu/CMakeLists.txt index 577f9f7a58..340adcc9e6 100644 --- a/libraries/gpu/CMakeLists.txt +++ b/libraries/gpu/CMakeLists.txt @@ -6,13 +6,32 @@ setup_hifi_library() include_glm() link_hifi_libraries(shared) + if (APPLE) # link in required OS X frameworks and include the right GL headers find_library(OpenGL OpenGL) target_link_libraries(${TARGET_NAME} ${OpenGL}) - -else (APPLE) +elseif (WIN32) + find_package(GLEW REQUIRED) + include_directories(${GLEW_INCLUDE_DIRS}) + + # we're using static GLEW, so define GLEW_STATIC + add_definitions(-DGLEW_STATIC) + + target_link_libraries(${TARGET_NAME} "${GLEW_LIBRARIES}" opengl32.lib) + + # need to bubble up the GLEW_INCLUDE_DIRS + list(APPEND ${TARGET_NAME}_DEPENDENCY_INCLUDES "${GLEW_INCLUDE_DIRS}") + + # try to find the Nsight package and add it to the build if we find it + find_package(NSIGHT) + if (NSIGHT_FOUND) + include_directories(${NSIGHT_INCLUDE_DIRS}) + add_definitions(-DNSIGHT_FOUND) + target_link_libraries(${TARGET_NAME} "${NSIGHT_LIBRARIES}") + endif () +else () find_package(OpenGL REQUIRED) if (${OPENGL_INCLUDE_DIR}) @@ -21,25 +40,8 @@ else (APPLE) target_link_libraries(${TARGET_NAME} "${OPENGL_LIBRARY}") - # link target to external libraries - if (WIN32) - find_package(GLEW REQUIRED) - include_directories(${GLEW_INCLUDE_DIRS}) - - # we're using static GLEW, so define GLEW_STATIC - add_definitions(-DGLEW_STATIC) - - target_link_libraries(${TARGET_NAME} "${GLEW_LIBRARIES}" "${NSIGHT_LIBRARIES}" opengl32.lib) - - # try to find the Nsight package and add it to the build if we find it - find_package(NSIGHT) - if (NSIGHT_FOUND) - include_directories(${NSIGHT_INCLUDE_DIRS}) - add_definitions(-DNSIGHT_FOUND) - target_link_libraries(${TARGET_NAME} "${NSIGHT_LIBRARIES}") - endif () - - endif() + # need to bubble up the OPENGL_INCLUDE_DIR + list(APPEND ${TARGET_NAME}_DEPENDENCY_INCLUDES "${OPENGL_INCLUDE_DIR}") endif (APPLE) # call macro to link our dependencies and bubble them up via a property on our target diff --git a/libraries/render-utils/CMakeLists.txt b/libraries/render-utils/CMakeLists.txt index 0244fa91a6..8d4f85a2ac 100644 --- a/libraries/render-utils/CMakeLists.txt +++ b/libraries/render-utils/CMakeLists.txt @@ -6,32 +6,6 @@ setup_hifi_library(Widgets OpenGL Network Script) include_glm() link_hifi_libraries(shared gpu) -if (APPLE) - # link in required OS X frameworks and include the right GL headers - find_library(OpenGL OpenGL) - - #target_link_libraries(${TARGET_NAME} ${OpenGL}) - -else (APPLE) - find_package(OpenGL REQUIRED) - - if (${OPENGL_INCLUDE_DIR}) - include_directories(SYSTEM "${OPENGL_INCLUDE_DIR}") - endif () - - # link target to external libraries - if (WIN32) - find_package(GLEW REQUIRED) - include_directories(${GLEW_INCLUDE_DIRS}) - - find_package(GLUT REQUIRED) - include_directories(SYSTEM "${GLUT_INCLUDE_DIRS}") - - # we're using static GLEW, so define GLEW_STATIC - add_definitions(-DGLEW_STATIC) - target_link_libraries(${TARGET_NAME} "${GLEW_LIBRARIES}") - endif() -endif (APPLE) # call macro to link our dependencies and bubble them up via a property on our target link_shared_dependencies() From d38c78f2c31f42e22c0ab84feac15e4bbbe1a4c5 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 18 Dec 2014 09:34:04 -0800 Subject: [PATCH 179/258] remove bubbling of linked libraries, cmake does it --- assignment-client/CMakeLists.txt | 2 +- cmake/macros/LinkHifiLibraries.cmake | 9 -------- cmake/macros/LinkSharedDependencies.cmake | 25 +---------------------- cmake/macros/SetupHifiLibrary.cmake | 7 +++++++ cmake/macros/SetupHifiProject.cmake | 7 +++++++ domain-server/CMakeLists.txt | 2 +- libraries/fbx/CMakeLists.txt | 2 +- libraries/networking/CMakeLists.txt | 2 +- libraries/octree/CMakeLists.txt | 2 +- libraries/voxels/CMakeLists.txt | 2 +- 10 files changed, 21 insertions(+), 39 deletions(-) diff --git a/assignment-client/CMakeLists.txt b/assignment-client/CMakeLists.txt index 69ad1cd815..6e31182f0d 100644 --- a/assignment-client/CMakeLists.txt +++ b/assignment-client/CMakeLists.txt @@ -12,7 +12,7 @@ link_hifi_libraries( ) if (UNIX) - list(APPEND ${TARGET_NAME}_LIBRARIES_TO_LINK ${CMAKE_DL_LIBS}) + target_link_libraries(${TARGET_NAME} ${CMAKE_DL_LIBS}) endif (UNIX) link_shared_dependencies() diff --git a/cmake/macros/LinkHifiLibraries.cmake b/cmake/macros/LinkHifiLibraries.cmake index 464af76553..646b680f27 100644 --- a/cmake/macros/LinkHifiLibraries.cmake +++ b/cmake/macros/LinkHifiLibraries.cmake @@ -25,18 +25,9 @@ macro(LINK_HIFI_LIBRARIES) # link the actual library - it is static so don't bubble it up target_link_libraries(${TARGET_NAME} ${HIFI_LIBRARY}) - # ask the library what its dynamic dependencies are and link them - get_target_property(LINKED_TARGET_DEPENDENCY_LIBRARIES ${HIFI_LIBRARY} DEPENDENCY_LIBRARIES) - list(APPEND ${TARGET_NAME}_LIBRARIES_TO_LINK ${LINKED_TARGET_DEPENDENCY_LIBRARIES}) - # ask the library what its include dependencies are and link them get_target_property(LINKED_TARGET_DEPENDENCY_INCLUDES ${HIFI_LIBRARY} DEPENDENCY_INCLUDES) list(APPEND ${TARGET_NAME}_DEPENDENCY_INCLUDES ${LINKED_TARGET_DEPENDENCY_INCLUDES}) - - # ask the library what its qt module dependencies are and link them - get_target_property(LINKED_TARGET_DEPENDENCY_QT_MODULES ${HIFI_LIBRARY} DEPENDENCY_QT_MODULES) - list(APPEND ${TARGET_NAME}_DEPENDENCY_QT_MODULES ${LINKED_TARGET_DEPENDENCY_QT_MODULES}) - endforeach() endmacro(LINK_HIFI_LIBRARIES) \ No newline at end of file diff --git a/cmake/macros/LinkSharedDependencies.cmake b/cmake/macros/LinkSharedDependencies.cmake index fd5461c288..9168c5a921 100644 --- a/cmake/macros/LinkSharedDependencies.cmake +++ b/cmake/macros/LinkSharedDependencies.cmake @@ -9,14 +9,7 @@ # See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html # -macro(LINK_SHARED_DEPENDENCIES) - if (${TARGET_NAME}_LIBRARIES_TO_LINK) - list(REMOVE_DUPLICATES ${TARGET_NAME}_LIBRARIES_TO_LINK) - - # link these libraries to our target - target_link_libraries(${TARGET_NAME} ${${TARGET_NAME}_LIBRARIES_TO_LINK}) - endif () - +macro(LINK_SHARED_DEPENDENCIES) if (${TARGET_NAME}_DEPENDENCY_INCLUDES) list(REMOVE_DUPLICATES ${TARGET_NAME}_DEPENDENCY_INCLUDES) @@ -24,22 +17,6 @@ macro(LINK_SHARED_DEPENDENCIES) include_directories(SYSTEM ${${TARGET_NAME}_DEPENDENCY_INCLUDES}) endif () - if (${TARGET_NAME}_DEPENDENCY_QT_MODULES) - list(REMOVE_DUPLICATES ${TARGET_NAME}_DEPENDENCY_QT_MODULES) - - # find these Qt modules and link them to our own target - find_package(Qt5 COMPONENTS ${${TARGET_NAME}_DEPENDENCY_QT_MODULES} REQUIRED) - - foreach(QT_MODULE ${${TARGET_NAME}_DEPENDENCY_QT_MODULES}) - target_link_libraries(${TARGET_NAME} Qt5::${QT_MODULE}) - endforeach() - endif () - - # we've already linked our Qt modules, but we need to bubble them up to parents - list(APPEND ${TARGET_NAME}_LIBRARIES_TO_LINK "${${TARGET_NAME}_QT_MODULES_TO_LINK}") - # set the property on this target so it can be retreived by targets linking to us - set_target_properties(${TARGET_NAME} PROPERTIES DEPENDENCY_LIBRARIES "${${TARGET_NAME}_LIBRARIES_TO_LINK}") set_target_properties(${TARGET_NAME} PROPERTIES DEPENDENCY_INCLUDES "${${TARGET_NAME}_DEPENDENCY_INCLUDES}") - set_target_properties(${TARGET_NAME} PROPERTIES DEPENDENCY_QT_MODULES "${${TARGET_NAME}_DEPENDENCY_QT_MODULES}") endmacro(LINK_SHARED_DEPENDENCIES) \ No newline at end of file diff --git a/cmake/macros/SetupHifiLibrary.cmake b/cmake/macros/SetupHifiLibrary.cmake index de9f9b9d1e..362a833862 100644 --- a/cmake/macros/SetupHifiLibrary.cmake +++ b/cmake/macros/SetupHifiLibrary.cmake @@ -21,4 +21,11 @@ macro(SETUP_HIFI_LIBRARY) set(${TARGET_NAME}_DEPENDENCY_QT_MODULES ${ARGN}) list(APPEND ${TARGET_NAME}_DEPENDENCY_QT_MODULES Core) + # find these Qt modules and link them to our own target + find_package(Qt5 COMPONENTS ${${TARGET_NAME}_DEPENDENCY_QT_MODULES} REQUIRED) + + foreach(QT_MODULE ${${TARGET_NAME}_DEPENDENCY_QT_MODULES}) + target_link_libraries(${TARGET_NAME} Qt5::${QT_MODULE}) + endforeach() + endmacro(SETUP_HIFI_LIBRARY) \ No newline at end of file diff --git a/cmake/macros/SetupHifiProject.cmake b/cmake/macros/SetupHifiProject.cmake index 157c22ea79..3f9787faa1 100644 --- a/cmake/macros/SetupHifiProject.cmake +++ b/cmake/macros/SetupHifiProject.cmake @@ -27,4 +27,11 @@ macro(SETUP_HIFI_PROJECT) set(${TARGET_NAME}_DEPENDENCY_QT_MODULES ${ARGN}) list(APPEND ${TARGET_NAME}_DEPENDENCY_QT_MODULES Core) + + # find these Qt modules and link them to our own target + find_package(Qt5 COMPONENTS ${${TARGET_NAME}_DEPENDENCY_QT_MODULES} REQUIRED) + + foreach(QT_MODULE ${${TARGET_NAME}_DEPENDENCY_QT_MODULES}) + target_link_libraries(${TARGET_NAME} Qt5::${QT_MODULE}) + endforeach() endmacro() \ No newline at end of file diff --git a/domain-server/CMakeLists.txt b/domain-server/CMakeLists.txt index b804ff27d3..b9f730baaf 100644 --- a/domain-server/CMakeLists.txt +++ b/domain-server/CMakeLists.txt @@ -50,6 +50,6 @@ endif () include_directories(SYSTEM "${OPENSSL_INCLUDE_DIR}") # append OpenSSL to our list of libraries to link -list(APPEND ${TARGET_NAME}_LIBRARIES_TO_LINK "${OPENSSL_LIBRARIES}") +target_link_libraries(${TARGET_NAME} "${OPENSSL_LIBRARIES}") link_shared_dependencies() \ No newline at end of file diff --git a/libraries/fbx/CMakeLists.txt b/libraries/fbx/CMakeLists.txt index 894fa14c33..2e58645b56 100644 --- a/libraries/fbx/CMakeLists.txt +++ b/libraries/fbx/CMakeLists.txt @@ -9,7 +9,7 @@ link_hifi_libraries(shared networking octree voxels) find_package(ZLIB REQUIRED) include_directories(SYSTEM "${ZLIB_INCLUDE_DIRS}") -list(APPEND ${TARGET_NAME}_LIBRARIES_TO_LINK "${ZLIB_LIBRARIES}") +target_link_libraries(${TARGET_NAME} "${ZLIB_LIBRARIES}") # call macro to link our dependencies and bubble them up via a property on our target link_shared_dependencies() diff --git a/libraries/networking/CMakeLists.txt b/libraries/networking/CMakeLists.txt index 7c8b628183..90e06bc13e 100644 --- a/libraries/networking/CMakeLists.txt +++ b/libraries/networking/CMakeLists.txt @@ -23,7 +23,7 @@ endif () include_directories(SYSTEM "${OPENSSL_INCLUDE_DIR}") # append OpenSSL to our list of libraries to link -list(APPEND ${TARGET_NAME}_LIBRARIES_TO_LINK "${OPENSSL_LIBRARIES}" "${TBB_LIBRARIES}") +target_link_libraries(${TARGET_NAME} "${OPENSSL_LIBRARIES}" "${TBB_LIBRARIES}") # append libcuckoo includes to our list of includes to bubble list(APPEND ${TARGET_NAME}_DEPENDENCY_INCLUDES "${TBB_INCLUDE_DIRS}") diff --git a/libraries/octree/CMakeLists.txt b/libraries/octree/CMakeLists.txt index 9aea2fdea1..f1a30f3724 100644 --- a/libraries/octree/CMakeLists.txt +++ b/libraries/octree/CMakeLists.txt @@ -13,7 +13,7 @@ find_package(ZLIB REQUIRED) include_directories(SYSTEM "${ZLIB_INCLUDE_DIRS}") # append ZLIB and OpenSSL to our list of libraries to link -list(APPEND ${TARGET_NAME}_LIBRARIES_TO_LINK "${ZLIB_LIBRARIES}") +target_link_libraries(${TARGET_NAME} "${ZLIB_LIBRARIES}") # call macro to link our dependencies and bubble them up via a property on our target link_shared_dependencies() diff --git a/libraries/voxels/CMakeLists.txt b/libraries/voxels/CMakeLists.txt index 3214978a2a..874a74ee95 100644 --- a/libraries/voxels/CMakeLists.txt +++ b/libraries/voxels/CMakeLists.txt @@ -12,7 +12,7 @@ find_package(ZLIB REQUIRED) include_directories(SYSTEM "${ZLIB_INCLUDE_DIRS}") # add it to our list of libraries to link -list(APPEND ${TARGET}_LIBRARIES_TO_LINK "${ZLIB_LIBRARIES}") +target_link_libraries(${TARGET_NAME} "${ZLIB_LIBRARIES}") # call macro to link our dependencies and bubble them up via a property on our target link_shared_dependencies() \ No newline at end of file From b326ab9839e4411927594799303cffb0ecf34393 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 18 Dec 2014 09:38:48 -0800 Subject: [PATCH 180/258] remove quotes from library links for debug/optimized --- domain-server/CMakeLists.txt | 2 +- libraries/fbx/CMakeLists.txt | 2 +- libraries/networking/CMakeLists.txt | 2 +- libraries/octree/CMakeLists.txt | 2 +- libraries/voxels/CMakeLists.txt | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/domain-server/CMakeLists.txt b/domain-server/CMakeLists.txt index b9f730baaf..482c397b14 100644 --- a/domain-server/CMakeLists.txt +++ b/domain-server/CMakeLists.txt @@ -50,6 +50,6 @@ endif () include_directories(SYSTEM "${OPENSSL_INCLUDE_DIR}") # append OpenSSL to our list of libraries to link -target_link_libraries(${TARGET_NAME} "${OPENSSL_LIBRARIES}") +target_link_libraries(${TARGET_NAME} ${OPENSSL_LIBRARIES}) link_shared_dependencies() \ No newline at end of file diff --git a/libraries/fbx/CMakeLists.txt b/libraries/fbx/CMakeLists.txt index 2e58645b56..5a151deb8b 100644 --- a/libraries/fbx/CMakeLists.txt +++ b/libraries/fbx/CMakeLists.txt @@ -9,7 +9,7 @@ link_hifi_libraries(shared networking octree voxels) find_package(ZLIB REQUIRED) include_directories(SYSTEM "${ZLIB_INCLUDE_DIRS}") -target_link_libraries(${TARGET_NAME} "${ZLIB_LIBRARIES}") +target_link_libraries(${TARGET_NAME} ${ZLIB_LIBRARIES}) # call macro to link our dependencies and bubble them up via a property on our target link_shared_dependencies() diff --git a/libraries/networking/CMakeLists.txt b/libraries/networking/CMakeLists.txt index 90e06bc13e..934e3e69b9 100644 --- a/libraries/networking/CMakeLists.txt +++ b/libraries/networking/CMakeLists.txt @@ -23,7 +23,7 @@ endif () include_directories(SYSTEM "${OPENSSL_INCLUDE_DIR}") # append OpenSSL to our list of libraries to link -target_link_libraries(${TARGET_NAME} "${OPENSSL_LIBRARIES}" "${TBB_LIBRARIES}") +target_link_libraries(${TARGET_NAME} ${OPENSSL_LIBRARIES} ${TBB_LIBRARIES}) # append libcuckoo includes to our list of includes to bubble list(APPEND ${TARGET_NAME}_DEPENDENCY_INCLUDES "${TBB_INCLUDE_DIRS}") diff --git a/libraries/octree/CMakeLists.txt b/libraries/octree/CMakeLists.txt index f1a30f3724..e8c6554ff4 100644 --- a/libraries/octree/CMakeLists.txt +++ b/libraries/octree/CMakeLists.txt @@ -13,7 +13,7 @@ find_package(ZLIB REQUIRED) include_directories(SYSTEM "${ZLIB_INCLUDE_DIRS}") # append ZLIB and OpenSSL to our list of libraries to link -target_link_libraries(${TARGET_NAME} "${ZLIB_LIBRARIES}") +target_link_libraries(${TARGET_NAME} ${ZLIB_LIBRARIES}) # call macro to link our dependencies and bubble them up via a property on our target link_shared_dependencies() diff --git a/libraries/voxels/CMakeLists.txt b/libraries/voxels/CMakeLists.txt index 874a74ee95..7980094884 100644 --- a/libraries/voxels/CMakeLists.txt +++ b/libraries/voxels/CMakeLists.txt @@ -12,7 +12,7 @@ find_package(ZLIB REQUIRED) include_directories(SYSTEM "${ZLIB_INCLUDE_DIRS}") # add it to our list of libraries to link -target_link_libraries(${TARGET_NAME} "${ZLIB_LIBRARIES}") +target_link_libraries(${TARGET_NAME} ${ZLIB_LIBRARIES}) # call macro to link our dependencies and bubble them up via a property on our target link_shared_dependencies() \ No newline at end of file From e6d3278b59c3d4a0530b054ee9e36ec2890f7668 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 18 Dec 2014 09:47:20 -0800 Subject: [PATCH 181/258] add back include of GLUT in render-utils --- libraries/render-utils/CMakeLists.txt | 3 +++ 1 file changed, 3 insertions(+) diff --git a/libraries/render-utils/CMakeLists.txt b/libraries/render-utils/CMakeLists.txt index 8d4f85a2ac..4be4d93a9a 100644 --- a/libraries/render-utils/CMakeLists.txt +++ b/libraries/render-utils/CMakeLists.txt @@ -7,5 +7,8 @@ include_glm() link_hifi_libraries(shared gpu) +find_package(GLUT REQUIRED) +include_directories(SYSTEM "${GLUT_INCLUDE_DIRS}") + # call macro to link our dependencies and bubble them up via a property on our target link_shared_dependencies() From 4042b8b17ac6525e77ed61d139fb0cbf18e1bbd3 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 18 Dec 2014 09:50:10 -0800 Subject: [PATCH 182/258] duh, glut only required on win --- libraries/render-utils/CMakeLists.txt | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/libraries/render-utils/CMakeLists.txt b/libraries/render-utils/CMakeLists.txt index 4be4d93a9a..a6943addcc 100644 --- a/libraries/render-utils/CMakeLists.txt +++ b/libraries/render-utils/CMakeLists.txt @@ -7,8 +7,10 @@ include_glm() link_hifi_libraries(shared gpu) -find_package(GLUT REQUIRED) -include_directories(SYSTEM "${GLUT_INCLUDE_DIRS}") +if (WIN32) + find_package(GLUT REQUIRED) + include_directories(SYSTEM "${GLUT_INCLUDE_DIRS}") +endif () # call macro to link our dependencies and bubble them up via a property on our target link_shared_dependencies() From af1591277c41dd38c8365c40ae1538b6f7ed0bb8 Mon Sep 17 00:00:00 2001 From: Adrianl3d Date: Fri, 19 Dec 2014 04:17:36 +1000 Subject: [PATCH 183/258] changes as per list removed dummy code, remove mic mute state at startup, some text changes. --- examples/notifications.js | 107 +++++++++++++++++--------------------- 1 file changed, 47 insertions(+), 60 deletions(-) diff --git a/examples/notifications.js b/examples/notifications.js index 2c2c4a5c0b..7946213abd 100644 --- a/examples/notifications.js +++ b/examples/notifications.js @@ -1,25 +1,32 @@ // -// notifications.js +// notifications.js +// Version 0.801 // Created by Adrian // // Adrian McCarlie 8-10-14 // This script demonstrates on-screen overlay type notifications. // Copyright 2014 High Fidelity, Inc. // +// // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// This script demonstrates notifications created via a number of ways, such as: -// Simple key press alerts, which only depend on a key being pressed, -// dummy examples of this are "q", "w", "e", "r", and "SPACEBAR". -// actual working examples are "a" for left turn, "d" for right turn and Ctrl/s for snapshot. - -// System generated alerts such as users joining and leaving and chat messages which mention this user. -// System generated alerts which originate with a user interface event such as Window Resize, and Mic Mute/Unmute. -// Mic Mute/Unmute may appear to be a key press alert, but it actually gets the call from the system as mic is muted and unmuted, -// so the mic mute/unmute will also trigger the notification by clicking the Mic Mute button at the top of the screen. +// This script generates notifications created via a number of ways, such as: +// keystroke: +// +// "q" returns number of users currently online (for debug purposes) +// CTRL/s for snapshot. +// CTRL/m for mic mute and unmute. +// System generated notifications: +// Displays users online at startup. +// If Screen is resized. +// Triggers notification if @MyUserName is mentioned in chat. +// Announces existing user logging out. +// Announces new user logging in. +// If mic is muted for any reason. +// // To add a new System notification type: // // 1. Set the Event Connector at the bottom of the script. @@ -45,22 +52,23 @@ // 2. Declare a text string. // 3. Call createNotifications(text) parsing the text. // example: -// if (key.text == "a") { -// var noteString = "Turning to the Left"; -// createNotification(noteString); -// } +// if (key.text == "q") { //queries number of users online +// var numUsers = GlobalServices.onlineUsers.length; +// var welcome = "There are " + numUsers + " users online now."; +// createNotification(welcome); +// } var width = 340.0; //width of notification overlay var height = 40.0; // height of a single line notification overlay var windowDimensions = Controller.getViewportDimensions(); // get the size of the interface window -var overlayLocationX = (windowDimensions.x - (width + 60.0));// positions window 60px from the right of the interface window +var overlayLocationX = (windowDimensions.x - (width + 20.0));// positions window 20px from the right of the interface window var buttonLocationX = overlayLocationX + (width - 28.0); var locationY = 20.0; // position down from top of interface window var topMargin = 13.0; var leftMargin = 10.0; var textColor = { red: 228, green: 228, blue: 228}; // text color -var backColor = { red: 38, green: 38, blue: 38}; // background color +var backColor = { red: 2, green: 2, blue: 2}; // background color was 38,38,38 var backgroundAlpha = 0; var fontSize = 12.0; var persistTime = 10.0; // time in seconds before notification fades @@ -115,7 +123,6 @@ function createNotification(text) { color: textColor, backgroundColor: backColor, alpha: backgroundAlpha, - backgroundAlpha: backgroundAlpha, topMargin: topMargin, leftMargin: leftMargin, font: {size: fontSize}, @@ -125,8 +132,8 @@ function createNotification(text) { var buttonProperties = { x: buttonLocationX, y: bLevel, - width: 15.0, - height: 15.0, + width: 10.0, + height: 10.0, subImage: { x: 0, y: 0, width: 10, height: 10 }, imageURL: "http://hifi-public.s3.amazonaws.com/images/close-small-light.svg", color: { red: 255, green: 255, blue: 255}, @@ -161,7 +168,7 @@ function fadeIn(noticeIn, buttonIn) { pauseTimer = Script.setInterval(function() { q++; qFade = q / 10.0; - Overlays.editOverlay(noticeIn, {alpha: qFade, backgroundAlpha: qFade}); + Overlays.editOverlay(noticeIn, {alpha: qFade}); Overlays.editOverlay(buttonIn, {alpha: qFade}); if (q >= 9.0) { Script.clearInterval(pauseTimer); @@ -203,41 +210,18 @@ function keyPressEvent(key) { if (key.key == 16777249) { ctrlIsPressed = true; } - if (key.text == "a") { - var noteString = "Turning to the Left"; - createNotification(noteString); - } - if (key.text == "d") { - var noteString = "Turning to the Right"; - createNotification(noteString); - } + if (key.text == "q") { //queries number of users online + var numUsers = GlobalServices.onlineUsers.length; + var welcome = "There are " + numUsers + " users online now."; + createNotification(welcome); + } + if (key.text == "s") { if (ctrlIsPressed == true){ - var noteString = "You have taken a snapshot"; + var noteString = "Snapshot taken."; createNotification(noteString); } } - if (key.text == "q") { - var noteString = "Enable Scripted Motor control is now on."; - wordWrap(noteString); - } - if (key.text == "w") { - var noteString = "This notification spans 2 lines. The overlay will resize to fit new lines."; - var noteString = "editVoxels.js stopped, editModels.js stopped, selectAudioDevice.js stopped."; - wordWrap(noteString); - } - if (key.text == "e") { - var noteString = "This is an example of a multiple line notification. This notification will span 3 lines." - wordWrap(noteString); - } - if (key.text == "r") { - var noteString = "This is a very long line of text that we are going to use in this example to divide it into rows of maximum 43 chars and see how many lines we use."; - wordWrap(noteString); - } - if (key.text == "SPACE") { - var noteString = "You have pressed the Spacebar, This is an example of a multiple line notification. Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam."; - wordWrap(noteString); - } } // formats string to add newline every 43 chars @@ -275,18 +259,14 @@ function checkSize(){ // Triggers notification if a user logs on or off function onOnlineUsersChanged(users) { - var joiners = []; - var leavers = []; for (user in users) { if (last_users.indexOf(users[user]) == -1.0) { - joiners.push(users[user]); - createNotification(users[user] + " Has joined"); + createNotification(users[user] + " has joined"); } } for (user in last_users) { if (users.indexOf(last_users[user]) == -1.0) { - leavers.push(last_users[user]); - createNotification(last_users[user] + " Has left"); + createNotification(last_users[user] + " has left"); } } last_users = users; @@ -303,8 +283,8 @@ function onIncomingMessage(user, message) { } // Triggers mic mute notification function onMuteStateChanged() { - var muteState = AudioDevice.getMuted() ? "Muted" : "Unmuted"; - var muteString = "Microphone is set to " + muteState; + var muteState = AudioDevice.getMuted() ? "muted" : "unmuted"; + var muteString = "Microphone is now " + muteState; createNotification(muteString); } @@ -345,7 +325,7 @@ function fadeOut(noticeOut, buttonOut, arraysOut) { pauseTimer = Script.setInterval(function() { r--; rFade = r / 10.0; - Overlays.editOverlay(noticeOut, {alpha: rFade, backgroundAlpha: rFade}); + Overlays.editOverlay(noticeOut, {alpha: rFade}); Overlays.editOverlay(buttonOut, {alpha: rFade}); if (r < 0) { dismiss(noticeOut, buttonOut, arraysOut); @@ -368,10 +348,17 @@ function dismiss(firstNoteOut, firstButOut, firstOut) { myAlpha.splice(firstOut,1); } -onMuteStateChanged(); +// This is meant to show users online at startup but currently shows 0 users. +function onConnected() { + var numUsers = GlobalServices.onlineUsers.length; + var welcome = "Welcome! There are " + numUsers + " users online now."; + createNotification(welcome); +} + AudioDevice.muteToggled.connect(onMuteStateChanged); Controller.keyPressEvent.connect(keyPressEvent); Controller.mousePressEvent.connect(mousePressEvent); +GlobalServices.connected.connect(onConnected); GlobalServices.onlineUsersChanged.connect(onOnlineUsersChanged); GlobalServices.incomingMessage.connect(onIncomingMessage); Controller.keyReleaseEvent.connect(keyReleaseEvent); From 11b44000998e222f3a2f523da63d58077a28a403 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Thu, 18 Dec 2014 11:20:17 -0800 Subject: [PATCH 184/258] move all glut-ness to geometry cache --- interface/src/Application.cpp | 2 +- interface/src/avatar/Hand.cpp | 2 +- interface/src/ui/MetavoxelEditor.cpp | 6 +- interface/src/ui/NodeBounds.cpp | 4 +- interface/src/ui/overlays/Sphere3DOverlay.cpp | 6 +- interface/src/voxels/VoxelFade.cpp | 3 +- .../src/RenderableBoxEntityItem.cpp | 78 +++---------------- .../src/DeferredLightingEffect.cpp | 6 +- .../render-utils/src/DeferredLightingEffect.h | 3 +- libraries/render-utils/src/GeometryCache.cpp | 10 +++ libraries/render-utils/src/GeometryCache.h | 2 + 11 files changed, 37 insertions(+), 85 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 4df23d2f7e..577f830495 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -3575,7 +3575,7 @@ void Application::renderViewFrustum(ViewFrustum& viewFrustum) { glPushMatrix(); glColor4f(1, 1, 0, 1); glTranslatef(position.x, position.y, position.z); // where we actually want it! - glutWireSphere(keyholeRadius, 20, 20); + DependencyManager::get()->renderSphere(keyholeRadius, 20, 20, false); glPopMatrix(); } } diff --git a/interface/src/avatar/Hand.cpp b/interface/src/avatar/Hand.cpp index 91d59ae2fa..0ea0d1b725 100644 --- a/interface/src/avatar/Hand.cpp +++ b/interface/src/avatar/Hand.cpp @@ -153,7 +153,7 @@ void Hand::renderHandTargets(bool isMine) { const float collisionRadius = 0.05f; glColor4f(0.5f,0.5f,0.5f, alpha); - glutWireSphere(collisionRadius, 10.0f, 10.0f); + DependencyManager::get()->renderSphere(collisionRadius, 10, 10, false); glPopMatrix(); } } diff --git a/interface/src/ui/MetavoxelEditor.cpp b/interface/src/ui/MetavoxelEditor.cpp index f0516ab955..1a440570b7 100644 --- a/interface/src/ui/MetavoxelEditor.cpp +++ b/interface/src/ui/MetavoxelEditor.cpp @@ -33,6 +33,7 @@ #include #include +#include #include #include #include @@ -492,12 +493,11 @@ void BoxTool::render() { glColor4f(GRID_BRIGHTNESS, GRID_BRIGHTNESS, GRID_BRIGHTNESS, BOX_ALPHA); } glEnable(GL_CULL_FACE); - glutSolidCube(1.0); + DependencyManager::get()->renderSolidCube(1.0f); glDisable(GL_CULL_FACE); } glColor3f(GRID_BRIGHTNESS, GRID_BRIGHTNESS, GRID_BRIGHTNESS); - glutWireCube(1.0); - + DependencyManager::get()->renderWireCube(1.0f); glPopMatrix(); } diff --git a/interface/src/ui/NodeBounds.cpp b/interface/src/ui/NodeBounds.cpp index b0d3ddd14f..c529f6bbf3 100644 --- a/interface/src/ui/NodeBounds.cpp +++ b/interface/src/ui/NodeBounds.cpp @@ -12,6 +12,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +#include + #include "Application.h" #include "Util.h" @@ -132,7 +134,7 @@ void NodeBounds::draw() { getColorForNodeType(selectedNode->getType(), red, green, blue); glColor4f(red, green, blue, 0.2f); - glutSolidCube(1.0); + DependencyManager::get()->renderSolidCube(1.0f); glPopMatrix(); diff --git a/interface/src/ui/overlays/Sphere3DOverlay.cpp b/interface/src/ui/overlays/Sphere3DOverlay.cpp index 522902194f..3e30ec033d 100644 --- a/interface/src/ui/overlays/Sphere3DOverlay.cpp +++ b/interface/src/ui/overlays/Sphere3DOverlay.cpp @@ -62,11 +62,7 @@ void Sphere3DOverlay::render(RenderArgs* args) { glm::vec3 positionToCenter = center - position; glTranslatef(positionToCenter.x, positionToCenter.y, positionToCenter.z); glScalef(dimensions.x, dimensions.y, dimensions.z); - if (_isSolid) { - DependencyManager::get()->renderSphere(1.0f, SLICES, SLICES); - } else { - glutWireSphere(1.0f, SLICES, SLICES); - } + DependencyManager::get()->renderSphere(1.0f, SLICES, SLICES, _isSolid); glPopMatrix(); glPopMatrix(); diff --git a/interface/src/voxels/VoxelFade.cpp b/interface/src/voxels/VoxelFade.cpp index 367090291c..7bb3be67ab 100644 --- a/interface/src/voxels/VoxelFade.cpp +++ b/interface/src/voxels/VoxelFade.cpp @@ -12,6 +12,7 @@ #include "InterfaceConfig.h" #include +#include #include #include "Application.h" @@ -47,7 +48,7 @@ void VoxelFade::render() { voxelDetails.y + voxelDetails.s * 0.5f, voxelDetails.z + voxelDetails.s * 0.5f); glLineWidth(1.0f); - glutSolidCube(voxelDetails.s); + DependencyManager::get()->renderSolidCube(voxelDetails.s); glLineWidth(1.0f); glPopMatrix(); glEnable(GL_LIGHTING); diff --git a/libraries/entities-renderer/src/RenderableBoxEntityItem.cpp b/libraries/entities-renderer/src/RenderableBoxEntityItem.cpp index bb0de0ce6d..276db09477 100644 --- a/libraries/entities-renderer/src/RenderableBoxEntityItem.cpp +++ b/libraries/entities-renderer/src/RenderableBoxEntityItem.cpp @@ -28,79 +28,23 @@ void RenderableBoxEntityItem::render(RenderArgs* args) { glm::vec3 position = getPositionInMeters(); glm::vec3 center = getCenter() * (float)TREE_SCALE; glm::vec3 dimensions = getDimensions() * (float)TREE_SCALE; - glm::vec3 halfDimensions = dimensions / 2.0f; glm::quat rotation = getRotation(); - const bool useGlutCube = true; const float MAX_COLOR = 255.0f; - if (useGlutCube) { - glColor4f(getColor()[RED_INDEX] / MAX_COLOR, getColor()[GREEN_INDEX] / MAX_COLOR, - getColor()[BLUE_INDEX] / MAX_COLOR, getLocalRenderAlpha()); + glColor4f(getColor()[RED_INDEX] / MAX_COLOR, getColor()[GREEN_INDEX] / MAX_COLOR, + getColor()[BLUE_INDEX] / MAX_COLOR, getLocalRenderAlpha()); + glPushMatrix(); + glTranslatef(position.x, position.y, position.z); + glm::vec3 axis = glm::axis(rotation); + glRotatef(glm::degrees(glm::angle(rotation)), axis.x, axis.y, axis.z); glPushMatrix(); - glTranslatef(position.x, position.y, position.z); - glm::vec3 axis = glm::axis(rotation); - glRotatef(glm::degrees(glm::angle(rotation)), axis.x, axis.y, axis.z); - glPushMatrix(); - glm::vec3 positionToCenter = center - position; - glTranslatef(positionToCenter.x, positionToCenter.y, positionToCenter.z); - glScalef(dimensions.x, dimensions.y, dimensions.z); - DependencyManager::get()->renderSolidCube(1.0f); - glPopMatrix(); + glm::vec3 positionToCenter = center - position; + glTranslatef(positionToCenter.x, positionToCenter.y, positionToCenter.z); + glScalef(dimensions.x, dimensions.y, dimensions.z); + DependencyManager::get()->renderSolidCube(1.0f); glPopMatrix(); - } else { - static GLfloat vertices[] = { 1, 1, 1, -1, 1, 1, -1,-1, 1, 1,-1, 1, // v0,v1,v2,v3 (front) - 1, 1, 1, 1,-1, 1, 1,-1,-1, 1, 1,-1, // v0,v3,v4,v5 (right) - 1, 1, 1, 1, 1,-1, -1, 1,-1, -1, 1, 1, // v0,v5,v6,v1 (top) - -1, 1, 1, -1, 1,-1, -1,-1,-1, -1,-1, 1, // v1,v6,v7,v2 (left) - -1,-1,-1, 1,-1,-1, 1,-1, 1, -1,-1, 1, // v7,v4,v3,v2 (bottom) - 1,-1,-1, -1,-1,-1, -1, 1,-1, 1, 1,-1 }; // v4,v7,v6,v5 (back) + glPopMatrix(); - // normal array - static GLfloat normals[] = { 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, // v0,v1,v2,v3 (front) - 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, // v0,v3,v4,v5 (right) - 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, // v0,v5,v6,v1 (top) - -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, // v1,v6,v7,v2 (left) - 0,-1, 0, 0,-1, 0, 0,-1, 0, 0,-1, 0, // v7,v4,v3,v2 (bottom) - 0, 0,-1, 0, 0,-1, 0, 0,-1, 0, 0,-1 }; // v4,v7,v6,v5 (back) - - // index array of vertex array for glDrawElements() & glDrawRangeElement() - static GLubyte indices[] = { 0, 1, 2, 2, 3, 0, // front - 4, 5, 6, 6, 7, 4, // right - 8, 9,10, 10,11, 8, // top - 12,13,14, 14,15,12, // left - 16,17,18, 18,19,16, // bottom - 20,21,22, 22,23,20 }; // back - - - - glEnableClientState(GL_NORMAL_ARRAY); - glEnableClientState(GL_VERTEX_ARRAY); - glNormalPointer(GL_FLOAT, 0, normals); - glVertexPointer(3, GL_FLOAT, 0, vertices); - - glColor4f(getColor()[RED_INDEX] / MAX_COLOR, getColor()[GREEN_INDEX] / MAX_COLOR, - getColor()[BLUE_INDEX] / MAX_COLOR, getLocalRenderAlpha()); - - DependencyManager::get()->bindSimpleProgram(); - - glPushMatrix(); - glTranslatef(position.x, position.y, position.z); - glm::vec3 axis = glm::axis(rotation); - glRotatef(glm::degrees(glm::angle(rotation)), axis.x, axis.y, axis.z); - glPushMatrix(); - glm::vec3 positionToCenter = center - position; - glTranslatef(positionToCenter.x, positionToCenter.y, positionToCenter.z); - // we need to do half the size because the geometry in the VBOs are from -1,-1,-1 to 1,1,1 - glScalef(halfDimensions.x, halfDimensions.y, halfDimensions.z); - glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_BYTE, indices); - glPopMatrix(); - glPopMatrix(); - - DependencyManager::get()->releaseSimpleProgram(); - - glDisableClientState(GL_VERTEX_ARRAY); // disable vertex arrays - glDisableClientState(GL_NORMAL_ARRAY); - } }; diff --git a/libraries/render-utils/src/DeferredLightingEffect.cpp b/libraries/render-utils/src/DeferredLightingEffect.cpp index 065ca3a741..0dd6f9d0b8 100644 --- a/libraries/render-utils/src/DeferredLightingEffect.cpp +++ b/libraries/render-utils/src/DeferredLightingEffect.cpp @@ -12,8 +12,6 @@ // include this before QOpenGLFramebufferObject, which includes an earlier version of OpenGL #include -#include // TODO - we need to get rid of this ASAP - #include #include @@ -74,13 +72,13 @@ void DeferredLightingEffect::renderWireSphere(float radius, int slices, int stac void DeferredLightingEffect::renderSolidCube(float size) { bindSimpleProgram(); - glutSolidCube(size); + DependencyManager::get()->renderSolidCube(size); releaseSimpleProgram(); } void DeferredLightingEffect::renderWireCube(float size) { bindSimpleProgram(); - glutWireCube(size); + DependencyManager::get()->renderWireCube(size); releaseSimpleProgram(); } diff --git a/libraries/render-utils/src/DeferredLightingEffect.h b/libraries/render-utils/src/DeferredLightingEffect.h index 7ace3448d7..4f3b930a09 100644 --- a/libraries/render-utils/src/DeferredLightingEffect.h +++ b/libraries/render-utils/src/DeferredLightingEffect.h @@ -30,8 +30,7 @@ public: void init(AbstractViewStateInterface* viewState); - /// Returns a reference to a simple program suitable for rendering static - /// untextured geometry (such as that generated by glutSolidSphere, etc.) + /// Returns a reference to a simple program suitable for rendering static untextured geometry ProgramObject& getSimpleProgram() { return _simpleProgram; } /// Sets up the state necessary to render static untextured geometry with the simple program. diff --git a/libraries/render-utils/src/GeometryCache.cpp b/libraries/render-utils/src/GeometryCache.cpp index a770d942fe..e31ae2333a 100644 --- a/libraries/render-utils/src/GeometryCache.cpp +++ b/libraries/render-utils/src/GeometryCache.cpp @@ -11,6 +11,7 @@ // include this before QOpenGLBuffer, which includes an earlier version of OpenGL #include +#include // TODO - we need to get rid of this ASAP #include @@ -507,6 +508,15 @@ void GeometryCache::renderGrid(int xDivisions, int yDivisions) { buffer.release(); } +void GeometryCache::renderSolidCube(float size) { + glutSolidCube(size); +} + +void GeometryCache::renderWireCube(float size) { + glutWireCube(size); +} + + QSharedPointer GeometryCache::getGeometry(const QUrl& url, const QUrl& fallback, bool delayLoad) { return getResource(url, fallback, delayLoad).staticCast(); } diff --git a/libraries/render-utils/src/GeometryCache.h b/libraries/render-utils/src/GeometryCache.h index f0045c10bf..92e65718ab 100644 --- a/libraries/render-utils/src/GeometryCache.h +++ b/libraries/render-utils/src/GeometryCache.h @@ -43,6 +43,8 @@ public: void renderHalfCylinder(int slices, int stacks); void renderCone(float base, float height, int slices, int stacks); void renderGrid(int xDivisions, int yDivisions); + void renderSolidCube(float size); + void renderWireCube(float size); /// Loads geometry from the specified URL. /// \param fallback a fallback URL to load if the desired one is unavailable From 011b313b681c4ac8767e51dbd3afa2d06b6f412d Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 18 Dec 2014 11:30:57 -0800 Subject: [PATCH 185/258] fix indentation in MetavoxelClientManager --- libraries/metavoxels/src/MetavoxelClientManager.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/libraries/metavoxels/src/MetavoxelClientManager.cpp b/libraries/metavoxels/src/MetavoxelClientManager.cpp index dfc736edc9..e0489b4bd0 100644 --- a/libraries/metavoxels/src/MetavoxelClientManager.cpp +++ b/libraries/metavoxels/src/MetavoxelClientManager.cpp @@ -50,7 +50,8 @@ SharedObjectPointer MetavoxelClientManager::findFirstRaySpannerIntersection(cons if (client) { float clientDistance; SharedObjectPointer clientSpanner = client->getDataCopy().findFirstRaySpannerIntersection( - origin, direction, attribute, clientDistance); + origin, direction, attribute, clientDistance + ); if (clientSpanner && clientDistance < closestDistance) { closestSpanner = clientSpanner; closestDistance = clientDistance; From 28381a3b7092fc956153df7561029059616c2a0b Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Thu, 18 Dec 2014 11:39:02 -0800 Subject: [PATCH 186/258] cleanup of EntityItem::_created timestamp logic EntityItem::_created initializes to 0 in ctor and must be set either by EntityItemProperties (via server update) or manually whenever a script creates a fresh entity --- libraries/entities/src/EntityItem.cpp | 101 +++++++++++------- libraries/entities/src/EntityItem.h | 3 +- .../entities/src/EntityItemProperties.cpp | 14 ++- libraries/entities/src/EntityItemProperties.h | 6 +- .../entities/src/EntityItemPropertiesMacros.h | 4 +- libraries/entities/src/EntityTree.cpp | 17 ++- libraries/entities/src/EntityTypes.cpp | 17 +-- 7 files changed, 95 insertions(+), 67 deletions(-) diff --git a/libraries/entities/src/EntityItem.cpp b/libraries/entities/src/EntityItem.cpp index cd34cd55c6..348efac9a3 100644 --- a/libraries/entities/src/EntityItem.cpp +++ b/libraries/entities/src/EntityItem.cpp @@ -53,13 +53,13 @@ void EntityItem::initFromEntityItemID(const EntityItemID& entityItemID) { _creatorTokenID = entityItemID.creatorTokenID; // init values with defaults before calling setProperties + quint64 now = usecTimestampNow(); + _lastSimulated = now; + _lastUpdated = now; _lastEdited = 0; _lastEditedFromRemote = 0; _lastEditedFromRemoteInRemoteTime = 0; - - _lastSimulated = 0; - _lastUpdated = 0; - _created = usecTimestampNow(); + _created = UNKNOWN_CREATED_TIME; _changedOnServer = 0; _position = glm::vec3(0,0,0); @@ -85,12 +85,13 @@ void EntityItem::initFromEntityItemID(const EntityItemID& entityItemID) { EntityItem::EntityItem(const EntityItemID& entityItemID) { _type = EntityTypes::Unknown; + quint64 now = usecTimestampNow(); + _lastSimulated = now; + _lastUpdated = now; _lastEdited = 0; _lastEditedFromRemote = 0; _lastEditedFromRemoteInRemoteTime = 0; - _lastSimulated = 0; - _lastUpdated = 0; - _created = 0; + _created = UNKNOWN_CREATED_TIME; _dirtyFlags = 0; _changedOnServer = 0; initFromEntityItemID(entityItemID); @@ -99,16 +100,16 @@ EntityItem::EntityItem(const EntityItemID& entityItemID) { EntityItem::EntityItem(const EntityItemID& entityItemID, const EntityItemProperties& properties) { _type = EntityTypes::Unknown; quint64 now = usecTimestampNow(); - _created = properties.getCreated() < now ? properties.getCreated() : now; - _lastEdited = _lastEditedFromRemote = _lastSimulated = _lastUpdated = _lastEditedFromRemoteInRemoteTime = _created; + _lastSimulated = now; + _lastUpdated = now; + _lastEdited = 0; _lastEditedFromRemote = 0; _lastEditedFromRemoteInRemoteTime = 0; - _lastSimulated = 0; - _lastUpdated = 0; + _created = UNKNOWN_CREATED_TIME; _dirtyFlags = 0; _changedOnServer = 0; initFromEntityItemID(entityItemID); - setProperties(properties, true); // force copy + setProperties(properties); } EntityPropertyFlags EntityItem::getEntityProperties(EncodeBitstreamParams& params) const { @@ -365,12 +366,15 @@ int EntityItem::readEntityDataFromBuffer(const unsigned char* data, int bytesLef memcpy(&createdFromBuffer, dataAt, sizeof(createdFromBuffer)); dataAt += sizeof(createdFromBuffer); bytesRead += sizeof(createdFromBuffer); - createdFromBuffer -= clockSkew; - - if (createdFromBuffer < _created) { - // the server claims that this entity has an older creation time so we accept it + + quint64 now = usecTimestampNow(); + if (_created == UNKNOWN_CREATED_TIME) { + // we don't yet have a _created timestamp, so we accept this one + createdFromBuffer -= clockSkew; + if (createdFromBuffer > now || createdFromBuffer == UNKNOWN_CREATED_TIME) { + createdFromBuffer = now; + } _created = createdFromBuffer; - _lastEdited = _created; } if (wantDebug) { @@ -385,7 +389,6 @@ int EntityItem::readEntityDataFromBuffer(const unsigned char* data, int bytesLef qDebug() << " ago=" << editedAgo << "seconds - " << agoAsString; } - quint64 now = usecTimestampNow(); quint64 lastEditedFromBuffer = 0; quint64 lastEditedFromBufferAdjusted = 0; @@ -395,6 +398,9 @@ int EntityItem::readEntityDataFromBuffer(const unsigned char* data, int bytesLef dataAt += sizeof(lastEditedFromBuffer); bytesRead += sizeof(lastEditedFromBuffer); lastEditedFromBufferAdjusted = lastEditedFromBuffer - clockSkew; + if (lastEditedFromBufferAdjusted > now) { + lastEditedFromBufferAdjusted = now; + } bool fromSameServerEdit = (lastEditedFromBuffer == _lastEditedFromRemoteInRemoteTime); @@ -444,10 +450,12 @@ int EntityItem::readEntityDataFromBuffer(const unsigned char* data, int bytesLef } // don't allow _lastEdited to be in the future - _lastEdited = lastEditedFromBufferAdjusted < now ? lastEditedFromBufferAdjusted : now; + _lastEdited = lastEditedFromBufferAdjusted; _lastEditedFromRemote = now; _lastEditedFromRemoteInRemoteTime = lastEditedFromBuffer; + // TODO: only send this notification if something ACTUALLY changed (hint, we haven't yet parsed + // the properties out of the bitstream (see below)) somethingChangedNotification(); // notify derived classes that something has changed } @@ -456,8 +464,7 @@ int EntityItem::readEntityDataFromBuffer(const unsigned char* data, int bytesLef ByteCountCoded updateDeltaCoder = encodedUpdateDelta; quint64 updateDelta = updateDeltaCoder; if (overwriteLocalData) { - _lastUpdated = lastEditedFromBufferAdjusted + updateDelta; // don't adjust for clock skew since we already did that for _lastEdited - _lastSimulated = now; + _lastUpdated = lastEditedFromBufferAdjusted + updateDelta; // don't adjust for clock skew since we already did that if (wantDebug) { qDebug() << "_lastUpdated =" << _lastUpdated; qDebug() << "_lastEdited=" << _lastEdited; @@ -529,6 +536,9 @@ int EntityItem::readEntityDataFromBuffer(const unsigned char* data, int bytesLef bytesRead += readEntitySubclassDataFromBuffer(dataAt, (bytesLeftToRead - bytesRead), args, propertyFlags, overwriteLocalData); recalculateCollisionShape(); + if (overwriteLocalData && (getDirtyFlags() & EntityItem::DIRTY_POSITION)) { + _lastSimulated = now; + } } return bytesRead; } @@ -774,21 +784,9 @@ EntityItemProperties EntityItem::getProperties() const { return properties; } -bool EntityItem::setProperties(const EntityItemProperties& properties, bool forceCopy) { +bool EntityItem::setProperties(const EntityItemProperties& properties) { bool somethingChanged = false; - // handle the setting of created timestamps for the basic new entity case - if (forceCopy) { - quint64 now = usecTimestampNow(); - if (properties.getCreated() == UNKNOWN_CREATED_TIME) { - _created = now; - } else if (properties.getCreated() != USE_EXISTING_CREATED_TIME) { - quint64 created = properties.getCreated(); - // don't allow _created to be in the future - _created = created < now ? created : now; - } - } - SET_ENTITY_PROPERTY_FROM_PROPERTIES(position, updatePositionInMeters); // this will call recalculate collision shape if needed SET_ENTITY_PROPERTY_FROM_PROPERTIES(dimensions, updateDimensionsInMeters); // NOTE: radius is obsolete SET_ENTITY_PROPERTY_FROM_PROPERTIES(rotation, updateRotation); @@ -818,16 +816,43 @@ bool EntityItem::setProperties(const EntityItemProperties& properties, bool forc qDebug() << "EntityItem::setProperties() AFTER update... edited AGO=" << elapsed << "now=" << now << " getLastEdited()=" << getLastEdited(); } - // don't allow _lastEdited to be in the future - setLastEdited(properties._lastEdited < now ? properties._lastEdited : now); + if (_created != UNKNOWN_CREATED_TIME) { + setLastEdited(now); + } if (getDirtyFlags() & EntityItem::DIRTY_POSITION) { - _lastSimulated = usecTimestampNow(); + _lastSimulated = now; } } - + + // timestamps + quint64 timestamp = properties.getCreated(); + if (_created == UNKNOWN_CREATED_TIME && timestamp != UNKNOWN_CREATED_TIME) { + quint64 now = usecTimestampNow(); + if (timestamp > now) { + timestamp = now; + } + _created = timestamp; + + timestamp = properties.getLastEdited(); + if (timestamp > now) { + timestamp = now; + } else if (timestamp < _created) { + timestamp = _created; + } + _lastEdited = timestamp; + } + return somethingChanged; } +void EntityItem::recordCreationTime() { + assert(_created == UNKNOWN_CREATED_TIME); + _created = usecTimestampNow(); + _lastEdited = _created; + _lastUpdated = _created; + _lastSimulated = _created; +} + // TODO: is this really correct? how do we use size, does it need to handle rotation? float EntityItem::getSize() const { diff --git a/libraries/entities/src/EntityItem.h b/libraries/entities/src/EntityItem.h index 7455b96f6b..0d0aa96706 100644 --- a/libraries/entities/src/EntityItem.h +++ b/libraries/entities/src/EntityItem.h @@ -74,12 +74,13 @@ public: virtual EntityItemProperties getProperties() const; /// returns true if something changed - virtual bool setProperties(const EntityItemProperties& properties, bool forceCopy = false); + virtual bool setProperties(const EntityItemProperties& properties); /// Override this in your derived class if you'd like to be informed when something about the state of the entity /// has changed. This will be called with properties change or when new data is loaded from a stream virtual void somethingChangedNotification() { } + void recordCreationTime(); // set _created to 'now' quint64 getLastSimulated() const { return _lastSimulated; } /// Last simulated time of this entity universal usecs /// Last edited time of this entity universal usecs diff --git a/libraries/entities/src/EntityItemProperties.cpp b/libraries/entities/src/EntityItemProperties.cpp index 11c9646cbc..58b110c4b0 100644 --- a/libraries/entities/src/EntityItemProperties.cpp +++ b/libraries/entities/src/EntityItemProperties.cpp @@ -156,6 +156,17 @@ void EntityItemProperties::debugDump() const { props.debugDumpBits(); } +void EntityItemProperties::setCreated(quint64 usecTime) { + _created = usecTime; + if (_lastEdited < _created) { + _lastEdited = _created; + } +} + +void EntityItemProperties::setLastEdited(quint64 usecTime) { + _lastEdited = usecTime > _created ? usecTime : _created; +} + EntityPropertyFlags EntityItemProperties::getChangedProperties() const { EntityPropertyFlags changedProperties; @@ -652,9 +663,6 @@ bool EntityItemProperties::decodeEntityEditPacket(const unsigned char* data, int entityID.creatorTokenID = UNKNOWN_ENTITY_TOKEN; entityID.isKnownID = true; valid = true; - - // created time is lastEdited time - properties.setCreated(USE_EXISTING_CREATED_TIME); } // Entity Type... diff --git a/libraries/entities/src/EntityItemProperties.h b/libraries/entities/src/EntityItemProperties.h index e5f78e8fc7..b843c85327 100644 --- a/libraries/entities/src/EntityItemProperties.h +++ b/libraries/entities/src/EntityItemProperties.h @@ -96,8 +96,6 @@ enum EntityPropertyList { typedef PropertyFlags EntityPropertyFlags; const quint64 UNKNOWN_CREATED_TIME = 0; -const quint64 USE_EXISTING_CREATED_TIME = 1; - /// A collection of properties of an entity item used in the scripting API. Translates between the actual properties of an /// entity and a JavaScript style hash/QScriptValue storing a set of properties. Used in scripting to set/get the complete @@ -134,7 +132,7 @@ public: AABox getAABoxInMeters() const; void debugDump() const; - void setLastEdited(quint64 usecTime) { _lastEdited = usecTime; } + void setLastEdited(quint64 usecTime); DEFINE_PROPERTY(PROP_VISIBLE, Visible, visible, bool); DEFINE_PROPERTY_REF_WITH_SETTER(PROP_POSITION, Position, position, glm::vec3); @@ -180,7 +178,7 @@ public: float getAge() const { return (float)(usecTimestampNow() - _created) / (float)USECS_PER_SECOND; } quint64 getCreated() const { return _created; } - void setCreated(quint64 usecTime) { _created = usecTime; } + void setCreated(quint64 usecTime); bool hasCreatedTime() const { return (_created != UNKNOWN_CREATED_TIME); } bool containsBoundsProperties() const { return (_positionChanged || _dimensionsChanged); } diff --git a/libraries/entities/src/EntityItemPropertiesMacros.h b/libraries/entities/src/EntityItemPropertiesMacros.h index 3288e56a3d..9f86156422 100644 --- a/libraries/entities/src/EntityItemPropertiesMacros.h +++ b/libraries/entities/src/EntityItemPropertiesMacros.h @@ -137,13 +137,13 @@ } #define SET_ENTITY_PROPERTY_FROM_PROPERTIES(P,M) \ - if (properties._##P##Changed || forceCopy) { \ + if (properties._##P##Changed) { \ M(properties._##P); \ somethingChanged = true; \ } #define SET_ENTITY_PROPERTY_FROM_PROPERTIES_GETTER(C,G,S) \ - if (properties.C() || forceCopy) { \ + if (properties.C()) { \ S(properties.G()); \ somethingChanged = true; \ } diff --git a/libraries/entities/src/EntityTree.cpp b/libraries/entities/src/EntityTree.cpp index fb8e4345f4..3580e64b35 100644 --- a/libraries/entities/src/EntityTree.cpp +++ b/libraries/entities/src/EntityTree.cpp @@ -164,9 +164,17 @@ EntityItem* EntityTree::addEntity(const EntityItemID& entityID, const EntityItem // NOTE: This method is used in the client and the server tree. In the client, it's possible to create EntityItems // that do not yet have known IDs. In the server tree however we don't want to have entities without known IDs. - if (getIsServer() && !entityID.isKnownID) { - qDebug() << "UNEXPECTED!!! ----- EntityTree::addEntity()... (getIsSever() && !entityID.isKnownID)"; - return result; + bool recordCreationTime = false; + if (!entityID.isKnownID) { + if (getIsServer()) { + qDebug() << "UNEXPECTED!!! ----- EntityTree::addEntity()... (getIsSever() && !entityID.isKnownID)"; + return result; + } + if (properties.getCreated() == UNKNOWN_CREATED_TIME) { + // the entity's creation time was not specified in properties, which means this is a NEW entity + // and we must record its creation time + recordCreationTime = true; + } } // You should not call this on existing entities that are already part of the tree! Call updateEntity() @@ -182,6 +190,9 @@ EntityItem* EntityTree::addEntity(const EntityItemID& entityID, const EntityItem result = EntityTypes::constructEntityItem(type, entityID, properties); if (result) { + if (recordCreationTime) { + result->recordCreationTime(); + } // Recurse the tree and store the entity in the correct tree element AddEntityOperator theOperator(this, result); recurseTreeWithOperator(&theOperator); diff --git a/libraries/entities/src/EntityTypes.cpp b/libraries/entities/src/EntityTypes.cpp index f7806445bc..fd9484e0d6 100644 --- a/libraries/entities/src/EntityTypes.cpp +++ b/libraries/entities/src/EntityTypes.cpp @@ -77,15 +77,7 @@ EntityItem* EntityTypes::constructEntityItem(EntityType entityType, const Entity factory = _factories[entityType]; } if (factory) { - // NOTE: if someone attempts to create an entity with properties that do not include a proper "created" time - // then set the created time to now - if (!properties.hasCreatedTime()) { - EntityItemProperties mutableProperties = properties; - mutableProperties.setCreated(usecTimestampNow()); - newEntityItem = factory(entityID, mutableProperties); - } else { - newEntityItem = factory(entityID, properties); - } + newEntityItem = factory(entityID, properties); } return newEntityItem; } @@ -128,13 +120,6 @@ EntityItem* EntityTypes::constructEntityItem(const unsigned char* data, int byte EntityItemID tempEntityID(actualID); EntityItemProperties tempProperties; - - // we set the Creation and Edit times to 'now', but if the server submits an earlier Creation time - // then it will be accepted - quint64 now = usecTimestampNow(); - tempProperties.setCreated(now); - tempProperties.setLastEdited(now); - return constructEntityItem(entityType, tempEntityID, tempProperties); } From b03e6c53e1b34c7b110c8ba4b0b6af01c7748e30 Mon Sep 17 00:00:00 2001 From: Andrew Meadows Date: Thu, 18 Dec 2014 11:41:20 -0800 Subject: [PATCH 187/258] fixing derived classes to use new EntityItem API remove 'forceCopy' argument in EntityItem::setProperties() --- .../entities-renderer/src/RenderableModelEntityItem.cpp | 4 ++-- libraries/entities-renderer/src/RenderableModelEntityItem.h | 2 +- libraries/entities/src/BoxEntityItem.cpp | 6 +++--- libraries/entities/src/BoxEntityItem.h | 2 +- libraries/entities/src/LightEntityItem.cpp | 6 +++--- libraries/entities/src/LightEntityItem.h | 2 +- libraries/entities/src/ModelEntityItem.cpp | 6 +++--- libraries/entities/src/ModelEntityItem.h | 2 +- libraries/entities/src/SphereEntityItem.cpp | 6 +++--- libraries/entities/src/SphereEntityItem.h | 2 +- libraries/entities/src/TextEntityItem.cpp | 6 +++--- libraries/entities/src/TextEntityItem.h | 2 +- 12 files changed, 23 insertions(+), 23 deletions(-) diff --git a/libraries/entities-renderer/src/RenderableModelEntityItem.cpp b/libraries/entities-renderer/src/RenderableModelEntityItem.cpp index 3e5118d203..92e925d73e 100644 --- a/libraries/entities-renderer/src/RenderableModelEntityItem.cpp +++ b/libraries/entities-renderer/src/RenderableModelEntityItem.cpp @@ -34,9 +34,9 @@ RenderableModelEntityItem::~RenderableModelEntityItem() { } } -bool RenderableModelEntityItem::setProperties(const EntityItemProperties& properties, bool forceCopy) { +bool RenderableModelEntityItem::setProperties(const EntityItemProperties& properties) { QString oldModelURL = getModelURL(); - bool somethingChanged = ModelEntityItem::setProperties(properties, forceCopy); + bool somethingChanged = ModelEntityItem::setProperties(properties); if (somethingChanged && oldModelURL != getModelURL()) { _needsModelReload = true; } diff --git a/libraries/entities-renderer/src/RenderableModelEntityItem.h b/libraries/entities-renderer/src/RenderableModelEntityItem.h index 6f61a1b9db..65cded0207 100644 --- a/libraries/entities-renderer/src/RenderableModelEntityItem.h +++ b/libraries/entities-renderer/src/RenderableModelEntityItem.h @@ -35,7 +35,7 @@ public: virtual ~RenderableModelEntityItem(); virtual EntityItemProperties getProperties() const; - virtual bool setProperties(const EntityItemProperties& properties, bool forceCopy); + virtual bool setProperties(const EntityItemProperties& properties); virtual int readEntitySubclassDataFromBuffer(const unsigned char* data, int bytesLeftToRead, ReadBitstreamToTreeParams& args, EntityPropertyFlags& propertyFlags, bool overwriteLocalData); diff --git a/libraries/entities/src/BoxEntityItem.cpp b/libraries/entities/src/BoxEntityItem.cpp index 16204f0c16..cece544263 100644 --- a/libraries/entities/src/BoxEntityItem.cpp +++ b/libraries/entities/src/BoxEntityItem.cpp @@ -29,7 +29,7 @@ BoxEntityItem::BoxEntityItem(const EntityItemID& entityItemID, const EntityItemP { _type = EntityTypes::Box; _created = properties.getCreated(); - setProperties(properties, true); + setProperties(properties); } EntityItemProperties BoxEntityItem::getProperties() const { @@ -44,9 +44,9 @@ EntityItemProperties BoxEntityItem::getProperties() const { return properties; } -bool BoxEntityItem::setProperties(const EntityItemProperties& properties, bool forceCopy) { +bool BoxEntityItem::setProperties(const EntityItemProperties& properties) { bool somethingChanged = false; - somethingChanged = EntityItem::setProperties(properties, forceCopy); // set the properties in our base class + somethingChanged = EntityItem::setProperties(properties); // set the properties in our base class SET_ENTITY_PROPERTY_FROM_PROPERTIES(color, setColor); diff --git a/libraries/entities/src/BoxEntityItem.h b/libraries/entities/src/BoxEntityItem.h index b5f4521f96..da9e7544c6 100644 --- a/libraries/entities/src/BoxEntityItem.h +++ b/libraries/entities/src/BoxEntityItem.h @@ -24,7 +24,7 @@ public: // methods for getting/setting all properties of an entity virtual EntityItemProperties getProperties() const; - virtual bool setProperties(const EntityItemProperties& properties, bool forceCopy = false); + virtual bool setProperties(const EntityItemProperties& properties); // TODO: eventually only include properties changed since the params.lastViewFrustumSent time virtual EntityPropertyFlags getEntityProperties(EncodeBitstreamParams& params) const; diff --git a/libraries/entities/src/LightEntityItem.cpp b/libraries/entities/src/LightEntityItem.cpp index 44b83bc94e..c125364e63 100644 --- a/libraries/entities/src/LightEntityItem.cpp +++ b/libraries/entities/src/LightEntityItem.cpp @@ -41,7 +41,7 @@ LightEntityItem::LightEntityItem(const EntityItemID& entityItemID, const EntityI _exponent = 0.0f; _cutoff = PI; - setProperties(properties, true); + setProperties(properties); // a light is not collide-able so we make it's shape be a tiny sphere at origin _emptyShape.setTranslation(glm::vec3(0.0f, 0.0f, 0.0f)); @@ -71,8 +71,8 @@ EntityItemProperties LightEntityItem::getProperties() const { return properties; } -bool LightEntityItem::setProperties(const EntityItemProperties& properties, bool forceCopy) { - bool somethingChanged = EntityItem::setProperties(properties, forceCopy); // set the properties in our base class +bool LightEntityItem::setProperties(const EntityItemProperties& properties) { + bool somethingChanged = EntityItem::setProperties(properties); // set the properties in our base class SET_ENTITY_PROPERTY_FROM_PROPERTIES(isSpotlight, setIsSpotlight); SET_ENTITY_PROPERTY_FROM_PROPERTIES(diffuseColor, setDiffuseColor); diff --git a/libraries/entities/src/LightEntityItem.h b/libraries/entities/src/LightEntityItem.h index 6ebb85beda..249a4c8472 100644 --- a/libraries/entities/src/LightEntityItem.h +++ b/libraries/entities/src/LightEntityItem.h @@ -28,7 +28,7 @@ public: // methods for getting/setting all properties of an entity virtual EntityItemProperties getProperties() const; - virtual bool setProperties(const EntityItemProperties& properties, bool forceCopy = false); + virtual bool setProperties(const EntityItemProperties& properties); virtual EntityPropertyFlags getEntityProperties(EncodeBitstreamParams& params) const; diff --git a/libraries/entities/src/ModelEntityItem.cpp b/libraries/entities/src/ModelEntityItem.cpp index b14248b3bc..02ebbebdb4 100644 --- a/libraries/entities/src/ModelEntityItem.cpp +++ b/libraries/entities/src/ModelEntityItem.cpp @@ -34,7 +34,7 @@ ModelEntityItem::ModelEntityItem(const EntityItemID& entityItemID, const EntityI EntityItem(entityItemID, properties) { _type = EntityTypes::Model; - setProperties(properties, true); + setProperties(properties); _lastAnimated = usecTimestampNow(); _jointMappingCompleted = false; _color[0] = _color[1] = _color[2] = 0; @@ -55,9 +55,9 @@ EntityItemProperties ModelEntityItem::getProperties() const { return properties; } -bool ModelEntityItem::setProperties(const EntityItemProperties& properties, bool forceCopy) { +bool ModelEntityItem::setProperties(const EntityItemProperties& properties) { bool somethingChanged = false; - somethingChanged = EntityItem::setProperties(properties, forceCopy); // set the properties in our base class + somethingChanged = EntityItem::setProperties(properties); // set the properties in our base class SET_ENTITY_PROPERTY_FROM_PROPERTIES(color, setColor); SET_ENTITY_PROPERTY_FROM_PROPERTIES(modelURL, setModelURL); diff --git a/libraries/entities/src/ModelEntityItem.h b/libraries/entities/src/ModelEntityItem.h index 6b4ca2416a..4c14dca177 100644 --- a/libraries/entities/src/ModelEntityItem.h +++ b/libraries/entities/src/ModelEntityItem.h @@ -26,7 +26,7 @@ public: // methods for getting/setting all properties of an entity virtual EntityItemProperties getProperties() const; - virtual bool setProperties(const EntityItemProperties& properties, bool forceCopy = false); + virtual bool setProperties(const EntityItemProperties& properties); // TODO: eventually only include properties changed since the params.lastViewFrustumSent time virtual EntityPropertyFlags getEntityProperties(EncodeBitstreamParams& params) const; diff --git a/libraries/entities/src/SphereEntityItem.cpp b/libraries/entities/src/SphereEntityItem.cpp index b0df310ad2..06035f6b6e 100644 --- a/libraries/entities/src/SphereEntityItem.cpp +++ b/libraries/entities/src/SphereEntityItem.cpp @@ -31,7 +31,7 @@ SphereEntityItem::SphereEntityItem(const EntityItemID& entityItemID, const Entit EntityItem(entityItemID, properties) { _type = EntityTypes::Sphere; - setProperties(properties, true); + setProperties(properties); } EntityItemProperties SphereEntityItem::getProperties() const { @@ -40,8 +40,8 @@ EntityItemProperties SphereEntityItem::getProperties() const { return properties; } -bool SphereEntityItem::setProperties(const EntityItemProperties& properties, bool forceCopy) { - bool somethingChanged = EntityItem::setProperties(properties, forceCopy); // set the properties in our base class +bool SphereEntityItem::setProperties(const EntityItemProperties& properties) { + bool somethingChanged = EntityItem::setProperties(properties); // set the properties in our base class SET_ENTITY_PROPERTY_FROM_PROPERTIES(color, setColor); diff --git a/libraries/entities/src/SphereEntityItem.h b/libraries/entities/src/SphereEntityItem.h index 74cc7d1635..3b7dccaff9 100644 --- a/libraries/entities/src/SphereEntityItem.h +++ b/libraries/entities/src/SphereEntityItem.h @@ -25,7 +25,7 @@ public: // methods for getting/setting all properties of an entity virtual EntityItemProperties getProperties() const; - virtual bool setProperties(const EntityItemProperties& properties, bool forceCopy = false); + virtual bool setProperties(const EntityItemProperties& properties); virtual EntityPropertyFlags getEntityProperties(EncodeBitstreamParams& params) const; diff --git a/libraries/entities/src/TextEntityItem.cpp b/libraries/entities/src/TextEntityItem.cpp index bb76a2e690..c43638f827 100644 --- a/libraries/entities/src/TextEntityItem.cpp +++ b/libraries/entities/src/TextEntityItem.cpp @@ -37,7 +37,7 @@ TextEntityItem::TextEntityItem(const EntityItemID& entityItemID, const EntityIte { _type = EntityTypes::Text; _created = properties.getCreated(); - setProperties(properties, true); + setProperties(properties); } void TextEntityItem::setDimensions(const glm::vec3& value) { @@ -57,9 +57,9 @@ EntityItemProperties TextEntityItem::getProperties() const { return properties; } -bool TextEntityItem::setProperties(const EntityItemProperties& properties, bool forceCopy) { +bool TextEntityItem::setProperties(const EntityItemProperties& properties) { bool somethingChanged = false; - somethingChanged = EntityItem::setProperties(properties, forceCopy); // set the properties in our base class + somethingChanged = EntityItem::setProperties(properties); // set the properties in our base class SET_ENTITY_PROPERTY_FROM_PROPERTIES(text, setText); SET_ENTITY_PROPERTY_FROM_PROPERTIES(lineHeight, setLineHeight); diff --git a/libraries/entities/src/TextEntityItem.h b/libraries/entities/src/TextEntityItem.h index 83143b1134..1f0bd7d85e 100644 --- a/libraries/entities/src/TextEntityItem.h +++ b/libraries/entities/src/TextEntityItem.h @@ -27,7 +27,7 @@ public: // methods for getting/setting all properties of an entity virtual EntityItemProperties getProperties() const; - virtual bool setProperties(const EntityItemProperties& properties, bool forceCopy = false); + virtual bool setProperties(const EntityItemProperties& properties); // TODO: eventually only include properties changed since the params.lastViewFrustumSent time virtual EntityPropertyFlags getEntityProperties(EncodeBitstreamParams& params) const; From 587df1178dfc19dc31e261466bd54ffa138fe646 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 18 Dec 2014 13:57:19 -0800 Subject: [PATCH 188/258] use constant for MSEC to USEC conversion --- libraries/networking/src/LimitedNodeList.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/networking/src/LimitedNodeList.cpp b/libraries/networking/src/LimitedNodeList.cpp index c6e79cc18f..de533ec7be 100644 --- a/libraries/networking/src/LimitedNodeList.cpp +++ b/libraries/networking/src/LimitedNodeList.cpp @@ -504,7 +504,7 @@ void LimitedNodeList::removeSilentNodes() { SharedNodePointer node = it->second; node->getMutex().lock(); - if ((usecTimestampNow() - node->getLastHeardMicrostamp()) > (NODE_SILENCE_THRESHOLD_MSECS * 1000)) { + if ((usecTimestampNow() - node->getLastHeardMicrostamp()) > (NODE_SILENCE_THRESHOLD_MSECS * USECS_PER_MSEC)) { // call the NodeHash erase to get rid of this node it = _nodeHash.unsafe_erase(it); From df3eca5aca594a6f8b6108c09f9fa72945076ea7 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 18 Dec 2014 14:01:22 -0800 Subject: [PATCH 189/258] add a comment for the UUID hasher --- libraries/networking/src/UUIDHasher.h | 3 +++ 1 file changed, 3 insertions(+) diff --git a/libraries/networking/src/UUIDHasher.h b/libraries/networking/src/UUIDHasher.h index d5d16e21e9..02f7e3685a 100644 --- a/libraries/networking/src/UUIDHasher.h +++ b/libraries/networking/src/UUIDHasher.h @@ -14,6 +14,9 @@ #include "UUID.h" +// uses the same hashing performed by Qt +// https://qt.gitorious.org/qt/qtbase/source/73ef64fb5fabb60101a3cac6e43f0c5bb2298000:src/corelib/plugin/quuid.cpp + class UUIDHasher { public: size_t operator()(const QUuid& uuid) const { From 07f95c597cde73fa127c72085e443f65cb2c68f5 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 18 Dec 2014 14:08:55 -0800 Subject: [PATCH 190/258] add read locks for find on tbb hash --- libraries/networking/src/LimitedNodeList.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/libraries/networking/src/LimitedNodeList.cpp b/libraries/networking/src/LimitedNodeList.cpp index de533ec7be..907ac86704 100644 --- a/libraries/networking/src/LimitedNodeList.cpp +++ b/libraries/networking/src/LimitedNodeList.cpp @@ -352,6 +352,8 @@ int LimitedNodeList::findNodeAndUpdateWithDataFromPacket(const QByteArray& packe } SharedNodePointer LimitedNodeList::nodeWithUUID(const QUuid& nodeUUID) { + QReadLocker readLocker(&_nodeMutex); + NodeHash::const_iterator it = _nodeHash.find(nodeUUID); return it == _nodeHash.cend() ? SharedNodePointer() : it->second; } @@ -386,10 +388,14 @@ void LimitedNodeList::reset() { } void LimitedNodeList::killNodeWithUUID(const QUuid& nodeUUID) { + _nodeMutex.lockForRead(); + NodeHash::iterator it = _nodeHash.find(nodeUUID); if (it != _nodeHash.end()) { SharedNodePointer matchingNode = it->second; + _nodeMutex.unlock(); + QWriteLocker writeLocker(&_nodeMutex); _nodeHash.unsafe_erase(it); From e13e9febdc69178a13e29e3e993b5f339bcfb0be Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 18 Dec 2014 14:16:22 -0800 Subject: [PATCH 191/258] unlock the node mutex if node not found --- libraries/networking/src/LimitedNodeList.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/libraries/networking/src/LimitedNodeList.cpp b/libraries/networking/src/LimitedNodeList.cpp index 907ac86704..5e13f6bbc9 100644 --- a/libraries/networking/src/LimitedNodeList.cpp +++ b/libraries/networking/src/LimitedNodeList.cpp @@ -400,6 +400,8 @@ void LimitedNodeList::killNodeWithUUID(const QUuid& nodeUUID) { _nodeHash.unsafe_erase(it); handleNodeKill(matchingNode); + } else { + _nodeMutex.unlock(); } } From 325d0dbce1daac75a9a6eda26df62616142d3fd2 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 18 Dec 2014 14:31:34 -0800 Subject: [PATCH 192/258] include QUuid instead of UUID in UUIDHasher --- libraries/networking/src/UUIDHasher.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/networking/src/UUIDHasher.h b/libraries/networking/src/UUIDHasher.h index 02f7e3685a..5429e151c7 100644 --- a/libraries/networking/src/UUIDHasher.h +++ b/libraries/networking/src/UUIDHasher.h @@ -12,7 +12,7 @@ #ifndef hifi_UUIDHasher_h #define hifi_UUIDHasher_h -#include "UUID.h" +#include // uses the same hashing performed by Qt // https://qt.gitorious.org/qt/qtbase/source/73ef64fb5fabb60101a3cac6e43f0c5bb2298000:src/corelib/plugin/quuid.cpp From 6beaa3d59a061ee9f111668ee7c90a32f9eb6c95 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 18 Dec 2014 14:36:15 -0800 Subject: [PATCH 193/258] set policy for shared lib creation on OS X --- CMakeLists.txt | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CMakeLists.txt b/CMakeLists.txt index 7a6118bb87..a0d463b766 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -12,6 +12,10 @@ if (POLICY CMP0043) cmake_policy(SET CMP0043 OLD) endif () +if (POLICY CMP0042) + cmake_policy(SET CMP0042 OLD) +endif () + project(hifi) add_definitions(-DGLM_FORCE_RADIANS) From 6a604ca340f24d514fccdd9f83c776ad43d98f98 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 18 Dec 2014 14:36:31 -0800 Subject: [PATCH 194/258] fix missing script dependency from shared --- libraries/shared/CMakeLists.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/libraries/shared/CMakeLists.txt b/libraries/shared/CMakeLists.txt index 17ccbdc6ce..b5a44c96e2 100644 --- a/libraries/shared/CMakeLists.txt +++ b/libraries/shared/CMakeLists.txt @@ -1,7 +1,8 @@ set(TARGET_NAME shared) # use setup_hifi_library macro to setup our project and link appropriate Qt modules -setup_hifi_library(Network Widgets) +# TODO: there isn't really a good reason to have Script linked here - let's get what is requiring it out (RegisteredMetaTypes.cpp) +setup_hifi_library(Network Script Widgets) # call macro to link our dependencies and bubble them up via a property on our target link_shared_dependencies() \ No newline at end of file From ecb17a61d6c7609b218ff92e8bad03a62d404223 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 18 Dec 2014 14:39:35 -0800 Subject: [PATCH 195/258] fix missing render-utils dependencies --- libraries/render-utils/CMakeLists.txt | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/libraries/render-utils/CMakeLists.txt b/libraries/render-utils/CMakeLists.txt index a6943addcc..881a75636b 100644 --- a/libraries/render-utils/CMakeLists.txt +++ b/libraries/render-utils/CMakeLists.txt @@ -5,11 +5,15 @@ setup_hifi_library(Widgets OpenGL Network Script) include_glm() -link_hifi_libraries(shared gpu) +link_hifi_libraries(fbx shared gpu) -if (WIN32) +if (APPLE) + find_library(GLUT GLUT) + target_link_libraries(${TARGET_NAME} GLUT) +else () find_package(GLUT REQUIRED) include_directories(SYSTEM "${GLUT_INCLUDE_DIRS}") + target_link_libraries(${TARGET_NAME} ${GLUT_LIBRARIES}) endif () # call macro to link our dependencies and bubble them up via a property on our target From 1b5552de1a9e2f0225cde7faf7a4a70284c520b2 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 18 Dec 2014 14:42:08 -0800 Subject: [PATCH 196/258] fix GLUT library link in render-utils --- libraries/render-utils/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/render-utils/CMakeLists.txt b/libraries/render-utils/CMakeLists.txt index 881a75636b..4108462000 100644 --- a/libraries/render-utils/CMakeLists.txt +++ b/libraries/render-utils/CMakeLists.txt @@ -9,7 +9,7 @@ link_hifi_libraries(fbx shared gpu) if (APPLE) find_library(GLUT GLUT) - target_link_libraries(${TARGET_NAME} GLUT) + target_link_libraries(${TARGET_NAME} ${GLUT}) else () find_package(GLUT REQUIRED) include_directories(SYSTEM "${GLUT_INCLUDE_DIRS}") From 4f4ffc42d35d269ce871d25146edc86eb5829726 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 18 Dec 2014 14:52:16 -0800 Subject: [PATCH 197/258] add missing link to fbx from avatars --- libraries/avatars/CMakeLists.txt | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/libraries/avatars/CMakeLists.txt b/libraries/avatars/CMakeLists.txt index 42b3cf7d3c..20aba226e0 100644 --- a/libraries/avatars/CMakeLists.txt +++ b/libraries/avatars/CMakeLists.txt @@ -5,8 +5,7 @@ setup_hifi_library(Network Script) include_glm() -link_hifi_libraries(shared octree voxels networking physics) -include_hifi_library_headers(fbx) +link_hifi_libraries(audio shared octree voxels networking physics fbx) # call macro to link our dependencies and bubble them up via a property on our target link_shared_dependencies() From e8adc19ac67088c386b56b21c528925829a04644 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 18 Dec 2014 14:52:31 -0800 Subject: [PATCH 198/258] fix more missing dependencies in render-utils --- libraries/render-utils/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/render-utils/CMakeLists.txt b/libraries/render-utils/CMakeLists.txt index 4108462000..211c7266b3 100644 --- a/libraries/render-utils/CMakeLists.txt +++ b/libraries/render-utils/CMakeLists.txt @@ -5,7 +5,7 @@ setup_hifi_library(Widgets OpenGL Network Script) include_glm() -link_hifi_libraries(fbx shared gpu) +link_hifi_libraries(animation fbx shared gpu) if (APPLE) find_library(GLUT GLUT) From 4bd3a94794ba8352c4dbc69227455587dd5bd7cb Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 18 Dec 2014 14:53:52 -0800 Subject: [PATCH 199/258] add missing avatars link to entities --- libraries/entities/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/entities/CMakeLists.txt b/libraries/entities/CMakeLists.txt index e48baa7615..d6f503f2ca 100644 --- a/libraries/entities/CMakeLists.txt +++ b/libraries/entities/CMakeLists.txt @@ -5,7 +5,7 @@ setup_hifi_library(Network Script) include_glm() -link_hifi_libraries(shared octree fbx networking animation physics) +link_hifi_libraries(avatars shared octree fbx networking animation physics) # call macro to link our dependencies and bubble them up via a property on our target link_shared_dependencies() From d87e06a9d36ff91f51905f05749c74c55e6ec3f2 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 18 Dec 2014 14:54:05 -0800 Subject: [PATCH 200/258] add missing metavoxels link to script-engine --- libraries/script-engine/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/script-engine/CMakeLists.txt b/libraries/script-engine/CMakeLists.txt index 3b3a63549d..7118e84443 100644 --- a/libraries/script-engine/CMakeLists.txt +++ b/libraries/script-engine/CMakeLists.txt @@ -5,7 +5,7 @@ setup_hifi_library(Gui Network Script Widgets) include_glm() -link_hifi_libraries(shared octree voxels fbx entities animation audio physics) +link_hifi_libraries(shared octree voxels fbx entities animation audio physics metavoxels) # call macro to link our dependencies and bubble them up via a property on our target link_shared_dependencies() From f474cfc9d0e89abf3ec52758582db575e08514da Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 18 Dec 2014 15:06:44 -0800 Subject: [PATCH 201/258] link to render-utils from entities renderer --- libraries/entities-renderer/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/entities-renderer/CMakeLists.txt b/libraries/entities-renderer/CMakeLists.txt index 1e77afe544..3b8a214675 100644 --- a/libraries/entities-renderer/CMakeLists.txt +++ b/libraries/entities-renderer/CMakeLists.txt @@ -5,7 +5,7 @@ setup_hifi_library(Widgets OpenGL Network Script) include_glm() -link_hifi_libraries(shared gpu script-engine) +link_hifi_libraries(shared gpu script-engine render-utils) # call macro to link our dependencies and bubble them up via a property on our target link_shared_dependencies() From 26bcca95c90e650076b23b7c4b69dd2780a9e278 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Thu, 18 Dec 2014 15:42:02 -0800 Subject: [PATCH 202/258] remove glutWireCube() --- libraries/render-utils/src/GeometryCache.cpp | 60 +++++++++++++++++++- libraries/render-utils/src/GeometryCache.h | 2 + 2 files changed, 61 insertions(+), 1 deletion(-) diff --git a/libraries/render-utils/src/GeometryCache.cpp b/libraries/render-utils/src/GeometryCache.cpp index e31ae2333a..d28702fa20 100644 --- a/libraries/render-utils/src/GeometryCache.cpp +++ b/libraries/render-utils/src/GeometryCache.cpp @@ -513,7 +513,65 @@ void GeometryCache::renderSolidCube(float size) { } void GeometryCache::renderWireCube(float size) { - glutWireCube(size); + VerticesIndices& vbo = _wireCubeVBOs[size]; + const int FLOATS_PER_VERTEX = 3; + const int VERTICES_PER_EDGE = 2; + const int TOP_EDGES = 4; + const int BOTTOM_EDGES = 4; + const int SIDE_EDGES = 4; + const int vertices = 8; + const int indices = (TOP_EDGES + BOTTOM_EDGES + SIDE_EDGES) * VERTICES_PER_EDGE; + if (vbo.first == 0) { + int vertexPoints = vertices * FLOATS_PER_VERTEX; + GLfloat* vertexData = new GLfloat[vertexPoints]; // only vertices, no normals because we're a wire cube + GLfloat* vertex = vertexData; + float halfSize = size / 2.0f; + + static GLfloat cannonicalVertices[] = + { 1, 1, 1, 1, 1,-1, -1, 1,-1, -1, 1, 1, // v0, v1, v2, v3 (top) + 1,-1, 1, 1,-1,-1, -1,-1,-1, -1,-1, 1 // v4, v5, v6, v7 (bottom) + }; + + // index array of vertex array for glDrawRangeElement() as a GL_LINES for each edge + const GLubyte LINE_BREAK = static_cast(-1); + static GLubyte cannonicalIndices[indices] = { + 0, 1, 1, 2, 2, 3, 3, 0, // (top) + 4, 5, 5, 6, 6, 7, 7, 4, // (bottom) + 0, 4, 1, 5, 2, 6, 3, 7, // (side edges) + }; + + for (int i = 0; i < vertexPoints; i++) { + vertex[i] = cannonicalVertices[i] * halfSize; + } + + glGenBuffers(1, &vbo.first); + glBindBuffer(GL_ARRAY_BUFFER, vbo.first); + glBufferData(GL_ARRAY_BUFFER, vertices * NUM_BYTES_PER_VERTEX, vertexData, GL_STATIC_DRAW); + delete[] vertexData; + + GLushort* indexData = new GLushort[indices]; + GLushort* index = indexData; + for (int i = 0; i < indices; i++) { + index[i] = cannonicalIndices[i]; + } + + glGenBuffers(1, &vbo.second); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo.second); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices * NUM_BYTES_PER_INDEX, indexData, GL_STATIC_DRAW); + delete[] indexData; + + } else { + glBindBuffer(GL_ARRAY_BUFFER, vbo.first); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo.second); + } + glEnableClientState(GL_VERTEX_ARRAY); + glVertexPointer(FLOATS_PER_VERTEX, GL_FLOAT, FLOATS_PER_VERTEX * sizeof(float), 0); + glDrawRangeElementsEXT(GL_LINES, 0, vertices - 1, indices, GL_UNSIGNED_SHORT, 0); + glDisableClientState(GL_VERTEX_ARRAY); + + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); + } diff --git a/libraries/render-utils/src/GeometryCache.h b/libraries/render-utils/src/GeometryCache.h index 92e65718ab..514ee03c79 100644 --- a/libraries/render-utils/src/GeometryCache.h +++ b/libraries/render-utils/src/GeometryCache.h @@ -68,6 +68,8 @@ private: QHash _squareVBOs; QHash _halfCylinderVBOs; QHash _coneVBOs; + QHash _wireCubeVBOs; + QHash _solidCubeVBOs; QHash _gridBuffers; QHash > _networkGeometry; From 087ac1db90394ee8dff79e2c97dcbcb9bb324ea1 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 18 Dec 2014 16:03:13 -0800 Subject: [PATCH 203/258] send port along with domain hostname lookup --- libraries/networking/src/AddressManager.cpp | 25 +++++++++++---------- 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/libraries/networking/src/AddressManager.cpp b/libraries/networking/src/AddressManager.cpp index 81b3a1328b..1352c54c79 100644 --- a/libraries/networking/src/AddressManager.cpp +++ b/libraries/networking/src/AddressManager.cpp @@ -107,7 +107,8 @@ bool AddressManager::handleUrl(const QUrl& lookupUrl) { if (!handleUsername(lookupUrl.authority())) { // we're assuming this is either a network address or global place name // check if it is a network address first - if (!handleNetworkAddress(lookupUrl.host())) { + if (!handleNetworkAddress(lookupUrl.host() + + (lookupUrl.port() == -1 ? "" : ":" + QString::number(lookupUrl.port())))) { // wasn't an address - lookup the place name attemptPlaceNameLookup(lookupUrl.host()); } @@ -246,17 +247,6 @@ bool AddressManager::handleNetworkAddress(const QString& lookupString) { const QString HOSTNAME_REGEX_STRING = "^((?:[A-Z0-9]|[A-Z0-9][A-Z0-9\\-]{0,61}[A-Z0-9])" "(?:\\.(?:[A-Z0-9]|[A-Z0-9][A-Z0-9\\-]{0,61}[A-Z0-9]))+|localhost)(:{1}\\d{1,5})?$"; - QRegExp hostnameRegex(HOSTNAME_REGEX_STRING, Qt::CaseInsensitive); - - if (hostnameRegex.indexIn(lookupString) != -1) { - QString domainHostname = hostnameRegex.cap(0); - - emit lookupResultsFinished(); - setDomainHostnameAndName(domainHostname); - - return true; - } - QRegExp ipAddressRegex(IP_ADDRESS_REGEX_STRING); if (ipAddressRegex.indexIn(lookupString) != -1) { @@ -268,6 +258,17 @@ bool AddressManager::handleNetworkAddress(const QString& lookupString) { return true; } + QRegExp hostnameRegex(HOSTNAME_REGEX_STRING, Qt::CaseInsensitive); + + if (hostnameRegex.indexIn(lookupString) != -1) { + QString domainHostname = hostnameRegex.cap(0); + + emit lookupResultsFinished(); + setDomainHostnameAndName(domainHostname); + + return true; + } + return false; } From 8091564a731f3ea08a275197b3935ce0e5078ae2 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Thu, 18 Dec 2014 16:12:30 -0800 Subject: [PATCH 204/258] remove all glut --- interface/src/Application.cpp | 2 - interface/src/Util.cpp | 6 -- libraries/gpu/src/gpu/GLUTConfig.h | 25 ------ libraries/render-utils/src/GeometryCache.cpp | 95 +++++++++++++++++++- 4 files changed, 91 insertions(+), 37 deletions(-) delete mode 100644 libraries/gpu/src/gpu/GLUTConfig.h diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index d502e380b5..a7b91db315 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -537,8 +537,6 @@ void Application::initializeGL() { } else { isInitialized = true; } - int argc = 0; - glutInit(&argc, 0); #endif #ifdef WIN32 diff --git a/interface/src/Util.cpp b/interface/src/Util.cpp index 38f18e96d9..d795964c5c 100644 --- a/interface/src/Util.cpp +++ b/interface/src/Util.cpp @@ -33,12 +33,6 @@ using namespace std; -// no clue which versions are affected... -#define WORKAROUND_BROKEN_GLUT_STROKES -// see http://www.opengl.org/resources/libraries/glut/spec3/node78.html - - - void renderWorldBox() { // Show edge of world float red[] = {1, 0, 0}; diff --git a/libraries/gpu/src/gpu/GLUTConfig.h b/libraries/gpu/src/gpu/GLUTConfig.h deleted file mode 100644 index 214f2bb2b0..0000000000 --- a/libraries/gpu/src/gpu/GLUTConfig.h +++ /dev/null @@ -1,25 +0,0 @@ -// -// GPUConfig.h -// libraries/gpu/src/gpu -// -// Created by Brad Hefta-Gaub on 12/17/14. -// Copyright 2014 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -#ifndef gpu__GLUTConfig__ -#define gpu__GLUTConfig__ - -// TODO: remove these once we migrate away from GLUT calls -#if defined(__APPLE__) -#include -#elif defined(WIN32) -#include -#else -#include -#endif - - -#endif // gpu__GLUTConfig__ diff --git a/libraries/render-utils/src/GeometryCache.cpp b/libraries/render-utils/src/GeometryCache.cpp index d28702fa20..2837568ef5 100644 --- a/libraries/render-utils/src/GeometryCache.cpp +++ b/libraries/render-utils/src/GeometryCache.cpp @@ -11,7 +11,6 @@ // include this before QOpenGLBuffer, which includes an earlier version of OpenGL #include -#include // TODO - we need to get rid of this ASAP #include @@ -509,7 +508,97 @@ void GeometryCache::renderGrid(int xDivisions, int yDivisions) { } void GeometryCache::renderSolidCube(float size) { - glutSolidCube(size); + VerticesIndices& vbo = _solidCubeVBOs[size]; + const int FLOATS_PER_VERTEX = 3; + const int VERTICES_PER_FACE = 4; + const int NUMBER_OF_FACES = 6; + const int TRIANGLES_PER_FACE = 2; + const int VERTICES_PER_TRIANGLE = 3; + const int vertices = NUMBER_OF_FACES * VERTICES_PER_FACE * FLOATS_PER_VERTEX; + const int indices = NUMBER_OF_FACES * TRIANGLES_PER_FACE * VERTICES_PER_TRIANGLE; + const int vertexPoints = vertices * FLOATS_PER_VERTEX; + if (vbo.first == 0) { + GLfloat* vertexData = new GLfloat[vertexPoints * 2]; // vertices and normals + GLfloat* vertex = vertexData; + float halfSize = size / 2.0f; + + static GLfloat cannonicalVertices[vertexPoints] = + { 1, 1, 1, -1, 1, 1, -1,-1, 1, 1,-1, 1, // v0,v1,v2,v3 (front) + 1, 1, 1, 1,-1, 1, 1,-1,-1, 1, 1,-1, // v0,v3,v4,v5 (right) + 1, 1, 1, 1, 1,-1, -1, 1,-1, -1, 1, 1, // v0,v5,v6,v1 (top) + -1, 1, 1, -1, 1,-1, -1,-1,-1, -1,-1, 1, // v1,v6,v7,v2 (left) + -1,-1,-1, 1,-1,-1, 1,-1, 1, -1,-1, 1, // v7,v4,v3,v2 (bottom) + 1,-1,-1, -1,-1,-1, -1, 1,-1, 1, 1,-1 }; // v4,v7,v6,v5 (back) + + // normal array + static GLfloat cannonicalNormals[vertexPoints] = + { 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, // v0,v1,v2,v3 (front) + 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, // v0,v3,v4,v5 (right) + 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, // v0,v5,v6,v1 (top) + -1, 0, 0, -1, 0, 0, -1, 0, 0, -1, 0, 0, // v1,v6,v7,v2 (left) + 0,-1, 0, 0,-1, 0, 0,-1, 0, 0,-1, 0, // v7,v4,v3,v2 (bottom) + 0, 0,-1, 0, 0,-1, 0, 0,-1, 0, 0,-1 }; // v4,v7,v6,v5 (back) + + // index array of vertex array for glDrawElements() & glDrawRangeElement() + static GLubyte cannonicalIndices[indices] = + { 0, 1, 2, 2, 3, 0, // front + 4, 5, 6, 6, 7, 4, // right + 8, 9,10, 10,11, 8, // top + 12,13,14, 14,15,12, // left + 16,17,18, 18,19,16, // bottom + 20,21,22, 22,23,20 }; // back + + + + GLfloat* cannonicalVertex = &cannonicalVertices[0]; + GLfloat* cannonicalNormal = &cannonicalNormals[0]; + + for (int i = 0; i < vertices; i++) { + //normals + *(vertex++) = *cannonicalNormal++; + *(vertex++) = *cannonicalNormal++; + *(vertex++) = *cannonicalNormal++; + + // vertices + *(vertex++) = halfSize * *cannonicalVertex++; + *(vertex++) = halfSize * *cannonicalVertex++; + *(vertex++) = halfSize * *cannonicalVertex++; + + } + + glGenBuffers(1, &vbo.first); + glBindBuffer(GL_ARRAY_BUFFER, vbo.first); + glBufferData(GL_ARRAY_BUFFER, vertices * NUM_BYTES_PER_VERTEX, vertexData, GL_STATIC_DRAW); + delete[] vertexData; + + GLushort* indexData = new GLushort[indices]; + GLushort* index = indexData; + for (int i = 0; i < indices; i++) { + index[i] = cannonicalIndices[i]; + } + + glGenBuffers(1, &vbo.second); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo.second); + glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices * NUM_BYTES_PER_INDEX, indexData, GL_STATIC_DRAW); + delete[] indexData; + + } else { + glBindBuffer(GL_ARRAY_BUFFER, vbo.first); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vbo.second); + } + glEnableClientState(GL_VERTEX_ARRAY); + glEnableClientState(GL_NORMAL_ARRAY); + + glNormalPointer(GL_FLOAT, 6 * sizeof(float), 0); + glVertexPointer(3, GL_FLOAT, (6 * sizeof(float)), (const void *)(3 * sizeof(float))); + + glDrawRangeElementsEXT(GL_TRIANGLES, 0, vertices - 1, indices, GL_UNSIGNED_SHORT, 0); + + glDisableClientState(GL_VERTEX_ARRAY); + glDisableClientState(GL_NORMAL_ARRAY); + + glBindBuffer(GL_ARRAY_BUFFER, 0); + glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); } void GeometryCache::renderWireCube(float size) { @@ -533,7 +622,6 @@ void GeometryCache::renderWireCube(float size) { }; // index array of vertex array for glDrawRangeElement() as a GL_LINES for each edge - const GLubyte LINE_BREAK = static_cast(-1); static GLubyte cannonicalIndices[indices] = { 0, 1, 1, 2, 2, 3, 3, 0, // (top) 4, 5, 5, 6, 6, 7, 7, 4, // (bottom) @@ -571,7 +659,6 @@ void GeometryCache::renderWireCube(float size) { glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); - } From 1ab66c2bfefb038824938ccf765afb428a3922b9 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 18 Dec 2014 16:17:03 -0800 Subject: [PATCH 205/258] split port and hostname for cleaner domain changes --- interface/src/Application.cpp | 22 +------------ interface/src/Application.h | 1 - libraries/networking/src/AddressManager.cpp | 24 ++++++++++---- libraries/networking/src/AddressManager.h | 4 +-- libraries/networking/src/DomainHandler.cpp | 36 +++++---------------- libraries/networking/src/DomainHandler.h | 6 ++-- libraries/networking/src/NodeList.cpp | 10 ++++++ 7 files changed, 40 insertions(+), 63 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index c3ec763426..a975716f9c 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -309,13 +309,6 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) : // use our MyAvatar position and quat for address manager path addressManager.setPositionGetter(getPositionForPath); addressManager.setOrientationGetter(getOrientationForPath); - - // handle domain change signals from AddressManager - connect(&addressManager, &AddressManager::possibleDomainChangeRequiredToHostname, - this, &Application::changeDomainHostname); - - connect(&addressManager, &AddressManager::possibleDomainChangeRequiredViaICEForID, - &domainHandler, &DomainHandler::setIceServerHostnameAndID); _settings = new QSettings(this); _numChangedSettings = 0; @@ -1435,7 +1428,7 @@ void Application::dropEvent(QDropEvent *event) { SnapshotMetaData* snapshotData = Snapshot::parseSnapshotData(snapshotPath); if (snapshotData) { if (!snapshotData->getDomain().isEmpty()) { - changeDomainHostname(snapshotData->getDomain()); + NodeList::getInstance()->getDomainHandler().setHostnameAndPort(snapshotData->getDomain()); } _myAvatar->setPosition(snapshotData->getLocation()); @@ -3700,19 +3693,6 @@ void Application::updateLocationInServer() { } } -void Application::changeDomainHostname(const QString &newDomainHostname) { - NodeList* nodeList = NodeList::getInstance(); - - if (!nodeList->getDomainHandler().isCurrentHostname(newDomainHostname)) { - // tell the MyAvatar object to send a kill packet so that it dissapears from its old avatar mixer immediately - _myAvatar->sendKillAvatar(); - - // call the domain hostname change as a queued connection on the nodelist - QMetaObject::invokeMethod(&NodeList::getInstance()->getDomainHandler(), "setHostname", - Q_ARG(const QString&, newDomainHostname)); - } -} - void Application::clearDomainOctreeDetails() { qDebug() << "Clearing domain octree details..."; // reset the environment so that we don't erroneously end up with multiple diff --git a/interface/src/Application.h b/interface/src/Application.h index 111f03c7c6..041e5e6b5b 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -335,7 +335,6 @@ signals: void importDone(); public slots: - void changeDomainHostname(const QString& newDomainHostname); void domainChanged(const QString& domainHostname); void updateWindowTitle(); void updateLocationInServer(); diff --git a/libraries/networking/src/AddressManager.cpp b/libraries/networking/src/AddressManager.cpp index 1352c54c79..f3c14a4597 100644 --- a/libraries/networking/src/AddressManager.cpp +++ b/libraries/networking/src/AddressManager.cpp @@ -173,7 +173,7 @@ void AddressManager::goToAddressFromObject(const QVariantMap& addressMap) { if (domainObject.contains(DOMAIN_NETWORK_ADDRESS_KEY)) { QString domainHostname = domainObject[DOMAIN_NETWORK_ADDRESS_KEY].toString(); - emit possibleDomainChangeRequiredToHostname(domainHostname); + emit possibleDomainChangeRequired(domainHostname, DEFAULT_DOMAIN_SERVER_PORT); } else { QString iceServerAddress = domainObject[DOMAIN_ICE_SERVER_ADDRESS_KEY].toString(); @@ -250,10 +250,15 @@ bool AddressManager::handleNetworkAddress(const QString& lookupString) { QRegExp ipAddressRegex(IP_ADDRESS_REGEX_STRING); if (ipAddressRegex.indexIn(lookupString) != -1) { - QString domainIPString = ipAddressRegex.cap(0); + QString domainIPString = ipAddressRegex.cap(1); + + qint16 domainPort = DEFAULT_DOMAIN_SERVER_PORT; + if (ipAddressRegex.captureCount() > 1) { + domainPort = (qint16) ipAddressRegex.cap(2).toInt(); + } emit lookupResultsFinished(); - setDomainHostnameAndName(domainIPString); + setDomainInfo(domainIPString, domainPort); return true; } @@ -261,10 +266,15 @@ bool AddressManager::handleNetworkAddress(const QString& lookupString) { QRegExp hostnameRegex(HOSTNAME_REGEX_STRING, Qt::CaseInsensitive); if (hostnameRegex.indexIn(lookupString) != -1) { - QString domainHostname = hostnameRegex.cap(0); + QString domainHostname = hostnameRegex.cap(1); + + qint16 domainPort = DEFAULT_DOMAIN_SERVER_PORT; + if (ipAddressRegex.captureCount() > 1) { + domainPort = (qint16) ipAddressRegex.cap(2).toInt(); + } emit lookupResultsFinished(); - setDomainHostnameAndName(domainHostname); + setDomainInfo(domainHostname, domainPort); return true; } @@ -340,9 +350,9 @@ bool AddressManager::handleUsername(const QString& lookupString) { } -void AddressManager::setDomainHostnameAndName(const QString& hostname, const QString& domainName) { +void AddressManager::setDomainInfo(const QString &hostname, quint16 port, const QString& domainName) { _currentDomain = domainName.isEmpty() ? hostname : domainName; - emit possibleDomainChangeRequiredToHostname(hostname); + emit possibleDomainChangeRequired(hostname, port); } void AddressManager::goToUser(const QString& username) { diff --git a/libraries/networking/src/AddressManager.h b/libraries/networking/src/AddressManager.h index cfdaaa7d41..7a83144488 100644 --- a/libraries/networking/src/AddressManager.h +++ b/libraries/networking/src/AddressManager.h @@ -59,7 +59,7 @@ signals: void lookupResultsFinished(); void lookupResultIsOffline(); void lookupResultIsNotFound(); - void possibleDomainChangeRequiredToHostname(const QString& newHostname); + void possibleDomainChangeRequired(const QString& newHostname, quint16 newPort); void possibleDomainChangeRequiredViaICEForID(const QString& iceServerHostname, const QUuid& domainID); void locationChangeRequired(const glm::vec3& newPosition, bool hasOrientationChange, const glm::quat& newOrientation, @@ -70,7 +70,7 @@ private slots: private: AddressManager(); - void setDomainHostnameAndName(const QString& hostname, const QString& domainName = QString()); + void setDomainInfo(const QString& hostname, quint16 port, const QString& domainName = QString()); const JSONCallbackParameters& apiCallbackParameters(); diff --git a/libraries/networking/src/DomainHandler.cpp b/libraries/networking/src/DomainHandler.cpp index 6091b0cdd2..34aef8b98f 100644 --- a/libraries/networking/src/DomainHandler.cpp +++ b/libraries/networking/src/DomainHandler.cpp @@ -97,39 +97,19 @@ void DomainHandler::setUUID(const QUuid& uuid) { } } -QString DomainHandler::hostnameWithoutPort(const QString& hostname) { - int colonIndex = hostname.indexOf(':'); - return colonIndex > 0 ? hostname.left(colonIndex) : hostname; -} - -bool DomainHandler::isCurrentHostname(const QString& hostname) { - return hostnameWithoutPort(hostname) == _hostname; -} - -void DomainHandler::setHostname(const QString& hostname) { +void DomainHandler::setHostnameAndPort(const QString& hostname, quint16 port) { - if (hostname != _hostname) { + if (hostname != _hostname || _sockAddr.getPort() != port) { // re-set the domain info so that auth information is reloaded hardReset(); - int colonIndex = hostname.indexOf(':'); + // the new hostname is everything up to the colon + _hostname = hostname; - if (colonIndex > 0) { - // the user has included a custom DS port with the hostname - - // the new hostname is everything up to the colon - _hostname = hostname.left(colonIndex); - - // grab the port by reading the string after the colon - _sockAddr.setPort(atoi(hostname.mid(colonIndex + 1, hostname.size()).toLocal8Bit().constData())); - - qDebug() << "Updated hostname to" << _hostname << "and port to" << _sockAddr.getPort(); - - } else { - // no port included with the hostname, simply set the member variable and reset the domain server port to default - _hostname = hostname; - _sockAddr.setPort(DEFAULT_DOMAIN_SERVER_PORT); - } + // grab the port by reading the string after the colon + _sockAddr.setPort(port); + + qDebug() << "Updated hostname to" << _hostname << "and port to" << _sockAddr.getPort(); // re-set the sock addr to null and fire off a lookup of the IP address for this domain-server's hostname qDebug("Looking up DS hostname %s.", _hostname.toLocal8Bit().constData()); diff --git a/libraries/networking/src/DomainHandler.h b/libraries/networking/src/DomainHandler.h index a27a5d1dd8..295e6eac01 100644 --- a/libraries/networking/src/DomainHandler.h +++ b/libraries/networking/src/DomainHandler.h @@ -37,9 +37,7 @@ public: const QUuid& getUUID() const { return _uuid; } void setUUID(const QUuid& uuid); - - static QString hostnameWithoutPort(const QString& hostname); - bool isCurrentHostname(const QString& hostname); + const QString& getHostname() const { return _hostname; } const QHostAddress& getIP() const { return _sockAddr.getAddress(); } @@ -75,7 +73,7 @@ public: void softReset(); public slots: - void setHostname(const QString& hostname); + void setHostnameAndPort(const QString& hostname, quint16 port = DEFAULT_DOMAIN_SERVER_PORT); void setIceServerHostnameAndID(const QString& iceServerHostname, const QUuid& id); private slots: diff --git a/libraries/networking/src/NodeList.cpp b/libraries/networking/src/NodeList.cpp index bf992e7b88..6f6c84f947 100644 --- a/libraries/networking/src/NodeList.cpp +++ b/libraries/networking/src/NodeList.cpp @@ -18,6 +18,7 @@ #include #include "AccountManager.h" +#include "AddressManager.h" #include "Assignment.h" #include "HifiSockAddr.h" #include "NodeList.h" @@ -62,6 +63,15 @@ NodeList::NodeList(char newOwnerType, unsigned short socketListenPort, unsigned _hasCompletedInitialSTUNFailure(false), _stunRequestsSinceSuccess(0) { + AddressManager& addressManager = AddressManager::getInstance(); + + // handle domain change signals from AddressManager + connect(&addressManager, &AddressManager::possibleDomainChangeRequired, + &_domainHandler, &DomainHandler::setHostnameAndPort); + + connect(&addressManager, &AddressManager::possibleDomainChangeRequiredViaICEForID, + &_domainHandler, &DomainHandler::setIceServerHostnameAndID); + // clear our NodeList when the domain changes connect(&_domainHandler, &DomainHandler::disconnectedFromDomain, this, &NodeList::reset); From 47d8b0b062ee4bd2179d0fe93acc923192575b10 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Thu, 18 Dec 2014 16:24:26 -0800 Subject: [PATCH 206/258] Replace Game Of Life with intructions --- .../resources/web/assignment/placeholder.js | 134 +----------------- 1 file changed, 3 insertions(+), 131 deletions(-) diff --git a/domain-server/resources/web/assignment/placeholder.js b/domain-server/resources/web/assignment/placeholder.js index 46a706999f..663215fc7e 100644 --- a/domain-server/resources/web/assignment/placeholder.js +++ b/domain-server/resources/web/assignment/placeholder.js @@ -1,131 +1,3 @@ -// Add your JavaScript for assignment below this line - -// The following is an example of Conway's Game of Life (http://en.wikipedia.org/wiki/Conway's_Game_of_Life) - -var NUMBER_OF_CELLS_EACH_DIMENSION = 64; -var NUMBER_OF_CELLS = NUMBER_OF_CELLS_EACH_DIMENSION * NUMBER_OF_CELLS_EACH_DIMENSION; - -var currentCells = []; -var nextCells = []; - -var METER_LENGTH = 1; -var cellScale = (NUMBER_OF_CELLS_EACH_DIMENSION * METER_LENGTH) / NUMBER_OF_CELLS_EACH_DIMENSION; - -// randomly populate the cell start values -for (var i = 0; i < NUMBER_OF_CELLS_EACH_DIMENSION; i++) { - // create the array to hold this row - currentCells[i] = []; - - // create the array to hold this row in the nextCells array - nextCells[i] = []; - - for (var j = 0; j < NUMBER_OF_CELLS_EACH_DIMENSION; j++) { - currentCells[i][j] = Math.floor(Math.random() * 2); - - // put the same value in the nextCells array for first board draw - nextCells[i][j] = currentCells[i][j]; - } -} - -function isNeighbourAlive(i, j) { - if (i < 0 || i >= NUMBER_OF_CELLS_EACH_DIMENSION - || i < 0 || j >= NUMBER_OF_CELLS_EACH_DIMENSION) { - return 0; - } else { - return currentCells[i][j]; - } -} - -function updateCells() { - var i = 0; - var j = 0; - - for (i = 0; i < NUMBER_OF_CELLS_EACH_DIMENSION; i++) { - for (j = 0; j < NUMBER_OF_CELLS_EACH_DIMENSION; j++) { - // figure out the number of live neighbours for the i-j cell - var liveNeighbours = - isNeighbourAlive(i + 1, j - 1) + isNeighbourAlive(i + 1, j) + isNeighbourAlive(i + 1, j + 1) + - isNeighbourAlive(i, j - 1) + isNeighbourAlive(i, j + 1) + - isNeighbourAlive(i - 1, j - 1) + isNeighbourAlive(i - 1, j) + isNeighbourAlive(i - 1, j + 1); - - if (currentCells[i][j]) { - // live cell - - if (liveNeighbours < 2) { - // rule #1 - under-population - this cell will die - // mark it zero to mark the change - nextCells[i][j] = 0; - } else if (liveNeighbours < 4) { - // rule #2 - this cell lives - // mark it -1 to mark no change - nextCells[i][j] = -1; - } else { - // rule #3 - overcrowding - this cell dies - // mark it zero to mark the change - nextCells[i][j] = 0; - } - } else { - // dead cell - if (liveNeighbours == 3) { - // rule #4 - reproduction - this cell revives - // mark it one to mark the change - nextCells[i][j] = 1; - } else { - // this cell stays dead - // mark it -1 for no change - nextCells[i][j] = -1; - } - } - - if (Math.random() < 0.001) { - // Random mutation to keep things interesting in there. - nextCells[i][j] = 1; - } - } - } - - for (i = 0; i < NUMBER_OF_CELLS_EACH_DIMENSION; i++) { - for (j = 0; j < NUMBER_OF_CELLS_EACH_DIMENSION; j++) { - if (nextCells[i][j] != -1) { - // there has been a change to this cell, change the value in the currentCells array - currentCells[i][j] = nextCells[i][j]; - } - } - } -} - -function sendNextCells() { - for (var i = 0; i < NUMBER_OF_CELLS_EACH_DIMENSION; i++) { - for (var j = 0; j < NUMBER_OF_CELLS_EACH_DIMENSION; j++) { - if (nextCells[i][j] != -1) { - // there has been a change to the state of this cell, send it - - // find the x and y position for this voxel, z = 0 - var x = j * cellScale; - var y = i * cellScale; - - // queue a packet to add a voxel for the new cell - var color = (nextCells[i][j] == 1) ? 255 : 1; - Voxels.setVoxel(x, y, 0, cellScale, color, color, color); - } - } - } -} - -var sentFirstBoard = false; - -function step(deltaTime) { - if (sentFirstBoard) { - // we've already sent the first full board, perform a step in time - updateCells(); - } else { - // this will be our first board send - sentFirstBoard = true; - } - - sendNextCells(); -} - - -Script.update.connect(step); -Voxels.setPacketsPerSecond(200); \ No newline at end of file +// Here you can put a script that will be run by an Assignement Client (AC) +// For examples, please go to http://public.highfidelity.io/scripts +// The directory named acScripts contains Assignement Clients specific scripts you can try. \ No newline at end of file From e6123ec4a7721c427f43728d951eb492c1c5d7c4 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Thu, 18 Dec 2014 16:31:19 -0800 Subject: [PATCH 207/258] Typo --- domain-server/resources/web/assignment/placeholder.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/domain-server/resources/web/assignment/placeholder.js b/domain-server/resources/web/assignment/placeholder.js index 663215fc7e..2c1d8253aa 100644 --- a/domain-server/resources/web/assignment/placeholder.js +++ b/domain-server/resources/web/assignment/placeholder.js @@ -1,3 +1,3 @@ -// Here you can put a script that will be run by an Assignement Client (AC) +// Here you can put a script that will be run by an assignment-client (AC) // For examples, please go to http://public.highfidelity.io/scripts -// The directory named acScripts contains Assignement Clients specific scripts you can try. \ No newline at end of file +// The directory named acScripts contains assignment-client specific scripts you can try. From 3a4f75ff62ead277e5206110e5125c3f129c212e Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 18 Dec 2014 16:40:02 -0800 Subject: [PATCH 208/258] fix AddressManager domain lookup to handle port --- libraries/networking/src/AddressManager.cpp | 12 ++++----- libraries/networking/src/DomainHandler.cpp | 28 +++++++++++++-------- 2 files changed, 23 insertions(+), 17 deletions(-) diff --git a/libraries/networking/src/AddressManager.cpp b/libraries/networking/src/AddressManager.cpp index f3c14a4597..57412b645f 100644 --- a/libraries/networking/src/AddressManager.cpp +++ b/libraries/networking/src/AddressManager.cpp @@ -241,11 +241,11 @@ void AddressManager::attemptPlaceNameLookup(const QString& lookupString) { } bool AddressManager::handleNetworkAddress(const QString& lookupString) { - const QString IP_ADDRESS_REGEX_STRING = "^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}" - "([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(:\\d{1,5})?$"; + const QString IP_ADDRESS_REGEX_STRING = "^((?:(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\\.){3}" + "(?:[0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))(?::(\\d{1,5}))?$"; const QString HOSTNAME_REGEX_STRING = "^((?:[A-Z0-9]|[A-Z0-9][A-Z0-9\\-]{0,61}[A-Z0-9])" - "(?:\\.(?:[A-Z0-9]|[A-Z0-9][A-Z0-9\\-]{0,61}[A-Z0-9]))+|localhost)(:{1}\\d{1,5})?$"; + "(?:\\.(?:[A-Z0-9]|[A-Z0-9][A-Z0-9\\-]{0,61}[A-Z0-9]))+|localhost)(?::(\\d{1,5}))?$"; QRegExp ipAddressRegex(IP_ADDRESS_REGEX_STRING); @@ -253,7 +253,7 @@ bool AddressManager::handleNetworkAddress(const QString& lookupString) { QString domainIPString = ipAddressRegex.cap(1); qint16 domainPort = DEFAULT_DOMAIN_SERVER_PORT; - if (ipAddressRegex.captureCount() > 1) { + if (!ipAddressRegex.cap(2).isEmpty()) { domainPort = (qint16) ipAddressRegex.cap(2).toInt(); } @@ -269,8 +269,8 @@ bool AddressManager::handleNetworkAddress(const QString& lookupString) { QString domainHostname = hostnameRegex.cap(1); qint16 domainPort = DEFAULT_DOMAIN_SERVER_PORT; - if (ipAddressRegex.captureCount() > 1) { - domainPort = (qint16) ipAddressRegex.cap(2).toInt(); + if (!hostnameRegex.cap(2).isEmpty()) { + domainPort = (qint16) hostnameRegex.cap(2).toInt(); } emit lookupResultsFinished(); diff --git a/libraries/networking/src/DomainHandler.cpp b/libraries/networking/src/DomainHandler.cpp index 34aef8b98f..126ef27414 100644 --- a/libraries/networking/src/DomainHandler.cpp +++ b/libraries/networking/src/DomainHandler.cpp @@ -103,20 +103,26 @@ void DomainHandler::setHostnameAndPort(const QString& hostname, quint16 port) { // re-set the domain info so that auth information is reloaded hardReset(); - // the new hostname is everything up to the colon - _hostname = hostname; + if (hostname != _hostname) { + // set the new hostname + _hostname = hostname; + + qDebug() << "Updated domain hostname to" << _hostname; + + // re-set the sock addr to null and fire off a lookup of the IP address for this domain-server's hostname + qDebug("Looking up DS hostname %s.", _hostname.toLocal8Bit().constData()); + QHostInfo::lookupHost(_hostname, this, SLOT(completedHostnameLookup(const QHostInfo&))); + + UserActivityLogger::getInstance().changedDomain(_hostname); + emit hostnameChanged(_hostname); + } + + if (_sockAddr.getPort() != port) { + qDebug() << "Updated domain port to" << port; + } // grab the port by reading the string after the colon _sockAddr.setPort(port); - - qDebug() << "Updated hostname to" << _hostname << "and port to" << _sockAddr.getPort(); - - // re-set the sock addr to null and fire off a lookup of the IP address for this domain-server's hostname - qDebug("Looking up DS hostname %s.", _hostname.toLocal8Bit().constData()); - QHostInfo::lookupHost(_hostname, this, SLOT(completedHostnameLookup(const QHostInfo&))); - - UserActivityLogger::getInstance().changedDomain(_hostname); - emit hostnameChanged(_hostname); } } From 0b1445f8b52139394dde411ea3ea066466e28cab Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 18 Dec 2014 16:41:37 -0800 Subject: [PATCH 209/258] show the address dialog with current address selected --- interface/src/ui/AddressBarDialog.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/interface/src/ui/AddressBarDialog.cpp b/interface/src/ui/AddressBarDialog.cpp index 5f55aa5210..75049f9ed4 100644 --- a/interface/src/ui/AddressBarDialog.cpp +++ b/interface/src/ui/AddressBarDialog.cpp @@ -116,8 +116,9 @@ void AddressBarDialog::setupUI() { void AddressBarDialog::showEvent(QShowEvent* event) { _goButton->setIcon(QIcon(PathUtils::resourcesPath() + ADDRESSBAR_GO_BUTTON_ICON)); - _addressLineEdit->setText(QString()); + _addressLineEdit->setText(AddressManager::getInstance().currentAddress().toString()); _addressLineEdit->setFocus(); + _addressLineEdit->selectAll(); FramelessDialog::showEvent(event); } From 114e3bb2ff27ea5e8f9ac67e29cf5ac78c64e60e Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Thu, 18 Dec 2014 16:51:20 -0800 Subject: [PATCH 210/258] rename cmake macro to represent actual purpose --- assignment-client/CMakeLists.txt | 2 +- ...edDependencies.cmake => IncludeDependencyIncludes.cmake} | 6 +++--- domain-server/CMakeLists.txt | 2 +- ice-server/CMakeLists.txt | 2 +- interface/CMakeLists.txt | 2 +- libraries/animation/CMakeLists.txt | 4 ++-- libraries/audio/CMakeLists.txt | 4 ++-- libraries/avatars/CMakeLists.txt | 4 ++-- libraries/embedded-webserver/CMakeLists.txt | 4 ++-- libraries/entities-renderer/CMakeLists.txt | 4 ++-- libraries/entities/CMakeLists.txt | 4 ++-- libraries/fbx/CMakeLists.txt | 4 ++-- libraries/gpu/CMakeLists.txt | 4 ++-- libraries/metavoxels/CMakeLists.txt | 4 ++-- libraries/networking/CMakeLists.txt | 4 ++-- libraries/octree/CMakeLists.txt | 4 ++-- libraries/physics/CMakeLists.txt | 4 ++-- libraries/render-utils/CMakeLists.txt | 4 ++-- libraries/script-engine/CMakeLists.txt | 4 ++-- libraries/shared/CMakeLists.txt | 4 ++-- libraries/voxels/CMakeLists.txt | 4 ++-- tests/audio/CMakeLists.txt | 2 +- tests/jitter/CMakeLists.txt | 2 +- tests/metavoxels/CMakeLists.txt | 2 +- tests/networking/CMakeLists.txt | 2 +- tests/octree/CMakeLists.txt | 2 +- tests/physics/CMakeLists.txt | 2 +- tests/shared/CMakeLists.txt | 2 +- tools/bitstream2json/CMakeLists.txt | 2 +- tools/json2bitstream/CMakeLists.txt | 2 +- tools/mtc/CMakeLists.txt | 2 +- 31 files changed, 49 insertions(+), 49 deletions(-) rename cmake/macros/{LinkSharedDependencies.cmake => IncludeDependencyIncludes.cmake} (86%) diff --git a/assignment-client/CMakeLists.txt b/assignment-client/CMakeLists.txt index 6e31182f0d..88b2b62bd9 100644 --- a/assignment-client/CMakeLists.txt +++ b/assignment-client/CMakeLists.txt @@ -15,4 +15,4 @@ if (UNIX) target_link_libraries(${TARGET_NAME} ${CMAKE_DL_LIBS}) endif (UNIX) -link_shared_dependencies() +include_dependency_includes() diff --git a/cmake/macros/LinkSharedDependencies.cmake b/cmake/macros/IncludeDependencyIncludes.cmake similarity index 86% rename from cmake/macros/LinkSharedDependencies.cmake rename to cmake/macros/IncludeDependencyIncludes.cmake index 9168c5a921..a375404164 100644 --- a/cmake/macros/LinkSharedDependencies.cmake +++ b/cmake/macros/IncludeDependencyIncludes.cmake @@ -1,5 +1,5 @@ # -# LinkSharedDependencies.cmake +# IncludeDependencyIncludes.cmake # cmake/macros # # Copyright 2014 High Fidelity, Inc. @@ -9,7 +9,7 @@ # See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html # -macro(LINK_SHARED_DEPENDENCIES) +macro(INCLUDE_DEPENDENCY_INCLUDES) if (${TARGET_NAME}_DEPENDENCY_INCLUDES) list(REMOVE_DUPLICATES ${TARGET_NAME}_DEPENDENCY_INCLUDES) @@ -19,4 +19,4 @@ macro(LINK_SHARED_DEPENDENCIES) # set the property on this target so it can be retreived by targets linking to us set_target_properties(${TARGET_NAME} PROPERTIES DEPENDENCY_INCLUDES "${${TARGET_NAME}_DEPENDENCY_INCLUDES}") -endmacro(LINK_SHARED_DEPENDENCIES) \ No newline at end of file +endmacro(INCLUDE_DEPENDENCY_INCLUDES) \ No newline at end of file diff --git a/domain-server/CMakeLists.txt b/domain-server/CMakeLists.txt index 482c397b14..421a1da2d4 100644 --- a/domain-server/CMakeLists.txt +++ b/domain-server/CMakeLists.txt @@ -52,4 +52,4 @@ include_directories(SYSTEM "${OPENSSL_INCLUDE_DIR}") # append OpenSSL to our list of libraries to link target_link_libraries(${TARGET_NAME} ${OPENSSL_LIBRARIES}) -link_shared_dependencies() \ No newline at end of file +include_dependency_includes() \ No newline at end of file diff --git a/ice-server/CMakeLists.txt b/ice-server/CMakeLists.txt index c81ba16248..24e780f9aa 100644 --- a/ice-server/CMakeLists.txt +++ b/ice-server/CMakeLists.txt @@ -6,4 +6,4 @@ setup_hifi_project(Network) # link the shared hifi libraries link_hifi_libraries(networking shared) -link_shared_dependencies() \ No newline at end of file +include_dependency_includes() \ No newline at end of file diff --git a/interface/CMakeLists.txt b/interface/CMakeLists.txt index a9688a5919..659ecf600f 100644 --- a/interface/CMakeLists.txt +++ b/interface/CMakeLists.txt @@ -246,4 +246,4 @@ else (APPLE) endif (APPLE) # link any dependencies bubbled up from our linked dependencies -link_shared_dependencies() +include_dependency_includes() diff --git a/libraries/animation/CMakeLists.txt b/libraries/animation/CMakeLists.txt index 3f65c1ab6c..d7cbe43e28 100644 --- a/libraries/animation/CMakeLists.txt +++ b/libraries/animation/CMakeLists.txt @@ -5,5 +5,5 @@ setup_hifi_library(Network Script) link_hifi_libraries(shared fbx) -# call macro to link our dependencies and bubble them up via a property on our target -link_shared_dependencies() \ No newline at end of file +# call macro to include our dependency includes and bubble them up via a property on our target +include_dependency_includes() \ No newline at end of file diff --git a/libraries/audio/CMakeLists.txt b/libraries/audio/CMakeLists.txt index 6ade1fc423..b08d9e88f4 100644 --- a/libraries/audio/CMakeLists.txt +++ b/libraries/audio/CMakeLists.txt @@ -7,5 +7,5 @@ include_glm() link_hifi_libraries(networking shared) -# call macro to link our dependencies and bubble them up via a property on our target -link_shared_dependencies() \ No newline at end of file +# call macro to include our dependency includes and bubble them up via a property on our target +include_dependency_includes() \ No newline at end of file diff --git a/libraries/avatars/CMakeLists.txt b/libraries/avatars/CMakeLists.txt index 20aba226e0..69d0f23717 100644 --- a/libraries/avatars/CMakeLists.txt +++ b/libraries/avatars/CMakeLists.txt @@ -7,5 +7,5 @@ include_glm() link_hifi_libraries(audio shared octree voxels networking physics fbx) -# call macro to link our dependencies and bubble them up via a property on our target -link_shared_dependencies() +# call macro to include our dependency includes and bubble them up via a property on our target +include_dependency_includes() diff --git a/libraries/embedded-webserver/CMakeLists.txt b/libraries/embedded-webserver/CMakeLists.txt index 6e4b92e217..ef2cf1054c 100644 --- a/libraries/embedded-webserver/CMakeLists.txt +++ b/libraries/embedded-webserver/CMakeLists.txt @@ -3,5 +3,5 @@ set(TARGET_NAME embedded-webserver) # use setup_hifi_library macro to setup our project and link appropriate Qt modules setup_hifi_library(Network) -# call macro to link our dependencies and bubble them up via a property on our target -link_shared_dependencies() \ No newline at end of file +# call macro to include our dependency includes and bubble them up via a property on our target +include_dependency_includes() \ No newline at end of file diff --git a/libraries/entities-renderer/CMakeLists.txt b/libraries/entities-renderer/CMakeLists.txt index 3b8a214675..6d7f5ee960 100644 --- a/libraries/entities-renderer/CMakeLists.txt +++ b/libraries/entities-renderer/CMakeLists.txt @@ -7,5 +7,5 @@ include_glm() link_hifi_libraries(shared gpu script-engine render-utils) -# call macro to link our dependencies and bubble them up via a property on our target -link_shared_dependencies() +# call macro to include our dependency includes and bubble them up via a property on our target +include_dependency_includes() diff --git a/libraries/entities/CMakeLists.txt b/libraries/entities/CMakeLists.txt index d6f503f2ca..10aba41ebb 100644 --- a/libraries/entities/CMakeLists.txt +++ b/libraries/entities/CMakeLists.txt @@ -7,5 +7,5 @@ include_glm() link_hifi_libraries(avatars shared octree fbx networking animation physics) -# call macro to link our dependencies and bubble them up via a property on our target -link_shared_dependencies() +# call macro to include our dependency includes and bubble them up via a property on our target +include_dependency_includes() diff --git a/libraries/fbx/CMakeLists.txt b/libraries/fbx/CMakeLists.txt index 5a151deb8b..4f4cb6eb76 100644 --- a/libraries/fbx/CMakeLists.txt +++ b/libraries/fbx/CMakeLists.txt @@ -11,5 +11,5 @@ find_package(ZLIB REQUIRED) include_directories(SYSTEM "${ZLIB_INCLUDE_DIRS}") target_link_libraries(${TARGET_NAME} ${ZLIB_LIBRARIES}) -# call macro to link our dependencies and bubble them up via a property on our target -link_shared_dependencies() +# call macro to include our dependency includes and bubble them up via a property on our target +include_dependency_includes() diff --git a/libraries/gpu/CMakeLists.txt b/libraries/gpu/CMakeLists.txt index 340adcc9e6..1264c1bf5c 100644 --- a/libraries/gpu/CMakeLists.txt +++ b/libraries/gpu/CMakeLists.txt @@ -44,5 +44,5 @@ else () list(APPEND ${TARGET_NAME}_DEPENDENCY_INCLUDES "${OPENGL_INCLUDE_DIR}") endif (APPLE) -# call macro to link our dependencies and bubble them up via a property on our target -link_shared_dependencies() +# call macro to include our dependency includes and bubble them up via a property on our target +include_dependency_includes() diff --git a/libraries/metavoxels/CMakeLists.txt b/libraries/metavoxels/CMakeLists.txt index aab8d2184d..4ead36e51a 100644 --- a/libraries/metavoxels/CMakeLists.txt +++ b/libraries/metavoxels/CMakeLists.txt @@ -10,5 +10,5 @@ link_hifi_libraries(shared networking) include_glm() -# call macro to link our dependencies and bubble them up via a property on our target -link_shared_dependencies() \ No newline at end of file +# call macro to include our dependency includes and bubble them up via a property on our target +include_dependency_includes() \ No newline at end of file diff --git a/libraries/networking/CMakeLists.txt b/libraries/networking/CMakeLists.txt index 934e3e69b9..bc251a42d4 100644 --- a/libraries/networking/CMakeLists.txt +++ b/libraries/networking/CMakeLists.txt @@ -28,5 +28,5 @@ target_link_libraries(${TARGET_NAME} ${OPENSSL_LIBRARIES} ${TBB_LIBRARIES}) # append libcuckoo includes to our list of includes to bubble list(APPEND ${TARGET_NAME}_DEPENDENCY_INCLUDES "${TBB_INCLUDE_DIRS}") -# call macro to link our dependencies and bubble them up via a property on our target -link_shared_dependencies() \ No newline at end of file +# call macro to include our dependency includes and bubble them up via a property on our target +include_dependency_includes() \ No newline at end of file diff --git a/libraries/octree/CMakeLists.txt b/libraries/octree/CMakeLists.txt index e8c6554ff4..cd90857637 100644 --- a/libraries/octree/CMakeLists.txt +++ b/libraries/octree/CMakeLists.txt @@ -15,5 +15,5 @@ include_directories(SYSTEM "${ZLIB_INCLUDE_DIRS}") # append ZLIB and OpenSSL to our list of libraries to link target_link_libraries(${TARGET_NAME} ${ZLIB_LIBRARIES}) -# call macro to link our dependencies and bubble them up via a property on our target -link_shared_dependencies() +# call macro to include our dependency includes and bubble them up via a property on our target +include_dependency_includes() diff --git a/libraries/physics/CMakeLists.txt b/libraries/physics/CMakeLists.txt index 5270f08730..4f74038ff5 100644 --- a/libraries/physics/CMakeLists.txt +++ b/libraries/physics/CMakeLists.txt @@ -15,5 +15,5 @@ link_hifi_libraries(shared) ## append BULLET to our list of libraries to link #list(APPEND ${TARGET_NAME}_LIBRARIES_TO_LINK "${BULLET_LIBRARIES}") -# call macro to link our dependencies and bubble them up via a property on our target -link_shared_dependencies() +# call macro to include our dependency includes and bubble them up via a property on our target +include_dependency_includes() diff --git a/libraries/render-utils/CMakeLists.txt b/libraries/render-utils/CMakeLists.txt index 211c7266b3..99d01760f8 100644 --- a/libraries/render-utils/CMakeLists.txt +++ b/libraries/render-utils/CMakeLists.txt @@ -16,5 +16,5 @@ else () target_link_libraries(${TARGET_NAME} ${GLUT_LIBRARIES}) endif () -# call macro to link our dependencies and bubble them up via a property on our target -link_shared_dependencies() +# call macro to include our dependency includes and bubble them up via a property on our target +include_dependency_includes() diff --git a/libraries/script-engine/CMakeLists.txt b/libraries/script-engine/CMakeLists.txt index 7118e84443..86e6c83b5d 100644 --- a/libraries/script-engine/CMakeLists.txt +++ b/libraries/script-engine/CMakeLists.txt @@ -7,5 +7,5 @@ include_glm() link_hifi_libraries(shared octree voxels fbx entities animation audio physics metavoxels) -# call macro to link our dependencies and bubble them up via a property on our target -link_shared_dependencies() +# call macro to include our dependency includes and bubble them up via a property on our target +include_dependency_includes() diff --git a/libraries/shared/CMakeLists.txt b/libraries/shared/CMakeLists.txt index b5a44c96e2..4b271bfeda 100644 --- a/libraries/shared/CMakeLists.txt +++ b/libraries/shared/CMakeLists.txt @@ -4,5 +4,5 @@ set(TARGET_NAME shared) # TODO: there isn't really a good reason to have Script linked here - let's get what is requiring it out (RegisteredMetaTypes.cpp) setup_hifi_library(Network Script Widgets) -# call macro to link our dependencies and bubble them up via a property on our target -link_shared_dependencies() \ No newline at end of file +# call macro to include our dependency includes and bubble them up via a property on our target +include_dependency_includes() \ No newline at end of file diff --git a/libraries/voxels/CMakeLists.txt b/libraries/voxels/CMakeLists.txt index 7980094884..75b5143321 100644 --- a/libraries/voxels/CMakeLists.txt +++ b/libraries/voxels/CMakeLists.txt @@ -14,5 +14,5 @@ include_directories(SYSTEM "${ZLIB_INCLUDE_DIRS}") # add it to our list of libraries to link target_link_libraries(${TARGET_NAME} ${ZLIB_LIBRARIES}) -# call macro to link our dependencies and bubble them up via a property on our target -link_shared_dependencies() \ No newline at end of file +# call macro to include our dependency includes and bubble them up via a property on our target +include_dependency_includes() \ No newline at end of file diff --git a/tests/audio/CMakeLists.txt b/tests/audio/CMakeLists.txt index 974b4dcd09..fb6b9c2e11 100644 --- a/tests/audio/CMakeLists.txt +++ b/tests/audio/CMakeLists.txt @@ -7,4 +7,4 @@ include_glm() # link in the shared libraries link_hifi_libraries(shared audio networking) -link_shared_dependencies() \ No newline at end of file +include_dependency_includes() \ No newline at end of file diff --git a/tests/jitter/CMakeLists.txt b/tests/jitter/CMakeLists.txt index d0b366e7ef..93f7caefdd 100644 --- a/tests/jitter/CMakeLists.txt +++ b/tests/jitter/CMakeLists.txt @@ -5,4 +5,4 @@ setup_hifi_project() # link in the shared libraries link_hifi_libraries(shared networking) -link_shared_dependencies() \ No newline at end of file +include_dependency_includes() \ No newline at end of file diff --git a/tests/metavoxels/CMakeLists.txt b/tests/metavoxels/CMakeLists.txt index 732c974f95..7524c5c87c 100644 --- a/tests/metavoxels/CMakeLists.txt +++ b/tests/metavoxels/CMakeLists.txt @@ -9,4 +9,4 @@ setup_hifi_project(Network Script Widgets) # link in the shared libraries link_hifi_libraries(metavoxels networking shared) -link_shared_dependencies() \ No newline at end of file +include_dependency_includes() \ No newline at end of file diff --git a/tests/networking/CMakeLists.txt b/tests/networking/CMakeLists.txt index a7293226b3..113a75ab50 100644 --- a/tests/networking/CMakeLists.txt +++ b/tests/networking/CMakeLists.txt @@ -5,4 +5,4 @@ setup_hifi_project() # link in the shared libraries link_hifi_libraries(shared networking) -link_shared_dependencies() \ No newline at end of file +include_dependency_includes() \ No newline at end of file diff --git a/tests/octree/CMakeLists.txt b/tests/octree/CMakeLists.txt index 7139d4edb6..3382f684cb 100644 --- a/tests/octree/CMakeLists.txt +++ b/tests/octree/CMakeLists.txt @@ -7,4 +7,4 @@ include_glm() # link in the shared libraries link_hifi_libraries(shared octree voxels fbx metavoxels networking entities avatars audio animation script-engine physics) -link_shared_dependencies() +include_dependency_includes() diff --git a/tests/physics/CMakeLists.txt b/tests/physics/CMakeLists.txt index d47b979459..31c741eecf 100644 --- a/tests/physics/CMakeLists.txt +++ b/tests/physics/CMakeLists.txt @@ -7,4 +7,4 @@ include_glm() # link in the shared libraries link_hifi_libraries(shared physics) -link_shared_dependencies() +include_dependency_includes() diff --git a/tests/shared/CMakeLists.txt b/tests/shared/CMakeLists.txt index fe3843e9eb..f067fa52b5 100644 --- a/tests/shared/CMakeLists.txt +++ b/tests/shared/CMakeLists.txt @@ -7,4 +7,4 @@ include_glm() # link in the shared libraries link_hifi_libraries(shared) -link_shared_dependencies() \ No newline at end of file +include_dependency_includes() \ No newline at end of file diff --git a/tools/bitstream2json/CMakeLists.txt b/tools/bitstream2json/CMakeLists.txt index bc23a1e193..2e8bb213be 100644 --- a/tools/bitstream2json/CMakeLists.txt +++ b/tools/bitstream2json/CMakeLists.txt @@ -5,4 +5,4 @@ include_glm() link_hifi_libraries(metavoxels) -link_shared_dependencies() \ No newline at end of file +include_dependency_includes() \ No newline at end of file diff --git a/tools/json2bitstream/CMakeLists.txt b/tools/json2bitstream/CMakeLists.txt index 91b56c18fd..283d450e11 100644 --- a/tools/json2bitstream/CMakeLists.txt +++ b/tools/json2bitstream/CMakeLists.txt @@ -5,4 +5,4 @@ include_glm() link_hifi_libraries(metavoxels) -link_shared_dependencies() \ No newline at end of file +include_dependency_includes() \ No newline at end of file diff --git a/tools/mtc/CMakeLists.txt b/tools/mtc/CMakeLists.txt index 4dfa8421ff..06b9f86d06 100644 --- a/tools/mtc/CMakeLists.txt +++ b/tools/mtc/CMakeLists.txt @@ -1,4 +1,4 @@ set(TARGET_NAME mtc) setup_hifi_project() -link_shared_dependencies() \ No newline at end of file +include_dependency_includes() \ No newline at end of file From dd06d1f4a9f5ca9b1d4cf6ce806ece502d530aba Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Fri, 19 Dec 2014 10:01:14 -0800 Subject: [PATCH 211/258] added comments to explain hand state --- libraries/avatars/src/AvatarData.cpp | 7 +++++++ libraries/avatars/src/AvatarData.h | 12 +++++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/libraries/avatars/src/AvatarData.cpp b/libraries/avatars/src/AvatarData.cpp index 01f84ca246..a5ee3f7fff 100644 --- a/libraries/avatars/src/AvatarData.cpp +++ b/libraries/avatars/src/AvatarData.cpp @@ -443,7 +443,14 @@ int AvatarData::parseDataAtOffset(const QByteArray& packet, int offset) { // key state, stored as a semi-nibble in the bitItems _keyState = (KeyState)getSemiNibbleAt(bitItems,KEY_STATE_START_BIT); + // hand state, stored as a semi-nibble plus a bit in the bitItems + // we store the hand state as well as other items in a shared bitset. The hand state is an octal, but is split + // into two sections to maintain backward compatibility. The bits are ordered as such (0-7 left to right). + // +---+-----+-----+--+ + // |x,x|H0,H1|x,x,x|H2| + // +---+-----+-----+--+ + // Hand state - H0,H1,H2 is found in the 3rd, 4th, and 8th bits _handState = getSemiNibbleAt(bitItems, HAND_STATE_START_BIT) + (oneAtBit(bitItems, HAND_STATE_FINGER_POINTING_BIT) ? IS_FINGER_POINTING_FLAG : 0); diff --git a/libraries/avatars/src/AvatarData.h b/libraries/avatars/src/AvatarData.h index 55b35377c0..6564d53317 100644 --- a/libraries/avatars/src/AvatarData.h +++ b/libraries/avatars/src/AvatarData.h @@ -76,7 +76,17 @@ const quint32 AVATAR_MOTION_SCRIPTABLE_BITS = AVATAR_MOTION_STAND_ON_NEARBY_FLOORS; -// First bitset +// Bitset of state flags - we store the key state, hand state, faceshift, chat circling, and existance of +// referential data in this bit set. The hand state is an octal, but is split into two sections to maintain +// backward compatibility. The bits are ordered as such (0-7 left to right). +// +-----+-----+-+-+-+--+ +// |K0,K1|H0,H1|F|C|R|H2| +// +-----+-----+-+-+-+--+ +// Key state - K0,K1 is found in the 1st and 2nd bits +// Hand state - H0,H1,H2 is found in the 3rd, 4th, and 8th bits +// Faceshift - F is found in the 5th bit +// Chat Circling - C is found in the 6th bit +// Referential Data - R is found in the 7th bit const int KEY_STATE_START_BIT = 0; // 1st and 2nd bits const int HAND_STATE_START_BIT = 2; // 3rd and 4th bits const int IS_FACESHIFT_CONNECTED = 4; // 5th bit From 51121554e51cc13d223d3ace1f47b6e453f8208a Mon Sep 17 00:00:00 2001 From: Adrianl3d Date: Sat, 20 Dec 2014 04:28:39 +1000 Subject: [PATCH 212/258] clean up code intentations lines 263 264 --- examples/notifications.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/notifications.js b/examples/notifications.js index 7946213abd..5527fc35fc 100644 --- a/examples/notifications.js +++ b/examples/notifications.js @@ -260,8 +260,8 @@ function checkSize(){ // Triggers notification if a user logs on or off function onOnlineUsersChanged(users) { for (user in users) { - if (last_users.indexOf(users[user]) == -1.0) { - createNotification(users[user] + " has joined"); + if (last_users.indexOf(users[user]) == -1.0) { + createNotification(users[user] + " has joined"); } } for (user in last_users) { From 715b3a245e39e1437c242f10ea00d21cb5a8f595 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 19 Dec 2014 10:53:36 -0800 Subject: [PATCH 213/258] remove GLUT from Cmake files --- cmake/modules/FindGLUT.cmake | 47 --------------------------- interface/CMakeLists.txt | 14 +++----- libraries/render-utils/CMakeLists.txt | 9 ----- 3 files changed, 5 insertions(+), 65 deletions(-) delete mode 100644 cmake/modules/FindGLUT.cmake diff --git a/cmake/modules/FindGLUT.cmake b/cmake/modules/FindGLUT.cmake deleted file mode 100644 index e7bf752aca..0000000000 --- a/cmake/modules/FindGLUT.cmake +++ /dev/null @@ -1,47 +0,0 @@ -# -# FindGLUT.cmake -# -# Try to find GLUT library and include path. -# Once done this will define -# -# GLUT_FOUND -# GLUT_INCLUDE_DIRS -# GLUT_LIBRARIES -# -# Created on 2/6/2014 by Stephen Birarda -# Copyright 2014 High Fidelity, Inc. -# -# Adapted from FindGLUT.cmake available in tlorach's OpenGLText Repository -# https://raw.github.com/tlorach/OpenGLText/master/cmake/FindGLUT.cmake -# -# Distributed under the Apache License, Version 2.0. -# See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -# - -include("${MACRO_DIR}/HifiLibrarySearchHints.cmake") -hifi_library_search_hints("freeglut") - -if (WIN32) - set(GLUT_HINT_DIRS "${FREEGLUT_SEARCH_DIRS} ${OPENGL_INCLUDE_DIR}") - - find_path(GLUT_INCLUDE_DIRS GL/glut.h PATH_SUFFIXES include HINTS ${FREEGLUT_SEARCH_DIRS}) - find_library(GLUT_LIBRARY freeglut PATH_SUFFIXES lib HINTS ${FREEGLUT_SEARCH_DIRS}) -else () - find_path(GLUT_INCLUDE_DIRS GL/glut.h PATH_SUFFIXES include HINTS ${FREEGLUT_SEARCH_DIRS}) - find_library(GLUT_LIBRARY glut PATH_SUFFIXES lib HINTS ${FREEGLUT_SEARCH_DIRS}) -endif () - -include(FindPackageHandleStandardArgs) - -set(GLUT_LIBRARIES "${GLUT_LIBRARY}" "${XMU_LIBRARY}" "${XI_LIBRARY}") - -if (UNIX) - find_library(XI_LIBRARY Xi PATH_SUFFIXES lib HINTS ${FREEGLUT_SEARCH_DIRS}) - find_library(XMU_LIBRARY Xmu PATH_SUFFIXES lib HINTS ${FREEGLUT_SEARCH_DIRS}) - - find_package_handle_standard_args(GLUT DEFAULT_MSG GLUT_INCLUDE_DIRS GLUT_LIBRARIES XI_LIBRARY XMU_LIBRARY) -else () - find_package_handle_standard_args(GLUT DEFAULT_MSG GLUT_INCLUDE_DIRS GLUT_LIBRARIES) -endif () - -mark_as_advanced(GLUT_INCLUDE_DIRS GLUT_LIBRARIES GLUT_LIBRARY XI_LIBRARY XMU_LIBRARY FREEGLUT_SEARCH_DIRS) \ No newline at end of file diff --git a/interface/CMakeLists.txt b/interface/CMakeLists.txt index 659ecf600f..ebbce669ea 100644 --- a/interface/CMakeLists.txt +++ b/interface/CMakeLists.txt @@ -25,15 +25,15 @@ else () endif () if (APPLE) - set(GL_HEADERS "#include \n#include ") + set(GL_HEADERS "#include ") elseif (UNIX) # include the right GL headers for UNIX - set(GL_HEADERS "#include \n#include \n#include ") + set(GL_HEADERS "#include \n#include ") elseif (WIN32) add_definitions(-D_USE_MATH_DEFINES) # apparently needed to get M_PI and other defines from cmath/math.h add_definitions(-DWINDOWS_LEAN_AND_MEAN) # needed to make sure windows doesn't go to crazy with its defines - set(GL_HEADERS "#include \n#include \n#include \n#include ") + set(GL_HEADERS "#include \n#include \n#include ") endif () # set up the external glm library @@ -194,11 +194,10 @@ if (APPLE) # link in required OS X frameworks and include the right GL headers find_library(CoreAudio CoreAudio) find_library(CoreFoundation CoreFoundation) - find_library(GLUT GLUT) find_library(OpenGL OpenGL) find_library(AppKit AppKit) - target_link_libraries(${TARGET_NAME} ${CoreAudio} ${CoreFoundation} ${GLUT} ${OpenGL} ${AppKit}) + target_link_libraries(${TARGET_NAME} ${CoreAudio} ${CoreFoundation} ${OpenGL} ${AppKit}) # install command for OS X bundle INSTALL(TARGETS ${TARGET_NAME} @@ -214,15 +213,12 @@ else (APPLE) ) find_package(OpenGL REQUIRED) - find_package(GLUT REQUIRED) - - include_directories(SYSTEM "${GLUT_INCLUDE_DIRS}") if (${OPENGL_INCLUDE_DIR}) include_directories(SYSTEM "${OPENGL_INCLUDE_DIR}") endif () - target_link_libraries(${TARGET_NAME} "${OPENGL_LIBRARY}" "${GLUT_LIBRARIES}") + target_link_libraries(${TARGET_NAME} "${OPENGL_LIBRARY}") # link target to external libraries if (WIN32) diff --git a/libraries/render-utils/CMakeLists.txt b/libraries/render-utils/CMakeLists.txt index 99d01760f8..97dc9c7bc8 100644 --- a/libraries/render-utils/CMakeLists.txt +++ b/libraries/render-utils/CMakeLists.txt @@ -7,14 +7,5 @@ include_glm() link_hifi_libraries(animation fbx shared gpu) -if (APPLE) - find_library(GLUT GLUT) - target_link_libraries(${TARGET_NAME} ${GLUT}) -else () - find_package(GLUT REQUIRED) - include_directories(SYSTEM "${GLUT_INCLUDE_DIRS}") - target_link_libraries(${TARGET_NAME} ${GLUT_LIBRARIES}) -endif () - # call macro to include our dependency includes and bubble them up via a property on our target include_dependency_includes() From 115dc28c9cabe9e5d35bcb881f7ae93d76f05ea1 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 19 Dec 2014 10:54:00 -0800 Subject: [PATCH 214/258] add glu includes on OS X to stopgap GLUT removal --- interface/src/Hair.cpp | 5 ++++- interface/src/avatar/Avatar.cpp | 5 +++++ interface/src/ui/ApplicationOverlay.cpp | 5 +++++ interface/src/ui/RearMirrorTools.cpp | 5 +++++ 4 files changed, 19 insertions(+), 1 deletion(-) diff --git a/interface/src/Hair.cpp b/interface/src/Hair.cpp index cb664f39ed..c2d3f78b98 100644 --- a/interface/src/Hair.cpp +++ b/interface/src/Hair.cpp @@ -10,11 +10,14 @@ // // Creates single flexible verlet-integrated strands that can be used for hair/fur/grass -#include "Hair.h" +#include #include "Util.h" #include "world.h" +#include "Hair.h" + + const float HAIR_DAMPING = 0.99f; const float CONSTRAINT_RELAXATION = 10.0f; const float HAIR_ACCELERATION_COUPLING = 0.045f; diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index 39c528d080..aa94b21d71 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -13,6 +13,11 @@ #include +// TODO: remove calls to gluProject to remove this include +#ifdef __APPLE__ +#include +#endif + #include #include diff --git a/interface/src/ui/ApplicationOverlay.cpp b/interface/src/ui/ApplicationOverlay.cpp index ab85da125c..f82b44a403 100644 --- a/interface/src/ui/ApplicationOverlay.cpp +++ b/interface/src/ui/ApplicationOverlay.cpp @@ -11,6 +11,11 @@ #include "InterfaceConfig.h" +// TODO: remove calls to gluProject to remove this include +#ifdef __APPLE__ +#include +#endif + #include #include diff --git a/interface/src/ui/RearMirrorTools.cpp b/interface/src/ui/RearMirrorTools.cpp index fd3fc34adb..2c671ef548 100644 --- a/interface/src/ui/RearMirrorTools.cpp +++ b/interface/src/ui/RearMirrorTools.cpp @@ -11,6 +11,11 @@ #include "InterfaceConfig.h" +// TODO: remove calls to gluProject to remove this include +#ifdef __APPLE__ +#include +#endif + #include #include From d43ec2ee28cc9b7c9c4c11371631e7d1355cab0f Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Fri, 19 Dec 2014 11:00:41 -0800 Subject: [PATCH 215/258] revert some prototype script stuff for now --- examples/entityScripts/movable.js | 412 ++++++++++++++++++++++- examples/entityScripts/movableClass.js | 426 ------------------------ examples/entityScripts/sitOnEntity.js | 363 +++++++++++++++++++- examples/entityScripts/sittable.js | 15 - examples/entityScripts/sittableClass.js | 393 ---------------------- 5 files changed, 767 insertions(+), 842 deletions(-) delete mode 100644 examples/entityScripts/movableClass.js delete mode 100644 examples/entityScripts/sittable.js delete mode 100644 examples/entityScripts/sittableClass.js diff --git a/examples/entityScripts/movable.js b/examples/entityScripts/movable.js index 0ea3641c6f..35d11116eb 100644 --- a/examples/entityScripts/movable.js +++ b/examples/entityScripts/movable.js @@ -8,8 +8,412 @@ // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +(function(){ -(function() { - Script.include("movableClass.js"); - return new Movable(); -}) + this.entityID = null; + this.properties = null; + this.graboffset = null; + this.clickedAt = null; + this.firstHolding = true; + this.clicked = { x: -1, y: -1}; + this.lastMovedPosition = { x: -1, y: -1}; + this.lastMovedTime = 0; + this.rotateOverlayTarget = null; + this.rotateOverlayInner = null; + this.rotateOverlayOuter = null; + this.rotateOverlayCurrent = null; + this.rotateMode = false; + this.originalRotation = null; + + this.moveSoundURLS = [ + "http://public.highfidelity.io/sounds/MovingFurniture/FurnitureMove1.wav", + "http://public.highfidelity.io/sounds/MovingFurniture/FurnitureMove2.wav", + "http://public.highfidelity.io/sounds/MovingFurniture/FurnitureMove3.wav" + ]; + + this.turnSoundURLS = [ + + "http://public.highfidelity.io/sounds/MovingFurniture/FurnitureMove1.wav", + "http://public.highfidelity.io/sounds/MovingFurniture/FurnitureMove2.wav", + "http://public.highfidelity.io/sounds/MovingFurniture/FurnitureMove3.wav" + + // TODO: determine if these or other turn sounds work better than move sounds. + //"http://public.highfidelity.io/sounds/MovingFurniture/FurnitureTurn1.wav", + //"http://public.highfidelity.io/sounds/MovingFurniture/FurnitureTurn2.wav", + //"http://public.highfidelity.io/sounds/MovingFurniture/FurnitureTurn3.wav" + ]; + + + this.moveSounds = new Array(); + this.turnSounds = new Array(); + this.moveSound = null; + this.turnSound = null; + this.injector = null; + + var debug = false; + var displayRotateTargets = true; // change to false if you don't want the rotate targets + var rotateOverlayTargetSize = 10000; // really big target + var innerSnapAngle = 22.5; // the angle which we snap to on the inner rotation tool + var innerRadius; + var outerRadius; + var yawCenter; + var yawZero; + var rotationNormal; + var yawNormal; + var stopSoundDelay = 100; // number of msecs of not moving to have sound stop + + this.getRandomInt = function(min, max) { + return Math.floor(Math.random() * (max - min + 1)) + min; + } + + this.downloadSounds = function() { + for (var i = 0; i < this.moveSoundURLS.length; i++) { + this.moveSounds[i] = SoundCache.getSound(this.moveSoundURLS[i]); + } + for (var i = 0; i < this.turnSoundURLS.length; i++) { + this.turnSounds[i] = SoundCache.getSound(this.turnSoundURLS[i]); + } + } + + this.pickRandomSounds = function() { + var moveIndex = this.getRandomInt(0, this.moveSounds.length - 1); + var turnIndex = this.getRandomInt(0, this.turnSounds.length - 1); + if (debug) { + print("Random sounds -- turn:" + turnIndex + " move:" + moveIndex); + } + this.moveSound = this.moveSounds[moveIndex]; + this.turnSound = this.turnSounds[turnIndex]; + } + + // Play move sound + this.playMoveSound = function() { + if (debug) { + print("playMoveSound()"); + } + if (this.moveSound && this.moveSound.downloaded) { + if (debug) { + print("playMoveSound() --- calling this.injector = Audio.playSound(this.moveSound...)"); + } + this.injector = Audio.playSound(this.moveSound, { position: this.properties.position, loop: true, volume: 0.1 }); + } + } + + // Play turn sound + this.playTurnSound = function() { + if (debug) { + print("playTurnSound()"); + } + if (this.turnSound && this.turnSound.downloaded) { + if (debug) { + print("playTurnSound() --- calling this.injector = Audio.playSound(this.turnSound...)"); + } + this.injector = Audio.playSound(this.turnSound, { position: this.properties.position, loop: true, volume: 0.1 }); + } + } + + // stop sound + this.stopSound = function() { + if (debug) { + print("stopSound()"); + } + if (this.injector) { + Audio.stopInjector(this.injector); + this.injector = null; + } + } + + // Pr, Vr are respectively the Ray's Point of origin and Vector director + // Pp, Np are respectively the Plane's Point of origin and Normal vector + this.rayPlaneIntersection = function(Pr, Vr, Pp, Np) { + var d = -Vec3.dot(Pp, Np); + var t = -(Vec3.dot(Pr, Np) + d) / Vec3.dot(Vr, Np); + return Vec3.sum(Pr, Vec3.multiply(t, Vr)); + }; + + // updates the piece position based on mouse input + this.updatePosition = function(mouseEvent) { + var pickRay = Camera.computePickRay(mouseEvent.x, mouseEvent.y) + var upVector = { x: 0, y: 1, z: 0 }; + var intersection = this.rayPlaneIntersection(pickRay.origin, pickRay.direction, + this.properties.position, upVector); + + var newPosition = Vec3.sum(intersection, this.graboffset); + Entities.editEntity(this.entityID, { position: newPosition }); + }; + + this.grab = function(mouseEvent) { + // first calculate the offset + var pickRay = Camera.computePickRay(mouseEvent.x, mouseEvent.y) + var upVector = { x: 0, y: 1, z: 0 }; + var intersection = this.rayPlaneIntersection(pickRay.origin, pickRay.direction, + this.properties.position, upVector); + this.graboffset = Vec3.subtract(this.properties.position, intersection); + }; + + this.stopSoundIfNotMoving = function(mouseEvent) { + var nowDate = new Date(); + var nowMSecs = nowDate.getTime(); + if(mouseEvent.x == this.lastMovedPosition.x && mouseEvent.y == this.lastMovedPosition.y) { + var elapsedSinceLastMove = nowMSecs - this.lastMovedMSecs; + if (debug) { + print("elapsedSinceLastMove:" + elapsedSinceLastMove); + } + if (elapsedSinceLastMove > stopSoundDelay) { + if (debug) { + print("calling stopSound()..."); + } + this.stopSound(); + } + } else { + // if we've moved, then track our last move position and time... + this.lastMovedMSecs = nowMSecs; + this.lastMovedPosition.x = mouseEvent.x; + this.lastMovedPosition.y = mouseEvent.y; + } + } + + this.move = function(mouseEvent) { + this.updatePosition(mouseEvent); + if (this.injector === null) { + this.playMoveSound(); + } + }; + + this.release = function(mouseEvent) { + this.updatePosition(mouseEvent); + }; + + this.rotate = function(mouseEvent) { + var pickRay = Camera.computePickRay(mouseEvent.x, mouseEvent.y) + var result = Overlays.findRayIntersection(pickRay); + + if (result.intersects) { + var center = yawCenter; + var zero = yawZero; + var centerToZero = Vec3.subtract(center, zero); + var centerToIntersect = Vec3.subtract(center, result.intersection); + var angleFromZero = Vec3.orientedAngle(centerToZero, centerToIntersect, rotationNormal); + + var distanceFromCenter = Vec3.distance(center, result.intersection); + var snapToInner = false; + // var innerRadius = (Vec3.length(selectionManager.worldDimensions) / 2) * 1.1; + if (distanceFromCenter < innerRadius) { + angleFromZero = Math.floor(angleFromZero/innerSnapAngle) * innerSnapAngle; + snapToInner = true; + } + + var yawChange = Quat.fromVec3Degrees({ x: 0, y: angleFromZero, z: 0 }); + Entities.editEntity(this.entityID, { rotation: Quat.multiply(yawChange, this.originalRotation) }); + + + // update the rotation display accordingly... + var startAtCurrent = 360-angleFromZero; + var endAtCurrent = 360; + var startAtRemainder = 0; + var endAtRemainder = 360-angleFromZero; + if (angleFromZero < 0) { + startAtCurrent = 0; + endAtCurrent = -angleFromZero; + startAtRemainder = -angleFromZero; + endAtRemainder = 360; + } + + if (snapToInner) { + Overlays.editOverlay(this.rotateOverlayOuter, { startAt: 0, endAt: 360 }); + Overlays.editOverlay(this.rotateOverlayInner, { startAt: startAtRemainder, endAt: endAtRemainder }); + Overlays.editOverlay(this.rotateOverlayCurrent, { startAt: startAtCurrent, endAt: endAtCurrent, size: innerRadius, + majorTickMarksAngle: innerSnapAngle, minorTickMarksAngle: 0, + majorTickMarksLength: -0.25, minorTickMarksLength: 0, }); + } else { + Overlays.editOverlay(this.rotateOverlayInner, { startAt: 0, endAt: 360 }); + Overlays.editOverlay(this.rotateOverlayOuter, { startAt: startAtRemainder, endAt: endAtRemainder }); + Overlays.editOverlay(this.rotateOverlayCurrent, { startAt: startAtCurrent, endAt: endAtCurrent, size: outerRadius, + majorTickMarksAngle: 45.0, minorTickMarksAngle: 5, + majorTickMarksLength: 0.25, minorTickMarksLength: 0.1, }); + } + } + + if (this.injector === null) { + this.playTurnSound(); + } + }; + // All callbacks start by updating the properties + this.updateProperties = function(entityID) { + if (this.entityID === null || !this.entityID.isKnownID) { + this.entityID = Entities.identifyEntity(entityID); + } + this.properties = Entities.getEntityProperties(this.entityID); + }; + + this.cleanupRotateOverlay = function() { + Overlays.deleteOverlay(this.rotateOverlayTarget); + Overlays.deleteOverlay(this.rotateOverlayInner); + Overlays.deleteOverlay(this.rotateOverlayOuter); + Overlays.deleteOverlay(this.rotateOverlayCurrent); + this.rotateOverlayTarget = null; + this.rotateOverlayInner = null; + this.rotateOverlayOuter = null; + this.rotateOverlayCurrent = null; + } + + this.displayRotateOverlay = function(mouseEvent) { + var yawOverlayAngles = { x: 90, y: 0, z: 0 }; + var yawOverlayRotation = Quat.fromVec3Degrees(yawOverlayAngles); + + yawNormal = { x: 0, y: 1, z: 0 }; + yawCenter = this.properties.position; + rotationNormal = yawNormal; + + // Size the overlays to the current selection size + var diagonal = (Vec3.length(this.properties.dimensions) / 2) * 1.1; + var halfDimensions = Vec3.multiply(this.properties.dimensions, 0.5); + innerRadius = diagonal; + outerRadius = diagonal * 1.15; + var innerAlpha = 0.2; + var outerAlpha = 0.2; + + this.rotateOverlayTarget = Overlays.addOverlay("circle3d", { + position: this.properties.position, + size: rotateOverlayTargetSize, + color: { red: 0, green: 0, blue: 0 }, + alpha: 0.0, + solid: true, + visible: true, + rotation: yawOverlayRotation, + ignoreRayIntersection: false + }); + + this.rotateOverlayInner = Overlays.addOverlay("circle3d", { + position: this.properties.position, + size: innerRadius, + innerRadius: 0.9, + alpha: innerAlpha, + color: { red: 51, green: 152, blue: 203 }, + solid: true, + visible: displayRotateTargets, + rotation: yawOverlayRotation, + hasTickMarks: true, + majorTickMarksAngle: innerSnapAngle, + minorTickMarksAngle: 0, + majorTickMarksLength: -0.25, + minorTickMarksLength: 0, + majorTickMarksColor: { red: 0, green: 0, blue: 0 }, + minorTickMarksColor: { red: 0, green: 0, blue: 0 }, + ignoreRayIntersection: true, // always ignore this + }); + + this.rotateOverlayOuter = Overlays.addOverlay("circle3d", { + position: this.properties.position, + size: outerRadius, + innerRadius: 0.9, + startAt: 0, + endAt: 360, + alpha: outerAlpha, + color: { red: 51, green: 152, blue: 203 }, + solid: true, + visible: displayRotateTargets, + rotation: yawOverlayRotation, + + hasTickMarks: true, + majorTickMarksAngle: 45.0, + minorTickMarksAngle: 5, + majorTickMarksLength: 0.25, + minorTickMarksLength: 0.1, + majorTickMarksColor: { red: 0, green: 0, blue: 0 }, + minorTickMarksColor: { red: 0, green: 0, blue: 0 }, + ignoreRayIntersection: true, // always ignore this + }); + + this.rotateOverlayCurrent = Overlays.addOverlay("circle3d", { + position: this.properties.position, + size: outerRadius, + startAt: 0, + endAt: 0, + innerRadius: 0.9, + color: { red: 224, green: 67, blue: 36}, + alpha: 0.8, + solid: true, + visible: displayRotateTargets, + rotation: yawOverlayRotation, + ignoreRayIntersection: true, // always ignore this + hasTickMarks: true, + majorTickMarksColor: { red: 0, green: 0, blue: 0 }, + minorTickMarksColor: { red: 0, green: 0, blue: 0 }, + }); + + var pickRay = Camera.computePickRay(mouseEvent.x, mouseEvent.y) + var result = Overlays.findRayIntersection(pickRay); + yawZero = result.intersection; + + }; + + this.preload = function(entityID) { + this.updateProperties(entityID); // All callbacks start by updating the properties + this.downloadSounds(); + }; + + this.clickDownOnEntity = function(entityID, mouseEvent) { + this.updateProperties(entityID); // All callbacks start by updating the properties + this.grab(mouseEvent); + + var nowDate = new Date(); + var nowMSecs = nowDate.getTime(); + this.clickedAt = nowMSecs; + this.firstHolding = true; + + this.clicked.x = mouseEvent.x; + this.clicked.y = mouseEvent.y; + this.lastMovedPosition.x = mouseEvent.x; + this.lastMovedPosition.y = mouseEvent.y; + this.lastMovedMSecs = nowMSecs; + + this.pickRandomSounds(); + }; + + this.holdingClickOnEntity = function(entityID, mouseEvent) { + + this.updateProperties(entityID); // All callbacks start by updating the properties + + if (this.firstHolding) { + // if we haven't moved yet... + if (this.clicked.x == mouseEvent.x && this.clicked.y == mouseEvent.y) { + var d = new Date(); + var now = d.getTime(); + + if (now - this.clickedAt > 500) { + this.displayRotateOverlay(mouseEvent); + this.firstHolding = false; + this.rotateMode = true; + this.originalRotation = this.properties.rotation; + } + } else { + this.firstHolding = false; + } + } + + if (this.rotateMode) { + this.rotate(mouseEvent); + } else { + this.move(mouseEvent); + } + + this.stopSoundIfNotMoving(mouseEvent); + }; + this.clickReleaseOnEntity = function(entityID, mouseEvent) { + this.updateProperties(entityID); // All callbacks start by updating the properties + if (this.rotateMode) { + this.rotate(mouseEvent); + } else { + this.release(mouseEvent); + } + + if (this.rotateOverlayTarget != null) { + this.cleanupRotateOverlay(); + this.rotateMode = false; + } + + this.firstHolding = false; + this.stopSound(); + }; + +}) \ No newline at end of file diff --git a/examples/entityScripts/movableClass.js b/examples/entityScripts/movableClass.js deleted file mode 100644 index 26fb643826..0000000000 --- a/examples/entityScripts/movableClass.js +++ /dev/null @@ -1,426 +0,0 @@ -// -// movableClass.js -// examples/entityScripts -// -// Created by Brad Hefta-Gaub on 11/17/14. -// Copyright 2014 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// -Movable = function() { - - this.entityID = null; - this.properties = null; - this.graboffset = null; - this.clickedAt = null; - this.firstHolding = true; - this.clicked = { x: -1, y: -1}; - this.lastMovedPosition = { x: -1, y: -1}; - this.lastMovedTime = 0; - this.rotateOverlayTarget = null; - this.rotateOverlayInner = null; - this.rotateOverlayOuter = null; - this.rotateOverlayCurrent = null; - this.rotateMode = false; - this.originalRotation = null; - - this.moveSoundURLS = [ - "http://public.highfidelity.io/sounds/MovingFurniture/FurnitureMove1.wav", - "http://public.highfidelity.io/sounds/MovingFurniture/FurnitureMove2.wav", - "http://public.highfidelity.io/sounds/MovingFurniture/FurnitureMove3.wav" - ]; - - this.turnSoundURLS = [ - - "http://public.highfidelity.io/sounds/MovingFurniture/FurnitureMove1.wav", - "http://public.highfidelity.io/sounds/MovingFurniture/FurnitureMove2.wav", - "http://public.highfidelity.io/sounds/MovingFurniture/FurnitureMove3.wav" - - // TODO: determine if these or other turn sounds work better than move sounds. - //"http://public.highfidelity.io/sounds/MovingFurniture/FurnitureTurn1.wav", - //"http://public.highfidelity.io/sounds/MovingFurniture/FurnitureTurn2.wav", - //"http://public.highfidelity.io/sounds/MovingFurniture/FurnitureTurn3.wav" - ]; - - - this.moveSounds = new Array(); - this.turnSounds = new Array(); - this.moveSound = null; - this.turnSound = null; - this.injector = null; - - var debug = false; - var displayRotateTargets = true; // change to false if you don't want the rotate targets - var rotateOverlayTargetSize = 10000; // really big target - var innerSnapAngle = 22.5; // the angle which we snap to on the inner rotation tool - var innerRadius; - var outerRadius; - var yawCenter; - var yawZero; - var rotationNormal; - var yawNormal; - var stopSoundDelay = 100; // number of msecs of not moving to have sound stop - - this.getRandomInt = function(min, max) { - return Math.floor(Math.random() * (max - min + 1)) + min; - } - - this.downloadSounds = function() { - for (var i = 0; i < this.moveSoundURLS.length; i++) { - this.moveSounds[i] = SoundCache.getSound(this.moveSoundURLS[i]); - } - for (var i = 0; i < this.turnSoundURLS.length; i++) { - this.turnSounds[i] = SoundCache.getSound(this.turnSoundURLS[i]); - } - } - - this.pickRandomSounds = function() { - var moveIndex = this.getRandomInt(0, this.moveSounds.length - 1); - var turnIndex = this.getRandomInt(0, this.turnSounds.length - 1); - if (debug) { - print("Random sounds -- turn:" + turnIndex + " move:" + moveIndex); - } - this.moveSound = this.moveSounds[moveIndex]; - this.turnSound = this.turnSounds[turnIndex]; - } - - // Play move sound - this.playMoveSound = function() { - if (debug) { - print("playMoveSound()"); - } - if (this.moveSound && this.moveSound.downloaded) { - if (debug) { - print("playMoveSound() --- calling this.injector = Audio.playSound(this.moveSound...)"); - } - this.injector = Audio.playSound(this.moveSound, { position: this.properties.position, loop: true, volume: 0.1 }); - } - } - - // Play turn sound - this.playTurnSound = function() { - if (debug) { - print("playTurnSound()"); - } - if (this.turnSound && this.turnSound.downloaded) { - if (debug) { - print("playTurnSound() --- calling this.injector = Audio.playSound(this.turnSound...)"); - } - this.injector = Audio.playSound(this.turnSound, { position: this.properties.position, loop: true, volume: 0.1 }); - } - } - - // stop sound - this.stopSound = function() { - if (debug) { - print("stopSound()"); - } - if (this.injector) { - Audio.stopInjector(this.injector); - this.injector = null; - } - } - - // Pr, Vr are respectively the Ray's Point of origin and Vector director - // Pp, Np are respectively the Plane's Point of origin and Normal vector - this.rayPlaneIntersection = function(Pr, Vr, Pp, Np) { - var d = -Vec3.dot(Pp, Np); - var t = -(Vec3.dot(Pr, Np) + d) / Vec3.dot(Vr, Np); - return Vec3.sum(Pr, Vec3.multiply(t, Vr)); - }; - - // updates the piece position based on mouse input - this.updatePosition = function(mouseEvent) { - var pickRay = Camera.computePickRay(mouseEvent.x, mouseEvent.y) - var upVector = { x: 0, y: 1, z: 0 }; - var intersection = this.rayPlaneIntersection(pickRay.origin, pickRay.direction, - this.properties.position, upVector); - - var newPosition = Vec3.sum(intersection, this.graboffset); - Entities.editEntity(this.entityID, { position: newPosition }); - }; - - this.grab = function(mouseEvent) { - // first calculate the offset - var pickRay = Camera.computePickRay(mouseEvent.x, mouseEvent.y) - var upVector = { x: 0, y: 1, z: 0 }; - var intersection = this.rayPlaneIntersection(pickRay.origin, pickRay.direction, - this.properties.position, upVector); - this.graboffset = Vec3.subtract(this.properties.position, intersection); - }; - - this.stopSoundIfNotMoving = function(mouseEvent) { - var nowDate = new Date(); - var nowMSecs = nowDate.getTime(); - if(mouseEvent.x == this.lastMovedPosition.x && mouseEvent.y == this.lastMovedPosition.y) { - var elapsedSinceLastMove = nowMSecs - this.lastMovedMSecs; - if (debug) { - print("elapsedSinceLastMove:" + elapsedSinceLastMove); - } - if (elapsedSinceLastMove > stopSoundDelay) { - if (debug) { - print("calling stopSound()..."); - } - this.stopSound(); - } - } else { - // if we've moved, then track our last move position and time... - this.lastMovedMSecs = nowMSecs; - this.lastMovedPosition.x = mouseEvent.x; - this.lastMovedPosition.y = mouseEvent.y; - } - } - - this.move = function(mouseEvent) { - this.updatePosition(mouseEvent); - if (this.injector === null) { - this.playMoveSound(); - } - }; - - this.release = function(mouseEvent) { - this.updatePosition(mouseEvent); - }; - - this.rotate = function(mouseEvent) { - var pickRay = Camera.computePickRay(mouseEvent.x, mouseEvent.y) - var result = Overlays.findRayIntersection(pickRay); - - if (result.intersects) { - var center = yawCenter; - var zero = yawZero; - var centerToZero = Vec3.subtract(center, zero); - var centerToIntersect = Vec3.subtract(center, result.intersection); - var angleFromZero = Vec3.orientedAngle(centerToZero, centerToIntersect, rotationNormal); - - var distanceFromCenter = Vec3.distance(center, result.intersection); - var snapToInner = false; - // var innerRadius = (Vec3.length(selectionManager.worldDimensions) / 2) * 1.1; - if (distanceFromCenter < innerRadius) { - angleFromZero = Math.floor(angleFromZero/innerSnapAngle) * innerSnapAngle; - snapToInner = true; - } - - var yawChange = Quat.fromVec3Degrees({ x: 0, y: angleFromZero, z: 0 }); - Entities.editEntity(this.entityID, { rotation: Quat.multiply(yawChange, this.originalRotation) }); - - - // update the rotation display accordingly... - var startAtCurrent = 360-angleFromZero; - var endAtCurrent = 360; - var startAtRemainder = 0; - var endAtRemainder = 360-angleFromZero; - if (angleFromZero < 0) { - startAtCurrent = 0; - endAtCurrent = -angleFromZero; - startAtRemainder = -angleFromZero; - endAtRemainder = 360; - } - - if (snapToInner) { - Overlays.editOverlay(this.rotateOverlayOuter, { startAt: 0, endAt: 360 }); - Overlays.editOverlay(this.rotateOverlayInner, { startAt: startAtRemainder, endAt: endAtRemainder }); - Overlays.editOverlay(this.rotateOverlayCurrent, { startAt: startAtCurrent, endAt: endAtCurrent, size: innerRadius, - majorTickMarksAngle: innerSnapAngle, minorTickMarksAngle: 0, - majorTickMarksLength: -0.25, minorTickMarksLength: 0, }); - } else { - Overlays.editOverlay(this.rotateOverlayInner, { startAt: 0, endAt: 360 }); - Overlays.editOverlay(this.rotateOverlayOuter, { startAt: startAtRemainder, endAt: endAtRemainder }); - Overlays.editOverlay(this.rotateOverlayCurrent, { startAt: startAtCurrent, endAt: endAtCurrent, size: outerRadius, - majorTickMarksAngle: 45.0, minorTickMarksAngle: 5, - majorTickMarksLength: 0.25, minorTickMarksLength: 0.1, }); - } - } - - if (this.injector === null) { - this.playTurnSound(); - } - }; - // All callbacks start by updating the properties - this.updateProperties = function(entityID) { - if (this.entityID === null || !this.entityID.isKnownID) { - this.entityID = Entities.identifyEntity(entityID); - } - this.properties = Entities.getEntityProperties(this.entityID); - }; - - this.cleanupRotateOverlay = function() { - Overlays.deleteOverlay(this.rotateOverlayTarget); - Overlays.deleteOverlay(this.rotateOverlayInner); - Overlays.deleteOverlay(this.rotateOverlayOuter); - Overlays.deleteOverlay(this.rotateOverlayCurrent); - this.rotateOverlayTarget = null; - this.rotateOverlayInner = null; - this.rotateOverlayOuter = null; - this.rotateOverlayCurrent = null; - } - - this.displayRotateOverlay = function(mouseEvent) { - var yawOverlayAngles = { x: 90, y: 0, z: 0 }; - var yawOverlayRotation = Quat.fromVec3Degrees(yawOverlayAngles); - - yawNormal = { x: 0, y: 1, z: 0 }; - yawCenter = this.properties.position; - rotationNormal = yawNormal; - - // Size the overlays to the current selection size - var diagonal = (Vec3.length(this.properties.dimensions) / 2) * 1.1; - var halfDimensions = Vec3.multiply(this.properties.dimensions, 0.5); - innerRadius = diagonal; - outerRadius = diagonal * 1.15; - var innerAlpha = 0.2; - var outerAlpha = 0.2; - - this.rotateOverlayTarget = Overlays.addOverlay("circle3d", { - position: this.properties.position, - size: rotateOverlayTargetSize, - color: { red: 0, green: 0, blue: 0 }, - alpha: 0.0, - solid: true, - visible: true, - rotation: yawOverlayRotation, - ignoreRayIntersection: false - }); - - this.rotateOverlayInner = Overlays.addOverlay("circle3d", { - position: this.properties.position, - size: innerRadius, - innerRadius: 0.9, - alpha: innerAlpha, - color: { red: 51, green: 152, blue: 203 }, - solid: true, - visible: displayRotateTargets, - rotation: yawOverlayRotation, - hasTickMarks: true, - majorTickMarksAngle: innerSnapAngle, - minorTickMarksAngle: 0, - majorTickMarksLength: -0.25, - minorTickMarksLength: 0, - majorTickMarksColor: { red: 0, green: 0, blue: 0 }, - minorTickMarksColor: { red: 0, green: 0, blue: 0 }, - ignoreRayIntersection: true, // always ignore this - }); - - this.rotateOverlayOuter = Overlays.addOverlay("circle3d", { - position: this.properties.position, - size: outerRadius, - innerRadius: 0.9, - startAt: 0, - endAt: 360, - alpha: outerAlpha, - color: { red: 51, green: 152, blue: 203 }, - solid: true, - visible: displayRotateTargets, - rotation: yawOverlayRotation, - - hasTickMarks: true, - majorTickMarksAngle: 45.0, - minorTickMarksAngle: 5, - majorTickMarksLength: 0.25, - minorTickMarksLength: 0.1, - majorTickMarksColor: { red: 0, green: 0, blue: 0 }, - minorTickMarksColor: { red: 0, green: 0, blue: 0 }, - ignoreRayIntersection: true, // always ignore this - }); - - this.rotateOverlayCurrent = Overlays.addOverlay("circle3d", { - position: this.properties.position, - size: outerRadius, - startAt: 0, - endAt: 0, - innerRadius: 0.9, - color: { red: 224, green: 67, blue: 36}, - alpha: 0.8, - solid: true, - visible: displayRotateTargets, - rotation: yawOverlayRotation, - ignoreRayIntersection: true, // always ignore this - hasTickMarks: true, - majorTickMarksColor: { red: 0, green: 0, blue: 0 }, - minorTickMarksColor: { red: 0, green: 0, blue: 0 }, - }); - - var pickRay = Camera.computePickRay(mouseEvent.x, mouseEvent.y) - var result = Overlays.findRayIntersection(pickRay); - yawZero = result.intersection; - - }; -}; - -Movable.prototype = { - preload : function(entityID) { - print("Movable.preload()"); - this.updateProperties(entityID); // All callbacks start by updating the properties - this.downloadSounds(); - }, - - clickDownOnEntity : function(entityID, mouseEvent) { - print("Movable.clickDownOnEntity()"); - - this.updateProperties(entityID); // All callbacks start by updating the properties - this.grab(mouseEvent); - - var nowDate = new Date(); - var nowMSecs = nowDate.getTime(); - this.clickedAt = nowMSecs; - this.firstHolding = true; - - this.clicked.x = mouseEvent.x; - this.clicked.y = mouseEvent.y; - this.lastMovedPosition.x = mouseEvent.x; - this.lastMovedPosition.y = mouseEvent.y; - this.lastMovedMSecs = nowMSecs; - - this.pickRandomSounds(); - }, - - holdingClickOnEntity : function(entityID, mouseEvent) { - print("Movable.holdingClickOnEntity()"); - - this.updateProperties(entityID); // All callbacks start by updating the properties - - if (this.firstHolding) { - // if we haven't moved yet... - if (this.clicked.x == mouseEvent.x && this.clicked.y == mouseEvent.y) { - var d = new Date(); - var now = d.getTime(); - - if (now - this.clickedAt > 500) { - this.displayRotateOverlay(mouseEvent); - this.firstHolding = false; - this.rotateMode = true; - this.originalRotation = this.properties.rotation; - } - } else { - this.firstHolding = false; - } - } - - if (this.rotateMode) { - this.rotate(mouseEvent); - } else { - this.move(mouseEvent); - } - - this.stopSoundIfNotMoving(mouseEvent); - }, - - clickReleaseOnEntity : function(entityID, mouseEvent) { - print("Movable.clickReleaseOnEntity()"); - this.updateProperties(entityID); // All callbacks start by updating the properties - if (this.rotateMode) { - this.rotate(mouseEvent); - } else { - this.release(mouseEvent); - } - - if (this.rotateOverlayTarget != null) { - this.cleanupRotateOverlay(); - this.rotateMode = false; - } - - this.firstHolding = false; - this.stopSound(); - }, -}; diff --git a/examples/entityScripts/sitOnEntity.js b/examples/entityScripts/sitOnEntity.js index 080acf61a8..d5c4fa9c52 100644 --- a/examples/entityScripts/sitOnEntity.js +++ b/examples/entityScripts/sitOnEntity.js @@ -11,7 +11,362 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -(function() { - Script.include("sittableClass.js"); - return new Sittable(); -}) +(function(){ + + this.entityID = null; + this.properties = null; + this.standUpButton = null; + this.indicatorsAdded = false; + this.indicator = new Array(); + + + var buttonImageUrl = "https://worklist-prod.s3.amazonaws.com/attachment/0aca88e1-9bd8-5c1d.svg"; + var windowDimensions = Controller.getViewportDimensions(); + var buttonWidth = 37; + var buttonHeight = 46; + var buttonPadding = 50; // inside the normal toolbar position + var buttonPositionX = windowDimensions.x - buttonPadding - buttonWidth; + var buttonPositionY = (windowDimensions.y - buttonHeight) / 2 - (buttonHeight + buttonPadding); + + var passedTime = 0.0; + var startPosition = null; + var startRotation = null; + var animationLenght = 2.0; + + var avatarOldPosition = { x: 0, y: 0, z: 0 }; + + var sittingSettingsHandle = "SitJsSittingPosition"; + var sitting = Settings.getValue(sittingSettingsHandle, false) == "true"; + print("Original sitting status: " + sitting); + var frame = 0; + + var seat = new Object(); + var hiddingSeats = false; + + // This is the pose we would like to end up + var pose = [ + {joint:"RightUpLeg", rotation: {x:100.0, y:15.0, z:0.0}}, + {joint:"RightLeg", rotation: {x:-130.0, y:15.0, z:0.0}}, + {joint:"RightFoot", rotation: {x:30, y:15.0, z:0.0}}, + {joint:"LeftUpLeg", rotation: {x:100.0, y:-15.0, z:0.0}}, + {joint:"LeftLeg", rotation: {x:-130.0, y:-15.0, z:0.0}}, + {joint:"LeftFoot", rotation: {x:30, y:15.0, z:0.0}} + ]; + + var startPoseAndTransition = []; + + function storeStartPoseAndTransition() { + for (var i = 0; i < pose.length; i++){ + var startRotation = Quat.safeEulerAngles(MyAvatar.getJointRotation(pose[i].joint)); + var transitionVector = Vec3.subtract( pose[i].rotation, startRotation ); + startPoseAndTransition.push({joint: pose[i].joint, start: startRotation, transition: transitionVector}); + } + } + + function updateJoints(factor){ + for (var i = 0; i < startPoseAndTransition.length; i++){ + var scaledTransition = Vec3.multiply(startPoseAndTransition[i].transition, factor); + var rotation = Vec3.sum(startPoseAndTransition[i].start, scaledTransition); + MyAvatar.setJointData(startPoseAndTransition[i].joint, Quat.fromVec3Degrees( rotation )); + } + } + + var sittingDownAnimation = function(deltaTime) { + + passedTime += deltaTime; + var factor = passedTime/animationLenght; + + if ( passedTime <= animationLenght ) { + updateJoints(factor); + + var pos = { x: startPosition.x - 0.3 * factor, y: startPosition.y - 0.5 * factor, z: startPosition.z}; + MyAvatar.position = pos; + } else { + Script.update.disconnect(sittingDownAnimation); + if (seat.model) { + MyAvatar.setModelReferential(seat.model.id); + } + } + } + + var standingUpAnimation = function(deltaTime) { + + passedTime += deltaTime; + var factor = 1 - passedTime/animationLenght; + + if ( passedTime <= animationLenght ) { + + updateJoints(factor); + + var pos = { x: startPosition.x + 0.3 * (passedTime/animationLenght), y: startPosition.y + 0.5 * (passedTime/animationLenght), z: startPosition.z}; + MyAvatar.position = pos; + } else { + Script.update.disconnect(standingUpAnimation); + + } + } + + var externalThis = this; + + var goToSeatAnimation = function(deltaTime) { + passedTime += deltaTime; + var factor = passedTime/animationLenght; + + if (passedTime <= animationLenght) { + var targetPosition = Vec3.sum(seat.position, { x: 0.3, y: 0.5, z: 0 }); + MyAvatar.position = Vec3.sum(Vec3.multiply(startPosition, 1 - factor), Vec3.multiply(targetPosition, factor)); + } else if (passedTime <= 2 * animationLenght) { + //Quat.print("MyAvatar: ", MyAvatar.orientation); + //Quat.print("Seat: ", seat.rotation); + MyAvatar.orientation = Quat.mix(startRotation, seat.rotation, factor - 1); + } else { + Script.update.disconnect(goToSeatAnimation); + externalThis.sitDown(); + externalThis.showIndicators(false); + } + } + + var globalMouseClick = function(event) { + var clickedOverlay = Overlays.getOverlayAtPoint({x: event.x, y: event.y}); + if (clickedOverlay == externalThis.standUpButton) { + seat.model = null; + externalThis.standUp(); + Controller.mousePressEvent.disconnect(globalMouseClick); + } + }; + + this.sitDown = function() { + sitting = true; + Settings.setValue(sittingSettingsHandle, sitting); + print("sitDown sitting status: " + Settings.getValue(sittingSettingsHandle, false)); + passedTime = 0.0; + startPosition = MyAvatar.position; + storeStartPoseAndTransition(); + try { + Script.update.disconnect(standingUpAnimation); + } catch(e){ + // no need to handle. if it wasn't connected no harm done + } + Script.update.connect(sittingDownAnimation); + Overlays.editOverlay(this.standUpButton, { visible: true }); + Controller.mousePressEvent.connect(globalMouseClick); + } + + this.standUp = function() { + sitting = false; + Settings.setValue(sittingSettingsHandle, sitting); + print("standUp sitting status: " + Settings.getValue(sittingSettingsHandle, false)); + passedTime = 0.0; + startPosition = MyAvatar.position; + MyAvatar.clearReferential(); + try{ + Script.update.disconnect(sittingDownAnimation); + } catch (e){} + Script.update.connect(standingUpAnimation); + Overlays.editOverlay(this.standUpButton, { visible: false }); + Controller.mousePressEvent.disconnect(globalMouseClick); + } + + function SeatIndicator(modelProperties, seatIndex) { + var halfDiagonal = Vec3.length(modelProperties.dimensions) / 2.0; + + this.position = Vec3.sum(modelProperties.position, + Vec3.multiply(Vec3.multiplyQbyV(modelProperties.rotation, modelProperties.sittingPoints[seatIndex].position), + halfDiagonal)); // hack + + this.orientation = Quat.multiply(modelProperties.rotation, + modelProperties.sittingPoints[seatIndex].rotation); + this.scale = MyAvatar.scale / 3; + + this.sphere = Overlays.addOverlay("billboard", { + subImage: { x: 0, y: buttonHeight, width: buttonWidth, height: buttonHeight}, + url: buttonImageUrl, + position: this.position, + scale: this.scale, + size: this.scale, + solid: true, + color: { red: 255, green: 255, blue: 255 }, + alpha: 0.8, + visible: true, + isFacingAvatar: true + }); + + this.show = function(doShow) { + Overlays.editOverlay(this.sphere, { visible: doShow }); + } + + this.update = function() { + Overlays.editOverlay(this.sphere, { + position: this.position, + size: this.scale + }); + } + + this.cleanup = function() { + Overlays.deleteOverlay(this.sphere); + } + } + + function update(deltaTime){ + var newWindowDimensions = Controller.getViewportDimensions(); + if( newWindowDimensions.x != windowDimensions.x || newWindowDimensions.y != windowDimensions.y ){ + windowDimensions = newWindowDimensions; + var newX = windowDimensions.x - buttonPadding - buttonWidth; + var newY = (windowDimensions.y - buttonHeight) / 2 ; + Overlays.editOverlay( this.standUpButton, {x: newX, y: newY} ); + } + + // For a weird reason avatar joint don't update till the 10th frame + // Set the update frame to 20 to be safe + var UPDATE_FRAME = 20; + if (frame <= UPDATE_FRAME) { + if (frame == UPDATE_FRAME) { + if (sitting == true) { + print("Was seated: " + sitting); + storeStartPoseAndTransition(); + updateJoints(1.0); + } + } + frame++; + } + } + + this.addIndicators = function() { + if (!this.indicatorsAdded) { + if (this.properties.sittingPoints.length > 0) { + for (var i = 0; i < this.properties.sittingPoints.length; ++i) { + this.indicator[i] = new SeatIndicator(this.properties, i); + } + this.indicatorsAdded = true; + } + } + } + + this.removeIndicators = function() { + for (var i = 0; i < this.properties.sittingPoints.length; ++i) { + this.indicator[i].cleanup(); + } + } + + this.showIndicators = function(doShow) { + this.addIndicators(); + if (this.indicatorsAdded) { + for (var i = 0; i < this.properties.sittingPoints.length; ++i) { + this.indicator[i].show(doShow); + } + } + hiddingSeats = !doShow; + } + + function raySphereIntersection(origin, direction, center, radius) { + var A = origin; + var B = Vec3.normalize(direction); + var P = center; + + var x = Vec3.dot(Vec3.subtract(P, A), B); + var X = Vec3.sum(A, Vec3.multiply(B, x)); + var d = Vec3.length(Vec3.subtract(P, X)); + + return (x > 0 && d <= radius); + } + + this.cleanup = function() { + this.standUp(); + MyAvatar.clearReferential(); + for (var i = 0; i < pose.length; i++){ + MyAvatar.clearJointData(pose[i].joint); + } + Overlays.deleteOverlay(this.standUpButton); + for (var i = 0; i < this.indicator.length; ++i) { + this.indicator[i].cleanup(); + } + }; + + + this.createStandupButton = function() { + this.standUpButton = Overlays.addOverlay("image", { + x: buttonPositionX, y: buttonPositionY, width: buttonWidth, height: buttonHeight, + subImage: { x: buttonWidth, y: buttonHeight, width: buttonWidth, height: buttonHeight}, + imageURL: buttonImageUrl, + visible: false, + alpha: 1.0 + }); + }; + + this.handleClickEvent = function(event) { + var clickedOverlay = Overlays.getOverlayAtPoint({x: event.x, y: event.y}); + + if (clickedOverlay == this.standUpButton) { + seat.model = null; + this.standUp(); + } else { + this.addIndicators(); + if (this.indicatorsAdded) { + var pickRay = Camera.computePickRay(event.x, event.y); + + var clickedOnSeat = false; + + for (var i = 0; i < this.properties.sittingPoints.length; ++i) { + if (raySphereIntersection(pickRay.origin, + pickRay.direction, + this.indicator[i].position, + this.indicator[i].scale / 2)) { + clickedOnSeat = true; + seat.model = this.entityID; // ?? + seat.position = this.indicator[i].position; + seat.rotation = this.indicator[i].orientation; + } + } + + if (clickedOnSeat) { + passedTime = 0.0; + startPosition = MyAvatar.position; + startRotation = MyAvatar.orientation; + try{ Script.update.disconnect(standingUpAnimation); } catch(e){} + try{ Script.update.disconnect(sittingDownAnimation); } catch(e){} + Script.update.connect(goToSeatAnimation); + } + } + } + }; + + + // All callbacks start by updating the properties + this.updateProperties = function(entityID) { + if (this.entityID === null || !this.entityID.isKnownID) { + this.entityID = Entities.identifyEntity(entityID); + } + this.properties = Entities.getEntityProperties(this.entityID); + }; + + this.unload = function(entityID) { + this.cleanup(); + Script.update.disconnect(update); + }; + + this.preload = function(entityID) { + this.updateProperties(entityID); // All callbacks start by updating the properties + this.createStandupButton(); + Script.update.connect(update); + }; + + + this.hoverOverEntity = function(entityID, mouseEvent) { + this.updateProperties(entityID); // All callbacks start by updating the properties + this.showIndicators(true); + }; + this.hoverLeaveEntity = function(entityID, mouseEvent) { + this.updateProperties(entityID); // All callbacks start by updating the properties + this.showIndicators(false); + }; + + this.clickDownOnEntity = function(entityID, mouseEvent) { + this.updateProperties(entityID); // All callbacks start by updating the properties + this.handleClickEvent(mouseEvent); + }; + + this.clickReleaseOnEntity = function(entityID, mouseEvent) { + this.updateProperties(entityID); // All callbacks start by updating the properties + }; + +}) \ No newline at end of file diff --git a/examples/entityScripts/sittable.js b/examples/entityScripts/sittable.js deleted file mode 100644 index 0753a46d2a..0000000000 --- a/examples/entityScripts/sittable.js +++ /dev/null @@ -1,15 +0,0 @@ -// -// sittable.js -// examples/entityScripts -// -// Created by Brad Hefta-Gaub on 11/17/14. -// Copyright 2014 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -(function() { - Script.include("sittableClass.js"); - return new Sittable(); -}) diff --git a/examples/entityScripts/sittableClass.js b/examples/entityScripts/sittableClass.js deleted file mode 100644 index 1a7b1df25a..0000000000 --- a/examples/entityScripts/sittableClass.js +++ /dev/null @@ -1,393 +0,0 @@ -// -// sitOnEntity.js -// examples/entityScripts -// -// Created by Brad Hefta-Gaub on 11/1/14. -// Copyright 2014 High Fidelity, Inc. -// -// This is an example of an entity script for sitting. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -var activeSittable = null; -function SittableUpdate(deltaTime){ - - // This keeps the standup button in a reasonable place. - var newWindowDimensions = Controller.getViewportDimensions(); - if( newWindowDimensions.x != windowDimensions.x || newWindowDimensions.y != windowDimensions.y ){ - windowDimensions = newWindowDimensions; - var newX = windowDimensions.x - buttonPadding - buttonWidth; - var newY = (windowDimensions.y - buttonHeight) / 2 ; - Overlays.editOverlay( activeSittable.standUpButton, {x: newX, y: newY} ); - } - - - // this appears to be some logic related to storing the original position - /* - - // For a weird reason avatar joint don't update till the 10th frame - // Set the update frame to 20 to be safe - var UPDATE_FRAME = 20; - if (frame <= UPDATE_FRAME) { - if (frame == UPDATE_FRAME) { - if (sitting == true) { - print("Was seated: " + sitting); - activeSittable.storeStartPoseAndTransition(); - activeSittable.updateJoints(1.0); - } - } - frame++; - } - */ -} - -SeatIndicator = function(modelProperties, seatIndex) { - var buttonImageUrl = "https://worklist-prod.s3.amazonaws.com/attachment/0aca88e1-9bd8-5c1d.svg"; - var buttonWidth = 37; - var buttonHeight = 46; - - var halfDiagonal = Vec3.length(modelProperties.dimensions) / 2.0; - - this.position = Vec3.sum(modelProperties.position, - Vec3.multiply(Vec3.multiplyQbyV(modelProperties.rotation, modelProperties.sittingPoints[seatIndex].position), - halfDiagonal)); // hack - - this.orientation = Quat.multiply(modelProperties.rotation, - modelProperties.sittingPoints[seatIndex].rotation); - this.scale = MyAvatar.scale / 3; - - this.sphere = Overlays.addOverlay("billboard", { - subImage: { x: 0, y: buttonHeight, width: buttonWidth, height: buttonHeight}, - url: buttonImageUrl, - position: this.position, - scale: this.scale, - size: this.scale, - solid: true, - color: { red: 255, green: 255, blue: 255 }, - alpha: 0.8, - visible: true, - isFacingAvatar: true - }); - - this.show = function(doShow) { - Overlays.editOverlay(this.sphere, { visible: doShow }); - } - - this.update = function() { - Overlays.editOverlay(this.sphere, { - position: this.position, - size: this.scale - }); - } - - this.cleanup = function() { - Overlays.deleteOverlay(this.sphere); - } -}; - -Sittable = function() { - - this.entityID = null; - this.properties = null; - this.standUpButton = null; - this.indicatorsAdded = false; - this.indicator = new Array(); - - - var buttonImageUrl = "https://worklist-prod.s3.amazonaws.com/attachment/0aca88e1-9bd8-5c1d.svg"; - var windowDimensions = Controller.getViewportDimensions(); - var buttonWidth = 37; - var buttonHeight = 46; - var buttonPadding = 50; // inside the normal toolbar position - var buttonPositionX = windowDimensions.x - buttonPadding - buttonWidth; - var buttonPositionY = (windowDimensions.y - buttonHeight) / 2 - (buttonHeight + buttonPadding); - - var passedTime = 0.0; - var startPosition = null; - var startRotation = null; - var animationLength = 2.0; - - var avatarOldPosition = { x: 0, y: 0, z: 0 }; - - var sittingSettingsHandle = "SitJsSittingPosition"; - var sitting = Settings.getValue(sittingSettingsHandle, false) == "true"; - print("Original sitting status: " + sitting); - var frame = 0; - - var seat = new Object(); - var hiddingSeats = false; - - // This is the pose we would like to end up - var pose = [ - {joint:"RightUpLeg", rotation: {x:100.0, y:15.0, z:0.0}}, - {joint:"RightLeg", rotation: {x:-130.0, y:15.0, z:0.0}}, - {joint:"RightFoot", rotation: {x:30, y:15.0, z:0.0}}, - {joint:"LeftUpLeg", rotation: {x:100.0, y:-15.0, z:0.0}}, - {joint:"LeftLeg", rotation: {x:-130.0, y:-15.0, z:0.0}}, - {joint:"LeftFoot", rotation: {x:30, y:15.0, z:0.0}} - ]; - - var startPoseAndTransition = []; - - function storeStartPoseAndTransition() { - for (var i = 0; i < pose.length; i++){ - var startRotation = Quat.safeEulerAngles(MyAvatar.getJointRotation(pose[i].joint)); - var transitionVector = Vec3.subtract( pose[i].rotation, startRotation ); - startPoseAndTransition.push({joint: pose[i].joint, start: startRotation, transition: transitionVector}); - } - } - - function updateJoints(factor){ - for (var i = 0; i < startPoseAndTransition.length; i++){ - var scaledTransition = Vec3.multiply(startPoseAndTransition[i].transition, factor); - var rotation = Vec3.sum(startPoseAndTransition[i].start, scaledTransition); - MyAvatar.setJointData(startPoseAndTransition[i].joint, Quat.fromVec3Degrees( rotation )); - } - } - - var sittingDownAnimation = function(deltaTime) { - - passedTime += deltaTime; - var factor = passedTime/animationLength; - - if ( passedTime <= animationLength ) { - updateJoints(factor); - - var pos = { x: startPosition.x - 0.3 * factor, y: startPosition.y - 0.5 * factor, z: startPosition.z}; - MyAvatar.position = pos; - } else { - Script.update.disconnect(sittingDownAnimation); - if (seat.model) { - MyAvatar.setModelReferential(seat.model.id); - } - } - } - - var standingUpAnimation = function(deltaTime) { - - passedTime += deltaTime; - var factor = 1 - passedTime/animationLength; - - if ( passedTime <= animationLength ) { - - updateJoints(factor); - - var pos = { x: startPosition.x + 0.3 * (passedTime/animationLength), y: startPosition.y + 0.5 * (passedTime/animationLength), z: startPosition.z}; - MyAvatar.position = pos; - } else { - Script.update.disconnect(standingUpAnimation); - - } - } - - var externalThis = this; - - var goToSeatAnimation = function(deltaTime) { - passedTime += deltaTime; - var factor = passedTime/animationLength; - - if (passedTime <= animationLength) { - var targetPosition = Vec3.sum(seat.position, { x: 0.3, y: 0.5, z: 0 }); - MyAvatar.position = Vec3.sum(Vec3.multiply(startPosition, 1 - factor), Vec3.multiply(targetPosition, factor)); - } else if (passedTime <= 2 * animationLength) { - //Quat.print("MyAvatar: ", MyAvatar.orientation); - //Quat.print("Seat: ", seat.rotation); - MyAvatar.orientation = Quat.mix(startRotation, seat.rotation, factor - 1); - } else { - Script.update.disconnect(goToSeatAnimation); - externalThis.sitDown(); - externalThis.showIndicators(false); - } - } - - var globalMouseClick = function(event) { - var clickedOverlay = Overlays.getOverlayAtPoint({x: event.x, y: event.y}); - if (clickedOverlay == externalThis.standUpButton) { - seat.model = null; - externalThis.standUp(); - Controller.mousePressEvent.disconnect(globalMouseClick); - } - }; - - this.sitDown = function() { - sitting = true; - Settings.setValue(sittingSettingsHandle, sitting); - print("sitDown sitting status: " + Settings.getValue(sittingSettingsHandle, false)); - passedTime = 0.0; - startPosition = MyAvatar.position; - storeStartPoseAndTransition(); - try { - Script.update.disconnect(standingUpAnimation); - } catch(e){ - // no need to handle. if it wasn't connected no harm done - } - Script.update.connect(sittingDownAnimation); - Overlays.editOverlay(this.standUpButton, { visible: true }); - Controller.mousePressEvent.connect(globalMouseClick); - } - - this.standUp = function() { - sitting = false; - Settings.setValue(sittingSettingsHandle, sitting); - print("standUp sitting status: " + Settings.getValue(sittingSettingsHandle, false)); - passedTime = 0.0; - startPosition = MyAvatar.position; - MyAvatar.clearReferential(); - try{ - Script.update.disconnect(sittingDownAnimation); - } catch (e){} - Script.update.connect(standingUpAnimation); - Overlays.editOverlay(this.standUpButton, { visible: false }); - Controller.mousePressEvent.disconnect(globalMouseClick); - } - - this.addIndicators = function() { - if (!this.indicatorsAdded) { - if (this.properties.sittingPoints.length > 0) { - for (var i = 0; i < this.properties.sittingPoints.length; ++i) { - this.indicator[i] = new SeatIndicator(this.properties, i); - } - this.indicatorsAdded = true; - } - } - } - - this.removeIndicators = function() { - for (var i = 0; i < this.properties.sittingPoints.length; ++i) { - this.indicator[i].cleanup(); - } - } - - this.showIndicators = function(doShow) { - this.addIndicators(); - if (this.indicatorsAdded) { - for (var i = 0; i < this.properties.sittingPoints.length; ++i) { - this.indicator[i].show(doShow); - } - } - hiddingSeats = !doShow; - } - - function raySphereIntersection(origin, direction, center, radius) { - var A = origin; - var B = Vec3.normalize(direction); - var P = center; - - var x = Vec3.dot(Vec3.subtract(P, A), B); - var X = Vec3.sum(A, Vec3.multiply(B, x)); - var d = Vec3.length(Vec3.subtract(P, X)); - - return (x > 0 && d <= radius); - } - - this.cleanup = function() { - this.standUp(); - MyAvatar.clearReferential(); - for (var i = 0; i < pose.length; i++){ - MyAvatar.clearJointData(pose[i].joint); - } - Overlays.deleteOverlay(this.standUpButton); - for (var i = 0; i < this.indicator.length; ++i) { - this.indicator[i].cleanup(); - } - }; - - - this.createStandupButton = function() { - this.standUpButton = Overlays.addOverlay("image", { - x: buttonPositionX, y: buttonPositionY, width: buttonWidth, height: buttonHeight, - subImage: { x: buttonWidth, y: buttonHeight, width: buttonWidth, height: buttonHeight}, - imageURL: buttonImageUrl, - visible: false, - alpha: 1.0 - }); - }; - - this.handleClickEvent = function(event) { - var clickedOverlay = Overlays.getOverlayAtPoint({x: event.x, y: event.y}); - - if (clickedOverlay == this.standUpButton) { - seat.model = null; - this.standUp(); - } else { - this.addIndicators(); - if (this.indicatorsAdded) { - var pickRay = Camera.computePickRay(event.x, event.y); - - var clickedOnSeat = false; - - for (var i = 0; i < this.properties.sittingPoints.length; ++i) { - if (raySphereIntersection(pickRay.origin, - pickRay.direction, - this.indicator[i].position, - this.indicator[i].scale / 2)) { - clickedOnSeat = true; - seat.model = this.entityID; // ?? - seat.position = this.indicator[i].position; - seat.rotation = this.indicator[i].orientation; - } - } - - if (clickedOnSeat) { - passedTime = 0.0; - startPosition = MyAvatar.position; - startRotation = MyAvatar.orientation; - try{ Script.update.disconnect(standingUpAnimation); } catch(e){} - try{ Script.update.disconnect(sittingDownAnimation); } catch(e){} - Script.update.connect(goToSeatAnimation); - } - } - } - }; - - - // All callbacks start by updating the properties - this.updateProperties = function(entityID) { - if (this.entityID === null || !this.entityID.isKnownID) { - this.entityID = Entities.identifyEntity(entityID); - } - this.properties = Entities.getEntityProperties(this.entityID); - }; -}; - -Sittable.prototype = { - - unload : function(entityID) { - print("Sittable.unload()"); - this.cleanup(); - //Script.update.disconnect(SittableUpdate); - }, - - preload : function(entityID) { - print("Sittable.preload()"); - this.updateProperties(entityID); // All callbacks start by updating the properties - this.createStandupButton(); - //Script.update.connect(SittableUpdate); - }, - - - hoverOverEntity : function(entityID, mouseEvent) { - print("Sittable.hoverOverEntity()"); - this.updateProperties(entityID); // All callbacks start by updating the properties - this.showIndicators(true); - }, - - hoverLeaveEntity : function(entityID, mouseEvent) { - print("Sittable.hoverLeaveEntity()"); - this.updateProperties(entityID); // All callbacks start by updating the properties - this.showIndicators(false); - }, - - clickDownOnEntity : function(entityID, mouseEvent) { - print("Sittable.clickDownOnEntity()"); - this.updateProperties(entityID); // All callbacks start by updating the properties - this.handleClickEvent(mouseEvent); - }, - - clickReleaseOnEntity : function(entityID, mouseEvent) { - print("Sittable.clickReleaseOnEntity()"); - this.updateProperties(entityID); // All callbacks start by updating the properties - } -}; \ No newline at end of file From 97d617bd174767a9aeb12eee0f900a5665662338 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Fri, 19 Dec 2014 11:01:35 -0800 Subject: [PATCH 216/258] revert some prototype script stuff for now --- examples/entityScripts/movable.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/entityScripts/movable.js b/examples/entityScripts/movable.js index 35d11116eb..21e6261179 100644 --- a/examples/entityScripts/movable.js +++ b/examples/entityScripts/movable.js @@ -416,4 +416,4 @@ this.stopSound(); }; -}) \ No newline at end of file +}) From e4ce7d11dc8b744dec8ec1c04cb0ee87a21ee055 Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Fri, 19 Dec 2014 11:32:52 -0800 Subject: [PATCH 217/258] Fix default scripts url to use s3.amazonaws.com --- interface/src/Application.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index a7b91db315..aae01681e0 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -130,7 +130,7 @@ static QTimer* idleTimer = NULL; const QString CHECK_VERSION_URL = "https://highfidelity.io/latestVersion.xml"; const QString SKIP_FILENAME = QStandardPaths::writableLocation(QStandardPaths::DataLocation) + "/hifi.skipversion"; -const QString DEFAULT_SCRIPTS_JS_URL = "http://public.highfidelity.io/scripts/defaultScripts.js"; +const QString DEFAULT_SCRIPTS_JS_URL = "http://s3.amazonaws.com/hifi-public/scripts/defaultScripts.js"; void messageHandler(QtMsgType type, const QMessageLogContext& context, const QString& message) { QString logMessage = LogHandler::getInstance().printMessage((LogMsgType) type, context, message); From 32ea38b93805d1abd260b1d33f5739dd587661a8 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Fri, 19 Dec 2014 11:33:25 -0800 Subject: [PATCH 218/258] added leaveAllEntities support --- .../entityScripts/playSoundOnEnterOrLeave.js | 2 ++ .../src/EntityTreeRenderer.cpp | 25 +++++++++++++++++-- .../src/EntityTreeRenderer.h | 1 + 3 files changed, 26 insertions(+), 2 deletions(-) diff --git a/examples/entityScripts/playSoundOnEnterOrLeave.js b/examples/entityScripts/playSoundOnEnterOrLeave.js index f82c05c580..b95e35ab1d 100644 --- a/examples/entityScripts/playSoundOnEnterOrLeave.js +++ b/examples/entityScripts/playSoundOnEnterOrLeave.js @@ -27,10 +27,12 @@ }; this.enterEntity = function(entityID) { + print("enterEntity("+entityID.id+")"); playSound(); }; this.leaveEntity = function(entityID) { + print("leaveEntity("+entityID.id+")"); playSound(); }; }) diff --git a/libraries/entities-renderer/src/EntityTreeRenderer.cpp b/libraries/entities-renderer/src/EntityTreeRenderer.cpp index e8530d5639..9f1185cfb9 100644 --- a/libraries/entities-renderer/src/EntityTreeRenderer.cpp +++ b/libraries/entities-renderer/src/EntityTreeRenderer.cpp @@ -62,6 +62,7 @@ EntityTreeRenderer::~EntityTreeRenderer() { } void EntityTreeRenderer::clear() { + leaveAllEntities(); foreach (const EntityItemID& entityID, _entityScripts.keys()) { checkAndCallUnload(entityID); } @@ -82,8 +83,7 @@ void EntityTreeRenderer::init() { // make sure our "last avatar position" is something other than our current position, so that on our // first chance, we'll check for enter/leave entity events. - glm::vec3 avatarPosition = _viewState->getAvatarPosition(); - _lastAvatarPosition = avatarPosition + glm::vec3(1.0f, 1.0f, 1.0f); + _lastAvatarPosition = _viewState->getAvatarPosition() + glm::vec3(1.0f, 1.0f, 1.0f); connect(entityTree, &EntityTree::deletingEntity, this, &EntityTreeRenderer::deletingEntity); connect(entityTree, &EntityTree::addingEntity, this, &EntityTreeRenderer::checkAndCallPreload); @@ -297,6 +297,27 @@ void EntityTreeRenderer::checkEnterLeaveEntities() { } } +void EntityTreeRenderer::leaveAllEntities() { + if (_tree) { + _tree->lockForWrite(); // so that our scripts can do edits if they want + + // for all of our previous containing entities, if they are no longer containing then send them a leave event + foreach(const EntityItemID& entityID, _currentEntitiesInside) { + emit leaveEntity(entityID); + QScriptValueList entityArgs = createEntityArgs(entityID); + QScriptValue entityScript = loadEntityScript(entityID); + if (entityScript.property("leaveEntity").isValid()) { + entityScript.property("leaveEntity").call(entityScript, entityArgs); + } + } + _currentEntitiesInside.clear(); + + // make sure our "last avatar position" is something other than our current position, so that on our + // first chance, we'll check for enter/leave entity events. + _lastAvatarPosition = _viewState->getAvatarPosition() + glm::vec3(1.0f, 1.0f, 1.0f); + _tree->unlock(); + } +} void EntityTreeRenderer::render(RenderArgs::RenderMode renderMode, RenderArgs::RenderSide renderSide) { if (_tree) { Model::startScene(renderSide); diff --git a/libraries/entities-renderer/src/EntityTreeRenderer.h b/libraries/entities-renderer/src/EntityTreeRenderer.h index 46c333d70d..92cc2c4dcc 100644 --- a/libraries/entities-renderer/src/EntityTreeRenderer.h +++ b/libraries/entities-renderer/src/EntityTreeRenderer.h @@ -129,6 +129,7 @@ private: QScriptValueList createEntityArgs(const EntityItemID& entityID); void checkEnterLeaveEntities(); + void leaveAllEntities(); glm::vec3 _lastAvatarPosition; QVector _currentEntitiesInside; From d585f8c7073a55915c3de4a76e89c769b18f42d7 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Fri, 19 Dec 2014 12:10:40 -0800 Subject: [PATCH 219/258] replace gluOrtho2D() with glOrtho() --- interface/src/devices/OculusManager.cpp | 2 +- interface/src/ui/ApplicationOverlay.cpp | 4 ++-- interface/src/ui/RearMirrorTools.cpp | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/interface/src/devices/OculusManager.cpp b/interface/src/devices/OculusManager.cpp index 1854c9539d..76a54eb9d8 100644 --- a/interface/src/devices/OculusManager.cpp +++ b/interface/src/devices/OculusManager.cpp @@ -582,7 +582,7 @@ void OculusManager::renderDistortionMesh(ovrPosef eyeRenderPose[ovrEye_Count]) { glLoadIdentity(); GLCanvas::SharedPointer glCanvas = DependencyManager::get(); - gluOrtho2D(0, glCanvas->getDeviceWidth(), 0, glCanvas->getDeviceHeight()); + glOrtho(0, glCanvas->getDeviceWidth(), 0, glCanvas->getDeviceHeight(), -1.0f, 1.0f); glDisable(GL_DEPTH_TEST); diff --git a/interface/src/ui/ApplicationOverlay.cpp b/interface/src/ui/ApplicationOverlay.cpp index ab85da125c..0350726d9c 100644 --- a/interface/src/ui/ApplicationOverlay.cpp +++ b/interface/src/ui/ApplicationOverlay.cpp @@ -180,7 +180,7 @@ void ApplicationOverlay::renderOverlay(bool renderToTexture) { glPushMatrix(); { glLoadIdentity(); - gluOrtho2D(0, glCanvas->width(), glCanvas->height(), 0); + glOrtho(0, glCanvas->width(), glCanvas->height(), 0, -1.0f, 1.0f); renderAudioMeter(); @@ -224,7 +224,7 @@ void ApplicationOverlay::displayOverlayTexture() { glMatrixMode(GL_PROJECTION); glPushMatrix(); { glLoadIdentity(); - gluOrtho2D(0, glCanvas->getDeviceWidth(), glCanvas->getDeviceHeight(), 0); + glOrtho(0, glCanvas->getDeviceWidth(), glCanvas->getDeviceHeight(), 0, -1.0f, 1.0f); glDisable(GL_DEPTH_TEST); glDisable(GL_LIGHTING); glEnable(GL_BLEND); diff --git a/interface/src/ui/RearMirrorTools.cpp b/interface/src/ui/RearMirrorTools.cpp index fd3fc34adb..2287324656 100644 --- a/interface/src/ui/RearMirrorTools.cpp +++ b/interface/src/ui/RearMirrorTools.cpp @@ -128,7 +128,7 @@ void RearMirrorTools::displayIcon(QRect bounds, QRect iconBounds, GLuint texture glPushMatrix(); glLoadIdentity(); - gluOrtho2D(bounds.left(), bounds.right(), bounds.bottom(), bounds.top()); + glOrtho(bounds.left(), bounds.right(), bounds.bottom(), bounds.top(), -1.0f, 1.0f); glDisable(GL_DEPTH_TEST); glDisable(GL_LIGHTING); glEnable(GL_TEXTURE_2D); From 979f5f8fc50784bb17dc1208e33f58a3f02ab844 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 19 Dec 2014 12:19:49 -0800 Subject: [PATCH 220/258] fix for coding standard compliance --- libraries/networking/src/AddressManager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/networking/src/AddressManager.cpp b/libraries/networking/src/AddressManager.cpp index 57412b645f..f9789ff97e 100644 --- a/libraries/networking/src/AddressManager.cpp +++ b/libraries/networking/src/AddressManager.cpp @@ -350,7 +350,7 @@ bool AddressManager::handleUsername(const QString& lookupString) { } -void AddressManager::setDomainInfo(const QString &hostname, quint16 port, const QString& domainName) { +void AddressManager::setDomainInfo(const QString& hostname, quint16 port, const QString& domainName) { _currentDomain = domainName.isEmpty() ? hostname : domainName; emit possibleDomainChangeRequired(hostname, port); } From 66b1886b440e810f7400ec186ca7ef4044d3b934 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 19 Dec 2014 12:33:26 -0800 Subject: [PATCH 221/258] don't add the unused assignment type to DS queue --- domain-server/src/DomainServer.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/domain-server/src/DomainServer.cpp b/domain-server/src/DomainServer.cpp index 73092b694b..cea5bec3ef 100644 --- a/domain-server/src/DomainServer.cpp +++ b/domain-server/src/DomainServer.cpp @@ -549,7 +549,9 @@ void DomainServer::populateDefaultStaticAssignmentsExcludingTypes(const QSet(static_cast(defaultedType) + 1)) { - if (!excludedTypes.contains(defaultedType) && defaultedType != Assignment::AgentType) { + if (!excludedTypes.contains(defaultedType) + && defaultedType != Assignment::UNUSED + && defaultedType != Assignment::AgentType) { // type has not been set from a command line or config file config, use the default // by clearing whatever exists and writing a single default assignment with no payload Assignment* newAssignment = new Assignment(Assignment::CreateCommand, (Assignment::Type) defaultedType); From 046564ec470dc7587ecd680e904eaf9fc40cca0b Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Fri, 19 Dec 2014 12:35:47 -0800 Subject: [PATCH 222/258] oops double --- interface/src/devices/OculusManager.cpp | 2 +- interface/src/ui/ApplicationOverlay.cpp | 4 ++-- interface/src/ui/RearMirrorTools.cpp | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/interface/src/devices/OculusManager.cpp b/interface/src/devices/OculusManager.cpp index 76a54eb9d8..f59ce639a0 100644 --- a/interface/src/devices/OculusManager.cpp +++ b/interface/src/devices/OculusManager.cpp @@ -582,7 +582,7 @@ void OculusManager::renderDistortionMesh(ovrPosef eyeRenderPose[ovrEye_Count]) { glLoadIdentity(); GLCanvas::SharedPointer glCanvas = DependencyManager::get(); - glOrtho(0, glCanvas->getDeviceWidth(), 0, glCanvas->getDeviceHeight(), -1.0f, 1.0f); + glOrtho(0, glCanvas->getDeviceWidth(), 0, glCanvas->getDeviceHeight(), -1.0, 1.0); glDisable(GL_DEPTH_TEST); diff --git a/interface/src/ui/ApplicationOverlay.cpp b/interface/src/ui/ApplicationOverlay.cpp index 0350726d9c..b2ed9fc77d 100644 --- a/interface/src/ui/ApplicationOverlay.cpp +++ b/interface/src/ui/ApplicationOverlay.cpp @@ -180,7 +180,7 @@ void ApplicationOverlay::renderOverlay(bool renderToTexture) { glPushMatrix(); { glLoadIdentity(); - glOrtho(0, glCanvas->width(), glCanvas->height(), 0, -1.0f, 1.0f); + glOrtho(0, glCanvas->width(), glCanvas->height(), 0, -1.0, 1.0); renderAudioMeter(); @@ -224,7 +224,7 @@ void ApplicationOverlay::displayOverlayTexture() { glMatrixMode(GL_PROJECTION); glPushMatrix(); { glLoadIdentity(); - glOrtho(0, glCanvas->getDeviceWidth(), glCanvas->getDeviceHeight(), 0, -1.0f, 1.0f); + glOrtho(0, glCanvas->getDeviceWidth(), glCanvas->getDeviceHeight(), 0, -1.0, 1.0); glDisable(GL_DEPTH_TEST); glDisable(GL_LIGHTING); glEnable(GL_BLEND); diff --git a/interface/src/ui/RearMirrorTools.cpp b/interface/src/ui/RearMirrorTools.cpp index 2287324656..37f7c6ae23 100644 --- a/interface/src/ui/RearMirrorTools.cpp +++ b/interface/src/ui/RearMirrorTools.cpp @@ -128,7 +128,7 @@ void RearMirrorTools::displayIcon(QRect bounds, QRect iconBounds, GLuint texture glPushMatrix(); glLoadIdentity(); - glOrtho(bounds.left(), bounds.right(), bounds.bottom(), bounds.top(), -1.0f, 1.0f); + glOrtho(bounds.left(), bounds.right(), bounds.bottom(), bounds.top(), -1.0, 1.0); glDisable(GL_DEPTH_TEST); glDisable(GL_LIGHTING); glEnable(GL_TEXTURE_2D); From 096b09e8e17d11ffca76611131d24196f8d8dd82 Mon Sep 17 00:00:00 2001 From: Sam Gateau Date: Fri, 19 Dec 2014 12:44:46 -0800 Subject: [PATCH 223/258] Importing fixes from Model branch to the gpu library --- libraries/gpu/src/gpu/Batch.cpp | 36 +++- libraries/gpu/src/gpu/Batch.h | 10 +- libraries/gpu/src/gpu/Context.h | 1 - libraries/gpu/src/gpu/Format.h | 9 +- libraries/gpu/src/gpu/GLBackend.cpp | 50 ++++- libraries/gpu/src/gpu/GLBackend.h | 14 ++ libraries/gpu/src/gpu/Resource.cpp | 40 +++- libraries/gpu/src/gpu/Resource.h | 295 +++++++++++++++++++++++++++- libraries/gpu/src/gpu/Stream.cpp | 4 +- libraries/gpu/src/gpu/Stream.h | 10 +- 10 files changed, 433 insertions(+), 36 deletions(-) diff --git a/libraries/gpu/src/gpu/Batch.cpp b/libraries/gpu/src/gpu/Batch.cpp index 30e591cc60..5604fa21c7 100644 --- a/libraries/gpu/src/gpu/Batch.cpp +++ b/libraries/gpu/src/gpu/Batch.cpp @@ -107,6 +107,19 @@ void Batch::setInputFormat(const Stream::FormatPointer& format) { _params.push_back(_streamFormats.cache(format)); } +void Batch::setInputBuffer(Slot channel, const BufferPointer& buffer, Offset offset, Offset stride) { + ADD_COMMAND(setInputBuffer); + + _params.push_back(stride); + _params.push_back(offset); + _params.push_back(_buffers.cache(buffer)); + _params.push_back(channel); +} + +void Batch::setInputBuffer(Slot channel, const BufferView& view) { + setInputBuffer(channel, view._buffer, view._offset, Offset(view._stride)); +} + void Batch::setInputStream(Slot startChannel, const BufferStream& stream) { if (stream.getNumBuffers()) { const Buffers& buffers = stream.getBuffers(); @@ -118,15 +131,6 @@ void Batch::setInputStream(Slot startChannel, const BufferStream& stream) { } } -void Batch::setInputBuffer(Slot channel, const BufferPointer& buffer, Offset offset, Offset stride) { - ADD_COMMAND(setInputBuffer); - - _params.push_back(stride); - _params.push_back(offset); - _params.push_back(_buffers.cache(buffer)); - _params.push_back(channel); -} - void Batch::setIndexBuffer(Type type, const BufferPointer& buffer, Offset offset) { ADD_COMMAND(setIndexBuffer); @@ -153,3 +157,17 @@ void Batch::setProjectionTransform(const Transform& proj) { _params.push_back(_transforms.cache(proj)); } +void Batch::setUniformBuffer(uint32 slot, const BufferPointer& buffer, Offset offset, Offset size) { + ADD_COMMAND(setUniformBuffer); + + _params.push_back(size); + _params.push_back(offset); + _params.push_back(_buffers.cache(buffer)); + _params.push_back(slot); +} + +void Batch::setUniformBuffer(uint32 slot, const BufferView& view) { + setUniformBuffer(slot, view._buffer, view._offset, view._size); +} + + diff --git a/libraries/gpu/src/gpu/Batch.h b/libraries/gpu/src/gpu/Batch.h index 601ae63a77..c3a87c8f19 100644 --- a/libraries/gpu/src/gpu/Batch.h +++ b/libraries/gpu/src/gpu/Batch.h @@ -72,8 +72,9 @@ public: // IndexBuffer void setInputFormat(const Stream::FormatPointer& format); - void setInputStream(Slot startChannel, const BufferStream& stream); // not a command, just unroll into a loop of setInputBuffer void setInputBuffer(Slot channel, const BufferPointer& buffer, Offset offset, Offset stride); + void setInputBuffer(Slot channel, const BufferView& buffer); // not a command, just a shortcut from a BufferView + void setInputStream(Slot startChannel, const BufferStream& stream); // not a command, just unroll into a loop of setInputBuffer void setIndexBuffer(Type type, const BufferPointer& buffer, Offset offset); @@ -87,6 +88,9 @@ public: void setViewTransform(const Transform& view); void setProjectionTransform(const Transform& proj); + // Shader Stage + void setUniformBuffer(uint32 slot, const BufferPointer& buffer, Offset offset, Offset size); + void setUniformBuffer(uint32 slot, const BufferView& view); // not a command, just a shortcut from a BufferView // TODO: As long as we have gl calls explicitely issued from interface // code, we need to be able to record and batch these calls. THe long @@ -117,6 +121,7 @@ public: void _glUseProgram(GLuint program); void _glUniform1f(GLint location, GLfloat v0); void _glUniform2f(GLint location, GLfloat v0, GLfloat v1); + void _glUniform4fv(GLint location, GLsizei count, const GLfloat* value); void _glUniformMatrix4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value); void _glMatrixMode(GLenum mode); @@ -161,6 +166,8 @@ public: COMMAND_setViewTransform, COMMAND_setProjectionTransform, + COMMAND_setUniformBuffer, + // TODO: As long as we have gl calls explicitely issued from interface // code, we need to be able to record and batch these calls. THe long // term strategy is to get rid of any GL calls in favor of the HIFI GPU API @@ -187,6 +194,7 @@ public: COMMAND_glUseProgram, COMMAND_glUniform1f, COMMAND_glUniform2f, + COMMAND_glUniform4fv, COMMAND_glUniformMatrix4fv, COMMAND_glMatrixMode, diff --git a/libraries/gpu/src/gpu/Context.h b/libraries/gpu/src/gpu/Context.h index 3a0fffb4ef..6839f9480a 100644 --- a/libraries/gpu/src/gpu/Context.h +++ b/libraries/gpu/src/gpu/Context.h @@ -12,7 +12,6 @@ #define hifi_gpu_Context_h #include -#include "GPUConfig.h" #include "Resource.h" diff --git a/libraries/gpu/src/gpu/Format.h b/libraries/gpu/src/gpu/Format.h index d216495b4c..aeeece8a62 100644 --- a/libraries/gpu/src/gpu/Format.h +++ b/libraries/gpu/src/gpu/Format.h @@ -12,8 +12,6 @@ #define hifi_gpu_Format_h #include -#include "GPUConfig.h" - namespace gpu { @@ -94,7 +92,8 @@ static const int DIMENSION_COUNT[NUM_DIMENSIONS] = { // Semantic of an Element // Provide information on how to use the element enum Semantic { - RGB = 0, + RAW = 0, // used as RAW memory + RGB, RGBA, XYZ, XYZW, @@ -104,6 +103,8 @@ enum Semantic { DIR_XYZ, UV, R8, + INDEX, //used by index buffer of a mesh + PART, // used by part buffer of a mesh NUM_SEMANTICS, }; @@ -119,7 +120,7 @@ public: _type(type) {} Element() : - _semantic(R8), + _semantic(RAW), _dimension(SCALAR), _type(INT8) {} diff --git a/libraries/gpu/src/gpu/GLBackend.cpp b/libraries/gpu/src/gpu/GLBackend.cpp index 90639929ca..436045e8a3 100644 --- a/libraries/gpu/src/gpu/GLBackend.cpp +++ b/libraries/gpu/src/gpu/GLBackend.cpp @@ -31,6 +31,8 @@ GLBackend::CommandCall GLBackend::_commandCalls[Batch::NUM_COMMANDS] = (&::gpu::GLBackend::do_setViewTransform), (&::gpu::GLBackend::do_setProjectionTransform), + (&::gpu::GLBackend::do_setUniformBuffer), + (&::gpu::GLBackend::do_glEnable), (&::gpu::GLBackend::do_glDisable), @@ -54,6 +56,7 @@ GLBackend::CommandCall GLBackend::_commandCalls[Batch::NUM_COMMANDS] = (&::gpu::GLBackend::do_glUseProgram), (&::gpu::GLBackend::do_glUniform1f), (&::gpu::GLBackend::do_glUniform2f), + (&::gpu::GLBackend::do_glUniform4fv), (&::gpu::GLBackend::do_glUniformMatrix4fv), (&::gpu::GLBackend::do_glMatrixMode), @@ -171,8 +174,8 @@ void GLBackend::checkGLError() { } } -//#define CHECK_GL_ERROR() ::gpu::GLBackend::checkGLError() -#define CHECK_GL_ERROR() +#define CHECK_GL_ERROR() ::gpu::GLBackend::checkGLError() +//#define CHECK_GL_ERROR() void GLBackend::do_draw(Batch& batch, uint32 paramOffset) { updateInput(); @@ -483,6 +486,25 @@ void GLBackend::updateTransform() { } } +void GLBackend::do_setUniformBuffer(Batch& batch, uint32 paramOffset) { + GLuint slot = batch._params[paramOffset + 3]._uint; + BufferPointer uniformBuffer = batch._buffers.get(batch._params[paramOffset + 2]._uint); + GLintptr rangeStart = batch._params[paramOffset + 1]._uint; + GLsizeiptr rangeSize = batch._params[paramOffset + 0]._uint; +#if defined(Q_OS_MAC) + GLfloat* data = (GLfloat*) (uniformBuffer->getData() + rangeStart); + glUniform4fv(slot, rangeSize / sizeof(GLfloat[4]), data); +#else + GLuint bo = getBufferID(*uniformBuffer); + glBindBufferRange(GL_UNIFORM_BUFFER, slot, bo, rangeStart, rangeSize); + + // glUniformBufferEXT(_shader._program, slot, bo); + + //glBindBufferBase(GL_UNIFORM_BUFFER, slot, bo); +#endif + CHECK_GL_ERROR(); +} + // TODO: As long as we have gl calls explicitely issued from interface // code, we need to be able to record and batch these calls. THe long // term strategy is to get rid of any GL calls in favor of the HIFI GPU API @@ -672,7 +694,10 @@ void Batch::_glUseProgram(GLuint program) { DO_IT_NOW(_glUseProgram, 1); } void GLBackend::do_glUseProgram(Batch& batch, uint32 paramOffset) { - glUseProgram(batch._params[paramOffset]._uint); + + _shader._program = batch._params[paramOffset]._uint; + glUseProgram(_shader._program); + CHECK_GL_ERROR(); } @@ -708,6 +733,25 @@ void GLBackend::do_glUniform2f(Batch& batch, uint32 paramOffset) { CHECK_GL_ERROR(); } +void Batch::_glUniform4fv(GLint location, GLsizei count, const GLfloat* value) { + ADD_COMMAND_GL(glUniform4fv); + + const int VEC4_SIZE = 4 * sizeof(float); + _params.push_back(cacheData(count * VEC4_SIZE, value)); + _params.push_back(count); + _params.push_back(location); + + DO_IT_NOW(_glUniform4fv, 3); +} +void GLBackend::do_glUniform4fv(Batch& batch, uint32 paramOffset) { + glUniform4fv( + batch._params[paramOffset + 2]._int, + batch._params[paramOffset + 1]._uint, + (const GLfloat*)batch.editData(batch._params[paramOffset + 0]._uint)); + + CHECK_GL_ERROR(); +} + void Batch::_glUniformMatrix4fv(GLint location, GLsizei count, GLboolean transpose, const GLfloat* value) { ADD_COMMAND_GL(glUniformMatrix4fv); diff --git a/libraries/gpu/src/gpu/GLBackend.h b/libraries/gpu/src/gpu/GLBackend.h index 5a40e9ca36..be7a0a594b 100644 --- a/libraries/gpu/src/gpu/GLBackend.h +++ b/libraries/gpu/src/gpu/GLBackend.h @@ -122,6 +122,19 @@ protected: _lastMode(GL_TEXTURE) {} } _transform; + // Shader Stage + void do_setUniformBuffer(Batch& batch, uint32 paramOffset); + + void updateShader(); + struct ShaderStageState { + + GLuint _program; + + ShaderStageState() : + _program(0) {} + } _shader; + + // TODO: As long as we have gl calls explicitely issued from interface // code, we need to be able to record and batch these calls. THe long // term strategy is to get rid of any GL calls in favor of the HIFI GPU API @@ -148,6 +161,7 @@ protected: void do_glUseProgram(Batch& batch, uint32 paramOffset); void do_glUniform1f(Batch& batch, uint32 paramOffset); void do_glUniform2f(Batch& batch, uint32 paramOffset); + void do_glUniform4fv(Batch& batch, uint32 paramOffset); void do_glUniformMatrix4fv(Batch& batch, uint32 paramOffset); void do_glMatrixMode(Batch& batch, uint32 paramOffset); diff --git a/libraries/gpu/src/gpu/Resource.cpp b/libraries/gpu/src/gpu/Resource.cpp index 3a6e47a7ba..085d97184b 100644 --- a/libraries/gpu/src/gpu/Resource.cpp +++ b/libraries/gpu/src/gpu/Resource.cpp @@ -67,6 +67,26 @@ Resource::Sysmem::Sysmem(Size size, const Byte* bytes) : } } +Resource::Sysmem::Sysmem(const Sysmem& sysmem) : + _stamp(0), + _size(0), + _data(NULL) +{ + if (sysmem.getSize() > 0) { + _size = allocateMemory(&_data, sysmem.getSize()); + if (_size >= sysmem.getSize()) { + if (sysmem.readData()) { + memcpy(_data, sysmem.readData(), sysmem.getSize()); + } + } + } +} + +Resource::Sysmem& Resource::Sysmem::operator=(const Sysmem& sysmem) { + setData(sysmem.getSize(), sysmem.readData()); + return (*this); +} + Resource::Sysmem::~Sysmem() { deallocateMemory( _data, _size ); _data = NULL; @@ -152,9 +172,25 @@ Resource::Size Resource::Sysmem::append(Size size, const Byte* bytes) { Buffer::Buffer() : Resource(), - _sysmem(NULL), + _sysmem(new Sysmem()), _gpuObject(NULL) { - _sysmem = new Sysmem(); +} + +Buffer::Buffer(Size size, const Byte* bytes) : + Resource(), + _sysmem(new Sysmem(size, bytes)), + _gpuObject(NULL) { +} + +Buffer::Buffer(const Buffer& buf) : + Resource(), + _sysmem(new Sysmem(buf.getSysmem())), + _gpuObject(NULL) { +} + +Buffer& Buffer::operator=(const Buffer& buf) { + (*_sysmem) = buf.getSysmem(); + return (*this); } Buffer::~Buffer() { diff --git a/libraries/gpu/src/gpu/Resource.h b/libraries/gpu/src/gpu/Resource.h index 6247efe675..ec528c230b 100644 --- a/libraries/gpu/src/gpu/Resource.h +++ b/libraries/gpu/src/gpu/Resource.h @@ -12,13 +12,15 @@ #define hifi_gpu_Resource_h #include -#include "GPUConfig.h" #include "Format.h" #include #include +#ifdef _DEBUG +#include +#endif namespace gpu { @@ -29,7 +31,7 @@ typedef int Stamp; class Resource { public: typedef unsigned char Byte; - typedef unsigned int Size; + typedef unsigned int Size; static const Size NOT_ALLOCATED = -1; @@ -47,6 +49,8 @@ protected: Sysmem(); Sysmem(Size size, const Byte* bytes); + Sysmem(const Sysmem& sysmem); // deep copy of the sysmem buffer + Sysmem& operator=(const Sysmem& sysmem); // deep copy of the sysmem buffer ~Sysmem(); Size getSize() const { return _size; } @@ -90,9 +94,6 @@ protected: static void deallocateMemory(Byte* memDeallocated, Size size); private: - Sysmem(const Sysmem& sysmem) {} - Sysmem &operator=(const Sysmem& other) {return *this;} - Stamp _stamp; Size _size; Byte* _data; @@ -104,12 +105,15 @@ class Buffer : public Resource { public: Buffer(); - Buffer(const Buffer& buf); + Buffer(Size size, const Byte* bytes); + Buffer(const Buffer& buf); // deep copy of the sysmem buffer + Buffer& operator=(const Buffer& buf); // deep copy of the sysmem buffer ~Buffer(); // The size in bytes of data stored in the buffer Size getSize() const { return getSysmem().getSize(); } const Byte* getData() const { return getSysmem().readData(); } + Byte* editData() { return editSysmem().editData(); } // Resize the buffer // Keep previous data [0 to min(pSize, mSize)] @@ -130,7 +134,7 @@ public: // Access the sysmem object. const Sysmem& getSysmem() const { assert(_sysmem); return (*_sysmem); } - + Sysmem& editSysmem() { assert(_sysmem); return (*_sysmem); } protected: @@ -138,8 +142,6 @@ protected: mutable GPUObject* _gpuObject; - Sysmem& editSysmem() { assert(_sysmem); return (*_sysmem); } - // This shouldn't be used by anything else than the Backend class with the proper casting. void setGPUObject(GPUObject* gpuObject) const { _gpuObject = gpuObject; } GPUObject* getGPUObject() const { return _gpuObject; } @@ -149,6 +151,281 @@ protected: typedef QSharedPointer BufferPointer; typedef std::vector< BufferPointer > Buffers; + + +class BufferView { +public: + typedef Resource::Size Size; + typedef int Index; + + BufferPointer _buffer; + Size _offset; + Size _size; + Element _element; + uint16 _stride; + + BufferView() : + _buffer(NULL), + _offset(0), + _size(0), + _element(gpu::SCALAR, gpu::UINT8, gpu::RAW), + _stride(1) + {}; + + BufferView(const Element& element) : + _buffer(NULL), + _offset(0), + _size(0), + _element(element), + _stride(uint16(element.getSize())) + {}; + + // create the BufferView and own the Buffer + BufferView(Buffer* newBuffer, const Element& element = Element(gpu::SCALAR, gpu::UINT8, gpu::RAW)) : + _buffer(newBuffer), + _offset(0), + _size(newBuffer->getSize()), + _element(element), + _stride(uint16(element.getSize())) + {}; + BufferView(const BufferPointer& buffer, const Element& element = Element(gpu::SCALAR, gpu::UINT8, gpu::RAW)) : + _buffer(buffer), + _offset(0), + _size(buffer->getSize()), + _element(element), + _stride(uint16(element.getSize())) + {}; + BufferView(const BufferPointer& buffer, Size offset, Size size, const Element& element = Element(gpu::SCALAR, gpu::UINT8, gpu::RAW)) : + _buffer(buffer), + _offset(offset), + _size(size), + _element(element), + _stride(uint16(element.getSize())) + {}; + ~BufferView() {} + BufferView(const BufferView& view) = default; + BufferView& operator=(const BufferView& view) = default; + + Size getNumElements() const { return _size / _element.getSize(); } + + //Template iterator with random access on the buffer sysmem + template + class Iterator : public std::iterator + { + public: + + Iterator(T* ptr = NULL) { _ptr = ptr; } + Iterator(const Iterator& iterator) = default; + ~Iterator() {} + + Iterator& operator=(const Iterator& iterator) = default; + Iterator& operator=(T* ptr) { + _ptr = ptr; + return (*this); + } + + operator bool() const + { + if(_ptr) + return true; + else + return false; + } + + bool operator==(const Iterator& iterator) const { return (_ptr == iterator.getConstPtr()); } + bool operator!=(const Iterator& iterator) const { return (_ptr != iterator.getConstPtr()); } + + Iterator& operator+=(const Index& movement) { + _ptr += movement; + return (*this); + } + Iterator& operator-=(const Index& movement) { + _ptr -= movement; + return (*this); + } + Iterator& operator++() { + ++_ptr; + return (*this); + } + Iterator& operator--() { + --_ptr; + return (*this); + } + Iterator operator++(Index) { + auto temp(*this); + ++_ptr; + return temp; + } + Iterator operator--(Index) { + auto temp(*this); + --_ptr; + return temp; + } + Iterator operator+(const Index& movement) { + auto oldPtr = _ptr; + _ptr += movement; + auto temp(*this); + _ptr = oldPtr; + return temp; + } + Iterator operator-(const Index& movement) { + auto oldPtr = _ptr; + _ptr -= movement; + auto temp(*this); + _ptr = oldPtr; + return temp; + } + + Index operator-(const Iterator& iterator) { return (iterator.getPtr() - this->getPtr())/sizeof(T); } + + T& operator*(){return *_ptr;} + const T& operator*()const{return *_ptr;} + T* operator->(){return _ptr;} + + T* getPtr()const{return _ptr;} + const T* getConstPtr()const{return _ptr;} + + protected: + + T* _ptr; + }; + + template Iterator begin() { return Iterator(&edit(0)); } + template Iterator end() { return Iterator(&edit(getNum())); } + template Iterator cbegin() const { return Iterator(&get(0)); } + template Iterator cend() const { return Iterator(&get(getNum())); } + + // the number of elements of the specified type fitting in the view size + template Index getNum() const { + return Index(_size / sizeof(T)); + } + + template const T& get() const { + #if _DEBUG + if (_buffer.isNull()) { + qDebug() << "Accessing null gpu::buffer!"; + } + if (sizeof(T) > (_buffer->getSize() - _offset)) { + qDebug() << "Accessing buffer in non allocated memory, element size = " << sizeof(T) << " available space in buffer at offset is = " << (_buffer->getSize() - _offset); + } + if (sizeof(T) > _size) { + qDebug() << "Accessing buffer outside the BufferView range, element size = " << sizeof(T) << " when bufferView size = " << _size; + } + #endif + const T* t = (reinterpret_cast (_buffer->getData() + _offset)); + return *(t); + } + + template T& edit() { + #if _DEBUG + if (_buffer.isNull()) { + qDebug() << "Accessing null gpu::buffer!"; + } + if (sizeof(T) > (_buffer->getSize() - _offset)) { + qDebug() << "Accessing buffer in non allocated memory, element size = " << sizeof(T) << " available space in buffer at offset is = " << (_buffer->getSize() - _offset); + } + if (sizeof(T) > _size) { + qDebug() << "Accessing buffer outside the BufferView range, element size = " << sizeof(T) << " when bufferView size = " << _size; + } + #endif + T* t = (reinterpret_cast (_buffer->editData() + _offset)); + return *(t); + } + + template const T& get(const Index index) const { + Resource::Size elementOffset = index * sizeof(T) + _offset; + #if _DEBUG + if (_buffer.isNull()) { + qDebug() << "Accessing null gpu::buffer!"; + } + if (sizeof(T) > (_buffer->getSize() - elementOffset)) { + qDebug() << "Accessing buffer in non allocated memory, index = " << index << ", element size = " << sizeof(T) << " available space in buffer at offset is = " << (_buffer->getSize() - elementOffset); + } + if (index > getNum()) { + qDebug() << "Accessing buffer outside the BufferView range, index = " << index << " number elements = " << getNum(); + } + #endif + return *(reinterpret_cast (_buffer->getData() + elementOffset)); + } + + template T& edit(const Index index) const { + Resource::Size elementOffset = index * sizeof(T) + _offset; + #if _DEBUG + if (_buffer.isNull()) { + qDebug() << "Accessing null gpu::buffer!"; + } + if (sizeof(T) > (_buffer->getSize() - elementOffset)) { + qDebug() << "Accessing buffer in non allocated memory, index = " << index << ", element size = " << sizeof(T) << " available space in buffer at offset is = " << (_buffer->getSize() - elementOffset); + } + if (index > getNum()) { + qDebug() << "Accessing buffer outside the BufferView range, index = " << index << " number elements = " << getNum(); + } + #endif + return *(reinterpret_cast (_buffer->editData() + elementOffset)); + } +}; + + + // TODO: For now TextureView works with Buffer as a place holder for the Texture. + // The overall logic should be about the same except that the Texture will be a real GL Texture under the hood +class TextureView { +public: + typedef Resource::Size Size; + typedef int Index; + + BufferPointer _buffer; + Size _offset; + Size _size; + Element _element; + uint16 _stride; + + TextureView() : + _buffer(NULL), + _offset(0), + _size(0), + _element(gpu::VEC3, gpu::UINT8, gpu::RGB), + _stride(1) + {}; + + TextureView(const Element& element) : + _buffer(NULL), + _offset(0), + _size(0), + _element(element), + _stride(uint16(element.getSize())) + {}; + + // create the BufferView and own the Buffer + TextureView(Buffer* newBuffer, const Element& element) : + _buffer(newBuffer), + _offset(0), + _size(newBuffer->getSize()), + _element(element), + _stride(uint16(element.getSize())) + {}; + TextureView(const BufferPointer& buffer, const Element& element) : + _buffer(buffer), + _offset(0), + _size(buffer->getSize()), + _element(element), + _stride(uint16(element.getSize())) + {}; + TextureView(const BufferPointer& buffer, Size offset, Size size, const Element& element) : + _buffer(buffer), + _offset(offset), + _size(size), + _element(element), + _stride(uint16(element.getSize())) + {}; + ~TextureView() {} + TextureView(const TextureView& view) = default; + TextureView& operator=(const TextureView& view) = default; +}; + }; diff --git a/libraries/gpu/src/gpu/Stream.cpp b/libraries/gpu/src/gpu/Stream.cpp index 099cbde24a..73677f715e 100644 --- a/libraries/gpu/src/gpu/Stream.cpp +++ b/libraries/gpu/src/gpu/Stream.cpp @@ -18,7 +18,7 @@ void Stream::Format::evaluateCache() { _elementTotalSize = 0; for(AttributeMap::iterator it = _attributes.begin(); it != _attributes.end(); it++) { Attribute& attrib = (*it).second; - Channel& channel = _channels[attrib._channel]; + ChannelInfo& channel = _channels[attrib._channel]; channel._slots.push_back(attrib._slot); channel._stride = std::max(channel._stride, attrib.getSize() + attrib._offset); channel._netSize += attrib.getSize(); @@ -41,7 +41,7 @@ BufferStream::BufferStream() : BufferStream::~BufferStream() { } -void BufferStream::addBuffer(BufferPointer& buffer, Offset offset, Offset stride) { +void BufferStream::addBuffer(const BufferPointer& buffer, Offset offset, Offset stride) { _buffers.push_back(buffer); _offsets.push_back(offset); _strides.push_back(stride); diff --git a/libraries/gpu/src/gpu/Stream.h b/libraries/gpu/src/gpu/Stream.h index 93abfeeca3..b1aaec665f 100644 --- a/libraries/gpu/src/gpu/Stream.h +++ b/libraries/gpu/src/gpu/Stream.h @@ -12,7 +12,6 @@ #define hifi_gpu_Stream_h #include -#include "GPUConfig.h" #include "Resource.h" #include "Format.h" @@ -83,16 +82,16 @@ public: public: typedef std::map< Slot, Attribute > AttributeMap; - class Channel { + class ChannelInfo { public: std::vector< Slot > _slots; std::vector< Offset > _offsets; Offset _stride; uint32 _netSize; - Channel() : _stride(0), _netSize(0) {} + ChannelInfo() : _stride(0), _netSize(0) {} }; - typedef std::map< Slot, Channel > ChannelMap; + typedef std::map< Slot, ChannelInfo > ChannelMap; Format() : _attributes(), @@ -104,6 +103,7 @@ public: uint8 getNumChannels() const { return _channels.size(); } const ChannelMap& getChannels() const { return _channels; } + const Offset getChannelStride(Slot channel) const { return _channels.at(channel)._stride; } uint32 getElementTotalSize() const { return _elementTotalSize; } @@ -131,7 +131,7 @@ public: BufferStream(); ~BufferStream(); - void addBuffer(BufferPointer& buffer, Offset offset, Offset stride); + void addBuffer(const BufferPointer& buffer, Offset offset, Offset stride); const Buffers& getBuffers() const { return _buffers; } const Offsets& getOffsets() const { return _offsets; } From a7b039fbb9703128a2e560d82f1456afab21fbfa Mon Sep 17 00:00:00 2001 From: Sam Gateau Date: Fri, 19 Dec 2014 13:28:19 -0800 Subject: [PATCH 224/258] Disabling glDebug --- libraries/gpu/src/gpu/GLBackend.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/libraries/gpu/src/gpu/GLBackend.cpp b/libraries/gpu/src/gpu/GLBackend.cpp index 436045e8a3..f5f998d0d9 100644 --- a/libraries/gpu/src/gpu/GLBackend.cpp +++ b/libraries/gpu/src/gpu/GLBackend.cpp @@ -174,8 +174,8 @@ void GLBackend::checkGLError() { } } -#define CHECK_GL_ERROR() ::gpu::GLBackend::checkGLError() -//#define CHECK_GL_ERROR() +//#define CHECK_GL_ERROR() ::gpu::GLBackend::checkGLError() +#define CHECK_GL_ERROR() void GLBackend::do_draw(Batch& batch, uint32 paramOffset) { updateInput(); From 1db1914a2efb409d5c1027343e1da4d40ab5b380 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Fri, 19 Dec 2014 13:46:33 -0800 Subject: [PATCH 225/258] replace gluProject() with just the math --- interface/src/avatar/Avatar.cpp | 138 ++++++++++++++++---------------- interface/src/avatar/Avatar.h | 1 + 2 files changed, 72 insertions(+), 67 deletions(-) diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index 39c528d080..4c309b2c8c 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -669,6 +669,49 @@ glm::vec3 Avatar::getDisplayNamePosition() { return namePosition; } +float Avatar::calculateDisplayNameScaleFactor(const glm::vec3& textPosition, bool inHMD) { + + // We need to compute the scale factor such as the text remains with fixed size respect to window coordinates + // We project a unit vector and check the difference in screen coordinates, to check which is the + // correction scale needed + // save the matrices for later scale correction factor + // The up vector must be relative to the rotation current rotation matrix: + // we set the identity + glm::vec3 testPoint0 = textPosition; + glm::vec3 testPoint1 = textPosition + (Application::getInstance()->getCamera()->getRotation() * IDENTITY_UP); + + double textWindowHeight; + + GLCanvas::SharedPointer glCanvas = DependencyManager::get(); + float windowSizeX = glCanvas->getDeviceWidth(); + float windowSizeY = glCanvas->getDeviceHeight(); + + glm::dmat4 modelViewMatrix; + glm::dmat4 projectionMatrix; + Application::getInstance()->getModelViewMatrix(&modelViewMatrix); + Application::getInstance()->getProjectionMatrix(&projectionMatrix); + + glm::dvec4 p0 = modelViewMatrix * glm::dvec4(testPoint0, 1.0); + p0 = projectionMatrix * p0; + glm::dvec2 result0 = glm::vec2(windowSizeX * (p0.x / p0.w + 1.0f) * 0.5f, windowSizeY * (p0.y / p0.w + 1.0f) * 0.5f); + + glm::dvec4 p1 = modelViewMatrix * glm::dvec4(testPoint1, 1.0); + p1 = projectionMatrix * p1; + glm::vec2 result1 = glm::vec2(windowSizeX * (p1.x / p1.w + 1.0f) * 0.5f, windowSizeY * (p1.y / p1.w + 1.0f) * 0.5f); + textWindowHeight = abs(result1.y - result0.y); + + // need to scale to compensate for the font resolution due to the device + float scaleFactor = QApplication::desktop()->windowHandle()->devicePixelRatio() * + ((textWindowHeight > EPSILON) ? 1.0f / textWindowHeight : 1.0f); + if (inHMD) { + const float HMDMODE_NAME_SCALE = 0.65f; + scaleFactor *= HMDMODE_NAME_SCALE; + } else { + scaleFactor *= Application::getInstance()->getRenderResolutionScale(); + } + return scaleFactor; +} + void Avatar::renderDisplayName() { if (_displayName.isEmpty() || _displayNameAlpha == 0.0f) { @@ -700,78 +743,39 @@ void Avatar::renderDisplayName() { frontAxis = glm::normalize(glm::vec3(frontAxis.z, 0.0f, -frontAxis.x)); float angle = acos(frontAxis.x) * ((frontAxis.z < 0) ? 1.0f : -1.0f); glRotatef(glm::degrees(angle), 0.0f, 1.0f, 0.0f); - - // We need to compute the scale factor such as the text remains with fixed size respect to window coordinates - // We project a unit vector and check the difference in screen coordinates, to check which is the - // correction scale needed - // save the matrices for later scale correction factor - glm::dmat4 modelViewMatrix; - glm::dmat4 projectionMatrix; - GLint viewportMatrix[4]; - Application::getInstance()->getModelViewMatrix(&modelViewMatrix); - Application::getInstance()->getProjectionMatrix(&projectionMatrix); - glGetIntegerv(GL_VIEWPORT, viewportMatrix); - GLdouble result0[3], result1[3]; - - // The up vector must be relative to the rotation current rotation matrix: - // we set the identity - glm::dvec3 testPoint0 = glm::dvec3(textPosition); - glm::dvec3 testPoint1 = glm::dvec3(textPosition) + glm::dvec3(Application::getInstance()->getCamera()->getRotation() * IDENTITY_UP); - bool success; - success = gluProject(testPoint0.x, testPoint0.y, testPoint0.z, - (GLdouble*)&modelViewMatrix, (GLdouble*)&projectionMatrix, viewportMatrix, - &result0[0], &result0[1], &result0[2]); - success = success && - gluProject(testPoint1.x, testPoint1.y, testPoint1.z, - (GLdouble*)&modelViewMatrix, (GLdouble*)&projectionMatrix, viewportMatrix, - &result1[0], &result1[1], &result1[2]); + float scaleFactor = calculateDisplayNameScaleFactor(textPosition, inHMD); + glScalef(scaleFactor, scaleFactor, 1.0); + + glScalef(1.0f, -1.0f, 1.0f); // TextRenderer::draw paints the text upside down in y axis - if (success) { - double textWindowHeight = abs(result1[1] - result0[1]); - // need to scale to compensate for the font resolution due to the device - float scaleFactor = QApplication::desktop()->windowHandle()->devicePixelRatio() * - ((textWindowHeight > EPSILON) ? 1.0f / textWindowHeight : 1.0f); - if (inHMD) { - const float HMDMODE_NAME_SCALE = 0.65f; - scaleFactor *= HMDMODE_NAME_SCALE; - } else { - scaleFactor *= Application::getInstance()->getRenderResolutionScale(); - } - glScalef(scaleFactor, scaleFactor, 1.0); - - glScalef(1.0f, -1.0f, 1.0f); // TextRenderer::draw paints the text upside down in y axis + int text_x = -_displayNameBoundingRect.width() / 2; + int text_y = -_displayNameBoundingRect.height() / 2; - int text_x = -_displayNameBoundingRect.width() / 2; - int text_y = -_displayNameBoundingRect.height() / 2; + // draw a gray background + int left = text_x + _displayNameBoundingRect.x(); + int right = left + _displayNameBoundingRect.width(); + int bottom = text_y + _displayNameBoundingRect.y(); + int top = bottom + _displayNameBoundingRect.height(); + const int border = 8; + bottom -= border; + left -= border; + top += border; + right += border; - // draw a gray background - int left = text_x + _displayNameBoundingRect.x(); - int right = left + _displayNameBoundingRect.width(); - int bottom = text_y + _displayNameBoundingRect.y(); - int top = bottom + _displayNameBoundingRect.height(); - const int border = 8; - bottom -= border; - left -= border; - top += border; - right += border; + // We are drawing coplanar textures with depth: need the polygon offset + glEnable(GL_POLYGON_OFFSET_FILL); + glPolygonOffset(1.0f, 1.0f); - // We are drawing coplanar textures with depth: need the polygon offset - glEnable(GL_POLYGON_OFFSET_FILL); - glPolygonOffset(1.0f, 1.0f); - - glColor4f(0.2f, 0.2f, 0.2f, _displayNameAlpha * DISPLAYNAME_BACKGROUND_ALPHA / DISPLAYNAME_ALPHA); - renderBevelCornersRect(left, bottom, right - left, top - bottom, 3); - - glColor4f(0.93f, 0.93f, 0.93f, _displayNameAlpha); - QByteArray ba = _displayName.toLocal8Bit(); - const char* text = ba.data(); - - glDisable(GL_POLYGON_OFFSET_FILL); - textRenderer(DISPLAYNAME)->draw(text_x, text_y, text); - - - } + glColor4f(0.2f, 0.2f, 0.2f, _displayNameAlpha * DISPLAYNAME_BACKGROUND_ALPHA / DISPLAYNAME_ALPHA); + renderBevelCornersRect(left, bottom, right - left, top - bottom, 3); + + glColor4f(0.93f, 0.93f, 0.93f, _displayNameAlpha); + QByteArray ba = _displayName.toLocal8Bit(); + const char* text = ba.data(); + + glDisable(GL_POLYGON_OFFSET_FILL); + textRenderer(DISPLAYNAME)->draw(text_x, text_y, text); glPopMatrix(); diff --git a/interface/src/avatar/Avatar.h b/interface/src/avatar/Avatar.h index 88ab3b12ca..d862e042c2 100644 --- a/interface/src/avatar/Avatar.h +++ b/interface/src/avatar/Avatar.h @@ -230,6 +230,7 @@ protected: float getPelvisFloatingHeight() const; glm::vec3 getDisplayNamePosition(); + float calculateDisplayNameScaleFactor(const glm::vec3& textPosition, bool inHMD); void renderDisplayName(); virtual void renderBody(RenderMode renderMode, bool postLighting, float glowLevel = 0.0f); virtual bool shouldRenderHead(const glm::vec3& cameraPosition, RenderMode renderMode) const; From 22e2fcf746af7df99a71b2f5caea198d1d63ef1e Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Fri, 19 Dec 2014 13:46:42 -0800 Subject: [PATCH 226/258] add some vec2 debugging --- libraries/shared/src/StreamUtils.cpp | 8 ++++++++ libraries/shared/src/StreamUtils.h | 1 + 2 files changed, 9 insertions(+) diff --git a/libraries/shared/src/StreamUtils.cpp b/libraries/shared/src/StreamUtils.cpp index 85b800efbe..47bb8dd4e4 100644 --- a/libraries/shared/src/StreamUtils.cpp +++ b/libraries/shared/src/StreamUtils.cpp @@ -98,6 +98,14 @@ std::ostream& operator<<(std::ostream& s, const CapsuleShape& capsule) { #ifndef QT_NO_DEBUG_STREAM #include +QDebug& operator<<(QDebug& dbg, const glm::vec2& v) { + dbg.nospace() << "{type='glm::vec2'" + ", x=" << v.x << + ", y=" << v.y << + "}"; + return dbg; +} + QDebug& operator<<(QDebug& dbg, const glm::vec3& v) { dbg.nospace() << "{type='glm::vec3'" ", x=" << v.x << diff --git a/libraries/shared/src/StreamUtils.h b/libraries/shared/src/StreamUtils.h index 6d00c0e354..d176d68e45 100644 --- a/libraries/shared/src/StreamUtils.h +++ b/libraries/shared/src/StreamUtils.h @@ -49,6 +49,7 @@ std::ostream& operator<<(std::ostream& s, const CapsuleShape& capsule); #ifndef QT_NO_DEBUG_STREAM class QDebug; // Add support for writing these to qDebug(). +QDebug& operator<<(QDebug& s, const glm::vec2& v); QDebug& operator<<(QDebug& s, const glm::vec3& v); QDebug& operator<<(QDebug& s, const glm::quat& q); QDebug& operator<<(QDebug& s, const glm::mat4& m); From 2e3a522e73d045d5efa071e8a6ca4417db52dae6 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Fri, 19 Dec 2014 13:53:44 -0800 Subject: [PATCH 227/258] remove glut.h from CmakeLists.txt and fix a compiler issue with Hair.cpp --- interface/CMakeLists.txt | 6 +++--- interface/src/Hair.cpp | 2 ++ 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/interface/CMakeLists.txt b/interface/CMakeLists.txt index a9688a5919..6d0b6a2f07 100644 --- a/interface/CMakeLists.txt +++ b/interface/CMakeLists.txt @@ -25,15 +25,15 @@ else () endif () if (APPLE) - set(GL_HEADERS "#include \n#include ") + set(GL_HEADERS "#include ") elseif (UNIX) # include the right GL headers for UNIX - set(GL_HEADERS "#include \n#include \n#include ") + set(GL_HEADERS "#include \n#include ") elseif (WIN32) add_definitions(-D_USE_MATH_DEFINES) # apparently needed to get M_PI and other defines from cmath/math.h add_definitions(-DWINDOWS_LEAN_AND_MEAN) # needed to make sure windows doesn't go to crazy with its defines - set(GL_HEADERS "#include \n#include \n#include \n#include ") + set(GL_HEADERS "#include \n#include \n#include ") endif () # set up the external glm library diff --git a/interface/src/Hair.cpp b/interface/src/Hair.cpp index cb664f39ed..6fd326a9b5 100644 --- a/interface/src/Hair.cpp +++ b/interface/src/Hair.cpp @@ -10,6 +10,8 @@ // // Creates single flexible verlet-integrated strands that can be used for hair/fur/grass +#include + #include "Hair.h" #include "Util.h" From 4f478e158f728412006464e0307013d908ad6e4b Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 19 Dec 2014 13:59:43 -0800 Subject: [PATCH 228/258] remove includes for glu for APPLE --- interface/src/avatar/Avatar.cpp | 5 ----- interface/src/ui/ApplicationOverlay.cpp | 5 ----- interface/src/ui/RearMirrorTools.cpp | 5 ----- 3 files changed, 15 deletions(-) diff --git a/interface/src/avatar/Avatar.cpp b/interface/src/avatar/Avatar.cpp index aa94b21d71..39c528d080 100644 --- a/interface/src/avatar/Avatar.cpp +++ b/interface/src/avatar/Avatar.cpp @@ -13,11 +13,6 @@ #include -// TODO: remove calls to gluProject to remove this include -#ifdef __APPLE__ -#include -#endif - #include #include diff --git a/interface/src/ui/ApplicationOverlay.cpp b/interface/src/ui/ApplicationOverlay.cpp index f82b44a403..ab85da125c 100644 --- a/interface/src/ui/ApplicationOverlay.cpp +++ b/interface/src/ui/ApplicationOverlay.cpp @@ -11,11 +11,6 @@ #include "InterfaceConfig.h" -// TODO: remove calls to gluProject to remove this include -#ifdef __APPLE__ -#include -#endif - #include #include diff --git a/interface/src/ui/RearMirrorTools.cpp b/interface/src/ui/RearMirrorTools.cpp index 2c671ef548..fd3fc34adb 100644 --- a/interface/src/ui/RearMirrorTools.cpp +++ b/interface/src/ui/RearMirrorTools.cpp @@ -11,11 +11,6 @@ #include "InterfaceConfig.h" -// TODO: remove calls to gluProject to remove this include -#ifdef __APPLE__ -#include -#endif - #include #include From 30e2a9c13f13c0e6cd3b13db85f4307b7b3783f4 Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Fri, 19 Dec 2014 14:18:44 -0800 Subject: [PATCH 229/258] Add notifications.js to defaultScripts --- examples/defaultScripts.js | 1 + 1 file changed, 1 insertion(+) diff --git a/examples/defaultScripts.js b/examples/defaultScripts.js index d39fce0186..cdb8e76c65 100644 --- a/examples/defaultScripts.js +++ b/examples/defaultScripts.js @@ -15,3 +15,4 @@ Script.load("hydraMove.js"); Script.load("headMove.js"); Script.load("inspect.js"); Script.load("lobby.js"); +Script.load("notifications.js"); From 7e37aaabde2f7597fdff8ef28b0c66ffd931d1dd Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Fri, 19 Dec 2014 14:24:04 -0800 Subject: [PATCH 230/258] windows build hack --- interface/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interface/CMakeLists.txt b/interface/CMakeLists.txt index 6d0b6a2f07..ff813343ab 100644 --- a/interface/CMakeLists.txt +++ b/interface/CMakeLists.txt @@ -232,7 +232,7 @@ else (APPLE) # we're using static GLEW, so define GLEW_STATIC add_definitions(-DGLEW_STATIC) - target_link_libraries(${TARGET_NAME} "${GLEW_LIBRARIES}" "${NSIGHT_LIBRARIES}" wsock32.lib opengl32.lib) + target_link_libraries(${TARGET_NAME} "${GLEW_LIBRARIES}" "${NSIGHT_LIBRARIES}" wsock32.lib opengl32.lib Winmm.lib) # try to find the Nsight package and add it to the build if we find it find_package(NSIGHT) From b7165abd5beaa5498024ed098bcbadcec83a12d5 Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Fri, 19 Dec 2014 14:33:45 -0800 Subject: [PATCH 231/258] possible glew warning fix for windows --- libraries/gpu/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/gpu/CMakeLists.txt b/libraries/gpu/CMakeLists.txt index 340adcc9e6..e63495867e 100644 --- a/libraries/gpu/CMakeLists.txt +++ b/libraries/gpu/CMakeLists.txt @@ -19,7 +19,7 @@ elseif (WIN32) # we're using static GLEW, so define GLEW_STATIC add_definitions(-DGLEW_STATIC) - target_link_libraries(${TARGET_NAME} "${GLEW_LIBRARIES}" opengl32.lib) + target_link_libraries(${TARGET_NAME} opengl32.lib) # need to bubble up the GLEW_INCLUDE_DIRS list(APPEND ${TARGET_NAME}_DEPENDENCY_INCLUDES "${GLEW_INCLUDE_DIRS}") From 691be3bf7c4e29b596b44ba3c889f4111c306cb0 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 19 Dec 2014 14:59:55 -0800 Subject: [PATCH 232/258] add a test to confirm link fail --- libraries/gpu/src/gpu/GLBackend.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/libraries/gpu/src/gpu/GLBackend.cpp b/libraries/gpu/src/gpu/GLBackend.cpp index 90639929ca..6663e0b169 100644 --- a/libraries/gpu/src/gpu/GLBackend.cpp +++ b/libraries/gpu/src/gpu/GLBackend.cpp @@ -117,7 +117,8 @@ GLBackend::GLBackend() : _input(), _transform() { - + // TEST FOR SANITY + glewInit(); } GLBackend::~GLBackend() { From d7d11955f3d4eafb3b7258ccd7f785752a1ff343 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 19 Dec 2014 15:05:13 -0800 Subject: [PATCH 233/258] Revert "add a test to confirm link fail" This reverts commit 691be3bf7c4e29b596b44ba3c889f4111c306cb0. --- libraries/gpu/src/gpu/GLBackend.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/libraries/gpu/src/gpu/GLBackend.cpp b/libraries/gpu/src/gpu/GLBackend.cpp index 6663e0b169..90639929ca 100644 --- a/libraries/gpu/src/gpu/GLBackend.cpp +++ b/libraries/gpu/src/gpu/GLBackend.cpp @@ -117,8 +117,7 @@ GLBackend::GLBackend() : _input(), _transform() { - // TEST FOR SANITY - glewInit(); + } GLBackend::~GLBackend() { From 2780415b1d4d529d91d8d6382d8cbadd8dbb18d1 Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Fri, 19 Dec 2014 15:07:31 -0800 Subject: [PATCH 234/258] put glew link back into gpu --- libraries/gpu/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/gpu/CMakeLists.txt b/libraries/gpu/CMakeLists.txt index b4da0d8b03..7f2b475dd2 100644 --- a/libraries/gpu/CMakeLists.txt +++ b/libraries/gpu/CMakeLists.txt @@ -19,7 +19,7 @@ elseif (WIN32) # we're using static GLEW, so define GLEW_STATIC add_definitions(-DGLEW_STATIC) - target_link_libraries(${TARGET_NAME} opengl32.lib) + target_link_libraries(${TARGET_NAME} ${GLEW_LIBRARIES} opengl32.lib) # need to bubble up the GLEW_INCLUDE_DIRS list(APPEND ${TARGET_NAME}_DEPENDENCY_INCLUDES "${GLEW_INCLUDE_DIRS}") From 25a78534aae5eae68b241e9419bffdd21f294fe8 Mon Sep 17 00:00:00 2001 From: Ryan Huffman Date: Fri, 19 Dec 2014 15:52:31 -0800 Subject: [PATCH 235/258] Fix quad vertices for ImageOverlay and TextOverlay --- interface/src/ui/overlays/ImageOverlay.cpp | 13 +++++++++---- interface/src/ui/overlays/TextOverlay.cpp | 13 +++++++++---- 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/interface/src/ui/overlays/ImageOverlay.cpp b/interface/src/ui/overlays/ImageOverlay.cpp index f903dfe19c..b14f49737f 100644 --- a/interface/src/ui/overlays/ImageOverlay.cpp +++ b/interface/src/ui/overlays/ImageOverlay.cpp @@ -100,26 +100,31 @@ void ImageOverlay::render(RenderArgs* args) { float w = fromImage.width() / imageWidth; // ?? is this what we want? not sure float h = fromImage.height() / imageHeight; + int left = _bounds.left(); + int right = _bounds.right() + 1; + int top = _bounds.top(); + int bottom = _bounds.bottom() + 1; + glBegin(GL_QUADS); if (_renderImage) { glTexCoord2f(x, 1.0f - y); } - glVertex2f(_bounds.left(), _bounds.top()); + glVertex2f(left, top); if (_renderImage) { glTexCoord2f(x + w, 1.0f - y); } - glVertex2f(_bounds.right(), _bounds.top()); + glVertex2f(right, top); if (_renderImage) { glTexCoord2f(x + w, 1.0f - (y + h)); } - glVertex2f(_bounds.right(), _bounds.bottom()); + glVertex2f(right, bottom); if (_renderImage) { glTexCoord2f(x, 1.0f - (y + h)); } - glVertex2f(_bounds.left(), _bounds.bottom()); + glVertex2f(left, bottom); glEnd(); if (_renderImage) { diff --git a/interface/src/ui/overlays/TextOverlay.cpp b/interface/src/ui/overlays/TextOverlay.cpp index 97d910eb64..03a5c3d846 100644 --- a/interface/src/ui/overlays/TextOverlay.cpp +++ b/interface/src/ui/overlays/TextOverlay.cpp @@ -70,11 +70,16 @@ void TextOverlay::render(RenderArgs* args) { glColor4f(backgroundColor.red / MAX_COLOR, backgroundColor.green / MAX_COLOR, backgroundColor.blue / MAX_COLOR, getBackgroundAlpha()); + int left = _bounds.left(); + int right = _bounds.right() + 1; + int top = _bounds.top(); + int bottom = _bounds.bottom() + 1; + glBegin(GL_QUADS); - glVertex2f(_bounds.left(), _bounds.top()); - glVertex2f(_bounds.right(), _bounds.top()); - glVertex2f(_bounds.right(), _bounds.bottom()); - glVertex2f(_bounds.left(), _bounds.bottom()); + glVertex2f(left, top); + glVertex2f(right, top); + glVertex2f(right, bottom); + glVertex2f(left, bottom); glEnd(); // Same font properties as textSize() From 967c6dbc4b93024bddce4bd608b4de0bd5eeacf8 Mon Sep 17 00:00:00 2001 From: Sam Gateau Date: Fri, 19 Dec 2014 16:19:06 -0800 Subject: [PATCH 236/258] Add the Model library --- assignment-client/CMakeLists.txt | 2 +- interface/CMakeLists.txt | 2 +- libraries/animation/CMakeLists.txt | 2 +- libraries/avatars/CMakeLists.txt | 4 +- libraries/entities/CMakeLists.txt | 2 +- libraries/fbx/CMakeLists.txt | 2 +- libraries/fbx/src/FBXReader.h | 7 +- libraries/model/CMakeLists.txt | 11 ++ libraries/model/src/model/Geometry.cpp | 141 +++++++++++++++++++++++ libraries/model/src/model/Geometry.h | 151 +++++++++++++++++++++++++ libraries/model/src/model/Material.cpp | 92 +++++++++++++++ libraries/model/src/model/Material.h | 114 +++++++++++++++++++ libraries/script-engine/CMakeLists.txt | 2 +- libraries/shared/src/AABox.cpp | 25 +++- libraries/shared/src/AABox.h | 5 + tests/octree/CMakeLists.txt | 2 +- 16 files changed, 549 insertions(+), 15 deletions(-) create mode 100755 libraries/model/CMakeLists.txt create mode 100755 libraries/model/src/model/Geometry.cpp create mode 100755 libraries/model/src/model/Geometry.h create mode 100755 libraries/model/src/model/Material.cpp create mode 100755 libraries/model/src/model/Material.h diff --git a/assignment-client/CMakeLists.txt b/assignment-client/CMakeLists.txt index 6e31182f0d..9d604cd5dd 100644 --- a/assignment-client/CMakeLists.txt +++ b/assignment-client/CMakeLists.txt @@ -6,7 +6,7 @@ include_glm() # link in the shared libraries link_hifi_libraries( - audio avatars octree voxels fbx entities metavoxels + audio avatars octree voxels gpu model fbx entities metavoxels networking animation shared script-engine embedded-webserver physics ) diff --git a/interface/CMakeLists.txt b/interface/CMakeLists.txt index a9688a5919..92c0d03add 100644 --- a/interface/CMakeLists.txt +++ b/interface/CMakeLists.txt @@ -107,7 +107,7 @@ endif() add_executable(${TARGET_NAME} MACOSX_BUNDLE ${INTERFACE_SRCS} ${QM}) # link required hifi libraries -link_hifi_libraries(shared octree voxels gpu fbx metavoxels networking entities avatars audio animation script-engine physics +link_hifi_libraries(shared octree voxels gpu model fbx metavoxels networking entities avatars audio animation script-engine physics render-utils entities-renderer) # find any optional and required libraries diff --git a/libraries/animation/CMakeLists.txt b/libraries/animation/CMakeLists.txt index 3f65c1ab6c..ee80db7567 100644 --- a/libraries/animation/CMakeLists.txt +++ b/libraries/animation/CMakeLists.txt @@ -3,7 +3,7 @@ set(TARGET_NAME animation) # use setup_hifi_library macro to setup our project and link appropriate Qt modules setup_hifi_library(Network Script) -link_hifi_libraries(shared fbx) +link_hifi_libraries(shared gpu model fbx) # call macro to link our dependencies and bubble them up via a property on our target link_shared_dependencies() \ No newline at end of file diff --git a/libraries/avatars/CMakeLists.txt b/libraries/avatars/CMakeLists.txt index 42b3cf7d3c..4c84c542ef 100644 --- a/libraries/avatars/CMakeLists.txt +++ b/libraries/avatars/CMakeLists.txt @@ -5,8 +5,8 @@ setup_hifi_library(Network Script) include_glm() -link_hifi_libraries(shared octree voxels networking physics) -include_hifi_library_headers(fbx) +link_hifi_libraries(shared octree voxels gpu model fbx networking physics) +include_hifi_library_headers(gpu model fbx) # call macro to link our dependencies and bubble them up via a property on our target link_shared_dependencies() diff --git a/libraries/entities/CMakeLists.txt b/libraries/entities/CMakeLists.txt index e48baa7615..b266050e69 100644 --- a/libraries/entities/CMakeLists.txt +++ b/libraries/entities/CMakeLists.txt @@ -5,7 +5,7 @@ setup_hifi_library(Network Script) include_glm() -link_hifi_libraries(shared octree fbx networking animation physics) +link_hifi_libraries(shared octree gpu model fbx networking animation physics) # call macro to link our dependencies and bubble them up via a property on our target link_shared_dependencies() diff --git a/libraries/fbx/CMakeLists.txt b/libraries/fbx/CMakeLists.txt index 5a151deb8b..fe460c93b5 100644 --- a/libraries/fbx/CMakeLists.txt +++ b/libraries/fbx/CMakeLists.txt @@ -5,7 +5,7 @@ setup_hifi_library() include_glm() -link_hifi_libraries(shared networking octree voxels) +link_hifi_libraries(shared gpu model networking octree voxels) find_package(ZLIB REQUIRED) include_directories(SYSTEM "${ZLIB_INCLUDE_DIRS}") diff --git a/libraries/fbx/src/FBXReader.h b/libraries/fbx/src/FBXReader.h index 736da3a349..3d07d29e7d 100644 --- a/libraries/fbx/src/FBXReader.h +++ b/libraries/fbx/src/FBXReader.h @@ -24,8 +24,10 @@ #include #include -class QIODevice; +#include +#include +class QIODevice; class FBXNode; typedef QList FBXNodeList; @@ -131,6 +133,7 @@ public: FBXTexture emissiveTexture; QString materialID; + model::MaterialPointer _material; }; /// A single mesh (with optional blendshapes) extracted from an FBX document. @@ -159,6 +162,8 @@ public: bool hasSpecularTexture() const; bool hasEmissiveTexture() const; + + model::Mesh _mesh; }; /// A single animation frame extracted from an FBX document. diff --git a/libraries/model/CMakeLists.txt b/libraries/model/CMakeLists.txt new file mode 100755 index 0000000000..d9fd4b67a7 --- /dev/null +++ b/libraries/model/CMakeLists.txt @@ -0,0 +1,11 @@ +set(TARGET_NAME model) + +# use setup_hifi_library macro to setup our project and link appropriate Qt modules +setup_hifi_library() + +include_glm() + +link_hifi_libraries(shared gpu) + +# call macro to link our dependencies and bubble them up via a property on our target +link_shared_dependencies() diff --git a/libraries/model/src/model/Geometry.cpp b/libraries/model/src/model/Geometry.cpp new file mode 100755 index 0000000000..d5d3ba6c07 --- /dev/null +++ b/libraries/model/src/model/Geometry.cpp @@ -0,0 +1,141 @@ +// +// Geometry.cpp +// libraries/model/src/model +// +// Created by Sam Gateau on 12/5/2014. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "Geometry.h" + +#include + +using namespace model; + +Mesh::Mesh() : + _vertexBuffer(gpu::Element(gpu::VEC3, gpu::FLOAT, gpu::XYZ)), + _indexBuffer(gpu::Element(gpu::SCALAR, gpu::UINT32, gpu::INDEX)), + _partBuffer(gpu::Element(gpu::VEC4, gpu::UINT32, gpu::PART)) { +} + +Mesh::Mesh(const Mesh& mesh) : + _vertexFormat(mesh._vertexFormat), + _vertexBuffer(mesh._vertexBuffer), + _attributeBuffers(mesh._attributeBuffers), + _indexBuffer(mesh._indexBuffer), + _partBuffer(mesh._partBuffer) { +} + +Mesh::~Mesh() { +} + +void Mesh::setVertexBuffer(const BufferView& buffer) { + _vertexBuffer = buffer; + evalVertexFormat(); +} + +void Mesh::addAttribute(Slot slot, const BufferView& buffer) { + _attributeBuffers[slot] = buffer; + evalVertexFormat(); +} + +void Mesh::evalVertexFormat() { + VertexFormat vf; + int channelNum = 0; + if (hasVertexData()) { + vf.setAttribute(gpu::Stream::POSITION, channelNum, _vertexBuffer._element, 0); + channelNum++; + } + for (auto attrib : _attributeBuffers) { + vf.setAttribute(attrib.first, channelNum, attrib.second._element, 0); + channelNum++; + } + + _vertexFormat = vf; +} + +void Mesh::setIndexBuffer(const BufferView& buffer) { + _indexBuffer = buffer; +} + +void Mesh::setPartBuffer(const BufferView& buffer) { + _partBuffer = buffer; +} + +const Box Mesh::evalPartBound(int partNum) const { + Box box; + if (partNum < _partBuffer.getNum()) { + const Part& part = _partBuffer.get(partNum); + auto index = _indexBuffer.cbegin(); + index += part._startIndex; + auto endIndex = index; + endIndex += part._numIndices; + auto vertices = &_vertexBuffer.get(part._baseVertex); + for (;index != endIndex; index++) { + // skip primitive restart indices + if ((*index) != PRIMITIVE_RESTART_INDEX) { + box += vertices[(*index)]; + } + } + } + return box; +} + +const Box Mesh::evalPartBounds(int partStart, int partEnd, Boxes& bounds) const { + Box totalBound; + auto part = _partBuffer.cbegin() + partStart; + auto partItEnd = _partBuffer.cbegin() + partEnd; + + for (;part != partItEnd; part++) { + + Box partBound; + auto index = _indexBuffer.cbegin() + (*part)._startIndex; + auto endIndex = index + (*part)._numIndices; + auto vertices = &_vertexBuffer.get((*part)._baseVertex); + for (;index != endIndex; index++) { + // skip primitive restart indices + if ((*index) != PRIMITIVE_RESTART_INDEX) { + partBound += vertices[(*index)]; + } + } + + totalBound += partBound; + } + return totalBound; +} + +const gpu::BufferStream Mesh::makeBufferStream() const { + gpu::BufferStream stream; + + int channelNum = 0; + if (hasVertexData()) { + stream.addBuffer(_vertexBuffer._buffer, _vertexBuffer._offset, _vertexFormat.getChannelStride(channelNum)); + channelNum++; + } + for (auto attrib : _attributeBuffers) { + BufferView& view = attrib.second; + stream.addBuffer(view._buffer, view._offset, _vertexFormat.getChannelStride(channelNum)); + channelNum++; + } + + return stream; +} + +Geometry::Geometry() { +} + +Geometry::Geometry(const Geometry& geometry): + _mesh(geometry._mesh), + _boxes(geometry._boxes) { +} + +Geometry::~Geometry() { +} + +void Geometry::setMesh(const MeshPointer& mesh) { + _mesh = mesh; +} + diff --git a/libraries/model/src/model/Geometry.h b/libraries/model/src/model/Geometry.h new file mode 100755 index 0000000000..8f0625ef69 --- /dev/null +++ b/libraries/model/src/model/Geometry.h @@ -0,0 +1,151 @@ +// +// Geometry.h +// libraries/model/src/model +// +// Created by Sam Gateau on 12/5/2014. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// +#ifndef hifi_model_Geometry_h +#define hifi_model_Geometry_h + +#include + +#include "AABox.h" + +#include "gpu/Resource.h" +#include "gpu/Stream.h" + +namespace model { +typedef gpu::BufferView::Index Index; +typedef gpu::BufferView BufferView; +typedef AABox Box; +typedef std::vector< Box > Boxes; + +class Mesh { +public: + const static Index PRIMITIVE_RESTART_INDEX = -1; + + typedef gpu::BufferView BufferView; + typedef std::vector< BufferView > BufferViews; + + typedef gpu::Stream::Slot Slot; + typedef gpu::Stream::Format VertexFormat; + typedef std::map< Slot, BufferView > BufferViewMap; + + typedef glm::vec3 Vec3; + + Mesh(); + Mesh(const Mesh& mesh); + Mesh& operator= (const Mesh& mesh) = default; + virtual ~Mesh(); + + // Vertex buffer + void setVertexBuffer(const BufferView& buffer); + const BufferView& getVertexBuffer() const { return _vertexBuffer; } + uint getNumVertices() const { return _vertexBuffer.getNumElements(); } + bool hasVertexData() const { return !_vertexBuffer._buffer.isNull(); } + + // Attribute Buffers + int getNumAttributes() const { return _attributeBuffers.size(); } + void addAttribute(Slot slot, const BufferView& buffer); + + // Stream format + const VertexFormat& getVertexFormat() const { return _vertexFormat; } + + // Index Buffer + void setIndexBuffer(const BufferView& buffer); + const BufferView& getIndexBuffer() const { return _indexBuffer; } + uint getNumIndices() const { return _indexBuffer.getNumElements(); } + + // Access vertex position value + const Vec3& getPos3(Index index) const { return _vertexBuffer.get(index); } + + enum Topology + { + POINTS = 0, + LINES, + LINE_STRIP, + TRIANGLES, + TRIANGLE_STRIP, + QUADS, + QUAD_STRIP, + + NUM_TOPOLOGIES, + }; + + // Subpart of a mesh, describing the toplogy of the surface + class Part { + public: + Index _startIndex; + Index _numIndices; + Index _baseVertex; + Topology _topology; + + Part() : + _startIndex(0), + _numIndices(0), + _baseVertex(0), + _topology(TRIANGLES) + {} + Part(Index startIndex, Index numIndices, Index baseVertex, Topology topology) : + _startIndex(startIndex), + _numIndices(numIndices), + _baseVertex(baseVertex), + _topology(topology) + {} + }; + + void setPartBuffer(const BufferView& buffer); + const BufferView& getPartBuffer() const { return _partBuffer; } + uint getNumParts() const { return _partBuffer.getNumElements(); } + + // evaluate the bounding box of A part + const Box evalPartBound(int partNum) const; + // evaluate the bounding boxes of the parts in the range [start, end[ and fill the bounds parameter + // the returned box is the bounding box of ALL the evaluated part bounds. + const Box evalPartBounds(int partStart, int partEnd, Boxes& bounds) const; + + + // Generate a BufferStream on the mesh vertices and attributes + const gpu::BufferStream makeBufferStream() const; + +protected: + + VertexFormat _vertexFormat; + + BufferView _vertexBuffer; + BufferViewMap _attributeBuffers; + + BufferView _indexBuffer; + + BufferView _partBuffer; + + void evalVertexFormat(); + +}; +typedef QSharedPointer< Mesh > MeshPointer; + + +class Geometry { +public: + + Geometry(); + Geometry(const Geometry& geometry); + ~Geometry(); + + void setMesh(const MeshPointer& mesh); + const MeshPointer& getMesh() const { return _mesh; } + +protected: + + MeshPointer _mesh; + BufferView _boxes; + +}; + +}; + +#endif diff --git a/libraries/model/src/model/Material.cpp b/libraries/model/src/model/Material.cpp new file mode 100755 index 0000000000..44e0051386 --- /dev/null +++ b/libraries/model/src/model/Material.cpp @@ -0,0 +1,92 @@ +// +// Material.cpp +// libraries/model/src/model +// +// Created by Sam Gateau on 12/10/2014. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// +#include "Material.h" + +using namespace model; + +Material::Material() : + _flags(0), + _schemaBuffer(), + _textureMap() { + + // only if created from nothing shall we create the Buffer to store the properties + Schema schema; + _schemaBuffer = gpu::BufferView(new gpu::Buffer(sizeof(Schema), (const gpu::Buffer::Byte*) &schema)); + + +} + +Material::Material(const Material& material) : + _flags(material._flags), + _schemaBuffer(material._schemaBuffer), + _textureMap(material._textureMap) { +} + +Material& Material::operator= (const Material& material) { + _flags = (material._flags); + _schemaBuffer = (material._schemaBuffer); + _textureMap = (material._textureMap); + + return (*this); +} + +Material::~Material() { +} + +void Material::setDiffuse(const Color& diffuse) { + if (glm::any(glm::greaterThan(diffuse, Color(0.0f)))) { + _flags.set(DIFFUSE_BIT); + } else { + _flags.reset(DIFFUSE_BIT); + } + _schemaBuffer.edit()._diffuse = diffuse; +} + +void Material::setSpecular(const Color& specular) { + if (glm::any(glm::greaterThan(specular, Color(0.0f)))) { + _flags.set(SPECULAR_BIT); + } else { + _flags.reset(SPECULAR_BIT); + } + _schemaBuffer.edit()._specular = specular; +} + +void Material::setEmissive(const Color& emissive) { + if (glm::any(glm::greaterThan(emissive, Color(0.0f)))) { + _flags.set(EMISSIVE_BIT); + } else { + _flags.reset(EMISSIVE_BIT); + } + _schemaBuffer.edit()._emissive = emissive; +} + +void Material::setShininess(float shininess) { + if (shininess > 0.0f) { + _flags.set(SHININESS_BIT); + } else { + _flags.reset(SHININESS_BIT); + } + _schemaBuffer.edit()._shininess = shininess; +} + +void Material::setOpacity(float opacity) { + if (opacity >= 1.0f) { + _flags.reset(TRANSPARENT_BIT); + } else { + _flags.set(TRANSPARENT_BIT); + } + _schemaBuffer.edit()._opacity = opacity; +} + +void Material::setTextureView(MapChannel channel, const TextureView& view) { + _flags.set(DIFFUSE_MAP_BIT + channel); + _textureMap[channel] = view; +} \ No newline at end of file diff --git a/libraries/model/src/model/Material.h b/libraries/model/src/model/Material.h new file mode 100755 index 0000000000..ec15522658 --- /dev/null +++ b/libraries/model/src/model/Material.h @@ -0,0 +1,114 @@ +// +// Material.h +// libraries/model/src/model +// +// Created by Sam Gateau on 12/10/2014. +// Copyright 2014 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// +#ifndef hifi_model_Material_h +#define hifi_model_Material_h + +#include +#include + +#include + +#include "gpu/Resource.h" + +namespace model { +typedef gpu::BufferView UniformBufferView; +typedef gpu::TextureView TextureView; + +class Material { +public: + + typedef glm::vec3 Color; + + enum MapChannel { + DIFFUSE_MAP = 0, + SPECULAR_MAP, + SHININESS_MAP, + EMISSIVE_MAP, + OPACITY_MAP, + NORMAL_MAP, + + NUM_MAPS, + }; + typedef std::map TextureMap; + + enum FlagBit { + DIFFUSE_BIT = 0, + SPECULAR_BIT, + SHININESS_BIT, + EMISSIVE_BIT, + TRANSPARENT_BIT, + + DIFFUSE_MAP_BIT, + SPECULAR_MAP_BIT, + SHININESS_MAP_BIT, + EMISSIVE_MAP_BIT, + OPACITY_MAP_BIT, + NORMAL_MAP_BIT, + + NUM_FLAGS, + }; + typedef std::bitset Flags; + + Material(); + Material(const Material& material); + Material& operator= (const Material& material); + virtual ~Material(); + + const Color& getEmissive() const { return _schemaBuffer.get()._emissive; } + const Color& getDiffuse() const { return _schemaBuffer.get()._diffuse; } + const Color& getSpecular() const { return _schemaBuffer.get()._specular; } + float getShininess() const { return _schemaBuffer.get()._shininess; } + float getOpacity() const { return _schemaBuffer.get()._opacity; } + + void setDiffuse(const Color& diffuse); + void setSpecular(const Color& specular); + void setEmissive(const Color& emissive); + void setShininess(float shininess); + void setOpacity(float opacity); + + // Schema to access the attribute values of the material + class Schema { + public: + + Color _diffuse; + float _opacity; + Color _specular; + float _shininess; + Color _emissive; + float _spare0; + + Schema() : + _diffuse(0.5f), + _opacity(1.0f), + _specular(0.03f), + _shininess(0.1f), + _emissive(0.0f) + {} + }; + + const UniformBufferView& getSchemaBuffer() const { return _schemaBuffer; } + + void setTextureView(MapChannel channel, const TextureView& texture); + const TextureMap& getTextureMap() const { return _textureMap; } + + const Schema* getSchema() const { return &_schemaBuffer.get(); } +protected: + + Flags _flags; + UniformBufferView _schemaBuffer; + TextureMap _textureMap; + +}; +typedef QSharedPointer< Material > MaterialPointer; + +}; + +#endif diff --git a/libraries/script-engine/CMakeLists.txt b/libraries/script-engine/CMakeLists.txt index 3b3a63549d..d5c5aac39a 100644 --- a/libraries/script-engine/CMakeLists.txt +++ b/libraries/script-engine/CMakeLists.txt @@ -5,7 +5,7 @@ setup_hifi_library(Gui Network Script Widgets) include_glm() -link_hifi_libraries(shared octree voxels fbx entities animation audio physics) +link_hifi_libraries(shared octree voxels gpu model fbx entities animation audio physics) # call macro to link our dependencies and bubble them up via a property on our target link_shared_dependencies() diff --git a/libraries/shared/src/AABox.cpp b/libraries/shared/src/AABox.cpp index 00e6db7d33..8823071132 100644 --- a/libraries/shared/src/AABox.cpp +++ b/libraries/shared/src/AABox.cpp @@ -33,7 +33,7 @@ AABox::AABox(const glm::vec3& corner, const glm::vec3& dimensions) : _corner(corner), _scale(dimensions) { }; -AABox::AABox() : _corner(0.0f, 0.0f, 0.0f), _scale(0.0f, 0.0f, 0.0f) { +AABox::AABox() : _corner(std::numeric_limits::infinity()), _scale(0.0f) { }; glm::vec3 AABox::calcCenter() const { @@ -69,7 +69,7 @@ glm::vec3 AABox::getVertex(BoxVertex vertex) const { return _corner + glm::vec3(0, 0, _scale.z); case TOP_RIGHT_FAR: return _corner + glm::vec3(0, _scale.y, _scale.z); - default: //quiet windows warnings + default: //quiet windows warnings case TOP_LEFT_FAR: return _corner + _scale; } @@ -357,7 +357,7 @@ glm::vec3 AABox::getClosestPointOnFace(const glm::vec3& point, BoxFace face) con return glm::clamp(point, glm::vec3(_corner.x, _corner.y, _corner.z), glm::vec3(_corner.x + _scale.z, _corner.y + _scale.y, _corner.z)); - default: //quiet windows warnings + default: //quiet windows warnings case MAX_Z_FACE: return glm::clamp(point, glm::vec3(_corner.x, _corner.y, _corner.z + _scale.z), glm::vec3(_corner.x + _scale.x, _corner.y + _scale.y, _corner.z + _scale.z)); @@ -438,7 +438,7 @@ glm::vec4 AABox::getPlane(BoxFace face) const { case MIN_Y_FACE: return glm::vec4(0.0f, -1.0f, 0.0f, _corner.y); case MAX_Y_FACE: return glm::vec4(0.0f, 1.0f, 0.0f, -_corner.y - _scale.y); case MIN_Z_FACE: return glm::vec4(0.0f, 0.0f, -1.0f, _corner.z); - default: //quiet windows warnings + default: //quiet windows warnings case MAX_Z_FACE: return glm::vec4(0.0f, 0.0f, 1.0f, -_corner.z - _scale.z); } } @@ -450,7 +450,7 @@ BoxFace AABox::getOppositeFace(BoxFace face) { case MIN_Y_FACE: return MAX_Y_FACE; case MAX_Y_FACE: return MIN_Y_FACE; case MIN_Z_FACE: return MAX_Z_FACE; - default: //quiet windows warnings + default: //quiet windows warnings case MAX_Z_FACE: return MIN_Z_FACE; } } @@ -470,3 +470,18 @@ AABox AABox::clamp(float min, float max) const { return AABox(clampedCorner, clampedScale); } + +AABox& AABox::operator += (const glm::vec3& point) { + _corner = glm::min(_corner, point); + _scale = glm::max(_scale, point - _corner); + + return (*this); +} + +AABox& AABox::operator += (const AABox& box) { + if (!box.isInvalid()) { + (*this) += box._corner; + _scale = glm::max(_scale, box.calcTopFarLeft() - _corner); + } + return (*this); +} diff --git a/libraries/shared/src/AABox.h b/libraries/shared/src/AABox.h index 010a7523c5..d862957642 100644 --- a/libraries/shared/src/AABox.h +++ b/libraries/shared/src/AABox.h @@ -72,6 +72,11 @@ public: AABox clamp(const glm::vec3& min, const glm::vec3& max) const; AABox clamp(float min, float max) const; + AABox& operator += (const glm::vec3& point); + AABox& operator += (const AABox& box); + + bool isInvalid() const { return _corner == glm::vec3(std::numeric_limits::infinity()); } + private: glm::vec3 getClosestPointOnFace(const glm::vec3& point, BoxFace face) const; glm::vec3 getClosestPointOnFace(const glm::vec4& origin, const glm::vec4& direction, BoxFace face) const; diff --git a/tests/octree/CMakeLists.txt b/tests/octree/CMakeLists.txt index 7139d4edb6..d4ca79fa1c 100644 --- a/tests/octree/CMakeLists.txt +++ b/tests/octree/CMakeLists.txt @@ -5,6 +5,6 @@ setup_hifi_project(Script Network) include_glm() # link in the shared libraries -link_hifi_libraries(shared octree voxels fbx metavoxels networking entities avatars audio animation script-engine physics) +link_hifi_libraries(shared octree voxels gpu model fbx metavoxels networking entities avatars audio animation script-engine physics) link_shared_dependencies() From 9ab6a680e9fa06c43d8ef2b8773fd443931c3cc8 Mon Sep 17 00:00:00 2001 From: Sam Gateau Date: Mon, 22 Dec 2014 11:03:08 -0800 Subject: [PATCH 237/258] fix typo in cmakelists --- libraries/script-engine/CMakeLists.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/libraries/script-engine/CMakeLists.txt b/libraries/script-engine/CMakeLists.txt index 84aca5d2bb..c153e093cd 100644 --- a/libraries/script-engine/CMakeLists.txt +++ b/libraries/script-engine/CMakeLists.txt @@ -8,4 +8,5 @@ include_glm() link_hifi_libraries(shared octree voxels gpu model fbx entities animation audio physics metavoxels) # call macro to include our dependency includes and bubble them up via a property on our target -gpu model () +include_dependency_includes() + From 979d50f7d82ebe20a977b51fed63439a96d7ab77 Mon Sep 17 00:00:00 2001 From: Sam Gateau Date: Mon, 22 Dec 2014 11:20:04 -0800 Subject: [PATCH 238/258] fixed pointers which were using 0 instead of NULL and syntax in resource.h --- libraries/gpu/src/gpu/Resource.cpp | 8 ++++---- libraries/gpu/src/gpu/Resource.h | 12 +++--------- 2 files changed, 7 insertions(+), 13 deletions(-) diff --git a/libraries/gpu/src/gpu/Resource.cpp b/libraries/gpu/src/gpu/Resource.cpp index 085d97184b..f59152550b 100644 --- a/libraries/gpu/src/gpu/Resource.cpp +++ b/libraries/gpu/src/gpu/Resource.cpp @@ -95,7 +95,7 @@ Resource::Sysmem::~Sysmem() { Resource::Size Resource::Sysmem::allocate(Size size) { if (size != _size) { - Byte* newData = 0; + Byte* newData = NULL; Size newSize = 0; if (size > 0) { Size allocated = allocateMemory(&newData, size); @@ -116,7 +116,7 @@ Resource::Size Resource::Sysmem::allocate(Size size) { Resource::Size Resource::Sysmem::resize(Size size) { if (size != _size) { - Byte* newData = 0; + Byte* newData = NULL; Size newSize = 0; if (size > 0) { Size allocated = allocateMemory(&newData, size); @@ -196,11 +196,11 @@ Buffer& Buffer::operator=(const Buffer& buf) { Buffer::~Buffer() { if (_sysmem) { delete _sysmem; - _sysmem = 0; + _sysmem = NULL; } if (_gpuObject) { delete _gpuObject; - _gpuObject = 0; + _gpuObject = NULL; } } diff --git a/libraries/gpu/src/gpu/Resource.h b/libraries/gpu/src/gpu/Resource.h index ec528c230b..2ec616251c 100644 --- a/libraries/gpu/src/gpu/Resource.h +++ b/libraries/gpu/src/gpu/Resource.h @@ -82,10 +82,8 @@ protected: inline const Byte* readData() const { return _data; } inline Byte* editData() { _stamp++; return _data; } - template< typename T > - const T* read() const { return reinterpret_cast< T* > ( _data ); } - template< typename T > - T* edit() { _stamp++; return reinterpret_cast< T* > ( _data ); } + template< typename T > const T* read() const { return reinterpret_cast< T* > ( _data ); } + template< typename T > T* edit() { _stamp++; return reinterpret_cast< T* > ( _data ); } // Access the current version of the sysmem, used to compare if copies are in sync inline Stamp getStamp() const { return _stamp; } @@ -210,11 +208,7 @@ public: //Template iterator with random access on the buffer sysmem template - class Iterator : public std::iterator + class Iterator : public std::iterator { public: From 1ae682ff21df7f209c5e144d3a2927f6bf1b0047 Mon Sep 17 00:00:00 2001 From: Sam Gateau Date: Mon, 22 Dec 2014 11:36:18 -0800 Subject: [PATCH 239/258] fix end line typo --- libraries/model/src/model/Material.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/libraries/model/src/model/Material.cpp b/libraries/model/src/model/Material.cpp index 44e0051386..1ce50174e0 100755 --- a/libraries/model/src/model/Material.cpp +++ b/libraries/model/src/model/Material.cpp @@ -89,4 +89,4 @@ void Material::setOpacity(float opacity) { void Material::setTextureView(MapChannel channel, const TextureView& view) { _flags.set(DIFFUSE_MAP_BIT + channel); _textureMap[channel] = view; -} \ No newline at end of file +} From 4ee005affa7436aa1b896cee0109969a8112e4cc Mon Sep 17 00:00:00 2001 From: Sam Gateau Date: Mon, 22 Dec 2014 11:51:54 -0800 Subject: [PATCH 240/258] adding scribe tool --- tools/CMakeLists.txt | 1 + tools/scribe/CMakeLists.txt | 5 + tools/scribe/src/TextTemplate.cpp | 1001 +++++++++++++++++++++++++++++ tools/scribe/src/TextTemplate.h | 205 ++++++ tools/scribe/src/main.cpp | 226 +++++++ 5 files changed, 1438 insertions(+) create mode 100755 tools/scribe/CMakeLists.txt create mode 100755 tools/scribe/src/TextTemplate.cpp create mode 100755 tools/scribe/src/TextTemplate.h create mode 100755 tools/scribe/src/main.cpp diff --git a/tools/CMakeLists.txt b/tools/CMakeLists.txt index 32a82627a3..a13933ba5e 100644 --- a/tools/CMakeLists.txt +++ b/tools/CMakeLists.txt @@ -2,3 +2,4 @@ add_subdirectory(bitstream2json) add_subdirectory(json2bitstream) add_subdirectory(mtc) +add_subdirectory(scribe) diff --git a/tools/scribe/CMakeLists.txt b/tools/scribe/CMakeLists.txt new file mode 100755 index 0000000000..e67354cffa --- /dev/null +++ b/tools/scribe/CMakeLists.txt @@ -0,0 +1,5 @@ +set(TARGET_NAME scribe) +setup_hifi_project() + +# call macro to include our dependency includes and bubble them up via a property on our target +include_dependency_includes() \ No newline at end of file diff --git a/tools/scribe/src/TextTemplate.cpp b/tools/scribe/src/TextTemplate.cpp new file mode 100755 index 0000000000..0199f7249e --- /dev/null +++ b/tools/scribe/src/TextTemplate.cpp @@ -0,0 +1,1001 @@ +// +// TextTemplate.cpp +// tools/shaderScribe/src +// +// Created by Sam Gateau on 12/15/2014. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +#include "TextTemplate.h" + +#include +#include +#include +#include + +typedef TextTemplate::Block::Pointer BlockPointer; +typedef TextTemplate::Config::Pointer ConfigPointer; +typedef TextTemplate::Pointer TextTemplatePointer; + +//----------------------------------------------------------------------------- +TextTemplate::Config::Config() : + _includes(), + _funcs(), + _logStream(&std::cout), + _numErrors(0), + _includerCallback(TextTemplate::loadFile) { + _paths.push_back(""); +} + +const TextTemplatePointer TextTemplate::Config::addInclude(const ConfigPointer& config, const char* include) { + if (!config) { + return TextTemplatePointer(); + } + + TextTemplatePointer included = config->findInclude(include); + if (included) { + return included; + } + + // INcluded doest exist yet so let's try to create it + String includeStream; + if (config->_includerCallback(config, include, includeStream)) { + // ok, then create a new Template on the include file with this as lib + included = TextTemplatePointer(new TextTemplate(include, config)); + + std::stringstream src(includeStream); + + int nbErrors = included->parse(src); + if (nbErrors > 0) { + included->logError(included->_root, "File failed to parse, not included"); + return TextTemplatePointer(); + } + config->_includes.insert(Includes::value_type(include, included)); + return included; + } + + return TextTemplatePointer(); +} + +const TextTemplatePointer TextTemplate::Config::findInclude(const char* include) { + Includes::iterator it = _includes.find(String(include)); + if (it != _includes.end()) { + return (*it).second; + } else { + return TextTemplatePointer(); + } +} + +void TextTemplate::Config::addIncludePath(const char* path) { + _paths.push_back(String(path)); +} + +bool TextTemplate::loadFile(const ConfigPointer& config, const char* filename, String& source) { + String s(filename); + String fullfilename; + for (unsigned int i = 0; i < config->_paths.size(); i++) { + fullfilename = config->_paths[i] + s; + { + std::ifstream ifs; + ifs.open(fullfilename.c_str()); + if (ifs.is_open()) { + std::string str((std::istreambuf_iterator(ifs)), std::istreambuf_iterator()); + source = str; + ifs.close(); + return (source.length() > 0); + } + } + } + + return false; +} + +//----------------------------------------------------------------------------- + +TextTemplate::Funcs::Funcs() : + _funcs() { +} + +TextTemplate::Funcs::~Funcs() { +} + + +const BlockPointer TextTemplate::Funcs::findFunc(const char* func) { + map::iterator it = _funcs.find(String(func)); + if (it != _funcs.end()) { + return (*it).second; + } else { + return BlockPointer(); + } +} + +const BlockPointer TextTemplate::Funcs::addFunc(const char* func, const BlockPointer& funcBlock) { + BlockPointer included = findFunc(func); + if (! included) { + _funcs.insert(map::value_type(func, funcBlock)); + } + return included; +} + +//----------------------------------------------------------------------------- + +void TextTemplate::Block::addNewBlock(const Pointer& parent, const Pointer& block) { + if (parent) { + parent->blocks.push_back(block); + block->parent = parent; + } +} + +const BlockPointer& TextTemplate::Block::getCurrentBlock(const Pointer& block) { + if ((block) && block->command.isBlockEnd()) { + return block->parent; + } else { + return block; + } +} + +//----------------------------------------------------------------------------- + +void TextTemplate::logError(const Block::Pointer& block, const char* fmt, ...) { + va_list argp; + va_start(argp, fmt); + + char buff[256]; + sprintf(buff, fmt, argp); + + _numErrors++; + log() << block->sourceName << " Error >>" << buff << std::endl; + + int level = 1; + displayTree(std::cerr, level); + +} + +bool TextTemplate::grabUntilBeginTag(std::istream* str, std::string& grabbed, Tag::Type& tagType) { + std::stringstream dst; + while (!str->eof()) { + + std::string datatoken; + getline((*str), datatoken, Tag::BEGIN); + dst << datatoken; + + char next = str->peek(); + if (next == Tag::VAR) { + tagType = Tag::VARIABLE; + grabbed = dst.str(); + str->get(); // skip tag char + return true; + } else if (next == Tag::COM) { + tagType = Tag::COMMAND; + grabbed = dst.str(); + str->get(); // skip tag char + return true; + } else if (next == Tag::REM) { + tagType = Tag::REMARK; + grabbed = dst.str(); + str->get(); // skip tag char + return true; + } else { + if (!str->eof()) { + // false positive, just found the Tag::BEGIN without consequence + dst << Tag::BEGIN; + // keep searching + } else { + // end of the file finishing with no tag + tagType = Tag::INVALID; + grabbed = dst.str(); + return true; + } + } + } + + return false; +} + +bool TextTemplate::grabUntilEndTag(std::istream* str, std::string& grabbed, Tag::Type& tagType) { + std::stringstream dst; + + // preend char depends on tag type + char preend = Tag::COM; + if (tagType == Tag::VARIABLE) { + preend = Tag::VAR; + } else if (tagType == Tag::REMARK) { + preend = Tag::REM; + } + + while (!str->eof()) { + // looking for the end of the tag means find the next preEnd + std::string datatoken; + getline((*str), datatoken, preend); + char end = str->peek(); + + dst << datatoken; + + // and if the next char is Tag::END then that's it + if (end == Tag::END) { + grabbed = dst.str(); + str->get(); // eat the Tag::END + return true; + } else { + // false positive, keep on searching + dst << preend; + } + } + grabbed = dst.str(); + return false; +} + +bool TextTemplate::stepForward(std::istream* str, std::string& grabbed, std::string& tag, Tag::Type& tagType, Tag::Type& nextTagType) { + if (str->eof()) { + return false; + } + + if (!_steppingStarted) { + _steppingStarted = true; + return grabUntilBeginTag(str, grabbed, nextTagType); + } + + // Read from the last opening Tag::BEGIN captured to the next Tag::END + if (grabUntilEndTag(str, tag, tagType)) { + // skip trailing space and new lines only after Command or Remark tag block + if ((tagType == Tag::COMMAND) || (tagType == Tag::REMARK)) { + while (!str->eof()) { + char c = str->peek(); + if ((c== ' ') || (c=='\t') || (c=='\n')) { + str->get(); + } else { + break; + } + } + } + + grabUntilBeginTag(str, grabbed, nextTagType); + /*if (grabbed.empty()) { + grabbed += ' '; + }*/ + } + + return true; //hasElement; +} + +const BlockPointer TextTemplate::processStep(const BlockPointer& block, std::string& grabbed, std::string& tag, Tag::Type& tagType) { + switch (tagType) { + case Tag::INVALID: + block->ostr << grabbed; + return block; + break; + case Tag::VARIABLE: + return processStepVar(block, grabbed, tag); + break; + case Tag::COMMAND: + return processStepCommand(block, grabbed, tag); + break; + case Tag::REMARK: + return processStepRemark(block, grabbed, tag); + break; + } + + logError(block, "Invalid tag"); + return block; +} + +bool TextTemplate::grabFirstToken(String& src, String& token, String& reminder) { + bool goOn = true; + std::string::size_type i = 0; + while (goOn && (i < src.length())) { + char c = src[i]; + if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || (c == '_') || (c == '.') || (c == '[') || (c == ']')) { + token += c; + } else { + if (!token.empty()) { + reminder = src.substr(i); + return true; + } + } + i++; + } + + return (!token.empty()); +} + +bool TextTemplate::convertExpressionToArguments(String& src, std::vector< String >& arguments) { + std::stringstream str(src); + String token; + + while (!str.eof()) { + str >> token; + if (!str.fail()) { + arguments.push_back(token); + } + } + + return true; +} + +bool TextTemplate::convertExpressionToDefArguments(String& src, std::vector< String >& arguments) { + if (src.empty()) { + return false; + } + + std::stringstream argstr(src); + std::stringstream dest; + bool inVar = false; + while (!argstr.eof()) { + // parse the value of a var, try to find a VAR, so look for the pattern BEGIN,VAR ... VAR,END + String token; + char tag; + if (!inVar) { + getline(argstr, token, Tag::BEGIN); + dest << token; + tag = argstr.peek(); + } else { + getline(argstr, token, Tag::END); + dest << token; + tag = token.back(); + } + + if (tag == Tag::VAR) { + if (!inVar) { + // real var coming: + arguments.push_back(dest.str()); + inVar = true; + } else { + // real var over + arguments.push_back(dest.str()); + inVar = false; + } + } else { + if (argstr.eof()) { + arguments.push_back(dest.str()); + } else { + // put back the tag char stolen + dest << (!inVar ? Tag::BEGIN : Tag::END); + } + } + } + + return true; +} + +bool TextTemplate::convertExpressionToFuncArguments(String& src, std::vector< String >& arguments) { + if (src.empty()) { + return false; + } + std::stringstream str_src(src); + String params; + getline(str_src, params, '('); + getline(str_src, params, ')'); + if (params.empty()) { + return false; + } + + std::stringstream str(params); + String token; + int nbTokens = 0; + while (!str.eof()) { + char c = str.peek(); + if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || (c == '_') || (c == '.') || (c == Tag::VAR) || (c == '[') || (c == ']')) { + token += c; + } else if (c == ',') { + if (!token.empty()) { + arguments.push_back(token); + nbTokens++; + } + token.clear(); + } + + str.get(); + } + + if (token.size()) { + arguments.push_back(token); + nbTokens++; + } + + return (nbTokens > 0); +} + +const BlockPointer TextTemplate::processStepVar(const BlockPointer& block, String& grabbed, String& tag) { + // then look at the define + String var = tag; + String varName; + String val; + + if (grabFirstToken(var, varName, val)) { + if (!varName.empty()) { + BlockPointer parent = Block::getCurrentBlock(block); + + // Add a new BLock + BlockPointer newBlock = BlockPointer(new Block(_root->sourceName)); + (newBlock->ostr) << grabbed; + + newBlock->command.type = Command::VAR; + + newBlock->command.arguments.push_back(varName); + + if (!val.empty()) { + convertExpressionToFuncArguments(val, newBlock->command.arguments); + } + + Block::addNewBlock(parent, newBlock); + + // dive in the new block + return newBlock; + } + } + + return block; +} + +const BlockPointer TextTemplate::processStepCommand(const BlockPointer& block, String& grabbed, String& tag) { + // Grab the command name + String command = tag; + String commandName; + + if (grabFirstToken(command, commandName, command)) { + if (commandName.compare("def") == 0) { + return processStepDef(block, grabbed, command); + } else if (commandName.compare("if") == 0) { + return processStepCommandIf(block, grabbed, command); + } else if (commandName.compare("endif") == 0) { + return processStepCommandEndIf(block, grabbed, command); + } else if (commandName.compare("else") == 0) { + return processStepCommandElse(block, grabbed, command); + } else if (commandName.compare("elif") == 0) { + return processStepCommandElif(block, grabbed, command); + } else if (commandName.compare("include") == 0) { + return processStepInclude(block, grabbed, command); + } else if (commandName.compare("func") == 0) { + return processStepFunc(block, grabbed, command); + } else if (commandName.compare("endfunc") == 0) { + return processStepEndFunc(block, grabbed, command); + } + } + + return block; +} + +const BlockPointer TextTemplate::processStepDef(const BlockPointer& block, String& grabbed, String& def) { + // then look at the define + String varName; + String val; + + if (!grabFirstToken(def, varName, val)) { + logError(block, "Invalid Var name in a tag"); + return block; + } + + BlockPointer parent = Block::getCurrentBlock(block); + + // Add a new BLock + BlockPointer newBlock = BlockPointer(new Block(_root->sourceName)); + (newBlock->ostr) << grabbed; + + newBlock->command.type = Command::DEF; + newBlock->command.arguments.push_back(varName); + if (! val.empty()) { + // loose first character which should be a white space + val = val.substr(val.find_first_not_of(' ')); + convertExpressionToDefArguments(val, newBlock->command.arguments); + } + + Block::addNewBlock(parent, newBlock); + + // dive in the new block + return newBlock; +} + + +const BlockPointer TextTemplate::processStepCommandIf(const BlockPointer& block, String& grabbed, String& expression) { + BlockPointer parent = Block::getCurrentBlock(block); + + // Add a new BLock depth + BlockPointer newIfBlock = BlockPointer(new Block(_root->sourceName)); + newIfBlock->command.type = Command::IFBLOCK; + + Block::addNewBlock(parent, newIfBlock); + + BlockPointer newBlock = BlockPointer(new Block(_root->sourceName)); + (newBlock->ostr) << grabbed; + + newBlock->command.type = Command::IF; + convertExpressionToArguments(expression, newBlock->command.arguments); + + Block::addNewBlock(newIfBlock, newBlock); + + // dive in the new If branch + return newBlock; +} + +const BlockPointer TextTemplate::processStepCommandEndIf(const BlockPointer& block, String& grabbed, String& expression) { + BlockPointer parent = Block::getCurrentBlock(block); + + // are we in a if block ? + if ((parent->command.type == Command::IF) + || (parent->command.type == Command::ELIF) + || (parent->command.type == Command::ELSE)) { + BlockPointer newBlock = BlockPointer(new Block(_root->sourceName)); + (newBlock->ostr) << grabbed; + + newBlock->command.type = Command::ENDIF; + newBlock->command.arguments.push_back(expression); + + Block::addNewBlock(parent->parent->parent, newBlock); + + return newBlock; + } else { + logError(block, "Invalid block, not in a block"); + return block; + } + + return block; +} + +const BlockPointer TextTemplate::processStepCommandElse(const BlockPointer& block, String& grabbed, String& expression) { + BlockPointer parent = Block::getCurrentBlock(block); + + // are we in a if block ? + if ((parent->command.type == Command::IF) + || (parent->command.type == Command::ELIF)) { + // All good go back to the IfBlock + parent = parent->parent; + + // Add a new BLock depth + BlockPointer newBlock = BlockPointer(new Block(_root->sourceName)); + newBlock->ostr << grabbed; + newBlock->command.type = Command::ELSE; + newBlock->command.arguments.push_back(expression); + + Block::addNewBlock(parent, newBlock); + + // dive in the new block + return newBlock; + + } else if ((block)->command.type == Command::ELSE) { + logError(block, "Invalid block, in a block but after a block"); + return block; + } else { + logError(block, "Invalid block, not in a block"); + return block; + } +} + +const BlockPointer TextTemplate::processStepCommandElif(const BlockPointer& block, String& grabbed, String& expression) { + BlockPointer parent = Block::getCurrentBlock(block); + + // are we in a if block ? + if ((parent->command.type == Command::IF) + || (parent->command.type == Command::ELIF)) { + // All good go back to the IfBlock + parent = parent->parent; + + // Add a new BLock depth + BlockPointer newBlock = BlockPointer(new Block(_root->sourceName)); + (newBlock->ostr) << grabbed; + + newBlock->command.type = Command::ELIF; + convertExpressionToArguments(expression, newBlock->command.arguments); + + Block::addNewBlock(parent, newBlock); + + // dive in the new block + return newBlock; + + } else if (parent->command.type == Command::ELSE) { + logError(block, "Invalid block, in a block but after a block"); + return block; + } else { + logError(block, "Invalid block, not in a block"); + return block; + } +} + +const BlockPointer TextTemplate::processStepRemark(const BlockPointer& block, String& grabbed, String& tag) { + // nothing to do :) + + // no need to think, let's just add the grabbed text + (block->ostr) << grabbed; + + return block; +} + +const BlockPointer TextTemplate::processStepInclude(const BlockPointer& block, String& grabbed, String& include) { + BlockPointer parent = Block::getCurrentBlock(block); + + // Add a new BLock + BlockPointer newBlock = BlockPointer(new Block(_root->sourceName)); + (newBlock->ostr) << grabbed; + + newBlock->command.type = Command::INCLUDE; + convertExpressionToArguments(include, newBlock->command.arguments); + + Block::addNewBlock(parent, newBlock); + + TextTemplatePointer inc = Config::addInclude(_config, newBlock->command.arguments.front().c_str()); + if (!inc) { + logError(newBlock, "Failed to include %s", newBlock->command.arguments.front().c_str()); + } + + // dive in the new block + return newBlock; +} + +const BlockPointer TextTemplate::processStepFunc(const BlockPointer& block, String& grabbed, String& func) { + // then look at the define + String varName; + String var; + + if (!grabFirstToken(func, varName, var)) { + logError(block, "Invalid func name <%s> in a block", func.c_str()); + return block; + } + + + // DOes the func already exists ? + if (_config->_funcs.findFunc(varName.c_str())) { + logError(block, "Declaring a new func named <%s> already exists", func.c_str()); + return block; + } + + BlockPointer parent = Block::getCurrentBlock(block); + + // Add a new BLock + BlockPointer newBlock = BlockPointer(new Block(_root->sourceName)); + (newBlock->ostr) << grabbed; + + newBlock->command.type = Command::FUNC; + newBlock->command.arguments.push_back(varName); + convertExpressionToFuncArguments(var, newBlock->command.arguments); + + _config->_funcs.addFunc(varName.c_str(), newBlock); + + Block::addNewBlock(parent, newBlock); + + // dive in the new block + return newBlock; +} + +const BlockPointer TextTemplate::processStepEndFunc(const BlockPointer& block, String& grabbed, String& tag) { + BlockPointer parent = Block::getCurrentBlock(block); + + // are we in a func block ? + if (parent->command.type == Command::FUNC) { + // Make sure the FUnc has been declared properly + BlockPointer funcBlock = _config->_funcs.findFunc(parent->command.arguments.front().c_str()); + if (funcBlock != parent) { + logError(block, "Mismatching blocks"); + return BlockPointer(); + } + + // Everything is cool , so let's unplugg the FUnc block from this tree and just put the EndFunc block + + BlockPointer newBlock = BlockPointer(new Block(_root->sourceName)); + (newBlock->ostr) << grabbed; + + newBlock->command.type = Command::ENDFUNC; + convertExpressionToArguments(tag, newBlock->command.arguments); + + newBlock->parent = parent->parent; + + parent->parent->blocks.back() = newBlock; + + parent->parent = 0; + + // dive in the new block + return newBlock; + } else { + logError(block, "Invalid block, not in a block"); + return BlockPointer(); + } + + return block; +} + +//----------------------------------------------------------------------------- + +TextTemplate::TextTemplate(const String& name, const ConfigPointer& externalConfig) : + _config(externalConfig), + _root(new Block(name)), + _numErrors(0), + _steppingStarted(false) { +} + +TextTemplate::~TextTemplate() { +} + +int TextTemplate::scribe(std::ostream& dst, std::istream& src, Vars& vars) { + int nbErrors = parse(src); + + if (nbErrors == 0) { + return generate(dst, vars); + } + return nbErrors; +} + +int TextTemplate::generateTree(std::ostream& dst, const BlockPointer& block, Vars& vars) { + BlockPointer newCurrentBlock; + int numPasses = evalBlockGeneration(dst, block, vars, newCurrentBlock); + for (int passNum= 0; passNum < numPasses; passNum++) { + dst << newCurrentBlock->ostr.str(); + + for (auto child : newCurrentBlock->blocks) { + generateTree(dst, child, vars); + } + } + + return _numErrors; +} + +int TextTemplate::evalBlockGeneration(std::ostream& dst, const BlockPointer& block, Vars& vars, BlockPointer& branch) { + switch (block->command.type) { + case Command::BLOCK: { + branch = block; + return 1; + } + break; + case Command::VAR: { + Vars::iterator it = vars.find(block->command.arguments.front()); + if (it != vars.end()) { + dst << (*it).second; + } else { + BlockPointer funcBlock = _config->_funcs.findFunc(block->command.arguments.front().c_str()); + if (funcBlock) { + // before diving in the func tree, let's modify the vars with the local defs: + int nbParams = std::min(block->command.arguments.size(), funcBlock->command.arguments.size()); + std::vector< String > paramCache; + paramCache.push_back(""); + String val; + for (int i = 1; i < nbParams; i++) { + val = block->command.arguments[i]; + if ((val[0] == Tag::VAR) && (val[val.length()-1] == Tag::VAR)) { + val = val.substr(1, val.length()-2); + Vars::iterator it = vars.find(val); + if (it != vars.end()) { + val = (*it).second; + } + } + + Vars::iterator it = vars.find(funcBlock->command.arguments[i]); + if (it != vars.end()) { + paramCache.push_back((*it).second); + (*it).second = val; + } else { + vars.insert(Vars::value_type(funcBlock->command.arguments[i], val)); + paramCache.push_back(""); + } + } + + generateTree(dst, funcBlock, vars); + + for (int i = 1; i < nbParams; i++) { + vars[ funcBlock->command.arguments[i] ] = paramCache[i]; + } + } + } + branch = block; + return 1; + } + break; + case Command::IFBLOCK: { + // ok, go through the branches and pick the first one that goes + for (auto child: block->blocks) { + int numPasses = evalBlockGeneration(dst, child, vars, branch); + if (numPasses > 0) { + return numPasses; + } + } + } + break; + case Command::IF: + case Command::ELIF: { + if (!block->command.arguments.empty()) { + // Just one argument means check for the var beeing defined + if (block->command.arguments.size() == 1) { + Vars::iterator it = vars.find(block->command.arguments.front()); + if (it != vars.end()) { + branch = block; + return 1; + } + } else if (block->command.arguments.size() == 2) { + if (block->command.arguments[0].compare("not") == 0) { + Vars::iterator it = vars.find(block->command.arguments[1]); + if (it == vars.end()) { + branch = block; + return 1; + } + } + } else if (block->command.arguments.size() == 3) { + if (block->command.arguments[1].compare("and") == 0) { + Vars::iterator itL = vars.find(block->command.arguments[0]); + Vars::iterator itR = vars.find(block->command.arguments[2]); + if ((itL != vars.end()) && (itR != vars.end())) { + branch = block; + return 1; + } + } else if (block->command.arguments[1].compare("or") == 0) { + Vars::iterator itL = vars.find(block->command.arguments[0]); + Vars::iterator itR = vars.find(block->command.arguments[2]); + if ((itL != vars.end()) || (itR != vars.end())) { + branch = block; + return 1; + } + } else if (block->command.arguments[1].compare("==") == 0) { + Vars::iterator itL = vars.find(block->command.arguments[0]); + if (itL != vars.end()) { + if ((*itL).second.compare(block->command.arguments[2]) == 0) { + branch = block; + return 1; + } + } + } + } + + } + return 0; + } + break; + case Command::ELSE: { + branch = block; + return 1; + } + break; + case Command::ENDIF: { + branch = block; + return 1; + } + break; + case Command::DEF: { + if (block->command.arguments.size()) { + // THe actual value of the var defined sneeds to be evaluated: + String val; + for (int t = 1; t < block->command.arguments.size(); t++) { + // detect if a param is a var + int len = block->command.arguments[t].length(); + if ((block->command.arguments[t][0] == Tag::VAR) + && (block->command.arguments[t][len-1] == Tag::VAR)) { + String var = block->command.arguments[t].substr(1, len-2); + Vars::iterator it = vars.find(var); + if (it != vars.end()) { + val += (*it).second; + } + } else { + val += block->command.arguments[t]; + } + } + + Vars::iterator it = vars.find(block->command.arguments.front()); + if (it == vars.end()) { + vars.insert(Vars::value_type(block->command.arguments.front(), val)); + } else { + (*it).second = val; + } + + branch = block; + return 1; + } else { + branch = block; + return 0; + } + } + break; + + case Command::INCLUDE: { + TextTemplatePointer include = _config->findInclude(block->command.arguments.front().c_str()); + if (include && !include->_root->blocks.empty()) { + if (&include->_root) { + generateTree(dst, include->_root, vars); + } + } + + branch = block; + return 1; + } + break; + + case Command::FUNC: { + branch = block; + return 1; + } + break; + + case Command::ENDFUNC: { + branch = block; + return 1; + } + break; + + default: { + } + } + + return 0; +} + + +int TextTemplate::parse(std::istream& src) { + _root->command.type = Command::BLOCK; + BlockPointer currentBlock = _root; + _numErrors = 0; + + // First Parse the input file + int nbLoops = 0; + bool goOn = true; + Tag::Type tagType = Tag::INVALID; + Tag::Type nextTagType = Tag::INVALID; + while (goOn) { + std::string data; + std::string tag; + if (stepForward(&src, data, tag, tagType, nextTagType)) { + currentBlock = processStep(currentBlock, data, tag, tagType); + } else { + goOn = false; + } + + tagType = nextTagType; + nbLoops++; + } + + return _numErrors; +} + +int TextTemplate::generate(std::ostream& dst, Vars& vars) { + return generateTree(dst, _root, vars); +} + +void TextTemplate::displayTree(std::ostream& dst, int& level) const { + Block::displayTree(_root, dst, level); +} + +void TextTemplate::Block::displayTree(const BlockPointer& block, std::ostream& dst, int& level) { + String tab(level * 2, ' '); + + const String BLOCK_TYPE_NAMES[] = { + "VAR", + "BLOCK", + "FUNC", + "ENDFUNC", + "IFBLOCK", + "IF", + "ELIF", + "ELSE", + "ENDIF", + "FOR", + "ENDFOR", + "INCLUDE", + "DEF" + }; + + dst << tab << "{ " << BLOCK_TYPE_NAMES[block->command.type] << ":"; + if (!block->command.arguments.empty()) { + for (auto arg: block->command.arguments) { + dst << " " << arg; + } + } + dst << std::endl; + + level++; + for (auto sub: block->blocks) { + displayTree(sub, dst, level); + } + level--; + + dst << tab << "}" << std::endl; +} + +void TextTemplate::Config::displayTree(std::ostream& dst, int& level) const { + String tab(level * 2, ' '); + + level++; + dst << tab << "Includes:" << std::endl; + for (auto inc: _includes) { + dst << tab << tab << inc.first << std::endl; + inc.second->displayTree(dst, level); + } + dst << tab << "Funcs:" << std::endl; + for (auto func: _funcs._funcs) { + dst << tab << tab << func.first << std::endl; + TextTemplate::Block::displayTree( func.second, dst, level); + } + level--; +} diff --git a/tools/scribe/src/TextTemplate.h b/tools/scribe/src/TextTemplate.h new file mode 100755 index 0000000000..54580aed09 --- /dev/null +++ b/tools/scribe/src/TextTemplate.h @@ -0,0 +1,205 @@ + +// +// TextTemplate.cpp +// tools/shaderScribe/src +// +// Created by Sam Gateau on 12/15/2014. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +#ifndef hifi_TEXT_TEMPLATE_H +#define hifi_TEXT_TEMPLATE_H + +#include +#include +#include +#include +#include +#include +#include + +class TextTemplate { +public: + typedef std::shared_ptr< TextTemplate > Pointer; + typedef std::string String; + typedef std::vector< String > StringVector; + typedef std::map< String, String > Vars; + typedef std::map< String, TextTemplate::Pointer > Includes; + + class Tag { + public: + enum Type { + VARIABLE = 0, + COMMAND, + REMARK, + INVALID = -1, + }; + + static const char BEGIN = '<'; + static const char END = '>'; + + static const char VAR = '$'; + static const char COM = '@'; + static const char REM = '!'; + }; + + class Command { + public: + typedef std::vector< Command > vector; + + enum Type { + VAR = 0, + BLOCK, + FUNC, + ENDFUNC, + IFBLOCK, + IF, + ELIF, + ELSE, + ENDIF, + FOR, + ENDFOR, + INCLUDE, + DEF, + }; + + Type type; + std::vector< String > arguments; + + bool isBlockEnd() { + switch (type) { + case ENDFUNC: + case ENDIF: + case ENDFOR: + case INCLUDE: + case DEF: + case VAR: + return true; + default: + return false; + } + } + }; + + class Block { + public: + typedef std::shared_ptr Pointer; + typedef std::vector< Block::Pointer > Vector; + + Block::Pointer parent; + Command command; + Vector blocks; + std::stringstream ostr; + + String sourceName; + + Block(const String& sourceFilename) : + sourceName(sourceFilename) + {} + + static void addNewBlock(const Block::Pointer& parent, const Block::Pointer& block); + static const Block::Pointer& getCurrentBlock(const Block::Pointer& block); + + static void displayTree(const Block::Pointer& block, std::ostream& dst, int& level); + }; + + class Funcs { + public: + typedef std::map< String, Block::Pointer > map; + + Funcs(); + ~Funcs(); + + const Block::Pointer findFunc(const char* func); + const Block::Pointer addFunc(const char* func, const Block::Pointer& root); + + map _funcs; + protected: + }; + + class Config { + public: + typedef std::shared_ptr< Config > Pointer; + typedef bool (*IncluderCallback) (const Config::Pointer& config, const char* filename, String& source); + + Includes _includes; + Funcs _funcs; + std::ostream* _logStream; + int _numErrors; + IncluderCallback _includerCallback; + StringVector _paths; + + Config(); + + static const TextTemplate::Pointer addInclude(const Config::Pointer& config, const char* include); + const TextTemplate::Pointer findInclude(const char* include); + + void addIncludePath(const char* path); + + void displayTree(std::ostream& dst, int& level) const; + }; + + static bool loadFile(const Config::Pointer& config, const char* filename, String& source); + + TextTemplate(const String& name, const Config::Pointer& config = Config::Pointer(new Config())); + ~TextTemplate(); + + // Scibe does all the job of parsing an inout template stream and then gneerating theresulting stream using the vars + int scribe(std::ostream& dst, std::istream& src, Vars& vars); + + int parse(std::istream& src); + int generate(std::ostream& dst, Vars& vars); + + const Config::Pointer config() { return _config; } + + void displayTree(std::ostream& dst, int& level) const; + +protected: + Config::Pointer _config; + Block::Pointer _root; + int _numErrors; + bool _steppingStarted; + + bool grabUntilBeginTag(std::istream* str, String& grabbed, Tag::Type& tagType); + bool grabUntilEndTag(std::istream* str, String& grabbed, Tag::Type& tagType); + + bool stepForward(std::istream* str, String& grabbed, String& tag, Tag::Type& tagType, Tag::Type& nextTagType); + + bool grabFirstToken(String& src, String& token, String& reminder); + bool convertExpressionToArguments(String& src, std::vector< String >& arguments); + bool convertExpressionToDefArguments(String& src, std::vector< String >& arguments); + bool convertExpressionToFuncArguments(String& src, std::vector< String >& arguments); + + // Filter between var, command or comments + const Block::Pointer processStep(const Block::Pointer& block, String& grabbed, String& tag, Tag::Type& tagType); + const Block::Pointer processStepVar(const Block::Pointer& block, String& grabbed, String& tag); + const Block::Pointer processStepCommand(const Block::Pointer& block, String& grabbed, String& tag); + const Block::Pointer processStepRemark(const Block::Pointer& block, String& grabbed, String& tag); + + // Define command + const Block::Pointer processStepDef(const Block::Pointer& block, String& grabbed, String& tag); + + // If commands + const Block::Pointer processStepCommandIf(const Block::Pointer& block, String& grabbed, String& expression); + const Block::Pointer processStepCommandEndIf(const Block::Pointer& block, String& grabbed, String& expression); + const Block::Pointer processStepCommandElif(const Block::Pointer& block, String& grabbed, String& expression); + const Block::Pointer processStepCommandElse(const Block::Pointer& block, String& grabbed, String& expression); + + // Include command + const Block::Pointer processStepInclude(const Block::Pointer& block, String& grabbed, String& tag); + + // Function command + const Block::Pointer processStepFunc(const Block::Pointer& block, String& grabbed, String& tag); + const Block::Pointer processStepEndFunc(const Block::Pointer& block, String& grabbed, String& tag); + + // Generation + int generateTree(std::ostream& dst, const Block::Pointer& block, Vars& vars); + int evalBlockGeneration(std::ostream& dst, const Block::Pointer& block, Vars& vars, Block::Pointer& branch); + + // Errors + std::ostream& log() { return (* _config->_logStream); } + void logError(const Block::Pointer& block, const char* error, ...); +}; + +#endif \ No newline at end of file diff --git a/tools/scribe/src/main.cpp b/tools/scribe/src/main.cpp new file mode 100755 index 0000000000..89e355de68 --- /dev/null +++ b/tools/scribe/src/main.cpp @@ -0,0 +1,226 @@ +// +// main.cpp +// tools/shaderScribe/src +// +// Created by Sam Gateau on 12/15/2014. +// Copyright 2013 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html + + +#include "TextTemplate.h" + +#include +#include +#include + +using namespace std; + +int main (int argc, char** argv) { + // process the command line arguments + std::vector< std::string > inputs; + + std::string srcFilename; + std::string destFilename; + std::string targetName; + TextTemplate::Vars vars; + + std::string lastVarName; + bool listVars = false; + bool showParseTree = false; + bool makeCplusplus = false; + + TextTemplate::Config::Pointer config(new TextTemplate::Config()); + + enum Mode { + READY = 0, + GRAB_OUTPUT, + GRAB_VAR_NAME, + GRAB_VAR_VALUE, + GRAB_INCLUDE_PATH, + GRAB_TARGET_NAME, + EXIT, + } mode = READY; + for (int ii = 1; (mode != EXIT) && (ii < argc); ii++) { + inputs.push_back(argv[ii]); + + switch (mode) { + case READY: { + if (inputs.back() == "-o") { + mode = GRAB_OUTPUT; + } else if (inputs.back() == "-tn") { + mode = GRAB_TARGET_NAME; + } else if (inputs.back() == "-D") { + mode = GRAB_VAR_NAME; + } else if (inputs.back() == "-I") { + mode = GRAB_INCLUDE_PATH; + } else if (inputs.back() == "-listvars") { + listVars = true; + mode = READY; + } else if (inputs.back() == "-showParseTree") { + showParseTree = true; + mode = READY; + } else if (inputs.back() == "-c++") { + makeCplusplus = true; + mode = READY; + } else { + // just grabbed the source filename, stop parameter parsing + srcFilename = inputs.back(); + mode = EXIT; + } + } + break; + + case GRAB_OUTPUT: { + destFilename = inputs.back(); + mode = READY; + } + break; + + case GRAB_TARGET_NAME: { + targetName = inputs.back(); + mode = READY; + } + break; + + case GRAB_VAR_NAME: { + // grab first the name of the var + lastVarName = inputs.back(); + mode = GRAB_VAR_VALUE; + } + break; + case GRAB_VAR_VALUE: { + // and then the value + vars.insert(TextTemplate::Vars::value_type(lastVarName, inputs.back())); + + mode = READY; + } + break; + + case GRAB_INCLUDE_PATH: { + config->addIncludePath(inputs.back().c_str()); + mode = READY; + } + break; + + case EXIT: { + // THis shouldn't happen + } + break; + } + } + + if (srcFilename.empty()) { + cerr << "Usage: shaderScribe [OPTION]... inputFilename" << endl; + cerr << "Where options include:" << endl; + cerr << " -o filename: Send output to filename rather than standard output." << endl; + cerr << " -tn targetName: Set the targetName used, if not defined use the output filename 'name' and if not defined use the inputFilename 'name'" << endl; + cerr << " -I include_directory: Declare a directory to be added to the includes search pool." << endl; + cerr << " -D varname varvalue: Declare a var used to generate the output file." << endl; + cerr << " varname and varvalue must be made of alpha numerical characters with no spaces." << endl; + cerr << " -listvars : Will list the vars name and value in the standard output." << endl; + cerr << " -showParseTree : Draw the tree obtained while parsing the source" << endl; + cerr << " -c++ : Generate a c++ header file containing the output file stream stored as a char[] variable" << endl; + return 0; + } + + // Define targetName: if none, get destFilenmae, if none get srcFilename + if (targetName.empty()) { + if (destFilename.empty()) { + targetName = srcFilename; + } else { + targetName = destFilename; + } + } + // no clean it to have just a descent c var name + if (!targetName.empty()) + { + // trim anything before '/' or '\' + targetName = targetName.substr(targetName.find_last_of('/') + 1); + targetName = targetName.substr(targetName.find_last_of('\\') + 1); + + // trim anything after '.' + targetName = targetName.substr(0, targetName.find_first_of('.')); + } + + // Add built in vars + time_t endTime = chrono::system_clock::to_time_t(chrono::system_clock::now()); + std::string endTimStr(ctime(&endTime)); + vars["_SCRIBE_DATE"] = endTimStr.substr(0, endTimStr.length() - 1); + + // List vars? + if (listVars) { + cerr << "Vars:" << endl; + for (auto v : vars) { + cerr << " " << v.first << " = " << v.second << endl; + } + } + + // Open up source + std::fstream srcStream; + srcStream.open(srcFilename, std::fstream::in); + if (!srcStream.is_open()) { + cerr << "Failed to open source file <" << srcFilename << ">" << endl; + return 0; + } + + + TextTemplate::Pointer scribe(new TextTemplate(srcFilename, config)); + + // ready to parse and generate + std::ostringstream destStringStream; + int numErrors = scribe->scribe(destStringStream, srcStream, vars); + if (numErrors) { + cerr << "Scribe " << srcFilename << "> failed: " << numErrors << " errors." << endl; + return 0; + }; + + + if (showParseTree) { + int level = 1; + cerr << "Config trees:" << std::endl; + config->displayTree(cerr, level); + + cerr << srcFilename << " tree:" << std::endl; + scribe->displayTree(cerr, level); + } + + std::ostringstream targetStringStream; + if (makeCplusplus) { + targetStringStream << "// File generated by Scribe " << vars["_SCRIBE_DATE"] << std::endl; + + targetStringStream << "#ifndef scribe_" << targetName << "_h" << std::endl; + targetStringStream << "#define scribe_" << targetName << "_h" << std::endl << std::endl; + + targetStringStream << "const char " << targetName << "[] = {\n\""; + + std::stringstream destStringStreamAgain(destStringStream.str()); + while (!destStringStreamAgain.eof()) { + std::string line; + std::getline(destStringStreamAgain, line); + targetStringStream << line << " \\n\\\n"; + } + targetStringStream << "\"};" << std::endl << std::endl; + + targetStringStream << "#endif" << std::endl; + } else { + targetStringStream << destStringStream.str(); + } + + // Destination stream + if (!destFilename.empty()) { + std::fstream destFileStream; + destFileStream.open(destFilename, std::fstream::out); + if (!destFileStream.is_open()) { + cerr << "Scribe output file " << destFilename << "> failed to open." << endl; + return 0; + } + + destFileStream << targetStringStream.str(); + } else { + cerr << targetStringStream.str(); + } + + return 0; +} From bc836413005e6aa93dd6fcf9491f013f718b7d65 Mon Sep 17 00:00:00 2001 From: Sam Gateau Date: Mon, 22 Dec 2014 14:05:09 -0800 Subject: [PATCH 241/258] add comments to Transform.h --- libraries/shared/src/Transform.h | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/libraries/shared/src/Transform.h b/libraries/shared/src/Transform.h index 4adeccb46f..e08f00c0ac 100644 --- a/libraries/shared/src/Transform.h +++ b/libraries/shared/src/Transform.h @@ -63,20 +63,20 @@ public: void setIdentity(); const Vec3& getTranslation() const; - void setTranslation(const Vec3& translation); - void preTranslate(const Vec3& translation); - void postTranslate(const Vec3& translation); + void setTranslation(const Vec3& translation); // [new this] = [translation] * [this.rotation] * [this.scale] + void preTranslate(const Vec3& translation); // [new this] = [translation] * [this] + void postTranslate(const Vec3& translation); // [new this] = [this] * [translation] equivalent to glTranslate const Quat& getRotation() const; - void setRotation(const Quat& rotation); - void preRotate(const Quat& rotation); - void postRotate(const Quat& rotation); + void setRotation(const Quat& rotation); // [new this] = [this.translation] * [rotation] * [this.scale] + void preRotate(const Quat& rotation); // [new this] = [rotation] * [this] + void postRotate(const Quat& rotation); // [new this] = [this] * [rotation] equivalent to glRotate const Vec3& getScale() const; void setScale(float scale); - void setScale(const Vec3& scale); - void postScale(float scale); - void postScale(const Vec3& scale); + void setScale(const Vec3& scale); // [new this] = [this.translation] * [this.rotation] * [scale] + void postScale(float scale); // [new this] = [this] * [scale] equivalent to glScale + void postScale(const Vec3& scale); // [new this] = [this] * [scale] equivalent to glScale bool isIdentity() const { return (_flags & ~Flags(FLAG_CACHE_INVALID_BITSET)).none(); } bool isTranslating() const { return _flags[FLAG_TRANSLATION]; } From 6b88eaceb568dd88705bb01a028bc7eedbf3ff80 Mon Sep 17 00:00:00 2001 From: Sam Gateau Date: Mon, 22 Dec 2014 15:44:46 -0800 Subject: [PATCH 242/258] FIx typos --- libraries/model/src/model/Geometry.h | 3 +-- tools/scribe/src/TextTemplate.h | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/libraries/model/src/model/Geometry.h b/libraries/model/src/model/Geometry.h index 8f0625ef69..0beaa20a83 100755 --- a/libraries/model/src/model/Geometry.h +++ b/libraries/model/src/model/Geometry.h @@ -63,8 +63,7 @@ public: // Access vertex position value const Vec3& getPos3(Index index) const { return _vertexBuffer.get(index); } - enum Topology - { + enum Topology { POINTS = 0, LINES, LINE_STRIP, diff --git a/tools/scribe/src/TextTemplate.h b/tools/scribe/src/TextTemplate.h index 54580aed09..0a61ae454a 100755 --- a/tools/scribe/src/TextTemplate.h +++ b/tools/scribe/src/TextTemplate.h @@ -202,4 +202,4 @@ protected: void logError(const Block::Pointer& block, const char* error, ...); }; -#endif \ No newline at end of file +#endif From e16da55b1b156150b8d245363d5d2afde78ac544 Mon Sep 17 00:00:00 2001 From: Sam Gateau Date: Mon, 22 Dec 2014 16:02:58 -0800 Subject: [PATCH 243/258] cleaning scribe main and checking naming --- tools/scribe/src/main.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tools/scribe/src/main.cpp b/tools/scribe/src/main.cpp index 89e355de68..e71b21f32b 100755 --- a/tools/scribe/src/main.cpp +++ b/tools/scribe/src/main.cpp @@ -55,7 +55,7 @@ int main (int argc, char** argv) { mode = GRAB_VAR_NAME; } else if (inputs.back() == "-I") { mode = GRAB_INCLUDE_PATH; - } else if (inputs.back() == "-listvars") { + } else if (inputs.back() == "-listVars") { listVars = true; mode = READY; } else if (inputs.back() == "-showParseTree") { @@ -115,11 +115,11 @@ int main (int argc, char** argv) { cerr << "Usage: shaderScribe [OPTION]... inputFilename" << endl; cerr << "Where options include:" << endl; cerr << " -o filename: Send output to filename rather than standard output." << endl; - cerr << " -tn targetName: Set the targetName used, if not defined use the output filename 'name' and if not defined use the inputFilename 'name'" << endl; + cerr << " -t targetName: Set the targetName used, if not defined use the output filename 'name' and if not defined use the inputFilename 'name'" << endl; cerr << " -I include_directory: Declare a directory to be added to the includes search pool." << endl; cerr << " -D varname varvalue: Declare a var used to generate the output file." << endl; cerr << " varname and varvalue must be made of alpha numerical characters with no spaces." << endl; - cerr << " -listvars : Will list the vars name and value in the standard output." << endl; + cerr << " -listVars : Will list the vars name and value in the standard output." << endl; cerr << " -showParseTree : Draw the tree obtained while parsing the source" << endl; cerr << " -c++ : Generate a c++ header file containing the output file stream stored as a char[] variable" << endl; return 0; From 55370477dbcaa9098c0bb1fbccf01bd4e59da615 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Mon, 22 Dec 2014 16:40:19 -0800 Subject: [PATCH 244/258] Remove Application dependency --- interface/src/ui/ModelsBrowser.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/interface/src/ui/ModelsBrowser.cpp b/interface/src/ui/ModelsBrowser.cpp index a39d9b9a19..8c1d90d8b5 100644 --- a/interface/src/ui/ModelsBrowser.cpp +++ b/interface/src/ui/ModelsBrowser.cpp @@ -12,16 +12,19 @@ #include #include #include +#include #include +#include #include +#include +#include +#include #include -#include +#include #include #include -#include "Application.h" - #include "ModelsBrowser.h" const char* MODEL_TYPE_NAMES[] = { "entities", "heads", "skeletons", "attachments" }; From 17ed92cf7ea81c651e531b3cbb867811853a588b Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 23 Dec 2014 10:11:08 -0800 Subject: [PATCH 245/258] fix runaway backup bug --- libraries/octree/src/OctreePersistThread.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/libraries/octree/src/OctreePersistThread.cpp b/libraries/octree/src/OctreePersistThread.cpp index c9dcf82099..d9ebea0c2b 100644 --- a/libraries/octree/src/OctreePersistThread.cpp +++ b/libraries/octree/src/OctreePersistThread.cpp @@ -189,6 +189,9 @@ void OctreePersistThread::backup() { quint64 intervalToBackup = _backupInterval * MSECS_TO_USECS; if (sinceLastBackup > intervalToBackup) { + qDebug() << "Time since last backup [" << sinceLastBackup << "] exceeds backup interval [" + << intervalToBackup << "] doing backup now..."; + struct tm* localTime = localtime(&_lastPersistTime); QString backupFileName; @@ -213,6 +216,8 @@ void OctreePersistThread::backup() { } else { qDebug() << "ERROR in backing up persist file..."; } + + _lastBackup = now; } } } From e105ba61e871b4fb49bacaad3fb022937d906c9f Mon Sep 17 00:00:00 2001 From: Chris Collins Date: Tue, 23 Dec 2014 11:01:25 -0800 Subject: [PATCH 246/258] Fix for model uploading to work Fix for model uploading to work. The deleted elements were causing an error when trying to upload models. --- examples/libraries/modelUploader.js | 12 ++---------- 1 file changed, 2 insertions(+), 10 deletions(-) diff --git a/examples/libraries/modelUploader.js b/examples/libraries/modelUploader.js index d83fc8c16d..7f575a54ef 100644 --- a/examples/libraries/modelUploader.js +++ b/examples/libraries/modelUploader.js @@ -274,19 +274,11 @@ modelUploader = (function () { } } - if (view.string(0, 18) === "Kaydara FBX Binary") { - previousNodeFilename = ""; - - index = 27; - while (index < view.byteLength - 39 && !EOF) { - parseBinaryFBX(); - } - - } else { + readTextFBX(); - } + } function readModel() { From 72cced12a6794e798971c6c138079ea6bf546eed Mon Sep 17 00:00:00 2001 From: ZappoMan Date: Tue, 23 Dec 2014 11:30:32 -0800 Subject: [PATCH 247/258] guards for NULL collisions, possible fix to fountain crash --- libraries/entities/src/EntityCollisionSystem.cpp | 7 +++++++ libraries/entities/src/EntityTreeElement.cpp | 8 ++++++-- 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/libraries/entities/src/EntityCollisionSystem.cpp b/libraries/entities/src/EntityCollisionSystem.cpp index 7669f73c7d..f0ffbefb46 100644 --- a/libraries/entities/src/EntityCollisionSystem.cpp +++ b/libraries/entities/src/EntityCollisionSystem.cpp @@ -144,6 +144,13 @@ void EntityCollisionSystem::updateCollisionWithEntities(EntityItem* entityA) { penetration = collision->_penetration; entityB = static_cast(collision->_extraData); + // The collision _extraData should be a valid entity, but if for some reason + // it's NULL then continue with a warning. + if (!entityB) { + qDebug() << "UNEXPECTED - we have a collision with missing _extraData. Something went wrong down below!"; + continue; // skip this loop pass if the entity is NULL + } + // don't collide entities with unknown IDs, if (!entityB->isKnownID()) { continue; // skip this loop pass if the entity has an unknown ID diff --git a/libraries/entities/src/EntityTreeElement.cpp b/libraries/entities/src/EntityTreeElement.cpp index 05928990d1..55693b6ff9 100644 --- a/libraries/entities/src/EntityTreeElement.cpp +++ b/libraries/entities/src/EntityTreeElement.cpp @@ -585,8 +585,12 @@ bool EntityTreeElement::findShapeCollisions(const Shape* shape, CollisionList& c if (shape != otherCollisionShape && !ignoreForCollisions) { if (ShapeCollider::collideShapes(shape, otherCollisionShape, collisions)) { CollisionInfo* lastCollision = collisions.getLastCollision(); - lastCollision->_extraData = entity; - atLeastOneCollision = true; + if (lastCollision) { + lastCollision->_extraData = entity; + atLeastOneCollision = true; + } else { + qDebug() << "UNEXPECTED - ShapeCollider::collideShapes() returned true, but no lastCollision."; + } } } ++entityItr; From 879c3e2fd078c844585e170cb566acd641a5bd47 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Tue, 23 Dec 2014 12:30:00 -0800 Subject: [PATCH 248/258] Add entity model upload --- interface/src/Application.cpp | 4 + interface/src/Application.h | 1 + interface/src/Menu.cpp | 10 +- interface/src/Menu.h | 1 + interface/src/ModelUploader.cpp | 182 +++++++++++++++++--------------- interface/src/ModelUploader.h | 2 +- 6 files changed, 109 insertions(+), 91 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index bc6c119fe9..67821e5f7f 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -4202,6 +4202,10 @@ void Application::uploadAttachment() { uploadModel(ATTACHMENT_MODEL); } +void Application::uploadEntity() { + uploadModel(ENTITY_MODEL); +} + void Application::openUrl(const QUrl& url) { if (!url.isEmpty()) { if (url.scheme() == HIFI_URL_SCHEME) { diff --git a/interface/src/Application.h b/interface/src/Application.h index 041e5e6b5b..c08e7359ab 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -374,6 +374,7 @@ public slots: void uploadHead(); void uploadSkeleton(); void uploadAttachment(); + void uploadEntity(); void openUrl(const QUrl& url); diff --git a/interface/src/Menu.cpp b/interface/src/Menu.cpp index f0c2a687a4..2147dd9220 100644 --- a/interface/src/Menu.cpp +++ b/interface/src/Menu.cpp @@ -189,10 +189,14 @@ Menu::Menu() : SLOT(toggleAddressBar())); addDisabledActionAndSeparator(fileMenu, "Upload Avatar Model"); - addActionToQMenuAndActionHash(fileMenu, MenuOption::UploadHead, 0, Application::getInstance(), SLOT(uploadHead())); - addActionToQMenuAndActionHash(fileMenu, MenuOption::UploadSkeleton, 0, Application::getInstance(), SLOT(uploadSkeleton())); + addActionToQMenuAndActionHash(fileMenu, MenuOption::UploadHead, 0, + Application::getInstance(), SLOT(uploadHead())); + addActionToQMenuAndActionHash(fileMenu, MenuOption::UploadSkeleton, 0, + Application::getInstance(), SLOT(uploadSkeleton())); addActionToQMenuAndActionHash(fileMenu, MenuOption::UploadAttachment, 0, - Application::getInstance(), SLOT(uploadAttachment())); + Application::getInstance(), SLOT(uploadAttachment())); + addActionToQMenuAndActionHash(fileMenu, MenuOption::UploadEntity, 0, + Application::getInstance(), SLOT(uploadEntity())); addDisabledActionAndSeparator(fileMenu, "Settings"); addActionToQMenuAndActionHash(fileMenu, MenuOption::SettingsImport, 0, this, SLOT(importSettings())); addActionToQMenuAndActionHash(fileMenu, MenuOption::SettingsExport, 0, this, SLOT(exportSettings())); diff --git a/interface/src/Menu.h b/interface/src/Menu.h index 77936e7ac4..27e57983af 100644 --- a/interface/src/Menu.h +++ b/interface/src/Menu.h @@ -482,6 +482,7 @@ namespace MenuOption { const QString TransmitterDrive = "Transmitter Drive"; const QString TurnWithHead = "Turn using Head"; const QString UploadAttachment = "Upload Attachment Model"; + const QString UploadEntity = "Upload Entity Model"; const QString UploadHead = "Upload Head Model"; const QString UploadSkeleton = "Upload Skeleton Model"; const QString UserInterface = "User Interface"; diff --git a/interface/src/ModelUploader.cpp b/interface/src/ModelUploader.cpp index 29d1596809..c400e25246 100644 --- a/interface/src/ModelUploader.cpp +++ b/interface/src/ModelUploader.cpp @@ -55,8 +55,9 @@ static const QString MODEL_URL = "/api/v1/models"; static const QString SETTING_NAME = "LastModelUploadLocation"; -static const int MAX_SIZE = 10 * 1024 * 1024; // 10 MB -static const int MAX_TEXTURE_SIZE = 1024; +static const int BYTES_PER_MEGABYTES = 1024 * 1024; +static const unsigned long MAX_SIZE = 50 * 1024 * BYTES_PER_MEGABYTES; // 50 GB (Virtually remove limit) +static const int MAX_TEXTURE_SIZE = 4096; static const int TIMEOUT = 1000; static const int MAX_CHECK = 30; @@ -590,9 +591,9 @@ bool ModelUploader::addPart(const QFile& file, const QByteArray& contents, const if (_totalSize > MAX_SIZE) { QMessageBox::warning(NULL, QString("ModelUploader::zip()"), - QString("Model too big, over %1 Bytes.").arg(MAX_SIZE), + QString("Model too big, over %1 MB.").arg(MAX_SIZE / BYTES_PER_MEGABYTES), QMessageBox::Ok); - qDebug() << "[Warning] " << QString("Model too big, over %1 Bytes.").arg(MAX_SIZE); + qDebug() << "[Warning] " << QString("Model too big, over %1 MB.").arg(MAX_SIZE / BYTES_PER_MEGABYTES); return false; } qDebug() << "Current model size: " << _totalSize; @@ -613,8 +614,8 @@ ModelPropertiesDialog::ModelPropertiesDialog(ModelType modelType, const QVariant _modelType(modelType), _originalMapping(originalMapping), _basePath(basePath), - _geometry(geometry) { - + _geometry(geometry) +{ setWindowTitle("Set Model Properties"); QFormLayout* form = new QFormLayout(); @@ -629,33 +630,35 @@ ModelPropertiesDialog::ModelPropertiesDialog(ModelType modelType, const QVariant _scale->setMaximum(FLT_MAX); _scale->setSingleStep(0.01); - if (_modelType == ATTACHMENT_MODEL) { - QHBoxLayout* translation = new QHBoxLayout(); - form->addRow("Translation:", translation); - translation->addWidget(_translationX = createTranslationBox()); - translation->addWidget(_translationY = createTranslationBox()); - translation->addWidget(_translationZ = createTranslationBox()); - form->addRow("Pivot About Center:", _pivotAboutCenter = new QCheckBox()); - form->addRow("Pivot Joint:", _pivotJoint = createJointBox()); - connect(_pivotAboutCenter, SIGNAL(toggled(bool)), SLOT(updatePivotJoint())); - _pivotAboutCenter->setChecked(true); - - } else { - form->addRow("Left Eye Joint:", _leftEyeJoint = createJointBox()); - form->addRow("Right Eye Joint:", _rightEyeJoint = createJointBox()); - form->addRow("Neck Joint:", _neckJoint = createJointBox()); - } - if (_modelType == SKELETON_MODEL) { - form->addRow("Root Joint:", _rootJoint = createJointBox()); - form->addRow("Lean Joint:", _leanJoint = createJointBox()); - form->addRow("Head Joint:", _headJoint = createJointBox()); - form->addRow("Left Hand Joint:", _leftHandJoint = createJointBox()); - form->addRow("Right Hand Joint:", _rightHandJoint = createJointBox()); - - form->addRow("Free Joints:", _freeJoints = new QVBoxLayout()); - QPushButton* newFreeJoint = new QPushButton("New Free Joint"); - _freeJoints->addWidget(newFreeJoint); - connect(newFreeJoint, SIGNAL(clicked(bool)), SLOT(createNewFreeJoint())); + if (_modelType != ENTITY_MODEL) { + if (_modelType == ATTACHMENT_MODEL) { + QHBoxLayout* translation = new QHBoxLayout(); + form->addRow("Translation:", translation); + translation->addWidget(_translationX = createTranslationBox()); + translation->addWidget(_translationY = createTranslationBox()); + translation->addWidget(_translationZ = createTranslationBox()); + form->addRow("Pivot About Center:", _pivotAboutCenter = new QCheckBox()); + form->addRow("Pivot Joint:", _pivotJoint = createJointBox()); + connect(_pivotAboutCenter, SIGNAL(toggled(bool)), SLOT(updatePivotJoint())); + _pivotAboutCenter->setChecked(true); + + } else { + form->addRow("Left Eye Joint:", _leftEyeJoint = createJointBox()); + form->addRow("Right Eye Joint:", _rightEyeJoint = createJointBox()); + form->addRow("Neck Joint:", _neckJoint = createJointBox()); + } + if (_modelType == SKELETON_MODEL) { + form->addRow("Root Joint:", _rootJoint = createJointBox()); + form->addRow("Lean Joint:", _leanJoint = createJointBox()); + form->addRow("Head Joint:", _headJoint = createJointBox()); + form->addRow("Left Hand Joint:", _leftHandJoint = createJointBox()); + form->addRow("Right Hand Joint:", _rightHandJoint = createJointBox()); + + form->addRow("Free Joints:", _freeJoints = new QVBoxLayout()); + QPushButton* newFreeJoint = new QPushButton("New Free Joint"); + _freeJoints->addWidget(newFreeJoint); + connect(newFreeJoint, SIGNAL(clicked(bool)), SLOT(createNewFreeJoint())); + } } QDialogButtonBox* buttons = new QDialogButtonBox(QDialogButtonBox::Ok | @@ -683,38 +686,40 @@ QVariantHash ModelPropertiesDialog::getMapping() const { } mapping.insert(JOINT_INDEX_FIELD, jointIndices); - QVariantHash joints = mapping.value(JOINT_FIELD).toHash(); - if (_modelType == ATTACHMENT_MODEL) { - glm::vec3 pivot; - if (_pivotAboutCenter->isChecked()) { - pivot = (_geometry.meshExtents.minimum + _geometry.meshExtents.maximum) * 0.5f; - - } else if (_pivotJoint->currentIndex() != 0) { - pivot = extractTranslation(_geometry.joints.at(_pivotJoint->currentIndex() - 1).transform); + if (_modelType != ENTITY_MODEL) { + QVariantHash joints = mapping.value(JOINT_FIELD).toHash(); + if (_modelType == ATTACHMENT_MODEL) { + glm::vec3 pivot; + if (_pivotAboutCenter->isChecked()) { + pivot = (_geometry.meshExtents.minimum + _geometry.meshExtents.maximum) * 0.5f; + + } else if (_pivotJoint->currentIndex() != 0) { + pivot = extractTranslation(_geometry.joints.at(_pivotJoint->currentIndex() - 1).transform); + } + mapping.insert(TRANSLATION_X_FIELD, -pivot.x * _scale->value() + _translationX->value()); + mapping.insert(TRANSLATION_Y_FIELD, -pivot.y * _scale->value() + _translationY->value()); + mapping.insert(TRANSLATION_Z_FIELD, -pivot.z * _scale->value() + _translationZ->value()); + + } else { + insertJointMapping(joints, "jointEyeLeft", _leftEyeJoint->currentText()); + insertJointMapping(joints, "jointEyeRight", _rightEyeJoint->currentText()); + insertJointMapping(joints, "jointNeck", _neckJoint->currentText()); } - mapping.insert(TRANSLATION_X_FIELD, -pivot.x * _scale->value() + _translationX->value()); - mapping.insert(TRANSLATION_Y_FIELD, -pivot.y * _scale->value() + _translationY->value()); - mapping.insert(TRANSLATION_Z_FIELD, -pivot.z * _scale->value() + _translationZ->value()); - - } else { - insertJointMapping(joints, "jointEyeLeft", _leftEyeJoint->currentText()); - insertJointMapping(joints, "jointEyeRight", _rightEyeJoint->currentText()); - insertJointMapping(joints, "jointNeck", _neckJoint->currentText()); - } - if (_modelType == SKELETON_MODEL) { - insertJointMapping(joints, "jointRoot", _rootJoint->currentText()); - insertJointMapping(joints, "jointLean", _leanJoint->currentText()); - insertJointMapping(joints, "jointHead", _headJoint->currentText()); - insertJointMapping(joints, "jointLeftHand", _leftHandJoint->currentText()); - insertJointMapping(joints, "jointRightHand", _rightHandJoint->currentText()); - - mapping.remove(FREE_JOINT_FIELD); - for (int i = 0; i < _freeJoints->count() - 1; i++) { - QComboBox* box = static_cast(_freeJoints->itemAt(i)->widget()->layout()->itemAt(0)->widget()); - mapping.insertMulti(FREE_JOINT_FIELD, box->currentText()); + if (_modelType == SKELETON_MODEL) { + insertJointMapping(joints, "jointRoot", _rootJoint->currentText()); + insertJointMapping(joints, "jointLean", _leanJoint->currentText()); + insertJointMapping(joints, "jointHead", _headJoint->currentText()); + insertJointMapping(joints, "jointLeftHand", _leftHandJoint->currentText()); + insertJointMapping(joints, "jointRightHand", _rightHandJoint->currentText()); + + mapping.remove(FREE_JOINT_FIELD); + for (int i = 0; i < _freeJoints->count() - 1; i++) { + QComboBox* box = static_cast(_freeJoints->itemAt(i)->widget()->layout()->itemAt(0)->widget()); + mapping.insertMulti(FREE_JOINT_FIELD, box->currentText()); + } } + mapping.insert(JOINT_FIELD, joints); } - mapping.insert(JOINT_FIELD, joints); return mapping; } @@ -729,32 +734,35 @@ void ModelPropertiesDialog::reset() { _scale->setValue(_originalMapping.value(SCALE_FIELD).toDouble()); QVariantHash jointHash = _originalMapping.value(JOINT_FIELD).toHash(); - if (_modelType == ATTACHMENT_MODEL) { - _translationX->setValue(_originalMapping.value(TRANSLATION_X_FIELD).toDouble()); - _translationY->setValue(_originalMapping.value(TRANSLATION_Y_FIELD).toDouble()); - _translationZ->setValue(_originalMapping.value(TRANSLATION_Z_FIELD).toDouble()); - _pivotAboutCenter->setChecked(true); - _pivotJoint->setCurrentIndex(0); - - } else { - setJointText(_leftEyeJoint, jointHash.value("jointEyeLeft").toString()); - setJointText(_rightEyeJoint, jointHash.value("jointEyeRight").toString()); - setJointText(_neckJoint, jointHash.value("jointNeck").toString()); - } - if (_modelType == SKELETON_MODEL) { - setJointText(_rootJoint, jointHash.value("jointRoot").toString()); - setJointText(_leanJoint, jointHash.value("jointLean").toString()); - setJointText(_headJoint, jointHash.value("jointHead").toString()); - setJointText(_leftHandJoint, jointHash.value("jointLeftHand").toString()); - setJointText(_rightHandJoint, jointHash.value("jointRightHand").toString()); - - while (_freeJoints->count() > 1) { - delete _freeJoints->itemAt(0)->widget(); + + if (_modelType != ENTITY_MODEL) { + if (_modelType == ATTACHMENT_MODEL) { + _translationX->setValue(_originalMapping.value(TRANSLATION_X_FIELD).toDouble()); + _translationY->setValue(_originalMapping.value(TRANSLATION_Y_FIELD).toDouble()); + _translationZ->setValue(_originalMapping.value(TRANSLATION_Z_FIELD).toDouble()); + _pivotAboutCenter->setChecked(true); + _pivotJoint->setCurrentIndex(0); + + } else { + setJointText(_leftEyeJoint, jointHash.value("jointEyeLeft").toString()); + setJointText(_rightEyeJoint, jointHash.value("jointEyeRight").toString()); + setJointText(_neckJoint, jointHash.value("jointNeck").toString()); } - foreach (const QVariant& joint, _originalMapping.values(FREE_JOINT_FIELD)) { - QString jointName = joint.toString(); - if (_geometry.jointIndices.contains(jointName)) { - createNewFreeJoint(jointName); + if (_modelType == SKELETON_MODEL) { + setJointText(_rootJoint, jointHash.value("jointRoot").toString()); + setJointText(_leanJoint, jointHash.value("jointLean").toString()); + setJointText(_headJoint, jointHash.value("jointHead").toString()); + setJointText(_leftHandJoint, jointHash.value("jointLeftHand").toString()); + setJointText(_rightHandJoint, jointHash.value("jointRightHand").toString()); + + while (_freeJoints->count() > 1) { + delete _freeJoints->itemAt(0)->widget(); + } + foreach (const QVariant& joint, _originalMapping.values(FREE_JOINT_FIELD)) { + QString jointName = joint.toString(); + if (_geometry.jointIndices.contains(jointName)) { + createNewFreeJoint(jointName); + } } } } diff --git a/interface/src/ModelUploader.h b/interface/src/ModelUploader.h index 7d8ad2b526..af347e36bd 100644 --- a/interface/src/ModelUploader.h +++ b/interface/src/ModelUploader.h @@ -53,7 +53,7 @@ private: QSet _textureFilenames; int _lodCount; int _texturesCount; - int _totalSize; + unsigned long _totalSize; ModelType _modelType; bool _readyToSend; From 0a66b23efa2fd66c9f1a9a69b3b70a43b3c3a8bd Mon Sep 17 00:00:00 2001 From: Stephen Birarda Date: Tue, 23 Dec 2014 13:33:19 -0800 Subject: [PATCH 249/258] remove current address from address bar dialog --- interface/src/ui/AddressBarDialog.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/interface/src/ui/AddressBarDialog.cpp b/interface/src/ui/AddressBarDialog.cpp index 75049f9ed4..5f55aa5210 100644 --- a/interface/src/ui/AddressBarDialog.cpp +++ b/interface/src/ui/AddressBarDialog.cpp @@ -116,9 +116,8 @@ void AddressBarDialog::setupUI() { void AddressBarDialog::showEvent(QShowEvent* event) { _goButton->setIcon(QIcon(PathUtils::resourcesPath() + ADDRESSBAR_GO_BUTTON_ICON)); - _addressLineEdit->setText(AddressManager::getInstance().currentAddress().toString()); + _addressLineEdit->setText(QString()); _addressLineEdit->setFocus(); - _addressLineEdit->selectAll(); FramelessDialog::showEvent(event); } From f317b54017cb299479376be8125854c167980dcd Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Tue, 23 Dec 2014 13:35:01 -0800 Subject: [PATCH 250/258] Broke down ModelUploader::zip() --- interface/src/ModelUploader.cpp | 170 ++++++++++++++++---------------- interface/src/ModelUploader.h | 2 +- 2 files changed, 88 insertions(+), 84 deletions(-) diff --git a/interface/src/ModelUploader.cpp b/interface/src/ModelUploader.cpp index c400e25246..687fae4c54 100644 --- a/interface/src/ModelUploader.cpp +++ b/interface/src/ModelUploader.cpp @@ -149,6 +149,91 @@ bool ModelUploader::zip() { FBXGeometry geometry = readFBX(fbxContents, QVariantHash()); // make sure we have some basic mappings + populateBasicMapping(mapping, filename, geometry); + + // open the dialog to configure the rest + ModelPropertiesDialog properties(_modelType, mapping, basePath, geometry); + if (properties.exec() == QDialog::Rejected) { + return false; + } + mapping = properties.getMapping(); + + QByteArray nameField = mapping.value(NAME_FIELD).toByteArray(); + QString urlBase; + if (!nameField.isEmpty()) { + QHttpPart textPart; + textPart.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data; name=\"model_name\""); + textPart.setBody(nameField); + _dataMultiPart->append(textPart); + urlBase = S3_URL + "/models/" + MODEL_TYPE_NAMES[_modelType] + "/" + nameField; + _url = urlBase + ".fst"; + + } else { + QMessageBox::warning(NULL, + QString("ModelUploader::zip()"), + QString("Model name is missing in the .fst file."), + QMessageBox::Ok); + qDebug() << "[Warning] " << QString("Model name is missing in the .fst file."); + return false; + } + + QByteArray texdirField = mapping.value(TEXDIR_FIELD).toByteArray(); + QString texDir; + _textureBase = urlBase + "/textures/"; + if (!texdirField.isEmpty()) { + texDir = basePath + "/" + texdirField; + QFileInfo texInfo(texDir); + if (!texInfo.exists() || !texInfo.isDir()) { + QMessageBox::warning(NULL, + QString("ModelUploader::zip()"), + QString("Texture directory could not be found."), + QMessageBox::Ok); + qDebug() << "[Warning] " << QString("Texture directory could not be found."); + return false; + } + } + + QVariantHash lodField = mapping.value(LOD_FIELD).toHash(); + for (QVariantHash::const_iterator it = lodField.constBegin(); it != lodField.constEnd(); it++) { + QFileInfo lod(basePath + "/" + it.key()); + if (!lod.exists() || !lod.isFile()) { // Check existence + QMessageBox::warning(NULL, + QString("ModelUploader::zip()"), + QString("LOD file %1 could not be found.").arg(lod.fileName()), + QMessageBox::Ok); + qDebug() << "[Warning] " << QString("FBX file %1 could not be found.").arg(lod.fileName()); + } + // Compress and copy + if (!addPart(lod.filePath(), QString("lod%1").arg(++_lodCount))) { + return false; + } + } + + // Write out, compress and copy the fst + if (!addPart(*fst, writeMapping(mapping), QString("fst"))) { + return false; + } + + // Compress and copy the fbx + if (!addPart(fbx, fbxContents, "fbx")) { + return false; + } + + if (!addTextures(texDir, geometry)) { + return false; + } + + QHttpPart textPart; + textPart.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data;" + " name=\"model_category\""); + textPart.setBody(MODEL_TYPE_NAMES[_modelType]); + _dataMultiPart->append(textPart); + + _readyToSend = true; + return true; +} + +void ModelUploader::populateBasicMapping(QVariantHash& mapping, QString filename, FBXGeometry geometry) { if (!mapping.contains(NAME_FIELD)) { mapping.insert(NAME_FIELD, QFileInfo(filename).baseName()); } @@ -163,11 +248,11 @@ bool ModelUploader::zip() { QVariantHash joints = mapping.value(JOINT_FIELD).toHash(); if (!joints.contains("jointEyeLeft")) { joints.insert("jointEyeLeft", geometry.jointIndices.contains("jointEyeLeft") ? "jointEyeLeft" : - (geometry.jointIndices.contains("EyeLeft") ? "EyeLeft" : "LeftEye")); + (geometry.jointIndices.contains("EyeLeft") ? "EyeLeft" : "LeftEye")); } if (!joints.contains("jointEyeRight")) { joints.insert("jointEyeRight", geometry.jointIndices.contains("jointEyeRight") ? "jointEyeRight" : - geometry.jointIndices.contains("EyeRight") ? "EyeRight" : "RightEye"); + geometry.jointIndices.contains("EyeRight") ? "EyeRight" : "RightEye"); } if (!joints.contains("jointNeck")) { joints.insert("jointNeck", geometry.jointIndices.contains("jointNeck") ? "jointNeck" : "Neck"); @@ -251,87 +336,6 @@ bool ModelUploader::zip() { blendshapes.insertMulti("Sneer", QVariantList() << "Squint_Right" << 0.5); mapping.insert(BLENDSHAPE_FIELD, blendshapes); } - - // open the dialog to configure the rest - ModelPropertiesDialog properties(_modelType, mapping, basePath, geometry); - if (properties.exec() == QDialog::Rejected) { - return false; - } - mapping = properties.getMapping(); - - QByteArray nameField = mapping.value(NAME_FIELD).toByteArray(); - QString urlBase; - if (!nameField.isEmpty()) { - QHttpPart textPart; - textPart.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data; name=\"model_name\""); - textPart.setBody(nameField); - _dataMultiPart->append(textPart); - urlBase = S3_URL + "/models/" + MODEL_TYPE_NAMES[_modelType] + "/" + nameField; - _url = urlBase + ".fst"; - - } else { - QMessageBox::warning(NULL, - QString("ModelUploader::zip()"), - QString("Model name is missing in the .fst file."), - QMessageBox::Ok); - qDebug() << "[Warning] " << QString("Model name is missing in the .fst file."); - return false; - } - - QByteArray texdirField = mapping.value(TEXDIR_FIELD).toByteArray(); - QString texDir; - _textureBase = urlBase + "/textures/"; - if (!texdirField.isEmpty()) { - texDir = basePath + "/" + texdirField; - QFileInfo texInfo(texDir); - if (!texInfo.exists() || !texInfo.isDir()) { - QMessageBox::warning(NULL, - QString("ModelUploader::zip()"), - QString("Texture directory could not be found."), - QMessageBox::Ok); - qDebug() << "[Warning] " << QString("Texture directory could not be found."); - return false; - } - } - - QVariantHash lodField = mapping.value(LOD_FIELD).toHash(); - for (QVariantHash::const_iterator it = lodField.constBegin(); it != lodField.constEnd(); it++) { - QFileInfo lod(basePath + "/" + it.key()); - if (!lod.exists() || !lod.isFile()) { // Check existence - QMessageBox::warning(NULL, - QString("ModelUploader::zip()"), - QString("LOD file %1 could not be found.").arg(lod.fileName()), - QMessageBox::Ok); - qDebug() << "[Warning] " << QString("FBX file %1 could not be found.").arg(lod.fileName()); - } - // Compress and copy - if (!addPart(lod.filePath(), QString("lod%1").arg(++_lodCount))) { - return false; - } - } - - // Write out, compress and copy the fst - if (!addPart(*fst, writeMapping(mapping), QString("fst"))) { - return false; - } - - // Compress and copy the fbx - if (!addPart(fbx, fbxContents, "fbx")) { - return false; - } - - if (!addTextures(texDir, geometry)) { - return false; - } - - QHttpPart textPart; - textPart.setHeader(QNetworkRequest::ContentDispositionHeader, "form-data;" - " name=\"model_category\""); - textPart.setBody(MODEL_TYPE_NAMES[_modelType]); - _dataMultiPart->append(textPart); - - _readyToSend = true; - return true; } void ModelUploader::send() { diff --git a/interface/src/ModelUploader.h b/interface/src/ModelUploader.h index af347e36bd..7013d33106 100644 --- a/interface/src/ModelUploader.h +++ b/interface/src/ModelUploader.h @@ -65,7 +65,7 @@ private: QDialog* _progressDialog; QProgressBar* _progressBar; - + void populateBasicMapping(QVariantHash& mapping, QString filename, FBXGeometry geometry); bool zip(); bool addTextures(const QString& texdir, const FBXGeometry& geometry); bool addPart(const QString& path, const QString& name, bool isTexture = false); From da636ca918b65d50eb41c2b45e6cd71924e514e4 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Tue, 23 Dec 2014 14:00:23 -0800 Subject: [PATCH 251/258] ModelUploader only has static methods accessible --- interface/src/Application.cpp | 18 ++++-------------- interface/src/Application.h | 2 -- interface/src/ModelUploader.cpp | 26 ++++++++++++++++++++++++++ interface/src/ModelUploader.h | 25 +++++++++++++++---------- 4 files changed, 45 insertions(+), 26 deletions(-) diff --git a/interface/src/Application.cpp b/interface/src/Application.cpp index 67821e5f7f..6ddf116acd 100644 --- a/interface/src/Application.cpp +++ b/interface/src/Application.cpp @@ -3626,16 +3626,6 @@ void Application::setMenuShortcutsEnabled(bool enabled) { setShortcutsEnabled(_window->menuBar(), enabled); } -void Application::uploadModel(ModelType modelType) { - ModelUploader* uploader = new ModelUploader(modelType); - QThread* thread = new QThread(); - thread->connect(uploader, SIGNAL(destroyed()), SLOT(quit())); - thread->connect(thread, SIGNAL(finished()), SLOT(deleteLater())); - uploader->connect(thread, SIGNAL(started()), SLOT(send())); - - thread->start(); -} - void Application::updateWindowTitle(){ QString buildVersion = " (build " + applicationVersion() + ")"; @@ -4191,19 +4181,19 @@ void Application::toggleRunningScriptsWidget() { } void Application::uploadHead() { - uploadModel(HEAD_MODEL); + ModelUploader::uploadHead(); } void Application::uploadSkeleton() { - uploadModel(SKELETON_MODEL); + ModelUploader::uploadSkeleton(); } void Application::uploadAttachment() { - uploadModel(ATTACHMENT_MODEL); + ModelUploader::uploadAttachment(); } void Application::uploadEntity() { - uploadModel(ENTITY_MODEL); + ModelUploader::uploadEntity(); } void Application::openUrl(const QUrl& url) { diff --git a/interface/src/Application.h b/interface/src/Application.h index c08e7359ab..a3c3d51d59 100644 --- a/interface/src/Application.h +++ b/interface/src/Application.h @@ -460,8 +460,6 @@ private: void setMenuShortcutsEnabled(bool enabled); - void uploadModel(ModelType modelType); - static void attachNewHeadToNode(Node *newNode); static void* networkReceive(void* args); // network receive thread diff --git a/interface/src/ModelUploader.cpp b/interface/src/ModelUploader.cpp index 687fae4c54..29d82d3b69 100644 --- a/interface/src/ModelUploader.cpp +++ b/interface/src/ModelUploader.cpp @@ -64,6 +64,32 @@ static const int MAX_CHECK = 30; static const int QCOMPRESS_HEADER_POSITION = 0; static const int QCOMPRESS_HEADER_SIZE = 4; +void ModelUploader::uploadModel(ModelType modelType) { + ModelUploader* uploader = new ModelUploader(modelType); + QThread* thread = new QThread(); + thread->connect(uploader, SIGNAL(destroyed()), SLOT(quit())); + thread->connect(thread, SIGNAL(finished()), SLOT(deleteLater())); + uploader->connect(thread, SIGNAL(started()), SLOT(send())); + + thread->start(); +} + +void ModelUploader::uploadHead() { + uploadModel(HEAD_MODEL); +} + +void ModelUploader::uploadSkeleton() { + uploadModel(SKELETON_MODEL); +} + +void ModelUploader::uploadAttachment() { + uploadModel(ATTACHMENT_MODEL); +} + +void ModelUploader::uploadEntity() { + uploadModel(ENTITY_MODEL); +} + ModelUploader::ModelUploader(ModelType modelType) : _lodCount(-1), _texturesCount(-1), diff --git a/interface/src/ModelUploader.h b/interface/src/ModelUploader.h index 7013d33106..eafb07c4b0 100644 --- a/interface/src/ModelUploader.h +++ b/interface/src/ModelUploader.h @@ -33,13 +33,15 @@ class ModelUploader : public QObject { Q_OBJECT public: - ModelUploader(ModelType type); - ~ModelUploader(); + static void uploadModel(ModelType modelType); -public slots: - void send(); + static void uploadHead(); + static void uploadSkeleton(); + static void uploadAttachment(); + static void uploadEntity(); private slots: + void send(); void checkJSON(QNetworkReply& requestReply); void uploadUpdate(qint64 bytesSent, qint64 bytesTotal); void uploadSuccess(QNetworkReply& requestReply); @@ -48,6 +50,15 @@ private slots: void processCheck(); private: + ModelUploader(ModelType type); + ~ModelUploader(); + + void populateBasicMapping(QVariantHash& mapping, QString filename, FBXGeometry geometry); + bool zip(); + bool addTextures(const QString& texdir, const FBXGeometry& geometry); + bool addPart(const QString& path, const QString& name, bool isTexture = false); + bool addPart(const QFile& file, const QByteArray& contents, const QString& name, bool isTexture = false); + QString _url; QString _textureBase; QSet _textureFilenames; @@ -64,12 +75,6 @@ private: QDialog* _progressDialog; QProgressBar* _progressBar; - - void populateBasicMapping(QVariantHash& mapping, QString filename, FBXGeometry geometry); - bool zip(); - bool addTextures(const QString& texdir, const FBXGeometry& geometry); - bool addPart(const QString& path, const QString& name, bool isTexture = false); - bool addPart(const QFile& file, const QByteArray& contents, const QString& name, bool isTexture = false); }; /// A dialog that allows customization of various model properties. From 59387be856f14e072227a69bb3f1e1afc3165ee4 Mon Sep 17 00:00:00 2001 From: Sam Gateau Date: Tue, 23 Dec 2014 14:20:12 -0800 Subject: [PATCH 252/258] Fixing typo and syntax --- tools/scribe/src/TextTemplate.cpp | 67 +++++++++++++------------------ 1 file changed, 28 insertions(+), 39 deletions(-) diff --git a/tools/scribe/src/TextTemplate.cpp b/tools/scribe/src/TextTemplate.cpp index 0199f7249e..e4bc8fcf6d 100755 --- a/tools/scribe/src/TextTemplate.cpp +++ b/tools/scribe/src/TextTemplate.cpp @@ -59,9 +59,9 @@ const TextTemplatePointer TextTemplate::Config::addInclude(const ConfigPointer& } const TextTemplatePointer TextTemplate::Config::findInclude(const char* include) { - Includes::iterator it = _includes.find(String(include)); - if (it != _includes.end()) { - return (*it).second; + Includes::iterator includeIt = _includes.find(String(include)); + if (includeIt != _includes.end()) { + return (*includeIt).second; } else { return TextTemplatePointer(); } @@ -76,23 +76,19 @@ bool TextTemplate::loadFile(const ConfigPointer& config, const char* filename, S String fullfilename; for (unsigned int i = 0; i < config->_paths.size(); i++) { fullfilename = config->_paths[i] + s; - { - std::ifstream ifs; - ifs.open(fullfilename.c_str()); - if (ifs.is_open()) { - std::string str((std::istreambuf_iterator(ifs)), std::istreambuf_iterator()); - source = str; - ifs.close(); - return (source.length() > 0); - } + std::ifstream ifs; + ifs.open(fullfilename.c_str()); + if (ifs.is_open()) { + std::string str((std::istreambuf_iterator(ifs)), std::istreambuf_iterator()); + source = str; + ifs.close(); + return (source.length() > 0); } } return false; } -//----------------------------------------------------------------------------- - TextTemplate::Funcs::Funcs() : _funcs() { } @@ -118,8 +114,6 @@ const BlockPointer TextTemplate::Funcs::addFunc(const char* func, const BlockPoi return included; } -//----------------------------------------------------------------------------- - void TextTemplate::Block::addNewBlock(const Pointer& parent, const Pointer& block) { if (parent) { parent->blocks.push_back(block); @@ -128,15 +122,13 @@ void TextTemplate::Block::addNewBlock(const Pointer& parent, const Pointer& bloc } const BlockPointer& TextTemplate::Block::getCurrentBlock(const Pointer& block) { - if ((block) && block->command.isBlockEnd()) { + if (block && block->command.isBlockEnd()) { return block->parent; } else { return block; } } -//----------------------------------------------------------------------------- - void TextTemplate::logError(const Block::Pointer& block, const char* fmt, ...) { va_list argp; va_start(argp, fmt); @@ -196,21 +188,21 @@ bool TextTemplate::grabUntilBeginTag(std::istream* str, std::string& grabbed, Ta bool TextTemplate::grabUntilEndTag(std::istream* str, std::string& grabbed, Tag::Type& tagType) { std::stringstream dst; - // preend char depends on tag type - char preend = Tag::COM; + // preEnd char depends on tag type + char preEnd = Tag::COM; if (tagType == Tag::VARIABLE) { - preend = Tag::VAR; + preEnd = Tag::VAR; } else if (tagType == Tag::REMARK) { - preend = Tag::REM; + preEnd = Tag::REM; } while (!str->eof()) { // looking for the end of the tag means find the next preEnd - std::string datatoken; - getline((*str), datatoken, preend); + std::string dataToken; + getline((*str), dataToken, preEnd); char end = str->peek(); - dst << datatoken; + dst << dataToken; // and if the next char is Tag::END then that's it if (end == Tag::END) { @@ -219,14 +211,15 @@ bool TextTemplate::grabUntilEndTag(std::istream* str, std::string& grabbed, Tag: return true; } else { // false positive, keep on searching - dst << preend; + dst << preEnd; } } grabbed = dst.str(); return false; } -bool TextTemplate::stepForward(std::istream* str, std::string& grabbed, std::string& tag, Tag::Type& tagType, Tag::Type& nextTagType) { +bool TextTemplate::stepForward(std::istream* str, std::string& grabbed, std::string& tag, Tag::Type& tagType, + Tag::Type& nextTagType) { if (str->eof()) { return false; } @@ -242,7 +235,7 @@ bool TextTemplate::stepForward(std::istream* str, std::string& grabbed, std::str if ((tagType == Tag::COMMAND) || (tagType == Tag::REMARK)) { while (!str->eof()) { char c = str->peek(); - if ((c== ' ') || (c=='\t') || (c=='\n')) { + if ((c == ' ') || (c == '\t') || (c == '\n')) { str->get(); } else { break; @@ -251,15 +244,13 @@ bool TextTemplate::stepForward(std::istream* str, std::string& grabbed, std::str } grabUntilBeginTag(str, grabbed, nextTagType); - /*if (grabbed.empty()) { - grabbed += ' '; - }*/ } return true; //hasElement; } -const BlockPointer TextTemplate::processStep(const BlockPointer& block, std::string& grabbed, std::string& tag, Tag::Type& tagType) { +const BlockPointer TextTemplate::processStep(const BlockPointer& block, std::string& grabbed, std::string& tag, + Tag::Type& tagType) { switch (tagType) { case Tag::INVALID: block->ostr << grabbed; @@ -362,10 +353,10 @@ bool TextTemplate::convertExpressionToFuncArguments(String& src, std::vector< St if (src.empty()) { return false; } - std::stringstream str_src(src); + std::stringstream streamSrc(src); String params; - getline(str_src, params, '('); - getline(str_src, params, ')'); + getline(streamSrc, params, '('); + getline(streamSrc, params, ')'); if (params.empty()) { return false; } @@ -474,7 +465,7 @@ const BlockPointer TextTemplate::processStepDef(const BlockPointer& block, Strin newBlock->command.type = Command::DEF; newBlock->command.arguments.push_back(varName); - if (! val.empty()) { + if (!val.empty()) { // loose first character which should be a white space val = val.substr(val.find_first_not_of(' ')); convertExpressionToDefArguments(val, newBlock->command.arguments); @@ -692,8 +683,6 @@ const BlockPointer TextTemplate::processStepEndFunc(const BlockPointer& block, S return block; } -//----------------------------------------------------------------------------- - TextTemplate::TextTemplate(const String& name, const ConfigPointer& externalConfig) : _config(externalConfig), _root(new Block(name)), From 4bdc0d718dda45b0cd31a1e6c7d955bcd164f152 Mon Sep 17 00:00:00 2001 From: Sam Gateau Date: Tue, 23 Dec 2014 14:29:26 -0800 Subject: [PATCH 253/258] Fixing typo and syntax --- tools/scribe/src/TextTemplate.cpp | 291 +++++++++++++++--------------- 1 file changed, 145 insertions(+), 146 deletions(-) diff --git a/tools/scribe/src/TextTemplate.cpp b/tools/scribe/src/TextTemplate.cpp index e4bc8fcf6d..6508a9787b 100755 --- a/tools/scribe/src/TextTemplate.cpp +++ b/tools/scribe/src/TextTemplate.cpp @@ -72,10 +72,10 @@ void TextTemplate::Config::addIncludePath(const char* path) { } bool TextTemplate::loadFile(const ConfigPointer& config, const char* filename, String& source) { - String s(filename); + String sourceFile(filename); String fullfilename; for (unsigned int i = 0; i < config->_paths.size(); i++) { - fullfilename = config->_paths[i] + s; + fullfilename = config->_paths[i] + sourceFile; std::ifstream ifs; ifs.open(fullfilename.c_str()); if (ifs.is_open()) { @@ -622,7 +622,6 @@ const BlockPointer TextTemplate::processStepFunc(const BlockPointer& block, Stri return block; } - // DOes the func already exists ? if (_config->_funcs.findFunc(varName.c_str())) { logError(block, "Declaring a new func named <%s> already exists", func.c_str()); @@ -719,183 +718,183 @@ int TextTemplate::generateTree(std::ostream& dst, const BlockPointer& block, Var int TextTemplate::evalBlockGeneration(std::ostream& dst, const BlockPointer& block, Vars& vars, BlockPointer& branch) { switch (block->command.type) { case Command::BLOCK: { - branch = block; - return 1; - } - break; + branch = block; + return 1; + } + break; case Command::VAR: { - Vars::iterator it = vars.find(block->command.arguments.front()); - if (it != vars.end()) { - dst << (*it).second; - } else { - BlockPointer funcBlock = _config->_funcs.findFunc(block->command.arguments.front().c_str()); - if (funcBlock) { - // before diving in the func tree, let's modify the vars with the local defs: - int nbParams = std::min(block->command.arguments.size(), funcBlock->command.arguments.size()); - std::vector< String > paramCache; - paramCache.push_back(""); - String val; - for (int i = 1; i < nbParams; i++) { - val = block->command.arguments[i]; - if ((val[0] == Tag::VAR) && (val[val.length()-1] == Tag::VAR)) { - val = val.substr(1, val.length()-2); - Vars::iterator it = vars.find(val); - if (it != vars.end()) { - val = (*it).second; - } - } - - Vars::iterator it = vars.find(funcBlock->command.arguments[i]); + Vars::iterator it = vars.find(block->command.arguments.front()); + if (it != vars.end()) { + dst << (*it).second; + } else { + BlockPointer funcBlock = _config->_funcs.findFunc(block->command.arguments.front().c_str()); + if (funcBlock) { + // before diving in the func tree, let's modify the vars with the local defs: + int nbParams = std::min(block->command.arguments.size(), funcBlock->command.arguments.size()); + std::vector< String > paramCache; + paramCache.push_back(""); + String val; + for (int i = 1; i < nbParams; i++) { + val = block->command.arguments[i]; + if ((val[0] == Tag::VAR) && (val[val.length()-1] == Tag::VAR)) { + val = val.substr(1, val.length()-2); + Vars::iterator it = vars.find(val); if (it != vars.end()) { - paramCache.push_back((*it).second); - (*it).second = val; - } else { - vars.insert(Vars::value_type(funcBlock->command.arguments[i], val)); - paramCache.push_back(""); + val = (*it).second; } } - generateTree(dst, funcBlock, vars); - - for (int i = 1; i < nbParams; i++) { - vars[ funcBlock->command.arguments[i] ] = paramCache[i]; + Vars::iterator it = vars.find(funcBlock->command.arguments[i]); + if (it != vars.end()) { + paramCache.push_back((*it).second); + (*it).second = val; + } else { + vars.insert(Vars::value_type(funcBlock->command.arguments[i], val)); + paramCache.push_back(""); } } - } - branch = block; - return 1; - } - break; - case Command::IFBLOCK: { - // ok, go through the branches and pick the first one that goes - for (auto child: block->blocks) { - int numPasses = evalBlockGeneration(dst, child, vars, branch); - if (numPasses > 0) { - return numPasses; + + generateTree(dst, funcBlock, vars); + + for (int i = 1; i < nbParams; i++) { + vars[ funcBlock->command.arguments[i] ] = paramCache[i]; } } } - break; + branch = block; + return 1; + } + break; + case Command::IFBLOCK: { + // ok, go through the branches and pick the first one that goes + for (auto child: block->blocks) { + int numPasses = evalBlockGeneration(dst, child, vars, branch); + if (numPasses > 0) { + return numPasses; + } + } + } + break; case Command::IF: case Command::ELIF: { - if (!block->command.arguments.empty()) { - // Just one argument means check for the var beeing defined - if (block->command.arguments.size() == 1) { - Vars::iterator it = vars.find(block->command.arguments.front()); - if (it != vars.end()) { + if (!block->command.arguments.empty()) { + // Just one argument means check for the var beeing defined + if (block->command.arguments.size() == 1) { + Vars::iterator it = vars.find(block->command.arguments.front()); + if (it != vars.end()) { + branch = block; + return 1; + } + } else if (block->command.arguments.size() == 2) { + if (block->command.arguments[0].compare("not") == 0) { + Vars::iterator it = vars.find(block->command.arguments[1]); + if (it == vars.end()) { branch = block; return 1; } - } else if (block->command.arguments.size() == 2) { - if (block->command.arguments[0].compare("not") == 0) { - Vars::iterator it = vars.find(block->command.arguments[1]); - if (it == vars.end()) { - branch = block; - return 1; - } + } + } else if (block->command.arguments.size() == 3) { + if (block->command.arguments[1].compare("and") == 0) { + Vars::iterator itL = vars.find(block->command.arguments[0]); + Vars::iterator itR = vars.find(block->command.arguments[2]); + if ((itL != vars.end()) && (itR != vars.end())) { + branch = block; + return 1; } - } else if (block->command.arguments.size() == 3) { - if (block->command.arguments[1].compare("and") == 0) { - Vars::iterator itL = vars.find(block->command.arguments[0]); - Vars::iterator itR = vars.find(block->command.arguments[2]); - if ((itL != vars.end()) && (itR != vars.end())) { + } else if (block->command.arguments[1].compare("or") == 0) { + Vars::iterator itL = vars.find(block->command.arguments[0]); + Vars::iterator itR = vars.find(block->command.arguments[2]); + if ((itL != vars.end()) || (itR != vars.end())) { + branch = block; + return 1; + } + } else if (block->command.arguments[1].compare("==") == 0) { + Vars::iterator itL = vars.find(block->command.arguments[0]); + if (itL != vars.end()) { + if ((*itL).second.compare(block->command.arguments[2]) == 0) { branch = block; return 1; } - } else if (block->command.arguments[1].compare("or") == 0) { - Vars::iterator itL = vars.find(block->command.arguments[0]); - Vars::iterator itR = vars.find(block->command.arguments[2]); - if ((itL != vars.end()) || (itR != vars.end())) { - branch = block; - return 1; - } - } else if (block->command.arguments[1].compare("==") == 0) { - Vars::iterator itL = vars.find(block->command.arguments[0]); - if (itL != vars.end()) { - if ((*itL).second.compare(block->command.arguments[2]) == 0) { - branch = block; - return 1; - } - } } } - } + + } + return 0; + } + break; + case Command::ELSE: { + branch = block; + return 1; + } + break; + case Command::ENDIF: { + branch = block; + return 1; + } + break; + case Command::DEF: { + if (block->command.arguments.size()) { + // THe actual value of the var defined sneeds to be evaluated: + String val; + for (int t = 1; t < block->command.arguments.size(); t++) { + // detect if a param is a var + int len = block->command.arguments[t].length(); + if ((block->command.arguments[t][0] == Tag::VAR) + && (block->command.arguments[t][len-1] == Tag::VAR)) { + String var = block->command.arguments[t].substr(1, len-2); + Vars::iterator it = vars.find(var); + if (it != vars.end()) { + val += (*it).second; + } + } else { + val += block->command.arguments[t]; + } + } + + Vars::iterator it = vars.find(block->command.arguments.front()); + if (it == vars.end()) { + vars.insert(Vars::value_type(block->command.arguments.front(), val)); + } else { + (*it).second = val; + } + + branch = block; + return 1; + } else { + branch = block; return 0; } - break; - case Command::ELSE: { - branch = block; - return 1; - } - break; - case Command::ENDIF: { - branch = block; - return 1; - } - break; - case Command::DEF: { - if (block->command.arguments.size()) { - // THe actual value of the var defined sneeds to be evaluated: - String val; - for (int t = 1; t < block->command.arguments.size(); t++) { - // detect if a param is a var - int len = block->command.arguments[t].length(); - if ((block->command.arguments[t][0] == Tag::VAR) - && (block->command.arguments[t][len-1] == Tag::VAR)) { - String var = block->command.arguments[t].substr(1, len-2); - Vars::iterator it = vars.find(var); - if (it != vars.end()) { - val += (*it).second; - } - } else { - val += block->command.arguments[t]; - } - } - - Vars::iterator it = vars.find(block->command.arguments.front()); - if (it == vars.end()) { - vars.insert(Vars::value_type(block->command.arguments.front(), val)); - } else { - (*it).second = val; - } - - branch = block; - return 1; - } else { - branch = block; - return 0; - } - } - break; + } + break; case Command::INCLUDE: { - TextTemplatePointer include = _config->findInclude(block->command.arguments.front().c_str()); - if (include && !include->_root->blocks.empty()) { - if (&include->_root) { - generateTree(dst, include->_root, vars); - } + TextTemplatePointer include = _config->findInclude(block->command.arguments.front().c_str()); + if (include && !include->_root->blocks.empty()) { + if (&include->_root) { + generateTree(dst, include->_root, vars); } - - branch = block; - return 1; } - break; + + branch = block; + return 1; + } + break; case Command::FUNC: { - branch = block; - return 1; - } - break; + branch = block; + return 1; + } + break; case Command::ENDFUNC: { - branch = block; - return 1; - } - break; + branch = block; + return 1; + } + break; default: { - } + } } return 0; From 0578a54ea044c0fa941ce42910c30a9821918931 Mon Sep 17 00:00:00 2001 From: Sam Gateau Date: Tue, 23 Dec 2014 14:41:05 -0800 Subject: [PATCH 254/258] Fixing typo and syntax --- tools/scribe/src/TextTemplate.cpp | 306 +++++++++++++++--------------- tools/scribe/src/TextTemplate.h | 3 +- 2 files changed, 154 insertions(+), 155 deletions(-) diff --git a/tools/scribe/src/TextTemplate.cpp b/tools/scribe/src/TextTemplate.cpp index 6508a9787b..7c92fe33fa 100755 --- a/tools/scribe/src/TextTemplate.cpp +++ b/tools/scribe/src/TextTemplate.cpp @@ -717,184 +717,184 @@ int TextTemplate::generateTree(std::ostream& dst, const BlockPointer& block, Var int TextTemplate::evalBlockGeneration(std::ostream& dst, const BlockPointer& block, Vars& vars, BlockPointer& branch) { switch (block->command.type) { - case Command::BLOCK: { - branch = block; - return 1; - } - break; - case Command::VAR: { - Vars::iterator it = vars.find(block->command.arguments.front()); - if (it != vars.end()) { - dst << (*it).second; - } else { - BlockPointer funcBlock = _config->_funcs.findFunc(block->command.arguments.front().c_str()); - if (funcBlock) { - // before diving in the func tree, let's modify the vars with the local defs: - int nbParams = std::min(block->command.arguments.size(), funcBlock->command.arguments.size()); - std::vector< String > paramCache; - paramCache.push_back(""); - String val; - for (int i = 1; i < nbParams; i++) { - val = block->command.arguments[i]; - if ((val[0] == Tag::VAR) && (val[val.length()-1] == Tag::VAR)) { - val = val.substr(1, val.length()-2); - Vars::iterator it = vars.find(val); + case Command::BLOCK: { + branch = block; + return 1; + } + break; + case Command::VAR: { + Vars::iterator it = vars.find(block->command.arguments.front()); + if (it != vars.end()) { + dst << (*it).second; + } else { + BlockPointer funcBlock = _config->_funcs.findFunc(block->command.arguments.front().c_str()); + if (funcBlock) { + // before diving in the func tree, let's modify the vars with the local defs: + int nbParams = std::min(block->command.arguments.size(), funcBlock->command.arguments.size()); + std::vector< String > paramCache; + paramCache.push_back(""); + String val; + for (int i = 1; i < nbParams; i++) { + val = block->command.arguments[i]; + if ((val[0] == Tag::VAR) && (val[val.length()-1] == Tag::VAR)) { + val = val.substr(1, val.length()-2); + Vars::iterator it = vars.find(val); + if (it != vars.end()) { + val = (*it).second; + } + } + + Vars::iterator it = vars.find(funcBlock->command.arguments[i]); if (it != vars.end()) { - val = (*it).second; + paramCache.push_back((*it).second); + (*it).second = val; + } else { + vars.insert(Vars::value_type(funcBlock->command.arguments[i], val)); + paramCache.push_back(""); } } - Vars::iterator it = vars.find(funcBlock->command.arguments[i]); + generateTree(dst, funcBlock, vars); + + for (int i = 1; i < nbParams; i++) { + vars[ funcBlock->command.arguments[i] ] = paramCache[i]; + } + } + } + branch = block; + return 1; + } + break; + case Command::IFBLOCK: { + // ok, go through the branches and pick the first one that goes + for (auto child: block->blocks) { + int numPasses = evalBlockGeneration(dst, child, vars, branch); + if (numPasses > 0) { + return numPasses; + } + } + } + break; + case Command::IF: + case Command::ELIF: { + if (!block->command.arguments.empty()) { + // Just one argument means check for the var beeing defined + if (block->command.arguments.size() == 1) { + Vars::iterator it = vars.find(block->command.arguments.front()); if (it != vars.end()) { - paramCache.push_back((*it).second); - (*it).second = val; - } else { - vars.insert(Vars::value_type(funcBlock->command.arguments[i], val)); - paramCache.push_back(""); - } - } - - generateTree(dst, funcBlock, vars); - - for (int i = 1; i < nbParams; i++) { - vars[ funcBlock->command.arguments[i] ] = paramCache[i]; - } - } - } - branch = block; - return 1; - } - break; - case Command::IFBLOCK: { - // ok, go through the branches and pick the first one that goes - for (auto child: block->blocks) { - int numPasses = evalBlockGeneration(dst, child, vars, branch); - if (numPasses > 0) { - return numPasses; - } - } - } - break; - case Command::IF: - case Command::ELIF: { - if (!block->command.arguments.empty()) { - // Just one argument means check for the var beeing defined - if (block->command.arguments.size() == 1) { - Vars::iterator it = vars.find(block->command.arguments.front()); - if (it != vars.end()) { - branch = block; - return 1; - } - } else if (block->command.arguments.size() == 2) { - if (block->command.arguments[0].compare("not") == 0) { - Vars::iterator it = vars.find(block->command.arguments[1]); - if (it == vars.end()) { branch = block; return 1; } - } - } else if (block->command.arguments.size() == 3) { - if (block->command.arguments[1].compare("and") == 0) { - Vars::iterator itL = vars.find(block->command.arguments[0]); - Vars::iterator itR = vars.find(block->command.arguments[2]); - if ((itL != vars.end()) && (itR != vars.end())) { - branch = block; - return 1; - } - } else if (block->command.arguments[1].compare("or") == 0) { - Vars::iterator itL = vars.find(block->command.arguments[0]); - Vars::iterator itR = vars.find(block->command.arguments[2]); - if ((itL != vars.end()) || (itR != vars.end())) { - branch = block; - return 1; - } - } else if (block->command.arguments[1].compare("==") == 0) { - Vars::iterator itL = vars.find(block->command.arguments[0]); - if (itL != vars.end()) { - if ((*itL).second.compare(block->command.arguments[2]) == 0) { + } else if (block->command.arguments.size() == 2) { + if (block->command.arguments[0].compare("not") == 0) { + Vars::iterator it = vars.find(block->command.arguments[1]); + if (it == vars.end()) { branch = block; return 1; } } - } - } - - } - return 0; - } - break; - case Command::ELSE: { - branch = block; - return 1; - } - break; - case Command::ENDIF: { - branch = block; - return 1; - } - break; - case Command::DEF: { - if (block->command.arguments.size()) { - // THe actual value of the var defined sneeds to be evaluated: - String val; - for (int t = 1; t < block->command.arguments.size(); t++) { - // detect if a param is a var - int len = block->command.arguments[t].length(); - if ((block->command.arguments[t][0] == Tag::VAR) - && (block->command.arguments[t][len-1] == Tag::VAR)) { - String var = block->command.arguments[t].substr(1, len-2); - Vars::iterator it = vars.find(var); - if (it != vars.end()) { - val += (*it).second; + } else if (block->command.arguments.size() == 3) { + if (block->command.arguments[1].compare("and") == 0) { + Vars::iterator itL = vars.find(block->command.arguments[0]); + Vars::iterator itR = vars.find(block->command.arguments[2]); + if ((itL != vars.end()) && (itR != vars.end())) { + branch = block; + return 1; + } + } else if (block->command.arguments[1].compare("or") == 0) { + Vars::iterator itL = vars.find(block->command.arguments[0]); + Vars::iterator itR = vars.find(block->command.arguments[2]); + if ((itL != vars.end()) || (itR != vars.end())) { + branch = block; + return 1; + } + } else if (block->command.arguments[1].compare("==") == 0) { + Vars::iterator itL = vars.find(block->command.arguments[0]); + if (itL != vars.end()) { + if ((*itL).second.compare(block->command.arguments[2]) == 0) { + branch = block; + return 1; + } + } } - } else { - val += block->command.arguments[t]; } - } - Vars::iterator it = vars.find(block->command.arguments.front()); - if (it == vars.end()) { - vars.insert(Vars::value_type(block->command.arguments.front(), val)); + } + return 0; + } + break; + case Command::ELSE: { + branch = block; + return 1; + } + break; + case Command::ENDIF: { + branch = block; + return 1; + } + break; + case Command::DEF: { + if (block->command.arguments.size()) { + // THe actual value of the var defined sneeds to be evaluated: + String val; + for (int t = 1; t < block->command.arguments.size(); t++) { + // detect if a param is a var + int len = block->command.arguments[t].length(); + if ((block->command.arguments[t][0] == Tag::VAR) + && (block->command.arguments[t][len-1] == Tag::VAR)) { + String var = block->command.arguments[t].substr(1, len-2); + Vars::iterator it = vars.find(var); + if (it != vars.end()) { + val += (*it).second; + } + } else { + val += block->command.arguments[t]; + } + } + + Vars::iterator it = vars.find(block->command.arguments.front()); + if (it == vars.end()) { + vars.insert(Vars::value_type(block->command.arguments.front(), val)); + } else { + (*it).second = val; + } + + branch = block; + return 1; } else { - (*it).second = val; + branch = block; + return 0; + } + } + break; + + case Command::INCLUDE: { + TextTemplatePointer include = _config->findInclude(block->command.arguments.front().c_str()); + if (include && !include->_root->blocks.empty()) { + if (&include->_root) { + generateTree(dst, include->_root, vars); + } } branch = block; return 1; - } else { + } + break; + + case Command::FUNC: { branch = block; - return 0; + return 1; } - } - break; + break; - case Command::INCLUDE: { - TextTemplatePointer include = _config->findInclude(block->command.arguments.front().c_str()); - if (include && !include->_root->blocks.empty()) { - if (&include->_root) { - generateTree(dst, include->_root, vars); - } + case Command::ENDFUNC: { + branch = block; + return 1; } + break; - branch = block; - return 1; - } - break; - - case Command::FUNC: { - branch = block; - return 1; - } - break; - - case Command::ENDFUNC: { - branch = block; - return 1; - } - break; - - default: { - } + default: { + } } return 0; diff --git a/tools/scribe/src/TextTemplate.h b/tools/scribe/src/TextTemplate.h index 0a61ae454a..30a17bc1c9 100755 --- a/tools/scribe/src/TextTemplate.h +++ b/tools/scribe/src/TextTemplate.h @@ -95,8 +95,7 @@ public: String sourceName; Block(const String& sourceFilename) : - sourceName(sourceFilename) - {} + sourceName(sourceFilename) {} static void addNewBlock(const Block::Pointer& parent, const Block::Pointer& block); static const Block::Pointer& getCurrentBlock(const Block::Pointer& block); From 522ca55ed8f74ff3a0580e97390a35f272bf0eab Mon Sep 17 00:00:00 2001 From: Sam Gateau Date: Tue, 23 Dec 2014 14:41:49 -0800 Subject: [PATCH 255/258] Fixing typo and syntax --- tools/scribe/src/main.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/scribe/src/main.cpp b/tools/scribe/src/main.cpp index e71b21f32b..e69d927941 100755 --- a/tools/scribe/src/main.cpp +++ b/tools/scribe/src/main.cpp @@ -42,6 +42,7 @@ int main (int argc, char** argv) { GRAB_TARGET_NAME, EXIT, } mode = READY; + for (int ii = 1; (mode != EXIT) && (ii < argc); ii++) { inputs.push_back(argv[ii]); From 4004831377c13f76c2db832a825b57aaeba39f32 Mon Sep 17 00:00:00 2001 From: Sam Gateau Date: Tue, 23 Dec 2014 14:46:58 -0800 Subject: [PATCH 256/258] Fixing typo and syntax --- tools/scribe/src/main.cpp | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/tools/scribe/src/main.cpp b/tools/scribe/src/main.cpp index e69d927941..55f23f8c55 100755 --- a/tools/scribe/src/main.cpp +++ b/tools/scribe/src/main.cpp @@ -29,7 +29,7 @@ int main (int argc, char** argv) { std::string lastVarName; bool listVars = false; bool showParseTree = false; - bool makeCplusplus = false; + bool makeCPlusPlus = false; TextTemplate::Config::Pointer config(new TextTemplate::Config()); @@ -63,7 +63,7 @@ int main (int argc, char** argv) { showParseTree = true; mode = READY; } else if (inputs.back() == "-c++") { - makeCplusplus = true; + makeCPlusPlus = true; mode = READY; } else { // just grabbed the source filename, stop parameter parsing @@ -135,8 +135,7 @@ int main (int argc, char** argv) { } } // no clean it to have just a descent c var name - if (!targetName.empty()) - { + if (!targetName.empty()) { // trim anything before '/' or '\' targetName = targetName.substr(targetName.find_last_of('/') + 1); targetName = targetName.substr(targetName.find_last_of('\\') + 1); @@ -166,7 +165,6 @@ int main (int argc, char** argv) { return 0; } - TextTemplate::Pointer scribe(new TextTemplate(srcFilename, config)); // ready to parse and generate @@ -188,7 +186,7 @@ int main (int argc, char** argv) { } std::ostringstream targetStringStream; - if (makeCplusplus) { + if (makeCPlusPlus) { targetStringStream << "// File generated by Scribe " << vars["_SCRIBE_DATE"] << std::endl; targetStringStream << "#ifndef scribe_" << targetName << "_h" << std::endl; From 249e6d02f8aaae95237540efc9c7629029108f8c Mon Sep 17 00:00:00 2001 From: Sam Gateau Date: Tue, 23 Dec 2014 14:49:06 -0800 Subject: [PATCH 257/258] Fixing typo and syntax --- tools/scribe/src/TextTemplate.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/tools/scribe/src/TextTemplate.cpp b/tools/scribe/src/TextTemplate.cpp index 7c92fe33fa..5d10e55e3f 100755 --- a/tools/scribe/src/TextTemplate.cpp +++ b/tools/scribe/src/TextTemplate.cpp @@ -841,8 +841,8 @@ int TextTemplate::evalBlockGeneration(std::ostream& dst, const BlockPointer& blo // detect if a param is a var int len = block->command.arguments[t].length(); if ((block->command.arguments[t][0] == Tag::VAR) - && (block->command.arguments[t][len-1] == Tag::VAR)) { - String var = block->command.arguments[t].substr(1, len-2); + && (block->command.arguments[t][len - 1] == Tag::VAR)) { + String var = block->command.arguments[t].substr(1, len - 2); Vars::iterator it = vars.find(var); if (it != vars.end()) { val += (*it).second; From 2a54ef01ef2b50d4745206cd4f24be2ea41da3f7 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Tue, 23 Dec 2014 15:06:22 -0800 Subject: [PATCH 258/258] Set texture limit back to 1024 --- interface/src/ModelUploader.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interface/src/ModelUploader.cpp b/interface/src/ModelUploader.cpp index 29d82d3b69..e702d9db76 100644 --- a/interface/src/ModelUploader.cpp +++ b/interface/src/ModelUploader.cpp @@ -57,7 +57,7 @@ static const QString SETTING_NAME = "LastModelUploadLocation"; static const int BYTES_PER_MEGABYTES = 1024 * 1024; static const unsigned long MAX_SIZE = 50 * 1024 * BYTES_PER_MEGABYTES; // 50 GB (Virtually remove limit) -static const int MAX_TEXTURE_SIZE = 4096; +static const int MAX_TEXTURE_SIZE = 1024; static const int TIMEOUT = 1000; static const int MAX_CHECK = 30;