Merge pull request #6978 from PhilipRosedale/flocking

Fish Tank flocking example - FlockOfFish.js
This commit is contained in:
Brad Davis 2016-01-29 21:37:09 -05:00
commit ffe7a0eaf1
3 changed files with 234 additions and 32 deletions

182
examples/FlockOfFish.js Normal file
View file

@ -0,0 +1,182 @@
//
// flockOfFish.js
// examples
//
// Philip Rosedale
// Copyright 2016 High Fidelity, Inc.
// Fish smimming around in a space in front of you
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
var LIFETIME = 300; // Fish live for 5 minutes
var NUM_FISH = 20;
var TANK_WIDTH = 3.0;
var TANK_HEIGHT = 1.0;
var FISH_WIDTH = 0.03;
var FISH_LENGTH = 0.15;
var MAX_SIGHT_DISTANCE = 0.8;
var MIN_SEPARATION = 0.15;
var AVOIDANCE_FORCE = 0.2;
var COHESION_FORCE = 0.05;
var ALIGNMENT_FORCE = 0.05;
var SWIMMING_FORCE = 0.05;
var SWIMMING_SPEED = 1.5;
var fishLoaded = false;
var fish = [];
var lowerCorner = { x: 0, y: 0, z: 0 };
var upperCorner = { x: 0, y: 0, z: 0 };
function randomVector(scale) {
return { x: Math.random() * scale - scale / 2.0, y: Math.random() * scale - scale / 2.0, z: Math.random() * scale - scale / 2.0 };
}
function updateFish(deltaTime) {
if (!Entities.serversExist() || !Entities.canRez()) {
return;
}
if (!fishLoaded) {
loadFish(NUM_FISH);
fishLoaded = true;
return;
}
var averageVelocity = { x: 0, y: 0, z: 0 };
var averagePosition = { x: 0, y: 0, z: 0 };
var birdPositionsCounted = 0;
var birdVelocitiesCounted = 0;
// First pre-load an array with properties on all the other fish so our per-fish loop
// isn't doing it.
var flockProperties = [];
for (var i = 0; i < fish.length; i++) {
var otherProps = Entities.getEntityProperties(fish[i].entityId, ["position", "velocity", "rotation"]);
flockProperties.push(otherProps);
}
for (var i = 0; i < fish.length; i++) {
if (fish[i].entityId) {
// Get only the properties we need, because that is faster
var properties = flockProperties[i];
// If fish has been deleted, bail
if (properties.id != fish[i].entityId) {
fish[i].entityId = false;
return;
}
// Store old values so we can check if they have changed enough to update
var velocity = { x: properties.velocity.x, y: properties.velocity.y, z: properties.velocity.z };
var position = { x: properties.position.x, y: properties.position.y, z: properties.position.z };
averageVelocity = { x: 0, y: 0, z: 0 };
averagePosition = { x: 0, y: 0, z: 0 };
var othersCounted = 0;
for (var j = 0; j < fish.length; j++) {
if (i != j) {
// Get only the properties we need, because that is faster
var otherProps = flockProperties[j];
var separation = Vec3.distance(properties.position, otherProps.position);
if (separation < MAX_SIGHT_DISTANCE) {
averageVelocity = Vec3.sum(averageVelocity, otherProps.velocity);
averagePosition = Vec3.sum(averagePosition, otherProps.position);
othersCounted++;
}
if (separation < MIN_SEPARATION) {
var pushAway = Vec3.multiply(Vec3.normalize(Vec3.subtract(properties.position, otherProps.position)), AVOIDANCE_FORCE);
velocity = Vec3.sum(velocity, pushAway);
}
}
}
if (othersCounted > 0) {
averageVelocity = Vec3.multiply(averageVelocity, 1.0 / othersCounted);
averagePosition = Vec3.multiply(averagePosition, 1.0 / othersCounted);
// Alignment: Follow group's direction and speed
velocity = Vec3.mix(velocity, Vec3.multiply(Vec3.normalize(averageVelocity), Vec3.length(velocity)), ALIGNMENT_FORCE);
// Cohesion: Steer towards center of flock
var towardCenter = Vec3.subtract(averagePosition, position);
velocity = Vec3.mix(velocity, Vec3.multiply(Vec3.normalize(towardCenter), Vec3.length(velocity)), COHESION_FORCE);
}
// Try to swim at a constant speed
velocity = Vec3.mix(velocity, Vec3.multiply(Vec3.normalize(velocity), SWIMMING_SPEED), SWIMMING_FORCE);
// Keep fish in their 'tank'
if (position.x < lowerCorner.x) {
position.x = lowerCorner.x;
velocity.x *= -1.0;
} else if (position.x > upperCorner.x) {
position.x = upperCorner.x;
velocity.x *= -1.0;
}
if (position.y < lowerCorner.y) {
position.y = lowerCorner.y;
velocity.y *= -1.0;
} else if (position.y > upperCorner.y) {
position.y = upperCorner.y;
velocity.y *= -1.0;
}
if (position.z < lowerCorner.z) {
position.z = lowerCorner.z;
velocity.z *= -1.0;
} else if (position.z > upperCorner.z) {
position.z = upperCorner.z;
velocity.z *= -1.0;
}
// Orient in direction of velocity
var rotation = Quat.rotationBetween(Vec3.UNIT_NEG_Z, velocity);
var VELOCITY_FOLLOW_RATE = 0.30;
// Only update properties if they have changed, to save bandwidth
var MIN_POSITION_CHANGE_FOR_UPDATE = 0.001;
if (Vec3.distance(properties.position, position) < MIN_POSITION_CHANGE_FOR_UPDATE) {
Entities.editEntity(fish[i].entityId, { velocity: velocity, rotation: Quat.mix(properties.rotation, rotation, VELOCITY_FOLLOW_RATE) });
} else {
Entities.editEntity(fish[i].entityId, { position: position, velocity: velocity, rotation: Quat.slerp(properties.rotation, rotation, VELOCITY_FOLLOW_RATE) });
}
}
}
}
// Connect a call back that happens every frame
Script.update.connect(updateFish);
// Delete our little friends if script is stopped
Script.scriptEnding.connect(function() {
for (var i = 0; i < fish.length; i++) {
Entities.deleteEntity(fish[i].entityId);
}
});
var STARTING_FRACTION = 0.25;
function loadFish(howMany) {
var center = Vec3.sum(MyAvatar.position, Vec3.multiply(Quat.getFront(MyAvatar.orientation), 2 * TANK_WIDTH));
lowerCorner = { x: center.x - TANK_WIDTH / 2, y: center.y, z: center.z - TANK_WIDTH / 2 };
upperCorner = { x: center.x + TANK_WIDTH / 2, y: center.y + TANK_HEIGHT, z: center.z + TANK_WIDTH / 2 };
for (var i = 0; i < howMany; i++) {
var position = {
x: lowerCorner.x + (upperCorner.x - lowerCorner.x) / 2.0 + (Math.random() - 0.5) * (upperCorner.x - lowerCorner.x) * STARTING_FRACTION,
y: lowerCorner.y + (upperCorner.y - lowerCorner.y) / 2.0 + (Math.random() - 0.5) * (upperCorner.y - lowerCorner.y) * STARTING_FRACTION,
z: lowerCorner.z + (upperCorner.z - lowerCorner.x) / 2.0 + (Math.random() - 0.5) * (upperCorner.z - lowerCorner.z) * STARTING_FRACTION
};
fish.push({
entityId: Entities.addEntity({
type: "Box",
position: position,
rotation: { x: 0, y: 0, z: 0, w: 1 },
dimensions: { x: FISH_WIDTH, y: FISH_WIDTH, z: FISH_LENGTH },
velocity: { x: SWIMMING_SPEED, y: SWIMMING_SPEED, z: SWIMMING_SPEED },
damping: 0.0,
dynamic: false,
lifetime: LIFETIME,
color: { red: 0, green: 255, blue: 255 }
})
});
}
}

