"""Rice-textured rounded cube -> STL/3MF. blender -b -P make_rice_cube.py -- --height tex_proc/rice_height_16bit.png \ --sidecar tex_proc/rice_maps.json blender -b -P make_rice_cube.py # scanned texture, as it started Design notes: * Displacement, not bump: an exported mesh has no materials, so the height field has to become vertices. * Triplanar sampling in Geometry Nodes from object-space Position. Cube UVs would slice grains at each of the 12 edges and give non-uniform texel density across bevels. * Voxel remesh provides the vertex density so displacement has something to sample; it is also what makes the result watertight and print-ready. * Relief is derived from the apparent grain size, never set independently: relief larger than the grain turns rice into popcorn. The ratio comes from the map itself when a sidecar is given, so the cube reproduces the source's own relief-to-grain proportion at whatever scale it is tiled. """ import argparse import json import os import sys import zipfile import bpy import numpy as np from mathutils import Vector HERE = os.path.dirname(os.path.abspath(__file__)) TEX = os.path.join(HERE, "tex") DEFAULT_OUT = os.path.join(HERE, "out") DEFAULT_SIZE_MM = 40.0 BEVEL_MM = 4.0 BEVEL_SEGMENTS = 8 # Voxel remesh resolution. This is the single biggest control on how much # adjacent grains fuse: at 0.3 mm the remesher cannot resolve sub-millimetre # valleys and rounds them away, at 0.2 mm crevices stay open. Cost is quadratic # in triangles -- 0.3 mm gives 210k tris / 10.5 MB, 0.2 mm gives 480k / 24 MB. VOXEL_MM = 0.2 # Triplanar blend exponent. The weights already resolve the axis hand-off to # under a millimetre at 8, so anything from 8 upwards looks the same until it # becomes a hard select, which leaves a visible height cliff along the bevel. AXIS_SHARPNESS = 8.0 DEFAULT_HEIGHT = os.path.join(TEX, "food_0015_height_2k.png") DEFAULT_ALBEDO = os.path.join(TEX, "food_0015_color_2k.jpg") # For the scan, measured by measure_scan_scale.py: median grain crown is 95 px # long in a 2048 px map, so a grain is 4.64% of the map's width. A procedural # map states its own numbers in the sidecar instead. DEFAULT_GRAIN_FRACTION = 95.0 / 2048.0 DEFAULT_GRAIN_MM = 6.5 # The map at 1:1: a 6.5 mm grain is 4.64% of the map's width, so the map spans # ~140 mm of rice. Tiling it at that patch reproduces the scan's true scale. DEFAULT_TRUE_SCALE_MM = DEFAULT_GRAIN_MM / DEFAULT_GRAIN_FRACTION DEFAULT_RELIEF_RATIO = 0.42 # Map patches are derived from the grain scale, so the variants are the same # pile at three apparent grain sizes rather than three arbitrary crops. SCALE_STEPS = (1.0, 0.6, 0.35) def parse_args(argv): parser = argparse.ArgumentParser(prog="make_rice_cube") parser.add_argument("--height", default=DEFAULT_HEIGHT, help="greyscale height map used as displacement") parser.add_argument("--albedo", default=None, help="colour map for the preview renders") parser.add_argument("--sidecar", default=None, help="rice_maps.json: supplies grain size and relief") parser.add_argument("--patch", nargs="*", type=float, default=None, help="texture width on the cube, in mm (one per variant)") parser.add_argument("--relief-ratio", type=float, default=None, help="peak-to-valley relief as a fraction of grain size") parser.add_argument("--size", type=float, default=DEFAULT_SIZE_MM, help="cube edge length in mm") parser.add_argument("--fillet", type=float, default=BEVEL_MM, help="edge fillet radius in mm (must be < cube/2)") parser.add_argument("--voxel", type=float, default=VOXEL_MM) parser.add_argument("--out", default=DEFAULT_OUT) known = argv[sys.argv.index("--") + 1:] if "--" in sys.argv else [] return parser.parse_args(known) def load_recipe(args): """Physical truth about the height map, from its own sidecar if it has one.""" recipe = { "height": args.height, "albedo": args.albedo or DEFAULT_ALBEDO, "grain_fraction": DEFAULT_GRAIN_FRACTION, "true_scale_mm": DEFAULT_TRUE_SCALE_MM, "relief_ratio": args.relief_ratio or DEFAULT_RELIEF_RATIO, "out": args.out, "voxel": args.voxel, "fillet": args.fillet, "size": args.size, "source": "scanned", } if args.sidecar: with open(args.sidecar) as handle: sidecar = json.load(handle) recipe["source"] = os.path.basename(os.path.dirname( os.path.abspath(args.sidecar))) recipe["grain_fraction"] = sidecar["grain_fraction_of_patch"] recipe["true_scale_mm"] = sidecar["patch_mm"] # Reproduce the source's own relief-to-grain proportion. recipe["relief_ratio"] = sidecar["relief_mm"] / sidecar["grain_mm"] albedo = os.path.join(os.path.dirname(os.path.abspath(args.sidecar)), sidecar["maps"]["albedo"]) recipe["albedo"] = args.albedo or albedo if args.relief_ratio is not None: recipe["relief_ratio"] = args.relief_ratio if args.patch: patches = list(args.patch) else: patches = [recipe["true_scale_mm"] * step for step in SCALE_STEPS] recipe["variants"] = [(f"g{grain_mm(p, recipe):.2f}".replace(".", "_"), p) for p in patches] return recipe def grain_mm(patch_mm, recipe): return patch_mm * recipe["grain_fraction"] def relief_mm(patch_mm, recipe): return round(recipe["relief_ratio"] * grain_mm(patch_mm, recipe), 3) def scene_setup(): bpy.ops.wm.read_factory_settings(use_empty=True) scene = bpy.context.scene scene.unit_settings.system = "METRIC" scene.unit_settings.length_unit = "MILLIMETERS" scene.unit_settings.scale_length = 0.001 # one Blender unit = 1 mm def load_height_image(path): """Height image plus the statistics the displacement scale depends on.""" img = bpy.data.images.load(path, check_existing=True) img.colorspace_settings.name = "Non-Color" width, height = img.size buf = np.empty(width * height * 4, dtype=np.float32) img.pixels.foreach_get(buf) values = buf[0::4] return img, { "mid": float(values.mean()), "lo": float(values.min()), "hi": float(values.max()), } def rounded_cube(size_mm, fillet_mm): if not 0.0 < fillet_mm < size_mm / 2.0: raise SystemExit(f"fillet must be in (0, {size_mm / 2.0}) mm") bpy.ops.mesh.primitive_cube_add(size=size_mm, location=(0, 0, 0)) obj = bpy.context.active_object obj.name = "rice_cube" bevel = obj.modifiers.new("bevel", "BEVEL") bevel.width = fillet_mm bevel.segments = BEVEL_SEGMENTS bevel.limit_method = "NONE" bevel.profile = 0.5 with bpy.context.temp_override(object=obj, active_object=obj): bpy.ops.object.modifier_apply(modifier=bevel.name) remesh = obj.modifiers.new("remesh", "REMESH") remesh.mode = "VOXEL" remesh.voxel_size = VOXEL_MM remesh.use_smooth_shade = True bpy.ops.object.shade_smooth() return obj class Tree: """Terse node-tree builder, to keep the topology of the graph legible.""" def __init__(self, name): self.nt = bpy.data.node_groups.new(name, "GeometryNodeTree") self.nt.interface.new_socket("Geometry", in_out="INPUT", socket_type="NodeSocketGeometry") self.nt.interface.new_socket("Geometry", in_out="OUTPUT", socket_type="NodeSocketGeometry") self.gin = self.nt.nodes.new("NodeGroupInput") self.gout = self.nt.nodes.new("NodeGroupOutput") self.n = 0 def new(self, kind, **props): node = self.nt.nodes.new(kind) node.location = ((self.n % 8) * 220, -(self.n // 8) * 260) self.n += 1 for key, value in props.items(): setattr(node, key, value) return node def link(self, out_socket, in_socket): self.nt.links.new(out_socket, in_socket) return in_socket def math(self, op, a, b=None): node = self.new("ShaderNodeMath", operation=op) self._feed(node.inputs[0], a) if b is not None: self._feed(node.inputs[1], b) return node.outputs[0] def vmath(self, op, a, b=None, scale=None): node = self.new("ShaderNodeVectorMath", operation=op) self._feed(node.inputs[0], a) if b is not None: self._feed(node.inputs[1], b) if scale is not None: self._feed(node.inputs["Scale"], scale) return node.outputs["Vector"] def _feed(self, socket, value): if hasattr(value, "is_output"): self.nt.links.new(value, socket) else: socket.default_value = value def sample(self, image, u, v): """Image lookup at (u, v), returning the scalar height.""" combine = self.new("ShaderNodeCombineXYZ") self._feed(combine.inputs["X"], u) self._feed(combine.inputs["Y"], v) tex = self.new("GeometryNodeImageTexture", interpolation="Linear", extension="REPEAT") tex.inputs["Image"].default_value = image self.link(combine.outputs["Vector"], tex.inputs["Vector"]) sep = self.new("FunctionNodeSeparateColor") self.link(tex.outputs["Color"], sep.inputs["Color"]) return sep.outputs["Red"] def displace_group(name, image, stats, patch_mm, relief, sharpness): """Position += normal * (triplanar_height - mid) * scale. Triplanar rather than UV: the bevels make UV texel density wildly uneven and slice grains open at every edge. Projecting object-space position onto the three axis planes and blending by normal keeps one continuous field. """ t = Tree(name) pos = t.new("GeometryNodeInputPosition").outputs["Position"] normal = t.new("GeometryNodeInputNormal").outputs["Normal"] scaled = t.vmath("SCALE", pos, scale=1.0 / patch_mm) xyz = t.new("ShaderNodeSeparateXYZ") t.link(scaled, xyz.inputs["Vector"]) x, y, z = xyz.outputs["X"], xyz.outputs["Y"], xyz.outputs["Z"] weights = [] heights = [] normal_xyz = t.new("ShaderNodeSeparateXYZ") t.link(normal, normal_xyz.inputs["Vector"]) for axis, (u, v) in enumerate([(y, z), (x, z), (x, y)]): heights.append(t.sample(image, u, v)) component = normal_xyz.outputs[("X", "Y", "Z")[axis]] weights.append( t.math("POWER", t.math("ABSOLUTE", component), sharpness)) total_w = t.math("ADD", weights[0], t.math("ADD", weights[1], weights[2])) accum = t.math("MULTIPLY", weights[0], heights[0]) for w, h in zip(weights[1:], heights[1:]): accum = t.math("ADD", accum, t.math("MULTIPLY", w, h)) blended = t.math("DIVIDE", accum, total_w) # Scale so the texture's full range maps to the relief peak-to-valley, and # subtract the mean so the body does not inflate. span = stats["hi"] - stats["lo"] offset = t.math("MULTIPLY", t.math("SUBTRACT", blended, stats["mid"]), relief / span) setpos = t.new("GeometryNodeSetPosition") t.link(t.vmath("SCALE", normal, scale=offset), setpos.inputs["Offset"]) t.link(t.gin.outputs["Geometry"], setpos.inputs["Geometry"]) t.link(setpos.outputs["Geometry"], t.gout.inputs["Geometry"]) return t.nt def apply_displacement(obj, image, stats, patch_mm, relief): group = displace_group(f"rice_{patch_mm:.1f}_{relief:.2f}", image, stats, patch_mm, relief, AXIS_SHARPNESS) modifier = obj.modifiers.new("rice", "NODES") modifier.node_group = group def evaluated_mesh(obj): depsgraph = bpy.context.evaluated_depsgraph_get() return obj.evaluated_get(depsgraph).to_mesh() def write_3mf(path, mesh, scale=1.0, chunk=200_000): """Minimal 3MF core 1.0 writer: zip of XML, millimetre units. Written in chunks straight into the zip. Assembling the whole model string first is fine at 200k triangles and several GB of text at 8M, which is where a 160 mm cube lands. """ mesh.calc_loop_triangles() verts = np.empty(len(mesh.vertices) * 3, dtype=np.float64) mesh.vertices.foreach_get("co", verts) verts = (verts.reshape(-1, 3) * scale).round(5) tris = np.empty(len(mesh.loop_triangles) * 3, dtype=np.int32) mesh.loop_triangles.foreach_get("vertices", tris) tris = tris.reshape(-1, 3) header = ( '\n' '' "" '' ) middle = "" footer = "" \ '' content_types = ( '\n' '' '' '' "" ) rels = ( '\n' '' ) with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED, compresslevel=9) as z: z.writestr("[Content_Types].xml", content_types) z.writestr("_rels/.rels", rels) with z.open("3D/3dmodel.model", "w") as out: out.write(header.encode()) for start in range(0, len(verts), chunk): out.write("".join( f'' for a, b, c in verts[start:start + chunk].tolist() ).encode()) out.write(middle.encode()) for start in range(0, len(tris), chunk): out.write("".join( f'' for a, b, c in tris[start:start + chunk].tolist() ).encode()) out.write(footer.encode()) def mesh_stats(mesh): """Cheap in-process sanity numbers. verify.py is the authoritative check, run against the exported files rather than Blender's idea of them.""" mesh.calc_loop_triangles() verts = np.empty(len(mesh.vertices) * 3, dtype=np.float64) mesh.vertices.foreach_get("co", verts) verts = verts.reshape(-1, 3) return { "vertices": len(mesh.vertices), "triangles": len(mesh.loop_triangles), "bbox_mm": [round(float(v), 3) for v in (verts.max(axis=0) - verts.min(axis=0))], "wire_edges": sum(1 for e in mesh.edges if len(e.vertices) != 2), } def select_only(obj): bpy.ops.object.select_all(action="DESELECT") obj.select_set(True) bpy.context.view_layer.objects.active = obj def export(obj, name, out_dir): mesh = evaluated_mesh(obj) stats = mesh_stats(mesh) select_only(obj) stl = os.path.join(out_dir, f"rice_cube_{name}.stl") bpy.ops.wm.stl_export(filepath=stl, ascii_format=False, export_selected_objects=True, global_scale=1.0, apply_modifiers=True) three_mf = os.path.join(out_dir, f"rice_cube_{name}.3mf") write_3mf(three_mf, mesh) stats["stl_mb"] = round(os.path.getsize(stl) / 1e6, 2) stats["3mf_mb"] = round(os.path.getsize(three_mf) / 1e6, 2) return stats def rice_material(patch_mm, albedo_path): mat = bpy.data.materials.new("rice") mat.use_nodes = True nt = mat.node_tree bsdf = nt.nodes["Principled BSDF"] # Cosmetic: cooked rice is wet and glossy, and that specular is much of what # makes the surface read as rice rather than as plaster. Irrelevant to print. bsdf.inputs["Roughness"].default_value = 0.38 bsdf.inputs["Specular IOR Level"].default_value = 0.5 # World-space position / patch: the same field the displacement samples, # so colour and relief stay registered. Generated coords would be off by # the displacement's share of the bbox. geo = nt.nodes.new("ShaderNodeNewGeometry") scale = nt.nodes.new("ShaderNodeVectorMath") scale.operation = "DIVIDE" scale.inputs[1].default_value = (patch_mm, patch_mm, patch_mm) nt.links.new(geo.outputs["Position"], scale.inputs[0]) color = nt.nodes.new("ShaderNodeTexImage") color.image = bpy.data.images.load(albedo_path, check_existing=True) color.projection = "BOX" color.projection_blend = 0.35 nt.links.new(scale.outputs[0], color.inputs["Vector"]) nt.links.new(color.outputs["Color"], bsdf.inputs["Base Color"]) return mat def preview_stage(obj, patch_mm, albedo_path, size_mm): # Framing and fill light are derived from the body size, so the preview # looks the same whether the cube is 40 mm or 160 mm. scale = size_mm / DEFAULT_SIZE_MM scene = bpy.context.scene scene.render.engine = "CYCLES" scene.cycles.device = "CPU" scene.cycles.samples = 64 scene.render.resolution_x = 1100 scene.render.resolution_y = 900 scene.view_settings.view_transform = "AgX" world = bpy.data.worlds.new("w") world.use_nodes = True bg = world.node_tree.nodes["Background"] bg.inputs[0].default_value = (0.42, 0.45, 0.5, 1) bg.inputs[1].default_value = 0.35 scene.world = world obj.data.materials.clear() obj.data.materials.append(rice_material(patch_mm, albedo_path)) # Sun rather than an area light: irradiance is independent of the scene's # unit scale, so exposure does not have to be re-derived per variant. bpy.ops.object.light_add(type="SUN", location=(0, 0, 200)) key = bpy.context.active_object key.data.energy = 3.2 key.data.angle = 0.12 key.rotation_euler = (0.95, 0.12, -0.55) bpy.ops.object.light_add(type="AREA", location=(-140 * scale, -80 * scale, 30 * scale)) fill = bpy.context.active_object fill.data.energy = 6.0e4 * scale ** 2 # same illuminance at any size fill.data.size = 200 * scale fill.rotation_euler = (1.35, 0, -1.15) # 45 deg azimuth: both visible faces foreshorten equally, so nothing reads # as a streak. Grazing angles make grains look smeared even when the field # is continuous. bpy.ops.object.camera_add(location=(105 * scale, -105 * scale, 62 * scale)) cam = bpy.context.active_object scene.camera = cam cam.rotation_euler = (Vector((0, 0, 0)) - cam.location).to_track_quat( "-Z", "Y").to_euler() cam.data.lens = 100 def set_material(obj, patch_mm, albedo_path): obj.data.materials.clear() obj.data.materials.append(rice_material(patch_mm, albedo_path)) def render(obj, name, patch_mm, albedo_path, out_dir, size_mm, stage=False): if stage: preview_stage(obj, patch_mm, albedo_path, size_mm) else: set_material(obj, patch_mm, albedo_path) bpy.context.scene.render.filepath = os.path.join(out_dir, f"preview_{name}.png") bpy.ops.render.render(write_still=True) def main(): args = parse_args(sys.argv) recipe = load_recipe(args) out_dir = recipe["out"] os.makedirs(out_dir, exist_ok=True) scene_setup() image, height_stats = load_height_image(recipe["height"]) print(f"[info] source {recipe['source']}: grain " f"{recipe['grain_fraction'] * 100:.2f}% of the patch, " f"relief ratio {recipe['relief_ratio']:.3f}") obj = rounded_cube(recipe["size"], recipe["fillet"]) obj.modifiers["remesh"].voxel_size = recipe["voxel"] print(f"[info] remeshed base: {mesh_stats(evaluated_mesh(obj))}") summary = { "cube_mm": recipe["size"], "fillet_mm": recipe["fillet"], "voxel_mm": recipe["voxel"], "source": recipe["source"], "height_map": os.path.basename(recipe["height"]), "relief_ratio": round(recipe["relief_ratio"], 4), "height_stats": {k: round(v, 5) for k, v in height_stats.items()}, "variants": {}, } for index, (name, patch) in enumerate(recipe["variants"]): relief = relief_mm(patch, recipe) apply_displacement(obj, image, height_stats, patch, relief) info = export(obj, name, out_dir) info.update(patch_mm=round(patch, 3), displacement_mm=relief, grain_mm=round(grain_mm(patch, recipe), 2)) summary["variants"][name] = info print(f"[info] {name}: {info}") render(obj, name, patch, recipe["albedo"], out_dir, recipe["size"], stage=index == 0) obj.modifiers.remove(obj.modifiers["rice"]) canonical_name, canonical_patch = recipe["variants"][0] apply_displacement(obj, image, height_stats, canonical_patch, relief_mm(canonical_patch, recipe)) set_material(obj, canonical_patch, recipe["albedo"]) bpy.ops.wm.save_as_mainfile(filepath=os.path.join(out_dir, "rice_cube.blend")) with open(os.path.join(out_dir, "summary.json"), "w") as handle: json.dump(summary, handle, indent=2) print(f"[done] canonical variant {canonical_name}") if __name__ == "__main__": main()