diff --git a/surfaces/blender/experiments/mechs/paint.py b/surfaces/blender/experiments/mechs/paint.py index d69f1cb..4b9f4fc 100644 --- a/surfaces/blender/experiments/mechs/paint.py +++ b/surfaces/blender/experiments/mechs/paint.py @@ -7,9 +7,10 @@ The hook, after a mech is built and before it is rendered: import paint; paint.apply("seraph") -apply(preset, ground=0.0, objects=None, scale=1.0, **overrides) swaps, by material name, every armour paint for -the preset's paint, every bare-metal material for its metal, every marking for its worn stencil; it leaves glass, -rubber, glows and pits alone; called again with another preset it repaints. Returns {old material name: new material}. `ground` is the world height of the +apply(preset, ground=0.0, objects=None, scale=1.0, roles=None, glass="smoked", lens="lens", **overrides) swaps, by material name, every armour paint for +the preset's paint, every bare-metal material for its metal, every marking for its worn stencil, every glass for +a MechGlass (glass="smoked" on panes, lens="lens" on optics under `lens_below` metres across); it leaves rubber, +glows and pits alone; called again with another preset it repaints. Returns {old material name: new material}. `ground` is the world height of the soles (mud and wet are measured from it); `scale` multiplies every noise frequency (a mech half as tall wants 2). An override is any MechPaint input by its lower-case name with underscores, e.g. apply("mcr3", wear=1.4); it reaches the armour and the markings, not the bare metal (material() tunes one role alone). @@ -18,11 +19,35 @@ PRESETS seraph (cleaner, warm drab: 30.webp), mcr3 (grey drab, middli breaker (dark, heavy wear, mud to the knee: 24.webp), paladin (27.webp), kestrel (29.webp). material(name, role="armour", preset="seraph", **overrides) one material of a preset: role is armour, metal, mark or hazard. +glass(name, preset="smoked", **overrides) + one MechGlass material. GLASS: smoked (a near-black canopy pane: RAPTOR, 38.webp), amber (a + dark amber dome: WYVERN, 35.webp), faceted (smoked, broken into panes by a dark lattice), + lens (a coated blue optic), lens_amber (a laser's or lamp's warm optic). +shield(objects=None, lights=None) + light-links the glass out of the stage's area lights; only a glass with Reflect over 0 needs it. +mirrored(*matrices) + True where a chain of frames (4x4 or 3x3) reverses handedness: what a marking placed in it + must be flipped by to read left to right. surface.decal asks it of the plate and the frame. + +Why glass is its own group, and why it does not mirror the scene. mechlib.stage_field lights a mech with three +square area lights, the key 5 scene radii across at 4 radii: half the sky over a canopy. A smooth dielectric +mirrors that key at Fresnel strength, and the key's radiance is many times the sky's, so any glossy pane turned +up or forward renders pale whatever its colour. Measured on WYVERN pass 2's canopy (wyvern.blend, 16 samples, mean +scene-linear radiance of the pane): 0.236 as built (roughness 0.3, coat 0.15); 0.061 with the key hidden from +glossy rays; 0.037 under the world alone; 0.406 with mechlib's own "glass" (roughness 0.04, coat 1). Transmission, +the light path and the missing interior play no part: the pane is opaque, and with its specular off it renders +(0.012, 0.005, 0.002) brown. So MechGlass keeps Cycles' specular off (Reflect 0) and paints its reflection as +emission, from the reflected ray alone: a horizon-bright overcast sky in banks, a dark ground, a small sun's glint, all at +Fresnel strength. It reads the same on any stage. Reflect over 0 brings Cycles' own reflections back +(the mech's frames in the pane); then call shield() once the stage's lights exist, or the pane goes pale again. group() the MechPaint node group (built once per file). Its layers, bottom up: base paint Base Color, toned per plate by Object Info's Random and Geometry's Random Per Island (value, and a little hue and saturation: Tone Variation), mottled by two world-space noises (Mottle). cover a marking's own colour over the paint (Cover Color, Cover); Cover Wear opens it, by Alpha, to - the plate under the decal, in specks and in patches. + the plate under the decal, in specks and in patches. Legibility (0 to 2) lifts the marking back + out of the film, streaks and dust laid over it, brightens it past 1 and closes part of the + wear; chips and mud still take it. 0 is the paint of the first pass, where a number under + breaker's grime could not be read at figure scale. cavity grime Ambient Occlusion (4 samples, 0.45 m) darkens recesses, seams and the undersides of overhangs, and a thin film lies in patches on open faces (Grime, Grime Color). streaks noise stretched along world Z, on faces that stand upright, stronger where AO says something @@ -50,6 +75,7 @@ INPUTS = { "Cover Color": ("NodeSocketColor", (0.2, 0.19, 0.165, 1.0)), "Cover": ("NodeSocketFloat", 0.0), "Cover Wear": ("NodeSocketFloat", 0.5), + "Legibility": ("NodeSocketFloat", 0.0), "Grime": ("NodeSocketFloat", 1.0), "Grime Color": ("NodeSocketColor", (0.02, 0.017, 0.013, 1.0)), "Streaks": ("NodeSocketFloat", 1.0), @@ -75,32 +101,33 @@ PRESETS = { # SERAPH, 30.webp: a warm grey drab, the cleanest of the sheets; small chips, light streaks, mud on the feet only. "seraph": {"armour": {"base_color": (0.066, 0.056, 0.038), "wear": 0.85, "grime": 0.8, "streaks": 0.8, "dust": 0.6, "mud": 0.8, "mud_top": 1.2, "wet_top": 2.0}, "metal": {**_METAL, "wear": 0.6, "mud": 0.8, "mud_top": 1.2}, - "mark": {"cover_color": (0.22, 0.21, 0.18), "cover_wear": 0.55}}, + "mark": {"cover_color": (0.3, 0.29, 0.25), "cover_wear": 0.5, "legibility": 0.8}}, # MCR-3, 25.webp: greyer and darker, every plate chipped along its edges, streaked, dirty to the shin. "mcr3": {"armour": {"base_color": (0.048, 0.044, 0.034), "wear": 1.0, "grime": 1.0, "streaks": 1.0, "dust": 0.45, "mud": 1.0, "mud_top": 1.4, "wet_top": 2.4, "tone_variation": 0.32}, "metal": {**_METAL, "wear": 0.9}, - "mark": {"cover_color": (0.2, 0.195, 0.175), "cover_wear": 0.5}}, + "mark": {"cover_color": (0.3, 0.29, 0.26), "cover_wear": 0.45, "legibility": 0.9}}, # BREAKER, 24.webp: the same drab two stops down, the heaviest wear on any sheet, mud to the knee. "breaker": {"armour": {"base_color": (0.03, 0.028, 0.021), "wear": 1.5, "grime": 1.3, "streaks": 1.3, "dust": 0.35, "mud": 1.3, "mud_top": 2.2, "wet_top": 4.0, "tone_variation": 0.35, "primer_color": (0.12, 0.11, 0.09)}, "metal": {**_METAL, "wear": 1.3, "grime": 1.5, "mud": 1.3, "mud_top": 2.2}, - "mark": {"cover_color": (0.19, 0.18, 0.15), "cover_wear": 0.75}}, + "mark": {"cover_color": (0.3, 0.285, 0.24), "cover_wear": 0.6, "legibility": 0.75}}, # PALADIN, 27.webp: an olive greener than SERAPH's, middling wear. "paladin": {"armour": {"base_color": (0.05, 0.052, 0.033), "wear": 0.9, "grime": 0.9, "streaks": 0.9}, "metal": {**_METAL, "wear": 0.8}, - "mark": {"cover_wear": 0.5}}, + "mark": {"cover_color": (0.3, 0.29, 0.25), "cover_wear": 0.5, "legibility": 0.8}}, # KESTREL, 29.webp: a light grey-green scout paint, thin wear, long streaks. "kestrel": {"armour": {"base_color": (0.06, 0.062, 0.048), "wear": 0.8, "grime": 0.9, "streaks": 1.2, "mud_top": 1.0}, "metal": {**_METAL, "wear": 0.7}, - "mark": {"cover_wear": 0.5}}, + "mark": {"cover_color": (0.3, 0.29, 0.25), "cover_wear": 0.5, "legibility": 0.8}}, } ROLES = { "armour": {"khaki", "olive", "olive_light", "plate_olive", "plate_white", "plate_grey", "plate_sand", "drab", "drab_fit", "drab_dark", "drab_dark_fit"}, "metal": {"gunmetal", "frame", "machine", "structure", "plate_dark"}, "mark": {"stencil", "marking", "marking_fresh"}, "hazard": {"hazard", "accent_yellow"}, + "glass": {"glass", "canopy", "wyvern_canopy", "optic"}, } -HAZARD = {"cover_color": (0.32, 0.2, 0.025), "cover_wear": 0.7} +HAZARD = {"cover_color": (0.32, 0.2, 0.025), "cover_wear": 0.7, "legibility": 0.5} class _Net: @@ -163,11 +190,22 @@ class _Net: return node.outputs[0] +def _current(name, inputs): + """The file's node group of this name if its inputs are this module's, else a new, empty one: a .blend painted + by an older paint.py keeps its group under .old, for whatever still uses it.""" + old = bpy.data.node_groups.get(name) + if old and [i.name for i in old.interface.items_tree if i.item_type == "SOCKET" and i.in_out == "INPUT"] == list(inputs): + return old + if old: + old.name = name + ".old" + return bpy.data.node_groups.new(name, "ShaderNodeTree") + + def group(): """The MechPaint node group; built on first call, then the one in the file.""" - if GROUP in bpy.data.node_groups: - return bpy.data.node_groups[GROUP] - tree = bpy.data.node_groups.new(GROUP, "ShaderNodeTree") + tree = _current(GROUP, INPUTS) + if tree.nodes: + return tree for name, (kind, default) in INPUTS.items(): s = tree.interface.new_socket(name, in_out="INPUT", socket_type=kind) s.default_value = default @@ -197,10 +235,11 @@ def group(): shade = n.math("ADD", n.math("ADD", n.ramp(blotch, 0.3, 0.7, (-0.3, 0.3)), n.ramp(speck, 0.3, 0.7, (-0.2, 0.2))), n.ramp(n.noise(pos, 6.0, 5.0, 0.7), 0.3, 0.7, (-0.22, 0.22))) col = n.vec("SCALE", hsv.outputs["Color"], scale=n.math("MULTIPLY_ADD", shade, G["Mottle"], 1.0)) # a marking's own colour over it, worn through by Alpha - col = n.mix(col, n.vec("SCALE", G["Cover Color"], scale=n.ramp(n.noise(pos, 7.0, 4.0), 0.3, 0.7, (0.6, 1.05))), G["Cover"]) + cover = n.vec("SCALE", G["Cover Color"], scale=n.ramp(n.noise(pos, 7.0, 4.0), 0.3, 0.7, (0.6, 1.05))) + col = n.mix(col, cover, G["Cover"]) fine_lo, patch_lo = n.ramp(G["Cover Wear"], 0.0, 1.0, (0.7, 0.46)), n.ramp(G["Cover Wear"], 0.0, 1.0, (0.82, 0.46)) gone = n.math("MAXIMUM", n.ramp(n.noise(pos, 38.0, 3.0, 0.6, 1.2), fine_lo, n.math("ADD", fine_lo, 0.03)), n.ramp(n.noise(pos, 4.5, 5.0), patch_lo, n.math("ADD", patch_lo, 0.05))) - alpha = n.math("SUBTRACT", 1.0, n.mul(gone, n.math("MINIMUM", G["Cover"], 1.0)), clamp=True) + alpha = n.math("SUBTRACT", 1.0, n.mul(gone, n.math("MINIMUM", G["Cover"], 1.0), n.ramp(G["Legibility"], 0.0, 2.0, (1.0, 0.3))), clamp=True) # cavity grime ao = tree.nodes.new("ShaderNodeAmbientOcclusion") @@ -224,6 +263,8 @@ def group(): # dust on what looks up dust = n.mul(n.ramp(up, 0.45, 0.95), n.ramp(n.noise(pos, 3.0, 6.0, 0.7), 0.25, 0.7, (0.25, 1.0)), G["Dust"], 0.6, clamp=True) col = n.mix(col, G["Dust Color"], dust) + # legibility: the marking's paint lifted back out of the film, streaks and dust; chips and mud below still take it + col = n.mix(col, n.vec("SCALE", cover, scale=n.ramp(G["Legibility"], 1.0, 2.0, (1.0, 1.7))), n.mul(G["Cover"], G["Legibility"], clamp=True)) # edge wear: chips to metal with a primer ring, scuffs on open faces bevel = tree.nodes.new("ShaderNodeBevel") @@ -262,11 +303,195 @@ def group(): return tree -def _input_name(key): - for name in INPUTS: +GLASS_GROUP = "MechGlass" +GLASS_INPUTS = { + "Tint": ("NodeSocketColor", (0.006, 0.007, 0.008, 1.0)), # the pane's own colour, seen where nothing shows through + "Interior": ("NodeSocketFloat", 0.5), # how much of Interior Color shows where the eye looks straight in + "Interior Color": ("NodeSocketColor", (0.01, 0.011, 0.012, 1.0)), + "Roughness": ("NodeSocketFloat", 0.04), + "Reflect": ("NodeSocketFloat", 0.0), # Cycles' own specular, 1 a plain dielectric: see shield() + "Sky": ("NodeSocketFloat", 2.2), # 1 is the physical reflection of the sky; the sheets paint it stronger + "Sky Color": ("NodeSocketColor", (0.58, 0.61, 0.67, 1.0)), # stage_field's world: (0.5, 0.53, 0.58) at 1.15 + "Clouds": ("NodeSocketFloat", 1.0), # the reflected sky broken into banks, so a reflection has a shape + "Ground Color": ("NodeSocketColor", (0.06, 0.055, 0.05, 1.0)), + "Glint": ("NodeSocketFloat", 1.0), + "Glint Direction": ("NodeSocketVector", (0.35, 0.5, 0.8)), # toward the sun, in the world: high over the mech's front left, where the hero views stand + "Glint Size": ("NodeSocketFloat", 0.006), # 1 - cos of the sun's half angle: 0.006 is 6 degrees + "Facets": ("NodeSocketFloat", 0.0), # panes a metre; 0 is one pane + "Facet Tilt": ("NodeSocketFloat", 0.1), + "Mullion": ("NodeSocketFloat", 0.02), # the lattice bar's width, metres + "Mullion Color": ("NodeSocketColor", (0.003, 0.003, 0.003, 1.0)), + "Dirt": ("NodeSocketFloat", 1.0), + "Dirt Color": ("NodeSocketColor", (0.03, 0.028, 0.023, 1.0)), + "Scale": ("NodeSocketFloat", 1.0), +} +GLASS_OUTPUTS = {"Color": "NodeSocketColor", "Roughness": "NodeSocketFloat", "Specular": "NodeSocketFloat", "Normal": "NodeSocketVector", "Emission": "NodeSocketColor"} +_LENS = {"roughness": 0.02, "interior": 1.0, "dirt": 0.5} +GLASS = { + # RAPTOR, 38.webp, RECESSED COCKPIT: near-black panes in an armour lattice, a pale sky low on each, no interior. + "smoked": {}, + # WYVERN, 35.webp, COCKPIT & SENSOR CANOPY: a dark amber dome, the amber showing where the eye looks in. + "amber": {"tint": (0.006, 0.0025, 0.001), "interior": 1.0, "interior_color": (0.02, 0.0062, 0.0012)}, + # one blown pane read as a lattice of flat ones: for a canopy built as a single dome with no frames of its own. + "faceted": {"facets": 3.5, "facet_tilt": 0.12, "mullion": 0.022}, + # a coated optic: a blue-violet depth, a cold reflection (WYVERN's projector and helmet sensor; RAPTOR's emitters). + "lens": {**_LENS, "tint": (0.004, 0.005, 0.012), "interior_color": (0.0015, 0.005, 0.022), "sky_color": (0.3, 0.45, 0.95), "sky": 1.2}, + "lens_amber": {**_LENS, "tint": (0.012, 0.005, 0.002), "interior_color": (0.02, 0.0055, 0.0008), "sky_color": (0.95, 0.6, 0.3), "sky": 1.2}, +} + + +def glass_group(): + """The MechGlass node group; built on first call, then the one in the file. See the module header for why its + reflection is painted. Its layers: the pane (Tint, Interior Color where the view is square to it, broken by a + slow noise); facets (a Voronoi lattice in the object's frame: each cell's normal tilted its own way, a bar of + Mullion Color on the cell borders); dirt (Ambient Occlusion puts it in the corners a frame makes, a noise on + what looks up); the painted reflection (sky above the reflected horizon, brightest at it and broken into banks by Clouds; ground below; a + sun's disc and halo about Glint Direction), at Fresnel strength for IOR 1.5, dimmed by the dirt.""" + tree = _current(GLASS_GROUP, GLASS_INPUTS) + if tree.nodes: + return tree + for name, (kind, default) in GLASS_INPUTS.items(): + tree.interface.new_socket(name, in_out="INPUT", socket_type=kind).default_value = default + for name, kind in GLASS_OUTPUTS.items(): + tree.interface.new_socket(name, in_out="OUTPUT", socket_type=kind) + n = _Net(tree) + gin, gout = tree.nodes.new("NodeGroupInput"), tree.nodes.new("NodeGroupOutput") + G = gin.outputs + geo, coords = tree.nodes.new("ShaderNodeNewGeometry"), tree.nodes.new("ShaderNodeTexCoord") + own = n.vec("SCALE", coords.outputs["Object"], scale=G["Scale"]) + + def z_of(vector): + node = tree.nodes.new("ShaderNodeSeparateXYZ") + tree.links.new(vector, node.inputs[0]) + return node.outputs["Z"] + + # facets: a tilt a cell, a bar on the borders + on = n.ramp(G["Facets"], 0.0, 0.01) + cells = n.vec("SCALE", own, scale=G["Facets"]) + lattice = {} + for feature in ("F1", "DISTANCE_TO_EDGE"): + node = tree.nodes.new("ShaderNodeTexVoronoi") + node.voronoi_dimensions, node.feature = "3D", feature + node.inputs["Scale"].default_value, node.inputs["Randomness"].default_value = 1.0, 0.75 + tree.links.new(cells, node.inputs["Vector"]) + lattice[feature] = node + tilt = n.vec("SCALE", n.vec("SUBTRACT", lattice["F1"].outputs["Color"], (0.5, 0.5, 0.5)), scale=n.mul(G["Facet Tilt"], on, 2.0)) + normal = n.vec("NORMALIZE", n.vec("ADD", geo.outputs["Normal"], tilt)) + half = n.mul(G["Mullion"], G["Facets"], 0.5) + bar = n.mul(n.ramp(lattice["DISTANCE_TO_EDGE"].outputs["Distance"], n.math("MULTIPLY_ADD", half, 1.25, 0.002), half), on) + + # dirt: in the corners a frame makes, and on what looks up + ao = tree.nodes.new("ShaderNodeAmbientOcclusion") + ao.samples, ao.inputs["Distance"].default_value = 4, 0.22 + patchy = n.ramp(n.noise(own, 6.0, 5.0, 0.7), 0.3, 0.65, (0.35, 1.0)) + corner = n.mul(n.ramp(ao.outputs["AO"], 0.9, 0.45), patchy) + settled = n.mul(n.ramp(z_of(geo.outputs["Normal"]), 0.35, 0.95), n.ramp(n.noise(own, 2.2, 6.0, 0.7), 0.35, 0.7, (0.05, 0.45))) + dirt = n.mul(n.math("MAXIMUM", corner, settled), G["Dirt"], clamp=True) + + # the pane: its tint, the interior's colour where the eye looks straight in + facing = tree.nodes.new("ShaderNodeLayerWeight") + facing.inputs["Blend"].default_value = 0.5 + tree.links.new(normal, facing.inputs["Normal"]) + square = n.math("POWER", n.math("SUBTRACT", 1.0, facing.outputs["Facing"], clamp=True), 3.0) + inside = n.mul(square, G["Interior"], n.ramp(n.noise(own, 2.6, 3.0, 0.5), 0.3, 0.7, (0.35, 1.0)), clamp=True) + col = n.mix(G["Tint"], G["Interior Color"], inside) + col = n.mix(col, G["Mullion Color"], bar) + col = n.mix(col, G["Dirt Color"], n.math("MULTIPLY", dirt, 0.8)) + + # the painted reflection, from the reflected ray + ray = n.vec("REFLECT", n.vec("SCALE", geo.outputs["Incoming"], scale=-1.0), normal) + rz = z_of(ray) + banks = n.noise(n.vec("MULTIPLY", ray, (1.6, 1.6, 4.0)), 1.0, 3.0, 0.55, 0.6) + banks = n.math("MULTIPLY_ADD", n.math("SUBTRACT", n.ramp(banks, 0.4, 0.62, (0.3, 1.45)), 1.0), G["Clouds"], 1.0) + sky = n.vec("SCALE", G["Sky Color"], scale=n.mul(n.ramp(rz, -0.06, 0.04), n.ramp(rz, 0.0, 0.75, (1.25, 0.4)), banks, G["Sky"])) + env = n.mix(n.vec("SCALE", G["Ground Color"], scale=G["Sky"]), sky, n.ramp(rz, -0.06, 0.04)) + toward = n.vec("DOT_PRODUCT", ray, n.vec("NORMALIZE", G["Glint Direction"])) + edge = n.math("SUBTRACT", 1.0, G["Glint Size"]) + disc = n.math("POWER", n.ramp(toward, n.math("MULTIPLY_ADD", G["Glint Size"], -3.0, edge), 1.0), 3.0) + halo = n.math("POWER", n.ramp(toward, 0.6, 1.0), 10.0) + sun = n.mul(n.math("ADD", n.math("MULTIPLY", disc, 7.0), n.math("MULTIPLY", halo, 0.4)), G["Glint"]) + env = n.vec("ADD", env, n.vec("SCALE", (1.0, 0.96, 0.9), scale=sun)) + fresnel = tree.nodes.new("ShaderNodeFresnel") + fresnel.inputs["IOR"].default_value = 1.5 + tree.links.new(normal, fresnel.inputs["Normal"]) + clear = n.mul(n.math("SUBTRACT", 1.0, n.math("MULTIPLY", dirt, 0.6)), n.math("SUBTRACT", 1.0, bar)) + painted = n.vec("SCALE", env, scale=n.mul(fresnel.outputs[0], clear, n.math("SUBTRACT", 1.0, G["Reflect"], clamp=True))) + + tree.links.new(col, gout.inputs["Color"]) + tree.links.new(n.math("ADD", G["Roughness"], n.math("MAXIMUM", n.math("MULTIPLY", dirt, 0.55), n.math("MULTIPLY", bar, 0.5)), clamp=True), gout.inputs["Roughness"]) + tree.links.new(n.mul(G["Reflect"], 0.5, n.math("SUBTRACT", 1.0, n.math("MULTIPLY", dirt, 0.6))), gout.inputs["Specular"]) + tree.links.new(normal, gout.inputs["Normal"]) + tree.links.new(painted, gout.inputs["Emission"]) + return tree + + +def glass(name, preset="smoked", **overrides): + """One MechGlass material: GLASS[preset], then `overrides` (MechGlass inputs, lower case with underscores).""" + values = {**GLASS[preset], **overrides} + mat = bpy.data.materials.get(name) or bpy.data.materials.new(name) + mat.use_nodes = True + nodes, links = mat.node_tree.nodes, mat.node_tree.links + nodes.clear() + out, bsdf, grp = nodes.new("ShaderNodeOutputMaterial"), nodes.new("ShaderNodeBsdfPrincipled"), nodes.new("ShaderNodeGroup") + grp.node_tree = glass_group() + for key, value in values.items(): + socket = grp.inputs[_input_name(key, GLASS_INPUTS)] + socket.default_value = value if isinstance(value, (int, float)) or len(value) == len(socket.default_value) else (*value, 1.0) + for a, b in (("Color", "Base Color"), ("Roughness", "Roughness"), ("Specular", "Specular IOR Level"), ("Normal", "Normal"), ("Emission", "Emission Color")): + links.new(grp.outputs[a], bsdf.inputs[b]) + bsdf.inputs["Emission Strength"].default_value = 1.0 + links.new(bsdf.outputs[0], out.inputs[0]) + tint = values.get("tint", GLASS_INPUTS["Tint"][1]) + mat.diffuse_color = (*tint[:3], 1.0) + mat["paint_role"], mat["paint_glass"] = "glass", preset + return mat + + +_make_glass = glass # apply() has a parameter of that name + + +def shield(objects=None, lights=None): + """Light-link glass out of the stage's softboxes, so a pane with Reflect over 0 mirrors the world and the mech + and not a key light half the sky across (the module header has the measurement). objects: default every + object whose only material is a MechGlass; lights: default every area light in the scene. Call it after the + stage's lights exist; call it again after adding glass. Returns the objects shielded. An object that also + carries another material is left alone and named: linking is per object, and its paint needs the lights.""" + scene = bpy.context.scene + lights = lights or [o for o in scene.objects if o.type == "LIGHT" and o.data.type == "AREA"] + if objects is None: + objects = [o for o in scene.objects if o.type == "MESH" and any(s.material and s.material.get("paint_role") == "glass" for s in o.material_slots)] + mixed = [o.name for o in objects if any(not s.material or s.material.get("paint_role") != "glass" for s in o.material_slots)] + if mixed: + print("SHIELD left alone, glass beside another material:", ", ".join(mixed), flush=True) + objects = [o for o in objects if o.name not in mixed] + group_ = bpy.data.collections.get("paint.shielded") or bpy.data.collections.new("paint.shielded") + for obj in list(group_.objects): + group_.objects.unlink(obj) + for obj in objects: + group_.objects.link(obj) + for entry in group_.collection_objects: + entry.light_linking.link_state = "EXCLUDE" + for light in lights: + light.light_linking.receiver_collection = group_ if objects else None + return objects + + +def mirrored(*matrices): + """True where the product of these frames (4x4 or 3x3, outermost first) reverses handedness: a reflection in + the object's world matrix, in a Build's to_host, or in a frame written for the other side. A marking laid in + such a chain reads right to left until its own x is reversed; surface.decal does that.""" + sign = 1.0 + for m in matrices: + sign *= (m.to_3x3() if len(m) == 4 else m).determinant() + return sign < 0.0 + + +def _input_name(key, table=None): + table = INPUTS if table is None else table + for name in table: if name.lower().replace(" ", "_") == key: return name - raise KeyError(f"MechPaint has no input {key!r}; it has " + ", ".join(k.lower().replace(" ", "_") for k in INPUTS)) + raise KeyError(f"no input {key!r}; there are " + ", ".join(k.lower().replace(" ", "_") for k in table)) def material(name, role="armour", preset="seraph", **overrides): @@ -298,8 +523,11 @@ def material(name, role="armour", preset="seraph", **overrides): return mat -def apply(preset="seraph", ground=0.0, objects=None, scale=1.0, roles=None, **overrides): - """Repaint a built mech: see the module header. `roles` adds or moves material names, {name: role}.""" +def apply(preset="seraph", ground=0.0, objects=None, scale=1.0, roles=None, glass="smoked", lens="lens", lens_below=0.3, **overrides): + """Repaint a built mech: see the module header. `roles` adds or moves material names, {name: role}; a role of + None leaves that material alone. glass, lens: the GLASS preset (or a dict of MechGlass inputs, over "smoked" + unless it names a "preset") for panes and for optics, an optic being a glass object under `lens_below` metres + across at scale 1.""" role_of = {name: role for role, names in ROLES.items() for name in names} role_of.update(roles or {}) made, swapped = {}, {} @@ -307,11 +535,20 @@ def apply(preset="seraph", ground=0.0, objects=None, scale=1.0, roles=None, **ov if obj.type not in {"MESH", "CURVE", "FONT"} or obj.get("stage"): continue for slot in obj.material_slots: - role = slot.material and (slot.material.get("paint_role") or role_of.get(slot.material.name)) # a painted mech can be repainted + role = slot.material and role_of.get(slot.material.name, slot.material.get("paint_role")) # a painted mech can be repainted if not role: continue - if role not in made: - made[role] = material(f"paint_{preset}_{role}", role, preset, ground_z=ground, scale=scale, **({} if role == "metal" else overrides)) - swapped[slot.material.name] = made[role] - slot.material = made[role] + key = role + if role == "glass": + key = "lens" if max(obj.dimensions) * scale < lens_below else "pane" + if key not in made: + if role == "glass": + which = lens if key == "lens" else glass + made[key] = _make_glass(f"paint_glass_{key}", **({"preset": which} if isinstance(which, str) else which), scale=scale) + else: + made[key] = material(f"paint_{preset}_{role}", role, preset, ground_z=ground, scale=scale, **({} if role == "metal" else overrides)) + swapped[slot.material.name] = made[key] + slot.material = made[key] + if any(m.get("paint_role") == "glass" and m.node_tree.nodes["Group"].inputs["Reflect"].default_value > 0 for m in made.values()): + shield() return swapped diff --git a/surfaces/blender/experiments/mechs/paint_bench.py b/surfaces/blender/experiments/mechs/paint_bench.py new file mode 100644 index 0000000..2698c4b --- /dev/null +++ b/surfaces/blender/experiments/mechs/paint_bench.py @@ -0,0 +1,206 @@ +"""The glass and marking bench for paint.py: one small hull with a domed canopy in hoops, a flat framed pane and an +optic in a bezel, under mechlib.stage_field, rendered once per tile of catalog_glass.png (paint_sheets.py lays +them out). No Brokkr add-on needed. + + blender --background --factory-startup --python paint_bench.py MECH_OUT takes bench/.png + PAINT_BENCH=tile,tile,... renders only those tiles; PAINT_SAMPLES (default 48), PAINT_WIDTH (default 720) + +Tiles + cause_* why glass rendered pale, on mechlib's own "glass" (roughness 0.04, a full coat): as it was; with the + key light hidden from glossy rays; under the world alone; and paint's two cures, the MechGlass (its + reflection painted) and a MechGlass with Reflect 1 behind shield(). + glass_* each GLASS preset on the canopy and the pane; the optic takes lens, or lens_amber under glass_amber. + mark_* the numeral 03 on a plate and on its mirror image (a negative scale): surface.decal as it was (the + mutant: mirrored() answering False) and as it is. + legible the 27 under breaker's paint, on plates leaning 50 degrees back, at Legibility 0, 0.4, 0.75 (the + preset's) and 1.5. +""" +import math +import os +import sys +from pathlib import Path + +import bmesh +import bpy +from mathutils import Matrix, Vector + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import mechlib as M +import paint +import surface as S + +OUT = Path(os.environ["MECH_OUT"]) / "bench" +assert OUT.is_absolute() +OUT.mkdir(parents=True, exist_ok=True) +ONLY = [t for t in os.environ.get("PAINT_BENCH", "").split(",") if t] +SAMPLES, WIDTH = int(os.environ.get("PAINT_SAMPLES", 48)), int(os.environ.get("PAINT_WIDTH", 720)) +T = Matrix.Translation + + +def mesh_object(name, bm, mat, smooth=False): + bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:]) + for f in bm.faces: + f.smooth = smooth + mesh = bpy.data.meshes.new(name) + bm.to_mesh(mesh) + bm.free() + obj = bpy.data.objects.new(name, mesh) + bpy.context.scene.collection.objects.link(obj) + mesh.materials.append(M.MATS[mat]) + return obj + + +def box(name, at, size, mat, turn=Matrix.Identity(4)): + bm = bmesh.new() + bmesh.ops.create_cube(bm, size=1.0, matrix=T(at) @ turn @ Matrix.Diagonal((*size, 1.0))) + return mesh_object(name, bm, mat) + + +def hull(): + """A 2.4 m hull: canopy on its deck, a pane in its raked brow, an optic in its nose.""" + box("Hull", (0, 0, 1.0), (2.4, 3.2, 1.6), "khaki") + box("Hull.brow", (0, 1.25, 2.02), (1.9, 0.9, 0.5), "khaki", Matrix.Rotation(math.radians(-24), 4, "X")) + # the canopy: half an ellipsoid, three hoops and a spine over it + bm = bmesh.new() + bmesh.ops.create_uvsphere(bm, u_segments=48, v_segments=24, radius=1.0, matrix=T((0, -0.35, 1.78)) @ Matrix.Diagonal((0.62, 1.05, 0.58, 1.0))) + bmesh.ops.bisect_plane(bm, geom=bm.verts[:] + bm.edges[:] + bm.faces[:], plane_co=(0, 0, 1.8), plane_no=(0, 0, -1), clear_outer=True) + mesh_object("Canopy.glass", bm, "glass", smooth=True) + for k, y in enumerate((-0.95, -0.35, 0.25)): + bm = bmesh.new() + w = 0.62 * math.sqrt(max(1 - ((y + 0.35) / 1.05) ** 2, 0.0)) + ring = [(1.03 * w * math.cos(a), y, 1.78 + 1.03 * 0.58 * math.sqrt(max(1 - ((y + 0.35) / 1.05) ** 2, 0.0)) * math.sin(a)) for a in (math.radians(6 * i) for i in range(31))] + for a, b in zip(ring, ring[1:]): + quad = [bm.verts.new((a[0], a[1] - 0.035, a[2])), bm.verts.new((b[0], b[1] - 0.035, b[2])), bm.verts.new((b[0], b[1] + 0.035, b[2])), bm.verts.new((a[0], a[1] + 0.035, a[2]))] + bm.faces.new(quad) + obj = mesh_object(f"Canopy.hoop{k}", bm, "gunmetal") + mod = obj.modifiers.new("Solidify", "SOLIDIFY") + mod.thickness, mod.offset = 0.05, 1.0 + box("Canopy.sill", (0, -0.35, 1.8), (1.36, 2.2, 0.08), "gunmetal") + # the pane in the brow, framed + turn = Matrix.Rotation(math.radians(-24), 4, "X") + face = T((0, 1.25, 2.02)) @ turn + box("Brow.glass", face @ Vector((0, 0.451, 0.0)), (1.5, 0.012, 0.32), "glass", turn) + for k, x in enumerate((-0.78, -0.26, 0.26, 0.78)): + box(f"Brow.bar{k}", face @ Vector((x, 0.47, 0.0)), (0.06, 0.05, 0.4), "khaki", turn) + for k, z in enumerate((-0.19, 0.19)): + box(f"Brow.rail{k}", face @ Vector((0, 0.47, z)), (1.62, 0.05, 0.06), "khaki", turn) + # the optic in the nose: a bezel, a domed glass + for k, (r, d) in enumerate(((0.2, 0.1), (0.16, 0.14))): + bm = bmesh.new() + bmesh.ops.create_cone(bm, cap_ends=True, segments=32, radius1=r, radius2=r, depth=d, matrix=T((0.7, 1.6 + 0.5 * d, 0.9)) @ Matrix.Rotation(math.radians(90), 4, "X")) + mesh_object(f"Optic.bezel{k}", bm, "gunmetal") + bm = bmesh.new() + bmesh.ops.create_uvsphere(bm, u_segments=32, v_segments=16, radius=1.0, matrix=T((0.7, 1.7, 0.9)) @ Matrix.Diagonal((0.14, 0.07, 0.14, 1.0))) + mesh_object("Optic.glass", bm, "glass", smooth=True) + + +def plate(name, world, mat="khaki", lean=0.0): + """A 1.5 x 1.0 m plate standing in the world's xz plane, outside toward -y (the camera), walled inward; `lean` + degrees back from upright, where dust and film settle on it.""" + bm = bmesh.new() + bmesh.ops.create_grid(bm, x_segments=6, y_segments=4, size=0.5, matrix=Matrix.Diagonal((1.5, 1.0, 1.0, 1.0))) + obj = mesh_object(name, bm, mat) + mod = obj.modifiers.new("Kit Solidify", "SOLIDIFY") + mod.thickness, mod.offset = 0.06, -1.0 + obj.matrix_world = world @ Matrix.Rotation(math.radians(90 - lean), 4, "X") + M.update() + return obj + + +def numeral(obj, text, height): + skin = S.Skin(obj) + mark = S.numeral(skin, S._frame(*skin.nearest((0, 0, 0)), (0, 1, 0)), text, height) + skin.commit() + return mark + + +def fresh(): + bpy.ops.wm.read_factory_settings(use_empty=True) + M.MATS.clear() + for name, color, metallic in (("khaki", (0.105, 0.1, 0.075), 0.0), ("gunmetal", (0.045, 0.047, 0.045), 0.75)): + M.material(name, color, metallic, 0.6) + M.material("glass", (0.01, 0.015, 0.02), 0.0, 0.04, coat=1.0) # mechlib.materials()'s own glass + M.material("marking", (0.6, 0.6, 0.55), 0.0, 0.8) + M.mud_ground() + + +def stage(): + rig, cam, centre, radius = M.stage_field(SAMPLES) + return rig, cam, radius + + +def render(tag, rig, cam, radius, azimuth=32.0, elevation=24.0, margin=0.6, size=None): + M.shot(rig, cam, radius, azimuth, elevation, OUT / f"{tag}.png", size or (WIDTH, int(WIDTH * 0.75)), margin=margin, lens=70.0) + + +def wanted(tag): + return not ONLY or tag in ONLY + + +# --- the cause, and the cures +CAUSE = {"cause_asbuilt": {}, "cause_key_hidden": {"hide": ("Sun",)}, "cause_world_only": {"hide": ("Sun", "Bounce", "Back"), "off": True}, + "cause_painted": {"glass": "smoked"}, "cause_shielded": {"glass": {"reflect": 1.0}}} +for tag, how in CAUSE.items(): + if not wanted(tag): + continue + fresh() + hull() + paint.apply("mcr3", roles=None if "glass" in how else {"glass": None}, glass=how.get("glass", "smoked"), lens=how.get("glass", "smoked")) + rig, cam, radius = stage() + for name in how.get("hide", ()): + if how.get("off"): + bpy.data.objects[name].hide_render = True + else: + bpy.data.objects[name].visible_glossy = False + if "glass" in how: + print("SHIELDED", [o.name for o in paint.shield()] if isinstance(how["glass"], dict) else "none: the reflection is painted", flush=True) + render(tag, rig, cam, radius) + +# --- the presets +for preset in paint.GLASS: + tag = f"glass_{preset}" + close = {"smoked": "lens", "amber": "lens_amber"}.get(preset) + if preset.startswith("lens") or not (wanted(tag) or (close and wanted(close))): + continue + fresh() + hull() + paint.apply("mcr3", glass=preset, lens="lens_amber" if preset == "amber" else "lens") + rig, cam, radius = stage() + render(tag, rig, cam, radius) + if close and wanted(close): # the optic close: lens on smoked, lens_amber on amber + target = Vector((0.7, 1.7, 0.9)) + rig.rotation_euler = (0, 0, math.radians(180 + 20)) + M.update() + a, e = math.radians(20), math.radians(8) + pos = target + 1.5 * Vector((-math.sin(a) * math.cos(e), math.cos(a) * math.cos(e), math.sin(e))) + cam.data.lens = 70.0 + cam.matrix_world = T(pos) @ (target - pos).to_track_quat("-Z", "Y").to_matrix().to_4x4() + bpy.context.scene.render.filepath = str(OUT / f"{close}.png") + bpy.ops.render.render(write_still=True) + print("RENDERED", bpy.context.scene.render.filepath, flush=True) + +# --- markings on a plate and its mirror image +kept = S.mirrored +for tag, answer in (("mark_before", lambda *matrices: False), ("mark_after", kept)): + if not wanted(tag): + continue + fresh() + S.mirrored = answer + for name, world in (("PlateL", T((-0.85, 0, 0.6))), ("PlateR", T((0.85, 0, 0.6)) @ Matrix.Diagonal((-1.0, 1.0, 1.0, 1.0)))): + numeral(plate(name, world), "03", 0.5) + S.mirrored = kept + paint.apply("mcr3", ground=-3.0) # the plates stand in for a wing: clear of the mud + rig, cam, radius = stage() + render(tag, rig, cam, radius, azimuth=180.0, elevation=4.0, margin=0.42, size=(WIDTH, int(WIDTH * 0.5))) + +if wanted("legible"): + fresh() + marks = {} + for k, value in enumerate((0.0, 0.4, 0.75, 1.5)): + marks[numeral(plate(f"Plate{k}", T((1.7 * (k - 1.5), 0, 0.6)), lean=50.0), "27", 0.5)] = value + paint.apply("breaker", ground=-3.0) + for mark, value in marks.items(): + mark.material_slots[0].material = paint.material(f"paint_breaker_mark_{value}", "mark", "breaker", legibility=value, ground_z=-3.0) + rig, cam, radius = stage() + render("legible", rig, cam, radius, azimuth=180.0, elevation=14.0, margin=0.3, size=(int(WIDTH * 1.6), int(WIDTH * 0.4))) +print("BENCH done", flush=True) diff --git a/surfaces/blender/experiments/mechs/paint_glass_sheets.py b/surfaces/blender/experiments/mechs/paint_glass_sheets.py new file mode 100644 index 0000000..61812b6 --- /dev/null +++ b/surfaces/blender/experiments/mechs/paint_glass_sheets.py @@ -0,0 +1,115 @@ +"""The glass and marking sheets, from paint_bench.py's tiles and the mechs' close-ups (plain Python, PIL): + + catalog_glass.png the cause of pale glass and its two cures; the GLASS presets on the bench hull with the + concept crops they answer; a numeral on a plate and on its mirror image, before and after + surface.decal's reversal; the Legibility knob. + canopy_.png per mech: the concept's canopy, the build as its track saved it, the build under this paint; + then the same pair at figure scale, and its number where it carries one. + +python paint_glass_sheets.py MECH_OUT holds bench/ and close/ and takes the sheets; MECH_CONCEPTS the concepts. +""" +import os +from pathlib import Path +from PIL import Image, ImageDraw, ImageFont + +OUT, CONCEPTS = Path(os.environ["MECH_OUT"]), Path(os.environ["MECH_CONCEPTS"]) +BENCH, CLOSE = OUT / "bench", OUT / "close" +BG, INK, DIM = (24, 25, 27), (228, 228, 222), (150, 152, 150) +W, H, PAD, CAP = 560, 420, 10, 62 + + +def font(size): + try: + return ImageFont.truetype("arial.ttf", size) + except OSError: + return ImageFont.load_default() + + +def fit(im, w, h): + k = min(w / im.width, h / im.height) + im = im.resize((max(1, round(im.width * k)), max(1, round(im.height * k))), Image.LANCZOS) + cell = Image.new("RGB", (w, h), BG) + cell.paste(im, ((w - im.width) // 2, (h - im.height) // 2)) + return cell + + +def concept(sheet, box): + im = Image.open(CONCEPTS / sheet).convert("RGB") + k = im.width / 1024 + return im.crop(tuple(round(v * k) for v in box)) + + +def tile(source, title, note="", w=W, h=H): + """An image (a path or an Image) over its name and a note of two lines at most.""" + im = source if isinstance(source, Image.Image) else (Image.open(source).convert("RGB") if Path(source).exists() else None) + cell = Image.new("RGB", (w, h + CAP), BG) + if im is None: + ImageDraw.Draw(cell).text((10, 10), f"missing {Path(source).name}", fill=(255, 120, 120), font=font(16)) + else: + cell.paste(fit(im, w, h), (0, 0)) + d = ImageDraw.Draw(cell) + d.text((6, h + 4), title, fill=INK, font=font(17)) + for k, line in enumerate(note.split("\n")[:2]): + d.text((6, h + 25 + 17 * k), line, fill=DIM, font=font(14)) + return cell + + +def sheet(path, title, rows): + """rows: [(heading, [tiles])]; the tiles of a row sit side by side at their own widths.""" + width = max(sum(t.width + PAD for t in tiles) for _, tiles in rows) + PAD + height = 56 + sum(34 + max(t.height for t in tiles) + PAD for _, tiles in rows) + out = Image.new("RGB", (width, height), BG) + d = ImageDraw.Draw(out) + d.text((PAD, 12), title, fill=INK, font=font(28)) + y = 56 + for heading, tiles in rows: + d.text((PAD, y + 4), heading, fill=INK, font=font(20)) + y += 34 + x = PAD + for t in tiles: + out.paste(t, (x, y)) + x += t.width + PAD + y += max(t.height for t in tiles) + PAD + out.save(path) + print("SHEET", path, out.size) + + +CANOPY = {"wyvern": ("35.webp", (830, 0, 1024, 130)), "raptor": ("38.webp", (745, 0, 1024, 164)), "manticore": ("39.webp", (330, 395, 500, 520))} + +sheet(OUT / "catalog_glass.png", "paint.py: glass, and markings on mirrored plates", [ + ("Why glass rendered pale: mechlib's \"glass\" (roughness 0.04, full coat) under stage_field. The pane mirrors the key light, an area light half the sky across.", [ + tile(BENCH / "cause_asbuilt.png", "as built", "the canopy and the brow pane mirror the key"), + tile(BENCH / "cause_key_hidden.png", "key hidden from glossy rays", "the same glass; WYVERN's pane fell 0.236 to 0.061"), + tile(BENCH / "cause_world_only.png", "world alone", "no lamps: 0.037 on WYVERN's pane"), + tile(BENCH / "cause_painted.png", "paint.glass(\"smoked\")", "Reflect 0: the reflection painted, any stage"), + tile(BENCH / "cause_shielded.png", "glass(reflect=1) + paint.shield()", "Cycles' reflections, the glass light-linked\nout of the area lights"), + ]), + ("paint.GLASS presets: apply(preset, glass=..., lens=...); a glass object under lens_below (0.3 m) across takes the lens", [ + tile(BENCH / "glass_smoked.png", "smoked", "near-black panes: RAPTOR's recessed cockpit"), + tile(BENCH / "glass_amber.png", "amber (optic: lens_amber)", "tint, interior_color: WYVERN's canopy"), + tile(BENCH / "glass_faceted.png", "faceted", "facets=3.5 a metre, facet_tilt=0.12, mullion=0.022\nfor a dome built with no frames of its own"), + tile(BENCH / "lens.png", "lens", "a coated optic: sky_color, interior_color", w=420), + tile(BENCH / "lens_amber.png", "lens_amber", "a laser's or lamp's optic", w=420), + ]), + ("The concepts' glass", [ + tile(concept(*CANOPY["wyvern"]), "WYVERN, 35.webp", "COCKPIT & SENSOR CANOPY: dark amber dome"), + tile(concept(*CANOPY["raptor"]), "RAPTOR, 38.webp", "RECESSED COCKPIT: black panes in a lattice"), + tile(concept(*CANOPY["manticore"]), "MANTICORE, 39.webp", "hero view: dark panes, a pale sky on them"), + ]), + ("Markings: surface.numeral on a plate (left) and on the same plate instanced at a negative scale (right); the Legibility input", [ + tile(BENCH / "mark_before.png", "before", "the mirrored plate reads backwards", w=720, h=360), + tile(BENCH / "mark_after.png", "after: paint.mirrored() in surface.decal", "the decal's own x reversed where the chain\nof frames reverses handedness; paint_test.py", w=720, h=360), + tile(BENCH / "legible.png", "legibility = 0, 0.4, 0.75, 1.5 (breaker)", "0 is the first pass's paint; presets carry 0.75 to 0.9", w=1152, h=360), + ]), +]) + +EXTRA = {"wyvern": [("number", "the wing's 03", "wings.stencil_digits in a mirrored Build (before);\nsurface.numeral on the section's skin (after)")], + "raptor": [("number", "the cheek's 27", "breaker's mark: cover 0.19, no Legibility (before);\ncover 0.3, Legibility 0.75 (after)")], "manticore": []} +GLASS_USED = {"wyvern": "glass=\"amber\"", "raptor": "glass=\"smoked\" (default)", "manticore": "glass=\"smoked\" (default)"} +for mech, (page, box) in CANOPY.items(): + rows = [("The canopy, close", [tile(concept(page, box), f"concept, {page}", ""), tile(CLOSE / f"{mech}_canopy_before.png", "before", "as the track saved it"), + tile(CLOSE / f"{mech}_canopy_after.png", "after", f"paint.apply(..., {GLASS_USED[mech]})")]), + ("At figure scale", [tile(CLOSE / f"{mech}_figure_before.png", "before", "", w=840, h=630), tile(CLOSE / f"{mech}_figure_after.png", "after", "", w=840, h=630)])] + for stem, name, note in EXTRA[mech]: + rows.append((name, [tile(CLOSE / f"{mech}_{stem}_before.png", "before", note.split("\n")[0]), tile(CLOSE / f"{mech}_{stem}_after.png", "after", note.split("\n")[1])])) + sheet(OUT / f"canopy_{mech}.png", f"{mech.upper()}: glass before and after paint.py's MechGlass", rows) diff --git a/surfaces/blender/experiments/mechs/paint_test.py b/surfaces/blender/experiments/mechs/paint_test.py new file mode 100644 index 0000000..80650c3 --- /dev/null +++ b/surfaces/blender/experiments/mechs/paint_test.py @@ -0,0 +1,174 @@ +"""Tests for paint.py and surface.decal, run in Blender; no Brokkr add-on needed. + + blender --background --factory-startup --python-exit-code 1 --python paint_test.py + +MIRRORED PLATE. A marking laid by surface.numeral must read left to right from outside the plate whatever mirrors +the plate. The same flat plate is set up five ways: plain; instanced at a negative scale; given a frame carried +through a mirror (left-handed, as a mirroring to_host hands one down); both at once; and with the mirror baked into +its points (mechlib.shell_action's way: the object's matrix stays a turn). The laid "L7" is drawn as a viewer +outside the plate sees it (x to the viewer's right, y up, 4 mm a pixel) and compared with the numerals as the font +writes them: the reading is the overlap of the two masks over their union. + +The bound follows lodur:ruling:deterministic-bound-margin. Shipped readings, all five plates: 1.000. The mutant, +surface.decal without its reversal (surface.mirrored made to answer False): the negative-scale plate and the +mirrored-frame plate read 0.209, which is "L7" against its own mirror image; the other three stay at 1.000. BOUND +is the geometric mean of 1.000 and 0.209, 0.46: 2.2 under the shipped reading, 2.2 over the mutant's. `--mutant` +runs the mutant and exits 0 only if it is caught on exactly those two plates. + +GLASS. Every GLASS preset builds, keeps Cycles' specular off (Reflect 0: see paint.py's header for why), and +apply() gives an optic the lens and a pane the pane glass by size. +LEGIBILITY. A mark material carries its preset's Legibility; an armour material carries 0. +""" +import sys +from pathlib import Path + +import bmesh +import bpy +import numpy as np +from mathutils import Matrix, Vector + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import mechlib as M +import paint +import surface as S + +BOUND = 0.46 +TEXT = "L7" # of the pairs tried, the least like its own mirror image: 0.21 (27: 0.37; 03: 0.62) +PIXEL = 0.004 +MUTANT = "--mutant" in sys.argv +MIRROR = Matrix.Diagonal((-1.0, 1.0, 1.0, 1.0)) + + +def plate(name, world=Matrix.Identity(4), baked=False): + """A 1.2 x 0.8 m plate in its own xy plane, outside toward +z, walled inward like a massing.plate. baked: the + mirror about x written into its points, its faces turned back so the outside stays +z.""" + bm = bmesh.new() + bmesh.ops.create_grid(bm, x_segments=6, y_segments=4, size=0.5, matrix=Matrix.Diagonal((1.2, 0.8, 1.0, 1.0))) + if baked: + bmesh.ops.transform(bm, matrix=MIRROR, verts=bm.verts[:]) + bmesh.ops.reverse_faces(bm, faces=bm.faces[:]) + bm.normal_update() + assert all(f.normal.z > 0.99 for f in bm.faces), name + mesh = bpy.data.meshes.new(name) + bm.to_mesh(mesh) + bm.free() + obj = bpy.data.objects.new(name, mesh) + bpy.context.scene.collection.objects.link(obj) + mod = obj.modifiers.new("Kit Solidify", "SOLIDIFY") + mod.thickness, mod.offset = 0.04, -1.0 + obj.matrix_world = world + M.update() + return obj + + +def raster(tris, span=0.6): + """Triangles in (right, up) metres, centred on their bounding box, as a boolean image `span` metres square.""" + tris = np.asarray(tris, dtype=np.float64) + tris -= (tris.reshape(-1, 2).min(0) + tris.reshape(-1, 2).max(0)) / 2 + n = int(span / PIXEL) + centres = (np.arange(n) + 0.5) * PIXEL - span / 2 + px, py = np.meshgrid(centres, centres[::-1]) + mask = np.zeros((n, n), bool) + for a, b, c in tris: + d = (b[1] - c[1]) * (a[0] - c[0]) + (c[0] - b[0]) * (a[1] - c[1]) + if abs(d) < 1e-12: + continue + u = ((b[1] - c[1]) * (px - c[0]) + (c[0] - b[0]) * (py - c[1])) / d + v = ((c[1] - a[1]) * (px - c[0]) + (a[0] - c[0]) * (py - c[1])) / d + mask |= (u >= 0) & (v >= 0) & (u + v <= 1) + return mask + + +def seen(obj, outward, up): + """A mesh object's triangles as a viewer outside sees them: `outward` and `up` in the world.""" + right = Vector(up).cross(Vector(outward)).normalized() + mesh = obj.data + mesh.calc_loop_triangles() + world = obj.matrix_world + pts = [world @ v.co for v in mesh.vertices] + return [[(pts[i].dot(right), pts[i].dot(Vector(up))) for i in tri.vertices] for tri in mesh.loop_triangles] + + +def written(text, height): + """The numerals as the font writes them, x right and y up: what a reader expects.""" + curve = bpy.data.curves.new("written", "FONT") + try: + curve.font = bpy.data.fonts.load(S.FONT, check_existing=True) + except RuntimeError: + pass + curve.body, curve.align_x, curve.align_y, curve.size = text, "CENTER", "CENTER", height / 0.72 + holder = bpy.data.objects.new("written", curve) + bpy.context.scene.collection.objects.link(holder) + M.update() + mesh = bpy.data.meshes.new_from_object(holder.evaluated_get(bpy.context.evaluated_depsgraph_get())) + mesh.calc_loop_triangles() + tris = [[tuple(mesh.vertices[i].co.xy) for i in tri.vertices] for tri in mesh.loop_triangles] + bpy.data.objects.remove(holder, do_unlink=True) + return raster(tris) + + +def reading(mask, truth): + return float((mask & truth).sum() / (mask | truth).sum()) + + +def mirrored_plate(): + M.MATS["marking"] = paint.material("marking", "mark", "mcr3") + truth = written(TEXT, 0.3) + own = reading(truth[:, ::-1], truth) + print(f"READING the numerals against their own mirror image: {own:.3f}", flush=True) + if MUTANT: + S.mirrored = lambda *matrices: False + cases = { # name: (world, frame's mirror, baked) + "plain": (Matrix.Identity(4), False, False), + "negative scale": (Matrix.Translation((3, 0, 0)) @ MIRROR, False, False), + "mirrored frame": (Matrix.Translation((6, 0, 0)), True, False), + "scale and frame": (Matrix.Translation((9, 0, 0)) @ MIRROR, True, False), + "baked mirror": (Matrix.Translation((12, 0, 0)), False, True), + } + readings = {} + for name, (world, flip, baked) in cases.items(): + obj = plate("Plate." + name.replace(" ", "_"), world, baked) + skin = S.Skin(obj) + frame = S._frame(*skin.nearest((0, 0, 0)), (0, 1, 0)) + if flip: + frame = MIRROR @ frame + mark = S.numeral(skin, frame, TEXT, 0.3) + M.update() + readings[name] = reading(raster(seen(mark, (0, 0, 1), (0, 1, 0))), truth) # every mirror here is about x: outside stays +z, up stays +y + print(f"READING {name}: {readings[name]:.3f}", flush=True) + failed = [name for name, r in readings.items() if r < BOUND] + if MUTANT: + assert sorted(failed) == ["mirrored frame", "negative scale"], f"the mutant must fail on the two mirrored plates, failed on {failed}" + worst = max(readings[name] for name in failed) + assert BOUND / worst >= 1.2, f"bound {BOUND} is within 1.2 of the mutant's {worst:.3f}" + else: + assert not failed, f"read backwards: {failed}" + assert min(readings.values()) / BOUND >= 1.2, f"bound {BOUND} is within 1.2 of the shipped {min(readings.values()):.3f}" + assert paint.mirrored(MIRROR) and not paint.mirrored(MIRROR, MIRROR) and paint.mirrored(MIRROR.to_3x3(), Matrix.Rotation(1.0, 4, "Z")) or MUTANT + + +def glass_and_legibility(): + for name in paint.GLASS: + mat = paint.glass("test_" + name, name) + group = mat.node_tree.nodes["Group"] + assert group.inputs["Reflect"].default_value == 0.0, name + assert group.outputs["Emission"].links and group.outputs["Normal"].links, name + small, big = plate("Lens"), plate("Pane") + small.scale = (0.1, 0.1, 0.1) + M.update() + for obj in (small, big): + obj.data.materials.append(bpy.data.materials.get("glass") or bpy.data.materials.new("glass")) + swapped = paint.apply("mcr3", objects=[small, big], glass="amber") + assert small.material_slots[0].material["paint_glass"] == "lens" and big.material_slots[0].material["paint_glass"] == "amber", swapped + assert paint.apply("breaker", objects=[small, big], glass="smoked") and big.material_slots[0].material["paint_glass"] == "smoked", "a painted glass must repaint" + mark, armour = paint.material("t_mark", "mark", "breaker"), paint.material("t_armour", "armour", "breaker") + assert mark.node_tree.nodes["Group"].inputs["Legibility"].default_value == paint.PRESETS["breaker"]["mark"]["legibility"] > 0 + assert armour.node_tree.nodes["Group"].inputs["Legibility"].default_value == 0.0 + assert paint.material("t_plain", "mark", "breaker", legibility=0.0).node_tree.nodes["Group"].inputs["Legibility"].default_value == 0.0 + + +bpy.ops.wm.read_factory_settings(use_empty=True) +mirrored_plate() +if not MUTANT: + glass_and_legibility() +print("PAINT TEST", "mutant caught" if MUTANT else "passed", flush=True) diff --git a/surfaces/blender/experiments/mechs/surface.py b/surfaces/blender/experiments/mechs/surface.py index 8a47b6a..2eb3739 100644 --- a/surfaces/blender/experiments/mechs/surface.py +++ b/surfaces/blender/experiments/mechs/surface.py @@ -46,6 +46,7 @@ from mathutils import Matrix, Vector from mathutils.bvhtree import BVHTree import mechlib as M +from paint import mirrored T = Matrix.Translation RX = lambda deg: Matrix.Rotation(math.radians(deg), 4, "X") # noqa: E731 @@ -784,7 +785,12 @@ FONT = r"C:\Windows\Fonts\bahnschrift.ttf" def decal(skin, frame, curve, mat="marking", lift=0.0012, grid=0.03): """A flat 2D curve (in its own xy, metres, centred) laid on the surface along the frame's -z: filled, cut to a - `grid` so it bends over a curve or a crease, each vertex set `lift` off the face. Becomes .mark..""" + `grid` so it bends over a curve or a crease, each vertex set `lift` off the face. Becomes .mark.. + It reads left to right from outside the plate on either side of a mech: where the plate's world matrix and the + frame together reverse handedness (paint.mirrored(): a plate instanced at a negative scale, a frame carried + through a mirroring to_host or written for the other side), the curve's own x is reversed before it is laid. + paint_test.py pins that on a mirrored plate.""" + reading = -1.0 if mirrored(skin.obj.matrix_world, frame) else 1.0 holder = bpy.data.objects.new("decal.tmp", curve) bpy.context.scene.collection.objects.link(holder) M.update() @@ -803,7 +809,7 @@ def decal(skin, frame, curve, mat="marking", lift=0.0012, grid=0.03): bmesh.ops.bisect_plane(bm, geom=bm.verts[:] + bm.edges[:] + bm.faces[:], plane_co=normal * (k * grid), plane_no=normal) k += 1 for v in bm.verts: - seat = skin.sub(frame, v.co.x - centre.x, v.co.y - centre.y) + seat = skin.sub(frame, reading * (v.co.x - centre.x), v.co.y - centre.y) v.co = seat.translation + seat.col[2].xyz * lift bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:]) probe = next(iter(bm.faces))