History

Merge branch 'master' of https://github.com/highfidelity/hifi

Stephen Birarda committed 10 years ago

Commit 27991232 parents 74d1685 a133dfa86 files · +3438 −836Browse files

Unified · Split

86 files
  1. CMakeLists.txt +11 −5
  2. cmake/externals/qxmpp/CMakeLists.txt +0 −77
  3. examples/acScripts/triggeredRecordingOnAC.js +72 −0
  4. examples/controllers/getHUDLookAtPositionTest.js +54 −0
  5. examples/controllers/handControllerGrab.js +390 −71
  6. examples/controllers/reticleHandRotationTest.js +178 −27
  7. examples/edit.js +30 −17
  8. examples/flowArts/arcBall/arcBall.js +145 −0
  9. examples/flowArts/arcBall/arcBallEntityScript.js +155 −0
  10. examples/flowArts/flowArtsHutSpawner.js +91 −0
  11. examples/flowArts/lightBall/lightBall.js +145 −0
  12. examples/flowArts/lightSaber/lightSaber.js +67 −0
  13. examples/flowArts/lightSaber/lightSaberEntityScript.js +116 −0
  14. examples/flowArts/lightTrails.js +191 −0
  15. examples/flowArts/raveStick/raveStick.js +90 −0
  16. examples/flowArts/raveStick/raveStickEntityScript.js +141 −0
  17. examples/painting/closePaint.js +4 −1
  18. examples/painting/whiteboard/whiteboardEntityScript.js +3 −0
  19. examples/painting/whiteboard/whiteboardSpawner.js +1 −1
  20. examples/rayPickingFilterExample.js +73 −0
  21. examples/toybox/bow/bow.js +2 −2
  22. examples/toybox/ping_pong_gun/createPingPongGun.js +8 −0
  23. examples/utilities/tools/cookies.js +4 −2
  24. examples/utilities/tools/renderEngineDebug.js +48 −64
  25. examples/winterSmashUp/targetPractice/shooterPlatform.js +73 −0
  26. examples/winterSmashUp/targetPractice/startTargetPractice.js +93 −0
  27. examples/winterSmashUp/targetPractice/targetPracticeGame.js +227 −0
  28. interface/resources/qml/QmlWebWindow.qml +17 −6
  29. interface/src/Application.cpp +13 −81
  30. interface/src/Application.h +4 −3
  31. libraries/audio/src/AudioInjector.cpp +0 −1
  32. libraries/entities-renderer/src/EntityTreeRenderer.cpp +36 −30
  33. libraries/entities-renderer/src/EntityTreeRenderer.h +2 −1
  34. libraries/entities-renderer/src/RenderableParticleEffectEntityItem.cpp +5 −2
  35. libraries/entities-renderer/src/RenderablePolyLineEntityItem.cpp +29 −34
  36. libraries/entities-renderer/src/RenderablePolyLineEntityItem.h +3 −0
  37. libraries/entities-renderer/src/RenderableProceduralItemShader.h +2 −4
  38. libraries/entities-renderer/src/paintStroke.slf +8 −7
  39. libraries/entities-renderer/src/paintStroke.slv +1 −0
  40. libraries/entities/src/EntityItemProperties.cpp +8 −8
  41. libraries/entities/src/EntityItemProperties.h +1 −1
  42. libraries/entities/src/EntityPropertyFlags.h +1 −1
  43. libraries/entities/src/EntityScriptingInterface.cpp +10 −8
  44. libraries/entities/src/EntityScriptingInterface.h +3 −3
  45. libraries/entities/src/EntityTree.cpp +4 −3
  46. libraries/entities/src/EntityTree.h +1 −0
  47. libraries/entities/src/EntityTreeElement.cpp +5 −5
  48. libraries/entities/src/EntityTreeElement.h +3 −1
  49. libraries/entities/src/ParticleEffectEntityItem.cpp +25 −15
  50. libraries/entities/src/ParticleEffectEntityItem.h +5 −5
  51. libraries/entities/src/PolyLineEntityItem.cpp +2 −0
  52. libraries/entities/src/PolyLineEntityItem.h +4 −2
  53. libraries/model/src/model/Stage.cpp +15 −0
  54. libraries/model/src/model/Stage.h +3 −0
  55. libraries/networking/src/AbstractUriHandler.h +19 −0
  56. libraries/octree/src/Octree.cpp +1 −1
  57. libraries/render-utils/src/DebugDeferredBuffer.cpp +1 −1
  58. libraries/render-utils/src/DeferredBufferWrite.slh +7 −10
  59. libraries/render-utils/src/DeferredLightingEffect.cpp +0 −4
  60. libraries/render-utils/src/MeshPartPayload.cpp +3 −7
  61. libraries/render-utils/src/ModelRender.cpp +2 −13
  62. libraries/render-utils/src/ModelRender.h +3 −5
  63. libraries/render-utils/src/RenderDeferredTask.cpp +72 −13
  64. libraries/render-utils/src/RenderDeferredTask.h +7 −0
  65. libraries/render-utils/src/RenderScriptingInterface.cpp +22 −11
  66. libraries/render-utils/src/RenderScriptingInterface.h +71 −51
  67. libraries/render-utils/src/SkyFromSpace.slf +2 −1
  68. libraries/render-utils/src/simple.slf +2 −2
  69. libraries/render-utils/src/simple_textured.slf +1 −1
  70. libraries/render-utils/src/simple_textured_emisive.slf +1 −1
  71. libraries/render/src/render/Engine.cpp +7 −3
  72. libraries/render/src/render/Engine.h +13 −14
  73. libraries/script-engine/src/SceneScriptingInterface.cpp +60 −45
  74. libraries/script-engine/src/SceneScriptingInterface.h +118 −41
  75. libraries/shared/src/RenderArgs.h +2 −2
  76. libraries/ui/src/QmlWebWindowClass.cpp +52 −8
  77. libraries/ui/src/QmlWebWindowClass.h +2 −1
  78. plugins/hifiSixense/src/SixenseManager.cpp +22 −1
  79. plugins/hifiSixense/src/SixenseManager.h +2 −0
  80. plugins/hifiSixense/src/SixenseSupportOSX.cpp +3 −0
  81. plugins/oculusLegacy/CMakeLists.txt +1 −2
  82. plugins/oculusLegacy/src/OculusLegacyDisplayPlugin.cpp +60 −91
  83. plugins/oculusLegacy/src/OculusLegacyDisplayPlugin.h +13 −15
  84. tests/gpu-test/src/unlit.slf +1 −1
  85. unpublishedScripts/hiddenEntityReset.js +122 −1
  86. unpublishedScripts/masterReset.js +124 −2
CMakeLists.txt+11−5
@@ -197,6 +197,10 @@ if (WIN32) · 196 unmodified lines
197 add_paths_to_fixup_libs("${QT_DIR}/bin")197 add_paths_to_fixup_libs("${QT_DIR}/bin")
198endif ()198endif ()
199 199
200if (NOT DEFINED SERVER_ONLY)
201 set(SERVER_ONLY 0)
202endif()
203
200# add subdirectories for all targets204# add subdirectories for all targets
201if (NOT ANDROID)205if (NOT ANDROID)
202 add_subdirectory(assignment-client)206 add_subdirectory(assignment-client)
@@ -205,14 +209,16 @@ if (NOT ANDROID) · 2 unmodified lines
205 set_target_properties(domain-server PROPERTIES FOLDER "Apps")209 set_target_properties(domain-server PROPERTIES FOLDER "Apps")
206 add_subdirectory(ice-server)210 add_subdirectory(ice-server)
207 set_target_properties(ice-server PROPERTIES FOLDER "Apps")211 set_target_properties(ice-server PROPERTIES FOLDER "Apps")
208 add_subdirectory(interface)
209 set_target_properties(interface PROPERTIES FOLDER "Apps")
210 add_subdirectory(stack-manager)212 add_subdirectory(stack-manager)
211 set_target_properties(stack-manager PROPERTIES FOLDER "Apps")213 set_target_properties(stack-manager PROPERTIES FOLDER "Apps")
212 add_subdirectory(tests)214 if (NOT SERVER_ONLY)
213 add_subdirectory(plugins)215 add_subdirectory(interface)
216 set_target_properties(interface PROPERTIES FOLDER "Apps")
217 add_subdirectory(tests)
218 add_subdirectory(plugins)
219 endif()
214 add_subdirectory(tools)220 add_subdirectory(tools)
215endif ()221endif()
216 222
217if (ANDROID OR DESKTOP_GVR)223if (ANDROID OR DESKTOP_GVR)
218 add_subdirectory(gvr-interface)224 add_subdirectory(gvr-interface)
cmake/externals/qxmpp/CMakeLists.txt+0−77
@@ -1,77 +0,0 @@
1set(EXTERNAL_NAME qxmpp)
2
3# we need to find qmake inside QT_DIR
4find_program(QMAKE_COMMAND NAME qmake PATHS ${QT_DIR}/bin $ENV{QTTOOLDIR} NO_DEFAULT_PATH)
5
6if (NOT QMAKE_COMMAND)
7 message(FATAL_ERROR "Could not find qmake. Qxmpp cannot be compiled without qmake.")
8endif ()
9
10if (ANDROID)
11 set(ANDROID_CMAKE_ARGS "-DCMAKE_TOOLCHAIN_FILE=${CMAKE_TOOLCHAIN_FILE}" "-DANDROID_NATIVE_API_LEVEL=19")
12endif ()
13
14if (WIN32)
15 find_program(PLATFORM_BUILD_COMMAND nmake PATHS "C:/Program Files (x86)/Microsoft Visual Studio 12.0/VC/bin")
16
17 if (NOT PLATFORM_BUILD_COMMAND)
18 message(FATAL_ERROR "You asked CMake to grap QXmpp and build it, but nmake was not found. Please make sure the folder containing nmake.exe is in your PATH.")
19 endif ()
20else ()
21 find_program(PLATFORM_BUILD_COMMAND make)
22endif ()
23
24include(ExternalProject)
25ExternalProject_Add(
26 ${EXTERNAL_NAME}
27 URL http://qxmpp.googlecode.com/files/qxmpp-0.7.6.tar.gz
28 URL_MD5 ee45a97313306ded2ff0f6618a3ed1e1
29 BUILD_IN_SOURCE 1
30 PATCH_COMMAND patch -p2 -t -N --verbose < ${CMAKE_CURRENT_SOURCE_DIR}/qxmpp.patch
31 CONFIGURE_COMMAND ${QMAKE_COMMAND} PREFIX=<INSTALL_DIR>
32 BUILD_COMMAND ${PLATFORM_BUILD_COMMAND}
33 INSTALL_COMMAND ${PLATFORM_BUILD_COMMAND} install
34 LOG_DOWNLOAD 1
35 LOG_CONFIGURE 1
36 LOG_BUILD 1
37)
38
39# Hide this external target (for ide users)
40set_target_properties(${EXTERNAL_NAME} PROPERTIES FOLDER "hidden/externals")
41
42ExternalProject_Get_Property(${EXTERNAL_NAME} INSTALL_DIR)
43
44if (CMAKE_GENERATOR STREQUAL Xcode)
45 find_program(DITTO_COMMAND ditto)
46
47 ExternalProject_Add_Step(
48 ${EXTERNAL_NAME}
49 copy-from-xcode-install
50 COMMENT "Copying from /tmp/hifi.dst${INSTALL_DIR} to move install to proper location"
51 COMMAND ${DITTO_COMMAND} /tmp/hifi.dst${INSTALL_DIR} ${INSTALL_DIR}
52 DEPENDEES install
53 LOG 1
54 )
55endif ()
56
57string(TOUPPER ${EXTERNAL_NAME} EXTERNAL_NAME_UPPER)
58set(${EXTERNAL_NAME_UPPER}_INCLUDE_DIRS ${INSTALL_DIR}/include CACHE FILEPATH "Path to Qxmpp include directory")
59
60set(_LIB_DIR ${INSTALL_DIR}/lib)
61
62if (WIN32)
63 set(_LIB_EXT "0.lib")
64
65 set(${EXTERNAL_NAME_UPPER}_DLL_PATH ${_LIB_DIR} CACHE PATH "Location of QXmpp DLL")
66else ()
67 if (APPLE)
68 set(_LIB_EXT ".dylib")
69 else ()
70 set(_LIB_EXT ".so")
71 endif ()
72
73 set(_LIB_PREFIX "lib")
74endif ()
75
76set(${EXTERNAL_NAME_UPPER}_LIBRARY_RELEASE ${_LIB_DIR}/${_LIB_PREFIX}qxmpp${_LIB_EXT} CACHE FILEPATH "Path to QXmpp release library")
77set(${EXTERNAL_NAME_UPPER}_LIBRARY_DEBUG "" CACHE FILEPATH "Path to QXmpp debug library")
examples/acScripts/triggeredRecordingOnAC.js+72−0
@@ -0,0 +1,72 @@
1//
2// triggeredRecordingOnAC.js
3// examples/acScripts
4//
5// Created by Thijs Wenker on 12/21/15.
6// Copyright 2015 High Fidelity, Inc.
7//
8// This is the triggered rocording script used in the winterSmashUp target practice game.
9// Change the CLIP_URL to your asset,
10// the RECORDING_CHANNEL and RECORDING_CHANNEL_MESSAGE are used to trigger it i.e.:
11// Messages.sendMessage("PlayBackOnAssignment", "BowShootingGameWelcome");
12//
13// Distributed under the Apache License, Version 2.0.
14// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
15//
16
17const CLIP_URL = "atp:3fbe82f2153c443f12f9a2b14ce2d7fa2fff81977263746d9e0885ea5aabed62.hfr";
18
19const RECORDING_CHANNEL = 'PlayBackOnAssignment';
20const RECORDING_CHANNEL_MESSAGE = 'BowShootingGameWelcome'; // For each different assignment add a different message here.
21const PLAY_FROM_CURRENT_LOCATION = true;
22const USE_DISPLAY_NAME = true;
23const USE_ATTACHMENTS = true;
24const USE_AVATAR_MODEL = true;
25const AUDIO_OFFSET = 0.0;
26const STARTING_TIME = 0.0;
27const COOLDOWN_PERIOD = 0; // The period in ms that no animations can be played after one has been played already
28
29var isPlaying = false;
30var isPlayable = true;
31
32var playRecording = function() {
33 if (!isPlayable || isPlaying) {
34 return;
35 }
36 Agent.isAvatar = true;
37 Recording.setPlayFromCurrentLocation(PLAY_FROM_CURRENT_LOCATION);
38 Recording.setPlayerUseDisplayName(USE_DISPLAY_NAME);
39 Recording.setPlayerUseAttachments(USE_ATTACHMENTS);
40 Recording.setPlayerUseHeadModel(false);
41 Recording.setPlayerUseSkeletonModel(USE_AVATAR_MODEL);
42 Recording.setPlayerLoop(false);
43 Recording.setPlayerTime(STARTING_TIME);
44 Recording.setPlayerAudioOffset(AUDIO_OFFSET);
45 Recording.loadRecording(CLIP_URL);
46 Recording.startPlaying();
47 isPlaying = true;
48 isPlayable = false; // Set this true again after the cooldown period
49};
50
51Script.update.connect(function(deltaTime) {
52 if (isPlaying && !Recording.isPlaying()) {
53 print('Reached the end of the recording. Resetting.');
54 isPlaying = false;
55 Agent.isAvatar = false;
56 if (COOLDOWN_PERIOD === 0) {
57 isPlayable = true;
58 return;
59 }
60 Script.setTimeout(function () {
61 isPlayable;
62 }, COOLDOWN_PERIOD);
63 }
64});
65
66Messages.subscribe(RECORDING_CHANNEL);
67
68Messages.messageReceived.connect(function (channel, message, senderID) {
69 if (channel === RECORDING_CHANNEL && message === RECORDING_CHANNEL_MESSAGE) {
70 playRecording();
71 }
72});
examples/controllers/getHUDLookAtPositionTest.js+54−0
@@ -0,0 +1,54 @@
1//
2// getHUDLookAtPositionTest.js
3// examples/controllers
4//
5// Created by Brad Hefta-Gaub on 2015/12/15
6// Copyright 2015 High Fidelity, Inc.
7//
8// Distributed under the Apache License, Version 2.0.
9// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
10//
11
12
13// This script demonstrates the testing of the HMD.getHUDLookAtPosition--() functions.
14// If these functions are working correctly, we'd expect to see a 3D cube and a 2D square
15// follow around the center of the HMD view.
16
17var cubePosition = { x: 0, y: 0, z: 0 };
18var cubeSize = 0.03;
19var cube = Overlays.addOverlay("cube", {
20 position: cubePosition,
21 size: cubeSize,
22 color: { red: 255, green: 0, blue: 0},
23 alpha: 1,
24 solid: false
25 });
26
27var square = Overlays.addOverlay("text", {
28 x: 0,
29 y: 0,
30 width: 20,
31 height: 20,
32 color: { red: 255, green: 255, blue: 0},
33 backgroundColor: { red: 255, green: 255, blue: 0},
34 alpha: 1
35 });
36
37
38Script.update.connect(function(deltaTime) {
39 if (!HMD.active) {
40 return;
41 }
42 var lookAt3D = HMD.getHUDLookAtPosition3D();
43 Overlays.editOverlay(cube, { position: lookAt3D });
44
45 var lookAt2D = HMD.getHUDLookAtPosition2D();
46 Overlays.editOverlay(square, { x: lookAt2D.x, y: lookAt2D.y });
47});
48
49Script.scriptEnding.connect(function(){
50 Overlays.deleteOverlay(cube);
51 Overlays.deleteOverlay(square);
52});
53
54
examples/controllers/handControllerGrab.js+390−71
@@ -1,5 +1,4 @@
1// handControllerGrab.js1// handControllerGrab.js
2// examples
3//2//
4// Created by Eric Levin on 9/2/153// Created by Eric Levin on 9/2/15
5// Additions by James B. Pollack @imgntn on 9/24/20154// Additions by James B. Pollack @imgntn on 9/24/2015
@@ -7,6 +6,7 @@ · 1 unmodified line
7// Copyright 2015 High Fidelity, Inc.6// Copyright 2015 High Fidelity, Inc.
8//7//
9// Grabs physically moveable entities with hydra-like controllers; it works for either near or far objects.8// Grabs physically moveable entities with hydra-like controllers; it works for either near or far objects.
9// Also supports touch and equipping objects.
10//10//
11// Distributed under the Apache License, Version 2.0.11// Distributed under the Apache License, Version 2.0.
12// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html12// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
@@ -14,7 +14,6 @@ · 1 unmodified line
14 14
15Script.include("../libraries/utils.js");15Script.include("../libraries/utils.js");
16 16
17
18//17//
19// add lines where the hand ray picking is happening18// add lines where the hand ray picking is happening
20//19//
@@ -54,6 +53,7 @@ var LINE_ENTITY_DIMENSIONS = { · 33 unmodified lines
54 y: 1000,53 y: 1000,
55 z: 100054 z: 1000
56};55};
56
57var LINE_LENGTH = 500;57var LINE_LENGTH = 500;
58var PICK_MAX_DISTANCE = 500; // max length of pick-ray58var PICK_MAX_DISTANCE = 500; // max length of pick-ray
59 59
@@ -116,6 +116,17 @@ var DEFAULT_GRABBABLE_DATA = { · 56 unmodified lines
116 invertSolidWhileHeld: false116 invertSolidWhileHeld: false
117};117};
118 118
119//we've created various ways of visualizing looking for and moving distant objects
120var USE_ENTITY_LINES_FOR_SEARCHING = false;
121var USE_OVERLAY_LINES_FOR_SEARCHING = false;
122var USE_PARTICLE_BEAM_FOR_SEARCHING = true;
123
124var USE_ENTITY_LINES_FOR_MOVING = false;
125var USE_OVERLAY_LINES_FOR_MOVING = false;
126var USE_PARTICLE_BEAM_FOR_MOVING = true;
127
128var USE_SPOTLIGHT = false;
129var USE_POINTLIGHT = false;
119 130
120// states for the state machine131// states for the state machine
121var STATE_OFF = 0;132var STATE_OFF = 0;
@@ -137,6 +148,7 @@ var STATE_WAITING_FOR_BUMPER_RELEASE = 15; · 15 unmodified lines
137var STATE_EQUIP_SPRING = 16;148var STATE_EQUIP_SPRING = 16;
138 149
139 150
151
140function stateToName(state) {152function stateToName(state) {
141 switch (state) {153 switch (state) {
142 case STATE_OFF:154 case STATE_OFF:
@@ -218,6 +230,7 @@ function getSpatialOffsetPosition(hand, spatialKey) { · 75 unmodified lines
218}230}
219 231
220var yFlip = Quat.angleAxis(180, Vec3.UNIT_Y);232var yFlip = Quat.angleAxis(180, Vec3.UNIT_Y);
233
221function getSpatialOffsetRotation(hand, spatialKey) {234function getSpatialOffsetRotation(hand, spatialKey) {
222 var rotation = Quat.IDENTITY;235 var rotation = Quat.IDENTITY;
223 236
@@ -261,7 +274,13 @@ function MyController(hand) { · 37 unmodified lines
261 this.triggerValue = 0; // rolling average of trigger value274 this.triggerValue = 0; // rolling average of trigger value
262 this.rawTriggerValue = 0;275 this.rawTriggerValue = 0;
263 this.rawBumperValue = 0;276 this.rawBumperValue = 0;
277 //for visualizations
278 this.overlayLine = null;
279 this.particleBeam = null;
264 280
281 //for lights
282 this.spotlight = null;
283 this.pointlight = null;
265 this.overlayLine = null;284 this.overlayLine = null;
266 285
267 this.ignoreIK = false;286 this.ignoreIK = false;
@@ -329,7 +348,7 @@ function MyController(hand) { · 61 unmodified lines
329 print("STATE: " + stateToName(this.state) + " --> " + stateToName(newState) + ", hand: " + this.hand);348 print("STATE: " + stateToName(this.state) + " --> " + stateToName(newState) + ", hand: " + this.hand);
330 }349 }
331 this.state = newState;350 this.state = newState;
332 }351 };
333 352
334 this.debugLine = function(closePoint, farPoint, color) {353 this.debugLine = function(closePoint, farPoint, color) {
335 Entities.addEntity({354 Entities.addEntity({
@@ -349,7 +368,38 @@ function MyController(hand) { · 13 unmodified lines
349 }368 }
350 })369 })
351 });370 });
371 };
372
373 this.lineOn = function(closePoint, farPoint, color) {
374 // draw a line
375 if (this.pointer === null) {
376 this.pointer = Entities.addEntity({
377 type: "Line",
378 name: "grab pointer",
379 dimensions: LINE_ENTITY_DIMENSIONS,
380 visible: true,
381 position: closePoint,
382 linePoints: [ZERO_VEC, farPoint],
383 color: color,
384 lifetime: LIFETIME,
385 collisionsWillMove: false,
386 ignoreForCollisions: true,
387 userData: JSON.stringify({
388 grabbableKey: {
389 grabbable: false
352 }390 }
391 })
392 });
393 } else {
394 var age = Entities.getEntityProperties(this.pointer, "age").age;
395 this.pointer = Entities.editEntity(this.pointer, {
396 position: closePoint,
397 linePoints: [ZERO_VEC, farPoint],
398 color: color,
399 lifetime: age + LIFETIME
400 });
401 }
402 };
353 403
354 this.overlayLineOn = function(closePoint, farPoint, color) {404 this.overlayLineOn = function(closePoint, farPoint, color) {
355 if (this.overlayLine === null) {405 if (this.overlayLine === null) {
@@ -376,36 +426,209 @@ function MyController(hand) { · 20 unmodified lines
376 alpha: 1426 alpha: 1
377 });427 });
378 }428 }
429 };
430
431 this.handleParticleBeam = function(position, orientation, color) {
432
433 var rotation = Quat.angleAxis(0, {
434 x: 1,
435 y: 0,
436 z: 0
437 });
438
439 var finalRotation = Quat.multiply(orientation, rotation);
440 var lifespan = LINE_LENGTH / 10;
441 var speed = 5;
442 var spread = 2;
443 if (this.particleBeam === null) {
444 this.createParticleBeam(position, finalRotation, color, speed, spread, lifespan);
445 } else {
446 this.updateParticleBeam(position, finalRotation, color, speed, spread, lifespan);
379 }447 }
448 };
380 449
381 this.lineOn = function(closePoint, farPoint, color) {450 this.handleDistantParticleBeam = function(handPosition, objectPosition, color) {
382 // draw a line451
383 if (this.pointer === null) {452 var handToObject = Vec3.subtract(objectPosition, handPosition);
384 this.pointer = Entities.addEntity({453 var finalRotation = Quat.rotationBetween(Vec3.multiply(-1, Vec3.UP), handToObject);
385 type: "Line",454
386 name: "grab pointer",455 var distance = Vec3.distance(handPosition, objectPosition);
387 dimensions: LINE_ENTITY_DIMENSIONS,456 var speed = 5;
457 var spread = 0;
458
459 var lifespan = distance / speed;
460
461
462 if (this.particleBeam === null) {
463 this.createParticleBeam(objectPosition, finalRotation, color, speed, spread, lifespan);
464 } else {
465 this.updateParticleBeam(objectPosition, finalRotation, color, speed, spread, lifespan);
466 }
467 };
468
469 this.createParticleBeam = function(position, orientation, color, speed, spread, lifespan) {
470
471 var particleBeamProperties = {
472 type: "ParticleEffect",
473 isEmitting: true,
474 position: position,
475 visible: false,
476 "name": "Particle Beam",
477 "color": color,
478 "maxParticles": 2000,
479 "lifespan": lifespan,
480 "emitRate": 50,
481 "emitSpeed": speed,
482 "speedSpread": spread,
483 "emitOrientation": {
484 "x": -1,
485 "y": 0,
486 "z": 0,
487 "w": 1
488 },
489 "emitDimensions": {
490 "x": 0,
491 "y": 0,
492 "z": 0
493 },
494 "emitRadiusStart": 0.5,
495 "polarStart": 0,
496 "polarFinish": 0,
497 "azimuthStart": -3.1415927410125732,
498 "azimuthFinish": 3.1415927410125732,
499 "emitAcceleration": {
500 x: 0,
501 y: 0,
502 z: 0
503 },
504 "accelerationSpread": {
505 "x": 0,
506 "y": 0,
507 "z": 0
508 },
509 "particleRadius": 0.015,
510 "radiusSpread": 0.005,
511 // "radiusStart": 0.01,
512 // "radiusFinish": 0.01,
513 // "colorSpread": {
514 // "red": 0,
515 // "green": 0,
516 // "blue": 0
517 // },
518 // "colorStart": color,
519 // "colorFinish": color,
520 "alpha": 1,
521 "alphaSpread": 0,
522 "alphaStart": 1,
523 "alphaFinish": 1,
524 "additiveBlending": 0,
525 "textures": "https://hifi-content.s3.amazonaws.com/alan/dev/textures/grabsprite-3.png"
526 }
527
528 this.particleBeam = Entities.addEntity(particleBeamProperties);
529 };
530
531 this.updateParticleBeam = function(position, orientation, color, speed, spread, lifespan) {
532 Entities.editEntity(this.particleBeam, {
533 rotation: orientation,
534 position: position,
388 visible: true,535 visible: true,
389 position: closePoint,
390 linePoints: [ZERO_VEC, farPoint],
391 color: color,536 color: color,
392 lifetime: LIFETIME,537 emitSpeed: speed,
393 collisionsWillMove: false,538 speedSpread: spread,
394 ignoreForCollisions: true,539 lifespan: lifespan
395 userData: JSON.stringify({
396 grabbableKey: {
397 grabbable: false
398 }
399 })540 })
541
542 };
543
544 this.evalLightWorldTransform = function(modelPos, modelRot) {
545
546 var MODEL_LIGHT_POSITION = {
547 x: 0,
548 y: -0.3,
549 z: 0
550 };
551
552 var MODEL_LIGHT_ROTATION = Quat.angleAxis(-90, {
553 x: 1,
554 y: 0,
555 z: 0
400 });556 });
557
558 return {
559 p: Vec3.sum(modelPos, Vec3.multiplyQbyV(modelRot, MODEL_LIGHT_POSITION)),
560 q: Quat.multiply(modelRot, MODEL_LIGHT_ROTATION)
561 };
562 };
563
564 this.handleSpotlight = function(parentID, position) {
565 var LIFETIME = 100;
566
567 var modelProperties = Entities.getEntityProperties(parentID, ['position', 'rotation']);
568
569 var lightTransform = this.evalLightWorldTransform(modelProperties.position, modelProperties.rotation);
570 var lightProperties = {
571 type: "Light",
572 isSpotlight: true,
573 dimensions: {
574 x: 2,
575 y: 2,
576 z: 20
577 },
578 parentID: parentID,
579 color: {
580 red: 255,
581 green: 255,
582 blue: 255
583 },
584 intensity: 2,
585 exponent: 0.3,
586 cutoff: 20,
587 lifetime: LIFETIME,
588 position: lightTransform.p,
589 };
590
591 if (this.spotlight === null) {
592 this.spotlight = Entities.addEntity(lightProperties);
401 } else {593 } else {
402 var age = Entities.getEntityProperties(this.pointer, "age").age;594 Entities.editEntity(this.spotlight, {
403 this.pointer = Entities.editEntity(this.pointer, {595 //without this, this light would maintain rotation with its parent
404 position: closePoint,596 rotation: Quat.fromPitchYawRollDegrees(-90, 0, 0),
405 linePoints: [ZERO_VEC, farPoint],597 })
406 color: color,598 }
407 lifetime: age + LIFETIME599 };
408 });600
601 this.handlePointLight = function(parentID, position) {
602 var LIFETIME = 100;
603
604 var modelProperties = Entities.getEntityProperties(parentID, ['position', 'rotation']);
605 var lightTransform = this.evalLightWorldTransform(modelProperties.position, modelProperties.rotation);
606
607 var lightProperties = {
608 type: "Light",
609 isSpotlight: false,
610 dimensions: {
611 x: 2,
612 y: 2,
613 z: 20
614 },
615 parentID: parentID,
616 color: {
617 red: 255,
618 green: 255,
619 blue: 255
620 },
621 intensity: 2,
622 exponent: 0.3,
623 cutoff: 20,
624 lifetime: LIFETIME,
625 position: lightTransform.p,
626 };
627
628 if (this.pointlight === null) {
629 this.pointlight = Entities.addEntity(lightProperties);
630 } else {
631
409 }632 }
410 };633 };
411 634
@@ -423,6 +646,41 @@ function MyController(hand) { · 11 unmodified lines
423 this.overlayLine = null;646 this.overlayLine = null;
424 };647 };
425 648
649 this.particleBeamOff = function() {
650 if (this.particleBeam !== null) {
651 Entities.editEntity(this.particleBeam, {
652 visible: false
653 })
654 }
655 }
656
657 this.turnLightsOff = function() {
658 if (this.spotlight !== null) {
659 Entities.deleteEntity(this.spotlight);
660 this.spotlight = null;
661 }
662
663 if (this.pointlight !== null) {
664 Entities.deleteEntity(this.pointlight);
665 this.pointlight = null;
666 }
667 };
668
669
670 this.turnOffVisualizations = function() {
671 if (USE_ENTITY_LINES_FOR_SEARCHING === true || USE_ENTITY_LINES_FOR_MOVING === true) {
672 this.lineOff();
673 }
674
675 if (USE_OVERLAY_LINES_FOR_SEARCHING === true || USE_OVERLAY_LINES_FOR_MOVING === true) {
676 this.overlayLineOff();
677 }
678
679 if (USE_PARTICLE_BEAM_FOR_SEARCHING === true || USE_PARTICLE_BEAM_FOR_MOVING === true) {
680 this.particleBeamOff();
681 }
682 };
683
426 this.triggerPress = function(value) {684 this.triggerPress = function(value) {
427 _this.rawTriggerValue = value;685 _this.rawTriggerValue = value;
428 };686 };
@@ -431,7 +689,6 @@ function MyController(hand) { · 2 unmodified lines
431 _this.rawBumperValue = value;689 _this.rawBumperValue = value;
432 };690 };
433 691
434
435 this.updateSmoothedTrigger = function() {692 this.updateSmoothedTrigger = function() {
436 var triggerValue = this.rawTriggerValue;693 var triggerValue = this.rawTriggerValue;
437 // smooth out trigger value694 // smooth out trigger value
@@ -454,12 +711,11 @@ function MyController(hand) { · 16 unmodified lines
454 711
455 this.bumperSqueezed = function() {712 this.bumperSqueezed = function() {
456 return _this.rawBumperValue > BUMPER_ON_VALUE;713 return _this.rawBumperValue > BUMPER_ON_VALUE;
457 }714 };
458 715
459 this.bumperReleased = function() {716 this.bumperReleased = function() {
460 return _this.rawBumperValue < BUMPER_ON_VALUE;717 return _this.rawBumperValue < BUMPER_ON_VALUE;
461 }718 };
462
463 719
464 this.off = function() {720 this.off = function() {
465 if (this.triggerSmoothedSqueezed()) {721 if (this.triggerSmoothedSqueezed()) {
@@ -472,7 +728,7 @@ function MyController(hand) { · 6 unmodified lines
472 this.setState(STATE_EQUIP_SEARCHING);728 this.setState(STATE_EQUIP_SEARCHING);
473 return;729 return;
474 }730 }
475 }731 };
476 732
477 this.search = function() {733 this.search = function() {
478 this.grabbedEntity = null;734 this.grabbedEntity = null;
@@ -671,8 +927,19 @@ function MyController(hand) { · 192 unmodified lines
671 }927 }
672 }928 }
673 929
674 //this.lineOn(distantPickRay.origin, Vec3.multiply(distantPickRay.direction, LINE_LENGTH), NO_INTERSECT_COLOR);930 //search line visualizations
931 if (USE_ENTITY_LINES_FOR_SEARCHING === true) {
932 this.lineOn(distantPickRay.origin, Vec3.multiply(distantPickRay.direction, LINE_LENGTH), NO_INTERSECT_COLOR);
933 }
934
935 if (USE_OVERLAY_LINES_FOR_SEARCHING === true) {
675 this.overlayLineOn(distantPickRay.origin, Vec3.sum(distantPickRay.origin, Vec3.multiply(distantPickRay.direction, LINE_LENGTH)), NO_INTERSECT_COLOR);936 this.overlayLineOn(distantPickRay.origin, Vec3.sum(distantPickRay.origin, Vec3.multiply(distantPickRay.direction, LINE_LENGTH)), NO_INTERSECT_COLOR);
937 }
938
939 if (USE_PARTICLE_BEAM_FOR_SEARCHING === true) {
940 this.handleParticleBeam(distantPickRay.origin, this.getHandRotation(), NO_INTERSECT_COLOR);
941 }
942
676 };943 };
677 944
678 this.distanceHolding = function() {945 this.distanceHolding = function() {
@@ -725,7 +992,7 @@ function MyController(hand) { · 46 unmodified lines
725 this.currentAvatarPosition = MyAvatar.position;992 this.currentAvatarPosition = MyAvatar.position;
726 this.currentAvatarOrientation = MyAvatar.orientation;993 this.currentAvatarOrientation = MyAvatar.orientation;
727 994
728 this.overlayLineOff();995 this.turnOffVisualizations();
729 };996 };
730 997
731 this.continueDistanceHolding = function() {998 this.continueDistanceHolding = function() {
@@ -751,7 +1018,6 @@ function MyController(hand) { · 19 unmodified lines
751 return;1018 return;
752 }1019 }
753 1020
754 this.lineOn(handPosition, Vec3.subtract(grabbedProperties.position, handPosition), INTERSECT_COLOR);
755 1021
756 // the action was set up on a previous call. update the targets.1022 // the action was set up on a previous call. update the targets.
757 var radius = Vec3.distance(this.currentObjectPosition, handControllerPosition) *1023 var radius = Vec3.distance(this.currentObjectPosition, handControllerPosition) *
@@ -815,17 +1081,43 @@ function MyController(hand) { · 57 unmodified lines
815 this.currentObjectRotation = Quat.multiply(handChange, this.currentObjectRotation);1081 this.currentObjectRotation = Quat.multiply(handChange, this.currentObjectRotation);
816 1082
817 Entities.callEntityMethod(this.grabbedEntity, "continueDistantGrab");1083 Entities.callEntityMethod(this.grabbedEntity, "continueDistantGrab");
818
819 // mix in head motion1084 // mix in head motion
820 if (MOVE_WITH_HEAD) {1085 if (MOVE_WITH_HEAD) {
821 var objDistance = Vec3.length(objectToAvatar);1086 var objDistance = Vec3.length(objectToAvatar);
822 var before = Vec3.multiplyQbyV(this.currentCameraOrientation, { x: 0.0, y: 0.0, z: objDistance });1087 var before = Vec3.multiplyQbyV(this.currentCameraOrientation, {
823 var after = Vec3.multiplyQbyV(Camera.orientation, { x: 0.0, y: 0.0, z: objDistance });1088 x: 0.0,
1089 y: 0.0,
1090 z: objDistance
1091 });
1092 var after = Vec3.multiplyQbyV(Camera.orientation, {
1093 x: 0.0,
1094 y: 0.0,
1095 z: objDistance
1096 });
824 var change = Vec3.subtract(before, after);1097 var change = Vec3.subtract(before, after);
825 this.currentCameraOrientation = Camera.orientation;1098 this.currentCameraOrientation = Camera.orientation;
826 this.currentObjectPosition = Vec3.sum(this.currentObjectPosition, change);1099 this.currentObjectPosition = Vec3.sum(this.currentObjectPosition, change);
827 }1100 }
828 1101
1102
1103 //visualizations
1104 if (USE_ENTITY_LINES_FOR_MOVING === true) {
1105 this.lineOn(handPosition, Vec3.subtract(grabbedProperties.position, handPosition), INTERSECT_COLOR);
1106 }
1107 if (USE_OVERLAY_LINES_FOR_MOVING === true) {
1108 this.overlayLineOn(handPosition, grabbedProperties.position, INTERSECT_COLOR);
1109 }
1110 if (USE_PARTICLE_BEAM_FOR_MOVING === true) {
1111 this.handleDistantParticleBeam(handPosition, grabbedProperties.position, INTERSECT_COLOR)
1112 // this.handleDistantParticleBeam(handPosition, this.currentObjectPosition, INTERSECT_COLOR)
1113 }
1114 if (USE_POINTLIGHT === true) {
1115 this.handlePointLight(this.grabbedEntity);
1116 }
1117 if (USE_SPOTLIGHT === true) {
1118 this.handleSpotlight(this.grabbedEntity);
1119 }
1120
829 Entities.updateAction(this.grabbedEntity, this.actionID, {1121 Entities.updateAction(this.grabbedEntity, this.actionID, {
830 targetPosition: this.currentObjectPosition,1122 targetPosition: this.currentObjectPosition,
831 linearTimeScale: DISTANCE_HOLDING_ACTION_TIMEFRAME,1123 linearTimeScale: DISTANCE_HOLDING_ACTION_TIMEFRAME,
@@ -833,6 +1125,7 @@ function MyController(hand) { · 1 unmodified line
833 angularTimeScale: DISTANCE_HOLDING_ACTION_TIMEFRAME,1125 angularTimeScale: DISTANCE_HOLDING_ACTION_TIMEFRAME,
834 ttl: ACTION_TTL1126 ttl: ACTION_TTL
835 });1127 });
1128
836 this.actionTimeout = now + (ACTION_TTL * MSEC_PER_SEC);1129 this.actionTimeout = now + (ACTION_TTL * MSEC_PER_SEC);
837 };1130 };
838 1131
@@ -846,8 +1139,7 @@ function MyController(hand) { · 7 unmodified lines
846 return;1139 return;
847 }1140 }
848 1141
849 this.lineOff();1142 this.turnOffVisualizations();
850 this.overlayLineOff();
851 1143
852 var grabbedProperties = Entities.getEntityProperties(this.grabbedEntity, GRABBABLE_PROPERTIES);1144 var grabbedProperties = Entities.getEntityProperties(this.grabbedEntity, GRABBABLE_PROPERTIES);
853 this.activateEntity(this.grabbedEntity, grabbedProperties);1145 this.activateEntity(this.grabbedEntity, grabbedProperties);
@@ -861,20 +1153,25 @@ function MyController(hand) { · 7 unmodified lines
861 var handPosition = this.getHandPosition();1153 var handPosition = this.getHandPosition();
862 1154
863 var grabbableData = getEntityCustomData(GRABBABLE_DATA_KEY, this.grabbedEntity, DEFAULT_GRABBABLE_DATA);1155 var grabbableData = getEntityCustomData(GRABBABLE_DATA_KEY, this.grabbedEntity, DEFAULT_GRABBABLE_DATA);
864 1156 var objectRotation = grabbedProperties.rotation;
1157 var currentObjectPosition = grabbedProperties.position;
1158 var offset = Vec3.subtract(currentObjectPosition, handPosition);
865 if (this.state != STATE_NEAR_GRABBING && grabbableData.spatialKey) {1159 if (this.state != STATE_NEAR_GRABBING && grabbableData.spatialKey) {
866 // if an object is "equipped" and has a spatialKey, use it.1160 // if an object is "equipped" and has a spatialKey, use it.
867 this.ignoreIK = grabbableData.spatialKey.ignoreIK ? grabbableData.spatialKey.ignoreIK : false;1161 this.ignoreIK = grabbableData.spatialKey.ignoreIK ? grabbableData.spatialKey.ignoreIK : false;
1162 if (grabbableData.spatialKey.relativePosition) {
868 this.offsetPosition = getSpatialOffsetPosition(this.hand, grabbableData.spatialKey);1163 this.offsetPosition = getSpatialOffsetPosition(this.hand, grabbableData.spatialKey);
1164 } else {
1165 this.offsetPosition = Vec3.multiplyQbyV(Quat.inverse(Quat.multiply(handRotation, this.offsetRotation)), offset);
1166 }
1167 if (grabbableData.spatialKey.relativeRotation) {
869 this.offsetRotation = getSpatialOffsetRotation(this.hand, grabbableData.spatialKey);1168 this.offsetRotation = getSpatialOffsetRotation(this.hand, grabbableData.spatialKey);
1169 } else {
1170 this.offsetRotation = Quat.multiply(Quat.inverse(handRotation), objectRotation);
1171 }
870 } else {1172 } else {
871 this.ignoreIK = false;1173 this.ignoreIK = false;
872
873 var objectRotation = grabbedProperties.rotation;
874 this.offsetRotation = Quat.multiply(Quat.inverse(handRotation), objectRotation);1174 this.offsetRotation = Quat.multiply(Quat.inverse(handRotation), objectRotation);
875
876 var currentObjectPosition = grabbedProperties.position;
877 var offset = Vec3.subtract(currentObjectPosition, handPosition);
878 this.offsetPosition = Vec3.multiplyQbyV(Quat.inverse(Quat.multiply(handRotation, this.offsetRotation)), offset);1175 this.offsetPosition = Vec3.multiplyQbyV(Quat.inverse(Quat.multiply(handRotation, this.offsetRotation)), offset);
879 }1176 }
880 1177
@@ -984,13 +1281,12 @@ function MyController(hand) { · 103 unmodified lines
984 Entities.callEntityMethod(this.grabbedEntity, "releaseGrab");1281 Entities.callEntityMethod(this.grabbedEntity, "releaseGrab");
985 Entities.callEntityMethod(this.grabbedEntity, "unequip");1282 Entities.callEntityMethod(this.grabbedEntity, "unequip");
986 this.endHandGrasp();1283 this.endHandGrasp();
987
988 }1284 }
989 };1285 };
990 1286
991 this.pullTowardEquipPosition = function() {1287 this.pullTowardEquipPosition = function() {
992 this.lineOff();1288
993 this.overlayLineOff();1289 this.turnOffVisualizations();
994 1290
995 var grabbedProperties = Entities.getEntityProperties(this.grabbedEntity, GRABBABLE_PROPERTIES);1291 var grabbedProperties = Entities.getEntityProperties(this.grabbedEntity, GRABBABLE_PROPERTIES);
996 var grabbableData = getEntityCustomData(GRABBABLE_DATA_KEY, this.grabbedEntity, DEFAULT_GRABBABLE_DATA);1292 var grabbableData = getEntityCustomData(GRABBABLE_DATA_KEY, this.grabbedEntity, DEFAULT_GRABBABLE_DATA);
@@ -1108,11 +1404,15 @@ function MyController(hand) { · 111 unmodified lines
1108 }1404 }
1109 }1405 }
1110 1406
1407 if (USE_ENTITY_LINES_FOR_MOVING === true) {
1111 this.lineOn(pickRay.origin, Vec3.multiply(pickRay.direction, LINE_LENGTH), NO_INTERSECT_COLOR);1408 this.lineOn(pickRay.origin, Vec3.multiply(pickRay.direction, LINE_LENGTH), NO_INTERSECT_COLOR);
1409 }
1410
1112 Entities.callEntityMethod(this.grabbedEntity, "continueFarTrigger");1411 Entities.callEntityMethod(this.grabbedEntity, "continueFarTrigger");
1113 };1412 };
1114 1413
1115 _this.allTouchedIDs = {};1414 _this.allTouchedIDs = {};
1415
1116 this.touchTest = function() {1416 this.touchTest = function() {
1117 var maxDistance = 0.05;1417 var maxDistance = 0.05;
1118 var leftHandPosition = MyAvatar.getLeftPalmPosition();1418 var leftHandPosition = MyAvatar.getLeftPalmPosition();
@@ -1181,8 +1481,9 @@ function MyController(hand) { · 62 unmodified lines
1181 1481
1182 this.release = function() {1482 this.release = function() {
1183 1483
1184 this.lineOff();1484 this.turnLightsOff();
1185 this.overlayLineOff();1485 this.turnOffVisualizations();
1486
1186 if (this.grabbedEntity !== null) {1487 if (this.grabbedEntity !== null) {
1187 if (this.actionID !== null) {1488 if (this.actionID !== null) {
1188 Entities.deleteAction(this.grabbedEntity, this.actionID);1489 Entities.deleteAction(this.grabbedEntity, this.actionID);
@@ -1199,6 +1500,9 @@ function MyController(hand) { · 10 unmodified lines
1199 this.cleanup = function() {1500 this.cleanup = function() {
1200 this.release();1501 this.release();
1201 this.endHandGrasp();1502 this.endHandGrasp();
1503 Entities.deleteEntity(this.particleBeam);
1504 Entities.deleteEntity(this.spotLight);
1505 Entities.deleteEntity(this.pointLight);
1202 };1506 };
1203 1507
1204 this.activateEntity = function(entityID, grabbedProperties) {1508 this.activateEntity = function(entityID, grabbedProperties) {
@@ -1269,27 +1573,34 @@ function MyController(hand) { · 64 unmodified lines
1269 }1573 }
1270 //return an object with our updated settings1574 //return an object with our updated settings
1271 return result;1575 return result;
1272 }1576 };
1273 1577
1274 this.graspHandler = null1578 this.graspHandler = null
1579
1275 this.startHandGrasp = function() {1580 this.startHandGrasp = function() {
1276 if (this.hand === RIGHT_HAND) {1581 if (this.hand === RIGHT_HAND) {
1277 this.graspHandler = MyAvatar.addAnimationStateHandler(this.graspHand, ['isRightHandGrab']);1582 this.graspHandler = MyAvatar.addAnimationStateHandler(this.graspHand, ['isRightHandGrab']);
1278 } else if (this.hand === LEFT_HAND) {1583 } else if (this.hand === LEFT_HAND) {
1279 this.graspHandler = MyAvatar.addAnimationStateHandler(this.graspHand, ['isLeftHandGrab']);1584 this.graspHandler = MyAvatar.addAnimationStateHandler(this.graspHand, ['isLeftHandGrab']);
1280 }1585 }
1281 }1586 };
1282 1587
1283 this.endHandGrasp = function() {1588 this.endHandGrasp = function() {
1284 // Tell the animation system we don't need any more callbacks.1589 // Tell the animation system we don't need any more callbacks.
1285 MyAvatar.removeAnimationStateHandler(this.graspHandler);1590 MyAvatar.removeAnimationStateHandler(this.graspHandler);
1286 }1591 };
1287 1592
1288}1593};
1289 1594
1290var rightController = new MyController(RIGHT_HAND);1595var rightController = new MyController(RIGHT_HAND);
1291var leftController = new MyController(LEFT_HAND);1596var leftController = new MyController(LEFT_HAND);
1292 1597
1598//preload the particle beams so that they are full length when you start searching
1599if (USE_PARTICLE_BEAM_FOR_SEARCHING === true || USE_PARTICLE_BEAM_FOR_MOVING === true) {
1600 rightController.createParticleBeam();
1601 leftController.createParticleBeam();
1602}
1603
1293var MAPPING_NAME = "com.highfidelity.handControllerGrab";1604var MAPPING_NAME = "com.highfidelity.handControllerGrab";
1294 1605
1295var mapping = Controller.newMapping(MAPPING_NAME);1606var mapping = Controller.newMapping(MAPPING_NAME);
@@ -1301,39 +1612,47 @@ mapping.from([Controller.Standard.LB]).peek().to(leftController.bumperPress); · 5 unmodified lines
1301 1612
1302Controller.enableMapping(MAPPING_NAME);1613Controller.enableMapping(MAPPING_NAME);
1303 1614
1615//the section below allows the grab script to listen for messages that disable either one or both hands. useful for two handed items
1304var handToDisable = 'none';1616var handToDisable = 'none';
1305 1617
1306function update() {1618function update() {
1307 if (handToDisable !== LEFT_HAND && handToDisable!=='both') {1619 if (handToDisable !== LEFT_HAND && handToDisable!=='both') {
1308 leftController.update();1620 leftController.update();
1309 }1621 }
1310 if (handToDisable !== RIGHT_HAND && handToDisable!=='both') {1622 if (handToDisable !== RIGHT_HAND && handToDisable !== 'both') {
1311 rightController.update();1623 rightController.update();
1312 }1624 }
1313}1625}
1314 1626
1315Messages.subscribe('Hifi-Hand-Disabler');1627Messages.subscribe('Hifi-Hand-Disabler');
1628Messages.subscribe('Hifi-Hand-Grab');
1316 1629
1317handleHandDisablerMessages = function(channel, message, sender) {1630handleHandMessages = function(channel, message, sender) {
1318
1319 if (sender === MyAvatar.sessionUUID) {1631 if (sender === MyAvatar.sessionUUID) {
1320 if (message === 'left') {1632 if (channel === 'Hifi-Hand-Disabler') {
1321 handToDisable = LEFT_HAND;1633 if (message === 'left') {
1322 }1634 handToDisable = LEFT_HAND;
1323 if (message === 'right') {1635 }
1324 handToDisable = RIGHT_HAND;1636 if (message === 'right') {
1325 }1637 handToDisable = RIGHT_HAND;
1326 if(message==='both'){1638 }
1327 handToDisable='both';1639 if (message === 'both' || message === 'none') {
1328 }1640 handToDisable = message;
1329 if(message==='none'){1641 }
1330 handToDisable='none';1642 } else if (channel === 'Hifi-Hand-Grab') {
1643 try {
1644 var data = JSON.parse(message);
1645 var selectedController = (data.hand === 'left') ? leftController : rightController;
1646 selectedController.release();
1647 selectedController.setState(STATE_EQUIP);
1648 selectedController.grabbedEntity = data.entityID;
1649
1650 } catch (e) { }
1331 }1651 }
1332 }1652 }
1333
1334}1653}
1335 1654
1336Messages.messageReceived.connect(handleHandDisablerMessages);1655Messages.messageReceived.connect(handleHandMessages);
1337 1656
1338function cleanup() {1657function cleanup() {
1339 rightController.cleanup();1658 rightController.cleanup();
@@ -1342,4 +1661,4 @@ function cleanup() { · 2 unmodified lines
1342}1661}
1343 1662
1344Script.scriptEnding.connect(cleanup);1663Script.scriptEnding.connect(cleanup);
1345Script.update.connect(update);1664Script.update.connect(update);
examples/controllers/reticleHandRotationTest.js+178−27
@@ -9,13 +9,12 @@ · 8 unmodified lines
9// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html9// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
10//10//
11 11
12var DEBUGGING = false;
13
12Math.clamp=function(a,b,c) {14Math.clamp=function(a,b,c) {
13 return Math.max(b,Math.min(c,a));15 return Math.max(b,Math.min(c,a));
14}16}
15 17
16var whichHand = Controller.Standard.RightHand;
17var whichTrigger = Controller.Standard.RT;
18
19function length(posA, posB) {18function length(posA, posB) {
20 var dx = posA.x - posB.x;19 var dx = posA.x - posB.x;
21 var dy = posA.y - posB.y;20 var dy = posA.y - posB.y;
@@ -33,14 +32,14 @@ function moveReticleAbsolute(x, y) { · 11 unmodified lines
33 // some debugging to see if position is jumping around on us...32 // some debugging to see if position is jumping around on us...
34 var distanceSinceLastMove = length(lastPos, globalPos);33 var distanceSinceLastMove = length(lastPos, globalPos);
35 if (distanceSinceLastMove > EXPECTED_CHANGE) {34 if (distanceSinceLastMove > EXPECTED_CHANGE) {
36 print("------------------ distanceSinceLastMove:" + distanceSinceLastMove + "----------------------------");35 debugPrint("------------------ distanceSinceLastMove:" + distanceSinceLastMove + "----------------------------");
37 }36 }
38 37
39 if (Math.abs(dX) > EXPECTED_CHANGE) {38 if (Math.abs(dX) > EXPECTED_CHANGE) {
40 print("surpressing unexpectedly large change dX:" + dX + "----------------------------");39 debugPrint("surpressing unexpectedly large change dX:" + dX + "----------------------------");
41 }40 }
42 if (Math.abs(dY) > EXPECTED_CHANGE) {41 if (Math.abs(dY) > EXPECTED_CHANGE) {
43 print("surpressing unexpectedly large change dY:" + dY + "----------------------------");42 debugPrint("surpressing unexpectedly large change dY:" + dY + "----------------------------");
44 }43 }
45 44
46 globalPos.x = x;45 globalPos.x = x;
@@ -52,49 +51,201 @@ function moveReticleAbsolute(x, y) { · 5 unmodified lines
52 51
53var MAPPING_NAME = "com.highfidelity.testing.reticleWithHandRotation";52var MAPPING_NAME = "com.highfidelity.testing.reticleWithHandRotation";
54var mapping = Controller.newMapping(MAPPING_NAME);53var mapping = Controller.newMapping(MAPPING_NAME);
55mapping.from(whichTrigger).peek().constrainToInteger().to(Controller.Actions.ReticleClick);54mapping.from(Controller.Standard.LT).peek().constrainToInteger().to(Controller.Actions.ReticleClick);
56mapping.from(whichHand).peek().to(function(pose) {55mapping.from(Controller.Standard.RT).peek().constrainToInteger().to(Controller.Actions.ReticleClick);
56mapping.enable();
57
58
59var lastRotatedLeft = Vec3.UNIT_NEG_Y;
60var lastRotatedRight = Vec3.UNIT_NEG_Y;
61
62function debugPrint(message) {
63 if (DEBUGGING) {
64 print(message);
65 }
66}
67
68var MAX_WAKE_UP_DISTANCE = 0.005;
69var MIN_WAKE_UP_DISTANCE = 0.001;
70var INITIAL_WAKE_UP_DISTANCE = MIN_WAKE_UP_DISTANCE;
71var INCREMENTAL_WAKE_UP_DISTANCE = 0.001;
72
73var MAX_SLEEP_DISTANCE = 0.0004;
74var MIN_SLEEP_DISTANCE = 0.00001; //0.00002;
75var INITIAL_SLEEP_DISTANCE = MIN_SLEEP_DISTANCE;
76var INCREMENTAL_SLEEP_DISTANCE = 0.000002; // 0.00002;
77
78var leftAsleep = true;
79var rightAsleep = true;
80
81var leftWakeUpDistance = INITIAL_WAKE_UP_DISTANCE;
82var rightWakeUpDistance = INITIAL_WAKE_UP_DISTANCE;
83
84var leftSleepDistance = INITIAL_SLEEP_DISTANCE;
85var rightSleepDistance = INITIAL_SLEEP_DISTANCE;
86
87Script.update.connect(function(deltaTime) {
88
89 var poseRight = Controller.getPoseValue(Controller.Standard.RightHand);
90 var poseLeft = Controller.getPoseValue(Controller.Standard.LeftHand);
57 91
58 // NOTE: hack for now92 // NOTE: hack for now
59 var screenSizeX = 1920;93 var screenSizeX = 1920;
60 var screenSizeY = 1080;94 var screenSizeY = 1080;
61 95
62 var rotated = Vec3.multiplyQbyV(pose.rotation, Vec3.UNIT_NEG_Y); // 96 var rotatedRight = Vec3.multiplyQbyV(poseRight.rotation, Vec3.UNIT_NEG_Y);
97 var rotatedLeft = Vec3.multiplyQbyV(poseLeft.rotation, Vec3.UNIT_NEG_Y);
98
99 var suppressRight = false;
100 var suppressLeft = false;
101
102 // What I really want to do is to slowly increase the epsilon you have to move it
103 // to wake up, the longer you go without moving it
104 var leftDistance = Vec3.distance(rotatedLeft, lastRotatedLeft);
105 var rightDistance = Vec3.distance(rotatedRight, lastRotatedRight);
106
107 // check to see if hand should wakeup or sleep
108 if (leftAsleep) {
109 if (leftDistance > leftWakeUpDistance) {
110 leftAsleep = false;
111 leftSleepDistance = INITIAL_SLEEP_DISTANCE;
112 leftWakeUpDistance = INITIAL_WAKE_UP_DISTANCE;
113 } else {
114 // grow the wake up distance to make it harder to wake up
115 leftWakeUpDistance = Math.min(leftWakeUpDistance + INCREMENTAL_WAKE_UP_DISTANCE, MAX_WAKE_UP_DISTANCE);
116 }
117 } else {
118 // we are awake, determine if we should fall asleep, if we haven't moved
119 // at least as much as our sleep distance then we sleep
120 if (leftDistance < leftSleepDistance) {
121 leftAsleep = true;
122 leftSleepDistance = INITIAL_SLEEP_DISTANCE;
123 leftWakeUpDistance = INITIAL_WAKE_UP_DISTANCE;
124 } else {
125 // if we moved more than the sleep amount, but we moved less than the max sleep
126 // amount, then increase our liklihood of sleep.
127 if (leftDistance < MAX_SLEEP_DISTANCE) {
128 print("growing sleep....");
129 leftSleepDistance = Math.max(leftSleepDistance + INCREMENTAL_SLEEP_DISTANCE, MAX_SLEEP_DISTANCE);
130 } else {
131 // otherwise reset it to initial
132 leftSleepDistance = INITIAL_SLEEP_DISTANCE;
133 }
134 }
135 }
136 if (leftAsleep) {
137 suppressLeft = true;
138 debugPrint("suppressing left not moving enough");
139 }
140
141 // check to see if hand should wakeup or sleep
142 if (rightAsleep) {
143 if (rightDistance > rightWakeUpDistance) {
144 rightAsleep = false;
145 rightSleepDistance = INITIAL_SLEEP_DISTANCE;
146 rightWakeUpDistance = INITIAL_WAKE_UP_DISTANCE;
147 } else {
148 // grow the wake up distance to make it harder to wake up
149 rightWakeUpDistance = Math.min(rightWakeUpDistance + INCREMENTAL_WAKE_UP_DISTANCE, MAX_WAKE_UP_DISTANCE);
150 }
151 } else {
152 // we are awake, determine if we should fall asleep, if we haven't moved
153 // at least as much as our sleep distance then we sleep
154 if (rightDistance < rightSleepDistance) {
155 rightAsleep = true;
156 rightSleepDistance = INITIAL_SLEEP_DISTANCE;
157 rightWakeUpDistance = INITIAL_WAKE_UP_DISTANCE;
158 } else {
159 // if we moved more than the sleep amount, but we moved less than the max sleep
160 // amount, then increase our liklihood of sleep.
161 if (rightDistance < MAX_SLEEP_DISTANCE) {
162 print("growing sleep....");
163 rightSleepDistance = Math.max(rightSleepDistance + INCREMENTAL_SLEEP_DISTANCE, MAX_SLEEP_DISTANCE);
164 } else {
165 // otherwise reset it to initial
166 rightSleepDistance = INITIAL_SLEEP_DISTANCE;
167 }
168 }
169 }
170 if (rightAsleep) {
171 suppressRight = true;
172 debugPrint("suppressing right not moving enough");
173 }
174
175 // check to see if hand is on base station
176 if (Vec3.equal(rotatedLeft, Vec3.UNIT_NEG_Y)) {
177 suppressLeft = true;
178 debugPrint("suppressing left on base station");
179 }
180 if (Vec3.equal(rotatedRight, Vec3.UNIT_NEG_Y)) {
181 suppressRight = true;
182 debugPrint("suppressing right on base station");
183 }
184
185 // Keep track of last rotations, to detect resting (but not on base station hands) in the future
186 lastRotatedLeft = rotatedLeft;
187 lastRotatedRight = rotatedRight;
188
189 if (suppressLeft && suppressRight) {
190 debugPrint("both hands suppressed bail out early");
191 return;
192 }
193
194 if (suppressLeft) {
195 debugPrint("right only");
196 rotatedLeft = rotatedRight;
197 }
198 if (suppressRight) {
199 debugPrint("left only");
200 rotatedRight = rotatedLeft;
201 }
202
203 // Average the two hand positions, if either hand is on base station, the
204 // other hand becomes the only used hand and the average is the hand in use
205 var rotated = Vec3.multiply(Vec3.sum(rotatedRight,rotatedLeft), 0.5);
206
207 if (DEBUGGING) {
208 Vec3.print("rotatedRight:", rotatedRight);
209 Vec3.print("rotatedLeft:", rotatedLeft);
210 Vec3.print("rotated:", rotated);
211 }
212
63 var absolutePitch = rotated.y; // from 1 down to -1 up ... but note: if you rotate down "too far" it starts to go up again...213 var absolutePitch = rotated.y; // from 1 down to -1 up ... but note: if you rotate down "too far" it starts to go up again...
64 var absoluteYaw = rotated.z; // from -1 left to 1 right214 var absoluteYaw = -rotated.x; // from -1 left to 1 right
65 //print("absolutePitch:" + absolutePitch);215
66 //print("absoluteYaw:" + absoluteYaw);216 if (DEBUGGING) {
67 //Vec3.print("rotated:", rotated);217 print("absolutePitch:" + absolutePitch);
218 print("absoluteYaw:" + absoluteYaw);
219 Vec3.print("rotated:", rotated);
220 }
68 221
69 var ROTATION_BOUND = 0.6;222 var ROTATION_BOUND = 0.6;
70 var clampYaw = Math.clamp(absoluteYaw, -ROTATION_BOUND, ROTATION_BOUND);223 var clampYaw = Math.clamp(absoluteYaw, -ROTATION_BOUND, ROTATION_BOUND);
71 var clampPitch = Math.clamp(absolutePitch, -ROTATION_BOUND, ROTATION_BOUND);224 var clampPitch = Math.clamp(absolutePitch, -ROTATION_BOUND, ROTATION_BOUND);
72 //var clampYaw = absoluteYaw;225 if (DEBUGGING) {
73 //print("clampYaw:" + clampYaw);226 print("clampYaw:" + clampYaw);
74 //print("clampPitch:" + clampPitch);227 print("clampPitch:" + clampPitch);
75 228 }
76 // if using entire span...
77 //var xRatio = (absoluteYaw + 1) / 2;
78 //var yRatio = (absolutePitch + 1) / 2;
79 229
80 // if using only from -0.5 to 0.5230 // using only from -ROTATION_BOUND to ROTATION_BOUND
81 var xRatio = (clampYaw + ROTATION_BOUND) / (2 * ROTATION_BOUND);231 var xRatio = (clampYaw + ROTATION_BOUND) / (2 * ROTATION_BOUND);
82 var yRatio = (clampPitch + ROTATION_BOUND) / (2 * ROTATION_BOUND);232 var yRatio = (clampPitch + ROTATION_BOUND) / (2 * ROTATION_BOUND);
83 233
84 //print("xRatio:" + xRatio);234 if (DEBUGGING) {
85 //print("yRatio:" + yRatio);235 print("xRatio:" + xRatio);
86 236 print("yRatio:" + yRatio);
87 //print("ratio x:" + xRatio + " y:" + yRatio);237 }
88 238
89 var x = screenSizeX * xRatio;239 var x = screenSizeX * xRatio;
90 var y = screenSizeY * yRatio;240 var y = screenSizeY * yRatio;
91 241
92 //print("position x:" + x + " y:" + y);242 if (DEBUGGING) {
243 print("position x:" + x + " y:" + y);
244 }
93 if (!(xRatio == 0.5 && yRatio == 0)) {245 if (!(xRatio == 0.5 && yRatio == 0)) {
94 moveReticleAbsolute(x, y);246 moveReticleAbsolute(x, y);
95 }247 }
96});248});
97mapping.enable();
98 249
99Script.scriptEnding.connect(function(){250Script.scriptEnding.connect(function(){
100 mapping.disable();251 mapping.disable();
examples/edit.js+30−17
@@ -140,9 +140,33 @@ var importingSVOTextOverlay = Overlays.addOverlay("text", { · 139 unmodified lines
140});140});
141 141
142var MARKETPLACE_URL = "https://metaverse.highfidelity.com/marketplace";142var MARKETPLACE_URL = "https://metaverse.highfidelity.com/marketplace";
143var marketplaceWindow = new WebWindow('Marketplace', MARKETPLACE_URL, 900, 700, false);143var marketplaceWindow = new OverlayWebWindow('Marketplace', "about:blank", 900, 700, false);
144marketplaceWindow.setVisible(false);144marketplaceWindow.setVisible(false);
145 145
146function showMarketplace(marketplaceID) {
147 var url = MARKETPLACE_URL;
148 if (marketplaceID) {
149 url = url + "/items/" + marketplaceID;
150 }
151 print("setting marketplace URL to " + url);
152 marketplaceWindow.setURL(url);
153 marketplaceWindow.setVisible(true);
154 marketplaceWindow.raise();
155}
156
157function hideMarketplace() {
158 marketplaceWindow.setVisible(false);
159 marketplaceWindow.setURL("about:blank");
160}
161
162function toggleMarketplace() {
163 if (marketplaceWindow.visible) {
164 hideMarketplace();
165 } else {
166 showMarketplace();
167 }
168}
169
146var toolBar = (function() {170var toolBar = (function() {
147 var that = {},171 var that = {},
148 toolBar,172 toolBar,
@@ -413,12 +437,9 @@ var toolBar = (function() { · 264 unmodified lines
413 newModelButtonDown = true;437 newModelButtonDown = true;
414 return true;438 return true;
415 }439 }
440
416 if (browseMarketplaceButton === toolBar.clicked(clickedOverlay)) {441 if (browseMarketplaceButton === toolBar.clicked(clickedOverlay)) {
417 if (marketplaceWindow.url != MARKETPLACE_URL) {442 toggleMarketplace();
418 marketplaceWindow.setURL(MARKETPLACE_URL);
419 }
420 marketplaceWindow.setVisible(true);
421 marketplaceWindow.raise();
422 return true;443 return true;
423 }444 }
424 445
@@ -1336,6 +1357,7 @@ function getPositionToCreateEntity() { · 911 unmodified lines
1336}1357}
1337 1358
1338function importSVO(importURL) {1359function importSVO(importURL) {
1360 print("Import URL requested: " + importURL)
1339 if (!Entities.canAdjustLocks()) {1361 if (!Entities.canAdjustLocks()) {
1340 Window.alert(INSUFFICIENT_PERMISSIONS_IMPORT_ERROR_MSG);1362 Window.alert(INSUFFICIENT_PERMISSIONS_IMPORT_ERROR_MSG);
1341 return;1363 return;
@@ -1574,11 +1596,7 @@ PropertiesTool = function(opts) { · 232 unmodified lines
1574 pushCommandForSelections();1596 pushCommandForSelections();
1575 selectionManager._update();1597 selectionManager._update();
1576 } else if (data.type == "showMarketplace") {1598 } else if (data.type == "showMarketplace") {
1577 if (marketplaceWindow.url != data.url) {1599 showMarketplace();
1578 marketplaceWindow.setURL(data.url);
1579 }
1580 marketplaceWindow.setVisible(true);
1581 marketplaceWindow.raise();
1582 } else if (data.type == "action") {1600 } else if (data.type == "action") {
1583 if (data.action == "moveSelectionToGrid") {1601 if (data.action == "moveSelectionToGrid") {
1584 if (selectionManager.hasSelection()) {1602 if (selectionManager.hasSelection()) {
@@ -1859,12 +1877,7 @@ var propertyMenu = PopupMenu(); · 274 unmodified lines
1859 1877
1860propertyMenu.onSelectMenuItem = function(name) {1878propertyMenu.onSelectMenuItem = function(name) {
1861 if (propertyMenu.marketplaceID) {1879 if (propertyMenu.marketplaceID) {
1862 var url = MARKETPLACE_URL + "/items/" + propertyMenu.marketplaceID;1880 showMarketplace(propertyMenu.marketplaceID);
1863 if (marketplaceWindow.url != url) {
1864 marketplaceWindow.setURL(url);
1865 }
1866 marketplaceWindow.setVisible(true);
1867 marketplaceWindow.raise();
1868 }1881 }
1869};1882};
1870 1883
examples/flowArts/arcBall/arcBall.js+145−0
@@ -0,0 +1,145 @@
1//
2// arcBall.js
3// examples/arcBall
4//
5// Created by Eric Levin on 12/17/15.
6// Copyright 2015 High Fidelity, Inc.
7//
8// This script creats a particle light ball which makes particle trails as you move it.
9//
10//
11// Distributed under the Apache License, Version 2.0.
12// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
13//
14
15Script.include("../../libraries/utils.js");
16
17
18var scriptURL = Script.resolvePath("arcBallEntityScript.js?v1" + Math.random());
19ArcBall = function(spawnPosition) {
20
21 var colorPalette = [{
22 red: 25,
23 green: 20,
24 blue: 162
25 }];
26
27
28 var containerBall = Entities.addEntity({
29 type: "Sphere",
30 name: "Arc Ball",
31 script: scriptURL,
32 position: Vec3.sum(spawnPosition, {
33 x: 0,
34 y: .7,
35 z: 0
36 }),
37 dimensions: {
38 x: .05,
39 y: .05,
40 z: .05
41 },
42 color: {
43 red: 100,
44 green: 10,
45 blue: 150
46 },
47 ignoreForCollisions: true,
48 damping: 0.8,
49 collisionsWillMove: true,
50 userData: JSON.stringify({
51 grabbableKey: {
52 spatialKey: {
53 // relativePosition: {
54 // x: 0,
55 // y: -0.5,
56 // z: 0.0
57 // },
58 },
59 // invertSolidWhileHeld: true
60 }
61 })
62 });
63
64
65 var light = Entities.addEntity({
66 type: 'Light',
67 name: "ballLight",
68 parentID: containerBall,
69 dimensions: {
70 x: 30,
71 y: 30,
72 z: 30
73 },
74 color: colorPalette[randInt(0, colorPalette.length)],
75 intensity: 5
76 });
77
78
79 var arcBall = Entities.addEntity({
80 type: "ParticleEffect",
81 parentID: containerBall,
82 isEmitting: true,
83 name: "Arc Ball Particle Effect",
84 colorStart: {
85 red: 200,
86 green: 20,
87 blue: 40
88 },
89 color: {
90 red: 200,
91 green: 200,
92 blue: 255
93 },
94 colorFinish: {
95 red: 25,
96 green: 20,
97 blue: 255
98 },
99 maxParticles: 100000,
100 lifespan: 2,
101 emitRate: 400,
102 emitSpeed: .1,
103 lifetime: -1,
104 speedSpread: 0.0,
105 emitDimensions: {
106 x: 0,
107 y: 0,
108 z: 0
109 },
110 polarStart: 0,
111 polarFinish: Math.PI,
112 azimuthStart: -Math.PI,
113 azimuthFinish: Math.PI,
114 emitAcceleration: {
115 x: 0,
116 y: 0,
117 z: 0
118 },
119 accelerationSpread: {
120 x: .00,
121 y: .00,
122 z: .00
123 },
124 particleRadius: 0.02,
125 radiusSpread: 0,
126 radiusStart: 0.03,
127 radiusFinish: 0.0003,
128 alpha: 0,
129 alphaSpread: .5,
130 alphaStart: 0,
131 alphaFinish: 0.5,
132 textures: "https://hifi-public.s3.amazonaws.com/alan/Particles/Particle-Sprite-Smoke-1.png",
133 emitterShouldTrail: true
134 })
135
136
137
138 function cleanup() {
139 Entities.deleteEntity(arcBall);
140 Entities.deleteEntity(containerBall);
141 Entities.deleteEntity(light);
142 }
143
144 this.cleanup = cleanup;
145}
examples/flowArts/arcBall/arcBallEntityScript.js+155−0
@@ -0,0 +1,155 @@
1// arcBallEntityScript.js
2//
3// Script Type: Entity
4// Created by Eric Levin on 12/17/15.
5// Copyright 2015 High Fidelity, Inc.
6//
7// This entity script handles the logic for the arcBall rave toy
8// Distributed under the Apache License, Version 2.0.
9// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
10//
11
12(function() {
13 Script.include("../../libraries/utils.js");
14 var _this;
15 var ArcBall = function() {
16 _this = this;
17 this.colorPalette = [{
18 red: 25,
19 green: 20,
20 blue: 162
21 }, {
22 red: 200,
23 green: 10,
24 blue: 10
25 }];
26
27 this.searchRadius = 10;
28 };
29
30 ArcBall.prototype = {
31 isGrabbed: false,
32 startDistantGrab: function() {
33 this.searchForNearbyArcBalls();
34 },
35
36 startNearGrab: function() {
37 this.searchForNearbyArcBalls();
38 },
39
40 searchForNearbyArcBalls: function() {
41 //Search for nearby balls and create an arc to it if one is found
42 var position = Entities.getEntityProperties(this.entityID, "position").position
43 var entities = Entities.findEntities(position, this.searchRadius);
44 entities.forEach(function(entity) {
45 var props = Entities.getEntityProperties(entity, ["position", "name"]);
46 if (props.name === "Arc Ball" && JSON.stringify(_this.entityID) !== JSON.stringify(entity)) {
47 _this.target = entity;
48 _this.createBeam(position, props.position);
49
50 }
51 });
52 },
53
54 createBeam: function(startPosition, endPosition) {
55
56 // Creates particle arc from start position to end position
57 var rotation = Entities.getEntityProperties(this.entityID, "rotation").rotation;
58 var sourceToTargetVec = Vec3.subtract(endPosition, startPosition);
59 var emitOrientation = Quat.rotationBetween(Vec3.UNIT_Z, sourceToTargetVec);
60 emitOrientation = Quat.multiply(Quat.inverse(rotation), emitOrientation);
61
62 var color = this.colorPalette[randInt(0, this.colorPalette.length)];
63 var props = {
64 type: "ParticleEffect",
65 name: "Particle Arc",
66 parentID: this.entityID,
67 parentJointIndex: -1,
68 // position: startPosition,
69 isEmitting: true,
70 colorStart: color,
71 color: {
72 red: 200,
73 green: 200,
74 blue: 255
75 },
76 colorFinish: color,
77 maxParticles: 100000,
78 lifespan: 1,
79 emitRate: 1000,
80 emitOrientation: emitOrientation,
81 emitSpeed: 1,
82 speedSpread: 0.02,
83 emitDimensions: {
84 x: .01,
85 y: .01,
86 z: .01
87 },
88 polarStart: 0,
89 polarFinish: 0,
90 azimuthStart: 0.02,
91 azimuthFinish: .01,
92 emitAcceleration: {
93 x: 0,
94 y: 0,
95 z: 0
96 },
97 accelerationSpread: {
98 x: 0,
99 y: 0,
100 z: 0
101 },
102 radiusStart: 0.01,
103 radiusFinish: 0.005,
104 radiusSpread: 0.005,
105 alpha: 0.5,
106 alphaSpread: 0.1,
107 alphaStart: 0.5,
108 alphaFinish: 0.5,
109 textures: "https://s3.amazonaws.com/hifi-public/eric/textures/particleSprites/beamParticle.png",
110 emitterShouldTrail: true
111 }
112 this.particleArc = Entities.addEntity(props);
113 },
114
115 updateBeam: function() {
116 if(!this.target) {
117 return;
118 }
119 var startPosition = Entities.getEntityProperties(this.entityID, "position").position;
120 var targetPosition = Entities.getEntityProperties(this.target, "position").position;
121 var rotation = Entities.getEntityProperties(this.entityID, "rotation").rotation;
122 var sourceToTargetVec = Vec3.subtract(targetPosition, startPosition);
123 var emitOrientation = Quat.rotationBetween(Vec3.UNIT_Z, sourceToTargetVec);
124 Entities.editEntity(this.particleArc, {
125 emitOrientation: emitOrientation
126 });
127 },
128
129 continueNearGrab: function() {
130 this.updateBeam();
131 },
132
133 continueDistantGrab: function() {
134 this.updateBeam();
135 },
136
137 releaseGrab: function() {
138 Entities.editEntity(this.particleArc, {
139 isEmitting: false
140 });
141 this.target = null;
142 },
143
144 unload: function() {
145 if (this.particleArc) {
146 Entities.deleteEntity(this.particleArc);
147 }
148 },
149
150 preload: function(entityID) {
151 this.entityID = entityID;
152 },
153 };
154 return new ArcBall();
155});
examples/flowArts/flowArtsHutSpawner.js+91−0
@@ -0,0 +1,91 @@
1//
2// flowArtsHutSpawner.js
3// examples/flowArts
4//
5// Created by Eric Levin on 12/17/15.
6// Copyright 2015 High Fidelity, Inc.
7//
8// This script creates a special flow arts hut with a bunch of flow art toys people can go in and play with
9//
10//
11// Distributed under the Apache License, Version 2.0.
12// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
13//
14
15
16Script.include("../../libraries/utils.js");
17Script.include("lightBall/lightBall.js");
18Script.include("raveStick/raveStick.js");
19Script.include("lightSaber/lightSaber.js");
20Script.include("arcBall/arcBall.js");
21
22
23
24var basePosition = Vec3.sum(MyAvatar.position, Vec3.multiply(1, Quat.getFront(Camera.getOrientation())));
25basePosition.y = MyAvatar.position.y + 1;
26
27// RAVE ITEMS
28// var lightBall = new LightBall(basePosition);
29
30var arcBall = new ArcBall(basePosition);
31var arcBall2 = new ArcBall(Vec3.sum(basePosition, {x: -1, y: 0, z: 0}));
32var raveStick = new RaveStick(Vec3.sum(basePosition, {x: 1, y: 0.5, z: 1}));
33var lightSaber = new LightSaber(Vec3.sum(basePosition, {x: 3, y: 0.5, z: 1}));
34
35
36var modelURL = "https://s3-us-west-1.amazonaws.com/hifi-content/eric/models/RaveRoom.fbx";
37
38var roomDimensions = {x: 30.58, y: 15.29, z: 30.58};
39
40var raveRoom = Entities.addEntity({
41 type: "Model",
42 name: "Rave Hut Room",
43 modelURL: modelURL,
44 position: basePosition,
45 dimensions:roomDimensions,
46 visible: true
47});
48
49var floor = Entities.addEntity({
50 type: "Box",
51 name: "Rave Floor",
52 position: Vec3.sum(basePosition, {x: 0, y: -1.2, z: 0}),
53 dimensions: {x: roomDimensions.x, y: 0.6, z: roomDimensions.z},
54 color: {red: 50, green: 10, blue: 100},
55 shapeType: 'box'
56});
57
58
59
60var lightZone = Entities.addEntity({
61 type: "Zone",
62 name: "Rave Hut Zone",
63 shapeType: 'box',
64 keyLightIntensity: 0.4,
65 keyLightColor: {
66 red: 50,
67 green: 0,
68 blue: 50
69 },
70 keyLightAmbientIntensity: .2,
71 position: MyAvatar.position,
72 dimensions: {
73 x: 100,
74 y: 100,
75 z: 100
76 }
77});
78
79function cleanup() {
80
81 Entities.deleteEntity(raveRoom);
82 Entities.deleteEntity(lightZone);
83 Entities.deleteEntity(floor);
84 // lightBall.cleanup();
85 arcBall.cleanup();
86 arcBall2.cleanup();
87 raveStick.cleanup();
88 lightSaber.cleanup();
89}
90
91Script.scriptEnding.connect(cleanup);
examples/flowArts/lightBall/lightBall.js+145−0
@@ -0,0 +1,145 @@
1//
2// LightBall.js
3// examples/lightBall
4//
5// Created by Eric Levin on 12/17/15.
6// Copyright 2014 High Fidelity, Inc.
7//
8// This script creats a particle light ball which makes particle trails as you move it.
9//
10//
11// Distributed under the Apache License, Version 2.0.
12// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
13//
14
15Script.include("../../libraries/utils.js");
16
17LightBall = function(spawnPosition) {
18
19 var colorPalette = [{
20 red: 25,
21 green: 20,
22 blue: 162
23 }];
24
25
26 var containerBall = Entities.addEntity({
27 type: "Sphere",
28 name: "containerBall",
29 position: Vec3.sum(spawnPosition, {
30 x: 0,
31 y: 0.5,
32 z: 0
33 }),
34 dimensions: {
35 x: 0.1,
36 y: 0.1,
37 z: 0.1
38 },
39 color: {
40 red: 15,
41 green: 10,
42 blue: 150
43 },
44 collisionsWillMove: true,
45 // gravity: {
46 // x: 0,
47 // y: -0.5,
48 // z: 0
49 // },
50 userData: JSON.stringify({
51 grabbableKey: {
52 spatialKey: {
53 relativePosition: {
54 x: 0,
55 y: 0.1,
56 z: 0
57 }
58 },
59 invertSolidWhileHeld: true
60 }
61 })
62 });
63
64
65 var light = Entities.addEntity({
66 type: 'Light',
67 name: "ballLight",
68 parentID: containerBall,
69 dimensions: {
70 x: 30,
71 y: 30,
72 z: 30
73 },
74 color: colorPalette[randInt(0, colorPalette.length)],
75 intensity: 5
76 });
77
78
79 var lightBall = Entities.addEntity({
80 type: "ParticleEffect",
81 parentID: containerBall,
82 isEmitting: true,
83 name: "particleBall",
84 colorStart: {
85 red: 200,
86 green: 20,
87 blue: 40
88 },
89 color: {
90 red: 200,
91 green: 200,
92 blue: 255
93 },
94 colorFinish: {
95 red: 25,
96 green: 20,
97 blue: 255
98 },
99 maxParticles: 100000,
100 lifespan: 2,
101 emitRate: 10000,
102 emitSpeed: 0.1,
103 lifetime: -1,
104 speedSpread: 0.0,
105 emitDimensions: {
106 x: 0,
107 y: 0,
108 z: 0
109 },
110 polarStart: 0,
111 polarFinish: Math.PI,
112 azimuthStart: -Math.PI,
113 azimuthFinish: Math.PI,
114 emitAcceleration: {
115 x: 0,
116 y: 0,
117 z: 0
118 },
119 accelerationSpread: {
120 x: 0.00,
121 y: 0.00,
122 z: 0.00
123 },
124 particleRadius: 0.02,
125 radiusSpread: 0,
126 radiusStart: 0.03,
127 radiusFinish: 0.0003,
128 alpha: 0,
129 alphaSpread: 0.5,
130 alphaStart: 0,
131 alphaFinish: 0.5,
132 textures: "https://hifi-public.s3.amazonaws.com/alan/Particles/Particle-Sprite-Smoke-1.png",
133 emitterShouldTrail: true
134 })
135
136
137
138 function cleanup() {
139 Entities.deleteEntity(lightBall);
140 Entities.deleteEntity(containerBall);
141 Entities.deleteEntity(light);
142 }
143
144 this.cleanup = cleanup;
145}
examples/flowArts/lightSaber/lightSaber.js+67−0
@@ -0,0 +1,67 @@
1//
2// LightSaber.js
3// examples
4//
5// Created by Eric Levin on 12/17/15.
6// Copyright 2015 High Fidelity, Inc.
7//
8// This script creates a lightsaber which activates on grab
9//
10//
11// Distributed under the Apache License, Version 2.0.
12// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
13//
14
15Script.include("../../libraries/utils.js");
16var modelURL = "https://s3-us-west-1.amazonaws.com/hifi-content/eric/models/lightSaber.fbx";
17var scriptURL = Script.resolvePath("lightSaberEntityScript.js");
18LightSaber = function(spawnPosition) {
19
20 var saberHandle = Entities.addEntity({
21 type: "Model",
22 name: "LightSaber Handle",
23 modelURL: modelURL,
24 position: spawnPosition,
25 shapeType: 'box',
26 collisionsWillMove: true,
27 script: scriptURL,
28 dimensions: {
29 x: 0.06,
30 y: 0.06,
31 z: 0.31
32 },
33 userData: JSON.stringify({
34 grabbableKey: {
35 spatialKey: {
36 relativePosition: {
37 x: 0,
38 y: 0,
39 z: -0.1
40 },
41 relativeRotation: Quat.fromPitchYawRollDegrees(180, 90, 0)
42 },
43 invertSolidWhileHeld: true
44 }
45 })
46 });
47
48 var light = Entities.addEntity({
49 type: 'Light',
50 name: "raveLight",
51 parentID: saberHandle,
52 dimensions: {
53 x: 30,
54 y: 30,
55 z: 30
56 },
57 color: {red: 200, green: 10, blue: 200},
58 intensity: 5
59 });
60
61
62 function cleanup() {
63 Entities.deleteEntity(saberHandle);
64 }
65
66 this.cleanup = cleanup;
67}
examples/flowArts/lightSaber/lightSaberEntityScript.js+116−0
@@ -0,0 +1,116 @@
1// lightSaberEntityScript.js
2//
3// Script Type: Entity
4// Created by Eric Levin on 12/17/15.
5// Copyright 2015 High Fidelity, Inc.
6//
7// This entity script creates the logic for displaying the lightsaber beam.
8// Distributed under the Apache License, Version 2.0.
9// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
10//
11
12(function() {
13 Script.include("../../libraries/utils.js");
14 var _this;
15 // this is the "constructor" for the entity as a JS object we don't do much here
16 var LightSaber = function() {
17 _this = this;
18 this.colorPalette = [{
19 red: 0,
20 green: 200,
21 blue: 40
22 }, {
23 red: 200,
24 green: 10,
25 blue: 40
26 }];
27 };
28
29 LightSaber.prototype = {
30 isGrabbed: false,
31
32 startNearGrab: function() {
33 Entities.editEntity(this.beam, {
34 isEmitting: true,
35 visible: true
36 });
37 },
38
39 releaseGrab: function() {
40 Entities.editEntity(this.beam, {
41 visible: false,
42 isEmitting: false
43 });
44 },
45
46 preload: function(entityID) {
47 this.entityID = entityID;
48 this.createBeam();
49 },
50
51 unload: function() {
52 Entities.deleteEntity(this.beam);
53 },
54
55 createBeam: function() {
56
57 this.props = Entities.getEntityProperties(this.entityID, ["position", "rotation"]);
58 var forwardVec = Quat.getFront(Quat.multiply(this.props.rotation, Quat.fromPitchYawRollDegrees(-90, 0, 0)));
59 var forwardQuat = Quat.rotationBetween(Vec3.UNIT_Z, forwardVec);
60 var position = this.props.position;
61
62 var color = this.colorPalette[randInt(0, this.colorPalette.length)];
63 var props = {
64 type: "ParticleEffect",
65 name: "LightSaber Beam",
66 position: position,
67 parentID: this.entityID,
68 isEmitting: false,
69 colorStart: color,
70 color: {
71 red: 200,
72 green: 200,
73 blue: 255
74 },
75 colorFinish: color,
76 maxParticles: 100000,
77 lifespan: 2,
78 emitRate: 1000,
79 emitOrientation: forwardQuat,
80 emitSpeed: 0.7,
81 speedSpread: 0.0,
82 emitDimensions: {
83 x: 0,
84 y: 0,
85 z: 0
86 },
87 polarStart: 0,
88 polarFinish: 0,
89 azimuthStart: 0.1,
90 azimuthFinish: 0.01,
91 emitAcceleration: {
92 x: 0,
93 y: 0,
94 z: 0
95 },
96 accelerationSpread: {
97 x: .00,
98 y: .00,
99 z: .00
100 },
101 radiusStart: 0.03,
102 adiusFinish: 0.025,
103 alpha: 0.7,
104 alphaSpread: 0.1,
105 alphaStart: 0.5,
106 alphaFinish: 0.5,
107 textures: "https://s3.amazonaws.com/hifi-public/eric/textures/particleSprites/beamParticle.png",
108 emitterShouldTrail: false
109 }
110 this.beam = Entities.addEntity(props);
111
112 }
113 };
114 // entity scripts always need to return a newly constructed object of our type
115 return new LightSaber();
116});
examples/flowArts/lightTrails.js+191−0
@@ -0,0 +1,191 @@
1//
2// lightTrails.js
3// examples
4//
5// Created by Eric Levin on 5/14/15.
6// Copyright 2015 High Fidelity, Inc.
7//
8// This script creates light trails as you move your hydra hands
9//
10//
11// Distributed under the Apache License, Version 2.0.
12// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
13//
14
15Script.include("../libraries/utils.js");
16
17var eraseTrail = true;
18var ugLSD = 25;
19// var eraseTrail = false;
20var LEFT = 0;
21var RIGHT = 1;
22var MAX_POINTS_PER_LINE = 50;
23
24var LIFETIME = 6000;
25var DRAWING_DEPTH = 0.8;
26var LINE_DIMENSIONS = 100;
27
28
29var MIN_POINT_DISTANCE = 0.02;
30
31
32var colorPalette = [{
33 red: 250,
34 green: 137,
35 blue: 162
36}, {
37 red: 204,
38 green: 244,
39 blue: 249
40}, {
41 red: 146,
42 green: 206,
43 blue: 116
44}, {
45 red: 240,
46 green: 87,
47 blue: 129
48}];
49
50var STROKE_WIDTH = 0.04;
51
52function controller(side, triggerAction) {
53 this.triggerHeld = false;
54 this.triggerThreshold = 0.9;
55 this.side = side;
56 this.triggerAction = triggerAction;
57 var texture = "https://s3.amazonaws.com/hifi-public/eric/textures/paintStrokes/trails.png";
58
59 this.light = Entities.addEntity({
60 type: 'Light',
61 position: MyAvatar.position,
62 dimensions: {
63 x: 30,
64 y: 30,
65 z: 30
66 },
67 color: colorPalette[randInt(0, colorPalette.length)],
68 intensity: 5
69 });
70
71 this.trail = Entities.addEntity({
72 type: "PolyLine",
73 dimensions: {
74 x: LINE_DIMENSIONS,
75 y: LINE_DIMENSIONS,
76 z: LINE_DIMENSIONS
77 },
78 color: {red: 255, green: 255, blue: 255},
79 textures: texture,
80 lifetime: LIFETIME
81 });
82 this.points = [];
83 this.normals = [];
84 this.strokeWidths = [];
85 var self = this;
86
87 this.trailEraseInterval = Script.setInterval(function() {
88 if (self.points.length > 0 && eraseTrail) {
89 self.points.shift();
90 self.normals.shift();
91 self.strokeWidths.shift();
92 Entities.editEntity(self.trail, {
93 linePoints: self.points,
94 strokeWidths: self.strokeWidths,
95 normals: self.normals
96 });
97 }
98 }, ugLSD);
99
100
101 this.setTrailPosition = function(position) {
102 this.trailPosition = position;
103 Entities.editEntity(this.trail, {
104 position: this.trailPosition
105 });
106 }
107
108
109 this.update = function(deltaTime) {
110 this.updateControllerState();
111 var newTrailPosOffset = Vec3.multiply(Vec3.normalize(Vec3.subtract(this.tipPosition, this.palmPosition)), DRAWING_DEPTH);
112 var newTrailPos = Vec3.sum(this.palmPosition, newTrailPosOffset);
113 Entities.editEntity(this.light, {
114 position: newTrailPos
115 });
116
117
118 if (!this.drawing) {
119 this.setTrailPosition(newTrailPos);
120 this.drawing = true;
121 }
122
123 if (this.drawing) {
124 var localPoint = Vec3.subtract(newTrailPos, this.trailPosition);
125 if (Vec3.distance(localPoint, this.points[this.points.length - 1]) < MIN_POINT_DISTANCE) {
126 //Need a minimum distance to avoid binormal NANs
127 return;
128 }
129
130 if (this.points.length === MAX_POINTS_PER_LINE) {
131 this.points.shift();
132 this.normals.shift();
133 this.strokeWidths.shift();
134 }
135
136 this.points.push(localPoint);
137 var normal = computeNormal(newTrailPos, Camera.getPosition());
138
139 this.normals.push(normal);
140 this.strokeWidths.push(STROKE_WIDTH + Math.random() * 0.01);
141 Entities.editEntity(this.trail, {
142 linePoints: this.points,
143 normals: this.normals,
144 strokeWidths: this.strokeWidths,
145 });
146
147 }
148 }
149
150
151 this.updateControllerState = function() {
152 this.palmPosition = this.side == RIGHT ? MyAvatar.rightHandPose.translation : MyAvatar.leftHandPose.translation;
153 this.tipPosition = this.side == RIGHT ? MyAvatar.rightHandTipPose.translation : MyAvatar.leftHandTipPose.translation;
154 this.triggerValue = Controller.getActionValue(this.triggerAction);
155
156 }
157
158 this.cleanup = function() {
159 Entities.deleteEntity(this.trail);
160 Entities.deleteEntity(this.light);
161 Script.clearInterval(this.trailEraseInterval);
162 }
163}
164
165function computeNormal(p1, p2) {
166 return Vec3.normalize(Vec3.subtract(p2, p1));
167}
168
169function update(deltaTime) {
170 leftController.update(deltaTime);
171 rightController.update(deltaTime);
172}
173
174function scriptEnding() {
175 leftController.cleanup();
176 rightController.cleanup();
177}
178
179function vectorIsZero(v) {
180 return v.x === 0 && v.y === 0 && v.z === 0;
181}
182
183
184var rightController = new controller(RIGHT, Controller.findAction("RIGHT_HAND_CLICK"));
185var leftController = new controller(LEFT, Controller.findAction("LEFT_HAND_CLICK"));
186Script.update.connect(update);
187Script.scriptEnding.connect(scriptEnding);
188
189function map(value, min1, max1, min2, max2) {
190 return min2 + (max2 - min2) * ((value - min1) / (max1 - min1));
191}
examples/flowArts/raveStick/raveStick.js+90−0
@@ -0,0 +1,90 @@
1//
2// RaveStick.js
3// examples/flowArats/raveStick
4//
5// Created by Eric Levin on 12/17/15.
6// Copyright 2015 High Fidelity, Inc.
7//
8// This script creates a rave stick which makes pretty light trails as you paint
9//
10// Distributed under the Apache License, Version 2.0.
11// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
12//
13
14Script.include("../../libraries/utils.js");
15var modelURL = "https://s3-us-west-1.amazonaws.com/hifi-content/eric/models/raveStick.fbx";
16var scriptURL = Script.resolvePath("raveStickEntityScript.js");
17RaveStick = function(spawnPosition) {
18 var colorPalette = [{
19 red: 0,
20 green: 200,
21 blue: 40
22 }, {
23 red: 200,
24 green: 10,
25 blue: 40
26 }];
27 var stick = Entities.addEntity({
28 type: "Model",
29 name: "raveStick",
30 modelURL: modelURL,
31 position: spawnPosition,
32 shapeType: 'box',
33 collisionsWillMove: true,
34 script: scriptURL,
35 dimensions: {
36 x: 0.06,
37 y: 0.06,
38 z: 0.31
39 },
40 userData: JSON.stringify({
41 grabbableKey: {
42 spatialKey: {
43 relativePosition: {
44 x: 0,
45 y: 0,
46 z: -0.1
47 },
48 relativeRotation: Quat.fromPitchYawRollDegrees(90, 90, 0)
49 },
50 invertSolidWhileHeld: true
51 }
52 })
53 });
54
55 var light = Entities.addEntity({
56 type: 'Light',
57 name: "raveLight",
58 parentID: stick,
59 dimensions: {
60 x: 30,
61 y: 30,
62 z: 30
63 },
64 color: colorPalette[randInt(0, colorPalette.length)],
65 intensity: 5
66 });
67
68 var rotation = Quat.fromPitchYawRollDegrees(0, 0, 0)
69 var forwardVec = Quat.getFront(Quat.multiply(rotation, Quat.fromPitchYawRollDegrees(-90, 0, 0)));
70 forwardVec = Vec3.normalize(forwardVec);
71 var forwardQuat = orientationOf(forwardVec);
72 var position = Vec3.sum(spawnPosition, Vec3.multiply(Quat.getFront(rotation), 0.1));
73 position.z += 0.1;
74 position.x += -0.035;
75 var color = {
76 red: 0,
77 green: 200,
78 blue: 40
79 };
80
81
82
83
84 function cleanup() {
85 Entities.deleteEntity(stick);
86 Entities.deleteEntity(light);
87 }
88
89 this.cleanup = cleanup;
90}
examples/flowArts/raveStick/raveStickEntityScript.js+141−0
@@ -0,0 +1,141 @@
1// raveStickEntityScript.js
2//
3// Script Type: Entity
4// Created by Eric Levin on 12/16/15.
5// Copyright 2015 High Fidelity, Inc.
6//
7// This entity script create light trails on a given object as it moves.
8// Distributed under the Apache License, Version 2.0.
9// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
10//
11
12(function() {
13 Script.include("../../libraries/utils.js");
14 var _this;
15 var LIFETIME = 6000;
16 var DRAWING_DEPTH = 0.8;
17 var LINE_DIMENSIONS = 100;
18 var MAX_POINTS_PER_LINE = 50;
19 var MIN_POINT_DISTANCE = 0.02;
20 var STROKE_WIDTH = 0.05
21 var ugLSD = 35;
22 var RaveStick = function() {
23 _this = this;
24 this.colorPalette = [{
25 red: 0,
26 green: 200,
27 blue: 40
28 }, {
29 red: 200,
30 green: 10,
31 blue: 40
32 }];
33 var texture = "https://s3.amazonaws.com/hifi-public/eric/textures/paintStrokes/trails.png";
34 this.trail = Entities.addEntity({
35 type: "PolyLine",
36 dimensions: {
37 x: LINE_DIMENSIONS,
38 y: LINE_DIMENSIONS,
39 z: LINE_DIMENSIONS
40 },
41 color: {
42 red: 255,
43 green: 255,
44 blue: 255
45 },
46 textures: texture,
47 lifetime: LIFETIME
48 });
49
50 this.points = [];
51 this.normals = [];
52 this.strokeWidths = [];
53 };
54
55 RaveStick.prototype = {
56 isGrabbed: false,
57
58 startNearGrab: function() {
59 this.trailBasePosition = Entities.getEntityProperties(this.entityID, "position").position;
60 Entities.editEntity(this.trail, {
61 position: this.trailBasePosition
62 });
63 this.points = [];
64 this.normals = [];
65 this.strokeWidths = [];
66 this.setupEraseInterval();
67 },
68
69 continueNearGrab: function() {
70 var props = Entities.getEntityProperties(this.entityID, ["position", "rotation"]);
71 var forwardVec = Quat.getFront(Quat.multiply(props.rotation, Quat.fromPitchYawRollDegrees(-90, 0, 0)));
72 forwardVec = Vec3.normalize(forwardVec);
73 var forwardQuat = orientationOf(forwardVec);
74 var position = Vec3.sum(props.position, Vec3.multiply(Quat.getFront(props.rotation), 0.04));
75 var localPoint = Vec3.subtract(position, this.trailBasePosition);
76 if (this.points.length >= 1 && Vec3.distance(localPoint, this.points[this.points.length - 1]) < MIN_POINT_DISTANCE) {
77 //Need a minimum distance to avoid binormal NANs
78 return;
79 }
80 if (this.points.length === MAX_POINTS_PER_LINE) {
81 this.points.shift();
82 this.normals.shift();
83 this.strokeWidths.shift();
84 }
85
86 this.points.push(localPoint);
87 var normal = Quat.getUp(props.rotation);
88 this.normals.push(normal);
89 this.strokeWidths.push(STROKE_WIDTH);
90 Entities.editEntity(this.trail, {
91 linePoints: this.points,
92 normals: this.normals,
93 strokeWidths: this.strokeWidths
94 });
95
96
97 },
98
99 setupEraseInterval: function() {
100 this.trailEraseInterval = Script.setInterval(function() {
101 if (_this.points.length > 0) {
102 _this.points.shift();
103 _this.normals.shift();
104 _this.strokeWidths.shift();
105 Entities.editEntity(_this.trail, {
106 linePoints: _this.points,
107 strokeWidths: _this.strokeWidths,
108 normals: _this.normals
109 });
110 }
111 }, ugLSD);
112 },
113
114 releaseGrab: function() {
115 if(!this.trailEraseInterval) {
116 return;
117 }
118 Script.setTimeout(function() {
119 Script.clearInterval(_this.trailEraseInterval);
120 _this.trailEraseInterval = null;
121 }, 3000);
122 },
123
124 preload: function(entityID) {
125 this.entityID = entityID;
126 },
127
128 unload: function() {
129 Entities.deleteEntity(this.beam);
130 Entities.deleteEntity(this.trail);
131 if (this.trailEraseInterval) {
132 Script.clearInterval(this.trailEraseInterval);
133 }
134 }
135 };
136 return new RaveStick();
137
138 function computeNormal(p1, p2) {
139 return Vec3.normalize(Vec3.subtract(p2, p1));
140 }
141});
examples/painting/closePaint.js+4−1
@@ -43,6 +43,8 @@ var MAX_STROKE_WIDTH = 0.04; · 42 unmodified lines
43 43
44var center = Vec3.sum(MyAvatar.position, Vec3.multiply(2, Quat.getFront(Camera.getOrientation())));44var center = Vec3.sum(MyAvatar.position, Vec3.multiply(2, Quat.getFront(Camera.getOrientation())));
45 45
46var textureURL = "https://s3.amazonaws.com/hifi-public/eric/textures/paintStrokes/paintStroke.png";
47
46 48
47 49
48function MyController(hand, triggerAction) {50function MyController(hand, triggerAction) {
@@ -148,7 +150,8 @@ function MyController(hand, triggerAction) { · 99 unmodified lines
148 y: 50,150 y: 50,
149 z: 50151 z: 50
150 },152 },
151 lifetime: 200153 lifetime: 200,
154 textures: textureURL
152 });155 });
153 this.strokePoints = [];156 this.strokePoints = [];
154 this.strokeNormals = [];157 this.strokeNormals = [];
examples/painting/whiteboard/whiteboardEntityScript.js+3−0
@@ -29,6 +29,8 @@ · 28 unmodified lines
29 var MIN_STROKE_WIDTH = 0.0005;29 var MIN_STROKE_WIDTH = 0.0005;
30 var MAX_STROKE_WIDTH = 0.03;30 var MAX_STROKE_WIDTH = 0.03;
31 31
32 var textureURL = "https://s3.amazonaws.com/hifi-public/eric/textures/paintStrokes/paintStroke.png";
33
32 var TRIGGER_CONTROLS = [34 var TRIGGER_CONTROLS = [
33 Controller.Standard.LT,35 Controller.Standard.LT,
34 Controller.Standard.RT,36 Controller.Standard.RT,
@@ -168,6 +170,7 @@ · 133 unmodified lines
168 type: "PolyLine",170 type: "PolyLine",
169 name: "paintStroke",171 name: "paintStroke",
170 color: this.strokeColor,172 color: this.strokeColor,
173 textures: "https://s3.amazonaws.com/hifi-public/eric/textures/paintStrokes/paintStroke.png",
171 dimensions: {174 dimensions: {
172 x: 50,175 x: 50,
173 y: 50,176 y: 50,
examples/painting/whiteboard/whiteboardSpawner.js+1−1
@@ -247,4 +247,4 @@ function cleanup() { · 246 unmodified lines
247 247
248 248
249// Uncomment this line to delete whiteboard and all associated entity on script close249// Uncomment this line to delete whiteboard and all associated entity on script close
250//Script.scriptEnding.connect(cleanup);250// Script.scriptEnding.connect(cleanup);
examples/rayPickingFilterExample.js+73−0
@@ -0,0 +1,73 @@
1 //
2 // rayPickingFilterExample.js
3 // examples
4 //
5 // Created by Eric Levin on 12/24/2015
6 // Copyright 2015 High Fidelity, Inc.
7 //
8 // This is an example script that demonstrates the use of filtering entities for ray picking
9 //
10 // Distributed under the Apache License, Version 2.0.
11 // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
12 //
13
14
15 var center = Vec3.sum(MyAvatar.position, Vec3.multiply(3, Quat.getFront(Camera.getOrientation())));
16
17 var whiteListBox = Entities.addEntity({
18 type: "Box",
19 color: {
20 red: 10,
21 green: 200,
22 blue: 10
23 },
24 dimensions: {
25 x: 0.2,
26 y: 0.2,
27 z: 0.2
28 },
29 position: center
30 });
31
32 var blackListBox = Entities.addEntity({
33 type: "Box",
34 color: {
35 red: 100,
36 green: 10,
37 blue: 10
38 },
39 dimensions: {
40 x: 0.2,
41 y: 0.2,
42 z: 0.2
43 },
44 position: Vec3.sum(center, {
45 x: 0,
46 y: 0.3,
47 z: 0
48 })
49 });
50
51
52 function castRay(event) {
53 var pickRay = Camera.computePickRay(event.x, event.y);
54 // In this example every entity will be pickable except the entities in the blacklist array
55 // the third argument is the whitelist array,and the fourth and final is the blacklist array
56 var pickResults = Entities.findRayIntersection(pickRay, true, [], [blackListBox]);
57
58 // With below example, only entities added to whitelist will be pickable
59 // var pickResults = Entities.findRayIntersection(pickRay, true, [whiteListBox], []);
60
61 if (pickResults.intersects) {
62 print("INTERSECTION!");
63 }
64
65 }
66
67 function cleanup() {
68 Entities.deleteEntity(whiteListBox);
69 Entities.deleteEntity(blackListBox);
70 }
71
72 Script.scriptEnding.connect(cleanup);
73 Controller.mousePressEvent.connect(castRay);
examples/toybox/bow/bow.js+2−2
@@ -241,9 +241,9 @@ · 240 unmodified lines
241 userData: JSON.stringify({241 userData: JSON.stringify({
242 grabbableKey: {242 grabbableKey: {
243 grabbable: false243 grabbable: false
244 }244 },
245 creatorSessionUUID: MyAvatar.sessionUUID
245 })246 })
246
247 });247 });
248 248
249 var makeArrowStick = function(entityA, entityB, collision) {249 var makeArrowStick = function(entityA, entityB, collision) {
examples/toybox/ping_pong_gun/createPingPongGun.js+8−0
@@ -38,6 +38,14 @@ var pingPongGun = Entities.addEntity({ · 37 unmodified lines
38 collisionSoundURL: COLLISION_SOUND_URL,38 collisionSoundURL: COLLISION_SOUND_URL,
39 userData: JSON.stringify({39 userData: JSON.stringify({
40 grabbableKey: {40 grabbableKey: {
41 spatialKey: {
42 relativePosition: {
43 x: -0.05,
44 y: 0,
45 z: 0.0
46 },
47 relativeRotation: Quat.fromPitchYawRollDegrees(0, -90, -90)
48 },
41 invertSolidWhileHeld: true49 invertSolidWhileHeld: true
42 }50 }
43 })51 })
examples/utilities/tools/cookies.js+4−2
@@ -814,12 +814,14 @@ var CHECK_MARK_COLOR = { · 813 unmodified lines
814 });814 });
815 };815 };
816 816
817
818 CollapsablePanelItem.prototype.destroy = function() {817 CollapsablePanelItem.prototype.destroy = function() {
819 Overlays.deleteOverlay(this.title);818 Overlays.deleteOverlay(this.title);
820 Overlays.deleteOverlay(this.thumb);819 Overlays.deleteOverlay(this.thumb);
821 };820 };
822 821
822 CollapsablePanelItem.prototype.editTitle = function(opts) {
823 Overlays.editOverlay(this.title, opts);
824 };
823 825
824 CollapsablePanelItem.prototype.hide = function() {826 CollapsablePanelItem.prototype.hide = function() {
825 Overlays.editOverlay(this.title, {827 Overlays.editOverlay(this.title, {
@@ -1531,4 +1533,4 @@ Controller.captureKeyEvents({ · 705 unmodified lines
1531});1533});
1532Controller.captureKeyEvents({1534Controller.captureKeyEvents({
1533 text: "right"1535 text: "right"
1534});1536});
examples/utilities/tools/renderEngineDebug.js+48−64
@@ -21,75 +21,55 @@ Number.prototype.clamp = function(min, max) { · 20 unmodified lines
21 21
22var panel = new Panel(10, 100);22var panel = new Panel(10, 100);
23 23
24function CounterWidget(parentPanel, name, feedGetter, drawGetter, capSetter, capGetter) {24function CounterWidget(parentPanel, name, counter) {
25 this.subPanel = panel.newSubPanel(name);25 var subPanel = parentPanel.newSubPanel(name);
26 26 var widget = parentPanel.items[name];
27 this.subPanel.newSlider("Num Feed", 0, 1, 27 widget.editTitle({ width: 270 });
28 function(value) { },28
29 feedGetter,29 subPanel.newSlider('Max Drawn', -1, 1,
30 function(value) { return (value); });30 function(value) { counter.maxDrawn = value; }, // setter
31 this.subPanel.newSlider("Num Drawn", 0, 1, 31 function() { return counter.maxDrawn; }, // getter
32 function(value) { },32 function(value) { return value; });
33 drawGetter,33
34 function(value) { return (value); });34 var slider = subPanel.getWidget('Max Drawn');
35 this.subPanel.newSlider("Max Drawn", -1, 1, 35
36 capSetter,36 this.update = function () {
37 capGetter,37 var numDrawn = counter.numDrawn; // avoid double polling
38 function(value) { return (value); });38 var numMax = Math.max(numDrawn, 1);
39 39 var title = [
40 this.update = function () {40 ' ' + name,
41 var numFeed = this.subPanel.get("Num Feed");41 numDrawn + ' / ' + counter.numFeed
42 this.subPanel.set("Num Feed", numFeed);42 ].join('\t');
43 this.subPanel.set("Num Drawn", this.subPanel.get("Num Drawn"));43
44 44 widget.editTitle({ text: title });
45 var numMax = Math.max(numFeed, 1);45 slider.setMaxValue(numMax);
46 this.subPanel.getWidget("Num Feed").setMaxValue(numMax);
47 this.subPanel.getWidget("Num Drawn").setMaxValue(numMax);
48 this.subPanel.getWidget("Max Drawn").setMaxValue(numMax);
49 };46 };
50};47};
51 48
52var opaquesCounter = new CounterWidget(panel, "Opaques",49var opaquesCounter = new CounterWidget(panel, "Opaques", Render.opaque);
53 function () { return Render.getEngineNumFeedOpaqueItems(); },50var transparentsCounter = new CounterWidget(panel, "Transparents", Render.transparent);
54 function () { return Render.getEngineNumDrawnOpaqueItems(); },51var overlaysCounter = new CounterWidget(panel, "Overlays", Render.overlay3D);
55 function(value) { Render.setEngineMaxDrawnOpaqueItems(value); },
56 function () { return Render.getEngineMaxDrawnOpaqueItems(); }
57);
58
59var transparentsCounter = new CounterWidget(panel, "Transparents",
60 function () { return Render.getEngineNumFeedTransparentItems(); },
61 function () { return Render.getEngineNumDrawnTransparentItems(); },
62 function(value) { Render.setEngineMaxDrawnTransparentItems(value); },
63 function () { return Render.getEngineMaxDrawnTransparentItems(); }
64);
65
66var overlaysCounter = new CounterWidget(panel, "Overlays",
67 function () { return Render.getEngineNumFeedOverlay3DItems(); },
68 function () { return Render.getEngineNumDrawnOverlay3DItems(); },
69 function(value) { Render.setEngineMaxDrawnOverlay3DItems(value); },
70 function () { return Render.getEngineMaxDrawnOverlay3DItems(); }
71);
72 52
73var resizing = false;53var resizing = false;
74var previousMode = Settings.getValue(SETTINGS_KEY, -1);54var previousMode = Settings.getValue(SETTINGS_KEY, -1);
75Menu.addActionGroup(MENU, ACTIONS, ACTIONS[previousMode + 1]);55Menu.addActionGroup(MENU, ACTIONS, ACTIONS[previousMode + 1]);
76Render.setEngineDeferredDebugMode(previousMode);56Render.deferredDebugMode = previousMode;
77Render.setEngineDeferredDebugSize({ x: 0.0, y: -1.0, z: 1.0, w: 1.0 }); // Reset to default size57Render.deferredDebugSize = { x: 0.0, y: -1.0, z: 1.0, w: 1.0 }; // Reset to default size
78 58
79function setEngineDeferredDebugSize(eventX) {59function setEngineDeferredDebugSize(eventX) {
80 var scaledX = (2.0 * (eventX / Window.innerWidth) - 1.0).clamp(-1.0, 1.0);60 var scaledX = (2.0 * (eventX / Window.innerWidth) - 1.0).clamp(-1.0, 1.0);
81 Render.setEngineDeferredDebugSize({ x: scaledX, y: -1.0, z: 1.0, w: 1.0 });61 Render.deferredDebugSize = { x: scaledX, y: -1.0, z: 1.0, w: 1.0 };
82}62}
83function shouldStartResizing(eventX) {63function shouldStartResizing(eventX) {
84 var x = Math.abs(eventX - Window.innerWidth * (1.0 + Render.getEngineDeferredDebugSize().x) / 2.0);64 var x = Math.abs(eventX - Window.innerWidth * (1.0 + Render.deferredDebugSize.x) / 2.0);
85 var mode = Render.getEngineDeferredDebugMode();65 var mode = Render.deferredDebugMode;
86 return mode !== -1 && x < 20;66 return mode !== -1 && x < 20;
87}67}
88 68
89function menuItemEvent(menuItem) {69function menuItemEvent(menuItem) {
90 var index = ACTIONS.indexOf(menuItem);70 var index = ACTIONS.indexOf(menuItem);
91 if (index >= 0) {71 if (index >= 0) {
92 Render.setEngineDeferredDebugMode(index - 1);72 Render.deferredDebugMode = (index - 1);
93 }73 }
94}74}
95 75
@@ -98,24 +78,24 @@ var showDisplayStatusFlag = 1; · 2 unmodified lines
98var showNetworkStatusFlag = 2;78var showNetworkStatusFlag = 2;
99 79
100panel.newCheckbox("Display status",80panel.newCheckbox("Display status",
101 function(value) { Render.setEngineDisplayItemStatus(value ?81 function(value) { Render.displayItemStatus = (value ?
102 Render.doEngineDisplayItemStatus() | showDisplayStatusFlag :82 Render.displayItemStatus | showDisplayStatusFlag :
103 Render.doEngineDisplayItemStatus() & ~showDisplayStatusFlag); },83 Render.displayItemStatus & ~showDisplayStatusFlag); },
104 function() { return (Render.doEngineDisplayItemStatus() & showDisplayStatusFlag) > 0; },84 function() { return (Render.displayItemStatus & showDisplayStatusFlag) > 0; },
105 function(value) { return (value & showDisplayStatusFlag) > 0; }85 function(value) { return (value & showDisplayStatusFlag) > 0; }
106);86);
107 87
108panel.newCheckbox("Network/Physics status",88panel.newCheckbox("Network/Physics status",
109 function(value) { Render.setEngineDisplayItemStatus(value ?89 function(value) { Render.displayItemStatus = (value ?
110 Render.doEngineDisplayItemStatus() | showNetworkStatusFlag :90 Render.displayItemStatus | showNetworkStatusFlag :
111 Render.doEngineDisplayItemStatus() & ~showNetworkStatusFlag); },91 Render.displayItemStatus & ~showNetworkStatusFlag); },
112 function() { return (Render.doEngineDisplayItemStatus() & showNetworkStatusFlag) > 0; },92 function() { return (Render.displayItemStatus & showNetworkStatusFlag) > 0; },
113 function(value) { return (value & showNetworkStatusFlag) > 0; }93 function(value) { return (value & showNetworkStatusFlag) > 0; }
114);94);
115 95
116panel.newSlider("Tone Mapping Exposure", -10, 10,96panel.newSlider("Tone Mapping Exposure", -10, 10,
117 function (value) { Render.setEngineToneMappingExposure(value); },97 function (value) { Render.tone.exposure = value; },
118 function() { return Render.getEngineToneMappingExposure(); },98 function() { return Render.tone.exposure; },
119 function (value) { return (value); });99 function (value) { return (value); });
120 100
121var tickTackPeriod = 500;101var tickTackPeriod = 500;
@@ -160,9 +140,13 @@ Menu.menuItemEvent.connect(menuItemEvent); · 38 unmodified lines
160function scriptEnding() {140function scriptEnding() {
161 panel.destroy();141 panel.destroy();
162 Menu.removeActionGroup(MENU);142 Menu.removeActionGroup(MENU);
163 Settings.setValue(SETTINGS_KEY, Render.getEngineDeferredDebugMode());143 // Reset
164 Render.setEngineDeferredDebugMode(-1);144 Settings.setValue(SETTINGS_KEY, Render.deferredDebugMode);
165 Render.setEngineDeferredDebugSize({ x: 0.0, y: -1.0, z: 1.0, w: 1.0 }); // Reset to default size145 Render.deferredDebugMode = -1;
146 Render.deferredDebugSize = { x: 0.0, y: -1.0, z: 1.0, w: 1.0 };
147 Render.opaque.maxDrawn = -1;
148 Render.transparent.maxDrawn = -1;
149 Render.overlay3D.maxDrawn = -1;
166}150}
167Script.scriptEnding.connect(scriptEnding);151Script.scriptEnding.connect(scriptEnding);
168 152
examples/winterSmashUp/targetPractice/shooterPlatform.js+73−0
@@ -0,0 +1,73 @@
1//
2// shooterPlatform.js
3// examples/winterSmashUp/targetPractice
4//
5// Created by Thijs Wenker on 12/21/15.
6// Copyright 2015 High Fidelity, Inc.
7//
8// The Winter Smash Up Target Practice Game using a bow.
9// This is the platform that spawns the bow and attaches it to the avatars hand,
10// then de-rez the bow on leaving to prevent walking up to the targets with the bow.
11//
12// Distributed under the Apache License, Version 2.0.
13// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
14//
15
16(function() {
17 var _this = this;
18
19 const GAME_CHANNEL = 'winterSmashUpGame';
20 const SCRIPT_URL = Script.resolvePath('../../toybox/bow/bow.js');
21 const MODEL_URL = "https://hifi-public.s3.amazonaws.com/models/bow/new/bow-deadly.fbx";
22 const COLLISION_HULL_URL = "https://hifi-public.s3.amazonaws.com/models/bow/new/bow_collision_hull.obj";
23 const RIGHT_HAND = 1;
24 const LEFT_HAND = 0;
25
26 var bowEntity = undefined;
27
28 _this.enterEntity = function(entityID) {
29 print('entered bow game entity');
30
31 // Triggers a recording on an assignment client:
32 Messages.sendMessage('PlayBackOnAssignment', 'BowShootingGameExplaination');
33
34 bowEntity = Entities.addEntity({
35 name: 'Hifi-Bow-For-Game',
36 type: 'Model',
37 modelURL: MODEL_URL,
38 position: MyAvatar.position,
39 dimensions: {x: 0.04, y: 1.3, z: 0.21},
40 collisionsWillMove: true,
41 gravity: {x: 0, y: 0, z: 0},
42 shapeType: 'compound',
43 compoundShapeURL: COLLISION_HULL_URL,
44 script: SCRIPT_URL,
45 userData: JSON.stringify({
46 grabbableKey: {
47 invertSolidWhileHeld: true,
48 spatialKey: {
49 leftRelativePosition: {
50 x: 0.05,
51 y: 0.06,
52 z: -0.05
53 },
54 rightRelativePosition: {
55 x: -0.05,
56 y: 0.06,
57 z: -0.05
58 },
59 relativeRotation: Quat.fromPitchYawRollDegrees(0, 90, -90)
60 }
61 }
62 })
63 });
64 Messages.sendMessage('Hifi-Hand-Grab', JSON.stringify({hand: 'left', entityID: bowEntity}));
65 };
66
67 _this.leaveEntity = function(entityID) {
68 if (bowEntity !== undefined) {
69 Entities.deleteEntity(bowEntity);
70 bowEntity = undefined;
71 }
72 };
73});
examples/winterSmashUp/targetPractice/startTargetPractice.js+93−0
@@ -0,0 +1,93 @@
1//
2// startTargetPractice.js
3// examples/winterSmashUp/targetPractice
4//
5// Created by Thijs Wenker on 12/21/15.
6// Copyright 2015 High Fidelity, Inc.
7//
8// The Winter Smash Up Target Practice Game using a bow.
9// This script starts the game, when the entity that contains the script gets shot.
10//
11// Distributed under the Apache License, Version 2.0.
12// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
13//
14
15(function() {
16 var _this = this;
17 var waitForScriptLoad = false;
18
19 const MAX_GAME_TIME = 60; //seconds
20 const SCRIPT_URL = 'http://s3.amazonaws.com/hifi-public/scripts/winterSmashUp/targetPractice/targetPracticeGame.js';
21 const GAME_CHANNEL = 'winterSmashUpGame';
22
23 var isScriptRunning = function(script) {
24 script = script.toLowerCase().trim();
25 var runningScripts = ScriptDiscoveryService.getRunning();
26 for (i in runningScripts) {
27 if (runningScripts[i].url.toLowerCase().trim() == script) {
28 return true;
29 }
30 }
31 return false;
32 };
33
34 var sendStartSignal = function() {
35 Messages.sendMessage(GAME_CHANNEL, JSON.stringify({
36 action: 'start',
37 gameEntityID: _this.entityID,
38 playerSessionUUID: MyAvatar.sessionUUID
39 }));
40 }
41
42 var startGame = function() {
43 //TODO: check here if someone is already playing this game instance by verifying the userData for playerSessionID
44 // and startTime with a maximum timeout of X seconds (30?)
45
46
47 if (!isScriptRunning(SCRIPT_URL)) {
48 // Loads the script for the player if this isn't yet loaded
49 Script.load(SCRIPT_URL);
50 waitForScriptLoad = true;
51 return;
52 }
53 sendStartSignal();
54 };
55
56 Messages.messageReceived.connect(function (channel, message, senderID) {
57 if (channel == GAME_CHANNEL) {
58 var data = JSON.parse(message);
59 switch (data.action) {
60 case 'scriptLoaded':
61 if (waitForPing) {
62 sendStartSignal();
63 waitForPing = false;
64 }
65 break;
66 }
67 }
68 });
69
70 _this.preload = function(entityID) {
71 _this.entityID = entityID;
72 };
73
74 _this.collisionWithEntity = function(entityA, entityB, collisionInfo) {
75 if (entityA == _this.entityID) {
76 try {
77 var data = JSON.parse(Entities.getEntityProperties(entityB).userData);
78 if (data.creatorSessionUUID === MyAvatar.sessionUUID) {
79 print('attempting to startGame by collisionWithEntity.');
80 startGame();
81 }
82 } catch(e) {
83 }
84 }
85 };
86
87 _this.onShot = function(forceDirection) {
88 print('attempting to startGame by onShot.');
89 startGame();
90 };
91
92 Messages.subscribe(GAME_CHANNEL);
93});
examples/winterSmashUp/targetPractice/targetPracticeGame.js+227−0
@@ -0,0 +1,227 @@
1//
2// targetPracticeGame.js
3// examples/winterSmashUp/targetPractice
4//
5// Created by Thijs Wenker on 12/21/15.
6// Copyright 2015 High Fidelity, Inc.
7//
8// The Winter Smash Up Target Practice Game using a bow.
9// This script runs on the client side (it is loaded through the platform trigger entity)
10//
11// Distributed under the Apache License, Version 2.0.
12// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
13//
14
15const GAME_CHANNEL = 'winterSmashUpGame';
16const SCORE_POST_URL = 'https://script.google.com/macros/s/AKfycbwZAMx6cMBx6-8NGEhR8ELUA-dldtpa_4P55z38Q4vYHW6kneg/exec';
17const MODEL_URL = 'http://cdn.highfidelity.com/chris/production/winter/game/';
18const MAX_GAME_TIME = 120; //seconds
19const TARGET_CLOSE_OFFSET = 0.5;
20const MILLISECS_IN_SEC = 1000;
21const HIT_SOUND_URL = 'http://hifi-public.s3.amazonaws.com/sounds/Clay_Pigeon_02.L.wav';
22const GRAVITY = -9.8;
23const MESSAGE_WIDTH = 100;
24const MESSAGE_HEIGHT = 50;
25
26const TARGETS = [
27 {pitch: -1, yaw: -20, maxDistance: 17},
28 {pitch: -1, yaw: -15, maxDistance: 17},
29 {pitch: -1, yaw: -10, maxDistance: 17},
30 {pitch: -2, yaw: -5, maxDistance: 17},
31 {pitch: -1, yaw: 0, maxDistance: 17},
32 {pitch: 3, yaw: 10, maxDistance: 17},
33 {pitch: -1, yaw: 15, maxDistance: 17},
34 {pitch: -1, yaw: 20, maxDistance: 17},
35 {pitch: 2, yaw: 25, maxDistance: 17},
36 {pitch: 0, yaw: 30, maxDistance: 17}
37];
38
39var gameRunning = false;
40var gameStartTime;
41var gameEntityID;
42var gameTimeoutTimer;
43var targetEntities = [];
44var hitSound = SoundCache.getSound(HIT_SOUND_URL);
45var messageOverlay = undefined;
46var messageExpire = 0;
47
48var clearMessage = function() {
49 if (messageOverlay !== undefined) {
50 Overlays.deleteOverlay(messageOverlay);
51 messageOverlay = undefined;
52 }
53};
54
55var displayMessage = function(message, timeout) {
56 clearMessage();
57 messageExpire = Date.now() + timeout;
58 messageOverlay = Overlays.addOverlay('text', {
59 text: message,
60 x: (Window.innerWidth / 2) - (MESSAGE_WIDTH / 2),
61 y: (Window.innerHeight / 2) - (MESSAGE_HEIGHT / 2),
62 width: MESSAGE_WIDTH,
63 height: MESSAGE_HEIGHT,
64 alpha: 1,
65 backgroundAlpha: 0.0,
66 font: {size: 20}
67 });
68};
69
70var getStatsText = function() {
71 var timeLeft = MAX_GAME_TIME - ((Date.now() - gameStartTime) / MILLISECS_IN_SEC);
72 return 'Time remaining: ' + timeLeft.toFixed(1) + 's\nTargets hit: ' + (TARGETS.length - targetEntities.length) + '/' + TARGETS.length;
73};
74
75const timerOverlayWidth = 50;
76var timerOverlay = Overlays.addOverlay('text', {
77 text: '',
78 x: Window.innerWidth / 2 - (timerOverlayWidth / 2),
79 y: 100,
80 width: timerOverlayWidth,
81 alpha: 1,
82 backgroundAlpha: 0.0,
83 visible: false,
84 font: {size: 20}
85});
86
87var cleanRemainingTargets = function() {
88 while (targetEntities.length > 0) {
89 Entities.deleteEntity(targetEntities.pop());
90 }
91};
92
93var createTarget = function(position, rotation, scale) {
94 var initialDimensions = {x: 1.8437, y: 0.1614, z: 1.8438};
95 var dimensions = Vec3.multiply(initialDimensions, scale);
96 return Entities.addEntity({
97 type: 'Model',
98 rotation: Quat.multiply(rotation, Quat.fromPitchYawRollDegrees(90, 0, 0)),
99 lifetime: MAX_GAME_TIME,
100 modelURL: MODEL_URL + 'target.fbx',
101 shapeType: 'compound',
102 compoundShapeURL: MODEL_URL + 'targetCollision.obj',
103 dimensions: dimensions,
104 position: position
105 });
106};
107
108var createTargetInDirection = function(startPosition, startRotation, pitch, yaw, maxDistance, scale) {
109 var directionQuat = Quat.multiply(startRotation, Quat.fromPitchYawRollDegrees(pitch, yaw, 0.0));
110 var directionVec = Vec3.multiplyQbyV(directionQuat, Vec3.FRONT);
111 var intersection = Entities.findRayIntersection({direction: directionVec, origin: startPosition}, true);
112 var distance = maxDistance;
113 if (intersection.intersects && intersection.distance <= maxDistance) {
114 distance = intersection.distance - TARGET_CLOSE_OFFSET;
115 }
116 return createTarget(Vec3.sum(startPosition, Vec3.multiplyQbyV(directionQuat, Vec3.multiply(Vec3.FRONT, distance))), startRotation, scale);
117};
118
119var killTimer = function() {
120 if (gameTimeoutTimer !== undefined) {
121 Script.clearTimeout(gameTimeoutTimer);
122 gameTimeoutTimer = undefined;
123 }
124};
125
126var submitScore = function() {
127 gameRunning = false;
128 killTimer();
129 Overlays.editOverlay(timerOverlay, {visible: false});
130 if (!GlobalServices.username) {
131 displayMessage('Could not submit score, you are not logged in.', 5000);
132 return;
133 }
134 var timeItTook = Date.now() - gameStartTime;
135 var req = new XMLHttpRequest();
136 req.open('POST', SCORE_POST_URL, false);
137 req.send(JSON.stringify({
138 username: GlobalServices.username,
139 time: timeItTook / MILLISECS_IN_SEC
140 }));
141 displayMessage('Your score has been submitted!', 5000);
142};
143
144var onTargetHit = function(targetEntity, projectileEntity, collision) {
145 var targetIndex = targetEntities.indexOf(targetEntity);
146 if (targetIndex !== -1) {
147 try {
148 var data = JSON.parse(Entities.getEntityProperties(projectileEntity).userData);
149 if (data.creatorSessionUUID === MyAvatar.sessionUUID) {
150 this.audioInjector = Audio.playSound(hitSound, {
151 position: collision.contactPoint,
152 volume: 0.5
153 });
154 // Attach arrow to target for the nice effect
155 Entities.editEntity(projectileEntity, {
156 ignoreForCollisions: true,
157 parentID: targetEntity
158 });
159 Entities.editEntity(targetEntity, {
160 collisionsWillMove: true,
161 gravity: {x: 0, y: GRAVITY, z: 0},
162 velocity: {x: 0, y: -0.01, z: 0}
163 });
164 targetEntities.splice(targetIndex, 1);
165 if (targetEntities.length === 0) {
166 submitScore();
167 }
168 }
169 } catch(e) {
170 }
171 }
172};
173
174var startGame = function(entityID) {
175 cleanRemainingTargets();
176 killTimer();
177 gameEntityID = entityID;
178 targetEntities = [];
179 var parentEntity = Entities.getEntityProperties(gameEntityID);
180 for (var i in TARGETS) {
181 var target = TARGETS[i];
182 var targetEntity = createTargetInDirection(parentEntity.position, parentEntity.rotation, target.pitch, target.yaw, target.maxDistance, 0.67);
183 Script.addEventHandler(targetEntity, 'collisionWithEntity', onTargetHit);
184 targetEntities.push(targetEntity);
185 }
186 gameStartTime = Date.now();
187 gameTimeoutTimer = Script.setTimeout(function() {
188 cleanRemainingTargets();
189 Overlays.editOverlay(timerOverlay, {visible: false});
190 gameRunning = false;
191 displayMessage('Game timed out.', 5000);
192 }, MAX_GAME_TIME * MILLISECS_IN_SEC);
193 gameRunning = true;
194 Overlays.editOverlay(timerOverlay, {visible: true, text: getStatsText()});
195 displayMessage('Game started! GO GO GO!', 3000);
196};
197
198Messages.messageReceived.connect(function (channel, message, senderID) {
199 if (channel == GAME_CHANNEL) {
200 var data = JSON.parse(message);
201 switch (data.action) {
202 case 'start':
203 if (data.playerSessionUUID === MyAvatar.sessionUUID) {
204 startGame(data.gameEntityID);
205 }
206 break;
207 }
208 }
209});
210
211Messages.subscribe(GAME_CHANNEL);
212Messages.sendMessage(GAME_CHANNEL, JSON.stringify({action: 'scriptLoaded'}));
213
214Script.update.connect(function(deltaTime) {
215 if (gameRunning) {
216 Overlays.editOverlay(timerOverlay, {text: getStatsText()});
217 }
218 if (messageOverlay !== undefined && Date.now() > messageExpire) {
219 clearMessage();
220 }
221});
222
223Script.scriptEnding.connect(function() {
224 Overlays.deleteOverlay(timerOverlay);
225 cleanRemainingTargets();
226 clearMessage();
227});
interface/resources/qml/QmlWebWindow.qml+17−6
@@ -13,12 +13,18 @@ VrDialog { · 12 unmodified lines
13 HifiConstants { id: hifi }13 HifiConstants { id: hifi }
14 title: "WebWindow"14 title: "WebWindow"
15 resizable: true15 resizable: true
16 // Don't destroy on close... otherwise the JS/C++ will have a dangling pointer
17 destroyOnCloseButton: false
16 contentImplicitWidth: clientArea.implicitWidth18 contentImplicitWidth: clientArea.implicitWidth
17 contentImplicitHeight: clientArea.implicitHeight19 contentImplicitHeight: clientArea.implicitHeight
18 backgroundColor: "#7f000000"20 backgroundColor: "#7f000000"
19 property url source: "about:blank"21 property url source: "about:blank"
20 22
21 signal navigating(string url)23 signal navigating(string url)
24 function stop() {
25 webview.stop();
26 }
27
22 28
23 Component.onCompleted: {29 Component.onCompleted: {
24 enabled = true30 enabled = true
@@ -26,18 +32,14 @@ VrDialog { · 1 unmodified line
26 webview.javaScriptConsoleMessage.connect(function(level, message, lineNumber, sourceID) {32 webview.javaScriptConsoleMessage.connect(function(level, message, lineNumber, sourceID) {
27 console.log("Web Window JS message: " + sourceID + " " + lineNumber + " " + message);33 console.log("Web Window JS message: " + sourceID + " " + lineNumber + " " + message);
28 });34 });
29
30 webview.loadingChanged.connect(handleWebviewLoading) 35 webview.loadingChanged.connect(handleWebviewLoading)
31 }36 }
32 37
33 38
34 function handleWebviewLoading(loadRequest) {39 function handleWebviewLoading(loadRequest) {
35 var HIFI_URL_PATTERN = /^hifi:\/\//;
36 if (WebEngineView.LoadStartedStatus == loadRequest.status) {40 if (WebEngineView.LoadStartedStatus == loadRequest.status) {
37 var newUrl = loadRequest.url.toString();41 var newUrl = loadRequest.url.toString();
38 if (newUrl.match(HIFI_URL_PATTERN)) {42 root.navigating(newUrl)
39 root.navigating(newUrl);
40 }
41 }43 }
42 }44 }
43 45
@@ -54,9 +56,18 @@ VrDialog { · 10 unmodified lines
54 id: webview56 id: webview
55 url: root.source57 url: root.source
56 anchors.fill: parent58 anchors.fill: parent
59 onUrlChanged: {
60 var currentUrl = url.toString();
61 var newUrl = urlFixer.fixupUrl(currentUrl);
62 if (newUrl != currentUrl) {
63 url = newUrl;
64 }
65 }
57 profile: WebEngineProfile {66 profile: WebEngineProfile {
67 id: webviewProfile
58 httpUserAgent: "Mozilla/5.0 (HighFidelityInterface)"68 httpUserAgent: "Mozilla/5.0 (HighFidelityInterface)"
59 }69 storageName: "qmlWebEngine"
70 }
60 }71 }
61 } // item72 } // item
62} // dialog73} // dialog
interface/src/Application.cpp+13−81
@@ -1207,23 +1207,12 @@ void Application::paintGL() { · 1206 unmodified lines
1207 auto primaryFbo = DependencyManager::get<FramebufferCache>()->getPrimaryFramebuffer();1207 auto primaryFbo = DependencyManager::get<FramebufferCache>()->getPrimaryFramebuffer();
1208 1208
1209 renderArgs._renderMode = RenderArgs::MIRROR_RENDER_MODE;1209 renderArgs._renderMode = RenderArgs::MIRROR_RENDER_MODE;
1210 renderArgs._blitFramebuffer = DependencyManager::get<FramebufferCache>()->getSelfieFramebuffer();
1211
1210 renderRearViewMirror(&renderArgs, _mirrorViewRect);1212 renderRearViewMirror(&renderArgs, _mirrorViewRect);
1211 renderArgs._renderMode = RenderArgs::DEFAULT_RENDER_MODE;
1212 1213
1213 {1214 renderArgs._blitFramebuffer.reset();
1214 float ratio = ((float)QApplication::desktop()->windowHandle()->devicePixelRatio() * getRenderResolutionScale());1215 renderArgs._renderMode = RenderArgs::DEFAULT_RENDER_MODE;
1215 // Flip the src and destination rect horizontally to do the mirror
1216 auto mirrorRect = glm::ivec4(0, 0, _mirrorViewRect.width() * ratio, _mirrorViewRect.height() * ratio);
1217 auto mirrorRectDest = glm::ivec4(mirrorRect.z, mirrorRect.y, mirrorRect.x, mirrorRect.w);
1218
1219 auto selfieFbo = DependencyManager::get<FramebufferCache>()->getSelfieFramebuffer();
1220 gpu::doInBatch(renderArgs._context, [=](gpu::Batch& batch) {
1221 batch.setFramebuffer(selfieFbo);
1222 batch.clearColorFramebuffer(gpu::Framebuffer::BUFFER_COLOR0, glm::vec4(0.0f, 0.0f, 0.0f, 0.0f));
1223 batch.blit(primaryFbo, mirrorRect, selfieFbo, mirrorRectDest);
1224 batch.setFramebuffer(nullptr);
1225 });
1226 }
1227 }1216 }
1228 1217
1229 {1218 {
@@ -1394,65 +1383,11 @@ void Application::paintGL() { · 164 unmodified lines
1394 renderArgs._context->setStereoProjections(eyeProjections);1383 renderArgs._context->setStereoProjections(eyeProjections);
1395 renderArgs._context->setStereoViews(eyeOffsets);1384 renderArgs._context->setStereoViews(eyeOffsets);
1396 }1385 }
1386 renderArgs._blitFramebuffer = finalFramebuffer;
1397 displaySide(&renderArgs, _myCamera);1387 displaySide(&renderArgs, _myCamera);
1398 renderArgs._context->enableStereo(false);
1399 1388
1400 // Blit primary to final FBO1389 renderArgs._blitFramebuffer.reset();
1401 auto primaryFbo = framebufferCache->getPrimaryFramebuffer();1390 renderArgs._context->enableStereo(false);
1402
1403 if (renderArgs._renderMode == RenderArgs::MIRROR_RENDER_MODE) {
1404 if (displayPlugin->isStereo()) {
1405 gpu::doInBatch(renderArgs._context, [=](gpu::Batch& batch) {
1406 gpu::Vec4i srcRectLeft;
1407 srcRectLeft.z = size.width() / 2;
1408 srcRectLeft.w = size.height();
1409
1410 gpu::Vec4i srcRectRight;
1411 srcRectRight.x = size.width() / 2;
1412 srcRectRight.z = size.width();
1413 srcRectRight.w = size.height();
1414
1415 gpu::Vec4i destRectLeft;
1416 destRectLeft.x = srcRectLeft.z;
1417 destRectLeft.z = srcRectLeft.x;
1418 destRectLeft.y = srcRectLeft.y;
1419 destRectLeft.w = srcRectLeft.w;
1420
1421 gpu::Vec4i destRectRight;
1422 destRectRight.x = srcRectRight.z;
1423 destRectRight.z = srcRectRight.x;
1424 destRectRight.y = srcRectRight.y;
1425 destRectRight.w = srcRectRight.w;
1426
1427 batch.setFramebuffer(finalFramebuffer);
1428 batch.clearColorFramebuffer(gpu::Framebuffer::BUFFER_COLOR0, glm::vec4(0.0f, 0.0f, 1.0f, 0.0f));
1429 // BLit left to right and right to left in stereo
1430 batch.blit(primaryFbo, srcRectRight, finalFramebuffer, destRectLeft);
1431 batch.blit(primaryFbo, srcRectLeft, finalFramebuffer, destRectRight);
1432 });
1433 } else {
1434 gpu::doInBatch(renderArgs._context, [=](gpu::Batch& batch) {
1435 gpu::Vec4i srcRect;
1436 srcRect.z = size.width();
1437 srcRect.w = size.height();
1438 gpu::Vec4i destRect;
1439 destRect.x = size.width();
1440 destRect.y = 0;
1441 destRect.z = 0;
1442 destRect.w = size.height();
1443 batch.setFramebuffer(finalFramebuffer);
1444 batch.blit(primaryFbo, srcRect, finalFramebuffer, destRect);
1445 });
1446 }
1447 } else {
1448 gpu::doInBatch(renderArgs._context, [=](gpu::Batch& batch) {
1449 gpu::Vec4i rect;
1450 rect.z = size.width();
1451 rect.w = size.height();
1452 batch.setFramebuffer(finalFramebuffer);
1453 batch.blit(primaryFbo, rect, finalFramebuffer, rect);
1454 });
1455 }
1456 }1391 }
1457 1392
1458 // Overlay Composition, needs to occur after screen space effects have completed1393 // Overlay Composition, needs to occur after screen space effects have completed
@@ -3721,21 +3656,18 @@ void Application::displaySide(RenderArgs* renderArgs, Camera& theCamera, bool se · 2262 unmodified lines
3721 {3656 {
3722 PerformanceTimer perfTimer("EngineRun");3657 PerformanceTimer perfTimer("EngineRun");
3723 3658
3659 auto renderInterface = DependencyManager::get<RenderScriptingInterface>();
3660 auto renderContext = renderInterface->getRenderContext();
3661
3724 renderArgs->_shouldRender = LODManager::shouldRender;3662 renderArgs->_shouldRender = LODManager::shouldRender;
3725 renderArgs->_viewFrustum = getDisplayViewFrustum();3663 renderArgs->_viewFrustum = getDisplayViewFrustum();
3726 3664 renderContext.setArgs(renderArgs);
3727 auto renderInterface = DependencyManager::get<RenderScriptingInterface>();
3728 auto renderItemsConfig = renderInterface->getItemsConfig();
3729 auto renderTone = renderInterface->getTone();
3730 int drawStatus = renderInterface->getDrawStatus();
3731 bool drawHitEffect = renderInterface->getDrawHitEffect();
3732 3665
3733 bool occlusionStatus = Menu::getInstance()->isOptionChecked(MenuOption::DebugAmbientOcclusion);3666 bool occlusionStatus = Menu::getInstance()->isOptionChecked(MenuOption::DebugAmbientOcclusion);
3734 bool antialiasingStatus = Menu::getInstance()->isOptionChecked(MenuOption::Antialiasing);3667 bool antialiasingStatus = Menu::getInstance()->isOptionChecked(MenuOption::Antialiasing);
3735 bool showOwnedStatus = Menu::getInstance()->isOptionChecked(MenuOption::PhysicsShowOwned);3668 bool showOwnedStatus = Menu::getInstance()->isOptionChecked(MenuOption::PhysicsShowOwned);
3669 renderContext.setOptions(occlusionStatus, antialiasingStatus, showOwnedStatus);
3736 3670
3737 render::RenderContext renderContext{renderArgs, renderItemsConfig, renderTone};
3738 renderContext.setOptions(drawStatus, drawHitEffect, occlusionStatus, antialiasingStatus, showOwnedStatus);
3739 _renderEngine->setRenderContext(renderContext);3671 _renderEngine->setRenderContext(renderContext);
3740 3672
3741 // Before the deferred pass, let's try to use the render engine3673 // Before the deferred pass, let's try to use the render engine
@@ -4204,7 +4136,7 @@ void Application::registerScriptEngineWithApplicationServices(ScriptEngine* scri · 462 unmodified lines
4204 scriptEngine->registerGlobalObject("ScriptDiscoveryService", this->getRunningScriptsWidget());4136 scriptEngine->registerGlobalObject("ScriptDiscoveryService", this->getRunningScriptsWidget());
4205}4137}
4206 4138
4207bool Application::canAcceptURL(const QString& urlString) {4139bool Application::canAcceptURL(const QString& urlString) const {
4208 QUrl url(urlString);4140 QUrl url(urlString);
4209 if (urlString.startsWith(HIFI_URL_SCHEME)) {4141 if (urlString.startsWith(HIFI_URL_SCHEME)) {
4210 return true;4142 return true;
interface/src/Application.h+4−3
@@ -38,6 +38,7 @@ · 37 unmodified lines
38#include <SimpleMovingAverage.h>38#include <SimpleMovingAverage.h>
39#include <StDev.h>39#include <StDev.h>
40#include <ViewFrustum.h>40#include <ViewFrustum.h>
41#include <AbstractUriHandler.h>
41 42
42#include "avatar/AvatarUpdate.h"43#include "avatar/AvatarUpdate.h"
43#include "avatar/MyAvatar.h"44#include "avatar/MyAvatar.h"
@@ -88,7 +89,7 @@ class Application; · 44 unmodified lines
88#endif89#endif
89#define qApp (static_cast<Application*>(QCoreApplication::instance()))90#define qApp (static_cast<Application*>(QCoreApplication::instance()))
90 91
91class Application : public QApplication, public AbstractViewStateInterface, public AbstractScriptingServicesInterface {92class Application : public QApplication, public AbstractViewStateInterface, public AbstractScriptingServicesInterface, public AbstractUriHandler {
92 Q_OBJECT93 Q_OBJECT
93 94
94 // TODO? Get rid of those95 // TODO? Get rid of those
@@ -219,8 +220,8 @@ public: · 124 unmodified lines
219 QString getScriptsLocation();220 QString getScriptsLocation();
220 void setScriptsLocation(const QString& scriptsLocation);221 void setScriptsLocation(const QString& scriptsLocation);
221 222
222 bool canAcceptURL(const QString& url);223 virtual bool canAcceptURL(const QString& url) const override;
223 bool acceptURL(const QString& url, bool defaultUpload = false);224 virtual bool acceptURL(const QString& url, bool defaultUpload = false) override;
224 225
225 void setMaxOctreePacketsPerSecond(int maxOctreePPS);226 void setMaxOctreePacketsPerSecond(int maxOctreePPS);
226 int getMaxOctreePacketsPerSecond();227 int getMaxOctreePacketsPerSecond();
libraries/audio/src/AudioInjector.cpp+0−1
@@ -289,7 +289,6 @@ uint64_t AudioInjector::injectNextFrame() { · 288 unmodified lines
289 _currentSendOffset = 0;289 _currentSendOffset = 0;
290 } else {290 } else {
291 // we weren't to loop, say that we're done now291 // we weren't to loop, say that we're done now
292 qDebug() << "AudioInjector::injectNextFrame has sent all data and was not asked to loop - calling finish().";
293 finish();292 finish();
294 return NEXT_FRAME_DELTA_ERROR_OR_FINISHED;293 return NEXT_FRAME_DELTA_ERROR_OR_FINISHED;
295 }294 }
libraries/entities-renderer/src/EntityTreeRenderer.cpp+36−30
@@ -256,33 +256,38 @@ void EntityTreeRenderer::forceRecheckEntities() { · 255 unmodified lines
256 256
257void EntityTreeRenderer::applyZonePropertiesToScene(std::shared_ptr<ZoneEntityItem> zone) {257void EntityTreeRenderer::applyZonePropertiesToScene(std::shared_ptr<ZoneEntityItem> zone) {
258 QSharedPointer<SceneScriptingInterface> scene = DependencyManager::get<SceneScriptingInterface>();258 QSharedPointer<SceneScriptingInterface> scene = DependencyManager::get<SceneScriptingInterface>();
259 auto sceneStage = scene->getStage();
260 auto sceneKeyLight = sceneStage->getKeyLight();
261 auto sceneLocation = sceneStage->getLocation();
262 auto sceneTime = sceneStage->getTime();
263
259 if (zone) {264 if (zone) {
260 if (!_hasPreviousZone) {265 if (!_hasPreviousZone) {
261 _previousKeyLightColor = scene->getKeyLightColor();266 _previousKeyLightColor = sceneKeyLight->getColor();
262 _previousKeyLightIntensity = scene->getKeyLightIntensity();267 _previousKeyLightIntensity = sceneKeyLight->getIntensity();
263 _previousKeyLightAmbientIntensity = scene->getKeyLightAmbientIntensity();268 _previousKeyLightAmbientIntensity = sceneKeyLight->getAmbientIntensity();
264 _previousKeyLightDirection = scene->getKeyLightDirection();269 _previousKeyLightDirection = sceneKeyLight->getDirection();
265 _previousStageSunModelEnabled = scene->isStageSunModelEnabled();270 _previousStageSunModelEnabled = sceneStage->isSunModelEnabled();
266 _previousStageLongitude = scene->getStageLocationLongitude();271 _previousStageLongitude = sceneLocation->getLongitude();
267 _previousStageLatitude = scene->getStageLocationLatitude();272 _previousStageLatitude = sceneLocation->getLatitude();
268 _previousStageAltitude = scene->getStageLocationAltitude();273 _previousStageAltitude = sceneLocation->getAltitude();
269 _previousStageHour = scene->getStageDayTime();274 _previousStageHour = sceneTime->getHour();
270 _previousStageDay = scene->getStageYearTime();275 _previousStageDay = sceneTime->getDay();
271 _hasPreviousZone = true;276 _hasPreviousZone = true;
272 }277 }
273 scene->setKeyLightColor(ColorUtils::toVec3(zone->getKeyLightProperties().getColor()));278 sceneKeyLight->setColor(ColorUtils::toVec3(zone->getKeyLightProperties().getColor()));
274 scene->setKeyLightIntensity(zone->getKeyLightProperties().getIntensity());279 sceneKeyLight->setIntensity(zone->getKeyLightProperties().getIntensity());
275 scene->setKeyLightAmbientIntensity(zone->getKeyLightProperties().getAmbientIntensity());280 sceneKeyLight->setAmbientIntensity(zone->getKeyLightProperties().getAmbientIntensity());
276 scene->setKeyLightDirection(zone->getKeyLightProperties().getDirection());281 sceneKeyLight->setDirection(zone->getKeyLightProperties().getDirection());
277 scene->setStageSunModelEnable(zone->getStageProperties().getSunModelEnabled());282 sceneStage->setSunModelEnable(zone->getStageProperties().getSunModelEnabled());
278 scene->setStageLocation(zone->getStageProperties().getLongitude(), zone->getStageProperties().getLatitude(),283 sceneStage->setLocation(zone->getStageProperties().getLongitude(), zone->getStageProperties().getLatitude(),
279 zone->getStageProperties().getAltitude());284 zone->getStageProperties().getAltitude());
280 scene->setStageDayTime(zone->getStageProperties().calculateHour());285 sceneTime->setHour(zone->getStageProperties().calculateHour());
281 scene->setStageYearTime(zone->getStageProperties().calculateDay());286 sceneTime->setDay(zone->getStageProperties().calculateDay());
282 287
283 if (zone->getBackgroundMode() == BACKGROUND_MODE_ATMOSPHERE) {288 if (zone->getBackgroundMode() == BACKGROUND_MODE_ATMOSPHERE) {
284 EnvironmentData data = zone->getEnvironmentData();289 EnvironmentData data = zone->getEnvironmentData();
285 glm::vec3 keyLightDirection = scene->getKeyLightDirection();290 glm::vec3 keyLightDirection = sceneKeyLight->getDirection();
286 glm::vec3 inverseKeyLightDirection = keyLightDirection * -1.0f;291 glm::vec3 inverseKeyLightDirection = keyLightDirection * -1.0f;
287 292
288 // NOTE: is this right? It seems like the "sun" should be based on the center of the293 // NOTE: is this right? It seems like the "sun" should be based on the center of the
@@ -293,7 +298,7 @@ void EntityTreeRenderer::applyZonePropertiesToScene(std::shared_ptr<ZoneEntityIt · 4 unmodified lines
293 data.setSunLocation(keyLightLocation);298 data.setSunLocation(keyLightLocation);
294 299
295 const float KEY_LIGHT_INTENSITY_TO_SUN_BRIGHTNESS_RATIO = 20.0f;300 const float KEY_LIGHT_INTENSITY_TO_SUN_BRIGHTNESS_RATIO = 20.0f;
296 float sunBrightness = scene->getKeyLightIntensity() * KEY_LIGHT_INTENSITY_TO_SUN_BRIGHTNESS_RATIO;301 float sunBrightness = sceneKeyLight->getIntensity() * KEY_LIGHT_INTENSITY_TO_SUN_BRIGHTNESS_RATIO;
297 data.setSunBrightness(sunBrightness);302 data.setSunBrightness(sunBrightness);
298 303
299 _viewState->overrideEnvironmentData(data);304 _viewState->overrideEnvironmentData(data);
@@ -339,15 +344,15 @@ void EntityTreeRenderer::applyZonePropertiesToScene(std::shared_ptr<ZoneEntityIt · 39 unmodified lines
339 } else {344 } else {
340 _pendingSkyboxTextureDownload = false;345 _pendingSkyboxTextureDownload = false;
341 if (_hasPreviousZone) {346 if (_hasPreviousZone) {
342 scene->setKeyLightColor(_previousKeyLightColor);347 sceneKeyLight->setColor(_previousKeyLightColor);
343 scene->setKeyLightIntensity(_previousKeyLightIntensity);348 sceneKeyLight->setIntensity(_previousKeyLightIntensity);
344 scene->setKeyLightAmbientIntensity(_previousKeyLightAmbientIntensity);349 sceneKeyLight->setAmbientIntensity(_previousKeyLightAmbientIntensity);
345 scene->setKeyLightDirection(_previousKeyLightDirection);350 sceneKeyLight->setDirection(_previousKeyLightDirection);
346 scene->setStageSunModelEnable(_previousStageSunModelEnabled);351 sceneStage->setSunModelEnable(_previousStageSunModelEnabled);
347 scene->setStageLocation(_previousStageLongitude, _previousStageLatitude,352 sceneStage->setLocation(_previousStageLongitude, _previousStageLatitude,
348 _previousStageAltitude);353 _previousStageAltitude);
349 scene->setStageDayTime(_previousStageHour);354 sceneTime->setHour(_previousStageHour);
350 scene->setStageYearTime(_previousStageDay);355 sceneTime->setDay(_previousStageDay);
351 _hasPreviousZone = false;356 _hasPreviousZone = false;
352 }357 }
353 _viewState->endOverrideEnvironmentData();358 _viewState->endOverrideEnvironmentData();
@@ -482,7 +487,8 @@ void EntityTreeRenderer::deleteReleasedModels() { · 128 unmodified lines
482}487}
483 488
484RayToEntityIntersectionResult EntityTreeRenderer::findRayIntersectionWorker(const PickRay& ray, Octree::lockType lockType,489RayToEntityIntersectionResult EntityTreeRenderer::findRayIntersectionWorker(const PickRay& ray, Octree::lockType lockType,
485 bool precisionPicking, const QVector<EntityItemID>& entityIdsToInclude) {490 bool precisionPicking, const QVector<EntityItemID>& entityIdsToInclude,
491 const QVector<EntityItemID>& entityIdsToDiscard) {
486 RayToEntityIntersectionResult result;492 RayToEntityIntersectionResult result;
487 if (_tree) {493 if (_tree) {
488 EntityTreePointer entityTree = std::static_pointer_cast<EntityTree>(_tree);494 EntityTreePointer entityTree = std::static_pointer_cast<EntityTree>(_tree);
@@ -490,7 +496,7 @@ RayToEntityIntersectionResult EntityTreeRenderer::findRayIntersectionWorker(cons · 1 unmodified line
490 OctreeElementPointer element;496 OctreeElementPointer element;
491 EntityItemPointer intersectedEntity = NULL;497 EntityItemPointer intersectedEntity = NULL;
492 result.intersects = entityTree->findRayIntersection(ray.origin, ray.direction, element, result.distance, 498 result.intersects = entityTree->findRayIntersection(ray.origin, ray.direction, element, result.distance,
493 result.face, result.surfaceNormal, entityIdsToInclude,499 result.face, result.surfaceNormal, entityIdsToInclude, entityIdsToDiscard,
494 (void**)&intersectedEntity, lockType, &result.accurate,500 (void**)&intersectedEntity, lockType, &result.accurate,
495 precisionPicking);501 precisionPicking);
496 if (result.intersects && intersectedEntity) {502 if (result.intersects && intersectedEntity) {
libraries/entities-renderer/src/EntityTreeRenderer.h+2−1
@@ -130,7 +130,8 @@ private: · 129 unmodified lines
130 130
131 QList<Model*> _releasedModels;131 QList<Model*> _releasedModels;
132 RayToEntityIntersectionResult findRayIntersectionWorker(const PickRay& ray, Octree::lockType lockType,132 RayToEntityIntersectionResult findRayIntersectionWorker(const PickRay& ray, Octree::lockType lockType,
133 bool precisionPicking, const QVector<EntityItemID>& entityIdsToInclude = QVector<EntityItemID>());133 bool precisionPicking, const QVector<EntityItemID>& entityIdsToInclude = QVector<EntityItemID>(),
134 const QVector<EntityItemID>& entityIdsToDiscard = QVector<EntityItemID>());
134 135
135 EntityItemID _currentHoverOverEntityID;136 EntityItemID _currentHoverOverEntityID;
136 EntityItemID _currentClickingOnEntityID;137 EntityItemID _currentClickingOnEntityID;
libraries/entities-renderer/src/RenderableParticleEffectEntityItem.cpp+5−2
@@ -240,8 +240,11 @@ void RenderableParticleEffectEntityItem::updateRenderItem() { · 239 unmodified lines
240 auto position = getPosition();240 auto position = getPosition();
241 auto rotation = getRotation();241 auto rotation = getRotation();
242 Transform transform;242 Transform transform;
243 transform.setTranslation(position);243 if (!getEmitterShouldTrail()) {
244 transform.setRotation(rotation);244 transform.setTranslation(position);
245 transform.setRotation(rotation);
246 }
247
245 248
246 render::PendingChanges pendingChanges;249 render::PendingChanges pendingChanges;
247 pendingChanges.updateItem<ParticlePayloadData>(_renderItemId, [=](ParticlePayloadData& payload) {250 pendingChanges.updateItem<ParticlePayloadData>(_renderItemId, [=](ParticlePayloadData& payload) {
libraries/entities-renderer/src/RenderablePolyLineEntityItem.cpp+29−34
@@ -23,6 +23,13 @@ · 22 unmodified lines
23#include "paintStroke_frag.h"23#include "paintStroke_frag.h"
24 24
25 25
26
27struct PolyLineUniforms {
28 glm::vec3 color;
29};
30
31
32
26EntityItemPointer RenderablePolyLineEntityItem::factory(const EntityItemID& entityID, const EntityItemProperties& properties) {33EntityItemPointer RenderablePolyLineEntityItem::factory(const EntityItemID& entityID, const EntityItemProperties& properties) {
27 EntityItemPointer entity{ new RenderablePolyLineEntityItem(entityID) };34 EntityItemPointer entity{ new RenderablePolyLineEntityItem(entityID) };
28 entity->setProperties(properties);35 entity->setProperties(properties);
@@ -30,9 +37,12 @@ EntityItemPointer RenderablePolyLineEntityItem::factory(const EntityItemID& enti · 1 unmodified line
30}37}
31 38
32RenderablePolyLineEntityItem::RenderablePolyLineEntityItem(const EntityItemID& entityItemID) :39RenderablePolyLineEntityItem::RenderablePolyLineEntityItem(const EntityItemID& entityItemID) :
33 PolyLineEntityItem(entityItemID) {40PolyLineEntityItem(entityItemID),
34 _numVertices = 0;41_numVertices(0)
42{
35 _vertices = QVector<glm::vec3>(0.0f);43 _vertices = QVector<glm::vec3>(0.0f);
44 PolyLineUniforms uniforms;
45 _uniformBuffer = std::make_shared<gpu::Buffer>(sizeof(PolyLineUniforms), (const gpu::Byte*) &uniforms);
36}46}
37 47
38gpu::PipelinePointer RenderablePolyLineEntityItem::_pipeline;48gpu::PipelinePointer RenderablePolyLineEntityItem::_pipeline;
@@ -41,13 +51,11 @@ int32_t RenderablePolyLineEntityItem::PAINTSTROKE_GPU_SLOT; · 2 unmodified lines
41 51
42void RenderablePolyLineEntityItem::createPipeline() {52void RenderablePolyLineEntityItem::createPipeline() {
43 static const int NORMAL_OFFSET = 12;53 static const int NORMAL_OFFSET = 12;
44 static const int COLOR_OFFSET = 24;54 static const int TEXTURE_OFFSET = 24;
45 static const int TEXTURE_OFFSET = 28;
46 55
47 _format.reset(new gpu::Stream::Format());56 _format.reset(new gpu::Stream::Format());
48 _format->setAttribute(gpu::Stream::POSITION, 0, gpu::Element(gpu::VEC3, gpu::FLOAT, gpu::XYZ), 0);57 _format->setAttribute(gpu::Stream::POSITION, 0, gpu::Element(gpu::VEC3, gpu::FLOAT, gpu::XYZ), 0);
49 _format->setAttribute(gpu::Stream::NORMAL, 0, gpu::Element(gpu::VEC3, gpu::FLOAT, gpu::XYZ), NORMAL_OFFSET);58 _format->setAttribute(gpu::Stream::NORMAL, 0, gpu::Element(gpu::VEC3, gpu::FLOAT, gpu::XYZ), NORMAL_OFFSET);
50 _format->setAttribute(gpu::Stream::COLOR, 0, gpu::Element::COLOR_RGBA_32, COLOR_OFFSET);
51 _format->setAttribute(gpu::Stream::TEXCOORD, 0, gpu::Element(gpu::VEC2, gpu::FLOAT, gpu::UV), TEXTURE_OFFSET);59 _format->setAttribute(gpu::Stream::TEXCOORD, 0, gpu::Element(gpu::VEC2, gpu::FLOAT, gpu::UV), TEXTURE_OFFSET);
52 60
53 auto VS = gpu::Shader::createVertex(std::string(paintStroke_vert));61 auto VS = gpu::Shader::createVertex(std::string(paintStroke_vert));
@@ -72,47 +80,28 @@ void RenderablePolyLineEntityItem::updateGeometry() { · 18 unmodified lines
72 _verticesBuffer.reset(new gpu::Buffer());80 _verticesBuffer.reset(new gpu::Buffer());
73 int vertexIndex = 0;81 int vertexIndex = 0;
74 vec2 uv;82 vec2 uv;
75 float tailStart = 0.0f;
76 float tailEnd = 0.25f;
77 float tailLength = tailEnd - tailStart;
78
79 float headStart = 0.76f;
80 float headEnd = 1.0f;
81 float headLength = headEnd - headStart;
82 float uCoord, vCoord;83 float uCoord, vCoord;
83 84 uCoord = 0.0f;
84 int numTailStrips = 5;85 float uCoordInc = 1.0 / (_vertices.size() / 2);
85 int numHeadStrips = 10;
86 int startHeadIndex = _vertices.size() / 2 - numHeadStrips;
87 for (int i = 0; i < _vertices.size() / 2; i++) {86 for (int i = 0; i < _vertices.size() / 2; i++) {
88 uCoord = 0.26f;
89 vCoord = 0.0f;87 vCoord = 0.0f;
90 //tail88
91 if (i < numTailStrips) {
92 uCoord = float(i) / numTailStrips * tailLength + tailStart;
93 }
94
95 //head
96 if (i > startHeadIndex) {
97 uCoord = float((i + 1) - startHeadIndex) / numHeadStrips * headLength + headStart;
98 }
99 89
100 uv = vec2(uCoord, vCoord);90 uv = vec2(uCoord, vCoord);
101 91
102 _verticesBuffer->append(sizeof(glm::vec3), (const gpu::Byte*)&_vertices.at(vertexIndex));92 _verticesBuffer->append(sizeof(glm::vec3), (const gpu::Byte*)&_vertices.at(vertexIndex));
103 _verticesBuffer->append(sizeof(glm::vec3), (const gpu::Byte*)&_normals.at(i));93 _verticesBuffer->append(sizeof(glm::vec3), (const gpu::Byte*)&_normals.at(i));
104 _verticesBuffer->append(sizeof(int), (gpu::Byte*)&_color);
105 _verticesBuffer->append(sizeof(glm::vec2), (gpu::Byte*)&uv);94 _verticesBuffer->append(sizeof(glm::vec2), (gpu::Byte*)&uv);
106 vertexIndex++;95 vertexIndex++;
107 96
108 uv.y = 1.0f;97 uv.y = 1.0f;
109 _verticesBuffer->append(sizeof(glm::vec3), (const gpu::Byte*)&_vertices.at(vertexIndex));98 _verticesBuffer->append(sizeof(glm::vec3), (const gpu::Byte*)&_vertices.at(vertexIndex));
110 _verticesBuffer->append(sizeof(glm::vec3), (const gpu::Byte*)&_normals.at(i));99 _verticesBuffer->append(sizeof(glm::vec3), (const gpu::Byte*)&_normals.at(i));
111 _verticesBuffer->append(sizeof(int), (gpu::Byte*)_color);
112 _verticesBuffer->append(sizeof(glm::vec2), (const gpu::Byte*)&uv);100 _verticesBuffer->append(sizeof(glm::vec2), (const gpu::Byte*)&uv);
113 vertexIndex++;101 vertexIndex++;
114 102
115 _numVertices += 2;103 _numVertices += 2;
104 uCoord += uCoordInc;
116 }105 }
117 _pointsChanged = false;106 _pointsChanged = false;
118 _normalsChanged = false;107 _normalsChanged = false;
@@ -161,6 +150,16 @@ void RenderablePolyLineEntityItem::updateVertices() { · 42 unmodified lines
161 150
162}151}
163 152
153void RenderablePolyLineEntityItem::update(const quint64& now) {
154 PolyLineUniforms uniforms;
155 uniforms.color = toGlm(getXColor());
156 memcpy(&_uniformBuffer.edit<PolyLineUniforms>(), &uniforms, sizeof(PolyLineUniforms));
157 if (_pointsChanged || _strokeWidthsChanged || _normalsChanged) {
158 updateVertices();
159 updateGeometry();
160 }
161
162}
164 163
165void RenderablePolyLineEntityItem::render(RenderArgs* args) {164void RenderablePolyLineEntityItem::render(RenderArgs* args) {
166 QWriteLocker lock(&_quadReadWriteLock);165 QWriteLocker lock(&_quadReadWriteLock);
@@ -181,17 +180,13 @@ void RenderablePolyLineEntityItem::render(RenderArgs* args) { · 14 unmodified lines
181 180
182 PerformanceTimer perfTimer("RenderablePolyLineEntityItem::render");181 PerformanceTimer perfTimer("RenderablePolyLineEntityItem::render");
183 Q_ASSERT(getType() == EntityTypes::PolyLine);182 Q_ASSERT(getType() == EntityTypes::PolyLine);
184
185 Q_ASSERT(args->_batch);183 Q_ASSERT(args->_batch);
186 if (_pointsChanged || _strokeWidthsChanged || _normalsChanged) {
187 updateVertices();
188 updateGeometry();
189 }
190 184
191 gpu::Batch& batch = *args->_batch;185 gpu::Batch& batch = *args->_batch;
192 Transform transform = Transform();186 Transform transform = Transform();
193 transform.setTranslation(getPosition());187 transform.setTranslation(getPosition());
194 transform.setRotation(getRotation());188 transform.setRotation(getRotation());
189 batch.setUniformBuffer(0, _uniformBuffer);
195 batch.setModelTransform(transform);190 batch.setModelTransform(transform);
196 191
197 batch.setPipeline(_pipeline);192 batch.setPipeline(_pipeline);
@@ -200,7 +195,7 @@ void RenderablePolyLineEntityItem::render(RenderArgs* args) { · 2 unmodified lines
200 } else {195 } else {
201 batch.setResourceTexture(PAINTSTROKE_GPU_SLOT, args->_whiteTexture);196 batch.setResourceTexture(PAINTSTROKE_GPU_SLOT, args->_whiteTexture);
202 }197 }
203 198
204 batch.setInputFormat(_format);199 batch.setInputFormat(_format);
205 batch.setInputBuffer(0, _verticesBuffer, 0, _format->getChannels().at(0)._stride);200 batch.setInputBuffer(0, _verticesBuffer, 0, _format->getChannels().at(0)._stride);
206 201
libraries/entities-renderer/src/RenderablePolyLineEntityItem.h+3−0
@@ -29,6 +29,8 @@ public: · 28 unmodified lines
29 RenderablePolyLineEntityItem(const EntityItemID& entityItemID);29 RenderablePolyLineEntityItem(const EntityItemID& entityItemID);
30 30
31 virtual void render(RenderArgs* args);31 virtual void render(RenderArgs* args);
32 virtual void update(const quint64& now) override;
33 virtual bool needsToCallUpdate() const { return true; };
32 34
33 SIMPLE_RENDERABLE();35 SIMPLE_RENDERABLE();
34 36
@@ -42,6 +44,7 @@ protected: · 7 unmodified lines
42 void updateGeometry();44 void updateGeometry();
43 void updateVertices();45 void updateVertices();
44 gpu::BufferPointer _verticesBuffer;46 gpu::BufferPointer _verticesBuffer;
47 gpu::BufferView _uniformBuffer;
45 unsigned int _numVertices;48 unsigned int _numVertices;
46 QVector<glm::vec3> _vertices;49 QVector<glm::vec3> _vertices;
47 50
libraries/entities-renderer/src/RenderableProceduralItemShader.h+2−4
@@ -23,8 +23,6 @@ layout(location = 0) out vec4 _fragColor0; · 22 unmodified lines
23layout(location = 1) out vec4 _fragColor1;23layout(location = 1) out vec4 _fragColor1;
24layout(location = 2) out vec4 _fragColor2;24layout(location = 2) out vec4 _fragColor2;
25 25
26// the glow intensity
27uniform float glowIntensity;
28// the alpha threshold26// the alpha threshold
29uniform float alphaThreshold;27uniform float alphaThreshold;
30uniform sampler2D normalFittingMap;28uniform sampler2D normalFittingMap;
@@ -318,8 +316,8 @@ const QString SHADER_TEMPLATE_V1 = SHADER_COMMON + R"SCRIBE( · 287 unmodified lines
318void main(void) {316void main(void) {
319 vec4 emissive = getProceduralColor();317 vec4 emissive = getProceduralColor();
320 318
321 float alpha = glowIntensity * emissive.a;319 float alpha = emissive.a;
322 if (alpha != glowIntensity) {320 if (alpha != 1.0) {
323 discard;321 discard;
324 }322 }
325 323
libraries/entities-renderer/src/paintStroke.slf+8−7
@@ -23,23 +23,24 @@ in vec3 interpolatedNormal; · 22 unmodified lines
23in vec2 varTexcoord;23in vec2 varTexcoord;
24in vec4 varColor;24in vec4 varColor;
25 25
26float rand(vec2 point){26struct PolyLineUniforms {
27 return fract(sin(dot(point.xy ,vec2(12.9898,78.233))) * 43758.5453);27 vec3 color;
28}28};
29
30 29
30uniform polyLineBuffer {
31 PolyLineUniforms polyline;
32};
31 33
32void main(void) {34void main(void) {
33 35
34 36
35 vec4 texel = texture(originalTexture, varTexcoord);37 vec4 texel = texture(originalTexture, varTexcoord);
36 int frontCondition = 1 -int(gl_FrontFacing) * 2;38 int frontCondition = 1 -int(gl_FrontFacing) * 2;
37 vec3 color = varColor.rgb;39 vec3 color = varColor.rgb;
38 //vec3 normal, float alpha, vec3 diffuse, vec3 specular, float shininess
39 packDeferredFragmentTranslucent(40 packDeferredFragmentTranslucent(
40 interpolatedNormal * frontCondition,41 interpolatedNormal * frontCondition,
41 texel.a,42 texel.a,
42 color *texel.rgb,43 polyline.color * texel.rgb,
43 vec3(0.01, 0.01, 0.01),44 vec3(0.01, 0.01, 0.01),
44 10.0);45 10.0);
45}46}
libraries/entities-renderer/src/paintStroke.slv+1−0
@@ -32,6 +32,7 @@ void main(void) { · 31 unmodified lines
32 // pass along the diffuse color32 // pass along the diffuse color
33 varColor = colorToLinearRGBA(inColor);33 varColor = colorToLinearRGBA(inColor);
34 34
35
35 // standard transform36 // standard transform
36 TransformCamera cam = getTransformCamera();37 TransformCamera cam = getTransformCamera();
37 TransformObject obj = getTransformObject();38 TransformObject obj = getTransformObject();
libraries/entities/src/EntityItemProperties.cpp+8−8
@@ -195,7 +195,7 @@ EntityPropertyFlags EntityItemProperties::getChangedProperties() const { · 194 unmodified lines
195 CHECK_PROPERTY_CHANGE(PROP_ALPHA_SPREAD, alphaSpread);195 CHECK_PROPERTY_CHANGE(PROP_ALPHA_SPREAD, alphaSpread);
196 CHECK_PROPERTY_CHANGE(PROP_ALPHA_START, alphaStart);196 CHECK_PROPERTY_CHANGE(PROP_ALPHA_START, alphaStart);
197 CHECK_PROPERTY_CHANGE(PROP_ALPHA_FINISH, alphaFinish);197 CHECK_PROPERTY_CHANGE(PROP_ALPHA_FINISH, alphaFinish);
198 CHECK_PROPERTY_CHANGE(PROP_ADDITIVE_BLENDING, additiveBlending);198 CHECK_PROPERTY_CHANGE(PROP_EMITTER_SHOULD_TRAIL, emitterShouldTrail);
199 CHECK_PROPERTY_CHANGE(PROP_MODEL_URL, modelURL);199 CHECK_PROPERTY_CHANGE(PROP_MODEL_URL, modelURL);
200 CHECK_PROPERTY_CHANGE(PROP_COMPOUND_SHAPE_URL, compoundShapeURL);200 CHECK_PROPERTY_CHANGE(PROP_COMPOUND_SHAPE_URL, compoundShapeURL);
201 CHECK_PROPERTY_CHANGE(PROP_VISIBLE, visible);201 CHECK_PROPERTY_CHANGE(PROP_VISIBLE, visible);
@@ -354,7 +354,7 @@ QScriptValue EntityItemProperties::copyToScriptValue(QScriptEngine* engine, bool · 152 unmodified lines
354 COPY_PROPERTY_TO_QSCRIPTVALUE(PROP_ALPHA_SPREAD, alphaSpread);354 COPY_PROPERTY_TO_QSCRIPTVALUE(PROP_ALPHA_SPREAD, alphaSpread);
355 COPY_PROPERTY_TO_QSCRIPTVALUE(PROP_ALPHA_START, alphaStart);355 COPY_PROPERTY_TO_QSCRIPTVALUE(PROP_ALPHA_START, alphaStart);
356 COPY_PROPERTY_TO_QSCRIPTVALUE(PROP_ALPHA_FINISH, alphaFinish);356 COPY_PROPERTY_TO_QSCRIPTVALUE(PROP_ALPHA_FINISH, alphaFinish);
357 COPY_PROPERTY_TO_QSCRIPTVALUE(PROP_ADDITIVE_BLENDING, additiveBlending);357 COPY_PROPERTY_TO_QSCRIPTVALUE(PROP_EMITTER_SHOULD_TRAIL, emitterShouldTrail);
358 COPY_PROPERTY_TO_QSCRIPTVALUE(PROP_LOCAL_POSITION, localPosition);358 COPY_PROPERTY_TO_QSCRIPTVALUE(PROP_LOCAL_POSITION, localPosition);
359 COPY_PROPERTY_TO_QSCRIPTVALUE(PROP_LOCAL_ROTATION, localRotation);359 COPY_PROPERTY_TO_QSCRIPTVALUE(PROP_LOCAL_ROTATION, localRotation);
360 }360 }
@@ -515,7 +515,7 @@ void EntityItemProperties::copyFromScriptValue(const QScriptValue& object, bool · 154 unmodified lines
515 COPY_PROPERTY_FROM_QSCRIPTVALUE(alphaSpread, float, setAlphaSpread);515 COPY_PROPERTY_FROM_QSCRIPTVALUE(alphaSpread, float, setAlphaSpread);
516 COPY_PROPERTY_FROM_QSCRIPTVALUE(alphaStart, float, setAlphaStart);516 COPY_PROPERTY_FROM_QSCRIPTVALUE(alphaStart, float, setAlphaStart);
517 COPY_PROPERTY_FROM_QSCRIPTVALUE(alphaFinish, float, setAlphaFinish);517 COPY_PROPERTY_FROM_QSCRIPTVALUE(alphaFinish, float, setAlphaFinish);
518 COPY_PROPERTY_FROM_QSCRIPTVALUE(additiveBlending, bool, setAdditiveBlending);518 COPY_PROPERTY_FROM_QSCRIPTVALUE(emitterShouldTrail , bool, setEmitterShouldTrail);
519 COPY_PROPERTY_FROM_QSCRIPTVALUE(modelURL, QString, setModelURL);519 COPY_PROPERTY_FROM_QSCRIPTVALUE(modelURL, QString, setModelURL);
520 COPY_PROPERTY_FROM_QSCRIPTVALUE(compoundShapeURL, QString, setCompoundShapeURL);520 COPY_PROPERTY_FROM_QSCRIPTVALUE(compoundShapeURL, QString, setCompoundShapeURL);
521 COPY_PROPERTY_FROM_QSCRIPTVALUE(glowLevel, float, setGlowLevel);521 COPY_PROPERTY_FROM_QSCRIPTVALUE(glowLevel, float, setGlowLevel);
@@ -670,7 +670,7 @@ void EntityItemProperties::entityPropertyFlagsFromScriptValue(const QScriptValue · 148 unmodified lines
670 ADD_PROPERTY_TO_MAP(PROP_ALPHA_SPREAD, AlphaSpread, alphaSpread, float);670 ADD_PROPERTY_TO_MAP(PROP_ALPHA_SPREAD, AlphaSpread, alphaSpread, float);
671 ADD_PROPERTY_TO_MAP(PROP_ALPHA_START, AlphaStart, alphaStart, float);671 ADD_PROPERTY_TO_MAP(PROP_ALPHA_START, AlphaStart, alphaStart, float);
672 ADD_PROPERTY_TO_MAP(PROP_ALPHA_FINISH, AlphaFinish, alphaFinish, float);672 ADD_PROPERTY_TO_MAP(PROP_ALPHA_FINISH, AlphaFinish, alphaFinish, float);
673 ADD_PROPERTY_TO_MAP(PROP_ADDITIVE_BLENDING, AdditiveBlending, additiveBlending, bool);673 ADD_PROPERTY_TO_MAP(PROP_EMITTER_SHOULD_TRAIL, EmitterShouldTrail, emitterShouldTrail, bool);
674 ADD_PROPERTY_TO_MAP(PROP_MODEL_URL, ModelURL, modelURL, QString);674 ADD_PROPERTY_TO_MAP(PROP_MODEL_URL, ModelURL, modelURL, QString);
675 ADD_PROPERTY_TO_MAP(PROP_COMPOUND_SHAPE_URL, CompoundShapeURL, compoundShapeURL, QString);675 ADD_PROPERTY_TO_MAP(PROP_COMPOUND_SHAPE_URL, CompoundShapeURL, compoundShapeURL, QString);
676 ADD_PROPERTY_TO_MAP(PROP_REGISTRATION_POINT, RegistrationPoint, registrationPoint, glm::vec3);676 ADD_PROPERTY_TO_MAP(PROP_REGISTRATION_POINT, RegistrationPoint, registrationPoint, glm::vec3);
@@ -980,7 +980,7 @@ bool EntityItemProperties::encodeEntityEditPacket(PacketType command, EntityItem · 303 unmodified lines
980 APPEND_ENTITY_PROPERTY(PROP_ALPHA_SPREAD, properties.getAlphaSpread());980 APPEND_ENTITY_PROPERTY(PROP_ALPHA_SPREAD, properties.getAlphaSpread());
981 APPEND_ENTITY_PROPERTY(PROP_ALPHA_START, properties.getAlphaStart());981 APPEND_ENTITY_PROPERTY(PROP_ALPHA_START, properties.getAlphaStart());
982 APPEND_ENTITY_PROPERTY(PROP_ALPHA_FINISH, properties.getAlphaFinish());982 APPEND_ENTITY_PROPERTY(PROP_ALPHA_FINISH, properties.getAlphaFinish());
983 APPEND_ENTITY_PROPERTY(PROP_ADDITIVE_BLENDING, properties.getAdditiveBlending());983 APPEND_ENTITY_PROPERTY(PROP_EMITTER_SHOULD_TRAIL, properties.getEmitterShouldTrail());
984 }984 }
985 985
986 if (properties.getType() == EntityTypes::Zone) {986 if (properties.getType() == EntityTypes::Zone) {
@@ -1265,7 +1265,7 @@ bool EntityItemProperties::decodeEntityEditPacket(const unsigned char* data, int · 278 unmodified lines
1265 READ_ENTITY_PROPERTY_TO_PROPERTIES(PROP_ALPHA_SPREAD, float, setAlphaSpread);1265 READ_ENTITY_PROPERTY_TO_PROPERTIES(PROP_ALPHA_SPREAD, float, setAlphaSpread);
1266 READ_ENTITY_PROPERTY_TO_PROPERTIES(PROP_ALPHA_START, float, setAlphaStart);1266 READ_ENTITY_PROPERTY_TO_PROPERTIES(PROP_ALPHA_START, float, setAlphaStart);
1267 READ_ENTITY_PROPERTY_TO_PROPERTIES(PROP_ALPHA_FINISH, float, setAlphaFinish);1267 READ_ENTITY_PROPERTY_TO_PROPERTIES(PROP_ALPHA_FINISH, float, setAlphaFinish);
1268 READ_ENTITY_PROPERTY_TO_PROPERTIES(PROP_ADDITIVE_BLENDING, bool, setAdditiveBlending);1268 READ_ENTITY_PROPERTY_TO_PROPERTIES(PROP_EMITTER_SHOULD_TRAIL, bool, setEmitterShouldTrail);
1269 }1269 }
1270 1270
1271 if (properties.getType() == EntityTypes::Zone) {1271 if (properties.getType() == EntityTypes::Zone) {
@@ -1608,8 +1608,8 @@ QList<QString> EntityItemProperties::listChangedProperties() { · 336 unmodified lines
1608 if (alphaFinishChanged()) {1608 if (alphaFinishChanged()) {
1609 out += "alphaFinish";1609 out += "alphaFinish";
1610 }1610 }
1611 if (additiveBlendingChanged()) {1611 if (emitterShouldTrailChanged()) {
1612 out += "additiveBlending";1612 out += "emitterShouldTrail";
1613 }1613 }
1614 if (modelURLChanged()) {1614 if (modelURLChanged()) {
1615 out += "modelURL";1615 out += "modelURL";
libraries/entities/src/EntityItemProperties.h+1−1
@@ -161,7 +161,7 @@ public: · 160 unmodified lines
161 DEFINE_PROPERTY(PROP_RADIUS_SPREAD, RadiusSpread, radiusSpread, float, ParticleEffectEntityItem::DEFAULT_RADIUS_SPREAD);161 DEFINE_PROPERTY(PROP_RADIUS_SPREAD, RadiusSpread, radiusSpread, float, ParticleEffectEntityItem::DEFAULT_RADIUS_SPREAD);
162 DEFINE_PROPERTY(PROP_RADIUS_START, RadiusStart, radiusStart, float, ParticleEffectEntityItem::DEFAULT_RADIUS_START);162 DEFINE_PROPERTY(PROP_RADIUS_START, RadiusStart, radiusStart, float, ParticleEffectEntityItem::DEFAULT_RADIUS_START);
163 DEFINE_PROPERTY(PROP_RADIUS_FINISH, RadiusFinish, radiusFinish, float, ParticleEffectEntityItem::DEFAULT_RADIUS_FINISH);163 DEFINE_PROPERTY(PROP_RADIUS_FINISH, RadiusFinish, radiusFinish, float, ParticleEffectEntityItem::DEFAULT_RADIUS_FINISH);
164 DEFINE_PROPERTY(PROP_ADDITIVE_BLENDING, AdditiveBlending, additiveBlending, bool, ParticleEffectEntityItem::DEFAULT_ADDITIVE_BLENDING);164 DEFINE_PROPERTY(PROP_EMITTER_SHOULD_TRAIL, EmitterShouldTrail, emitterShouldTrail, bool, ParticleEffectEntityItem::DEFAULT_EMITTER_SHOULD_TRAIL);
165 DEFINE_PROPERTY_REF(PROP_MARKETPLACE_ID, MarketplaceID, marketplaceID, QString, ENTITY_ITEM_DEFAULT_MARKETPLACE_ID);165 DEFINE_PROPERTY_REF(PROP_MARKETPLACE_ID, MarketplaceID, marketplaceID, QString, ENTITY_ITEM_DEFAULT_MARKETPLACE_ID);
166 DEFINE_PROPERTY_GROUP(KeyLight, keyLight, KeyLightPropertyGroup);166 DEFINE_PROPERTY_GROUP(KeyLight, keyLight, KeyLightPropertyGroup);
167 DEFINE_PROPERTY_REF(PROP_VOXEL_VOLUME_SIZE, VoxelVolumeSize, voxelVolumeSize, glm::vec3, PolyVoxEntityItem::DEFAULT_VOXEL_VOLUME_SIZE);167 DEFINE_PROPERTY_REF(PROP_VOXEL_VOLUME_SIZE, VoxelVolumeSize, voxelVolumeSize, glm::vec3, PolyVoxEntityItem::DEFAULT_VOXEL_VOLUME_SIZE);
libraries/entities/src/EntityPropertyFlags.h+1−1
@@ -149,7 +149,7 @@ enum EntityPropertyList { · 148 unmodified lines
149 PROP_ANIMATION_HOLD,149 PROP_ANIMATION_HOLD,
150 PROP_ANIMATION_START_AUTOMATICALLY,150 PROP_ANIMATION_START_AUTOMATICALLY,
151 151
152 PROP_ADDITIVE_BLENDING,152 PROP_EMITTER_SHOULD_TRAIL,
153 153
154 PROP_PARENT_ID,154 PROP_PARENT_ID,
155 PROP_PARENT_JOINT_INDEX,155 PROP_PARENT_JOINT_INDEX,
libraries/entities/src/EntityScriptingInterface.cpp+10−8
@@ -357,19 +357,21 @@ QVector<QUuid> EntityScriptingInterface::findEntitiesInBox(const glm::vec3& corn · 356 unmodified lines
357 return result;357 return result;
358}358}
359 359
360RayToEntityIntersectionResult EntityScriptingInterface::findRayIntersection(const PickRay& ray, bool precisionPicking, const QScriptValue& entityIdsToInclude) {360RayToEntityIntersectionResult EntityScriptingInterface::findRayIntersection(const PickRay& ray, bool precisionPicking, const QScriptValue& entityIdsToInclude, const QScriptValue& entityIdsToDiscard) {
361 QVector<EntityItemID> entities = qVectorEntityItemIDFromScriptValue(entityIdsToInclude);361 QVector<EntityItemID> entitiesToInclude = qVectorEntityItemIDFromScriptValue(entityIdsToInclude);
362 return findRayIntersectionWorker(ray, Octree::TryLock, precisionPicking, entities);362 QVector<EntityItemID> entitiesToDiscard = qVectorEntityItemIDFromScriptValue(entityIdsToDiscard);
363 return findRayIntersectionWorker(ray, Octree::TryLock, precisionPicking, entitiesToInclude, entitiesToDiscard);
363}364}
364 365
365RayToEntityIntersectionResult EntityScriptingInterface::findRayIntersectionBlocking(const PickRay& ray, bool precisionPicking, const QScriptValue& entityIdsToInclude) {366RayToEntityIntersectionResult EntityScriptingInterface::findRayIntersectionBlocking(const PickRay& ray, bool precisionPicking, const QScriptValue& entityIdsToInclude, const QScriptValue& entityIdsToDiscard) {
366 const QVector<EntityItemID>& entities = qVectorEntityItemIDFromScriptValue(entityIdsToInclude);367 const QVector<EntityItemID>& entitiesToInclude = qVectorEntityItemIDFromScriptValue(entityIdsToInclude);
367 return findRayIntersectionWorker(ray, Octree::Lock, precisionPicking, entities);368 const QVector<EntityItemID> entitiesToDiscard = qVectorEntityItemIDFromScriptValue(entityIdsToDiscard);
369 return findRayIntersectionWorker(ray, Octree::Lock, precisionPicking, entitiesToInclude, entitiesToDiscard);
368}370}
369 371
370RayToEntityIntersectionResult EntityScriptingInterface::findRayIntersectionWorker(const PickRay& ray,372RayToEntityIntersectionResult EntityScriptingInterface::findRayIntersectionWorker(const PickRay& ray,
371 Octree::lockType lockType,373 Octree::lockType lockType,
372 bool precisionPicking, const QVector<EntityItemID>& entityIdsToInclude) {374 bool precisionPicking, const QVector<EntityItemID>& entityIdsToInclude, const QVector<EntityItemID>& entityIdsToDiscard) {
373 375
374 376
375 RayToEntityIntersectionResult result;377 RayToEntityIntersectionResult result;
@@ -377,7 +379,7 @@ RayToEntityIntersectionResult EntityScriptingInterface::findRayIntersectionWorke · 1 unmodified line
377 OctreeElementPointer element;379 OctreeElementPointer element;
378 EntityItemPointer intersectedEntity = NULL;380 EntityItemPointer intersectedEntity = NULL;
379 result.intersects = _entityTree->findRayIntersection(ray.origin, ray.direction, element, result.distance, result.face,381 result.intersects = _entityTree->findRayIntersection(ray.origin, ray.direction, element, result.distance, result.face,
380 result.surfaceNormal, entityIdsToInclude, (void**)&intersectedEntity, lockType, &result.accurate,382 result.surfaceNormal, entityIdsToInclude, entityIdsToDiscard, (void**)&intersectedEntity, lockType, &result.accurate,
381 precisionPicking);383 precisionPicking);
382 if (result.intersects && intersectedEntity) {384 if (result.intersects && intersectedEntity) {
383 result.entityID = intersectedEntity->getEntityItemID();385 result.entityID = intersectedEntity->getEntityItemID();
libraries/entities/src/EntityScriptingInterface.h+3−3
@@ -112,11 +112,11 @@ public slots: · 111 unmodified lines
112 /// If the scripting context has visible entities, this will determine a ray intersection, the results112 /// If the scripting context has visible entities, this will determine a ray intersection, the results
113 /// may be inaccurate if the engine is unable to access the visible entities, in which case result.accurate113 /// may be inaccurate if the engine is unable to access the visible entities, in which case result.accurate
114 /// will be false.114 /// will be false.
115 Q_INVOKABLE RayToEntityIntersectionResult findRayIntersection(const PickRay& ray, bool precisionPicking = false, const QScriptValue& entityIdsToInclude = QScriptValue());115 Q_INVOKABLE RayToEntityIntersectionResult findRayIntersection(const PickRay& ray, bool precisionPicking = false, const QScriptValue& entityIdsToInclude = QScriptValue(), const QScriptValue& entityIdsToDiscard = QScriptValue());
116 116
117 /// If the scripting context has visible entities, this will determine a ray intersection, and will block in117 /// If the scripting context has visible entities, this will determine a ray intersection, and will block in
118 /// order to return an accurate result118 /// order to return an accurate result
119 Q_INVOKABLE RayToEntityIntersectionResult findRayIntersectionBlocking(const PickRay& ray, bool precisionPicking = false, const QScriptValue& entityIdsToInclude = QScriptValue());119 Q_INVOKABLE RayToEntityIntersectionResult findRayIntersectionBlocking(const PickRay& ray, bool precisionPicking = false, const QScriptValue& entityIdsToInclude = QScriptValue(), const QScriptValue& entityIdsToDiscard = QScriptValue());
120 120
121 Q_INVOKABLE void setLightsArePickable(bool value);121 Q_INVOKABLE void setLightsArePickable(bool value);
122 Q_INVOKABLE bool getLightsArePickable() const;122 Q_INVOKABLE bool getLightsArePickable() const;
@@ -189,7 +189,7 @@ private: · 66 unmodified lines
189 189
190 /// actually does the work of finding the ray intersection, can be called in locking mode or tryLock mode190 /// actually does the work of finding the ray intersection, can be called in locking mode or tryLock mode
191 RayToEntityIntersectionResult findRayIntersectionWorker(const PickRay& ray, Octree::lockType lockType,191 RayToEntityIntersectionResult findRayIntersectionWorker(const PickRay& ray, Octree::lockType lockType,
192 bool precisionPicking, const QVector<EntityItemID>& entityIdsToInclude);192 bool precisionPicking, const QVector<EntityItemID>& entityIdsToInclude, const QVector<EntityItemID>& entityIdsToDiscard);
193 193
194 EntityTreePointer _entityTree;194 EntityTreePointer _entityTree;
195 EntitiesScriptEngineProvider* _entitiesScriptEngine = nullptr;195 EntitiesScriptEngineProvider* _entitiesScriptEngine = nullptr;
libraries/entities/src/EntityTree.cpp+4−3
@@ -498,6 +498,7 @@ public: · 497 unmodified lines
498 BoxFace& face;498 BoxFace& face;
499 glm::vec3& surfaceNormal;499 glm::vec3& surfaceNormal;
500 const QVector<EntityItemID>& entityIdsToInclude;500 const QVector<EntityItemID>& entityIdsToInclude;
501 const QVector<EntityItemID>& entityIdsToDiscard;
501 void** intersectedObject;502 void** intersectedObject;
502 bool found;503 bool found;
503 bool precisionPicking;504 bool precisionPicking;
@@ -510,7 +511,7 @@ bool findRayIntersectionOp(OctreeElementPointer element, void* extraData) { · 6 unmodified lines
510 EntityTreeElementPointer entityTreeElementPointer = std::dynamic_pointer_cast<EntityTreeElement>(element);511 EntityTreeElementPointer entityTreeElementPointer = std::dynamic_pointer_cast<EntityTreeElement>(element);
511 if (entityTreeElementPointer ->findRayIntersection(args->origin, args->direction, keepSearching,512 if (entityTreeElementPointer ->findRayIntersection(args->origin, args->direction, keepSearching,
512 args->element, args->distance, args->face, args->surfaceNormal, args->entityIdsToInclude,513 args->element, args->distance, args->face, args->surfaceNormal, args->entityIdsToInclude,
513 args->intersectedObject, args->precisionPicking)) {514 args->entityIdsToDiscard, args->intersectedObject, args->precisionPicking)) {
514 args->found = true;515 args->found = true;
515 }516 }
516 return keepSearching;517 return keepSearching;
@@ -518,9 +519,9 @@ bool findRayIntersectionOp(OctreeElementPointer element, void* extraData) { · 1 unmodified line
518 519
519bool EntityTree::findRayIntersection(const glm::vec3& origin, const glm::vec3& direction,520bool EntityTree::findRayIntersection(const glm::vec3& origin, const glm::vec3& direction,
520 OctreeElementPointer& element, float& distance, 521 OctreeElementPointer& element, float& distance,
521 BoxFace& face, glm::vec3& surfaceNormal, const QVector<EntityItemID>& entityIdsToInclude, void** intersectedObject,522 BoxFace& face, glm::vec3& surfaceNormal, const QVector<EntityItemID>& entityIdsToInclude, const QVector<EntityItemID>& entityIdsToDiscard, void** intersectedObject,
522 Octree::lockType lockType, bool* accurateResult, bool precisionPicking) {523 Octree::lockType lockType, bool* accurateResult, bool precisionPicking) {
523 RayArgs args = { origin, direction, element, distance, face, surfaceNormal, entityIdsToInclude, intersectedObject, false, precisionPicking };524 RayArgs args = { origin, direction, element, distance, face, surfaceNormal, entityIdsToInclude, entityIdsToDiscard, intersectedObject, false, precisionPicking };
524 distance = FLT_MAX;525 distance = FLT_MAX;
525 526
526 bool requireLock = lockType == Octree::Lock;527 bool requireLock = lockType == Octree::Lock;
libraries/entities/src/EntityTree.h+1−0
@@ -84,6 +84,7 @@ public: · 83 unmodified lines
84 virtual bool findRayIntersection(const glm::vec3& origin, const glm::vec3& direction,84 virtual bool findRayIntersection(const glm::vec3& origin, const glm::vec3& direction,
85 OctreeElementPointer& node, float& distance, BoxFace& face, glm::vec3& surfaceNormal,85 OctreeElementPointer& node, float& distance, BoxFace& face, glm::vec3& surfaceNormal,
86 const QVector<EntityItemID>& entityIdsToInclude = QVector<EntityItemID>(),86 const QVector<EntityItemID>& entityIdsToInclude = QVector<EntityItemID>(),
87 const QVector<EntityItemID>& entityIdsToDiscard = QVector<EntityItemID>(),
87 void** intersectedObject = NULL,88 void** intersectedObject = NULL,
88 Octree::lockType lockType = Octree::TryLock,89 Octree::lockType lockType = Octree::TryLock,
89 bool* accurateResult = NULL,90 bool* accurateResult = NULL,
libraries/entities/src/EntityTreeElement.cpp+5−5
@@ -475,8 +475,8 @@ bool EntityTreeElement::bestFitBounds(const glm::vec3& minPoint, const glm::vec3 · 474 unmodified lines
475 475
476bool EntityTreeElement::findRayIntersection(const glm::vec3& origin, const glm::vec3& direction,476bool EntityTreeElement::findRayIntersection(const glm::vec3& origin, const glm::vec3& direction,
477 bool& keepSearching, OctreeElementPointer& element, float& distance,477 bool& keepSearching, OctreeElementPointer& element, float& distance,
478 BoxFace& face, glm::vec3& surfaceNormal, const QVector<EntityItemID>& entityIdsToInclude,478 BoxFace& face, glm::vec3& surfaceNormal, const QVector<EntityItemID>& entityIdsToInclude,
479 void** intersectedObject, bool precisionPicking) {479 const QVector<EntityItemID>& entityIdsToDiscard, void** intersectedObject, bool precisionPicking) {
480 480
481 keepSearching = true; // assume that we will continue searching after this.481 keepSearching = true; // assume that we will continue searching after this.
482 482
@@ -501,7 +501,7 @@ bool EntityTreeElement::findRayIntersection(const glm::vec3& origin, const glm:: · 18 unmodified lines
501 if (_cube.contains(origin) || distanceToElementCube < distance) {501 if (_cube.contains(origin) || distanceToElementCube < distance) {
502 502
503 if (findDetailedRayIntersection(origin, direction, keepSearching, element, distanceToElementDetails,503 if (findDetailedRayIntersection(origin, direction, keepSearching, element, distanceToElementDetails,
504 face, localSurfaceNormal, entityIdsToInclude, intersectedObject, precisionPicking, distanceToElementCube)) {504 face, localSurfaceNormal, entityIdsToInclude, entityIdsToDiscard, intersectedObject, precisionPicking, distanceToElementCube)) {
505 505
506 if (distanceToElementDetails < distance) {506 if (distanceToElementDetails < distance) {
507 distance = distanceToElementDetails;507 distance = distanceToElementDetails;
@@ -516,13 +516,13 @@ bool EntityTreeElement::findRayIntersection(const glm::vec3& origin, const glm:: · 8 unmodified lines
516 516
517bool EntityTreeElement::findDetailedRayIntersection(const glm::vec3& origin, const glm::vec3& direction, bool& keepSearching,517bool EntityTreeElement::findDetailedRayIntersection(const glm::vec3& origin, const glm::vec3& direction, bool& keepSearching,
518 OctreeElementPointer& element, float& distance, BoxFace& face, glm::vec3& surfaceNormal,518 OctreeElementPointer& element, float& distance, BoxFace& face, glm::vec3& surfaceNormal,
519 const QVector<EntityItemID>& entityIdsToInclude, void** intersectedObject, bool precisionPicking, float distanceToElementCube) {519 const QVector<EntityItemID>& entityIdsToInclude, const QVector<EntityItemID>& entityIDsToDiscard, void** intersectedObject, bool precisionPicking, float distanceToElementCube) {
520 520
521 // only called if we do intersect our bounding cube, but find if we actually intersect with entities...521 // only called if we do intersect our bounding cube, but find if we actually intersect with entities...
522 int entityNumber = 0;522 int entityNumber = 0;
523 bool somethingIntersected = false;523 bool somethingIntersected = false;
524 forEachEntity([&](EntityItemPointer entity) {524 forEachEntity([&](EntityItemPointer entity) {
525 if (entityIdsToInclude.size() > 0 && !entityIdsToInclude.contains(entity->getID())) {525 if ( (entityIdsToInclude.size() > 0 && !entityIdsToInclude.contains(entity->getID())) || (entityIDsToDiscard.size() > 0 && entityIDsToDiscard.contains(entity->getID())) ) {
526 return;526 return;
527 }527 }
528 528
libraries/entities/src/EntityTreeElement.h+3−1
@@ -144,11 +144,13 @@ public: · 143 unmodified lines
144 virtual bool canRayIntersect() const { return hasEntities(); }144 virtual bool canRayIntersect() const { return hasEntities(); }
145 virtual bool findRayIntersection(const glm::vec3& origin, const glm::vec3& direction,145 virtual bool findRayIntersection(const glm::vec3& origin, const glm::vec3& direction,
146 bool& keepSearching, OctreeElementPointer& node, float& distance,146 bool& keepSearching, OctreeElementPointer& node, float& distance,
147 BoxFace& face, glm::vec3& surfaceNormal, const QVector<EntityItemID>& entityIdsToInclude,147 BoxFace& face, glm::vec3& surfaceNormal, const QVector<EntityItemID>& entityIdsToInclude,
148 const QVector<EntityItemID>& entityIdsToDiscard,
148 void** intersectedObject = NULL, bool precisionPicking = false);149 void** intersectedObject = NULL, bool precisionPicking = false);
149 virtual bool findDetailedRayIntersection(const glm::vec3& origin, const glm::vec3& direction,150 virtual bool findDetailedRayIntersection(const glm::vec3& origin, const glm::vec3& direction,
150 bool& keepSearching, OctreeElementPointer& element, float& distance, 151 bool& keepSearching, OctreeElementPointer& element, float& distance,
151 BoxFace& face, glm::vec3& surfaceNormal, const QVector<EntityItemID>& entityIdsToInclude,152 BoxFace& face, glm::vec3& surfaceNormal, const QVector<EntityItemID>& entityIdsToInclude,
153 const QVector<EntityItemID>& entityIdsToDiscard,
152 void** intersectedObject, bool precisionPicking, float distanceToElementCube);154 void** intersectedObject, bool precisionPicking, float distanceToElementCube);
153 virtual bool findSpherePenetration(const glm::vec3& center, float radius,155 virtual bool findSpherePenetration(const glm::vec3& center, float radius,
154 glm::vec3& penetration, void** penetratedObject) const;156 glm::vec3& penetration, void** penetratedObject) const;
libraries/entities/src/ParticleEffectEntityItem.cpp+25−15
@@ -52,13 +52,13 @@ const float ParticleEffectEntityItem::MINIMUM_ALPHA = 0.0f; · 51 unmodified lines
52const float ParticleEffectEntityItem::MAXIMUM_ALPHA = 1.0f;52const float ParticleEffectEntityItem::MAXIMUM_ALPHA = 1.0f;
53const quint32 ParticleEffectEntityItem::DEFAULT_MAX_PARTICLES = 1000;53const quint32 ParticleEffectEntityItem::DEFAULT_MAX_PARTICLES = 1000;
54const quint32 ParticleEffectEntityItem::MINIMUM_MAX_PARTICLES = 1;54const quint32 ParticleEffectEntityItem::MINIMUM_MAX_PARTICLES = 1;
55const quint32 ParticleEffectEntityItem::MAXIMUM_MAX_PARTICLES = 10000;55const quint32 ParticleEffectEntityItem::MAXIMUM_MAX_PARTICLES = 100000;
56const float ParticleEffectEntityItem::DEFAULT_LIFESPAN = 3.0f;56const float ParticleEffectEntityItem::DEFAULT_LIFESPAN = 3.0f;
57const float ParticleEffectEntityItem::MINIMUM_LIFESPAN = 0.0f;57const float ParticleEffectEntityItem::MINIMUM_LIFESPAN = 0.0f;
58const float ParticleEffectEntityItem::MAXIMUM_LIFESPAN = 86400.0f; // 1 day58const float ParticleEffectEntityItem::MAXIMUM_LIFESPAN = 86400.0f; // 1 day
59const float ParticleEffectEntityItem::DEFAULT_EMIT_RATE = 15.0f;59const float ParticleEffectEntityItem::DEFAULT_EMIT_RATE = 15.0f;
60const float ParticleEffectEntityItem::MINIMUM_EMIT_RATE = 0.0f;60const float ParticleEffectEntityItem::MINIMUM_EMIT_RATE = 0.0f;
61const float ParticleEffectEntityItem::MAXIMUM_EMIT_RATE = 1000.0f;61const float ParticleEffectEntityItem::MAXIMUM_EMIT_RATE = 100000.0f;
62const float ParticleEffectEntityItem::DEFAULT_EMIT_SPEED = 5.0f;62const float ParticleEffectEntityItem::DEFAULT_EMIT_SPEED = 5.0f;
63const float ParticleEffectEntityItem::MINIMUM_EMIT_SPEED = 0.0f;63const float ParticleEffectEntityItem::MINIMUM_EMIT_SPEED = 0.0f;
64const float ParticleEffectEntityItem::MAXIMUM_EMIT_SPEED = 1000.0f; // Approx mach 364const float ParticleEffectEntityItem::MAXIMUM_EMIT_SPEED = 1000.0f; // Approx mach 3
@@ -91,7 +91,7 @@ const float ParticleEffectEntityItem::DEFAULT_RADIUS_SPREAD = 0.0f; · 26 unmodified lines
91const float ParticleEffectEntityItem::DEFAULT_RADIUS_START = DEFAULT_PARTICLE_RADIUS;91const float ParticleEffectEntityItem::DEFAULT_RADIUS_START = DEFAULT_PARTICLE_RADIUS;
92const float ParticleEffectEntityItem::DEFAULT_RADIUS_FINISH = DEFAULT_PARTICLE_RADIUS;92const float ParticleEffectEntityItem::DEFAULT_RADIUS_FINISH = DEFAULT_PARTICLE_RADIUS;
93const QString ParticleEffectEntityItem::DEFAULT_TEXTURES = "";93const QString ParticleEffectEntityItem::DEFAULT_TEXTURES = "";
94const bool ParticleEffectEntityItem::DEFAULT_ADDITIVE_BLENDING = false;94const bool ParticleEffectEntityItem::DEFAULT_EMITTER_SHOULD_TRAIL = false;
95 95
96 96
97EntityItemPointer ParticleEffectEntityItem::factory(const EntityItemID& entityID, const EntityItemProperties& properties) {97EntityItemPointer ParticleEffectEntityItem::factory(const EntityItemID& entityID, const EntityItemProperties& properties) {
@@ -331,7 +331,7 @@ EntityItemProperties ParticleEffectEntityItem::getProperties(EntityPropertyFlags · 233 unmodified lines
331 COPY_ENTITY_PROPERTY_TO_PROPERTIES(alphaStart, getAlphaStart);331 COPY_ENTITY_PROPERTY_TO_PROPERTIES(alphaStart, getAlphaStart);
332 COPY_ENTITY_PROPERTY_TO_PROPERTIES(alphaFinish, getAlphaFinish);332 COPY_ENTITY_PROPERTY_TO_PROPERTIES(alphaFinish, getAlphaFinish);
333 COPY_ENTITY_PROPERTY_TO_PROPERTIES(textures, getTextures);333 COPY_ENTITY_PROPERTY_TO_PROPERTIES(textures, getTextures);
334 COPY_ENTITY_PROPERTY_TO_PROPERTIES(additiveBlending, getAdditiveBlending);334 COPY_ENTITY_PROPERTY_TO_PROPERTIES(emitterShouldTrail, getEmitterShouldTrail);
335 335
336 336
337 return properties;337 return properties;
@@ -370,7 +370,7 @@ bool ParticleEffectEntityItem::setProperties(const EntityItemProperties& propert · 32 unmodified lines
370 SET_ENTITY_PROPERTY_FROM_PROPERTIES(alphaStart, setAlphaStart);370 SET_ENTITY_PROPERTY_FROM_PROPERTIES(alphaStart, setAlphaStart);
371 SET_ENTITY_PROPERTY_FROM_PROPERTIES(alphaFinish, setAlphaFinish);371 SET_ENTITY_PROPERTY_FROM_PROPERTIES(alphaFinish, setAlphaFinish);
372 SET_ENTITY_PROPERTY_FROM_PROPERTIES(textures, setTextures);372 SET_ENTITY_PROPERTY_FROM_PROPERTIES(textures, setTextures);
373 SET_ENTITY_PROPERTY_FROM_PROPERTIES(additiveBlending, setAdditiveBlending);373 SET_ENTITY_PROPERTY_FROM_PROPERTIES(emitterShouldTrail, setEmitterShouldTrail);
374 374
375 if (somethingChanged) {375 if (somethingChanged) {
376 bool wantDebug = false;376 bool wantDebug = false;
@@ -463,7 +463,7 @@ int ParticleEffectEntityItem::readEntitySubclassDataFromBuffer(const unsigned ch · 86 unmodified lines
463 }463 }
464 464
465 if (args.bitstreamVersion >= VERSION_ENTITIES_PARTICLES_ADDITIVE_BLENDING) {465 if (args.bitstreamVersion >= VERSION_ENTITIES_PARTICLES_ADDITIVE_BLENDING) {
466 READ_ENTITY_PROPERTY(PROP_ADDITIVE_BLENDING, bool, setAdditiveBlending);466 READ_ENTITY_PROPERTY(PROP_EMITTER_SHOULD_TRAIL, bool, setEmitterShouldTrail);
467 }467 }
468 468
469 return bytesRead;469 return bytesRead;
@@ -503,7 +503,7 @@ EntityPropertyFlags ParticleEffectEntityItem::getEntityProperties(EncodeBitstrea · 33 unmodified lines
503 requestedProperties += PROP_POLAR_FINISH;503 requestedProperties += PROP_POLAR_FINISH;
504 requestedProperties += PROP_AZIMUTH_START;504 requestedProperties += PROP_AZIMUTH_START;
505 requestedProperties += PROP_AZIMUTH_FINISH;505 requestedProperties += PROP_AZIMUTH_FINISH;
506 requestedProperties += PROP_ADDITIVE_BLENDING;506 requestedProperties += PROP_EMITTER_SHOULD_TRAIL;
507 507
508 return requestedProperties;508 return requestedProperties;
509}509}
@@ -546,7 +546,7 @@ void ParticleEffectEntityItem::appendSubclassData(OctreePacketData* packetData, · 36 unmodified lines
546 APPEND_ENTITY_PROPERTY(PROP_POLAR_FINISH, getPolarFinish());546 APPEND_ENTITY_PROPERTY(PROP_POLAR_FINISH, getPolarFinish());
547 APPEND_ENTITY_PROPERTY(PROP_AZIMUTH_START, getAzimuthStart());547 APPEND_ENTITY_PROPERTY(PROP_AZIMUTH_START, getAzimuthStart());
548 APPEND_ENTITY_PROPERTY(PROP_AZIMUTH_FINISH, getAzimuthFinish());548 APPEND_ENTITY_PROPERTY(PROP_AZIMUTH_FINISH, getAzimuthFinish());
549 APPEND_ENTITY_PROPERTY(PROP_ADDITIVE_BLENDING, getAdditiveBlending());549 APPEND_ENTITY_PROPERTY(PROP_EMITTER_SHOULD_TRAIL, getEmitterShouldTrail());
550}550}
551 551
552bool ParticleEffectEntityItem::isEmittingParticles() const {552bool ParticleEffectEntityItem::isEmittingParticles() const {
@@ -641,13 +641,17 @@ void ParticleEffectEntityItem::stepSimulation(float deltaTime) { · 88 unmodified lines
641 641
642ParticleEffectEntityItem::Particle ParticleEffectEntityItem::createParticle() {642ParticleEffectEntityItem::Particle ParticleEffectEntityItem::createParticle() {
643 Particle particle;643 Particle particle;
644 644
645 particle.seed = randFloatInRange(0.0f, 1.0f);645
646 646 particle.seed = randFloatInRange(-1.0f, 1.0f);
647 if (getEmitterShouldTrail()) {
648 particle.position = getPosition();
649 }
647 // Position, velocity, and acceleration650 // Position, velocity, and acceleration
648 if (_polarStart == 0.0f && _polarFinish == 0.0f && _emitDimensions.z == 0.0f) {651 if (_polarStart == 0.0f && _polarFinish == 0.0f && _emitDimensions.z == 0.0f) {
649 // Emit along z-axis from position652 // Emit along z-axis from position
650 particle.velocity = (_emitSpeed + randFloatInRange(-1.0f, 1.0f) * _speedSpread) * (_emitOrientation * Vectors::UNIT_Z);653
654 particle.velocity = (_emitSpeed + 0.2f * _speedSpread) * (_emitOrientation * Vectors::UNIT_Z);
651 particle.acceleration = _emitAcceleration + randFloatInRange(-1.0f, 1.0f) * _accelerationSpread;655 particle.acceleration = _emitAcceleration + randFloatInRange(-1.0f, 1.0f) * _accelerationSpread;
652 656
653 } else {657 } else {
@@ -658,11 +662,12 @@ ParticleEffectEntityItem::Particle ParticleEffectEntityItem::createParticle() { · 4 unmodified lines
658 662
659 float elevationMinZ = sin(PI_OVER_TWO - _polarFinish);663 float elevationMinZ = sin(PI_OVER_TWO - _polarFinish);
660 float elevationMaxZ = sin(PI_OVER_TWO - _polarStart);664 float elevationMaxZ = sin(PI_OVER_TWO - _polarStart);
661 float elevation = asin(elevationMinZ + (elevationMaxZ - elevationMinZ) * randFloat());665 // float elevation = asin(elevationMinZ + (elevationMaxZ - elevationMinZ) * randFloat());
666 float elevation = asin(elevationMinZ + (elevationMaxZ - elevationMinZ) *randFloat());
662 667
663 float azimuth;668 float azimuth;
664 if (_azimuthFinish >= _azimuthStart) {669 if (_azimuthFinish >= _azimuthStart) {
665 azimuth = _azimuthStart + (_azimuthFinish - _azimuthStart) * randFloat();670 azimuth = _azimuthStart + (_azimuthFinish - _azimuthStart) * randFloat();
666 } else {671 } else {
667 azimuth = _azimuthStart + (TWO_PI + _azimuthFinish - _azimuthStart) * randFloat();672 azimuth = _azimuthStart + (TWO_PI + _azimuthFinish - _azimuthStart) * randFloat();
668 }673 }
@@ -693,7 +698,12 @@ ParticleEffectEntityItem::Particle ParticleEffectEntityItem::createParticle() { · 24 unmodified lines
693 radii.z > 0.0f ? z / (radii.z * radii.z) : 0.0f698 radii.z > 0.0f ? z / (radii.z * radii.z) : 0.0f
694 ));699 ));
695 700
696 particle.position = _emitOrientation * emitPosition;701 if (getEmitterShouldTrail()) {
702 particle.position += _emitOrientation * emitPosition;
703 }
704 else {
705 particle.position = _emitOrientation * emitPosition;
706 }
697 }707 }
698 708
699 particle.velocity = (_emitSpeed + randFloatInRange(-1.0f, 1.0f) * _speedSpread) * (_emitOrientation * emitDirection);709 particle.velocity = (_emitSpeed + randFloatInRange(-1.0f, 1.0f) * _speedSpread) * (_emitOrientation * emitDirection);
libraries/entities/src/ParticleEffectEntityItem.h+5−5
@@ -213,10 +213,10 @@ public: · 212 unmodified lines
213 }213 }
214 }214 }
215 215
216 static const bool DEFAULT_ADDITIVE_BLENDING;216 static const bool DEFAULT_EMITTER_SHOULD_TRAIL;
217 bool getAdditiveBlending() const { return _additiveBlending; }217 bool getEmitterShouldTrail() const { return _emitterShouldTrail; }
218 void setAdditiveBlending(bool additiveBlending) {218 void setEmitterShouldTrail(bool emitterShouldTrail) {
219 _additiveBlending = additiveBlending;219 _emitterShouldTrail = emitterShouldTrail;
220 }220 }
221 221
222 virtual bool supportsDetailedRayIntersection() const { return false; }222 virtual bool supportsDetailedRayIntersection() const { return false; }
@@ -286,7 +286,7 @@ protected: · 63 unmodified lines
286 float _timeUntilNextEmit { 0.0f };286 float _timeUntilNextEmit { 0.0f };
287 287
288 288
289 bool _additiveBlending { DEFAULT_ADDITIVE_BLENDING };289 bool _emitterShouldTrail { DEFAULT_EMITTER_SHOULD_TRAIL };
290};290};
291 291
292#endif // hifi_ParticleEffectEntityItem_h292#endif // hifi_ParticleEffectEntityItem_h
libraries/entities/src/PolyLineEntityItem.cpp+2−0
@@ -89,6 +89,7 @@ bool PolyLineEntityItem::setProperties(const EntityItemProperties& properties) { · 88 unmodified lines
89 return somethingChanged;89 return somethingChanged;
90}90}
91 91
92
92bool PolyLineEntityItem::appendPoint(const glm::vec3& point) {93bool PolyLineEntityItem::appendPoint(const glm::vec3& point) {
93 if (_points.size() > MAX_POINTS_PER_LINE - 1) {94 if (_points.size() > MAX_POINTS_PER_LINE - 1) {
94 qDebug() << "MAX POINTS REACHED!";95 qDebug() << "MAX POINTS REACHED!";
@@ -104,6 +105,7 @@ bool PolyLineEntityItem::appendPoint(const glm::vec3& point) { · 9 unmodified lines
104 return true;105 return true;
105}106}
106 107
108
107bool PolyLineEntityItem::setStrokeWidths(const QVector<float>& strokeWidths) {109bool PolyLineEntityItem::setStrokeWidths(const QVector<float>& strokeWidths) {
108 _strokeWidths = strokeWidths;110 _strokeWidths = strokeWidths;
109 _strokeWidthsChanged = true;111 _strokeWidthsChanged = true;
libraries/entities/src/PolyLineEntityItem.h+4−2
@@ -49,7 +49,7 @@ class PolyLineEntityItem : public EntityItem { · 48 unmodified lines
49 memcpy(_color, value, sizeof(_color));49 memcpy(_color, value, sizeof(_color));
50 }50 }
51 void setColor(const xColor& value) {51 void setColor(const xColor& value) {
52 52
53 _color[RED_INDEX] = value.red;53 _color[RED_INDEX] = value.red;
54 _color[GREEN_INDEX] = value.green;54 _color[GREEN_INDEX] = value.green;
55 _color[BLUE_INDEX] = value.blue;55 _color[BLUE_INDEX] = value.blue;
@@ -75,7 +75,9 @@ class PolyLineEntityItem : public EntityItem { · 19 unmodified lines
75 _texturesChangedFlag = true;75 _texturesChangedFlag = true;
76 }76 }
77 }77 }
78 78
79 virtual bool needsToCallUpdate() const { return true; }
80
79 virtual ShapeType getShapeType() const { return SHAPE_TYPE_LINE; }81 virtual ShapeType getShapeType() const { return SHAPE_TYPE_LINE; }
80 82
81 // never have a ray intersection pick a PolyLineEntityItem.83 // never have a ray intersection pick a PolyLineEntityItem.
libraries/model/src/model/Stage.cpp+15−0
@@ -225,6 +225,21 @@ void SunSkyStage::setOriginOrientation(const Quat& orientation) { · 224 unmodified lines
225 invalidate();225 invalidate();
226}226}
227 227
228void SunSkyStage::setOriginLongitude(float longitude) {
229 _earthSunModel.setLongitude(longitude);
230 invalidate();
231}
232
233void SunSkyStage::setOriginLatitude(float latitude) {
234 _earthSunModel.setLatitude(latitude);
235 invalidate();
236}
237
238void SunSkyStage::setOriginSurfaceAltitude(float altitude) {
239 _earthSunModel.setAltitude(altitude);
240 invalidate();
241}
242
228void SunSkyStage::setOriginLocation(float longitude, float latitude, float altitude) {243void SunSkyStage::setOriginLocation(float longitude, float latitude, float altitude) {
229 _earthSunModel.setLongitude(longitude);244 _earthSunModel.setLongitude(longitude);
230 _earthSunModel.setLatitude(latitude);245 _earthSunModel.setLatitude(latitude);
libraries/model/src/model/Stage.h+3−0
@@ -184,6 +184,9 @@ public: · 183 unmodified lines
184 const Quat& getOriginOrientation() const { return _earthSunModel.getSurfaceOrientation(); }184 const Quat& getOriginOrientation() const { return _earthSunModel.getSurfaceOrientation(); }
185 185
186 // Location used to define the sun & sky is a longitude and latitude [rad] and a earth surface altitude [km]186 // Location used to define the sun & sky is a longitude and latitude [rad] and a earth surface altitude [km]
187 void setOriginLatitude(float latitude);
188 void setOriginLongitude(float longitude);
189 void setOriginSurfaceAltitude(float surfaceAltitude);
187 void setOriginLocation(float longitude, float latitude, float surfaceAltitude);190 void setOriginLocation(float longitude, float latitude, float surfaceAltitude);
188 float getOriginLatitude() const { return _earthSunModel.getLatitude(); }191 float getOriginLatitude() const { return _earthSunModel.getLatitude(); }
189 float getOriginLongitude() const { return _earthSunModel.getLongitude(); }192 float getOriginLongitude() const { return _earthSunModel.getLongitude(); }
libraries/networking/src/AbstractUriHandler.h+19−0
@@ -0,0 +1,19 @@
1//
2// Created by Bradley Austin Davis on 2015/12/17
3// Copyright 2013-2015 High Fidelity, Inc.
4//
5// Distributed under the Apache License, Version 2.0.
6// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
7//
8
9#pragma once
10#ifndef hifi_network_AbstractUriHandler_h
11#define hifi_network_AbstractUriHandler_h
12
13class AbstractUriHandler {
14public:
15 virtual bool canAcceptURL(const QString& url) const = 0;
16 virtual bool acceptURL(const QString& url, bool defaultUpload = false) = 0;
17};
18
19#endif
libraries/octree/src/Octree.cpp+1−1
@@ -1867,7 +1867,7 @@ bool Octree::readJSONFromStream(unsigned long streamLength, QDataStream& inputSt · 1866 unmodified lines
1867 1867
1868 QByteArray jsonBuffer;1868 QByteArray jsonBuffer;
1869 char* rawData = new char[READ_JSON_BUFFER_SIZE];1869 char* rawData = new char[READ_JSON_BUFFER_SIZE];
1870 while (true) {1870 while (!inputStream.atEnd()) {
1871 int got = inputStream.readRawData(rawData, READ_JSON_BUFFER_SIZE - 1);1871 int got = inputStream.readRawData(rawData, READ_JSON_BUFFER_SIZE - 1);
1872 if (got < 0) {1872 if (got < 0) {
1873 qCritical() << "error while reading from json stream";1873 qCritical() << "error while reading from json stream";
libraries/render-utils/src/DebugDeferredBuffer.cpp+1−1
@@ -56,7 +56,7 @@ static const std::string DEEFAULT_ROUGHNESS_SHADER { · 55 unmodified lines
56};56};
57static const std::string DEEFAULT_NORMAL_SHADER {57static const std::string DEEFAULT_NORMAL_SHADER {
58 "vec4 getFragmentColor() {"58 "vec4 getFragmentColor() {"
59 " return vec4(texture(normalMap, uv).xyz, 1.0);"59 " return vec4(normalize(texture(normalMap, uv).xyz), 1.0);"
60 " }"60 " }"
61};61};
62static const std::string DEEFAULT_DEPTH_SHADER {62static const std::string DEEFAULT_DEPTH_SHADER {
libraries/render-utils/src/DeferredBufferWrite.slh+7−10
@@ -15,12 +15,6 @@ layout(location = 0) out vec4 _fragColor0; · 14 unmodified lines
15layout(location = 1) out vec4 _fragColor1;15layout(location = 1) out vec4 _fragColor1;
16layout(location = 2) out vec4 _fragColor2;16layout(location = 2) out vec4 _fragColor2;
17 17
18// the glow intensity
19uniform float glowIntensity;
20
21// the alpha threshold
22uniform float alphaThreshold;
23
24uniform sampler2D normalFittingMap;18uniform sampler2D normalFittingMap;
25 19
26vec3 bestFitNormal(vec3 normal) {20vec3 bestFitNormal(vec3 normal) {
@@ -39,15 +33,18 @@ vec3 bestFitNormal(vec3 normal) { · 12 unmodified lines
39 return (cN * 0.5 + 0.5);33 return (cN * 0.5 + 0.5);
40}34}
41 35
36
37// the alpha threshold
38const float alphaThreshold = 0.5;
42float evalOpaqueFinalAlpha(float alpha, float mapAlpha) {39float evalOpaqueFinalAlpha(float alpha, float mapAlpha) {
43 return mix(alpha * glowIntensity, 1.0 - alpha * glowIntensity, step(mapAlpha, alphaThreshold));40 return mix(alpha, 1.0 - alpha, step(mapAlpha, alphaThreshold));
44}41}
45 42
46const vec3 DEFAULT_SPECULAR = vec3(0.1);43const vec3 DEFAULT_SPECULAR = vec3(0.1);
47const float DEFAULT_SHININESS = 10;44const float DEFAULT_SHININESS = 10;
48 45
49void packDeferredFragment(vec3 normal, float alpha, vec3 diffuse, vec3 specular, float shininess) {46void packDeferredFragment(vec3 normal, float alpha, vec3 diffuse, vec3 specular, float shininess) {
50 if (alpha != glowIntensity) {47 if (alpha != 1.0) {
51 discard;48 discard;
52 }49 }
53 50
@@ -57,7 +54,7 @@ void packDeferredFragment(vec3 normal, float alpha, vec3 diffuse, vec3 specular, · 3 unmodified lines
57}54}
58 55
59void packDeferredFragmentLightmap(vec3 normal, float alpha, vec3 diffuse, vec3 specular, float shininess, vec3 emissive) {56void packDeferredFragmentLightmap(vec3 normal, float alpha, vec3 diffuse, vec3 specular, float shininess, vec3 emissive) {
60 if (alpha != glowIntensity) {57 if (alpha != 1.0) {
61 discard;58 discard;
62 }59 }
63 60
@@ -67,7 +64,7 @@ void packDeferredFragmentLightmap(vec3 normal, float alpha, vec3 diffuse, vec3 s · 3 unmodified lines
67}64}
68 65
69void packDeferredFragmentTranslucent(vec3 normal, float alpha, vec3 diffuse, vec3 specular, float shininess) {66void packDeferredFragmentTranslucent(vec3 normal, float alpha, vec3 diffuse, vec3 specular, float shininess) {
70 if (alpha <= alphaThreshold) {67 if (alpha <= 0.0) {
71 discard;68 discard;
72 } 69 }
73 70
libraries/render-utils/src/DeferredLightingEffect.cpp+0−4
@@ -40,8 +40,6 @@ · 39 unmodified lines
40#include "point_light_frag.h"40#include "point_light_frag.h"
41#include "spot_light_frag.h"41#include "spot_light_frag.h"
42 42
43static const std::string glowIntensityShaderHandle = "glowIntensity";
44
45struct LightLocations {43struct LightLocations {
46 int radius;44 int radius;
47 int ambientSphere;45 int ambientSphere;
@@ -134,8 +132,6 @@ gpu::PipelinePointer DeferredLightingEffect::bindSimpleProgram(gpu::Batch& batch · 86 unmodified lines
134 batch.setPipeline(pipeline);132 batch.setPipeline(pipeline);
135 133
136 gpu::ShaderPointer program = (config.isEmissive()) ? _emissiveShader : _simpleShader;134 gpu::ShaderPointer program = (config.isEmissive()) ? _emissiveShader : _simpleShader;
137 int glowIntensity = program->getUniforms().findLocation("glowIntensity");
138 batch._glUniform1f(glowIntensity, 1.0f);
139 135
140 if (!config.isTextured()) {136 if (!config.isTextured()) {
141 // If it is not textured, bind white texture and keep using textured pipeline137 // If it is not textured, bind white texture and keep using textured pipeline
libraries/render-utils/src/MeshPartPayload.cpp+3−7
@@ -199,8 +199,6 @@ void MeshPartPayload::render(RenderArgs* args) const { · 198 unmodified lines
199 gpu::Batch& batch = *(args->_batch);199 gpu::Batch& batch = *(args->_batch);
200 auto mode = args->_renderMode;200 auto mode = args->_renderMode;
201 201
202 auto alphaThreshold = args->_alphaThreshold; //translucent ? TRANSPARENT_ALPHA_THRESHOLD : OPAQUE_ALPHA_THRESHOLD; // FIX ME
203
204 model::MaterialKey drawMaterialKey;202 model::MaterialKey drawMaterialKey;
205 if (_drawMaterial) {203 if (_drawMaterial) {
206 drawMaterialKey = _drawMaterial->getKey();204 drawMaterialKey = _drawMaterial->getKey();
@@ -217,7 +215,7 @@ void MeshPartPayload::render(RenderArgs* args) const { · 10 unmodified lines
217 }215 }
218 216
219 ModelRender::Locations* locations = nullptr;217 ModelRender::Locations* locations = nullptr;
220 ModelRender::pickPrograms(batch, mode, translucentMesh, alphaThreshold, hasLightmap, hasTangents, hasSpecular, isSkinned, wireframe,218 ModelRender::pickPrograms(batch, mode, translucentMesh, hasLightmap, hasTangents, hasSpecular, isSkinned, wireframe,
221 args, locations);219 args, locations);
222 220
223 221
@@ -395,9 +393,7 @@ void ModelMeshPartPayload::render(RenderArgs* args) const { · 171 unmodified lines
395 393
396 gpu::Batch& batch = *(args->_batch);394 gpu::Batch& batch = *(args->_batch);
397 auto mode = args->_renderMode;395 auto mode = args->_renderMode;
398 396
399 auto alphaThreshold = args->_alphaThreshold; //translucent ? TRANSPARENT_ALPHA_THRESHOLD : OPAQUE_ALPHA_THRESHOLD; // FIX ME
400
401 const FBXGeometry& geometry = _model->_geometry->getFBXGeometry();397 const FBXGeometry& geometry = _model->_geometry->getFBXGeometry();
402 const std::vector<std::unique_ptr<NetworkMesh>>& networkMeshes = _model->_geometry->getMeshes();398 const std::vector<std::unique_ptr<NetworkMesh>>& networkMeshes = _model->_geometry->getMeshes();
403 399
@@ -467,7 +463,7 @@ void ModelMeshPartPayload::render(RenderArgs* args) const { · 63 unmodified lines
467 }463 }
468 464
469 ModelRender::Locations* locations = nullptr;465 ModelRender::Locations* locations = nullptr;
470 ModelRender::pickPrograms(batch, mode, translucentMesh, alphaThreshold, hasLightmap, hasTangents, hasSpecular, isSkinned, wireframe,466 ModelRender::pickPrograms(batch, mode, translucentMesh, hasLightmap, hasTangents, hasSpecular, isSkinned, wireframe,
471 args, locations);467 args, locations);
472 468
473 if (!locations) { // the pipeline could not be found469 if (!locations) { // the pipeline could not be found
libraries/render-utils/src/ModelRender.cpp+2−13
@@ -228,10 +228,8 @@ void ModelRender::RenderPipelineLib::addRenderPipeline(ModelRender::RenderKey ke · 227 unmodified lines
228 228
229 229
230void ModelRender::RenderPipelineLib::initLocations(gpu::ShaderPointer& program, ModelRender::Locations& locations) {230void ModelRender::RenderPipelineLib::initLocations(gpu::ShaderPointer& program, ModelRender::Locations& locations) {
231 locations.alphaThreshold = program->getUniforms().findLocation("alphaThreshold");
232 locations.texcoordMatrices = program->getUniforms().findLocation("texcoordMatrices");231 locations.texcoordMatrices = program->getUniforms().findLocation("texcoordMatrices");
233 locations.emissiveParams = program->getUniforms().findLocation("emissiveParams");232 locations.emissiveParams = program->getUniforms().findLocation("emissiveParams");
234 locations.glowIntensity = program->getUniforms().findLocation("glowIntensity");
235 locations.normalFittingMapUnit = program->getTextures().findLocation("normalFittingMap");233 locations.normalFittingMapUnit = program->getTextures().findLocation("normalFittingMap");
236 locations.diffuseTextureUnit = program->getTextures().findLocation("diffuseMap");234 locations.diffuseTextureUnit = program->getTextures().findLocation("diffuseMap");
237 locations.normalTextureUnit = program->getTextures().findLocation("normalMap");235 locations.normalTextureUnit = program->getTextures().findLocation("normalMap");
@@ -244,14 +242,14 @@ void ModelRender::RenderPipelineLib::initLocations(gpu::ShaderPointer& program, · 6 unmodified lines
244}242}
245 243
246 244
247void ModelRender::pickPrograms(gpu::Batch& batch, RenderArgs::RenderMode mode, bool translucent, float alphaThreshold,245void ModelRender::pickPrograms(gpu::Batch& batch, RenderArgs::RenderMode mode, bool translucent,
248 bool hasLightmap, bool hasTangents, bool hasSpecular, bool isSkinned, bool isWireframe, RenderArgs* args,246 bool hasLightmap, bool hasTangents, bool hasSpecular, bool isSkinned, bool isWireframe, RenderArgs* args,
249 Locations*& locations) {247 Locations*& locations) {
250 248
251 PerformanceTimer perfTimer("Model::pickPrograms");249 PerformanceTimer perfTimer("Model::pickPrograms");
252 getRenderPipelineLib();250 getRenderPipelineLib();
253 251
254 RenderKey key(mode, translucent, alphaThreshold, hasLightmap, hasTangents, hasSpecular, isSkinned, isWireframe);252 RenderKey key(mode, translucent, hasLightmap, hasTangents, hasSpecular, isSkinned, isWireframe);
255 auto pipeline = _renderPipelineLib.find(key.getRaw());253 auto pipeline = _renderPipelineLib.find(key.getRaw());
256 if (pipeline == _renderPipelineLib.end()) {254 if (pipeline == _renderPipelineLib.end()) {
257 qDebug() << "No good, couldn't find a pipeline from the key ?" << key.getRaw();255 qDebug() << "No good, couldn't find a pipeline from the key ?" << key.getRaw();
@@ -266,15 +264,6 @@ void ModelRender::pickPrograms(gpu::Batch& batch, RenderArgs::RenderMode mode, b · 8 unmodified lines
266 // Setup the One pipeline264 // Setup the One pipeline
267 batch.setPipeline((*pipeline).second._pipeline);265 batch.setPipeline((*pipeline).second._pipeline);
268 266
269 if ((locations->alphaThreshold > -1) && (mode != RenderArgs::SHADOW_RENDER_MODE)) {
270 batch._glUniform1f(locations->alphaThreshold, alphaThreshold);
271 }
272
273 if ((locations->glowIntensity > -1) && (mode != RenderArgs::SHADOW_RENDER_MODE)) {
274 const float DEFAULT_GLOW_INTENSITY = 1.0f; // FIXME - glow is removed
275 batch._glUniform1f(locations->glowIntensity, DEFAULT_GLOW_INTENSITY);
276 }
277
278 if ((locations->normalFittingMapUnit > -1)) {267 if ((locations->normalFittingMapUnit > -1)) {
279 batch.setResourceTexture(locations->normalFittingMapUnit,268 batch.setResourceTexture(locations->normalFittingMapUnit,
280 DependencyManager::get<TextureCache>()->getNormalFittingTexture());269 DependencyManager::get<TextureCache>()->getNormalFittingTexture());
libraries/render-utils/src/ModelRender.h+3−5
@@ -29,21 +29,19 @@ public: · 28 unmodified lines
29 29
30 class Locations {30 class Locations {
31 public:31 public:
32 int alphaThreshold;
33 int texcoordMatrices;32 int texcoordMatrices;
34 int diffuseTextureUnit;33 int diffuseTextureUnit;
35 int normalTextureUnit;34 int normalTextureUnit;
36 int specularTextureUnit;35 int specularTextureUnit;
37 int emissiveTextureUnit;36 int emissiveTextureUnit;
38 int emissiveParams;37 int emissiveParams;
39 int glowIntensity;
40 int normalFittingMapUnit;38 int normalFittingMapUnit;
41 int skinClusterBufferUnit;39 int skinClusterBufferUnit;
42 int materialBufferUnit;40 int materialBufferUnit;
43 int lightBufferUnit;41 int lightBufferUnit;
44 };42 };
45 43
46 static void pickPrograms(gpu::Batch& batch, RenderArgs::RenderMode mode, bool translucent, float alphaThreshold,44 static void pickPrograms(gpu::Batch& batch, RenderArgs::RenderMode mode, bool translucent,
47 bool hasLightmap, bool hasTangents, bool hasSpecular, bool isSkinned, bool isWireframe, RenderArgs* args,45 bool hasLightmap, bool hasTangents, bool hasSpecular, bool isSkinned, bool isWireframe, RenderArgs* args,
48 Locations*& locations);46 Locations*& locations);
49 47
@@ -111,9 +109,9 @@ public: · 61 unmodified lines
111 ) {}109 ) {}
112 110
113 RenderKey(RenderArgs::RenderMode mode,111 RenderKey(RenderArgs::RenderMode mode,
114 bool translucent, float alphaThreshold, bool hasLightmap,112 bool translucent, bool hasLightmap,
115 bool hasTangents, bool hasSpecular, bool isSkinned, bool isWireframe) :113 bool hasTangents, bool hasSpecular, bool isSkinned, bool isWireframe) :
116 RenderKey(((translucent && (alphaThreshold == 0.0f) && (mode != RenderArgs::SHADOW_RENDER_MODE)) ? IS_TRANSLUCENT : 0)114 RenderKey(((translucent && (mode != RenderArgs::SHADOW_RENDER_MODE)) ? IS_TRANSLUCENT : 0)
117 | (hasLightmap && (mode != RenderArgs::SHADOW_RENDER_MODE) ? HAS_LIGHTMAP : 0) // Lightmap, tangents and specular don't matter for depthOnly115 | (hasLightmap && (mode != RenderArgs::SHADOW_RENDER_MODE) ? HAS_LIGHTMAP : 0) // Lightmap, tangents and specular don't matter for depthOnly
118 | (hasTangents && (mode != RenderArgs::SHADOW_RENDER_MODE) ? HAS_TANGENTS : 0)116 | (hasTangents && (mode != RenderArgs::SHADOW_RENDER_MODE) ? HAS_TANGENTS : 0)
119 | (hasSpecular && (mode != RenderArgs::SHADOW_RENDER_MODE) ? HAS_SPECULAR : 0)117 | (hasSpecular && (mode != RenderArgs::SHADOW_RENDER_MODE) ? HAS_SPECULAR : 0)
libraries/render-utils/src/RenderDeferredTask.cpp+72−13
@@ -127,11 +127,7 @@ RenderDeferredTask::RenderDeferredTask() : Task() { · 126 unmodified lines
127 _jobs.back().setEnabled(false);127 _jobs.back().setEnabled(false);
128 _drawHitEffectJobIndex = (int)_jobs.size() -1;128 _drawHitEffectJobIndex = (int)_jobs.size() -1;
129 129
130 // Give ourselves 3 frmaes of timer queries130 _jobs.push_back(Job(new Blit::JobModel("Blit")));
131 _timerQueries.push_back(std::make_shared<gpu::Query>());
132 _timerQueries.push_back(std::make_shared<gpu::Query>());
133 _timerQueries.push_back(std::make_shared<gpu::Query>());
134 _currentTimerQueryIndex = 0;
135}131}
136 132
137RenderDeferredTask::~RenderDeferredTask() {133RenderDeferredTask::~RenderDeferredTask() {
@@ -197,10 +193,6 @@ void DrawOpaqueDeferred::run(const SceneContextPointer& sceneContext, const Rend · 59 unmodified lines
197 batch.setProjectionTransform(projMat);193 batch.setProjectionTransform(projMat);
198 batch.setViewTransform(viewMat);194 batch.setViewTransform(viewMat);
199 195
200 {
201 const float OPAQUE_ALPHA_THRESHOLD = 0.5f;
202 args->_alphaThreshold = OPAQUE_ALPHA_THRESHOLD;
203 }
204 renderItems(sceneContext, renderContext, inItems, opaque.maxDrawn);196 renderItems(sceneContext, renderContext, inItems, opaque.maxDrawn);
205 args->_batch = nullptr;197 args->_batch = nullptr;
206 });198 });
@@ -226,10 +218,7 @@ void DrawTransparentDeferred::run(const SceneContextPointer& sceneContext, const · 19 unmodified lines
226 218
227 batch.setProjectionTransform(projMat);219 batch.setProjectionTransform(projMat);
228 batch.setViewTransform(viewMat);220 batch.setViewTransform(viewMat);
229 221
230 const float TRANSPARENT_ALPHA_THRESHOLD = 0.0f;
231 args->_alphaThreshold = TRANSPARENT_ALPHA_THRESHOLD;
232
233 renderItems(sceneContext, renderContext, inItems, transparent.maxDrawn);222 renderItems(sceneContext, renderContext, inItems, transparent.maxDrawn);
234 args->_batch = nullptr;223 args->_batch = nullptr;
235 });224 });
@@ -398,6 +387,76 @@ void DrawBackgroundDeferred::run(const SceneContextPointer& sceneContext, const · 162 unmodified lines
398 args->_batch = nullptr;387 args->_batch = nullptr;
399}388}
400 389
390void Blit::run(const SceneContextPointer& sceneContext, const RenderContextPointer& renderContext) {
391 assert(renderContext->getArgs());
392 assert(renderContext->getArgs()->_context);
393
394 RenderArgs* renderArgs = renderContext->getArgs();
395 auto blitFbo = renderArgs->_blitFramebuffer;
396
397 if (!blitFbo) {
398 return;
399 }
400
401 // Determine size from viewport
402 int width = renderArgs->_viewport.z;
403 int height = renderArgs->_viewport.w;
404
405 // Blit primary to blit FBO
406 auto framebufferCache = DependencyManager::get<FramebufferCache>();
407 auto primaryFbo = framebufferCache->getPrimaryFramebuffer();
408
409 gpu::doInBatch(renderArgs->_context, [=](gpu::Batch& batch) {
410 batch.setFramebuffer(blitFbo);
411
412 if (renderArgs->_renderMode == RenderArgs::MIRROR_RENDER_MODE) {
413 if (renderArgs->_context->isStereo()) {
414 gpu::Vec4i srcRectLeft;
415 srcRectLeft.z = width / 2;
416 srcRectLeft.w = height;
417
418 gpu::Vec4i srcRectRight;
419 srcRectRight.x = width / 2;
420 srcRectRight.z = width;
421 srcRectRight.w = height;
422
423 gpu::Vec4i destRectLeft;
424 destRectLeft.x = srcRectLeft.z;
425 destRectLeft.z = srcRectLeft.x;
426 destRectLeft.y = srcRectLeft.y;
427 destRectLeft.w = srcRectLeft.w;
428
429 gpu::Vec4i destRectRight;
430 destRectRight.x = srcRectRight.z;
431 destRectRight.z = srcRectRight.x;
432 destRectRight.y = srcRectRight.y;
433 destRectRight.w = srcRectRight.w;
434
435 // Blit left to right and right to left in stereo
436 batch.blit(primaryFbo, srcRectRight, blitFbo, destRectLeft);
437 batch.blit(primaryFbo, srcRectLeft, blitFbo, destRectRight);
438 } else {
439 gpu::Vec4i srcRect;
440 srcRect.z = width;
441 srcRect.w = height;
442
443 gpu::Vec4i destRect;
444 destRect.x = width;
445 destRect.y = 0;
446 destRect.z = 0;
447 destRect.w = height;
448
449 batch.blit(primaryFbo, srcRect, blitFbo, destRect);
450 }
451 } else {
452 gpu::Vec4i rect;
453 rect.z = width;
454 rect.w = height;
455
456 batch.blit(primaryFbo, rect, blitFbo, rect);
457 }
458 });
459}
401 460
402void RenderDeferredTask::setToneMappingExposure(float exposure) {461void RenderDeferredTask::setToneMappingExposure(float exposure) {
403 if (_toneMappingJobIndex >= 0) {462 if (_toneMappingJobIndex >= 0) {
libraries/render-utils/src/RenderDeferredTask.h+7−0
@@ -90,6 +90,13 @@ public: · 89 unmodified lines
90 typedef render::Job::Model<DrawOverlay3D> JobModel;90 typedef render::Job::Model<DrawOverlay3D> JobModel;
91};91};
92 92
93class Blit {
94public:
95 void run(const render::SceneContextPointer& sceneContext, const render::RenderContextPointer& renderContext);
96
97 typedef render::Job::Model<Blit> JobModel;
98};
99
93class RenderDeferredTask : public render::Task {100class RenderDeferredTask : public render::Task {
94public:101public:
95 102
libraries/render-utils/src/RenderScriptingInterface.cpp+22−11
@@ -13,20 +13,20 @@ · 12 unmodified lines
13 13
14RenderScriptingInterface::RenderScriptingInterface() {};14RenderScriptingInterface::RenderScriptingInterface() {};
15 15
16void RenderScriptingInterface::setEngineToneMappingToneCurve(const QString& toneCurve) {16void RenderScripting::Tone::setCurve(const QString& curve) {
17 if (toneCurve == QString("None")) {17 if (curve == QString("None")) {
18 _tone.toneCurve = 0;18 toneCurve = 0;
19 } else if (toneCurve == QString("Gamma22")) {19 } else if (curve == QString("Gamma22")) {
20 _tone.toneCurve = 1;20 toneCurve = 1;
21 } else if (toneCurve == QString("Reinhard")) {21 } else if (curve == QString("Reinhard")) {
22 _tone.toneCurve = 2;22 toneCurve = 2;
23 } else if (toneCurve == QString("Filmic")) {23 } else if (curve == QString("Filmic")) {
24 _tone.toneCurve = 3;24 toneCurve = 3;
25 }25 }
26}26}
27 27
28QString RenderScriptingInterface::getEngineToneMappingToneCurve() const {28QString RenderScripting::Tone::getCurve() const {
29 switch (_tone.toneCurve) {29 switch (toneCurve) {
30 case 0:30 case 0:
31 return QString("None");31 return QString("None");
32 case 1:32 case 1:
@@ -38,4 +38,15 @@ QString RenderScriptingInterface::getEngineToneMappingToneCurve() const { · 5 unmodified lines
38 default:38 default:
39 return QString("Filmic");39 return QString("Filmic");
40 };40 };
41}
42
43render::RenderContext RenderScriptingInterface::getRenderContext() {
44 render::RenderContext::ItemsConfig items{ *_opaque, *_transparent, *_overlay3D };
45 return render::RenderContext{ items, *_tone, _drawStatus, _drawHitEffect, _deferredDebugSize, _deferredDebugMode };
46}
47
48void RenderScriptingInterface::setItemCounts(const render::RenderContext::ItemsConfig& items) {
49 _opaque->setCounts(items.opaque);
50 _transparent->setCounts(items.transparent);
51 _overlay3D->setCounts(items.overlay3D);
41}52}
libraries/render-utils/src/RenderScriptingInterface.h+71−51
@@ -17,71 +17,91 @@ · 16 unmodified lines
17 17
18#include "render/Engine.h"18#include "render/Engine.h"
19 19
20namespace RenderScripting {
21 using State = render::RenderContext::ItemsConfig::State;
22 using Counter = render::RenderContext::ItemsConfig::Counter;
23
24 class ItemCounter : public QObject, public Counter {
25 Q_OBJECT
26
27 public:
28 Q_PROPERTY(int numFeed READ getNumFeed)
29 Q_PROPERTY(int numDrawn READ getNumDrawn)
30 Q_PROPERTY(int maxDrawn MEMBER maxDrawn)
31
32 protected:
33 int getNumFeed() const { return numFeed; }
34 int getNumDrawn() const { return numDrawn; }
35 };
36 using ItemCounterPointer = std::unique_ptr<ItemCounter>;
37
38 class ItemState : public QObject, public State {
39 Q_OBJECT
40
41 public:
42 Q_PROPERTY(bool render MEMBER render)
43 Q_PROPERTY(bool cull MEMBER cull)
44 Q_PROPERTY(bool sort MEMBER sort)
45
46 Q_PROPERTY(int numFeed READ getNumFeed)
47 Q_PROPERTY(int numDrawn READ getNumDrawn)
48 Q_PROPERTY(int maxDrawn MEMBER maxDrawn)
49
50 protected:
51 int getNumFeed() const { return numFeed; }
52 int getNumDrawn() const { return numDrawn; }
53 };
54 using ItemStatePointer = std::unique_ptr<ItemState>;
55
56 class Tone : public QObject, public render::RenderContext::Tone {
57 Q_OBJECT
58
59 public:
60 Q_PROPERTY(float exposure MEMBER exposure)
61 Q_PROPERTY(QString curve READ getCurve WRITE setCurve)
62
63 QString getCurve() const;
64 int getCurveValue() const { return toneCurve; }
65 void setCurve(const QString& curve);
66 };
67 using TonePointer = std::unique_ptr<Tone>;
68};
69
20class RenderScriptingInterface : public QObject, public Dependency {70class RenderScriptingInterface : public QObject, public Dependency {
21 Q_OBJECT71 Q_OBJECT
22 SINGLETON_DEPENDENCY72 SINGLETON_DEPENDENCY
23 73
24 public:74 public:
25 Q_INVOKABLE void setEngineRenderOpaque(bool renderOpaque) { _items.opaque.render = renderOpaque; };75 Q_PROPERTY(RenderScripting::ItemState* opaque READ getOpaque)
26 Q_INVOKABLE bool doEngineRenderOpaque() const { return _items.opaque.render; }76 Q_PROPERTY(RenderScripting::ItemState* transparent READ getTransparent)
27 Q_INVOKABLE void setEngineRenderTransparent(bool renderTransparent) { _items.transparent.render = renderTransparent; };77 Q_PROPERTY(RenderScripting::ItemCounter* overlay3D READ getOverlay3D)
28 Q_INVOKABLE bool doEngineRenderTransparent() const { return _items.transparent.render; }
29
30 Q_INVOKABLE void setEngineCullOpaque(bool cullOpaque) { _items.opaque.cull = cullOpaque; };
31 Q_INVOKABLE bool doEngineCullOpaque() const { return _items.opaque.cull; }
32 Q_INVOKABLE void setEngineCullTransparent(bool cullTransparent) { _items.transparent.cull = cullTransparent; };
33 Q_INVOKABLE bool doEngineCullTransparent() const { return _items.transparent.cull; }
34
35 Q_INVOKABLE void setEngineSortOpaque(bool sortOpaque) { _items.opaque.sort = sortOpaque; };
36 Q_INVOKABLE bool doEngineSortOpaque() const { return _items.opaque.sort; }
37 Q_INVOKABLE void setEngineSortTransparent(bool sortTransparent) { _items.transparent.sort = sortTransparent; };
38 Q_INVOKABLE bool doEngineSortTransparent() const { return _items.transparent.sort; }
39
40 Q_INVOKABLE int getEngineNumDrawnOpaqueItems() { return _items.opaque.numDrawn; }
41 Q_INVOKABLE int getEngineNumDrawnTransparentItems() { return _items.transparent.numDrawn; }
42 Q_INVOKABLE int getEngineNumDrawnOverlay3DItems() { return _items.overlay3D.numDrawn; }
43
44 Q_INVOKABLE int getEngineNumFeedOpaqueItems() { return _items.opaque.numFeed; }
45 Q_INVOKABLE int getEngineNumFeedTransparentItems() { return _items.transparent.numFeed; }
46 Q_INVOKABLE int getEngineNumFeedOverlay3DItems() { return _items.overlay3D.numFeed; }
47
48 Q_INVOKABLE void setEngineMaxDrawnOpaqueItems(int count) { _items.opaque.maxDrawn = count; }
49 Q_INVOKABLE int getEngineMaxDrawnOpaqueItems() { return _items.opaque.maxDrawn; }
50 Q_INVOKABLE void setEngineMaxDrawnTransparentItems(int count) { _items.transparent.maxDrawn = count; }
51 Q_INVOKABLE int getEngineMaxDrawnTransparentItems() { return _items.transparent.maxDrawn; }
52 Q_INVOKABLE void setEngineMaxDrawnOverlay3DItems(int count) { _items.overlay3D.maxDrawn = count; }
53 Q_INVOKABLE int getEngineMaxDrawnOverlay3DItems() { return _items.overlay3D.maxDrawn; }
54
55 Q_INVOKABLE void setEngineDeferredDebugMode(int mode) { _deferredDebugMode = mode; }
56 Q_INVOKABLE int getEngineDeferredDebugMode() { return _deferredDebugMode; }
57 Q_INVOKABLE void setEngineDeferredDebugSize(glm::vec4 size) { _deferredDebugSize = size; }
58 Q_INVOKABLE glm::vec4 getEngineDeferredDebugSize() { return _deferredDebugSize; }
59
60 Q_INVOKABLE void setEngineDisplayItemStatus(int display) { _drawStatus = display; }
61 Q_INVOKABLE int doEngineDisplayItemStatus() { return _drawStatus; }
62 78
63 Q_INVOKABLE void setEngineDisplayHitEffect(bool display) { _drawHitEffect = display; }79 Q_PROPERTY(RenderScripting::Tone* tone READ getTone)
64 Q_INVOKABLE bool doEngineDisplayHitEffect() { return _drawHitEffect; }
65 80
66 Q_INVOKABLE void setEngineToneMappingExposure(float exposure) { _tone.exposure = exposure; }81 Q_PROPERTY(int displayItemStatus MEMBER _drawStatus)
67 Q_INVOKABLE float getEngineToneMappingExposure() const { return _tone.exposure; }82 Q_PROPERTY(bool displayHitEffect MEMBER _drawHitEffect)
68 83
69 Q_INVOKABLE void setEngineToneMappingToneCurve(const QString& curve);84 Q_PROPERTY(int deferredDebugMode MEMBER _deferredDebugMode)
70 Q_INVOKABLE QString getEngineToneMappingToneCurve() const;85 Q_PROPERTY(glm::vec4 deferredDebugSize MEMBER _deferredDebugSize)
71 int getEngineToneMappingToneCurveValue() const { return _tone.toneCurve; }
72 86
73 inline int getDrawStatus() { return _drawStatus; }87 render::RenderContext getRenderContext();
74 inline bool getDrawHitEffect() { return _drawHitEffect; }88 void setItemCounts(const render::RenderContext::ItemsConfig& items);
75 inline const render::RenderContext::ItemsConfig& getItemsConfig() { return _items; }
76 inline const render::RenderContext::Tone& getTone() { return _tone; }
77 void setItemCounts(const render::RenderContext::ItemsConfig& items) { _items.setCounts(items); };
78 89
79protected:90protected:
80 RenderScriptingInterface();91 RenderScriptingInterface();
81 ~RenderScriptingInterface() {};92 ~RenderScriptingInterface() {};
82 93
83 render::RenderContext::ItemsConfig _items;94 RenderScripting::ItemState* getOpaque() const { return _opaque.get(); }
84 render::RenderContext::Tone _tone;95 RenderScripting::ItemState* getTransparent() const { return _transparent.get(); }
96 RenderScripting::ItemCounter* getOverlay3D() const { return _overlay3D.get(); }
97
98 RenderScripting::Tone* getTone() const { return _tone.get(); }
99
100 RenderScripting::ItemStatePointer _opaque = RenderScripting::ItemStatePointer{new RenderScripting::ItemState{}};
101 RenderScripting::ItemStatePointer _transparent = RenderScripting::ItemStatePointer{new RenderScripting::ItemState{}};
102 RenderScripting::ItemCounterPointer _overlay3D = RenderScripting::ItemCounterPointer{new RenderScripting::ItemCounter{}};
103
104 RenderScripting::TonePointer _tone = RenderScripting::TonePointer{ new RenderScripting::Tone{} };
85 105
86 // Options106 // Options
87 int _drawStatus = 0;107 int _drawStatus = 0;
libraries/render-utils/src/SkyFromSpace.slf+2−1
@@ -114,5 +114,6 @@ void main (void) · 113 unmodified lines
114 114
115 vec3 finalColor = color + fMiePhase * secondaryColor;115 vec3 finalColor = color + fMiePhase * secondaryColor;
116 outFragColor.a = finalColor.b;116 outFragColor.a = finalColor.b;
117 outFragColor.rgb = pow(finalColor.rgb, vec3(1.0/2.2));117 // outFragColor.rgb = pow(finalColor.rgb, vec3(1.0/2.2));
118 outFragColor.rgb = finalColor.rgb;
118}119}
libraries/render-utils/src/simple.slf+2−2
@@ -51,9 +51,9 @@ void main(void) { · 50 unmodified lines
51 51
52 if (emissiveAmount > 0.0) {52 if (emissiveAmount > 0.0) {
53 packDeferredFragmentLightmap(53 packDeferredFragmentLightmap(
54 normal, glowIntensity, diffuse, specular, shininess, specular);54 normal, 1.0, diffuse, specular, shininess, specular);
55 } else {55 } else {
56 packDeferredFragment(56 packDeferredFragment(
57 normal, glowIntensity, diffuse, specular, shininess);57 normal, 1.0, diffuse, specular, shininess);
58 }58 }
59}59}
libraries/render-utils/src/simple_textured.slf+1−1
@@ -29,7 +29,7 @@ void main(void) { · 28 unmodified lines
29 29
30 packDeferredFragment(30 packDeferredFragment(
31 normalize(_normal.xyz), 31 normalize(_normal.xyz),
32 glowIntensity * texel.a,32 texel.a,
33 _color.rgb * texel.rgb,33 _color.rgb * texel.rgb,
34 DEFAULT_SPECULAR, DEFAULT_SHININESS);34 DEFAULT_SPECULAR, DEFAULT_SHININESS);
35}35}
libraries/render-utils/src/simple_textured_emisive.slf+1−1
@@ -27,7 +27,7 @@ void main(void) { · 26 unmodified lines
27 27
28 packDeferredFragmentLightmap(28 packDeferredFragmentLightmap(
29 normalize(_normal),29 normalize(_normal),
30 glowIntensity * texel.a,30 texel.a,
31 _color.rgb,31 _color.rgb,
32 DEFAULT_SPECULAR, DEFAULT_SHININESS,32 DEFAULT_SPECULAR, DEFAULT_SHININESS,
33 texel.rgb);33 texel.rgb);
libraries/render/src/render/Engine.cpp+7−3
@@ -13,11 +13,15 @@ · 12 unmodified lines
13#include "DrawTask.h"13#include "DrawTask.h"
14using namespace render;14using namespace render;
15 15
16void RenderContext::setOptions(int drawStatus, bool drawHitEffect, bool occlusion, bool fxaa, bool showOwned) {16RenderContext::RenderContext(ItemsConfig items, Tone tone, int drawStatus, bool drawHitEffect, glm::vec4 deferredDebugSize, int deferredDebugMode)
17 _drawStatus = drawStatus;17 : _deferredDebugMode{ deferredDebugMode }, _deferredDebugSize{ deferredDebugSize },
18 _args{ nullptr },
19 _drawStatus{ drawStatus }, _drawHitEffect{ drawHitEffect },
20 _items{ items }, _tone{ tone } {}
21
22void RenderContext::setOptions(bool occlusion, bool fxaa, bool showOwned) {
18 _occlusionStatus = occlusion;23 _occlusionStatus = occlusion;
19 _fxaaStatus = fxaa;24 _fxaaStatus = fxaa;
20 _drawHitEffect = drawHitEffect;
21 25
22 if (showOwned) {26 if (showOwned) {
23 _drawStatus |= render::showNetworkStatusFlag;27 _drawStatus |= render::showNetworkStatusFlag;
libraries/render/src/render/Engine.h+13−14
@@ -34,12 +34,6 @@ class RenderContext { · 33 unmodified lines
34public:34public:
35 class ItemsConfig {35 class ItemsConfig {
36 public:36 public:
37 inline void setCounts(const ItemsConfig& items) {
38 opaque.setCounts(items.opaque);
39 transparent.setCounts(items.transparent);
40 overlay3D.setCounts(items.overlay3D);
41 };
42
43 class Counter {37 class Counter {
44 public:38 public:
45 Counter() {};39 Counter() {};
@@ -48,7 +42,7 @@ public: · 2 unmodified lines
48 maxDrawn = counter.maxDrawn;42 maxDrawn = counter.maxDrawn;
49 };43 };
50 44
51 inline void setCounts(const Counter& counter) {45 void setCounts(const Counter& counter) {
52 numFeed = counter.numFeed;46 numFeed = counter.numFeed;
53 numDrawn = counter.numDrawn;47 numDrawn = counter.numDrawn;
54 };48 };
@@ -67,6 +61,10 @@ public: · 12 unmodified lines
67 Counter counter{};61 Counter counter{};
68 };62 };
69 63
64 ItemsConfig(State opaqueState, State transparentState, Counter overlay3DCounter)
65 : opaque{ opaqueState }, transparent{ transparentState }, overlay3D{ overlay3DCounter } {}
66 ItemsConfig() : ItemsConfig{ {}, {}, {} } {}
67
70 // TODO: If member count increases, store counters in a map instead of multiple members68 // TODO: If member count increases, store counters in a map instead of multiple members
71 State opaque{};69 State opaque{};
72 State transparent{};70 State transparent{};
@@ -79,9 +77,10 @@ public: · 6 unmodified lines
79 float exposure = 0.0;77 float exposure = 0.0;
80 };78 };
81 79
82 RenderContext(RenderArgs* args, ItemsConfig items, Tone tone) : _args{args}, _items{items}, _tone{tone} {};80 RenderContext(ItemsConfig items, Tone tone, int drawStatus, bool drawHitEffect, glm::vec4 deferredDebugSize, int deferredDebugMode);
83 RenderContext() : RenderContext(nullptr, {}, {}) {};81 RenderContext() : RenderContext({}, {}, {}, {}, {}, {}) {};
84 82
83 void setArgs(RenderArgs* args) { _args = args; }
85 inline RenderArgs* getArgs() { return _args; }84 inline RenderArgs* getArgs() { return _args; }
86 inline ItemsConfig& getItemsConfig() { return _items; }85 inline ItemsConfig& getItemsConfig() { return _items; }
87 inline Tone& getTone() { return _tone; }86 inline Tone& getTone() { return _tone; }
@@ -89,18 +88,18 @@ public: · 1 unmodified line
89 inline bool getDrawHitEffect() { return _drawHitEffect; }88 inline bool getDrawHitEffect() { return _drawHitEffect; }
90 inline bool getOcclusionStatus() { return _occlusionStatus; }89 inline bool getOcclusionStatus() { return _occlusionStatus; }
91 inline bool getFxaaStatus() { return _fxaaStatus; }90 inline bool getFxaaStatus() { return _fxaaStatus; }
92 void setOptions(int drawStatus, bool drawHitEffect, bool occlusion, bool fxaa, bool showOwned);91 void setOptions(bool occlusion, bool fxaa, bool showOwned);
93 92
94 // Debugging93 // Debugging
95 int _deferredDebugMode = -1;94 int _deferredDebugMode;
96 glm::vec4 _deferredDebugSize { 0.0f, -1.0f, 1.0f, 1.0f };95 glm::vec4 _deferredDebugSize;
97 96
98protected:97protected:
99 RenderArgs* _args;98 RenderArgs* _args;
100 99
101 // Options100 // Options
102 int _drawStatus = 0; // bitflag101 int _drawStatus; // bitflag
103 bool _drawHitEffect = false;102 bool _drawHitEffect;
104 bool _occlusionStatus = false;103 bool _occlusionStatus = false;
105 bool _fxaaStatus = false;104 bool _fxaaStatus = false;
106 105
libraries/script-engine/src/SceneScriptingInterface.cpp+60−45
@@ -13,99 +13,95 @@ · 12 unmodified lines
13 13
14#include <procedural/ProceduralSkybox.h>14#include <procedural/ProceduralSkybox.h>
15 15
16SceneScriptingInterface::SceneScriptingInterface() {16float SceneScripting::Location::getLongitude() const {
17 // Let's make sure the sunSkyStage is using a proceduralSkybox17 return _skyStage->getOriginLongitude();
18 _skyStage->setSkybox(model::SkyboxPointer(new ProceduralSkybox()));
19}18}
20 19
21void SceneScriptingInterface::setShouldRenderAvatars(bool shouldRenderAvatars) {20float SceneScripting::Location::getLatitude() const {
22 if (shouldRenderAvatars != _shouldRenderAvatars) {21 return _skyStage->getOriginLatitude();
23 _shouldRenderAvatars = shouldRenderAvatars;
24 emit shouldRenderAvatarsChanged(_shouldRenderAvatars);
25 }
26}22}
27 23
28void SceneScriptingInterface::setShouldRenderEntities(bool shouldRenderEntities) {24float SceneScripting::Location::getAltitude() const {
29 if (shouldRenderEntities != _shouldRenderEntities) {25 return _skyStage->getOriginSurfaceAltitude();
30 _shouldRenderEntities = shouldRenderEntities;
31 emit shouldRenderEntitiesChanged(_shouldRenderEntities);
32 }
33}26}
34 27
35void SceneScriptingInterface::setStageOrientation(const glm::quat& orientation) {28void SceneScripting::Location::setLongitude(float longitude) {
36 _skyStage->setOriginOrientation(orientation);29 _skyStage->setOriginLongitude(longitude);
37}
38void SceneScriptingInterface::setStageLocation(float longitude, float latitude, float altitude) {
39 _skyStage->setOriginLocation(longitude, latitude, altitude);
40}30}
41 31
42float SceneScriptingInterface::getStageLocationLongitude() const {32void SceneScripting::Location::setLatitude(float latitude) {
43 return _skyStage->getOriginLongitude();33 _skyStage->setOriginLatitude(latitude);
44}
45float SceneScriptingInterface::getStageLocationLatitude() const {
46 return _skyStage->getOriginLatitude();
47}34}
48float SceneScriptingInterface::getStageLocationAltitude() const {35
49 return _skyStage->getOriginSurfaceAltitude();36void SceneScripting::Location::setAltitude(float altitude) {
37 _skyStage->setOriginSurfaceAltitude(altitude);
50}38}
51 39
52void SceneScriptingInterface::setStageDayTime(float hour) {40void SceneScripting::Time::setHour(float hour) {
53 _skyStage->setDayTime(hour);41 _skyStage->setDayTime(hour);
54}42}
55 43
56float SceneScriptingInterface::getStageDayTime() const {44float SceneScripting::Time::getHour() const {
57 return _skyStage->getDayTime();45 return _skyStage->getDayTime();
58}46}
59 47
60void SceneScriptingInterface::setStageYearTime(int day) {48void SceneScripting::Time::setDay(int day) {
61 _skyStage->setYearTime(day);49 _skyStage->setYearTime(day);
62}50}
63 51
64int SceneScriptingInterface::getStageYearTime() const {52int SceneScripting::Time::getDay() const {
65 return _skyStage->getYearTime();53 return _skyStage->getYearTime();
66}54}
67 55
68void SceneScriptingInterface::setKeyLightColor(const glm::vec3& color) {56glm::vec3 SceneScripting::KeyLight::getColor() const {
57 return _skyStage->getSunColor();
58}
59
60void SceneScripting::KeyLight::setColor(const glm::vec3& color) {
69 _skyStage->setSunColor(color);61 _skyStage->setSunColor(color);
70}62}
71 63
72glm::vec3 SceneScriptingInterface::getKeyLightColor() const {64float SceneScripting::KeyLight::getIntensity() const {
73 return _skyStage->getSunColor();65 return _skyStage->getSunIntensity();
74}66}
75 67
76void SceneScriptingInterface::setKeyLightIntensity(float intensity) {68void SceneScripting::KeyLight::setIntensity(float intensity) {
77 _skyStage->setSunIntensity(intensity);69 _skyStage->setSunIntensity(intensity);
78}70}
79 71
80float SceneScriptingInterface::getKeyLightIntensity() const {72float SceneScripting::KeyLight::getAmbientIntensity() const {
81 return _skyStage->getSunIntensity();73 return _skyStage->getSunAmbientIntensity();
82}74}
83 75
84void SceneScriptingInterface::setKeyLightAmbientIntensity(float intensity) {76void SceneScripting::KeyLight::setAmbientIntensity(float intensity) {
85 _skyStage->setSunAmbientIntensity(intensity);77 _skyStage->setSunAmbientIntensity(intensity);
86}78}
87 79
88float SceneScriptingInterface::getKeyLightAmbientIntensity() const {80glm::vec3 SceneScripting::KeyLight::getDirection() const {
89 return _skyStage->getSunAmbientIntensity();81 return _skyStage->getSunDirection();
90}82}
91 83
92void SceneScriptingInterface::setKeyLightDirection(const glm::vec3& direction) {84void SceneScripting::KeyLight::setDirection(const glm::vec3& direction) {
93 _skyStage->setSunDirection(direction);85 _skyStage->setSunDirection(direction);
94}86}
95 87
96glm::vec3 SceneScriptingInterface::getKeyLightDirection() const {88void SceneScripting::Stage::setOrientation(const glm::quat& orientation) const {
97 return _skyStage->getSunDirection();89 _skyStage->setOriginOrientation(orientation);
90}
91
92void SceneScripting::Stage::setLocation(float longitude, float latitude, float altitude) {
93 _skyStage->setOriginLocation(longitude, latitude, altitude);
98}94}
99 95
100void SceneScriptingInterface::setStageSunModelEnable(bool isEnabled) {96void SceneScripting::Stage::setSunModelEnable(bool isEnabled) {
101 _skyStage->setSunModelEnable(isEnabled);97 _skyStage->setSunModelEnable(isEnabled);
102}98}
103 99
104bool SceneScriptingInterface::isStageSunModelEnabled() const {100bool SceneScripting::Stage::isSunModelEnabled() const {
105 return _skyStage->isSunModelEnabled();101 return _skyStage->isSunModelEnabled();
106}102}
107 103
108void SceneScriptingInterface::setBackgroundMode(const QString& mode) {104void SceneScripting::Stage::setBackgroundMode(const QString& mode) {
109 if (mode == QString("inherit")) {105 if (mode == QString("inherit")) {
110 _skyStage->setBackgroundMode(model::SunSkyStage::NO_BACKGROUND);106 _skyStage->setBackgroundMode(model::SunSkyStage::NO_BACKGROUND);
111 } else if (mode == QString("atmosphere")) {107 } else if (mode == QString("atmosphere")) {
@@ -115,7 +111,7 @@ void SceneScriptingInterface::setBackgroundMode(const QString& mode) { · 3 unmodified lines
115 }111 }
116}112}
117 113
118QString SceneScriptingInterface::getBackgroundMode() const {114QString SceneScripting::Stage::getBackgroundMode() const {
119 switch (_skyStage->getBackgroundMode()) {115 switch (_skyStage->getBackgroundMode()) {
120 case model::SunSkyStage::NO_BACKGROUND:116 case model::SunSkyStage::NO_BACKGROUND:
121 return QString("inherit");117 return QString("inherit");
@@ -128,6 +124,25 @@ QString SceneScriptingInterface::getBackgroundMode() const { · 6 unmodified lines
128 };124 };
129}125}
130 126
127SceneScriptingInterface::SceneScriptingInterface() : _stage{ new SceneScripting::Stage{ _skyStage } } {
128 // Let's make sure the sunSkyStage is using a proceduralSkybox
129 _skyStage->setSkybox(model::SkyboxPointer(new ProceduralSkybox()));
130}
131
132void SceneScriptingInterface::setShouldRenderAvatars(bool shouldRenderAvatars) {
133 if (shouldRenderAvatars != _shouldRenderAvatars) {
134 _shouldRenderAvatars = shouldRenderAvatars;
135 emit shouldRenderAvatarsChanged(_shouldRenderAvatars);
136 }
137}
138
139void SceneScriptingInterface::setShouldRenderEntities(bool shouldRenderEntities) {
140 if (shouldRenderEntities != _shouldRenderEntities) {
141 _shouldRenderEntities = shouldRenderEntities;
142 emit shouldRenderEntitiesChanged(_shouldRenderEntities);
143 }
144}
145
131model::SunSkyStagePointer SceneScriptingInterface::getSkyStage() const {146model::SunSkyStagePointer SceneScriptingInterface::getSkyStage() const {
132 return _skyStage;147 return _skyStage;
133}148}
libraries/script-engine/src/SceneScriptingInterface.h+118−41
@@ -17,6 +17,114 @@ · 16 unmodified lines
17 17
18#include "model/Stage.h"18#include "model/Stage.h"
19 19
20// TODO: if QT moc ever supports nested classes, subclass these to the interface instead of namespacing
21namespace SceneScripting {
22 class Location : public QObject {
23 Q_OBJECT
24
25 public:
26 Location(model::SunSkyStagePointer skyStage) : _skyStage{ skyStage } {}
27
28 Q_PROPERTY(float longitude READ getLongitude WRITE setLongitude)
29 Q_PROPERTY(float latitude READ getLatitude WRITE setLatitude)
30 Q_PROPERTY(float altitude READ getAltitude WRITE setAltitude)
31
32 float getLongitude() const;
33 float getLatitude() const;
34 float getAltitude() const;
35 void setLongitude(float longitude);
36 void setLatitude(float latitude);
37 void setAltitude(float altitude);
38
39 protected:
40 model::SunSkyStagePointer _skyStage;
41 };
42 using LocationPointer = std::unique_ptr<Location>;
43
44 class Time : public QObject {
45 Q_OBJECT
46
47 public:
48 Time(model::SunSkyStagePointer skyStage) : _skyStage{ skyStage } {}
49
50 Q_PROPERTY(float hour READ getHour WRITE setHour)
51 Q_PROPERTY(int day READ getDay WRITE setDay)
52
53 float getHour() const;
54 void setHour(float hour);
55 int getDay() const;
56 void setDay(int day);
57
58 protected:
59 model::SunSkyStagePointer _skyStage;
60 };
61 using TimePointer = std::unique_ptr<Time>;
62
63 class KeyLight : public QObject {
64 Q_OBJECT
65
66 public:
67 KeyLight(model::SunSkyStagePointer skyStage) : _skyStage{ skyStage } {}
68
69 Q_PROPERTY(glm::vec3 color READ getColor WRITE setColor)
70 Q_PROPERTY(float intensity READ getIntensity WRITE setIntensity)
71 Q_PROPERTY(float ambientIntensity READ getAmbientIntensity WRITE setAmbientIntensity)
72 Q_PROPERTY(glm::vec3 direction READ getDirection WRITE setDirection)
73
74 glm::vec3 getColor() const;
75 void setColor(const glm::vec3& color);
76 float getIntensity() const;
77 void setIntensity(float intensity);
78 float getAmbientIntensity() const;
79 void setAmbientIntensity(float intensity);
80 glm::vec3 getDirection() const;
81 // setDirection is only effective if stage Sun model is disabled
82 void setDirection(const glm::vec3& direction);
83
84 protected:
85 model::SunSkyStagePointer _skyStage;
86 };
87 using KeyLightPointer = std::unique_ptr<KeyLight>;
88
89 class Stage : public QObject {
90 Q_OBJECT
91
92 public:
93 Stage(model::SunSkyStagePointer skyStage)
94 : _skyStage{ skyStage },
95 _location{ new Location{ skyStage } }, _time{ new Time{ skyStage } }, _keyLight{ new KeyLight{ skyStage } }{}
96
97 Q_INVOKABLE void setOrientation(const glm::quat& orientation) const;
98
99 Q_PROPERTY(Location* location READ getLocation)
100 Location* getLocation() const { return _location.get(); }
101 Q_INVOKABLE void setLocation(float longitude, float latitude, float altitude);
102
103 Q_PROPERTY(Time* time READ getTime)
104 Time* getTime() const { return _time.get(); }
105
106 Q_PROPERTY(KeyLight* keyLight READ getKeyLight)
107 KeyLight* getKeyLight() const { return _keyLight.get(); }
108
109 // Enable/disable the stage sun model which uses the key light to simulate
110 // the sun light based on the location of the stage relative to earth and the current time
111 Q_PROPERTY(bool sunModel READ isSunModelEnabled WRITE setSunModelEnable)
112 void setSunModelEnable(bool isEnabled);
113 bool isSunModelEnabled() const;
114
115 Q_PROPERTY(QString backgroundMode READ getBackgroundMode WRITE setBackgroundMode)
116 void setBackgroundMode(const QString& mode);
117 QString getBackgroundMode() const;
118
119 protected:
120 model::SunSkyStagePointer _skyStage;
121 LocationPointer _location;
122 TimePointer _time;
123 KeyLightPointer _keyLight;
124 };
125 using StagePointer = std::unique_ptr<Stage>;
126};
127
20class SceneScriptingInterface : public QObject, public Dependency {128class SceneScriptingInterface : public QObject, public Dependency {
21 Q_OBJECT129 Q_OBJECT
22 SINGLETON_DEPENDENCY130 SINGLETON_DEPENDENCY
@@ -24,46 +132,14 @@ class SceneScriptingInterface : public QObject, public Dependency { · 1 unmodified line
24public:132public:
25 Q_PROPERTY(bool shouldRenderAvatars READ shouldRenderAvatars WRITE setShouldRenderAvatars)133 Q_PROPERTY(bool shouldRenderAvatars READ shouldRenderAvatars WRITE setShouldRenderAvatars)
26 Q_PROPERTY(bool shouldRenderEntities READ shouldRenderEntities WRITE setShouldRenderEntities)134 Q_PROPERTY(bool shouldRenderEntities READ shouldRenderEntities WRITE setShouldRenderEntities)
27 135 bool shouldRenderAvatars() const { return _shouldRenderAvatars; }
28 Q_INVOKABLE void setShouldRenderAvatars(bool shouldRenderAvatars);136 bool shouldRenderEntities() const { return _shouldRenderEntities; }
29 Q_INVOKABLE bool shouldRenderAvatars() const { return _shouldRenderAvatars; }137 void setShouldRenderAvatars(bool shouldRenderAvatars);
30 138 void setShouldRenderEntities(bool shouldRenderEntities);
31 Q_INVOKABLE void setShouldRenderEntities(bool shouldRenderEntities);139
32 Q_INVOKABLE bool shouldRenderEntities() const { return _shouldRenderEntities; }140 Q_PROPERTY(SceneScripting::Stage* stage READ getStage)
33 141 SceneScripting::Stage* getStage() const { return _stage.get(); }
34 Q_INVOKABLE void setStageOrientation(const glm::quat& orientation);142
35
36 Q_INVOKABLE void setStageLocation(float longitude, float latitude, float altitude);
37 Q_INVOKABLE float getStageLocationLongitude() const;
38 Q_INVOKABLE float getStageLocationLatitude() const;
39 Q_INVOKABLE float getStageLocationAltitude() const;
40
41 Q_INVOKABLE void setStageDayTime(float hour);
42 Q_INVOKABLE float getStageDayTime() const;
43 Q_INVOKABLE void setStageYearTime(int day);
44 Q_INVOKABLE int getStageYearTime() const;
45
46 // Enable/disable the stage sun model which uses the key light to simulate
47 // the sun light based on the location of the stage trelative to earth and the current time
48 Q_INVOKABLE void setStageSunModelEnable(bool isEnabled);
49 Q_INVOKABLE bool isStageSunModelEnabled() const;
50
51 Q_INVOKABLE void setKeyLightColor(const glm::vec3& color);
52 Q_INVOKABLE glm::vec3 getKeyLightColor() const;
53 Q_INVOKABLE void setKeyLightIntensity(float intensity);
54 Q_INVOKABLE float getKeyLightIntensity() const;
55 Q_INVOKABLE void setKeyLightAmbientIntensity(float intensity);
56 Q_INVOKABLE float getKeyLightAmbientIntensity() const;
57
58 // setKeyLightDIrection is only effective if stage Sun model is disabled
59 Q_INVOKABLE void setKeyLightDirection(const glm::vec3& direction);
60
61 Q_INVOKABLE glm::vec3 getKeyLightDirection() const;
62
63
64 Q_INVOKABLE void setBackgroundMode(const QString& mode);
65 Q_INVOKABLE QString getBackgroundMode() const;
66
67 model::SunSkyStagePointer getSkyStage() const;143 model::SunSkyStagePointer getSkyStage() const;
68 144
69signals:145signals:
@@ -75,9 +151,10 @@ protected: · 5 unmodified lines
75 ~SceneScriptingInterface() {};151 ~SceneScriptingInterface() {};
76 152
77 model::SunSkyStagePointer _skyStage = std::make_shared<model::SunSkyStage>();153 model::SunSkyStagePointer _skyStage = std::make_shared<model::SunSkyStage>();
154 SceneScripting::StagePointer _stage;
78 155
79 bool _shouldRenderAvatars = true;156 bool _shouldRenderAvatars = true;
80 bool _shouldRenderEntities = true;157 bool _shouldRenderEntities = true;
81};158};
82 159
83#endif // hifi_SceneScriptingInterface_h160#endif // hifi_SceneScriptingInterface_h
libraries/shared/src/RenderArgs.h+2−2
@@ -24,6 +24,7 @@ namespace gpu { · 23 unmodified lines
24class Batch;24class Batch;
25class Context;25class Context;
26class Texture;26class Texture;
27class Framebuffer;
27}28}
28 29
29class RenderDetails {30class RenderDetails {
@@ -101,6 +102,7 @@ public: · 71 unmodified lines
101 }102 }
102 103
103 std::shared_ptr<gpu::Context> _context = nullptr;104 std::shared_ptr<gpu::Context> _context = nullptr;
105 std::shared_ptr<gpu::Framebuffer> _blitFramebuffer = nullptr;
104 OctreeRenderer* _renderer = nullptr;106 OctreeRenderer* _renderer = nullptr;
105 ViewFrustum* _viewFrustum = nullptr;107 ViewFrustum* _viewFrustum = nullptr;
106 glm::ivec4 _viewport{ 0, 0, 1, 1 };108 glm::ivec4 _viewport{ 0, 0, 1, 1 };
@@ -115,8 +117,6 @@ public: · 8 unmodified lines
115 std::shared_ptr<gpu::Texture> _whiteTexture;117 std::shared_ptr<gpu::Texture> _whiteTexture;
116 118
117 RenderDetails _details;119 RenderDetails _details;
118
119 float _alphaThreshold = 0.5f;
120};120};
121 121
122#endif // hifi_RenderArgs_h122#endif // hifi_RenderArgs_h
libraries/ui/src/QmlWebWindowClass.cpp+52−8
@@ -10,18 +10,20 @@ · 9 unmodified lines
10 10
11#include <mutex>11#include <mutex>
12 12
13#include <QtCore/QCoreApplication>
14#include <QtCore/QJsonDocument>
15#include <QtCore/QJsonObject>
16#include <QtCore/QUrl>
17#include <QtCore/QUrlQuery>
13#include <QtCore/QThread>18#include <QtCore/QThread>
19#include <QtQml/QQmlContext>
14#include <QtScript/QScriptContext>20#include <QtScript/QScriptContext>
15#include <QtScript/QScriptEngine>21#include <QtScript/QScriptEngine>
16 22#include <QtWebChannel/QWebChannel>
17#include <QtQuick/QQuickItem>
18
19#include <QtWebSockets/QWebSocketServer>23#include <QtWebSockets/QWebSocketServer>
20#include <QtWebSockets/QWebSocket>24#include <QtWebSockets/QWebSocket>
21#include <QtWebChannel/QWebChannel>
22#include <QtCore/QJsonDocument>
23#include <QtCore/QJsonObject>
24 25
26#include <AbstractUriHandler.h>
25#include <AddressManager.h>27#include <AddressManager.h>
26#include <DependencyManager.h>28#include <DependencyManager.h>
27 29
@@ -83,17 +85,41 @@ void QmlWebWindowClass::setupServer() { · 55 unmodified lines
83 }85 }
84}86}
85 87
88class UrlFixer : public QObject {
89 Q_OBJECT
90public:
91 Q_INVOKABLE QString fixupUrl(const QString& originalUrl) {
92 static const QString ACCESS_TOKEN_PARAMETER = "access_token";
93 static const QString ALLOWED_HOST = "metaverse.highfidelity.com";
94 QString result = originalUrl;
95 QUrl url(originalUrl);
96 QUrlQuery query(url);
97 if (url.host() == ALLOWED_HOST && query.allQueryItemValues(ACCESS_TOKEN_PARAMETER).empty()) {
98 qDebug() << "Updating URL with auth token";
99 AccountManager& accountManager = AccountManager::getInstance();
100 query.addQueryItem(ACCESS_TOKEN_PARAMETER, accountManager.getAccountInfo().getAccessToken().token);
101 url.setQuery(query.query());
102 result = url.toString();
103 }
104
105 return result;
106 }
107};
108
109static UrlFixer URL_FIXER;
110
86// Method called by Qt scripts to create a new web window in the overlay111// Method called by Qt scripts to create a new web window in the overlay
87QScriptValue QmlWebWindowClass::constructor(QScriptContext* context, QScriptEngine* engine) {112QScriptValue QmlWebWindowClass::constructor(QScriptContext* context, QScriptEngine* engine) {
88 QmlWebWindowClass* retVal { nullptr };113 QmlWebWindowClass* retVal { nullptr };
89 const QString title = context->argument(0).toString();114 const QString title = context->argument(0).toString();
90 QString url = context->argument(1).toString();115 QString url = context->argument(1).toString();
91 if (!url.startsWith("http") && !url.startsWith("file://")) {116 if (!url.startsWith("http") && !url.startsWith("file://") && !url.startsWith("about:")) {
92 url = QUrl::fromLocalFile(url).toString();117 url = QUrl::fromLocalFile(url).toString();
93 }118 }
94 const int width = std::max(100, std::min(1280, context->argument(2).toInt32()));;119 const int width = std::max(100, std::min(1280, context->argument(2).toInt32()));;
95 const int height = std::max(100, std::min(720, context->argument(3).toInt32()));;120 const int height = std::max(100, std::min(720, context->argument(3).toInt32()));;
96 121
122
97 // Build the event bridge and wrapper on the main thread123 // Build the event bridge and wrapper on the main thread
98 QMetaObject::invokeMethod(DependencyManager::get<OffscreenUi>().data(), "load", Qt::BlockingQueuedConnection,124 QMetaObject::invokeMethod(DependencyManager::get<OffscreenUi>().data(), "load", Qt::BlockingQueuedConnection,
99 Q_ARG(const QString&, "QmlWebWindow.qml"),125 Q_ARG(const QString&, "QmlWebWindow.qml"),
@@ -101,6 +127,7 @@ QScriptValue QmlWebWindowClass::constructor(QScriptContext* context, QScriptEngi · 1 unmodified line
101 setupServer();127 setupServer();
102 retVal = new QmlWebWindowClass(object);128 retVal = new QmlWebWindowClass(object);
103 webChannel.registerObject(url.toLower(), retVal);129 webChannel.registerObject(url.toLower(), retVal);
130 context->setContextProperty("urlFixer", &URL_FIXER);
104 retVal->setTitle(title);131 retVal->setTitle(title);
105 retVal->setURL(url);132 retVal->setURL(url);
106 retVal->setSize(width, height);133 retVal->setSize(width, height);
@@ -119,7 +146,23 @@ QmlWebWindowClass::QmlWebWindowClass(QObject* qmlWindow) · 12 unmodified lines
119}146}
120 147
121void QmlWebWindowClass::handleNavigation(const QString& url) {148void QmlWebWindowClass::handleNavigation(const QString& url) {
122 DependencyManager::get<AddressManager>()->handleLookupString(url);149 bool handled = false;
150
151 if (url.contains(HIFI_URL_PATTERN)) {
152 DependencyManager::get<AddressManager>()->handleLookupString(url);
153 handled = true;
154 } else {
155 static auto handler = dynamic_cast<AbstractUriHandler*>(qApp);
156 if (handler) {
157 if (handler->canAcceptURL(url)) {
158 handled = handler->acceptURL(url);
159 }
160 }
161 }
162
163 if (handled) {
164 QMetaObject::invokeMethod(_qmlWindow, "stop", Qt::AutoConnection);
165 }
123}166}
124 167
125void QmlWebWindowClass::setVisible(bool visible) {168void QmlWebWindowClass::setVisible(bool visible) {
@@ -202,6 +245,7 @@ QString QmlWebWindowClass::getURL() const { · 76 unmodified lines
202 QMetaObject::invokeMethod(const_cast<QmlWebWindowClass*>(this), "getURL", Qt::BlockingQueuedConnection, Q_RETURN_ARG(QString, result));245 QMetaObject::invokeMethod(const_cast<QmlWebWindowClass*>(this), "getURL", Qt::BlockingQueuedConnection, Q_RETURN_ARG(QString, result));
203 return result;246 return result;
204 }247 }
248
205 return _qmlWindow->property(URL_PROPERTY).toString();249 return _qmlWindow->property(URL_PROPERTY).toString();
206}250}
207 251
libraries/ui/src/QmlWebWindowClass.h+2−1
@@ -10,11 +10,12 @@ · 9 unmodified lines
10#define hifi_ui_QmlWebWindowClass_h10#define hifi_ui_QmlWebWindowClass_h
11 11
12#include <QtCore/QObject>12#include <QtCore/QObject>
13#include <GLMHelpers.h>
14#include <QtScript/QScriptValue>13#include <QtScript/QScriptValue>
15#include <QtQuick/QQuickItem>14#include <QtQuick/QQuickItem>
16#include <QtWebChannel/QWebChannelAbstractTransport>15#include <QtWebChannel/QWebChannelAbstractTransport>
17 16
17#include <GLMHelpers.h>
18
18class QScriptEngine;19class QScriptEngine;
19class QScriptContext;20class QScriptContext;
20class QmlWebWindowClass;21class QmlWebWindowClass;
plugins/hifiSixense/src/SixenseManager.cpp+22−1
@@ -13,6 +13,9 @@ · 12 unmodified lines
13 13
14#ifdef HAVE_SIXENSE14#ifdef HAVE_SIXENSE
15#include <sixense.h>15#include <sixense.h>
16#else
17#define SIXENSE_FAILURE -1
18#define SIXENSE_SUCCESS 0
16#endif19#endif
17 20
18#include <QCoreApplication>21#include <QCoreApplication>
@@ -43,6 +46,14 @@ static const unsigned int BUTTON_TRIGGER = 1U << 8; · 24 unmodified lines
43 46
44const glm::vec3 SixenseManager::DEFAULT_AVATAR_POSITION { -0.25f, -0.35f, -0.3f }; // in hydra frame47const glm::vec3 SixenseManager::DEFAULT_AVATAR_POSITION { -0.25f, -0.35f, -0.3f }; // in hydra frame
45const float SixenseManager::CONTROLLER_THRESHOLD { 0.35f };48const float SixenseManager::CONTROLLER_THRESHOLD { 0.35f };
49bool SixenseManager::_sixenseLoaded = false;
50
51#define BAIL_IF_NOT_LOADED \
52 if (!_sixenseLoaded) { \
53 return; \
54 }
55
56
46 57
47const QString SixenseManager::NAME = "Sixense";58const QString SixenseManager::NAME = "Sixense";
48const QString SixenseManager::HYDRA_ID_STRING = "Razer Hydra";59const QString SixenseManager::HYDRA_ID_STRING = "Razer Hydra";
@@ -89,11 +100,12 @@ void SixenseManager::activate() { · 40 unmodified lines
89 userInputMapper->registerDevice(_inputDevice);100 userInputMapper->registerDevice(_inputDevice);
90 101
91 loadSettings();102 loadSettings();
92 sixenseInit();103 _sixenseLoaded = (sixenseInit() == SIXENSE_SUCCESS);
93#endif104#endif
94}105}
95 106
96void SixenseManager::deactivate() {107void SixenseManager::deactivate() {
108 BAIL_IF_NOT_LOADED
97 InputPlugin::deactivate();109 InputPlugin::deactivate();
98 110
99#ifdef HAVE_SIXENSE111#ifdef HAVE_SIXENSE
@@ -114,12 +126,14 @@ void SixenseManager::deactivate() { · 14 unmodified lines
114}126}
115 127
116void SixenseManager::setSixenseFilter(bool filter) {128void SixenseManager::setSixenseFilter(bool filter) {
129 BAIL_IF_NOT_LOADED
117#ifdef HAVE_SIXENSE130#ifdef HAVE_SIXENSE
118 sixenseSetFilterEnabled(filter ? 1 : 0);131 sixenseSetFilterEnabled(filter ? 1 : 0);
119#endif132#endif
120}133}
121 134
122void SixenseManager::pluginUpdate(float deltaTime, bool jointsCaptured) {135void SixenseManager::pluginUpdate(float deltaTime, bool jointsCaptured) {
136 BAIL_IF_NOT_LOADED
123 _inputDevice->update(deltaTime, jointsCaptured);137 _inputDevice->update(deltaTime, jointsCaptured);
124 if (_inputDevice->_requestReset) {138 if (_inputDevice->_requestReset) {
125 _container->requestReset();139 _container->requestReset();
@@ -128,6 +142,7 @@ void SixenseManager::pluginUpdate(float deltaTime, bool jointsCaptured) { · 2 unmodified lines
128}142}
129 143
130void SixenseManager::InputDevice::update(float deltaTime, bool jointsCaptured) {144void SixenseManager::InputDevice::update(float deltaTime, bool jointsCaptured) {
145 BAIL_IF_NOT_LOADED
131#ifdef HAVE_SIXENSE146#ifdef HAVE_SIXENSE
132 _buttonPressedMap.clear();147 _buttonPressedMap.clear();
133 148
@@ -246,6 +261,7 @@ void SixenseManager::InputDevice::update(float deltaTime, bool jointsCaptured) { · 112 unmodified lines
246}261}
247 262
248void SixenseManager::InputDevice::setDebugDrawRaw(bool flag) {263void SixenseManager::InputDevice::setDebugDrawRaw(bool flag) {
264 BAIL_IF_NOT_LOADED
249 _debugDrawRaw = flag;265 _debugDrawRaw = flag;
250 if (!flag) {266 if (!flag) {
251 DebugDraw::getInstance().removeMyAvatarMarker("SIXENSE_RAW_LEFT");267 DebugDraw::getInstance().removeMyAvatarMarker("SIXENSE_RAW_LEFT");
@@ -254,6 +270,7 @@ void SixenseManager::InputDevice::setDebugDrawRaw(bool flag) { · 2 unmodified lines
254}270}
255 271
256void SixenseManager::InputDevice::setDebugDrawCalibrated(bool flag) {272void SixenseManager::InputDevice::setDebugDrawCalibrated(bool flag) {
273 BAIL_IF_NOT_LOADED
257 _debugDrawCalibrated = flag;274 _debugDrawCalibrated = flag;
258 if (!flag) {275 if (!flag) {
259 DebugDraw::getInstance().removeMyAvatarMarker("SIXENSE_CALIBRATED_LEFT");276 DebugDraw::getInstance().removeMyAvatarMarker("SIXENSE_CALIBRATED_LEFT");
@@ -281,6 +298,7 @@ static bool calibrationRequested(SixenseControllerData* controllers) { · 21 unmodified lines
281}298}
282 299
283void SixenseManager::InputDevice::updateCalibration(SixenseControllerData* controllers) {300void SixenseManager::InputDevice::updateCalibration(SixenseControllerData* controllers) {
301 BAIL_IF_NOT_LOADED
284 const SixenseControllerData* dataLeft = controllers;302 const SixenseControllerData* dataLeft = controllers;
285 const SixenseControllerData* dataRight = controllers + 1;303 const SixenseControllerData* dataRight = controllers + 1;
286 304
@@ -365,11 +383,13 @@ void SixenseManager::InputDevice::updateCalibration(SixenseControllerData* contr · 78 unmodified lines
365#endif // HAVE_SIXENSE383#endif // HAVE_SIXENSE
366 384
367void SixenseManager::InputDevice::focusOutEvent() {385void SixenseManager::InputDevice::focusOutEvent() {
386 BAIL_IF_NOT_LOADED
368 _axisStateMap.clear();387 _axisStateMap.clear();
369 _buttonPressedMap.clear();388 _buttonPressedMap.clear();
370};389};
371 390
372void SixenseManager::InputDevice::handleButtonEvent(unsigned int buttons, bool left) {391void SixenseManager::InputDevice::handleButtonEvent(unsigned int buttons, bool left) {
392 BAIL_IF_NOT_LOADED
373 using namespace controller;393 using namespace controller;
374 if (buttons & BUTTON_0) {394 if (buttons & BUTTON_0) {
375 _buttonPressedMap.insert(left ? BACK : START);395 _buttonPressedMap.insert(left ? BACK : START);
@@ -395,6 +415,7 @@ void SixenseManager::InputDevice::handleButtonEvent(unsigned int buttons, bool l · 19 unmodified lines
395}415}
396 416
397void SixenseManager::InputDevice::handlePoseEvent(float deltaTime, glm::vec3 position, glm::quat rotation, bool left) {417void SixenseManager::InputDevice::handlePoseEvent(float deltaTime, glm::vec3 position, glm::quat rotation, bool left) {
418 BAIL_IF_NOT_LOADED
398#ifdef HAVE_SIXENSE419#ifdef HAVE_SIXENSE
399 auto hand = left ? controller::StandardPoseChannel::LEFT_HAND : controller::StandardPoseChannel::RIGHT_HAND;420 auto hand = left ? controller::StandardPoseChannel::LEFT_HAND : controller::StandardPoseChannel::RIGHT_HAND;
400 421
plugins/hifiSixense/src/SixenseManager.h+2−0
@@ -98,6 +98,8 @@ private: · 97 unmodified lines
98 98
99 static const QString NAME;99 static const QString NAME;
100 static const QString HYDRA_ID_STRING;100 static const QString HYDRA_ID_STRING;
101
102 static bool _sixenseLoaded;
101};103};
102 104
103#endif // hifi_SixenseManager_h105#endif // hifi_SixenseManager_h
plugins/hifiSixense/src/SixenseSupportOSX.cpp+3−0
@@ -63,6 +63,9 @@ void unloadSixense() { · 62 unmodified lines
63// sixense.h wrapper for OSX dynamic linking63// sixense.h wrapper for OSX dynamic linking
64int sixenseInit() {64int sixenseInit() {
65 loadSixense();65 loadSixense();
66 if (!SIXENSE || !SIXENSE->isLoaded()) {
67 return SIXENSE_FAILURE;
68 }
66 return FORWARD();69 return FORWARD();
67}70}
68int sixenseExit() {71int sixenseExit() {
plugins/oculusLegacy/CMakeLists.txt+1−2
@@ -6,8 +6,7 @@ · 5 unmodified lines
6# See the accompanying file LICENSE or http:#www.apache.org/licenses/LICENSE-2.0.html6# See the accompanying file LICENSE or http:#www.apache.org/licenses/LICENSE-2.0.html
7#7#
8 8
9#if (NOT WIN32)9if (NOT WIN32)
10if (FALSE)
11 10
12 set(TARGET_NAME oculusLegacy)11 set(TARGET_NAME oculusLegacy)
13 setup_hifi_plugin()12 setup_hifi_plugin()
plugins/oculusLegacy/src/OculusLegacyDisplayPlugin.cpp+60−91
@@ -26,7 +26,7 @@ · 25 unmodified lines
26 26
27using namespace oglplus;27using namespace oglplus;
28 28
29const QString OculusLegacyDisplayPlugin::NAME("Oculus Rift (0.5)");29const QString OculusLegacyDisplayPlugin::NAME("Oculus Rift (0.5) (Simulated)");
30 30
31const QString & OculusLegacyDisplayPlugin::getName() const {31const QString & OculusLegacyDisplayPlugin::getName() const {
32 return NAME;32 return NAME;
@@ -39,12 +39,6 @@ uvec2 OculusLegacyDisplayPlugin::getRecommendedRenderSize() const { · 6 unmodified lines
39 return _desiredFramebufferSize;39 return _desiredFramebufferSize;
40}40}
41 41
42void OculusLegacyDisplayPlugin::preRender() {
43 ovrHmd_GetEyePoses(_hmd, _frameIndex, _eyeOffsets, _eyePoses, &_trackingState);
44 ovrHmd_BeginFrame(_hmd, _frameIndex);
45 WindowOpenGLDisplayPlugin::preRender();
46}
47
48glm::mat4 OculusLegacyDisplayPlugin::getProjection(Eye eye, const glm::mat4& baseProjection) const {42glm::mat4 OculusLegacyDisplayPlugin::getProjection(Eye eye, const glm::mat4& baseProjection) const {
49 return _eyeProjections[eye];43 return _eyeProjections[eye];
50}44}
@@ -57,13 +51,18 @@ glm::mat4 OculusLegacyDisplayPlugin::getEyeToHeadTransform(Eye eye) const { · 6 unmodified lines
57 return toGlm(_eyePoses[eye]);51 return toGlm(_eyePoses[eye]);
58}52}
59 53
60// Should NOT be used for rendering as this will mess up timewarp. Use the getModelview() method above for54
61// any use of head poses for rendering, ensuring you use the correct eye55glm::mat4 OculusLegacyDisplayPlugin::getHeadPose(uint32_t frameIndex) const {
62glm::mat4 OculusLegacyDisplayPlugin::getHeadPose() const {56 static uint32_t lastFrameSeen = 0;
57 if (frameIndex > lastFrameSeen) {
58 Lock lock(_mutex);
59 _trackingState = ovrHmd_GetTrackingState(_hmd, ovr_GetTimeInSeconds());
60 ovrHmd_GetEyePoses(_hmd, frameIndex, _eyeOffsets, _eyePoses, &_trackingState);
61 lastFrameSeen = frameIndex;
62 }
63 return toGlm(_trackingState.HeadPose.ThePose);63 return toGlm(_trackingState.HeadPose.ThePose);
64}64}
65 65
66
67bool OculusLegacyDisplayPlugin::isSupported() const {66bool OculusLegacyDisplayPlugin::isSupported() const {
68 if (!ovr_Initialize(nullptr)) {67 if (!ovr_Initialize(nullptr)) {
69 return false;68 return false;
@@ -92,10 +91,13 @@ bool OculusLegacyDisplayPlugin::isSupported() const { · 22 unmodified lines
92}91}
93 92
94void OculusLegacyDisplayPlugin::activate() {93void OculusLegacyDisplayPlugin::activate() {
94 WindowOpenGLDisplayPlugin::activate();
95
95 if (!(ovr_Initialize(nullptr))) {96 if (!(ovr_Initialize(nullptr))) {
96 Q_ASSERT(false);97 Q_ASSERT(false);
97 qFatal("Failed to Initialize SDK");98 qFatal("Failed to Initialize SDK");
98 }99 }
100
99 _hswDismissed = false;101 _hswDismissed = false;
100 _hmd = ovrHmd_Create(0);102 _hmd = ovrHmd_Create(0);
101 if (!_hmd) {103 if (!_hmd) {
@@ -107,13 +109,13 @@ void OculusLegacyDisplayPlugin::activate() { · 5 unmodified lines
107 _eyeFovs[eye] = _hmd->MaxEyeFov[eye];109 _eyeFovs[eye] = _hmd->MaxEyeFov[eye];
108 ovrEyeRenderDesc erd = _eyeRenderDescs[eye] = ovrHmd_GetRenderDesc(_hmd, eye, _eyeFovs[eye]);110 ovrEyeRenderDesc erd = _eyeRenderDescs[eye] = ovrHmd_GetRenderDesc(_hmd, eye, _eyeFovs[eye]);
109 ovrMatrix4f ovrPerspectiveProjection =111 ovrMatrix4f ovrPerspectiveProjection =
110 ovrMatrix4f_Projection(erd.Fov, DEFAULT_NEAR_CLIP, DEFAULT_FAR_CLIP, ovrProjection_RightHanded);112 ovrMatrix4f_Projection(erd.Fov, DEFAULT_NEAR_CLIP, DEFAULT_FAR_CLIP, ovrProjection_RightHanded);
111 _eyeProjections[eye] = toGlm(ovrPerspectiveProjection);113 _eyeProjections[eye] = toGlm(ovrPerspectiveProjection);
112 114
113 ovrPerspectiveProjection =115 ovrPerspectiveProjection =
114 ovrMatrix4f_Projection(erd.Fov, 0.001f, 10.0f, ovrProjection_RightHanded);116 ovrMatrix4f_Projection(erd.Fov, 0.001f, 10.0f, ovrProjection_RightHanded);
115 _compositeEyeProjections[eye] = toGlm(ovrPerspectiveProjection);117 _compositeEyeProjections[eye] = toGlm(ovrPerspectiveProjection);
116 118
117 _eyeOffsets[eye] = erd.HmdToEyeViewOffset;119 _eyeOffsets[eye] = erd.HmdToEyeViewOffset;
118 eyeSizes[eye] = toGlm(ovrHmd_GetFovTextureSize(_hmd, eye, erd.Fov, 1.0f));120 eyeSizes[eye] = toGlm(ovrHmd_GetFovTextureSize(_hmd, eye, erd.Fov, 1.0f));
119 });121 });
@@ -121,38 +123,43 @@ void OculusLegacyDisplayPlugin::activate() { · 1 unmodified line
121 combined.LeftTan = std::max(_eyeFovs[Left].LeftTan, _eyeFovs[Right].LeftTan);123 combined.LeftTan = std::max(_eyeFovs[Left].LeftTan, _eyeFovs[Right].LeftTan);
122 combined.RightTan = std::max(_eyeFovs[Left].RightTan, _eyeFovs[Right].RightTan);124 combined.RightTan = std::max(_eyeFovs[Left].RightTan, _eyeFovs[Right].RightTan);
123 ovrMatrix4f ovrPerspectiveProjection =125 ovrMatrix4f ovrPerspectiveProjection =
124 ovrMatrix4f_Projection(combined, DEFAULT_NEAR_CLIP, DEFAULT_FAR_CLIP, ovrProjection_RightHanded);126 ovrMatrix4f_Projection(combined, DEFAULT_NEAR_CLIP, DEFAULT_FAR_CLIP, ovrProjection_RightHanded);
125 _eyeProjections[Mono] = toGlm(ovrPerspectiveProjection);127 _eyeProjections[Mono] = toGlm(ovrPerspectiveProjection);
126 128
127 _desiredFramebufferSize = uvec2(129 _desiredFramebufferSize = uvec2(eyeSizes[0].x + eyeSizes[1].x,
128 eyeSizes[0].x + eyeSizes[1].x,130 std::max(eyeSizes[0].y, eyeSizes[1].y));
129 std::max(eyeSizes[0].y, eyeSizes[1].y));131
130
131 _frameIndex = 0;
132
133 if (!ovrHmd_ConfigureTracking(_hmd,132 if (!ovrHmd_ConfigureTracking(_hmd,
134 ovrTrackingCap_Orientation | ovrTrackingCap_Position | ovrTrackingCap_MagYawCorrection, 0)) {133 ovrTrackingCap_Orientation | ovrTrackingCap_Position | ovrTrackingCap_MagYawCorrection, 0)) {
135 qFatal("Could not attach to sensor device");134 qFatal("Could not attach to sensor device");
136 }135 }
136}
137 137
138 WindowOpenGLDisplayPlugin::activate();138void OculusLegacyDisplayPlugin::deactivate() {
139 WindowOpenGLDisplayPlugin::deactivate();
140 ovrHmd_Destroy(_hmd);
141 _hmd = nullptr;
142 ovr_Shutdown();
143}
139 144
140 int screen = getHmdScreen();145
141 if (screen != -1) {146// DLL based display plugins MUST initialize GLEW inside the DLL code.
142 _container->setFullscreen(qApp->screens()[screen]);147void OculusLegacyDisplayPlugin::customizeContext() {
143 }148 static std::once_flag once;
144 149 std::call_once(once, []{
145 _window->installEventFilter(this);150 glewExperimental = true;
146 _window->makeCurrent();151 glewInit();
152 glGetError();
153 });
154 WindowOpenGLDisplayPlugin::customizeContext();
155#if 0
147 ovrGLConfig config; memset(&config, 0, sizeof(ovrRenderAPIConfig));156 ovrGLConfig config; memset(&config, 0, sizeof(ovrRenderAPIConfig));
148 auto& header = config.Config.Header;157 auto& header = config.Config.Header;
149 header.API = ovrRenderAPI_OpenGL;158 header.API = ovrRenderAPI_OpenGL;
150 header.BackBufferSize = _hmd->Resolution;159 header.BackBufferSize = _hmd->Resolution;
151 header.Multisample = 1;160 header.Multisample = 1;
152 int distortionCaps = 0161 int distortionCaps = ovrDistortionCap_TimeWarp;
153 | ovrDistortionCap_TimeWarp162
154 ;
155
156 memset(_eyeTextures, 0, sizeof(ovrTexture) * 2);163 memset(_eyeTextures, 0, sizeof(ovrTexture) * 2);
157 ovr_for_each_eye([&](ovrEyeType eye) {164 ovr_for_each_eye([&](ovrEyeType eye) {
158 auto& header = _eyeTextures[eye].Header;165 auto& header = _eyeTextures[eye].Header;
@@ -164,74 +171,36 @@ void OculusLegacyDisplayPlugin::activate() { · 5 unmodified lines
164 header.RenderViewport.Pos.x = header.RenderViewport.Size.w;171 header.RenderViewport.Pos.x = header.RenderViewport.Size.w;
165 }172 }
166 });173 });
167 174
168 #ifndef NDEBUG175#ifndef NDEBUG
169 ovrBool result =176 ovrBool result =
170 #endif177#endif
171 ovrHmd_ConfigureRendering(_hmd, &config.Config, distortionCaps, _eyeFovs, _eyeRenderDescs);178 ovrHmd_ConfigureRendering(_hmd, &config.Config, distortionCaps, _eyeFovs, _eyeRenderDescs);
172 assert(result);179 assert(result);
173}180#endif
174
175void OculusLegacyDisplayPlugin::deactivate() {
176 _window->removeEventFilter(this);
177
178 WindowOpenGLDisplayPlugin::deactivate();
179 181
180 QScreen* riftScreen = nullptr;
181 if (_hmdScreen >= 0) {
182 riftScreen = qApp->screens()[_hmdScreen];
183 }
184 _container->unsetFullscreen(riftScreen);
185
186 ovrHmd_Destroy(_hmd);
187 _hmd = nullptr;
188 ovr_Shutdown();
189}
190
191// DLL based display plugins MUST initialize GLEW inside the DLL code.
192void OculusLegacyDisplayPlugin::customizeContext() {
193 glewExperimental = true;
194 glewInit();
195 glGetError();
196 WindowOpenGLDisplayPlugin::customizeContext();
197}182}
198 183
199void OculusLegacyDisplayPlugin::preDisplay() {184#if 0
200 _window->makeCurrent();185void OculusLegacyDisplayPlugin::uncustomizeContext() {
186 WindowOpenGLDisplayPlugin::uncustomizeContext();
201}187}
202 188
203void OculusLegacyDisplayPlugin::display(GLuint finalTexture, const glm::uvec2& sceneSize) {189void OculusLegacyDisplayPlugin::internalPresent() {
204 ++_frameIndex;190 ovrHmd_BeginFrame(_hmd, 0);
205 ovr_for_each_eye([&](ovrEyeType eye) {191 ovr_for_each_eye([&](ovrEyeType eye) {
206 reinterpret_cast<ovrGLTexture&>(_eyeTextures[eye]).OGL.TexId = finalTexture;192 reinterpret_cast<ovrGLTexture&>(_eyeTextures[eye]).OGL.TexId = _currentSceneTexture;
207 });193 });
208 ovrHmd_EndFrame(_hmd, _eyePoses, _eyeTextures);194 ovrHmd_EndFrame(_hmd, _eyePoses, _eyeTextures);
209}195}
210 196
211// Pass input events on to the application197#endif
212bool OculusLegacyDisplayPlugin::eventFilter(QObject* receiver, QEvent* event) {
213 if (!_hswDismissed && (event->type() == QEvent::KeyPress)) {
214 static ovrHSWDisplayState hswState;
215 ovrHmd_GetHSWDisplayState(_hmd, &hswState);
216 if (hswState.Displayed) {
217 ovrHmd_DismissHSWDisplay(_hmd);
218 } else {
219 _hswDismissed = true;
220 }
221 }
222 return WindowOpenGLDisplayPlugin::eventFilter(receiver, event);
223}
224
225// FIXME mirroring tot he main window is diffucult on OSX because it requires that we
226// trigger a swap, which causes the client to wait for the v-sync of the main screen running
227// at 60 Hz. This would introduce judder. Perhaps we can push mirroring to a separate
228// thread
229// FIXME If we move to the 'batch rendering on a different thread' we can possibly do this.
230// however, we need to make sure it doesn't block the event handling.
231void OculusLegacyDisplayPlugin::finishFrame() {
232 _window->doneCurrent();
233};
234 198
235int OculusLegacyDisplayPlugin::getHmdScreen() const {199int OculusLegacyDisplayPlugin::getHmdScreen() const {
236 return _hmdScreen;200 return _hmdScreen;
237}201}
202
203float OculusLegacyDisplayPlugin::getTargetFrameRate() {
204 return TARGET_RATE_OculusLegacy;
205}
206
plugins/oculusLegacy/src/OculusLegacyDisplayPlugin.h+13−15
@@ -24,11 +24,8 @@ public: · 23 unmodified lines
24 virtual void activate() override;24 virtual void activate() override;
25 virtual void deactivate() override;25 virtual void deactivate() override;
26 26
27 virtual bool eventFilter(QObject* receiver, QEvent* event) override;
28 virtual int getHmdScreen() const override;27 virtual int getHmdScreen() const override;
29 28
30 virtual float getTargetFrameRate() override { return TARGET_RATE_OculusLegacy; }
31
32 // Stereo specific methods29 // Stereo specific methods
33 virtual bool isHmd() const override { return true; }30 virtual bool isHmd() const override { return true; }
34 virtual glm::mat4 getProjection(Eye eye, const glm::mat4& baseProjection) const override;31 virtual glm::mat4 getProjection(Eye eye, const glm::mat4& baseProjection) const override;
@@ -36,31 +33,32 @@ public: · 1 unmodified line
36 virtual glm::uvec2 getRecommendedUiSize() const override { return uvec2(1920, 1080); }33 virtual glm::uvec2 getRecommendedUiSize() const override { return uvec2(1920, 1080); }
37 virtual void resetSensors() override;34 virtual void resetSensors() override;
38 virtual glm::mat4 getEyeToHeadTransform(Eye eye) const override;35 virtual glm::mat4 getEyeToHeadTransform(Eye eye) const override;
39 virtual glm::mat4 getHeadPose() const override;36 virtual glm::mat4 getHeadPose(uint32_t frameIndex) const override;
37
38 virtual float getTargetFrameRate() override;
40 39
41protected:40protected:
42 virtual void customizeContext() override;41 virtual void customizeContext() override;
43 virtual void preRender() override;42#if 0
44 virtual void preDisplay() override;43 virtual void uncustomizeContext() override;
45 virtual void display(GLuint finalTexture, const glm::uvec2& sceneSize) override;44 virtual void internalPresent() override;
46 // Do not perform swap in finish45#endif
47 virtual void finishFrame() override;46
48
49private:47private:
50 static const QString NAME;48 static const QString NAME;
51 49
52 ovrHmd _hmd;50 ovrHmd _hmd;
53 ovrTrackingState _trackingState;51 mutable ovrTrackingState _trackingState;
54 ovrEyeRenderDesc _eyeRenderDescs[2];52 ovrEyeRenderDesc _eyeRenderDescs[2];
55 ovrPosef _eyePoses[2];53 mutable ovrPosef _eyePoses[2];
56 ovrVector3f _eyeOffsets[2];54 ovrVector3f _eyeOffsets[2];
57 ovrFovPort _eyeFovs[2];55 ovrFovPort _eyeFovs[2];
58 mat4 _eyeProjections[3];56 mat4 _eyeProjections[3];
59 mat4 _compositeEyeProjections[2];57 mat4 _compositeEyeProjections[2];
60 uvec2 _desiredFramebufferSize;58 uvec2 _desiredFramebufferSize;
61 ovrTexture _eyeTextures[2];59 //ovrTexture _eyeTextures[2]; // FIXME - not currently in use
62 mutable int _hmdScreen{ -1 };60 mutable int _hmdScreen { -1 };
63 bool _hswDismissed{ false };61 bool _hswDismissed { false };
64};62};
65 63
66 64
tests/gpu-test/src/unlit.slf+1−1
@@ -22,7 +22,7 @@ in vec3 _color; · 21 unmodified lines
22void main(void) {22void main(void) {
23 packDeferredFragment(23 packDeferredFragment(
24 normalize(_normal.xyz), 24 normalize(_normal.xyz),
25 glowIntensity,25 1.0,
26 _color.rgb,26 _color.rgb,
27 DEFAULT_SPECULAR, DEFAULT_SHININESS);27 DEFAULT_SPECULAR, DEFAULT_SHININESS);
28}28}
unpublishedScripts/hiddenEntityReset.js+122−1
@@ -24,6 +24,7 @@ · 23 unmodified lines
24 var lightsScriptURL = Script.resolvePath("../examples/toybox/lights/lightSwitch.js");24 var lightsScriptURL = Script.resolvePath("../examples/toybox/lights/lightSwitch.js");
25 var targetsScriptURL = Script.resolvePath('../examples/toybox/ping_pong_gun/wallTarget.js');25 var targetsScriptURL = Script.resolvePath('../examples/toybox/ping_pong_gun/wallTarget.js');
26 var bowScriptURL = Script.resolvePath('../examples/toybox/bow/bow.js');26 var bowScriptURL = Script.resolvePath('../examples/toybox/bow/bow.js');
27 var raveStickEntityScriptURL = Script.resolvePath("../examples/flowArts/raveStick/raveStickEntityScript.js");
27 var basketballResetterScriptURL = Script.resolvePath('basketballsResetter.js');28 var basketballResetterScriptURL = Script.resolvePath('basketballsResetter.js');
28 var targetsResetterScriptURL = Script.resolvePath('targetsResetter.js');29 var targetsResetterScriptURL = Script.resolvePath('targetsResetter.js');
29 30
@@ -106,6 +107,13 @@ · 76 unmodified lines
106 z: 505.78107 z: 505.78
107 });108 });
108 109
110 createRaveStick({
111 x: 547.4,
112 y: 495.4,
113 z: 504.5
114 });
115
116
109 createCombinedArmChair({117 createCombinedArmChair({
110 x: 549.29,118 x: 549.29,
111 y: 494.9,119 y: 494.9,
@@ -160,6 +168,111 @@ · 48 unmodified lines
160 });168 });
161 }169 }
162 170
171 function createRaveStick(position) {
172 var modelURL = "https://s3.amazonaws.com/hifi-public/eric/models/rave/raveStick.fbx";
173 var stick = Entities.addEntity({
174 type: "Model",
175 name: "raveStick",
176 modelURL: modelURL,
177 position: position,
178 shapeType: 'box',
179 collisionsWillMove: true,
180 script: raveStickEntityScriptURL,
181 dimensions: {
182 x: 0.06,
183 y: 0.06,
184 z: 0.31
185 },
186 gravity: {
187 x: 0,
188 y: -3,
189 z: 0
190 },
191 userData: JSON.stringify({
192 resetMe: {
193 resetMe: true
194 },
195 grabbableKey: {
196 spatialKey: {
197 relativePosition: {
198 x: 0,
199 y: 0,
200 z: -0.1
201 },
202 relativeRotation: Quat.fromPitchYawRollDegrees(90, 90, 0)
203 },
204 invertSolidWhileHeld: true
205 }
206 })
207 });
208 var rotation = Quat.fromPitchYawRollDegrees(0, 0, 0)
209 var forwardVec = Quat.getFront(Quat.multiply(rotation, Quat.fromPitchYawRollDegrees(-90, 0, 0)));
210 forwardVec = Vec3.normalize(forwardVec);
211 var forwardQuat = orientationOf(forwardVec);
212 position = Vec3.sum(position, Vec3.multiply(Quat.getFront(rotation), 0.1));
213 position.z += 0.1;
214 position.x += -0.035;
215 var color = {
216 red: 0,
217 green: 200,
218 blue: 40
219 };
220 var props = {
221 type: "ParticleEffect",
222 position: position,
223 parentID: stick,
224 isEmitting: true,
225 name: "raveBeam",
226 colorStart: color,
227 colorSpread: {
228 red: 200,
229 green: 10,
230 blue: 10
231 },
232 color: {
233 red: 200,
234 green: 200,
235 blue: 255
236 },
237 colorFinish: color,
238 maxParticles: 100000,
239 lifespan: 1,
240 emitRate: 1000,
241 emitOrientation: forwardQuat,
242 emitSpeed: 0.2,
243 speedSpread: 0.0,
244 polarStart: 0,
245 polarFinish: 0.0,
246 azimuthStart: 0.1,
247 azimuthFinish: 0.01,
248 emitAcceleration: {
249 x: 0,
250 y: 0,
251 z: 0
252 },
253 accelerationSpread: {
254 x: 0.00,
255 y: 0.00,
256 z: 0.00
257 },
258 radiusStart: 0.03,
259 radiusFinish: 0.025,
260 alpha: 0.7,
261 alphaSpread:0.1,
262 alphaStart: 0.5,
263 alphaFinish: 0.5,
264 textures: "https://s3.amazonaws.com/hifi-public/eric/textures/particleSprites/beamParticle.png",
265 emitterShouldTrail: false,
266 userData: JSON.stringify({
267 resetMe: {
268 resetMe: true
269 }
270 })
271 }
272 var beam = Entities.addEntity(props);
273
274 }
275
163 function createGun(position) {276 function createGun(position) {
164 var modelURL = "https://s3.amazonaws.com/hifi-public/eric/models/gun.fbx";277 var modelURL = "https://s3.amazonaws.com/hifi-public/eric/models/gun.fbx";
165 278
@@ -1012,7 +1125,7 @@ · 846 unmodified lines
1012 z: 503.391125 z: 503.39
1013 };1126 };
1014 1127
1015 var rotation = Quat.fromPitchYawRollDegrees(0, 36, 0);1128 var rotation = Quat.fromPitchYawRollDegrees(0, 0, 0);
1016 1129
1017 var pingPongGun = Entities.addEntity({1130 var pingPongGun = Entities.addEntity({
1018 type: "Model",1131 type: "Model",
@@ -1040,6 +1153,14 @@ · 21 unmodified lines
1040 resetMe: true1153 resetMe: true
1041 },1154 },
1042 grabbableKey: {1155 grabbableKey: {
1156 spatialKey: {
1157 relativePosition: {
1158 x: -0.05,
1159 y: 0,
1160 z: 0.0
1161 },
1162 relativeRotation: Quat.fromPitchYawRollDegrees(0, -90, -90)
1163 },
1043 invertSolidWhileHeld: true1164 invertSolidWhileHeld: true
1044 }1165 }
1045 1166
unpublishedScripts/masterReset.js+124−2
@@ -23,10 +23,12 @@ var wandScriptURL = Script.resolvePath("../examples/toybox/bubblewand/wand.js"); · 22 unmodified lines
23var dollScriptURL = Script.resolvePath("../examples/toybox/doll/doll.js");23var dollScriptURL = Script.resolvePath("../examples/toybox/doll/doll.js");
24var lightsScriptURL = Script.resolvePath("../examples/toybox/lights/lightSwitch.js");24var lightsScriptURL = Script.resolvePath("../examples/toybox/lights/lightSwitch.js");
25var bowScriptURL = Script.resolvePath("../examples/toybox/bow/bow.js");25var bowScriptURL = Script.resolvePath("../examples/toybox/bow/bow.js");
26var raveStickEntityScriptURL = Script.resolvePath("../examples/flowArts/raveStick/raveStickEntityScript.js");
26var targetsScriptURL = Script.resolvePath('../examples/toybox/ping_pong_gun/wallTarget.js');27var targetsScriptURL = Script.resolvePath('../examples/toybox/ping_pong_gun/wallTarget.js');
27var basketballResetterScriptURL = Script.resolvePath('basketballsResetter.js');28var basketballResetterScriptURL = Script.resolvePath('basketballsResetter.js');
28var targetsResetterScriptURL = Script.resolvePath('targetsResetter.js');29var targetsResetterScriptURL = Script.resolvePath('targetsResetter.js');
29 30
31
30MasterReset = function() {32MasterReset = function() {
31 var resetKey = "resetMe";33 var resetKey = "resetMe";
32 34
@@ -80,6 +82,12 @@ MasterReset = function() { · 47 unmodified lines
80 z: 505.7882 z: 505.78
81 });83 });
82 84
85 createRaveStick({
86 x: 547.4,
87 y: 495.4,
88 z: 504.5
89 });
90
83 91
84 92
85 createCombinedArmChair({93 createCombinedArmChair({
@@ -94,6 +102,8 @@ MasterReset = function() { · 8 unmodified lines
94 z: 504.53102 z: 504.53
95 });103 });
96 104
105
106
97 createPingPongBallGun();107 createPingPongBallGun();
98 createTargets();108 createTargets();
99 createTargetResetter();109 createTargetResetter();
@@ -137,6 +147,110 @@ MasterReset = function() { · 37 unmodified lines
137 });147 });
138 }148 }
139 149
150 function createRaveStick(position) {
151 var modelURL = "https://s3.amazonaws.com/hifi-public/eric/models/rave/raveStick.fbx";
152 var stick = Entities.addEntity({
153 type: "Model",
154 name: "raveStick",
155 modelURL: modelURL,
156 position: position,
157 shapeType: 'box',
158 collisionsWillMove: true,
159 script: raveStickEntityScriptURL,
160 dimensions: {
161 x: 0.06,
162 y: 0.06,
163 z: 0.31
164 },
165 gravity: {
166 x: 0,
167 y: -3,
168 z: 0
169 },
170 userData: JSON.stringify({
171 resetMe: {
172 resetMe: true
173 },
174 grabbableKey: {
175 spatialKey: {
176 relativePosition: {
177 x: 0,
178 y: 0,
179 z: -0.1
180 },
181 relativeRotation: Quat.fromPitchYawRollDegrees(90, 90, 0)
182 },
183 invertSolidWhileHeld: true
184 }
185 })
186 });
187 var rotation = Quat.fromPitchYawRollDegrees(0, 0, 0)
188 var forwardVec = Quat.getFront(Quat.multiply(rotation, Quat.fromPitchYawRollDegrees(-90, 0, 0)));
189 forwardVec = Vec3.normalize(forwardVec);
190 var forwardQuat = orientationOf(forwardVec);
191 position = Vec3.sum(position, Vec3.multiply(Quat.getFront(rotation), 0.1));
192 position.z += 0.1;
193 position.x += -0.035;
194 var color = {
195 red: 0,
196 green: 200,
197 blue: 40
198 };
199 var props = {
200 type: "ParticleEffect",
201 position: position,
202 parentID: stick,
203 isEmitting: true,
204 name: "raveBeam",
205 colorStart: color,
206 colorSpread: {
207 red: 200,
208 green: 10,
209 blue: 10
210 },
211 color: {
212 red: 200,
213 green: 200,
214 blue: 255
215 },
216 colorFinish: color,
217 maxParticles: 100000,
218 lifespan: 1,
219 emitRate: 1000,
220 emitOrientation: forwardQuat,
221 emitSpeed: 0.2,
222 speedSpread: 0.0,
223 polarStart: 0,
224 polarFinish: 0.0,
225 azimuthStart: 0.1,
226 azimuthFinish: 0.01,
227 emitAcceleration: {
228 x: 0,
229 y: 0,
230 z: 0
231 },
232 accelerationSpread: {
233 x: 0.00,
234 y: 0.00,
235 z: 0.00
236 },
237 radiusStart: 0.03,
238 radiusFinish: 0.025,
239 alpha: 0.7,
240 alphaSpread: 0.1,
241 alphaStart: 0.5,
242 alphaFinish: 0.5,
243 textures: "https://s3.amazonaws.com/hifi-public/eric/textures/particleSprites/beamParticle.png",
244 emitterShouldTrail: false,
245 userData: JSON.stringify({
246 resetMe: {
247 resetMe: true
248 }
249 })
250 }
251 var beam = Entities.addEntity(props);
252
253 }
140 254
141 function createGun(position) {255 function createGun(position) {
142 var modelURL = "https://s3.amazonaws.com/hifi-public/eric/models/gun.fbx";256 var modelURL = "https://s3.amazonaws.com/hifi-public/eric/models/gun.fbx";
@@ -992,7 +1106,7 @@ MasterReset = function() { · 849 unmodified lines
992 z: 503.391106 z: 503.39
993 };1107 };
994 1108
995 var rotation = Quat.fromPitchYawRollDegrees(0, 36, 0);1109 var rotation = Quat.fromPitchYawRollDegrees(0, 0, 0);
996 1110
997 var pingPongGun = Entities.addEntity({1111 var pingPongGun = Entities.addEntity({
998 type: "Model",1112 type: "Model",
@@ -1020,6 +1134,14 @@ MasterReset = function() { · 21 unmodified lines
1020 resetMe: true1134 resetMe: true
1021 },1135 },
1022 grabbableKey: {1136 grabbableKey: {
1137 spatialKey: {
1138 relativePosition: {
1139 x: -0.05,
1140 y: 0,
1141 z: 0.0
1142 },
1143 relativeRotation: Quat.fromPitchYawRollDegrees(0,-90, -90)
1144 },
1023 invertSolidWhileHeld: true1145 invertSolidWhileHeld: true
1024 }1146 }
1025 1147
@@ -1349,7 +1471,7 @@ MasterReset = function() { · 323 unmodified lines
1349 resetMe: true1471 resetMe: true
1350 },1472 },
1351 grabbableKey: {1473 grabbableKey: {
1352 invertSolidWhileHeld: true 1474 invertSolidWhileHeld: true
1353 }1475 }
1354 })1476 })
1355 });1477 });

Keyboard shortcuts

General

Show keyboard shortcuts
?
Focus the current search
/

Issues and pull requests

Open filters
f

Issues, pull requests and Inbox

Select next item
j↓
Select previous item
k↑
Open selected item
Enter
Dismiss filters or clear selection
Esc

Repository code

Go to file
t