0.2.1 • Published 2 years ago

bird-oid v0.2.1

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

bird-oid

npm version stability-stable npm minzipped size dependencies types Conventional Commits styled with prettier linted with eslint license

A 3D boid system with accompanying emergent behaviors. Implementation mostly based on Craig Reynolds paper Steering Behaviors For Autonomous Characters.

paypal coinbase twitter

npm.io

Installation

npm install bird-oid

Usage

import { System as BoidSystem, behaviors } from "bird-oid";

const BOIDS_COUNT = 100;
const WANDER_SPEED = 2;

const system = new BoidSystem({
  maxSpeed: 0.3,
  maxForce: 0.4,
});

const boidBehaviors = [
  {
    fn: behaviors.wander,
    options: {
      distance: system.scale * 0.04,
      radius: system.scale * 0.3,
      theta: 0,
      phi: 0.3,
    },
  },
  {
    enabled: true,
    fn: behaviors.boundsConstrain,
    scale: 2,
  },
  {
    enabled: false,
    fn: behaviors.boundsWrapConstrain,
  },
];

for (let i = 0; i < BOIDS_COUNT; i++) {
  const boid = new Boid(boidBehaviors);

  // Position in the bounds
  boid.position = system.getRandomPosition();

  // Add initial velocity
  boid.velocity = [
    Math.random() * 0.5 * system.maxSpeed,
    Math.random() * 0.5 * system.maxSpeed,
    Math.random() * 0.5 * system.maxSpeed,
  ];
  system.addBoid(boid);
}

const frame = () => {
  const dt = Math.min(0.1, myClock.getDelta());

  // Wander requires angle update
  boidBehaviors[0].options.theta +=
    Math.random() * WANDER_SPEED - WANDER_SPEED * 0.5;
  boidBehaviors[0].options.phi +=
    Math.random() * WANDER_SPEED - WANDER_SPEED * 0.5;

  system.update(dt);

  requestAnimationFrame(frame);
};

requestAnimationFrame(() => {
  frame();
});

API

Modules

Classes

Typedefs

behaviors

Steering based on https://www.red3d.com/cwr/steer/gdc99/ Use these function as fn property of the BehaviorObject passed to a Boid.

behaviors.seek(options) ⇒ module:gl-matrix~vec3

"Seek (or pursuit of a static target) acts to steer the character towards a specified position in global space."

Kind: static method of behaviors

ParamType
optionsBasicBehaviorOptions

behaviors.flee(options) ⇒ module:gl-matrix~vec3

"Flee is simply the inverse of seek and acts to steer the character so that its velocity is radially aligned away from the target. The desired velocity points in the opposite direction."

Kind: static method of behaviors

ParamType
optionsBasicBehaviorOptions

behaviors.pursue(options) ⇒ module:gl-matrix~vec3

"Pursuit is similar to seek except that the quarry (target) is another moving character. ... The position of a character T units of time in the future (assuming it does not maneuver) can be obtained by scaling its velocity by T and adding that offset to its current position. Steering for pursuit is then simply the result of applying the seek steering behavior to the predicted target location."

Kind: static method of behaviors

ParamType
optionsExtendedBasicBehaviorOptions

behaviors.evade(options) ⇒ module:gl-matrix~vec3

"Evasion is analogous to pursuit, except that flee is used to steer away from the predicted future position of the target character."

Kind: static method of behaviors

ParamType
optionsExtendedBasicBehaviorOptions

behaviors.arrive(options) ⇒ module:gl-matrix~vec3

"Arrival behavior is identical to seek while the character is far from its target. But instead of moving through the target at full speed, this behavior causes the character to slow down as it approaches the target, eventually slowing to a stop coincident with the target"

Kind: static method of behaviors

ParamType
optionsBasicWithRadiusBehaviorOptions

behaviors.avoidObstacles(options) ⇒ module:gl-matrix~vec3

