Math
Tide's math follows Unity.Mathematics, with Tide's naming: functions live on Math, in PascalCase. It's all deterministic: the same inputs give the same bits on every platform (see Determinism).
quaternion spin = quaternion.AxisAngle(float3(0, 1, 0), input.turn * time.dt);
trs.rotation = Math.Mul(trs.rotation, spin);
float3 forward = Math.Rotate(trs.rotation, float3(0, 0, 1));
trs.position += Math.Normalize(forward) * 5 * time.dt;
float2 flat = trs.position.xz;Types
| Type | What it is |
|---|---|
float2, float3, float4 |
32-bit float vectors |
double2, double3, double4 |
64-bit double vectors |
int2, int3, int4 |
Int vectors |
quaternion |
A rotation |
float2x2, float3x3, float4x4 |
32-bit matrices, stored column by column |
double2x2, double3x3, double4x4 |
64-bit matrices with the same column storage |
They're lowercase built-in value types, like float. Angles are in radians: Math.Radians(degrees) and Math.Degrees(radians) convert.
For a constant angle, add lowercase deg to a decimal number: quaternion.Euler(0, 180deg, 0) turns halfway around Y. 180deg is an ordinary float already in radians, converted at compile time with the same result as Math.Radians(180.0). Fractional, exponent and underscore forms work too (.5deg, 1e2deg, 1_8_0deg), as does unary minus (-90deg). Use Math.Radians(value) when the degree value is computed at runtime.
Building values
- Vectors take any mix of scalars and vectors that adds up to their size,
float4(v.xy, 0, 1), or one scalar for every component,float3(1). float3(i)andint3(f)convert between int and float vectors, andint(x)andfloat(x)between scalars. Float to int truncates toward zero, saturates at the int range, and turns NaN into 0.- An int vector converts to a float vector of the same size by itself, like
inttofloat. quaternion(x, y, z, w),quaternion(float4)andquaternion(float3x3).- Matrices take one vector per column,
float3x3(c0, c1, c2), or all their numbers row by row: infloat2x2(1, 2, 3, 4),1, 2is the first row. Alsofloat3x3(quaternion), andfloat4x4(rotation, translation)from afloat3x3and afloat3.
Color space
Math.ToLinear(value) decodes sRGB RGB to linear light; Math.ToDisplay(value) encodes
linear RGB for display. They take float, float3 or Color in CPU and GPU code. RGB
clamps to [0, 1], NaN maps to zero, and a Color's alpha is copied unchanged. GPU results
have the same rounding limits as other Math functions. Both ends are exact everywhere: 0
gives 0 and 1 gives 1, so Math.ToDisplay(Math.ToLinear(Color.white)) == Color.white. Tone-map HDR light before encoding.
For color textures, prefer [Linear], which also
makes filtering and mipmaps operate in linear light.
Double precision
Use double and double2/double3/double4 for high precision values. They support ordinary construction, swizzles and component-wise + - * /. Integers and floats widen when mixed with doubles; converting back requires an explicit constructor.
double3 objectPosition = double3(1_000_000_000.125d, 2d, 3d);
double3 cameraPosition = double3(1_000_000_000d, 0d, 0d);
float3 nearby = float3(objectPosition - cameraPosition);Subtract in double precision before converting to float. This example preserves the 0.125 offset. It is an explicit conversion pattern; the camera and Transform APIs still take floats.
Double math includes Abs, Sign, Min, Max, Clamp, Floor, Ceil, Round, Trunc, Frac, Sqrt, Rsqrt, Saturate, Radians, Degrees, Step, Lerp, Unlerp and SmoothStep, component by component. Vector geometry includes Dot, Length, LengthSq, Distance, DistanceSq, Normalize, Reflect, Csum, Cmin, Cmax and three-dimensional Cross. Math.Hash hashes all 64 bits of each component.
The same deterministic arithmetic rules apply. Normalize gives zero when the squared length is NaN or at or below the smallest normal double (about 2.23e-308); otherwise it uses v * (1 / Sqrt(Dot(v, v))).
Sin, Cos, Tan, Asin, Acos, Atan, Atan2, Exp, Exp2, Log, Log2, Log10 and Pow also work on doubles and double vectors, retaining binary64 input and output precision. They use portable source compiled with Tide's deterministic flags, including full-range argument reduction for large angles; they do not call the platform math library. Like the float implementations, these are accurate approximations, not a promise of correctly rounded results for every input.
Use double.PI, double.TAU and double.E for binary64 constants. Existing Math.PI, Math.TAU and Math.E remain floats.
Double matrices have the same operations as float matrices: columns, construction from columns or numbers row by row, identity, +, -, scalar *//, and Math.Mul, Transpose, Inverse and Determinant. Matching float matrices widen implicitly; float4x4(matrix) explicitly narrows every component. double3x3(quaternion) widens quaternion components before evaluating the matrix. double4x4(rotation, translation) takes a double3x3 and a double3.
Math.Transform and Math.Rotate accept double4x4 and double3. double4x4 provides Translate, Scale, TRS, PerspectiveFov and Ortho. TRS accepts either a double3x3 rotation or a quaternion; a quaternion retains its original float precision, then the matrix arithmetic is double. Views interpolate double matrices column by column in double precision.
double angle = double.PI / 4d;
double c = Math.Cos(angle);
double s = Math.Sin(angle);
double3x3 rotation = double3x3(c, -s, 0d, s, c, 0d, 0d, 0d, 1d);
double4x4 transform = double4x4.TRS(objectPosition, rotation, double3(1d));
double3 worldPoint = Math.Transform(transform, double3(.125d, 0d, 0d));Double noise and a double quaternion type remain unsupported. Doubles are CPU values: convert to float scalars, vectors or matrices in local code before supplying shader data. The renderer and cameras still take floats.
Members
- Vectors have
x,y,zandw. - Swizzles read any combination:
v.xz,v.zyx,v.xxyy. They can be assigned too, as long as no component repeats:v.xz = float2(1, 2). - A
quaternion'svalueis afloat4, with (x, y, z) as the vector part. - A matrix's columns are
c0toc3.
Constants
Math.PI, Math.TAU, Math.E, quaternion.identity, float2x2.identity, float3x3.identity and float4x4.identity.
And these build values:
quaternion.AxisAngle(axis, angle)quaternion.Euler(radians)takes afloat3, orquaternion.Euler(x, y, z)takes three angles in radians. The scalar form equalsquaternion.Euler(float3(x, y, z)). Both rotate Z first, then X, then Y, Unity's default order.quaternion.LookRotation(forward, up)turns +z toforwardand +y as nearupas it can go. Neither need be normalized. A zero or nonfiniteforwardgives identity; anupwith no side to it (zero, nonfinite or alongforward) givesFromToRotation(float3(0, 0, 1), forward), as Unity does.quaternion.FromToRotation(from, to)gives the shortest rotation between twofloat3directions. They need not be normalized. Zero or nonfinite directions give identity; opposite directions use a deterministic perpendicular axis.float4x4.TRS(translation, rotation, scale)float4x4.Translate(translation)float4x4.Scale(scale)builds a scale matrix from afloat3, with no rotation or translation. Zero and negative scales work too.float4x4.PerspectiveFov(verticalFov, aspect, near, far)andfloat4x4.Ortho(width, height, near, far): projections for a 3D camera, as Unity.Mathematics' (see Any projection)
var aim = quaternion.FromToRotation(float3(0, 0, 1), target - position);
var size = float4x4.Scale(float3(2, 1, 0.5));FromToRotation accepts finite nonzero directions across the full float range. For an exact half-turn, it crosses normalized from with the least-aligned cardinal axis, preferring X, then Y, then Z when tied.
LookRotation's result is a unit rotation whose forward is forward normalized, across the full float range. Its up is up with the part along forward taken out. When the cross product of the two normalized is shorter than 1e-5 (Unity's epsilon), they're along one line, or within about 1e-5 radians of it, and there's no side to take the up from: the result is FromToRotation from +z instead.
These builders work in frags and verts too, with the GPU's usual float rounding.
Operators
+ - * /work component by component on vectors, and%on int vectors. A scalar widens to the vector's size, and int to float, sov * 2 + 1works.- Matrices have
+and-with their own type, and*and/by a number. There's no*between matrices, or between a matrix and a vector: that'sMath.Mul. - Quaternions have no operators: combine rotations with
Math.Mul, and rotate vectors withMath.Rotate. ==and!=compare two vectors of one size, or two colors, whole, and give onebool:a == bis true when every component is equal, anda != bwhen any differs. An int vector beside a float or a double one is widened first, as for+, soint2(1, 2) == float2(1, 2)is true. Each component compares as floats do:-0equals0, and a NaN equals nothing, itself included. A color's alpha counts.<,<=,>and>=work on scalars only: a vector has no order. Compare the components you mean (a.x < b.x) or a length (Math.LengthSq(a) < Math.LengthSq(b)).- A vector never compares with a number: write the vector you mean,
v == float3(0). Matrices compare column by column (a.c0 == b.c0 && a.c1 == b.c1), aRectby its parts (a.position == b.position && a.size == b.size), and a quaternion has no==, asqand-qare one rotation:a.value == b.valuecompares its four numbers, andMath.Abs(Math.Dot(a, b)) > 0.99999asks for the same rotation.
if (cell == target) found = true; // int2: both components
if (body.velocity != float3(0)) Wake(body); // Any component that isn't 0
bool spotted = seen.Contains(int2(x, y)); // A list's Contains, IndexOf and Remove compare the same wayThis is Tide's own: Unity.Mathematics' == on vectors gives a vector of bools, where Tide's gives the one answer a condition needs. It works in frags and verts too, and in constants and field defaults, though there the value is worked out as the game runs, not while compiling: a constant made from a vector comparison can't be a case label, an array's length or a setting.
Functions
Component by component, on numbers, vectors and colors:
Abs, Sign, Min, Max, Clamp (ints too), Floor, Ceil, Round (ties to even), Trunc, Frac, Sqrt, Rsqrt, Saturate, Radians, Degrees, Sin, Cos, Tan, Asin, Acos, Atan, Atan2, Exp, Exp2, Log, Log2, Log10, Pow, Step, Lerp, Unlerp, SmoothStep.
A color goes through them channel by channel, alpha too, with other colors and with numbers, which count for every channel: Math.Lerp(cold, hot, heat) is the color that far from cold to hot, and Math.Saturate(color) keeps each channel from 0 to 1. A color and a vector don't mix in one call.
Easing, a progress t from 0 to 1 shaped as an animation's is:
| Function | Shape |
|---|---|
Math.EaseIn(t) |
Starts slowly and speeds up (cubic) |
Math.EaseOut(t) |
Starts fast and settles: what most UI that arrives uses |
Math.EaseInOut(t) |
Slow at both ends, for something that moves from one place to another |
Math.EaseInBack(t) |
Pulls back a little below 0 first: an anticipation |
Math.EaseOutBack(t) |
Overshoots 1 by about 10% and settles back: a pop |
Each is 0 at 0 and 1 at 1; past the ends it's at them, and NaN is 0. They're plain arithmetic, the same on every machine, so they work in match code, in views, and in GPU code. Shape a progress with them and blend by it: Math.Lerp(from, to, Math.EaseOutBack(t)). GUI.Tween makes a progress that takes a fixed time.
On the way to a value, for a speed that builds up, a camera that follows and a turn that takes the short way:
| Function | Gives |
|---|---|
Math.MoveTowards(current, target, step) |
current at most step closer to target, never past it. Floats, and float2 and float3 points along the straight line between them |
Math.Damp(current, target, rate, dt) |
current eased towards target: closer by the same share each second, whatever dt is. Floats, float2 and float3 |
Math.DeltaAngle(from, to) |
The shortest turn from one angle to the other, over -PI and up to PI: 0.18 from 6.2 to 0.1, not -6.1 |
Math.WrapAngle(angle) |
The same angle over -PI and up to PI |
Math.MoveTowardsAngle(current, target, step) |
current turned at most step towards target, the short way round. It isn't wrapped |
body.speed = Math.MoveTowards(body.speed, wanted, ACCELERATION * time.dt);
body.yaw = Math.WrapAngle(Math.MoveTowardsAngle(body.yaw, aim, TURN_SPEED * time.dt));
look.eye = Math.Damp(look.eye, target, 12, Frame.dt);Math.Damp is what Math.Lerp(a, b, dt * 12) is usually meant to be: the lerp goes further on a slow frame than on two fast ones and overshoots past dt * 12 = 1, where Damp ends in the same place however the seconds are cut. rate is in shares a second: at 12, about 70% of the way in a tenth of a second. A rate * dt under 0, or one that isn't a number, leaves current as it is.
MoveTowards with a step that isn't a number gives target, and a step under 0 moves away, as Unity's does. DeltaAngle of an angle that isn't a number, or is infinite, is 0. All five are the same on every machine and work in GPU code.
Vectors:
Dot, Cross, Length, LengthSq, Distance, DistanceSq, Normalize (zero for a zero vector, never NaN), Reflect, Csum, Cmin, Cmax.
Quaternions:
Mul (two rotations, or a rotation and a float3, which it rotates), Rotate, Inverse, Conjugate, Normalize (the identity for a zero quaternion), Dot, Slerp, Nlerp, Forward, Up, Right, Angle.
Matrices:
Mul (two matrices, or a matrix and a vector of its size), Transpose, Inverse, Determinant, and for float4x4, Transform (a point) and Rotate (a direction).
Each button below plots a function of Math from 0 to 1. The white dot goes along the curve, and the teal one moves by the same number, to see what it does to something that moves.
settings { title = "Math"; }
local scene Main { }
local singleton Plot
{
int curve = 1;
float x; // Goes from 0 to 1, again and again
}
// Each takes a number from 0 to 1 and gives one back.
float Curve(int curve, float x)
{
switch (curve)
{
case 0: return Math.Lerp(0, 1, x);
case 1: return Math.SmoothStep(0, 1, x);
case 2: return Math.Pow(x, 3);
case 3: return Math.Sin(x * Math.PI);
case 4: return Math.Frac(x * 3);
}
return Math.Abs(Math.Cos(x * Math.TAU * 1.5)) * (1 - x);
}
string Formula(int curve)
{
switch (curve)
{
case 0: return "Math.Lerp(0, 1, x)";
case 1: return "Math.SmoothStep(0, 1, x)";
case 2: return "Math.Pow(x, 3)";
case 3: return "Math.Sin(x * Math.PI)";
case 4: return "Math.Frac(x * 3)";
}
return "Math.Abs(Math.Cos(x * Math.TAU * 1.5)) * (1 - x)";
}
view Graph(mut Plot plot)
{
plot.x += Math.Min(Frame.dt, 0.05) * 0.4;
if (plot.x > 1) plot.x -= 1;
Draw.Clear(Color(0.086, 0.086, 0.094));
Draw.SetCamera(float2(0.62, 0.42), 0.85); // The graph goes from (0, 0) to (1, 1)
Draw.WireRect(float2(0.5), float2(1), Color(0.24, 0.25, 0.27));
for (var i = 0; i < 96; i++)
{
float from = i / 96.0;
float to = (i + 1) / 96.0;
Draw.Line(float2(from, Curve(plot.curve, from)), float2(to, Curve(plot.curve, to)), 0.012, Color(0.98, 0.75, 0.14));
}
var y = Curve(plot.curve, plot.x);
Draw.Line(float2(plot.x, 0), float2(plot.x, y), Color(0.3, 0.3, 0.33));
Draw.Line(float2(plot.x, y), float2(1.25, y), Color(0.3, 0.3, 0.33));
Draw.Circle(float2(plot.x, y), 0.03, Color.white);
// The same number, moving something.
Draw.Circle(float2(1.25, y), 0.06, Color(0.18, 0.83, 0.75));
Draw.SetScreen();
Draw.Text(Formula(plot.curve), float2(16, 14), 15, Color.white);
GUI.SetTheme(GUITheme { radius = 6 });
GUILayout.Area(Rect(12, Screen.height - 52, Screen.width - 24, 40))
{
GUILayout.Horizontal()
{
if (GUILayout.Button("Lerp")) plot.curve = 0;
if (GUILayout.Button("Smooth")) plot.curve = 1;
if (GUILayout.Button("Pow")) plot.curve = 2;
if (GUILayout.Button("Sin")) plot.curve = 3;
if (GUILayout.Button("Frac")) plot.curve = 4;
if (GUILayout.Button("Mix")) plot.curve = 5;
}
}
}Hashing:
Math.Hash(value) turns an int, long, int2, int3, int4, float, float2, float3 or float4 into a random-looking int from 0 to 2147483647. The same value always gives the same number, on every machine. It keeps no state, so it works anywhere, parallel loops included:
// About one cell in four starts as sand, the same cells everywhere.
if (Math.Hash(int2(x, y)) % 4 == 0) field.cells[x, y] = Material.Sand;Put a seed in the value to get other numbers for the same cell: Math.Hash(int3(x, y, seed)). It's xxHash32, so every bit of the value affects the result. With the match's seed, Random.seed, matches can get different fields: Math.Hash(int3(x, y, Random.seed)). Reusing a seed repeats its field.
It gives the same numbers in a frag or vert, so a pattern drawn from it is the same on every GPU. Only a long's hash stays on the CPU.
Float hashes use the exact input bits: Math.Hash(value) equals Math.Hash(Math.AsInt(value)). Positive and negative zero hash differently. This hashes represented values; float calculations on the GPU still have their usual rounding.
Bit casts:
Math.AsInt(value) reinterprets a float, float2, float3 or float4 as the corresponding int type. Math.AsFloat(bits) reverses it. These preserve the 32 bits of each component without a numeric conversion:
int bits = Math.AsInt(1.0); // 0x3f800000
float value = Math.AsFloat(bits); // 1.0Both work on the CPU and in frags/verts. Use the ordinary int(value) or float(value) constructors for numeric conversions.
Noise
Noise is random that's smooth: a number for every point, with nearby points nearby. It's what terrain, clouds, water and wear are made of. Each function takes a float2 or a float3 and a seed, which a call can leave out (it's 0 then), and keeps no state, so it works anywhere a hash does: in a system, a parallel loop or a frag.
| Function | Gives | What it's like |
|---|---|---|
Math.Perlin(point[, seed]) |
A float from -1 to 1 | Gradient noise: smooth hills, 0 at every whole number, so the features are about a unit across |
Math.Simplex(point[, seed]) |
A float from about -1 to 1 | The same kind of hills with no grid showing through, cheaper in 3D |
Math.Cellular(point[, seed]) |
A float2: the distances to the nearest feature point and the next, from 0 to about 1.4 |
Cells, like a dry lake bed or a cobbled road: there's a feature point in every unit cell, .x is 0 on one, and .y - .x is 0 on the borders between cells |
The point's scale sets the features' size: Math.Perlin(position * 0.1) has hills about ten units across. Octaves add detail: each twice as fine and half as strong, summed.
// Terrain: three octaves of Perlin noise, from -1 to 1, the same on every machine
float Height(float2 at, int seed)
{
return Math.Perlin(at * 0.05, seed) * 0.57 + Math.Perlin(at * 0.1, seed + 1) * 0.29 + Math.Perlin(at * 0.2, seed + 2) * 0.14;
}Every one of them is built from the basic operations and Math.Hash, so a point gives the same bits on every machine: noise can be in the match, and a cell of terrain is the same for every player. Another seed is another field of noise, so Random.seed gives each match its own world. They go to the GPU too (next), with the same cells, so a frag that shades a tile by its noise shades it as the match computed it.
settings { title = "Noise"; }
local scene Main { }
struct FieldVertex
{
float2 position;
float2 uv;
}
local singleton Field
{
List<FieldVertex> corners;
List<int> faces;
int kind; // 0 Perlin, 1 Simplex, 2 Cellular
int seed;
float scale = 4;
float octaves = 1; // More octaves, each twice as fine and half as strong, for detail
float drift;
}
// The noise at a point, in the kind the buttons picked: from 0 to 1.
float FieldAt(float2 at, int kind, int seed)
{
if (kind == 0) return Math.Perlin(at, seed) * 0.5 + 0.5;
if (kind == 1) return Math.Simplex(at, seed) * 0.5 + 0.5;
float2 cells = Math.Cellular(at, seed);
return cells.y - cells.x; // 0 on the borders between cells
}
// Every pixel of the quad: octaves of noise, summed, in the site's colors.
frag Shade(FieldVertex vertex, out Color color, Field field)
{
mut float2 at = vertex.uv * field.scale + field.drift;
mut float sum = 0;
mut float weight = 1;
mut float total = 0;
for (int octave = 0; octave < int(field.octaves); octave++)
{
sum += FieldAt(at, field.kind, field.seed + octave) * weight;
total += weight;
at *= 2;
weight *= 0.5;
}
float3 dark = float3(0.086, 0.086, 0.094);
float3 light = field.kind == 2 ? float3(0.18, 0.83, 0.75) : float3(0.98, 0.75, 0.14);
float3 rgb = Math.Lerp(dark, light, sum / total);
color = Color(rgb.x, rgb.y, rgb.z, 1);
}
view Show(mut Field field)
{
if (field.corners.count == 0)
{
// A quad under the controls, its uv in units of its width, so the noise isn't stretched
field.corners = [FieldVertex { position = float2(-1, -1.55), uv = float2(0, 0) },
FieldVertex { position = float2(1, -1.55), uv = float2(1, 0) },
FieldVertex { position = float2(1, -0.1), uv = float2(1, 0.725) },
FieldVertex { position = float2(-1, -0.1), uv = float2(0, 0.725) }];
field.faces = [0, 1, 2, 0, 2, 3];
}
field.drift += Math.Min(Frame.dt, 0.05) * 0.2;
Draw.Clear(Color(0.086, 0.086, 0.094));
Draw.SetCamera(float2(0, -0.6), 1.25);
Draw.Mesh(field.corners, field.faces, Shade);
GUI.SetTheme(GUITheme { radius = 6 });
GUILayout.Area(Anchor.UpperLeft)
{
GUILayout.Horizontal()
{
if (GUILayout.Button("Perlin")) field.kind = 0;
if (GUILayout.Button("Simplex")) field.kind = 1;
if (GUILayout.Button("Cellular")) field.kind = 2;
if (GUILayout.Button("New seed")) field.seed += 1;
}
GUILayout.Slider("Scale", field.scale, 1, 16);
GUILayout.Slider("Octaves", field.octaves, 1, 6);
}
}Random numbers
Random rolls numbers, with nothing to set up:
component Wanderer
{
float2 heading;
}
system Wander(mut Wanderer wanderer, mut Body body)
{
// About twice a second, another way to go.
if (Random.NextInt(30) == 0) wanderer.heading = Random.NextFloat2Direction();
body.velocity = wanderer.heading * 3;
}In the match, a roll comes from the match's seed, the tick, the entity the code runs for and which system or handler is rolling. So every machine rolls the same numbers, each entity gets its own, and a tick a client runs again after a wrong prediction rolls what it rolled the first time. Nothing is stored and nothing is written: a system that rolls takes no parameter for it, waits for no other system over it, and still runs its entities on several threads at once.
| Method | What it gives |
|---|---|
NextInt() |
An int from 0 to 2147483647, like Math.Hash's, so % never goes negative |
NextInt(max) |
From 0 up to max, max excluded: NextInt(6) is 0 to 5 |
NextInt(min, max) |
From min up to max, max excluded: NextInt(1, 7) is a die |
NextFloat() |
A float from 0 up to 1, 1 excluded |
NextFloat(max) |
From 0 up to max, max excluded |
NextFloat(min, max) |
From min up to max, max excluded |
NextBool() |
True or false, each as likely |
NextFloat2(), NextFloat3() |
A vector with each component from 0 up to 1 |
NextFloat2(min, max), NextFloat3(min, max) |
Each component from min's up to max's: a point in a rectangle or a box |
NextFloat2Direction(), NextFloat3Direction() |
A vector of length 1, every direction as likely |
NextQuaternionRotation() |
A rotation, every one as likely |
They follow Unity.Mathematics' Random. A range with nothing in it gives its start: NextInt(0) is 0, and NextFloat(2, 1) is 2.
In CPU code, rolls run in the order they're written, left to right: in float2(Random.NextFloat(), Random.NextFloat()), x is rolled first, on every platform. GPU code has additional ordering limits.
Where rolls work
- Systems and the match's handlers roll for the entity they run for, or for the match where they run once. Two systems that roll for the same entity in the same tick get different numbers, and so do two runs of a handler.
- Views and local handlers roll with this machine's own generator, for effects: sparks, shakes, anything the match doesn't see. It's no part of the match, and other machines roll otherwise.
- Functions, methods and operators they call roll too, with nothing passed:
float2 Scatter(float spread)
{
return Random.NextFloat2Direction() * Random.NextFloat(spread);
}- A parallel loop's steps roll each for their own cell or element, so the loop gives the same numbers however many threads run it. A
foreachover a grid that rolls for each cell still runs its steps at once.
system Scatter(mut Field field)
{
parallel (var at in field.cells)
{
if (Random.NextInt(100) == 0) field.cells[at] = Material.Rock;
}
}- A task has a sequence of its own, which goes on across its waits and into the tasks it awaits. Two tasks started alike in the same tick roll differently.
- The input's
Samplerolls on the machine that sends the input, with that machine's generator, as a view does. - An audio declaration rolls for noise, each voice from a sequence of its own.
- A sort's comparison can roll, which shuffles:
cards.Sort(a, b) { return Random.NextBool(); }. - Frags and verts roll on the GPU: each pixel and each vertex with a generator of its own, and other numbers every frame. Those aren't the CPU's numbers (below).
A few places never roll, and the compiler says why:
- The input's
Sanitize, which has to repair an input the same way on every machine from the input alone. - A type's
Interpolate, which the engine calls itself as a view blends between two ticks: the same two values have to blend the same every time. - Constants and defaults, which are worked out with no code running.
A system's rolls start over each tick, from that tick's number. What has to go on from where it was, like a deck that's dealt from over many ticks, or has to come from a seed the game picks, is a generator of your own.
A generator of your own
Random is also a type: a random number generator whose state is 8 bytes of data, which live wherever the game puts them. Each Next call on one gives a number and steps its state. It's a value, like a float3: it goes in a field or a local, and where it is decides whose numbers they are.
- In a component, every entity has a sequence of its own. A system that rolls for its entities still runs them on several threads at once, each from its own generator, with the same results.
- In a singleton, it's the match's: one sequence, for what the whole match shares, like a deck.
- In local state, it's this machine's, for effects: sparks, shakes, anything the match doesn't see.
- In a local, it lasts as long as the code that made it:
mut var random = Random(seed);.
singleton Deck
{
Random random;
List<int> cards;
}
system Shuffle(mut Deck deck)
{
// Each card trades places with one before it, or stays.
for (var i = deck.cards.count - 1; i > 0; i--)
{
var other = deck.random.NextInt(i + 1);
var card = deck.cards[i];
deck.cards[i] = deck.cards[other];
deck.cards[other] = card;
}
}A Next call changes the generator, so the code that rolls needs it mut: mut Wanderer wanderer, mut Deck deck, a mut var. That's all a system says, and the rest follows as for any other data: two systems that roll with the same component run one after the other, a generator in the match is in every snapshot, and a tick a client runs again after a wrong prediction rolls the same numbers again.
A function that rolls takes the generator as mut:
float2 Scatter(mut Random random, float spread)
{
return random.NextFloat2Direction() * random.NextFloat(spread);
}Seeds
A generator the game leaves alone is seeded by the engine, so there's nothing to do for the common case:
- A
Randomfield of a component is seeded as its entity spawns (or as the component is added), from the match's seed and the entity. Two entities spawned alike in the same tick still get sequences of their own. - A
Randomfield of a singleton is seeded as the match starts, from the match's seed. - In local state, each gets a sequence of its own too, the same every run: a local component's, a local singleton's, and a
local Randomfield of a match component, which is the entity's own on this machine.
Adding or moving local singletons and attached local fields does not change a match singleton's sequence.
Random(seed) makes one for a seed of the game's, an int or a long: the same seed, the same numbers. Seeds next to each other (1, 2, 3) give sequences that have nothing to do with each other.
Spawn(Wanderer { random = Random(7) }); // Every match, the same wandererThe view below makes a generator from the slider's seed every frame, and rolls every dot's place, size and color with it. The dots stay where they are, since the same seed rolls the same numbers; another seed gives other dots, and going back gives the first ones again.
settings { title = "Random"; }
local scene Main { }
local singleton Dice
{
int seed = 7;
int dots = 400;
}
view Scatter(mut Dice dice)
{
Draw.Clear(Color(0.086, 0.086, 0.094));
Draw.SetCamera(float2(0, -0.25), 2.2);
// A generator is a value. The same seed rolls the same numbers, on every
// machine and in every frame: the dots stay where they are.
mut var random = Random(dice.seed);
for (var i = 0; i < dice.dots; i++)
{
var at = random.NextFloat2Direction() * Math.Sqrt(random.NextFloat()) * 1.5;
var size = random.NextFloat(0.015, 0.05);
Draw.Circle(at, size, Color(1, random.NextFloat(0.5, 0.85), random.NextFloat(0.1, 0.45)));
}
// Another generator with that seed starts the same sequence over.
mut var die = Random(dice.seed);
mut var rolls = $"Random({dice.seed}) rolls";
for (var i = 0; i < 8; i++) rolls += $" {die.NextInt(1, 7)}";
Draw.SetScreen();
Draw.Text(rolls, float2(16, 14), 16, Color.white);
GUI.SetTheme(GUITheme { radius = 6 });
GUILayout.Area(Rect(12, Screen.height - 86, Screen.width - 24, 74))
{
GUILayout.IntSlider("Seed", dice.seed, 0, 20);
GUILayout.IntSlider("Dots", dice.dots, 10, 2000);
}
}A Random has one field, long state, which is all there is to it: copy it to keep where a sequence is, and set it to go on from there. A state of 0 is a generator nothing seeded yet. It still rolls, but the same numbers as every other one at 0: what a Random in a list starts as, since the engine seeds the fields of components and singletons, and no further.
The match's seed
Random.seed is an int from 0 to 2147483647 that the machine starting a match picks, so matches can vary (but in a game run without a window, where it's 0, so the run repeats). tide run --seed 7 --stats picks it, to play a match's rolls again or to try others. It's part of the match: a player who joins gets it with the world, and players don't send a seed separately. The match's rolls come from it, the engine seeds the match's generators from it, and a game reads it, with no parameter, where it wants numbers by place:
// The same cave on every machine, and another one every match.
if (Math.Hash(int3(x, y, Random.seed)) % 4 == 0) field.cells[x, y] = Material.Rock;It's read wherever code rolls, but in an audio declaration, which has no match. Local code reads the seed of the match its last frame drew, and 0 with no match.
It's 0 where nothing picks one: tests, benchmarks, and a world a C host starts with tide_world_init. A run there repeats exactly.
Every player can read it
The seed is in the world, and every player's machine has the whole world for now. A game whose players mustn't know what comes next, like the order of a deck, can't keep that from someone who reads their own machine's memory yet. Scene visibility filtering isn't built yet.
Rolls on the GPU
A frag or vert rolls too, with the same calls: Random.NextFloat() in a frag is another number at every pixel, and in a vert at every vertex.
frag Static(Vertex vertex, out Color color)
{
var gray = Random.NextFloat();
color = Color(gray, gray, gray);
}What's different there:
- Each pixel and each vertex has a generator of its own, made as its code starts: from where the pixel is, or which vertex it is, and from a number the frame rolls. So no two pixels roll alike, and a frame later they all roll something else. That's what grain, static and sparkle want. What should stay put from frame to frame is
Math.Hashor noise. - They aren't the CPU's numbers. A GPU's ints are 32 bits, so it rolls with a smaller generator than a system does. What a roll gives is the same: the table above holds, ranges and all.
- Give separate rolls separate statements when their order matters. Not every shader language Tide translates to promises the CPU's left-to-right order for several rolls in one expression (Unity's HLSL doesn't). Also, a
?:that rolls evaluates the rolls on both sides on the GPU; use anifwhen only the selected branch should roll. Random.seedis there too, so a frag can draw noise from the match's seed.- A
Randomof your own stays on the CPU. Its state is 64 bits. A frag rolls on the type.
Frags and verts has the details.
Forgiving with bad values
Values can come from other players' input, so math avoids spreading NaN where it can:
Math.Clampalways returns a value in range: NaN gives the lower bound.Math.MinandMath.Maxwith one NaN argument return the other.Math.Normalizegives zero for a vector too short to have a direction, and the identity for a quaternion that short. Dividing a zero vector by its length would give NaN.
That last one is the first thing most games run into: a move is zero while no key is held.
// No key held: move is zero, and the body stays where it is.
float3 move = Math.Normalize(float3(input.horizontal, 0, input.vertical));
body.position += move * 5 * time.dt;Too short means a length under about 1e-19. Anything longer comes out at length 1.
Info
Unity.Mathematics has two, normalize and normalizesafe. Tide has one, and it's the safe one: there's no Math.NormalizeSafe.
Everywhere else, results match Unity.Mathematics. The transcendental functions (Sin, Exp, Pow and the others) are Tide's own, accurate to about 1 ulp, and give the same bits everywhere.
On the GPU
Everything on this page works in a frag or vert too, unless it makes no sense there: the types, what builds them, and every Math function, quaternions and matrix inverses included. The same function runs in a system and in a frag, and gives the same answer up to how the GPU rounds.
Math.Hashis integers, so the GPU's number is exactly the CPU's.Math.Perlin,SimplexandCellulartake their cells and gradients fromMath.Hash, so a frag draws the cells the match computed, and their floats come out as the GPU rounds, like any.- Floats follow the same formulas with the GPU's own rounding, which differs from one GPU to the next, most for big numbers. They're only ever drawn: nothing a GPU works out reaches the match.
- It's forgiving in the same ways:
Normalize,Min,Max,ClampandSaturatedo there what Forgiving with bad values says. Math.Hashof alongis the one function that isn't there, as a GPU's ints are 32 bits.Math.Hash(int2(int(x), int(x >> 32)))is the same number asMath.Hash(x): split the long on the CPU, and hash its halves in the frag.