Skip to content

About

Random value generators (float, int, vector and noise) for PEX.

Topics

Resources

Code of conduct

Contributing

Stars

5 stars

Watchers

4 watching

Forks

Repository files navigation

pex-random

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

Random value generators (float, int, vector and noise) for PEX.

Installation

npm install pex-random

Usage

import random from "pex-random";

// Use global PRNG
console.log(random.float());
// => unpredictable (seeded by performance.now())

// Seed global PRNG
random.seed("0");
console.log(random.float());
// => predictable, always returns: 0.8071179636424909

// Use local PRNG
const localRandom = random.create();
console.log(localRandom.float());
// => unpredictable (seeded by performance.now() + INCREMENT)

// Use seeded local PRNG
const localSeededRandom = random.create("0");
console.log(localSeededRandom.float());
// => predictable, always returns: 0.8071179636424909

Vector and curl noise

  • vec2Noise(x, y, z?, out?) / vec3Noise(x, y, z, w?, out?): one independent noise per component, in [-1, 1]. For displacement, wind, colour.
  • curl2(x, y, t?, out?) / curl3(x, y, z, t?, out?): divergence-free velocity (Bridson et al. 2007). Particles swirl without piling up or leaving holes.
  • The last coordinate animates the field: pass time.
import random from "pex-random";
import { vec2 } from "pex-math";

const field = random.create("flow");
const frequency = 0.01;
const speed = 1;
const velocity = [];
const particles = Array.from({ length: 1000 }, () => ({
  position: field.vec2InRect([
    [0, 0],
    [512, 512],
  ]),
  age: 0,
}));

let time = 0;
const update = (dt) => {
  time += dt * 0.2;
  for (const particle of particles) {
    const [x, y] = particle.position;
    field.curl2(x * frequency, y * frequency, time, velocity);
    vec2.addScaled(particle.position, velocity, speed);

    // Unbounded field: respawn after a lifetime.
    if ((particle.age += dt) > 3) {
      field.vec2InRect(
        [
          [0, 0],
          [512, 512],
        ],
        particle.position,
      );
      particle.age = 0;
    }
  }
};

Notes:

  • noise2/3/4, vector and curl noise: coordinates must be between -2^31 and 2^31. Eg. using Date.now() is not viable but performance.now() is.
  • similar seeds might not result in different starting values
  • Move particles with curl2/3, not vec2Noise/vec3Noise. Plain noise has sinks: particles collapse into lines and points.
  • 2D particles: use curl2. The xy of curl3 is not divergence-free in 2D.
  • Don't normalize the curl: it breaks divergence-free. Scale it by a constant instead.
  • Spatially varying strength: don't multiply the velocity by a mask A(p), use A · curl3(p) + cross(∇A, vec3Noise(p)).
  • Turbulence: sum curl3 at several frequencies, each scaled by any amplitude. Still divergence-free.
  • Time morphs the field in place: swirls form and fade, they don't travel. To scroll it, offset the coordinates instead (curl2(x + t, y)).
  • Curl vectors are longer than noise values: typical length ~2–4, rare peaks ~14. Scale them before adding to positions (e.g. × 0.5 moves ~1–2 units per step).
  • Frequency sets the swirl size, not the curl length: curl2(x * f, y * f) returns similar lengths for any f. Multiply the result by f for smaller swirls to move faster, as in a real fluid.
  • vec3Noise returns shorter vectors than vec2Noise (~0.4 vs ~0.7 on average, 4D vs 3D simplex): rescale when switching.

API

Modules

pex-random

Classes

pex-random

Typedefs

FBMOptions

pex-random

Summary: Export a Random instance using the global PRNG:

  • The instance is seeded by performance.now()
  • Call random.seed("seed") to overwrite the global PRNG: all other calls to random.float() will derive from the new seeded state.
  • Call random.create() to create a local instance of Random with a separate unpredictable PRNG.
  • Call random.create("seed") to create a local instance of Random with a separate predictable PRNG: all other calls to random.float() will derive from the new seeded state.

pex-random

Kind: global class

new Random([seed])

Creates an instance of Random.

Param Type Default
[seed] string | number "Random.NOW + Random.#instanceCount"

pex-random.create ⇒ Random

Create an instance of Random.

Kind: instance property of pex-random

Param Type Description
[seed] string | number If omitted, the global PRNG seed will be used and incremented for each local PRNG.

pex-random.seed(s)

Set the seed for the random number generator.

Kind: instance method of pex-random

Param Type Description
s string Seed value

pex-random.float([min], [max]) ⇒ number

Get a float between min and max. Defaults to:

  • 0 <= x < 1 if no argument supplied
  • 0 <= x < max if only one argument supplied

Kind: instance method of pex-random

Param Type
[min] number
[max] number

pex-random.int([min], [max]) ⇒ number