View file

@ -12,7 +12,7 @@
// The rectangular area in the domain where the flock will fly
var lowerCorner = { x: 0, y: 0, z: 0 };
var upperCorner = { x: 10, y: 10, z: 10 };
var upperCorner = { x: 30, y: 10, z: 30 };
var STARTING_FRACTION = 0.25;
var NUM_BIRDS = 50;
@ -36,7 +36,7 @@ var ALIGNMENT_FORCE = 1.5;
var COHESION_FORCE = 1.0;
var MAX_COHESION_VELOCITY = 0.5;
var followBirds = true;
var followBirds = false;
var AVATAR_FOLLOW_RATE = 0.001;
var AVATAR_FOLLOW_VELOCITY_TIMESCALE = 2.0;
var AVATAR_FOLLOW_ORIENTATION_RATE = 0.005;

View file

@ -41,6 +41,8 @@ var PICK_WITH_HAND_RAY = true;
var DISTANCE_HOLDING_RADIUS_FACTOR = 3.5; // multiplied by distance between hand and object
var DISTANCE_HOLDING_ACTION_TIMEFRAME = 0.1; // how quickly objects move to their new position
var DISTANCE_HOLDING_UNITY_MASS = 1200; // The mass at which the distance holding action timeframe is unmodified
var DISTANCE_HOLDING_UNITY_DISTANCE = 6; // The distance at which the distance holding action timeframe is unmodified
var DISTANCE_HOLDING_ROTATION_EXAGGERATION_FACTOR = 2.0; // object rotates this much more than hand did
var MOVE_WITH_HEAD = true; // experimental head-control of distantly held objects
var FAR_TO_NEAR_GRAB_PADDING_FACTOR = 1.2;
@ -114,7 +116,9 @@ var GRABBABLE_PROPERTIES = [
"name",
"shapeType",
"parentID",
"parentJointIndex"
"parentJointIndex",
"density",
"dimensions"
];
var GRABBABLE_DATA_KEY = "grabbableKey"; // shared with grab.js
@ -295,7 +299,7 @@ function MyController(hand) {
this.rawBumperValue = 0;
//for visualizations
this.overlayLine = null;
this.particleBeam = null;
this.particleBeamObject = null;
//for lights
this.spotlight = null;
@ -479,34 +483,32 @@ function MyController(hand) {
this.handleDistantParticleBeam = function(handPosition, objectPosition, color) {
var handToObject = Vec3.subtract(objectPosition, handPosition);
var finalRotation = Quat.rotationBetween(Vec3.multiply(-1, Vec3.UP), handToObject);
var finalRotationObject = Quat.rotationBetween(Vec3.multiply(-1, Vec3.UP), handToObject);
var distance = Vec3.distance(handPosition, objectPosition);
var speed = 5;
var speed = distance * 3;
var spread = 0;
var lifespan = distance / speed;
if (this.particleBeam === null) {
this.createParticleBeam(objectPosition, finalRotation, color, speed, spread, lifespan);
if (this.particleBeamObject === null) {
this.createParticleBeam(objectPosition, finalRotationObject, color, speed, spread, lifespan);
} else {
this.updateParticleBeam(objectPosition, finalRotation, color, speed, spread, lifespan);
this.updateParticleBeam(objectPosition, finalRotationObject, color, speed, spread, lifespan);
}
};
this.createParticleBeam = function(position, orientation, color, speed, spread, lifespan) {
this.createParticleBeam = function(positionObject, orientationObject, color, speed, spread, lifespan) {
var particleBeamProperties = {
var particleBeamPropertiesObject = {
type: "ParticleEffect",
isEmitting: true,
position: position,
position: positionObject,
visible: false,
lifetime: 60,
"name": "Particle Beam",
"color": color,
"maxParticles": 2000,
"lifespan": lifespan,
"emitRate": 50,
"emitRate": 1000,
"emitSpeed": speed,
"speedSpread": spread,
"emitOrientation": {
@ -544,26 +546,25 @@ function MyController(hand) {
"additiveBlending": 0,
"textures": "https://hifi-content.s3.amazonaws.com/alan/dev/textures/grabsprite-3.png"
}
this.particleBeam = Entities.addEntity(particleBeamProperties);
this.particleBeamObject = Entities.addEntity(particleBeamPropertiesObject);
};
this.updateParticleBeam = function(position, orientation, color, speed, spread, lifespan) {
Entities.editEntity(this.particleBeam, {
rotation: orientation,
position: position,
this.updateParticleBeam = function(positionObject, orientationObject, color, speed, spread, lifespan) {
Entities.editEntity(this.particleBeamObject, {
rotation: orientationObject,
position: positionObject,
visible: true,
color: color,
emitSpeed: speed,
speedSpread: spread,
lifespan: lifespan
})
};
this.renewParticleBeamLifetime = function() {
var props = Entities.getEntityProperties(this.particleBeam, "age");
Entities.editEntity(this.particleBeam, {
var props = Entities.getEntityProperties(this.particleBeamObject, "age");
Entities.editEntity(this.particleBeamObject, {
lifetime: TEMPORARY_PARTICLE_BEAM_LIFETIME + props.age // renew lifetime
})
}
@ -684,9 +685,9 @@ function MyController(hand) {
};
this.particleBeamOff = function() {
if (this.particleBeam !== null) {
Entities.deleteEntity(this.particleBeam);
this.particleBeam = null;
if (this.particleBeamObject !== null) {
Entities.deleteEntity(this.particleBeamObject);
this.particleBeamObject = null;
}
}
@ -864,6 +865,7 @@ function MyController(hand) {
// too far away, don't grab
continue;
}
if (distance < minDistance) {
this.grabbedEntity = candidateEntities[i];
minDistance = distance;
@ -932,6 +934,18 @@ function MyController(hand) {
}
};
this.distanceGrabTimescale = function(mass, distance) {
var timeScale = DISTANCE_HOLDING_ACTION_TIMEFRAME * mass / DISTANCE_HOLDING_UNITY_MASS * distance / DISTANCE_HOLDING_UNITY_DISTANCE;
if (timeScale < DISTANCE_HOLDING_ACTION_TIMEFRAME) {
timeScale = DISTANCE_HOLDING_ACTION_TIMEFRAME;
}
return timeScale;
}
this.getMass = function(dimensions, density) {
return (dimensions.x * dimensions.y * dimensions.z) * density;
}
this.distanceHolding = function() {
var handControllerPosition = (this.hand === RIGHT_HAND) ? MyAvatar.rightHandPosition : MyAvatar.leftHandPosition;
var controllerHandInput = (this.hand === RIGHT_HAND) ? Controller.Standard.RightHand : Controller.Standard.LeftHand;
@ -953,12 +967,17 @@ function MyController(hand) {
this.radiusScalar = 1.0;
}
// compute the mass for the purpose of energy and how quickly to move object
this.mass = this.getMass(grabbedProperties.dimensions, grabbedProperties.density);
var distanceToObject = Vec3.length(Vec3.subtract(MyAvatar.position, grabbedProperties.position));
var timeScale = this.distanceGrabTimescale(this.mass, distanceToObject);
this.actionID = NULL_UUID;
this.actionID = Entities.addAction("spring", this.grabbedEntity, {
targetPosition: this.currentObjectPosition,
linearTimeScale: DISTANCE_HOLDING_ACTION_TIMEFRAME,
linearTimeScale: timeScale,
targetRotation: this.currentObjectRotation,
angularTimeScale: DISTANCE_HOLDING_ACTION_TIMEFRAME,
angularTimeScale: timeScale,
tag: getTag(),
ttl: ACTION_TTL
});
@ -1135,11 +1154,12 @@ function MyController(hand) {
this.handleSpotlight(this.grabbedEntity);
}
var distanceToObject = Vec3.length(Vec3.subtract(MyAvatar.position, this.currentObjectPosition));
var success = Entities.updateAction(this.grabbedEntity, this.actionID, {
targetPosition: targetPosition,
linearTimeScale: DISTANCE_HOLDING_ACTION_TIMEFRAME,
linearTimeScale: this.distanceGrabTimescale(this.mass, distanceToObject),
targetRotation: this.currentObjectRotation,
angularTimeScale: DISTANCE_HOLDING_ACTION_TIMEFRAME,
angularTimeScale: this.distanceGrabTimescale(this.mass, distanceToObject),
ttl: ACTION_TTL
});
if (success) {
@ -1607,7 +1627,7 @@ function MyController(hand) {
this.cleanup = function() {
this.release();
Entities.deleteEntity(this.particleBeam);
Entities.deleteEntity(this.particleBeamObject);
Entities.deleteEntity(this.spotLight);
Entities.deleteEntity(this.pointLight);
};