From 0a083c070f9c00b719431da0f1d07e429b7b6587 Mon Sep 17 00:00:00 2001 From: "James B. Pollack" Date: Fri, 30 Oct 2015 20:21:53 -0700 Subject: [PATCH 01/45] color busters cooperative game --- examples/color_busters/colorBusterWand.js | 226 ++++++++++++++++++ .../color_busters/createColorBusterCubes.js | 89 +++++++ .../color_busters/createColorBusterWand.js | 55 +++++ 3 files changed, 370 insertions(+) create mode 100644 examples/color_busters/colorBusterWand.js create mode 100644 examples/color_busters/createColorBusterCubes.js create mode 100644 examples/color_busters/createColorBusterWand.js diff --git a/examples/color_busters/colorBusterWand.js b/examples/color_busters/colorBusterWand.js new file mode 100644 index 0000000000..26948da91b --- /dev/null +++ b/examples/color_busters/colorBusterWand.js @@ -0,0 +1,226 @@ +(function() { + + //seconds that the combination lasts + var COMBINED_COLOR_DURATION = 10; + + var INDICATOR_OFFSET_UP = 0.5; + + var REMOVE_CUBE_SOUND_URL = ''; + var COMBINE_COLORS_SOUND_URL = ''; + + var _this; + + function ColorWand() { + _this = this; + }; + + ColorBusterWand.prototype = { + combinedColorsTimer: null, + + preload: function(entityID) { + print("preload"); + this.entityID = entityID; + this.REMOVE_CUBE_SOUND = SoundCache.getSound(REMOVE_CUBE_SOUND_URL); + this.COMBINE_COLORS_SOUND = SoundCache.getSound(COMBINE_COLORS_SOUND_URL); + + }, + + entityCollisionWithEntity: function(me, otherEntity, collision) { + + var otherProperties = Entities.getEntityProperties(otherEntity, ["name", "userData"]); + var myProperties = Entities.getEntityProperties(otherEntity, ["userData"]); + var myUserData = JSON.parse(myProperties.userData); + var otherUserData = JSON.parse(otherProperties.userData); + + if (otherProperties.name === 'Hifi-ColorBusterWand') { + if (otherUserData.hifiColorBusterWandKey.colorLocked !== true && myUserData.hifiColorBusterWandKey.colorLocked !== true) { + if (otherUserData.hifiColorBusterWandKey.originalColorName === myUserData.hifiColorBusterWandKey.originalColorName) { + return; + } else { + this.combineColorsWithOtherWand(otherUserData.hifiColorBusterWandKey.originalColorName, myUserData.hifiColorBusterWandKey.originalColorName); + } + } + } + + if (otherProperties.name === 'Hifi-ColorBusterCube') { + if (otherUserData.hifiColorBusterCubeKey.originalColorName === myUserData.hifiColorBusterWandKey.currentColor) { + removeCubeOfSameColor(otherEntity); + } + + } + }, + + combineColorsWithOtherWand: function(otherColor, myColor) { + var newColor; + + if ((otherColor === 'red' && myColor == 'yellow') || (myColor === 'red' && otherColor === 'yellow')) { + //orange + newColor = 'orange'; + } + + if ((otherColor === 'red' && myColor == 'blue') || (myColor === 'red' && otherColor === 'blue')) { + //violet + newColor = 'violet'; + } + + if ((otherColor === 'blue' && myColor == 'yellow') || (myColor === 'blue' && otherColor === 'yellow')) { + //green. + newColor = 'green'; + } + + _this.combinedColorsTimer = Script.setTimeout(function() { + _this.resetToOriginalColor(myColor); + _this.combinedColorsTimer = null; + }, COMBINED_COLOR_DURATION * 1000); + + setEntityCustomData(hifiColorWandKey, this.entityID, { + owner: MyAvatar.sessionUUID, + currentColor: newColor + originalColorName: myColor, + colorLocked: false + }); + + _this.setCurrentColor(newColor); + + }, + + setCurrentColor: function(newColor) { + + var color; + + if (newColor === 'orange') { + color = { + red: 255, + green: 165, + blue: 0 + }; + } + + if (newColor === 'violet') { + color = { + red: 128, + green: 0, + blue: 128 + }; + } + + if (newColor === 'green') { + color = { + red: 0, + green: 255, + blue: 0 + }; + } + + if (newColor === 'red') { + color = { + red: 255, + green: 0, + blue: 0 + }; + } + + if (newColor === 'yellow') { + color = { + red: 255, + green: 255, + blue: 0 + }; + } + + if (newColor === 'blue') { + color = { + red: 0, + green: 0, + blue: 255 + }; + } + + Entities.editEntity(this.colorIndicator, { + color: color + }) + }, + + resetToOriginalColor: function(myColor) { + setEntityCustomData(hifiColorWandKey, this.entityID, { + owner: MyAvatar.sessionUUID, + currentColor: myColor + originalColorName: myColor, + colorLocked: true + }); + + this.setCurrentColor(myColor); + }, + + removeCubeOfSameColor: function(cube) { + Entities.callEntityMethod(cube, 'cubeEnding'); + Entities.deleteEntity(cube); + }, + + startNearGrab: function() { + this.currentProperties = Entities.getEntityProperties(this.entityID); + this.createColorIndicator(); + }, + + continueNearGrab: function() { + this.currentProperties = Entities.getEntityProperties(this.entityID); + this.updateColorIndicatorLocation(); + }, + + releaseGrab: function() { + this.deleteEntity(this.colorIndicator); + if (this.combinedColorsTimer !== null) { + Script.clearTimeout(this.combinedColorsTimer); + } + + }, + + createColorIndicator: function() { + var properties = { + name: 'Hifi-ColorBusterIndicator', + type: 'Box', + dimensions: COLOR_INDICATOR_DIMENSIONS, + color: this.currentProperties.position, + position: this.currentProperties.position + } + + this.colorIndicator = Entities.addEntity(properties); + }, + + updateColorIndicatorLocation: function() { + + var position; + + var upVector = Quat.getUp(this.currentProperties.rotation); + var indicatorVector = Vec3.multiply(upVector, INDICATOR_OFFSET_UP); + position = Vec3.sum(this.currentProperties.position, indicatorVector); + + var properties = { + position: position, + rotation: this.currentProperties.rotation + } + + Entities.editEntity(this.colorIndicator, properties); + }, + + + playSoundAtCurrentPosition: function(removeCubeSound) { + var position = Entities.getEntityProperties(this.entityID, "position").position; + + var audioProperties = { + volume: 0.25, + position: position + }; + + if (removeCubeSound) { + Audio.playSound(this.REMOVE_CUBE_SOUND, audioProperties); + } else { + Audio.playSound(this.COMBINE_COLORS_SOUND, audioProperties); + } + }, + + + }; + + return new ColorBusterWand(); +}); \ No newline at end of file diff --git a/examples/color_busters/createColorBusterCubes.js b/examples/color_busters/createColorBusterCubes.js new file mode 100644 index 0000000000..ad7b8b5307 --- /dev/null +++ b/examples/color_busters/createColorBusterCubes.js @@ -0,0 +1,89 @@ +var CUBE_DIMENSIONS = { + x: 1, + y: 1, + z: 1 +}; + +var NUMBER_OF_CUBES_PER_SIDE: 20; + +var STARTING_CORNER_POSITION = { + x: 0, + y: 0, + z: 0 +} + +var STARTING_COLORS = [ + ['red', { + red: 255, + green: 0, + blue: 0 + }], + ['yellow', { + red: 255, + green: 255, + blue: 0 + }], + ['blue', { + red: 0, + green: 0, + blue: 255 + }], + ['orange', { + red: 255, + green: 165, + blue: 0 + }], + ['violet', { + red: 128, + green: 0, + blue: 128 + }], + ['green', { + red: 0, + green: 255, + blue: 0 + }] +] + +function chooseStartingColor() { + var startingColor = STARTING_COLORS[Math.floor(Math.random() * STARTING_COLORS.length)]; + return startingColor +} + +function createColorBusterCube(row, column, vertical) { + + var startingColor = chooseStartingColor(); + var colorBusterCubeProperties = { + name: 'Hifi-ColorBusterWand', + type: 'Model', + url: COLOR_WAND_MODEL_URL, + dimensions: COLOR_WAND_DIMENSIONS, + position: { + x: row, + y: vertical, + z: column + } + userData: JSON.stringify({ + hifiColorBusterCubeKey: { + originalColorName: startingColor[0], + + } + }) + }; + + return Entities.addEntity(colorBusterCubeProperties); +} + +function createBoard() { + var vertical; + for (vertical = 0; vertical === NUMBER_OF_CUBES_PER_SIDE) { + var row; + var column; + //create a single layer + for (row = 0; row === NUMBER_OF_CUBES_PER_SIDE; row++) { + for (column = 0; column === NUMBER_OF_CUBES_PER_SIDE; column++) { + this.createColorBusterCube(row, column, vertical) + } + } + } +} \ No newline at end of file diff --git a/examples/color_busters/createColorBusterWand.js b/examples/color_busters/createColorBusterWand.js new file mode 100644 index 0000000000..68e6ecfee5 --- /dev/null +++ b/examples/color_busters/createColorBusterWand.js @@ -0,0 +1,55 @@ +var COLOR_WAND_MODEL_URL = ''; +var COLOR_WAND_DIMENSIONS = { + x: 0, + y: 0, + z: 0 +}; +var COLOR_WAND_START_POSITION = { + x: 0, + y: 0, + z: 0 +}; +var STARTING_COLORS = [ + ['red', { + red: 255, + green: 0, + blue: 0 + }], + ['yellow', { + red: 255, + green: 255, + blue: 0 + }], + ['blue', { + red: 0, + green: 0, + blue: 255 + }] +] + +function chooseStartingColor() { + var startingColor = STARTING_COLORS[Math.floor(Math.random() * STARTING_COLORS.length)]; + return startingColor +} + +function createColorBusterWand() { + + var startingColor = chooseStartingColor(); + var colorBusterWandProperties = { + name: 'Hifi-ColorBusterWand', + type: 'Model', + url: COLOR_WAND_MODEL_URL, + dimensions: COLOR_WAND_DIMENSIONS, + position: COLOR_WAND_START_POSITION, + userData: JSON.stringify({ + hifiColorBusterWandKey: { + owner: MyAvatar.sessionUUID, + currentColor: startingColor[1] + originalColorName: startingColor[0], + colorLocked: false + } + }) + }; + + Entities.addEntity(colorBusterWandProperties); +} \ No newline at end of file From 459b449a7fed46786541bebcd5691a8a3b8bbfbf Mon Sep 17 00:00:00 2001 From: "James B. Pollack" Date: Fri, 30 Oct 2015 20:52:19 -0700 Subject: [PATCH 02/45] rename folder --- examples/{color_busters => color_busters_game}/colorBusterWand.js | 0 .../createColorBusterCubes.js | 0 .../createColorBusterWand.js | 0 3 files changed, 0 insertions(+), 0 deletions(-) rename examples/{color_busters => color_busters_game}/colorBusterWand.js (100%) rename examples/{color_busters => color_busters_game}/createColorBusterCubes.js (100%) rename examples/{color_busters => color_busters_game}/createColorBusterWand.js (100%) diff --git a/examples/color_busters/colorBusterWand.js b/examples/color_busters_game/colorBusterWand.js similarity index 100% rename from examples/color_busters/colorBusterWand.js rename to examples/color_busters_game/colorBusterWand.js diff --git a/examples/color_busters/createColorBusterCubes.js b/examples/color_busters_game/createColorBusterCubes.js similarity index 100% rename from examples/color_busters/createColorBusterCubes.js rename to examples/color_busters_game/createColorBusterCubes.js diff --git a/examples/color_busters/createColorBusterWand.js b/examples/color_busters_game/createColorBusterWand.js similarity index 100% rename from examples/color_busters/createColorBusterWand.js rename to examples/color_busters_game/createColorBusterWand.js From e79ebdb8aa88157fd3be5233ca7fe5a9a865661a Mon Sep 17 00:00:00 2001 From: "James B. Pollack" Date: Sun, 1 Nov 2015 19:47:13 -0800 Subject: [PATCH 03/45] cleanup syntax --- examples/color_busters_game/createColorBusterCubes.js | 6 +++--- examples/color_busters_game/createColorBusterWand.js | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/color_busters_game/createColorBusterCubes.js b/examples/color_busters_game/createColorBusterCubes.js index ad7b8b5307..2bc14e5a01 100644 --- a/examples/color_busters_game/createColorBusterCubes.js +++ b/examples/color_busters_game/createColorBusterCubes.js @@ -4,7 +4,7 @@ var CUBE_DIMENSIONS = { z: 1 }; -var NUMBER_OF_CUBES_PER_SIDE: 20; +var NUMBER_OF_CUBES_PER_SIDE= 20; var STARTING_CORNER_POSITION = { x: 0, @@ -62,7 +62,7 @@ function createColorBusterCube(row, column, vertical) { x: row, y: vertical, z: column - } + }, userData: JSON.stringify({ hifiColorBusterCubeKey: { originalColorName: startingColor[0], @@ -76,7 +76,7 @@ function createColorBusterCube(row, column, vertical) { function createBoard() { var vertical; - for (vertical = 0; vertical === NUMBER_OF_CUBES_PER_SIDE) { + for (vertical = 0; vertical === NUMBER_OF_CUBES_PER_SIDE;vertical++) { var row; var column; //create a single layer diff --git a/examples/color_busters_game/createColorBusterWand.js b/examples/color_busters_game/createColorBusterWand.js index 68e6ecfee5..4af5306177 100644 --- a/examples/color_busters_game/createColorBusterWand.js +++ b/examples/color_busters_game/createColorBusterWand.js @@ -44,7 +44,7 @@ function createColorBusterWand() { userData: JSON.stringify({ hifiColorBusterWandKey: { owner: MyAvatar.sessionUUID, - currentColor: startingColor[1] + currentColor: startingColor[1], originalColorName: startingColor[0], colorLocked: false } From 15af28337b8494b6e0f8890431c8a8b0f1c545bf Mon Sep 17 00:00:00 2001 From: "James B. Pollack" Date: Mon, 2 Nov 2015 16:02:30 -0800 Subject: [PATCH 04/45] add color busters game for testing --- .../createColorBusterCubes.js | 89 ------------ .../createColorBusterWand.js | 55 -------- .../games/color_busters}/colorBusterWand.js | 101 +++++++++----- .../color_busters/createColorBusterCubes.js | 130 ++++++++++++++++++ .../color_busters/createColorBusterWand.js | 99 +++++++++++++ 5 files changed, 299 insertions(+), 175 deletions(-) delete mode 100644 examples/color_busters_game/createColorBusterCubes.js delete mode 100644 examples/color_busters_game/createColorBusterWand.js rename examples/{color_busters_game => example/games/color_busters}/colorBusterWand.js (69%) create mode 100644 examples/example/games/color_busters/createColorBusterCubes.js create mode 100644 examples/example/games/color_busters/createColorBusterWand.js diff --git a/examples/color_busters_game/createColorBusterCubes.js b/examples/color_busters_game/createColorBusterCubes.js deleted file mode 100644 index 2bc14e5a01..0000000000 --- a/examples/color_busters_game/createColorBusterCubes.js +++ /dev/null @@ -1,89 +0,0 @@ -var CUBE_DIMENSIONS = { - x: 1, - y: 1, - z: 1 -}; - -var NUMBER_OF_CUBES_PER_SIDE= 20; - -var STARTING_CORNER_POSITION = { - x: 0, - y: 0, - z: 0 -} - -var STARTING_COLORS = [ - ['red', { - red: 255, - green: 0, - blue: 0 - }], - ['yellow', { - red: 255, - green: 255, - blue: 0 - }], - ['blue', { - red: 0, - green: 0, - blue: 255 - }], - ['orange', { - red: 255, - green: 165, - blue: 0 - }], - ['violet', { - red: 128, - green: 0, - blue: 128 - }], - ['green', { - red: 0, - green: 255, - blue: 0 - }] -] - -function chooseStartingColor() { - var startingColor = STARTING_COLORS[Math.floor(Math.random() * STARTING_COLORS.length)]; - return startingColor -} - -function createColorBusterCube(row, column, vertical) { - - var startingColor = chooseStartingColor(); - var colorBusterCubeProperties = { - name: 'Hifi-ColorBusterWand', - type: 'Model', - url: COLOR_WAND_MODEL_URL, - dimensions: COLOR_WAND_DIMENSIONS, - position: { - x: row, - y: vertical, - z: column - }, - userData: JSON.stringify({ - hifiColorBusterCubeKey: { - originalColorName: startingColor[0], - - } - }) - }; - - return Entities.addEntity(colorBusterCubeProperties); -} - -function createBoard() { - var vertical; - for (vertical = 0; vertical === NUMBER_OF_CUBES_PER_SIDE;vertical++) { - var row; - var column; - //create a single layer - for (row = 0; row === NUMBER_OF_CUBES_PER_SIDE; row++) { - for (column = 0; column === NUMBER_OF_CUBES_PER_SIDE; column++) { - this.createColorBusterCube(row, column, vertical) - } - } - } -} \ No newline at end of file diff --git a/examples/color_busters_game/createColorBusterWand.js b/examples/color_busters_game/createColorBusterWand.js deleted file mode 100644 index 4af5306177..0000000000 --- a/examples/color_busters_game/createColorBusterWand.js +++ /dev/null @@ -1,55 +0,0 @@ -var COLOR_WAND_MODEL_URL = ''; -var COLOR_WAND_DIMENSIONS = { - x: 0, - y: 0, - z: 0 -}; -var COLOR_WAND_START_POSITION = { - x: 0, - y: 0, - z: 0 -}; -var STARTING_COLORS = [ - ['red', { - red: 255, - green: 0, - blue: 0 - }], - ['yellow', { - red: 255, - green: 255, - blue: 0 - }], - ['blue', { - red: 0, - green: 0, - blue: 255 - }] -] - -function chooseStartingColor() { - var startingColor = STARTING_COLORS[Math.floor(Math.random() * STARTING_COLORS.length)]; - return startingColor -} - -function createColorBusterWand() { - - var startingColor = chooseStartingColor(); - var colorBusterWandProperties = { - name: 'Hifi-ColorBusterWand', - type: 'Model', - url: COLOR_WAND_MODEL_URL, - dimensions: COLOR_WAND_DIMENSIONS, - position: COLOR_WAND_START_POSITION, - userData: JSON.stringify({ - hifiColorBusterWandKey: { - owner: MyAvatar.sessionUUID, - currentColor: startingColor[1], - originalColorName: startingColor[0], - colorLocked: false - } - }) - }; - - Entities.addEntity(colorBusterWandProperties); -} \ No newline at end of file diff --git a/examples/color_busters_game/colorBusterWand.js b/examples/example/games/color_busters/colorBusterWand.js similarity index 69% rename from examples/color_busters_game/colorBusterWand.js rename to examples/example/games/color_busters/colorBusterWand.js index 26948da91b..6080d6f345 100644 --- a/examples/color_busters_game/colorBusterWand.js +++ b/examples/example/games/color_busters/colorBusterWand.js @@ -1,42 +1,63 @@ +// +// colorBusterWand.js +// +// Created by James B. Pollack @imgntn on 11/2/2015 +// Copyright 2015 High Fidelity, Inc. +// +// This is the entity script that attaches to a wand for the Color Busters game +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + + + (function() { + Script.include("../../../libraries/utils.js"); - //seconds that the combination lasts - var COMBINED_COLOR_DURATION = 10; + var COMBINED_COLOR_DURATION = 5; - var INDICATOR_OFFSET_UP = 0.5; + var INDICATOR_OFFSET_UP = 0.40; - var REMOVE_CUBE_SOUND_URL = ''; - var COMBINE_COLORS_SOUND_URL = ''; + var REMOVE_CUBE_SOUND_URL = 'http://hifi-public.s3.amazonaws.com/sounds/color_busters/boop.wav'; + var COMBINE_COLORS_SOUND_URL = 'http://hifi-public.s3.amazonaws.com/sounds/color_busters/powerup.wav'; + + var COLOR_INDICATOR_DIMENSIONS = { + x: 0.10, + y: 0.10, + z: 0.10 + }; var _this; - function ColorWand() { + function ColorBusterWand() { _this = this; - }; + } ColorBusterWand.prototype = { combinedColorsTimer: null, - + soundIsPlaying: false, preload: function(entityID) { print("preload"); this.entityID = entityID; this.REMOVE_CUBE_SOUND = SoundCache.getSound(REMOVE_CUBE_SOUND_URL); this.COMBINE_COLORS_SOUND = SoundCache.getSound(COMBINE_COLORS_SOUND_URL); - }, - entityCollisionWithEntity: function(me, otherEntity, collision) { - + collisionWithEntity: function(me, otherEntity, collision) { var otherProperties = Entities.getEntityProperties(otherEntity, ["name", "userData"]); - var myProperties = Entities.getEntityProperties(otherEntity, ["userData"]); + var myProperties = Entities.getEntityProperties(me, ["userData"]); var myUserData = JSON.parse(myProperties.userData); var otherUserData = JSON.parse(otherProperties.userData); if (otherProperties.name === 'Hifi-ColorBusterWand') { + print('HIT ANOTHER COLOR WAND!!'); if (otherUserData.hifiColorBusterWandKey.colorLocked !== true && myUserData.hifiColorBusterWandKey.colorLocked !== true) { if (otherUserData.hifiColorBusterWandKey.originalColorName === myUserData.hifiColorBusterWandKey.originalColorName) { + print('BUT ITS THE SAME COLOR!') return; } else { + print('COMBINE COLORS!' + this.entityID); this.combineColorsWithOtherWand(otherUserData.hifiColorBusterWandKey.originalColorName, myUserData.hifiColorBusterWandKey.originalColorName); } } @@ -44,15 +65,23 @@ if (otherProperties.name === 'Hifi-ColorBusterCube') { if (otherUserData.hifiColorBusterCubeKey.originalColorName === myUserData.hifiColorBusterWandKey.currentColor) { - removeCubeOfSameColor(otherEntity); + print('HIT THE SAME COLOR CUBE'); + this.removeCubeOfSameColor(otherEntity); + } else { + print('HIT A CUBE OF A DIFFERENT COLOR'); } - } }, combineColorsWithOtherWand: function(otherColor, myColor) { - var newColor; + print('combining my :' + myColor + " with their: " + otherColor); + if ((myColor === 'violet') || (myColor === 'orange') || (myColor === 'green')) { + print('MY WAND ALREADY COMBINED'); + return; + } + + var newColor; if ((otherColor === 'red' && myColor == 'yellow') || (myColor === 'red' && otherColor === 'yellow')) { //orange newColor = 'orange'; @@ -73,19 +102,18 @@ _this.combinedColorsTimer = null; }, COMBINED_COLOR_DURATION * 1000); - setEntityCustomData(hifiColorWandKey, this.entityID, { + setEntityCustomData('hifiColorBusterWandKey', this.entityID, { owner: MyAvatar.sessionUUID, - currentColor: newColor + currentColor: newColor, originalColorName: myColor, colorLocked: false }); - _this.setCurrentColor(newColor); + this.playSoundAtCurrentPosition(false); }, setCurrentColor: function(newColor) { - var color; if (newColor === 'orange') { @@ -138,23 +166,27 @@ Entities.editEntity(this.colorIndicator, { color: color - }) + }); + + // print('SET THIS COLOR INDICATOR TO:' + newColor); }, resetToOriginalColor: function(myColor) { - setEntityCustomData(hifiColorWandKey, this.entityID, { + setEntityCustomData('hifiColorBusterWandKey', this.entityID, { owner: MyAvatar.sessionUUID, - currentColor: myColor + currentColor: myColor, originalColorName: myColor, - colorLocked: true + colorLocked: false }); this.setCurrentColor(myColor); }, removeCubeOfSameColor: function(cube) { + this.playSoundAtCurrentPosition(true); Entities.callEntityMethod(cube, 'cubeEnding'); Entities.deleteEntity(cube); + }, startNearGrab: function() { @@ -164,24 +196,31 @@ continueNearGrab: function() { this.currentProperties = Entities.getEntityProperties(this.entityID); + + var color = JSON.parse(this.currentProperties.userData).hifiColorBusterWandKey.currentColor; + + this.setCurrentColor(color); this.updateColorIndicatorLocation(); }, releaseGrab: function() { - this.deleteEntity(this.colorIndicator); + Entities.deleteEntity(this.colorIndicator); if (this.combinedColorsTimer !== null) { Script.clearTimeout(this.combinedColorsTimer); } }, - createColorIndicator: function() { + createColorIndicator: function(color) { + + var properties = { name: 'Hifi-ColorBusterIndicator', type: 'Box', dimensions: COLOR_INDICATOR_DIMENSIONS, - color: this.currentProperties.position, - position: this.currentProperties.position + position: this.currentProperties.position, + collisionsWillMove: false, + ignoreForCollisions: true } this.colorIndicator = Entities.addEntity(properties); @@ -204,15 +243,15 @@ }, - playSoundAtCurrentPosition: function(removeCubeSound) { - var position = Entities.getEntityProperties(this.entityID, "position").position; + playSoundAtCurrentPosition: function(isRemoveCubeSound) { + var position = Entities.getEntityProperties(this.entityID, "position").position; var audioProperties = { - volume: 0.25, + volume: 0.5, position: position }; - if (removeCubeSound) { + if (isRemoveCubeSound === true) { Audio.playSound(this.REMOVE_CUBE_SOUND, audioProperties); } else { Audio.playSound(this.COMBINE_COLORS_SOUND, audioProperties); diff --git a/examples/example/games/color_busters/createColorBusterCubes.js b/examples/example/games/color_busters/createColorBusterCubes.js new file mode 100644 index 0000000000..1b7aac51a5 --- /dev/null +++ b/examples/example/games/color_busters/createColorBusterCubes.js @@ -0,0 +1,130 @@ +// +// createColorBusterCubes.js +// +// Created by James B. Pollack @imgntn on 11/2/2015 +// Copyright 2015 High Fidelity, Inc. +// +// This script creates cubes that can be removed with a Color Buster wand. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + + +var DELETE_AT_ENDING = true; + +var CUBE_DIMENSIONS = { + x: 1, + y: 1, + z: 1 +}; + +var NUMBER_OF_CUBES_PER_SIDE = 5; + +var STARTING_CORNER_POSITION = { + x: 100, + y: 100, + z: 100 +}; +var STARTING_COLORS = [ + ['red', { + red: 255, + green: 0, + blue: 0 + }], + ['yellow', { + red: 255, + green: 255, + blue: 0 + }], + ['blue', { + red: 0, + green: 0, + blue: 255 + }], + ['orange', { + red: 255, + green: 165, + blue: 0 + }], + ['violet', { + red: 128, + green: 0, + blue: 128 + }], + ['green', { + red: 0, + green: 255, + blue: 0 + }] +]; + +function chooseStartingColor() { + var startingColor = STARTING_COLORS[Math.floor(Math.random() * STARTING_COLORS.length)]; + return startingColor; +} + +var cubes = []; + +function createColorBusterCube(row, column, vertical) { + + print('make cube at ' + row + ':' + column + ":" + vertical); + + var position = { + x: STARTING_CORNER_POSITION.x + row, + y: STARTING_CORNER_POSITION.y + vertical, + z: STARTING_CORNER_POSITION.z + column + }; + + var startingColor = chooseStartingColor(); + var colorBusterCubeProperties = { + name: 'Hifi-ColorBusterCube', + type: 'Box', + dimensions: CUBE_DIMENSIONS, + collisionsWillMove: false, + ignoreForCollisions: false, + color: startingColor[1], + position: position, + userData: JSON.stringify({ + hifiColorBusterCubeKey: { + originalColorName: startingColor[0] + }, + grabbableKey: { + grabbable: false + } + }) + }; + var cube = Entities.addEntity(colorBusterCubeProperties); + cubes.push(cube); + return cube +} + +function createBoard() { + var vertical; + var row; + var column; + for (vertical = 0; vertical < NUMBER_OF_CUBES_PER_SIDE; vertical++) { + print('vertical:' + vertical) + //create a single layer + for (row = 0; row < NUMBER_OF_CUBES_PER_SIDE; row++) { + print('row:' + row) + for (column = 0; column < NUMBER_OF_CUBES_PER_SIDE; column++) { + print('column:' + column) + createColorBusterCube(row, column, vertical) + } + } + } +} + +function deleteCubes() { + while (cubes.length > 0) { + Entities.deleteEntity(cubes.pop()); + } +} + +if (DELETE_AT_ENDING === true) { + Script.scriptEnding.connect(deleteCubes); + +} + +createBoard(); \ No newline at end of file diff --git a/examples/example/games/color_busters/createColorBusterWand.js b/examples/example/games/color_busters/createColorBusterWand.js new file mode 100644 index 0000000000..a08f529aa8 --- /dev/null +++ b/examples/example/games/color_busters/createColorBusterWand.js @@ -0,0 +1,99 @@ +// +// createColorBusterWand.js +// +// Created by James B. Pollack @imgntn on 11/2/2015 +// Copyright 2015 High Fidelity, Inc. +// +// This script creates a wand that can be used to remove color buster blocks. Touch your wand to someone else's to combine colors. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +var DELETE_AT_ENDING = false; + +var COLOR_WAND_MODEL_URL = 'http://hifi-public.s3.amazonaws.com/models/color_busters/wand.fbx'; +var COLOR_WAND_COLLISION_HULL_URL = 'http://hifi-public.s3.amazonaws.com/models/color_busters/wand_collision_hull.obj'; +var COLOR_WAND_SCRIPT_URL = Script.resolvePath('colorBusterWand.js'); + +var COLOR_WAND_DIMENSIONS = { + x: 0.04, + y: 0.87, + z: 0.04 +}; + +var COLOR_WAND_START_POSITION = { + x: 0, + y: 0, + z: 0 +}; + +var STARTING_COLORS = [ + ['red', { + red: 255, + green: 0, + blue: 0 + }], + ['yellow', { + red: 255, + green: 255, + blue: 0 + }], + ['blue', { + red: 0, + green: 0, + blue: 255 + }] +]; + +var center = Vec3.sum(Vec3.sum(MyAvatar.position, { + x: 0, + y: 0.5, + z: 0 +}), Vec3.multiply(0.5, Quat.getFront(Camera.getOrientation()))); + + +function chooseStartingColor() { + var startingColor = STARTING_COLORS[Math.floor(Math.random() * STARTING_COLORS.length)]; + return startingColor +} + +var wand; + +function createColorBusterWand() { + var startingColor = chooseStartingColor(); + var colorBusterWandProperties = { + name: 'Hifi-ColorBusterWand', + type: 'Model', + modelURL: COLOR_WAND_MODEL_URL, + shapeType: 'compound', + compoundShapeURL: COLOR_WAND_COLLISION_HULL_URL, + dimensions: COLOR_WAND_DIMENSIONS, + position: center, + script: COLOR_WAND_SCRIPT_URL, + collisionsWillMove: true, + userData: JSON.stringify({ + hifiColorBusterWandKey: { + owner: MyAvatar.sessionUUID, + currentColor: startingColor[0], + originalColorName: startingColor[0], + colorLocked: false + }, + grabbableKey: { + invertSolidWhileHeld: false + } + }) + }; + + wand = Entities.addEntity(colorBusterWandProperties); +} + +function deleteWand() { + Entities.deleteEntity(wand); +} + +if (DELETE_AT_ENDING === true) { + Script.scriptEnding.connect(deleteWand); +} + +createColorBusterWand(); \ No newline at end of file From aeac31cf6a5470f760af1536adb718e782b3d4ec Mon Sep 17 00:00:00 2001 From: "James B. Pollack" Date: Mon, 2 Nov 2015 16:37:24 -0800 Subject: [PATCH 05/45] dont delete cubes by default --- examples/example/games/color_busters/createColorBusterCubes.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/examples/example/games/color_busters/createColorBusterCubes.js b/examples/example/games/color_busters/createColorBusterCubes.js index 1b7aac51a5..6a2942bbe9 100644 --- a/examples/example/games/color_busters/createColorBusterCubes.js +++ b/examples/example/games/color_busters/createColorBusterCubes.js @@ -11,7 +11,7 @@ // -var DELETE_AT_ENDING = true; +var DELETE_AT_ENDING = false; var CUBE_DIMENSIONS = { x: 1, From 811fd0cec7f786011dfe23bdf57634025ff21220 Mon Sep 17 00:00:00 2001 From: "James B. Pollack" Date: Tue, 3 Nov 2015 10:42:15 -0800 Subject: [PATCH 06/45] prep for meeting --- examples/example/games/color_busters/colorBusterWand.js | 2 +- examples/example/games/color_busters/createColorBusterCubes.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/example/games/color_busters/colorBusterWand.js b/examples/example/games/color_busters/colorBusterWand.js index 6080d6f345..f9d69e8414 100644 --- a/examples/example/games/color_busters/colorBusterWand.js +++ b/examples/example/games/color_busters/colorBusterWand.js @@ -247,7 +247,7 @@ var position = Entities.getEntityProperties(this.entityID, "position").position; var audioProperties = { - volume: 0.5, + volume: 0.25, position: position }; diff --git a/examples/example/games/color_busters/createColorBusterCubes.js b/examples/example/games/color_busters/createColorBusterCubes.js index 6a2942bbe9..3fdd772704 100644 --- a/examples/example/games/color_busters/createColorBusterCubes.js +++ b/examples/example/games/color_busters/createColorBusterCubes.js @@ -19,7 +19,7 @@ var CUBE_DIMENSIONS = { z: 1 }; -var NUMBER_OF_CUBES_PER_SIDE = 5; +var NUMBER_OF_CUBES_PER_SIDE = 8; var STARTING_CORNER_POSITION = { x: 100, From 94c5637024bb3d5f2aa2f24b8f62f0e17d27f996 Mon Sep 17 00:00:00 2001 From: ericrius1 Date: Thu, 5 Nov 2015 17:27:30 -0800 Subject: [PATCH 07/45] marketplace spawner --- examples/marketplace/marketplaceSpawner.js | 50 ++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 examples/marketplace/marketplaceSpawner.js diff --git a/examples/marketplace/marketplaceSpawner.js b/examples/marketplace/marketplaceSpawner.js new file mode 100644 index 0000000000..3e655e3e74 --- /dev/null +++ b/examples/marketplace/marketplaceSpawner.js @@ -0,0 +1,50 @@ +var floorPosition = Vec3.sum(MyAvatar.position, Vec3.multiply(3, Quat.getFront(Camera.getOrientation())));; +floorPosition.y = MyAvatar.position.y - 5; + +var modelsToLoad = [ + { + lowURL: "https://s3.amazonaws.com/hifi-public/ozan/3d_marketplace/sets/tuscany/tuscany_low.fbx", + highURL: "https://s3.amazonaws.com/hifi-public/ozan/3d_marketplace/sets/tuscany/tuscany_hi.fbx" + } +]; + +var models = []; + +var floor = Entities.addEntity({ + type: "Model", + modelURL: "https://hifi-public.s3.amazonaws.com/ozan/3d_marketplace/props/floor/3d_mp_floor.fbx", + position: floorPosition, + shapeType: 'box', + dimensions: {x: 1000, y: 9, z: 1000} +}); + +//Create grid +var modelParams = { + type: "Model", + shapeType: "box", + dimensions: {x: 53, y: 15.7, z: 44.8}, + velocity: {x: 0, y: -1, z: 0}, + gravity: {x: 0, y: -1, z: 0}, + collisionsWillMove: true +}; + +var modelPosition = {x: floorPosition.x + 10, y: floorPosition.y + 15, z: floorPosition.z}; +for (var i = 0; i < modelsToLoad.length; i++) { + modelParams.modelURL = modelsToLoad[i].lowURL; + modelPosition.z -= 10; + modelParams.position = modelPosition; + var model = Entities.addEntity(modelParams); + models.push(model); +} + + + + +function cleanup() { + Entities.deleteEntity(floor); + models.forEach(function(model) { + Entities.deleteEntity(model); + }); +} + +Script.scriptEnding.connect(cleanup); \ No newline at end of file From a432a62deecf405ad1f53911a479feb07d3a0001 Mon Sep 17 00:00:00 2001 From: ericrius1 Date: Fri, 6 Nov 2015 13:53:25 -0800 Subject: [PATCH 08/45] model swapping --- examples/marketplace/marketplaceSpawner.js | 68 ++++++++++++++++------ examples/marketplace/modelSwap.js | 41 +++++++++++++ 2 files changed, 91 insertions(+), 18 deletions(-) create mode 100644 examples/marketplace/modelSwap.js diff --git a/examples/marketplace/marketplaceSpawner.js b/examples/marketplace/marketplaceSpawner.js index 3e655e3e74..6799ed63a3 100644 --- a/examples/marketplace/marketplaceSpawner.js +++ b/examples/marketplace/marketplaceSpawner.js @@ -1,12 +1,17 @@ var floorPosition = Vec3.sum(MyAvatar.position, Vec3.multiply(3, Quat.getFront(Camera.getOrientation())));; floorPosition.y = MyAvatar.position.y - 5; -var modelsToLoad = [ - { - lowURL: "https://s3.amazonaws.com/hifi-public/ozan/3d_marketplace/sets/tuscany/tuscany_low.fbx", - highURL: "https://s3.amazonaws.com/hifi-public/ozan/3d_marketplace/sets/tuscany/tuscany_hi.fbx" - } -]; +Script.include('../libraries/utils.js'); + +var entityScriptURL = Script.resolvePath("modelSwap.js"); + +var modelsToLoad = [{ + lowURL: "https://s3.amazonaws.com/hifi-public/ozan/3d_marketplace/sets/dojo/dojo_low.fbx", + highURL: "https://s3.amazonaws.com/hifi-public/ozan/3d_marketplace/sets/dojo/dojo_hi.fbx" +}, { + lowURL: "https://s3.amazonaws.com/hifi-public/ozan/3d_marketplace/sets/tuscany/tuscany_low.fbx", + highURL: "https://s3.amazonaws.com/hifi-public/ozan/3d_marketplace/sets/tuscany/tuscany_hi.fbx" +}]; var models = []; @@ -15,35 +20,62 @@ var floor = Entities.addEntity({ modelURL: "https://hifi-public.s3.amazonaws.com/ozan/3d_marketplace/props/floor/3d_mp_floor.fbx", position: floorPosition, shapeType: 'box', - dimensions: {x: 1000, y: 9, z: 1000} + dimensions: { + x: 1000, + y: 9, + z: 1000 + } }); //Create grid var modelParams = { type: "Model", - shapeType: "box", - dimensions: {x: 53, y: 15.7, z: 44.8}, - velocity: {x: 0, y: -1, z: 0}, - gravity: {x: 0, y: -1, z: 0}, - collisionsWillMove: true + dimensions: { + x: 31.85, + y: 7.75, + z: 54.51 + }, + script: entityScriptURL, + userData: JSON.stringify({ + grabbableKey: { + wantsTrigger: true + } + }) + }; -var modelPosition = {x: floorPosition.x + 10, y: floorPosition.y + 15, z: floorPosition.z}; +var modelPosition = { + x: floorPosition.x + 10, + y: floorPosition.y + 8.5, + z: floorPosition.z - 30 +}; for (var i = 0; i < modelsToLoad.length; i++) { modelParams.modelURL = modelsToLoad[i].lowURL; - modelPosition.z -= 10; modelParams.position = modelPosition; - var model = Entities.addEntity(modelParams); - models.push(model); -} + var lowModel = Entities.addEntity(modelParams); + modelParams.modelURL = modelsToLoad[i].highURL; + modelParams.visible = false; + modelParams.dimensions = Vec3.multiply(modelParams.dimensions, 0.5); + var highModel = Entities.addEntity(modelParams); + models.push({ + low: lowModel, + high: highModel + }); + // customKey, id, data + setEntityCustomData('modelCounterpart', lowModel, {modelCounterpartId: highModel}); + setEntityCustomData('modelCounterpart', highModel, {modelCounterpartId: lowModel}); + + modelPosition.z -= 60; +} function cleanup() { Entities.deleteEntity(floor); models.forEach(function(model) { - Entities.deleteEntity(model); + Entities.deleteEntity(model.low); + Entities.deleteEntity(model.high); }); } diff --git a/examples/marketplace/modelSwap.js b/examples/marketplace/modelSwap.js new file mode 100644 index 0000000000..29dbc84e98 --- /dev/null +++ b/examples/marketplace/modelSwap.js @@ -0,0 +1,41 @@ +// When user holds down trigger on model for enough time, the model with do a cool animation and swap out with the low or high version of it + + + +(function() { + + var _this; + ModelSwaper = function() { + _this = this; + }; + + ModelSwaper.prototype = { + + startFarTrigger: function() { + print("START TRIGGER") + + //make self invisible and make the model's counterpart visible! + var dimensions = Entities.getEntityProperties(this.entityID, "dimensions").dimensions; + Entities.editEntity(this.entityID, { + visible: false, + dimensions: Vec3.multiply(dimensions, 0.5) + }); + dimensions = Entities.getEntityProperties(this.modelCounterpartId, "dimensions").dimensions; + Entities.editEntity(this.modelCounterpartId, { + visible: true, + dimensions: Vec3.multiply(dimensions, 2) + }); + + }, + + preload: function(entityID) { + this.entityID = entityID; + var props = Entities.getEntityProperties(this.entityID, ["userData"]); + this.modelCounterpartId = JSON.parse(props.userData).modelCounterpart.modelCounterpartId; + } + + }; + + // entity scripts always need to return a newly constructed object of our type + return new ModelSwaper(); +}); \ No newline at end of file From c002888808765940fc0b4dd42d444f6be25645d5 Mon Sep 17 00:00:00 2001 From: "Anthony J. Thibault" Date: Fri, 6 Nov 2015 14:52:12 -0800 Subject: [PATCH 09/45] Added cache extractor to the tools directory It should find the local High Fidelity/Interface qt cache, iterate over each file in the cache and output each corresponding file into the High Fidelity/Interface/extracted dir. The file path will be determined from the source url. Untested on windows. --- tools/CMakeLists.txt | 3 + tools/cache-extract/CMakeLists.txt | 6 + tools/cache-extract/src/CacheExtractApp.cpp | 125 ++++++++++++++++++++ tools/cache-extract/src/CacheExtractApp.h | 47 ++++++++ tools/cache-extract/src/main.cpp | 17 +++ 5 files changed, 198 insertions(+) create mode 100644 tools/cache-extract/CMakeLists.txt create mode 100644 tools/cache-extract/src/CacheExtractApp.cpp create mode 100644 tools/cache-extract/src/CacheExtractApp.h create mode 100644 tools/cache-extract/src/main.cpp diff --git a/tools/CMakeLists.txt b/tools/CMakeLists.txt index 2056044a4b..9bc7031720 100644 --- a/tools/CMakeLists.txt +++ b/tools/CMakeLists.txt @@ -10,3 +10,6 @@ set_target_properties(udt-test PROPERTIES FOLDER "Tools") add_subdirectory(vhacd-util) set_target_properties(vhacd-util PROPERTIES FOLDER "Tools") + +add_subdirectory(cache-extract) +set_target_properties(cache-extract PROPERTIES FOLDER "Tools") diff --git a/tools/cache-extract/CMakeLists.txt b/tools/cache-extract/CMakeLists.txt new file mode 100644 index 0000000000..045fa996d2 --- /dev/null +++ b/tools/cache-extract/CMakeLists.txt @@ -0,0 +1,6 @@ +set(TARGET_NAME cache-extract) + +setup_hifi_project() + +link_hifi_libraries() + diff --git a/tools/cache-extract/src/CacheExtractApp.cpp b/tools/cache-extract/src/CacheExtractApp.cpp new file mode 100644 index 0000000000..e7e60973af --- /dev/null +++ b/tools/cache-extract/src/CacheExtractApp.cpp @@ -0,0 +1,125 @@ +// +// CacheExtractApp.cpp +// tools/cache-extract/src +// +// Created by Anthony Thibault on 11/6/2015. +// Copyright 2015 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "CacheExtractApp.h" +#include +#include +#include +#include + +// extracted from qnetworkdiskcache.cpp +#define CACHE_VERSION 8 +enum { + CacheMagic = 0xe8, + CurrentCacheVersion = CACHE_VERSION +}; +#define DATA_DIR QLatin1String("data") + +CacheExtractApp::CacheExtractApp(int& argc, char** argv) : + QCoreApplication(argc, argv) +{ + QString myDataLoc = QStandardPaths::writableLocation(QStandardPaths::DataLocation); + int lastSlash = myDataLoc.lastIndexOf(QDir::separator()); + QString cachePath = myDataLoc.leftRef(lastSlash).toString() + QDir::separator() + + "High Fidelity" + QDir::separator() + "Interface" + QDir::separator() + + DATA_DIR + QString::number(CACHE_VERSION) + QLatin1Char('/'); + + QString outputPath = myDataLoc.leftRef(lastSlash).toString() + QDir::separator() + + "High Fidelity" + QDir::separator() + "Interface" + QDir::separator() + "extracted"; + + qDebug() << "Searching cachePath = " << cachePath << "..."; + + // build list of files + QList fileList; + QDir dir(cachePath); + dir.setFilter(QDir::AllDirs | QDir::NoDotAndDotDot); + QFileInfoList list = dir.entryInfoList(); + for (int i = 0; i < list.size(); ++i) { + QFileInfo fileInfo = list.at(i); + if (fileInfo.isDir()) { + QDir subDir(fileInfo.filePath()); + subDir.setFilter(QDir::Files); + QFileInfoList subList = subDir.entryInfoList(); + for (int j = 0; j < subList.size(); ++j) { + fileList << subList.at(j).filePath(); + } + } + } + + // dump each cache file into the outputPath + for (int i = 0; i < fileList.size(); ++i) { + QByteArray contents; + MyMetaData metaData; + if (extractFile(fileList.at(i), metaData, contents)) { + QString outFileName = outputPath + metaData.url.path(); + int lastSlash = outFileName.lastIndexOf(QDir::separator()); + QString outDirName = outFileName.leftRef(lastSlash).toString(); + QDir dir(outputPath); + dir.mkpath(outDirName); + QFile out(outFileName); + if (out.open(QIODevice::WriteOnly)) { + out.write(contents); + out.close(); + } + } else { + qCritical() << "Error extracting = " << fileList.at(i); + } + } + + QMetaObject::invokeMethod(this, "quit", Qt::QueuedConnection); +} + +bool CacheExtractApp::extractFile(const QString& filePath, MyMetaData& metaData, QByteArray& data) const { + QFile f(filePath); + if (!f.open(QIODevice::ReadOnly)) { + qDebug() << "error opening " << filePath; + return false; + } + QDataStream in(&f); + // from qnetworkdiskcache.cpp QCacheItem::read() + qint32 marker, version, streamVersion; + in >> marker; + if (marker != CacheMagic) { + return false; + } + in >> version; + if (version != CurrentCacheVersion) { + return false; + } + in >> streamVersion; + if (streamVersion > in.version()) + return false; + in.setVersion(streamVersion); + + bool compressed; + in >> metaData; + in >> compressed; + if (compressed) { + QByteArray compressedData; + in >> compressedData; + QBuffer buffer; + buffer.setData(qUncompress(compressedData)); + buffer.open(QBuffer::ReadOnly); + data = buffer.readAll(); + } else { + data = f.readAll(); + } + return true; +} + +QDataStream &operator>>(QDataStream& in, MyMetaData& metaData) { + in >> metaData.url; + in >> metaData.expirationDate; + in >> metaData.lastModified; + in >> metaData.saveToDisk; + in >> metaData.attributes; + in >> metaData.rawHeaders; +} diff --git a/tools/cache-extract/src/CacheExtractApp.h b/tools/cache-extract/src/CacheExtractApp.h new file mode 100644 index 0000000000..3dde1f684d --- /dev/null +++ b/tools/cache-extract/src/CacheExtractApp.h @@ -0,0 +1,47 @@ +// +// CacheExtractApp.h +// tools/cache-extract/src +// +// Created by Anthony Thibault on 11/6/2015 +// Copyright 2015 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#ifndef hifi_CacheExtractApp_h +#define hifi_CacheExtractApp_h + +#include +#include +#include +#include +#include +#include + +// copy of QNetworkCacheMetaData +class MyMetaData { +public: + typedef QPair RawHeader; + typedef QList RawHeaderList; + typedef QHash AttributesMap; + + QUrl url; + QDateTime expirationDate; + QDateTime lastModified; + bool saveToDisk; + AttributesMap attributes; + RawHeaderList rawHeaders; +}; + +QDataStream &operator>>(QDataStream &, MyMetaData &); + +class CacheExtractApp : public QCoreApplication { + Q_OBJECT +public: + CacheExtractApp(int& argc, char** argv); + + bool extractFile(const QString& filePath, MyMetaData& metaData, QByteArray& data) const; +}; + +#endif // hifi_CacheExtractApp_h diff --git a/tools/cache-extract/src/main.cpp b/tools/cache-extract/src/main.cpp new file mode 100644 index 0000000000..71a364ed3e --- /dev/null +++ b/tools/cache-extract/src/main.cpp @@ -0,0 +1,17 @@ +// +// main.cpp +// tools/cache-extract/src +// +// Created by Anthony Thibault on 11/6/2015. +// Copyright 2015 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html + +#include +#include "CacheExtractApp.h" + +int main (int argc, char** argv) { + CacheExtractApp app(argc, argv); + return app.exec(); +} From 086b0645273f33c9fc00cfd99cb82b82fef0725e Mon Sep 17 00:00:00 2001 From: "Anthony J. Thibault" Date: Fri, 6 Nov 2015 15:07:38 -0800 Subject: [PATCH 10/45] Dumps all urls extracted to stdout. --- tools/cache-extract/src/CacheExtractApp.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/tools/cache-extract/src/CacheExtractApp.cpp b/tools/cache-extract/src/CacheExtractApp.cpp index e7e60973af..a0d0bf54ec 100644 --- a/tools/cache-extract/src/CacheExtractApp.cpp +++ b/tools/cache-extract/src/CacheExtractApp.cpp @@ -68,6 +68,7 @@ CacheExtractApp::CacheExtractApp(int& argc, char** argv) : if (out.open(QIODevice::WriteOnly)) { out.write(contents); out.close(); + qDebug().noquote() << metaData.url.toDisplayString(); } } else { qCritical() << "Error extracting = " << fileList.at(i); From 9a484ff00dd71b94c34712759fc4a863a99c910a Mon Sep 17 00:00:00 2001 From: "Anthony J. Thibault" Date: Fri, 6 Nov 2015 15:33:06 -0800 Subject: [PATCH 11/45] Fixes for windows --- tools/cache-extract/CMakeLists.txt | 1 + tools/cache-extract/src/CacheExtractApp.cpp | 22 ++++++++++++--------- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/tools/cache-extract/CMakeLists.txt b/tools/cache-extract/CMakeLists.txt index 045fa996d2..1aaa4d9d04 100644 --- a/tools/cache-extract/CMakeLists.txt +++ b/tools/cache-extract/CMakeLists.txt @@ -3,4 +3,5 @@ set(TARGET_NAME cache-extract) setup_hifi_project() link_hifi_libraries() +copy_dlls_beside_windows_executable() diff --git a/tools/cache-extract/src/CacheExtractApp.cpp b/tools/cache-extract/src/CacheExtractApp.cpp index a0d0bf54ec..0cfaef3f83 100644 --- a/tools/cache-extract/src/CacheExtractApp.cpp +++ b/tools/cache-extract/src/CacheExtractApp.cpp @@ -14,6 +14,7 @@ #include #include #include +#include // extracted from qnetworkdiskcache.cpp #define CACHE_VERSION 8 @@ -21,19 +22,18 @@ enum { CacheMagic = 0xe8, CurrentCacheVersion = CACHE_VERSION }; -#define DATA_DIR QLatin1String("data") CacheExtractApp::CacheExtractApp(int& argc, char** argv) : QCoreApplication(argc, argv) { QString myDataLoc = QStandardPaths::writableLocation(QStandardPaths::DataLocation); - int lastSlash = myDataLoc.lastIndexOf(QDir::separator()); - QString cachePath = myDataLoc.leftRef(lastSlash).toString() + QDir::separator() + - "High Fidelity" + QDir::separator() + "Interface" + QDir::separator() + - DATA_DIR + QString::number(CACHE_VERSION) + QLatin1Char('/'); + int lastSlash = myDataLoc.lastIndexOf("/"); + QString cachePath = myDataLoc.leftRef(lastSlash).toString() + "/" + + "High Fidelity" + "/" + "Interface" + "/" + + "data" + QString::number(CACHE_VERSION) + "/"; - QString outputPath = myDataLoc.leftRef(lastSlash).toString() + QDir::separator() + - "High Fidelity" + QDir::separator() + "Interface" + QDir::separator() + "extracted"; + QString outputPath = myDataLoc.leftRef(lastSlash).toString() + "/" + + "High Fidelity" + "/" + "Interface" + "/" + "extracted"; qDebug() << "Searching cachePath = " << cachePath << "..."; @@ -60,9 +60,9 @@ CacheExtractApp::CacheExtractApp(int& argc, char** argv) : MyMetaData metaData; if (extractFile(fileList.at(i), metaData, contents)) { QString outFileName = outputPath + metaData.url.path(); - int lastSlash = outFileName.lastIndexOf(QDir::separator()); + int lastSlash = outFileName.lastIndexOf("/"); QString outDirName = outFileName.leftRef(lastSlash).toString(); - QDir dir(outputPath); + QDir dir; dir.mkpath(outDirName); QFile out(outFileName); if (out.open(QIODevice::WriteOnly)) { @@ -70,6 +70,9 @@ CacheExtractApp::CacheExtractApp(int& argc, char** argv) : out.close(); qDebug().noquote() << metaData.url.toDisplayString(); } + else { + qCritical() << "Error opening outputFile = " << outFileName; + } } else { qCritical() << "Error extracting = " << fileList.at(i); } @@ -123,4 +126,5 @@ QDataStream &operator>>(QDataStream& in, MyMetaData& metaData) { in >> metaData.saveToDisk; in >> metaData.attributes; in >> metaData.rawHeaders; + return in; } From c4318bcbd3c7aecab58b1b49ed5db92981504bc0 Mon Sep 17 00:00:00 2001 From: "James B. Pollack" Date: Fri, 6 Nov 2015 17:38:53 -0800 Subject: [PATCH 12/45] add easystar lib --- examples/libraries/easyStar.js | 744 ++++++++++++++++++++++++++ examples/libraries/easyStarExample.js | 30 ++ 2 files changed, 774 insertions(+) create mode 100644 examples/libraries/easyStar.js create mode 100644 examples/libraries/easyStarExample.js diff --git a/examples/libraries/easyStar.js b/examples/libraries/easyStar.js new file mode 100644 index 0000000000..b76ff1d7ec --- /dev/null +++ b/examples/libraries/easyStar.js @@ -0,0 +1,744 @@ +// The MIT License (MIT) + +// Copyright (c) 2012-2015 Bryce Neal + +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: + +// The above copyright notice and this permission notice shall be included in +// all copies or substantial portions of the Software. + +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +// THE SOFTWARE. + +// Adapted for High Fidelity by James B. Pollack on 11/6/2015 + +loadEasyStar = function() { + var ezStar = eStar(); + return new ezStar.js() +} + +var eStar = function() { + + var EasyStar = EasyStar || {}; + + + /** + * A simple Node that represents a single tile on the grid. + * @param {Object} parent The parent node. + * @param {Number} x The x position on the grid. + * @param {Number} y The y position on the grid. + * @param {Number} costSoFar How far this node is in moves*cost from the start. + * @param {Number} simpleDistanceToTarget Manhatten distance to the end point. + **/ + EasyStar.Node = function(parent, x, y, costSoFar, simpleDistanceToTarget) { + this.parent = parent; + this.x = x; + this.y = y; + this.costSoFar = costSoFar; + this.simpleDistanceToTarget = simpleDistanceToTarget; + + /** + * @return {Number} Best guess distance of a cost using this node. + **/ + this.bestGuessDistance = function() { + return this.costSoFar + this.simpleDistanceToTarget; + } + }; + + // Constants + EasyStar.Node.OPEN_LIST = 0; + EasyStar.Node.CLOSED_LIST = 1; + /** + * This is an improved Priority Queue data type implementation that can be used to sort any object type. + * It uses a technique called a binary heap. + * + * For more on binary heaps see: http://en.wikipedia.org/wiki/Binary_heap + * + * @param {String} criteria The criteria by which to sort the objects. + * This should be a property of the objects you're sorting. + * + * @param {Number} heapType either PriorityQueue.MAX_HEAP or PriorityQueue.MIN_HEAP. + **/ + EasyStar.PriorityQueue = function(criteria, heapType) { + this.length = 0; //The current length of heap. + var queue = []; + var isMax = false; + + //Constructor + if (heapType == EasyStar.PriorityQueue.MAX_HEAP) { + isMax = true; + } else if (heapType == EasyStar.PriorityQueue.MIN_HEAP) { + isMax = false; + } else { + throw heapType + " not supported."; + } + + /** + * Inserts the value into the heap and sorts it. + * + * @param value The object to insert into the heap. + **/ + this.insert = function(value) { + if (!value.hasOwnProperty(criteria)) { + throw "Cannot insert " + value + " because it does not have a property by the name of " + criteria + "."; + } + queue.push(value); + this.length++; + bubbleUp(this.length - 1); + } + + /** + * Peeks at the highest priority element. + * + * @return the highest priority element + **/ + this.getHighestPriorityElement = function() { + return queue[0]; + } + + /** + * Removes and returns the highest priority element from the queue. + * + * @return the highest priority element + **/ + this.shiftHighestPriorityElement = function() { + if (this.length === 0) { + throw ("There are no more elements in your priority queue."); + } else if (this.length === 1) { + var onlyValue = queue[0]; + queue = []; + this.length = 0; + return onlyValue; + } + var oldRoot = queue[0]; + var newRoot = queue.pop(); + this.length--; + queue[0] = newRoot; + swapUntilQueueIsCorrect(0); + return oldRoot; + } + + var bubbleUp = function(index) { + if (index === 0) { + return; + } + var parent = getParentOf(index); + if (evaluate(index, parent)) { + swap(index, parent); + bubbleUp(parent); + } else { + return; + } + } + + var swapUntilQueueIsCorrect = function(value) { + var left = getLeftOf(value); + var right = getRightOf(value); + if (evaluate(left, value)) { + swap(value, left); + swapUntilQueueIsCorrect(left); + } else if (evaluate(right, value)) { + swap(value, right); + swapUntilQueueIsCorrect(right); + } else if (value == 0) { + return; + } else { + swapUntilQueueIsCorrect(0); + } + } + + var swap = function(self, target) { + var placeHolder = queue[self]; + queue[self] = queue[target]; + queue[target] = placeHolder; + } + + var evaluate = function(self, target) { + if (queue[target] === undefined || queue[self] === undefined) { + return false; + } + + var selfValue; + var targetValue; + + // Check if the criteria should be the result of a function call. + if (typeof queue[self][criteria] === 'function') { + selfValue = queue[self][criteria](); + targetValue = queue[target][criteria](); + } else { + selfValue = queue[self][criteria]; + targetValue = queue[target][criteria]; + } + + if (isMax) { + if (selfValue > targetValue) { + return true; + } else { + return false; + } + } else { + if (selfValue < targetValue) { + return true; + } else { + return false; + } + } + } + + var getParentOf = function(index) { + return Math.floor((index - 1) / 2); + } + + var getLeftOf = function(index) { + return index * 2 + 1; + } + + var getRightOf = function(index) { + return index * 2 + 2; + } + }; + + // Constants + EasyStar.PriorityQueue.MAX_HEAP = 0; + EasyStar.PriorityQueue.MIN_HEAP = 1; + + /** + * Represents a single instance of EasyStar. + * A path that is in the queue to eventually be found. + */ + EasyStar.instance = function() { + this.isDoneCalculating = true; + this.pointsToAvoid = {}; + this.startX; + this.callback; + this.startY; + this.endX; + this.endY; + this.nodeHash = {}; + this.openList; + }; + /** + * EasyStar.js + * github.com/prettymuchbryce/EasyStarJS + * Licensed under the MIT license. + * + * Implementation By Bryce Neal (@prettymuchbryce) + **/ + EasyStar.js = function() { + var STRAIGHT_COST = 1.0; + var DIAGONAL_COST = 1.4; + var syncEnabled = false; + var pointsToAvoid = {}; + var collisionGrid; + var costMap = {}; + var pointsToCost = {}; + var allowCornerCutting = true; + var iterationsSoFar; + var instances = []; + var iterationsPerCalculation = Number.MAX_VALUE; + var acceptableTiles; + var diagonalsEnabled = false; + + /** + * Sets the collision grid that EasyStar uses. + * + * @param {Array|Number} tiles An array of numbers that represent + * which tiles in your grid should be considered + * acceptable, or "walkable". + **/ + this.setAcceptableTiles = function(tiles) { + if (tiles instanceof Array) { + // Array + acceptableTiles = tiles; + } else if (!isNaN(parseFloat(tiles)) && isFinite(tiles)) { + // Number + acceptableTiles = [tiles]; + } + }; + + /** + * Enables sync mode for this EasyStar instance.. + * if you're into that sort of thing. + **/ + this.enableSync = function() { + syncEnabled = true; + }; + + /** + * Disables sync mode for this EasyStar instance. + **/ + this.disableSync = function() { + syncEnabled = false; + }; + + /** + * Enable diagonal pathfinding. + */ + this.enableDiagonals = function() { + diagonalsEnabled = true; + } + + /** + * Disable diagonal pathfinding. + */ + this.disableDiagonals = function() { + diagonalsEnabled = false; + } + + /** + * Sets the collision grid that EasyStar uses. + * + * @param {Array} grid The collision grid that this EasyStar instance will read from. + * This should be a 2D Array of Numbers. + **/ + this.setGrid = function(grid) { + print('EASY GRID') + collisionGrid = grid; + + //Setup cost map + for (var y = 0; y < collisionGrid.length; y++) { + for (var x = 0; x < collisionGrid[0].length; x++) { + if (!costMap[collisionGrid[y][x]]) { + costMap[collisionGrid[y][x]] = 1 + } + } + } + }; + + /** + * Sets the tile cost for a particular tile type. + * + * @param {Number} The tile type to set the cost for. + * @param {Number} The multiplicative cost associated with the given tile. + **/ + this.setTileCost = function(tileType, cost) { + costMap[tileType] = cost; + }; + + /** + * Sets the an additional cost for a particular point. + * Overrides the cost from setTileCost. + * + * @param {Number} x The x value of the point to cost. + * @param {Number} y The y value of the point to cost. + * @param {Number} The multiplicative cost associated with the given point. + **/ + this.setAdditionalPointCost = function(x, y, cost) { + pointsToCost[x + '_' + y] = cost; + }; + + /** + * Remove the additional cost for a particular point. + * + * @param {Number} x The x value of the point to stop costing. + * @param {Number} y The y value of the point to stop costing. + **/ + this.removeAdditionalPointCost = function(x, y) { + delete pointsToCost[x + '_' + y]; + } + + /** + * Remove all additional point costs. + **/ + this.removeAllAdditionalPointCosts = function() { + pointsToCost = {}; + } + + /** + * Sets the number of search iterations per calculation. + * A lower number provides a slower result, but more practical if you + * have a large tile-map and don't want to block your thread while + * finding a path. + * + * @param {Number} iterations The number of searches to prefrom per calculate() call. + **/ + this.setIterationsPerCalculation = function(iterations) { + iterationsPerCalculation = iterations; + }; + + /** + * Avoid a particular point on the grid, + * regardless of whether or not it is an acceptable tile. + * + * @param {Number} x The x value of the point to avoid. + * @param {Number} y The y value of the point to avoid. + **/ + this.avoidAdditionalPoint = function(x, y) { + pointsToAvoid[x + "_" + y] = 1; + }; + + /** + * Stop avoiding a particular point on the grid. + * + * @param {Number} x The x value of the point to stop avoiding. + * @param {Number} y The y value of the point to stop avoiding. + **/ + this.stopAvoidingAdditionalPoint = function(x, y) { + delete pointsToAvoid[x + "_" + y]; + }; + + /** + * Enables corner cutting in diagonal movement. + **/ + this.enableCornerCutting = function() { + allowCornerCutting = true; + }; + + /** + * Disables corner cutting in diagonal movement. + **/ + this.disableCornerCutting = function() { + allowCornerCutting = false; + }; + + /** + * Stop avoiding all additional points on the grid. + **/ + this.stopAvoidingAllAdditionalPoints = function() { + pointsToAvoid = {}; + }; + + /** + * Find a path. + * + * @param {Number} startX The X position of the starting point. + * @param {Number} startY The Y position of the starting point. + * @param {Number} endX The X position of the ending point. + * @param {Number} endY The Y position of the ending point. + * @param {Function} callback A function that is called when your path + * is found, or no path is found. + * + **/ + this.findPath = function(startX, startY, endX, endY, callback) { + // Wraps the callback for sync vs async logic + var callbackWrapper = function(result) { + if (syncEnabled) { + callback(result); + } else { + Script.setTimeout(function() { + callback(result); + }, 1); + } + } + + // No acceptable tiles were set + if (acceptableTiles === undefined) { + throw new Error("You can't set a path without first calling setAcceptableTiles() on EasyStar."); + } + // No grid was set + if (collisionGrid === undefined) { + throw new Error("You can't set a path without first calling setGrid() on EasyStar."); + } + + // Start or endpoint outside of scope. + if (startX < 0 || startY < 0 || endX < 0 || endX < 0 || + startX > collisionGrid[0].length - 1 || startY > collisionGrid.length - 1 || + endX > collisionGrid[0].length - 1 || endY > collisionGrid.length - 1) { + throw new Error("Your start or end point is outside the scope of your grid."); + } + + // Start and end are the same tile. + if (startX === endX && startY === endY) { + callbackWrapper([]); + return; + } + + // End point is not an acceptable tile. + var endTile = collisionGrid[endY][endX]; + var isAcceptable = false; + for (var i = 0; i < acceptableTiles.length; i++) { + if (endTile === acceptableTiles[i]) { + isAcceptable = true; + break; + } + } + + if (isAcceptable === false) { + callbackWrapper(null); + return; + } + + // Create the instance + var instance = new EasyStar.instance(); + instance.openList = new EasyStar.PriorityQueue("bestGuessDistance", EasyStar.PriorityQueue.MIN_HEAP); + instance.isDoneCalculating = false; + instance.nodeHash = {}; + instance.startX = startX; + instance.startY = startY; + instance.endX = endX; + instance.endY = endY; + instance.callback = callbackWrapper; + + instance.openList.insert(coordinateToNode(instance, instance.startX, + instance.startY, null, STRAIGHT_COST)); + + instances.push(instance); + }; + + /** + * This method steps through the A* Algorithm in an attempt to + * find your path(s). It will search 4-8 tiles (depending on diagonals) for every calculation. + * You can change the number of calculations done in a call by using + * easystar.setIteratonsPerCalculation(). + **/ + this.calculate = function() { + if (instances.length === 0 || collisionGrid === undefined || acceptableTiles === undefined) { + return; + } + for (iterationsSoFar = 0; iterationsSoFar < iterationsPerCalculation; iterationsSoFar++) { + if (instances.length === 0) { + return; + } + + if (syncEnabled) { + // If this is a sync instance, we want to make sure that it calculates synchronously. + iterationsSoFar = 0; + } + + // Couldn't find a path. + if (instances[0].openList.length === 0) { + var ic = instances[0]; + ic.callback(null); + instances.shift(); + continue; + } + + var searchNode = instances[0].openList.shiftHighestPriorityElement(); + + var tilesToSearch = []; + searchNode.list = EasyStar.Node.CLOSED_LIST; + + if (searchNode.y > 0) { + tilesToSearch.push({ + instance: instances[0], + searchNode: searchNode, + x: 0, + y: -1, + cost: STRAIGHT_COST * getTileCost(searchNode.x, searchNode.y - 1) + }); + } + if (searchNode.x < collisionGrid[0].length - 1) { + tilesToSearch.push({ + instance: instances[0], + searchNode: searchNode, + x: 1, + y: 0, + cost: STRAIGHT_COST * getTileCost(searchNode.x + 1, searchNode.y) + }); + } + if (searchNode.y < collisionGrid.length - 1) { + tilesToSearch.push({ + instance: instances[0], + searchNode: searchNode, + x: 0, + y: 1, + cost: STRAIGHT_COST * getTileCost(searchNode.x, searchNode.y + 1) + }); + } + if (searchNode.x > 0) { + tilesToSearch.push({ + instance: instances[0], + searchNode: searchNode, + x: -1, + y: 0, + cost: STRAIGHT_COST * getTileCost(searchNode.x - 1, searchNode.y) + }); + } + if (diagonalsEnabled) { + if (searchNode.x > 0 && searchNode.y > 0) { + + if (allowCornerCutting || + (isTileWalkable(collisionGrid, acceptableTiles, searchNode.x, searchNode.y - 1) && + isTileWalkable(collisionGrid, acceptableTiles, searchNode.x - 1, searchNode.y))) { + + tilesToSearch.push({ + instance: instances[0], + searchNode: searchNode, + x: -1, + y: -1, + cost: DIAGONAL_COST * getTileCost(searchNode.x - 1, searchNode.y - 1) + }); + } + } + if (searchNode.x < collisionGrid[0].length - 1 && searchNode.y < collisionGrid.length - 1) { + + if (allowCornerCutting || + (isTileWalkable(collisionGrid, acceptableTiles, searchNode.x, searchNode.y + 1) && + isTileWalkable(collisionGrid, acceptableTiles, searchNode.x + 1, searchNode.y))) { + + tilesToSearch.push({ + instance: instances[0], + searchNode: searchNode, + x: 1, + y: 1, + cost: DIAGONAL_COST * getTileCost(searchNode.x + 1, searchNode.y + 1) + }); + } + } + if (searchNode.x < collisionGrid[0].length - 1 && searchNode.y > 0) { + + if (allowCornerCutting || + (isTileWalkable(collisionGrid, acceptableTiles, searchNode.x, searchNode.y - 1) && + isTileWalkable(collisionGrid, acceptableTiles, searchNode.x + 1, searchNode.y))) { + + + tilesToSearch.push({ + instance: instances[0], + searchNode: searchNode, + x: 1, + y: -1, + cost: DIAGONAL_COST * getTileCost(searchNode.x + 1, searchNode.y - 1) + }); + } + } + if (searchNode.x > 0 && searchNode.y < collisionGrid.length - 1) { + + if (allowCornerCutting || + (isTileWalkable(collisionGrid, acceptableTiles, searchNode.x, searchNode.y + 1) && + isTileWalkable(collisionGrid, acceptableTiles, searchNode.x - 1, searchNode.y))) { + + + tilesToSearch.push({ + instance: instances[0], + searchNode: searchNode, + x: -1, + y: 1, + cost: DIAGONAL_COST * getTileCost(searchNode.x - 1, searchNode.y + 1) + }); + } + } + } + + // First sort all of the potential nodes we could search by their cost + heuristic distance. + tilesToSearch.sort(function(a, b) { + var aCost = a.cost + getDistance(searchNode.x + a.x, searchNode.y + a.y, instances[0].endX, instances[0].endY) + var bCost = b.cost + getDistance(searchNode.x + b.x, searchNode.y + b.y, instances[0].endX, instances[0].endY) + if (aCost < bCost) { + return -1; + } else if (aCost === bCost) { + return 0; + } else { + return 1; + } + }); + + var isDoneCalculating = false; + + // Search all of the surrounding nodes + for (var i = 0; i < tilesToSearch.length; i++) { + checkAdjacentNode(tilesToSearch[i].instance, tilesToSearch[i].searchNode, + tilesToSearch[i].x, tilesToSearch[i].y, tilesToSearch[i].cost); + if (tilesToSearch[i].instance.isDoneCalculating === true) { + isDoneCalculating = true; + break; + } + } + + if (isDoneCalculating) { + instances.shift(); + continue; + } + + } + }; + + // Private methods follow + var checkAdjacentNode = function(instance, searchNode, x, y, cost) { + var adjacentCoordinateX = searchNode.x + x; + var adjacentCoordinateY = searchNode.y + y; + + if (pointsToAvoid[adjacentCoordinateX + "_" + adjacentCoordinateY] === undefined) { + // Handles the case where we have found the destination + if (instance.endX === adjacentCoordinateX && instance.endY === adjacentCoordinateY) { + instance.isDoneCalculating = true; + var path = []; + var pathLen = 0; + path[pathLen] = { + x: adjacentCoordinateX, + y: adjacentCoordinateY + }; + pathLen++; + path[pathLen] = { + x: searchNode.x, + y: searchNode.y + }; + pathLen++; + var parent = searchNode.parent; + while (parent != null) { + path[pathLen] = { + x: parent.x, + y: parent.y + }; + pathLen++; + parent = parent.parent; + } + path.reverse(); + var ic = instance; + var ip = path; + ic.callback(ip); + return + } + + if (isTileWalkable(collisionGrid, acceptableTiles, adjacentCoordinateX, adjacentCoordinateY)) { + var node = coordinateToNode(instance, adjacentCoordinateX, + adjacentCoordinateY, searchNode, cost); + + if (node.list === undefined) { + node.list = EasyStar.Node.OPEN_LIST; + instance.openList.insert(node); + } else if (node.list === EasyStar.Node.OPEN_LIST) { + if (searchNode.costSoFar + cost < node.costSoFar) { + node.costSoFar = searchNode.costSoFar + cost; + node.parent = searchNode; + } + } + } + } + }; + + // Helpers + var isTileWalkable = function(collisionGrid, acceptableTiles, x, y) { + for (var i = 0; i < acceptableTiles.length; i++) { + if (collisionGrid[y][x] === acceptableTiles[i]) { + return true; + } + } + + return false; + }; + + var getTileCost = function(x, y) { + return pointsToCost[x + '_' + y] || costMap[collisionGrid[y][x]] + }; + + var coordinateToNode = function(instance, x, y, parent, cost) { + if (instance.nodeHash[x + "_" + y] !== undefined) { + return instance.nodeHash[x + "_" + y]; + } + var simpleDistanceToTarget = getDistance(x, y, instance.endX, instance.endY); + if (parent !== null) { + var costSoFar = parent.costSoFar + cost; + } else { + costSoFar = simpleDistanceToTarget; + } + var node = new EasyStar.Node(parent, x, y, costSoFar, simpleDistanceToTarget); + instance.nodeHash[x + "_" + y] = node; + return node; + }; + + var getDistance = function(x1, y1, x2, y2) { + return Math.sqrt((x2 -= x1) * x2 + (y2 -= y1) * y2); + }; + } + return EasyStar +} \ No newline at end of file diff --git a/examples/libraries/easyStarExample.js b/examples/libraries/easyStarExample.js new file mode 100644 index 0000000000..3e28fb571e --- /dev/null +++ b/examples/libraries/easyStarExample.js @@ -0,0 +1,30 @@ +Script.include('easyStar.js'); +var easystar = loadEasyStar(); + +var grid = [ + [0, 0, 1, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 0, 0] +]; + +easystar.setGrid(grid); + +easystar.setAcceptableTiles([0]); + +easystar.findPath(0, 0, 4, 0, function(path) { + if (path === null) { + print("Path was not found."); + Script.update.disconnect(tickEasyStar) + } else { + print("Path was found. The first Point is " + path[0].x + " " + path[0].y); + Script.update.disconnect(tickEasyStar) + } +}); + +var tickEasyStar = function() { + easystar.calculate(); +} + +Script.update.connect(tickEasyStar); \ No newline at end of file From 82b26b75f4024099e569ef6703594adf3321759b Mon Sep 17 00:00:00 2001 From: "Anthony J. Thibault" Date: Mon, 9 Nov 2015 08:14:27 -0800 Subject: [PATCH 13/45] Code convention fixes --- tools/cache-extract/src/CacheExtractApp.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/tools/cache-extract/src/CacheExtractApp.h b/tools/cache-extract/src/CacheExtractApp.h index 3dde1f684d..3b34ff891d 100644 --- a/tools/cache-extract/src/CacheExtractApp.h +++ b/tools/cache-extract/src/CacheExtractApp.h @@ -22,9 +22,9 @@ // copy of QNetworkCacheMetaData class MyMetaData { public: - typedef QPair RawHeader; - typedef QList RawHeaderList; - typedef QHash AttributesMap; + using RawHeader = QPair; + using RawHeaderList = QList; + using AttributesMap = QHash; QUrl url; QDateTime expirationDate; @@ -34,7 +34,7 @@ public: RawHeaderList rawHeaders; }; -QDataStream &operator>>(QDataStream &, MyMetaData &); +QDataStream &operator>>(QDataStream& in, MyMetaData& metaData); class CacheExtractApp : public QCoreApplication { Q_OBJECT From 17814446ca3306f75b5821a87076aad8f5375dfe Mon Sep 17 00:00:00 2001 From: "James B. Pollack" Date: Mon, 9 Nov 2015 17:11:09 -0800 Subject: [PATCH 14/45] Add example with entities, add tween.js --- examples/libraries/easyStar.js | 1 - examples/libraries/easyStarExample.js | 214 ++++++- examples/libraries/tween.js | 878 ++++++++++++++++++++++++++ 3 files changed, 1082 insertions(+), 11 deletions(-) create mode 100644 examples/libraries/tween.js diff --git a/examples/libraries/easyStar.js b/examples/libraries/easyStar.js index b76ff1d7ec..15166c87c5 100644 --- a/examples/libraries/easyStar.js +++ b/examples/libraries/easyStar.js @@ -302,7 +302,6 @@ var eStar = function() { * This should be a 2D Array of Numbers. **/ this.setGrid = function(grid) { - print('EASY GRID') collisionGrid = grid; //Setup cost map diff --git a/examples/libraries/easyStarExample.js b/examples/libraries/easyStarExample.js index 3e28fb571e..eb758a2fe3 100644 --- a/examples/libraries/easyStarExample.js +++ b/examples/libraries/easyStarExample.js @@ -1,25 +1,45 @@ +// +// easyStarExample.js +// +// Created by James B. Pollack @imgntn on 11/9/2015 +// Copyright 2015 High Fidelity, Inc. +// +// This is a script that sets up a grid of obstacles and passable tiles, finds a path, and then moves an entity along the path. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html + +// To-Do: +// Abstract start position and make tiles, spheres, etc. relative +// Handle dynamically changing grids + Script.include('easyStar.js'); var easystar = loadEasyStar(); +Script.include('tween.js'); +var TWEEN = loadTween(); +var ANIMATION_DURATION = 350; var grid = [ - [0, 0, 1, 0, 0], - [0, 0, 1, 0, 0], - [0, 0, 1, 0, 0], - [0, 0, 1, 0, 0], - [0, 0, 0, 0, 0] + [0, 0, 1, 0, 0, 0, 0, 0, 0], + [0, 1, 1, 0, 1, 0, 1, 0, 0], + [0, 0, 1, 0, 0, 0, 0, 1, 1], + [0, 0, 1, 1, 0, 0, 0, 0, 0], + [0, 0, 0, 0, 1, 1, 1, 0, 0], + [0, 0, 0, 0, 0, 0, 0, 0, 0] ]; easystar.setGrid(grid); easystar.setAcceptableTiles([0]); -easystar.findPath(0, 0, 4, 0, function(path) { +easystar.findPath(0, 0, 8, 0, function(path) { if (path === null) { print("Path was not found."); - Script.update.disconnect(tickEasyStar) + Script.update.disconnect(tickEasyStar); } else { - print("Path was found. The first Point is " + path[0].x + " " + path[0].y); - Script.update.disconnect(tickEasyStar) + print('path' + JSON.stringify(path)); + convertPath(path); + Script.update.disconnect(tickEasyStar); } }); @@ -27,4 +47,178 @@ var tickEasyStar = function() { easystar.calculate(); } -Script.update.connect(tickEasyStar); \ No newline at end of file +Script.update.connect(tickEasyStar); + +//a sphere that will get moved +var playerSphere = Entities.addEntity({ + type: 'Sphere', + shape: 'Sphere', + color: { + red: 255, + green: 0, + blue: 0 + }, + dimensions: { + x: 0.5, + y: 0.5, + z: 0.5 + }, + position: { + x: 0, + y: 0, + z: 0 + } +}) + + +//for keeping track of entities +var obstacles = []; +var passables = []; + +function createPassableAtTilePosition(posX, posY) { + var properties = { + type: 'Box', + shapeType: 'Box', + dimensions: { + x: 1, + y: 1, + z: 1 + }, + position: { + x: posY, + y: -1, + z: posX + }, + color: { + red: 0, + green: 0, + blue: 255 + } + }; + var passable = Entities.addEntity(properties); + passables.push(passable); +} + +function createObstacleAtTilePosition(posX, posY) { + var properties = { + type: 'Box', + shapeType: 'Box', + dimensions: { + x: 1, + y: 1, + z: 1 + }, + position: { + x: posY, + y: 0, + z: posX + }, + color: { + red: 0, + green: 255, + blue: 0 + } + }; + var obstacle = Entities.addEntity(properties); + obstacles.push(obstacle); +} + +function createObstacles(grid) { + grid.forEach(function(row, rowIndex) { + row.forEach(function(v, index) { + if (v === 1) { + createObstacleAtTilePosition(rowIndex, index); + } + if (v === 0) { + createPassableAtTilePosition(rowIndex, index); + } + }) + + }) +} + + + +createObstacles(grid); + + +var currentSpherePosition = { + x: 0, + y: 0, + z: 0 +}; + + +function convertPathPointToCoordinates(x, y) { + return { + x: y, + y: 0, + z: x + }; +} + +var convertedPath = []; + +//convert our path to Vec3s +function convertPath(path) { + path.forEach(function(point) { + var convertedPoint = convertPathPointToCoordinates(point.x, point.y); + convertedPath.push(convertedPoint); + }); + createTweenPath(convertedPath); +} + +function updatePosition() { + Entities.editEntity(playerSphere, { + position: { + x: currentSpherePosition.z, + y: currentSpherePosition.y, + z: currentSpherePosition.x + } + }); +} + +function createTweenPath(convertedPath) { + var i; + var stepTweens = []; + + //create the tweens + for (i = 0; i < convertedPath.length - 1; i++) { + var stepTween = new TWEEN.Tween(currentSpherePosition).to(convertedPath[i + 1], ANIMATION_DURATION).onUpdate(updatePosition).onComplete(tweenStep); + stepTweens.push(stepTween); + } + + var j; + //chain one tween to the next + for (j = 0; j < stepTweens.length - 1; j++) { + stepTweens[j].chain(stepTweens[j + 1]); + } + + //start the tween + stepTweens[0].start(); +} + +function tweenStep() { + // print('step between tweens') +} + +function updateTweens() { + //hook tween updates into our update loop + TWEEN.update(); +} + +Script.update.connect(updateTweens); + +function cleanup() { + while (obstacles.length > 0) { + Entities.deleteEntity(obstacles.pop()); + } + while (passables.length > 0) { + Entities.deleteEntity(passables.pop()); + } + Entities.deleteEntity(playerSphere); + Script.update.disconnect(updateTweens); +} + + +Script.scriptEnding.connect(cleanup); \ No newline at end of file diff --git a/examples/libraries/tween.js b/examples/libraries/tween.js new file mode 100644 index 0000000000..f50e9533ae --- /dev/null +++ b/examples/libraries/tween.js @@ -0,0 +1,878 @@ +/** + * Tween.js - Licensed under the MIT license + * https://github.com/tweenjs/tween.js + * ---------------------------------------------- + * + * See https://github.com/tweenjs/tween.js/graphs/contributors for the full list of contributors. + * Thank you all, you're awesome! + */ + +// Include a performance.now polyfill +(function () { + window= {} + if ('performance' in window === false) { + window.performance = {}; + } + + // IE 8 + Date.now = (Date.now || function () { + return new Date().getTime(); + }); + + if ('now' in window.performance === false) { + var offset = window.performance.timing && window.performance.timing.navigationStart ? window.performance.timing.navigationStart + : Date.now(); + + window.performance.now = function () { + return Date.now() - offset; + }; + } + +})(); + +var TWEEN = TWEEN || (function () { + + var _tweens = []; + + return { + + getAll: function () { + + return _tweens; + + }, + + removeAll: function () { + + _tweens = []; + + }, + + add: function (tween) { + + _tweens.push(tween); + + }, + + remove: function (tween) { + + var i = _tweens.indexOf(tween); + + if (i !== -1) { + _tweens.splice(i, 1); + } + + }, + + update: function (time) { + + if (_tweens.length === 0) { + return false; + } + + var i = 0; + + time = time !== undefined ? time : window.performance.now(); + + while (i < _tweens.length) { + + if (_tweens[i].update(time)) { + i++; + } else { + _tweens.splice(i, 1); + } + + } + + return true; + + } + }; + +})(); + +TWEEN.Tween = function (object) { + + var _object = object; + var _valuesStart = {}; + var _valuesEnd = {}; + var _valuesStartRepeat = {}; + var _duration = 1000; + var _repeat = 0; + var _yoyo = false; + var _isPlaying = false; + var _reversed = false; + var _delayTime = 0; + var _startTime = null; + var _easingFunction = TWEEN.Easing.Linear.None; + var _interpolationFunction = TWEEN.Interpolation.Linear; + var _chainedTweens = []; + var _onStartCallback = null; + var _onStartCallbackFired = false; + var _onUpdateCallback = null; + var _onCompleteCallback = null; + var _onStopCallback = null; + + // Set all starting values present on the target object + for (var field in object) { + _valuesStart[field] = parseFloat(object[field], 10); + } + + this.to = function (properties, duration) { + + if (duration !== undefined) { + _duration = duration; + } + + _valuesEnd = properties; + + return this; + + }; + + this.start = function (time) { + + TWEEN.add(this); + + _isPlaying = true; + + _onStartCallbackFired = false; + + _startTime = time !== undefined ? time : window.performance.now(); + _startTime += _delayTime; + + for (var property in _valuesEnd) { + + // Check if an Array was provided as property value + if (_valuesEnd[property] instanceof Array) { + + if (_valuesEnd[property].length === 0) { + continue; + } + + // Create a local copy of the Array with the start value at the front + _valuesEnd[property] = [_object[property]].concat(_valuesEnd[property]); + + } + + _valuesStart[property] = _object[property]; + + if ((_valuesStart[property] instanceof Array) === false) { + _valuesStart[property] *= 1.0; // Ensures we're using numbers, not strings + } + + _valuesStartRepeat[property] = _valuesStart[property] || 0; + + } + + return this; + + }; + + this.stop = function () { + + if (!_isPlaying) { + return this; + } + + TWEEN.remove(this); + _isPlaying = false; + + if (_onStopCallback !== null) { + _onStopCallback.call(_object); + } + + this.stopChainedTweens(); + return this; + + }; + + this.stopChainedTweens = function () { + + for (var i = 0, numChainedTweens = _chainedTweens.length; i < numChainedTweens; i++) { + _chainedTweens[i].stop(); + } + + }; + + this.delay = function (amount) { + + _delayTime = amount; + return this; + + }; + + this.repeat = function (times) { + + _repeat = times; + return this; + + }; + + this.yoyo = function (yoyo) { + + _yoyo = yoyo; + return this; + + }; + + + this.easing = function (easing) { + + _easingFunction = easing; + return this; + + }; + + this.interpolation = function (interpolation) { + + _interpolationFunction = interpolation; + return this; + + }; + + this.chain = function () { + + _chainedTweens = arguments; + return this; + + }; + + this.onStart = function (callback) { + + _onStartCallback = callback; + return this; + + }; + + this.onUpdate = function (callback) { + + _onUpdateCallback = callback; + return this; + + }; + + this.onComplete = function (callback) { + + _onCompleteCallback = callback; + return this; + + }; + + this.onStop = function (callback) { + + _onStopCallback = callback; + return this; + + }; + + this.update = function (time) { + + var property; + var elapsed; + var value; + + if (time < _startTime) { + return true; + } + + if (_onStartCallbackFired === false) { + + if (_onStartCallback !== null) { + _onStartCallback.call(_object); + } + + _onStartCallbackFired = true; + + } + + elapsed = (time - _startTime) / _duration; + elapsed = elapsed > 1 ? 1 : elapsed; + + value = _easingFunction(elapsed); + + for (property in _valuesEnd) { + + var start = _valuesStart[property] || 0; + var end = _valuesEnd[property]; + + if (end instanceof Array) { + + _object[property] = _interpolationFunction(end, value); + + } else { + + // Parses relative end values with start as base (e.g.: +10, -3) + if (typeof (end) === 'string') { + end = start + parseFloat(end, 10); + } + + // Protect against non numeric properties. + if (typeof (end) === 'number') { + _object[property] = start + (end - start) * value; + } + + } + + } + + if (_onUpdateCallback !== null) { + _onUpdateCallback.call(_object, value); + } + + if (elapsed === 1) { + + if (_repeat > 0) { + + if (isFinite(_repeat)) { + _repeat--; + } + + // Reassign starting values, restart by making startTime = now + for (property in _valuesStartRepeat) { + + if (typeof (_valuesEnd[property]) === 'string') { + _valuesStartRepeat[property] = _valuesStartRepeat[property] + parseFloat(_valuesEnd[property], 10); + } + + if (_yoyo) { + var tmp = _valuesStartRepeat[property]; + + _valuesStartRepeat[property] = _valuesEnd[property]; + _valuesEnd[property] = tmp; + } + + _valuesStart[property] = _valuesStartRepeat[property]; + + } + + if (_yoyo) { + _reversed = !_reversed; + } + + _startTime = time + _delayTime; + + return true; + + } else { + + if (_onCompleteCallback !== null) { + _onCompleteCallback.call(_object); + } + + for (var i = 0, numChainedTweens = _chainedTweens.length; i < numChainedTweens; i++) { + // Make the chained tweens start exactly at the time they should, + // even if the `update()` method was called way past the duration of the tween + _chainedTweens[i].start(_startTime + _duration); + } + + return false; + + } + + } + + return true; + + }; + +}; + + +TWEEN.Easing = { + + Linear: { + + None: function (k) { + + return k; + + } + + }, + + Quadratic: { + + In: function (k) { + + return k * k; + + }, + + Out: function (k) { + + return k * (2 - k); + + }, + + InOut: function (k) { + + if ((k *= 2) < 1) { + return 0.5 * k * k; + } + + return - 0.5 * (--k * (k - 2) - 1); + + } + + }, + + Cubic: { + + In: function (k) { + + return k * k * k; + + }, + + Out: function (k) { + + return --k * k * k + 1; + + }, + + InOut: function (k) { + + if ((k *= 2) < 1) { + return 0.5 * k * k * k; + } + + return 0.5 * ((k -= 2) * k * k + 2); + + } + + }, + + Quartic: { + + In: function (k) { + + return k * k * k * k; + + }, + + Out: function (k) { + + return 1 - (--k * k * k * k); + + }, + + InOut: function (k) { + + if ((k *= 2) < 1) { + return 0.5 * k * k * k * k; + } + + return - 0.5 * ((k -= 2) * k * k * k - 2); + + } + + }, + + Quintic: { + + In: function (k) { + + return k * k * k * k * k; + + }, + + Out: function (k) { + + return --k * k * k * k * k + 1; + + }, + + InOut: function (k) { + + if ((k *= 2) < 1) { + return 0.5 * k * k * k * k * k; + } + + return 0.5 * ((k -= 2) * k * k * k * k + 2); + + } + + }, + + Sinusoidal: { + + In: function (k) { + + return 1 - Math.cos(k * Math.PI / 2); + + }, + + Out: function (k) { + + return Math.sin(k * Math.PI / 2); + + }, + + InOut: function (k) { + + return 0.5 * (1 - Math.cos(Math.PI * k)); + + } + + }, + + Exponential: { + + In: function (k) { + + return k === 0 ? 0 : Math.pow(1024, k - 1); + + }, + + Out: function (k) { + + return k === 1 ? 1 : 1 - Math.pow(2, - 10 * k); + + }, + + InOut: function (k) { + + if (k === 0) { + return 0; + } + + if (k === 1) { + return 1; + } + + if ((k *= 2) < 1) { + return 0.5 * Math.pow(1024, k - 1); + } + + return 0.5 * (- Math.pow(2, - 10 * (k - 1)) + 2); + + } + + }, + + Circular: { + + In: function (k) { + + return 1 - Math.sqrt(1 - k * k); + + }, + + Out: function (k) { + + return Math.sqrt(1 - (--k * k)); + + }, + + InOut: function (k) { + + if ((k *= 2) < 1) { + return - 0.5 * (Math.sqrt(1 - k * k) - 1); + } + + return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1); + + } + + }, + + Elastic: { + + In: function (k) { + + var s; + var a = 0.1; + var p = 0.4; + + if (k === 0) { + return 0; + } + + if (k === 1) { + return 1; + } + + if (!a || a < 1) { + a = 1; + s = p / 4; + } else { + s = p * Math.asin(1 / a) / (2 * Math.PI); + } + + return - (a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p)); + + }, + + Out: function (k) { + + var s; + var a = 0.1; + var p = 0.4; + + if (k === 0) { + return 0; + } + + if (k === 1) { + return 1; + } + + if (!a || a < 1) { + a = 1; + s = p / 4; + } else { + s = p * Math.asin(1 / a) / (2 * Math.PI); + } + + return (a * Math.pow(2, - 10 * k) * Math.sin((k - s) * (2 * Math.PI) / p) + 1); + + }, + + InOut: function (k) { + + var s; + var a = 0.1; + var p = 0.4; + + if (k === 0) { + return 0; + } + + if (k === 1) { + return 1; + } + + if (!a || a < 1) { + a = 1; + s = p / 4; + } else { + s = p * Math.asin(1 / a) / (2 * Math.PI); + } + + if ((k *= 2) < 1) { + return - 0.5 * (a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p)); + } + + return a * Math.pow(2, -10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1; + + } + + }, + + Back: { + + In: function (k) { + + var s = 1.70158; + + return k * k * ((s + 1) * k - s); + + }, + + Out: function (k) { + + var s = 1.70158; + + return --k * k * ((s + 1) * k + s) + 1; + + }, + + InOut: function (k) { + + var s = 1.70158 * 1.525; + + if ((k *= 2) < 1) { + return 0.5 * (k * k * ((s + 1) * k - s)); + } + + return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2); + + } + + }, + + Bounce: { + + In: function (k) { + + return 1 - TWEEN.Easing.Bounce.Out(1 - k); + + }, + + Out: function (k) { + + if (k < (1 / 2.75)) { + return 7.5625 * k * k; + } else if (k < (2 / 2.75)) { + return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75; + } else if (k < (2.5 / 2.75)) { + return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375; + } else { + return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375; + } + + }, + + InOut: function (k) { + + if (k < 0.5) { + return TWEEN.Easing.Bounce.In(k * 2) * 0.5; + } + + return TWEEN.Easing.Bounce.Out(k * 2 - 1) * 0.5 + 0.5; + + } + + } + +}; + +TWEEN.Interpolation = { + + Linear: function (v, k) { + + var m = v.length - 1; + var f = m * k; + var i = Math.floor(f); + var fn = TWEEN.Interpolation.Utils.Linear; + + if (k < 0) { + return fn(v[0], v[1], f); + } + + if (k > 1) { + return fn(v[m], v[m - 1], m - f); + } + + return fn(v[i], v[i + 1 > m ? m : i + 1], f - i); + + }, + + Bezier: function (v, k) { + + var b = 0; + var n = v.length - 1; + var pw = Math.pow; + var bn = TWEEN.Interpolation.Utils.Bernstein; + + for (var i = 0; i <= n; i++) { + b += pw(1 - k, n - i) * pw(k, i) * v[i] * bn(n, i); + } + + return b; + + }, + + CatmullRom: function (v, k) { + + var m = v.length - 1; + var f = m * k; + var i = Math.floor(f); + var fn = TWEEN.Interpolation.Utils.CatmullRom; + + if (v[0] === v[m]) { + + if (k < 0) { + i = Math.floor(f = m * (1 + k)); + } + + return fn(v[(i - 1 + m) % m], v[i], v[(i + 1) % m], v[(i + 2) % m], f - i); + + } else { + + if (k < 0) { + return v[0] - (fn(v[0], v[0], v[1], v[1], -f) - v[0]); + } + + if (k > 1) { + return v[m] - (fn(v[m], v[m], v[m - 1], v[m - 1], f - m) - v[m]); + } + + return fn(v[i ? i - 1 : 0], v[i], v[m < i + 1 ? m : i + 1], v[m < i + 2 ? m : i + 2], f - i); + + } + + }, + + Utils: { + + Linear: function (p0, p1, t) { + + return (p1 - p0) * t + p0; + + }, + + Bernstein: function (n, i) { + + var fc = TWEEN.Interpolation.Utils.Factorial; + + return fc(n) / fc(i) / fc(n - i); + + }, + + Factorial: (function () { + + var a = [1]; + + return function (n) { + + var s = 1; + + if (a[n]) { + return a[n]; + } + + for (var i = n; i > 1; i--) { + s *= i; + } + + a[n] = s; + return s; + + }; + + })(), + + CatmullRom: function (p0, p1, p2, p3, t) { + + var v0 = (p2 - p0) * 0.5; + var v1 = (p3 - p1) * 0.5; + var t2 = t * t; + var t3 = t * t2; + + return (2 * p1 - 2 * p2 + v0 + v1) * t3 + (- 3 * p1 + 3 * p2 - 2 * v0 - v1) * t2 + v0 * t + p1; + + } + + } + +}; + +// UMD (Universal Module Definition) +(function (root) { + + if (typeof define === 'function' && define.amd) { + + // AMD + define([], function () { + return TWEEN; + }); + + } else if (typeof exports === 'object') { + + // Node.js + module.exports = TWEEN; + + } else { + + // Global variable + root.TWEEN = TWEEN; + + } + +})(this); + +loadTween = function(){ + return TWEEN +} \ No newline at end of file From 1ec70e81705cd0130a8c4bcf9f7d505c7dbea505 Mon Sep 17 00:00:00 2001 From: "James B. Pollack" Date: Mon, 9 Nov 2015 19:10:11 -0800 Subject: [PATCH 15/45] add physics to the ball and make it bounce --- examples/libraries/easyStarExample.js | 64 ++++++++++++++++++++++++--- 1 file changed, 57 insertions(+), 7 deletions(-) diff --git a/examples/libraries/easyStarExample.js b/examples/libraries/easyStarExample.js index eb758a2fe3..c4368f8ff8 100644 --- a/examples/libraries/easyStarExample.js +++ b/examples/libraries/easyStarExample.js @@ -28,10 +28,12 @@ var grid = [ [0, 0, 0, 0, 0, 0, 0, 0, 0] ]; + + easystar.setGrid(grid); easystar.setAcceptableTiles([0]); - +easystar.enableCornerCutting(); easystar.findPath(0, 0, 8, 0, function(path) { if (path === null) { print("Path was not found."); @@ -67,9 +69,17 @@ var playerSphere = Entities.addEntity({ x: 0, y: 0, z: 0 - } -}) + }, + gravity: { + x: 0, + y: -9.8, + z: 0 + }, + collisionsWillMove: true, + linearDamping: 0.2 +}); +var sphereProperties; //for keeping track of entities var obstacles = []; @@ -99,13 +109,15 @@ function createPassableAtTilePosition(posX, posY) { passables.push(passable); } + + function createObstacleAtTilePosition(posX, posY) { var properties = { type: 'Box', shapeType: 'Box', dimensions: { x: 1, - y: 1, + y: 2, z: 1 }, position: { @@ -152,7 +164,6 @@ var currentSpherePosition = { function convertPathPointToCoordinates(x, y) { return { x: y, - y: 0, z: x }; } @@ -169,22 +180,44 @@ function convertPath(path) { } function updatePosition() { + sphereProperties = Entities.getEntityProperties(playerSphere, "position"); + Entities.editEntity(playerSphere, { position: { x: currentSpherePosition.z, - y: currentSpherePosition.y, + y: sphereProperties.position.y, z: currentSpherePosition.x + }, + velocity: { + x: 0, + y: velocityShaper.y, + z: 0 } }); } +var upVelocity = { + x: 0, + y: 2.5, + z: 0 +} + +var noVelocity = { + x: 0, + y: -3.5, + z: 0 +} + function createTweenPath(convertedPath) { var i; var stepTweens = []; + var velocityTweens = []; //create the tweens for (i = 0; i < convertedPath.length - 1; i++) { var stepTween = new TWEEN.Tween(currentSpherePosition).to(convertedPath[i + 1], ANIMATION_DURATION).onUpdate(updatePosition).onComplete(tweenStep); + + stepTweens.push(stepTween); } @@ -194,8 +227,25 @@ function createTweenPath(convertedPath) { stepTweens[j].chain(stepTweens[j + 1]); } - //start the tween + + var velocityUpTween = new TWEEN.Tween(velocityShaper).to(upVelocity, ANIMATION_DURATION).onUpdate(updatePosition); + var velocityDownTween = new TWEEN.Tween(velocityShaper).to(noVelocity, ANIMATION_DURATION).onUpdate(updatePosition); + + velocityUpTween.chain(velocityDownTween); + velocityDownTween.chain(velocityUpTween); + + + velocityUpTween.easing(TWEEN.Easing.Linear.None) + velocityDownTween.easing(TWEEN.Easing.Back.InOut) + //start the tween stepTweens[0].start(); + velocityUpTween.start(); +} + +var velocityShaper = { + x: 0, + y: 0, + z: 0 } function tweenStep() { From 789f3231e10dbe705e20996dcf88dc9110630e83 Mon Sep 17 00:00:00 2001 From: "James B. Pollack" Date: Mon, 9 Nov 2015 19:18:19 -0800 Subject: [PATCH 16/45] easier bouncing --- examples/libraries/easyStarExample.js | 32 ++++++++++++--------------- 1 file changed, 14 insertions(+), 18 deletions(-) diff --git a/examples/libraries/easyStarExample.js b/examples/libraries/easyStarExample.js index c4368f8ff8..20a50d2f7d 100644 --- a/examples/libraries/easyStarExample.js +++ b/examples/libraries/easyStarExample.js @@ -29,7 +29,6 @@ var grid = [ ]; - easystar.setGrid(grid); easystar.setAcceptableTiles([0]); @@ -40,6 +39,7 @@ easystar.findPath(0, 0, 8, 0, function(path) { Script.update.disconnect(tickEasyStar); } else { print('path' + JSON.stringify(path)); + convertPath(path); Script.update.disconnect(tickEasyStar); } @@ -79,6 +79,16 @@ var playerSphere = Entities.addEntity({ linearDamping: 0.2 }); +Script.setInterval(function(){ + Entities.editEntity(playerSphere,{ + velocity:{ + x:0, + y:4, + z:0 + } + }) +},1000) + var sphereProperties; //for keeping track of entities @@ -187,12 +197,8 @@ function updatePosition() { x: currentSpherePosition.z, y: sphereProperties.position.y, z: currentSpherePosition.x - }, - velocity: { - x: 0, - y: velocityShaper.y, - z: 0 } + }); } @@ -227,19 +233,9 @@ function createTweenPath(convertedPath) { stepTweens[j].chain(stepTweens[j + 1]); } - - var velocityUpTween = new TWEEN.Tween(velocityShaper).to(upVelocity, ANIMATION_DURATION).onUpdate(updatePosition); - var velocityDownTween = new TWEEN.Tween(velocityShaper).to(noVelocity, ANIMATION_DURATION).onUpdate(updatePosition); - - velocityUpTween.chain(velocityDownTween); - velocityDownTween.chain(velocityUpTween); - - - velocityUpTween.easing(TWEEN.Easing.Linear.None) - velocityDownTween.easing(TWEEN.Easing.Back.InOut) - //start the tween + //start the tween stepTweens[0].start(); - velocityUpTween.start(); + } var velocityShaper = { From e7a2e82745f7763b0175f6053665b63f21d34736 Mon Sep 17 00:00:00 2001 From: "James B. Pollack" Date: Tue, 10 Nov 2015 13:58:07 -0800 Subject: [PATCH 17/45] remove bball and targets resetter AC since we are doing this with hidden reset entities now --- .../AC_scripts/originalPositionResetter.js | 217 ------------------ 1 file changed, 217 deletions(-) delete mode 100644 examples/toybox/AC_scripts/originalPositionResetter.js diff --git a/examples/toybox/AC_scripts/originalPositionResetter.js b/examples/toybox/AC_scripts/originalPositionResetter.js deleted file mode 100644 index d3112732f7..0000000000 --- a/examples/toybox/AC_scripts/originalPositionResetter.js +++ /dev/null @@ -1,217 +0,0 @@ -// -// originalPositionResetter.js -// toybox -// -// Created by James B. Pollack @imgntn 10/16/2015 -// Copyright 2015 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// -var HIFI_PUBLIC_BUCKET = "http://s3.amazonaws.com/hifi-public/"; - -var TARGET_MODEL_URL = HIFI_PUBLIC_BUCKET + "models/ping_pong_gun/target.fbx"; -var TARGET_COLLISION_HULL_URL = HIFI_PUBLIC_BUCKET + "models/ping_pong_gun/target_collision_hull.obj"; -var TARGET_DIMENSIONS = { - x: 0.06, - y: 0.42, - z: 0.42 -}; -var TARGET_ROTATION = Quat.fromPitchYawRollDegrees(0, -55.25, 0); - -var targetsScriptURL = Script.resolvePath('../ping_pong_gun/wallTarget.js'); - - -var basketballURL = HIFI_PUBLIC_BUCKET + "models/content/basketball2.fbx"; - -var NUMBER_OF_BALLS = 4; -var BALL_DIAMETER = 0.30; -var RESET_DISTANCE = 1; -var MINIMUM_MOVE_LENGTH = 0.05; - -var totalTime = 0; -var lastUpdate = 0; -var UPDATE_INTERVAL = 1 / 5; // 5fps - -var Resetter = { - searchForEntitiesToResetToOriginalPosition: function(searchOrigin, objectName) { - var ids = Entities.findEntities(searchOrigin, 5); - var objects = []; - var i; - var entityID; - var name; - for (i = 0; i < ids.length; i++) { - entityID = ids[i]; - name = Entities.getEntityProperties(entityID, "name").name; - if (name === objectName) { - //we found an object to reset - objects.push(entityID); - } - } - return objects; - }, - deleteObjects: function(objects) { - while (objects.length > 0) { - Entities.deleteEntity(objects.pop()); - } - }, - createBasketBalls: function() { - var position = { - x: 542.86, - y: 494.84, - z: 475.06 - }; - var i; - var ballPosition; - var collidingBall; - for (i = 0; i < NUMBER_OF_BALLS; i++) { - ballPosition = { - x: position.x, - y: position.y + BALL_DIAMETER * 2, - z: position.z + (BALL_DIAMETER) - (BALL_DIAMETER * i) - }; - - collidingBall = Entities.addEntity({ - type: "Model", - name: 'Hifi-Basketball', - shapeType: 'Sphere', - position: ballPosition, - dimensions: { - x: BALL_DIAMETER, - y: BALL_DIAMETER, - z: BALL_DIAMETER - }, - restitution: 1.0, - linearDamping: 0.00001, - gravity: { - x: 0, - y: -9.8, - z: 0 - }, - collisionsWillMove: true, - ignoreForCollisions: false, - modelURL: basketballURL, - userData: JSON.stringify({ - originalPositionKey: { - originalPosition: ballPosition - }, - resetMe: { - resetMe: true - }, - grabbable: { - invertSolidWhileHeld: true - } - }) - }); - - } - }, - testBallDistanceFromStart: function(balls) { - var resetCount = 0; - balls.forEach(function(ball, index) { - var properties = Entities.getEntityProperties(ball, ["position", "userData"]); - var currentPosition = properties.position; - var originalPosition = properties.userData.originalPositionKey.originalPosition; - var distance = Vec3.subtract(originalPosition, currentPosition); - var length = Vec3.length(distance); - if (length > RESET_DISTANCE) { - Script.setTimeout(function() { - var newPosition = Entities.getEntityProperties(ball, "position").position; - var moving = Vec3.length(Vec3.subtract(currentPosition, newPosition)); - if (moving < MINIMUM_MOVE_LENGTH) { - if (resetCount === balls.length) { - this.deleteObjects(balls); - this.createBasketBalls(); - } - } - }, 200); - } - }); - }, - testTargetDistanceFromStart: function(targets) { - targets.forEach(function(target, index) { - var properties = Entities.getEntityProperties(target, ["position", "userData"]); - var currentPosition = properties.position; - var originalPosition = properties.userData.originalPositionKey.originalPosition; - var distance = Vec3.subtract(originalPosition, currentPosition); - var length = Vec3.length(distance); - if (length > RESET_DISTANCE) { - Script.setTimeout(function() { - var newPosition = Entities.getEntityProperties(target, "position").position; - var moving = Vec3.length(Vec3.subtract(currentPosition, newPosition)); - if (moving < MINIMUM_MOVE_LENGTH) { - - Entities.deleteEntity(target); - - var targetProperties = { - name: 'Hifi-Target', - type: 'Model', - modelURL: TARGET_MODEL_URL, - shapeType: 'compound', - collisionsWillMove: true, - dimensions: TARGET_DIMENSIONS, - compoundShapeURL: TARGET_COLLISION_HULL_URL, - position: originalPosition, - rotation: TARGET_ROTATION, - script: targetsScriptURL, - userData: JSON.stringify({ - resetMe: { - resetMe: true - }, - grabbableKey: { - grabbable: false - }, - originalPositionKey: originalPosition - - }) - }; - - Entities.addEntity(targetProperties); - } - }, 200); - } - - }); - - } -}; - -function update(deltaTime) { - - if (!Entities.serversExist() || !Entities.canRez()) { - return; - } - - - totalTime += deltaTime; - - // We don't want to edit the entity EVERY update cycle, because that's just a lot - // of wasted bandwidth and extra effort on the server for very little visual gain - if (totalTime - lastUpdate > UPDATE_INTERVAL) { - //do stuff - var balls = Resetter.searchForEntitiesToResetToOriginalPosition({ - x: 542.86, - y: 494.84, - z: 475.06 - }, "Hifi-Basketball"); - - var targets = Resetter.searchForEntitiesToResetToOriginalPosition({ - x: 548.68, - y: 497.30, - z: 509.74 - }, "Hifi-Target"); - - if (balls.length !== 0) { - Resetter.testBallDistanceFromStart(balls); - } - - if (targets.length !== 0) { - Resetter.testTargetDistanceFromStart(targets); - } - - lastUpdate = totalTime; - } - -} - -Script.update.connect(update); \ No newline at end of file From 006a1d60c82699612fa2d98629ba990735a3e356 Mon Sep 17 00:00:00 2001 From: Brad Hefta-Gaub Date: Tue, 10 Nov 2015 15:31:51 -0800 Subject: [PATCH 18/45] keep some additional erase entities history and send to viewers --- .../src/entities/EntityNodeData.h | 6 +- .../src/entities/EntityServer.cpp | 5 +- libraries/entities/src/EntityTree.cpp | 116 +++++++++--------- 3 files changed, 65 insertions(+), 62 deletions(-) diff --git a/assignment-client/src/entities/EntityNodeData.h b/assignment-client/src/entities/EntityNodeData.h index e4008fcb03..69da9ee14b 100644 --- a/assignment-client/src/entities/EntityNodeData.h +++ b/assignment-client/src/entities/EntityNodeData.h @@ -18,9 +18,7 @@ class EntityNodeData : public OctreeQueryNode { public: - EntityNodeData() : - OctreeQueryNode(), - _lastDeletedEntitiesSentAt(0) { } + EntityNodeData() : OctreeQueryNode() { } virtual PacketType getMyPacketType() const { return PacketType::EntityData; } @@ -28,7 +26,7 @@ public: void setLastDeletedEntitiesSentAt(quint64 sentAt) { _lastDeletedEntitiesSentAt = sentAt; } private: - quint64 _lastDeletedEntitiesSentAt; + quint64 _lastDeletedEntitiesSentAt { usecTimestampNow() }; }; #endif // hifi_EntityNodeData_h diff --git a/assignment-client/src/entities/EntityServer.cpp b/assignment-client/src/entities/EntityServer.cpp index f2a4c2664a..e2941541af 100644 --- a/assignment-client/src/entities/EntityServer.cpp +++ b/assignment-client/src/entities/EntityServer.cpp @@ -82,7 +82,6 @@ bool EntityServer::hasSpecialPacketsToSend(const SharedNodePointer& node) { EntityNodeData* nodeData = static_cast(node->getLinkedData()); if (nodeData) { quint64 deletedEntitiesSentAt = nodeData->getLastDeletedEntitiesSentAt(); - EntityTreePointer tree = std::static_pointer_cast(_tree); shouldSendDeletedEntities = tree->hasEntitiesDeletedSince(deletedEntitiesSentAt); } @@ -97,7 +96,6 @@ int EntityServer::sendSpecialPackets(const SharedNodePointer& node, OctreeQueryN if (nodeData) { quint64 deletedEntitiesSentAt = nodeData->getLastDeletedEntitiesSentAt(); quint64 deletePacketSentAt = usecTimestampNow(); - EntityTreePointer tree = std::static_pointer_cast(_tree); bool hasMoreToSend = true; @@ -127,7 +125,6 @@ void EntityServer::pruneDeletedEntities() { if (tree->hasAnyDeletedEntities()) { quint64 earliestLastDeletedEntitiesSent = usecTimestampNow() + 1; // in the future - DependencyManager::get()->eachNode([&earliestLastDeletedEntitiesSent](const SharedNodePointer& node) { if (node->getLinkedData()) { EntityNodeData* nodeData = static_cast(node->getLinkedData()); @@ -138,6 +135,8 @@ void EntityServer::pruneDeletedEntities() { } }); + int EXTRA_SECONDS_TO_KEEP = 4; + earliestLastDeletedEntitiesSent -= USECS_PER_SECOND * EXTRA_SECONDS_TO_KEEP; tree->forgetEntitiesDeletedBefore(earliestLastDeletedEntitiesSent); } } diff --git a/libraries/entities/src/EntityTree.cpp b/libraries/entities/src/EntityTree.cpp index 8e32158362..c69c2daa16 100644 --- a/libraries/entities/src/EntityTree.cpp +++ b/libraries/entities/src/EntityTree.cpp @@ -384,16 +384,17 @@ void EntityTree::deleteEntities(QSet entityIDs, bool force, bool i } void EntityTree::processRemovedEntities(const DeleteEntityOperator& theOperator) { + quint64 deletedAt = usecTimestampNow(); const RemovedEntities& entities = theOperator.getEntities(); foreach(const EntityToDeleteDetails& details, entities) { EntityItemPointer theEntity = details.entity; if (getIsServer()) { // set up the deleted entities ID - quint64 deletedAt = usecTimestampNow(); - _recentlyDeletedEntitiesLock.lockForWrite(); - _recentlyDeletedEntityItemIDs.insert(deletedAt, theEntity->getEntityItemID()); - _recentlyDeletedEntitiesLock.unlock(); + { + QWriteLocker locker(&_recentlyDeletedEntitiesLock); + _recentlyDeletedEntityItemIDs.insert(deletedAt, theEntity->getEntityItemID()); + } } if (_simulation) { @@ -802,18 +803,23 @@ void EntityTree::update() { } bool EntityTree::hasEntitiesDeletedSince(quint64 sinceTime) { + int EXTRA_SECONDS_TO_CONSIDER = 4; + quint64 considerEntitiesSince = sinceTime - (USECS_PER_SECOND * EXTRA_SECONDS_TO_CONSIDER); + // we can probably leverage the ordered nature of QMultiMap to do this quickly... bool hasSomethingNewer = false; + { + QReadLocker locker(&_recentlyDeletedEntitiesLock); - _recentlyDeletedEntitiesLock.lockForRead(); - QMultiMap::const_iterator iterator = _recentlyDeletedEntityItemIDs.constBegin(); - while (iterator != _recentlyDeletedEntityItemIDs.constEnd()) { - if (iterator.key() > sinceTime) { - hasSomethingNewer = true; + QMultiMap::const_iterator iterator = _recentlyDeletedEntityItemIDs.constBegin(); + while (iterator != _recentlyDeletedEntityItemIDs.constEnd()) { + if (iterator.key() > considerEntitiesSince) { + hasSomethingNewer = true; + } + ++iterator; } - ++iterator; } - _recentlyDeletedEntitiesLock.unlock(); + return hasSomethingNewer; } @@ -821,6 +827,8 @@ bool EntityTree::hasEntitiesDeletedSince(quint64 sinceTime) { std::unique_ptr EntityTree::encodeEntitiesDeletedSince(OCTREE_PACKET_SEQUENCE sequenceNumber, quint64& sinceTime, bool& hasMore) { + int EXTRA_SECONDS_TO_CONSIDER = 4; + quint64 considerEntitiesSince = sinceTime - (USECS_PER_SECOND * EXTRA_SECONDS_TO_CONSIDER); auto deletesPacket = NLPacket::create(PacketType::EntityErase); // pack in flags @@ -841,48 +849,46 @@ std::unique_ptr EntityTree::encodeEntitiesDeletedSince(OCTREE_PACKET_S // we keep a multi map of entity IDs to timestamps, we only want to include the entity IDs that have been // deleted since we last sent to this node - _recentlyDeletedEntitiesLock.lockForRead(); + { + QReadLocker locker(&_recentlyDeletedEntitiesLock); - bool hasFilledPacket = false; + bool hasFilledPacket = false; - auto it = _recentlyDeletedEntityItemIDs.constBegin(); - while (it != _recentlyDeletedEntityItemIDs.constEnd()) { - QList values = _recentlyDeletedEntityItemIDs.values(it.key()); - for (int valueItem = 0; valueItem < values.size(); ++valueItem) { + auto it = _recentlyDeletedEntityItemIDs.constBegin(); + while (it != _recentlyDeletedEntityItemIDs.constEnd()) { + QList values = _recentlyDeletedEntityItemIDs.values(it.key()); + for (int valueItem = 0; valueItem < values.size(); ++valueItem) { - // if the timestamp is more recent then out last sent time, include it - if (it.key() > sinceTime) { - QUuid entityID = values.at(valueItem); - deletesPacket->write(entityID.toRfc4122()); + // if the timestamp is more recent then out last sent time, include it + if (it.key() > considerEntitiesSince) { + QUuid entityID = values.at(valueItem); + deletesPacket->write(entityID.toRfc4122()); + ++numberOfIDs; - ++numberOfIDs; - - // check to make sure we have room for one more ID - if (NUM_BYTES_RFC4122_UUID > deletesPacket->bytesAvailableForWrite()) { - hasFilledPacket = true; - break; + // check to make sure we have room for one more ID + if (NUM_BYTES_RFC4122_UUID > deletesPacket->bytesAvailableForWrite()) { + hasFilledPacket = true; + break; + } } } + + // check to see if we're about to return + if (hasFilledPacket) { + // let our caller know how far we got + sinceTime = it.key(); + break; + } + + ++it; } - // check to see if we're about to return - if (hasFilledPacket) { - // let our caller know how far we got - sinceTime = it.key(); - - break; + // if we got to the end, then we're done sending + if (it == _recentlyDeletedEntityItemIDs.constEnd()) { + hasMore = false; } - - ++it; } - // if we got to the end, then we're done sending - if (it == _recentlyDeletedEntityItemIDs.constEnd()) { - hasMore = false; - } - - _recentlyDeletedEntitiesLock.unlock(); - // replace the count for the number of included IDs deletesPacket->seek(numberOfIDsPos); deletesPacket->writePrimitive(numberOfIDs); @@ -895,23 +901,23 @@ std::unique_ptr EntityTree::encodeEntitiesDeletedSince(OCTREE_PACKET_S void EntityTree::forgetEntitiesDeletedBefore(quint64 sinceTime) { QSet keysToRemove; - _recentlyDeletedEntitiesLock.lockForWrite(); - QMultiMap::iterator iterator = _recentlyDeletedEntityItemIDs.begin(); + { + QWriteLocker locker(&_recentlyDeletedEntitiesLock); + QMultiMap::iterator iterator = _recentlyDeletedEntityItemIDs.begin(); - // First find all the keys in the map that are older and need to be deleted - while (iterator != _recentlyDeletedEntityItemIDs.end()) { - if (iterator.key() <= sinceTime) { - keysToRemove << iterator.key(); + // First find all the keys in the map that are older and need to be deleted + while (iterator != _recentlyDeletedEntityItemIDs.end()) { + if (iterator.key() <= sinceTime) { + keysToRemove << iterator.key(); + } + ++iterator; } - ++iterator; - } - // Now run through the keysToRemove and remove them - foreach (quint64 value, keysToRemove) { - _recentlyDeletedEntityItemIDs.remove(value); + // Now run through the keysToRemove and remove them + foreach (quint64 value, keysToRemove) { + _recentlyDeletedEntityItemIDs.remove(value); + } } - - _recentlyDeletedEntitiesLock.unlock(); } From 3316b63bf6e8efb1c9a494dd5ce027983b76c026 Mon Sep 17 00:00:00 2001 From: Brad Hefta-Gaub Date: Tue, 10 Nov 2015 15:46:53 -0800 Subject: [PATCH 19/45] add a fixme comment --- libraries/entities/src/EntityTree.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/libraries/entities/src/EntityTree.cpp b/libraries/entities/src/EntityTree.cpp index c69c2daa16..34b09eb67c 100644 --- a/libraries/entities/src/EntityTree.cpp +++ b/libraries/entities/src/EntityTree.cpp @@ -862,6 +862,12 @@ std::unique_ptr EntityTree::encodeEntitiesDeletedSince(OCTREE_PACKET_S // if the timestamp is more recent then out last sent time, include it if (it.key() > considerEntitiesSince) { QUuid entityID = values.at(valueItem); + + // FIXME - we still seem to see cases where incorrect EntityIDs get sent from the server + // to the client. These were causing "lost" entities like flashlights and laser pointers + // now that we keep around some additional history of the erased entities and resend that + // history for a longer time window, these entities are not "lost". But we haven't yet + // found/fixed the underlying issue that caused bad UUIDs to be sent to some users. deletesPacket->write(entityID.toRfc4122()); ++numberOfIDs; From fc3602d780ff9e3b4e86fe532710dd31a9924939 Mon Sep 17 00:00:00 2001 From: Brad Hefta-Gaub Date: Tue, 10 Nov 2015 16:46:58 -0800 Subject: [PATCH 20/45] change context menu to RightPrimaryThumb, add filter to mouse click to not count slow clicks --- examples/libraries/omniTool.js | 2 +- interface/resources/controllers/standard.json | 2 +- .../src/input-plugins/KeyboardMouseDevice.cpp | 11 +++++++---- .../src/input-plugins/KeyboardMouseDevice.h | 1 + 4 files changed, 10 insertions(+), 6 deletions(-) diff --git a/examples/libraries/omniTool.js b/examples/libraries/omniTool.js index 4c995d6528..e0e5da4496 100644 --- a/examples/libraries/omniTool.js +++ b/examples/libraries/omniTool.js @@ -64,7 +64,7 @@ OmniTool = function(left) { }); this.mapping = Controller.newMapping(); - this.mapping.from(left ? standard.LeftPrimaryThumb : standard.RightPrimaryThumb).to(function(value){ + this.mapping.from(left ? standard.LeftPrimaryThumb : standard.RightSecondaryThumb).to(function(value){ that.onUpdateTrigger(value); }) this.mapping.enable(); diff --git a/interface/resources/controllers/standard.json b/interface/resources/controllers/standard.json index d4988fc00d..4833388080 100644 --- a/interface/resources/controllers/standard.json +++ b/interface/resources/controllers/standard.json @@ -33,7 +33,7 @@ { "from": "Standard.Start", "to": "Standard.RightSecondaryThumb" }, { "from": "Standard.LeftSecondaryThumb", "to": "Actions.CycleCamera" }, - { "from": "Standard.RightSecondaryThumb", "to": "Actions.ContextMenu" }, + { "from": "Standard.RightPrimaryThumb", "to": "Actions.ContextMenu" }, { "from": "Standard.LT", "to": "Actions.LeftHandClick" }, { "from": "Standard.RT", "to": "Actions.RightHandClick" }, diff --git a/libraries/input-plugins/src/input-plugins/KeyboardMouseDevice.cpp b/libraries/input-plugins/src/input-plugins/KeyboardMouseDevice.cpp index e91ea90aaf..6a08a50b13 100755 --- a/libraries/input-plugins/src/input-plugins/KeyboardMouseDevice.cpp +++ b/libraries/input-plugins/src/input-plugins/KeyboardMouseDevice.cpp @@ -16,6 +16,7 @@ #include #include +#include const QString KeyboardMouseDevice::NAME = "Keyboard/Mouse"; @@ -64,6 +65,7 @@ void KeyboardMouseDevice::mousePressEvent(QMouseEvent* event, unsigned int devic } _lastCursor = event->pos(); _mousePressAt = event->pos(); + _mousePressTime = usecTimestampNow(); eraseMouseClicked(); } @@ -72,10 +74,11 @@ void KeyboardMouseDevice::mouseReleaseEvent(QMouseEvent* event, unsigned int dev auto input = _inputDevice->makeInput((Qt::MouseButton) event->button()); _inputDevice->_buttonPressedMap.erase(input.getChannel()); - // if we pressed and released at the same location, then create a "_CLICKED" input for this button - // we might want to add some small tolerance to this so if you do a small drag it still counts as - // a clicked. - if (_mousePressAt == event->pos()) { + // if we pressed and released at the same location within a small time window, then create a "_CLICKED" + // input for this button we might want to add some small tolerance to this so if you do a small drag it + // till counts as a clicked. + static const int CLICK_TIME = USECS_PER_MSEC * 500; // 500 ms to click + if (_mousePressAt == event->pos() && (usecTimestampNow() - _mousePressTime < CLICK_TIME)) { _inputDevice->_buttonPressedMap.insert(_inputDevice->makeInput((Qt::MouseButton) event->button(), true).getChannel()); } } diff --git a/libraries/input-plugins/src/input-plugins/KeyboardMouseDevice.h b/libraries/input-plugins/src/input-plugins/KeyboardMouseDevice.h index 4abdc44478..7182424df0 100644 --- a/libraries/input-plugins/src/input-plugins/KeyboardMouseDevice.h +++ b/libraries/input-plugins/src/input-plugins/KeyboardMouseDevice.h @@ -116,6 +116,7 @@ public: protected: QPoint _lastCursor; QPoint _mousePressAt; + quint64 _mousePressTime; glm::vec2 _lastTouch; std::shared_ptr _inputDevice { std::make_shared() }; From e4b271d6d8ffe6f3e554d65f641560d7aed4364a Mon Sep 17 00:00:00 2001 From: ericrius1 Date: Tue, 10 Nov 2015 16:49:46 -0800 Subject: [PATCH 21/45] dynamic loading content from s3 --- examples/marketplace/dynamicLoader.js | 74 +++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 examples/marketplace/dynamicLoader.js diff --git a/examples/marketplace/dynamicLoader.js b/examples/marketplace/dynamicLoader.js new file mode 100644 index 0000000000..5c9c4560d8 --- /dev/null +++ b/examples/marketplace/dynamicLoader.js @@ -0,0 +1,74 @@ +var BASE_URL = "https://hifi-public.s3.amazonaws.com/"; +var models = []; +var floorPosition = Vec3.sum(MyAvatar.position, Vec3.multiply(3, Quat.getFront(Camera.getOrientation())));; +floorPosition.y = MyAvatar.position.y - 5; +var floor = Entities.addEntity({ + type: "Model", + modelURL: "https://hifi-public.s3.amazonaws.com/ozan/3d_marketplace/props/floor/3d_mp_floor.fbx", + position: floorPosition, + shapeType: 'box', + dimensions: { + x: 1000, + y: 9, + z: 1000 + } +}); + +var urls = []; +var req = new XMLHttpRequest(); +req.open("GET", "https://serene-headland-4300.herokuapp.com/?assetDir=ozan/3d_marketplace/sets", false); +// req.open("GET", "http://localhost:5000", false); +req.send(); + +var res = req.responseText; +var urls = JSON.parse(res).urls; +if (urls.length > 0) { + print("WAAAH") + // We've got an array of urls back from server- let's display them in grid + createGrid(); +} + +function createGrid() { + var fbxUrls = urls.filter(function(url) { + return url.indexOf('fbx') !== -1; + }); + print(JSON.stringify(fbxUrls)); + + var modelParams = { + type: "Model", + // dimensions: { + // x: 31.85, + // y: 7.75, + // z: 54.51 + // }, + }; + + var modelPosition = { + x: floorPosition.x + 10, + y: floorPosition.y + 8.5, + z: floorPosition.z + }; + + for (var i = 0; i < fbxUrls.length; i++) { + if(i % 2 === 0) { + modelPosition.x = floorPosition.x - 40 + } else { + modelPosition.x = floorPosition.x + 40 + } + modelPosition.z -= 30; + modelParams.position = modelPosition; + modelParams.modelURL = BASE_URL + fbxUrls[i] + var model = Entities.addEntity(modelParams); + models.push(model); + } +} + +function cleanup() { + Entities.deleteEntity(floor); + models.forEach(function(model) { + Entities.deleteEntity(model); + }); + Entities.deleteEntity(model); +} + +Script.scriptEnding.connect(cleanup); \ No newline at end of file From 0aefb8747f3c59c14138077ba25368e1b6fd6624 Mon Sep 17 00:00:00 2001 From: ericrius1 Date: Tue, 10 Nov 2015 16:55:17 -0800 Subject: [PATCH 22/45] Dynamic loading of models from specified directory --- examples/marketplace/dynamicLoader.js | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/examples/marketplace/dynamicLoader.js b/examples/marketplace/dynamicLoader.js index 5c9c4560d8..b40eaa9dba 100644 --- a/examples/marketplace/dynamicLoader.js +++ b/examples/marketplace/dynamicLoader.js @@ -17,13 +17,11 @@ var floor = Entities.addEntity({ var urls = []; var req = new XMLHttpRequest(); req.open("GET", "https://serene-headland-4300.herokuapp.com/?assetDir=ozan/3d_marketplace/sets", false); -// req.open("GET", "http://localhost:5000", false); req.send(); var res = req.responseText; var urls = JSON.parse(res).urls; if (urls.length > 0) { - print("WAAAH") // We've got an array of urls back from server- let's display them in grid createGrid(); } @@ -36,11 +34,11 @@ function createGrid() { var modelParams = { type: "Model", - // dimensions: { - // x: 31.85, - // y: 7.75, - // z: 54.51 - // }, + dimensions: { + x: 10, + y: 10, + z: 10 + }, }; var modelPosition = { @@ -61,6 +59,15 @@ function createGrid() { var model = Entities.addEntity(modelParams); models.push(model); } + + Script.setTimeout(function() { + //Until we add callbacks on model loaded, we need to set a timeout and hope model is loaded by the time + //we hit it in order to set model dimensions correctly + for(var i = 0; i < models.length; i++){ + var modelDimensions = Entities.getEntityProperties(models[i], 'naturalDimensions').naturalDimensions; + Entities.editEntity(models[i], {dimensions: modelDimensions}); + } + }, 10000); } function cleanup() { From c2fe937a5c4cc34b6b4b6f6c08ee9b4a28468769 Mon Sep 17 00:00:00 2001 From: Eric Levin Date: Tue, 10 Nov 2015 17:07:55 -0800 Subject: [PATCH 23/45] Removed logging line --- examples/marketplace/dynamicLoader.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/examples/marketplace/dynamicLoader.js b/examples/marketplace/dynamicLoader.js index b40eaa9dba..bc7f4f5fb9 100644 --- a/examples/marketplace/dynamicLoader.js +++ b/examples/marketplace/dynamicLoader.js @@ -30,7 +30,6 @@ function createGrid() { var fbxUrls = urls.filter(function(url) { return url.indexOf('fbx') !== -1; }); - print(JSON.stringify(fbxUrls)); var modelParams = { type: "Model", @@ -78,4 +77,4 @@ function cleanup() { Entities.deleteEntity(model); } -Script.scriptEnding.connect(cleanup); \ No newline at end of file +Script.scriptEnding.connect(cleanup); From 3f5cd0237d351556d0d9106e801a9d063df3e569 Mon Sep 17 00:00:00 2001 From: ericrius1 Date: Tue, 10 Nov 2015 17:29:15 -0800 Subject: [PATCH 24/45] Added header to dynamicLoader and removed files that are not ready for merging --- examples/marketplace/dynamicLoader.js | 14 ++++ examples/marketplace/marketplaceSpawner.js | 82 ---------------------- examples/marketplace/modelSwap.js | 41 ----------- 3 files changed, 14 insertions(+), 123 deletions(-) delete mode 100644 examples/marketplace/marketplaceSpawner.js delete mode 100644 examples/marketplace/modelSwap.js diff --git a/examples/marketplace/dynamicLoader.js b/examples/marketplace/dynamicLoader.js index bc7f4f5fb9..674b6e86cd 100644 --- a/examples/marketplace/dynamicLoader.js +++ b/examples/marketplace/dynamicLoader.js @@ -1,3 +1,17 @@ +// +// dynamicLoader.js +// examples +// +// Created by Eric Levin on 11/10/2015. +// Copyright 2013 High Fidelity, Inc. +// +// This is script loads models from a specified directory +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html + + + var BASE_URL = "https://hifi-public.s3.amazonaws.com/"; var models = []; var floorPosition = Vec3.sum(MyAvatar.position, Vec3.multiply(3, Quat.getFront(Camera.getOrientation())));; diff --git a/examples/marketplace/marketplaceSpawner.js b/examples/marketplace/marketplaceSpawner.js deleted file mode 100644 index 6799ed63a3..0000000000 --- a/examples/marketplace/marketplaceSpawner.js +++ /dev/null @@ -1,82 +0,0 @@ -var floorPosition = Vec3.sum(MyAvatar.position, Vec3.multiply(3, Quat.getFront(Camera.getOrientation())));; -floorPosition.y = MyAvatar.position.y - 5; - -Script.include('../libraries/utils.js'); - -var entityScriptURL = Script.resolvePath("modelSwap.js"); - -var modelsToLoad = [{ - lowURL: "https://s3.amazonaws.com/hifi-public/ozan/3d_marketplace/sets/dojo/dojo_low.fbx", - highURL: "https://s3.amazonaws.com/hifi-public/ozan/3d_marketplace/sets/dojo/dojo_hi.fbx" -}, { - lowURL: "https://s3.amazonaws.com/hifi-public/ozan/3d_marketplace/sets/tuscany/tuscany_low.fbx", - highURL: "https://s3.amazonaws.com/hifi-public/ozan/3d_marketplace/sets/tuscany/tuscany_hi.fbx" -}]; - -var models = []; - -var floor = Entities.addEntity({ - type: "Model", - modelURL: "https://hifi-public.s3.amazonaws.com/ozan/3d_marketplace/props/floor/3d_mp_floor.fbx", - position: floorPosition, - shapeType: 'box', - dimensions: { - x: 1000, - y: 9, - z: 1000 - } -}); - -//Create grid -var modelParams = { - type: "Model", - dimensions: { - x: 31.85, - y: 7.75, - z: 54.51 - }, - script: entityScriptURL, - userData: JSON.stringify({ - grabbableKey: { - wantsTrigger: true - } - }) - -}; - -var modelPosition = { - x: floorPosition.x + 10, - y: floorPosition.y + 8.5, - z: floorPosition.z - 30 -}; -for (var i = 0; i < modelsToLoad.length; i++) { - modelParams.modelURL = modelsToLoad[i].lowURL; - modelParams.position = modelPosition; - var lowModel = Entities.addEntity(modelParams); - - modelParams.modelURL = modelsToLoad[i].highURL; - modelParams.visible = false; - modelParams.dimensions = Vec3.multiply(modelParams.dimensions, 0.5); - var highModel = Entities.addEntity(modelParams); - models.push({ - low: lowModel, - high: highModel - }); - // customKey, id, data - setEntityCustomData('modelCounterpart', lowModel, {modelCounterpartId: highModel}); - setEntityCustomData('modelCounterpart', highModel, {modelCounterpartId: lowModel}); - - modelPosition.z -= 60; -} - - - -function cleanup() { - Entities.deleteEntity(floor); - models.forEach(function(model) { - Entities.deleteEntity(model.low); - Entities.deleteEntity(model.high); - }); -} - -Script.scriptEnding.connect(cleanup); \ No newline at end of file diff --git a/examples/marketplace/modelSwap.js b/examples/marketplace/modelSwap.js deleted file mode 100644 index 29dbc84e98..0000000000 --- a/examples/marketplace/modelSwap.js +++ /dev/null @@ -1,41 +0,0 @@ -// When user holds down trigger on model for enough time, the model with do a cool animation and swap out with the low or high version of it - - - -(function() { - - var _this; - ModelSwaper = function() { - _this = this; - }; - - ModelSwaper.prototype = { - - startFarTrigger: function() { - print("START TRIGGER") - - //make self invisible and make the model's counterpart visible! - var dimensions = Entities.getEntityProperties(this.entityID, "dimensions").dimensions; - Entities.editEntity(this.entityID, { - visible: false, - dimensions: Vec3.multiply(dimensions, 0.5) - }); - dimensions = Entities.getEntityProperties(this.modelCounterpartId, "dimensions").dimensions; - Entities.editEntity(this.modelCounterpartId, { - visible: true, - dimensions: Vec3.multiply(dimensions, 2) - }); - - }, - - preload: function(entityID) { - this.entityID = entityID; - var props = Entities.getEntityProperties(this.entityID, ["userData"]); - this.modelCounterpartId = JSON.parse(props.userData).modelCounterpart.modelCounterpartId; - } - - }; - - // entity scripts always need to return a newly constructed object of our type - return new ModelSwaper(); -}); \ No newline at end of file From a76385808041f4e6a3dc2b9576c242176bed9668 Mon Sep 17 00:00:00 2001 From: "Anthony J. Thibault" Date: Wed, 11 Nov 2015 11:22:05 -0800 Subject: [PATCH 25/45] Revert cache-extract This reverts these commits: * 82b26b7 Code convention fixes * 9a484ff Fixes for windows * 086b064 Dumps all urls extracted to stdout. * c002888 Added cache extractor to the tools directory --- tools/CMakeLists.txt | 3 - tools/cache-extract/CMakeLists.txt | 7 -- tools/cache-extract/src/CacheExtractApp.cpp | 130 -------------------- tools/cache-extract/src/CacheExtractApp.h | 47 ------- tools/cache-extract/src/main.cpp | 17 --- 5 files changed, 204 deletions(-) delete mode 100644 tools/cache-extract/CMakeLists.txt delete mode 100644 tools/cache-extract/src/CacheExtractApp.cpp delete mode 100644 tools/cache-extract/src/CacheExtractApp.h delete mode 100644 tools/cache-extract/src/main.cpp diff --git a/tools/CMakeLists.txt b/tools/CMakeLists.txt index 9bc7031720..2056044a4b 100644 --- a/tools/CMakeLists.txt +++ b/tools/CMakeLists.txt @@ -10,6 +10,3 @@ set_target_properties(udt-test PROPERTIES FOLDER "Tools") add_subdirectory(vhacd-util) set_target_properties(vhacd-util PROPERTIES FOLDER "Tools") - -add_subdirectory(cache-extract) -set_target_properties(cache-extract PROPERTIES FOLDER "Tools") diff --git a/tools/cache-extract/CMakeLists.txt b/tools/cache-extract/CMakeLists.txt deleted file mode 100644 index 1aaa4d9d04..0000000000 --- a/tools/cache-extract/CMakeLists.txt +++ /dev/null @@ -1,7 +0,0 @@ -set(TARGET_NAME cache-extract) - -setup_hifi_project() - -link_hifi_libraries() -copy_dlls_beside_windows_executable() - diff --git a/tools/cache-extract/src/CacheExtractApp.cpp b/tools/cache-extract/src/CacheExtractApp.cpp deleted file mode 100644 index 0cfaef3f83..0000000000 --- a/tools/cache-extract/src/CacheExtractApp.cpp +++ /dev/null @@ -1,130 +0,0 @@ -// -// CacheExtractApp.cpp -// tools/cache-extract/src -// -// Created by Anthony Thibault on 11/6/2015. -// Copyright 2015 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -#include "CacheExtractApp.h" -#include -#include -#include -#include -#include - -// extracted from qnetworkdiskcache.cpp -#define CACHE_VERSION 8 -enum { - CacheMagic = 0xe8, - CurrentCacheVersion = CACHE_VERSION -}; - -CacheExtractApp::CacheExtractApp(int& argc, char** argv) : - QCoreApplication(argc, argv) -{ - QString myDataLoc = QStandardPaths::writableLocation(QStandardPaths::DataLocation); - int lastSlash = myDataLoc.lastIndexOf("/"); - QString cachePath = myDataLoc.leftRef(lastSlash).toString() + "/" + - "High Fidelity" + "/" + "Interface" + "/" + - "data" + QString::number(CACHE_VERSION) + "/"; - - QString outputPath = myDataLoc.leftRef(lastSlash).toString() + "/" + - "High Fidelity" + "/" + "Interface" + "/" + "extracted"; - - qDebug() << "Searching cachePath = " << cachePath << "..."; - - // build list of files - QList fileList; - QDir dir(cachePath); - dir.setFilter(QDir::AllDirs | QDir::NoDotAndDotDot); - QFileInfoList list = dir.entryInfoList(); - for (int i = 0; i < list.size(); ++i) { - QFileInfo fileInfo = list.at(i); - if (fileInfo.isDir()) { - QDir subDir(fileInfo.filePath()); - subDir.setFilter(QDir::Files); - QFileInfoList subList = subDir.entryInfoList(); - for (int j = 0; j < subList.size(); ++j) { - fileList << subList.at(j).filePath(); - } - } - } - - // dump each cache file into the outputPath - for (int i = 0; i < fileList.size(); ++i) { - QByteArray contents; - MyMetaData metaData; - if (extractFile(fileList.at(i), metaData, contents)) { - QString outFileName = outputPath + metaData.url.path(); - int lastSlash = outFileName.lastIndexOf("/"); - QString outDirName = outFileName.leftRef(lastSlash).toString(); - QDir dir; - dir.mkpath(outDirName); - QFile out(outFileName); - if (out.open(QIODevice::WriteOnly)) { - out.write(contents); - out.close(); - qDebug().noquote() << metaData.url.toDisplayString(); - } - else { - qCritical() << "Error opening outputFile = " << outFileName; - } - } else { - qCritical() << "Error extracting = " << fileList.at(i); - } - } - - QMetaObject::invokeMethod(this, "quit", Qt::QueuedConnection); -} - -bool CacheExtractApp::extractFile(const QString& filePath, MyMetaData& metaData, QByteArray& data) const { - QFile f(filePath); - if (!f.open(QIODevice::ReadOnly)) { - qDebug() << "error opening " << filePath; - return false; - } - QDataStream in(&f); - // from qnetworkdiskcache.cpp QCacheItem::read() - qint32 marker, version, streamVersion; - in >> marker; - if (marker != CacheMagic) { - return false; - } - in >> version; - if (version != CurrentCacheVersion) { - return false; - } - in >> streamVersion; - if (streamVersion > in.version()) - return false; - in.setVersion(streamVersion); - - bool compressed; - in >> metaData; - in >> compressed; - if (compressed) { - QByteArray compressedData; - in >> compressedData; - QBuffer buffer; - buffer.setData(qUncompress(compressedData)); - buffer.open(QBuffer::ReadOnly); - data = buffer.readAll(); - } else { - data = f.readAll(); - } - return true; -} - -QDataStream &operator>>(QDataStream& in, MyMetaData& metaData) { - in >> metaData.url; - in >> metaData.expirationDate; - in >> metaData.lastModified; - in >> metaData.saveToDisk; - in >> metaData.attributes; - in >> metaData.rawHeaders; - return in; -} diff --git a/tools/cache-extract/src/CacheExtractApp.h b/tools/cache-extract/src/CacheExtractApp.h deleted file mode 100644 index 3b34ff891d..0000000000 --- a/tools/cache-extract/src/CacheExtractApp.h +++ /dev/null @@ -1,47 +0,0 @@ -// -// CacheExtractApp.h -// tools/cache-extract/src -// -// Created by Anthony Thibault on 11/6/2015 -// Copyright 2015 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html -// - -#ifndef hifi_CacheExtractApp_h -#define hifi_CacheExtractApp_h - -#include -#include -#include -#include -#include -#include - -// copy of QNetworkCacheMetaData -class MyMetaData { -public: - using RawHeader = QPair; - using RawHeaderList = QList; - using AttributesMap = QHash; - - QUrl url; - QDateTime expirationDate; - QDateTime lastModified; - bool saveToDisk; - AttributesMap attributes; - RawHeaderList rawHeaders; -}; - -QDataStream &operator>>(QDataStream& in, MyMetaData& metaData); - -class CacheExtractApp : public QCoreApplication { - Q_OBJECT -public: - CacheExtractApp(int& argc, char** argv); - - bool extractFile(const QString& filePath, MyMetaData& metaData, QByteArray& data) const; -}; - -#endif // hifi_CacheExtractApp_h diff --git a/tools/cache-extract/src/main.cpp b/tools/cache-extract/src/main.cpp deleted file mode 100644 index 71a364ed3e..0000000000 --- a/tools/cache-extract/src/main.cpp +++ /dev/null @@ -1,17 +0,0 @@ -// -// main.cpp -// tools/cache-extract/src -// -// Created by Anthony Thibault on 11/6/2015. -// Copyright 2015 High Fidelity, Inc. -// -// Distributed under the Apache License, Version 2.0. -// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html - -#include -#include "CacheExtractApp.h" - -int main (int argc, char** argv) { - CacheExtractApp app(argc, argv); - return app.exec(); -} From f40e46957bea804287ca1925de2df531976e90dc Mon Sep 17 00:00:00 2001 From: AlessandroSigna Date: Tue, 10 Nov 2015 17:18:34 -0800 Subject: [PATCH 26/45] handControlledHead.js added --- .../avatarcontrol/handControlledHead.js | 65 +++++++++++++++++++ 1 file changed, 65 insertions(+) create mode 100644 examples/example/avatarcontrol/handControlledHead.js diff --git a/examples/example/avatarcontrol/handControlledHead.js b/examples/example/avatarcontrol/handControlledHead.js new file mode 100644 index 0000000000..87c24e9a7e --- /dev/null +++ b/examples/example/avatarcontrol/handControlledHead.js @@ -0,0 +1,65 @@ +// handControlledHead.js + +//This script allows you to look around, driving the rotation of the avatar's head by the right hand orientation. + +const YAW_MULTIPLIER = 20000; +const PITCH_MULTIPLIER = 15000; +const EPSILON = 0.001; +var firstPress = true; +var handPreviousVerticalRotation = 0.0; +var handCurrentVerticalRotation = 0.0; +var handPreviousHorizontalRotation = 0.0; +var handCurrentHorizontalRotation = 0.0; +var rotatedHandPosition; +var rotatedTipPosition; + +function update(deltaTime) { + if(Controller.getValue(Controller.Standard.RightPrimaryThumb)){ + pitchManager(deltaTime); + }else if(!firstPress){ + firstPress = true; + } + if(firstPress && MyAvatar.headYaw){ + MyAvatar.headYaw -= MyAvatar.headYaw/10; + } + +} + +function pitchManager(deltaTime){ + + rotatedHandPosition = Vec3.multiplyQbyV(Quat.fromPitchYawRollDegrees(0, -MyAvatar.bodyYaw, 0), MyAvatar.getRightHandPosition()); + rotatedTipPosition = Vec3.multiplyQbyV(Quat.fromPitchYawRollDegrees(0, -MyAvatar.bodyYaw, 0), MyAvatar.getRightHandTipPosition()); + + handCurrentVerticalRotation = Vec3.subtract(rotatedTipPosition, rotatedHandPosition).y; + handCurrentHorizontalRotation = Vec3.subtract(rotatedTipPosition, rotatedHandPosition).x; + + var handCurrentHorizontalRotationFiltered = handCurrentHorizontalRotation; + + //to avoid yaw drift + if((handCurrentHorizontalRotation - handPreviousHorizontalRotation) < EPSILON && (handCurrentHorizontalRotation - handPreviousHorizontalRotation) > -EPSILON){ + handCurrentHorizontalRotationFiltered = handPreviousHorizontalRotation; + } + + if(firstPress){ + handPreviousVerticalRotation = handCurrentVerticalRotation; + handPreviousHorizontalRotation = handCurrentHorizontalRotation; + firstPress = false; + } + + MyAvatar.headPitch += (handCurrentVerticalRotation - handPreviousVerticalRotation)*PITCH_MULTIPLIER*deltaTime; + MyAvatar.headYaw -= (handCurrentHorizontalRotationFiltered - handPreviousHorizontalRotation)*YAW_MULTIPLIER*deltaTime; + + + handPreviousVerticalRotation = handCurrentVerticalRotation; + handPreviousHorizontalRotation = handCurrentHorizontalRotationFiltered; + + +} + +function clean(){ + MyAvatar.headYaw = 0.0; +} + + +Script.update.connect(update); +Script.scriptEnding.connect(clean); \ No newline at end of file From e4b1b54e005384e5bc072824278e1a3bb9bebb46 Mon Sep 17 00:00:00 2001 From: AlessandroSigna Date: Wed, 11 Nov 2015 12:07:54 -0800 Subject: [PATCH 27/45] added header --- .../example/avatarcontrol/handControlledHead.js | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/examples/example/avatarcontrol/handControlledHead.js b/examples/example/avatarcontrol/handControlledHead.js index 87c24e9a7e..95ad1655ab 100644 --- a/examples/example/avatarcontrol/handControlledHead.js +++ b/examples/example/avatarcontrol/handControlledHead.js @@ -1,6 +1,14 @@ -// handControlledHead.js - -//This script allows you to look around, driving the rotation of the avatar's head by the right hand orientation. +// +// handControlledHead.js +// examples +// +// Created by Alessandro Signa on 10/11/15. +// Copyright 2015 High Fidelity, Inc. +// +// This script allows you to look around, driving the rotation of the avatar's head by the right hand orientation. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html const YAW_MULTIPLIER = 20000; const PITCH_MULTIPLIER = 15000; From 866116d2855baf69b25777cde78cbafe4c66741a Mon Sep 17 00:00:00 2001 From: Brad Hefta-Gaub Date: Wed, 11 Nov 2015 12:13:47 -0800 Subject: [PATCH 28/45] more debugging --- .../src/entities/EntityServer.cpp | 11 +++- .../src/octree/OctreeSendThread.cpp | 2 +- libraries/entities/src/EntityTree.cpp | 65 +++++++++++-------- libraries/entities/src/EntityTree.h | 1 + 4 files changed, 49 insertions(+), 30 deletions(-) diff --git a/assignment-client/src/entities/EntityServer.cpp b/assignment-client/src/entities/EntityServer.cpp index e2941541af..81dabd4dcd 100644 --- a/assignment-client/src/entities/EntityServer.cpp +++ b/assignment-client/src/entities/EntityServer.cpp @@ -84,6 +84,10 @@ bool EntityServer::hasSpecialPacketsToSend(const SharedNodePointer& node) { quint64 deletedEntitiesSentAt = nodeData->getLastDeletedEntitiesSentAt(); EntityTreePointer tree = std::static_pointer_cast(_tree); shouldSendDeletedEntities = tree->hasEntitiesDeletedSince(deletedEntitiesSentAt); + if (shouldSendDeletedEntities) { + int elapsed = usecTimestampNow() - deletedEntitiesSentAt; + qDebug() << "shouldSendDeletedEntities to node:" << node->getUUID() << "deletedEntitiesSentAt:" << deletedEntitiesSentAt << "elapsed:" << elapsed; + } } return shouldSendDeletedEntities; @@ -116,6 +120,10 @@ int EntityServer::sendSpecialPackets(const SharedNodePointer& node, OctreeQueryN nodeData->setLastDeletedEntitiesSentAt(deletePacketSentAt); } + if (packetsSent > 0) { + qDebug() << "EntityServer::sendSpecialPackets() sent " << packetsSent << "special packets of " << totalBytes << " total bytes to node:" << node->getUUID(); + } + // TODO: caller is expecting a packetLength, what if we send more than one packet?? return totalBytes; } @@ -134,9 +142,6 @@ void EntityServer::pruneDeletedEntities() { } } }); - - int EXTRA_SECONDS_TO_KEEP = 4; - earliestLastDeletedEntitiesSent -= USECS_PER_SECOND * EXTRA_SECONDS_TO_KEEP; tree->forgetEntitiesDeletedBefore(earliestLastDeletedEntitiesSent); } } diff --git a/assignment-client/src/octree/OctreeSendThread.cpp b/assignment-client/src/octree/OctreeSendThread.cpp index 2696c92253..b94317050c 100644 --- a/assignment-client/src/octree/OctreeSendThread.cpp +++ b/assignment-client/src/octree/OctreeSendThread.cpp @@ -570,7 +570,7 @@ int OctreeSendThread::packetDistributor(OctreeQueryNode* nodeData, bool viewFrus } - if (somethingToSend) { + if (somethingToSend && _myServer->wantsVerboseDebug()) { qDebug() << "Hit PPS Limit, packetsSentThisInterval =" << packetsSentThisInterval << " maxPacketsPerInterval = " << maxPacketsPerInterval << " clientMaxPacketsPerInterval = " << clientMaxPacketsPerInterval; diff --git a/libraries/entities/src/EntityTree.cpp b/libraries/entities/src/EntityTree.cpp index 34b09eb67c..7f350888be 100644 --- a/libraries/entities/src/EntityTree.cpp +++ b/libraries/entities/src/EntityTree.cpp @@ -25,6 +25,7 @@ #include "RecurseOctreeToMapOperator.h" #include "LogHandler.h" +const quint64 EntityTree::DELETED_ENTITIES_EXTRA_USECS_TO_CONSIDER = USECS_PER_MSEC * 500; EntityTree::EntityTree(bool shouldReaverage) : Octree(shouldReaverage), @@ -803,21 +804,26 @@ void EntityTree::update() { } bool EntityTree::hasEntitiesDeletedSince(quint64 sinceTime) { - int EXTRA_SECONDS_TO_CONSIDER = 4; - quint64 considerEntitiesSince = sinceTime - (USECS_PER_SECOND * EXTRA_SECONDS_TO_CONSIDER); + quint64 considerEntitiesSince = sinceTime - DELETED_ENTITIES_EXTRA_USECS_TO_CONSIDER; // we can probably leverage the ordered nature of QMultiMap to do this quickly... bool hasSomethingNewer = false; - { - QReadLocker locker(&_recentlyDeletedEntitiesLock); - QMultiMap::const_iterator iterator = _recentlyDeletedEntityItemIDs.constBegin(); - while (iterator != _recentlyDeletedEntityItemIDs.constEnd()) { - if (iterator.key() > considerEntitiesSince) { - hasSomethingNewer = true; - } - ++iterator; + QReadLocker locker(&_recentlyDeletedEntitiesLock); + QMultiMap::const_iterator iterator = _recentlyDeletedEntityItemIDs.constBegin(); + while (iterator != _recentlyDeletedEntityItemIDs.constEnd()) { + if (iterator.key() > considerEntitiesSince) { + hasSomethingNewer = true; + break; // if we have at least one item, we don't need to keep searching } + ++iterator; + } + + if (hasSomethingNewer) { + int elapsed = usecTimestampNow() - considerEntitiesSince; + int difference = considerEntitiesSince - sinceTime; + qDebug() << "EntityTree::hasEntitiesDeletedSince() sinceTime:" << sinceTime + << "considerEntitiesSince:" << considerEntitiesSince << "elapsed:" << elapsed << "difference:" << difference; } return hasSomethingNewer; @@ -826,14 +832,16 @@ bool EntityTree::hasEntitiesDeletedSince(quint64 sinceTime) { // sinceTime is an in/out parameter - it will be side effected with the last time sent out std::unique_ptr EntityTree::encodeEntitiesDeletedSince(OCTREE_PACKET_SEQUENCE sequenceNumber, quint64& sinceTime, bool& hasMore) { + qDebug() << "EntityTree::encodeEntitiesDeletedSince()"; - int EXTRA_SECONDS_TO_CONSIDER = 4; - quint64 considerEntitiesSince = sinceTime - (USECS_PER_SECOND * EXTRA_SECONDS_TO_CONSIDER); + quint64 considerEntitiesSince = sinceTime - DELETED_ENTITIES_EXTRA_USECS_TO_CONSIDER; auto deletesPacket = NLPacket::create(PacketType::EntityErase); + qDebug() << " ---- at line:" << __LINE__ << " deletes packet size:" << deletesPacket->getDataSize(); // pack in flags OCTREE_PACKET_FLAGS flags = 0; deletesPacket->writePrimitive(flags); + qDebug() << " ---- at line:" << __LINE__ << " deletes packet size:" << deletesPacket->getDataSize(); // pack in sequence number deletesPacket->writePrimitive(sequenceNumber); @@ -841,11 +849,13 @@ std::unique_ptr EntityTree::encodeEntitiesDeletedSince(OCTREE_PACKET_S // pack in timestamp OCTREE_PACKET_SENT_TIME now = usecTimestampNow(); deletesPacket->writePrimitive(now); + qDebug() << " ---- at line:" << __LINE__ << " deletes packet size:" << deletesPacket->getDataSize(); // figure out where we are now and pack a temporary number of IDs uint16_t numberOfIDs = 0; qint64 numberOfIDsPos = deletesPacket->pos(); deletesPacket->writePrimitive(numberOfIDs); + qDebug() << " ---- at line:" << __LINE__ << " deletes packet size:" << deletesPacket->getDataSize(); // we keep a multi map of entity IDs to timestamps, we only want to include the entity IDs that have been // deleted since we last sent to this node @@ -869,6 +879,8 @@ std::unique_ptr EntityTree::encodeEntitiesDeletedSince(OCTREE_PACKET_S // history for a longer time window, these entities are not "lost". But we haven't yet // found/fixed the underlying issue that caused bad UUIDs to be sent to some users. deletesPacket->write(entityID.toRfc4122()); + qDebug() << "EntityTree::encodeEntitiesDeletedSince() including:" << entityID; + qDebug() << " ---- at line:" << __LINE__ << " deletes packet size:" << deletesPacket->getDataSize(); ++numberOfIDs; // check to make sure we have room for one more ID @@ -898,6 +910,9 @@ std::unique_ptr EntityTree::encodeEntitiesDeletedSince(OCTREE_PACKET_S // replace the count for the number of included IDs deletesPacket->seek(numberOfIDsPos); deletesPacket->writePrimitive(numberOfIDs); + qDebug() << " ---- at line:" << __LINE__ <<" deletes packet size:" << deletesPacket->getDataSize(); + + qDebug() << " ---- EntityTree::encodeEntitiesDeletedSince() numberOfIDs:" << numberOfIDs; return deletesPacket; } @@ -905,24 +920,22 @@ std::unique_ptr EntityTree::encodeEntitiesDeletedSince(OCTREE_PACKET_S // called by the server when it knows all nodes have been sent deleted packets void EntityTree::forgetEntitiesDeletedBefore(quint64 sinceTime) { + quint64 considerSinceTime = sinceTime - DELETED_ENTITIES_EXTRA_USECS_TO_CONSIDER; QSet keysToRemove; + QWriteLocker locker(&_recentlyDeletedEntitiesLock); + QMultiMap::iterator iterator = _recentlyDeletedEntityItemIDs.begin(); - { - QWriteLocker locker(&_recentlyDeletedEntitiesLock); - QMultiMap::iterator iterator = _recentlyDeletedEntityItemIDs.begin(); - - // First find all the keys in the map that are older and need to be deleted - while (iterator != _recentlyDeletedEntityItemIDs.end()) { - if (iterator.key() <= sinceTime) { - keysToRemove << iterator.key(); - } - ++iterator; + // First find all the keys in the map that are older and need to be deleted + while (iterator != _recentlyDeletedEntityItemIDs.end()) { + if (iterator.key() <= considerSinceTime) { + keysToRemove << iterator.key(); } + ++iterator; + } - // Now run through the keysToRemove and remove them - foreach (quint64 value, keysToRemove) { - _recentlyDeletedEntityItemIDs.remove(value); - } + // Now run through the keysToRemove and remove them + foreach (quint64 value, keysToRemove) { + _recentlyDeletedEntityItemIDs.remove(value); } } diff --git a/libraries/entities/src/EntityTree.h b/libraries/entities/src/EntityTree.h index c177840199..dd31901a4d 100644 --- a/libraries/entities/src/EntityTree.h +++ b/libraries/entities/src/EntityTree.h @@ -147,6 +147,7 @@ public: void addNewlyCreatedHook(NewlyCreatedEntityHook* hook); void removeNewlyCreatedHook(NewlyCreatedEntityHook* hook); + static const quint64 DELETED_ENTITIES_EXTRA_USECS_TO_CONSIDER; bool hasAnyDeletedEntities() const { return _recentlyDeletedEntityItemIDs.size() > 0; } bool hasEntitiesDeletedSince(quint64 sinceTime); std::unique_ptr encodeEntitiesDeletedSince(OCTREE_PACKET_SEQUENCE sequenceNumber, quint64& sinceTime, From 040bae60142ef9ed611510382cae777f64d77450 Mon Sep 17 00:00:00 2001 From: Brad Hefta-Gaub Date: Wed, 11 Nov 2015 12:31:50 -0800 Subject: [PATCH 29/45] more debugging --- libraries/entities/src/EntityTree.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/libraries/entities/src/EntityTree.cpp b/libraries/entities/src/EntityTree.cpp index 7f350888be..49d50b28ff 100644 --- a/libraries/entities/src/EntityTree.cpp +++ b/libraries/entities/src/EntityTree.cpp @@ -942,6 +942,7 @@ void EntityTree::forgetEntitiesDeletedBefore(quint64 sinceTime) { // TODO: consider consolidating processEraseMessageDetails() and processEraseMessage() int EntityTree::processEraseMessage(NLPacket& packet, const SharedNodePointer& sourceNode) { + qDebug() << "EntityTree::processEraseMessage()"; withWriteLock([&] { packet.seek(sizeof(OCTREE_PACKET_FLAGS) + sizeof(OCTREE_PACKET_SEQUENCE) + sizeof(OCTREE_PACKET_SENT_TIME)); @@ -959,6 +960,7 @@ int EntityTree::processEraseMessage(NLPacket& packet, const SharedNodePointer& s } QUuid entityID = QUuid::fromRfc4122(packet.readWithoutCopy(NUM_BYTES_RFC4122_UUID)); + qDebug() << " ---- EntityTree::processEraseMessage() contained ID:" << entityID; EntityItemID entityItemID(entityID); entityItemIDsToDelete << entityItemID; @@ -978,6 +980,7 @@ int EntityTree::processEraseMessage(NLPacket& packet, const SharedNodePointer& s // NOTE: Caller must lock the tree before calling this. // TODO: consider consolidating processEraseMessageDetails() and processEraseMessage() int EntityTree::processEraseMessageDetails(const QByteArray& dataByteArray, const SharedNodePointer& sourceNode) { + qDebug() << "EntityTree::processEraseMessageDetails()"; const unsigned char* packetData = (const unsigned char*)dataByteArray.constData(); const unsigned char* dataAt = packetData; size_t packetLength = dataByteArray.size(); @@ -1004,6 +1007,8 @@ int EntityTree::processEraseMessageDetails(const QByteArray& dataByteArray, cons dataAt += encodedID.size(); processedBytes += encodedID.size(); + qDebug() << " ---- EntityTree::processEraseMessageDetails() contains id:" << entityID; + EntityItemID entityItemID(entityID); entityItemIDsToDelete << entityItemID; From bdfe304f7aee9f8b6a8b3e6969b8146cea690aaa Mon Sep 17 00:00:00 2001 From: Brad Hefta-Gaub Date: Wed, 11 Nov 2015 14:08:15 -0800 Subject: [PATCH 30/45] remove some logging --- .../src/entities/EntityServer.cpp | 20 +++++++---- libraries/entities/src/EntityTree.cpp | 35 ++++++++++--------- 2 files changed, 32 insertions(+), 23 deletions(-) diff --git a/assignment-client/src/entities/EntityServer.cpp b/assignment-client/src/entities/EntityServer.cpp index 81dabd4dcd..493a16fea4 100644 --- a/assignment-client/src/entities/EntityServer.cpp +++ b/assignment-client/src/entities/EntityServer.cpp @@ -84,10 +84,13 @@ bool EntityServer::hasSpecialPacketsToSend(const SharedNodePointer& node) { quint64 deletedEntitiesSentAt = nodeData->getLastDeletedEntitiesSentAt(); EntityTreePointer tree = std::static_pointer_cast(_tree); shouldSendDeletedEntities = tree->hasEntitiesDeletedSince(deletedEntitiesSentAt); - if (shouldSendDeletedEntities) { - int elapsed = usecTimestampNow() - deletedEntitiesSentAt; - qDebug() << "shouldSendDeletedEntities to node:" << node->getUUID() << "deletedEntitiesSentAt:" << deletedEntitiesSentAt << "elapsed:" << elapsed; - } + + #ifdef EXTRA_ERASE_DEBUGGING + if (shouldSendDeletedEntities) { + int elapsed = usecTimestampNow() - deletedEntitiesSentAt; + qDebug() << "shouldSendDeletedEntities to node:" << node->getUUID() << "deletedEntitiesSentAt:" << deletedEntitiesSentAt << "elapsed:" << elapsed; + } + #endif } return shouldSendDeletedEntities; @@ -120,9 +123,12 @@ int EntityServer::sendSpecialPackets(const SharedNodePointer& node, OctreeQueryN nodeData->setLastDeletedEntitiesSentAt(deletePacketSentAt); } - if (packetsSent > 0) { - qDebug() << "EntityServer::sendSpecialPackets() sent " << packetsSent << "special packets of " << totalBytes << " total bytes to node:" << node->getUUID(); - } + #ifdef EXTRA_ERASE_DEBUGGING + if (packetsSent > 0) { + qDebug() << "EntityServer::sendSpecialPackets() sent " << packetsSent << "special packets of " + << totalBytes << " total bytes to node:" << node->getUUID(); + } + #endif // TODO: caller is expecting a packetLength, what if we send more than one packet?? return totalBytes; diff --git a/libraries/entities/src/EntityTree.cpp b/libraries/entities/src/EntityTree.cpp index 49d50b28ff..077bd1b76b 100644 --- a/libraries/entities/src/EntityTree.cpp +++ b/libraries/entities/src/EntityTree.cpp @@ -25,7 +25,7 @@ #include "RecurseOctreeToMapOperator.h" #include "LogHandler.h" -const quint64 EntityTree::DELETED_ENTITIES_EXTRA_USECS_TO_CONSIDER = USECS_PER_MSEC * 500; +const quint64 EntityTree::DELETED_ENTITIES_EXTRA_USECS_TO_CONSIDER = USECS_PER_MSEC * 50; EntityTree::EntityTree(bool shouldReaverage) : Octree(shouldReaverage), @@ -819,12 +819,14 @@ bool EntityTree::hasEntitiesDeletedSince(quint64 sinceTime) { ++iterator; } +#ifdef EXTRA_ERASE_DEBUGGING if (hasSomethingNewer) { int elapsed = usecTimestampNow() - considerEntitiesSince; int difference = considerEntitiesSince - sinceTime; qDebug() << "EntityTree::hasEntitiesDeletedSince() sinceTime:" << sinceTime << "considerEntitiesSince:" << considerEntitiesSince << "elapsed:" << elapsed << "difference:" << difference; } +#endif return hasSomethingNewer; } @@ -832,16 +834,12 @@ bool EntityTree::hasEntitiesDeletedSince(quint64 sinceTime) { // sinceTime is an in/out parameter - it will be side effected with the last time sent out std::unique_ptr EntityTree::encodeEntitiesDeletedSince(OCTREE_PACKET_SEQUENCE sequenceNumber, quint64& sinceTime, bool& hasMore) { - qDebug() << "EntityTree::encodeEntitiesDeletedSince()"; - quint64 considerEntitiesSince = sinceTime - DELETED_ENTITIES_EXTRA_USECS_TO_CONSIDER; auto deletesPacket = NLPacket::create(PacketType::EntityErase); - qDebug() << " ---- at line:" << __LINE__ << " deletes packet size:" << deletesPacket->getDataSize(); // pack in flags OCTREE_PACKET_FLAGS flags = 0; deletesPacket->writePrimitive(flags); - qDebug() << " ---- at line:" << __LINE__ << " deletes packet size:" << deletesPacket->getDataSize(); // pack in sequence number deletesPacket->writePrimitive(sequenceNumber); @@ -849,13 +847,11 @@ std::unique_ptr EntityTree::encodeEntitiesDeletedSince(OCTREE_PACKET_S // pack in timestamp OCTREE_PACKET_SENT_TIME now = usecTimestampNow(); deletesPacket->writePrimitive(now); - qDebug() << " ---- at line:" << __LINE__ << " deletes packet size:" << deletesPacket->getDataSize(); // figure out where we are now and pack a temporary number of IDs uint16_t numberOfIDs = 0; qint64 numberOfIDsPos = deletesPacket->pos(); deletesPacket->writePrimitive(numberOfIDs); - qDebug() << " ---- at line:" << __LINE__ << " deletes packet size:" << deletesPacket->getDataSize(); // we keep a multi map of entity IDs to timestamps, we only want to include the entity IDs that have been // deleted since we last sent to this node @@ -879,10 +875,12 @@ std::unique_ptr EntityTree::encodeEntitiesDeletedSince(OCTREE_PACKET_S // history for a longer time window, these entities are not "lost". But we haven't yet // found/fixed the underlying issue that caused bad UUIDs to be sent to some users. deletesPacket->write(entityID.toRfc4122()); - qDebug() << "EntityTree::encodeEntitiesDeletedSince() including:" << entityID; - qDebug() << " ---- at line:" << __LINE__ << " deletes packet size:" << deletesPacket->getDataSize(); ++numberOfIDs; + #ifdef EXTRA_ERASE_DEBUGGING + qDebug() << "EntityTree::encodeEntitiesDeletedSince() including:" << entityID; + #endif + // check to make sure we have room for one more ID if (NUM_BYTES_RFC4122_UUID > deletesPacket->bytesAvailableForWrite()) { hasFilledPacket = true; @@ -910,9 +908,6 @@ std::unique_ptr EntityTree::encodeEntitiesDeletedSince(OCTREE_PACKET_S // replace the count for the number of included IDs deletesPacket->seek(numberOfIDsPos); deletesPacket->writePrimitive(numberOfIDs); - qDebug() << " ---- at line:" << __LINE__ <<" deletes packet size:" << deletesPacket->getDataSize(); - - qDebug() << " ---- EntityTree::encodeEntitiesDeletedSince() numberOfIDs:" << numberOfIDs; return deletesPacket; } @@ -942,7 +937,9 @@ void EntityTree::forgetEntitiesDeletedBefore(quint64 sinceTime) { // TODO: consider consolidating processEraseMessageDetails() and processEraseMessage() int EntityTree::processEraseMessage(NLPacket& packet, const SharedNodePointer& sourceNode) { - qDebug() << "EntityTree::processEraseMessage()"; + #ifdef EXTRA_ERASE_DEBUGGING + qDebug() << "EntityTree::processEraseMessage()"; + #endif withWriteLock([&] { packet.seek(sizeof(OCTREE_PACKET_FLAGS) + sizeof(OCTREE_PACKET_SEQUENCE) + sizeof(OCTREE_PACKET_SENT_TIME)); @@ -960,7 +957,9 @@ int EntityTree::processEraseMessage(NLPacket& packet, const SharedNodePointer& s } QUuid entityID = QUuid::fromRfc4122(packet.readWithoutCopy(NUM_BYTES_RFC4122_UUID)); - qDebug() << " ---- EntityTree::processEraseMessage() contained ID:" << entityID; + #ifdef EXTRA_ERASE_DEBUGGING + qDebug() << " ---- EntityTree::processEraseMessage() contained ID:" << entityID; + #endif EntityItemID entityItemID(entityID); entityItemIDsToDelete << entityItemID; @@ -980,7 +979,9 @@ int EntityTree::processEraseMessage(NLPacket& packet, const SharedNodePointer& s // NOTE: Caller must lock the tree before calling this. // TODO: consider consolidating processEraseMessageDetails() and processEraseMessage() int EntityTree::processEraseMessageDetails(const QByteArray& dataByteArray, const SharedNodePointer& sourceNode) { - qDebug() << "EntityTree::processEraseMessageDetails()"; + #ifdef EXTRA_ERASE_DEBUGGING + qDebug() << "EntityTree::processEraseMessageDetails()"; + #endif const unsigned char* packetData = (const unsigned char*)dataByteArray.constData(); const unsigned char* dataAt = packetData; size_t packetLength = dataByteArray.size(); @@ -1007,7 +1008,9 @@ int EntityTree::processEraseMessageDetails(const QByteArray& dataByteArray, cons dataAt += encodedID.size(); processedBytes += encodedID.size(); - qDebug() << " ---- EntityTree::processEraseMessageDetails() contains id:" << entityID; + #ifdef EXTRA_ERASE_DEBUGGING + qDebug() << " ---- EntityTree::processEraseMessageDetails() contains id:" << entityID; + #endif EntityItemID entityItemID(entityID); entityItemIDsToDelete << entityItemID; From 2f903a9513f43a7e5da301a756e4eccf082359bb Mon Sep 17 00:00:00 2001 From: Brad Hefta-Gaub Date: Wed, 11 Nov 2015 14:21:14 -0800 Subject: [PATCH 31/45] CR feedback and some cleanup --- assignment-client/src/entities/EntityNodeData.h | 2 -- libraries/entities/src/EntityTree.cpp | 8 +++----- libraries/entities/src/EntityTree.h | 1 - 3 files changed, 3 insertions(+), 8 deletions(-) diff --git a/assignment-client/src/entities/EntityNodeData.h b/assignment-client/src/entities/EntityNodeData.h index 69da9ee14b..0ca0834fef 100644 --- a/assignment-client/src/entities/EntityNodeData.h +++ b/assignment-client/src/entities/EntityNodeData.h @@ -18,8 +18,6 @@ class EntityNodeData : public OctreeQueryNode { public: - EntityNodeData() : OctreeQueryNode() { } - virtual PacketType getMyPacketType() const { return PacketType::EntityData; } quint64 getLastDeletedEntitiesSentAt() const { return _lastDeletedEntitiesSentAt; } diff --git a/libraries/entities/src/EntityTree.cpp b/libraries/entities/src/EntityTree.cpp index 077bd1b76b..0174dbe39b 100644 --- a/libraries/entities/src/EntityTree.cpp +++ b/libraries/entities/src/EntityTree.cpp @@ -25,7 +25,7 @@ #include "RecurseOctreeToMapOperator.h" #include "LogHandler.h" -const quint64 EntityTree::DELETED_ENTITIES_EXTRA_USECS_TO_CONSIDER = USECS_PER_MSEC * 50; +static const quint64 DELETED_ENTITIES_EXTRA_USECS_TO_CONSIDER = USECS_PER_MSEC * 50; EntityTree::EntityTree(bool shouldReaverage) : Octree(shouldReaverage), @@ -392,10 +392,8 @@ void EntityTree::processRemovedEntities(const DeleteEntityOperator& theOperator) if (getIsServer()) { // set up the deleted entities ID - { - QWriteLocker locker(&_recentlyDeletedEntitiesLock); - _recentlyDeletedEntityItemIDs.insert(deletedAt, theEntity->getEntityItemID()); - } + QWriteLocker locker(&_recentlyDeletedEntitiesLock); + _recentlyDeletedEntityItemIDs.insert(deletedAt, theEntity->getEntityItemID()); } if (_simulation) { diff --git a/libraries/entities/src/EntityTree.h b/libraries/entities/src/EntityTree.h index dd31901a4d..c177840199 100644 --- a/libraries/entities/src/EntityTree.h +++ b/libraries/entities/src/EntityTree.h @@ -147,7 +147,6 @@ public: void addNewlyCreatedHook(NewlyCreatedEntityHook* hook); void removeNewlyCreatedHook(NewlyCreatedEntityHook* hook); - static const quint64 DELETED_ENTITIES_EXTRA_USECS_TO_CONSIDER; bool hasAnyDeletedEntities() const { return _recentlyDeletedEntityItemIDs.size() > 0; } bool hasEntitiesDeletedSince(quint64 sinceTime); std::unique_ptr encodeEntitiesDeletedSince(OCTREE_PACKET_SEQUENCE sequenceNumber, quint64& sinceTime, From 0f057d722987180d9a47c6c1373201b0e3325de8 Mon Sep 17 00:00:00 2001 From: EdgarPironti Date: Fri, 6 Nov 2015 18:58:50 -0800 Subject: [PATCH 32/45] Set clip for ControlledAC --- examples/acScripts/ControlACs.js | 29 +++++++++++++++++++++++++++-- examples/acScripts/ControlledAC.js | 16 +++++++++++++--- 2 files changed, 40 insertions(+), 5 deletions(-) diff --git a/examples/acScripts/ControlACs.js b/examples/acScripts/ControlACs.js index 403c0878cb..fb33dd3178 100644 --- a/examples/acScripts/ControlACs.js +++ b/examples/acScripts/ControlACs.js @@ -17,17 +17,21 @@ var NAMES = new Array("Craig", "Clement", "Jeff"); // ACs names ordered by IDs ( // Those variables MUST be common to every scripts var controlEntitySize = 0.25; -var controlEntityPosition = { x: 2000 , y: 0, z: 0 }; +var controlEntityPosition = { x: 0, y: 0, z: 0 }; // Script. DO NOT MODIFY BEYOND THIS LINE. Script.include("../libraries/toolBars.js"); +var filename = null; +var fileloaded = null; + var DO_NOTHING = 0; var PLAY = 1; var PLAY_LOOP = 2; var STOP = 3; var SHOW = 4; var HIDE = 5; +var LOAD = 6; var COLORS = []; COLORS[PLAY] = { red: PLAY, green: 0, blue: 0 }; @@ -35,6 +39,7 @@ COLORS[PLAY_LOOP] = { red: PLAY_LOOP, green: 0, blue: 0 }; COLORS[STOP] = { red: STOP, green: 0, blue: 0 }; COLORS[SHOW] = { red: SHOW, green: 0, blue: 0 }; COLORS[HIDE] = { red: HIDE, green: 0, blue: 0 }; +COLORS[LOAD] = { red: LOAD, green: 0, blue: 0 }; @@ -53,6 +58,7 @@ var onOffIcon = new Array(); var playIcon = new Array(); var playLoopIcon = new Array(); var stopIcon = new Array(); +var loadIcon = new Array(); setupToolBars(); @@ -104,6 +110,14 @@ function setupToolBars() { alpha: ALPHA_OFF, visible: true }, false); + + loadIcon[i] = toolBars[i].addTool({ + imageURL: TOOL_ICON_URL + "recording-upload.svg", + width: Tool.IMAGE_WIDTH, + height: Tool.IMAGE_HEIGHT, + alpha: ALPHA_OFF, + visible: true + }, false); nameOverlays.push(Overlays.addOverlay("text", { backgroundColor: { red: 0, green: 0, blue: 0 }, @@ -129,11 +143,13 @@ function sendCommand(id, action) { toolBars[id].setAlpha(ALPHA_ON, playIcon[id]); toolBars[id].setAlpha(ALPHA_ON, playLoopIcon[id]); toolBars[id].setAlpha(ALPHA_ON, stopIcon[id]); + toolBars[id].setAlpha(ALPHA_ON, loadIcon[id]); } else if (action === HIDE) { toolBars[id].selectTool(onOffIcon[id], true); toolBars[id].setAlpha(ALPHA_OFF, playIcon[id]); toolBars[id].setAlpha(ALPHA_OFF, playLoopIcon[id]); toolBars[id].setAlpha(ALPHA_OFF, stopIcon[id]); + toolBars[id].setAlpha(ALPHA_OFF, loadIcon[id]); } else if (toolBars[id].toolSelected(onOffIcon[id])) { return; } @@ -148,6 +164,7 @@ function sendCommand(id, action) { var position = { x: controlEntityPosition.x + id * controlEntitySize, y: controlEntityPosition.y, z: controlEntityPosition.z }; Entities.addEntity({ + name: filename, type: "Box", position: position, dimensions: { x: controlEntitySize, y: controlEntitySize, z: controlEntitySize }, @@ -173,6 +190,8 @@ function mousePressEvent(event) { sendCommand(i, PLAY_LOOP); } else if (stopIcon[i] === toolBars[i].clicked(clickedOverlay, false)) { sendCommand(i, STOP); + } else if (loadIcon[i] === toolBars[i].clicked(clickedOverlay, false)) { + sendCommand(i, LOAD); } else { // Check individual controls for (i = 0; i < NUM_AC; i++) { @@ -188,6 +207,12 @@ function mousePressEvent(event) { sendCommand(i, PLAY_LOOP); } else if (stopIcon[i] === toolBars[i].clicked(clickedOverlay, false)) { sendCommand(i, STOP); + } else if (loadIcon[i] === toolBars[i].clicked(clickedOverlay, false)) { + fileloaded = Window.browse("Load recording from file", ".", "Recordings (*.hfr *.rec *.HFR *.REC)"); + if (!(fileloaded === "null" || fileloaded === null || fileloaded === "")) { + filename = fileloaded; + sendCommand(i, LOAD); + } } else { } @@ -231,4 +256,4 @@ Controller.mousePressEvent.connect(mousePressEvent); Script.update.connect(update); Script.scriptEnding.connect(scriptEnding); -moveUI(); +moveUI(); \ No newline at end of file diff --git a/examples/acScripts/ControlledAC.js b/examples/acScripts/ControlledAC.js index 93c71aa1a1..25c2ae72d9 100644 --- a/examples/acScripts/ControlledAC.js +++ b/examples/acScripts/ControlledAC.js @@ -22,7 +22,7 @@ var useAvatarModel = true; var id = 0; // Set avatar model URL -Avatar.skeletonModelURL = "https://hifi-public.s3.amazonaws.com/marketplace/contents/e21c0b95-e502-4d15-8c41-ea2fc40f1125/3585ddf674869a67d31d5964f7b52de1.fst?1427169998"; +Avatar.skeletonModelURL = "https://hifi-public.s3.amazonaws.com/marketplace/contents/d029ae8d-2905-4eb7-ba46-4bd1b8cb9d73/4618d52e711fbb34df442b414da767bb.fst?1427170144"; // Set position/orientation/scale here if playFromCurrentLocation is true Avatar.position = { x:1, y: 1, z: 1 }; Avatar.orientation = Quat.fromPitchYawRollDegrees(0, 0, 0); @@ -30,7 +30,7 @@ Avatar.scale = 1.0; // Those variables MUST be common to every scripts var controlEntitySize = 0.25; -var controlEntityPosition = { x: 2000, y: 0, z: 0 }; +var controlEntityPosition = { x: 0, y: 0, z: 0 }; // Script. DO NOT MODIFY BEYOND THIS LINE. var DO_NOTHING = 0; @@ -39,6 +39,7 @@ var PLAY_LOOP = 2; var STOP = 3; var SHOW = 4; var HIDE = 5; +var LOAD = 6; var COLORS = []; COLORS[PLAY] = { red: PLAY, green: 0, blue: 0 }; @@ -46,6 +47,7 @@ COLORS[PLAY_LOOP] = { red: PLAY_LOOP, green: 0, blue: 0 }; COLORS[STOP] = { red: STOP, green: 0, blue: 0 }; COLORS[SHOW] = { red: SHOW, green: 0, blue: 0 }; COLORS[HIDE] = { red: HIDE, green: 0, blue: 0 }; +COLORS[LOAD] = { red: LOAD, green: 0, blue: 0 }; controlEntityPosition.x += id * controlEntitySize; @@ -68,7 +70,9 @@ function setupEntityViewer() { EntityViewer.queryOctree(); } -function getAction(controlEntity) { +function getAction(controlEntity) { + filename = controlEntity.name; + if (controlEntity === null || controlEntity.position.x !== controlEntityPosition.x || controlEntity.position.y !== controlEntityPosition.y || @@ -141,6 +145,12 @@ function update(event) { } Agent.isAvatar = false; break; + case LOAD: + print("Load"); + if(filename !== null) { + Avatar.loadRecording(filename); + } + break; case DO_NOTHING: break; default: From 55d386aaabc040184ae5e9450b7487b47792dc06 Mon Sep 17 00:00:00 2001 From: EdgarPironti Date: Mon, 9 Nov 2015 18:14:42 -0800 Subject: [PATCH 33/45] Fixes: Prompt and userData --- examples/acScripts/ControlACs.js | 13 +++++++------ examples/acScripts/ControlledAC.js | 10 +++++----- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/examples/acScripts/ControlACs.js b/examples/acScripts/ControlACs.js index fb33dd3178..60b72446bb 100644 --- a/examples/acScripts/ControlACs.js +++ b/examples/acScripts/ControlACs.js @@ -22,8 +22,8 @@ var controlEntityPosition = { x: 0, y: 0, z: 0 }; // Script. DO NOT MODIFY BEYOND THIS LINE. Script.include("../libraries/toolBars.js"); -var filename = null; -var fileloaded = null; +var clip_url = null; +var input_text = null; var DO_NOTHING = 0; var PLAY = 1; @@ -164,7 +164,8 @@ function sendCommand(id, action) { var position = { x: controlEntityPosition.x + id * controlEntitySize, y: controlEntityPosition.y, z: controlEntityPosition.z }; Entities.addEntity({ - name: filename, + name: "Actor Controller", + userData: clip_url, type: "Box", position: position, dimensions: { x: controlEntitySize, y: controlEntitySize, z: controlEntitySize }, @@ -208,9 +209,9 @@ function mousePressEvent(event) { } else if (stopIcon[i] === toolBars[i].clicked(clickedOverlay, false)) { sendCommand(i, STOP); } else if (loadIcon[i] === toolBars[i].clicked(clickedOverlay, false)) { - fileloaded = Window.browse("Load recording from file", ".", "Recordings (*.hfr *.rec *.HFR *.REC)"); - if (!(fileloaded === "null" || fileloaded === null || fileloaded === "")) { - filename = fileloaded; + input_text = Window.prompt("Insert the url of the clip: ",""); + if(!(input_text === "" || input_text === null)){ + clip_url = input_text; sendCommand(i, LOAD); } } else { diff --git a/examples/acScripts/ControlledAC.js b/examples/acScripts/ControlledAC.js index 25c2ae72d9..8be1172080 100644 --- a/examples/acScripts/ControlledAC.js +++ b/examples/acScripts/ControlledAC.js @@ -12,7 +12,7 @@ HIFI_PUBLIC_BUCKET = "http://s3.amazonaws.com/hifi-public/"; // Set the following variables to the values needed -var filename = "/Users/clement/Desktop/recording.hfr"; +var clip_url = "https://dl.dropboxusercontent.com/u/14127429/Clips/recording1.hfr"; var playFromCurrentLocation = true; var useDisplayName = true; var useAttachments = true; @@ -51,7 +51,7 @@ COLORS[LOAD] = { red: LOAD, green: 0, blue: 0 }; controlEntityPosition.x += id * controlEntitySize; -Avatar.loadRecording(filename); +Avatar.loadRecording(clip_url); Avatar.setPlayFromCurrentLocation(playFromCurrentLocation); Avatar.setPlayerUseDisplayName(useDisplayName); @@ -71,7 +71,7 @@ function setupEntityViewer() { } function getAction(controlEntity) { - filename = controlEntity.name; + clip_url = controlEntity.userData; if (controlEntity === null || controlEntity.position.x !== controlEntityPosition.x || @@ -147,8 +147,8 @@ function update(event) { break; case LOAD: print("Load"); - if(filename !== null) { - Avatar.loadRecording(filename); + if(clip_url !== null) { + Avatar.loadRecording(clip_url); } break; case DO_NOTHING: From da2b49a1b04a7f310ffc0001a6205c18cf439991 Mon Sep 17 00:00:00 2001 From: EdgarPironti Date: Wed, 11 Nov 2015 15:03:19 -0800 Subject: [PATCH 34/45] Remove hardcoded url --- examples/acScripts/ControlledAC.js | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/examples/acScripts/ControlledAC.js b/examples/acScripts/ControlledAC.js index 8be1172080..4eecc11136 100644 --- a/examples/acScripts/ControlledAC.js +++ b/examples/acScripts/ControlledAC.js @@ -9,10 +9,9 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // -HIFI_PUBLIC_BUCKET = "http://s3.amazonaws.com/hifi-public/"; // Set the following variables to the values needed -var clip_url = "https://dl.dropboxusercontent.com/u/14127429/Clips/recording1.hfr"; +var clip_url = null; var playFromCurrentLocation = true; var useDisplayName = true; var useAttachments = true; @@ -21,8 +20,6 @@ var useAvatarModel = true; // ID of the agent. Two agents can't have the same ID. var id = 0; -// Set avatar model URL -Avatar.skeletonModelURL = "https://hifi-public.s3.amazonaws.com/marketplace/contents/d029ae8d-2905-4eb7-ba46-4bd1b8cb9d73/4618d52e711fbb34df442b414da767bb.fst?1427170144"; // Set position/orientation/scale here if playFromCurrentLocation is true Avatar.position = { x:1, y: 1, z: 1 }; Avatar.orientation = Quat.fromPitchYawRollDegrees(0, 0, 0); From 4fc44b09294e903f22a70126db5222006efe3aba Mon Sep 17 00:00:00 2001 From: ericrius1 Date: Wed, 11 Nov 2015 15:19:36 -0800 Subject: [PATCH 35/45] Updated header summary to be more specific with how the loading works --- examples/marketplace/dynamicLoader.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/examples/marketplace/dynamicLoader.js b/examples/marketplace/dynamicLoader.js index 674b6e86cd..27f50aa9cd 100644 --- a/examples/marketplace/dynamicLoader.js +++ b/examples/marketplace/dynamicLoader.js @@ -5,7 +5,8 @@ // Created by Eric Levin on 11/10/2015. // Copyright 2013 High Fidelity, Inc. // -// This is script loads models from a specified directory +// This script is an example of a way to dynamically load and place models in a grid from a specified s3 directory on the hifi-public bucket. +// The directory can be specified by changing the query string variable on line 19 to the desired relative path. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html From 4fddc86851d4ff595e1994632efe34a8f3bdc330 Mon Sep 17 00:00:00 2001 From: Brad Hefta-Gaub Date: Wed, 11 Nov 2015 15:26:16 -0800 Subject: [PATCH 36/45] tweaks to click --- .../input-plugins/src/input-plugins/KeyboardMouseDevice.cpp | 5 +++-- .../input-plugins/src/input-plugins/KeyboardMouseDevice.h | 2 +- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/libraries/input-plugins/src/input-plugins/KeyboardMouseDevice.cpp b/libraries/input-plugins/src/input-plugins/KeyboardMouseDevice.cpp index 6a08a50b13..9a9514db1b 100755 --- a/libraries/input-plugins/src/input-plugins/KeyboardMouseDevice.cpp +++ b/libraries/input-plugins/src/input-plugins/KeyboardMouseDevice.cpp @@ -64,8 +64,8 @@ void KeyboardMouseDevice::mousePressEvent(QMouseEvent* event, unsigned int devic // key pressed again ? without catching the release event ? } _lastCursor = event->pos(); - _mousePressAt = event->pos(); _mousePressTime = usecTimestampNow(); + _mouseMoved = false; eraseMouseClicked(); } @@ -78,7 +78,7 @@ void KeyboardMouseDevice::mouseReleaseEvent(QMouseEvent* event, unsigned int dev // input for this button we might want to add some small tolerance to this so if you do a small drag it // till counts as a clicked. static const int CLICK_TIME = USECS_PER_MSEC * 500; // 500 ms to click - if (_mousePressAt == event->pos() && (usecTimestampNow() - _mousePressTime < CLICK_TIME)) { + if (!_mouseMoved && (usecTimestampNow() - _mousePressTime < CLICK_TIME)) { _inputDevice->_buttonPressedMap.insert(_inputDevice->makeInput((Qt::MouseButton) event->button(), true).getChannel()); } } @@ -100,6 +100,7 @@ void KeyboardMouseDevice::mouseMoveEvent(QMouseEvent* event, unsigned int device _inputDevice->_axisStateMap[MOUSE_AXIS_Y_NEG] = (currentMove.y() > 0 ? currentMove.y() : 0.0f); _lastCursor = currentPos; + _mouseMoved = true; eraseMouseClicked(); } diff --git a/libraries/input-plugins/src/input-plugins/KeyboardMouseDevice.h b/libraries/input-plugins/src/input-plugins/KeyboardMouseDevice.h index 7182424df0..b31c59d11a 100644 --- a/libraries/input-plugins/src/input-plugins/KeyboardMouseDevice.h +++ b/libraries/input-plugins/src/input-plugins/KeyboardMouseDevice.h @@ -115,8 +115,8 @@ public: protected: QPoint _lastCursor; - QPoint _mousePressAt; quint64 _mousePressTime; + bool _mouseMoved; glm::vec2 _lastTouch; std::shared_ptr _inputDevice { std::make_shared() }; From d36cc1556ab869f0732a04b250547814aca595cf Mon Sep 17 00:00:00 2001 From: Brad Hefta-Gaub Date: Wed, 11 Nov 2015 15:32:07 -0800 Subject: [PATCH 37/45] switch back context menu to secondary thumb --- examples/libraries/omniTool.js | 2 +- interface/resources/controllers/standard.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/libraries/omniTool.js b/examples/libraries/omniTool.js index e0e5da4496..4c995d6528 100644 --- a/examples/libraries/omniTool.js +++ b/examples/libraries/omniTool.js @@ -64,7 +64,7 @@ OmniTool = function(left) { }); this.mapping = Controller.newMapping(); - this.mapping.from(left ? standard.LeftPrimaryThumb : standard.RightSecondaryThumb).to(function(value){ + this.mapping.from(left ? standard.LeftPrimaryThumb : standard.RightPrimaryThumb).to(function(value){ that.onUpdateTrigger(value); }) this.mapping.enable(); diff --git a/interface/resources/controllers/standard.json b/interface/resources/controllers/standard.json index 4833388080..d4988fc00d 100644 --- a/interface/resources/controllers/standard.json +++ b/interface/resources/controllers/standard.json @@ -33,7 +33,7 @@ { "from": "Standard.Start", "to": "Standard.RightSecondaryThumb" }, { "from": "Standard.LeftSecondaryThumb", "to": "Actions.CycleCamera" }, - { "from": "Standard.RightPrimaryThumb", "to": "Actions.ContextMenu" }, + { "from": "Standard.RightSecondaryThumb", "to": "Actions.ContextMenu" }, { "from": "Standard.LT", "to": "Actions.LeftHandClick" }, { "from": "Standard.RT", "to": "Actions.RightHandClick" }, From 56dc9092e0ec8df78576be16b4af64dbe13aa71d Mon Sep 17 00:00:00 2001 From: ericrius1 Date: Wed, 11 Nov 2015 15:52:12 -0800 Subject: [PATCH 38/45] added s3 server --- examples/marketplace/S3Server/Procfile | 1 + examples/marketplace/S3Server/index.js | 44 ++++++++++++++++++++++ examples/marketplace/S3Server/package.json | 18 +++++++++ 3 files changed, 63 insertions(+) create mode 100644 examples/marketplace/S3Server/Procfile create mode 100644 examples/marketplace/S3Server/index.js create mode 100644 examples/marketplace/S3Server/package.json diff --git a/examples/marketplace/S3Server/Procfile b/examples/marketplace/S3Server/Procfile new file mode 100644 index 0000000000..5ec9cc2c50 --- /dev/null +++ b/examples/marketplace/S3Server/Procfile @@ -0,0 +1 @@ +web: node index.js \ No newline at end of file diff --git a/examples/marketplace/S3Server/index.js b/examples/marketplace/S3Server/index.js new file mode 100644 index 0000000000..e21adb99ad --- /dev/null +++ b/examples/marketplace/S3Server/index.js @@ -0,0 +1,44 @@ +var express = require('express'); +var app = express(); +var AWS = require('aws-sdk'); +var url = require('url'); +var querystring = require('querystring'); +var _ = require('underscore'); + +AWS.config.update({ + region: "us-east-1" +}); + +var s3 = new AWS.S3(); + +app.set('port', (process.env.PORT || 5000)); + +app.get('/', function(req, res) { + var urlParts = url.parse(req.url) + var query = querystring.parse(urlParts.query); + + var params = { + Bucket: "hifi-public", + Marker: query.assetDir, + MaxKeys: 10 + }; + s3.listObjects(params, function(err, data) { + if (err) { + console.log(err, err.stack); + res.send("ERROR") + } else { + var keys = _.pluck(data.Contents, 'Key') + res.send({ + urls: keys + }); + } + }); +}); + + +app.listen(app.get('port'), function() { + console.log('Node app is running on port', app.get('port')); +}) + + +//ozan/3d_marketplace \ No newline at end of file diff --git a/examples/marketplace/S3Server/package.json b/examples/marketplace/S3Server/package.json new file mode 100644 index 0000000000..51a77e7ff9 --- /dev/null +++ b/examples/marketplace/S3Server/package.json @@ -0,0 +1,18 @@ +{ + "name": "s3fileserver", + "version": "1.0.0", + "description": "", + "main": "index.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "author": "eric", + "license": "ISC", + "dependencies": { + "aws-sdk": "^2.2.15", + "express": "^4.13.3", + "querystring": "^0.2.0", + "underscore": "^1.8.3", + "url": "^0.11.0" + } +} \ No newline at end of file From 115b63a1178fedbd28ed98ec446b3f342d625814 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Wed, 11 Nov 2015 15:54:48 -0800 Subject: [PATCH 39/45] Simplify rotationBetween --- libraries/shared/src/GLMHelpers.cpp | 25 +------------------------ 1 file changed, 1 insertion(+), 24 deletions(-) diff --git a/libraries/shared/src/GLMHelpers.cpp b/libraries/shared/src/GLMHelpers.cpp index dc7887c9f8..b57754066b 100644 --- a/libraries/shared/src/GLMHelpers.cpp +++ b/libraries/shared/src/GLMHelpers.cpp @@ -201,30 +201,7 @@ float angleBetween(const glm::vec3& v1, const glm::vec3& v2) { // Helper function return the rotation from the first vector onto the second glm::quat rotationBetween(const glm::vec3& v1, const glm::vec3& v2) { - float angle = angleBetween(v1, v2); - if (glm::isnan(angle) || angle < EPSILON) { - return glm::quat(); - } - glm::vec3 axis; - if (angle > 179.99f * RADIANS_PER_DEGREE) { // 180 degree rotation; must use another axis - axis = glm::cross(v1, glm::vec3(1.0f, 0.0f, 0.0f)); - float axisLength = glm::length(axis); - if (axisLength < EPSILON) { // parallel to x; y will work - axis = glm::normalize(glm::cross(v1, glm::vec3(0.0f, 1.0f, 0.0f))); - } else { - axis /= axisLength; - } - } else { - axis = glm::normalize(glm::cross(v1, v2)); - // It is possible for axis to be nan even when angle is not less than EPSILON. - // For example when angle is small but not tiny but v1 and v2 and have very short lengths. - if (glm::isnan(glm::dot(axis, axis))) { - // set angle and axis to values that will generate an identity rotation - angle = 0.0f; - axis = glm::vec3(1.0f, 0.0f, 0.0f); - } - } - return glm::angleAxis(angle, axis); + return glm::quat(glm::normalize(v1), glm::normalize(v2)); } bool isPointBehindTrianglesPlane(glm::vec3 point, glm::vec3 p0, glm::vec3 p1, glm::vec3 p2) { From 806d303dcd8b245de1d2093846c6d445d97655e5 Mon Sep 17 00:00:00 2001 From: ericrius1 Date: Wed, 11 Nov 2015 15:55:32 -0800 Subject: [PATCH 40/45] Added header file --- examples/marketplace/S3Server/index.js | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/examples/marketplace/S3Server/index.js b/examples/marketplace/S3Server/index.js index e21adb99ad..ff7eac6cdf 100644 --- a/examples/marketplace/S3Server/index.js +++ b/examples/marketplace/S3Server/index.js @@ -1,3 +1,18 @@ +// +// index.js +// examples +// +// Created by Eric Levin on 11/10/2015. +// Copyright 2013 High Fidelity, Inc. +// +// This is a simple REST API that allows an interface client script to get a list of files paths from an S3 bucket. +// To change your bucket, modify line 34 to your desired bucket. +// Please refer to http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/node-configuring.html +// for instructions on how to configure the SDK to work with your bucket. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html + var express = require('express'); var app = express(); var AWS = require('aws-sdk'); @@ -40,5 +55,3 @@ app.listen(app.get('port'), function() { console.log('Node app is running on port', app.get('port')); }) - -//ozan/3d_marketplace \ No newline at end of file From e4897a8de77345e08800946c3433f3115cd32cf1 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Wed, 11 Nov 2015 15:58:27 -0800 Subject: [PATCH 41/45] Use new constants --- libraries/script-engine/src/Quat.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/libraries/script-engine/src/Quat.cpp b/libraries/script-engine/src/Quat.cpp index 14a6573415..bb74b20be0 100644 --- a/libraries/script-engine/src/Quat.cpp +++ b/libraries/script-engine/src/Quat.cpp @@ -64,15 +64,15 @@ glm::quat Quat::inverse(const glm::quat& q) { } glm::vec3 Quat::getFront(const glm::quat& orientation) { - return orientation * IDENTITY_FRONT; + return orientation * Vectors::FRONT; } glm::vec3 Quat::getRight(const glm::quat& orientation) { - return orientation * IDENTITY_RIGHT; + return orientation * Vectors::RIGHT; } glm::vec3 Quat::getUp(const glm::quat& orientation) { - return orientation * IDENTITY_UP; + return orientation * Vectors::UP; } glm::vec3 Quat::safeEulerAngles(const glm::quat& orientation) { From 80e15fb77dd12fcef55301280568b5b5902fa0ca Mon Sep 17 00:00:00 2001 From: Brad Hefta-Gaub Date: Wed, 11 Nov 2015 17:03:21 -0800 Subject: [PATCH 42/45] reduce client to server to client entity edit latency --- assignment-client/src/octree/OctreeServerConsts.h | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/assignment-client/src/octree/OctreeServerConsts.h b/assignment-client/src/octree/OctreeServerConsts.h index 02f59f3802..30b55b8786 100644 --- a/assignment-client/src/octree/OctreeServerConsts.h +++ b/assignment-client/src/octree/OctreeServerConsts.h @@ -17,8 +17,14 @@ #include const int MAX_FILENAME_LENGTH = 1024; -const int INTERVALS_PER_SECOND = 60; + +/// This is the frequency (hz) that we check the octree server for changes to determine if we need to +/// send new "scene" information to the viewers. This will directly effect how quickly edits are +/// sent down do viewers. By setting it to 90hz we allow edits happening at 90hz to be sent down +/// to viewers at a rate more closely matching the edit rate. It would probably be better to allow +/// clients to ask the server to send at a rate consistent with their current vsynch since clients +/// can't render any faster than their vsynch even if the server sent them more acurate information +const int INTERVALS_PER_SECOND = 90; const int OCTREE_SEND_INTERVAL_USECS = (1000 * 1000)/INTERVALS_PER_SECOND; -const int SENDING_TIME_TO_SPARE = 5 * 1000; // usec of sending interval to spare for sending octree elements #endif // hifi_OctreeServerConsts_h From 118d05d824935f6dfd067c41e2b31667fe6b0227 Mon Sep 17 00:00:00 2001 From: Atlante45 Date: Wed, 11 Nov 2015 17:24:50 -0800 Subject: [PATCH 43/45] Use a clearer function --- libraries/shared/src/GLMHelpers.cpp | 2 +- libraries/shared/src/GLMHelpers.h | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/libraries/shared/src/GLMHelpers.cpp b/libraries/shared/src/GLMHelpers.cpp index b57754066b..fa010a85bd 100644 --- a/libraries/shared/src/GLMHelpers.cpp +++ b/libraries/shared/src/GLMHelpers.cpp @@ -201,7 +201,7 @@ float angleBetween(const glm::vec3& v1, const glm::vec3& v2) { // Helper function return the rotation from the first vector onto the second glm::quat rotationBetween(const glm::vec3& v1, const glm::vec3& v2) { - return glm::quat(glm::normalize(v1), glm::normalize(v2)); + return glm::rotation(glm::normalize(v1), glm::normalize(v2)); } bool isPointBehindTrianglesPlane(glm::vec3 point, glm::vec3 p0, glm::vec3 p1, glm::vec3 p2) { diff --git a/libraries/shared/src/GLMHelpers.h b/libraries/shared/src/GLMHelpers.h index 9c1bbe23a4..8d3410aaf2 100644 --- a/libraries/shared/src/GLMHelpers.h +++ b/libraries/shared/src/GLMHelpers.h @@ -16,6 +16,7 @@ #include #include +#include // Bring the most commonly used GLM types into the default namespace using glm::ivec2; From f521be10fedd734003254e9beb38984884e95498 Mon Sep 17 00:00:00 2001 From: Brad Davis Date: Tue, 10 Nov 2015 10:19:53 -0800 Subject: [PATCH 44/45] Avatar recording work in progress --- assignment-client/CMakeLists.txt | 2 +- interface/src/avatar/MyAvatar.cpp | 88 +++--- interface/src/avatar/MyAvatar.h | 10 +- libraries/avatars/CMakeLists.txt | 2 +- libraries/avatars/src/AvatarData.cpp | 272 ++++++++++++++---- libraries/avatars/src/AvatarData.h | 29 +- libraries/avatars/src/HeadData.cpp | 14 +- libraries/avatars/src/HeadData.h | 2 + libraries/avatars/src/Player.cpp | 3 + libraries/avatars/src/Player.h | 4 + libraries/avatars/src/Recorder.cpp | 2 + libraries/avatars/src/Recorder.h | 5 +- libraries/avatars/src/Recording.cpp | 2 + libraries/avatars/src/Recording.h | 5 +- libraries/recording/src/recording/Clip.cpp | 2 +- libraries/recording/src/recording/Clip.h | 6 +- libraries/recording/src/recording/Deck.cpp | 115 +++++++- libraries/recording/src/recording/Deck.h | 52 +++- libraries/recording/src/recording/Forward.h | 7 + libraries/recording/src/recording/Frame.cpp | 16 +- libraries/recording/src/recording/Frame.h | 3 +- .../recording/src/recording/Recorder.cpp | 18 +- libraries/recording/src/recording/Recorder.h | 8 +- .../src/recording/impl/BufferClip.cpp | 14 +- .../recording/src/recording/impl/BufferClip.h | 6 +- .../recording/src/recording/impl/FileClip.cpp | 32 ++- .../recording/src/recording/impl/FileClip.h | 8 +- libraries/script-engine/CMakeLists.txt | 2 +- libraries/shared/src/shared/JSONHelpers.cpp | 57 ++++ libraries/shared/src/shared/JSONHelpers.h | 23 ++ .../shared/src/shared/UniformTransform.cpp | 84 ++++++ .../shared/src/shared/UniformTransform.h | 40 +++ 32 files changed, 777 insertions(+), 156 deletions(-) create mode 100644 libraries/shared/src/shared/JSONHelpers.cpp create mode 100644 libraries/shared/src/shared/JSONHelpers.h create mode 100644 libraries/shared/src/shared/UniformTransform.cpp create mode 100644 libraries/shared/src/shared/UniformTransform.h diff --git a/assignment-client/CMakeLists.txt b/assignment-client/CMakeLists.txt index 5b92dfba99..830164eb60 100644 --- a/assignment-client/CMakeLists.txt +++ b/assignment-client/CMakeLists.txt @@ -5,7 +5,7 @@ setup_hifi_project(Core Gui Network Script Quick Widgets WebSockets) # link in the shared libraries link_hifi_libraries( audio avatars octree environment gpu model fbx entities - networking animation shared script-engine embedded-webserver + networking animation recording shared script-engine embedded-webserver controllers physics ) diff --git a/interface/src/avatar/MyAvatar.cpp b/interface/src/avatar/MyAvatar.cpp index 6f60ad179c..852e1d1389 100644 --- a/interface/src/avatar/MyAvatar.cpp +++ b/interface/src/avatar/MyAvatar.cpp @@ -35,7 +35,10 @@ #include #include #include - +#include +#include +#include +#include #include "devices/Faceshift.h" @@ -77,6 +80,10 @@ const QString& DEFAULT_AVATAR_COLLISION_SOUND_URL = "https://hifi-public.s3.amaz const float MyAvatar::ZOOM_MIN = 0.5f; const float MyAvatar::ZOOM_MAX = 25.0f; const float MyAvatar::ZOOM_DEFAULT = 1.5f; +static const QString HEADER_NAME = "com.highfidelity.recording.AvatarData"; +static recording::FrameType AVATAR_FRAME_TYPE = recording::Frame::TYPE_INVALID; +static std::once_flag frameTypeRegistration; + MyAvatar::MyAvatar(RigPointer rig) : Avatar(rig), @@ -112,6 +119,19 @@ MyAvatar::MyAvatar(RigPointer rig) : _audioListenerMode(FROM_HEAD), _hmdAtRestDetector(glm::vec3(0), glm::quat()) { + using namespace recording; + + std::call_once(frameTypeRegistration, [] { + AVATAR_FRAME_TYPE = recording::Frame::registerFrameType(HEADER_NAME); + }); + + // FIXME how to deal with driving multiple avatars locally? + Frame::registerFrameHandler(AVATAR_FRAME_TYPE, [this](Frame::Pointer frame) { + qDebug() << "Playback of avatar frame length: " << frame->data.size(); + avatarStateFromFrame(frame->data, this); + }); + + for (int i = 0; i < MAX_DRIVE_KEYS; i++) { _driveKeys[i] = 0.0f; } @@ -235,14 +255,12 @@ void MyAvatar::update(float deltaTime) { simulate(deltaTime); } +extern QByteArray avatarStateToFrame(const AvatarData* _avatar); +extern void avatarStateFromFrame(const QByteArray& frameData, AvatarData* _avatar); + void MyAvatar::simulate(float deltaTime) { PerformanceTimer perfTimer("simulate"); - // Play back recording - if (_player && _player->isPlaying()) { - _player->play(); - } - if (_scale != _targetScale) { float scale = (1.0f - SMOOTHING_RATIO) * _scale + SMOOTHING_RATIO * _targetScale; setScale(scale); @@ -310,7 +328,7 @@ void MyAvatar::simulate(float deltaTime) { // Record avatars movements. if (_recorder && _recorder->isRecording()) { - _recorder->record(); + _recorder->recordFrame(AVATAR_FRAME_TYPE, avatarStateToFrame(this)); } // consider updating our billboard @@ -580,33 +598,35 @@ bool MyAvatar::isRecording() { return _recorder && _recorder->isRecording(); } -qint64 MyAvatar::recorderElapsed() { +float MyAvatar::recorderElapsed() { + if (QThread::currentThread() != thread()) { + float result; + QMetaObject::invokeMethod(this, "recorderElapsed", Qt::BlockingQueuedConnection, + Q_RETURN_ARG(float, result)); + return result; + } if (!_recorder) { return 0; } - if (QThread::currentThread() != thread()) { - qint64 result; - QMetaObject::invokeMethod(this, "recorderElapsed", Qt::BlockingQueuedConnection, - Q_RETURN_ARG(qint64, result)); - return result; - } - return _recorder->elapsed(); + return (float)_recorder->position() / MSECS_PER_SECOND; } +QMetaObject::Connection _audioClientRecorderConnection; + void MyAvatar::startRecording() { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "startRecording", Qt::BlockingQueuedConnection); return; } - if (!_recorder) { - _recorder = QSharedPointer::create(this); - } + + _recorder = std::make_shared(); // connect to AudioClient's signal so we get input audio auto audioClient = DependencyManager::get(); - connect(audioClient.data(), &AudioClient::inputReceived, _recorder.data(), - &Recorder::recordAudio, Qt::QueuedConnection); - - _recorder->startRecording(); + _audioClientRecorderConnection = connect(audioClient.data(), &AudioClient::inputReceived, [] { + // FIXME, missing audio data handling + }); + setRecordingBasis(); + _recorder->start(); } void MyAvatar::stopRecording() { @@ -618,15 +638,14 @@ void MyAvatar::stopRecording() { return; } if (_recorder) { - // stop grabbing audio from the AudioClient - auto audioClient = DependencyManager::get(); - disconnect(audioClient.data(), 0, _recorder.data(), 0); - - _recorder->stopRecording(); + QObject::disconnect(_audioClientRecorderConnection); + _audioClientRecorderConnection = QMetaObject::Connection(); + _recorder->stop(); + clearRecordingBasis(); } } -void MyAvatar::saveRecording(QString filename) { +void MyAvatar::saveRecording(const QString& filename) { if (!_recorder) { qCDebug(interfaceapp) << "There is no recording to save"; return; @@ -636,8 +655,10 @@ void MyAvatar::saveRecording(QString filename) { Q_ARG(QString, filename)); return; } + if (_recorder) { - _recorder->saveToFile(filename); + auto clip = _recorder->getClip(); + recording::Clip::toFile(filename, clip); } } @@ -646,15 +667,18 @@ void MyAvatar::loadLastRecording() { QMetaObject::invokeMethod(this, "loadLastRecording", Qt::BlockingQueuedConnection); return; } - if (!_recorder) { + + if (!_recorder || !_recorder->getClip()) { qCDebug(interfaceapp) << "There is no recording to load"; return; } + if (!_player) { - _player = QSharedPointer::create(this); + _player = std::make_shared(); } - _player->loadRecording(_recorder->getRecording()); + _player->queueClip(_recorder->getClip()); + _player->play(); } void MyAvatar::startAnimation(const QString& url, float fps, float priority, diff --git a/interface/src/avatar/MyAvatar.h b/interface/src/avatar/MyAvatar.h index da836b7f15..52f1ffce3f 100644 --- a/interface/src/avatar/MyAvatar.h +++ b/interface/src/avatar/MyAvatar.h @@ -257,10 +257,10 @@ public slots: bool setJointReferential(const QUuid& id, int jointIndex); bool isRecording(); - qint64 recorderElapsed(); + float recorderElapsed(); void startRecording(); void stopRecording(); - void saveRecording(QString filename); + void saveRecording(const QString& filename); void loadLastRecording(); virtual void rebuildSkeletonBody() override; @@ -311,8 +311,8 @@ private: const glm::vec3& translation = glm::vec3(), const glm::quat& rotation = glm::quat(), float scale = 1.0f, bool allowDuplicates = false, bool useSaved = true) override; - const RecorderPointer getRecorder() const { return _recorder; } - const PlayerPointer getPlayer() const { return _player; } + const recording::RecorderPointer getRecorder() const { return _recorder; } + const recording::DeckPointer getPlayer() const { return _player; } //void beginFollowingHMD(); //bool shouldFollowHMD() const; @@ -360,7 +360,7 @@ private: eyeContactTarget _eyeContactTarget; - RecorderPointer _recorder; + recording::RecorderPointer _recorder; glm::vec3 _trackedHeadPosition; diff --git a/libraries/avatars/CMakeLists.txt b/libraries/avatars/CMakeLists.txt index 849828bbf6..6d4d9cc341 100644 --- a/libraries/avatars/CMakeLists.txt +++ b/libraries/avatars/CMakeLists.txt @@ -1,3 +1,3 @@ set(TARGET_NAME avatars) setup_hifi_library(Network Script) -link_hifi_libraries(audio shared networking) +link_hifi_libraries(audio shared networking recording) diff --git a/libraries/avatars/src/AvatarData.cpp b/libraries/avatars/src/AvatarData.cpp index a698c6f374..c4e356d402 100644 --- a/libraries/avatars/src/AvatarData.cpp +++ b/libraries/avatars/src/AvatarData.cpp @@ -16,6 +16,9 @@ #include #include #include +#include +#include +#include #include #include @@ -25,6 +28,10 @@ #include #include #include +#include +#include +#include +#include #include "AvatarLogging.h" #include "AvatarData.h" @@ -62,7 +69,6 @@ AvatarData::AvatarData() : _targetVelocity(0.0f), _localAABox(DEFAULT_LOCAL_AABOX_CORNER, DEFAULT_LOCAL_AABOX_SCALE) { - } AvatarData::~AvatarData() { @@ -791,7 +797,7 @@ bool AvatarData::isPaused() { return _player && _player->isPaused(); } -qint64 AvatarData::playerElapsed() { +float AvatarData::playerElapsed() { if (!_player) { return 0; } @@ -801,10 +807,10 @@ qint64 AvatarData::playerElapsed() { Q_RETURN_ARG(qint64, result)); return result; } - return _player->elapsed(); + return (float)_player->position() / MSECS_PER_SECOND; } -qint64 AvatarData::playerLength() { +float AvatarData::playerLength() { if (!_player) { return 0; } @@ -814,28 +820,24 @@ qint64 AvatarData::playerLength() { Q_RETURN_ARG(qint64, result)); return result; } - return _player->getRecording()->getLength(); + return _player->length() / MSECS_PER_SECOND; } -int AvatarData::playerCurrentFrame() { - return (_player) ? _player->getCurrentFrame() : 0; -} - -int AvatarData::playerFrameNumber() { - return (_player && _player->getRecording()) ? _player->getRecording()->getFrameNumber() : 0; -} - -void AvatarData::loadRecording(QString filename) { +void AvatarData::loadRecording(const QString& filename) { if (QThread::currentThread() != thread()) { QMetaObject::invokeMethod(this, "loadRecording", Qt::BlockingQueuedConnection, Q_ARG(QString, filename)); return; } - if (!_player) { - _player = QSharedPointer::create(this); + using namespace recording; + + ClipPointer clip = Clip::fromFile(filename); + if (!clip) { + qWarning() << "Unable to load clip data from " << filename; } - _player->loadFromFile(filename); + _player = std::make_shared(); + _player->queueClip(clip); } void AvatarData::startPlaying() { @@ -843,70 +845,56 @@ void AvatarData::startPlaying() { QMetaObject::invokeMethod(this, "startPlaying", Qt::BlockingQueuedConnection); return; } + if (!_player) { - _player = QSharedPointer::create(this); + qWarning() << "No clip loaded for playback"; + return; } - _player->startPlaying(); + setRecordingBasis(); + _player->play(); } void AvatarData::setPlayerVolume(float volume) { - if (_player) { - _player->setVolume(volume); - } + // FIXME } -void AvatarData::setPlayerAudioOffset(int audioOffset) { - if (_player) { - _player->setAudioOffset(audioOffset); - } +void AvatarData::setPlayerAudioOffset(float audioOffset) { + // FIXME } -void AvatarData::setPlayerFrame(unsigned int frame) { - if (_player) { - _player->setCurrentFrame(frame); - } -} +void AvatarData::setPlayerTime(float time) { + if (!_player) { + qWarning() << "No player active"; + return; + } -void AvatarData::setPlayerTime(unsigned int time) { - if (_player) { - _player->setCurrentTime(time); - } + _player->seek(time * MSECS_PER_SECOND); } void AvatarData::setPlayFromCurrentLocation(bool playFromCurrentLocation) { - if (_player) { - _player->setPlayFromCurrentLocation(playFromCurrentLocation); - } + // FIXME } void AvatarData::setPlayerLoop(bool loop) { if (_player) { - _player->setLoop(loop); + _player->loop(loop); } } void AvatarData::setPlayerUseDisplayName(bool useDisplayName) { - if(_player) { - _player->useDisplayName(useDisplayName); - } + // FIXME } void AvatarData::setPlayerUseAttachments(bool useAttachments) { - if(_player) { - _player->useAttachements(useAttachments); - } + // FIXME } void AvatarData::setPlayerUseHeadModel(bool useHeadModel) { - if(_player) { - _player->useHeadModel(useHeadModel); - } + // FIXME } void AvatarData::setPlayerUseSkeletonModel(bool useSkeletonModel) { - if(_player) { - _player->useSkeletonModel(useSkeletonModel); - } + // FIXME } void AvatarData::play() { @@ -920,6 +908,10 @@ void AvatarData::play() { } } +std::shared_ptr AvatarData::getRecordingBasis() const { + return _recordingBasis; +} + void AvatarData::pausePlayer() { if (!_player) { return; @@ -929,7 +921,7 @@ void AvatarData::pausePlayer() { return; } if (_player) { - _player->pausePlayer(); + _player->pause(); } } @@ -942,7 +934,7 @@ void AvatarData::stopPlaying() { return; } if (_player) { - _player->stopPlaying(); + _player->stop(); } } @@ -1514,3 +1506,177 @@ void registerAvatarTypes(QScriptEngine* engine) { new AttachmentDataObject(), QScriptEngine::ScriptOwnership)); } +void AvatarData::setRecordingBasis(std::shared_ptr recordingBasis) { + if (!recordingBasis) { + recordingBasis = std::make_shared(); + recordingBasis->rotation = getOrientation(); + recordingBasis->translation = getPosition(); + recordingBasis->scale = getTargetScale(); + } + _recordingBasis = recordingBasis; +} + +void AvatarData::clearRecordingBasis() { + _recordingBasis.reset(); +} + +static const QString JSON_AVATAR_BASIS = QStringLiteral("basisTransform"); +static const QString JSON_AVATAR_RELATIVE = QStringLiteral("relativeTransform"); +static const QString JSON_AVATAR_JOINT_ROTATIONS = QStringLiteral("jointRotations"); +static const QString JSON_AVATAR_HEAD = QStringLiteral("head"); +static const QString JSON_AVATAR_HEAD_ROTATION = QStringLiteral("rotation"); +static const QString JSON_AVATAR_HEAD_BLENDSHAPE_COEFFICIENTS = QStringLiteral("blendShapes"); +static const QString JSON_AVATAR_HEAD_LEAN_FORWARD = QStringLiteral("leanForward"); +static const QString JSON_AVATAR_HEAD_LEAN_SIDEWAYS = QStringLiteral("leanSideways"); +static const QString JSON_AVATAR_HEAD_LOOKAT = QStringLiteral("lookAt"); +static const QString JSON_AVATAR_HEAD_MODEL = QStringLiteral("headModel"); +static const QString JSON_AVATAR_BODY_MODEL = QStringLiteral("bodyModel"); +static const QString JSON_AVATAR_DISPLAY_NAME = QStringLiteral("displayName"); +static const QString JSON_AVATAR_ATTACHEMENTS = QStringLiteral("attachments"); + + +// Every frame will store both a basis for the recording and a relative transform +// This allows the application to decide whether playback should be relative to an avatar's +// transform at the start of playback, or relative to the transform of the recorded +// avatar +QByteArray avatarStateToFrame(const AvatarData* _avatar) { + QJsonObject root; + + if (!_avatar->getFaceModelURL().isEmpty()) { + root[JSON_AVATAR_HEAD_MODEL] = _avatar->getFaceModelURL().toString(); + } + if (!_avatar->getSkeletonModelURL().isEmpty()) { + root[JSON_AVATAR_BODY_MODEL] = _avatar->getSkeletonModelURL().toString(); + } + if (!_avatar->getDisplayName().isEmpty()) { + root[JSON_AVATAR_DISPLAY_NAME] = _avatar->getDisplayName(); + } + if (!_avatar->getAttachmentData().isEmpty()) { + // FIXME serialize attachment data + } + + auto recordingBasis = _avatar->getRecordingBasis(); + if (recordingBasis) { + // FIXME if the resulting relative basis is identity, we shouldn't record anything + // Record the transformation basis + root[JSON_AVATAR_BASIS] = recordingBasis->toJson(); + + // Record the relative transform + auto relativeTransform = recordingBasis->relativeTransform( + UniformTransform(_avatar->getPosition(), _avatar->getOrientation(), _avatar->getTargetScale())); + + root[JSON_AVATAR_RELATIVE] = relativeTransform.toJson(); + } + + QJsonArray jointRotations; + for (const auto& jointRotation : _avatar->getJointRotations()) { + jointRotations.push_back(toJsonValue(jointRotation)); + } + root[JSON_AVATAR_JOINT_ROTATIONS] = jointRotations; + + const HeadData* head = _avatar->getHeadData(); + if (head) { + QJsonObject headJson; + QJsonArray blendshapeCoefficients; + for (const auto& blendshapeCoefficient : head->getBlendshapeCoefficients()) { + blendshapeCoefficients.push_back(blendshapeCoefficient); + } + headJson[JSON_AVATAR_HEAD_BLENDSHAPE_COEFFICIENTS] = blendshapeCoefficients; + headJson[JSON_AVATAR_HEAD_ROTATION] = toJsonValue(head->getRawOrientation()); + headJson[JSON_AVATAR_HEAD_LEAN_FORWARD] = QJsonValue(head->getLeanForward()); + headJson[JSON_AVATAR_HEAD_LEAN_SIDEWAYS] = QJsonValue(head->getLeanSideways()); + vec3 relativeLookAt = glm::inverse(_avatar->getOrientation()) * + (head->getLookAtPosition() - _avatar->getPosition()); + headJson[JSON_AVATAR_HEAD_LOOKAT] = toJsonValue(relativeLookAt); + root[JSON_AVATAR_HEAD] = headJson; + } + + return QJsonDocument(root).toBinaryData(); +} + +void avatarStateFromFrame(const QByteArray& frameData, AvatarData* _avatar) { + QJsonDocument doc = QJsonDocument::fromBinaryData(frameData); + QJsonObject root = doc.object(); + + if (root.contains(JSON_AVATAR_HEAD_MODEL)) { + auto faceModelURL = root[JSON_AVATAR_HEAD_MODEL].toString(); + if (faceModelURL != _avatar->getFaceModelURL().toString()) { + _avatar->setFaceModelURL(faceModelURL); + } + } + if (root.contains(JSON_AVATAR_BODY_MODEL)) { + auto bodyModelURL = root[JSON_AVATAR_BODY_MODEL].toString(); + if (bodyModelURL != _avatar->getSkeletonModelURL().toString()) { + _avatar->setSkeletonModelURL(bodyModelURL); + } + } + if (root.contains(JSON_AVATAR_DISPLAY_NAME)) { + auto newDisplayName = root[JSON_AVATAR_DISPLAY_NAME].toString(); + if (newDisplayName != _avatar->getDisplayName()) { + _avatar->setDisplayName(newDisplayName); + } + } + + // During playback you can either have the recording basis set to the avatar current state + // meaning that all playback is relative to this avatars starting position, or + // the basis can be loaded from the recording, meaning the playback is relative to the + // original avatar location + // The first is more useful for playing back recordings on your own avatar, while + // the latter is more useful for playing back other avatars within your scene. + auto currentBasis = _avatar->getRecordingBasis(); + if (!currentBasis) { + currentBasis = UniformTransform::parseJson(root[JSON_AVATAR_BASIS]); + } + + auto relativeTransform = UniformTransform::parseJson(root[JSON_AVATAR_RELATIVE]); + auto worldTransform = currentBasis->worldTransform(*relativeTransform); + _avatar->setPosition(worldTransform.translation); + _avatar->setOrientation(worldTransform.rotation); + _avatar->setTargetScale(worldTransform.scale); + +#if 0 + if (root.contains(JSON_AVATAR_ATTACHEMENTS)) { + // FIXME de-serialize attachment data + } + + // Joint rotations are relative to the avatar, so they require no basis correction + if (root.contains(JSON_AVATAR_JOINT_ROTATIONS)) { + QVector jointRotations; + QJsonArray jointRotationsJson = root[JSON_AVATAR_JOINT_ROTATIONS].toArray(); + jointRotations.reserve(jointRotationsJson.size()); + for (const auto& jointRotationJson : jointRotationsJson) { + jointRotations.push_back(quatFromJsonValue(jointRotationJson)); + } + } + + // Most head data is relative to the avatar, and needs no basis correction, + // but the lookat vector does need correction + HeadData* head = _avatar->_headData; + if (head && root.contains(JSON_AVATAR_HEAD)) { + QJsonObject headJson = root[JSON_AVATAR_HEAD].toObject(); + if (headJson.contains(JSON_AVATAR_HEAD_BLENDSHAPE_COEFFICIENTS)) { + QVector blendshapeCoefficients; + QJsonArray blendshapeCoefficientsJson = headJson[JSON_AVATAR_HEAD_BLENDSHAPE_COEFFICIENTS].toArray(); + for (const auto& blendshapeCoefficient : blendshapeCoefficientsJson) { + blendshapeCoefficients.push_back((float)blendshapeCoefficient.toDouble()); + } + head->setBlendshapeCoefficients(blendshapeCoefficients); + } + if (headJson.contains(JSON_AVATAR_HEAD_ROTATION)) { + head->setOrientation(quatFromJsonValue(headJson[JSON_AVATAR_HEAD_ROTATION])); + } + if (headJson.contains(JSON_AVATAR_HEAD_LEAN_FORWARD)) { + head->setLeanForward((float)headJson[JSON_AVATAR_HEAD_LEAN_FORWARD].toDouble()); + } + if (headJson.contains(JSON_AVATAR_HEAD_LEAN_SIDEWAYS)) { + head->setLeanSideways((float)headJson[JSON_AVATAR_HEAD_LEAN_SIDEWAYS].toDouble()); + } + if (headJson.contains(JSON_AVATAR_HEAD_LOOKAT)) { + auto relativeLookAt = vec3FromJsonValue(headJson[JSON_AVATAR_HEAD_LOOKAT]); + if (glm::length2(relativeLookAt) > 0.01) { + head->setLookAtPosition((_avatar->getOrientation() * relativeLookAt) + _avatar->getPosition()); + } + } + } +#endif +} diff --git a/libraries/avatars/src/AvatarData.h b/libraries/avatars/src/AvatarData.h index 9079f15f53..ebb6e1a78f 100644 --- a/libraries/avatars/src/AvatarData.h +++ b/libraries/avatars/src/AvatarData.h @@ -134,6 +134,7 @@ class QDataStream; class AttachmentData; class JointData; +struct UniformTransform; class AvatarData : public QObject { Q_OBJECT @@ -332,6 +333,11 @@ public: bool shouldDie() const { return _owningAvatarMixer.isNull() || getUsecsSinceLastUpdate() > AVATAR_SILENCE_THRESHOLD_USECS; } + void clearRecordingBasis(); + std::shared_ptr getRecordingBasis() const; + void setRecordingBasis(std::shared_ptr recordingBasis = std::shared_ptr()); + + public slots: void sendAvatarDataPacket(); void sendIdentityPacket(); @@ -344,17 +350,13 @@ public slots: bool isPlaying(); bool isPaused(); - qint64 playerElapsed(); - qint64 playerLength(); - int playerCurrentFrame(); - int playerFrameNumber(); - - void loadRecording(QString filename); + float playerElapsed(); + float playerLength(); + void loadRecording(const QString& filename); void startPlaying(); void setPlayerVolume(float volume); - void setPlayerAudioOffset(int audioOffset); - void setPlayerFrame(unsigned int frame); - void setPlayerTime(unsigned int time); + void setPlayerAudioOffset(float audioOffset); + void setPlayerTime(float time); void setPlayFromCurrentLocation(bool playFromCurrentLocation); void setPlayerLoop(bool loop); void setPlayerUseDisplayName(bool useDisplayName); @@ -364,7 +366,7 @@ public slots: void play(); void pausePlayer(); void stopPlaying(); - + protected: QUuid _sessionUUID; glm::vec3 _position = START_LOCATION; @@ -418,7 +420,7 @@ protected: QWeakPointer _owningAvatarMixer; - PlayerPointer _player; + recording::DeckPointer _player; /// Loads the joint indices, names from the FST file (if any) virtual void updateJointMappings(); @@ -432,8 +434,13 @@ protected: SimpleMovingAverage _averageBytesReceived; QMutex avatarLock; // Name is redundant, but it aids searches. + + // During recording, this holds the starting position, orientation & scale of the recorded avatar + // During playback, it holds the + std::shared_ptr _recordingBasis; private: + friend void avatarStateFromFrame(const QByteArray& frameData, AvatarData* _avatar); static QUrl _defaultFullAvatarModelUrl; // privatize the copy constructor and assignment operator so they cannot be called AvatarData(const AvatarData&); diff --git a/libraries/avatars/src/HeadData.cpp b/libraries/avatars/src/HeadData.cpp index e853a3c57e..e971b184c8 100644 --- a/libraries/avatars/src/HeadData.cpp +++ b/libraries/avatars/src/HeadData.cpp @@ -42,8 +42,20 @@ HeadData::HeadData(AvatarData* owningAvatar) : } +glm::quat HeadData::getRawOrientation() const { + return glm::quat(glm::radians(glm::vec3(_basePitch, _baseYaw, _baseRoll))); +} + +void HeadData::setRawOrientation(const glm::quat& q) { + auto euler = glm::eulerAngles(q); + _basePitch = euler.x; + _baseYaw = euler.y; + _baseRoll = euler.z; +} + + glm::quat HeadData::getOrientation() const { - return _owningAvatar->getOrientation() * glm::quat(glm::radians(glm::vec3(_basePitch, _baseYaw, _baseRoll))); + return _owningAvatar->getOrientation() * getRawOrientation(); } void HeadData::setOrientation(const glm::quat& orientation) { diff --git a/libraries/avatars/src/HeadData.h b/libraries/avatars/src/HeadData.h index e2c3f69c39..38503f6e1e 100644 --- a/libraries/avatars/src/HeadData.h +++ b/libraries/avatars/src/HeadData.h @@ -48,6 +48,8 @@ public: virtual float getFinalYaw() const { return _baseYaw; } virtual float getFinalPitch() const { return _basePitch; } virtual float getFinalRoll() const { return _baseRoll; } + virtual glm::quat getRawOrientation() const; + virtual void setRawOrientation(const glm::quat& orientation); glm::quat getOrientation() const; void setOrientation(const glm::quat& orientation); diff --git a/libraries/avatars/src/Player.cpp b/libraries/avatars/src/Player.cpp index 47fc1390d9..31efb4cd9c 100644 --- a/libraries/avatars/src/Player.cpp +++ b/libraries/avatars/src/Player.cpp @@ -9,6 +9,8 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // + +#if 0 #include #include #include @@ -438,3 +440,4 @@ bool Player::computeCurrentFrame() { return true; } +#endif diff --git a/libraries/avatars/src/Player.h b/libraries/avatars/src/Player.h index 96f3cbc268..558ff309e6 100644 --- a/libraries/avatars/src/Player.h +++ b/libraries/avatars/src/Player.h @@ -12,6 +12,9 @@ #ifndef hifi_Player_h #define hifi_Player_h +#include + +#if 0 #include #include @@ -86,5 +89,6 @@ private: bool _useHeadURL; bool _useSkeletonURL; }; +#endif #endif // hifi_Player_h diff --git a/libraries/avatars/src/Recorder.cpp b/libraries/avatars/src/Recorder.cpp index 5e47c296eb..343302d472 100644 --- a/libraries/avatars/src/Recorder.cpp +++ b/libraries/avatars/src/Recorder.cpp @@ -10,6 +10,7 @@ // +#if 0 #include #include #include @@ -143,3 +144,4 @@ void Recorder::record() { void Recorder::recordAudio(const QByteArray& audioByteArray) { _recording->addAudioPacket(audioByteArray); } +#endif diff --git a/libraries/avatars/src/Recorder.h b/libraries/avatars/src/Recorder.h index f81539a417..15bffcec8b 100644 --- a/libraries/avatars/src/Recorder.h +++ b/libraries/avatars/src/Recorder.h @@ -12,6 +12,9 @@ #ifndef hifi_Recorder_h #define hifi_Recorder_h +#include + +#if 0 #include "Recording.h" template @@ -49,6 +52,6 @@ private: AvatarData* _avatar; }; - +#endif #endif // hifi_Recorder_h diff --git a/libraries/avatars/src/Recording.cpp b/libraries/avatars/src/Recording.cpp index 26c5ab66dd..884ed495be 100644 --- a/libraries/avatars/src/Recording.cpp +++ b/libraries/avatars/src/Recording.cpp @@ -9,6 +9,7 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +#if 0 #include #include #include @@ -659,3 +660,4 @@ RecordingPointer readRecordingFromFile(RecordingPointer recording, const QString return recording; } +#endif diff --git a/libraries/avatars/src/Recording.h b/libraries/avatars/src/Recording.h index 7657a12b46..a5829b1e2f 100644 --- a/libraries/avatars/src/Recording.h +++ b/libraries/avatars/src/Recording.h @@ -12,6 +12,8 @@ #ifndef hifi_Recording_h #define hifi_Recording_h +#if 0 + #include #include @@ -124,5 +126,6 @@ private: void writeRecordingToFile(RecordingPointer recording, const QString& filename); RecordingPointer readRecordingFromFile(RecordingPointer recording, const QString& filename); - +RecordingPointer readRecordingFromRecFile(RecordingPointer recording, const QString& filename, const QByteArray& byteArray); +#endif #endif // hifi_Recording_h diff --git a/libraries/recording/src/recording/Clip.cpp b/libraries/recording/src/recording/Clip.cpp index 09acf0579f..ba13b359f0 100644 --- a/libraries/recording/src/recording/Clip.cpp +++ b/libraries/recording/src/recording/Clip.cpp @@ -35,7 +35,7 @@ Clip::Pointer Clip::duplicate() { Clip::Pointer result = std::make_shared(); Locker lock(_mutex); - float currentPosition = position(); + Time currentPosition = position(); seek(0); Frame::Pointer frame = nextFrame(); diff --git a/libraries/recording/src/recording/Clip.h b/libraries/recording/src/recording/Clip.h index e7034ef077..70fc4b3f7f 100644 --- a/libraries/recording/src/recording/Clip.h +++ b/libraries/recording/src/recording/Clip.h @@ -28,11 +28,11 @@ public: Pointer duplicate(); - virtual float duration() const = 0; + virtual Time duration() const = 0; virtual size_t frameCount() const = 0; - virtual void seek(float offset) = 0; - virtual float position() const = 0; + virtual void seek(Time offset) = 0; + virtual Time position() const = 0; virtual FramePointer peekFrame() const = 0; virtual FramePointer nextFrame() = 0; diff --git a/libraries/recording/src/recording/Deck.cpp b/libraries/recording/src/recording/Deck.cpp index f0db37078b..4349a39732 100644 --- a/libraries/recording/src/recording/Deck.cpp +++ b/libraries/recording/src/recording/Deck.cpp @@ -6,7 +6,116 @@ // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // +#include "Deck.h" + +#include +#include -// FIXME -- DO NOT include headers in empty CPP files, it produces warnings. Once we define new symbols -// and some actual code here, we can uncomment this include. -//#include "Deck.h" +#include "Clip.h" +#include "Frame.h" +#include "Logging.h" + +using namespace recording; + +void Deck::queueClip(ClipPointer clip, Time timeOffset) { + if (!clip) { + qCWarning(recordingLog) << "Clip invalid, ignoring"; + return; + } + + // FIXME if the time offset is not zero, wrap the clip in a OffsetClip wrapper + _clips.push_back(clip); +} + +void Deck::play() { + if (_pause) { + _pause = false; + _startEpoch = usecTimestampNow() - (_position * USECS_PER_MSEC); + emit playbackStateChanged(); + processFrames(); + } +} + +void Deck::pause() { + if (!_pause) { + _pause = true; + emit playbackStateChanged(); + } +} + +Clip::Pointer Deck::getNextClip() { + Clip::Pointer result; + Time soonestFramePosition = INVALID_TIME; + for (const auto& clip : _clips) { + Time nextFramePosition = clip->position(); + if (nextFramePosition < soonestFramePosition) { + result = clip; + soonestFramePosition = nextFramePosition; + } + } + return result; +} + +void Deck::seek(Time position) { + _position = position; + // FIXME reset the frames to the appropriate spot + for (auto& clip : _clips) { + clip->seek(position); + } + + if (!_pause) { + // FIXME what if the timer is already running? + processFrames(); + } +} + +Time Deck::position() const { + if (_pause) { + return _position; + } + return (usecTimestampNow() - _startEpoch) / USECS_PER_MSEC; +} + +static const Time MIN_FRAME_WAIT_INTERVAL_MS = 1; + +void Deck::processFrames() { + if (_pause) { + return; + } + + _position = position(); + auto triggerPosition = _position + MIN_FRAME_WAIT_INTERVAL_MS; + Clip::Pointer nextClip; + for (nextClip = getNextClip(); nextClip; nextClip = getNextClip()) { + // If the clip is too far in the future, just break out of the handling loop + Time framePosition = nextClip->position(); + if (framePosition > triggerPosition) { + break; + } + + // Handle the frame and advance the clip + Frame::handleFrame(nextClip->nextFrame()); + } + + + if (!nextClip) { + qCDebug(recordingLog) << "No more frames available"; + // No more frames available, so handle the end of playback + if (_loop) { + qCDebug(recordingLog) << "Looping enabled, seeking back to beginning"; + // If we have looping enabled, start the playback over + seek(0); + } else { + // otherwise pause playback + pause(); + } + return; + } + + // If we have more clip frames available, set the timer for the next one + Time nextClipPosition = nextClip->position(); + Time interval = nextClipPosition - _position; + _timer.singleShot(interval, [this] { + processFrames(); + }); +} diff --git a/libraries/recording/src/recording/Deck.h b/libraries/recording/src/recording/Deck.h index 2ae8d6a7be..a3b4405210 100644 --- a/libraries/recording/src/recording/Deck.h +++ b/libraries/recording/src/recording/Deck.h @@ -10,26 +10,62 @@ #ifndef hifi_Recording_Deck_h #define hifi_Recording_Deck_h -#include "Forward.h" +#include +#include #include +#include + +#include "Forward.h" -class QIODevice; namespace recording { class Deck : public QObject { + Q_OBJECT public: using Pointer = std::shared_ptr; - Deck(QObject* parent = nullptr) : QObject(parent) {} - virtual ~Deck(); // Place a clip on the deck for recording or playback - void queueClip(ClipPointer clip, float timeOffset = 0.0f); - void play(float timeOffset = 0.0f); - void reposition(float timeOffsetDelta); - void setPlaybackSpeed(float rate); + void queueClip(ClipPointer clip, Time timeOffset = 0.0f); + + void play(); + bool isPlaying() { return !_pause; } + + void pause(); + bool isPaused() const { return _pause; } + + void stop() { pause(); seek(0.0f); } + + Time length() const { return _length; } + + void loop(bool enable = true) { _loop = enable; } + bool isLooping() const { return _loop; } + + Time position() const; + void seek(Time position); + + void setPlaybackSpeed(float factor) { _playbackSpeed = factor; } + float getPlaybackSpeed() { return _playbackSpeed; } + +signals: + void playbackStateChanged(); + +private: + using Clips = std::list; + + ClipPointer getNextClip(); + void processFrames(); + + QTimer _timer; + Clips _clips; + quint64 _startEpoch { 0 }; + Time _position { 0 }; + float _playbackSpeed { 1.0f }; + bool _pause { true }; + bool _loop { false }; + Time _length { 0 }; }; } diff --git a/libraries/recording/src/recording/Forward.h b/libraries/recording/src/recording/Forward.h index 5bd6dd917f..31aa40521c 100644 --- a/libraries/recording/src/recording/Forward.h +++ b/libraries/recording/src/recording/Forward.h @@ -12,11 +12,18 @@ #include #include +#include namespace recording { +using Time = uint32_t; + +static const Time INVALID_TIME = std::numeric_limits::max(); + using FrameType = uint16_t; +using FrameSize = uint16_t; + struct Frame; using FramePointer = std::shared_ptr; diff --git a/libraries/recording/src/recording/Frame.cpp b/libraries/recording/src/recording/Frame.cpp index aac8a4d9c3..ad2a583424 100644 --- a/libraries/recording/src/recording/Frame.cpp +++ b/libraries/recording/src/recording/Frame.cpp @@ -82,7 +82,8 @@ FrameType Frame::registerFrameType(const QString& frameTypeName) { Q_ASSERT(headerType == Frame::TYPE_HEADER); Q_UNUSED(headerType); // FIXME - build system on unix still not upgraded to Qt 5.5.1 so Q_ASSERT still produces warnings }); - return frameTypes.registerValue(frameTypeName); + auto result = frameTypes.registerValue(frameTypeName); + return result; } QMap Frame::getFrameTypes() { @@ -102,3 +103,16 @@ Frame::Handler Frame::registerFrameHandler(FrameType type, Handler handler) { handlerMap[type] = handler; return result; } + +void Frame::handleFrame(const Frame::Pointer& frame) { + Handler handler; + { + Locker lock(mutex); + auto iterator = handlerMap.find(frame->type); + if (iterator == handlerMap.end()) { + return; + } + handler = *iterator; + } + handler(frame); +} diff --git a/libraries/recording/src/recording/Frame.h b/libraries/recording/src/recording/Frame.h index 0fb95c4b2e..563b042656 100644 --- a/libraries/recording/src/recording/Frame.h +++ b/libraries/recording/src/recording/Frame.h @@ -26,7 +26,7 @@ public: static const FrameType TYPE_INVALID = 0xFFFF; static const FrameType TYPE_HEADER = 0x0; FrameType type { TYPE_INVALID }; - float timeOffset { 0 }; + Time timeOffset { 0 }; QByteArray data; Frame() {} @@ -37,6 +37,7 @@ public: static QMap getFrameTypes(); static QMap getFrameTypeNames(); static Handler registerFrameHandler(FrameType type, Handler handler); + static void handleFrame(const Pointer& frame); }; } diff --git a/libraries/recording/src/recording/Recorder.cpp b/libraries/recording/src/recording/Recorder.cpp index b2e7399cd4..f007367cae 100644 --- a/libraries/recording/src/recording/Recorder.cpp +++ b/libraries/recording/src/recording/Recorder.cpp @@ -9,25 +9,35 @@ #include "Recorder.h" #include +#include #include "impl/BufferClip.h" #include "Frame.h" using namespace recording; +Recorder::~Recorder() { + +} + +Time Recorder::position() { + return 0.0f; +} + void Recorder::start() { if (!_recording) { _recording = true; if (!_clip) { _clip = std::make_shared(); } + _startEpoch = usecTimestampNow(); _timer.start(); emit recordingStateChanged(); } } void Recorder::stop() { - if (!_recording) { + if (_recording) { _recording = false; _elapsed = _timer.elapsed(); emit recordingStateChanged(); @@ -50,13 +60,11 @@ void Recorder::recordFrame(FrameType type, QByteArray frameData) { Frame::Pointer frame = std::make_shared(); frame->type = type; frame->data = frameData; - frame->timeOffset = (float)(_elapsed + _timer.elapsed()) / MSECS_PER_SECOND; + frame->timeOffset = (usecTimestampNow() - _startEpoch) / USECS_PER_MSEC; _clip->addFrame(frame); } ClipPointer Recorder::getClip() { - auto result = _clip; - _clip.reset(); - return result; + return _clip; } diff --git a/libraries/recording/src/recording/Recorder.h b/libraries/recording/src/recording/Recorder.h index deae543bb0..f8346456d4 100644 --- a/libraries/recording/src/recording/Recorder.h +++ b/libraries/recording/src/recording/Recorder.h @@ -20,18 +20,23 @@ namespace recording { // An interface for interacting with clips, creating them by recording or // playing them back. Also serialization to and from files / network sources class Recorder : public QObject { + Q_OBJECT public: using Pointer = std::shared_ptr; Recorder(QObject* parent = nullptr) : QObject(parent) {} virtual ~Recorder(); + Time position(); + // Start recording frames void start(); // Stop recording void stop(); + // Test if recording is active bool isRecording(); + // Erase the currently recorded content void clear(); @@ -46,7 +51,8 @@ signals: private: QElapsedTimer _timer; ClipPointer _clip; - quint64 _elapsed; + quint64 _elapsed { 0 }; + quint64 _startEpoch { 0 }; bool _recording { false }; }; diff --git a/libraries/recording/src/recording/impl/BufferClip.cpp b/libraries/recording/src/recording/impl/BufferClip.cpp index 4d5a910d42..5dc75bbce2 100644 --- a/libraries/recording/src/recording/impl/BufferClip.cpp +++ b/libraries/recording/src/recording/impl/BufferClip.cpp @@ -8,24 +8,26 @@ #include "BufferClip.h" +#include + #include "../Frame.h" using namespace recording; -void BufferClip::seek(float offset) { +void BufferClip::seek(Time offset) { Locker lock(_mutex); - auto itr = std::lower_bound(_frames.begin(), _frames.end(), offset, - [](Frame::Pointer a, float b)->bool{ + auto itr = std::lower_bound(_frames.begin(), _frames.end(), offset, + [](Frame::Pointer a, Time b)->bool { return a->timeOffset < b; } ); _frameIndex = itr - _frames.begin(); } -float BufferClip::position() const { +Time BufferClip::position() const { Locker lock(_mutex); - float result = std::numeric_limits::max(); + Time result = INVALID_TIME; if (_frameIndex < _frames.size()) { result = _frames[_frameIndex]->timeOffset; } @@ -77,7 +79,7 @@ void BufferClip::reset() { _frameIndex = 0; } -float BufferClip::duration() const { +Time BufferClip::duration() const { if (_frames.empty()) { return 0; } diff --git a/libraries/recording/src/recording/impl/BufferClip.h b/libraries/recording/src/recording/impl/BufferClip.h index b40687a4ec..bfb0234600 100644 --- a/libraries/recording/src/recording/impl/BufferClip.h +++ b/libraries/recording/src/recording/impl/BufferClip.h @@ -22,11 +22,11 @@ public: virtual ~BufferClip() {} - virtual float duration() const override; + virtual Time duration() const override; virtual size_t frameCount() const override; - virtual void seek(float offset) override; - virtual float position() const override; + virtual void seek(Time offset) override; + virtual Time position() const override; virtual FramePointer peekFrame() const override; virtual FramePointer nextFrame() override; diff --git a/libraries/recording/src/recording/impl/FileClip.cpp b/libraries/recording/src/recording/impl/FileClip.cpp index be7230e3f8..e64085517a 100644 --- a/libraries/recording/src/recording/impl/FileClip.cpp +++ b/libraries/recording/src/recording/impl/FileClip.cpp @@ -22,7 +22,7 @@ using namespace recording; -static const qint64 MINIMUM_FRAME_SIZE = sizeof(FrameType) + sizeof(float) + sizeof(uint16_t); +static const qint64 MINIMUM_FRAME_SIZE = sizeof(FrameType) + sizeof(Time) + sizeof(FrameSize); static const QString FRAME_TYPE_MAP = QStringLiteral("frameTypes"); @@ -60,10 +60,10 @@ FrameHeaderList parseFrameHeaders(uchar* const start, const qint64& size) { FrameHeader header; memcpy(&(header.type), current, sizeof(FrameType)); current += sizeof(FrameType); - memcpy(&(header.timeOffset), current, sizeof(float)); - current += sizeof(float); - memcpy(&(header.size), current, sizeof(uint16_t)); - current += sizeof(uint16_t); + memcpy(&(header.timeOffset), current, sizeof(Time)); + current += sizeof(Time); + memcpy(&(header.size), current, sizeof(FrameSize)); + current += sizeof(FrameSize); header.fileOffset = current - start; if (end - current < header.size) { current = end; @@ -117,6 +117,7 @@ FileClip::FileClip(const QString& fileName) : _file(fileName) { qWarning() << "Header missing frame type map, invalid file"; return; } + qDebug() << translationMap; // Update the loaded headers with the frame data _frameHeaders.reserve(parsedFrameHeaders.size()); @@ -132,16 +133,21 @@ FileClip::FileClip(const QString& fileName) : _file(fileName) { // FIXME move to frame? bool writeFrame(QIODevice& output, const Frame& frame) { + if (frame.type == Frame::TYPE_INVALID) { + qWarning() << "Attempting to write invalid frame"; + return true; + } + auto written = output.write((char*)&(frame.type), sizeof(FrameType)); if (written != sizeof(FrameType)) { return false; } - written = output.write((char*)&(frame.timeOffset), sizeof(float)); - if (written != sizeof(float)) { + written = output.write((char*)&(frame.timeOffset), sizeof(Time)); + if (written != sizeof(Time)) { return false; } uint16_t dataSize = frame.data.size(); - written = output.write((char*)&dataSize, sizeof(uint16_t)); + written = output.write((char*)&dataSize, sizeof(FrameSize)); if (written != sizeof(uint16_t)) { return false; } @@ -201,19 +207,19 @@ FileClip::~FileClip() { } } -void FileClip::seek(float offset) { +void FileClip::seek(Time offset) { Locker lock(_mutex); auto itr = std::lower_bound(_frameHeaders.begin(), _frameHeaders.end(), offset, - [](const FrameHeader& a, float b)->bool { + [](const FrameHeader& a, Time b)->bool { return a.timeOffset < b; } ); _frameIndex = itr - _frameHeaders.begin(); } -float FileClip::position() const { +Time FileClip::position() const { Locker lock(_mutex); - float result = std::numeric_limits::max(); + Time result = INVALID_TIME; if (_frameIndex < _frameHeaders.size()) { result = _frameHeaders[_frameIndex].timeOffset; } @@ -260,7 +266,7 @@ void FileClip::addFrame(FramePointer) { throw std::runtime_error("File clips are read only"); } -float FileClip::duration() const { +Time FileClip::duration() const { if (_frameHeaders.empty()) { return 0; } diff --git a/libraries/recording/src/recording/impl/FileClip.h b/libraries/recording/src/recording/impl/FileClip.h index 08eacd8337..78256dcf23 100644 --- a/libraries/recording/src/recording/impl/FileClip.h +++ b/libraries/recording/src/recording/impl/FileClip.h @@ -26,11 +26,11 @@ public: FileClip(const QString& file); virtual ~FileClip(); - virtual float duration() const override; + virtual Time duration() const override; virtual size_t frameCount() const override; - virtual void seek(float offset) override; - virtual float position() const override; + virtual void seek(Time offset) override; + virtual Time position() const override; virtual FramePointer peekFrame() const override; virtual FramePointer nextFrame() override; @@ -45,7 +45,7 @@ public: struct FrameHeader { FrameType type; - float timeOffset; + Time timeOffset; uint16_t size; quint64 fileOffset; }; diff --git a/libraries/script-engine/CMakeLists.txt b/libraries/script-engine/CMakeLists.txt index 5e3d135034..3796abd92a 100644 --- a/libraries/script-engine/CMakeLists.txt +++ b/libraries/script-engine/CMakeLists.txt @@ -1,3 +1,3 @@ set(TARGET_NAME script-engine) setup_hifi_library(Gui Network Script WebSockets Widgets) -link_hifi_libraries(shared networking octree gpu procedural model model-networking fbx entities controllers animation audio physics) +link_hifi_libraries(shared networking octree gpu procedural model model-networking recording avatars fbx entities controllers animation audio physics) diff --git a/libraries/shared/src/shared/JSONHelpers.cpp b/libraries/shared/src/shared/JSONHelpers.cpp new file mode 100644 index 0000000000..dc872574fe --- /dev/null +++ b/libraries/shared/src/shared/JSONHelpers.cpp @@ -0,0 +1,57 @@ +// +// Created by Bradley Austin Davis on 2015/11/09 +// Copyright 2013-2015 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "JSONHelpers.h" + +#include +#include +#include + +template +QJsonValue glmToJson(const T& t) { + static const T DEFAULT_VALUE = T(); + if (t == DEFAULT_VALUE) { + return QJsonValue(); + } + QJsonArray result; + for (auto i = 0; i < t.length(); ++i) { + result.push_back(t[i]); + } + return result; +} + +template +T glmFromJson(const QJsonValue& json) { + static const T DEFAULT_VALUE = T(); + T result; + if (json.isArray()) { + QJsonArray array = json.toArray(); + size_t length = std::min(array.size(), result.length()); + for (size_t i = 0; i < length; ++i) { + result[i] = (float)array[i].toDouble(); + } + } + return result; +} + +QJsonValue toJsonValue(const quat& q) { + return glmToJson(q); +} + +QJsonValue toJsonValue(const vec3& v) { + return glmToJson(v); +} + +quat quatFromJsonValue(const QJsonValue& q) { + return glmFromJson(q); +} + +vec3 vec3FromJsonValue(const QJsonValue& v) { + return glmFromJson(v); +} + diff --git a/libraries/shared/src/shared/JSONHelpers.h b/libraries/shared/src/shared/JSONHelpers.h new file mode 100644 index 0000000000..0eda8ac94a --- /dev/null +++ b/libraries/shared/src/shared/JSONHelpers.h @@ -0,0 +1,23 @@ +// +// Created by Bradley Austin Davis on 2015/11/09 +// Copyright 2013-2015 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#pragma once +#ifndef hifi_Shared_JSONHelpers_h +#define hifi_Shared_JSONHelpers_h + +#include "../GLMHelpers.h" + +QJsonValue toJsonValue(const quat& q); + +QJsonValue toJsonValue(const vec3& q); + +quat quatFromJsonValue(const QJsonValue& q); + +vec3 vec3FromJsonValue(const QJsonValue& q); + +#endif diff --git a/libraries/shared/src/shared/UniformTransform.cpp b/libraries/shared/src/shared/UniformTransform.cpp new file mode 100644 index 0000000000..fdcf489154 --- /dev/null +++ b/libraries/shared/src/shared/UniformTransform.cpp @@ -0,0 +1,84 @@ +// +// Created by Bradley Austin Davis on 2015/11/09 +// Copyright 2013-2015 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#include "UniformTransform.h" + +#include "JSONHelpers.h" + +#include +#include +#include + +#include + +const float UniformTransform::DEFAULT_SCALE = 1.0f; + +std::shared_ptr UniformTransform::parseJson(const QJsonValue& basis) { + std::shared_ptr result = std::make_shared(); + result->fromJson(basis); + return result; +} + +static const QString JSON_TRANSLATION = QStringLiteral("translation"); +static const QString JSON_ROTATION = QStringLiteral("rotation"); +static const QString JSON_SCALE = QStringLiteral("scale"); + +void UniformTransform::fromJson(const QJsonValue& basisValue) { + if (!basisValue.isObject()) { + return; + } + QJsonObject basis = basisValue.toObject(); + if (basis.contains(JSON_ROTATION)) { + rotation = quatFromJsonValue(basis[JSON_ROTATION]); + } + if (basis.contains(JSON_TRANSLATION)) { + translation = vec3FromJsonValue(basis[JSON_TRANSLATION]); + } + if (basis.contains(JSON_SCALE)) { + scale = (float)basis[JSON_SCALE].toDouble(); + } +} + +glm::mat4 toMat4(const UniformTransform& transform) { + return glm::translate(glm::mat4(), transform.translation) * glm::mat4_cast(transform.rotation); +} + +UniformTransform fromMat4(const glm::mat4& m) { + UniformTransform result; + result.translation = vec3(m[3]); + result.rotation = glm::quat_cast(m); + return result; +} + +UniformTransform UniformTransform::relativeTransform(const UniformTransform& worldTransform) const { + UniformTransform result = fromMat4(glm::inverse(toMat4(*this)) * toMat4(worldTransform)); + result.scale = scale / worldTransform.scale; + return result; +} + +UniformTransform UniformTransform::worldTransform(const UniformTransform& relativeTransform) const { + UniformTransform result = fromMat4(toMat4(*this) * toMat4(relativeTransform)); + result.scale = relativeTransform.scale * scale; + return result; +} + +QJsonObject UniformTransform::toJson() const { + QJsonObject result; + auto json = toJsonValue(translation); + if (!json.isNull()) { + result[JSON_TRANSLATION] = json; + } + json = toJsonValue(rotation); + if (!json.isNull()) { + result[JSON_ROTATION] = json; + } + if (scale != DEFAULT_SCALE) { + result[JSON_SCALE] = scale; + } + return result; +} diff --git a/libraries/shared/src/shared/UniformTransform.h b/libraries/shared/src/shared/UniformTransform.h new file mode 100644 index 0000000000..5b46de531e --- /dev/null +++ b/libraries/shared/src/shared/UniformTransform.h @@ -0,0 +1,40 @@ +// +// Created by Bradley Austin Davis on 2015/11/09 +// Copyright 2013-2015 High Fidelity, Inc. +// +// Distributed under the Apache License, Version 2.0. +// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html +// + +#pragma once +#ifndef hifi_Shared_UniformTransform_h +#define hifi_Shared_UniformTransform_h + +#include "../GLMHelpers.h" + +class QJsonValue; + +struct UniformTransform { + static const float DEFAULT_SCALE; + glm::vec3 translation; + glm::quat rotation; + float scale { DEFAULT_SCALE }; + + UniformTransform() {} + + UniformTransform(const glm::vec3& translation, const glm::quat& rotation, const float& scale) + : translation(translation), rotation(rotation), scale(scale) {} + + UniformTransform relativeTransform(const UniformTransform& worldTransform) const; + glm::vec3 relativeVector(const UniformTransform& worldTransform) const; + + UniformTransform worldTransform(const UniformTransform& relativeTransform) const; + glm::vec3 worldVector(const UniformTransform& relativeTransform) const; + + QJsonObject toJson() const; + void fromJson(const QJsonValue& json); + + static std::shared_ptr parseJson(const QJsonValue& json); +}; + +#endif From eefe26d96ab6192fa68d1cd661207be0325692e9 Mon Sep 17 00:00:00 2001 From: Brad Hefta-Gaub Date: Thu, 12 Nov 2015 09:24:49 -0800 Subject: [PATCH 45/45] fix crash in Model::deleteGeometry when _rig is not initialized --- libraries/render-utils/src/Model.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/libraries/render-utils/src/Model.cpp b/libraries/render-utils/src/Model.cpp index 5b9bfdca3d..700b88e97b 100644 --- a/libraries/render-utils/src/Model.cpp +++ b/libraries/render-utils/src/Model.cpp @@ -1099,10 +1099,12 @@ void Model::setGeometry(const QSharedPointer& newGeometry) { void Model::deleteGeometry() { _blendedVertexBuffers.clear(); - _rig->clearJointStates(); _meshStates.clear(); - _rig->deleteAnimations(); - _rig->destroyAnimGraph(); + if (_rig) { + _rig->clearJointStates(); + _rig->deleteAnimations(); + _rig->destroyAnimGraph(); + } _blendedBlendshapeCoefficients.clear(); }