Files
Markk116 8104e01d6b Rice cube: procedural rice material and displaced filleted cubes
Two halves, one pipeline.

make_rice_texture.py models short-grain rice as randomly oriented 3D
ellipsoids (surface height solved as the quadratic root, so any orientation
works -- including grains standing on end), scattered by Poisson disk on a
torus and unioned into a height field. Because the scatter wraps by index, the
baked height/normal/AO/albedo set tiles exactly; that is proven by translating
the whole scatter a quarter patch and requiring a rolled copy back (0.0 mm
error), not by sampling a seam line, which turned out to be a coin flip.

make_rice_cube.py displaces a filleted cube with that height map: voxel remesh
for uniform vertex density, then triplanar sampling of the height field in
Geometry Nodes on object-space position. Exports STL via Blender and a
hand-rolled core-1.0 3MF, because this Blender build has no 3MF support and the
nix store is read-only.

Kept here: the procedural map set, the render of each body that was built
(40 mm / 4 mm fillet, and 160 mm / 8 mm), and the A/B sheets that record why --
fusing is voxel resolution, relief ratio 0.6 beats the map's own 0.9 on a small
body, and the fillet only reads once the body is large relative to the relief.

Not kept: mesh binaries (560 MB, 384 MB of it one STL), the scan extract, and
the baseline runs whose renders survive inside the sheets. rebuild.sh
regenerates all of it, in dependency order, including the sheets.
2026-11-12 10:54:43 +01:00