"The implementation of obstacle avoidance behavior described here will make a simplifying assumption that both the character and obstacle can be reasonably approximated as spheres, although the basic concept can be easily extend to more precise shape models. ... It is convenient to consider the geometrical situation from the character’s local coordinate system. The goal of the behavior is to keep an imaginary cylinder of free space in front of the character. The cylinder lies along the character’s forward axis, has a diameter equal to the character’s bounding sphere, and extends from the character’s center for a distance based on the character’s speed and agility. An obstacle further than this distance away is not an immediate threat. The obstacle avoidance behavior considers each obstacle in turn (perhaps using a spatial portioning scheme to cull out distance obstacles) and determines if they intersect with the cylinder. By localizing the center of each spherical obstacle, the test for non-intersection with the cylinder is very fast. The local obstacle center is projected onto the side-up plane (by setting its forward coordinate to zero) if the 2D distance from that point to the local origin is greater than the sum of the radii of the obstacle and the character, then there is no potential collision. Similarly obstacles which are fully behind the character, or fully ahead of the cylinder, can be quickly rejected. For any remaining obstacles a line-sphere intersection calculation is performed. The obstacle which intersects the forward axis nearest the character is selected as the “most threatening.” Steering to avoid this obstacle is computed by negating the (lateral) side-up projection of the obstacle’s center.

Kind: static method of behaviors

ParamType
optionsObstacleBehaviorOptions

behaviors.wander(options) ⇒ module:gl-matrix~vec3

"The steering force takes a “random walk” from one direction to another. This idea ... is to constrain the steering force to the surface of a sphere located slightly ahead of the character. To produce the steering force for the next frame: a random displacement is added to the previous value, and the sum is constrained again to the sphere’s surface. The sphere’s radius ... determines the maximum wandering “strength” and the magnitude of the random displacement ... determines the wander “rate.”" Note: Don't forget to update theta and phi angles: angle += Math.random() WANDER_SPEED - WANDER_SPEED 0.5;

Kind: static method of behaviors

ParamType
optionsWanderBehaviorOptions

behaviors.followPath(options) ⇒ module:gl-matrix~vec3

"Path following behavior enables a character to steer along a predetermined path, such as a roadway, corridor or tunnel."

Kind: static method of behaviors

ParamType
optionsFollowPathBehaviorOptions

behaviors.followFlowFieldSimple(options) ⇒ module:gl-matrix~vec3

"In flow field following behavior the character steers to align its motion with the local tangent of a flow field (also known as a force field or a vector field). ... The future position of a character is estimated and the flow field is sampled at that location. This flow direction ... is the “desired velocity” and the steering direction (vector S) is simply the difference between the current velocity (vector V) and the desired velocity."

Kind: static method of behaviors

ParamType
optionsFollowFlowFieldSimpleBehaviorOptions

behaviors.followFlowField(options) ⇒ module:gl-matrix~vec3

Kind: static method of behaviors

ParamType
optionsFollowFlowFieldBehaviorOptions

behaviors.followLeaderSimple(options) ⇒ module:gl-matrix~vec3

"Leader following behavior causes one or more character to follow another moving character designated as the leader. Generally the followers want to stay near the leader, without crowding the leader, and taking care to stay out of the leader’s way (in case they happen to find them selves in front of the leader). In addition, if there is more than one follower, they want to avoid bumping each other. The implementation of leader following relies on arrival behavior (see above) a desire to move towards a point, slowing as it draws near. The arrival target is a point offset slightly behind the leader. (The offset distance might optionally increases with speed.) If a follower finds itself in a rectangular region in front of the leader, it will steer laterally away from the leader’s path before resuming arrival behavior. In addition the followers use separation behavior to prevent crowding each other."

Kind: static method of behaviors

ParamType
optionsFollowLeaderSimpleBehaviorOptions

behaviors.followLeader(options) ⇒ module:gl-matrix~vec3

Notes: next behaviour should be a separation

Kind: static method of behaviors

ParamType
optionsFollowLeaderBehaviorOptions

behaviors.separate(options) ⇒ module:gl-matrix~vec3

"To compute steering for separation, first a search is made to find other characters within the specified neighborhood. ... For each nearby character, a repulsive force is computed by subtracting the positions of our character and the nearby character, normalizing, and then applying a 1/r weighting. (That is, the position offset vector is scaled by 1/r 2.) Note that 1/r is just a setting that has worked well, not a fundamental value. These repulsive forces for each nearby character are summed together to produce the overall steering force."

Kind: static method of behaviors

ParamType
optionsGroupsBehaviorOptions

