Skip to content

Source: raymarch.h

raymarch

Rendering a 3D scene by walking a ray through a distance field.

A scene is described as a function saying how far the nearest surface is from any point, so geometry emerges from arithmetic rather than being stored.

Classes

Name Description
Vec3 A point in 3D, in plain floats, which keeps a scene function readable.
Hit What a ray found.
Camera A camera: where it stands, what it looks at, and how wide it sees.

Vec3

struct Vec3
src/light/powerfunctions/raymarch.h:36

A point in 3D, in plain floats, which keeps a scene function readable.

Public Attributes

float x = 0

float y = 0

float z = 0 : the three axes

Hit

struct Hit
src/light/powerfunctions/raymarch.h:99

What a ray found.

Public Attributes

bool hit = false : whether the ray reached a surface before leaving

float dist = 0 : how far along the ray

Vec3 point : where it landed

Vec3 normal : the surface orientation there

Camera

struct Camera
src/light/powerfunctions/raymarch.h:143

A camera: where it stands, what it looks at, and how wide it sees.

@moreinfo Building a pixel's ray is what every effect would otherwise re-derive, and getting it wrong puts a scene half off-screen.

Public Attributes

Vec3 position {0, 1, -3}

Vec3 target {0, 0, 0}

float focal = 1.2f : smaller = wider field of view

Public Methods

inline Vec3 ray(int32_t sx, int32_t sy) const : The ray through shader-space coordinates sx, sy (16.16, short side spanning -1..1).

More info

Sphere tracing

The field guarantees nothing is nearer than the value it returns, so a ray jumps exactly that far without passing through anything. That guarantee is why it converges in tens of steps rather than thousands. It is also why a scene costs the same whether it holds one sphere or a thousand.

Float, deliberately and locally

A raymarch is per-pixel float by nature, each ray taking many square roots, so this header compiles only where the platform declares a hardware FPU. Everything in the shader vocabulary stays fixed point and runs everywhere: this is the one bounded exception, gated as a whole header rather than weakening a rule in place.

Prior art

John Hart's sphere tracing, and IƱigo Quilez's distance-function and raymarching articles. The primitives, the gradient normal and the operators follow his descriptions, implemented fresh.