Get an int between min and max. Defaults to:

  • 0 <= x < Number.MAX_SAFE_INTEGER if no argument supplied
  • 0 <= x < max if only one argument supplied

Kind: instance method of pex-random

Param Type
[min] number
[max] number

pex-random.vec2([r], [out]) ⇒ module:pex-math~Vec2

Get a vec2 included in a radius.

Kind: instance method of pex-random

Param Type Default Description
[r] number 1 Radius
[out] module:pex-math~Vec2 []

pex-random.vec3([r], [out]) ⇒ module:pex-math~Vec3

Get a vec3 included in a radius.

Kind: instance method of pex-random

Param Type Default Description
[r] number 1 Radius
[out] module:pex-math~Vec3 []

pex-random.vec2InRect(rect, [out]) ⇒ module:pex-math~Vec2

Get a vec2 included in a rectangle.

Kind: instance method of pex-random

Param Type Default Description
rect number Rectangle
[out] module:pex-math~Vec2 []

pex-random.vec3InAABB(bbox, [out]) ⇒ module:pex-math~Vec3

Get a vec3 included in a rectangle bbox.

Kind: instance method of pex-random

Param Type Default Description
bbox number Rectangle bbox
[out] module:pex-math~Vec3 []

pex-random.quat([out]) ⇒ module:pex-math~Quat

Get a random quaternion.

Kind: instance method of pex-random See

  • [Graphics Gems III, Edited by David Kirk, III.6 UNIFORM RANDOM ROTATIONS]
  • Steve LaValle
Param Type Default
[out] module:pex-math~Quat []

pex-random.chance([probability]) ⇒ boolean

Returns a chance of an event occuring according to a given probability between 0 and 1.

Kind: instance method of pex-random

Param Type Default Description
[probability] number 0.5 Float between 0 and 1.

pex-random.element(list) ⇒ any

Gets a random element from a list.

Kind: instance method of pex-random

Param Type
list Array

pex-random.noise2(x, y) ⇒ number

Samples the noise field in 2 dimensions.

Kind: instance method of pex-random Returns: number - In the interval [-1, 1]

Param Type
x number
y number

pex-random.noise3(x, y, z) ⇒ number

Samples the noise field in 3 dimensions.

Kind: instance method of pex-random Returns: number - In the interval [-1, 1]

Param Type
x number
y number
z number

pex-random.noise4(x, y, z, w) ⇒ number

Samples the noise field in 4 dimensions.

Kind: instance method of pex-random Returns: number - In the interval [-1, 1]

Param Type
x number
y number
z number
w number

pex-random.vec2Noise(x, y, [z], [out]) ⇒ module:pex-math~Vec2

Samples a vector noise field in 2 dimensions.

Kind: instance method of pex-random Returns: module:pex-math~Vec2 - Each component in the interval [-1, 1]

Param Type Default Description
x number
y number
[z] number 0 E.g. time
[out] module:pex-math~Vec2 []

pex-random.vec3Noise(x, y, z, [w], [out]) ⇒ module:pex-math~Vec3

Samples a vector noise field in 3 dimensions.

Kind: instance method of pex-random Returns: module:pex-math~Vec3 - Each component in the interval [-1, 1]

Param Type Default Description
x number
y number
z number
[w] number 0 E.g. time
[out] module:pex-math~Vec3 []

pex-random.curl2(x, y, [t], [out]) ⇒ module:pex-math~Vec2

Samples a divergence-free curl noise field in 2 dimensions.

Kind: instance method of pex-random See: Bridson et al., Curl-Noise for Procedural Fluid Flow

Param Type Default Description
x number
y number
[t] number 0 Time
[out] module:pex-math~Vec2 []

pex-random.curl3(x, y, z, [t], [out]) ⇒ module:pex-math~Vec3

Samples a divergence-free curl noise field in 3 dimensions.

Kind: instance method of pex-random See: Bridson et al., Curl-Noise for Procedural Fluid Flow

Param Type Default Description
x number
y number
z number
[t] number 0 Time
[out] module:pex-math~Vec3 []

pex-random.fbm(options, ...d) ⇒ number

Fractional Brownian motion (also called fractal Brownian motion) noise. Default to 1/f noise with 8 octaves.

Kind: instance method of pex-random Returns: number - In the interval [-1, 1]

Param Type Description
options FBMOptions
...d number X, y, z?, w?

FBMOptions

Kind: global typedef Properties

Name Type Default
[octaves] number 8
[lacunarity] number 2
[gain] number 0.5
[frequency] number 1
[amplitude] number gain
[noise] function

License

MIT. See license file.

About

Random value generators (float, int, vector and noise) for PEX.

Topics

Resources

Code of conduct

Contributing

Stars

5 stars

Watchers

4 watching

Forks

Releases

Used by

Contributors

Languages