From 9ca0df07967fbc945b16bdf94c59e9ca3955eb9d Mon Sep 17 00:00:00 2001
From: Chris Collins <chris@highfidelity.io>
Date: Thu, 8 Jan 2015 16:05:32 -0800
Subject: [PATCH] Small fixes to scripts

-merge duplicate gun scripts
-fix url of sit
---
 examples/controllers/hydra/gun.js | 209 +++++++++++++++++++++---------
 examples/gun.js                   |   3 +-
 examples/sit.js                   |   2 +-
 3 files changed, 153 insertions(+), 61 deletions(-)

diff --git a/examples/controllers/hydra/gun.js b/examples/controllers/hydra/gun.js
index de18317335..18fe9c542d 100644
--- a/examples/controllers/hydra/gun.js
+++ b/examples/controllers/hydra/gun.js
@@ -14,7 +14,7 @@
 //  See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
 //
 
-Script.include("../../libraries/globals.js");
+Script.include("libraries/globals.js");
 
 function getRandomFloat(min, max) {
     return Math.random() * (max - min) + min;
@@ -26,14 +26,19 @@ var yawFromMouse = 0;
 var pitchFromMouse = 0;
 var isMouseDown = false; 
 
-var BULLET_VELOCITY = 5.0;
+var BULLET_VELOCITY = 20.0;
 var MIN_THROWER_DELAY = 1000;
 var MAX_THROWER_DELAY = 1000;
 var LEFT_BUTTON_3 = 3;
 var RELOAD_INTERVAL = 5;
 
+var KICKBACK_ANGLE = 15;
+var elbowKickAngle = 0.0;
+var rotationBeforeKickback; 
+
 var showScore = false;
 
+
 // Load some sound to use for loading and firing 
 var fireSound = SoundCache.getSound(HIFI_PUBLIC_BUCKET + "sounds/Guns/GUN-SHOT2.raw");
 var loadSound = SoundCache.getSound(HIFI_PUBLIC_BUCKET + "sounds/Guns/Gun_Reload_Weapon22.raw");
@@ -48,10 +53,11 @@ var audioOptions = {
 }
 
 var shotsFired = 0;
-
 var shotTime = new Date(); 
 
-// initialize our triggers
+var activeControllers = 0; 
+
+// initialize our controller triggers
 var triggerPulled = new Array();
 var numberOfTriggers = Controller.getNumberOfTriggers();
 for (t = 0; t < numberOfTriggers; t++) {
@@ -59,9 +65,11 @@ for (t = 0; t < numberOfTriggers; t++) {
 }
 
 var isLaunchButtonPressed = false; 
-
 var score = 0; 
 
+var bulletID = false;
+var targetID = false;
+
 //  Create a reticle image in center of screen 
 var screenSize = Controller.getViewportDimensions();
 var reticle = Overlays.addOverlay("image", {
@@ -74,6 +82,16 @@ var reticle = Overlays.addOverlay("image", {
                     alpha: 1
                 });
 
+var offButton = Overlays.addOverlay("image", {
+                    x: screenSize.x - 48,
+                    y: 96,
+                    width: 32,
+                    height: 32,
+                    imageURL: HIFI_PUBLIC_BUCKET + "images/close.png",
+                    color: { red: 255, green: 255, blue: 255},
+                    alpha: 1
+                });
+
 if (showScore) {
     var text = Overlays.addOverlay("text", {
                     x: screenSize.x / 2 - 100,
@@ -95,18 +113,20 @@ function printVector(string, vector) {
 }
 
 function shootBullet(position, velocity) {
-    var BULLET_SIZE = 0.01;
-    var BULLET_LIFETIME = 20.0;
+    var BULLET_SIZE = 0.07;
+    var BULLET_LIFETIME = 10.0;
     var BULLET_GRAVITY = -0.02;
-    Entities.addEntity(
+    bulletID = Entities.addEntity(
         { type: "Sphere",
           position: position, 
           dimensions: { x: BULLET_SIZE, y: BULLET_SIZE, z: BULLET_SIZE }, 
-          color: {  red: 10, green: 10, blue: 10 },  
+          color: {  red: 255, green: 0, blue: 0 },  
           velocity: velocity, 
           lifetime: BULLET_LIFETIME,
-          gravity: {  x: 0, y: BULLET_GRAVITY, z: 0 }, 
-          damping: 0 });
+          gravity: {  x: 0, y: BULLET_GRAVITY, z: 0 },
+          ignoreCollisions: false,
+          collisionsWillMove: true
+      });
 
     // Play firing sounds 
     audioOptions.position = position;   
@@ -115,36 +135,45 @@ function shootBullet(position, velocity) {
     if ((shotsFired % RELOAD_INTERVAL) == 0) {
         Audio.playSound(loadSound, audioOptions);
     }
+
+    // Kickback the arm 
+    rotationBeforeKickback = MyAvatar.getJointRotation("LeftForeArm"); 
+    var armRotation = MyAvatar.getJointRotation("LeftForeArm"); 
+    armRotation = Quat.multiply(armRotation, Quat.fromPitchYawRollDegrees(0.0, 0.0, KICKBACK_ANGLE));
+    MyAvatar.setJointData("LeftForeArm", armRotation);
+    elbowKickAngle = KICKBACK_ANGLE;
 }
 
 function shootTarget() {
-    var TARGET_SIZE = 0.25;
-    var TARGET_GRAVITY = -0.6;
+    var TARGET_SIZE = 0.50;
+    var TARGET_GRAVITY = -0.25;
     var TARGET_LIFETIME = 300.0;
-    var TARGET_UP_VELOCITY = 3.0;
-    var TARGET_FWD_VELOCITY = 5.0;
+    var TARGET_UP_VELOCITY = 0.5;
+    var TARGET_FWD_VELOCITY = 1.0;
     var DISTANCE_TO_LAUNCH_FROM = 3.0;
+    var ANGLE_RANGE_FOR_LAUNCH = 20.0;
     var camera = Camera.getPosition();
     //printVector("camera", camera);
-    var targetDirection = Quat.angleAxis(getRandomFloat(-20.0, 20.0), { x:0, y:1, z:0 });
+    var targetDirection = Quat.angleAxis(getRandomFloat(-ANGLE_RANGE_FOR_LAUNCH, ANGLE_RANGE_FOR_LAUNCH), { x:0, y:1, z:0 });
     targetDirection = Quat.multiply(Camera.getOrientation(), targetDirection);
     var forwardVector = Quat.getFront(targetDirection);
-    //printVector("forwardVector", forwardVector);
+ 
     var newPosition = Vec3.sum(camera, Vec3.multiply(forwardVector, DISTANCE_TO_LAUNCH_FROM));
-    //printVector("newPosition", newPosition);
+
     var velocity = Vec3.multiply(forwardVector, TARGET_FWD_VELOCITY);
     velocity.y += TARGET_UP_VELOCITY;
-    //printVector("velocity", velocity);
-    
-    Entities.addEntity(
-        { type: "Sphere",
+
+    targetID = Entities.addEntity(
+        { type: "Box",
           position: newPosition, 
           dimensions: { x: TARGET_SIZE, y: TARGET_SIZE, z: TARGET_SIZE }, 
           color: {  red: 0, green: 200, blue: 200 },  
+          //angularVelocity: { x: 1, y: 0, z: 0 },
           velocity: velocity, 
           gravity: {  x: 0, y: TARGET_GRAVITY, z: 0 }, 
           lifetime: TARGET_LIFETIME,
-          damping: 0.0001 });
+          damping: 0.0001, 
+          collisionsWillMove: true });
 
     // Record start time 
     shotTime = new Date();
@@ -157,24 +186,25 @@ function shootTarget() {
 
 
 function entityCollisionWithEntity(entity1, entity2, collision) {
-    score++;
-    if (showScore) {
-        Overlays.editOverlay(text, { text: "Score: " + score } );
-    }
-    
-    //  Sort out which entity is which 
 
-    //  Record shot time 
-    var endTime = new Date(); 
-    var msecs = endTime.valueOf() - shotTime.valueOf();
-    //print("hit, msecs = " + msecs);
-    //Vec3.print("penetration = ", collision.penetration);
-    //Vec3.print("contactPoint = ", collision.contactPoint);
-    Entities.deleteEntity(entity1);
-    Entities.deleteEntity(entity2);
-    // play the sound near the camera so the shooter can hear it
-    audioOptions.position = Vec3.sum(Camera.getPosition(), Quat.getFront(Camera.getOrientation()));   
-    Audio.playSound(targetHitSound, audioOptions);
+    if (((entity1.id == bulletID.id) || (entity1.id == targetID.id)) && 
+        ((entity2.id == bulletID.id) || (entity2.id == targetID.id))) {
+        score++;
+        if (showScore) {
+            Overlays.editOverlay(text, { text: "Score: " + score } );
+        }
+
+        //  We will delete the bullet and target in 1/2 sec, but for now we can see them bounce!
+        Script.setTimeout(deleteBulletAndTarget, 500); 
+
+        // Turn the target and the bullet white
+        Entities.editEntity(entity1, { color: { red: 255, green: 255, blue: 255 }});
+        Entities.editEntity(entity2, { color: { red: 255, green: 255, blue: 255 }});
+
+        // play the sound near the camera so the shooter can hear it
+        audioOptions.position = Vec3.sum(Camera.getPosition(), Quat.getFront(Camera.getOrientation()));   
+        Audio.playSound(targetHitSound, audioOptions);
+    }
 }
 
 function keyPressEvent(event) {
@@ -186,12 +216,42 @@ function keyPressEvent(event) {
         shootFromMouse();
     } else if (event.text == "r") {
         playLoadSound();
+    } else if (event.text == "s") {
+        //  Hit this key to dump a posture from hydra to log
+        Quat.print("arm = ", MyAvatar.getJointRotation("LeftArm"));
+        Quat.print("forearm = ", MyAvatar.getJointRotation("LeftForeArm"));
+        Quat.print("hand = ", MyAvatar.getJointRotation("LeftHand"));
+
     }
 }
 
 function playLoadSound() {
     audioOptions.position = Vec3.sum(Camera.getPosition(), Quat.getFront(Camera.getOrientation())); 
     Audio.playSound(loadSound, audioOptions);
+    // Raise arm to firing posture 
+    takeFiringPose();
+}
+
+function clearPose() {
+    MyAvatar.clearJointData("LeftForeArm");
+    MyAvatar.clearJointData("LeftArm");
+    MyAvatar.clearJointData("LeftHand");
+}
+
+function deleteBulletAndTarget() {
+    Entities.deleteEntity(bulletID);
+    Entities.deleteEntity(targetID);
+    bulletID = false; 
+    targetID = false; 
+}
+
+function takeFiringPose() {
+    clearPose();
+    if (Controller.getNumberOfSpatialControls() == 0) {
+        MyAvatar.setJointData("LeftForeArm", {x: -0.251919, y: -0.0415449, z: 0.499487, w: 0.827843});
+        MyAvatar.setJointData("LeftArm", { x: 0.470196, y: -0.132559, z: 0.494033, w: 0.719219});
+        MyAvatar.setJointData("LeftHand", { x: -0.0104815, y: -0.110551, z: -0.352111, w: 0.929333});
+    }
 }
 
 MyAvatar.attach(gunModel, "RightHand", {x:0.02, y: 0.11, z: 0.04}, Quat.fromPitchYawRollDegrees(-0, -160, -79), 0.20);
@@ -201,17 +261,49 @@ MyAvatar.attach(gunModel, "RightHand", {x:0.02, y: 0.11, z: 0.04}, Quat.fromPitc
 Script.setTimeout(playLoadSound, 2000); 
 
 function update(deltaTime) {
+    if (bulletID && !bulletID.isKnownID) {
+        print("Trying to identify bullet");
+        bulletID = Entities.identifyEntity(bulletID);
+    }
+    if (targetID && !targetID.isKnownID) {
+        targetID = Entities.identifyEntity(targetID);
+    }
     //  Check for mouseLook movement, update rotation 
        // rotate body yaw for yaw received from mouse
     var newOrientation = Quat.multiply(MyAvatar.orientation, Quat.fromVec3Radians( { x: 0, y: yawFromMouse, z: 0 } ));
-    MyAvatar.orientation = newOrientation;
+    //MyAvatar.orientation = newOrientation;
     yawFromMouse = 0;
 
     // apply pitch from mouse
     var newPitch = MyAvatar.headPitch + pitchFromMouse;
-    MyAvatar.headPitch = newPitch;
+    //MyAvatar.headPitch = newPitch;
     pitchFromMouse = 0;
 
+    
+    if (activeControllers == 0) {
+        if (Controller.getNumberOfSpatialControls() > 0) { 
+            activeControllers = Controller.getNumberOfSpatialControls();
+            clearPose();
+        }
+    }
+
+    var KICKBACK_DECAY_RATE = 0.125;
+    if (elbowKickAngle > 0.0)  {       
+        if (elbowKickAngle > 0.5) {
+            var newAngle = elbowKickAngle * KICKBACK_DECAY_RATE;
+            elbowKickAngle -= newAngle; 
+            var armRotation = MyAvatar.getJointRotation("LeftForeArm");
+            armRotation = Quat.multiply(armRotation, Quat.fromPitchYawRollDegrees(0.0, 0.0, -newAngle));
+            MyAvatar.setJointData("LeftForeArm", armRotation);
+        } else {
+            MyAvatar.setJointData("LeftForeArm", rotationBeforeKickback);
+            if (Controller.getNumberOfSpatialControls() > 0) {
+                clearPose();
+            }
+            elbowKickAngle = 0.0;
+        }
+    }
+
     //  Check hydra controller for launch button press 
     if (!isLaunchButtonPressed && Controller.isButtonPressed(LEFT_BUTTON_3)) {
         isLaunchButtonPressed = true; 
@@ -222,15 +314,13 @@ function update(deltaTime) {
         
     }
 
-    //  Check hydra controller for trigger press 
+    // check for trigger press
 
-    var numberOfTriggers = Controller.getNumberOfTriggers();
-    var numberOfSpatialControls = Controller.getNumberOfSpatialControls();
-    var controllersPerTrigger = numberOfSpatialControls / numberOfTriggers;
+    var numberOfTriggers = 2; 
+    var controllersPerTrigger = 2;
 
-    // this is expected for hydras
     if (numberOfTriggers == 2 && controllersPerTrigger == 2) {
-        for (var t = 0; t < numberOfTriggers; t++) {
+        for (var t = 0; t < 2; t++) {
             var shootABullet = false;
             var triggerValue = Controller.getTriggerValue(t);
             if (triggerPulled[t]) {
@@ -239,14 +329,13 @@ function update(deltaTime) {
                     triggerPulled[t] = false; // unpulled
                 }
             } else {
-                // must pull to at least 0.9
-                if (triggerValue > 0.9) {
+                // must pull to at least 
+                if (triggerValue > 0.5) {
                     triggerPulled[t] = true; // pulled
                     shootABullet = true;
                 }
             }
 
-
             if (shootABullet) {
                 var palmController = t * controllersPerTrigger; 
                 var palmPosition = Controller.getSpatialControlPosition(palmController);
@@ -263,12 +352,8 @@ function update(deltaTime) {
                 var position = { x: fingerTipPosition.x + palmToFingerTipVector.x/2, 
                                  y: fingerTipPosition.y + palmToFingerTipVector.y/2, 
                                  z: fingerTipPosition.z  + palmToFingerTipVector.z/2};   
-
-                var linearVelocity = 25; 
-                                    
-                var velocity = { x: palmToFingerTipVector.x * linearVelocity,
-                                 y: palmToFingerTipVector.y * linearVelocity,
-                                 z: palmToFingerTipVector.z * linearVelocity };
+                   
+                var velocity = Vec3.multiply(BULLET_VELOCITY, Vec3.normalize(palmToFingerTipVector)); 
 
                 shootBullet(position, velocity);
             }
@@ -280,8 +365,12 @@ function mousePressEvent(event) {
     isMouseDown = true;
     lastX = event.x;
     lastY = event.y;
-    //audioOptions.position = Vec3.sum(Camera.getPosition(), Quat.getFront(Camera.getOrientation()));
-    //Audio.playSound(loadSound, audioOptions);
+
+    if (Overlays.getOverlayAtPoint({ x: event.x, y: event.y }) === offButton) {
+        Script.stop();
+    } else {
+        shootFromMouse();
+    } 
 }
 
 function shootFromMouse() {
@@ -312,8 +401,10 @@ function mouseMoveEvent(event) {
 
 function scriptEnding() {
     Overlays.deleteOverlay(reticle); 
+    Overlays.deleteOverlay(offButton);
     Overlays.deleteOverlay(text);
     MyAvatar.detachOne(gunModel);
+    clearPose();
 }
 
 Entities.entityCollisionWithEntity.connect(entityCollisionWithEntity);
diff --git a/examples/gun.js b/examples/gun.js
index c5b7b17052..18fe9c542d 100644
--- a/examples/gun.js
+++ b/examples/gun.js
@@ -254,7 +254,8 @@ function takeFiringPose() {
     }
 }
 
-MyAvatar.attach(gunModel, "LeftHand", {x: -0.02, y: -.14, z: 0.07}, Quat.fromPitchYawRollDegrees(-70, -151, 72), 0.20);
+MyAvatar.attach(gunModel, "RightHand", {x:0.02, y: 0.11, z: 0.04}, Quat.fromPitchYawRollDegrees(-0, -160, -79), 0.20);
+//MyAvatar.attach(gunModel, "LeftHand", {x: -0.02, y: -.14, z: 0.07}, Quat.fromPitchYawRollDegrees(-70, -151, 72), 0.20);
 
 //  Give a bit of time to load before playing sound
 Script.setTimeout(playLoadSound, 2000); 
diff --git a/examples/sit.js b/examples/sit.js
index 71d909d1e7..196a1a1972 100644
--- a/examples/sit.js
+++ b/examples/sit.js
@@ -10,7 +10,7 @@
 //
 
 
-var buttonImageUrl = "https://public.highfidelity.io/images/tools/sit.svg";
+var buttonImageUrl = "https://s3.amazonaws.com/hifi-public/images/tools/sit.svg";
 
 var windowDimensions = Controller.getViewportDimensions();