227 lines
12 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Rice cube
A filleted cube surfaced with real rice relief and exported to STL + 3MF. Size
and fillet radius are flags: the two bodies that were built are 40 mm / 4 mm and
160 mm / 8 mm.
Two sources, same pipeline:
- **`tex_proc/` — procedural short-grain rice.** Grain shapes are modelled and
scattered on a torus, then baked to a seamless texture set. **This is the good
one**, and it is the only texture set committed.
- **`tex/` — the ambientCG `food_0015` photo scan.** The baseline the procedural
version is measured against. Not committed: it is an unzip of a downloaded
archive, see `rebuild.sh`.
Start with `out/size_ab.png`, then `tex_proc/maps_sheet.png` and
`out/scan_vs_procedural.png`.
```
make_rice_texture.py python3 procedural maps -> tex_proc/
preview_maps.py python3 maps_sheet.png, fake-lit preview
make_rice_cube.py blender -b -P ... -- args displaced cube -> <out>/
verify.py python3 verify.py <out> [3mf|stl] checks exported files
compare.py python3 labelled A/B sheet, full + zoom
contact_sheet.py python3 variant ladder
measure_scan_scale.py python3 derives the scan's mm scale
rebuild.sh ./rebuild.sh everything not tracked here
```
```sh
python3 make_rice_texture.py && python3 preview_maps.py
blender -b -P make_rice_cube.py -- --height tex_proc/rice_height_16bit.png \
--sidecar tex_proc/rice_maps.json --patch 60 --voxel 0.2 --relief-ratio 0.6
```
Texture bake ~14 s, 40 mm cube ~30 s, 160 mm cube ~2 min, all CPU only.
## What is tracked, and what is not
Committed: the seven scripts, this README, `rebuild.sh`, the procedural map set
(`tex_proc/`, 23 MB, the good one), the render of each body that was kept, and
the five A/B sheets in `out/`.
Not committed, because it is all rebuildable from the above in a couple of
minutes: every `.stl` / `.3mf` / `.blend` (560 MB, and 384 MB of that is the
single 160 mm STL), the scan extract (`tex/`, 57 MB), and the baseline runs
`out_scan/` and `out_crisp/` whose renders survive inside the A/B sheets.
`./rebuild.sh` regenerates the lot, in dependency order, including the sheets.
## How the material is made, and why that way
A bump map is a height map with a strength scalar; a normal map is the *gradient*
of that same field, stored so the shader does not have to differentiate it per
pixel. So the real outputs are height and its derivative — deriving the normal is
a gradient, not a render.
The standard pipeline is author-in-3D → bake-out-to-maps, and that is what
`make_rice_texture.py` does. The part that is easy to get wrong is seamlessness.
Baking a photo gives a map that does not tile, which is exactly the wall the scan
hit: its patch had to stay ≥ one cube face to keep the seam off the surface. So
here the *source* is periodic:
1. **Grain model: a rotated ellipsoid, solved not approximated.** The body is a
3D ellipsoid with a random 3D orientation; for each texel the surface height
is where the vertical line leaves the ellipsoid, i.e. the larger root of a
quadratic (each local coordinate is affine in z, so the equation is quadratic
in z). That is exact for any orientation and is what makes a *standing* grain
possible — laid flat its footprint is a whole grain, stood on end it is the
cross-section with the height of most of a grain. Length lognormal around
5 mm, aspect ~1.78, thickness ~0.44 × length, drawn per grain.
2. **Orientation mixture.** 34% of grains are tilted 30–65° out of plane, the
rest lie down within ~12° of flat. A blanket of shingled grains does not look
like pressed rice; the grains jutting out end-on are most of what the
reference photograph reads as.
3. **Scatter on a torus.** Poisson-disk (blue noise) with torus distance, five
layers spaced 0.38 mm apart — closer than a grain is thick, so upper grains
rest *on* lower ones rather than forming a second storey.
4. **Wrap by index.** Every grain rasterises through `index % N`, so a grain
straddling an edge reappears on the opposite edge without any special case.
5. **Gap filling, not coverage tuning.** Nominal layer coverage is a bad proxy
for closure: an upright grain covers ~2.4 mm² against ~11 mm² for a flat one,
so a pile with many standing grains leaves holes straight down to the plate.
Remaining floor texels are found by connected-component labelling and a grain
dropped into each, until the surface is closed (measured: 0.0000%).
6. **Union by `max()`**, then a wrap-mode blur to soften the creases, then
horizon-marched AO and a per-grain albedo tint.
Outputs (`tex_proc/`): `rice_height_16bit.png` (the bump map, and the
displacement source), `rice_normal_opengl.png` + `rice_normal_directx.png`,
`rice_ao_8bit.png`, `rice_albedo.png`, and `rice_maps.json`.
Two modelling fixes worth recording, both found by looking rather than by
reasoning:
- **A lengthwise groove cut into each grain's top was the "depression at the top
of every grain".** The crease on a real grain is on its *hidden* side; carving
it into a domed top reads as a dent. Removed.
- **Seating grains by their lowest point made upright grains stand a full
grain-length proud of their layer**, which compounds across layers into a spike
field (9.55 mm peak-to-valley for a 5 mm grain). Placing grain *centres* on the
layer plane is what compaction does and bounds the protrusion; with layer
spacing tightened as well, PV came down to 4.48 mm.
**Periodicity is proven, not sampled.** The first check compared one seam line
against interior gradient statistics; across seeds that statistic landed anywhere
from the 4th to the 99th percentile on *correct* fields, so it was a coin flip in
disguise. The test is now: translate the whole scatter by a quarter patch on the
torus and require the same field back, rolled. Reported error: **0.0 mm**
(bitwise identical).
## Cube pipeline
1. Cube + fillet (8 segments), applied. Size and fillet radius are CLI flags:
`--size` and `--fillet` (defaults 40 mm and 4 mm). The preview camera and fill
light are derived from the body size, so framing does not change with scale.
2. **Voxel remesh, 0.2 mm** (`--voxel`). Subdivision surface was the first plan
and is wrong here: it distributes vertices per face, not per millimetre, so on
a filleted cube the fillet strips get ~8× the density of the flats and the
displacement gets 2 mm sampling exactly where it needs 0.2 mm. Voxel remesh is
uniform by construction and watertight. Cost: tri soup, one global density
knob, and that knob is what controls fusing (below).
3. **Triplanar displacement in Geometry Nodes** from object-space `Position`.
Cube UVs slice grains at all 12 edges and give uneven texel density across
bevels. Sampling `position / patch` on the three axis planes and blending by
`|normal|^8` gives one continuous field, no unwrap. The exponent barely
matters between 8 and 48; a hard select leaves a visible height cliff along
every bevel.
4. **Relief derived, not chosen.** `relief = ratio × apparent grain size`, where
the ratio comes from the map's sidecar: 4.48/5.0 = 0.90 for the procedural set,
0.42 for the scan. Relief larger than the grain is what turns rice into
popcorn — tried at 1.25, unmistakable. `--relief-ratio 0.6` is the composition
that was liked; see the relief A/B below for why 0.90 is not it.
5. **Export** STL via `bpy.ops.wm.stl_export` and 3MF via a small stdlib writer.
## The two bodies that were kept
| body | fillet | rice | relief | triangles |
|---|---|---|---|---|
| `out_calm/` | 40 mm | 4 mm | 5.00 mm grains, 60 mm patch | 3.00 mm | 479,532 |
| `out_160/` | 160 mm | 8 mm | 5.00 mm grains, 60 mm patch | 3.00 mm | 7,680,300 |
The rice is the same in both; only the body scales. Patch size is a free choice
because the procedural map tiles exactly — the scan needed patch ≥ face size to
hide its seam.
Grain scale is set by the patch, `grain = 0.0833 × patch`: a 60 mm patch gives
5 mm grains (~8 across a 40 mm face), 36 mm gives 3 mm (~13), 21 mm gives 1.75 mm
(~23). `out/variants.png` is that ladder at 0.3 mm voxel.
Three single-variable A/Bs are rendered rather than described:
`out/fusing_ab.png`, `out/relief_ab.png`, `out/size_ab.png`.
- **Fusing is voxel resolution, nothing else** (`out/fusing_ab.png`).
`BLUR_TEXELS` is 0.5 texels = 0.015 mm, which cannot matter next to a 0.3 mm
voxel — the remesher is the whole story, because it cannot resolve
sub-millimetre valleys and rounds them shut. 0.2 mm (480k tris, 24 MB) keeps
crevices open; 0.3 mm is the coarse pane of that sheet.
- **Relief ratio** (`out/relief_ab.png`). 0.90 × grain is the map's own
peak-to-valley over its grain size, which is right for a flat material but eats
the cube's silhouette: at 4.48 mm the body reads as a lumpy blob. 0.60 × grain
(3.00 mm) keeps the grains clearly modelled while the cube still reads as a
cube. The default follows the map, so `--relief-ratio 0.6` is what the kept
runs use.
- **Body size** (`out/size_ab.png`). At 40 mm the 4 mm fillet is the same order
as the relief, so the rice buries it and the body reads as a lumpy blob; at
160 mm / 8 mm the fillet is a visible band and the cube reads as a cube, with
the rice unchanged at its physical scale.
## Size is not free
Scaling the *body* while keeping the rice at its physical size (5 mm grains,
0.2 mm voxel) scales the surface area, and therefore the triangle count, with the
square. `--size 160 --fillet 8` gives a 16x surface: **7,680,300 triangles,
384 MB STL, 70 MB 3MF, 2 minutes, and a peak of ~3.1 GB RSS**. That is the honest
cost of "same rice, bigger cube"; the alternative is to scale the rice with the
body, which is a different object.
## Verification
`verify.py` reads the delivered files the way a slicer would — welding STL
vertices by coordinate, then an edge census, signed volume, and a structural
check of the 3MF zip/XML.
Verified: 4,070,164 mm³ for the 160 mm body against 4,096,000 for a bare cube,
0 boundary / non-manifold / misoriented / degenerate. At 7.7M triangles the check
runs on the 3MF only — see the note below.
All smaller files: 479,532 triangles, **0 boundary / 0 non-manifold / 0 misoriented /
0 degenerate**, positive signed volume 62,341–63,681 mm³ against 64,000 for a bare
40 mm cube (corner rounding plus relief). 3MF declares `unit="millimeter"`; STL is
unitless and every slicer will assume mm.
Two fixes were needed to check a mesh that size, both real rather than
workarounds. `verify.py` welded STL vertices by sorting N x 3 coordinate keys,
which is enough to get OOM-killed at 8M triangles — but a 3MF already carries
shared indices, so that path needs no welding at all (`verify.py out 3mf`). And
`read_3mf` built the whole XML tree with ElementTree, i.e. 11.5M Python element
objects; it now streams events into flat arrays and clears each container as it
goes, which drops it to the size of the data.
Self-intersection (which manifoldness does not catch) via BVH overlap: **0
intersecting non-adjacent triangle pairs**, with the check controlled against
interpenetrating cubes (12 detected) and a single cube (0). Caveat: it does not
detect coincident coplanar surfaces, and an unwelded triangle soup produced ~59k
false positives at this coordinate scale — weld before testing.
## Still open
- **3MF is hand-rolled** (~50 lines, core-1.0, no extensions) because this
Blender has no 3MF support and the nix store is read-only. Worth one manual
import into PrusaSlicer/Bambu Studio before trusting it in anger.
- **Grains are all separate objects on a common floor.** A real pile has grains
partially covered by others, which happens here via overlap, but there is no
friability, no broken grains, and no dust. Those are what would push it from
"clearly rice" to "scan".
- **The triplanar band along the fillets is the largest remaining artifact.** An
8 mm fillet is 1.6 grains wide, so the crossfade between the two face
projections shows up as a band of stretched grains down every edge. Options
are a wider fillet (~3 grains, so ~15 mm on this body) or fading displacement
out on the fillet so the corners are smooth — the latter is a composition
decision, not a fix, and is not implemented.
- **The generator emits maps, not geometry.** For printing, the baked height map
resamples through the 0.3 mm voxel mesh anyway; scattering the grains as real
meshes and taking the union directly would avoid that resampling step
entirely, and would also give free undercuts that a height field cannot
represent.