behaviors.cohere(options) ⇒ module:gl-matrix~vec3

"Cohesion steering behavior gives an character the ability to cohere with (approach and form a group with) other nearby characters. ... Steering for cohesion can be computed by finding all characters in the local neighborhood (as described above for separation), computing the “average position” (or “center of gravity”) of the nearby characters. The steering force can applied in the direction of that “average position” (subtracting our character position from the average position, as in the original boids model), or it can be used as the target for seek steering behavior."

Kind: static method of behaviors

ParamType
optionsGroupsBehaviorOptions

behaviors.align(options) ⇒ module:gl-matrix~vec3

"Alignment steering behavior gives an character the ability to align itself with (that is, head in the same direction and/or speed as) other nearby characters .... Steering for alignment can be computed by finding all characters in the local neighborhood (as described above for separation), averaging together the velocity (or alternately, the unit forward vector) of the nearby characters. This average is the “desired velocity,” and so the steering vector is the difference between the average and our character’s current velocity (or alternately, its unit forward vector)."

Kind: static method of behaviors

ParamType
optionsGroupsBehaviorOptions

behaviors.flock(options) ⇒ module:gl-matrix~vec3

"... in addition to other applications, the separation, cohesion and alignment behaviors can be combined to produce the boids model of flocks, herds and schools"

Kind: static method of behaviors

ParamType
optionsGroupsBehaviorOptions

behaviors.boundsConstrain(options) ⇒ module:gl-matrix~vec3

Constraint in system bounds.

Kind: static method of behaviors

ParamType
optionsBoundsConstraintBehaviorOptions

behaviors.sphereConstrain(options) ⇒ module:gl-matrix~vec3

Constraint in sphere bounds.

Kind: static method of behaviors

ParamType
optionsSphereConstraintBehaviorOptions

behaviors.boundsWrapConstrain(options) ⇒ module:gl-matrix~vec3

Wrap to opposite bound (no velocity change).

Kind: static method of behaviors

ParamType
optionsBoundsWrapConstraintBehaviorOptions

behaviors.sphereWrapConstrain(options) ⇒ module:gl-matrix~vec3

Wrap to opposite bound (no velocity change).

Kind: static method of behaviors

ParamType
optionsSphereWrapConstraintBehaviorOptions

Boid

A data structure for a single Boid.

Kind: global class Properties

NameType
positionmodule:gl-matrix~vec3
velocitymodule:gl-matrix~vec3
accelerationmodule:gl-matrix~vec3
targetArray.<module:gl-matrix~vec3>
behaviousArray.<BehaviorObject>

new Boid(behaviors)

ParamTypeDescription
behaviorsArray.<BehaviorObject>An array of behaviors to apply to the boid.

boid.applyForce(force)

Add a force to the boid's acceleration vector. If you need mass, you can either use behaviors.scale or override.

Kind: instance method of Boid

ParamType
forcemodule:gl-matrix~vec3

boid.applyBehaviors(applyOptions)

Compute all the behaviors specified in boid.behaviors and apply them via applyForce. Arguments usually come from the system and can be overridden via behavior.options.

Kind: instance method of Boid

ParamType
applyOptionsApplyBehaviorObject

boid.update(dt, maxSpeed)

Update a boid's position according to its current acceleration/velocity and reset acceleration. Usually called consecutively to boid.applyBehaviors.

Kind: instance method of Boid

ParamType
dtnumber
maxSpeednumber

Obstacle

Data structure used for obstacle avoidance behavior.

Kind: global class

new Obstacle(position, radius)

ParamTypeDescription
positionmodule:gl-matrix~vec3The center of the obstacle.
radiusnumberThe radius of the sphere.

Path

Data structure used for path following behavior.

Kind: global class

new Path(points, radius)

ParamTypeDescription
pointsArray.<module:gl-matrix~vec3>An array of 3d points.
radiusnumber

System

Handle common boids update and global state.

Kind: global class

new System(options)

ParamType
optionsSystemOptions

system.getRandomPosition() ⇒ Array.<number>

Get a position within the system's bounds.

Kind: instance method of System

system.addBoid(boid)

Push a new boid to the system.

Kind: instance method of System

ParamType
boidBoid

system.update(dt)

