Drawing

Reference grids

A reference grid is the floor of a CAD program or a 3D plot: lines every metre, a heavier line every ten, and the axes in color. It must look clean at any zoom, from a millimetre to a continent, in perspective and orthographic views, and stay in place far from the world's origin. This page explains how to draw one from a single triangle. The last part shows how RASM does it.

In short

  • Draw one triangle over the screen. Each pixel sends its ray to the grid's plane and finds the point it shows there.
  • The point's depth goes to the depth test, so objects hide the grid where they stand in front of it.
  • Lines have a width in pixels, from the screen derivatives of the plane coordinates. A line thinner than a pixel fades instead of breaking up.
  • Cells come in levels (1, 10, 100, ...). Each pixel shows the levels whose cells are wide enough there, and fades between them, so the grid stays crisp at any zoom.
  • Far from the origin, split the camera's place on the plane into whole cells and a rest, in doubles on the CPU. The lines stay exact anywhere.

1Why not a mesh of lines

The obvious grid is geometry: a quad per line, or a big textured square. Both break at the edges of what a camera can see.

Lines as geometry

far lines flicker; the grid ends

Far lines get thinner than a pixel and flicker; a fine grid turns into moiré; the mesh has an end, and a mesh as big as a planet has no precision left.

A ray per pixel

lines fade before they break up

The grid is a rule, not a mesh: every pixel computes it for its own point. It has no end, no seams, and every line is as wide as it should be on screen.

2A ray per pixel

The triangle covers the whole target. For each pixel the shader builds the ray through the pixel's centre, meets the plane, and computes the hit's coordinates on the plane and its depth.

the grid's plane camera pixels no hit: discarded behind the box: the depth test hides it near pixels: hits close together, fine cells far pixels: hits far apart, coarse cells
The hit's depth is written as the fragment's depth: the test against the scene's depth then hides the grid behind the gray box, and the grid hides nothing, since it writes no depth.

A perspective camera's rays start at the camera and spread out. An orthographic camera's rays are parallel: they all have the view's direction, and start across the near plane.

Perspective

Ray from the camera through (x / P00, y / P11, −1) in view space.

Orthographic

Ray along −Z from ((x − P03) / P00, (y − P13) / P11, 0): even spacing everywhere.

n t = −(h + n·o) / (n·d)

The plane

h is the camera's height above the plane, so the numbers stay small near the camera.

3Lines a pixel wide

The hit's plane coordinates, counted in cells, are uv. Their change from one pixel to the next, the derivative, says how many cells one pixel covers there. With it, a width in pixels becomes a width in cells.

d = ( |(∂u/∂x, ∂u/∂y)|, |(∂v/∂x, ∂v/∂y)| )

w = widthPixels · d

distance = 1 − |fract(uv) · 2 − 1|

coverage = smoothstep(w + 1.5 d, w − 1.5 d, distance)

d
cells per pixel along each axis, from ddx and ddy of uv
w
the line's width in cells
distance
twice the distance to the nearest line, in cells: 0 on a line, 1 halfway between two
smoothstep
an edge about a pixel and a half wide: the line is smooth, not stair-stepped

