mirror of
https://github.com/overte-org/overte.git
synced 2025-04-23 09:33:29 +02:00
Merge branch 'master' of https://github.com/ZappoMan/hifi
This commit is contained in:
commit
b94976485d
262 changed files with 9831 additions and 7399 deletions
1
BUILD.md
1
BUILD.md
|
@ -13,7 +13,6 @@
|
|||
* [Intel Threading Building Blocks](https://www.threadingbuildingblocks.org/) ~> 4.3
|
||||
* [glm](http://glm.g-truc.net/0.9.5/index.html) ~> 0.9.5.4
|
||||
* [gverb](https://github.com/highfidelity/gverb)
|
||||
* [Soxr](http://sourceforge.net/projects/soxr/) ~> 0.1.1
|
||||
|
||||
The following external projects are optional dependencies. You can indicate to CMake that you would like to include them by passing -DGET_$NAME=1 when running a clean CMake build. For example, to get CMake to download and compile SDL2 you would pass -DGET_SDL2=1.
|
||||
|
||||
|
|
|
@ -46,6 +46,9 @@ if (WIN32)
|
|||
# Caveats: http://stackoverflow.com/questions/2288728/drawbacks-of-using-largeaddressaware-for-32-bit-windows-executables
|
||||
# TODO: Remove when building 64-bit.
|
||||
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /LARGEADDRESSAWARE")
|
||||
# always produce symbols as PDB files
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /Zi")
|
||||
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} /DEBUG /OPT:REF /OPT:ICF")
|
||||
else ()
|
||||
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall -Wextra -fno-strict-aliasing -Wno-unused-parameter")
|
||||
if (CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_GNUCXX)
|
||||
|
@ -112,7 +115,11 @@ set(CMAKE_PREFIX_PATH ${CMAKE_PREFIX_PATH} ${QT_CMAKE_PREFIX_PATH})
|
|||
|
||||
if (APPLE)
|
||||
|
||||
SET(OSX_SDK "10.9" CACHE String "OS X SDK version to look for inside Xcode bundle or at OSX_SDK_PATH")
|
||||
exec_program(sw_vers ARGS -productVersion OUTPUT_VARIABLE OSX_VERSION)
|
||||
string(REGEX MATCH "^[0-9]+\\.[0-9]+" OSX_VERSION ${OSX_VERSION})
|
||||
message(STATUS "Detected OS X version = ${OSX_VERSION}")
|
||||
|
||||
set(OSX_SDK "${OSX_VERSION}" CACHE String "OS X SDK version to look for inside Xcode bundle or at OSX_SDK_PATH")
|
||||
|
||||
# set our OS X deployment target
|
||||
set(CMAKE_OSX_DEPLOYMENT_TARGET 10.8)
|
||||
|
@ -127,13 +134,14 @@ if (APPLE)
|
|||
)
|
||||
|
||||
if (NOT _OSX_DESIRED_SDK_PATH)
|
||||
message(FATAL_ERROR "Could not find OS X ${OSX_SDK} SDK. Please pass OSX_SDK_PATH to CMake to point us to your SDKs directory.")
|
||||
message(STATUS "Could not find OS X ${OSX_SDK} SDK. Will fall back to default. If you want a specific SDK, please pass OSX_SDK and optionally OSX_SDK_PATH to CMake.")
|
||||
else ()
|
||||
message(STATUS "Found OS X ${OSX_SDK} SDK at ${_OSX_DESIRED_SDK_PATH}/MacOSX${OSX_SDK}.sdk")
|
||||
|
||||
# set that as the SDK to use
|
||||
set(CMAKE_OSX_SYSROOT ${_OSX_DESIRED_SDK_PATH}/MacOSX${OSX_SDK}.sdk)
|
||||
endif ()
|
||||
|
||||
# set that as the SDK to use
|
||||
set(CMAKE_OSX_SYSROOT ${_OSX_DESIRED_SDK_PATH}/MacOSX${OSX_SDK}.sdk)
|
||||
endif ()
|
||||
|
||||
# Hide automoc folders (for IDEs)
|
||||
|
@ -181,7 +189,6 @@ setup_externals_binary_dir()
|
|||
option(GET_BULLET "Get Bullet library automatically as external project" 1)
|
||||
option(GET_GLM "Get GLM library automatically as external project" 1)
|
||||
option(GET_GVERB "Get Gverb library automatically as external project" 1)
|
||||
option(GET_SOXR "Get Soxr library automatically as external project" 1)
|
||||
option(GET_TBB "Get Threading Building Blocks library automatically as external project" 1)
|
||||
option(GET_LIBOVR "Get LibOVR library automatically as external project" 1)
|
||||
option(GET_VHACD "Get V-HACD library automatically as external project" 1)
|
||||
|
|
|
@ -233,8 +233,8 @@ void Agent::setIsAvatar(bool isAvatar) {
|
|||
}
|
||||
|
||||
if (_avatarBillboardTimer) {
|
||||
_avatarIdentityTimer->stop();
|
||||
delete _avatarIdentityTimer;
|
||||
_avatarBillboardTimer->stop();
|
||||
delete _avatarBillboardTimer;
|
||||
_avatarBillboardTimer = nullptr;
|
||||
}
|
||||
}
|
||||
|
@ -364,10 +364,15 @@ void Agent::processAgentAvatarAndAudio(float deltaTime) {
|
|||
}
|
||||
|
||||
void Agent::aboutToFinish() {
|
||||
_scriptEngine->stop();
|
||||
setIsAvatar(false);// will stop timers for sending billboards and identity packets
|
||||
if (_scriptEngine) {
|
||||
_scriptEngine->stop();
|
||||
}
|
||||
|
||||
_pingTimer->stop();
|
||||
delete _pingTimer;
|
||||
if (_pingTimer) {
|
||||
_pingTimer->stop();
|
||||
delete _pingTimer;
|
||||
}
|
||||
|
||||
// our entity tree is going to go away so tell that to the EntityScriptingInterface
|
||||
DependencyManager::get<EntityScriptingInterface>()->setEntityTree(NULL);
|
||||
|
|
|
@ -77,7 +77,19 @@ void ScriptableAvatar::update(float deltatime) {
|
|||
int mapping = animationJoints.indexOf(modelJoints[i]);
|
||||
if (mapping != -1 && !_maskedJoints.contains(modelJoints[i])) {
|
||||
JointData& data = _jointData[i];
|
||||
data.rotation = safeMix(floorFrame.rotations.at(i), ceilFrame.rotations.at(i), frameFraction);
|
||||
|
||||
auto newRotation = safeMix(floorFrame.rotations.at(i), ceilFrame.rotations.at(i), frameFraction);
|
||||
auto newTranslation = floorFrame.translations.at(i) * (1.0f - frameFraction) +
|
||||
ceilFrame.translations.at(i) * frameFraction;
|
||||
|
||||
if (data.rotation != newRotation) {
|
||||
data.rotation = newRotation;
|
||||
data.rotationSet = true;
|
||||
}
|
||||
if (data.translation != newTranslation) {
|
||||
data.translation = newTranslation;
|
||||
data.translationSet = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
|
|
|
@ -238,7 +238,6 @@ int OctreeInboundPacketProcessor::sendNackPackets() {
|
|||
return 0;
|
||||
}
|
||||
|
||||
auto nackPacketList = NLPacketList::create(_myServer->getMyEditNackType());
|
||||
auto nodeList = DependencyManager::get<NodeList>();
|
||||
int packetsSent = 0;
|
||||
|
||||
|
@ -272,18 +271,19 @@ int OctreeInboundPacketProcessor::sendNackPackets() {
|
|||
|
||||
auto it = missingSequenceNumbers.constBegin();
|
||||
|
||||
while (it != missingSequenceNumbers.constEnd()) {
|
||||
unsigned short int sequenceNumber = *it;
|
||||
nackPacketList->writePrimitive(sequenceNumber);
|
||||
++it;
|
||||
}
|
||||
|
||||
|
||||
if (nackPacketList->getNumPackets()) {
|
||||
if (it != missingSequenceNumbers.constEnd()) {
|
||||
auto nackPacketList = NLPacketList::create(_myServer->getMyEditNackType());
|
||||
|
||||
while (it != missingSequenceNumbers.constEnd()) {
|
||||
unsigned short int sequenceNumber = *it;
|
||||
nackPacketList->writePrimitive(sequenceNumber);
|
||||
++it;
|
||||
}
|
||||
|
||||
qDebug() << "NACK Sent back to editor/client... destinationNode=" << nodeUUID;
|
||||
|
||||
|
||||
packetsSent += nackPacketList->getNumPackets();
|
||||
|
||||
|
||||
// send the list of nack packets
|
||||
nodeList->sendPacketList(std::move(nackPacketList), *destinationNode);
|
||||
}
|
||||
|
|
2
cmake/externals/LibOVR/CMakeLists.txt
vendored
2
cmake/externals/LibOVR/CMakeLists.txt
vendored
|
@ -43,7 +43,7 @@ if (WIN32)
|
|||
endif()
|
||||
|
||||
elseif(APPLE)
|
||||
|
||||
|
||||
ExternalProject_Add(
|
||||
${EXTERNAL_NAME}
|
||||
URL http://static.oculus.com/sdk-downloads/ovr_sdk_macos_0.5.0.1.tar.gz
|
||||
|
|
7
cmake/externals/polyvox/CMakeLists.txt
vendored
7
cmake/externals/polyvox/CMakeLists.txt
vendored
|
@ -19,19 +19,20 @@ ExternalProject_Get_Property(${EXTERNAL_NAME} INSTALL_DIR)
|
|||
|
||||
if (APPLE)
|
||||
set(INSTALL_NAME_LIBRARY_DIR ${INSTALL_DIR}/lib)
|
||||
message(STATUS "in polyvox INSTALL_NAME_LIBRARY_DIR ${INSTALL_NAME_LIBRARY_DIR}")
|
||||
|
||||
ExternalProject_Add_Step(
|
||||
${EXTERNAL_NAME}
|
||||
change-install-name
|
||||
change-install-name-debug
|
||||
COMMENT "Calling install_name_tool on libraries to fix install name for dylib linking"
|
||||
COMMAND ${CMAKE_COMMAND} -DINSTALL_NAME_LIBRARY_DIR=${INSTALL_NAME_LIBRARY_DIR}/Debug -P ${EXTERNAL_PROJECT_DIR}/OSXInstallNameChange.cmake
|
||||
DEPENDEES install
|
||||
WORKING_DIRECTORY <SOURCE_DIR>
|
||||
LOG 1
|
||||
)
|
||||
|
||||
ExternalProject_Add_Step(
|
||||
${EXTERNAL_NAME}
|
||||
change-install-name
|
||||
change-install-name-release
|
||||
COMMENT "Calling install_name_tool on libraries to fix install name for dylib linking"
|
||||
COMMAND ${CMAKE_COMMAND} -DINSTALL_NAME_LIBRARY_DIR=${INSTALL_NAME_LIBRARY_DIR}/Release -P ${EXTERNAL_PROJECT_DIR}/OSXInstallNameChange.cmake
|
||||
DEPENDEES install
|
||||
|
|
34
cmake/externals/soxr/CMakeLists.txt
vendored
34
cmake/externals/soxr/CMakeLists.txt
vendored
|
@ -1,34 +0,0 @@
|
|||
set(EXTERNAL_NAME soxr)
|
||||
|
||||
if (ANDROID)
|
||||
set(PLATFORM_CMAKE_ARGS "-DCMAKE_TOOLCHAIN_FILE=${CMAKE_TOOLCHAIN_FILE}" "-DANDROID_NATIVE_API_LEVEL=19" "-DHAVE_WORDS_BIGENDIAN_EXITCODE=1")
|
||||
endif ()
|
||||
|
||||
include(ExternalProject)
|
||||
ExternalProject_Add(
|
||||
${EXTERNAL_NAME}
|
||||
URL http://hifi-public.s3.amazonaws.com/dependencies/soxr-0.1.1.zip
|
||||
URL_MD5 349b5b2f323a7380bc12186d98c77d1d
|
||||
CMAKE_ARGS ${PLATFORM_CMAKE_ARGS} -DBUILD_SHARED_LIBS=1 -DBUILD_TESTS=0 -DCMAKE_INSTALL_PREFIX:PATH=<INSTALL_DIR>
|
||||
LOG_DOWNLOAD 1
|
||||
LOG_CONFIGURE 1
|
||||
LOG_BUILD 1
|
||||
BINARY_DIR ${EXTERNAL_PROJECT_PREFIX}/build
|
||||
)
|
||||
|
||||
# Hide this external target (for ide users)
|
||||
set_target_properties(${EXTERNAL_NAME} PROPERTIES FOLDER "hidden/externals")
|
||||
|
||||
ExternalProject_Get_Property(${EXTERNAL_NAME} INSTALL_DIR)
|
||||
|
||||
string(TOUPPER ${EXTERNAL_NAME} EXTERNAL_NAME_UPPER)
|
||||
set(${EXTERNAL_NAME_UPPER}_INCLUDE_DIRS ${INSTALL_DIR}/include CACHE PATH "List of soxr include directories")
|
||||
|
||||
if (WIN32)
|
||||
set(${EXTERNAL_NAME_UPPER}_LIBRARIES ${INSTALL_DIR}/lib/soxr.lib CACHE FILEPATH "List of soxr libraries")
|
||||
set(${EXTERNAL_NAME_UPPER}_DLL_PATH ${INSTALL_DIR}/bin CACHE PATH "Path to soxr dll")
|
||||
elseif (APPLE)
|
||||
set(${EXTERNAL_NAME_UPPER}_LIBRARIES ${INSTALL_DIR}/lib/libsoxr.dylib CACHE FILEPATH "List of soxr libraries")
|
||||
else ()
|
||||
set(${EXTERNAL_NAME_UPPER}_LIBRARIES ${INSTALL_DIR}/lib/libsoxr.so CACHE FILEPATH "List of soxr libraries")
|
||||
endif ()
|
|
@ -37,7 +37,7 @@ macro(COPY_DLLS_BESIDE_WINDOWS_EXECUTABLE)
|
|||
add_custom_command(
|
||||
TARGET ${TARGET_NAME}
|
||||
POST_BUILD
|
||||
COMMAND CMD /C "SET PATH=%PATH%;${QT_DIR}/bin && ${WINDEPLOYQT_COMMAND} $<TARGET_FILE:${TARGET_NAME}>"
|
||||
COMMAND CMD /C "SET PATH=%PATH%;${QT_DIR}/bin && ${WINDEPLOYQT_COMMAND} $<$<OR:$<CONFIG:Release>,$<CONFIG:MinSizeRel>,$<CONFIG:RelWithDebInfo>>:--release> $<TARGET_FILE:${TARGET_NAME}>"
|
||||
)
|
||||
endif ()
|
||||
endmacro()
|
|
@ -1,43 +0,0 @@
|
|||
#
|
||||
# FindSoxr.cmake
|
||||
#
|
||||
# Try to find the libsoxr resampling library
|
||||
#
|
||||
# You can provide a LIBSOXR_ROOT_DIR which contains lib and include directories
|
||||
#
|
||||
# Once done this will define
|
||||
#
|
||||
# SOXR_FOUND - system found libsoxr
|
||||
# SOXR_INCLUDE_DIRS - the libsoxr include directory
|
||||
# SOXR_LIBRARIES - link to this to use libsoxr
|
||||
#
|
||||
# Created on 1/22/2015 by Stephen Birarda
|
||||
# Copyright 2015 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("soxr")
|
||||
|
||||
find_path(SOXR_INCLUDE_DIRS soxr.h PATH_SUFFIXES include HINTS ${SOXR_SEARCH_DIRS})
|
||||
find_library(SOXR_LIBRARIES NAMES soxr PATH_SUFFIXES lib HINTS ${SOXR_SEARCH_DIRS})
|
||||
|
||||
if (WIN32)
|
||||
find_path(SOXR_DLL_PATH soxr.dll PATH_SUFFIXES bin HINTS ${SOXR_SEARCH_DIRS})
|
||||
endif()
|
||||
|
||||
set(SOXR_REQUIREMENTS SOXR_INCLUDE_DIRS SOXR_LIBRARIES)
|
||||
if (WIN32)
|
||||
list(APPEND SOXR_REQUIREMENTS SOXR_DLL_PATH)
|
||||
endif ()
|
||||
|
||||
include(FindPackageHandleStandardArgs)
|
||||
find_package_handle_standard_args(Soxr DEFAULT_MSG ${SOXR_REQUIREMENTS})
|
||||
|
||||
if (WIN32)
|
||||
add_paths_to_fixup_libs(${SOXR_DLL_PATH})
|
||||
endif ()
|
||||
|
||||
mark_as_advanced(SOXR_INCLUDE_DIRS SOXR_LIBRARIES SOXR_SEARCH_DIRS)
|
93
examples/acScripts/flickeringLight.js
Normal file
93
examples/acScripts/flickeringLight.js
Normal file
|
@ -0,0 +1,93 @@
|
|||
//
|
||||
// flickeringLight.js
|
||||
// examples
|
||||
//
|
||||
// Created by Brad Hefta-Gaub on 2015/09/29.
|
||||
// Copyright 2015 High Fidelity, Inc.
|
||||
//
|
||||
// Creates an ephemeral flickering light that will randomly flicker as long as the script is running.
|
||||
// After the script stops running, the light will eventually disappear (~10 seconds later). This script
|
||||
// can run in the interface or in an assignment client and it will work equally well.
|
||||
//
|
||||
// Distributed under the Apache License, Version 2.0.
|
||||
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
|
||||
//
|
||||
|
||||
|
||||
function randFloat(low, high) {
|
||||
return low + Math.random() * (high - low);
|
||||
}
|
||||
|
||||
var LIGHT_NAME = "flickering fire";
|
||||
|
||||
var LIGHT_POSITION = {
|
||||
x: 551.13,
|
||||
y: 494.77,
|
||||
z: 502.26
|
||||
};
|
||||
|
||||
var LIGHT_COLOR = {
|
||||
red: 255,
|
||||
green: 100,
|
||||
blue: 28
|
||||
};
|
||||
|
||||
var ZERO_VEC = {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
};
|
||||
|
||||
var totalTime = 0;
|
||||
var lastUpdate = 0;
|
||||
var UPDATE_INTERVAL = 1 / 30; // 30fps
|
||||
|
||||
var MINIMUM_LIGHT_INTENSITY = 0.75;
|
||||
var MAXIMUM_LIGHT_INTENSITY = 2.75;
|
||||
var LIGHT_INTENSITY_RANDOMNESS = 0.3;
|
||||
var EPHEMERAL_LIFETIME = 60; // ephemeral entities will live for 60 seconds after script stops running
|
||||
|
||||
var LightMaker = {
|
||||
light: null,
|
||||
spawnLight: function() {
|
||||
print('CREATING LIGHT')
|
||||
var _this = this;
|
||||
_this.light = Entities.addEntity({
|
||||
type: "Light",
|
||||
name: LIGHT_NAME,
|
||||
position: LIGHT_POSITION,
|
||||
lifetime: EPHEMERAL_LIFETIME,
|
||||
color: LIGHT_COLOR,
|
||||
dimensions: { x: 10, y: 10, z: 10 }
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
var hasSpawned = false;
|
||||
|
||||
function update(deltaTime) {
|
||||
|
||||
if (!Entities.serversExist() || !Entities.canRez()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (hasSpawned === false) {
|
||||
hasSpawned = true;
|
||||
LightMaker.spawnLight();
|
||||
} else {
|
||||
totalTime += deltaTime;
|
||||
|
||||
// We don't want to edit the entity EVERY update cycle, because that's just a lot
|
||||
// of wasted bandwidth and extra effort on the server for very little visual gain
|
||||
if (totalTime - lastUpdate > UPDATE_INTERVAL) {
|
||||
var intensity = (MINIMUM_LIGHT_INTENSITY + (MAXIMUM_LIGHT_INTENSITY + (Math.sin(totalTime) * MAXIMUM_LIGHT_INTENSITY)));
|
||||
intensity += randFloat(-LIGHT_INTENSITY_RANDOMNESS, LIGHT_INTENSITY_RANDOMNESS);
|
||||
var properties = Entities.getEntityProperties(LightMaker.light, "age");
|
||||
var newLifetime = properties.age + EPHEMERAL_LIFETIME;
|
||||
Entities.editEntity(LightMaker.light, { type: "Light", intensity: intensity, lifetime: newLifetime });
|
||||
lastUpdate = totalTime;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Script.update.connect(update);
|
|
@ -18,7 +18,7 @@ var RainSquall = function (properties) {
|
|||
dropFallSpeed = 1, // m/s
|
||||
dropLifetime = 60, // Seconds
|
||||
dropSpinMax = 0, // Maximum angular velocity per axis; deg/s
|
||||
debug = false, // Display origin circle; don't use running on Stack Manager
|
||||
debug = true, // Display origin circle; don't use running on Stack Manager
|
||||
// Other
|
||||
squallCircle,
|
||||
SQUALL_CIRCLE_COLOR = { red: 255, green: 0, blue: 0 },
|
||||
|
@ -151,8 +151,10 @@ var RainSquall = function (properties) {
|
|||
};
|
||||
};
|
||||
|
||||
var center = Vec3.sum(MyAvatar.position, Vec3.multiply(3, Quat.getFront(Camera.getOrientation())));
|
||||
center.y += 10;
|
||||
var rainSquall1 = new RainSquall({
|
||||
origin: { x: 1195, y: 1223, z: 1020 },
|
||||
origin:center,
|
||||
radius: 25,
|
||||
dropsPerMinute: 120,
|
||||
dropSize: { x: 0.1, y: 0.1, z: 0.1 },
|
||||
|
|
146
examples/actionInspector.js
Normal file
146
examples/actionInspector.js
Normal file
|
@ -0,0 +1,146 @@
|
|||
//
|
||||
// actionInspector.js
|
||||
// examples
|
||||
//
|
||||
// Created by Seth Alves on 2015-9-30.
|
||||
// Copyright 2015 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
|
||||
//
|
||||
|
||||
Script.include("libraries/utils.js");
|
||||
|
||||
|
||||
var INSPECT_RADIUS = 10;
|
||||
var overlays = {};
|
||||
|
||||
|
||||
var toType = function(obj) {
|
||||
return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
|
||||
}
|
||||
|
||||
|
||||
function actionArgumentsToString(actionArguments) {
|
||||
var result = "type: " + actionArguments["type"] + "\n";
|
||||
for (var argumentName in actionArguments) {
|
||||
if (actionArguments.hasOwnProperty(argumentName)) {
|
||||
if (argumentName == "type") {
|
||||
continue;
|
||||
}
|
||||
var arg = actionArguments[argumentName];
|
||||
var argType = toType(arg);
|
||||
var argString = arg;
|
||||
if (argType == "object") {
|
||||
if (Object.keys(arg).length == 3) {
|
||||
argString = vec3toStr(arg, 1);
|
||||
}
|
||||
} else if (argType == "number") {
|
||||
argString = arg.toFixed(2);
|
||||
}
|
||||
result += argumentName + ": "
|
||||
// + toType(arg) + " -- "
|
||||
+ argString + "\n";
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
function updateOverlay(entityID, actionText) {
|
||||
var properties = Entities.getEntityProperties(entityID, ["position", "dimensions"]);
|
||||
var position = Vec3.sum(properties.position, {x:0, y:properties.dimensions.y, z:0});
|
||||
// print("position: " + vec3toStr(position) + " " + actionText);
|
||||
if (entityID in overlays) {
|
||||
var overlay = overlays[entityID];
|
||||
Overlays.editOverlay(overlay, {
|
||||
text: actionText,
|
||||
position: position
|
||||
});
|
||||
} else {
|
||||
var lines = actionText.split(/\r\n|\r|\n/);
|
||||
|
||||
var maxLineLength = lines[0].length;
|
||||
for (var i = 1; i < lines.length; i++) {
|
||||
if (lines[i].length > maxLineLength) {
|
||||
maxLineLength = lines[i].length;
|
||||
}
|
||||
}
|
||||
|
||||
var textWidth = maxLineLength * 0.034; // XXX how to know this?
|
||||
var textHeight = .5;
|
||||
var numberOfLines = lines.length;
|
||||
var textMargin = 0.05;
|
||||
var lineHeight = (textHeight - (2 * textMargin)) / numberOfLines;
|
||||
|
||||
overlays[entityID] = Overlays.addOverlay("text3d", {
|
||||
position: position,
|
||||
dimensions: { x: textWidth, y: textHeight },
|
||||
backgroundColor: { red: 0, green: 0, blue: 0},
|
||||
color: { red: 255, green: 255, blue: 255},
|
||||
topMargin: textMargin,
|
||||
leftMargin: textMargin,
|
||||
bottomMargin: textMargin,
|
||||
rightMargin: textMargin,
|
||||
text: actionText,
|
||||
lineHeight: lineHeight,
|
||||
alpha: 0.9,
|
||||
backgroundAlpha: 0.9,
|
||||
ignoreRayIntersection: true,
|
||||
visible: true,
|
||||
isFacingAvatar: true
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
function cleanup() {
|
||||
for (var entityID in overlays) {
|
||||
Overlays.deleteOverlay(overlays[entityID]);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Script.setInterval(function() {
|
||||
var nearbyEntities = Entities.findEntities(MyAvatar.position, INSPECT_RADIUS);
|
||||
for (var entityIndex = 0; entityIndex < nearbyEntities.length; entityIndex++) {
|
||||
var entityID = nearbyEntities[entityIndex];
|
||||
var actionIDs = Entities.getActionIDs(entityID);
|
||||
var actionText = ""
|
||||
for (var actionIndex = 0; actionIndex < actionIDs.length; actionIndex++) {
|
||||
var actionID = actionIDs[actionIndex];
|
||||
var actionArguments = Entities.getActionArguments(entityID, actionID);
|
||||
var actionArgumentText = actionArgumentsToString(actionArguments);
|
||||
if (actionArgumentText != "") {
|
||||
actionText += "-----------------\n";
|
||||
actionText += actionArgumentText;
|
||||
}
|
||||
}
|
||||
if (actionText != "") {
|
||||
updateOverlay(entityID, actionText);
|
||||
}
|
||||
|
||||
// if an entity no longer has an action, remove its overlay
|
||||
if (actionIDs.length == 0) {
|
||||
if (entityID in overlays) {
|
||||
Overlays.deleteOverlay(overlays[entityID]);
|
||||
delete overlays[entityID];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// if an entity is too far away, remove its overlay
|
||||
for (var entityID in overlays) {
|
||||
var position = Entities.getEntityProperties(entityID, ["position"]).position;
|
||||
if (Vec3.distance(position, MyAvatar.position) > INSPECT_RADIUS) {
|
||||
Overlays.deleteOverlay(overlays[entityID]);
|
||||
delete overlays[entityID];
|
||||
}
|
||||
}
|
||||
|
||||
}, 100);
|
||||
|
||||
|
||||
Script.scriptEnding.connect(cleanup);
|
289
examples/closePaint.js
Normal file
289
examples/closePaint.js
Normal file
|
@ -0,0 +1,289 @@
|
|||
//
|
||||
// closePaint.js
|
||||
// examples
|
||||
//
|
||||
// Created by Eric Levina on 9/30/15.
|
||||
// Copyright 2015 High Fidelity, Inc.
|
||||
//
|
||||
// Run this script to be able to paint on entities you are close to, with hydras.
|
||||
//
|
||||
// Distributed under the Apache License, Version 2.0.
|
||||
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
|
||||
//
|
||||
|
||||
Script.include("libraries/utils.js");
|
||||
|
||||
|
||||
var RIGHT_HAND = 1;
|
||||
var LEFT_HAND = 0;
|
||||
|
||||
var MIN_POINT_DISTANCE = 0.02;
|
||||
var MAX_POINT_DISTANCE = 0.5;
|
||||
|
||||
var SPATIAL_CONTROLLERS_PER_PALM = 2;
|
||||
var TIP_CONTROLLER_OFFSET = 1;
|
||||
|
||||
var TRIGGER_ON_VALUE = 0.3;
|
||||
|
||||
var MAX_DISTANCE = 10;
|
||||
|
||||
var MAX_POINTS_PER_LINE = 40;
|
||||
|
||||
var RIGHT_4_ACTION = 18;
|
||||
var RIGHT_2_ACTION = 16;
|
||||
|
||||
var LEFT_4_ACTION = 17;
|
||||
var LEFT_2_ACTION = 16;
|
||||
|
||||
var HUE_INCREMENT = 0.02;
|
||||
|
||||
var MIN_STROKE_WIDTH = 0.002;
|
||||
var MAX_STROKE_WIDTH = 0.04;
|
||||
|
||||
|
||||
var center = Vec3.sum(MyAvatar.position, Vec3.multiply(2, Quat.getFront(Camera.getOrientation())));
|
||||
|
||||
|
||||
|
||||
function MyController(hand, triggerAction) {
|
||||
this.hand = hand;
|
||||
this.strokes = [];
|
||||
this.painting = false;
|
||||
this.currentStrokeWidth = MIN_STROKE_WIDTH;
|
||||
|
||||
if (this.hand === RIGHT_HAND) {
|
||||
this.getHandPosition = MyAvatar.getRightPalmPosition;
|
||||
this.getHandRotation = MyAvatar.getRightPalmRotation;
|
||||
} else {
|
||||
this.getHandPosition = MyAvatar.getLeftPalmPosition;
|
||||
this.getHandRotation = MyAvatar.getLeftPalmRotation;
|
||||
}
|
||||
|
||||
this.triggerAction = triggerAction;
|
||||
this.palm = SPATIAL_CONTROLLERS_PER_PALM * hand;
|
||||
this.tip = SPATIAL_CONTROLLERS_PER_PALM * hand + TIP_CONTROLLER_OFFSET;
|
||||
|
||||
|
||||
this.strokeColor = {
|
||||
h: 0.8,
|
||||
s: 0.8,
|
||||
l: 0.4
|
||||
};
|
||||
|
||||
|
||||
this.laserPointer = Overlays.addOverlay("circle3d", {
|
||||
color: hslToRgb(this.strokeColor),
|
||||
solid: true,
|
||||
position: center
|
||||
});
|
||||
this.triggerValue = 0;
|
||||
this.prevTriggerValue = 0;
|
||||
var _this = this;
|
||||
|
||||
this.update = function() {
|
||||
this.updateControllerState();
|
||||
this.search();
|
||||
if (this.canPaint === true) {
|
||||
this.paint(this.intersection.intersection, this.intersection.surfaceNormal);
|
||||
}
|
||||
};
|
||||
|
||||
this.paint = function(position, normal) {
|
||||
if (this.painting === false) {
|
||||
if (this.oldPosition) {
|
||||
this.newStroke(this.oldPosition);
|
||||
} else {
|
||||
this.newStroke(position);
|
||||
}
|
||||
this.painting = true;
|
||||
}
|
||||
|
||||
|
||||
|
||||
var localPoint = Vec3.subtract(position, this.strokeBasePosition);
|
||||
//Move stroke a bit forward along normal so it doesnt zfight with mesh its drawing on
|
||||
localPoint = Vec3.sum(localPoint, Vec3.multiply(normal, 0.001 + Math.random() * .001)); //rand avoid z fighting
|
||||
|
||||
var distance = Vec3.distance(localPoint, this.strokePoints[this.strokePoints.length - 1]);
|
||||
if (this.strokePoints.length > 0 && distance < MIN_POINT_DISTANCE) {
|
||||
//need a minimum distance to avoid binormal NANs
|
||||
return;
|
||||
}
|
||||
if (this.strokePoints.length > 0 && distance > MAX_POINT_DISTANCE) {
|
||||
//Prevents drawing lines accross models
|
||||
this.painting = false;
|
||||
return;
|
||||
}
|
||||
if (this.strokePoints.length === 0) {
|
||||
localPoint = {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
};
|
||||
}
|
||||
|
||||
this.strokePoints.push(localPoint);
|
||||
this.strokeNormals.push(normal);
|
||||
this.strokeWidths.push(this.currentStrokeWidth);
|
||||
Entities.editEntity(this.currentStroke, {
|
||||
linePoints: this.strokePoints,
|
||||
normals: this.strokeNormals,
|
||||
strokeWidths: this.strokeWidths
|
||||
});
|
||||
if (this.strokePoints.length === MAX_POINTS_PER_LINE) {
|
||||
this.painting = false;
|
||||
return;
|
||||
}
|
||||
this.oldPosition = position;
|
||||
}
|
||||
|
||||
this.newStroke = function(position) {
|
||||
this.strokeBasePosition = position;
|
||||
this.currentStroke = Entities.addEntity({
|
||||
position: position,
|
||||
type: "PolyLine",
|
||||
color: hslToRgb(this.strokeColor),
|
||||
dimensions: {
|
||||
x: 50,
|
||||
y: 50,
|
||||
z: 50
|
||||
},
|
||||
lifetime: 200
|
||||
});
|
||||
this.strokePoints = [];
|
||||
this.strokeNormals = [];
|
||||
this.strokeWidths = [];
|
||||
|
||||
this.strokes.push(this.currentStroke);
|
||||
|
||||
}
|
||||
|
||||
this.updateControllerState = function() {
|
||||
this.triggerValue = Controller.getActionValue(this.triggerAction);
|
||||
if (this.triggerValue > TRIGGER_ON_VALUE && this.prevTriggerValue <= TRIGGER_ON_VALUE) {
|
||||
this.squeeze();
|
||||
} else if (this.triggerValue < TRIGGER_ON_VALUE && this.prevTriggerValue >= TRIGGER_ON_VALUE) {
|
||||
this.release();
|
||||
}
|
||||
|
||||
this.prevTriggerValue = this.triggerValue;
|
||||
}
|
||||
|
||||
this.squeeze = function() {
|
||||
this.tryPainting = true;
|
||||
|
||||
}
|
||||
this.release = function() {
|
||||
this.painting = false;
|
||||
this.tryPainting = false;
|
||||
this.canPaint = false;
|
||||
this.oldPosition = null;
|
||||
}
|
||||
this.search = function() {
|
||||
|
||||
// the trigger is being pressed, do a ray test
|
||||
var handPosition = this.getHandPosition();
|
||||
var pickRay = {
|
||||
origin: handPosition,
|
||||
direction: Quat.getUp(this.getHandRotation())
|
||||
};
|
||||
|
||||
|
||||
this.intersection = Entities.findRayIntersection(pickRay, true);
|
||||
if (this.intersection.intersects) {
|
||||
var distance = Vec3.distance(handPosition, this.intersection.intersection);
|
||||
if (distance < MAX_DISTANCE) {
|
||||
var displayPoint = this.intersection.intersection;
|
||||
displayPoint = Vec3.sum(displayPoint, Vec3.multiply(this.intersection.surfaceNormal, .01));
|
||||
if (this.tryPainting) {
|
||||
this.canPaint = true;
|
||||
}
|
||||
this.currentStrokeWidth = map(this.triggerValue, TRIGGER_ON_VALUE, 1, MIN_STROKE_WIDTH, MAX_STROKE_WIDTH);
|
||||
var laserSize = map(distance, 1, MAX_DISTANCE, 0.01, 0.1);
|
||||
laserSize += this.currentStrokeWidth / 2;
|
||||
Overlays.editOverlay(this.laserPointer, {
|
||||
visible: true,
|
||||
position: displayPoint,
|
||||
rotation: orientationOf(this.intersection.surfaceNormal),
|
||||
size: {
|
||||
x: laserSize,
|
||||
y: laserSize
|
||||
}
|
||||
});
|
||||
|
||||
} else {
|
||||
this.hitFail();
|
||||
}
|
||||
} else {
|
||||
this.hitFail();
|
||||
}
|
||||
};
|
||||
|
||||
this.hitFail = function() {
|
||||
this.canPaint = false;
|
||||
|
||||
Overlays.editOverlay(this.laserPointer, {
|
||||
visible: false
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
this.cleanup = function() {
|
||||
Overlays.deleteOverlay(this.laserPointer);
|
||||
this.strokes.forEach(function(stroke) {
|
||||
Entities.deleteEntity(stroke);
|
||||
});
|
||||
}
|
||||
|
||||
this.cycleColorDown = function() {
|
||||
this.strokeColor.h -= HUE_INCREMENT;
|
||||
if (this.strokeColor.h < 0) {
|
||||
this.strokeColor = 1;
|
||||
}
|
||||
Overlays.editOverlay(this.laserPointer, {
|
||||
color: hslToRgb(this.strokeColor)
|
||||
});
|
||||
}
|
||||
|
||||
this.cycleColorUp = function() {
|
||||
this.strokeColor.h += HUE_INCREMENT;
|
||||
if (this.strokeColor.h > 1) {
|
||||
this.strokeColor.h = 0;
|
||||
}
|
||||
Overlays.editOverlay(this.laserPointer, {
|
||||
color: hslToRgb(this.strokeColor)
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
var rightController = new MyController(RIGHT_HAND, Controller.findAction("RIGHT_HAND_CLICK"));
|
||||
var leftController = new MyController(LEFT_HAND, Controller.findAction("LEFT_HAND_CLICK"));
|
||||
|
||||
Controller.actionEvent.connect(function(action, state) {
|
||||
if (state === 0) {
|
||||
return;
|
||||
}
|
||||
if (action === RIGHT_4_ACTION) {
|
||||
rightController.cycleColorUp();
|
||||
} else if (action === RIGHT_2_ACTION) {
|
||||
rightController.cycleColorDown();
|
||||
}
|
||||
if (action === LEFT_4_ACTION) {
|
||||
leftController.cycleColorUp();
|
||||
} else if (action === LEFT_2_ACTION) {
|
||||
leftController.cycleColorDown();
|
||||
}
|
||||
});
|
||||
|
||||
function update() {
|
||||
rightController.update();
|
||||
leftController.update();
|
||||
}
|
||||
|
||||
function cleanup() {
|
||||
rightController.cleanup();
|
||||
leftController.cleanup();
|
||||
}
|
||||
|
||||
Script.scriptEnding.connect(cleanup);
|
||||
Script.update.connect(update);
|
|
@ -2,24 +2,25 @@
|
|||
// examples
|
||||
//
|
||||
// Created by Eric Levin on 9/2/15
|
||||
// Additions by James B. Pollack @imgntn on 9/24/2015
|
||||
// Copyright 2015 High Fidelity, Inc.
|
||||
//
|
||||
// Grabs physically moveable entities with hydra-like controllers; it works for either near or far objects.
|
||||
//
|
||||
// Distributed under the Apache License, Version 2.0.
|
||||
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
|
||||
//
|
||||
/*global print, MyAvatar, Entities, AnimationCache, SoundCache, Scene, Camera, Overlays, Audio, HMD, AvatarList, AvatarManager, Controller, UndoStack, Window, Account, GlobalServices, Script, ScriptDiscoveryService, LODManager, Menu, Vec3, Quat, AudioDevice, Paths, Clipboard, Settings, XMLHttpRequest, randFloat, randInt, pointInExtents, vec3equal, setEntityCustomData, getEntityCustomData */
|
||||
|
||||
Script.include("../libraries/utils.js");
|
||||
|
||||
|
||||
/////////////////////////////////////////////////////////////////
|
||||
//
|
||||
// these tune time-averaging and "on" value for analog trigger
|
||||
//
|
||||
|
||||
var TRIGGER_SMOOTH_RATIO = 0.1; // 0.0 disables smoothing of trigger value
|
||||
var TRIGGER_ON_VALUE = 0.2;
|
||||
var TRIGGER_ON_VALUE = 0.4;
|
||||
var TRIGGER_OFF_VALUE = 0.15;
|
||||
|
||||
/////////////////////////////////////////////////////////////////
|
||||
//
|
||||
|
@ -29,9 +30,9 @@ var TRIGGER_ON_VALUE = 0.2;
|
|||
var DISTANCE_HOLDING_RADIUS_FACTOR = 5; // multiplied by distance between hand and object
|
||||
var DISTANCE_HOLDING_ACTION_TIMEFRAME = 0.1; // how quickly objects move to their new position
|
||||
var DISTANCE_HOLDING_ROTATION_EXAGGERATION_FACTOR = 2.0; // object rotates this much more than hand did
|
||||
var NO_INTERSECT_COLOR = {red: 10, green: 10, blue: 255}; // line color when pick misses
|
||||
var INTERSECT_COLOR = {red: 250, green: 10, blue: 10}; // line color when pick hits
|
||||
var LINE_ENTITY_DIMENSIONS = {x: 1000, y: 1000, z: 1000};
|
||||
var NO_INTERSECT_COLOR = { red: 10, green: 10, blue: 255}; // line color when pick misses
|
||||
var INTERSECT_COLOR = { red: 250, green: 10, blue: 10}; // line color when pick hits
|
||||
var LINE_ENTITY_DIMENSIONS = { x: 1000, y: 1000, z: 1000};
|
||||
var LINE_LENGTH = 500;
|
||||
|
||||
|
||||
|
@ -54,25 +55,55 @@ var RELEASE_VELOCITY_MULTIPLIER = 1.5; // affects throwing things
|
|||
var RIGHT_HAND = 1;
|
||||
var LEFT_HAND = 0;
|
||||
|
||||
var ZERO_VEC = {x: 0, y: 0, z: 0};
|
||||
var ZERO_VEC = {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
};
|
||||
var NULL_ACTION_ID = "{00000000-0000-0000-000000000000}";
|
||||
var MSEC_PER_SEC = 1000.0;
|
||||
|
||||
// these control how long an abandoned pointer line will hang around
|
||||
var startTime = Date.now();
|
||||
var LIFETIME = 10;
|
||||
var ACTION_LIFETIME = 10; // seconds
|
||||
|
||||
// states for the state machine
|
||||
var STATE_SEARCHING = 0;
|
||||
var STATE_DISTANCE_HOLDING = 1;
|
||||
var STATE_CONTINUE_DISTANCE_HOLDING = 2;
|
||||
var STATE_NEAR_GRABBING = 3;
|
||||
var STATE_CONTINUE_NEAR_GRABBING = 4;
|
||||
var STATE_RELEASE = 5;
|
||||
var STATE_OFF = 0;
|
||||
var STATE_SEARCHING = 1;
|
||||
var STATE_DISTANCE_HOLDING = 2;
|
||||
var STATE_CONTINUE_DISTANCE_HOLDING = 3;
|
||||
var STATE_NEAR_GRABBING = 4;
|
||||
var STATE_CONTINUE_NEAR_GRABBING = 5;
|
||||
var STATE_NEAR_GRABBING_NON_COLLIDING = 6;
|
||||
var STATE_CONTINUE_NEAR_GRABBING_NON_COLLIDING = 7;
|
||||
var STATE_RELEASE = 8;
|
||||
|
||||
var GRAB_USER_DATA_KEY = "grabKey";
|
||||
var GRABBABLE_DATA_KEY = "grabbableKey";
|
||||
|
||||
function controller(hand, triggerAction) {
|
||||
function getTag() {
|
||||
return "grab-" + MyAvatar.sessionUUID;
|
||||
}
|
||||
|
||||
function entityIsGrabbedByOther(entityID) {
|
||||
var actionIDs = Entities.getActionIDs(entityID);
|
||||
for (var actionIndex = 0; actionIndex < actionIDs.length; actionIndex++) {
|
||||
var actionID = actionIDs[actionIndex];
|
||||
var actionArguments = Entities.getActionArguments(entityID, actionID);
|
||||
var tag = actionArguments["tag"];
|
||||
if (tag == getTag()) {
|
||||
continue;
|
||||
}
|
||||
if (tag.slice(0, 5) == "grab-") {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
function MyController(hand, triggerAction) {
|
||||
this.hand = hand;
|
||||
if (this.hand === RIGHT_HAND) {
|
||||
this.getHandPosition = MyAvatar.getRightPalmPosition;
|
||||
|
@ -81,19 +112,31 @@ function controller(hand, triggerAction) {
|
|||
this.getHandPosition = MyAvatar.getLeftPalmPosition;
|
||||
this.getHandRotation = MyAvatar.getLeftPalmRotation;
|
||||
}
|
||||
|
||||
var SPATIAL_CONTROLLERS_PER_PALM = 2;
|
||||
var TIP_CONTROLLER_OFFSET = 1;
|
||||
this.triggerAction = triggerAction;
|
||||
this.palm = 2 * hand;
|
||||
// this.tip = 2 * hand + 1; // unused, but I'm leaving this here for fear it will be needed
|
||||
this.palm = SPATIAL_CONTROLLERS_PER_PALM * hand;
|
||||
this.tip = SPATIAL_CONTROLLERS_PER_PALM * hand + TIP_CONTROLLER_OFFSET;
|
||||
|
||||
this.actionID = null; // action this script created...
|
||||
this.grabbedEntity = null; // on this entity.
|
||||
this.grabbedVelocity = ZERO_VEC; // rolling average of held object's velocity
|
||||
this.state = 0;
|
||||
this.state = STATE_OFF;
|
||||
this.pointer = null; // entity-id of line object
|
||||
this.triggerValue = 0; // rolling average of trigger value
|
||||
|
||||
var _this = this;
|
||||
|
||||
this.update = function() {
|
||||
switch(this.state) {
|
||||
|
||||
this.updateSmoothedTrigger();
|
||||
|
||||
switch (this.state) {
|
||||
case STATE_OFF:
|
||||
this.off();
|
||||
this.touchTest();
|
||||
break;
|
||||
case STATE_SEARCHING:
|
||||
this.search();
|
||||
break;
|
||||
|
@ -109,69 +152,93 @@ function controller(hand, triggerAction) {
|
|||
case STATE_CONTINUE_NEAR_GRABBING:
|
||||
this.continueNearGrabbing();
|
||||
break;
|
||||
case STATE_NEAR_GRABBING_NON_COLLIDING:
|
||||
this.nearGrabbingNonColliding();
|
||||
break;
|
||||
case STATE_CONTINUE_NEAR_GRABBING_NON_COLLIDING:
|
||||
this.continueNearGrabbingNonColliding();
|
||||
break;
|
||||
case STATE_RELEASE:
|
||||
this.release();
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
this.lineOn = function(closePoint, farPoint, color) {
|
||||
// draw a line
|
||||
if (this.pointer == null) {
|
||||
if (this.pointer === null) {
|
||||
this.pointer = Entities.addEntity({
|
||||
type: "Line",
|
||||
name: "pointer",
|
||||
dimensions: LINE_ENTITY_DIMENSIONS,
|
||||
visible: true,
|
||||
position: closePoint,
|
||||
linePoints: [ ZERO_VEC, farPoint ],
|
||||
linePoints: [ZERO_VEC, farPoint],
|
||||
color: color,
|
||||
lifetime: LIFETIME
|
||||
});
|
||||
} else {
|
||||
Entities.editEntity(this.pointer, {
|
||||
position: closePoint,
|
||||
linePoints: [ ZERO_VEC, farPoint ],
|
||||
linePoints: [ZERO_VEC, farPoint],
|
||||
color: color,
|
||||
lifetime: (Date.now() - startTime) / MSEC_PER_SEC + LIFETIME
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
this.lineOff = function() {
|
||||
if (this.pointer != null) {
|
||||
if (this.pointer !== null) {
|
||||
Entities.deleteEntity(this.pointer);
|
||||
}
|
||||
this.pointer = null;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
this.triggerSmoothedSqueezed = function() {
|
||||
this.updateSmoothedTrigger = function() {
|
||||
var triggerValue = Controller.getActionValue(this.triggerAction);
|
||||
// smooth out trigger value
|
||||
this.triggerValue = (this.triggerValue * TRIGGER_SMOOTH_RATIO) +
|
||||
(triggerValue * (1.0 - TRIGGER_SMOOTH_RATIO));
|
||||
return this.triggerValue > TRIGGER_ON_VALUE;
|
||||
}
|
||||
|
||||
this.triggerSmoothedSqueezed = function() {
|
||||
return this.triggerValue > TRIGGER_ON_VALUE;
|
||||
};
|
||||
|
||||
this.triggerSmoothedReleased = function() {
|
||||
return this.triggerValue < TRIGGER_OFF_VALUE;
|
||||
};
|
||||
|
||||
this.triggerSqueezed = function() {
|
||||
var triggerValue = Controller.getActionValue(this.triggerAction);
|
||||
return triggerValue > TRIGGER_ON_VALUE;
|
||||
};
|
||||
|
||||
this.off = function() {
|
||||
if (this.triggerSmoothedSqueezed()) {
|
||||
this.state = STATE_SEARCHING;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
this.search = function() {
|
||||
if (!this.triggerSmoothedSqueezed()) {
|
||||
if (this.triggerSmoothedReleased()) {
|
||||
this.state = STATE_RELEASE;
|
||||
return;
|
||||
}
|
||||
|
||||
// the trigger is being pressed, do a ray test
|
||||
var handPosition = this.getHandPosition();
|
||||
var pickRay = {origin: handPosition, direction: Quat.getUp(this.getHandRotation())};
|
||||
var pickRay = {
|
||||
origin: handPosition,
|
||||
direction: Quat.getUp(this.getHandRotation())
|
||||
};
|
||||
|
||||
var defaultGrabbableData = {
|
||||
grabbable: true
|
||||
};
|
||||
|
||||
var intersection = Entities.findRayIntersection(pickRay, true);
|
||||
if (intersection.intersects &&
|
||||
intersection.properties.collisionsWillMove === 1 &&
|
||||
|
@ -180,10 +247,20 @@ function controller(hand, triggerAction) {
|
|||
var handControllerPosition = Controller.getSpatialControlPosition(this.palm);
|
||||
var intersectionDistance = Vec3.distance(handControllerPosition, intersection.intersection);
|
||||
this.grabbedEntity = intersection.entityID;
|
||||
|
||||
var grabbableData = getEntityCustomData(GRABBABLE_DATA_KEY, intersection.entityID, defaultGrabbableData);
|
||||
if (grabbableData.grabbable === false) {
|
||||
return;
|
||||
}
|
||||
if (intersectionDistance < NEAR_PICK_MAX_DISTANCE) {
|
||||
// the hand is very close to the intersected object. go into close-grabbing mode.
|
||||
this.state = STATE_NEAR_GRABBING;
|
||||
|
||||
} else {
|
||||
if (entityIsGrabbedByOther(intersection.entityID)) {
|
||||
// don't allow two people to distance grab the same object
|
||||
return;
|
||||
}
|
||||
// the hand is far from the intersected object. go into distance-holding mode
|
||||
this.state = STATE_DISTANCE_HOLDING;
|
||||
this.lineOn(pickRay.origin, Vec3.multiply(pickRay.direction, LINE_LENGTH), NO_INTERSECT_COLOR);
|
||||
|
@ -192,30 +269,40 @@ function controller(hand, triggerAction) {
|
|||
// forward ray test failed, try sphere test.
|
||||
var nearbyEntities = Entities.findEntities(handPosition, GRAB_RADIUS);
|
||||
var minDistance = GRAB_RADIUS;
|
||||
var grabbedEntity = null;
|
||||
for (var i = 0; i < nearbyEntities.length; i++) {
|
||||
var props = Entities.getEntityProperties(nearbyEntities[i]);
|
||||
var distance = Vec3.distance(props.position, handPosition);
|
||||
if (distance < minDistance && props.name !== "pointer" &&
|
||||
props.collisionsWillMove === 1 &&
|
||||
props.locked === 0) {
|
||||
var i, props, distance;
|
||||
|
||||
for (i = 0; i < nearbyEntities.length; i++) {
|
||||
|
||||
var grabbableData = getEntityCustomData(GRABBABLE_DATA_KEY, nearbyEntities[i], defaultGrabbableData);
|
||||
if (grabbableData.grabbable === false) {
|
||||
return;
|
||||
}
|
||||
|
||||
props = Entities.getEntityProperties(nearbyEntities[i], ["position", "name", "collisionsWillMove", "locked"]);
|
||||
|
||||
distance = Vec3.distance(props.position, handPosition);
|
||||
if (distance < minDistance && props.name !== "pointer") {
|
||||
this.grabbedEntity = nearbyEntities[i];
|
||||
minDistance = distance;
|
||||
}
|
||||
}
|
||||
if (this.grabbedEntity === null) {
|
||||
this.lineOn(pickRay.origin, Vec3.multiply(pickRay.direction, LINE_LENGTH), NO_INTERSECT_COLOR);
|
||||
} else {
|
||||
} else if (props.locked === 0 && props.collisionsWillMove === 1) {
|
||||
this.state = STATE_NEAR_GRABBING;
|
||||
} else if (props.collisionsWillMove === 0) {
|
||||
// We have grabbed a non-physical object, so we want to trigger a non-colliding event as opposed to a grab event
|
||||
this.state = STATE_NEAR_GRABBING_NON_COLLIDING;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
this.distanceHolding = function() {
|
||||
|
||||
var handControllerPosition = Controller.getSpatialControlPosition(this.palm);
|
||||
var handRotation = Quat.multiply(MyAvatar.orientation, Controller.getSpatialControlRawRotation(this.palm));
|
||||
var grabbedProperties = Entities.getEntityProperties(this.grabbedEntity, ["position","rotation"]);
|
||||
var grabbedProperties = Entities.getEntityProperties(this.grabbedEntity, ["position", "rotation"]);
|
||||
|
||||
// add the action and initialize some variables
|
||||
this.currentObjectPosition = grabbedProperties.position;
|
||||
|
@ -224,32 +311,37 @@ function controller(hand, triggerAction) {
|
|||
this.handPreviousPosition = handControllerPosition;
|
||||
this.handPreviousRotation = handRotation;
|
||||
|
||||
this.actionID = NULL_ACTION_ID;
|
||||
this.actionID = Entities.addAction("spring", this.grabbedEntity, {
|
||||
targetPosition: this.currentObjectPosition,
|
||||
linearTimeScale: DISTANCE_HOLDING_ACTION_TIMEFRAME,
|
||||
targetRotation: this.currentObjectRotation,
|
||||
angularTimeScale: DISTANCE_HOLDING_ACTION_TIMEFRAME
|
||||
angularTimeScale: DISTANCE_HOLDING_ACTION_TIMEFRAME,
|
||||
tag: getTag(),
|
||||
lifetime: ACTION_LIFETIME
|
||||
});
|
||||
if (this.actionID == NULL_ACTION_ID) {
|
||||
if (this.actionID === NULL_ACTION_ID) {
|
||||
this.actionID = null;
|
||||
}
|
||||
|
||||
if (this.actionID != null) {
|
||||
if (this.actionID !== null) {
|
||||
this.state = STATE_CONTINUE_DISTANCE_HOLDING;
|
||||
this.activateEntity(this.grabbedEntity);
|
||||
Entities.callEntityMethod(this.grabbedEntity, "startDistantGrab");
|
||||
|
||||
if (this.hand === RIGHT_HAND) {
|
||||
Entities.callEntityMethod(this.grabbedEntity, "setRightHand");
|
||||
} else {
|
||||
Entities.callEntityMethod(this.grabbedEntity, "setLeftHand");
|
||||
}
|
||||
Entities.callEntityMethod(this.grabbedEntity, "startDistantGrab");
|
||||
}
|
||||
}
|
||||
|
||||
this.currentAvatarPosition = MyAvatar.position;
|
||||
this.currentAvatarOrientation = MyAvatar.orientation;
|
||||
|
||||
};
|
||||
|
||||
this.continueDistanceHolding = function() {
|
||||
if (!this.triggerSmoothedSqueezed()) {
|
||||
if (this.triggerSmoothedReleased()) {
|
||||
this.state = STATE_RELEASE;
|
||||
return;
|
||||
}
|
||||
|
@ -262,15 +354,48 @@ function controller(hand, triggerAction) {
|
|||
this.lineOn(handPosition, Vec3.subtract(grabbedProperties.position, handPosition), INTERSECT_COLOR);
|
||||
|
||||
// the action was set up on a previous call. update the targets.
|
||||
var radius = Math.max(Vec3.distance(this.currentObjectPosition,
|
||||
handControllerPosition) * DISTANCE_HOLDING_RADIUS_FACTOR,
|
||||
DISTANCE_HOLDING_RADIUS_FACTOR);
|
||||
var radius = Math.max(Vec3.distance(this.currentObjectPosition, handControllerPosition) * DISTANCE_HOLDING_RADIUS_FACTOR, DISTANCE_HOLDING_RADIUS_FACTOR);
|
||||
|
||||
// how far did avatar move this timestep?
|
||||
var currentPosition = MyAvatar.position;
|
||||
var avatarDeltaPosition = Vec3.subtract(currentPosition, this.currentAvatarPosition);
|
||||
this.currentAvatarPosition = currentPosition;
|
||||
|
||||
// How far did the avatar turn this timestep?
|
||||
// Note: The following code is too long because we need a Quat.quatBetween() function
|
||||
// that returns the minimum quaternion between two quaternions.
|
||||
var currentOrientation = MyAvatar.orientation;
|
||||
if (Quat.dot(currentOrientation, this.currentAvatarOrientation) < 0.0) {
|
||||
var negativeCurrentOrientation = {
|
||||
x: -currentOrientation.x,
|
||||
y: -currentOrientation.y,
|
||||
z: -currentOrientation.z,
|
||||
w: -currentOrientation.w
|
||||
};
|
||||
var avatarDeltaOrientation = Quat.multiply(negativeCurrentOrientation, Quat.inverse(this.currentAvatarOrientation));
|
||||
} else {
|
||||
var avatarDeltaOrientation = Quat.multiply(currentOrientation, Quat.inverse(this.currentAvatarOrientation));
|
||||
}
|
||||
var handToAvatar = Vec3.subtract(handControllerPosition, this.currentAvatarPosition);
|
||||
var objectToAvatar = Vec3.subtract(this.currentObjectPosition, this.currentAvatarPosition);
|
||||
var handMovementFromTurning = Vec3.subtract(Quat.multiply(avatarDeltaOrientation, handToAvatar), handToAvatar);
|
||||
var objectMovementFromTurning = Vec3.subtract(Quat.multiply(avatarDeltaOrientation, objectToAvatar), objectToAvatar);
|
||||
this.currentAvatarOrientation = currentOrientation;
|
||||
|
||||
// how far did hand move this timestep?
|
||||
var handMoved = Vec3.subtract(handControllerPosition, this.handPreviousPosition);
|
||||
this.handPreviousPosition = handControllerPosition;
|
||||
|
||||
// magnify the hand movement but not the change from avatar movement & rotation
|
||||
handMoved = Vec3.subtract(handMoved, avatarDeltaPosition);
|
||||
handMoved = Vec3.subtract(handMoved, handMovementFromTurning);
|
||||
var superHandMoved = Vec3.multiply(handMoved, radius);
|
||||
|
||||
// Move the object by the magnified amount and then by amount from avatar movement & rotation
|
||||
var newObjectPosition = Vec3.sum(this.currentObjectPosition, superHandMoved);
|
||||
newObjectPosition = Vec3.sum(newObjectPosition, avatarDeltaPosition);
|
||||
newObjectPosition = Vec3.sum(newObjectPosition, objectMovementFromTurning);
|
||||
|
||||
var deltaPosition = Vec3.subtract(newObjectPosition, this.currentObjectPosition); // meters
|
||||
var now = Date.now();
|
||||
var deltaTime = (now - this.currentObjectTime) / MSEC_PER_SEC; // convert to seconds
|
||||
|
@ -280,23 +405,24 @@ function controller(hand, triggerAction) {
|
|||
this.currentObjectTime = now;
|
||||
|
||||
// this doubles hand rotation
|
||||
var handChange = Quat.multiply(Quat.slerp(this.handPreviousRotation, handRotation,
|
||||
DISTANCE_HOLDING_ROTATION_EXAGGERATION_FACTOR),
|
||||
Quat.inverse(this.handPreviousRotation));
|
||||
var handChange = Quat.multiply(Quat.slerp(this.handPreviousRotation, handRotation, DISTANCE_HOLDING_ROTATION_EXAGGERATION_FACTOR), Quat.inverse(this.handPreviousRotation));
|
||||
this.handPreviousRotation = handRotation;
|
||||
this.currentObjectRotation = Quat.multiply(handChange, this.currentObjectRotation);
|
||||
|
||||
Entities.callEntityMethod(this.grabbedEntity, "continueDistantGrab");
|
||||
|
||||
Entities.updateAction(this.grabbedEntity, this.actionID, {
|
||||
targetPosition: this.currentObjectPosition, linearTimeScale: DISTANCE_HOLDING_ACTION_TIMEFRAME,
|
||||
targetRotation: this.currentObjectRotation, angularTimeScale: DISTANCE_HOLDING_ACTION_TIMEFRAME
|
||||
targetPosition: this.currentObjectPosition,
|
||||
linearTimeScale: DISTANCE_HOLDING_ACTION_TIMEFRAME,
|
||||
targetRotation: this.currentObjectRotation,
|
||||
angularTimeScale: DISTANCE_HOLDING_ACTION_TIMEFRAME,
|
||||
lifetime: ACTION_LIFETIME
|
||||
});
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
this.nearGrabbing = function() {
|
||||
if (!this.triggerSmoothedSqueezed()) {
|
||||
|
||||
if (this.triggerSmoothedReleased()) {
|
||||
this.state = STATE_RELEASE;
|
||||
return;
|
||||
}
|
||||
|
@ -313,52 +439,151 @@ function controller(hand, triggerAction) {
|
|||
var objectRotation = grabbedProperties.rotation;
|
||||
var offsetRotation = Quat.multiply(Quat.inverse(handRotation), objectRotation);
|
||||
|
||||
currentObjectPosition = grabbedProperties.position;
|
||||
var currentObjectPosition = grabbedProperties.position;
|
||||
var offset = Vec3.subtract(currentObjectPosition, handPosition);
|
||||
var offsetPosition = Vec3.multiplyQbyV(Quat.inverse(Quat.multiply(handRotation, offsetRotation)), offset);
|
||||
|
||||
this.actionID = NULL_ACTION_ID;
|
||||
this.actionID = Entities.addAction("hold", this.grabbedEntity, {
|
||||
hand: this.hand == RIGHT_HAND ? "right" : "left",
|
||||
hand: this.hand === RIGHT_HAND ? "right" : "left",
|
||||
timeScale: NEAR_GRABBING_ACTION_TIMEFRAME,
|
||||
relativePosition: offsetPosition,
|
||||
relativeRotation: offsetRotation
|
||||
relativeRotation: offsetRotation,
|
||||
lifetime: ACTION_LIFETIME
|
||||
});
|
||||
if (this.actionID == NULL_ACTION_ID) {
|
||||
if (this.actionID === NULL_ACTION_ID) {
|
||||
this.actionID = null;
|
||||
} else {
|
||||
this.state = STATE_CONTINUE_NEAR_GRABBING;
|
||||
Entities.callEntityMethod(this.grabbedEntity, "startNearGrab");
|
||||
if (this.hand === RIGHT_HAND) {
|
||||
Entities.callEntityMethod(this.grabbedEntity, "setRightHand");
|
||||
} else {
|
||||
Entities.callEntityMethod(this.grabbedEntity, "setLeftHand");
|
||||
}
|
||||
Entities.callEntityMethod(this.grabbedEntity, "startNearGrab");
|
||||
|
||||
}
|
||||
|
||||
this.currentHandControllerPosition = Controller.getSpatialControlPosition(this.palm);
|
||||
this.currentObjectTime = Date.now();
|
||||
}
|
||||
this.currentHandControllerTipPosition = Controller.getSpatialControlPosition(this.tip);
|
||||
|
||||
this.currentObjectTime = Date.now();
|
||||
};
|
||||
|
||||
this.continueNearGrabbing = function() {
|
||||
if (!this.triggerSmoothedSqueezed()) {
|
||||
if (this.triggerSmoothedReleased()) {
|
||||
this.state = STATE_RELEASE;
|
||||
return;
|
||||
}
|
||||
|
||||
// keep track of the measured velocity of the held object
|
||||
var handControllerPosition = Controller.getSpatialControlPosition(this.palm);
|
||||
// Keep track of the fingertip velocity to impart when we release the object
|
||||
// Note that the idea of using a constant 'tip' velocity regardless of the
|
||||
// object's actual held offset is an idea intended to make it easier to throw things:
|
||||
// Because we might catch something or transfer it between hands without a good idea
|
||||
// of it's actual offset, let's try imparting a velocity which is at a fixed radius
|
||||
// from the palm.
|
||||
|
||||
var handControllerPosition = Controller.getSpatialControlPosition(this.tip);
|
||||
var now = Date.now();
|
||||
|
||||
var deltaPosition = Vec3.subtract(handControllerPosition, this.currentHandControllerPosition); // meters
|
||||
var deltaPosition = Vec3.subtract(handControllerPosition, this.currentHandControllerTipPosition); // meters
|
||||
var deltaTime = (now - this.currentObjectTime) / MSEC_PER_SEC; // convert to seconds
|
||||
this.computeReleaseVelocity(deltaPosition, deltaTime, true);
|
||||
|
||||
this.currentHandControllerPosition = handControllerPosition;
|
||||
this.currentHandControllerTipPosition = handControllerPosition;
|
||||
this.currentObjectTime = now;
|
||||
Entities.callEntityMethod(this.grabbedEntity, "continueNearGrab");
|
||||
}
|
||||
|
||||
Entities.updateAction(this.grabbedEntity, this.actionID, {lifetime: ACTION_LIFETIME});
|
||||
};
|
||||
|
||||
this.nearGrabbingNonColliding = function() {
|
||||
if (this.triggerSmoothedReleased()) {
|
||||
this.state = STATE_RELEASE;
|
||||
return;
|
||||
}
|
||||
if (this.hand === RIGHT_HAND) {
|
||||
Entities.callEntityMethod(this.grabbedEntity, "setRightHand");
|
||||
} else {
|
||||
Entities.callEntityMethod(this.grabbedEntity, "setLeftHand");
|
||||
}
|
||||
Entities.callEntityMethod(this.grabbedEntity, "startNearGrabNonColliding");
|
||||
this.state = STATE_CONTINUE_NEAR_GRABBING_NON_COLLIDING;
|
||||
};
|
||||
|
||||
this.continueNearGrabbingNonColliding = function() {
|
||||
if (this.triggerSmoothedReleased()) {
|
||||
this.state = STATE_RELEASE;
|
||||
return;
|
||||
}
|
||||
Entities.callEntityMethod(this.grabbedEntity, "continueNearGrabbingNonColliding");
|
||||
};
|
||||
|
||||
_this.allTouchedIDs = {};
|
||||
this.touchTest = function() {
|
||||
var maxDistance = 0.05;
|
||||
var leftHandPosition = MyAvatar.getLeftPalmPosition();
|
||||
var rightHandPosition = MyAvatar.getRightPalmPosition();
|
||||
var leftEntities = Entities.findEntities(leftHandPosition, maxDistance);
|
||||
var rightEntities = Entities.findEntities(rightHandPosition, maxDistance);
|
||||
var ids = [];
|
||||
|
||||
if (leftEntities.length !== 0) {
|
||||
leftEntities.forEach(function(entity) {
|
||||
ids.push(entity);
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
if (rightEntities.length !== 0) {
|
||||
rightEntities.forEach(function(entity) {
|
||||
ids.push(entity);
|
||||
});
|
||||
}
|
||||
|
||||
ids.forEach(function(id) {
|
||||
|
||||
var props = Entities.getEntityProperties(id, ["boundingBox", "name"]);
|
||||
if (props.name === 'pointer') {
|
||||
return;
|
||||
} else {
|
||||
var entityMinPoint = props.boundingBox.brn;
|
||||
var entityMaxPoint = props.boundingBox.tfl;
|
||||
var leftIsTouching = pointInExtents(leftHandPosition, entityMinPoint, entityMaxPoint);
|
||||
var rightIsTouching = pointInExtents(rightHandPosition, entityMinPoint, entityMaxPoint);
|
||||
|
||||
if ((leftIsTouching || rightIsTouching) && _this.allTouchedIDs[id] === undefined) {
|
||||
// we haven't been touched before, but either right or left is touching us now
|
||||
_this.allTouchedIDs[id] = true;
|
||||
_this.startTouch(id);
|
||||
} else if ((leftIsTouching || rightIsTouching) && _this.allTouchedIDs[id] === true) {
|
||||
// we have been touched before and are still being touched
|
||||
// continue touch
|
||||
_this.continueTouch(id);
|
||||
} else if (_this.allTouchedIDs[id] === true) {
|
||||
delete _this.allTouchedIDs[id];
|
||||
_this.stopTouch(id);
|
||||
|
||||
} else {
|
||||
//we are in another state
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
};
|
||||
|
||||
this.startTouch = function(entityID) {
|
||||
Entities.callEntityMethod(entityID, "startTouch");
|
||||
};
|
||||
|
||||
this.continueTouch = function(entityID) {
|
||||
Entities.callEntityMethod(entityID, "continueTouch");
|
||||
};
|
||||
|
||||
this.stopTouch = function(entityID) {
|
||||
Entities.callEntityMethod(entityID, "stopTouch");
|
||||
};
|
||||
|
||||
this.computeReleaseVelocity = function(deltaPosition, deltaTime, useMultiplier) {
|
||||
if (deltaTime > 0.0 && !vec3equal(deltaPosition, ZERO_VEC)) {
|
||||
|
@ -367,75 +592,73 @@ function controller(hand, triggerAction) {
|
|||
// value would otherwise give the held object time to slow down.
|
||||
if (this.triggerSqueezed()) {
|
||||
this.grabbedVelocity =
|
||||
Vec3.sum(Vec3.multiply(this.grabbedVelocity,
|
||||
(1.0 - NEAR_GRABBING_VELOCITY_SMOOTH_RATIO)),
|
||||
Vec3.multiply(grabbedVelocity, NEAR_GRABBING_VELOCITY_SMOOTH_RATIO));
|
||||
Vec3.sum(Vec3.multiply(this.grabbedVelocity, (1.0 - NEAR_GRABBING_VELOCITY_SMOOTH_RATIO)),
|
||||
Vec3.multiply(grabbedVelocity, NEAR_GRABBING_VELOCITY_SMOOTH_RATIO));
|
||||
}
|
||||
|
||||
if (useMultiplier) {
|
||||
this.grabbedVelocity = Vec3.multiply(this.grabbedVelocity, RELEASE_VELOCITY_MULTIPLIER);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
this.release = function() {
|
||||
|
||||
this.lineOff();
|
||||
|
||||
if (this.grabbedEntity != null && this.actionID != null) {
|
||||
Entities.deleteAction(this.grabbedEntity, this.actionID);
|
||||
if (this.grabbedEntity !== null) {
|
||||
if(this.actionID !== null) {
|
||||
Entities.deleteAction(this.grabbedEntity, this.actionID);
|
||||
}
|
||||
Entities.callEntityMethod(this.grabbedEntity, "releaseGrab");
|
||||
}
|
||||
|
||||
// the action will tend to quickly bring an object's velocity to zero. now that
|
||||
// the action is gone, set the objects velocity to something the holder might expect.
|
||||
Entities.editEntity(this.grabbedEntity, {velocity: this.grabbedVelocity});
|
||||
Entities.editEntity(this.grabbedEntity, {
|
||||
velocity: this.grabbedVelocity
|
||||
});
|
||||
this.deactivateEntity(this.grabbedEntity);
|
||||
|
||||
this.grabbedVelocity = ZERO_VEC;
|
||||
this.grabbedEntity = null;
|
||||
this.actionID = null;
|
||||
this.state = STATE_SEARCHING;
|
||||
}
|
||||
|
||||
this.state = STATE_OFF;
|
||||
};
|
||||
|
||||
this.cleanup = function() {
|
||||
release();
|
||||
}
|
||||
this.release();
|
||||
};
|
||||
|
||||
this.activateEntity = function(entity) {
|
||||
this.activateEntity = function() {
|
||||
var data = {
|
||||
activated: true,
|
||||
avatarId: MyAvatar.sessionUUID
|
||||
};
|
||||
setEntityCustomData(GRAB_USER_DATA_KEY, this.grabbedEntity, data);
|
||||
}
|
||||
};
|
||||
|
||||
this.deactivateEntity = function(entity) {
|
||||
this.deactivateEntity = function() {
|
||||
var data = {
|
||||
activated: false,
|
||||
avatarId: null
|
||||
};
|
||||
setEntityCustomData(GRAB_USER_DATA_KEY, this.grabbedEntity, data);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
var rightController = new controller(RIGHT_HAND, Controller.findAction("RIGHT_HAND_CLICK"));
|
||||
var leftController = new controller(LEFT_HAND, Controller.findAction("LEFT_HAND_CLICK"));
|
||||
|
||||
var rightController = new MyController(RIGHT_HAND, Controller.findAction("RIGHT_HAND_CLICK"));
|
||||
var leftController = new MyController(LEFT_HAND, Controller.findAction("LEFT_HAND_CLICK"));
|
||||
|
||||
function update() {
|
||||
rightController.update();
|
||||
leftController.update();
|
||||
}
|
||||
|
||||
|
||||
function cleanup() {
|
||||
rightController.cleanup();
|
||||
leftController.cleanup();
|
||||
}
|
||||
|
||||
|
||||
Script.scriptEnding.connect(cleanup);
|
||||
Script.update.connect(update)
|
||||
Script.update.connect(update);
|
||||
|
|
|
@ -1035,7 +1035,7 @@ function handeMenuEvent(menuItem) {
|
|||
|
||||
var importURL;
|
||||
if (menuItem == "Import Entities") {
|
||||
importURL = Window.browse("Select models to import", "", "*.json");
|
||||
importURL = "file:///" + Window.browse("Select models to import", "", "*.json");
|
||||
} else {
|
||||
importURL = Window.prompt("URL of SVO to import", "");
|
||||
}
|
||||
|
|
71
examples/entityScripts/changeColorOnTouch.js
Normal file
71
examples/entityScripts/changeColorOnTouch.js
Normal file
|
@ -0,0 +1,71 @@
|
|||
//
|
||||
// changeColorOnTouch.js
|
||||
// examples/entityScripts
|
||||
//
|
||||
// Created by Brad Hefta-Gaub on 11/1/14.
|
||||
// Additions by James B. Pollack @imgntn on 9/23/2015
|
||||
// Copyright 2014 High Fidelity, Inc.
|
||||
//
|
||||
// ATTENTION: Requires you to run handControllerGrab.js
|
||||
// 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 touch it.
|
||||
//
|
||||
// Distributed under the Apache License, Version 2.0.
|
||||
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
|
||||
//
|
||||
/*global print, MyAvatar, Entities, AnimationCache, SoundCache, Scene, Camera, Overlays, Audio, HMD, AvatarList, AvatarManager, Controller, UndoStack, Window, Account, GlobalServices, Script, ScriptDiscoveryService, LODManager, Menu, Vec3, Quat, AudioDevice, Paths, Clipboard, Settings, XMLHttpRequest, randFloat, randInt, pointInExtents, vec3equal, setEntityCustomData, getEntityCustomData */
|
||||
|
||||
|
||||
(function() {
|
||||
|
||||
function ChangeColorOnTouch () {
|
||||
this.oldColor = {};
|
||||
this.oldColorKnown = false;
|
||||
}
|
||||
|
||||
ChangeColorOnTouch.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.entityID = entityID;
|
||||
this.storeOldColor(entityID);
|
||||
},
|
||||
|
||||
startTouch: function() {
|
||||
print("startTouch");
|
||||
|
||||
if (!this.oldColorKnown) {
|
||||
this.storeOldColor(this.entityID);
|
||||
}
|
||||
|
||||
Entities.editEntity(this.entityID, {color: { red: 0, green: 255, blue: 255 }});
|
||||
},
|
||||
|
||||
continueTouch: function() {
|
||||
//unused here
|
||||
return;
|
||||
},
|
||||
|
||||
stopTouch: function() {
|
||||
print("stopTouch");
|
||||
|
||||
if (this.oldColorKnown) {
|
||||
print("leave restoring old color... this.oldColor=" + this.oldColor.red + "," + this.oldColor.green + "," + this.oldColor.blue);
|
||||
Entities.editEntity(this.entityID, {color: this.oldColor});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
};
|
||||
|
||||
return new ChangeColorOnTouch();
|
||||
});
|
|
@ -1,252 +0,0 @@
|
|||
(function() {
|
||||
// Script.include("../libraries/utils.js");
|
||||
//Need absolute path for now, for testing before PR merge and s3 cloning. Will change post-merge
|
||||
|
||||
Script.include("../libraries/utils.js");
|
||||
GRAB_FRAME_USER_DATA_KEY = "grabFrame";
|
||||
this.userData = {};
|
||||
|
||||
var TIP_OFFSET_Z = 0.14;
|
||||
var TIP_OFFSET_Y = 0.04;
|
||||
|
||||
var ZERO_VEC = {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
}
|
||||
|
||||
var MAX_POINTS_PER_LINE = 40;
|
||||
var MIN_POINT_DISTANCE = 0.01;
|
||||
var STROKE_WIDTH = 0.02;
|
||||
|
||||
var self = this;
|
||||
|
||||
var timeSinceLastMoved = 0;
|
||||
var RESET_TIME_THRESHOLD = 5;
|
||||
var DISTANCE_FROM_HOME_THRESHOLD = 0.5;
|
||||
var HOME_POSITION = {
|
||||
x: 549.12,
|
||||
y: 495.555,
|
||||
z: 503.77
|
||||
};
|
||||
this.getUserData = function() {
|
||||
|
||||
|
||||
if (this.properties.userData) {
|
||||
this.userData = JSON.parse(this.properties.userData);
|
||||
}
|
||||
}
|
||||
|
||||
this.updateUserData = function() {
|
||||
Entities.editEntity(this.entityId, {
|
||||
userData: JSON.stringify(this.userData)
|
||||
});
|
||||
}
|
||||
|
||||
this.update = function(deltaTime) {
|
||||
self.getUserData();
|
||||
self.properties = Entities.getEntityProperties(self.entityId);
|
||||
|
||||
if (Vec3.length(self.properties.velocity) < 0.1 && Vec3.distance(HOME_POSITION, self.properties.position) > DISTANCE_FROM_HOME_THRESHOLD) {
|
||||
timeSinceLastMoved += deltaTime;
|
||||
if (timeSinceLastMoved > RESET_TIME_THRESHOLD) {
|
||||
self.reset();
|
||||
timeSinceLastMoved = 0;
|
||||
}
|
||||
} else {
|
||||
timeSinceLastMoved = 0;
|
||||
}
|
||||
|
||||
//Only activate for the user who grabbed the object
|
||||
if (self.userData.grabKey && self.userData.grabKey.activated === true && self.userData.grabKey.avatarId == MyAvatar.sessionUUID) {
|
||||
if (self.activated !== true) {
|
||||
//We were just grabbed, so create a particle system
|
||||
self.grab();
|
||||
}
|
||||
//Move emitter to where entity is always when its activated
|
||||
self.sprayStream();
|
||||
} else if (self.userData.grabKey && self.userData.grabKey.activated === false && self.activated) {
|
||||
self.letGo();
|
||||
}
|
||||
}
|
||||
|
||||
this.grab = function() {
|
||||
this.activated = true;
|
||||
var animationSettings = JSON.stringify({
|
||||
fps: 30,
|
||||
loop: true,
|
||||
firstFrame: 1,
|
||||
lastFrame: 10000,
|
||||
running: true
|
||||
});
|
||||
|
||||
this.paintStream = Entities.addEntity({
|
||||
type: "ParticleEffect",
|
||||
animationSettings: animationSettings,
|
||||
position: this.properties.position,
|
||||
textures: "https://raw.githubusercontent.com/ericrius1/SantasLair/santa/assets/smokeparticle.png",
|
||||
emitVelocity: ZERO_VEC,
|
||||
emitAcceleration: ZERO_VEC,
|
||||
velocitySpread: {
|
||||
x: .1,
|
||||
y: .1,
|
||||
z: 0.1
|
||||
},
|
||||
emitRate: 100,
|
||||
particleRadius: 0.01,
|
||||
color: {
|
||||
red: 170,
|
||||
green: 20,
|
||||
blue: 150
|
||||
},
|
||||
lifetime: 50, //probably wont be holding longer than this straight
|
||||
});
|
||||
}
|
||||
|
||||
this.letGo = function() {
|
||||
this.activated = false;
|
||||
Entities.deleteEntity(this.paintStream);
|
||||
this.paintStream = null;
|
||||
}
|
||||
|
||||
this.reset = function() {
|
||||
Entities.editEntity(self.entityId, {
|
||||
position: HOME_POSITION,
|
||||
rotation: Quat.fromPitchYawRollDegrees(0, 0, 0),
|
||||
angularVelocity: ZERO_VEC,
|
||||
velocity: ZERO_VEC
|
||||
});
|
||||
}
|
||||
|
||||
this.sprayStream = function() {
|
||||
var forwardVec = Quat.getFront(Quat.multiply(self.properties.rotation , Quat.fromPitchYawRollDegrees(0, 90, 0)));
|
||||
forwardVec = Vec3.normalize(forwardVec);
|
||||
|
||||
var upVec = Quat.getUp(self.properties.rotation);
|
||||
var position = Vec3.sum(self.properties.position, Vec3.multiply(forwardVec, TIP_OFFSET_Z));
|
||||
position = Vec3.sum(position, Vec3.multiply(upVec, TIP_OFFSET_Y))
|
||||
Entities.editEntity(self.paintStream, {
|
||||
position: position,
|
||||
emitVelocity: Vec3.multiply(5, forwardVec)
|
||||
});
|
||||
|
||||
//Now check for an intersection with an entity
|
||||
//move forward so ray doesnt intersect with gun
|
||||
var origin = Vec3.sum(position, forwardVec);
|
||||
var pickRay = {
|
||||
origin: origin,
|
||||
direction: Vec3.multiply(forwardVec, 2)
|
||||
}
|
||||
|
||||
var intersection = Entities.findRayIntersection(pickRay, true);
|
||||
if (intersection.intersects) {
|
||||
var normal = Vec3.multiply(-1, Quat.getFront(intersection.properties.rotation));
|
||||
this.paint(intersection.intersection, normal);
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
this.paint = function(position, normal) {
|
||||
if (!this.painting) {
|
||||
|
||||
this.newStroke(position);
|
||||
this.painting = true;
|
||||
}
|
||||
|
||||
if (this.strokePoints.length > MAX_POINTS_PER_LINE) {
|
||||
this.painting = false;
|
||||
return;
|
||||
}
|
||||
|
||||
var localPoint = Vec3.subtract(position, this.strokeBasePosition);
|
||||
//Move stroke a bit forward along normal so it doesnt zfight with mesh its drawing on
|
||||
localPoint = Vec3.sum(localPoint, Vec3.multiply(normal, .1));
|
||||
|
||||
if (this.strokePoints.length > 0 && Vec3.distance(localPoint, this.strokePoints[this.strokePoints.length - 1]) < MIN_POINT_DISTANCE) {
|
||||
//need a minimum distance to avoid binormal NANs
|
||||
return;
|
||||
}
|
||||
|
||||
this.strokePoints.push(localPoint);
|
||||
this.strokeNormals.push(normal);
|
||||
this.strokeWidths.push(STROKE_WIDTH);
|
||||
Entities.editEntity(this.currentStroke, {
|
||||
linePoints: this.strokePoints,
|
||||
normals: this.strokeNormals,
|
||||
strokeWidths: this.strokeWidths
|
||||
});
|
||||
|
||||
|
||||
}
|
||||
|
||||
this.newStroke = function(position) {
|
||||
this.strokeBasePosition = position;
|
||||
this.currentStroke = Entities.addEntity({
|
||||
position: position,
|
||||
type: "PolyLine",
|
||||
color: {
|
||||
red: randInt(160, 250),
|
||||
green: randInt(10, 20),
|
||||
blue: randInt(190, 250)
|
||||
},
|
||||
dimensions: {
|
||||
x: 50,
|
||||
y: 50,
|
||||
z: 50
|
||||
},
|
||||
lifetime: 100
|
||||
});
|
||||
this.strokePoints = [];
|
||||
this.strokeNormals = [];
|
||||
this.strokeWidths = [];
|
||||
|
||||
this.strokes.push(this.currentStroke);
|
||||
}
|
||||
|
||||
this.preload = function(entityId) {
|
||||
this.strokes = [];
|
||||
this.activated = false;
|
||||
this.entityId = entityId;
|
||||
this.properties = Entities.getEntityProperties(self.entityId);
|
||||
this.getUserData();
|
||||
|
||||
//Only activate for the avatar who is grabbing the can!
|
||||
if (this.userData.grabKey && this.userData.grabKey.activated) {
|
||||
this.activated = true;
|
||||
}
|
||||
if (!this.userData.grabFrame) {
|
||||
var data = {
|
||||
relativePosition: {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
},
|
||||
relativeRotation: Quat.fromPitchYawRollDegrees(0, 0, 0)
|
||||
}
|
||||
setEntityCustomData(GRAB_FRAME_USER_DATA_KEY, this.entityId, data);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
this.unload = function() {
|
||||
Script.update.disconnect(this.update);
|
||||
if(this.paintStream) {
|
||||
Entities.deleteEntity(this.paintStream);
|
||||
}
|
||||
this.strokes.forEach(function(stroke) {
|
||||
Entities.deleteEntity(stroke);
|
||||
});
|
||||
}
|
||||
Script.update.connect(this.update);
|
||||
});
|
||||
|
||||
|
||||
|
||||
function randFloat(min, max) {
|
||||
return Math.random() * (max - min) + min;
|
||||
}
|
||||
|
||||
function randInt(min, max) {
|
||||
return Math.floor(Math.random() * (max - min)) + min;
|
||||
}
|
|
@ -13,35 +13,49 @@
|
|||
|
||||
(function () {
|
||||
var box,
|
||||
sphere,
|
||||
sphereDimensions = { x: 0.4, y: 0.8, z: 0.2 },
|
||||
pointDimensions = { x: 0.0, y: 0.0, z: 0.0 },
|
||||
sphereOrientation = Quat.fromPitchYawRollDegrees(-60.0, 30.0, 0.0),
|
||||
verticalOrientation = Quat.fromPitchYawRollDegrees(-90.0, 0.0, 0.0),
|
||||
particles,
|
||||
particleExample = -1,
|
||||
NUM_PARTICLE_EXAMPLES = 11,
|
||||
PARTICLE_RADIUS = 0.04;
|
||||
PARTICLE_RADIUS = 0.04,
|
||||
SLOW_EMIT_RATE = 2.0,
|
||||
HALF_EMIT_RATE = 50.0,
|
||||
FAST_EMIT_RATE = 100.0,
|
||||
SLOW_EMIT_SPEED = 0.025,
|
||||
FAST_EMIT_SPEED = 1.0,
|
||||
GRAVITY_EMIT_ACCELERATON = { x: 0.0, y: -0.3, z: 0.0 },
|
||||
ZERO_EMIT_ACCELERATON = { x: 0.0, y: 0.0, z: 0.0 },
|
||||
PI = 3.141593,
|
||||
DEG_TO_RAD = PI / 180.0,
|
||||
NUM_PARTICLE_EXAMPLES = 18;
|
||||
|
||||
function onClickDownOnEntity(entityID) {
|
||||
if (entityID === box || entityID === particles) {
|
||||
if (entityID === box || entityID === sphere || entityID === particles) {
|
||||
particleExample = (particleExample + 1) % NUM_PARTICLE_EXAMPLES;
|
||||
|
||||
switch (particleExample) {
|
||||
case 0:
|
||||
print("Simple emitter");
|
||||
Entities.editEntity(particles, {
|
||||
velocitySpread: { x: 0.0, y: 0.0, z: 0.0 },
|
||||
speedSpread: 0.0,
|
||||
accelerationSpread: { x: 0.0, y: 0.0, z: 0.0 },
|
||||
radiusSpread: 0.0,
|
||||
animationIsPlaying: true
|
||||
});
|
||||
break;
|
||||
case 1:
|
||||
print("Velocity spread");
|
||||
print("Speed spread");
|
||||
Entities.editEntity(particles, {
|
||||
velocitySpread: { x: 0.1, y: 0.0, z: 0.1 }
|
||||
speedSpread: 0.1
|
||||
});
|
||||
break;
|
||||
case 2:
|
||||
print("Acceleration spread");
|
||||
Entities.editEntity(particles, {
|
||||
velocitySpread: { x: 0.0, y: 0.0, z: 0.0 },
|
||||
speedSpread: 0.0,
|
||||
accelerationSpread: { x: 0.0, y: 0.1, z: 0.0 }
|
||||
});
|
||||
break;
|
||||
|
@ -104,19 +118,99 @@
|
|||
});
|
||||
break;
|
||||
case 10:
|
||||
print("Stop emitting");
|
||||
print("Emit in a spread beam");
|
||||
Entities.editEntity(particles, {
|
||||
colorStart: { red: 255, green: 255, blue: 255 },
|
||||
colorFinish: { red: 255, green: 255, blue: 255 },
|
||||
alphaFinish: 0.0,
|
||||
emitRate: FAST_EMIT_RATE,
|
||||
polarFinish: 2.0 * DEG_TO_RAD
|
||||
});
|
||||
break;
|
||||
case 11:
|
||||
print("Emit in all directions from point");
|
||||
Entities.editEntity(particles, {
|
||||
emitSpeed: SLOW_EMIT_SPEED,
|
||||
emitAcceleration: ZERO_EMIT_ACCELERATON,
|
||||
polarFinish: PI
|
||||
});
|
||||
break;
|
||||
case 12:
|
||||
print("Emit from sphere surface");
|
||||
Entities.editEntity(particles, {
|
||||
colorStart: { red: 255, green: 255, blue: 255 },
|
||||
colorFinish: { red: 255, green: 255, blue: 255 },
|
||||
emitDimensions: sphereDimensions,
|
||||
emitOrientation: sphereOrientation
|
||||
});
|
||||
Entities.editEntity(box, {
|
||||
visible: false
|
||||
});
|
||||
Entities.editEntity(sphere, {
|
||||
visible: true
|
||||
});
|
||||
break;
|
||||
case 13:
|
||||
print("Emit from hemisphere of sphere surface");
|
||||
Entities.editEntity(particles, {
|
||||
polarFinish: PI / 2.0
|
||||
});
|
||||
break;
|
||||
case 14:
|
||||
print("Emit from equator of sphere surface");
|
||||
Entities.editEntity(particles, {
|
||||
polarStart: PI / 2.0,
|
||||
emitRate: HALF_EMIT_RATE
|
||||
});
|
||||
break;
|
||||
case 15:
|
||||
print("Emit from half equator of sphere surface");
|
||||
Entities.editEntity(particles, {
|
||||
azimuthStart: -PI / 2.0,
|
||||
azimuthFinish: PI / 2.0
|
||||
});
|
||||
break;
|
||||
case 16:
|
||||
print("Emit within eighth of sphere volume");
|
||||
Entities.editEntity(particles, {
|
||||
polarStart: 0.0,
|
||||
polarFinish: PI / 2.0,
|
||||
azimuthStart: 0,
|
||||
azimuthFinish: PI / 2.0,
|
||||
emitRadiusStart: 0.0,
|
||||
alphaFinish: 1.0,
|
||||
emitSpeed: 0.0
|
||||
});
|
||||
break;
|
||||
case 17:
|
||||
print("Stop emitting");
|
||||
Entities.editEntity(particles, {
|
||||
emitDimensions: pointDimensions,
|
||||
emitOrientation: verticalOrientation,
|
||||
alphaFinish: 1.0,
|
||||
emitRate: SLOW_EMIT_RATE,
|
||||
emitSpeed: FAST_EMIT_SPEED,
|
||||
emitAcceleration: GRAVITY_EMIT_ACCELERATON,
|
||||
polarStart: 0.0,
|
||||
polarFinish: 0.0,
|
||||
azimuthStart: -PI,
|
||||
azimuthFinish: PI,
|
||||
animationIsPlaying: false
|
||||
});
|
||||
Entities.editEntity(box, {
|
||||
visible: true
|
||||
});
|
||||
Entities.editEntity(sphere, {
|
||||
visible: false
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function setUp() {
|
||||
var spawnPoint = Vec3.sum(MyAvatar.position, Vec3.multiply(4.0, Quat.getFront(Camera.getOrientation()))),
|
||||
var boxPoint,
|
||||
spawnPoint,
|
||||
animation = {
|
||||
fps: 30,
|
||||
frameIndex: 0,
|
||||
|
@ -126,28 +220,50 @@
|
|||
loop: true
|
||||
};
|
||||
|
||||
boxPoint = Vec3.sum(MyAvatar.position, Vec3.multiply(4.0, Quat.getFront(Camera.getOrientation())));
|
||||
boxPoint = Vec3.sum(boxPoint, { x: 0.0, y: -0.5, z: 0.0 });
|
||||
spawnPoint = Vec3.sum(boxPoint, { x: 0.0, y: 1.0, z: 0.0 });
|
||||
|
||||
box = Entities.addEntity({
|
||||
type: "Box",
|
||||
position: spawnPoint,
|
||||
name: "ParticlesTest Box",
|
||||
position: boxPoint,
|
||||
rotation: verticalOrientation,
|
||||
dimensions: { x: 0.3, y: 0.3, z: 0.3 },
|
||||
color: { red: 128, green: 128, blue: 128 },
|
||||
lifetime: 3600 // 1 hour; just in case
|
||||
lifetime: 3600, // 1 hour; just in case
|
||||
visible: true
|
||||
});
|
||||
|
||||
// Same size and orientation as emitter when ellipsoid.
|
||||
sphere = Entities.addEntity({
|
||||
type: "Sphere",
|
||||
name: "ParticlesTest Sphere",
|
||||
position: boxPoint,
|
||||
rotation: sphereOrientation,
|
||||
dimensions: sphereDimensions,
|
||||
color: { red: 128, green: 128, blue: 128 },
|
||||
lifetime: 3600, // 1 hour; just in case
|
||||
visible: false
|
||||
});
|
||||
|
||||
// 1.0m above the box or ellipsoid.
|
||||
particles = Entities.addEntity({
|
||||
type: "ParticleEffect",
|
||||
name: "ParticlesTest Emitter",
|
||||
position: spawnPoint,
|
||||
emitOrientation: verticalOrientation,
|
||||
particleRadius: PARTICLE_RADIUS,
|
||||
radiusSpread: 0.0,
|
||||
emitRate: 2.0,
|
||||
emitVelocity: { x: 0.0, y: 1.0, z: 0.0 },
|
||||
velocitySpread: { x: 0.0, y: 0.0, z: 0.0 },
|
||||
emitAcceleration: { x: 0.0, y: -0.3, z: 0.0 },
|
||||
emitRate: SLOW_EMIT_RATE,
|
||||
emitSpeed: FAST_EMIT_SPEED,
|
||||
speedSpread: 0.0,
|
||||
emitAcceleration: GRAVITY_EMIT_ACCELERATON,
|
||||
accelerationSpread: { x: 0.0, y: 0.0, z: 0.0 },
|
||||
textures: "https://hifi-public.s3.amazonaws.com/alan/Particles/Particle-Sprite-Smoke-1.png",
|
||||
color: { red: 255, green: 255, blue: 255 },
|
||||
lifespan: 5.0,
|
||||
visible: true,
|
||||
visible: false,
|
||||
locked: false,
|
||||
animationSettings: animation,
|
||||
animationIsPlaying: false,
|
||||
|
@ -163,6 +279,7 @@
|
|||
Entities.clickDownOnEntity.disconnect(onClickDownOnEntity);
|
||||
Entities.deleteEntity(particles);
|
||||
Entities.deleteEntity(box);
|
||||
Entities.deleteEntity(sphere);
|
||||
}
|
||||
|
||||
setUp();
|
||||
|
|
10
examples/example/hmd/colorCube.fs
Normal file
10
examples/example/hmd/colorCube.fs
Normal file
|
@ -0,0 +1,10 @@
|
|||
|
||||
float getProceduralColors(inout vec3 diffuse, inout vec3 specular, inout float shininess) {
|
||||
|
||||
specular = _modelNormal.rgb;
|
||||
if (any(lessThan(specular, vec3(0.0)))) {
|
||||
specular = vec3(1.0) + specular;
|
||||
}
|
||||
diffuse = vec3(1.0, 1.0, 1.0);
|
||||
return 1.0;
|
||||
}
|
42
examples/example/hmd/colorCube.js
Normal file
42
examples/example/hmd/colorCube.js
Normal file
|
@ -0,0 +1,42 @@
|
|||
function avatarRelativePosition(position) {
|
||||
return Vec3.sum(MyAvatar.position, Vec3.multiplyQbyV(MyAvatar.orientation, position));
|
||||
}
|
||||
|
||||
ColorCube = function() {};
|
||||
ColorCube.prototype.NAME = "ColorCube";
|
||||
ColorCube.prototype.POSITION = { x: 0, y: 0.5, z: -0.5 };
|
||||
ColorCube.prototype.USER_DATA = { ProceduralEntity: {
|
||||
version: 2, shaderUrl: Script.resolvePath("colorCube.fs"),
|
||||
} };
|
||||
|
||||
// Clear any previous entities within 50 meters
|
||||
ColorCube.prototype.clear = function() {
|
||||
var ids = Entities.findEntities(MyAvatar.position, 50);
|
||||
var that = this;
|
||||
ids.forEach(function(id) {
|
||||
var properties = Entities.getEntityProperties(id);
|
||||
if (properties.name == that.NAME) {
|
||||
Entities.deleteEntity(id);
|
||||
}
|
||||
}, this);
|
||||
}
|
||||
|
||||
ColorCube.prototype.create = function() {
|
||||
var that = this;
|
||||
var size = HMD.ipd;
|
||||
var id = Entities.addEntity({
|
||||
type: "Box",
|
||||
position: avatarRelativePosition(that.POSITION),
|
||||
name: that.NAME,
|
||||
color: that.COLOR,
|
||||
ignoreCollisions: true,
|
||||
collisionsWillMove: false,
|
||||
dimensions: { x: size, y: size, z: size },
|
||||
lifetime: 3600,
|
||||
userData: JSON.stringify(that.USER_DATA)
|
||||
});
|
||||
}
|
||||
|
||||
var colorCube = new ColorCube();
|
||||
colorCube.clear();
|
||||
colorCube.create();
|
94
examples/example/misc/collectHifiStats.js
Normal file
94
examples/example/misc/collectHifiStats.js
Normal file
|
@ -0,0 +1,94 @@
|
|||
//
|
||||
// collectHifiStats.js
|
||||
//
|
||||
// Created by Thijs Wenker on 24 Sept 2015
|
||||
// Additions by James B. Pollack @imgntn on 25 Sept 2015
|
||||
// Copyright 2015 High Fidelity, Inc.
|
||||
//
|
||||
// Collects stats for analysis to a REST endpoint. Defaults to batching stats, but can be customized.
|
||||
//
|
||||
// Distributed under the Apache License, Version 2.0.
|
||||
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
|
||||
//
|
||||
|
||||
// The url where the data will be posted.
|
||||
var ENDPOINT_URL = "";
|
||||
|
||||
var BATCH_STATS = true;
|
||||
var BATCH_SIZE = 5;
|
||||
|
||||
var batch = [];
|
||||
|
||||
if (BATCH_STATS) {
|
||||
|
||||
var RECORD_EVERY = 1000; // 1 seconds
|
||||
var batchCount = 0;
|
||||
|
||||
Script.setInterval(function() {
|
||||
|
||||
if (batchCount === BATCH_SIZE) {
|
||||
sendBatchToEndpoint(batch);
|
||||
batchCount = 0;
|
||||
}
|
||||
Stats.forceUpdateStats();
|
||||
batch.push(getBatchStats());
|
||||
batchCount++;
|
||||
}, RECORD_EVERY);
|
||||
|
||||
|
||||
} else {
|
||||
// Send the data every:
|
||||
var SEND_EVERY = 30000; // 30 seconds
|
||||
|
||||
Script.setInterval(function() {
|
||||
Stats.forceUpdateStats();
|
||||
var req = new XMLHttpRequest();
|
||||
req.open("POST", ENDPOINT_URL, false);
|
||||
req.send(getStats());
|
||||
}, SEND_EVERY);
|
||||
}
|
||||
|
||||
function getStats() {
|
||||
return JSON.stringify({
|
||||
username: GlobalServices.username,
|
||||
location: Window.location.hostname,
|
||||
framerate: Stats.framerate,
|
||||
simrate: Stats.simrate,
|
||||
ping: {
|
||||
audio: Stats.audioPing,
|
||||
avatar: Stats.avatarPing,
|
||||
entities: Stats.entitiesPing,
|
||||
asset: Stats.assetPing
|
||||
},
|
||||
position: Camera.position,
|
||||
yaw: Stats.yaw,
|
||||
rotation: Camera.orientation.x + ',' + Camera.orientation.y + ',' + Camera.orientation.z + ',' + Camera.orientation.w
|
||||
})
|
||||
}
|
||||
|
||||
function getBatchStats() {
|
||||
// print('GET BATCH STATS');
|
||||
return {
|
||||
username: GlobalServices.username,
|
||||
location: Window.location.hostname,
|
||||
framerate: Stats.framerate,
|
||||
simrate: Stats.simrate,
|
||||
ping: {
|
||||
audio: Stats.audioPing,
|
||||
avatar: Stats.avatarPing,
|
||||
entities: Stats.entitiesPing,
|
||||
asset: Stats.assetPing
|
||||
},
|
||||
position: Camera.position,
|
||||
yaw: Stats.yaw,
|
||||
rotation: Camera.orientation.x + ',' + Camera.orientation.y + ',' + Camera.orientation.z + ',' + Camera.orientation.w
|
||||
}
|
||||
}
|
||||
|
||||
function sendBatchToEndpoint(batch) {
|
||||
// print('SEND BATCH TO ENDPOINT');
|
||||
var req = new XMLHttpRequest();
|
||||
req.open("POST", ENDPOINT_URL, false);
|
||||
req.send(JSON.stringify(batch));
|
||||
batch = [];
|
||||
}
|
67
examples/example/misc/statsExample.js
Normal file
67
examples/example/misc/statsExample.js
Normal file
|
@ -0,0 +1,67 @@
|
|||
//
|
||||
// statsExample.js
|
||||
// examples/example/misc
|
||||
//
|
||||
// Created by Thijs Wenker on 24 Sept 2015
|
||||
// Copyright 2015 High Fidelity, Inc.
|
||||
//
|
||||
// Prints the stats to the console.
|
||||
//
|
||||
// Distributed under the Apache License, Version 2.0.
|
||||
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
|
||||
//
|
||||
|
||||
// The stats to be displayed
|
||||
var stats = [
|
||||
'serverCount',
|
||||
'framerate', // a.k.a. FPS
|
||||
'simrate',
|
||||
'avatarSimrate',
|
||||
'avatarCount',
|
||||
'packetInCount',
|
||||
'packetOutCount',
|
||||
'mbpsIn',
|
||||
'mbpsOut',
|
||||
'audioPing',
|
||||
'avatarPing',
|
||||
'entitiesPing',
|
||||
'assetPing',
|
||||
'velocity',
|
||||
'yaw',
|
||||
'avatarMixerKbps',
|
||||
'avatarMixerPps',
|
||||
'audioMixerKbps',
|
||||
'audioMixerPps',
|
||||
'downloads',
|
||||
'downloadsPending',
|
||||
'triangles',
|
||||
'quads',
|
||||
'materialSwitches',
|
||||
'meshOpaque',
|
||||
'meshTranslucent',
|
||||
'opaqueConsidered',
|
||||
'opaqueOutOfView',
|
||||
'opaqueTooSmall',
|
||||
'translucentConsidered',
|
||||
'translucentOutOfView',
|
||||
'translucentTooSmall',
|
||||
'sendingMode',
|
||||
'packetStats',
|
||||
'lodStatus',
|
||||
'timingStats',
|
||||
'serverElements',
|
||||
'serverInternal',
|
||||
'serverLeaves',
|
||||
'localElements',
|
||||
'localInternal',
|
||||
'localLeaves'
|
||||
];
|
||||
|
||||
// Force update the stats, in case the stats panel is invisible
|
||||
Stats.forceUpdateStats();
|
||||
|
||||
// Loop through the stats and display them
|
||||
for (var i in stats) {
|
||||
var stat = stats[i];
|
||||
print(stat + " = " + Stats[stat]);
|
||||
}
|
|
@ -11,6 +11,17 @@
|
|||
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
|
||||
//
|
||||
|
||||
|
||||
var normalDisplay = Entities.addEntity({
|
||||
type: "Line",
|
||||
name: "normalDisplay",
|
||||
visible: false,
|
||||
color: { red: 255, green: 0, blue: 0 },
|
||||
dimensions: { x: 100, y: 100, z: 100 }
|
||||
});
|
||||
|
||||
var wasVisible = false;
|
||||
|
||||
function mouseMoveEvent(event) {
|
||||
print("mouseMoveEvent event.x,y=" + event.x + ", " + event.y);
|
||||
var pickRay = Camera.computePickRay(event.x, event.y);
|
||||
|
@ -18,26 +29,45 @@ function mouseMoveEvent(event) {
|
|||
print("computePickRay origin=" + pickRay.origin.x + ", " + pickRay.origin.y + ", " + pickRay.origin.z);
|
||||
print("computePickRay direction=" + pickRay.direction.x + ", " + pickRay.direction.y + ", " + pickRay.direction.z);
|
||||
var pickRay = Camera.computePickRay(event.x, event.y);
|
||||
intersection = Entities.findRayIntersection(pickRay);
|
||||
intersection = Entities.findRayIntersection(pickRay, true); // to get precise picking
|
||||
if (!intersection.accurate) {
|
||||
print(">>> NOTE: intersection not accurate. will try calling Entities.findRayIntersectionBlocking()");
|
||||
intersection = Entities.findRayIntersectionBlocking(pickRay);
|
||||
intersection = Entities.findRayIntersectionBlocking(pickRay, true); // to get precise picking
|
||||
print(">>> AFTER BLOCKING CALL intersection.accurate=" + intersection.accurate);
|
||||
}
|
||||
|
||||
if (intersection.intersects) {
|
||||
print("intersection entityID.id=" + intersection.entityID.id);
|
||||
print("intersection entityID=" + intersection.entityID);
|
||||
print("intersection properties.modelURL=" + intersection.properties.modelURL);
|
||||
print("intersection face=" + intersection.face);
|
||||
print("intersection distance=" + intersection.distance);
|
||||
print("intersection intersection.x/y/z=" + intersection.intersection.x + ", "
|
||||
print("intersection intersection.x/y/z=" + intersection.intersection.x + ", "
|
||||
+ intersection.intersection.y + ", " + intersection.intersection.z);
|
||||
print("intersection surfaceNormal.x/y/z=" + intersection.surfaceNormal.x + ", "
|
||||
+ intersection.surfaceNormal.y + ", " + intersection.surfaceNormal.z);
|
||||
|
||||
|
||||
// Note: line entity takes points in "entity relative frame"
|
||||
var lineStart = { x: 0, y: 0, z: 0 };
|
||||
var lineEnd = intersection.surfaceNormal;
|
||||
|
||||
Entities.editEntity(normalDisplay, {
|
||||
visible: true,
|
||||
position: intersection.intersection,
|
||||
linePoints: [lineStart, lineEnd],
|
||||
});
|
||||
wasVisible = true;
|
||||
} else {
|
||||
if (wasVisible) {
|
||||
Entities.editEntity(normalDisplay, { visible: false });
|
||||
wasVisible = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Controller.mouseMoveEvent.connect(mouseMoveEvent);
|
||||
|
||||
function scriptEnding() {
|
||||
}
|
||||
Script.scriptEnding.connect(scriptEnding);
|
||||
Script.scriptEnding.connect(function() {
|
||||
Entities.deleteEntity(normalDisplay);
|
||||
});
|
||||
|
||||
|
|
|
@ -101,7 +101,6 @@ Rocket = function(point, colorPalette) {
|
|||
this.burst = false;
|
||||
|
||||
this.emitRate = randInt(80, 120);
|
||||
this.emitStrength = randInt(5.0, 7.0);
|
||||
|
||||
this.rocket = Entities.addEntity({
|
||||
type: "Sphere",
|
||||
|
@ -163,6 +162,9 @@ Rocket.prototype.explode = function(position) {
|
|||
});
|
||||
|
||||
var colorIndex = 0;
|
||||
var PI = 3.141593;
|
||||
var DEG_TO_RAD = PI / 180.0;
|
||||
|
||||
for (var i = 0; i < NUM_BURSTS; ++i) {
|
||||
var color = this.colors[colorIndex];
|
||||
print(JSON.stringify(color));
|
||||
|
@ -172,12 +174,7 @@ Rocket.prototype.explode = function(position) {
|
|||
position: position,
|
||||
textures: 'https://raw.githubusercontent.com/ericrius1/SantasLair/santa/assets/smokeparticle.png',
|
||||
emitRate: this.emitRate,
|
||||
emitStrength: this.emitStrength,
|
||||
emitDirection: {
|
||||
x: Math.pow(-1, i) * randFloat(0.0, 1.4),
|
||||
y: 1.0,
|
||||
z: 0.0
|
||||
},
|
||||
polarFinish: 25 * DEG_TO_RAD,
|
||||
color: color,
|
||||
lifespan: 1.0,
|
||||
visible: true,
|
||||
|
|
209
examples/grab.js
209
examples/grab.js
|
@ -9,11 +9,67 @@
|
|||
// Distributed under the Apache License, Version 2.0.
|
||||
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
|
||||
//
|
||||
/*global print, Mouse, MyAvatar, Entities, AnimationCache, SoundCache, Scene, Camera, Overlays, Audio, HMD, AvatarList, AvatarManager, Controller, UndoStack, Window, Account, GlobalServices, Script, ScriptDiscoveryService, LODManager, Menu, Vec3, Quat, AudioDevice, Paths, Clipboard, Settings, XMLHttpRequest, randFloat, randInt, pointInExtents, vec3equal, setEntityCustomData, getEntityCustomData */
|
||||
|
||||
Script.include("libraries/utils.js");
|
||||
// objects that appear smaller than this can't be grabbed
|
||||
var MAX_SOLID_ANGLE = 0.01;
|
||||
|
||||
var ZERO_VEC3 = {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
};
|
||||
var IDENTITY_QUAT = {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0,
|
||||
w: 0
|
||||
};
|
||||
var GRABBABLE_DATA_KEY = "grabbableKey";
|
||||
|
||||
var defaultGrabbableData = {
|
||||
grabbable: true
|
||||
};
|
||||
|
||||
|
||||
var MAX_SOLID_ANGLE = 0.01; // objects that appear smaller than this can't be grabbed
|
||||
var ZERO_VEC3 = {x: 0, y: 0, z: 0};
|
||||
var IDENTITY_QUAT = {x: 0, y: 0, z: 0, w: 0};
|
||||
var ZERO_VEC3 = {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
};
|
||||
var IDENTITY_QUAT = {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0,
|
||||
w: 0
|
||||
};
|
||||
var ACTION_LIFETIME = 120; // 2 minutes
|
||||
|
||||
function getTag() {
|
||||
return "grab-" + MyAvatar.sessionUUID;
|
||||
}
|
||||
|
||||
function entityIsGrabbedByOther(entityID) {
|
||||
var actionIDs = Entities.getActionIDs(entityID);
|
||||
var actionIndex;
|
||||
var actionID;
|
||||
var actionArguments;
|
||||
var tag;
|
||||
for (actionIndex = 0; actionIndex < actionIDs.length; actionIndex++) {
|
||||
actionID = actionIDs[actionIndex];
|
||||
actionArguments = Entities.getActionArguments(entityID, actionID);
|
||||
tag = actionArguments.tag;
|
||||
if (tag === getTag()) {
|
||||
continue;
|
||||
}
|
||||
if (tag.slice(0, 5) === "grab-") {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// helper function
|
||||
function mouseIntersectionWithPlane(pointOnPlane, planeNormal, event, maxDistance) {
|
||||
|
@ -59,36 +115,72 @@ function mouseIntersectionWithPlane(pointOnPlane, planeNormal, event, maxDistanc
|
|||
|
||||
// Mouse class stores mouse click and drag info
|
||||
Mouse = function() {
|
||||
this.current = {x: 0, y: 0 };
|
||||
this.previous = {x: 0, y: 0 };
|
||||
this.rotateStart = {x: 0, y: 0 };
|
||||
this.cursorRestore = {x: 0, y: 0};
|
||||
this.current = {
|
||||
x: 0,
|
||||
y: 0
|
||||
};
|
||||
this.previous = {
|
||||
x: 0,
|
||||
y: 0
|
||||
};
|
||||
this.rotateStart = {
|
||||
x: 0,
|
||||
y: 0
|
||||
};
|
||||
this.cursorRestore = {
|
||||
x: 0,
|
||||
y: 0
|
||||
};
|
||||
}
|
||||
|
||||
Mouse.prototype.startDrag = function(position) {
|
||||
this.current = {x: position.x, y: position.y};
|
||||
this.current = {
|
||||
x: position.x,
|
||||
y: position.y
|
||||
};
|
||||
this.startRotateDrag();
|
||||
}
|
||||
|
||||
Mouse.prototype.updateDrag = function(position) {
|
||||
this.current = {x: position.x, y: position.y };
|
||||
this.current = {
|
||||
x: position.x,
|
||||
y: position.y
|
||||
};
|
||||
}
|
||||
|
||||
Mouse.prototype.startRotateDrag = function() {
|
||||
this.previous = {x: this.current.x, y: this.current.y};
|
||||
this.rotateStart = {x: this.current.x, y: this.current.y};
|
||||
this.cursorRestore = { x: Window.getCursorPositionX(), y: Window.getCursorPositionY() };
|
||||
this.previous = {
|
||||
x: this.current.x,
|
||||
y: this.current.y
|
||||
};
|
||||
this.rotateStart = {
|
||||
x: this.current.x,
|
||||
y: this.current.y
|
||||
};
|
||||
this.cursorRestore = {
|
||||
x: Window.getCursorPositionX(),
|
||||
y: Window.getCursorPositionY()
|
||||
};
|
||||
}
|
||||
|
||||
Mouse.prototype.getDrag = function() {
|
||||
var delta = {x: this.current.x - this.previous.x, y: this.current.y - this.previous.y};
|
||||
this.previous = {x: this.current.x, y: this.current.y};
|
||||
var delta = {
|
||||
x: this.current.x - this.previous.x,
|
||||
y: this.current.y - this.previous.y
|
||||
};
|
||||
this.previous = {
|
||||
x: this.current.x,
|
||||
y: this.current.y
|
||||
};
|
||||
return delta;
|
||||
}
|
||||
|
||||
Mouse.prototype.restoreRotateCursor = function() {
|
||||
Window.setCursorPosition(this.cursorRestore.x, this.cursorRestore.y);
|
||||
this.current = {x: this.rotateStart.x, y: this.rotateStart.y};
|
||||
this.current = {
|
||||
x: this.rotateStart.x,
|
||||
y: this.rotateStart.y
|
||||
};
|
||||
}
|
||||
|
||||
var mouse = new Mouse();
|
||||
|
@ -98,19 +190,27 @@ var mouse = new Mouse();
|
|||
Beacon = function() {
|
||||
this.height = 0.10;
|
||||
this.overlayID = Overlays.addOverlay("line3d", {
|
||||
color: {red: 200, green: 200, blue: 200},
|
||||
color: {
|
||||
red: 200,
|
||||
green: 200,
|
||||
blue: 200
|
||||
},
|
||||
alpha: 1,
|
||||
visible: false,
|
||||
lineWidth: 2
|
||||
lineWidth: 2
|
||||
});
|
||||
}
|
||||
|
||||
Beacon.prototype.enable = function() {
|
||||
Overlays.editOverlay(this.overlayID, { visible: true });
|
||||
Overlays.editOverlay(this.overlayID, {
|
||||
visible: true
|
||||
});
|
||||
}
|
||||
|
||||
Beacon.prototype.disable = function() {
|
||||
Overlays.editOverlay(this.overlayID, { visible: false });
|
||||
Overlays.editOverlay(this.overlayID, {
|
||||
visible: false
|
||||
});
|
||||
}
|
||||
|
||||
Beacon.prototype.updatePosition = function(position) {
|
||||
|
@ -158,13 +258,17 @@ Grabber = function() {
|
|||
// verticalCylinder (SHIFT)
|
||||
// rotate (CONTROL)
|
||||
this.mode = "xzplane";
|
||||
|
||||
|
||||
// offset allows the user to grab an object off-center. It points from the object's center
|
||||
// to the point where the ray intersects the grab plane (at the moment the grab is initiated).
|
||||
// Future target positions of the ray intersection are on the same plane, and the offset is subtracted
|
||||
// to compute the target position of the object's center.
|
||||
this.offset = {x: 0, y: 0, z: 0 };
|
||||
|
||||
this.offset = {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
};
|
||||
|
||||
this.targetPosition;
|
||||
this.targetRotation;
|
||||
|
||||
|
@ -179,7 +283,11 @@ Grabber.prototype.computeNewGrabPlane = function() {
|
|||
|
||||
var modeWasRotate = (this.mode == "rotate");
|
||||
this.mode = "xzPlane";
|
||||
this.planeNormal = {x: 0, y: 1, z: 0 };
|
||||
this.planeNormal = {
|
||||
x: 0,
|
||||
y: 1,
|
||||
z: 0
|
||||
};
|
||||
if (this.rotateKey) {
|
||||
this.mode = "rotate";
|
||||
mouse.startRotateDrag();
|
||||
|
@ -192,7 +300,7 @@ Grabber.prototype.computeNewGrabPlane = function() {
|
|||
this.mode = "verticalCylinder";
|
||||
// NOTE: during verticalCylinder mode a new planeNormal will be computed each move
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this.pointOnPlane = Vec3.sum(this.currentPosition, this.offset);
|
||||
var xzOffset = Vec3.subtract(this.pointOnPlane, Camera.getPosition());
|
||||
|
@ -217,6 +325,12 @@ Grabber.prototype.pressEvent = function(event) {
|
|||
return;
|
||||
}
|
||||
|
||||
|
||||
var grabbableData = getEntityCustomData(GRABBABLE_DATA_KEY, pickResults.entityID, defaultGrabbableData);
|
||||
if (grabbableData.grabbable === false) {
|
||||
return;
|
||||
}
|
||||
|
||||
mouse.startDrag(event);
|
||||
|
||||
var clickedEntity = pickResults.entityID;
|
||||
|
@ -233,13 +347,19 @@ Grabber.prototype.pressEvent = function(event) {
|
|||
return;
|
||||
}
|
||||
|
||||
Entities.editEntity(clickedEntity, { gravity: ZERO_VEC3 });
|
||||
Entities.editEntity(clickedEntity, {
|
||||
gravity: ZERO_VEC3
|
||||
});
|
||||
this.isGrabbing = true;
|
||||
|
||||
this.entityID = clickedEntity;
|
||||
this.currentPosition = entityProperties.position;
|
||||
this.originalGravity = entityProperties.gravity;
|
||||
this.targetPosition = {x: this.startPosition.x, y: this.startPosition.y, z: this.startPosition.z};
|
||||
this.targetPosition = {
|
||||
x: this.startPosition.x,
|
||||
y: this.startPosition.y,
|
||||
z: this.startPosition.z
|
||||
};
|
||||
|
||||
// compute the grab point
|
||||
var nearestPoint = Vec3.subtract(this.startPosition, cameraPosition);
|
||||
|
@ -261,7 +381,9 @@ Grabber.prototype.pressEvent = function(event) {
|
|||
Grabber.prototype.releaseEvent = function() {
|
||||
if (this.isGrabbing) {
|
||||
if (Vec3.length(this.originalGravity) != 0) {
|
||||
Entities.editEntity(this.entityID, { gravity: this.originalGravity});
|
||||
Entities.editEntity(this.entityID, {
|
||||
gravity: this.originalGravity
|
||||
});
|
||||
}
|
||||
|
||||
this.isGrabbing = false
|
||||
|
@ -288,7 +410,10 @@ Grabber.prototype.moveEvent = function(event) {
|
|||
}
|
||||
this.currentPosition = entityProperties.position;
|
||||
|
||||
var actionArgs = {};
|
||||
var actionArgs = {
|
||||
tag: getTag(),
|
||||
lifetime: ACTION_LIFETIME
|
||||
};
|
||||
|
||||
if (this.mode === "rotate") {
|
||||
var drag = mouse.getDrag();
|
||||
|
@ -303,7 +428,14 @@ Grabber.prototype.moveEvent = function(event) {
|
|||
// var qZero = entityProperties.rotation;
|
||||
//var qZero = this.lastRotation;
|
||||
this.lastRotation = Quat.multiply(deltaQ, this.lastRotation);
|
||||
actionArgs = {targetRotation: this.lastRotation, angularTimeScale: 0.1};
|
||||
|
||||
actionArgs = {
|
||||
targetRotation: this.lastRotation,
|
||||
angularTimeScale: 0.1,
|
||||
tag: getTag(),
|
||||
lifetime: ACTION_LIFETIME
|
||||
};
|
||||
|
||||
} else {
|
||||
var newPointOnPlane;
|
||||
if (this.mode === "verticalCylinder") {
|
||||
|
@ -314,7 +446,11 @@ Grabber.prototype.moveEvent = function(event) {
|
|||
var pointOnCylinder = Vec3.multiply(planeNormal, this.xzDistanceToGrab);
|
||||
pointOnCylinder = Vec3.sum(Camera.getPosition(), pointOnCylinder);
|
||||
this.pointOnPlane = mouseIntersectionWithPlane(pointOnCylinder, planeNormal, mouse.current, this.maxDistance);
|
||||
newPointOnPlane = {x: this.pointOnPlane.x, y: this.pointOnPlane.y, z: this.pointOnPlane.z};
|
||||
newPointOnPlane = {
|
||||
x: this.pointOnPlane.x,
|
||||
y: this.pointOnPlane.y,
|
||||
z: this.pointOnPlane.z
|
||||
};
|
||||
} else {
|
||||
var cameraPosition = Camera.getPosition();
|
||||
newPointOnPlane = mouseIntersectionWithPlane(this.pointOnPlane, this.planeNormal, mouse.current, this.maxDistance);
|
||||
|
@ -327,13 +463,22 @@ Grabber.prototype.moveEvent = function(event) {
|
|||
}
|
||||
}
|
||||
this.targetPosition = Vec3.subtract(newPointOnPlane, this.offset);
|
||||
actionArgs = {targetPosition: this.targetPosition, linearTimeScale: 0.1};
|
||||
|
||||
actionArgs = {
|
||||
targetPosition: this.targetPosition,
|
||||
linearTimeScale: 0.1,
|
||||
tag: getTag(),
|
||||
lifetime: ACTION_LIFETIME
|
||||
};
|
||||
|
||||
|
||||
beacon.updatePosition(this.targetPosition);
|
||||
}
|
||||
|
||||
if (!this.actionID) {
|
||||
this.actionID = Entities.addAction("spring", this.entityID, actionArgs);
|
||||
if (!entityIsGrabbedByOther(this.entityID)) {
|
||||
this.actionID = Entities.addAction("spring", this.entityID, actionArgs);
|
||||
}
|
||||
} else {
|
||||
Entities.updateAction(this.entityID, this.actionID, actionArgs);
|
||||
}
|
||||
|
@ -385,4 +530,4 @@ Controller.mousePressEvent.connect(pressEvent);
|
|||
Controller.mouseMoveEvent.connect(moveEvent);
|
||||
Controller.mouseReleaseEvent.connect(releaseEvent);
|
||||
Controller.keyPressEvent.connect(keyPressEvent);
|
||||
Controller.keyReleaseEvent.connect(keyReleaseEvent);
|
||||
Controller.keyReleaseEvent.connect(keyReleaseEvent);
|
|
@ -179,3 +179,69 @@ pointInExtents = function(point, minPoint, maxPoint) {
|
|||
(point.y >= minPoint.y && point.y <= maxPoint.y) &&
|
||||
(point.z >= minPoint.z && point.z <= maxPoint.z);
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts an HSL color value to RGB. Conversion formula
|
||||
* adapted from http://en.wikipedia.org/wiki/HSL_color_space.
|
||||
* Assumes h, s, and l are contained in the set [0, 1] and
|
||||
* returns r, g, and b in the set [0, 255].
|
||||
*
|
||||
* @param Number h The hue
|
||||
* @param Number s The saturation
|
||||
* @param Number l The lightness
|
||||
* @return Array The RGB representation
|
||||
*/
|
||||
hslToRgb = function(hsl, hueOffset) {
|
||||
var r, g, b;
|
||||
if (hsl.s == 0) {
|
||||
r = g = b = hsl.l; // achromatic
|
||||
} else {
|
||||
var hue2rgb = function hue2rgb(p, q, t) {
|
||||
if (t < 0) t += 1;
|
||||
if (t > 1) t -= 1;
|
||||
if (t < 1 / 6) return p + (q - p) * 6 * t;
|
||||
if (t < 1 / 2) return q;
|
||||
if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
|
||||
return p;
|
||||
}
|
||||
|
||||
var q = hsl.l < 0.5 ? hsl.l * (1 + hsl.s) : hsl.l + hsl.s - hsl.l * hsl.s;
|
||||
var p = 2 * hsl.l - q;
|
||||
r = hue2rgb(p, q, hsl.h + 1 / 3);
|
||||
g = hue2rgb(p, q, hsl.h);
|
||||
b = hue2rgb(p, q, hsl.h - 1 / 3);
|
||||
}
|
||||
|
||||
return {
|
||||
red: Math.round(r * 255),
|
||||
green: Math.round(g * 255),
|
||||
blue: Math.round(b * 255)
|
||||
};
|
||||
}
|
||||
|
||||
map = function(value, min1, max1, min2, max2) {
|
||||
return min2 + (max2 - min2) * ((value - min1) / (max1 - min1));
|
||||
}
|
||||
|
||||
orientationOf = function(vector) {
|
||||
var Y_AXIS = {
|
||||
x: 0,
|
||||
y: 1,
|
||||
z: 0
|
||||
};
|
||||
var X_AXIS = {
|
||||
x: 1,
|
||||
y: 0,
|
||||
z: 0
|
||||
};
|
||||
|
||||
var theta = 0.0;
|
||||
|
||||
var RAD_TO_DEG = 180.0 / Math.PI;
|
||||
var direction, yaw, pitch;
|
||||
direction = Vec3.normalize(vector);
|
||||
yaw = Quat.angleAxis(Math.atan2(direction.x, direction.z) * RAD_TO_DEG, Y_AXIS);
|
||||
pitch = Quat.angleAxis(Math.asin(-direction.y) * RAD_TO_DEG, X_AXIS);
|
||||
return Quat.multiply(yaw, pitch);
|
||||
}
|
||||
|
||||
|
|
|
@ -6,6 +6,9 @@
|
|||
var AUDIO_RANGE = 0.5 * RANGE;
|
||||
var DIST_BETWEEN_BURSTS = 1.0;
|
||||
|
||||
var PI = 3.141593;
|
||||
var DEG_TO_RAD = PI / 180.0;
|
||||
|
||||
var LOUDNESS_RADIUS_RATIO = 10;
|
||||
|
||||
var TEXTURE_PATH = 'https://raw.githubusercontent.com/ericrius1/SantasLair/santa/assets/smokeparticle.png';
|
||||
|
@ -86,12 +89,7 @@
|
|||
position: this.point,
|
||||
textures: TEXTURE_PATH,
|
||||
emitRate: this.emitRate,
|
||||
emitStrength: this.emitStrength,
|
||||
emitDirection: {
|
||||
x: Math.pow(-1, i) * randFloat(0.0, 0.4),
|
||||
y: 1.0,
|
||||
z: 0.0
|
||||
},
|
||||
polarFinish: 25 * DEG_TO_RAD,
|
||||
color: color,
|
||||
lifespan: 1.0,
|
||||
visible: true,
|
||||
|
|
95
examples/particle_explorer/dat.gui.min.js
vendored
Normal file
95
examples/particle_explorer/dat.gui.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
58
examples/particle_explorer/index.html
Normal file
58
examples/particle_explorer/index.html
Normal file
|
@ -0,0 +1,58 @@
|
|||
<!--
|
||||
// main.js
|
||||
//
|
||||
//
|
||||
// Created by James B. Pollack @imgntn on 9/26/2015
|
||||
// Copyright 2015 High Fidelity, Inc.
|
||||
//
|
||||
// Loads dat.gui, underscore, and the app
|
||||
// Quickly edit the aesthetics of a particle system.
|
||||
//
|
||||
// Distributed under the Apache License, Version 2.0.
|
||||
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
|
||||
//
|
||||
-->
|
||||
<html>
|
||||
<head>
|
||||
<script type="text/javascript" src="dat.gui.min.js"></script>
|
||||
<script type="text/javascript" src="underscore-min.js"></script>
|
||||
<script type="text/javascript" src="main.js?123"></script>
|
||||
<script>
|
||||
</script>
|
||||
<style>
|
||||
|
||||
body{
|
||||
background-color:black;
|
||||
overflow-x: hidden;
|
||||
}
|
||||
|
||||
#my-gui-container{
|
||||
|
||||
}
|
||||
|
||||
.importer{
|
||||
margin-bottom:4px;
|
||||
}
|
||||
|
||||
::-webkit-input-placeholder {
|
||||
text-align: center;
|
||||
font-family: Helvetica
|
||||
}
|
||||
|
||||
#importer-input{
|
||||
width:90%;
|
||||
line-height: 2;
|
||||
margin-left:5%;
|
||||
}
|
||||
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="importer">
|
||||
<input type='text' id="importer-input" placeholder="Import: Paste JSON here." onkeypress="handleInputKeyPress(event)">
|
||||
</div>
|
||||
<div id="my-gui-container">
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
513
examples/particle_explorer/main.js
Normal file
513
examples/particle_explorer/main.js
Normal file
|
@ -0,0 +1,513 @@
|
|||
//
|
||||
// main.js
|
||||
//
|
||||
// Created by James B. Pollack @imgntn on 9/26/2015
|
||||
// Copyright 2015 High Fidelity, Inc.
|
||||
// Web app side of the App - contains GUI.
|
||||
// This is an example of a new, easy way to do two way bindings between dynamically created GUI and in-world entities.
|
||||
//
|
||||
// Distributed under the Apache License, Version 2.0.
|
||||
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
|
||||
//
|
||||
/*global window, alert, EventBridge, dat, convertBinaryToBoolean, listenForSettingsUpdates,createVec3Folder,createQuatFolder,writeVec3ToInterface,writeDataToInterface*/
|
||||
|
||||
var Settings = function() {
|
||||
this.exportSettings = function() {
|
||||
//copyExportSettingsToClipboard();
|
||||
showPreselectedPrompt();
|
||||
};
|
||||
this.importSettings = function() {
|
||||
importSettings();
|
||||
};
|
||||
};
|
||||
|
||||
//2-way bindings-aren't quite ready yet. see bottom of file.
|
||||
var AUTO_UPDATE = false;
|
||||
var UPDATE_ALL_FREQUENCY = 100;
|
||||
|
||||
var controllers = [];
|
||||
var colorControllers = [];
|
||||
var folders = [];
|
||||
var gui = null;
|
||||
var settings = new Settings();
|
||||
var updateInterval;
|
||||
|
||||
var currentInputField;
|
||||
var storedController;
|
||||
var keysToIgnore = [
|
||||
'importSettings',
|
||||
'exportSettings',
|
||||
'script',
|
||||
'visible',
|
||||
'locked',
|
||||
'userData',
|
||||
'position',
|
||||
'dimensions',
|
||||
'rotation',
|
||||
'id',
|
||||
'description',
|
||||
'type',
|
||||
'created',
|
||||
'age',
|
||||
'ageAsText',
|
||||
'boundingBox',
|
||||
'naturalDimensions',
|
||||
'naturalPosition',
|
||||
'velocity',
|
||||
'gravity',
|
||||
'acceleration',
|
||||
'damping',
|
||||
'restitution',
|
||||
'friction',
|
||||
'density',
|
||||
'lifetime',
|
||||
'scriptTimestamp',
|
||||
'registrationPoint',
|
||||
'angularVelocity',
|
||||
'angularDamping',
|
||||
'ignoreForCollisions',
|
||||
'collisionsWillMove',
|
||||
'href',
|
||||
'actionData',
|
||||
'marketplaceID',
|
||||
'collisionSoundURL',
|
||||
'shapeType',
|
||||
'animationSettings',
|
||||
'animationFrameIndex',
|
||||
'animationIsPlaying',
|
||||
'animationFPS',
|
||||
'sittingPoints',
|
||||
'originalTextures'
|
||||
];
|
||||
|
||||
var individualKeys = [];
|
||||
var vec3Keys = [];
|
||||
var quatKeys = [];
|
||||
var colorKeys = [];
|
||||
|
||||
window.onload = function() {
|
||||
if (typeof EventBridge !== 'undefined') {
|
||||
|
||||
var stringifiedData = JSON.stringify({
|
||||
messageType: 'page_loaded'
|
||||
});
|
||||
|
||||
EventBridge.emitWebEvent(
|
||||
stringifiedData
|
||||
);
|
||||
|
||||
listenForSettingsUpdates();
|
||||
window.onresize = setGUIWidthToWindowWidth;
|
||||
} else {
|
||||
console.log('No event bridge, probably not in interface.');
|
||||
}
|
||||
};
|
||||
|
||||
function loadGUI() {
|
||||
//whether or not to autoplace
|
||||
gui = new dat.GUI({
|
||||
autoPlace: false
|
||||
});
|
||||
|
||||
//if not autoplacing, put gui in a custom container
|
||||
if (gui.autoPlace === false) {
|
||||
var customContainer = document.getElementById('my-gui-container');
|
||||
customContainer.appendChild(gui.domElement);
|
||||
}
|
||||
|
||||
// presets for the GUI itself. a little confusing and import/export is mostly what we want to do at the moment.
|
||||
// gui.remember(settings);
|
||||
|
||||
var keys = _.keys(settings);
|
||||
|
||||
_.each(keys, function(key) {
|
||||
var shouldIgnore = _.contains(keysToIgnore, key);
|
||||
|
||||
if (shouldIgnore) {
|
||||
return;
|
||||
}
|
||||
|
||||
var subKeys = _.keys(settings[key]);
|
||||
var hasX = _.contains(subKeys, 'x');
|
||||
var hasY = _.contains(subKeys, 'y');
|
||||
var hasZ = _.contains(subKeys, 'z');
|
||||
var hasW = _.contains(subKeys, 'w');
|
||||
var hasRed = _.contains(subKeys, 'red');
|
||||
var hasGreen = _.contains(subKeys, 'green');
|
||||
var hasBlue = _.contains(subKeys, 'blue');
|
||||
|
||||
if ((hasX && hasY && hasZ) && hasW === false) {
|
||||
vec3Keys.push(key);
|
||||
} else if (hasX && hasY && hasZ && hasW) {
|
||||
quatKeys.push(key);
|
||||
} else if (hasRed || hasGreen || hasBlue) {
|
||||
colorKeys.push(key);
|
||||
|
||||
} else {
|
||||
individualKeys.push(key);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
//alphabetize our keys
|
||||
individualKeys.sort();
|
||||
vec3Keys.sort();
|
||||
quatKeys.sort();
|
||||
colorKeys.sort();
|
||||
|
||||
//add to gui in the order they should appear
|
||||
gui.add(settings, 'importSettings');
|
||||
gui.add(settings, 'exportSettings');
|
||||
addIndividualKeys();
|
||||
addFolders();
|
||||
|
||||
//set the gui width to match the web window width
|
||||
gui.width = window.innerWidth;
|
||||
|
||||
//2-way binding stuff
|
||||
// if (AUTO_UPDATE) {
|
||||
// setInterval(manuallyUpdateDisplay, UPDATE_ALL_FREQUENCY);
|
||||
// registerDOMElementsForListenerBlocking();
|
||||
// }
|
||||
|
||||
}
|
||||
|
||||
function addIndividualKeys() {
|
||||
_.each(individualKeys, function(key) {
|
||||
//temporary patch for not crashing when this goes below 0
|
||||
var controller;
|
||||
|
||||
if (key.indexOf('emitRate') > -1) {
|
||||
controller = gui.add(settings, key).min(0);
|
||||
} else {
|
||||
controller = gui.add(settings, key);
|
||||
|
||||
}
|
||||
|
||||
//2-way - need to fix not being able to input exact values if constantly listening
|
||||
//controller.listen();
|
||||
|
||||
//keep track of our controller
|
||||
controllers.push(controller);
|
||||
|
||||
//hook into change events for this gui controller
|
||||
controller.onChange(function(value) {
|
||||
// Fires on every change, drag, keypress, etc.
|
||||
writeDataToInterface(this.property, value);
|
||||
});
|
||||
|
||||
});
|
||||
}
|
||||
|
||||
function addFolders() {
|
||||
_.each(colorKeys, function(key) {
|
||||
createColorPicker(key);
|
||||
});
|
||||
_.each(vec3Keys, function(key) {
|
||||
createVec3Folder(key);
|
||||
});
|
||||
_.each(quatKeys, function(key) {
|
||||
createQuatFolder(key);
|
||||
});
|
||||
}
|
||||
|
||||
function createColorPicker(key) {
|
||||
var colorObject = settings[key];
|
||||
var colorArray = convertColorObjectToArray(colorObject);
|
||||
settings[key] = colorArray;
|
||||
var controller = gui.addColor(settings, key);
|
||||
controller.onChange(function(value) {
|
||||
var obj = {};
|
||||
obj[key] = convertColorArrayToObject(value);
|
||||
writeVec3ToInterface(obj);
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
function createVec3Folder(category) {
|
||||
var folder = gui.addFolder(category);
|
||||
|
||||
folder.add(settings[category], 'x').step(0.1).onChange(function(value) {
|
||||
// Fires when a controller loses focus.
|
||||
var obj = {};
|
||||
obj[category] = {};
|
||||
obj[category][this.property] = value;
|
||||
obj[category].y = settings[category].y;
|
||||
obj[category].z = settings[category].z;
|
||||
writeVec3ToInterface(obj);
|
||||
});
|
||||
|
||||
folder.add(settings[category], 'y').step(0.1).onChange(function(value) {
|
||||
// Fires when a controller loses focus.
|
||||
var obj = {};
|
||||
obj[category] = {};
|
||||
obj[category].x = settings[category].x;
|
||||
obj[category][this.property] = value;
|
||||
obj[category].z = settings[category].z;
|
||||
writeVec3ToInterface(obj);
|
||||
});
|
||||
|
||||
folder.add(settings[category], 'z').step(0.1).onChange(function(value) {
|
||||
// Fires when a controller loses focus.
|
||||
var obj = {};
|
||||
obj[category] = {};
|
||||
obj[category].y = settings[category].y;
|
||||
obj[category].x = settings[category].x;
|
||||
obj[category][this.property] = value;
|
||||
writeVec3ToInterface(obj);
|
||||
});
|
||||
|
||||
folders.push(folder);
|
||||
folder.open();
|
||||
}
|
||||
|
||||
function createQuatFolder(category) {
|
||||
var folder = gui.addFolder(category);
|
||||
|
||||
folder.add(settings[category], 'x').step(0.1).onChange(function(value) {
|
||||
// Fires when a controller loses focus.
|
||||
var obj = {};
|
||||
obj[category] = {};
|
||||
obj[category][this.property] = value;
|
||||
obj[category].y = settings[category].y;
|
||||
obj[category].z = settings[category].z;
|
||||
obj[category].w = settings[category].w;
|
||||
writeVec3ToInterface(obj);
|
||||
});
|
||||
|
||||
folder.add(settings[category], 'y').step(0.1).onChange(function(value) {
|
||||
// Fires when a controller loses focus.
|
||||
var obj = {};
|
||||
obj[category] = {};
|
||||
obj[category].x = settings[category].x;
|
||||
obj[category][this.property] = value;
|
||||
obj[category].z = settings[category].z;
|
||||
obj[category].w = settings[category].w;
|
||||
writeVec3ToInterface(obj);
|
||||
});
|
||||
|
||||
folder.add(settings[category], 'z').step(0.1).onChange(function(value) {
|
||||
// Fires when a controller loses focus.
|
||||
var obj = {};
|
||||
obj[category] = {};
|
||||
obj[category].x = settings[category].x;
|
||||
obj[category].y = settings[category].y;
|
||||
obj[category][this.property] = value;
|
||||
obj[category].w = settings[category].w;
|
||||
writeVec3ToInterface(obj);
|
||||
});
|
||||
|
||||
folder.add(settings[category], 'w').step(0.1).onChange(function(value) {
|
||||
// Fires when a controller loses focus.
|
||||
var obj = {};
|
||||
obj[category] = {};
|
||||
obj[category].x = settings[category].x;
|
||||
obj[category].y = settings[category].y;
|
||||
obj[category].z = settings[category].z;
|
||||
obj[category][this.property] = value;
|
||||
writeVec3ToInterface(obj);
|
||||
});
|
||||
|
||||
folders.push(folder);
|
||||
folder.open();
|
||||
}
|
||||
|
||||
function convertColorObjectToArray(colorObject) {
|
||||
var colorArray = [];
|
||||
|
||||
_.each(colorObject, function(singleColor) {
|
||||
colorArray.push(singleColor);
|
||||
});
|
||||
|
||||
return colorArray;
|
||||
}
|
||||
|
||||
function convertColorArrayToObject(colorArray) {
|
||||
var colorObject = {
|
||||
red: colorArray[0],
|
||||
green: colorArray[1],
|
||||
blue: colorArray[2]
|
||||
};
|
||||
|
||||
return colorObject;
|
||||
}
|
||||
|
||||
function writeDataToInterface(property, value) {
|
||||
var data = {};
|
||||
data[property] = value;
|
||||
|
||||
var sendData = {
|
||||
messageType: "settings_update",
|
||||
updatedSettings: data
|
||||
};
|
||||
|
||||
var stringifiedData = JSON.stringify(sendData);
|
||||
|
||||
EventBridge.emitWebEvent(stringifiedData);
|
||||
}
|
||||
|
||||
function writeVec3ToInterface(obj) {
|
||||
var sendData = {
|
||||
messageType: "settings_update",
|
||||
updatedSettings: obj
|
||||
};
|
||||
|
||||
var stringifiedData = JSON.stringify(sendData);
|
||||
|
||||
EventBridge.emitWebEvent(stringifiedData);
|
||||
}
|
||||
|
||||
function listenForSettingsUpdates() {
|
||||
EventBridge.scriptEventReceived.connect(function(data) {
|
||||
data = JSON.parse(data);
|
||||
|
||||
//2-way
|
||||
// if (data.messageType === 'object_update') {
|
||||
// _.each(data.objectSettings, function(value, key) {
|
||||
// settings[key] = value;
|
||||
// });
|
||||
// }
|
||||
|
||||
if (data.messageType === 'initial_settings') {
|
||||
_.each(data.initialSettings, function(value, key) {
|
||||
settings[key] = {};
|
||||
settings[key] = value;
|
||||
});
|
||||
|
||||
loadGUI();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function manuallyUpdateDisplay() {
|
||||
// Iterate over all controllers
|
||||
// this is expensive, write a method for indiviudal controllers and use it when the value is different than a cached value, perhaps.
|
||||
var i;
|
||||
for (i in gui.__controllers) {
|
||||
gui.__controllers[i].updateDisplay();
|
||||
}
|
||||
}
|
||||
|
||||
function setGUIWidthToWindowWidth() {
|
||||
if (gui !== null) {
|
||||
gui.width = window.innerWidth;
|
||||
}
|
||||
}
|
||||
|
||||
function handleInputKeyPress(e) {
|
||||
if (e.keyCode === 13) {
|
||||
importSettings();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function importSettings() {
|
||||
var importInput = document.getElementById('importer-input');
|
||||
|
||||
try {
|
||||
var importedSettings = JSON.parse(importInput.value);
|
||||
|
||||
var keys = _.keys(importedSettings);
|
||||
|
||||
_.each(keys, function(key) {
|
||||
var shouldIgnore = _.contains(keysToIgnore, key);
|
||||
|
||||
if (shouldIgnore) {
|
||||
return;
|
||||
}
|
||||
|
||||
settings[key] = importedSettings[key];
|
||||
});
|
||||
|
||||
writeVec3ToInterface(settings);
|
||||
|
||||
manuallyUpdateDisplay();
|
||||
} catch (e) {
|
||||
alert('Not properly formatted JSON');
|
||||
}
|
||||
}
|
||||
|
||||
function prepareSettingsForExport() {
|
||||
var keys = _.keys(settings);
|
||||
|
||||
var exportSettings = {};
|
||||
|
||||
_.each(keys, function(key) {
|
||||
var shouldIgnore = _.contains(keysToIgnore, key);
|
||||
|
||||
if (shouldIgnore) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (key.indexOf('color') > -1) {
|
||||
var colorObject = convertColorArrayToObject(settings[key]);
|
||||
settings[key] = colorObject;
|
||||
}
|
||||
|
||||
exportSettings[key] = settings[key];
|
||||
});
|
||||
|
||||
return JSON.stringify(exportSettings);
|
||||
}
|
||||
|
||||
function showPreselectedPrompt() {
|
||||
window.prompt("Ctrl-C to copy, then Enter.", prepareSettingsForExport());
|
||||
}
|
||||
|
||||
function removeContainerDomElement() {
|
||||
var elem = document.getElementById("my-gui-container");
|
||||
elem.parentNode.removeChild(elem);
|
||||
}
|
||||
|
||||
function removeListenerFromGUI(key) {
|
||||
_.each(gui.__listening, function(controller, index) {
|
||||
if (controller.property === key) {
|
||||
storedController = controller;
|
||||
gui.__listening.splice(index, 1);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
//the section below is to try to work at achieving two way bindings;
|
||||
function addListenersBackToGUI() {
|
||||
gui.__listening.push(storedController);
|
||||
storedController = null;
|
||||
}
|
||||
|
||||
function registerDOMElementsForListenerBlocking() {
|
||||
_.each(gui.__controllers, function(controller) {
|
||||
var input = controller.domElement.childNodes[0];
|
||||
input.addEventListener('focus', function() {
|
||||
console.log('INPUT ELEMENT GOT FOCUS!' + controller.property);
|
||||
removeListenerFromGUI(controller.property);
|
||||
});
|
||||
});
|
||||
|
||||
_.each(gui.__controllers, function(controller) {
|
||||
var input = controller.domElement.childNodes[0];
|
||||
input.addEventListener('blur', function() {
|
||||
console.log('INPUT ELEMENT GOT BLUR!' + controller.property);
|
||||
addListenersBackToGUI();
|
||||
});
|
||||
});
|
||||
|
||||
// also listen to inputs inside of folders
|
||||
_.each(gui.__folders, function(folder) {
|
||||
_.each(folder.__controllers, function(controller) {
|
||||
var input = controller.__input;
|
||||
input.addEventListener('focus', function() {
|
||||
console.log('FOLDER ELEMENT GOT FOCUS!' + controller.property);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
///utility method for converting weird collisionWillMove type propertyies from binary to new Boolean()
|
||||
//
|
||||
// function convertBinaryToBoolean(value) {
|
||||
// if (value === 0) {
|
||||
// return false;
|
||||
// }
|
||||
// return true;
|
||||
// }
|
226
examples/particle_explorer/particleExplorer.js
Normal file
226
examples/particle_explorer/particleExplorer.js
Normal file
|
@ -0,0 +1,226 @@
|
|||
//
|
||||
// particleExplorer.js
|
||||
//
|
||||
// Created by James B. Pollack @imgntn on 9/26/2015
|
||||
// includes setup from @ctrlaltdavid's particlesTest.js
|
||||
// Copyright 2015 High Fidelity, Inc.
|
||||
//
|
||||
// Interface side of the App.
|
||||
// Quickly edit the aesthetics of a particle system.
|
||||
//
|
||||
// Distributed under the Apache License, Version 2.0.
|
||||
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
|
||||
//
|
||||
// next version: 2 way bindings, integrate with edit.js
|
||||
//
|
||||
/*global print, WebWindow, MyAvatar, Entities, AnimationCache, SoundCache, Scene, Camera, Overlays, HMD, AvatarList, AvatarManager, Controller, UndoStack, Window, Account, GlobalServices, Script, ScriptDiscoveryService, LODManager, Menu, Vec3, Quat, AudioDevice, Paths, Clipboard, Settings, XMLHttpRequest, randFloat, randInt */
|
||||
|
||||
var box,
|
||||
sphere,
|
||||
sphereDimensions = {
|
||||
x: 0.4,
|
||||
y: 0.8,
|
||||
z: 0.2
|
||||
},
|
||||
pointDimensions = {
|
||||
x: 0.0,
|
||||
y: 0.0,
|
||||
z: 0.0
|
||||
},
|
||||
sphereOrientation = Quat.fromPitchYawRollDegrees(-60.0, 30.0, 0.0),
|
||||
verticalOrientation = Quat.fromPitchYawRollDegrees(-90.0, 0.0, 0.0),
|
||||
particles,
|
||||
particleExample = -1,
|
||||
PARTICLE_RADIUS = 0.04,
|
||||
SLOW_EMIT_RATE = 2.0,
|
||||
HALF_EMIT_RATE = 50.0,
|
||||
FAST_EMIT_RATE = 100.0,
|
||||
SLOW_EMIT_SPEED = 0.025,
|
||||
FAST_EMIT_SPEED = 1.0,
|
||||
GRAVITY_EMIT_ACCELERATON = {
|
||||
x: 0.0,
|
||||
y: -0.3,
|
||||
z: 0.0
|
||||
},
|
||||
ZERO_EMIT_ACCELERATON = {
|
||||
x: 0.0,
|
||||
y: 0.0,
|
||||
z: 0.0
|
||||
},
|
||||
PI = 3.141593,
|
||||
DEG_TO_RAD = PI / 180.0,
|
||||
NUM_PARTICLE_EXAMPLES = 18;
|
||||
|
||||
var particleProperties;
|
||||
|
||||
function setUp() {
|
||||
var boxPoint,
|
||||
spawnPoint,
|
||||
animation = {
|
||||
fps: 30,
|
||||
frameIndex: 0,
|
||||
running: true,
|
||||
firstFrame: 0,
|
||||
lastFrame: 30,
|
||||
loop: true
|
||||
};
|
||||
|
||||
boxPoint = Vec3.sum(MyAvatar.position, Vec3.multiply(4.0, Quat.getFront(Camera.getOrientation())));
|
||||
boxPoint = Vec3.sum(boxPoint, {
|
||||
x: 0.0,
|
||||
y: -0.5,
|
||||
z: 0.0
|
||||
});
|
||||
spawnPoint = Vec3.sum(boxPoint, {
|
||||
x: 0.0,
|
||||
y: 1.0,
|
||||
z: 0.0
|
||||
});
|
||||
|
||||
box = Entities.addEntity({
|
||||
type: "Box",
|
||||
name: "ParticlesTest Box",
|
||||
position: boxPoint,
|
||||
rotation: verticalOrientation,
|
||||
dimensions: {
|
||||
x: 0.3,
|
||||
y: 0.3,
|
||||
z: 0.3
|
||||
},
|
||||
color: {
|
||||
red: 128,
|
||||
green: 128,
|
||||
blue: 128
|
||||
},
|
||||
lifetime: 3600, // 1 hour; just in case
|
||||
visible: true
|
||||
});
|
||||
|
||||
// Same size and orientation as emitter when ellipsoid.
|
||||
sphere = Entities.addEntity({
|
||||
type: "Sphere",
|
||||
name: "ParticlesTest Sphere",
|
||||
position: boxPoint,
|
||||
rotation: sphereOrientation,
|
||||
dimensions: sphereDimensions,
|
||||
color: {
|
||||
red: 128,
|
||||
green: 128,
|
||||
blue: 128
|
||||
},
|
||||
lifetime: 3600, // 1 hour; just in case
|
||||
visible: false
|
||||
});
|
||||
|
||||
// 1.0m above the box or ellipsoid.
|
||||
particles = Entities.addEntity({
|
||||
type: "ParticleEffect",
|
||||
name: "ParticlesTest Emitter",
|
||||
position: spawnPoint,
|
||||
emitOrientation: verticalOrientation,
|
||||
particleRadius: PARTICLE_RADIUS,
|
||||
radiusSpread: 0.0,
|
||||
emitRate: SLOW_EMIT_RATE,
|
||||
emitSpeed: FAST_EMIT_SPEED,
|
||||
speedSpread: 0.0,
|
||||
emitAcceleration: GRAVITY_EMIT_ACCELERATON,
|
||||
accelerationSpread: {
|
||||
x: 0.0,
|
||||
y: 0.0,
|
||||
z: 0.0
|
||||
},
|
||||
textures: "https://hifi-public.s3.amazonaws.com/alan/Particles/Particle-Sprite-Smoke-1.png",
|
||||
color: {
|
||||
red: 255,
|
||||
green: 255,
|
||||
blue: 255
|
||||
},
|
||||
lifespan: 5.0,
|
||||
visible: false,
|
||||
locked: false,
|
||||
animationSettings: animation,
|
||||
animationIsPlaying: true,
|
||||
lifetime: 3600 // 1 hour; just in case
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
SettingsWindow = function() {
|
||||
var _this = this;
|
||||
|
||||
this.webWindow = null;
|
||||
|
||||
this.init = function() {
|
||||
Script.update.connect(waitForObjectAuthorization);
|
||||
_this.webWindow = new WebWindow('Particle Explorer', Script.resolvePath('index.html'), 400, 600, false);
|
||||
_this.webWindow.eventBridge.webEventReceived.connect(_this.onWebEventReceived);
|
||||
};
|
||||
|
||||
this.sendData = function(data) {
|
||||
_this.webWindow.eventBridge.emitScriptEvent(JSON.stringify(data));
|
||||
};
|
||||
|
||||
this.onWebEventReceived = function(data) {
|
||||
var _data = JSON.parse(data);
|
||||
if (_data.messageType === 'page_loaded') {
|
||||
_this.webWindow.setVisible(true);
|
||||
_this.pageLoaded = true;
|
||||
sendInitialSettings(particleProperties);
|
||||
}
|
||||
if (_data.messageType === 'settings_update') {
|
||||
editEntity(_data.updatedSettings);
|
||||
return;
|
||||
}
|
||||
|
||||
};
|
||||
};
|
||||
|
||||
function waitForObjectAuthorization() {
|
||||
var properties = Entities.getEntityProperties(particles, "isKnownID");
|
||||
var isKnownID = properties.isKnownID;
|
||||
if (isKnownID === false || SettingsWindow.pageLoaded === false) {
|
||||
return;
|
||||
}
|
||||
var currentProperties = Entities.getEntityProperties(particles);
|
||||
particleProperties = currentProperties;
|
||||
Script.update.connect(sendObjectUpdates);
|
||||
Script.update.disconnect(waitForObjectAuthorization);
|
||||
}
|
||||
|
||||
function sendObjectUpdates() {
|
||||
var currentProperties = Entities.getEntityProperties(particles);
|
||||
sendUpdatedObject(currentProperties);
|
||||
}
|
||||
|
||||
function sendInitialSettings(properties) {
|
||||
var settings = {
|
||||
messageType: 'initial_settings',
|
||||
initialSettings: properties
|
||||
};
|
||||
|
||||
settingsWindow.sendData(settings);
|
||||
}
|
||||
|
||||
function sendUpdatedObject(properties) {
|
||||
var settings = {
|
||||
messageType: 'object_update',
|
||||
objectSettings: properties
|
||||
};
|
||||
settingsWindow.sendData(settings);
|
||||
}
|
||||
|
||||
function editEntity(properties) {
|
||||
Entities.editEntity(particles, properties);
|
||||
}
|
||||
|
||||
function tearDown() {
|
||||
Entities.deleteEntity(particles);
|
||||
Entities.deleteEntity(box);
|
||||
Entities.deleteEntity(sphere);
|
||||
Script.update.disconnect(sendObjectUpdates);
|
||||
}
|
||||
|
||||
var settingsWindow = new SettingsWindow();
|
||||
settingsWindow.init();
|
||||
setUp();
|
||||
Script.scriptEnding.connect(tearDown);
|
6
examples/particle_explorer/underscore-min.js
vendored
Normal file
6
examples/particle_explorer/underscore-min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
|
@ -35,13 +35,16 @@
|
|||
firstFrame: 0,
|
||||
lastFrame: 30,
|
||||
loop: true });
|
||||
var PI = 3.141593;
|
||||
var DEG_TO_RAD = PI / 180.0;
|
||||
|
||||
this.entity = Entities.addEntity({ type: "ParticleEffect",
|
||||
animationSettings: animationSettings,
|
||||
position: spawnPoint,
|
||||
dimensions: {x: 2, y: 2, z: 2},
|
||||
emitVelocity: {x: 0, y: 5, z: 0},
|
||||
velocitySpread: {x: 2, y: 0, z: 2},
|
||||
emitSpeed: 5,
|
||||
speedSpread: 2,
|
||||
polarFinish: 30 * DEG_TO_RAD,
|
||||
emitAcceleration: {x: 0, y: -9.8, z: 0},
|
||||
textures: "https://hifi-public.s3.amazonaws.com/alan/Particles/Particle-Sprite-Smoke-1.png",
|
||||
color: color,
|
||||
|
|
|
@ -1,41 +0,0 @@
|
|||
// sprayPaintSpawner.js
|
||||
//
|
||||
// Created by Eric Levin on 9/3/15
|
||||
// Copyright 2015 High Fidelity, Inc.
|
||||
//
|
||||
// This is script spwans a spreay paint can model with the sprayPaintCan.js entity script attached
|
||||
//
|
||||
// Distributed under the Apache License, Version 2.0.
|
||||
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
|
||||
|
||||
//Just temporarily using my own bucket here so others can test the entity. Once PR is tested and merged, then the entity script will appear in its proper place in S3, and I wil switch it
|
||||
// var scriptURL = "https://hifi-public.s3.amazonaws.com/eric/scripts/sprayPaintCan.js?=v6 ";
|
||||
var scriptURL = Script.resolvePath("entityScripts/sprayPaintCan.js?v2");
|
||||
var modelURL = "https://hifi-public.s3.amazonaws.com/eric/models/paintcan.fbx";
|
||||
|
||||
var sprayCan = Entities.addEntity({
|
||||
type: "Model",
|
||||
name: "spraycan",
|
||||
modelURL: modelURL,
|
||||
position: {x: 549.12, y:495.55, z:503.77},
|
||||
rotation: {x: 0, y: 0, z: 0, w: 1},
|
||||
dimensions: {
|
||||
x: 0.07,
|
||||
y: 0.17,
|
||||
z: 0.07
|
||||
},
|
||||
collisionsWillMove: true,
|
||||
shapeType: 'box',
|
||||
script: scriptURL,
|
||||
gravity: {x: 0, y: -0.5, z: 0},
|
||||
velocity: {x: 0, y: -1, z: 0}
|
||||
});
|
||||
|
||||
function cleanup() {
|
||||
|
||||
// Uncomment the below line to delete sprayCan on script reload- for faster iteration during development
|
||||
// Entities.deleteEntity(sprayCan);
|
||||
}
|
||||
|
||||
Script.scriptEnding.connect(cleanup);
|
||||
|
BIN
examples/tests/dot.png
Normal file
BIN
examples/tests/dot.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 7.9 KiB |
46
examples/tests/overlayMouseTrackingTest.js
Normal file
46
examples/tests/overlayMouseTrackingTest.js
Normal file
|
@ -0,0 +1,46 @@
|
|||
MouseTracker = function() {
|
||||
this.WIDTH = 60;
|
||||
this.HEIGHT = 60;
|
||||
|
||||
this.overlay = Overlays.addOverlay("image", {
|
||||
imageURL: Script.resolvePath("dot.png"),
|
||||
width: this.HEIGHT,
|
||||
height: this.WIDTH,
|
||||
x: 100,
|
||||
y: 100,
|
||||
visible: true
|
||||
});
|
||||
|
||||
var that = this;
|
||||
Script.scriptEnding.connect(function() {
|
||||
that.onCleanup();
|
||||
});
|
||||
|
||||
Controller.mousePressEvent.connect(function(event) {
|
||||
that.onMousePress(event);
|
||||
});
|
||||
|
||||
Controller.mouseMoveEvent.connect(function(event) {
|
||||
that.onMouseMove(event);
|
||||
});
|
||||
}
|
||||
|
||||
MouseTracker.prototype.onCleanup = function() {
|
||||
Overlays.deleteOverlay(this.overlay);
|
||||
}
|
||||
|
||||
MouseTracker.prototype.onMousePress = function(event) {
|
||||
}
|
||||
|
||||
MouseTracker.prototype.onMouseMove = function(event) {
|
||||
var width = Overlays.width();
|
||||
var height = Overlays.height();
|
||||
var x = Math.max(event.x, 0);
|
||||
x = Math.min(x, width);
|
||||
var y = Math.max(event.y, 0);
|
||||
y = Math.min(y, height);
|
||||
Overlays.editOverlay(this.overlay, {x: x - this.WIDTH / 2.0, y: y - this.HEIGHT / 2.0});
|
||||
}
|
||||
|
||||
|
||||
new MouseTracker();
|
43
examples/toys/basketball_hoop/createHoop.js
Normal file
43
examples/toys/basketball_hoop/createHoop.js
Normal file
|
@ -0,0 +1,43 @@
|
|||
//
|
||||
// createHoop.js
|
||||
// examples/entityScripts
|
||||
//
|
||||
// Created by James B. Pollack on 9/29/2015
|
||||
// Copyright 2015 High Fidelity, Inc.
|
||||
//
|
||||
// This is a script that creates a persistent basketball hoop with a working collision hull. Feel free to move it.
|
||||
// Run basketball.js to make a basketball.
|
||||
//
|
||||
// Distributed under the Apache License, Version 2.0.
|
||||
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
|
||||
/*global MyAvatar, Entities, AnimationCache, SoundCache, Scene, Camera, Overlays, HMD, AvatarList, AvatarManager, Controller, UndoStack, Window, Account, GlobalServices, Script, ScriptDiscoveryService, LODManager, Menu, Vec3, Quat, AudioDevice, Paths, Clipboard, Settings, XMLHttpRequest, randFloat, randInt */
|
||||
|
||||
var hoopURL = "http://hifi-public.s3.amazonaws.com/models/basketball_hoop/basketball_hoop.fbx";
|
||||
var hoopCollisionHullURL = "http://hifi-public.s3.amazonaws.com/models/basketball_hoop/basketball_hoop_collision_hull.obj";
|
||||
|
||||
var hoopStartPosition =
|
||||
Vec3.sum(MyAvatar.position,
|
||||
Vec3.multiplyQbyV(MyAvatar.orientation, {
|
||||
x: 0,
|
||||
y: 0.0,
|
||||
z: -2
|
||||
}));
|
||||
|
||||
var hoop = Entities.addEntity({
|
||||
type: "Model",
|
||||
modelURL: hoopURL,
|
||||
position: hoopStartPosition,
|
||||
shapeType: 'compound',
|
||||
gravity: {
|
||||
x: 0,
|
||||
y: -9.8,
|
||||
z: 0
|
||||
},
|
||||
dimensions: {
|
||||
x: 1.89,
|
||||
y: 3.99,
|
||||
z: 3.79
|
||||
},
|
||||
compoundShapeURL: hoopCollisionHullURL
|
||||
});
|
||||
|
52
examples/toys/cat.js
Normal file
52
examples/toys/cat.js
Normal file
|
@ -0,0 +1,52 @@
|
|||
//
|
||||
// cat.js
|
||||
// examples/toybox/entityScripts
|
||||
//
|
||||
// Created by Eric Levin on 9/21/15.
|
||||
// Copyright 2015 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
|
||||
/*global Cat, print, MyAvatar, Entities, AnimationCache, SoundCache, Scene, Camera, Overlays, Audio, HMD, AvatarList, AvatarManager, Controller, UndoStack, Window, Account, GlobalServices, Script, ScriptDiscoveryService, LODManager, Menu, Vec3, Quat, AudioDevice, Paths, Clipboard, Settings, XMLHttpRequest, randFloat, randInt */
|
||||
|
||||
|
||||
(function() {
|
||||
|
||||
var _this;
|
||||
Cat = function() {
|
||||
_this = this;
|
||||
this.meowSound = SoundCache.getSound("https://s3.amazonaws.com/hifi-public/sounds/Animals/cat_meow.wav");
|
||||
};
|
||||
|
||||
Cat.prototype = {
|
||||
isMeowing: false,
|
||||
injector: null,
|
||||
startTouch: function() {
|
||||
if (this.isMeowing !== true) {
|
||||
this.meow();
|
||||
this.isMeowing = true;
|
||||
}
|
||||
|
||||
},
|
||||
meow: function() {
|
||||
this.injector = Audio.playSound(this.meowSound, {
|
||||
position: this.position,
|
||||
volume: 0.1
|
||||
});
|
||||
Script.setTimeout(function() {
|
||||
_this.isMeowing = false;
|
||||
}, this.soundClipTime);
|
||||
},
|
||||
|
||||
preload: function(entityID) {
|
||||
this.entityID = entityID;
|
||||
this.position = Entities.getEntityProperties(this.entityID, "position").position;
|
||||
this.soundClipTime = 700;
|
||||
},
|
||||
|
||||
};
|
||||
|
||||
// entity scripts always need to return a newly constructed object of our type
|
||||
return new Cat();
|
||||
});
|
47
examples/toys/doll/createDoll.js
Normal file
47
examples/toys/doll/createDoll.js
Normal file
|
@ -0,0 +1,47 @@
|
|||
// createDoll.js
|
||||
//
|
||||
// Script Type: Entity
|
||||
// Created by James B. Pollack @imgntn 9/23/2015
|
||||
// Copyright 2015 High Fidelity, Inc.
|
||||
//
|
||||
// Creates a doll entity in front of you.
|
||||
// Distributed under the Apache License, Version 2.0.
|
||||
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
|
||||
//
|
||||
/*global MyAvatar, Entities, AnimationCache, SoundCache, Scene, Camera, Overlays, Audio, HMD, AvatarList, AvatarManager, Controller, UndoStack, Window, Account, GlobalServices, Script, ScriptDiscoveryService, LODManager, Menu, Vec3, Quat, AudioDevice, Paths, Clipboard, Settings, XMLHttpRequest, randFloat, randInt */
|
||||
|
||||
function createDoll() {
|
||||
var modelURL = "http://hifi-public.s3.amazonaws.com/models/Bboys/bboy2/bboy2.fbx";
|
||||
|
||||
var scriptURL = Script.resolvePath("doll.js");
|
||||
|
||||
var center = Vec3.sum(Vec3.sum(MyAvatar.position, { x: 0, y: 0.5, z: 0 }), Vec3.multiply(0.5, Quat.getFront(Camera.getOrientation())));
|
||||
|
||||
var naturalDimensions = { x: 1.63, y: 1.67, z: 0.26};
|
||||
|
||||
var desiredDimensions = Vec3.multiply(naturalDimensions, 0.15);
|
||||
|
||||
var doll = Entities.addEntity({
|
||||
type: "Model",
|
||||
name: "doll",
|
||||
modelURL: modelURL,
|
||||
script: scriptURL,
|
||||
position: center,
|
||||
shapeType: 'box',
|
||||
dimensions: desiredDimensions,
|
||||
gravity: {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
},
|
||||
velocity: {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
},
|
||||
collisionsWillMove: true
|
||||
});
|
||||
return doll;
|
||||
}
|
||||
|
||||
createDoll();
|
85
examples/toys/doll/doll.js
Normal file
85
examples/toys/doll/doll.js
Normal file
|
@ -0,0 +1,85 @@
|
|||
// doll.js
|
||||
//
|
||||
// Script Type: Entity
|
||||
// Created by Eric Levin on 9/21/15.
|
||||
// Additions by James B. Pollack @imgntn on 9/24/15
|
||||
// Copyright 2015 High Fidelity, Inc.
|
||||
//
|
||||
// This entity script plays an animation and a sound while you hold it.
|
||||
// Distributed under the Apache License, Version 2.0.
|
||||
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
|
||||
//
|
||||
// Known issues: If you pass the doll between hands, animation can get into a weird state. We want to prevent the animation from starting again when you switch hands, but when you switch mid-animation your hand at release is still the first hand and not the current hand.
|
||||
/*global MyAvatar, Entities, AnimationCache, SoundCache, Scene, Camera, Overlays, Audio, HMD, AvatarList, AvatarManager, Controller, UndoStack, Window, Account, GlobalServices, Script, ScriptDiscoveryService, LODManager, Menu, Vec3, Quat, AudioDevice, Paths, Clipboard, Settings, XMLHttpRequest, randFloat, randInt */
|
||||
|
||||
(function() {
|
||||
Script.include("../../utilities.js");
|
||||
Script.include("../../libraries/utils.js");
|
||||
var _this;
|
||||
// this is the "constructor" for the entity as a JS object we don't do much here
|
||||
var Doll = function() {
|
||||
_this = this;
|
||||
this.screamSounds = [SoundCache.getSound("https://hifi-public.s3.amazonaws.com/sounds/KenDoll_1%2303.wav")];
|
||||
};
|
||||
|
||||
Doll.prototype = {
|
||||
audioInjector: null,
|
||||
isGrabbed: false,
|
||||
setLeftHand: function() {
|
||||
this.hand = 'left';
|
||||
},
|
||||
|
||||
setRightHand: function() {
|
||||
this.hand = 'right';
|
||||
},
|
||||
|
||||
startNearGrab: function() {
|
||||
Entities.editEntity(this.entityID, {
|
||||
animationURL: "https://hifi-public.s3.amazonaws.com/models/Bboys/zombie_scream.fbx",
|
||||
animationFrameIndex: 0
|
||||
});
|
||||
|
||||
Entities.editEntity(_this.entityID, {
|
||||
animationIsPlaying: true
|
||||
});
|
||||
|
||||
var position = Entities.getEntityProperties(this.entityID, "position").position;
|
||||
this.audioInjector = Audio.playSound(this.screamSounds[randInt(0, this.screamSounds.length)], {
|
||||
position: position,
|
||||
volume: 0.1
|
||||
});
|
||||
|
||||
this.isGrabbed = true;
|
||||
this.initialHand = this.hand;
|
||||
},
|
||||
|
||||
continueNearGrab: function() {
|
||||
var props = Entities.getEntityProperties(this.entityID, ["position"]);
|
||||
var audioOptions = {
|
||||
position: props.position
|
||||
};
|
||||
this.audioInjector.options = audioOptions;
|
||||
},
|
||||
|
||||
releaseGrab: function() {
|
||||
if (this.isGrabbed === true && this.hand === this.initialHand) {
|
||||
this.audioInjector.stop();
|
||||
Entities.editEntity(this.entityID, {
|
||||
animationFrameIndex: 0
|
||||
});
|
||||
|
||||
Entities.editEntity(this.entityID, {
|
||||
animationURL: "http://hifi-public.s3.amazonaws.com/models/Bboys/bboy2/bboy2.fbx"
|
||||
});
|
||||
|
||||
this.isGrabbed = false;
|
||||
}
|
||||
},
|
||||
|
||||
preload: function(entityID) {
|
||||
this.entityID = entityID;
|
||||
},
|
||||
};
|
||||
// entity scripts always need to return a newly constructed object of our type
|
||||
return new Doll();
|
||||
});
|
|
@ -1,5 +1,5 @@
|
|||
//
|
||||
// createFlashligh.js
|
||||
// createFlashlight.js
|
||||
// examples/entityScripts
|
||||
//
|
||||
// Created by Sam Gateau on 9/9/15.
|
||||
|
@ -11,7 +11,7 @@
|
|||
// Distributed under the Apache License, Version 2.0.
|
||||
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
|
||||
//
|
||||
|
||||
/*global MyAvatar, Entities, AnimationCache, SoundCache, Scene, Camera, Overlays, HMD, AvatarList, AvatarManager, Controller, UndoStack, Window, Account, GlobalServices, Script, ScriptDiscoveryService, LODManager, Menu, Vec3, Quat, AudioDevice, Paths, Clipboard, Settings, XMLHttpRequest, randFloat, randInt */
|
||||
Script.include("https://hifi-public.s3.amazonaws.com/scripts/utilities.js");
|
||||
|
||||
|
||||
|
@ -19,31 +19,14 @@ var scriptURL = Script.resolvePath('flashlight.js?123123');
|
|||
|
||||
var modelURL = "https://hifi-public.s3.amazonaws.com/models/props/flashlight.fbx";
|
||||
|
||||
var center = Vec3.sum(Vec3.sum(MyAvatar.position, {
|
||||
x: 0,
|
||||
y: 0.5,
|
||||
z: 0
|
||||
}), Vec3.multiply(0.5, Quat.getFront(Camera.getOrientation())));
|
||||
var center = Vec3.sum(Vec3.sum(MyAvatar.position, {x: 0, y: 0.5, z: 0}), Vec3.multiply(0.5, Quat.getFront(Camera.getOrientation())));
|
||||
|
||||
var flashlight = Entities.addEntity({
|
||||
type: "Model",
|
||||
modelURL: modelURL,
|
||||
position: center,
|
||||
dimensions: {
|
||||
x: 0.08,
|
||||
y: 0.30,
|
||||
z: 0.08
|
||||
},
|
||||
collisionsWillMove: true,
|
||||
shapeType: 'box',
|
||||
script: scriptURL
|
||||
type: "Model",
|
||||
modelURL: modelURL,
|
||||
position: center,
|
||||
dimensions: { x: 0.08, y: 0.30, z: 0.08},
|
||||
collisionsWillMove: true,
|
||||
shapeType: 'box',
|
||||
script: scriptURL
|
||||
});
|
||||
|
||||
|
||||
function cleanup() {
|
||||
//commenting out the line below makes this persistent. to delete at cleanup, uncomment
|
||||
//Entities.deleteEntity(flashlight);
|
||||
}
|
||||
|
||||
|
||||
Script.scriptEnding.connect(cleanup);
|
|
@ -14,39 +14,28 @@
|
|||
// Distributed under the Apache License, Version 2.0.
|
||||
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
|
||||
//
|
||||
|
||||
/*global MyAvatar, Entities, AnimationCache, SoundCache, Scene, Camera, Overlays, Audio, HMD, AvatarList, AvatarManager, Controller, UndoStack, Window, Account, GlobalServices, Script, ScriptDiscoveryService, LODManager, Menu, Vec3, Quat, AudioDevice, Paths, Clipboard, Settings, XMLHttpRequest, randFloat, randInt */
|
||||
(function() {
|
||||
|
||||
Script.include("../../libraries/utils.js");
|
||||
|
||||
var _this;
|
||||
var ON_SOUND_URL = 'http://hifi-public.s3.amazonaws.com/sounds/Switches%20and%20sliders/flashlight_on.wav';
|
||||
var OFF_SOUND_URL = 'http://hifi-public.s3.amazonaws.com/sounds/Switches%20and%20sliders/flashlight_off.wav';
|
||||
|
||||
// this is the "constructor" for the entity as a JS object we don't do much here, but we do want to remember
|
||||
// our this object, so we can access it in cases where we're called without a this (like in the case of various global signals)
|
||||
Flashlight = function() {
|
||||
_this = this;
|
||||
};
|
||||
function Flashlight() {
|
||||
return;
|
||||
}
|
||||
|
||||
//if the trigger value goes below this while held, the flashlight will turn off. if it goes above, it will
|
||||
var DISABLE_LIGHT_THRESHOLD = 0.7;
|
||||
|
||||
// These constants define the Spotlight position and orientation relative to the model
|
||||
var MODEL_LIGHT_POSITION = {
|
||||
x: 0,
|
||||
y: -0.3,
|
||||
z: 0
|
||||
};
|
||||
var MODEL_LIGHT_ROTATION = Quat.angleAxis(-90, {
|
||||
x: 1,
|
||||
y: 0,
|
||||
z: 0
|
||||
});
|
||||
var MODEL_LIGHT_POSITION = { x: 0, y: -0.3, z: 0 };
|
||||
var MODEL_LIGHT_ROTATION = Quat.angleAxis(-90, { x: 1, y: 0, z: 0 });
|
||||
|
||||
var GLOW_LIGHT_POSITION = {
|
||||
x: 0,
|
||||
y: -0.1,
|
||||
z: 0
|
||||
}
|
||||
var GLOW_LIGHT_POSITION = { x: 0, y: -0.1, z: 0};
|
||||
|
||||
// Evaluate the world light entity positions and orientations from the model ones
|
||||
function evalLightWorldTransform(modelPos, modelRot) {
|
||||
|
@ -55,15 +44,14 @@
|
|||
p: Vec3.sum(modelPos, Vec3.multiplyQbyV(modelRot, MODEL_LIGHT_POSITION)),
|
||||
q: Quat.multiply(modelRot, MODEL_LIGHT_ROTATION)
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
function glowLightWorldTransform(modelPos, modelRot) {
|
||||
return {
|
||||
p: Vec3.sum(modelPos, Vec3.multiplyQbyV(modelRot, GLOW_LIGHT_POSITION)),
|
||||
q: Quat.multiply(modelRot, MODEL_LIGHT_ROTATION)
|
||||
};
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
Flashlight.prototype = {
|
||||
lightOn: false,
|
||||
|
@ -74,11 +62,13 @@
|
|||
setRightHand: function() {
|
||||
this.hand = 'RIGHT';
|
||||
},
|
||||
|
||||
setLeftHand: function() {
|
||||
this.hand = 'LEFT';
|
||||
},
|
||||
|
||||
startNearGrab: function() {
|
||||
if (!_this.hasSpotlight) {
|
||||
if (!this.hasSpotlight) {
|
||||
|
||||
//this light casts the beam
|
||||
this.spotlight = Entities.addEntity({
|
||||
|
@ -117,29 +107,16 @@
|
|||
cutoff: 90, // in degrees
|
||||
});
|
||||
|
||||
this.debugBox = Entities.addEntity({
|
||||
type: 'Box',
|
||||
color: {
|
||||
red: 255,
|
||||
blue: 0,
|
||||
green: 0
|
||||
},
|
||||
dimensions: {
|
||||
x: 0.25,
|
||||
y: 0.25,
|
||||
z: 0.25
|
||||
},
|
||||
ignoreForCollisions:true
|
||||
})
|
||||
|
||||
this.hasSpotlight = true;
|
||||
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
setWhichHand: function() {
|
||||
this.whichHand = this.hand;
|
||||
},
|
||||
|
||||
continueNearGrab: function() {
|
||||
if (this.whichHand === null) {
|
||||
//only set the active hand once -- if we always read the current hand, our 'holding' hand will get overwritten
|
||||
|
@ -149,6 +126,7 @@
|
|||
this.changeLightWithTriggerPressure(this.whichHand);
|
||||
}
|
||||
},
|
||||
|
||||
releaseGrab: function() {
|
||||
//delete the lights and reset state
|
||||
if (this.hasSpotlight) {
|
||||
|
@ -158,9 +136,10 @@
|
|||
this.glowLight = null;
|
||||
this.spotlight = null;
|
||||
this.whichHand = null;
|
||||
|
||||
this.lightOn = false;
|
||||
}
|
||||
},
|
||||
|
||||
updateLightPositions: function() {
|
||||
var modelProperties = Entities.getEntityProperties(this.entityID, ['position', 'rotation']);
|
||||
|
||||
|
@ -168,27 +147,20 @@
|
|||
var lightTransform = evalLightWorldTransform(modelProperties.position, modelProperties.rotation);
|
||||
var glowLightTransform = glowLightWorldTransform(modelProperties.position, modelProperties.rotation);
|
||||
|
||||
|
||||
//move them with the entity model
|
||||
Entities.editEntity(this.spotlight, {
|
||||
position: lightTransform.p,
|
||||
rotation: lightTransform.q,
|
||||
})
|
||||
|
||||
});
|
||||
|
||||
Entities.editEntity(this.glowLight, {
|
||||
position: glowLightTransform.p,
|
||||
rotation: glowLightTransform.q,
|
||||
})
|
||||
|
||||
// Entities.editEntity(this.debugBox, {
|
||||
// position: lightTransform.p,
|
||||
// rotation: lightTransform.q,
|
||||
// })
|
||||
});
|
||||
|
||||
},
|
||||
changeLightWithTriggerPressure: function(flashLightHand) {
|
||||
|
||||
changeLightWithTriggerPressure: function(flashLightHand) {
|
||||
var handClickString = flashLightHand + "_HAND_CLICK";
|
||||
|
||||
var handClick = Controller.findAction(handClickString);
|
||||
|
@ -200,37 +172,62 @@
|
|||
} else if (this.triggerValue >= DISABLE_LIGHT_THRESHOLD && this.lightOn === false) {
|
||||
this.turnLightOn();
|
||||
}
|
||||
return
|
||||
return;
|
||||
},
|
||||
|
||||
turnLightOff: function() {
|
||||
this.playSoundAtCurrentPosition(false);
|
||||
Entities.editEntity(this.spotlight, {
|
||||
intensity: 0
|
||||
});
|
||||
Entities.editEntity(this.glowLight, {
|
||||
intensity: 0
|
||||
});
|
||||
this.lightOn = false
|
||||
this.lightOn = false;
|
||||
},
|
||||
|
||||
turnLightOn: function() {
|
||||
this.playSoundAtCurrentPosition(true);
|
||||
|
||||
Entities.editEntity(this.glowLight, {
|
||||
intensity: 2
|
||||
});
|
||||
Entities.editEntity(this.spotlight, {
|
||||
intensity: 2
|
||||
});
|
||||
this.lightOn = true
|
||||
this.lightOn = true;
|
||||
},
|
||||
// preload() will be called when the entity has become visible (or known) to the interface
|
||||
// it gives us a chance to set our local JavaScript object up. In this case it means:
|
||||
// * remembering our entityID, so we can access it in cases where we're called without an entityID
|
||||
|
||||
playSoundAtCurrentPosition: function(playOnSound) {
|
||||
var position = Entities.getEntityProperties(this.entityID, "position").position;
|
||||
|
||||
var audioProperties = {
|
||||
volume: 0.25,
|
||||
position: position
|
||||
};
|
||||
|
||||
if (playOnSound) {
|
||||
Audio.playSound(this.ON_SOUND, audioProperties);
|
||||
} else {
|
||||
Audio.playSound(this.OFF_SOUND, audioProperties);
|
||||
}
|
||||
},
|
||||
|
||||
preload: function(entityID) {
|
||||
|
||||
// preload() will be called when the entity has become visible (or known) to the interface
|
||||
// it gives us a chance to set our local JavaScript object up. In this case it means:
|
||||
// * remembering our entityID, so we can access it in cases where we're called without an entityID
|
||||
// * preloading sounds
|
||||
this.entityID = entityID;
|
||||
this.ON_SOUND = SoundCache.getSound(ON_SOUND_URL);
|
||||
this.OFF_SOUND = SoundCache.getSound(OFF_SOUND_URL);
|
||||
|
||||
},
|
||||
|
||||
// unload() will be called when our entity is no longer available. It may be because we were deleted,
|
||||
// or because we've left the domain or quit the application.
|
||||
unload: function(entityID) {
|
||||
|
||||
unload: function() {
|
||||
// unload() will be called when our entity is no longer available. It may be because we were deleted,
|
||||
// or because we've left the domain or quit the application.
|
||||
if (this.hasSpotlight) {
|
||||
Entities.deleteEntity(this.spotlight);
|
||||
Entities.deleteEntity(this.glowLight);
|
||||
|
@ -238,12 +235,13 @@
|
|||
this.glowLight = null;
|
||||
this.spotlight = null;
|
||||
this.whichHand = null;
|
||||
this.lightOn = false;
|
||||
}
|
||||
|
||||
|
||||
},
|
||||
|
||||
};
|
||||
|
||||
// entity scripts always need to return a newly constructed object of our type
|
||||
return new Flashlight();
|
||||
})
|
||||
});
|
|
@ -45,6 +45,8 @@ var explodeAnimationSettings = JSON.stringify({
|
|||
var GRAVITY = -9.8;
|
||||
var TIME_TO_EXPLODE = 2500;
|
||||
var DISTANCE_IN_FRONT_OF_ME = 1.0;
|
||||
var PI = 3.141593;
|
||||
var DEG_TO_RAD = PI / 180.0;
|
||||
|
||||
function makeGrenade() {
|
||||
var position = Vec3.sum(MyAvatar.position,
|
||||
|
@ -87,8 +89,7 @@ function update() {
|
|||
position: newProperties.position,
|
||||
textures: 'https://raw.githubusercontent.com/ericrius1/SantasLair/santa/assets/smokeparticle.png',
|
||||
emitRate: 100,
|
||||
emitStrength: 2.0,
|
||||
emitDirection: { x: 0.0, y: 1.0, z: 0.0 },
|
||||
polarFinish: 25 * DEG_TO_RAD,
|
||||
color: { red: 200, green: 0, blue: 0 },
|
||||
lifespan: 10.0,
|
||||
visible: true,
|
||||
|
@ -145,8 +146,7 @@ function boom() {
|
|||
position: properties.position,
|
||||
textures: 'https://raw.githubusercontent.com/ericrius1/SantasLair/santa/assets/smokeparticle.png',
|
||||
emitRate: 200,
|
||||
emitStrength: 3.0,
|
||||
emitDirection: { x: 0.0, y: 1.0, z: 0.0 },
|
||||
polarFinish: 25 * DEG_TO_RAD,
|
||||
color: { red: 255, green: 255, blue: 0 },
|
||||
lifespan: 2.0,
|
||||
visible: true,
|
||||
|
|
202
examples/toys/lightSwitchGarage.js
Normal file
202
examples/toys/lightSwitchGarage.js
Normal file
|
@ -0,0 +1,202 @@
|
|||
//
|
||||
// lightSwitchGarage.js.js
|
||||
// examples/entityScripts
|
||||
//
|
||||
// Created by Eric Levin on 9/21/15.
|
||||
// Copyright 2015 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() {
|
||||
|
||||
var _this;
|
||||
|
||||
// this is the "constructor" for the entity as a JS object we don't do much here, but we do want to remember
|
||||
// our this object, so we can access it in cases where we're called without a this (like in the case of various global signals)
|
||||
LightSwitchGarage = function() {
|
||||
_this = this;
|
||||
|
||||
this.lightStateKey = "lightStateKey";
|
||||
this.resetKey = "resetMe";
|
||||
|
||||
this.switchSound = SoundCache.getSound("https://hifi-public.s3.amazonaws.com/sounds/Switches%20and%20sliders/lamp_switch_2.wav");
|
||||
|
||||
};
|
||||
|
||||
LightSwitchGarage.prototype = {
|
||||
|
||||
clickReleaseOnEntity: function(entityID, mouseEvent) {
|
||||
if (!mouseEvent.isLeftButton) {
|
||||
return;
|
||||
}
|
||||
this.toggleLights();
|
||||
},
|
||||
|
||||
startNearGrabNonColliding: function() {
|
||||
this.toggleLights();
|
||||
},
|
||||
|
||||
toggleLights: function() {
|
||||
var defaultLightData = {
|
||||
on: false
|
||||
};
|
||||
var lightState = getEntityCustomData(this.lightStateKey, this.entityID, defaultLightData);
|
||||
if (lightState.on === true) {
|
||||
this.clearLights();
|
||||
} else if (lightState.on === false) {
|
||||
this.createLights();
|
||||
}
|
||||
|
||||
this.flipLights();
|
||||
|
||||
Audio.playSound(this.switchSound, {
|
||||
volume: 0.5,
|
||||
position: this.position
|
||||
});
|
||||
|
||||
},
|
||||
|
||||
clearLights: function() {
|
||||
var entities = Entities.findEntities(MyAvatar.position, 100);
|
||||
var self = this;
|
||||
entities.forEach(function(entity) {
|
||||
var resetData = getEntityCustomData(self.resetKey, entity, {})
|
||||
if (resetData.resetMe === true && resetData.lightType === "Sconce Light Garage") {
|
||||
Entities.deleteEntity(entity);
|
||||
}
|
||||
});
|
||||
|
||||
setEntityCustomData(this.lightStateKey, this.entityID, {
|
||||
on: false
|
||||
});
|
||||
},
|
||||
|
||||
createLights: function() {
|
||||
|
||||
var sconceLight3 = Entities.addEntity({
|
||||
type: "Light",
|
||||
position: {
|
||||
x: 545.49468994140625,
|
||||
y: 496.24026489257812,
|
||||
z: 500.63516235351562
|
||||
},
|
||||
|
||||
name: "Sconce 3 Light",
|
||||
dimensions: {
|
||||
x: 2.545,
|
||||
y: 2.545,
|
||||
z: 2.545
|
||||
},
|
||||
cutoff: 90,
|
||||
color: {
|
||||
red: 217,
|
||||
green: 146,
|
||||
blue: 24
|
||||
}
|
||||
});
|
||||
|
||||
setEntityCustomData(this.resetKey, sconceLight3, {
|
||||
resetMe: true,
|
||||
lightType: "Sconce Light Garage"
|
||||
});
|
||||
|
||||
var sconceLight4 = Entities.addEntity({
|
||||
type: "Light",
|
||||
position: {
|
||||
x: 550.90399169921875,
|
||||
y: 496.24026489257812,
|
||||
z: 507.90237426757812
|
||||
},
|
||||
name: "Sconce 4 Light",
|
||||
dimensions: {
|
||||
x: 2.545,
|
||||
y: 2.545,
|
||||
z: 2.545
|
||||
},
|
||||
cutoff: 90,
|
||||
color: {
|
||||
red: 217,
|
||||
green: 146,
|
||||
blue: 24
|
||||
}
|
||||
});
|
||||
|
||||
setEntityCustomData(this.resetKey, sconceLight4, {
|
||||
resetMe: true,
|
||||
lightType: "Sconce Light Garage"
|
||||
});
|
||||
|
||||
var sconceLight5 = Entities.addEntity({
|
||||
type: "Light",
|
||||
position: {
|
||||
x: 548.407958984375,
|
||||
y: 496.24026489257812,
|
||||
z: 509.5504150390625
|
||||
},
|
||||
name: "Sconce 5 Light",
|
||||
dimensions: {
|
||||
x: 2.545,
|
||||
y: 2.545,
|
||||
z: 2.545
|
||||
},
|
||||
cutoff: 90,
|
||||
color: {
|
||||
red: 217,
|
||||
green: 146,
|
||||
blue: 24
|
||||
}
|
||||
});
|
||||
|
||||
setEntityCustomData(this.resetKey, sconceLight5, {
|
||||
resetMe: true,
|
||||
lightType: "Sconce Light Garage"
|
||||
});
|
||||
|
||||
setEntityCustomData(this.lightStateKey, this.entityID, {
|
||||
on: true
|
||||
});
|
||||
},
|
||||
|
||||
flipLights: function() {
|
||||
// flip model to give illusion of light switch being flicked
|
||||
var rotation = Entities.getEntityProperties(this.entityID, "rotation").rotation;
|
||||
var axis = {
|
||||
x: 0,
|
||||
y: 1,
|
||||
z: 0
|
||||
};
|
||||
var dQ = Quat.angleAxis(180, axis);
|
||||
rotation = Quat.multiply(rotation, dQ);
|
||||
|
||||
|
||||
Entities.editEntity(this.entityID, {
|
||||
rotation: rotation
|
||||
});
|
||||
|
||||
},
|
||||
|
||||
preload: function(entityID) {
|
||||
this.entityID = entityID;
|
||||
|
||||
//The light switch is static, so just cache its position once
|
||||
this.position = Entities.getEntityProperties(this.entityID, "position").position;
|
||||
var defaultLightData = {
|
||||
on: false
|
||||
};
|
||||
var lightState = getEntityCustomData(this.lightStateKey, this.entityID, defaultLightData);
|
||||
|
||||
//If light is off, then we create two new lights- at the position of the sconces
|
||||
if (lightState.on === false) {
|
||||
this.createLights();
|
||||
this.flipLights();
|
||||
}
|
||||
//If lights are on, do nothing!
|
||||
},
|
||||
};
|
||||
|
||||
// entity scripts always need to return a newly constructed object of our type
|
||||
return new LightSwitchGarage();
|
||||
})
|
179
examples/toys/lightSwitchHall.js
Normal file
179
examples/toys/lightSwitchHall.js
Normal file
|
@ -0,0 +1,179 @@
|
|||
//
|
||||
// lightSwitchHall.js
|
||||
// examples/entityScripts
|
||||
//
|
||||
// Created by Eric Levin on 9/21/15.
|
||||
// Copyright 2015 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() {
|
||||
|
||||
var _this;
|
||||
|
||||
|
||||
// this is the "constructor" for the entity as a JS object we don't do much here, but we do want to remember
|
||||
// our this object, so we can access it in cases where we're called without a this (like in the case of various global signals)
|
||||
LightSwitchHall = function() {
|
||||
_this = this;
|
||||
|
||||
this.lightStateKey = "lightStateKey";
|
||||
this.resetKey = "resetMe";
|
||||
|
||||
this.switchSound = SoundCache.getSound("https://hifi-public.s3.amazonaws.com/sounds/Switches%20and%20sliders/lamp_switch_2.wav");
|
||||
};
|
||||
|
||||
LightSwitchHall.prototype = {
|
||||
|
||||
clickReleaseOnEntity: function(entityId, mouseEvent) {
|
||||
if (!mouseEvent.isLeftButton) {
|
||||
return;
|
||||
}
|
||||
this.toggleLights();
|
||||
},
|
||||
|
||||
startNearGrabNonColliding: function() {
|
||||
this.toggleLights();
|
||||
},
|
||||
|
||||
toggleLights: function() {
|
||||
var defaultLightData = {
|
||||
on: false
|
||||
};
|
||||
var lightState = getEntityCustomData(this.lightStateKey, this.entityID, defaultLightData);
|
||||
if (lightState.on === true) {
|
||||
this.clearLights();
|
||||
} else if (lightState.on === false) {
|
||||
this.createLights();
|
||||
}
|
||||
|
||||
// flip model to give illusion of light switch being flicked
|
||||
this.flipLights();
|
||||
|
||||
Audio.playSound(this.switchSound, {
|
||||
volume: 0.5,
|
||||
position: this.position
|
||||
});
|
||||
|
||||
},
|
||||
|
||||
clearLights: function() {
|
||||
var entities = Entities.findEntities(MyAvatar.position, 100);
|
||||
var self = this;
|
||||
entities.forEach(function(entity) {
|
||||
var resetData = getEntityCustomData(self.resetKey, entity, {})
|
||||
if (resetData.resetMe === true && resetData.lightType === "Sconce Light Hall") {
|
||||
Entities.deleteEntity(entity);
|
||||
}
|
||||
});
|
||||
|
||||
setEntityCustomData(this.lightStateKey, this.entityID, {
|
||||
on: false
|
||||
});
|
||||
},
|
||||
|
||||
createLights: function() {
|
||||
var sconceLight1 = Entities.addEntity({
|
||||
type: "Light",
|
||||
position: {
|
||||
x: 543.75,
|
||||
y: 496.24,
|
||||
z: 511.13
|
||||
},
|
||||
name: "Sconce 1 Light",
|
||||
dimensions: {
|
||||
x: 2.545,
|
||||
y: 2.545,
|
||||
z: 2.545
|
||||
},
|
||||
cutoff: 90,
|
||||
color: {
|
||||
red: 217,
|
||||
green: 146,
|
||||
blue: 24
|
||||
}
|
||||
});
|
||||
|
||||
setEntityCustomData(this.resetKey, sconceLight1, {
|
||||
resetMe: true,
|
||||
lightType: "Sconce Light Hall"
|
||||
});
|
||||
|
||||
var sconceLight2 = Entities.addEntity({
|
||||
type: "Light",
|
||||
position: {
|
||||
x: 540.1,
|
||||
y: 496.24,
|
||||
z: 505.57
|
||||
},
|
||||
name: "Sconce 2 Light",
|
||||
dimensions: {
|
||||
x: 2.545,
|
||||
y: 2.545,
|
||||
z: 2.545
|
||||
},
|
||||
cutoff: 90,
|
||||
color: {
|
||||
red: 217,
|
||||
green: 146,
|
||||
blue: 24
|
||||
}
|
||||
});
|
||||
|
||||
setEntityCustomData(this.resetKey, sconceLight2, {
|
||||
resetMe: true,
|
||||
lightType: "Sconce Light Hall"
|
||||
});
|
||||
|
||||
setEntityCustomData(this.lightStateKey, this.entityID, {
|
||||
on: true
|
||||
});
|
||||
|
||||
},
|
||||
|
||||
flipLights: function() {
|
||||
// flip model to give illusion of light switch being flicked
|
||||
var rotation = Entities.getEntityProperties(this.entityID, "rotation").rotation;
|
||||
var axis = {
|
||||
x: 0,
|
||||
y: 1,
|
||||
z: 0
|
||||
};
|
||||
var dQ = Quat.angleAxis(180, axis);
|
||||
rotation = Quat.multiply(rotation, dQ);
|
||||
|
||||
|
||||
Entities.editEntity(this.entityID, {
|
||||
rotation: rotation
|
||||
});
|
||||
|
||||
},
|
||||
|
||||
// preload() will be called when the entity has become visible (or known) to the interface
|
||||
// it gives us a chance to set our local JavaScript object up. In this case it means:
|
||||
preload: function(entityID) {
|
||||
this.entityID = entityID;
|
||||
|
||||
//The light switch is static, so just cache its position once
|
||||
this.position = Entities.getEntityProperties(this.entityID, "position").position;
|
||||
var defaultLightData = {
|
||||
on: false
|
||||
};
|
||||
var lightState = getEntityCustomData(this.lightStateKey, this.entityID, defaultLightData);
|
||||
|
||||
//If light is off, then we create two new lights- at the position of the sconces
|
||||
if (lightState.on === false) {
|
||||
this.createLights();
|
||||
this.flipLights();
|
||||
|
||||
}
|
||||
//If lights are on, do nothing!
|
||||
},
|
||||
};
|
||||
|
||||
// entity scripts always need to return a newly constructed object of our type
|
||||
return new LightSwitchHall();
|
||||
})
|
43
examples/toys/ping_pong_gun/createPingPongGun.js
Normal file
43
examples/toys/ping_pong_gun/createPingPongGun.js
Normal file
|
@ -0,0 +1,43 @@
|
|||
// createPingPongGun.js
|
||||
//
|
||||
// Script Type: Entity Spawner
|
||||
// Created by James B. Pollack on 9/30/2015
|
||||
// Copyright 2015 High Fidelity, Inc.
|
||||
//
|
||||
// This script creates a gun that shoots ping pong balls when you pull the trigger on a hand controller.
|
||||
// Distributed under the Apache License, Version 2.0.
|
||||
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
|
||||
//
|
||||
/*global MyAvatar, Entities, AnimationCache, SoundCache, Scene, Camera, Overlays, HMD, AvatarList, AvatarManager, Controller, UndoStack, Window, Account, GlobalServices, Script, ScriptDiscoveryService, LODManager, Menu, Vec3, Quat, AudioDevice, Paths, Clipboard, Settings, XMLHttpRequest, randFloat, randInt */
|
||||
Script.include("../../utilities.js");
|
||||
|
||||
var scriptURL = Script.resolvePath('pingPongGun.js');
|
||||
|
||||
var MODEL_URL = 'http://hifi-public.s3.amazonaws.com/models/ping_pong_gun/ping_pong_gun.fbx'
|
||||
var COLLISION_HULL_URL = 'http://hifi-public.s3.amazonaws.com/models/ping_pong_gun/ping_pong_gun_collision_hull.obj';
|
||||
|
||||
var center = Vec3.sum(Vec3.sum(MyAvatar.position, {
|
||||
x: 0,
|
||||
y: 0.5,
|
||||
z: 0
|
||||
}), Vec3.multiply(0.5, Quat.getFront(Camera.getOrientation())));
|
||||
|
||||
var pingPongGun = Entities.addEntity({
|
||||
type: "Model",
|
||||
modelURL: MODEL_URL,
|
||||
shapeType: 'compound',
|
||||
compoundShapeURL: COLLISION_HULL_URL,
|
||||
script: scriptURL,
|
||||
position: center,
|
||||
dimensions: {
|
||||
x:0.67,
|
||||
y: 0.14,
|
||||
z: 0.09
|
||||
},
|
||||
collisionsWillMove: true,
|
||||
});
|
||||
|
||||
function cleanUp() {
|
||||
Entities.deleteEntity(pingPongGun);
|
||||
}
|
||||
Script.scriptEnding.connect(cleanUp);
|
160
examples/toys/ping_pong_gun/pingPongGun.js
Normal file
160
examples/toys/ping_pong_gun/pingPongGun.js
Normal file
|
@ -0,0 +1,160 @@
|
|||
// pingPongGun.js
|
||||
//
|
||||
// Script Type: Entity
|
||||
// Created by James B. Pollack @imgntn on 9/21/2015
|
||||
// Copyright 2015 High Fidelity, Inc.
|
||||
//
|
||||
// This script shoots a ping pong ball.
|
||||
// Distributed under the Apache License, Version 2.0.
|
||||
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
|
||||
//
|
||||
/*global print, MyAvatar, Entities, AnimationCache, SoundCache, Scene, Camera, Overlays, Audio, HMD, AvatarList, AvatarManager, Controller, UndoStack, Window, Account, GlobalServices, Script, ScriptDiscoveryService, LODManager, Menu, Vec3, Quat, AudioDevice, Paths, Clipboard, Settings, XMLHttpRequest, randFloat, randInt */
|
||||
(function() {
|
||||
|
||||
Script.include("../../libraries/utils.js");
|
||||
|
||||
var SHOOTING_SOUND_URL = 'http://hifi-public.s3.amazonaws.com/sounds/ping_pong_gun/pong_sound.wav';
|
||||
|
||||
function PingPongGun() {
|
||||
return;
|
||||
}
|
||||
|
||||
//if the trigger value goes below this value, reload the gun.
|
||||
var RELOAD_THRESHOLD = 0.95;
|
||||
var GUN_TIP_FWD_OFFSET = 0.45;
|
||||
var GUN_TIP_UP_OFFSET = 0.040;
|
||||
var GUN_FORCE = 15;
|
||||
var BALL_RESTITUTION = 0.6;
|
||||
var BALL_LINEAR_DAMPING = 0.4;
|
||||
var BALL_GRAVITY = {
|
||||
x: 0,
|
||||
y: -9.8,
|
||||
z: 0
|
||||
};
|
||||
|
||||
var BALL_DIMENSIONS = {
|
||||
x: 0.04,
|
||||
y: 0.04,
|
||||
z: 0.04
|
||||
}
|
||||
|
||||
|
||||
var BALL_COLOR = {
|
||||
red: 255,
|
||||
green: 255,
|
||||
blue: 255
|
||||
}
|
||||
|
||||
PingPongGun.prototype = {
|
||||
hand: null,
|
||||
whichHand: null,
|
||||
gunTipPosition: null,
|
||||
canShoot: false,
|
||||
canShootTimeout: null,
|
||||
setRightHand: function() {
|
||||
this.hand = 'RIGHT';
|
||||
},
|
||||
|
||||
setLeftHand: function() {
|
||||
this.hand = 'LEFT';
|
||||
},
|
||||
|
||||
startNearGrab: function() {
|
||||
this.setWhichHand();
|
||||
},
|
||||
|
||||
setWhichHand: function() {
|
||||
this.whichHand = this.hand;
|
||||
},
|
||||
|
||||
continueNearGrab: function() {
|
||||
|
||||
if (this.whichHand === null) {
|
||||
//only set the active hand once -- if we always read the current hand, our 'holding' hand will get overwritten
|
||||
this.setWhichHand();
|
||||
} else {
|
||||
if (this.canShootTimeout !== null) {
|
||||
Script.clearTimeout(this.canShootTimeout);
|
||||
}
|
||||
this.checkTriggerPressure(this.whichHand);
|
||||
}
|
||||
},
|
||||
|
||||
releaseGrab: function() {
|
||||
var _t = this;
|
||||
this.canShootTimeout = Script.setTimeout(function() {
|
||||
_t.canShoot = false;
|
||||
}, 250)
|
||||
},
|
||||
|
||||
checkTriggerPressure: function(gunHand) {
|
||||
var handClickString = gunHand + "_HAND_CLICK";
|
||||
|
||||
var handClick = Controller.findAction(handClickString);
|
||||
|
||||
this.triggerValue = Controller.getActionValue(handClick);
|
||||
|
||||
if (this.triggerValue < RELOAD_THRESHOLD) {
|
||||
// print('RELOAD');
|
||||
this.canShoot = true;
|
||||
} else if (this.triggerValue >= RELOAD_THRESHOLD && this.canShoot === true) {
|
||||
var gunProperties = Entities.getEntityProperties(this.entityID, ["position", "rotation"]);
|
||||
this.shootBall(gunProperties);
|
||||
this.canShoot = false;
|
||||
}
|
||||
return;
|
||||
},
|
||||
|
||||
shootBall: function(gunProperties) {
|
||||
var forwardVec = Quat.getFront(Quat.multiply(gunProperties.rotation, Quat.fromPitchYawRollDegrees(0, -90, 0)));
|
||||
forwardVec = Vec3.normalize(forwardVec);
|
||||
forwardVec = Vec3.multiply(forwardVec, GUN_FORCE);
|
||||
var properties = {
|
||||
type: 'Sphere',
|
||||
color: BALL_COLOR,
|
||||
dimensions: BALL_DIMENSIONS,
|
||||
linearDamping: BALL_LINEAR_DAMPING,
|
||||
gravity: BALL_GRAVITY,
|
||||
restitution: BALL_RESTITUTION,
|
||||
collisionsWillMove: true,
|
||||
rotation: gunProperties.rotation,
|
||||
position: this.getGunTipPosition(gunProperties),
|
||||
velocity: forwardVec,
|
||||
lifetime: 10
|
||||
};
|
||||
|
||||
Entities.addEntity(properties);
|
||||
|
||||
this.playSoundAtCurrentPosition(gunProperties.position);
|
||||
},
|
||||
|
||||
playSoundAtCurrentPosition: function(position) {
|
||||
var audioProperties = {
|
||||
volume: 0.1,
|
||||
position: position
|
||||
};
|
||||
|
||||
Audio.playSound(this.SHOOTING_SOUND, audioProperties);
|
||||
},
|
||||
|
||||
getGunTipPosition: function(properties) {
|
||||
//the tip of the gun is going to be in a different place than the center, so we move in space relative to the model to find that position
|
||||
var frontVector = Quat.getRight(properties.rotation);
|
||||
var frontOffset = Vec3.multiply(frontVector, GUN_TIP_FWD_OFFSET);
|
||||
var upVector = Quat.getRight(properties.rotation);
|
||||
var upOffset = Vec3.multiply(upVector, GUN_TIP_UP_OFFSET);
|
||||
var gunTipPosition = Vec3.sum(properties.position, frontOffset);
|
||||
gunTipPosition = Vec3.sum(gunTipPosition, upOffset);
|
||||
return gunTipPosition;
|
||||
},
|
||||
|
||||
preload: function(entityID) {
|
||||
this.entityID = entityID;
|
||||
this.SHOOTING_SOUND = SoundCache.getSound(SHOOTING_SOUND_URL);
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
// entity scripts always need to return a newly constructed object of our type
|
||||
return new PingPongGun();
|
||||
});
|
162
examples/toys/sprayPaintCan.js
Normal file
162
examples/toys/sprayPaintCan.js
Normal file
|
@ -0,0 +1,162 @@
|
|||
//
|
||||
// sprayPaintCan.js
|
||||
// examples/entityScripts
|
||||
//
|
||||
// Created by Eric Levin on 9/21/15.
|
||||
// Copyright 2015 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("../libraries/utils.js");
|
||||
//Need absolute path for now, for testing before PR merge and s3 cloning. Will change post-merge
|
||||
|
||||
Script.include("../libraries/utils.js");
|
||||
|
||||
this.spraySound = SoundCache.getSound("https://s3.amazonaws.com/hifi-public/sounds/sprayPaintSound.wav");
|
||||
|
||||
var TIP_OFFSET_Z = 0.02;
|
||||
var TIP_OFFSET_Y = 0.08;
|
||||
|
||||
var ZERO_VEC = {
|
||||
x: 0,
|
||||
y: 0,
|
||||
z: 0
|
||||
};
|
||||
|
||||
// if the trigger value goes below this while held, the can will stop spraying. if it goes above, it will spray
|
||||
var DISABLE_SPRAY_THRESHOLD = 0.5;
|
||||
|
||||
var MAX_POINTS_PER_LINE = 40;
|
||||
var MIN_POINT_DISTANCE = 0.01;
|
||||
var STROKE_WIDTH = 0.02;
|
||||
|
||||
this.setRightHand = function() {
|
||||
this.hand = 'RIGHT';
|
||||
}
|
||||
|
||||
this.setLeftHand = function() {
|
||||
this.hand = 'LEFT';
|
||||
}
|
||||
|
||||
this.startNearGrab = function() {
|
||||
this.whichHand = this.hand;
|
||||
}
|
||||
|
||||
this.toggleWithTriggerPressure = function() {
|
||||
var handClickString = this.whichHand + "_HAND_CLICK";
|
||||
|
||||
var handClick = Controller.findAction(handClickString);
|
||||
|
||||
this.triggerValue = Controller.getActionValue(handClick);
|
||||
if (this.triggerValue < DISABLE_SPRAY_THRESHOLD && this.spraying === true) {
|
||||
this.spraying = false;
|
||||
this.disableStream();
|
||||
} else if (this.triggerValue >= DISABLE_SPRAY_THRESHOLD && this.spraying === false) {
|
||||
this.spraying = true;
|
||||
this.enableStream();
|
||||
}
|
||||
}
|
||||
|
||||
this.enableStream = function() {
|
||||
var position = Entities.getEntityProperties(this.entityId, "position").position;
|
||||
var animationSettings = JSON.stringify({
|
||||
fps: 30,
|
||||
loop: true,
|
||||
firstFrame: 1,
|
||||
lastFrame: 10000,
|
||||
running: true
|
||||
});
|
||||
var PI = 3.141593;
|
||||
var DEG_TO_RAD = PI / 180.0;
|
||||
|
||||
this.paintStream = Entities.addEntity({
|
||||
type: "ParticleEffect",
|
||||
name: "streamEffect",
|
||||
animationSettings: animationSettings,
|
||||
position: position,
|
||||
textures: "https://raw.githubusercontent.com/ericrius1/SantasLair/santa/assets/smokeparticle.png",
|
||||
emitSpeed: 3,
|
||||
speedSpread: 0.02,
|
||||
emitAcceleration: ZERO_VEC,
|
||||
emitRate: 100,
|
||||
particleRadius: 0.01,
|
||||
radiusSpread: 0.005,
|
||||
polarFinish: 0.05,
|
||||
color: {
|
||||
red: 170,
|
||||
green: 20,
|
||||
blue: 150
|
||||
},
|
||||
lifetime: 50, //probably wont be holding longer than this straight
|
||||
});
|
||||
|
||||
setEntityCustomData(this.resetKey, this.paintStream, {
|
||||
resetMe: true
|
||||
});
|
||||
|
||||
this.sprayInjector = Audio.playSound(this.spraySound, {
|
||||
position: position,
|
||||
volume: this.sprayVolume,
|
||||
loop: true
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
this.releaseGrab = function() {
|
||||
this.disableStream();
|
||||
}
|
||||
|
||||
this.disableStream = function() {
|
||||
Entities.deleteEntity(this.paintStream);
|
||||
this.paintStream = null;
|
||||
this.spraying = false;
|
||||
this.sprayInjector.stop();
|
||||
}
|
||||
|
||||
|
||||
this.continueNearGrab = function() {
|
||||
|
||||
this.toggleWithTriggerPressure();
|
||||
|
||||
if (this.spraying === false) {
|
||||
return;
|
||||
}
|
||||
|
||||
var props = Entities.getEntityProperties(this.entityId, ["position, rotation"]);
|
||||
var forwardVec = Quat.getFront(Quat.multiply(props.rotation, Quat.fromPitchYawRollDegrees(0, 90, 0)));
|
||||
forwardVec = Vec3.normalize(forwardVec);
|
||||
var forwardQuat = orientationOf(forwardVec);
|
||||
var upVec = Quat.getUp(props.rotation);
|
||||
var position = Vec3.sum(props.position, Vec3.multiply(forwardVec, TIP_OFFSET_Z));
|
||||
position = Vec3.sum(position, Vec3.multiply(upVec, TIP_OFFSET_Y))
|
||||
Entities.editEntity(this.paintStream, {
|
||||
position: position,
|
||||
emitOrientation: forwardQuat,
|
||||
});
|
||||
|
||||
this.sprayInjector.setOptions({
|
||||
position: position,
|
||||
volume: this.sprayVolume
|
||||
});
|
||||
}
|
||||
|
||||
this.preload = function(entityId) {
|
||||
this.sprayVolume = 0.1;
|
||||
this.spraying = false;
|
||||
this.entityId = entityId;
|
||||
this.resetKey = "resetMe";
|
||||
}
|
||||
|
||||
|
||||
this.unload = function() {
|
||||
if (this.paintStream) {
|
||||
Entities.deleteEntity(this.paintStream);
|
||||
}
|
||||
this.strokes.forEach(function(stroke) {
|
||||
Entities.deleteEntity(stroke);
|
||||
});
|
||||
}
|
||||
});
|
|
@ -10,22 +10,21 @@
|
|||
//
|
||||
|
||||
var array = [];
|
||||
var buffer = "\n\n\n\n\n======= JS API list =======";
|
||||
function listKeys(string, object) {
|
||||
if (string == "listKeys" || string == "array" || string == "buffer" || string == "i") {
|
||||
if (string === "listKeys" || string === "array" || string === "buffer" || string === "i") {
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof(object) != "object") {
|
||||
if (typeof(object) !== "object" || object === null) {
|
||||
array.push(string + " " + typeof(object));
|
||||
return;
|
||||
}
|
||||
|
||||
var keys = Object.keys(object);
|
||||
for (var i = 0; i < keys.length; ++i) {
|
||||
if (string == "") {
|
||||
if (string === "") {
|
||||
listKeys(keys[i], object[keys[i]]);
|
||||
} else {
|
||||
} else if (keys[i] !== "parent") {
|
||||
listKeys(string + "." + keys[i], object[keys[i]]);
|
||||
}
|
||||
}
|
||||
|
@ -34,9 +33,10 @@ function listKeys(string, object) {
|
|||
listKeys("", this);
|
||||
array.sort();
|
||||
|
||||
var buffer = "\n======= JS API list =======";
|
||||
for (var i = 0; i < array.length; ++i) {
|
||||
buffer = buffer + "\n" + array[i];
|
||||
buffer += "\n" + array[i];
|
||||
}
|
||||
buffer = buffer + "\n========= API END =========\n\n\n\n\n";
|
||||
buffer += "\n========= API END =========\n";
|
||||
|
||||
print(buffer);
|
||||
|
|
|
@ -13,6 +13,7 @@
|
|||
|
||||
var createdRenderMenu = false;
|
||||
var createdGeneratedAudioMenu = false;
|
||||
var createdAudioListenerModeMenu = false;
|
||||
var createdStereoInputMenuItem = false;
|
||||
|
||||
var DEVELOPER_MENU = "Developer";
|
||||
|
@ -29,6 +30,20 @@ var AUDIO_SOURCE_INJECT = "Generated Audio";
|
|||
var AUDIO_SOURCE_MENU = AUDIO_MENU + " > Generated Audio Source";
|
||||
var AUDIO_SOURCE_PINK_NOISE = "Pink Noise";
|
||||
var AUDIO_SOURCE_SINE_440 = "Sine 440hz";
|
||||
var AUDIO_LISTENER_MODE_MENU = AUDIO_MENU + " > Audio Listener Mode"
|
||||
var AUDIO_LISTENER_MODE_FROM_HEAD = "Audio from head";
|
||||
var AUDIO_LISTENER_MODE_FROM_CAMERA = "Audio from camera";
|
||||
var AUDIO_LISTENER_MODE_CUSTOM = "Audio from custom position";
|
||||
|
||||
// be sure that the audio listener options are in the right order (same as the enumerator)
|
||||
var AUDIO_LISTENER_OPTIONS = [
|
||||
// MyAvatar.FROM_HEAD (0)
|
||||
AUDIO_LISTENER_MODE_FROM_HEAD,
|
||||
// MyAvatar.FROM_CAMERA (1)
|
||||
AUDIO_LISTENER_MODE_FROM_CAMERA,
|
||||
// MyAvatar.CUSTOM (2)
|
||||
AUDIO_LISTENER_MODE_CUSTOM
|
||||
];
|
||||
var AUDIO_STEREO_INPUT = "Stereo Input";
|
||||
|
||||
|
||||
|
@ -67,7 +82,6 @@ function setupMenus() {
|
|||
Menu.addMenuItem({ menuName: RENDER_MENU, menuItemName: AVATARS_ITEM, isCheckable: true, isChecked: Scene.shouldRenderAvatars })
|
||||
}
|
||||
|
||||
|
||||
if (!Menu.menuExists(AUDIO_MENU)) {
|
||||
Menu.addMenu(AUDIO_MENU);
|
||||
}
|
||||
|
@ -80,6 +94,15 @@ function setupMenus() {
|
|||
Audio.selectPinkNoise();
|
||||
createdGeneratedAudioMenu = true;
|
||||
}
|
||||
|
||||
if (!Menu.menuExists(AUDIO_LISTENER_MODE_MENU)) {
|
||||
Menu.addMenu(AUDIO_LISTENER_MODE_MENU);
|
||||
for (var i = 0; i < AUDIO_LISTENER_OPTIONS.length; i++) {
|
||||
Menu.addMenuItem({ menuName: AUDIO_LISTENER_MODE_MENU, menuItemName: AUDIO_LISTENER_OPTIONS[i], isCheckable: true, isChecked: (MyAvatar.audioListenerMode === i) });
|
||||
}
|
||||
createdAudioListenerModeMenu = true;
|
||||
}
|
||||
|
||||
if (!Menu.menuItemExists(AUDIO_MENU, AUDIO_STEREO_INPUT)) {
|
||||
Menu.addMenuItem({ menuName: AUDIO_MENU, menuItemName: AUDIO_STEREO_INPUT, isCheckable: true, isChecked: false });
|
||||
createdStereoInputMenuItem = true;
|
||||
|
@ -99,15 +122,23 @@ Menu.menuItemEvent.connect(function (menuItem) {
|
|||
Scene.shouldRenderAvatars = Menu.isOptionChecked(AVATARS_ITEM);
|
||||
} else if (menuItem == AUDIO_SOURCE_INJECT && !createdGeneratedAudioMenu) {
|
||||
Audio.injectGeneratedNoise(Menu.isOptionChecked(AUDIO_SOURCE_INJECT));
|
||||
} else if (menuItem == AUDIO_SOURCE_PINK_NOISE && !createdGeneratedAudioMenu) {
|
||||
Audio.selectPinkNoise();
|
||||
Menu.setIsOptionChecked(AUDIO_SOURCE_SINE_440, false);
|
||||
} else if (menuItem == AUDIO_SOURCE_SINE_440 && !createdGeneratedAudioMenu) {
|
||||
Audio.selectSine440();
|
||||
Menu.setIsOptionChecked(AUDIO_SOURCE_PINK_NOISE, false);
|
||||
} else if (menuItem == AUDIO_STEREO_INPUT) {
|
||||
Audio.setStereoInput(Menu.isOptionChecked(AUDIO_STEREO_INPUT))
|
||||
}
|
||||
} else if (menuItem == AUDIO_SOURCE_PINK_NOISE && !createdGeneratedAudioMenu) {
|
||||
Audio.selectPinkNoise();
|
||||
Menu.setIsOptionChecked(AUDIO_SOURCE_SINE_440, false);
|
||||
} else if (menuItem == AUDIO_SOURCE_SINE_440 && !createdGeneratedAudioMenu) {
|
||||
Audio.selectSine440();
|
||||
Menu.setIsOptionChecked(AUDIO_SOURCE_PINK_NOISE, false);
|
||||
} else if (menuItem == AUDIO_STEREO_INPUT) {
|
||||
Audio.setStereoInput(Menu.isOptionChecked(AUDIO_STEREO_INPUT))
|
||||
} else if (AUDIO_LISTENER_OPTIONS.indexOf(menuItem) !== -1) {
|
||||
MyAvatar.audioListenerMode = AUDIO_LISTENER_OPTIONS.indexOf(menuItem);
|
||||
}
|
||||
});
|
||||
|
||||
MyAvatar.audioListenerModeChanged.connect(function() {
|
||||
for (var i = 0; i < AUDIO_LISTENER_OPTIONS.length; i++) {
|
||||
Menu.setIsOptionChecked(AUDIO_LISTENER_OPTIONS[i], (MyAvatar.audioListenerMode === i));
|
||||
}
|
||||
});
|
||||
|
||||
Scene.shouldRenderAvatarsChanged.connect(function(shouldRenderAvatars) {
|
||||
|
@ -134,6 +165,10 @@ function scriptEnding() {
|
|||
Menu.removeMenu(AUDIO_SOURCE_MENU);
|
||||
}
|
||||
|
||||
if (createdAudioListenerModeMenu) {
|
||||
Menu.removeMenu(AUDIO_LISTENER_MODE_MENU);
|
||||
}
|
||||
|
||||
if (createdStereoInputMenuItem) {
|
||||
Menu.removeMenuItem(AUDIO_MENU, AUDIO_STEREO_INPUT);
|
||||
}
|
||||
|
|
|
@ -1,6 +1,8 @@
|
|||
set(TARGET_NAME interface)
|
||||
project(${TARGET_NAME})
|
||||
|
||||
add_definitions(-DGLEW_STATIC)
|
||||
|
||||
# set a default root dir for each of our optional externals if it was not passed
|
||||
set(OPTIONAL_EXTERNALS "Faceshift" "LeapMotion" "RtMidi" "RSSDK" "3DConnexionClient" "iViewHMD")
|
||||
foreach(EXTERNAL ${OPTIONAL_EXTERNALS})
|
||||
|
|
|
@ -23,10 +23,17 @@
|
|||
"positionVar": "leftHandPosition",
|
||||
"rotationVar": "leftHandRotation"
|
||||
},
|
||||
{
|
||||
"jointName": "Neck",
|
||||
"positionVar": "neckPosition",
|
||||
"rotationVar": "neckRotation",
|
||||
"typeVar": "headAndNeckType"
|
||||
},
|
||||
{
|
||||
"jointName": "Head",
|
||||
"positionVar": "headPosition",
|
||||
"rotationVar": "headRotation"
|
||||
"rotationVar": "headRotation",
|
||||
"typeVar": "headAndNeckType"
|
||||
}
|
||||
]
|
||||
},
|
||||
|
@ -554,7 +561,7 @@
|
|||
"id": "strafeLeft",
|
||||
"type": "clip",
|
||||
"data": {
|
||||
"url": "https://hifi-public.s3.amazonaws.com/ozan/anim/standard_anims/strafe_left.fbx",
|
||||
"url": "http://hifi-public.s3.amazonaws.com/ozan/anim/standard_anims/side_step_left.fbx",
|
||||
"startFrame": 0.0,
|
||||
"endFrame": 31.0,
|
||||
"timeScale": 1.0,
|
||||
|
@ -566,7 +573,7 @@
|
|||
"id": "strafeRight",
|
||||
"type": "clip",
|
||||
"data": {
|
||||
"url": "https://hifi-public.s3.amazonaws.com/ozan/anim/standard_anims/strafe_right.fbx",
|
||||
"url": "http://hifi-public.s3.amazonaws.com/ozan/anim/standard_anims/side_step_right.fbx",
|
||||
"startFrame": 0.0,
|
||||
"endFrame": 31.0,
|
||||
"timeScale": 1.0,
|
||||
|
|
|
@ -196,7 +196,6 @@ Hifi.VrMenu {
|
|||
|
||||
function insertItem(menu, beforeItem, newMenuItem) {
|
||||
for (var i = 0; i < menu.items.length; ++i) {
|
||||
console.log(menu.items[i]);
|
||||
if (menu.items[i] === beforeItem) {
|
||||
return menu.insertItem(i, newMenuItem);
|
||||
}
|
||||
|
|
|
@ -708,7 +708,6 @@ Application::Application(int& argc, char** argv, QElapsedTimer &startup_time) :
|
|||
|
||||
// Now that menu is initalized we can sync myAvatar with it's state.
|
||||
_myAvatar->updateMotionBehaviorFromMenu();
|
||||
_myAvatar->updateStandingHMDModeFromMenu();
|
||||
|
||||
// the 3Dconnexion device wants to be initiliazed after a window is displayed.
|
||||
ConnexionClient::getInstance().init();
|
||||
|
@ -794,6 +793,8 @@ void Application::cleanupBeforeQuit() {
|
|||
DependencyManager::get<EyeTracker>()->setEnabled(false, true);
|
||||
#endif
|
||||
|
||||
AnimDebugDraw::getInstance().shutdown();
|
||||
|
||||
if (_keyboardFocusHighlightID > 0) {
|
||||
getOverlays().deleteOverlay(_keyboardFocusHighlightID);
|
||||
_keyboardFocusHighlightID = -1;
|
||||
|
@ -1033,15 +1034,10 @@ void Application::initializeUi() {
|
|||
updateInputModes();
|
||||
}
|
||||
|
||||
template<typename F>
|
||||
void doInBatch(RenderArgs* args, F f) {
|
||||
gpu::Batch batch;
|
||||
f(batch);
|
||||
args->_context->render(batch);
|
||||
}
|
||||
|
||||
void Application::paintGL() {
|
||||
PROFILE_RANGE(__FUNCTION__);
|
||||
PerformanceTimer perfTimer("paintGL");
|
||||
|
||||
if (nullptr == _displayPlugin) {
|
||||
return;
|
||||
}
|
||||
|
@ -1058,6 +1054,7 @@ void Application::paintGL() {
|
|||
auto displayPlugin = getActiveDisplayPlugin();
|
||||
displayPlugin->preRender();
|
||||
_offscreenContext->makeCurrent();
|
||||
|
||||
// update the avatar with a fresh HMD pose
|
||||
_myAvatar->updateFromHMDSensorMatrix(getHMDSensorPose());
|
||||
|
||||
|
@ -1068,18 +1065,19 @@ void Application::paintGL() {
|
|||
lodManager->getBoundaryLevelAdjust(), RenderArgs::DEFAULT_RENDER_MODE,
|
||||
RenderArgs::MONO, RenderArgs::RENDER_DEBUG_NONE);
|
||||
|
||||
PerformanceTimer perfTimer("paintGL");
|
||||
|
||||
|
||||
PerformanceWarning::setSuppressShortTimings(Menu::getInstance()->isOptionChecked(MenuOption::SuppressShortTimings));
|
||||
bool showWarnings = Menu::getInstance()->isOptionChecked(MenuOption::PipelineWarnings);
|
||||
PerformanceWarning warn(showWarnings, "Application::paintGL()");
|
||||
resizeGL();
|
||||
|
||||
// Before anything else, let's sync up the gpuContext with the true glcontext used in case anything happened
|
||||
renderArgs._context->syncCache();
|
||||
{
|
||||
PerformanceTimer perfTimer("syncCache");
|
||||
renderArgs._context->syncCache();
|
||||
}
|
||||
|
||||
if (Menu::getInstance()->isOptionChecked(MenuOption::Mirror)) {
|
||||
PerformanceTimer perfTimer("Mirror");
|
||||
auto primaryFbo = DependencyManager::get<FramebufferCache>()->getPrimaryFramebufferDepthColor();
|
||||
|
||||
renderArgs._renderMode = RenderArgs::MIRROR_RENDER_MODE;
|
||||
|
@ -1093,12 +1091,12 @@ void Application::paintGL() {
|
|||
auto mirrorRectDest = glm::ivec4(mirrorRect.z, mirrorRect.y, mirrorRect.x, mirrorRect.w);
|
||||
|
||||
auto selfieFbo = DependencyManager::get<FramebufferCache>()->getSelfieFramebuffer();
|
||||
gpu::Batch batch;
|
||||
batch.setFramebuffer(selfieFbo);
|
||||
batch.clearColorFramebuffer(gpu::Framebuffer::BUFFER_COLOR0, glm::vec4(0.0f, 0.0f, 0.0f, 0.0f));
|
||||
batch.blit(primaryFbo, mirrorRect, selfieFbo, mirrorRectDest);
|
||||
batch.setFramebuffer(nullptr);
|
||||
renderArgs._context->render(batch);
|
||||
gpu::doInBatch(renderArgs._context, [=](gpu::Batch& batch) {
|
||||
batch.setFramebuffer(selfieFbo);
|
||||
batch.clearColorFramebuffer(gpu::Framebuffer::BUFFER_COLOR0, glm::vec4(0.0f, 0.0f, 0.0f, 0.0f));
|
||||
batch.blit(primaryFbo, mirrorRect, selfieFbo, mirrorRectDest);
|
||||
batch.setFramebuffer(nullptr);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1111,81 +1109,86 @@ void Application::paintGL() {
|
|||
_applicationOverlay.renderOverlay(&renderArgs);
|
||||
}
|
||||
|
||||
_myAvatar->startCapture();
|
||||
if (_myCamera.getMode() == CAMERA_MODE_FIRST_PERSON || _myCamera.getMode() == CAMERA_MODE_THIRD_PERSON) {
|
||||
Menu::getInstance()->setIsOptionChecked(MenuOption::FirstPerson, _myAvatar->getBoomLength() <= MyAvatar::ZOOM_MIN);
|
||||
Menu::getInstance()->setIsOptionChecked(MenuOption::ThirdPerson, !(_myAvatar->getBoomLength() <= MyAvatar::ZOOM_MIN));
|
||||
Application::getInstance()->cameraMenuChanged();
|
||||
}
|
||||
{
|
||||
PerformanceTimer perfTimer("CameraUpdates");
|
||||
|
||||
// The render mode is default or mirror if the camera is in mirror mode, assigned further below
|
||||
renderArgs._renderMode = RenderArgs::DEFAULT_RENDER_MODE;
|
||||
|
||||
// Always use the default eye position, not the actual head eye position.
|
||||
// Using the latter will cause the camera to wobble with idle animations,
|
||||
// or with changes from the face tracker
|
||||
if (_myCamera.getMode() == CAMERA_MODE_FIRST_PERSON) {
|
||||
if (isHMDMode()) {
|
||||
mat4 camMat = _myAvatar->getSensorToWorldMatrix() * _myAvatar->getHMDSensorMatrix();
|
||||
_myCamera.setPosition(extractTranslation(camMat));
|
||||
_myCamera.setRotation(glm::quat_cast(camMat));
|
||||
} else {
|
||||
_myCamera.setPosition(_myAvatar->getDefaultEyePosition());
|
||||
_myCamera.setRotation(_myAvatar->getHead()->getCameraOrientation());
|
||||
_myAvatar->startCapture();
|
||||
if (_myCamera.getMode() == CAMERA_MODE_FIRST_PERSON || _myCamera.getMode() == CAMERA_MODE_THIRD_PERSON) {
|
||||
Menu::getInstance()->setIsOptionChecked(MenuOption::FirstPerson, _myAvatar->getBoomLength() <= MyAvatar::ZOOM_MIN);
|
||||
Menu::getInstance()->setIsOptionChecked(MenuOption::ThirdPerson, !(_myAvatar->getBoomLength() <= MyAvatar::ZOOM_MIN));
|
||||
Application::getInstance()->cameraMenuChanged();
|
||||
}
|
||||
} else if (_myCamera.getMode() == CAMERA_MODE_THIRD_PERSON) {
|
||||
if (isHMDMode()) {
|
||||
glm::quat hmdRotation = extractRotation(_myAvatar->getHMDSensorMatrix());
|
||||
_myCamera.setRotation(_myAvatar->getWorldAlignedOrientation() * hmdRotation);
|
||||
// Ignore MenuOption::CenterPlayerInView in HMD view
|
||||
glm::vec3 hmdOffset = extractTranslation(_myAvatar->getHMDSensorMatrix());
|
||||
_myCamera.setPosition(_myAvatar->getDefaultEyePosition()
|
||||
+ _myAvatar->getOrientation()
|
||||
* (_myAvatar->getScale() * _myAvatar->getBoomLength() * glm::vec3(0.0f, 0.0f, 1.0f) + hmdOffset));
|
||||
} else {
|
||||
_myCamera.setRotation(_myAvatar->getHead()->getOrientation());
|
||||
if (Menu::getInstance()->isOptionChecked(MenuOption::CenterPlayerInView)) {
|
||||
_myCamera.setPosition(_myAvatar->getDefaultEyePosition()
|
||||
+ _myCamera.getRotation()
|
||||
* (_myAvatar->getScale() * _myAvatar->getBoomLength() * glm::vec3(0.0f, 0.0f, 1.0f)));
|
||||
|
||||
// The render mode is default or mirror if the camera is in mirror mode, assigned further below
|
||||
renderArgs._renderMode = RenderArgs::DEFAULT_RENDER_MODE;
|
||||
|
||||
// Always use the default eye position, not the actual head eye position.
|
||||
// Using the latter will cause the camera to wobble with idle animations,
|
||||
// or with changes from the face tracker
|
||||
if (_myCamera.getMode() == CAMERA_MODE_FIRST_PERSON) {
|
||||
if (isHMDMode()) {
|
||||
mat4 camMat = _myAvatar->getSensorToWorldMatrix() * _myAvatar->getHMDSensorMatrix();
|
||||
_myCamera.setPosition(extractTranslation(camMat));
|
||||
_myCamera.setRotation(glm::quat_cast(camMat));
|
||||
} else {
|
||||
_myCamera.setPosition(_myAvatar->getDefaultEyePosition());
|
||||
_myCamera.setRotation(_myAvatar->getHead()->getCameraOrientation());
|
||||
}
|
||||
} else if (_myCamera.getMode() == CAMERA_MODE_THIRD_PERSON) {
|
||||
if (isHMDMode()) {
|
||||
glm::quat hmdRotation = extractRotation(_myAvatar->getHMDSensorMatrix());
|
||||
_myCamera.setRotation(_myAvatar->getWorldAlignedOrientation() * hmdRotation);
|
||||
// Ignore MenuOption::CenterPlayerInView in HMD view
|
||||
glm::vec3 hmdOffset = extractTranslation(_myAvatar->getHMDSensorMatrix());
|
||||
_myCamera.setPosition(_myAvatar->getDefaultEyePosition()
|
||||
+ _myAvatar->getOrientation()
|
||||
* (_myAvatar->getScale() * _myAvatar->getBoomLength() * glm::vec3(0.0f, 0.0f, 1.0f)));
|
||||
* (_myAvatar->getScale() * _myAvatar->getBoomLength() * glm::vec3(0.0f, 0.0f, 1.0f) + hmdOffset));
|
||||
} else {
|
||||
_myCamera.setRotation(_myAvatar->getHead()->getOrientation());
|
||||
if (Menu::getInstance()->isOptionChecked(MenuOption::CenterPlayerInView)) {
|
||||
_myCamera.setPosition(_myAvatar->getDefaultEyePosition()
|
||||
+ _myCamera.getRotation()
|
||||
* (_myAvatar->getScale() * _myAvatar->getBoomLength() * glm::vec3(0.0f, 0.0f, 1.0f)));
|
||||
} else {
|
||||
_myCamera.setPosition(_myAvatar->getDefaultEyePosition()
|
||||
+ _myAvatar->getOrientation()
|
||||
* (_myAvatar->getScale() * _myAvatar->getBoomLength() * glm::vec3(0.0f, 0.0f, 1.0f)));
|
||||
}
|
||||
}
|
||||
} else if (_myCamera.getMode() == CAMERA_MODE_MIRROR) {
|
||||
if (isHMDMode()) {
|
||||
glm::quat hmdRotation = extractRotation(_myAvatar->getHMDSensorMatrix());
|
||||
_myCamera.setRotation(_myAvatar->getWorldAlignedOrientation()
|
||||
* glm::quat(glm::vec3(0.0f, PI + _rotateMirror, 0.0f)) * hmdRotation);
|
||||
glm::vec3 hmdOffset = extractTranslation(_myAvatar->getHMDSensorMatrix());
|
||||
_myCamera.setPosition(_myAvatar->getDefaultEyePosition()
|
||||
+ glm::vec3(0, _raiseMirror * _myAvatar->getScale(), 0)
|
||||
+ (_myAvatar->getOrientation() * glm::quat(glm::vec3(0.0f, _rotateMirror, 0.0f))) *
|
||||
glm::vec3(0.0f, 0.0f, -1.0f) * MIRROR_FULLSCREEN_DISTANCE * _scaleMirror
|
||||
+ (_myAvatar->getOrientation() * glm::quat(glm::vec3(0.0f, PI + _rotateMirror, 0.0f))) * hmdOffset);
|
||||
} else {
|
||||
_myCamera.setRotation(_myAvatar->getWorldAlignedOrientation()
|
||||
* glm::quat(glm::vec3(0.0f, PI + _rotateMirror, 0.0f)));
|
||||
_myCamera.setPosition(_myAvatar->getDefaultEyePosition()
|
||||
+ glm::vec3(0, _raiseMirror * _myAvatar->getScale(), 0)
|
||||
+ (_myAvatar->getOrientation() * glm::quat(glm::vec3(0.0f, _rotateMirror, 0.0f))) *
|
||||
glm::vec3(0.0f, 0.0f, -1.0f) * MIRROR_FULLSCREEN_DISTANCE * _scaleMirror);
|
||||
}
|
||||
renderArgs._renderMode = RenderArgs::MIRROR_RENDER_MODE;
|
||||
}
|
||||
} else if (_myCamera.getMode() == CAMERA_MODE_MIRROR) {
|
||||
if (isHMDMode()) {
|
||||
glm::quat hmdRotation = extractRotation(_myAvatar->getHMDSensorMatrix());
|
||||
_myCamera.setRotation(_myAvatar->getWorldAlignedOrientation()
|
||||
* glm::quat(glm::vec3(0.0f, PI + _rotateMirror, 0.0f)) * hmdRotation);
|
||||
glm::vec3 hmdOffset = extractTranslation(_myAvatar->getHMDSensorMatrix());
|
||||
_myCamera.setPosition(_myAvatar->getDefaultEyePosition()
|
||||
+ glm::vec3(0, _raiseMirror * _myAvatar->getScale(), 0)
|
||||
+ (_myAvatar->getOrientation() * glm::quat(glm::vec3(0.0f, _rotateMirror, 0.0f))) *
|
||||
glm::vec3(0.0f, 0.0f, -1.0f) * MIRROR_FULLSCREEN_DISTANCE * _scaleMirror
|
||||
+ (_myAvatar->getOrientation() * glm::quat(glm::vec3(0.0f, PI + _rotateMirror, 0.0f))) * hmdOffset);
|
||||
} else {
|
||||
_myCamera.setRotation(_myAvatar->getWorldAlignedOrientation()
|
||||
* glm::quat(glm::vec3(0.0f, PI + _rotateMirror, 0.0f)));
|
||||
_myCamera.setPosition(_myAvatar->getDefaultEyePosition()
|
||||
+ glm::vec3(0, _raiseMirror * _myAvatar->getScale(), 0)
|
||||
+ (_myAvatar->getOrientation() * glm::quat(glm::vec3(0.0f, _rotateMirror, 0.0f))) *
|
||||
glm::vec3(0.0f, 0.0f, -1.0f) * MIRROR_FULLSCREEN_DISTANCE * _scaleMirror);
|
||||
// Update camera position
|
||||
if (!isHMDMode()) {
|
||||
_myCamera.update(1.0f / _fps);
|
||||
}
|
||||
renderArgs._renderMode = RenderArgs::MIRROR_RENDER_MODE;
|
||||
_myAvatar->endCapture();
|
||||
}
|
||||
// Update camera position
|
||||
if (!isHMDMode()) {
|
||||
_myCamera.update(1.0f / _fps);
|
||||
}
|
||||
_myAvatar->endCapture();
|
||||
|
||||
// Primary rendering pass
|
||||
auto framebufferCache = DependencyManager::get<FramebufferCache>();
|
||||
const QSize size = framebufferCache->getFrameBufferSize();
|
||||
{
|
||||
PROFILE_RANGE(__FUNCTION__ "/mainRender");
|
||||
PerformanceTimer perfTimer("mainRender");
|
||||
// Viewport is assigned to the size of the framebuffer
|
||||
renderArgs._viewport = ivec4(0, 0, size.width(), size.height());
|
||||
if (displayPlugin->isStereo()) {
|
||||
|
@ -1222,7 +1225,7 @@ void Application::paintGL() {
|
|||
}
|
||||
displaySide(&renderArgs, _myCamera);
|
||||
renderArgs._context->enableStereo(false);
|
||||
doInBatch(&renderArgs, [](gpu::Batch& batch) {
|
||||
gpu::doInBatch(renderArgs._context, [](gpu::Batch& batch) {
|
||||
batch.setFramebuffer(nullptr);
|
||||
});
|
||||
}
|
||||
|
@ -1230,6 +1233,7 @@ void Application::paintGL() {
|
|||
// Overlay Composition, needs to occur after screen space effects have completed
|
||||
{
|
||||
PROFILE_RANGE(__FUNCTION__ "/compositor");
|
||||
PerformanceTimer perfTimer("compositor");
|
||||
auto primaryFbo = framebufferCache->getPrimaryFramebuffer();
|
||||
glBindFramebuffer(GL_DRAW_FRAMEBUFFER, gpu::GLBackend::getFramebufferID(primaryFbo));
|
||||
if (displayPlugin->isStereo()) {
|
||||
|
@ -1254,6 +1258,7 @@ void Application::paintGL() {
|
|||
// deliver final composited scene to the display plugin
|
||||
{
|
||||
PROFILE_RANGE(__FUNCTION__ "/pluginOutput");
|
||||
PerformanceTimer perfTimer("pluginOutput");
|
||||
auto primaryFbo = framebufferCache->getPrimaryFramebuffer();
|
||||
GLuint finalTexture = gpu::GLBackend::getTextureID(primaryFbo->getRenderBuffer(0));
|
||||
// Ensure the rendering context commands are completed when rendering
|
||||
|
@ -1271,24 +1276,29 @@ void Application::paintGL() {
|
|||
|
||||
{
|
||||
PROFILE_RANGE(__FUNCTION__ "/pluginDisplay");
|
||||
PerformanceTimer perfTimer("pluginDisplay");
|
||||
displayPlugin->display(finalTexture, toGlm(size));
|
||||
}
|
||||
|
||||
{
|
||||
PROFILE_RANGE(__FUNCTION__ "/bufferSwap");
|
||||
PerformanceTimer perfTimer("bufferSwap");
|
||||
displayPlugin->finishFrame();
|
||||
}
|
||||
}
|
||||
|
||||
_offscreenContext->makeCurrent();
|
||||
_frameCount++;
|
||||
Stats::getInstance()->setRenderDetails(renderArgs._details);
|
||||
{
|
||||
PerformanceTimer perfTimer("makeCurrent");
|
||||
_offscreenContext->makeCurrent();
|
||||
_frameCount++;
|
||||
Stats::getInstance()->setRenderDetails(renderArgs._details);
|
||||
|
||||
// Reset the gpu::Context Stages
|
||||
// Back to the default framebuffer;
|
||||
gpu::Batch batch;
|
||||
batch.resetStages();
|
||||
renderArgs._context->render(batch);
|
||||
// Reset the gpu::Context Stages
|
||||
// Back to the default framebuffer;
|
||||
gpu::doInBatch(renderArgs._context, [=](gpu::Batch& batch) {
|
||||
batch.resetStages();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void Application::runTests() {
|
||||
|
@ -1839,8 +1849,16 @@ void Application::mouseMoveEvent(QMouseEvent* event, unsigned int deviceID) {
|
|||
|
||||
|
||||
_entities.mouseMoveEvent(event, deviceID);
|
||||
{
|
||||
auto offscreenUi = DependencyManager::get<OffscreenUi>();
|
||||
QPointF transformedPos = offscreenUi->mapToVirtualScreen(event->localPos(), _glWidget);
|
||||
QMouseEvent mappedEvent(event->type(),
|
||||
transformedPos,
|
||||
event->screenPos(), event->button(),
|
||||
event->buttons(), event->modifiers());
|
||||
_controllerScriptingInterface.emitMouseMoveEvent(&mappedEvent, deviceID); // send events to any registered scripts
|
||||
}
|
||||
|
||||
_controllerScriptingInterface.emitMouseMoveEvent(event, deviceID); // send events to any registered scripts
|
||||
// if one of our scripts have asked to capture this event, then stop processing it
|
||||
if (_controllerScriptingInterface.isMouseCaptured()) {
|
||||
return;
|
||||
|
@ -1855,12 +1873,19 @@ void Application::mouseMoveEvent(QMouseEvent* event, unsigned int deviceID) {
|
|||
void Application::mousePressEvent(QMouseEvent* event, unsigned int deviceID) {
|
||||
// Inhibit the menu if the user is using alt-mouse dragging
|
||||
_altPressed = false;
|
||||
|
||||
if (!_aboutToQuit) {
|
||||
_entities.mousePressEvent(event, deviceID);
|
||||
}
|
||||
|
||||
_controllerScriptingInterface.emitMousePressEvent(event); // send events to any registered scripts
|
||||
{
|
||||
auto offscreenUi = DependencyManager::get<OffscreenUi>();
|
||||
QPointF transformedPos = offscreenUi->mapToVirtualScreen(event->localPos(), _glWidget);
|
||||
QMouseEvent mappedEvent(event->type(),
|
||||
transformedPos,
|
||||
event->screenPos(), event->button(),
|
||||
event->buttons(), event->modifiers());
|
||||
_controllerScriptingInterface.emitMousePressEvent(&mappedEvent); // send events to any registered scripts
|
||||
}
|
||||
|
||||
// if one of our scripts have asked to capture this event, then stop processing it
|
||||
if (_controllerScriptingInterface.isMouseCaptured()) {
|
||||
|
@ -1911,7 +1936,15 @@ void Application::mouseReleaseEvent(QMouseEvent* event, unsigned int deviceID) {
|
|||
_entities.mouseReleaseEvent(event, deviceID);
|
||||
}
|
||||
|
||||
_controllerScriptingInterface.emitMouseReleaseEvent(event); // send events to any registered scripts
|
||||
{
|
||||
auto offscreenUi = DependencyManager::get<OffscreenUi>();
|
||||
QPointF transformedPos = offscreenUi->mapToVirtualScreen(event->localPos(), _glWidget);
|
||||
QMouseEvent mappedEvent(event->type(),
|
||||
transformedPos,
|
||||
event->screenPos(), event->button(),
|
||||
event->buttons(), event->modifiers());
|
||||
_controllerScriptingInterface.emitMouseReleaseEvent(&mappedEvent); // send events to any registered scripts
|
||||
}
|
||||
|
||||
// if one of our scripts have asked to capture this event, then stop processing it
|
||||
if (_controllerScriptingInterface.isMouseCaptured()) {
|
||||
|
@ -2330,7 +2363,8 @@ bool Application::exportEntities(const QString& filename, const QVector<EntityIt
|
|||
QVector<EntityItemPointer> entities;
|
||||
|
||||
auto entityTree = _entities.getTree();
|
||||
EntityTree exportTree;
|
||||
auto exportTree = std::make_shared<EntityTree>();
|
||||
exportTree->createRootElement();
|
||||
|
||||
glm::vec3 root(TREE_SCALE, TREE_SCALE, TREE_SCALE);
|
||||
for (auto entityID : entityIDs) {
|
||||
|
@ -2357,10 +2391,10 @@ bool Application::exportEntities(const QString& filename, const QVector<EntityIt
|
|||
auto properties = entityItem->getProperties();
|
||||
|
||||
properties.setPosition(properties.getPosition() - root);
|
||||
exportTree.addEntity(entityItem->getEntityItemID(), properties);
|
||||
exportTree->addEntity(entityItem->getEntityItemID(), properties);
|
||||
}
|
||||
|
||||
exportTree.writeToJSONFile(filename.toLocal8Bit().constData());
|
||||
exportTree->writeToJSONFile(filename.toLocal8Bit().constData());
|
||||
|
||||
// restore the main window's active state
|
||||
_window->activateWindow();
|
||||
|
@ -2373,15 +2407,16 @@ bool Application::exportEntities(const QString& filename, float x, float y, floa
|
|||
|
||||
if (entities.size() > 0) {
|
||||
glm::vec3 root(x, y, z);
|
||||
EntityTree exportTree;
|
||||
auto exportTree = std::make_shared<EntityTree>();
|
||||
exportTree->createRootElement();
|
||||
|
||||
for (int i = 0; i < entities.size(); i++) {
|
||||
EntityItemProperties properties = entities.at(i)->getProperties();
|
||||
EntityItemID id = entities.at(i)->getEntityItemID();
|
||||
properties.setPosition(properties.getPosition() - root);
|
||||
exportTree.addEntity(id, properties);
|
||||
exportTree->addEntity(id, properties);
|
||||
}
|
||||
exportTree.writeToSVOFile(filename.toLocal8Bit().constData());
|
||||
exportTree->writeToSVOFile(filename.toLocal8Bit().constData());
|
||||
} else {
|
||||
qCDebug(interfaceapp) << "No models were selected";
|
||||
return false;
|
||||
|
@ -4029,6 +4064,8 @@ void Application::registerScriptEngineWithApplicationServices(ScriptEngine* scri
|
|||
|
||||
// hook our avatar and avatar hash map object into this script engine
|
||||
scriptEngine->registerGlobalObject("MyAvatar", _myAvatar);
|
||||
qScriptRegisterMetaType(scriptEngine, audioListenModeToScriptValue, audioListenModeFromScriptValue);
|
||||
|
||||
scriptEngine->registerGlobalObject("AvatarList", DependencyManager::get<AvatarManager>().data());
|
||||
|
||||
scriptEngine->registerGlobalObject("Camera", &_myCamera);
|
||||
|
@ -4063,6 +4100,7 @@ void Application::registerScriptEngineWithApplicationServices(ScriptEngine* scri
|
|||
scriptEngine->registerFunction("WebWindow", WebWindowClass::constructor, 1);
|
||||
|
||||
scriptEngine->registerGlobalObject("Menu", MenuScriptingInterface::getInstance());
|
||||
scriptEngine->registerGlobalObject("Stats", Stats::getInstance());
|
||||
scriptEngine->registerGlobalObject("Settings", SettingsScriptingInterface::getInstance());
|
||||
scriptEngine->registerGlobalObject("AudioDevice", AudioDeviceScriptingInterface::getInstance());
|
||||
scriptEngine->registerGlobalObject("AnimationCache", DependencyManager::get<AnimationCache>().data());
|
||||
|
|
|
@ -142,8 +142,8 @@ public:
|
|||
static Application* getInstance() { return qApp; } // TODO: replace fully by qApp
|
||||
static const glm::vec3& getPositionForPath() { return getInstance()->_myAvatar->getPosition(); }
|
||||
static glm::quat getOrientationForPath() { return getInstance()->_myAvatar->getOrientation(); }
|
||||
static glm::vec3 getPositionForAudio() { return getInstance()->_myAvatar->getHead()->getPosition(); }
|
||||
static glm::quat getOrientationForAudio() { return getInstance()->_myAvatar->getHead()->getFinalOrientationInWorldFrame(); }
|
||||
static glm::vec3 getPositionForAudio() { return getInstance()->_myAvatar->getPositionForAudio(); }
|
||||
static glm::quat getOrientationForAudio() { return getInstance()->_myAvatar->getOrientationForAudio(); }
|
||||
static void initPlugins();
|
||||
static void shutdownPlugins();
|
||||
|
||||
|
|
|
@ -43,6 +43,9 @@ EntityActionPointer InterfaceActionFactory::factory(EntityActionType type,
|
|||
if (action) {
|
||||
bool ok = action->updateArguments(arguments);
|
||||
if (ok) {
|
||||
if (action->lifetimeIsOver()) {
|
||||
return nullptr;
|
||||
}
|
||||
return action;
|
||||
}
|
||||
}
|
||||
|
@ -63,5 +66,9 @@ EntityActionPointer InterfaceActionFactory::factoryBA(EntityItemPointer ownerEnt
|
|||
if (action) {
|
||||
action->deserialize(data);
|
||||
}
|
||||
if (action->lifetimeIsOver()) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
return action;
|
||||
}
|
||||
|
|
|
@ -294,9 +294,6 @@ Menu::Menu() {
|
|||
|
||||
addCheckableActionToQMenuAndActionHash(viewMenu, MenuOption::TurnWithHead, 0, false);
|
||||
|
||||
addCheckableActionToQMenuAndActionHash(viewMenu, MenuOption::StandingHMDSensorMode, 0, false,
|
||||
avatar, SLOT(updateStandingHMDModeFromMenu()));
|
||||
|
||||
addCheckableActionToQMenuAndActionHash(viewMenu, MenuOption::WorldAxes);
|
||||
|
||||
addCheckableActionToQMenuAndActionHash(viewMenu, MenuOption::Stats);
|
||||
|
@ -449,9 +446,9 @@ Menu::Menu() {
|
|||
addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::FixGaze, 0, false);
|
||||
addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::EnableAvatarUpdateThreading, 0, false,
|
||||
qApp, SLOT(setAvatarUpdateThreading(bool)));
|
||||
addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::EnableRigAnimations, 0, true,
|
||||
addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::EnableRigAnimations, 0, false,
|
||||
avatar, SLOT(setEnableRigAnimations(bool)));
|
||||
addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::EnableAnimGraph, 0, false,
|
||||
addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::EnableAnimGraph, 0, true,
|
||||
avatar, SLOT(setEnableAnimGraph(bool)));
|
||||
addCheckableActionToQMenuAndActionHash(avatarDebugMenu, MenuOption::AnimDebugDrawBindPose, 0, false,
|
||||
avatar, SLOT(setEnableDebugDrawBindPose(bool)));
|
||||
|
|
|
@ -141,6 +141,7 @@ void Stars::render(RenderArgs* renderArgs, float alpha) {
|
|||
auto state = gpu::StatePointer(new gpu::State());
|
||||
// enable decal blend
|
||||
state->setDepthTest(gpu::State::DepthTest(false));
|
||||
state->setStencilTest(true, 0xFF, gpu::State::StencilTest(0, 0xFF, gpu::EQUAL, gpu::State::STENCIL_OP_KEEP, gpu::State::STENCIL_OP_KEEP, gpu::State::STENCIL_OP_KEEP));
|
||||
state->setBlendFunction(true, gpu::State::SRC_ALPHA, gpu::State::BLEND_OP_ADD, gpu::State::INV_SRC_ALPHA);
|
||||
_gridPipeline.reset(gpu::Pipeline::create(program, state));
|
||||
}
|
||||
|
@ -152,6 +153,7 @@ void Stars::render(RenderArgs* renderArgs, float alpha) {
|
|||
auto state = gpu::StatePointer(new gpu::State());
|
||||
// enable decal blend
|
||||
state->setDepthTest(gpu::State::DepthTest(false));
|
||||
state->setStencilTest(true, 0xFF, gpu::State::StencilTest(0, 0xFF, gpu::EQUAL, gpu::State::STENCIL_OP_KEEP, gpu::State::STENCIL_OP_KEEP, gpu::State::STENCIL_OP_KEEP));
|
||||
state->setAntialiasedLineEnable(true); // line smoothing also smooth points
|
||||
state->setBlendFunction(true, gpu::State::SRC_ALPHA, gpu::State::BLEND_OP_ADD, gpu::State::INV_SRC_ALPHA);
|
||||
_starsPipeline.reset(gpu::Pipeline::create(program, state));
|
||||
|
|
|
@ -202,11 +202,14 @@ void Avatar::simulate(float deltaTime) {
|
|||
PerformanceTimer perfTimer("skeleton");
|
||||
for (int i = 0; i < _jointData.size(); i++) {
|
||||
const JointData& data = _jointData.at(i);
|
||||
_skeletonModel.setJointState(i, true, data.rotation);
|
||||
_skeletonModel.setJointRotation(i, data.rotationSet, data.rotation, 1.0f);
|
||||
_skeletonModel.setJointTranslation(i, data.translationSet, data.translation, 1.0f);
|
||||
}
|
||||
_skeletonModel.simulate(deltaTime, _hasNewJointRotations);
|
||||
|
||||
_skeletonModel.simulate(deltaTime, _hasNewJointRotations || _hasNewJointTranslations);
|
||||
simulateAttachments(deltaTime);
|
||||
_hasNewJointRotations = false;
|
||||
_hasNewJointTranslations = false;
|
||||
}
|
||||
{
|
||||
PerformanceTimer perfTimer("head");
|
||||
|
@ -879,6 +882,16 @@ glm::quat Avatar::getJointRotation(int index) const {
|
|||
return rotation;
|
||||
}
|
||||
|
||||
glm::vec3 Avatar::getJointTranslation(int index) const {
|
||||
if (QThread::currentThread() != thread()) {
|
||||
return AvatarData::getJointTranslation(index);
|
||||
}
|
||||
glm::vec3 translation;
|
||||
_skeletonModel.getJointTranslation(index, translation);
|
||||
return translation;
|
||||
}
|
||||
|
||||
|
||||
int Avatar::getJointIndex(const QString& name) const {
|
||||
if (QThread::currentThread() != thread()) {
|
||||
int result;
|
||||
|
|
|
@ -115,6 +115,7 @@ public:
|
|||
|
||||
virtual QVector<glm::quat> getJointRotations() const;
|
||||
virtual glm::quat getJointRotation(int index) const;
|
||||
virtual glm::vec3 getJointTranslation(int index) const;
|
||||
virtual int getJointIndex(const QString& name) const;
|
||||
virtual QStringList getJointNames() const;
|
||||
|
||||
|
|
|
@ -84,6 +84,9 @@ void AvatarActionHold::updateActionWorker(float deltaTimeStep) {
|
|||
|
||||
|
||||
bool AvatarActionHold::updateArguments(QVariantMap arguments) {
|
||||
if (!ObjectAction::updateArguments(arguments)) {
|
||||
return false;
|
||||
}
|
||||
bool ok = true;
|
||||
glm::vec3 relativePosition =
|
||||
EntityActionInterface::extractVec3Argument("hold", arguments, "relativePosition", ok, false);
|
||||
|
@ -134,7 +137,7 @@ bool AvatarActionHold::updateArguments(QVariantMap arguments) {
|
|||
|
||||
|
||||
QVariantMap AvatarActionHold::getArguments() {
|
||||
QVariantMap arguments;
|
||||
QVariantMap arguments = ObjectAction::getArguments();
|
||||
withReadLock([&]{
|
||||
if (!_mine) {
|
||||
arguments = ObjectActionSpring::getArguments();
|
||||
|
|
|
@ -124,14 +124,12 @@ void Head::simulate(float deltaTime, bool isMine, bool billboard) {
|
|||
_isEyeTrackerConnected = eyeTracker->isTracking();
|
||||
}
|
||||
|
||||
if (!myAvatar->getStandingHMDSensorMode()) {
|
||||
// Twist the upper body to follow the rotation of the head, but only do this with my avatar,
|
||||
// since everyone else will see the full joint rotations for other people.
|
||||
const float BODY_FOLLOW_HEAD_YAW_RATE = 0.1f;
|
||||
const float BODY_FOLLOW_HEAD_FACTOR = 0.66f;
|
||||
float currentTwist = getTorsoTwist();
|
||||
setTorsoTwist(currentTwist + (getFinalYaw() * BODY_FOLLOW_HEAD_FACTOR - currentTwist) * BODY_FOLLOW_HEAD_YAW_RATE);
|
||||
}
|
||||
// Twist the upper body to follow the rotation of the head, but only do this with my avatar,
|
||||
// since everyone else will see the full joint rotations for other people.
|
||||
const float BODY_FOLLOW_HEAD_YAW_RATE = 0.1f;
|
||||
const float BODY_FOLLOW_HEAD_FACTOR = 0.66f;
|
||||
float currentTwist = getTorsoTwist();
|
||||
setTorsoTwist(currentTwist + (getFinalYaw() * BODY_FOLLOW_HEAD_FACTOR - currentTwist) * BODY_FOLLOW_HEAD_YAW_RATE);
|
||||
}
|
||||
|
||||
if (!(_isFaceTrackerConnected || billboard)) {
|
||||
|
@ -392,7 +390,7 @@ glm::quat Head::getCameraOrientation() const {
|
|||
// always the same.
|
||||
if (qApp->getAvatarUpdater()->isHMDMode()) {
|
||||
MyAvatar* myAvatar = dynamic_cast<MyAvatar*>(_owningAvatar);
|
||||
if (myAvatar && myAvatar->getStandingHMDSensorMode()) {
|
||||
if (myAvatar) {
|
||||
return glm::quat_cast(myAvatar->getSensorToWorldMatrix()) * myAvatar->getHMDSensorOrientation();
|
||||
} else {
|
||||
return getOrientation();
|
||||
|
|
|
@ -47,6 +47,7 @@
|
|||
#include "Recorder.h"
|
||||
#include "Util.h"
|
||||
#include "InterfaceLogging.h"
|
||||
#include "DebugDraw.h"
|
||||
|
||||
using namespace std;
|
||||
|
||||
|
@ -103,12 +104,12 @@ MyAvatar::MyAvatar(RigPointer rig) :
|
|||
_hmdSensorPosition(),
|
||||
_bodySensorMatrix(),
|
||||
_sensorToWorldMatrix(),
|
||||
_standingHMDSensorMode(false),
|
||||
_goToPending(false),
|
||||
_goToPosition(),
|
||||
_goToOrientation(),
|
||||
_rig(rig),
|
||||
_prevShouldDrawHead(true)
|
||||
_prevShouldDrawHead(true),
|
||||
_audioListenerMode(FROM_HEAD)
|
||||
{
|
||||
for (int i = 0; i < MAX_DRIVE_KEYS; i++) {
|
||||
_driveKeys[i] = 0.0f;
|
||||
|
@ -149,6 +150,26 @@ void MyAvatar::reset() {
|
|||
eulers.x = 0.0f;
|
||||
eulers.z = 0.0f;
|
||||
setOrientation(glm::quat(eulers));
|
||||
|
||||
// This should be simpler when we have only graph animations always on.
|
||||
bool isRig = _rig->getEnableRig();
|
||||
// seting rig animation to true, below, will clear the graph animation menu item, so grab it now.
|
||||
bool isGraph = _rig->getEnableAnimGraph() || Menu::getInstance()->isOptionChecked(MenuOption::EnableAnimGraph);
|
||||
qApp->setRawAvatarUpdateThreading(false);
|
||||
_rig->disableHands = true;
|
||||
setEnableRigAnimations(true);
|
||||
_skeletonModel.simulate(0.1f); // non-zero
|
||||
setEnableRigAnimations(false);
|
||||
_skeletonModel.simulate(0.1f);
|
||||
if (isRig) {
|
||||
setEnableRigAnimations(true);
|
||||
Menu::getInstance()->setIsOptionChecked(MenuOption::EnableRigAnimations, true);
|
||||
} else if (isGraph) {
|
||||
setEnableAnimGraph(true);
|
||||
Menu::getInstance()->setIsOptionChecked(MenuOption::EnableAnimGraph, true);
|
||||
}
|
||||
_rig->disableHands = false;
|
||||
qApp->setRawAvatarUpdateThreading();
|
||||
}
|
||||
|
||||
void MyAvatar::update(float deltaTime) {
|
||||
|
@ -219,9 +240,11 @@ void MyAvatar::simulate(float deltaTime) {
|
|||
PerformanceTimer perfTimer("joints");
|
||||
// copy out the skeleton joints from the model
|
||||
_jointData.resize(_rig->getJointStateCount());
|
||||
|
||||
for (int i = 0; i < _jointData.size(); i++) {
|
||||
JointData& data = _jointData[i];
|
||||
_rig->getJointStateRotation(i, data.rotation);
|
||||
data.rotationSet |= _rig->getJointStateRotation(i, data.rotation);
|
||||
data.translationSet |= _rig->getJointStateTranslation(i, data.translation);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -247,29 +270,90 @@ void MyAvatar::simulate(float deltaTime) {
|
|||
}
|
||||
|
||||
glm::mat4 MyAvatar::getSensorToWorldMatrix() const {
|
||||
if (getStandingHMDSensorMode()) {
|
||||
return _sensorToWorldMatrix;
|
||||
return _sensorToWorldMatrix;
|
||||
}
|
||||
|
||||
// returns true if pos is OUTSIDE of the vertical capsule
|
||||
// where the middle cylinder length is defined by capsuleLen and the radius by capsuleRad.
|
||||
static bool capsuleCheck(const glm::vec3& pos, float capsuleLen, float capsuleRad) {
|
||||
const float halfCapsuleLen = capsuleLen / 2.0f;
|
||||
if (fabs(pos.y) <= halfCapsuleLen) {
|
||||
// cylinder check for middle capsule
|
||||
glm::vec2 horizPos(pos.x, pos.z);
|
||||
return glm::length(horizPos) > capsuleRad;
|
||||
} else if (pos.y > halfCapsuleLen) {
|
||||
glm::vec3 center(0.0f, halfCapsuleLen, 0.0f);
|
||||
return glm::length(center - pos) > capsuleRad;
|
||||
} else if (pos.y < halfCapsuleLen) {
|
||||
glm::vec3 center(0.0f, -halfCapsuleLen, 0.0f);
|
||||
return glm::length(center - pos) > capsuleRad;
|
||||
} else {
|
||||
return createMatFromQuatAndPos(getWorldAlignedOrientation(), getDefaultEyePosition());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// best called at start of main loop just after we have a fresh hmd pose.
|
||||
// update internal body position from new hmd pose.
|
||||
// Pass a recent sample of the HMD to the avatar.
|
||||
// This can also update the avatar's position to follow the HMD
|
||||
// as it moves through the world.
|
||||
void MyAvatar::updateFromHMDSensorMatrix(const glm::mat4& hmdSensorMatrix) {
|
||||
|
||||
auto now = usecTimestampNow();
|
||||
auto deltaUsecs = now - _lastUpdateFromHMDTime;
|
||||
_lastUpdateFromHMDTime = now;
|
||||
double actualDeltaTime = (double)deltaUsecs / (double)USECS_PER_SECOND;
|
||||
const float BIGGEST_DELTA_TIME_SECS = 0.25f;
|
||||
float deltaTime = glm::clamp((float)actualDeltaTime, 0.0f, BIGGEST_DELTA_TIME_SECS);
|
||||
|
||||
// update the sensorMatrices based on the new hmd pose
|
||||
_hmdSensorMatrix = hmdSensorMatrix;
|
||||
_hmdSensorPosition = extractTranslation(hmdSensorMatrix);
|
||||
_hmdSensorOrientation = glm::quat_cast(hmdSensorMatrix);
|
||||
_bodySensorMatrix = deriveBodyFromHMDSensor();
|
||||
|
||||
if (getStandingHMDSensorMode()) {
|
||||
// set the body position/orientation to reflect motion due to the head.
|
||||
auto worldMat = _sensorToWorldMatrix * _bodySensorMatrix;
|
||||
nextAttitude(extractTranslation(worldMat), glm::quat_cast(worldMat));
|
||||
const float STRAIGHTING_LEAN_DURATION = 0.5f; // seconds
|
||||
|
||||
// define a vertical capsule
|
||||
const float STRAIGHTING_LEAN_CAPSULE_RADIUS = 0.2f; // meters
|
||||
const float STRAIGHTING_LEAN_CAPSULE_LENGTH = 0.05f; // length of the cylinder part of the capsule in meters.
|
||||
|
||||
auto newBodySensorMatrix = deriveBodyFromHMDSensor();
|
||||
glm::vec3 diff = extractTranslation(newBodySensorMatrix) - extractTranslation(_bodySensorMatrix);
|
||||
if (!_straightingLean && capsuleCheck(diff, STRAIGHTING_LEAN_CAPSULE_LENGTH, STRAIGHTING_LEAN_CAPSULE_RADIUS)) {
|
||||
|
||||
// begin homing toward derived body position.
|
||||
_straightingLean = true;
|
||||
_straightingLeanAlpha = 0.0f;
|
||||
|
||||
} else if (_straightingLean) {
|
||||
|
||||
auto newBodySensorMatrix = deriveBodyFromHMDSensor();
|
||||
auto worldBodyMatrix = _sensorToWorldMatrix * newBodySensorMatrix;
|
||||
glm::vec3 worldBodyPos = extractTranslation(worldBodyMatrix);
|
||||
glm::quat worldBodyRot = glm::normalize(glm::quat_cast(worldBodyMatrix));
|
||||
|
||||
_straightingLeanAlpha += (1.0f / STRAIGHTING_LEAN_DURATION) * deltaTime;
|
||||
|
||||
if (_straightingLeanAlpha >= 1.0f) {
|
||||
_straightingLean = false;
|
||||
nextAttitude(worldBodyPos, worldBodyRot);
|
||||
_bodySensorMatrix = newBodySensorMatrix;
|
||||
} else {
|
||||
// interp position toward the desired pos
|
||||
glm::vec3 pos = lerp(getPosition(), worldBodyPos, _straightingLeanAlpha);
|
||||
glm::quat rot = glm::normalize(safeMix(getOrientation(), worldBodyRot, _straightingLeanAlpha));
|
||||
nextAttitude(pos, rot);
|
||||
|
||||
// interp sensor matrix toward desired
|
||||
glm::vec3 nextBodyPos = extractTranslation(newBodySensorMatrix);
|
||||
glm::quat nextBodyRot = glm::normalize(glm::quat_cast(newBodySensorMatrix));
|
||||
glm::vec3 prevBodyPos = extractTranslation(_bodySensorMatrix);
|
||||
glm::quat prevBodyRot = glm::normalize(glm::quat_cast(_bodySensorMatrix));
|
||||
pos = lerp(prevBodyPos, nextBodyPos, _straightingLeanAlpha);
|
||||
rot = glm::normalize(safeMix(prevBodyRot, nextBodyRot, _straightingLeanAlpha));
|
||||
_bodySensorMatrix = createMatFromQuatAndPos(rot, pos);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
// best called at end of main loop, just before rendering.
|
||||
// update sensor to world matrix from current body position and hmd sensor.
|
||||
// This is so the correct camera can be used for rendering.
|
||||
|
@ -338,11 +422,9 @@ void MyAvatar::updateFromTrackers(float deltaTime) {
|
|||
|
||||
Head* head = getHead();
|
||||
if (inHmd || isPlaying()) {
|
||||
if (!getStandingHMDSensorMode()) {
|
||||
head->setDeltaPitch(estimatedRotation.x);
|
||||
head->setDeltaYaw(estimatedRotation.y);
|
||||
head->setDeltaRoll(estimatedRotation.z);
|
||||
}
|
||||
head->setDeltaPitch(estimatedRotation.x);
|
||||
head->setDeltaYaw(estimatedRotation.y);
|
||||
head->setDeltaRoll(estimatedRotation.z);
|
||||
} else {
|
||||
float magnifyFieldOfView = qApp->getFieldOfView() /
|
||||
_realWorldFieldOfView.get();
|
||||
|
@ -364,12 +446,10 @@ void MyAvatar::updateFromTrackers(float deltaTime) {
|
|||
relativePosition.x = -relativePosition.x;
|
||||
}
|
||||
|
||||
if (!(inHmd && getStandingHMDSensorMode())) {
|
||||
head->setLeanSideways(glm::clamp(glm::degrees(atanf(relativePosition.x * _leanScale / TORSO_LENGTH)),
|
||||
-MAX_LEAN, MAX_LEAN));
|
||||
head->setLeanForward(glm::clamp(glm::degrees(atanf(relativePosition.z * _leanScale / TORSO_LENGTH)),
|
||||
-MAX_LEAN, MAX_LEAN));
|
||||
}
|
||||
head->setLeanSideways(glm::clamp(glm::degrees(atanf(relativePosition.x * _leanScale / TORSO_LENGTH)),
|
||||
-MAX_LEAN, MAX_LEAN));
|
||||
head->setLeanForward(glm::clamp(glm::degrees(atanf(relativePosition.z * _leanScale / TORSO_LENGTH)),
|
||||
-MAX_LEAN, MAX_LEAN));
|
||||
}
|
||||
|
||||
|
||||
|
@ -1037,21 +1117,43 @@ void MyAvatar::setJointRotations(QVector<glm::quat> jointRotations) {
|
|||
int numStates = glm::min(_skeletonModel.getJointStateCount(), jointRotations.size());
|
||||
for (int i = 0; i < numStates; ++i) {
|
||||
// HACK: ATM only Recorder calls setJointRotations() so we hardcode its priority here
|
||||
_skeletonModel.setJointState(i, true, jointRotations[i], RECORDER_PRIORITY);
|
||||
_skeletonModel.setJointRotation(i, true, jointRotations[i], RECORDER_PRIORITY);
|
||||
}
|
||||
}
|
||||
|
||||
void MyAvatar::setJointData(int index, const glm::quat& rotation) {
|
||||
void MyAvatar::setJointTranslations(QVector<glm::vec3> jointTranslations) {
|
||||
int numStates = glm::min(_skeletonModel.getJointStateCount(), jointTranslations.size());
|
||||
for (int i = 0; i < numStates; ++i) {
|
||||
// HACK: ATM only Recorder calls setJointTranslations() so we hardcode its priority here
|
||||
_skeletonModel.setJointTranslation(i, true, jointTranslations[i], RECORDER_PRIORITY);
|
||||
}
|
||||
}
|
||||
|
||||
void MyAvatar::setJointData(int index, const glm::quat& rotation, const glm::vec3& translation) {
|
||||
if (QThread::currentThread() == thread()) {
|
||||
// HACK: ATM only JS scripts call setJointData() on MyAvatar so we hardcode the priority
|
||||
_rig->setJointState(index, true, rotation, SCRIPT_PRIORITY);
|
||||
_rig->setJointState(index, true, rotation, translation, SCRIPT_PRIORITY);
|
||||
}
|
||||
}
|
||||
|
||||
void MyAvatar::setJointRotation(int index, const glm::quat& rotation) {
|
||||
if (QThread::currentThread() == thread()) {
|
||||
// HACK: ATM only JS scripts call setJointData() on MyAvatar so we hardcode the priority
|
||||
_rig->setJointRotation(index, true, rotation, SCRIPT_PRIORITY);
|
||||
}
|
||||
}
|
||||
|
||||
void MyAvatar::setJointTranslation(int index, const glm::vec3& translation) {
|
||||
if (QThread::currentThread() == thread()) {
|
||||
// HACK: ATM only JS scripts call setJointData() on MyAvatar so we hardcode the priority
|
||||
_rig->setJointTranslation(index, true, translation, SCRIPT_PRIORITY);
|
||||
}
|
||||
}
|
||||
|
||||
void MyAvatar::clearJointData(int index) {
|
||||
if (QThread::currentThread() == thread()) {
|
||||
// HACK: ATM only JS scripts call clearJointData() on MyAvatar so we hardcode the priority
|
||||
_rig->setJointState(index, false, glm::quat(), 0.0f);
|
||||
_rig->setJointState(index, false, glm::quat(), glm::vec3(), 0.0f);
|
||||
_rig->clearJointAnimationPriority(index);
|
||||
}
|
||||
}
|
||||
|
@ -1333,7 +1435,7 @@ void MyAvatar::preRender(RenderArgs* renderArgs) {
|
|||
|
||||
// bones are aligned such that z is forward, not -z.
|
||||
glm::quat rotY180 = glm::angleAxis((float)M_PI, glm::vec3(0.0f, 1.0f, 0.0f));
|
||||
AnimPose xform(glm::vec3(1), rotY180 * getOrientation(), getPosition());
|
||||
AnimPose xform(glm::vec3(1), getOrientation() * rotY180, getPosition());
|
||||
|
||||
if (_enableDebugDrawBindPose && _debugDrawSkeleton) {
|
||||
glm::vec4 gray(0.2f, 0.2f, 0.2f, 0.2f);
|
||||
|
@ -1350,7 +1452,10 @@ void MyAvatar::preRender(RenderArgs* renderArgs) {
|
|||
AnimPose pose = _debugDrawSkeleton->getRelativeBindPose(i);
|
||||
glm::quat jointRot;
|
||||
_rig->getJointRotationInConstrainedFrame(i, jointRot);
|
||||
glm::vec3 jointTrans;
|
||||
_rig->getJointTranslation(i, jointTrans);
|
||||
pose.rot = pose.rot * jointRot;
|
||||
pose.trans = jointTrans;
|
||||
poses.push_back(pose);
|
||||
}
|
||||
|
||||
|
@ -1358,6 +1463,9 @@ void MyAvatar::preRender(RenderArgs* renderArgs) {
|
|||
}
|
||||
}
|
||||
|
||||
DebugDraw::getInstance().updateMyAvatarPos(getPosition());
|
||||
DebugDraw::getInstance().updateMyAvatarRot(getOrientation());
|
||||
|
||||
if (shouldDrawHead != _prevShouldDrawHead) {
|
||||
_skeletonModel.setCauterizeBones(!shouldDrawHead);
|
||||
}
|
||||
|
@ -1706,6 +1814,12 @@ void MyAvatar::goToLocation(const glm::vec3& newPosition,
|
|||
}
|
||||
|
||||
void MyAvatar::updateMotionBehaviorFromMenu() {
|
||||
|
||||
if (QThread::currentThread() != thread()) {
|
||||
QMetaObject::invokeMethod(this, "updateMotionBehaviorFromMenu");
|
||||
return;
|
||||
}
|
||||
|
||||
Menu* menu = Menu::getInstance();
|
||||
if (menu->isOptionChecked(MenuOption::KeyboardMotorControl)) {
|
||||
_motionBehaviors |= AVATAR_MOTION_KEYBOARD_MOTOR_ENABLED;
|
||||
|
@ -1720,11 +1834,6 @@ void MyAvatar::updateMotionBehaviorFromMenu() {
|
|||
_characterController.setEnabled(menu->isOptionChecked(MenuOption::EnableCharacterController));
|
||||
}
|
||||
|
||||
void MyAvatar::updateStandingHMDModeFromMenu() {
|
||||
Menu* menu = Menu::getInstance();
|
||||
_standingHMDSensorMode = menu->isOptionChecked(MenuOption::StandingHMDSensorMode);
|
||||
}
|
||||
|
||||
//Renders sixense laser pointers for UI selection with controllers
|
||||
void MyAvatar::renderLaserPointers(gpu::Batch& batch) {
|
||||
const float PALM_TIP_ROD_RADIUS = 0.002f;
|
||||
|
@ -1794,13 +1903,39 @@ glm::mat4 MyAvatar::deriveBodyFromHMDSensor() const {
|
|||
const glm::quat hmdOrientation = getHMDSensorOrientation();
|
||||
const glm::quat hmdOrientationYawOnly = cancelOutRollAndPitch(hmdOrientation);
|
||||
|
||||
// In sensor space, figure out where the avatar body should be,
|
||||
// by applying offsets from the avatar's neck & head joints.
|
||||
vec3 localEyes = _skeletonModel.getDefaultEyeModelPosition();
|
||||
vec3 localNeck(0.0f, 0.48f, 0.0f); // start with some kind of guess if the skeletonModel is not loaded yet.
|
||||
_skeletonModel.getLocalNeckPosition(localNeck);
|
||||
const glm::vec3 DEFAULT_RIGHT_EYE_POS(-0.3f, 1.6f, 0.0f);
|
||||
const glm::vec3 DEFAULT_LEFT_EYE_POS(0.3f, 1.6f, 0.0f);
|
||||
const glm::vec3 DEFAULT_NECK_POS(0.0f, 1.5f, 0.0f);
|
||||
const glm::vec3 DEFAULT_HIPS_POS(0.0f, 1.0f, 0.0f);
|
||||
|
||||
vec3 localEyes, localNeck;
|
||||
if (!_debugDrawSkeleton) {
|
||||
const glm::quat rotY180 = glm::angleAxis((float)PI, glm::vec3(0.0f, 1.0f, 0.0f));
|
||||
localEyes = rotY180 * (((DEFAULT_RIGHT_EYE_POS + DEFAULT_LEFT_EYE_POS) / 2.0f) - DEFAULT_HIPS_POS);
|
||||
localNeck = rotY180 * (DEFAULT_NECK_POS - DEFAULT_HIPS_POS);
|
||||
} else {
|
||||
// TODO: At the moment MyAvatar does not have access to the rig, which has the skeleton, which has the bind poses.
|
||||
// for now use the _debugDrawSkeleton, which is initialized with the same FBX model as the rig.
|
||||
|
||||
// TODO: cache these indices.
|
||||
int rightEyeIndex = _debugDrawSkeleton->nameToJointIndex("RightEye");
|
||||
int leftEyeIndex = _debugDrawSkeleton->nameToJointIndex("LeftEye");
|
||||
int neckIndex = _debugDrawSkeleton->nameToJointIndex("Neck");
|
||||
int hipsIndex = _debugDrawSkeleton->nameToJointIndex("Hips");
|
||||
|
||||
glm::vec3 absRightEyePos = rightEyeIndex != -1 ? _debugDrawSkeleton->getAbsoluteBindPose(rightEyeIndex).trans : DEFAULT_RIGHT_EYE_POS;
|
||||
glm::vec3 absLeftEyePos = leftEyeIndex != -1 ? _debugDrawSkeleton->getAbsoluteBindPose(leftEyeIndex).trans : DEFAULT_LEFT_EYE_POS;
|
||||
glm::vec3 absNeckPos = neckIndex != -1 ? _debugDrawSkeleton->getAbsoluteBindPose(neckIndex).trans : DEFAULT_NECK_POS;
|
||||
glm::vec3 absHipsPos = neckIndex != -1 ? _debugDrawSkeleton->getAbsoluteBindPose(hipsIndex).trans : DEFAULT_HIPS_POS;
|
||||
|
||||
const glm::quat rotY180 = glm::angleAxis((float)PI, glm::vec3(0.0f, 1.0f, 0.0f));
|
||||
localEyes = rotY180 * (((absRightEyePos + absLeftEyePos) / 2.0f) - absHipsPos);
|
||||
localNeck = rotY180 * (absNeckPos - absHipsPos);
|
||||
}
|
||||
|
||||
// apply simplistic head/neck model
|
||||
// figure out where the avatar body should be by applying offsets from the avatar's neck & head joints.
|
||||
|
||||
// eyeToNeck offset is relative full HMD orientation.
|
||||
// while neckToRoot offset is only relative to HMDs yaw.
|
||||
glm::vec3 eyeToNeck = hmdOrientation * (localNeck - localEyes);
|
||||
|
@ -1810,3 +1945,42 @@ glm::mat4 MyAvatar::deriveBodyFromHMDSensor() const {
|
|||
// avatar facing is determined solely by hmd orientation.
|
||||
return createMatFromQuatAndPos(hmdOrientationYawOnly, bodyPos);
|
||||
}
|
||||
|
||||
glm::vec3 MyAvatar::getPositionForAudio() {
|
||||
switch (_audioListenerMode) {
|
||||
case AudioListenerMode::FROM_HEAD:
|
||||
return getHead()->getPosition();
|
||||
case AudioListenerMode::FROM_CAMERA:
|
||||
return Application::getInstance()->getCamera()->getPosition();
|
||||
case AudioListenerMode::CUSTOM:
|
||||
return _customListenPosition;
|
||||
}
|
||||
return vec3();
|
||||
}
|
||||
|
||||
glm::quat MyAvatar::getOrientationForAudio() {
|
||||
switch (_audioListenerMode) {
|
||||
case AudioListenerMode::FROM_HEAD:
|
||||
return getHead()->getFinalOrientationInWorldFrame();
|
||||
case AudioListenerMode::FROM_CAMERA:
|
||||
return Application::getInstance()->getCamera()->getOrientation();
|
||||
case AudioListenerMode::CUSTOM:
|
||||
return _customListenOrientation;
|
||||
}
|
||||
return quat();
|
||||
}
|
||||
|
||||
void MyAvatar::setAudioListenerMode(AudioListenerMode audioListenerMode) {
|
||||
if (_audioListenerMode != audioListenerMode) {
|
||||
_audioListenerMode = audioListenerMode;
|
||||
emit audioListenerModeChanged();
|
||||
}
|
||||
}
|
||||
|
||||
QScriptValue audioListenModeToScriptValue(QScriptEngine* engine, const AudioListenerMode& audioListenerMode) {
|
||||
return audioListenerMode;
|
||||
}
|
||||
|
||||
void audioListenModeFromScriptValue(const QScriptValue& object, AudioListenerMode& audioListenerMode) {
|
||||
audioListenerMode = (AudioListenerMode)object.toUInt16();
|
||||
}
|
||||
|
|
|
@ -26,6 +26,14 @@ enum eyeContactTarget {
|
|||
MOUTH
|
||||
};
|
||||
|
||||
enum AudioListenerMode {
|
||||
FROM_HEAD = 0,
|
||||
FROM_CAMERA,
|
||||
CUSTOM
|
||||
};
|
||||
Q_DECLARE_METATYPE(AudioListenerMode);
|
||||
|
||||
|
||||
class MyAvatar : public Avatar {
|
||||
Q_OBJECT
|
||||
Q_PROPERTY(bool shouldRenderLocally READ getShouldRenderLocally WRITE setShouldRenderLocally)
|
||||
|
@ -33,12 +41,21 @@ class MyAvatar : public Avatar {
|
|||
Q_PROPERTY(float motorTimescale READ getScriptedMotorTimescale WRITE setScriptedMotorTimescale)
|
||||
Q_PROPERTY(QString motorReferenceFrame READ getScriptedMotorFrame WRITE setScriptedMotorFrame)
|
||||
Q_PROPERTY(QString collisionSoundURL READ getCollisionSoundURL WRITE setCollisionSoundURL)
|
||||
Q_PROPERTY(AudioListenerMode audioListenerMode READ getAudioListenerMode WRITE setAudioListenerMode)
|
||||
Q_PROPERTY(glm::vec3 customListenPosition READ getCustomListenPosition WRITE setCustomListenPosition)
|
||||
Q_PROPERTY(glm::quat customListenOrientation READ getCustomListenOrientation WRITE setCustomListenOrientation)
|
||||
Q_PROPERTY(AudioListenerMode FROM_HEAD READ getAudioListenerModeHead)
|
||||
Q_PROPERTY(AudioListenerMode FROM_CAMERA READ getAudioListenerModeCamera)
|
||||
Q_PROPERTY(AudioListenerMode CUSTOM READ getAudioListenerModeCustom)
|
||||
//TODO: make gravity feature work Q_PROPERTY(glm::vec3 gravity READ getGravity WRITE setGravity)
|
||||
|
||||
public:
|
||||
MyAvatar(RigPointer rig);
|
||||
~MyAvatar();
|
||||
|
||||
AudioListenerMode getAudioListenerModeHead() const { return FROM_HEAD; }
|
||||
AudioListenerMode getAudioListenerModeCamera() const { return FROM_CAMERA; }
|
||||
AudioListenerMode getAudioListenerModeCustom() const { return CUSTOM; }
|
||||
|
||||
void reset();
|
||||
void update(float deltaTime);
|
||||
|
@ -49,8 +66,9 @@ public:
|
|||
const glm::quat& getHMDSensorOrientation() const { return _hmdSensorOrientation; }
|
||||
glm::mat4 getSensorToWorldMatrix() const;
|
||||
|
||||
// best called at start of main loop just after we have a fresh hmd pose.
|
||||
// update internal body position from new hmd pose.
|
||||
// Pass a recent sample of the HMD to the avatar.
|
||||
// This can also update the avatar's position to follow the HMD
|
||||
// as it moves through the world.
|
||||
void updateFromHMDSensorMatrix(const glm::mat4& hmdSensorMatrix);
|
||||
|
||||
// best called at end of main loop, just before rendering.
|
||||
|
@ -122,7 +140,10 @@ public:
|
|||
void clearLookAtTargetAvatar();
|
||||
|
||||
virtual void setJointRotations(QVector<glm::quat> jointRotations);
|
||||
virtual void setJointData(int index, const glm::quat& rotation);
|
||||
virtual void setJointTranslations(QVector<glm::vec3> jointTranslations);
|
||||
virtual void setJointData(int index, const glm::quat& rotation, const glm::vec3& translation);
|
||||
virtual void setJointRotation(int index, const glm::quat& rotation);
|
||||
virtual void setJointTranslation(int index, const glm::vec3& translation);
|
||||
virtual void clearJointData(int index);
|
||||
virtual void clearJointsData();
|
||||
|
||||
|
@ -151,10 +172,16 @@ public:
|
|||
static const float ZOOM_MAX;
|
||||
static const float ZOOM_DEFAULT;
|
||||
|
||||
bool getStandingHMDSensorMode() const { return _standingHMDSensorMode; }
|
||||
void doUpdateBillboard();
|
||||
void destroyAnimGraph();
|
||||
|
||||
AudioListenerMode getAudioListenerMode() { return _audioListenerMode; }
|
||||
void setAudioListenerMode(AudioListenerMode audioListenerMode);
|
||||
glm::vec3 getCustomListenPosition() { return _customListenPosition; }
|
||||
void setCustomListenPosition(glm::vec3 customListenPosition) { _customListenPosition = customListenPosition; }
|
||||
glm::quat getCustomListenOrientation() { return _customListenOrientation; }
|
||||
void setCustomListenOrientation(glm::quat customListenOrientation) { _customListenOrientation = customListenOrientation; }
|
||||
|
||||
public slots:
|
||||
void increaseSize();
|
||||
void decreaseSize();
|
||||
|
@ -169,8 +196,7 @@ public slots:
|
|||
glm::vec3 getThrust() { return _thrust; };
|
||||
void setThrust(glm::vec3 newThrust) { _thrust = newThrust; }
|
||||
|
||||
void updateMotionBehaviorFromMenu();
|
||||
void updateStandingHMDModeFromMenu();
|
||||
Q_INVOKABLE void updateMotionBehaviorFromMenu();
|
||||
|
||||
glm::vec3 getLeftPalmPosition();
|
||||
glm::vec3 getLeftPalmVelocity();
|
||||
|
@ -204,7 +230,11 @@ public slots:
|
|||
void setEnableMeshVisible(bool isEnabled);
|
||||
void setAnimGraphUrl(const QString& url) { _animGraphUrl = url; }
|
||||
|
||||
glm::vec3 getPositionForAudio();
|
||||
glm::quat getOrientationForAudio();
|
||||
|
||||
signals:
|
||||
void audioListenerModeChanged();
|
||||
void transformChanged();
|
||||
void newCollisionSoundURL(const QUrl& url);
|
||||
void collisionWithEntity(const Collision& collision);
|
||||
|
@ -317,8 +347,6 @@ private:
|
|||
// used to transform any sensor into world space, including the _hmdSensorMat, or hand controllers.
|
||||
glm::mat4 _sensorToWorldMatrix;
|
||||
|
||||
bool _standingHMDSensorMode;
|
||||
|
||||
bool _goToPending;
|
||||
glm::vec3 _goToPosition;
|
||||
glm::quat _goToOrientation;
|
||||
|
@ -330,6 +358,18 @@ private:
|
|||
bool _enableDebugDrawBindPose = false;
|
||||
bool _enableDebugDrawAnimPose = false;
|
||||
AnimSkeleton::ConstPointer _debugDrawSkeleton = nullptr;
|
||||
|
||||
AudioListenerMode _audioListenerMode;
|
||||
glm::vec3 _customListenPosition;
|
||||
glm::quat _customListenOrientation;
|
||||
|
||||
bool _straightingLean = false;
|
||||
float _straightingLeanAlpha = 0.0f;
|
||||
|
||||
quint64 _lastUpdateFromHMDTime = usecTimestampNow();
|
||||
};
|
||||
|
||||
QScriptValue audioListenModeToScriptValue(QScriptEngine* engine, const AudioListenerMode& audioListenerMode);
|
||||
void audioListenModeFromScriptValue(const QScriptValue& object, AudioListenerMode& audioListenerMode);
|
||||
|
||||
#endif // hifi_MyAvatar_h
|
||||
|
|
|
@ -21,6 +21,7 @@
|
|||
#include "SkeletonModel.h"
|
||||
#include "Util.h"
|
||||
#include "InterfaceLogging.h"
|
||||
#include "AnimDebugDraw.h"
|
||||
|
||||
SkeletonModel::SkeletonModel(Avatar* owningAvatar, QObject* parent, RigPointer rig) :
|
||||
Model(rig, parent),
|
||||
|
@ -122,23 +123,39 @@ void SkeletonModel::updateRig(float deltaTime, glm::mat4 parentTransform) {
|
|||
Rig::HeadParameters headParams;
|
||||
headParams.modelRotation = getRotation();
|
||||
headParams.modelTranslation = getTranslation();
|
||||
headParams.enableLean = qApp->getAvatarUpdater()->isHMDMode() && !myAvatar->getStandingHMDSensorMode();
|
||||
headParams.enableLean = qApp->getAvatarUpdater()->isHMDMode();
|
||||
headParams.leanSideways = head->getFinalLeanSideways();
|
||||
headParams.leanForward = head->getFinalLeanForward();
|
||||
headParams.torsoTwist = head->getTorsoTwist();
|
||||
headParams.localHeadOrientation = head->getFinalOrientationInLocalFrame();
|
||||
headParams.localHeadPitch = head->getFinalPitch();
|
||||
headParams.localHeadYaw = head->getFinalYaw();
|
||||
headParams.localHeadRoll = head->getFinalRoll();
|
||||
headParams.isInHMD = qApp->getAvatarUpdater()->isHMDMode();
|
||||
|
||||
// get HMD position from sensor space into world space, and back into model space
|
||||
glm::mat4 worldToModel = glm::inverse(createMatFromQuatAndPos(myAvatar->getOrientation(), myAvatar->getPosition()));
|
||||
glm::vec3 yAxis(0.0f, 1.0f, 0.0f);
|
||||
glm::vec3 hmdPosition = glm::angleAxis((float)M_PI, yAxis) * transformPoint(worldToModel * myAvatar->getSensorToWorldMatrix(), myAvatar->getHMDSensorPosition());
|
||||
headParams.localHeadPosition = hmdPosition;
|
||||
if (qApp->getAvatarUpdater()->isHMDMode()) {
|
||||
headParams.isInHMD = true;
|
||||
|
||||
// get HMD position from sensor space into world space, and back into model space
|
||||
AnimPose avatarToWorld(glm::vec3(1), myAvatar->getOrientation(), myAvatar->getPosition());
|
||||
glm::mat4 worldToAvatar = glm::inverse((glm::mat4)avatarToWorld);
|
||||
glm::mat4 worldHMDMat = myAvatar->getSensorToWorldMatrix() * myAvatar->getHMDSensorMatrix();
|
||||
glm::mat4 hmdMat = worldToAvatar * worldHMDMat;
|
||||
|
||||
// in local avatar space (i.e. relative to avatar pos/orientation.)
|
||||
glm::vec3 hmdPosition = extractTranslation(hmdMat);
|
||||
glm::quat hmdOrientation = extractRotation(hmdMat);
|
||||
|
||||
headParams.localHeadPosition = hmdPosition;
|
||||
headParams.localHeadOrientation = hmdOrientation;
|
||||
|
||||
headParams.worldHeadOrientation = extractRotation(worldHMDMat);
|
||||
} else {
|
||||
headParams.isInHMD = false;
|
||||
|
||||
// We don't have a valid localHeadPosition.
|
||||
headParams.localHeadOrientation = head->getFinalOrientationInLocalFrame();
|
||||
headParams.worldHeadOrientation = head->getFinalOrientationInWorldFrame();
|
||||
}
|
||||
|
||||
headParams.worldHeadOrientation = head->getFinalOrientationInWorldFrame();
|
||||
headParams.eyeLookAt = head->getLookAtPosition();
|
||||
headParams.eyeSaccade = head->getSaccade();
|
||||
headParams.leanJointIndex = geometry.leanJointIndex;
|
||||
|
@ -229,33 +246,42 @@ void SkeletonModel::simulate(float deltaTime, bool fullUpdate) {
|
|||
Hand* hand = _owningAvatar->getHand();
|
||||
hand->getLeftRightPalmIndices(leftPalmIndex, rightPalmIndex);
|
||||
|
||||
const float HAND_RESTORATION_RATE = 0.25f;
|
||||
if (leftPalmIndex == -1 && rightPalmIndex == -1) {
|
||||
// palms are not yet set, use mouse
|
||||
if (_owningAvatar->getHandState() == HAND_STATE_NULL) {
|
||||
restoreRightHandPosition(HAND_RESTORATION_RATE, PALM_PRIORITY);
|
||||
} else {
|
||||
// transform into model-frame
|
||||
glm::vec3 handPosition = glm::inverse(_rotation) * (_owningAvatar->getHandPosition() - _translation);
|
||||
applyHandPosition(geometry.rightHandJointIndex, handPosition);
|
||||
}
|
||||
restoreLeftHandPosition(HAND_RESTORATION_RATE, PALM_PRIORITY);
|
||||
// let rig compute the model offset
|
||||
glm::vec3 modelOffset;
|
||||
if (_rig->getModelOffset(modelOffset)) {
|
||||
setOffset(modelOffset);
|
||||
}
|
||||
|
||||
} else if (leftPalmIndex == rightPalmIndex) {
|
||||
// right hand only
|
||||
applyPalmData(geometry.rightHandJointIndex, hand->getPalms()[leftPalmIndex]);
|
||||
restoreLeftHandPosition(HAND_RESTORATION_RATE, PALM_PRIORITY);
|
||||
|
||||
} else {
|
||||
if (leftPalmIndex != -1) {
|
||||
applyPalmData(geometry.leftHandJointIndex, hand->getPalms()[leftPalmIndex]);
|
||||
} else {
|
||||
// Don't Relax toward hand positions when in animGraph mode.
|
||||
if (!_rig->getEnableAnimGraph()) {
|
||||
const float HAND_RESTORATION_RATE = 0.25f;
|
||||
if (leftPalmIndex == -1 && rightPalmIndex == -1) {
|
||||
// palms are not yet set, use mouse
|
||||
if (_owningAvatar->getHandState() == HAND_STATE_NULL) {
|
||||
restoreRightHandPosition(HAND_RESTORATION_RATE, PALM_PRIORITY);
|
||||
} else {
|
||||
// transform into model-frame
|
||||
glm::vec3 handPosition = glm::inverse(_rotation) * (_owningAvatar->getHandPosition() - _translation);
|
||||
applyHandPosition(geometry.rightHandJointIndex, handPosition);
|
||||
}
|
||||
restoreLeftHandPosition(HAND_RESTORATION_RATE, PALM_PRIORITY);
|
||||
}
|
||||
if (rightPalmIndex != -1) {
|
||||
applyPalmData(geometry.rightHandJointIndex, hand->getPalms()[rightPalmIndex]);
|
||||
|
||||
} else if (leftPalmIndex == rightPalmIndex) {
|
||||
// right hand only
|
||||
applyPalmData(geometry.rightHandJointIndex, hand->getPalms()[leftPalmIndex]);
|
||||
restoreLeftHandPosition(HAND_RESTORATION_RATE, PALM_PRIORITY);
|
||||
|
||||
} else {
|
||||
restoreRightHandPosition(HAND_RESTORATION_RATE, PALM_PRIORITY);
|
||||
if (leftPalmIndex != -1) {
|
||||
applyPalmData(geometry.leftHandJointIndex, hand->getPalms()[leftPalmIndex]);
|
||||
} else {
|
||||
restoreLeftHandPosition(HAND_RESTORATION_RATE, PALM_PRIORITY);
|
||||
}
|
||||
if (rightPalmIndex != -1) {
|
||||
applyPalmData(geometry.rightHandJointIndex, hand->getPalms()[rightPalmIndex]);
|
||||
} else {
|
||||
restoreRightHandPosition(HAND_RESTORATION_RATE, PALM_PRIORITY);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -300,7 +326,7 @@ void SkeletonModel::applyHandPosition(int jointIndex, const glm::vec3& position)
|
|||
float sign = (jointIndex == geometry.rightHandJointIndex) ? 1.0f : -1.0f;
|
||||
_rig->applyJointRotationDelta(jointIndex,
|
||||
rotationBetween(handRotation * glm::vec3(-sign, 0.0f, 0.0f), forearmVector),
|
||||
true, PALM_PRIORITY);
|
||||
PALM_PRIORITY);
|
||||
}
|
||||
|
||||
void SkeletonModel::applyPalmData(int jointIndex, PalmData& palm) {
|
||||
|
@ -631,6 +657,7 @@ void SkeletonModel::computeBoundingShape() {
|
|||
// RECOVER FROM BOUNINDG SHAPE HACK: now that we're all done, restore the default pose
|
||||
for (int i = 0; i < numStates; i++) {
|
||||
_rig->restoreJointRotation(i, 1.0f, 1.0f);
|
||||
_rig->restoreJointTranslation(i, 1.0f, 1.0f);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
@ -160,6 +160,8 @@ ConnexionClient& ConnexionClient::getInstance() {
|
|||
|
||||
#ifdef Q_OS_WIN
|
||||
|
||||
#include <VersionHelpers.h>
|
||||
|
||||
void ConnexionClient::toggleConnexion(bool shouldEnable) {
|
||||
ConnexionData& connexiondata = ConnexionData::getInstance();
|
||||
if (shouldEnable && connexiondata.getDeviceID() == 0) {
|
||||
|
@ -425,18 +427,13 @@ bool ConnexionClient::InitializeRawInput(HWND hwndTarget) {
|
|||
return false;
|
||||
}
|
||||
|
||||
// FIXME - http://www.codeproject.com/Articles/678606/Part-Overcoming-Windows-s-deprecation-of-GetVe
|
||||
// Get OS version.
|
||||
OSVERSIONINFO osvi = { sizeof(OSVERSIONINFO), 0 };
|
||||
::GetVersionEx(&osvi);
|
||||
|
||||
unsigned int cbSize = sizeof(devicesToRegister[0]);
|
||||
for (size_t i = 0; i < numDevices; i++) {
|
||||
// Set the target window to use
|
||||
//devicesToRegister[i].hwndTarget = hwndTarget;
|
||||
|
||||
// If Vista or newer, enable receiving the WM_INPUT_DEVICE_CHANGE message.
|
||||
if (osvi.dwMajorVersion >= 6) {
|
||||
if (IsWindowsVistaOrGreater()) {
|
||||
devicesToRegister[i].dwFlags |= RIDEV_DEVNOTIFY;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -19,17 +19,40 @@ float ClipboardScriptingInterface::getClipboardContentsLargestDimension() {
|
|||
}
|
||||
|
||||
bool ClipboardScriptingInterface::exportEntities(const QString& filename, const QVector<EntityItemID>& entityIDs) {
|
||||
return Application::getInstance()->exportEntities(filename, entityIDs);
|
||||
bool retVal;
|
||||
QMetaObject::invokeMethod(Application::getInstance(), "exportEntities", Qt::BlockingQueuedConnection,
|
||||
Q_RETURN_ARG(bool, retVal),
|
||||
Q_ARG(const QString&, filename),
|
||||
Q_ARG(const QVector<EntityItemID>&, entityIDs));
|
||||
return retVal;
|
||||
}
|
||||
|
||||
bool ClipboardScriptingInterface::exportEntities(const QString& filename, float x, float y, float z, float s) {
|
||||
return Application::getInstance()->exportEntities(filename, x, y, z, s);
|
||||
bool retVal;
|
||||
QMetaObject::invokeMethod(Application::getInstance(), "exportEntities", Qt::BlockingQueuedConnection,
|
||||
Q_RETURN_ARG(bool, retVal),
|
||||
Q_ARG(const QString&, filename),
|
||||
Q_ARG(float, x),
|
||||
Q_ARG(float, y),
|
||||
Q_ARG(float, z),
|
||||
Q_ARG(float, s));
|
||||
return retVal;
|
||||
}
|
||||
|
||||
bool ClipboardScriptingInterface::importEntities(const QString& filename) {
|
||||
return Application::getInstance()->importEntities(filename);
|
||||
bool retVal;
|
||||
QMetaObject::invokeMethod(Application::getInstance(), "importEntities", Qt::BlockingQueuedConnection,
|
||||
Q_RETURN_ARG(bool, retVal),
|
||||
Q_ARG(const QString&, filename));
|
||||
return retVal;
|
||||
}
|
||||
|
||||
QVector<EntityItemID> ClipboardScriptingInterface::pasteEntities(glm::vec3 position) {
|
||||
return Application::getInstance()->pasteEntities(position.x, position.y, position.z);
|
||||
QVector<EntityItemID> retVal;
|
||||
QMetaObject::invokeMethod(Application::getInstance(), "pasteEntities", Qt::BlockingQueuedConnection,
|
||||
Q_RETURN_ARG(QVector<EntityItemID>, retVal),
|
||||
Q_ARG(float, position.x),
|
||||
Q_ARG(float, position.y),
|
||||
Q_ARG(float, position.z));
|
||||
return retVal;
|
||||
}
|
||||
|
|
|
@ -10,7 +10,7 @@
|
|||
//
|
||||
|
||||
#include "HMDScriptingInterface.h"
|
||||
|
||||
#include "display-plugins/DisplayPlugin.h"
|
||||
#include <avatar/AvatarManager.h>
|
||||
|
||||
HMDScriptingInterface& HMDScriptingInterface::getInstance() {
|
||||
|
@ -53,3 +53,7 @@ QScriptValue HMDScriptingInterface::getHUDLookAtPosition3D(QScriptContext* conte
|
|||
}
|
||||
return QScriptValue::NullValue;
|
||||
}
|
||||
|
||||
float HMDScriptingInterface::getIPD() const {
|
||||
return Application::getInstance()->getActiveDisplayPlugin()->getIPD();
|
||||
}
|
||||
|
|
|
@ -20,6 +20,7 @@ class HMDScriptingInterface : public QObject {
|
|||
Q_OBJECT
|
||||
Q_PROPERTY(bool magnifier READ getMagnifier)
|
||||
Q_PROPERTY(bool active READ isHMDMode)
|
||||
Q_PROPERTY(float ipd READ getIPD)
|
||||
public:
|
||||
static HMDScriptingInterface& getInstance();
|
||||
|
||||
|
@ -33,6 +34,7 @@ private:
|
|||
HMDScriptingInterface() {};
|
||||
bool getMagnifier() const { return Application::getInstance()->getApplicationCompositor().hasMagnifier(); };
|
||||
bool isHMDMode() const { return Application::getInstance()->isHMDMode(); }
|
||||
float getIPD() const;
|
||||
|
||||
bool getHUDLookAtPosition3D(glm::vec3& result) const;
|
||||
|
||||
|
|
|
@ -207,36 +207,36 @@ void ApplicationCompositor::displayOverlayTexture(RenderArgs* renderArgs) {
|
|||
updateTooltips();
|
||||
|
||||
//Handle fading and deactivation/activation of UI
|
||||
gpu::Batch batch;
|
||||
gpu::doInBatch(renderArgs->_context, [=](gpu::Batch& batch) {
|
||||
|
||||
auto geometryCache = DependencyManager::get<GeometryCache>();
|
||||
auto geometryCache = DependencyManager::get<GeometryCache>();
|
||||
|
||||
geometryCache->useSimpleDrawPipeline(batch);
|
||||
batch.setViewportTransform(renderArgs->_viewport);
|
||||
batch.setModelTransform(Transform());
|
||||
batch.setViewTransform(Transform());
|
||||
batch.setProjectionTransform(mat4());
|
||||
batch.setResourceTexture(0, overlayFramebuffer->getRenderBuffer(0));
|
||||
geometryCache->renderUnitQuad(batch, vec4(vec3(1), _alpha));
|
||||
geometryCache->useSimpleDrawPipeline(batch);
|
||||
batch.setViewportTransform(renderArgs->_viewport);
|
||||
batch.setModelTransform(Transform());
|
||||
batch.setViewTransform(Transform());
|
||||
batch.setProjectionTransform(mat4());
|
||||
batch.setResourceTexture(0, overlayFramebuffer->getRenderBuffer(0));
|
||||
geometryCache->renderUnitQuad(batch, vec4(vec3(1), _alpha));
|
||||
|
||||
// Doesn't actually render
|
||||
renderPointers(batch);
|
||||
// Doesn't actually render
|
||||
renderPointers(batch);
|
||||
|
||||
//draw the mouse pointer
|
||||
// Get the mouse coordinates and convert to NDC [-1, 1]
|
||||
vec2 canvasSize = qApp->getCanvasSize();
|
||||
vec2 mousePosition = toNormalizedDeviceScale(vec2(qApp->getMouse()), canvasSize);
|
||||
// Invert the Y axis
|
||||
mousePosition.y *= -1.0f;
|
||||
//draw the mouse pointer
|
||||
// Get the mouse coordinates and convert to NDC [-1, 1]
|
||||
vec2 canvasSize = qApp->getCanvasSize();
|
||||
vec2 mousePosition = toNormalizedDeviceScale(vec2(qApp->getMouse()), canvasSize);
|
||||
// Invert the Y axis
|
||||
mousePosition.y *= -1.0f;
|
||||
|
||||
Transform model;
|
||||
model.setTranslation(vec3(mousePosition, 0));
|
||||
vec2 mouseSize = CURSOR_PIXEL_SIZE / canvasSize;
|
||||
model.setScale(vec3(mouseSize, 1.0f));
|
||||
batch.setModelTransform(model);
|
||||
bindCursorTexture(batch);
|
||||
geometryCache->renderUnitQuad(batch, vec4(1));
|
||||
renderArgs->_context->render(batch);
|
||||
Transform model;
|
||||
model.setTranslation(vec3(mousePosition, 0));
|
||||
vec2 mouseSize = CURSOR_PIXEL_SIZE / canvasSize;
|
||||
model.setScale(vec3(mouseSize, 1.0f));
|
||||
batch.setModelTransform(model);
|
||||
bindCursorTexture(batch);
|
||||
geometryCache->renderUnitQuad(batch, vec4(1));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
@ -278,75 +278,70 @@ void ApplicationCompositor::displayOverlayTextureHmd(RenderArgs* renderArgs, int
|
|||
|
||||
auto geometryCache = DependencyManager::get<GeometryCache>();
|
||||
|
||||
gpu::Batch batch;
|
||||
geometryCache->useSimpleDrawPipeline(batch);
|
||||
//batch._glDisable(GL_DEPTH_TEST);
|
||||
//batch._glDisable(GL_CULL_FACE);
|
||||
//batch._glBindTexture(GL_TEXTURE_2D, texture);
|
||||
//batch._glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
|
||||
//batch._glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
|
||||
gpu::doInBatch(renderArgs->_context, [=](gpu::Batch& batch) {
|
||||
geometryCache->useSimpleDrawPipeline(batch);
|
||||
|
||||
batch.setResourceTexture(0, overlayFramebuffer->getRenderBuffer(0));
|
||||
batch.setResourceTexture(0, overlayFramebuffer->getRenderBuffer(0));
|
||||
|
||||
mat4 camMat;
|
||||
_cameraBaseTransform.getMatrix(camMat);
|
||||
camMat = camMat * qApp->getEyePose(eye);
|
||||
batch.setViewportTransform(renderArgs->_viewport);
|
||||
batch.setViewTransform(camMat);
|
||||
mat4 camMat;
|
||||
_cameraBaseTransform.getMatrix(camMat);
|
||||
camMat = camMat * qApp->getEyePose(eye);
|
||||
batch.setViewportTransform(renderArgs->_viewport);
|
||||
batch.setViewTransform(camMat);
|
||||
|
||||
batch.setProjectionTransform(qApp->getEyeProjection(eye));
|
||||
batch.setProjectionTransform(qApp->getEyeProjection(eye));
|
||||
|
||||
#ifdef DEBUG_OVERLAY
|
||||
{
|
||||
batch.setModelTransform(glm::translate(mat4(), vec3(0, 0, -2)));
|
||||
geometryCache->renderUnitQuad(batch, glm::vec4(1));
|
||||
}
|
||||
#else
|
||||
{
|
||||
//batch.setModelTransform(overlayXfm);
|
||||
#ifdef DEBUG_OVERLAY
|
||||
{
|
||||
batch.setModelTransform(glm::translate(mat4(), vec3(0, 0, -2)));
|
||||
geometryCache->renderUnitQuad(batch, glm::vec4(1));
|
||||
}
|
||||
#else
|
||||
{
|
||||
batch.setModelTransform(_modelTransform);
|
||||
drawSphereSection(batch);
|
||||
}
|
||||
#endif
|
||||
|
||||
batch.setModelTransform(_modelTransform);
|
||||
drawSphereSection(batch);
|
||||
}
|
||||
#endif
|
||||
// Doesn't actually render
|
||||
renderPointers(batch);
|
||||
vec3 reticleScale = vec3(Cursor::Manager::instance().getScale() * reticleSize);
|
||||
|
||||
// Doesn't actually render
|
||||
renderPointers(batch);
|
||||
vec3 reticleScale = vec3(Cursor::Manager::instance().getScale() * reticleSize);
|
||||
bindCursorTexture(batch);
|
||||
|
||||
bindCursorTexture(batch);
|
||||
//Controller Pointers
|
||||
glm::mat4 overlayXfm;
|
||||
_modelTransform.getMatrix(overlayXfm);
|
||||
|
||||
//Controller Pointers
|
||||
glm::mat4 overlayXfm;
|
||||
_modelTransform.getMatrix(overlayXfm);
|
||||
// Only render the hand pointers if the HandMouseInput is enabled
|
||||
if (Menu::getInstance()->isOptionChecked(MenuOption::HandMouseInput)) {
|
||||
MyAvatar* myAvatar = DependencyManager::get<AvatarManager>()->getMyAvatar();
|
||||
for (int i = 0; i < (int)myAvatar->getHand()->getNumPalms(); i++) {
|
||||
PalmData& palm = myAvatar->getHand()->getPalms()[i];
|
||||
if (palm.isActive()) {
|
||||
glm::vec2 polar = getPolarCoordinates(palm);
|
||||
// Convert to quaternion
|
||||
mat4 pointerXfm = glm::mat4_cast(quat(vec3(polar.y, -polar.x, 0.0f))) * glm::translate(mat4(), vec3(0, 0, -1));
|
||||
mat4 reticleXfm = overlayXfm * pointerXfm;
|
||||
reticleXfm = glm::scale(reticleXfm, reticleScale);
|
||||
batch.setModelTransform(reticleXfm);
|
||||
// Render reticle at location
|
||||
geometryCache->renderUnitQuad(batch, glm::vec4(1), _reticleQuad);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
MyAvatar* myAvatar = DependencyManager::get<AvatarManager>()->getMyAvatar();
|
||||
for (int i = 0; i < (int)myAvatar->getHand()->getNumPalms(); i++) {
|
||||
PalmData& palm = myAvatar->getHand()->getPalms()[i];
|
||||
if (palm.isActive()) {
|
||||
glm::vec2 polar = getPolarCoordinates(palm);
|
||||
// Convert to quaternion
|
||||
mat4 pointerXfm = glm::mat4_cast(quat(vec3(polar.y, -polar.x, 0.0f))) * glm::translate(mat4(), vec3(0, 0, -1));
|
||||
//Mouse Pointer
|
||||
if (_reticleActive[MOUSE]) {
|
||||
glm::vec2 projection = screenToSpherical(glm::vec2(_reticlePosition[MOUSE].x(),
|
||||
_reticlePosition[MOUSE].y()));
|
||||
mat4 pointerXfm = glm::mat4_cast(quat(vec3(-projection.y, projection.x, 0.0f))) * glm::translate(mat4(), vec3(0, 0, -1));
|
||||
mat4 reticleXfm = overlayXfm * pointerXfm;
|
||||
reticleXfm = glm::scale(reticleXfm, reticleScale);
|
||||
batch.setModelTransform(reticleXfm);
|
||||
// Render reticle at location
|
||||
geometryCache->renderUnitQuad(batch, glm::vec4(1), _reticleQuad);
|
||||
}
|
||||
}
|
||||
|
||||
//Mouse Pointer
|
||||
if (_reticleActive[MOUSE]) {
|
||||
glm::vec2 projection = screenToSpherical(glm::vec2(_reticlePosition[MOUSE].x(),
|
||||
_reticlePosition[MOUSE].y()));
|
||||
mat4 pointerXfm = glm::mat4_cast(quat(vec3(-projection.y, projection.x, 0.0f))) * glm::translate(mat4(), vec3(0, 0, -1));
|
||||
mat4 reticleXfm = overlayXfm * pointerXfm;
|
||||
reticleXfm = glm::scale(reticleXfm, reticleScale);
|
||||
batch.setModelTransform(reticleXfm);
|
||||
geometryCache->renderUnitQuad(batch, glm::vec4(1), _reticleQuad);
|
||||
}
|
||||
|
||||
renderArgs->_context->render(batch);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
|
|
@ -70,29 +70,28 @@ void ApplicationOverlay::renderOverlay(RenderArgs* renderArgs) {
|
|||
}
|
||||
|
||||
// Execute the batch into our framebuffer
|
||||
gpu::Batch batch;
|
||||
renderArgs->_batch = &batch;
|
||||
doInBatch(renderArgs->_context, [=](gpu::Batch& batch) {
|
||||
renderArgs->_batch = &batch;
|
||||
|
||||
int width = _overlayFramebuffer->getWidth();
|
||||
int height = _overlayFramebuffer->getHeight();
|
||||
int width = _overlayFramebuffer->getWidth();
|
||||
int height = _overlayFramebuffer->getHeight();
|
||||
|
||||
batch.setViewportTransform(glm::ivec4(0, 0, width, height));
|
||||
batch.setFramebuffer(_overlayFramebuffer);
|
||||
batch.setViewportTransform(glm::ivec4(0, 0, width, height));
|
||||
batch.setFramebuffer(_overlayFramebuffer);
|
||||
|
||||
glm::vec4 color { 0.0f, 0.0f, 0.0f, 0.0f };
|
||||
float depth = 1.0f;
|
||||
int stencil = 0;
|
||||
batch.clearFramebuffer(gpu::Framebuffer::BUFFER_COLOR0 | gpu::Framebuffer::BUFFER_DEPTH, color, depth, stencil);
|
||||
glm::vec4 color { 0.0f, 0.0f, 0.0f, 0.0f };
|
||||
float depth = 1.0f;
|
||||
int stencil = 0;
|
||||
batch.clearFramebuffer(gpu::Framebuffer::BUFFER_COLOR0 | gpu::Framebuffer::BUFFER_DEPTH, color, depth, stencil);
|
||||
|
||||
// Now render the overlay components together into a single texture
|
||||
renderDomainConnectionStatusBorder(renderArgs); // renders the connected domain line
|
||||
renderAudioScope(renderArgs); // audio scope in the very back
|
||||
renderRearView(renderArgs); // renders the mirror view selfie
|
||||
renderQmlUi(renderArgs); // renders a unit quad with the QML UI texture, and the text overlays from scripts
|
||||
renderOverlays(renderArgs); // renders Scripts Overlay and AudioScope
|
||||
renderStatsAndLogs(renderArgs); // currently renders nothing
|
||||
|
||||
renderArgs->_context->render(batch);
|
||||
// Now render the overlay components together into a single texture
|
||||
renderDomainConnectionStatusBorder(renderArgs); // renders the connected domain line
|
||||
renderAudioScope(renderArgs); // audio scope in the very back
|
||||
renderRearView(renderArgs); // renders the mirror view selfie
|
||||
renderQmlUi(renderArgs); // renders a unit quad with the QML UI texture, and the text overlays from scripts
|
||||
renderOverlays(renderArgs); // renders Scripts Overlay and AudioScope
|
||||
renderStatsAndLogs(renderArgs); // currently renders nothing
|
||||
});
|
||||
|
||||
renderArgs->_batch = nullptr; // so future users of renderArgs don't try to use our batch
|
||||
|
||||
|
|
|
@ -68,12 +68,7 @@ void OverlayConductor::updateMode() {
|
|||
|
||||
Mode newMode;
|
||||
if (qApp->isHMDMode()) {
|
||||
MyAvatar* myAvatar = DependencyManager::get<AvatarManager>()->getMyAvatar();
|
||||
if (myAvatar->getStandingHMDSensorMode()) {
|
||||
newMode = STANDING;
|
||||
} else {
|
||||
newMode = SITTING;
|
||||
}
|
||||
newMode = SITTING;
|
||||
} else {
|
||||
newMode = FLAT;
|
||||
}
|
||||
|
|
|
@ -46,6 +46,7 @@ Stats::Stats(QQuickItem* parent) : QQuickItem(parent) {
|
|||
INSTANCE = this;
|
||||
const QFont font = QFontDatabase::systemFont(QFontDatabase::FixedFont);
|
||||
_monospaceFont = font.family();
|
||||
_audioStats = &DependencyManager::get<AudioClient>()->getStats();
|
||||
}
|
||||
|
||||
bool Stats::includeTimingRecord(const QString& name) {
|
||||
|
@ -89,14 +90,14 @@ bool Stats::includeTimingRecord(const QString& name) {
|
|||
}
|
||||
|
||||
|
||||
void Stats::updateStats() {
|
||||
if (!Menu::getInstance()->isOptionChecked(MenuOption::Stats)) {
|
||||
if (isVisible()) {
|
||||
setVisible(false);
|
||||
}
|
||||
return;
|
||||
} else {
|
||||
if (!isVisible()) {
|
||||
void Stats::updateStats(bool force) {
|
||||
if (!force) {
|
||||
if (!Menu::getInstance()->isOptionChecked(MenuOption::Stats)) {
|
||||
if (isVisible()) {
|
||||
setVisible(false);
|
||||
}
|
||||
return;
|
||||
} else if (!isVisible()) {
|
||||
setVisible(true);
|
||||
}
|
||||
}
|
||||
|
@ -161,7 +162,7 @@ void Stats::updateStats() {
|
|||
STAT_UPDATE(position, QVector3D(avatarPos.x, avatarPos.y, avatarPos.z));
|
||||
STAT_UPDATE_FLOAT(velocity, glm::length(myAvatar->getVelocity()), 0.1f);
|
||||
STAT_UPDATE_FLOAT(yaw, myAvatar->getBodyYaw(), 0.1f);
|
||||
if (_expanded) {
|
||||
if (_expanded || force) {
|
||||
SharedNodePointer avatarMixer = nodeList->soloNodeOfType(NodeType::AvatarMixer);
|
||||
if (avatarMixer) {
|
||||
STAT_UPDATE(avatarMixerKbps, roundf(
|
||||
|
@ -175,7 +176,7 @@ void Stats::updateStats() {
|
|||
STAT_UPDATE(avatarMixerPps, -1);
|
||||
}
|
||||
SharedNodePointer audioMixerNode = nodeList->soloNodeOfType(NodeType::AudioMixer);
|
||||
if (audioMixerNode) {
|
||||
if (audioMixerNode || force) {
|
||||
STAT_UPDATE(audioMixerKbps, roundf(
|
||||
bandwidthRecorder->getAverageInputKilobitsPerSecond(NodeType::AudioMixer) +
|
||||
bandwidthRecorder->getAverageOutputKilobitsPerSecond(NodeType::AudioMixer)));
|
||||
|
@ -230,7 +231,7 @@ void Stats::updateStats() {
|
|||
totalLeaves += stats.getTotalLeaves();
|
||||
}
|
||||
}
|
||||
if (_expanded) {
|
||||
if (_expanded || force) {
|
||||
if (serverCount == 0) {
|
||||
sendingModeStream << "---";
|
||||
}
|
||||
|
@ -272,7 +273,7 @@ void Stats::updateStats() {
|
|||
STAT_UPDATE(serverElements, (int)totalNodes);
|
||||
STAT_UPDATE(localElements, (int)OctreeElement::getNodeCount());
|
||||
|
||||
if (_expanded) {
|
||||
if (_expanded || force) {
|
||||
STAT_UPDATE(serverInternal, (int)totalInternal);
|
||||
STAT_UPDATE(serverLeaves, (int)totalLeaves);
|
||||
// Local Voxels
|
||||
|
|
|
@ -12,6 +12,7 @@
|
|||
#include <OffscreenQmlElement.h>
|
||||
#include <RenderArgs.h>
|
||||
#include <QVector3D>
|
||||
#include <AudioIOStats.h>
|
||||
|
||||
#define STATS_PROPERTY(type, name, initialValue) \
|
||||
Q_PROPERTY(type name READ name NOTIFY name##Changed) \
|
||||
|
@ -27,6 +28,8 @@ class Stats : public QQuickItem {
|
|||
Q_PROPERTY(bool expanded READ isExpanded WRITE setExpanded NOTIFY expandedChanged)
|
||||
Q_PROPERTY(bool timingExpanded READ isTimingExpanded NOTIFY timingExpandedChanged)
|
||||
Q_PROPERTY(QString monospaceFont READ monospaceFont CONSTANT)
|
||||
Q_PROPERTY(float audioPacketlossUpstream READ getAudioPacketLossUpstream)
|
||||
Q_PROPERTY(float audioPacketlossDownstream READ getAudioPacketLossDownstream)
|
||||
|
||||
STATS_PROPERTY(int, serverCount, 0)
|
||||
STATS_PROPERTY(int, framerate, 0)
|
||||
|
@ -81,7 +84,11 @@ public:
|
|||
const QString& monospaceFont() {
|
||||
return _monospaceFont;
|
||||
}
|
||||
void updateStats();
|
||||
|
||||
float getAudioPacketLossUpstream() { return _audioStats->getMixerAvatarStreamStats()._packetStreamStats.getLostRate(); }
|
||||
float getAudioPacketLossDownstream() { return _audioStats->getMixerDownstreamStats()._packetStreamStats.getLostRate(); }
|
||||
|
||||
void updateStats(bool force = false);
|
||||
|
||||
bool isExpanded() { return _expanded; }
|
||||
bool isTimingExpanded() { return _timingExpanded; }
|
||||
|
@ -93,6 +100,9 @@ public:
|
|||
}
|
||||
}
|
||||
|
||||
public slots:
|
||||
void forceUpdateStats() { updateStats(true); }
|
||||
|
||||
signals:
|
||||
void expandedChanged();
|
||||
void timingExpandedChanged();
|
||||
|
@ -146,6 +156,8 @@ private:
|
|||
bool _expanded{ false };
|
||||
bool _timingExpanded{ false };
|
||||
QString _monospaceFont;
|
||||
const AudioIOStats* _audioStats;
|
||||
};
|
||||
|
||||
#endif // hifi_Stats_h
|
||||
|
||||
|
|
|
@ -171,6 +171,6 @@ QScriptValue Base3DOverlay::getProperty(const QString& property) {
|
|||
}
|
||||
|
||||
bool Base3DOverlay::findRayIntersection(const glm::vec3& origin, const glm::vec3& direction,
|
||||
float& distance, BoxFace& face) {
|
||||
float& distance, BoxFace& face, glm::vec3& surfaceNormal) {
|
||||
return false;
|
||||
}
|
||||
|
|
|
@ -57,11 +57,12 @@ public:
|
|||
virtual void setProperties(const QScriptValue& properties);
|
||||
virtual QScriptValue getProperty(const QString& property);
|
||||
|
||||
virtual bool findRayIntersection(const glm::vec3& origin, const glm::vec3& direction, float& distance, BoxFace& face);
|
||||
virtual bool findRayIntersection(const glm::vec3& origin, const glm::vec3& direction, float& distance,
|
||||
BoxFace& face, glm::vec3& surfaceNormal);
|
||||
|
||||
virtual bool findRayIntersectionExtraInfo(const glm::vec3& origin, const glm::vec3& direction,
|
||||
float& distance, BoxFace& face, QString& extraInfo) {
|
||||
return findRayIntersection(origin, direction, distance, face);
|
||||
float& distance, BoxFace& face, glm::vec3& surfaceNormal, QString& extraInfo) {
|
||||
return findRayIntersection(origin, direction, distance, face, surfaceNormal);
|
||||
}
|
||||
|
||||
protected:
|
||||
|
|
|
@ -391,10 +391,10 @@ QScriptValue Circle3DOverlay::getProperty(const QString& property) {
|
|||
}
|
||||
|
||||
|
||||
bool Circle3DOverlay::findRayIntersection(const glm::vec3& origin,
|
||||
const glm::vec3& direction, float& distance, BoxFace& face) {
|
||||
bool Circle3DOverlay::findRayIntersection(const glm::vec3& origin, const glm::vec3& direction, float& distance,
|
||||
BoxFace& face, glm::vec3& surfaceNormal) {
|
||||
|
||||
bool intersects = Planar3DOverlay::findRayIntersection(origin, direction, distance, face);
|
||||
bool intersects = Planar3DOverlay::findRayIntersection(origin, direction, distance, face, surfaceNormal);
|
||||
|
||||
if (intersects) {
|
||||
glm::vec3 hitPosition = origin + (distance * direction);
|
||||
|
|
|
@ -52,7 +52,8 @@ public:
|
|||
void setMajorTickMarksColor(const xColor& value) { _majorTickMarksColor = value; }
|
||||
void setMinorTickMarksColor(const xColor& value) { _minorTickMarksColor = value; }
|
||||
|
||||
virtual bool findRayIntersection(const glm::vec3& origin, const glm::vec3& direction, float& distance, BoxFace& face);
|
||||
virtual bool findRayIntersection(const glm::vec3& origin, const glm::vec3& direction, float& distance,
|
||||
BoxFace& face, glm::vec3& surfaceNormal);
|
||||
|
||||
virtual Circle3DOverlay* createClone() const;
|
||||
|
||||
|
|
|
@ -166,7 +166,7 @@ void Image3DOverlay::setURL(const QString& url) {
|
|||
}
|
||||
|
||||
bool Image3DOverlay::findRayIntersection(const glm::vec3& origin, const glm::vec3& direction,
|
||||
float& distance, BoxFace& face) {
|
||||
float& distance, BoxFace& face, glm::vec3& surfaceNormal) {
|
||||
if (_texture && _texture->isLoaded()) {
|
||||
// Make sure position and rotation is updated.
|
||||
applyTransformTo(_transform, true);
|
||||
|
@ -178,6 +178,7 @@ bool Image3DOverlay::findRayIntersection(const glm::vec3& origin, const glm::vec
|
|||
float maxSize = glm::max(width, height);
|
||||
glm::vec2 dimensions = _dimensions * glm::vec2(width / maxSize, height / maxSize);
|
||||
|
||||
// FIXME - face and surfaceNormal not being set
|
||||
return findRayRectangleIntersection(origin, direction, getRotation(), getPosition(), dimensions, distance);
|
||||
}
|
||||
|
||||
|
|
|
@ -38,7 +38,8 @@ public:
|
|||
virtual void setProperties(const QScriptValue& properties);
|
||||
virtual QScriptValue getProperty(const QString& property);
|
||||
|
||||
virtual bool findRayIntersection(const glm::vec3& origin, const glm::vec3& direction, float& distance, BoxFace& face);
|
||||
virtual bool findRayIntersection(const glm::vec3& origin, const glm::vec3& direction, float& distance,
|
||||
BoxFace& face, glm::vec3& surfaceNormal);
|
||||
|
||||
virtual Image3DOverlay* createClone() const;
|
||||
|
||||
|
|
|
@ -159,16 +159,16 @@ QScriptValue ModelOverlay::getProperty(const QString& property) {
|
|||
}
|
||||
|
||||
bool ModelOverlay::findRayIntersection(const glm::vec3& origin, const glm::vec3& direction,
|
||||
float& distance, BoxFace& face) {
|
||||
float& distance, BoxFace& face, glm::vec3& surfaceNormal) {
|
||||
|
||||
QString subMeshNameTemp;
|
||||
return _model.findRayIntersectionAgainstSubMeshes(origin, direction, distance, face, subMeshNameTemp);
|
||||
return _model.findRayIntersectionAgainstSubMeshes(origin, direction, distance, face, surfaceNormal, subMeshNameTemp);
|
||||
}
|
||||
|
||||
bool ModelOverlay::findRayIntersectionExtraInfo(const glm::vec3& origin, const glm::vec3& direction,
|
||||
float& distance, BoxFace& face, QString& extraInfo) {
|
||||
float& distance, BoxFace& face, glm::vec3& surfaceNormal, QString& extraInfo) {
|
||||
|
||||
return _model.findRayIntersectionAgainstSubMeshes(origin, direction, distance, face, extraInfo);
|
||||
return _model.findRayIntersectionAgainstSubMeshes(origin, direction, distance, face, surfaceNormal, extraInfo);
|
||||
}
|
||||
|
||||
ModelOverlay* ModelOverlay::createClone() const {
|
||||
|
|
|
@ -29,9 +29,10 @@ public:
|
|||
virtual void render(RenderArgs* args);
|
||||
virtual void setProperties(const QScriptValue& properties);
|
||||
virtual QScriptValue getProperty(const QString& property);
|
||||
virtual bool findRayIntersection(const glm::vec3& origin, const glm::vec3& direction, float& distance, BoxFace& face);
|
||||
virtual bool findRayIntersection(const glm::vec3& origin, const glm::vec3& direction, float& distance,
|
||||
BoxFace& face, glm::vec3& surfaceNormal);
|
||||
virtual bool findRayIntersectionExtraInfo(const glm::vec3& origin, const glm::vec3& direction,
|
||||
float& distance, BoxFace& face, QString& extraInfo);
|
||||
float& distance, BoxFace& face, glm::vec3& surfaceNormal, QString& extraInfo);
|
||||
|
||||
virtual ModelOverlay* createClone() const;
|
||||
|
||||
|
|
|
@ -10,7 +10,7 @@
|
|||
|
||||
#include "Overlays.h"
|
||||
|
||||
#include <QScriptValueIterator>
|
||||
#include <QtScript/QScriptValueIterator>
|
||||
|
||||
#include <limits>
|
||||
|
||||
|
@ -31,6 +31,7 @@
|
|||
#include "TextOverlay.h"
|
||||
#include "Text3DOverlay.h"
|
||||
#include "Web3DOverlay.h"
|
||||
#include <QtQuick/QQuickWindow>
|
||||
|
||||
|
||||
Overlays::Overlays() : _nextOverlayID(1) {
|
||||
|
@ -331,10 +332,6 @@ void Overlays::setParentPanel(unsigned int childId, unsigned int panelId) {
|
|||
|
||||
unsigned int Overlays::getOverlayAtPoint(const glm::vec2& point) {
|
||||
glm::vec2 pointCopy = point;
|
||||
if (qApp->isHMDMode()) {
|
||||
pointCopy = qApp->getApplicationCompositor().screenToOverlay(point);
|
||||
}
|
||||
|
||||
QReadLocker lock(&_lock);
|
||||
if (!_enabled) {
|
||||
return 0;
|
||||
|
@ -346,6 +343,7 @@ unsigned int Overlays::getOverlayAtPoint(const glm::vec2& point) {
|
|||
glm::vec3 origin(pointCopy.x, pointCopy.y, LARGE_NEGATIVE_FLOAT);
|
||||
glm::vec3 direction(0, 0, 1);
|
||||
BoxFace thisFace;
|
||||
glm::vec3 thisSurfaceNormal;
|
||||
float distance;
|
||||
|
||||
while (i.hasPrevious()) {
|
||||
|
@ -354,7 +352,7 @@ unsigned int Overlays::getOverlayAtPoint(const glm::vec2& point) {
|
|||
if (i.value()->is3D()) {
|
||||
auto thisOverlay = std::dynamic_pointer_cast<Base3DOverlay>(i.value());
|
||||
if (thisOverlay && !thisOverlay->getIgnoreRayIntersection()) {
|
||||
if (thisOverlay->findRayIntersection(origin, direction, distance, thisFace)) {
|
||||
if (thisOverlay->findRayIntersection(origin, direction, distance, thisFace, thisSurfaceNormal)) {
|
||||
return thisID;
|
||||
}
|
||||
}
|
||||
|
@ -423,8 +421,10 @@ RayToOverlayIntersectionResult Overlays::findRayIntersection(const PickRay& ray)
|
|||
if (thisOverlay && thisOverlay->getVisible() && !thisOverlay->getIgnoreRayIntersection() && thisOverlay->isLoaded()) {
|
||||
float thisDistance;
|
||||
BoxFace thisFace;
|
||||
glm::vec3 thisSurfaceNormal;
|
||||
QString thisExtraInfo;
|
||||
if (thisOverlay->findRayIntersectionExtraInfo(ray.origin, ray.direction, thisDistance, thisFace, thisExtraInfo)) {
|
||||
if (thisOverlay->findRayIntersectionExtraInfo(ray.origin, ray.direction, thisDistance,
|
||||
thisFace, thisSurfaceNormal, thisExtraInfo)) {
|
||||
bool isDrawInFront = thisOverlay->getDrawInFront();
|
||||
if (thisDistance < bestDistance && (!bestIsFront || isDrawInFront)) {
|
||||
bestIsFront = isDrawInFront;
|
||||
|
@ -432,6 +432,7 @@ RayToOverlayIntersectionResult Overlays::findRayIntersection(const PickRay& ray)
|
|||
result.intersects = true;
|
||||
result.distance = thisDistance;
|
||||
result.face = thisFace;
|
||||
result.surfaceNormal = thisSurfaceNormal;
|
||||
result.overlayID = thisID;
|
||||
result.intersection = ray.origin + (ray.direction * thisDistance);
|
||||
result.extraInfo = thisExtraInfo;
|
||||
|
@ -603,3 +604,13 @@ void Overlays::deletePanel(unsigned int panelId) {
|
|||
bool Overlays::isAddedOverlay(unsigned int id) {
|
||||
return _overlaysHUD.contains(id) || _overlaysWorld.contains(id);
|
||||
}
|
||||
|
||||
float Overlays::width() const {
|
||||
auto offscreenUi = DependencyManager::get<OffscreenUi>();
|
||||
return offscreenUi->getWindow()->size().width();
|
||||
}
|
||||
|
||||
float Overlays::height() const {
|
||||
auto offscreenUi = DependencyManager::get<OffscreenUi>();
|
||||
return offscreenUi->getWindow()->size().height();
|
||||
}
|
|
@ -46,6 +46,7 @@ public:
|
|||
int overlayID;
|
||||
float distance;
|
||||
BoxFace face;
|
||||
glm::vec3 surfaceNormal;
|
||||
glm::vec3 intersection;
|
||||
QString extraInfo;
|
||||
};
|
||||
|
@ -112,6 +113,10 @@ public slots:
|
|||
/// overlay; in meters if it is a 3D text overlay
|
||||
QSizeF textSize(unsigned int id, const QString& text) const;
|
||||
|
||||
// Return the size of the virtual screen
|
||||
float width() const;
|
||||
float height() const;
|
||||
|
||||
|
||||
/// adds a panel that has already been created
|
||||
unsigned int addPanel(OverlayPanel::Pointer panel);
|
||||
|
|
|
@ -92,6 +92,7 @@ QScriptValue Planar3DOverlay::getProperty(const QString& property) {
|
|||
}
|
||||
|
||||
bool Planar3DOverlay::findRayIntersection(const glm::vec3& origin, const glm::vec3& direction,
|
||||
float& distance, BoxFace& face) {
|
||||
float& distance, BoxFace& face, glm::vec3& surfaceNormal) {
|
||||
// FIXME - face and surfaceNormal not being returned
|
||||
return findRayRectangleIntersection(origin, direction, getRotation(), getPosition(), getDimensions(), distance);
|
||||
}
|
||||
|
|
|
@ -29,7 +29,8 @@ public:
|
|||
virtual void setProperties(const QScriptValue& properties);
|
||||
virtual QScriptValue getProperty(const QString& property);
|
||||
|
||||
virtual bool findRayIntersection(const glm::vec3& origin, const glm::vec3& direction, float& distance, BoxFace& face);
|
||||
virtual bool findRayIntersection(const glm::vec3& origin, const glm::vec3& direction, float& distance,
|
||||
BoxFace& face, glm::vec3& surfaceNormal);
|
||||
|
||||
protected:
|
||||
glm::vec2 _dimensions;
|
||||
|
|
|
@ -211,7 +211,8 @@ QSizeF Text3DOverlay::textSize(const QString& text) const {
|
|||
return QSizeF(extents.x, extents.y) * pointToWorldScale;
|
||||
}
|
||||
|
||||
bool Text3DOverlay::findRayIntersection(const glm::vec3 &origin, const glm::vec3 &direction, float &distance, BoxFace &face) {
|
||||
bool Text3DOverlay::findRayIntersection(const glm::vec3 &origin, const glm::vec3 &direction, float &distance,
|
||||
BoxFace &face, glm::vec3& surfaceNormal) {
|
||||
applyTransformTo(_transform, true);
|
||||
return Billboard3DOverlay::findRayIntersection(origin, direction, distance, face);
|
||||
return Billboard3DOverlay::findRayIntersection(origin, direction, distance, face, surfaceNormal);
|
||||
}
|
||||
|
|
|
@ -54,7 +54,8 @@ public:
|
|||
|
||||
QSizeF textSize(const QString& test) const; // Meters
|
||||
|
||||
virtual bool findRayIntersection(const glm::vec3& origin, const glm::vec3& direction, float& distance, BoxFace& face);
|
||||
virtual bool findRayIntersection(const glm::vec3& origin, const glm::vec3& direction, float& distance,
|
||||
BoxFace& face, glm::vec3& surfaceNormal);
|
||||
|
||||
virtual Text3DOverlay* createClone() const;
|
||||
|
||||
|
|
|
@ -93,7 +93,7 @@ QScriptValue Volume3DOverlay::getProperty(const QString& property) {
|
|||
}
|
||||
|
||||
bool Volume3DOverlay::findRayIntersection(const glm::vec3& origin, const glm::vec3& direction,
|
||||
float& distance, BoxFace& face) {
|
||||
float& distance, BoxFace& face, glm::vec3& surfaceNormal) {
|
||||
// extents is the entity relative, scaled, centered extents of the entity
|
||||
glm::mat4 worldToEntityMatrix;
|
||||
_transform.getInverseMatrix(worldToEntityMatrix);
|
||||
|
@ -103,5 +103,5 @@ bool Volume3DOverlay::findRayIntersection(const glm::vec3& origin, const glm::ve
|
|||
|
||||
// we can use the AABox's ray intersection by mapping our origin and direction into the overlays frame
|
||||
// and testing intersection there.
|
||||
return _localBoundingBox.findRayIntersection(overlayFrameOrigin, overlayFrameDirection, distance, face);
|
||||
return _localBoundingBox.findRayIntersection(overlayFrameOrigin, overlayFrameDirection, distance, face, surfaceNormal);
|
||||
}
|
||||
|
|
|
@ -29,7 +29,8 @@ public:
|
|||
virtual void setProperties(const QScriptValue& properties);
|
||||
virtual QScriptValue getProperty(const QString& property);
|
||||
|
||||
virtual bool findRayIntersection(const glm::vec3& origin, const glm::vec3& direction, float& distance, BoxFace& face);
|
||||
virtual bool findRayIntersection(const glm::vec3& origin, const glm::vec3& direction, float& distance,
|
||||
BoxFace& face, glm::vec3& surfaceNormal);
|
||||
|
||||
protected:
|
||||
// Centered local bounding box
|
||||
|
|
|
@ -151,8 +151,10 @@ void Web3DOverlay::setURL(const QString& url) {
|
|||
|
||||
}
|
||||
|
||||
bool Web3DOverlay::findRayIntersection(const glm::vec3& origin, const glm::vec3& direction, float& distance, BoxFace& face) {
|
||||
//// Make sure position and rotation is updated.
|
||||
bool Web3DOverlay::findRayIntersection(const glm::vec3& origin, const glm::vec3& direction, float& distance, BoxFace& face, glm::vec3& surfaceNormal) {
|
||||
// FIXME - face and surfaceNormal not being returned
|
||||
|
||||
// Make sure position and rotation is updated.
|
||||
applyTransformTo(_transform, true);
|
||||
vec2 size = _resolution / _dpi * INCHES_TO_METERS * vec2(getDimensions());
|
||||
// Produce the dimensions of the overlay based on the image's aspect ratio and the overlay's scale.
|
||||
|
|
|
@ -34,7 +34,8 @@ public:
|
|||
virtual void setProperties(const QScriptValue& properties);
|
||||
virtual QScriptValue getProperty(const QString& property);
|
||||
|
||||
virtual bool findRayIntersection(const glm::vec3& origin, const glm::vec3& direction, float& distance, BoxFace& face);
|
||||
virtual bool findRayIntersection(const glm::vec3& origin, const glm::vec3& direction, float& distance,
|
||||
BoxFace& face, glm::vec3& surfaceNormal);
|
||||
|
||||
virtual Web3DOverlay* createClone() const;
|
||||
|
||||
|
|
|
@ -135,23 +135,46 @@ void AnimClip::copyFromNetworkAnim() {
|
|||
const int frameCount = geom.animationFrames.size();
|
||||
const int skeletonJointCount = _skeleton->getNumJoints();
|
||||
_anim.resize(frameCount);
|
||||
for (int i = 0; i < frameCount; i++) {
|
||||
|
||||
const glm::vec3 offsetScale = extractScale(geom.offset);
|
||||
|
||||
for (int frame = 0; frame < frameCount; frame++) {
|
||||
|
||||
// init all joints in animation to bind pose
|
||||
_anim[i].reserve(skeletonJointCount);
|
||||
for (int j = 0; j < skeletonJointCount; j++) {
|
||||
_anim[i].push_back(_skeleton->getRelativeBindPose(j));
|
||||
// this will give us a resonable result for bones in the skeleton but not in the animation.
|
||||
_anim[frame].reserve(skeletonJointCount);
|
||||
for (int skeletonJoint = 0; skeletonJoint < skeletonJointCount; skeletonJoint++) {
|
||||
_anim[frame].push_back(_skeleton->getRelativeBindPose(skeletonJoint));
|
||||
}
|
||||
|
||||
// init over all joint animations
|
||||
for (int j = 0; j < animJointCount; j++) {
|
||||
int k = jointMap[j];
|
||||
if (k >= 0 && k < skeletonJointCount) {
|
||||
// currently FBX animations only have rotation.
|
||||
_anim[i][k].rot = _skeleton->getRelativeBindPose(k).rot * geom.animationFrames[i].rotations[j];
|
||||
for (int animJoint = 0; animJoint < animJointCount; animJoint++) {
|
||||
|
||||
int skeletonJoint = jointMap[animJoint];
|
||||
|
||||
// skip joints that are in the animation but not in the skeleton.
|
||||
if (skeletonJoint >= 0 && skeletonJoint < skeletonJointCount) {
|
||||
|
||||
const glm::vec3& fbxZeroTrans = geom.animationFrames[0].translations[animJoint] * offsetScale;
|
||||
const AnimPose& relBindPose = _skeleton->getRelativeBindPose(skeletonJoint);
|
||||
|
||||
// used to adjust translation offsets, so large translation animatons on the reference skeleton
|
||||
// will be adjusted when played on a skeleton with short limbs.
|
||||
float limbLengthScale = fabs(glm::length(fbxZeroTrans)) <= 0.0001f ? 1.0f : (glm::length(relBindPose.trans) / glm::length(fbxZeroTrans));
|
||||
|
||||
AnimPose& pose = _anim[frame][skeletonJoint];
|
||||
const FBXAnimationFrame& fbxAnimFrame = geom.animationFrames[frame];
|
||||
|
||||
// rotation in fbxAnimationFrame is a delta from a reference skeleton bind pose.
|
||||
pose.rot = relBindPose.rot * fbxAnimFrame.rotations[animJoint];
|
||||
|
||||
// translation in fbxAnimationFrame is not a delta.
|
||||
// convert it into a delta by subtracting from the first frame.
|
||||
const glm::vec3& fbxTrans = fbxAnimFrame.translations[animJoint] * offsetScale;
|
||||
pose.trans = relBindPose.trans + limbLengthScale * (fbxTrans - fbxZeroTrans);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_poses.resize(skeletonJointCount);
|
||||
}
|
||||
|
||||
|
|
|
@ -9,6 +9,7 @@
|
|||
|
||||
#include "AnimInverseKinematics.h"
|
||||
|
||||
#include <GeometryUtil.h>
|
||||
#include <GLMHelpers.h>
|
||||
#include <NumericalConstants.h>
|
||||
#include <SharedUtil.h>
|
||||
|
@ -42,9 +43,8 @@ void AnimInverseKinematics::loadPoses(const AnimPoseVec& poses) {
|
|||
|
||||
void AnimInverseKinematics::computeAbsolutePoses(AnimPoseVec& absolutePoses) const {
|
||||
int numJoints = (int)_relativePoses.size();
|
||||
absolutePoses.clear();
|
||||
absolutePoses.resize(numJoints);
|
||||
assert(numJoints <= _skeleton->getNumJoints());
|
||||
assert(numJoints == (int)absolutePoses.size());
|
||||
for (int i = 0; i < numJoints; ++i) {
|
||||
int parentIndex = _skeleton->getParentIndex(i);
|
||||
if (parentIndex < 0) {
|
||||
|
@ -55,7 +55,11 @@ void AnimInverseKinematics::computeAbsolutePoses(AnimPoseVec& absolutePoses) con
|
|||
}
|
||||
}
|
||||
|
||||
void AnimInverseKinematics::setTargetVars(const QString& jointName, const QString& positionVar, const QString& rotationVar) {
|
||||
void AnimInverseKinematics::setTargetVars(
|
||||
const QString& jointName,
|
||||
const QString& positionVar,
|
||||
const QString& rotationVar,
|
||||
const QString& typeVar) {
|
||||
// if there are dups, last one wins.
|
||||
bool found = false;
|
||||
for (auto& targetVar: _targetVarVec) {
|
||||
|
@ -63,13 +67,14 @@ void AnimInverseKinematics::setTargetVars(const QString& jointName, const QStrin
|
|||
// update existing targetVar
|
||||
targetVar.positionVar = positionVar;
|
||||
targetVar.rotationVar = rotationVar;
|
||||
targetVar.typeVar = typeVar;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
// create a new entry
|
||||
_targetVarVec.push_back(IKTargetVar(jointName, positionVar, rotationVar));
|
||||
_targetVarVec.push_back(IKTargetVar(jointName, positionVar, rotationVar, typeVar));
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -84,8 +89,9 @@ static int findRootJointInSkeleton(AnimSkeleton::ConstPointer skeleton, int inde
|
|||
return rootIndex;
|
||||
}
|
||||
|
||||
void AnimInverseKinematics::computeTargets(const AnimVariantMap& animVars, std::vector<IKTarget>& targets) {
|
||||
void AnimInverseKinematics::computeTargets(const AnimVariantMap& animVars, std::vector<IKTarget>& targets, const AnimPoseVec& underPoses) {
|
||||
// build a list of valid targets from _targetVarVec and animVars
|
||||
_maxTargetIndex = -1;
|
||||
bool removeUnfoundJoints = false;
|
||||
for (auto& targetVar : _targetVarVec) {
|
||||
if (targetVar.jointIndex == -1) {
|
||||
|
@ -100,14 +106,17 @@ void AnimInverseKinematics::computeTargets(const AnimVariantMap& animVars, std::
|
|||
removeUnfoundJoints = true;
|
||||
}
|
||||
} else {
|
||||
// TODO: get this done without a double-lookup of each var in animVars
|
||||
IKTarget target;
|
||||
AnimPose defaultPose = _skeleton->getAbsolutePose(targetVar.jointIndex, _relativePoses);
|
||||
AnimPose defaultPose = _skeleton->getAbsolutePose(targetVar.jointIndex, underPoses);
|
||||
target.pose.trans = animVars.lookup(targetVar.positionVar, defaultPose.trans);
|
||||
target.pose.rot = animVars.lookup(targetVar.rotationVar, defaultPose.rot);
|
||||
target.setType(animVars.lookup(targetVar.typeVar, QString("")));
|
||||
target.rootIndex = targetVar.rootIndex;
|
||||
target.index = targetVar.jointIndex;
|
||||
targets.push_back(target);
|
||||
if (target.index > _maxTargetIndex) {
|
||||
_maxTargetIndex = target.index;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -129,9 +138,10 @@ void AnimInverseKinematics::computeTargets(const AnimVariantMap& animVars, std::
|
|||
}
|
||||
}
|
||||
|
||||
void AnimInverseKinematics::solveWithCyclicCoordinateDescent(std::vector<IKTarget>& targets) {
|
||||
void AnimInverseKinematics::solveWithCyclicCoordinateDescent(const std::vector<IKTarget>& targets) {
|
||||
// compute absolute poses that correspond to relative target poses
|
||||
AnimPoseVec absolutePoses;
|
||||
absolutePoses.resize(_relativePoses.size());
|
||||
computeAbsolutePoses(absolutePoses);
|
||||
|
||||
// clear the accumulators before we start the IK solver
|
||||
|
@ -139,86 +149,124 @@ void AnimInverseKinematics::solveWithCyclicCoordinateDescent(std::vector<IKTarge
|
|||
accumulator.clearAndClean();
|
||||
}
|
||||
|
||||
float largestError = 0.0f;
|
||||
const float ACCEPTABLE_RELATIVE_ERROR = 1.0e-3f;
|
||||
int numLoops = 0;
|
||||
const int MAX_IK_LOOPS = 16;
|
||||
const quint64 MAX_IK_TIME = 10 * USECS_PER_MSEC;
|
||||
quint64 expiry = usecTimestampNow() + MAX_IK_TIME;
|
||||
const int MAX_IK_LOOPS = 4;
|
||||
do {
|
||||
largestError = 0.0f;
|
||||
int lowestMovedIndex = _relativePoses.size();
|
||||
for (auto& target: targets) {
|
||||
int tipIndex = target.index;
|
||||
if (target.type == IKTarget::Type::RotationOnly) {
|
||||
// the final rotation will be enforced after the iterations
|
||||
continue;
|
||||
}
|
||||
AnimPose targetPose = target.pose;
|
||||
|
||||
glm::vec3 tip = absolutePoses[tipIndex].trans;
|
||||
float error = glm::length(targetPose.trans - tip);
|
||||
// cache tip absolute transform
|
||||
int tipIndex = target.index;
|
||||
glm::vec3 tipPosition = absolutePoses[tipIndex].trans;
|
||||
glm::quat tipRotation = absolutePoses[tipIndex].rot;
|
||||
|
||||
// cache tip's parent's absolute rotation so we can recompute the tip's parent-relative
|
||||
// as we proceed walking down the joint chain
|
||||
int pivotIndex = _skeleton->getParentIndex(tipIndex);
|
||||
glm::quat tipParentRotation;
|
||||
if (pivotIndex != -1) {
|
||||
tipParentRotation = absolutePoses[pivotIndex].rot;
|
||||
}
|
||||
|
||||
// descend toward root, pivoting each joint to get tip closer to target
|
||||
int pivotIndex = _skeleton->getParentIndex(tipIndex);
|
||||
while (pivotIndex != -1 && error > ACCEPTABLE_RELATIVE_ERROR) {
|
||||
int ancestorCount = 1;
|
||||
while (pivotIndex != -1) {
|
||||
// compute the two lines that should be aligned
|
||||
glm::vec3 jointPosition = absolutePoses[pivotIndex].trans;
|
||||
glm::vec3 leverArm = tip - jointPosition;
|
||||
glm::vec3 leverArm = tipPosition - jointPosition;
|
||||
glm::vec3 targetLine = targetPose.trans - jointPosition;
|
||||
|
||||
// compute the axis of the rotation that would align them
|
||||
// compute the swing that would get get tip closer
|
||||
glm::vec3 axis = glm::cross(leverArm, targetLine);
|
||||
float axisLength = glm::length(axis);
|
||||
if (axisLength > EPSILON) {
|
||||
// compute deltaRotation for alignment (brings tip closer to target)
|
||||
glm::quat deltaRotation;
|
||||
const float MIN_AXIS_LENGTH = 1.0e-4f;
|
||||
if (axisLength > MIN_AXIS_LENGTH) {
|
||||
// compute deltaRotation for alignment (swings tip closer to target)
|
||||
axis /= axisLength;
|
||||
float angle = acosf(glm::dot(leverArm, targetLine) / (glm::length(leverArm) * glm::length(targetLine)));
|
||||
|
||||
// NOTE: even when axisLength is not zero (e.g. lever-arm and pivot-arm are not quite aligned) it is
|
||||
// still possible for the angle to be zero so we also check that to avoid unnecessary calculations.
|
||||
if (angle > EPSILON) {
|
||||
// reduce angle by half: slows convergence but adds stability to IK solution
|
||||
angle = 0.5f * angle;
|
||||
glm::quat deltaRotation = glm::angleAxis(angle, axis);
|
||||
const float MIN_ADJUSTMENT_ANGLE = 1.0e-4f;
|
||||
if (angle > MIN_ADJUSTMENT_ANGLE) {
|
||||
// reduce angle by a fraction (reduces IK swing contribution of this joint)
|
||||
angle /= (float)ancestorCount;
|
||||
deltaRotation = glm::angleAxis(angle, axis);
|
||||
}
|
||||
|
||||
int parentIndex = _skeleton->getParentIndex(pivotIndex);
|
||||
if (parentIndex == -1) {
|
||||
// TODO? apply constraints to root?
|
||||
// TODO? harvest the root's transform as movement of entire skeleton?
|
||||
} else {
|
||||
// compute joint's new parent-relative rotation
|
||||
// Q' = dQ * Q and Q = Qp * q --> q' = Qp^ * dQ * Q
|
||||
glm::quat newRot = glm::normalize(glm::inverse(
|
||||
absolutePoses[parentIndex].rot) *
|
||||
deltaRotation *
|
||||
absolutePoses[pivotIndex].rot);
|
||||
RotationConstraint* constraint = getConstraint(pivotIndex);
|
||||
if (constraint) {
|
||||
bool constrained = constraint->apply(newRot);
|
||||
if (constrained) {
|
||||
// the constraint will modify the movement of the tip so we have to compute the modified
|
||||
// model-frame deltaRotation
|
||||
// Q' = Qp^ * dQ * Q --> dQ = Qp * Q' * Q^
|
||||
deltaRotation = absolutePoses[parentIndex].rot *
|
||||
newRot *
|
||||
glm::inverse(absolutePoses[pivotIndex].rot);
|
||||
}
|
||||
}
|
||||
// store the rotation change in the accumulator
|
||||
_accumulators[pivotIndex].add(newRot);
|
||||
}
|
||||
// this joint has been changed so we check to see if it has the lowest index
|
||||
if (pivotIndex < lowestMovedIndex) {
|
||||
lowestMovedIndex = pivotIndex;
|
||||
}
|
||||
// The swing will re-orient the tip but there will tend to be be a non-zero delta between the tip's
|
||||
// new rotation and its target. We compute that delta here and rotate the tipJoint accordingly.
|
||||
glm::quat tipRelativeRotation = glm::inverse(deltaRotation * tipParentRotation) * targetPose.rot;
|
||||
|
||||
// keep track of tip's new position as we descend towards root
|
||||
tip = jointPosition + deltaRotation * leverArm;
|
||||
error = glm::length(targetPose.trans - tip);
|
||||
// enforce tip's constraint
|
||||
RotationConstraint* constraint = getConstraint(tipIndex);
|
||||
if (constraint) {
|
||||
bool constrained = constraint->apply(tipRelativeRotation);
|
||||
if (constrained) {
|
||||
// The tip's final parent-relative rotation violates its constraint
|
||||
// so we try to twist this pivot to compensate.
|
||||
glm::quat constrainedTipRotation = deltaRotation * tipParentRotation * tipRelativeRotation;
|
||||
glm::quat missingRotation = targetPose.rot * glm::inverse(constrainedTipRotation);
|
||||
glm::quat swingPart;
|
||||
glm::quat twistPart;
|
||||
glm::vec3 axis = glm::normalize(deltaRotation * leverArm);
|
||||
swingTwistDecomposition(missingRotation, axis, swingPart, twistPart);
|
||||
deltaRotation = twistPart * deltaRotation;
|
||||
}
|
||||
// we update the tip rotation here to rotate it as close to its target orientation as possible
|
||||
// before moving on to next pivot
|
||||
tipRotation = tipParentRotation * tipRelativeRotation;
|
||||
}
|
||||
}
|
||||
++ancestorCount;
|
||||
|
||||
int parentIndex = _skeleton->getParentIndex(pivotIndex);
|
||||
if (parentIndex == -1) {
|
||||
// TODO? apply constraints to root?
|
||||
// TODO? harvest the root's transform as movement of entire skeleton?
|
||||
} else {
|
||||
// compute joint's new parent-relative rotation after swing
|
||||
// Q' = dQ * Q and Q = Qp * q --> q' = Qp^ * dQ * Q
|
||||
glm::quat newRot = glm::normalize(glm::inverse(
|
||||
absolutePoses[parentIndex].rot) *
|
||||
deltaRotation *
|
||||
absolutePoses[pivotIndex].rot);
|
||||
|
||||
// enforce pivot's constraint
|
||||
RotationConstraint* constraint = getConstraint(pivotIndex);
|
||||
if (constraint) {
|
||||
bool constrained = constraint->apply(newRot);
|
||||
if (constrained) {
|
||||
// the constraint will modify the movement of the tip so we have to compute the modified
|
||||
// model-frame deltaRotation
|
||||
// Q' = Qp^ * dQ * Q --> dQ = Qp * Q' * Q^
|
||||
deltaRotation = absolutePoses[parentIndex].rot *
|
||||
newRot *
|
||||
glm::inverse(absolutePoses[pivotIndex].rot);
|
||||
}
|
||||
}
|
||||
|
||||
// store the rotation change in the accumulator
|
||||
_accumulators[pivotIndex].add(newRot);
|
||||
}
|
||||
// this joint has been changed so we check to see if it has the lowest index
|
||||
if (pivotIndex < lowestMovedIndex) {
|
||||
lowestMovedIndex = pivotIndex;
|
||||
}
|
||||
|
||||
// keep track of tip's new transform as we descend towards root
|
||||
tipPosition = jointPosition + deltaRotation * leverArm;
|
||||
tipRotation = glm::normalize(deltaRotation * tipRotation);
|
||||
tipParentRotation = glm::normalize(deltaRotation * tipParentRotation);
|
||||
|
||||
pivotIndex = _skeleton->getParentIndex(pivotIndex);
|
||||
}
|
||||
if (largestError < error) {
|
||||
largestError = error;
|
||||
}
|
||||
}
|
||||
++numLoops;
|
||||
|
||||
|
@ -238,7 +286,18 @@ void AnimInverseKinematics::solveWithCyclicCoordinateDescent(std::vector<IKTarge
|
|||
absolutePoses[i] = absolutePoses[parentIndex] * _relativePoses[i];
|
||||
}
|
||||
}
|
||||
} while (largestError > ACCEPTABLE_RELATIVE_ERROR && numLoops < MAX_IK_LOOPS && usecTimestampNow() < expiry);
|
||||
} while (numLoops < MAX_IK_LOOPS);
|
||||
|
||||
/* KEEP: example code for measuring endeffector error of IK solution
|
||||
for (uint32_t i = 0; i < targets.size(); ++i) {
|
||||
auto& target = targets[i];
|
||||
if (target.type == IKTarget::Type::RotationOnly) {
|
||||
continue;
|
||||
}
|
||||
glm::vec3 tipPosition = absolutePoses[target.index].trans;
|
||||
std::cout << i << " IK error = " << glm::distance(tipPosition, target.pose.trans) << std::endl; // adebug
|
||||
}
|
||||
*/
|
||||
|
||||
// finally set the relative rotation of each tip to agree with absolute target rotation
|
||||
for (auto& target: targets) {
|
||||
|
@ -264,25 +323,8 @@ void AnimInverseKinematics::solveWithCyclicCoordinateDescent(std::vector<IKTarge
|
|||
|
||||
//virtual
|
||||
const AnimPoseVec& AnimInverseKinematics::evaluate(const AnimVariantMap& animVars, float dt, AnimNode::Triggers& triggersOut) {
|
||||
if (!_relativePoses.empty()) {
|
||||
// build a list of targets from _targetVarVec
|
||||
std::vector<IKTarget> targets;
|
||||
computeTargets(animVars, targets);
|
||||
|
||||
if (targets.empty()) {
|
||||
// no IK targets but still need to enforce constraints
|
||||
std::map<int, RotationConstraint*>::iterator constraintItr = _constraints.begin();
|
||||
while (constraintItr != _constraints.end()) {
|
||||
int index = constraintItr->first;
|
||||
glm::quat rotation = _relativePoses[index].rot;
|
||||
constraintItr->second->apply(rotation);
|
||||
_relativePoses[index].rot = rotation;
|
||||
++constraintItr;
|
||||
}
|
||||
} else {
|
||||
solveWithCyclicCoordinateDescent(targets);
|
||||
}
|
||||
}
|
||||
// don't call this function, call overlay() instead
|
||||
assert(false);
|
||||
return _relativePoses;
|
||||
}
|
||||
|
||||
|
@ -306,9 +348,30 @@ const AnimPoseVec& AnimInverseKinematics::overlay(const AnimVariantMap& animVars
|
|||
} else {
|
||||
_relativePoses[i].rot = underPoses[i].rot;
|
||||
}
|
||||
_relativePoses[i].trans = underPoses[i].trans;
|
||||
}
|
||||
}
|
||||
return evaluate(animVars, dt, triggersOut);
|
||||
|
||||
if (!_relativePoses.empty()) {
|
||||
// build a list of targets from _targetVarVec
|
||||
std::vector<IKTarget> targets;
|
||||
computeTargets(animVars, targets, underPoses);
|
||||
|
||||
if (targets.empty()) {
|
||||
// no IK targets but still need to enforce constraints
|
||||
std::map<int, RotationConstraint*>::iterator constraintItr = _constraints.begin();
|
||||
while (constraintItr != _constraints.end()) {
|
||||
int index = constraintItr->first;
|
||||
glm::quat rotation = _relativePoses[index].rot;
|
||||
constraintItr->second->apply(rotation);
|
||||
_relativePoses[index].rot = rotation;
|
||||
++constraintItr;
|
||||
}
|
||||
} else {
|
||||
solveWithCyclicCoordinateDescent(targets);
|
||||
}
|
||||
}
|
||||
return _relativePoses;
|
||||
}
|
||||
|
||||
RotationConstraint* AnimInverseKinematics::getConstraint(int index) {
|
||||
|
@ -380,7 +443,7 @@ void AnimInverseKinematics::initConstraints() {
|
|||
}
|
||||
}
|
||||
|
||||
_constraints.clear();
|
||||
clearConstraints();
|
||||
for (int i = 0; i < numJoints; ++i) {
|
||||
// compute the joint's baseName and remember whether its prefix was "Left" or not
|
||||
QString baseName = _skeleton->getJointName(i);
|
||||
|
@ -456,7 +519,7 @@ void AnimInverseKinematics::initConstraints() {
|
|||
} else if (0 == baseName.compare("Hand", Qt::CaseInsensitive)) {
|
||||
SwingTwistConstraint* stConstraint = new SwingTwistConstraint();
|
||||
stConstraint->setReferenceRotation(_defaultRelativePoses[i].rot);
|
||||
const float MAX_HAND_TWIST = PI;
|
||||
const float MAX_HAND_TWIST = 3.0f * PI / 5.0f;
|
||||
const float MIN_HAND_TWIST = -PI / 2.0f;
|
||||
if (isLeft) {
|
||||
stConstraint->setTwistLimits(-MAX_HAND_TWIST, -MIN_HAND_TWIST);
|
||||
|
@ -639,9 +702,12 @@ void AnimInverseKinematics::setSkeletonInternal(AnimSkeleton::ConstPointer skele
|
|||
targetVar.jointIndex = -1;
|
||||
}
|
||||
|
||||
_maxTargetIndex = 0;
|
||||
_maxTargetIndex = -1;
|
||||
|
||||
for (auto& accumulator: _accumulators) {
|
||||
accumulator.clearAndClean();
|
||||
}
|
||||
|
||||
_accumulators.clear();
|
||||
if (skeleton) {
|
||||
initConstraints();
|
||||
} else {
|
||||
|
|
|
@ -31,20 +31,27 @@ public:
|
|||
void loadPoses(const AnimPoseVec& poses);
|
||||
void computeAbsolutePoses(AnimPoseVec& absolutePoses) const;
|
||||
|
||||
void setTargetVars(const QString& jointName, const QString& positionVar, const QString& rotationVar);
|
||||
void setTargetVars(const QString& jointName, const QString& positionVar, const QString& rotationVar, const QString& typeVar);
|
||||
|
||||
virtual const AnimPoseVec& evaluate(const AnimVariantMap& animVars, float dt, AnimNode::Triggers& triggersOut) override;
|
||||
virtual const AnimPoseVec& overlay(const AnimVariantMap& animVars, float dt, Triggers& triggersOut, const AnimPoseVec& underPoses) override;
|
||||
|
||||
protected:
|
||||
struct IKTarget {
|
||||
enum class Type {
|
||||
RotationAndPosition,
|
||||
RotationOnly
|
||||
};
|
||||
AnimPose pose;
|
||||
int index;
|
||||
int rootIndex;
|
||||
Type type = Type::RotationAndPosition;
|
||||
|
||||
void setType(const QString& typeVar) { type = ((typeVar == "RotationOnly") ? Type::RotationOnly : Type::RotationAndPosition); }
|
||||
};
|
||||
|
||||
void computeTargets(const AnimVariantMap& animVars, std::vector<IKTarget>& targets);
|
||||
void solveWithCyclicCoordinateDescent(std::vector<IKTarget>& targets);
|
||||
void computeTargets(const AnimVariantMap& animVars, std::vector<IKTarget>& targets, const AnimPoseVec& underPoses);
|
||||
void solveWithCyclicCoordinateDescent(const std::vector<IKTarget>& targets);
|
||||
virtual void setSkeletonInternal(AnimSkeleton::ConstPointer skeleton);
|
||||
|
||||
// for AnimDebugDraw rendering
|
||||
|
@ -55,15 +62,20 @@ protected:
|
|||
void initConstraints();
|
||||
|
||||
struct IKTargetVar {
|
||||
IKTargetVar(const QString& jointNameIn, const QString& positionVarIn, const QString& rotationVarIn) :
|
||||
IKTargetVar(const QString& jointNameIn,
|
||||
const QString& positionVarIn,
|
||||
const QString& rotationVarIn,
|
||||
const QString& typeVarIn) :
|
||||
positionVar(positionVarIn),
|
||||
rotationVar(rotationVarIn),
|
||||
typeVar(typeVarIn),
|
||||
jointName(jointNameIn),
|
||||
jointIndex(-1),
|
||||
rootIndex(-1) {}
|
||||
|
||||
QString positionVar;
|
||||
QString rotationVar;
|
||||
QString typeVar;
|
||||
QString jointName;
|
||||
int jointIndex; // cached joint index
|
||||
int rootIndex; // cached root index
|
||||
|
|
|
@ -29,6 +29,12 @@ const AnimPoseVec& AnimManipulator::evaluate(const AnimVariantMap& animVars, flo
|
|||
const AnimPoseVec& AnimManipulator::overlay(const AnimVariantMap& animVars, float dt, Triggers& triggersOut, const AnimPoseVec& underPoses) {
|
||||
_alpha = animVars.lookup(_alphaVar, _alpha);
|
||||
|
||||
_poses = underPoses;
|
||||
|
||||
if (underPoses.size() == 0) {
|
||||
return _poses;
|
||||
}
|
||||
|
||||
for (auto& jointVar : _jointVars) {
|
||||
if (!jointVar.hasPerformedJointLookup) {
|
||||
jointVar.jointIndex = _skeleton->nameToJointIndex(jointVar.jointName);
|
||||
|
|
|
@ -61,7 +61,7 @@ public:
|
|||
// hierarchy accessors
|
||||
void addChild(Pointer child) { _children.push_back(child); }
|
||||
void removeChild(Pointer child);
|
||||
|
||||
|
||||
Pointer getChild(int i) const;
|
||||
int getChildCount() const { return (int)_children.size(); }
|
||||
|
||||
|
|
|
@ -342,8 +342,9 @@ AnimNode::Pointer loadInverseKinematicsNode(const QJsonObject& jsonObj, const QS
|
|||
READ_STRING(jointName, targetObj, id, jsonUrl, nullptr);
|
||||
READ_STRING(positionVar, targetObj, id, jsonUrl, nullptr);
|
||||
READ_STRING(rotationVar, targetObj, id, jsonUrl, nullptr);
|
||||
READ_OPTIONAL_STRING(typeVar, targetObj);
|
||||
|
||||
node->setTargetVars(jointName, positionVar, rotationVar);
|
||||
node->setTargetVars(jointName, positionVar, rotationVar, typeVar);
|
||||
};
|
||||
|
||||
return node;
|
||||
|
|
|
@ -51,8 +51,8 @@ const AnimPoseVec& AnimOverlay::evaluate(const AnimVariantMap& animVars, float d
|
|||
_alpha = animVars.lookup(_alphaVar, _alpha);
|
||||
|
||||
if (_children.size() >= 2) {
|
||||
auto underPoses = _children[1]->evaluate(animVars, dt, triggersOut);
|
||||
auto overPoses = _children[0]->overlay(animVars, dt, triggersOut, underPoses);
|
||||
auto& underPoses = _children[1]->evaluate(animVars, dt, triggersOut);
|
||||
auto& overPoses = _children[0]->overlay(animVars, dt, triggersOut, underPoses);
|
||||
|
||||
if (underPoses.size() > 0 && underPoses.size() == overPoses.size()) {
|
||||
_poses.resize(underPoses.size());
|
||||
|
|
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue