Skip to main content

Math Utilities

Immutable vector and color classes optimized for game development, backed by Float32Array for performance.

Overview

The math module provides:

  • Vector2 - 2D vectors for screen coordinates, UV mapping
  • Vector3 - 3D vectors for world positions, rotations, velocities
  • Color - RGBA colors with hex conversion

All classes are immutable by default—operations return new instances rather than mutating.

Design

Float32Array Backend

Uses typed arrays for efficient memory layout and GPU compatibility:

// Internally stores [x, y, z] in a Float32Array
const pos = vec3(100, 200, 30);

Immutable Operations

Math operations create new vectors:

const a = vec3(1, 2, 3);
const b = vec3(4, 5, 6);

const sum = a.add(b); // New vector (5, 7, 9)
const scaled = a.scale(2); // New vector (2, 4, 6)
// 'a' remains unchanged

Freezing

Use freeze() for truly immutable constants:

const ORIGIN = vec3(0, 0, 0).freeze();
// Any mutation attempt throws ImmutableVectorException

Built-in constants Vector3.ZERO and Vector3.ONE are pre-frozen.

Helper Functions

Convenience constructors for cleaner code:

import { vec2, vec3, color } from "@core/math";

const screenPos = vec2(0.5, 0.5);
const worldPos = vec3(100, 200, 30);
const red = color(1, 0, 0, 1);

Common Operations

OperationDescription
add(other)Vector addition
sub(other)Vector subtraction
scale(n)Scalar multiplication
normalize()Unit vector
magnitude()Vector length
distance(other)Distance between vectors
dot(other)Dot product
cross(other)Cross product (Vector3 only)

Integration with Entity Classes

Entity classes use Vector3 for positions and rotations:

import { Player, vec3 } from "@core/classes";

const ped = Player.LOCAL.ped;
const pos = ped.coords; // Returns Vector3
ped.coords = vec3(100, 200, 30); // Accepts Vector3

Color Utilities

Colors support hex conversion for UI integration:

import { color, Color } from "@core/math";

const c = color(1.0, 0.5, 0.0, 1.0);
const hex = c.toHex(); // "#ff8000ff"
const parsed = Color.fromHex("#ff8000");

See the API Reference for complete method documentation.