Two more rules keep thin and dense lines quiet (Ben Golus' "pristine grid"):

Thin lines drawn thin

a line under a pixel: dashes that crawl

A line 0.3 pixels wide covers some pixel centres and misses others: it breaks into dashes, and they crawl as the view moves.

Clamp to a pixel, then fade

one pixel wide, fainter: steady

A thin line is drawn a pixel wide and faded by w / d. When cells get near two pixels wide, the result blends to the line's share of the cell, the average a far grid would have.

4Levels: crisp at any zoom

One cell size cannot serve every zoom: zoomed out, 1 cm cells are a gray haze; zoomed in, 1 km cells are empty. So the cells come in levels: cellSize × sk for s subdivisions. Each pixel picks the level whose cells are F pixels wide there, and draws three levels next to each other.

A: cells near F / s, fading out B: cells near F, major → minor C: cells near F · s, fading in together zoom out: A fades away, B becomes the minor lines, C the major ones, the next level fades in
The levels nest: every B line is also an A line, every C line a B line. As the zoom changes, each level slides into the next one's role, so the picture changes smoothly, with no jump between levels.

lod = max(0, logs(max(dx, dy) · F))

A = ⌊lod⌋    blend = lod − A

d
finest cells per pixel, as above
F
the width in pixels where a level's cells are fully shown (32 here)
blend
A's lines fade by 1 − blend, B's turn from major to minor, C's fade in by blend

In a perspective view, d grows with distance, so near pixels show fine cells and far pixels coarse ones. In an orthographic view, d is the same everywhere, so the whole view shows the same levels.

Zoom out slowly and watch a level fade while the next takes its place. Tilt the view to see near and far pixels pick different levels in one picture. Set the subdivisions to 2 for a binary grid.

5Far from the origin

The lines sit at whole cells of the plane's coordinate. Far from the grid's origin, that coordinate is a big number, and a float cannot hold its fraction.

6.4 × 108cells to the camera6 371 km from the origin, 1 cm cells
64 cellsbetween two floats therea float has 24 bits: 229 / 223
exactwith whole cells modulo sJcomputed in doubles on the CPU

The fix splits the camera's coordinate on the plane, in doubles, into whole cells n and a rest f in [0, 1). Only n modulo a period matters, and the period can be a power of s, because every level's cells divide it.

camera coordinate / cellSize = n + f

R = n mod sJ  (an integer, sJ ≤ 232)

uv at level k = ((R mod sk) + f + q / cellSize) / sk

q
the hit relative to the camera, small near the camera, where the fine levels are
R mod sk
exact integer math; the sum stays below a few cells of level k, so a float holds it

The camera's height above the plane comes from the CPU in doubles too, so the ray meets the plane at the right place however far both are from the origin.

6Fades and edges

a few degrees: faded

Grazing angles

Where the ray almost runs along the plane, the grid fades out: an edge-on plane is all moiré.

full → gone at the distance

Distance

A perspective view can fade the grid out with distance, so it does not reach the horizon.

inside the extent only

A bounded grid

An extent cuts the grid to a rectangle, its edge smoothed over a pixel like a line.

7Pitfalls

The grid shows through objects
It was drawn without its own depth. Write the hit's depth and test it against the scene.
Lines flicker and crawl in the distance
A fixed width in world units. Use a width in pixels from the derivatives, and fade lines thinner than a pixel.
A gray haze of moiré far away
One level of cells for every pixel. Pick levels per pixel from the derivative.
A sudden jump while zooming
Levels switch at a threshold. Blend three levels by the fraction of the level of detail.
Lines step or wobble far from the origin
The plane coordinate was a float. Split it into whole cells modulo a period and a rest, in doubles on the CPU.
Black pixels or lines along the horizon
The derivatives blow up where the ray runs along the plane. Fade by the grazing angle, and take the derivatives before any discard so all four pixels of a quad have them.

8In RASM

A grid belongs to a camera: Renderer::setCameraGrid(camera, Grid) draws it in every shaded view of that camera, so each viewport of a CAD layout can have its own plane. A Grid is the plane (origin in doubles, orientation: its local XZ plane), the finest cellSize, subdivisions, an extent (0: endless), colors and widths, the axes, and a fadeDistance.

Pixel sizes in an export In a tiled export's pipelines (RASM_EXPORT_VIEW) sizes given in pixels are multiplied by SceneData::pixelScale (getPixelScale), its ExportDesc::pixelScale, which also divides the LOD's pixels per unit; in every other view it is 1 and the shaders do no work for it. Sizes in metres do not change.
Scene 1, Scene 2 opaque draws, the sky write depth Transparent drawGrid: grid.slang one triangle, SV_Depth tested, not written; blended blend run, back to front see-through meshes, vectors, labels: over the grid SceneData::grid (GridData) written per view by makeGridData, in doubles
The grid writes its own motion, premultiplied like the blend run's, so TAA keeps it steady; under MSAA its depth is tested per sample, so object edges over the grid stay smooth.
This pageRASM
One triangle, a ray per pixelRenderer::drawGrid (src/renderer/gpuScene.cpp) draws three vertices with shaders/passes/grid.slang, first in the Transparent pass, after the opaque draws and the sky. Not in a debug view, and not in depth-only views.
Depth tested, not writtenThe pipeline has BlendMode::PREMULTIPLIED_ALPHA, depth test on, depth write off; the fragment writes the hit's depth. Its motion is the hit's, from previousViewProjection.
Lines in pixelslineWidth and majorLineWidth; the axes are majorLineWidth + 0.5 pixels, in xAxisColor and zAxisColor (alpha 0 hides one).
LevelsF = 32 pixels (FADE_PIXELS in the shader); subdivisions from 2 to 1000, so at least three levels fit in 32 bits.
Whole cells and a restmakeGridData (src/renderer/grid.cpp) writes residueX, residueZ, fractionX, fractionZ and the camera's height above the plane from doubles, every frame, in each view's render space (Large worlds). period is the largest power of subdivisions in 32 bits.
Fades and edgesGrazing angle always; fadeDistance in perspective views; extent in world units along the plane's X and Z.
0.22 msfour grids, 27_cad_viewsfour views at 1920 × 1080, three with 4× MSAA, RTX 3060, Release
0 pixelsdiffer 6 000 km out27_cad_views --far against the origin, frame 70
0 bytesper frame on the heapthe grid is a SceneData row

Code map

WhatWhere
The APIGrid in include/rasm/grid.h; Renderer::setCameraGrid, Renderer::getCameraGrid; rasm_set_camera_grid in C
Per-view datacheckGrid and makeGridData in src/renderer/grid.cpp; gfx::GridData in src/renderer/uberMaterialTypes.h and shaders/lib/core.slang
The drawprepareSceneView fills SceneData::grid (also while the scene's meshes still load); drawGrid in the Transparent pass
The shadershaders/passes/grid.slang: getLineCoverage, getLevelUv, getAxisCoverage
Exampleexamples/27_cad_views/main.cpp: four views, each with a grid in its own plane
Teststests/gridTests.cpp (the residues against a direct computation, far and near); image tests grid, grid_ortho, grid_msaa4, grid_taa, far_grid, and a bounded grid in ortho
Rules to keep

Every value that depends on where the camera is on the plane comes from makeGridData in doubles. Keep GridData in step on both sides (struct layout). The grid reads only SceneData: no draw, no culling, no pick.

Not yet

Further reading