Update all behaviours in the system.

Kind: instance method of System

ParamType
dtnumber

SystemOptions : Object

Kind: global typedef Properties

NameTypeDefaultDescription
scalenumber1A global scale for the system.
maxSpeednumberscaleA maximum speed for the boids in the system. Can be tweaked individually via boid.maxSpeed.
maxForcenumberscaleA maximum force for each behavior of a boid. Can be tweaked individually via boid.maxForce or via behaviors.options.maxForce.
centermodule:gl-matrix~vec30, 0, 0A center point for the system.
boundsmodule:gl-matrix~vec3scale, scale, scalePositives bounds x/y/z for the system expanding from the center point.

Radians : number

Kind: global typedef

BehaviorObject : Object

Kind: global typedef Properties

NameType
fnfunction
enabledboolean
scalenumber
optionsObject

ApplyBehaviorObject : Object

Kind: global typedef Properties

NameType
boidsArray.<Boid>
maxSpeednumber
maxForcenumber
centermodule:gl-matrix~vec3
boundsmodule:gl-matrix~vec3

BehaviorOptions : Object

Kind: global typedef Properties

NameType
positionmodule:gl-matrix~vec3
velocitymodule:gl-matrix~vec3
maxSpeednumber

BasicBehaviorOptions : BehaviorOptions

Kind: global typedef Properties

NameType
targetmodule:gl-matrix~vec3

ExtendedBasicBehaviorOptions : BasicBehaviorOptions

Kind: global typedef Properties

NameType
targetVelocitymodule:gl-matrix~vec3

BasicWithRadiusBehaviorOptions : BasicBehaviorOptions

Kind: global typedef Properties

NameType
radiusnumber

ObstacleBehaviorOptions : BehaviorOptions

Kind: global typedef Properties

NameTypeDefault
obstaclesArray.<Obstacles>
maxAvoidForcenumber
fixedDistancebooleanfalse

WanderBehaviorOptions : Object

Kind: global typedef Properties

NameType
velocitymodule:gl-matrix~vec3
distancenumber
maxSpeednumber
radiusnumber
thetaRadians
phiRadians

FollowPathBehaviorOptions : BehaviorOptions

Kind: global typedef Properties

NameTypeDefault
pathPath
fixedDistancebooleanfalse

FollowFlowFieldSimpleBehaviorOptions : BehaviorOptions

Kind: global typedef Properties

NameType
flowFieldmodule:vector-field~FlowField

FollowFlowFieldBehaviorOptions : FollowFlowFieldSimpleBehaviorOptions

Kind: global typedef Properties

NameTypeDefault
flowFieldmodule:vector-field~FlowField
fixedDistancebooleanfalse

FollowLeaderSimpleBehaviorOptions : BehaviorOptions

Kind: global typedef Properties

NameType
leaderBoid
distancenumber
radiusnumber

FollowLeaderBehaviorOptions : FollowLeaderSimpleBehaviorOptions

Kind: global typedef Properties

NameTypeDefault
evadeScalenumber1
arriveScalenumber1

GroupsBehaviorOptions : BehaviorOptions

Kind: global typedef Properties

NameType
boidsArray.<Boid>
maxDistancenumber

ConstraintBehaviorOptions : BehaviorOptions

Kind: global typedef Properties

NameTypeDefault
centermodule:gl-matrix~vec3
maxDistancenumber
fixedDistancebooleanfalse

BoundsConstraintBehaviorOptions : ConstraintBehaviorOptions

Kind: global typedef Properties

NameType
boundsmodule:gl-matrix~vec3

SphereConstraintBehaviorOptions : ConstraintBehaviorOptions

Kind: global typedef Properties

NameType
radiusnumber

WrapConstraintBehaviorOptions : Object

Kind: global typedef Properties

NameType
positionmodule:gl-matrix~vec3
centermodule:gl-matrix~vec3

BoundsWrapConstraintBehaviorOptions : WrapConstraintBehaviorOptions

Kind: global typedef Properties

NameType
boundsmodule:gl-matrix~vec3

SphereWrapConstraintBehaviorOptions : WrapConstraintBehaviorOptions

Kind: global typedef Properties

NameType
radiusnumber

License

MIT. See license file.