libraryextensions/blender/lib/Bpy.xtl
Bpy.xtl -- Blender's Python (bpy) written by X_eTaL: each function returns a piece of a script as text, and a program joins the pieces into the script Blender runs inside (written with bl:w_rite!, run by the launcher bp:launcher through bl:r_un!). The geometry is X_eTaL's: a set of cubes is worked out as arrays -- every corner, every face -- and written into the script as numbers, one mesh for them all. Written for Blender 5.1 (EEVEE is BLENDER_EEVEE; video output is media_type VIDEO). Import: "bp:" u_se< "Bpy"
The two scripts
ˡlauncher : Char
bp:launcher: the outer script. python3 run.py SCRIPT ARGS runs Blender (XETAL_BLENDER, set by bl:r_un!) in the background with its factory settings on SCRIPT, passing ARGS after "--"; a Python error inside makes the run fail. Audio is disabled; XETAL_BLENDER_ARGS supplies optional command-line arguments (shell quoting, without a shell), for example --gpu-backend vulkan on a Linux NVIDIA machine.
ˡlauncher ← "import os, shlex, subprocess, sys\nblender = os.environ.get(\"XETAL_BLENDER\") or sys.exit(\"no Blender found\")\nrun = [blender, \"--background\"] + shlex.split(os.environ.get(\"XETAL_BLENDER_ARGS\", \"\")) + [\"-noaudio\", \"--factory-startup\", \"--python-exit-code\", \"1\", \"--python\", sys.argv[1], \"--\"] + sys.argv[2:]\nsys.exit(subprocess.run(run).returncode)\n"
ˡhead : Char
bp:head: the inner script's start: an empty scene, the output directory (the first argument after "--", made), keyframes linear (an orbit at an even speed), 30 frames a second (bp:s_etup may change it), and helpers: nums(text, k) reads numbers written by X_eTaL k to a row; material, link; piece, made, attach, mesh_object (outward normals) and group build a piece of parts; keys keys a part into a named clip, clips makes each clip a track (NLA) so it exports by its name; export_piece writes one piece as glTF, its clips with it; glb_clips reads a .glb's clips back; mesh_toml writes a piece as a low-poly mesh in TOML (bp:m_eshToml); triangles counts a piece's triangles
ˡhead ← "import bmesh, bpy, math, os, sys\nargs = sys.argv[sys.argv.index(\"--\") + 1:]\nout = args[0]\nos.makedirs(out, exist_ok=True)\nbpy.ops.wm.read_factory_settings(use_empty=True)\nbpy.context.preferences.edit.keyframe_new_interpolation_type = \"LINEAR\"\nscene = bpy.context.scene\nscene.render.fps = 30\n\ndef nums(text, k):\n v = [float(t) for t in text.split()]\n return [tuple(v[i:i + k]) for i in range(0, len(v), k)]\n\ndef material(name, rgb, emit=0.0):\n m = bpy.data.materials.new(name)\n m.use_nodes = True\n p = m.node_tree.nodes[\"Principled BSDF\"]\n p.inputs[\"Base Color\"].default_value = rgb + (1.0,)\n p.inputs[\"Emission Color\"].default_value = rgb + (1.0,)\n p.inputs[\"Emission Strength\"].default_value = emit\n return m\n\ndef link(obj, mat):\n scene.collection.objects.link(obj)\n obj.data.materials.append(mat)\n return obj\n\ndef piece(name):\n p = bpy.data.objects.new(name, None)\n scene.collection.objects.link(p)\n return p\n\ndef made(name):\n o = bpy.context.active_object\n o.name = name\n o.data.name = name\n return o\n\ndef mesh_object(name, verts, faces):\n m = bpy.data.meshes.new(name)\n m.from_pydata(verts, [], faces)\n m.validate()\n bm = bmesh.new()\n bm.from_mesh(m)\n bmesh.ops.recalc_face_normals(bm, faces=bm.faces)\n bm.to_mesh(m)\n bm.free()\n m.update()\n o = bpy.data.objects.new(name, m)\n scene.collection.objects.link(o)\n return o\n\ndef group(name, owner, at, turn):\n g = bpy.data.objects.new(name, None)\n scene.collection.objects.link(g)\n g.parent = owner\n g.location = at\n g.rotation_euler = tuple(math.radians(a) for a in turn)\n return g\n\ndef attach(obj, owner, mat, at, turn):\n obj.parent = owner\n obj.location = at\n obj.rotation_euler = tuple(math.radians(a) for a in turn)\n obj.data.materials.clear()\n obj.data.materials.append(mat)\n return obj\n\nactions = {}\n\ndef keys(name, clip, path, times, values):\n o = bpy.data.objects[name]\n if o.animation_data is None:\n o.animation_data_create()\n act = actions.get((name, clip))\n if act is None:\n act = bpy.data.actions.new(name + \" \" + clip)\n actions[(name, clip)] = act\n rest = tuple(getattr(o, path))\n o.animation_data.action = act\n for t, v in zip(times, values):\n if path == \"rotation_euler\":\n v = tuple(math.radians(a) for a in v)\n setattr(o, path, v)\n o.keyframe_insert(data_path=path, frame=round(t * scene.render.fps))\n o.animation_data.action = None\n setattr(o, path, rest)\n\ndef clips():\n for (name, clip), act in actions.items():\n o = bpy.data.objects[name]\n if not any(t.name == clip for t in o.animation_data.nla_tracks):\n t = o.animation_data.nla_tracks.new()\n t.name = clip\n t.strips.new(clip, 0, act)\n\ndef glb_clips(path):\n import json, struct\n data = open(path, \"rb\").read()\n g = json.loads(data[20:20 + struct.unpack(\"<I\", data[12:16])[0]])\n found = []\n for a in g.get(\"animations\", []):\n times = [g[\"accessors\"][s[\"input\"]] for s in a[\"samplers\"]]\n what = sorted(\"%s %s\" % (g[\"nodes\"][c[\"target\"][\"node\"]][\"name\"], c[\"target\"][\"path\"]) for c in a[\"channels\"])\n found.append(\"clip %s %.2f-%.2f s: %s\" % (a[\"name\"], min(t[\"min\"][0] for t in times), max(t[\"max\"][0] for t in times), \", \".join(what)))\n return found\n\ndef export_piece(owner, path):\n clips()\n bpy.ops.object.select_all(action=\"DESELECT\")\n owner.select_set(True)\n for c in owner.children_recursive:\n c.select_set(True)\n bpy.context.view_layer.objects.active = owner\n bpy.ops.export_scene.gltf(filepath=path, export_format=\"GLB\", use_selection=True, export_animations=True, export_animation_mode=\"NLA_TRACKS\")\n\ndef triangles(owner):\n return sum(sum(len(p.vertices) - 2 for p in c.data.polygons) for c in owner.children_recursive if c.type == \"MESH\")\n\ndef srgb(x):\n return 12.92 * x if x <= 0.0031308 else 1.055 * x ** (1 / 2.4) - 0.055\n\ndef mesh_toml(owner, path, most):\n parts = sorted((c for c in owner.children_recursive if c.type == \"MESH\"), key=lambda c: c.name)\n tracks = [t for o in [owner] + list(owner.children_recursive) if o.animation_data for t in o.animation_data.nla_tracks if not t.mute]\n for t in tracks:\n t.mute = True\n total = triangles(owner)\n ratio = min(1.0, most / total) if total else 1.0\n if ratio < 1.0:\n for c in parts:\n d = c.modifiers.new(\"low\", \"DECIMATE\")\n d.use_collapse_triangulate = True\n while True:\n for c in parts:\n if ratio < 1.0:\n c.modifiers[\"low\"].ratio = ratio\n bpy.context.view_layer.update()\n deps = bpy.context.evaluated_depsgraph_get()\n n = sum(len(c.evaluated_get(deps).data.loop_triangles) for c in parts)\n if n <= most or ratio < 0.05:\n break\n ratio *= 0.97 * most / n\n back = owner.matrix_world.inverted()\n verts, faces, colors = [], [], []\n for c in parts:\n e = c.evaluated_get(deps)\n bm = bmesh.new()\n bm.from_mesh(e.to_mesh())\n bmesh.ops.triangulate(bm, faces=bm.faces)\n bm.verts.index_update()\n at = back @ c.matrix_world\n first = len(verts)\n verts += [at @ v.co for v in bm.verts]\n for f in bm.faces:\n faces.append(tuple(first + v.index + 1 for v in f.verts))\n m = c.data.materials[f.material_index]\n rgb = m.node_tree.nodes[\"Principled BSDF\"].inputs[\"Base Color\"].default_value[:3]\n colors.append(\"#\" + \"\".join(\"%02x\" % round(255 * min(1.0, max(0.0, srgb(x)))) for x in rgb))\n bm.free()\n e.to_mesh_clear()\n if ratio < 1.0:\n c.modifiers.remove(c.modifiers[\"low\"])\n for t in tracks:\n t.mute = False\n with open(path, \"w\") as f:\n f.write(\"# %s at rest, low-poly: meters, Z up, its front -Y, the origin at the middle of its base\\n\" % owner.name)\n f.write(\"name = \\\"%s\\\"\\ntriangles = %d\\n\" % (owner.name, len(faces)))\n f.write(\"vertices = [\\n\" + \"\".join(\" \\\"%.4f %.4f %.4f\\\",\\n\" % tuple(v) for v in verts) + \"]\\n\")\n f.write(\"faces = [\\n\" + \"\".join(\" \\\"%d %d %d\\\",\\n\" % t for t in faces) + \"]\\n\")\n f.write(\"colors = [\\n\" + \"\".join(\" \\\"%s\\\",\\n\" % c for c in colors) + \"]\\n\")\n return len(faces)\n\n"
ˡlook : Char
bp:look: more of the inner script, joined after bp:head by a program that uses the look's functions (bp:t_exture to bp:c_ontents): the procedural textures (stone, wood, weave, grass, thatch, snow: shader nodes that repeat over a square, baked with Cycles into images, the normals worked out from the baked height), bevel, paint; armature, bind, pose_keys; wave (a cloth simulated and kept as shapes); export_look and glb_look (a .glb's textures, skins, shapes and clips read back). bp:head is as it was, so a script without the look is unchanged.
ˡlook ← "import mathutils, numpy\n\nlooks = {}\n\ndef calc(t, op, *xs):\n n = t.nodes.new(\"ShaderNodeMath\")\n n.operation = op\n for i, x in enumerate(xs):\n if isinstance(x, (int, float)):\n n.inputs[i].default_value = x\n else:\n t.links.new(x, n.inputs[i])\n return n.outputs[0]\n\ndef ramp(t, x, lo, hi, smooth=False):\n n = t.nodes.new(\"ShaderNodeMapRange\")\n n.interpolation_type = \"SMOOTHSTEP\" if smooth else \"LINEAR\"\n t.links.new(x, n.inputs[0])\n n.inputs[1].default_value = lo\n n.inputs[2].default_value = hi\n return n.outputs[0]\n\ndef tiled_noise(t, u, v, fu, fv, detail, seed):\n tau = 2 * math.pi\n au = calc(t, \"MULTIPLY\", u, tau)\n av = calc(t, \"MULTIPLY\", v, tau)\n at = t.nodes.new(\"ShaderNodeCombineXYZ\")\n t.links.new(calc(t, \"ADD\", calc(t, \"MULTIPLY\", calc(t, \"COSINE\", au), fu / tau), 17.3 * seed), at.inputs[0])\n t.links.new(calc(t, \"MULTIPLY\", calc(t, \"SINE\", au), fu / tau), at.inputs[1])\n t.links.new(calc(t, \"MULTIPLY\", calc(t, \"COSINE\", av), fv / tau), at.inputs[2])\n n = t.nodes.new(\"ShaderNodeTexNoise\")\n n.noise_dimensions = \"4D\"\n n.inputs[\"Scale\"].default_value = 1.0\n n.inputs[\"Detail\"].default_value = detail\n t.links.new(at.outputs[0], n.inputs[\"Vector\"])\n t.links.new(calc(t, \"MULTIPLY\", calc(t, \"SINE\", av), fv / tau), n.inputs[\"W\"])\n return n.outputs[0]\n\ndef each_cell(t, a, b):\n at = t.nodes.new(\"ShaderNodeCombineXYZ\")\n for i, x in enumerate((a, b)):\n if isinstance(x, (int, float)):\n at.inputs[i].default_value = x\n else:\n t.links.new(x, at.inputs[i])\n n = t.nodes.new(\"ShaderNodeTexWhiteNoise\")\n n.noise_dimensions = \"2D\"\n t.links.new(at.outputs[0], n.inputs[\"Vector\"])\n return n.outputs[0]\n\ndef look_stone(t, u, v):\n y = calc(t, \"MULTIPLY\", v, 4.0)\n row = calc(t, \"FLOOR\", y)\n fv = calc(t, \"FRACT\", y)\n x = calc(t, \"ADD\", calc(t, \"MULTIPLY\", u, 2.0), calc(t, \"MULTIPLY\", calc(t, \"MODULO\", row, 2.0), 0.5))\n col = calc(t, \"MODULO\", calc(t, \"FLOOR\", x), 2.0)\n fu = calc(t, \"FRACT\", x)\n eu = calc(t, \"MULTIPLY\", calc(t, \"MINIMUM\", fu, calc(t, \"SUBTRACT\", 1.0, fu)), 0.5)\n ev = calc(t, \"MULTIPLY\", calc(t, \"MINIMUM\", fv, calc(t, \"SUBTRACT\", 1.0, fv)), 0.25)\n grain = tiled_noise(t, u, v, 20.0, 20.0, 5.0, 1)\n edge = calc(t, \"ADD\", calc(t, \"MINIMUM\", eu, ev), calc(t, \"MULTIPLY\", calc(t, \"SUBTRACT\", grain, 0.5), 0.03))\n face = ramp(t, edge, 0.006, 0.03, True)\n block = each_cell(t, col, row)\n shade = calc(t, \"ADD\", calc(t, \"ADD\", 0.6, calc(t, \"MULTIPLY\", block, 0.46)), calc(t, \"MULTIPLY\", grain, 0.36))\n height = calc(t, \"MULTIPLY\", face, calc(t, \"ADD\", 0.7, calc(t, \"MULTIPLY\", grain, 0.6)))\n rough = calc(t, \"SUBTRACT\", 0.98, calc(t, \"MULTIPLY\", face, 0.16))\n return face, shade, height, rough\n\ndef look_wood(t, u, v):\n y = calc(t, \"MULTIPLY\", v, 4.0)\n plank = calc(t, \"FLOOR\", y)\n fv = calc(t, \"FRACT\", y)\n one = each_cell(t, plank, 3.0)\n grain = tiled_noise(t, calc(t, \"ADD\", u, calc(t, \"MULTIPLY\", one, 3.7)), v, 3.0, 56.0, 3.0, 2)\n lines = ramp(t, grain, 0.3, 0.7)\n gap = ramp(t, calc(t, \"MULTIPLY\", calc(t, \"MINIMUM\", fv, calc(t, \"SUBTRACT\", 1.0, fv)), 0.25), 0.003, 0.012, True)\n shade = calc(t, \"MULTIPLY\", calc(t, \"ADD\", 0.8, calc(t, \"MULTIPLY\", one, 0.35)), calc(t, \"ADD\", 0.35, calc(t, \"MULTIPLY\", gap, 0.65)))\n height = calc(t, \"MULTIPLY\", gap, calc(t, \"ADD\", 0.8, calc(t, \"MULTIPLY\", lines, 0.2)))\n rough = calc(t, \"ADD\", 0.62, calc(t, \"MULTIPLY\", lines, 0.2))\n return lines, shade, height, rough\n\ndef look_weave(t, u, v):\n x = calc(t, \"MULTIPLY\", u, 16.0)\n y = calc(t, \"MULTIPLY\", v, 16.0)\n over = calc(t, \"MODULO\", calc(t, \"ADD\", calc(t, \"FLOOR\", x), calc(t, \"FLOOR\", y)), 2.0)\n hu = calc(t, \"SINE\", calc(t, \"MULTIPLY\", calc(t, \"FRACT\", x), math.pi))\n hv = calc(t, \"SINE\", calc(t, \"MULTIPLY\", calc(t, \"FRACT\", y), math.pi))\n warp = calc(t, \"MULTIPLY\", hu, calc(t, \"ADD\", 0.5, calc(t, \"MULTIPLY\", hv, 0.5)))\n weft = calc(t, \"MULTIPLY\", hv, calc(t, \"ADD\", 0.5, calc(t, \"MULTIPLY\", hu, 0.5)))\n height = calc(t, \"ADD\", weft, calc(t, \"MULTIPLY\", over, calc(t, \"SUBTRACT\", warp, weft)))\n fuzz = tiled_noise(t, u, v, 90.0, 90.0, 1.0, 3)\n tone = ramp(t, height, 0.1, 0.75)\n shade = calc(t, \"ADD\", calc(t, \"ADD\", 0.74, calc(t, \"MULTIPLY\", over, 0.14)), calc(t, \"MULTIPLY\", fuzz, 0.3))\n rough = calc(t, \"ADD\", 0.86, calc(t, \"MULTIPLY\", fuzz, 0.1))\n return tone, shade, height, rough\n\ndef look_grass(t, u, v):\n patch = tiled_noise(t, u, v, 5.0, 5.0, 3.0, 4)\n blade = tiled_noise(t, u, v, 150.0, 40.0, 2.0, 5)\n tone = ramp(t, calc(t, \"ADD\", calc(t, \"MULTIPLY\", patch, 0.6), calc(t, \"MULTIPLY\", blade, 0.4)), 0.35, 0.65)\n shade = calc(t, \"ADD\", 0.6, calc(t, \"MULTIPLY\", blade, 0.8))\n height = ramp(t, blade, 0.25, 0.75)\n rough = calc(t, \"ADD\", 0.8, calc(t, \"MULTIPLY\", blade, 0.15))\n return tone, shade, height, rough\n\ndef look_thatch(t, u, v):\n fv = calc(t, \"FRACT\", calc(t, \"MULTIPLY\", v, 3.0))\n reed = ramp(t, tiled_noise(t, u, v, 140.0, 5.0, 2.0, 6), 0.3, 0.7)\n lip = ramp(t, fv, 0.0, 0.3, True)\n shade = calc(t, \"MULTIPLY\", calc(t, \"ADD\", 0.45, calc(t, \"MULTIPLY\", lip, 0.55)), calc(t, \"ADD\", 0.75, calc(t, \"MULTIPLY\", reed, 0.5)))\n height = calc(t, \"ADD\", calc(t, \"MULTIPLY\", calc(t, \"SUBTRACT\", 1.0, fv), 0.7), calc(t, \"MULTIPLY\", reed, 0.3))\n rough = calc(t, \"ADD\", 0.84, calc(t, \"MULTIPLY\", reed, 0.1))\n return reed, shade, height, rough\n\ndef look_snow(t, u, v):\n drift = tiled_noise(t, u, v, 3.0, 3.0, 3.0, 7)\n grit = tiled_noise(t, u, v, 70.0, 70.0, 1.0, 8)\n tone = ramp(t, calc(t, \"ADD\", calc(t, \"MULTIPLY\", drift, 0.8), calc(t, \"MULTIPLY\", grit, 0.2)), 0.3, 0.7, True)\n shade = calc(t, \"ADD\", 0.94, calc(t, \"MULTIPLY\", grit, 0.12))\n height = calc(t, \"ADD\", calc(t, \"MULTIPLY\", ramp(t, drift, 0.25, 0.75, True), 0.9), calc(t, \"MULTIPLY\", grit, 0.1))\n rough = calc(t, \"ADD\", 0.5, calc(t, \"MULTIPLY\", grit, 0.25))\n return tone, shade, height, rough\n\nLOOKS = {\"stone\": (look_stone, 0.02, 0.9), \"wood\": (look_wood, 0.006, 0.7), \"weave\": (look_weave, 0.003, 0.9), \"grass\": (look_grass, 0.03, 0.9), \"thatch\": (look_thatch, 0.04, 0.9), \"snow\": (look_snow, 0.05, 0.6)}\n\ndef texture_image(name, pixels, data, deep=False):\n i = bpy.data.images.new(name, pixels, pixels, alpha=False, float_buffer=deep)\n if data:\n i.colorspace_settings.name = \"Non-Color\"\n return i\n\ndef keep_image(i):\n os.makedirs(os.path.join(out, \"textures\"), exist_ok=True)\n i.filepath_raw = os.path.join(out, \"textures\", i.name.replace(\" \", \"-\") + \".png\")\n i.file_format = \"PNG\"\n i.save()\n\ndef texture(name, kind, rgb, rgb2, meters, pixels, maps):\n if name in looks:\n return looks[name][0]\n make, relief, plain = LOOKS[kind]\n src = bpy.data.materials.new(name + \" source\")\n src.use_nodes = True\n t = src.node_tree\n t.nodes.clear()\n co = t.nodes.new(\"ShaderNodeTexCoord\")\n uv = t.nodes.new(\"ShaderNodeSeparateXYZ\")\n t.links.new(co.outputs[\"UV\"], uv.inputs[0])\n tone, shade, height, rough = make(t, uv.outputs[0], uv.outputs[1])\n mix = t.nodes.new(\"ShaderNodeMix\")\n mix.data_type = \"RGBA\"\n t.links.new(tone, mix.inputs[0])\n mix.inputs[6].default_value = rgb2 + (1.0,)\n mix.inputs[7].default_value = rgb + (1.0,)\n gray = t.nodes.new(\"ShaderNodeCombineXYZ\")\n for i in range(3):\n t.links.new(shade, gray.inputs[i])\n lit = t.nodes.new(\"ShaderNodeMix\")\n lit.data_type = \"RGBA\"\n lit.blend_type = \"MULTIPLY\"\n lit.inputs[0].default_value = 1.0\n t.links.new(mix.outputs[2], lit.inputs[6])\n t.links.new(gray.outputs[0], lit.inputs[7])\n glow = t.nodes.new(\"ShaderNodeEmission\")\n end = t.nodes.new(\"ShaderNodeOutputMaterial\")\n t.links.new(glow.outputs[0], end.inputs[0])\n to = t.nodes.new(\"ShaderNodeTexImage\")\n t.nodes.active = to\n swatch = mesh_object(name + \" swatch\", [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)], [(0, 1, 2, 3)])\n layer = swatch.data.uv_layers.new(name=\"UVMap\")\n for l in swatch.data.loops:\n layer.data[l.index].uv = swatch.data.vertices[l.vertex_index].co[:2]\n swatch.data.materials.append(src)\n engine = scene.render.engine\n scene.render.engine = \"CYCLES\"\n scene.cycles.device = \"CPU\"\n scene.cycles.samples = 16\n bpy.ops.object.select_all(action=\"DESELECT\")\n swatch.select_set(True)\n bpy.context.view_layer.objects.active = swatch\n def bake(socket, image):\n to.image = image\n t.links.new(socket, glow.inputs[0])\n bpy.ops.object.bake(type=\"EMIT\", margin=0, use_clear=True)\n return image\n m = bpy.data.materials.new(name)\n m.use_nodes = True\n mt = m.node_tree\n p = mt.nodes[\"Principled BSDF\"]\n p.inputs[\"Base Color\"].default_value = rgb + (1.0,)\n p.inputs[\"Roughness\"].default_value = plain\n def use(image, socket):\n keep_image(image)\n n = mt.nodes.new(\"ShaderNodeTexImage\")\n n.image = image\n if socket:\n mt.links.new(n.outputs[0], p.inputs[socket])\n return n\n use(bake(lit.outputs[2], texture_image(name + \" color\", pixels, False)), \"Base Color\")\n if maps >= 2:\n use(bake(rough, texture_image(name + \" roughness\", pixels, True)), \"Roughness\")\n if maps >= 3:\n deep = bake(height, texture_image(name + \" height\", pixels, True, True))\n h = numpy.empty(pixels * pixels * 4, dtype=numpy.float32)\n deep.pixels.foreach_get(h)\n h = h.reshape(pixels, pixels, 4)[:, :, 0] * (relief * pixels / meters)\n dx = (numpy.roll(h, -1, 1) - numpy.roll(h, 1, 1)) / 2\n dy = (numpy.roll(h, -1, 0) - numpy.roll(h, 1, 0)) / 2\n size = numpy.sqrt(dx * dx + dy * dy + 1)\n px = numpy.ones((pixels, pixels, 4), dtype=numpy.float32)\n px[:, :, 0] = 0.5 - 0.5 * dx / size\n px[:, :, 1] = 0.5 - 0.5 * dy / size\n px[:, :, 2] = 0.5 + 0.5 / size\n bump = texture_image(name + \" normal\", pixels, True)\n bump.pixels.foreach_set(px.ravel())\n bpy.data.images.remove(deep)\n turn = mt.nodes.new(\"ShaderNodeNormalMap\")\n mt.links.new(use(bump, None).outputs[0], turn.inputs[\"Color\"])\n mt.links.new(turn.outputs[0], p.inputs[\"Normal\"])\n scene.render.engine = engine\n mesh = swatch.data\n bpy.data.objects.remove(swatch)\n bpy.data.meshes.remove(mesh)\n bpy.data.materials.remove(src)\n looks[name] = (m, meters)\n return m\n\ndef bevel(name, width, segments):\n o = bpy.data.objects[name]\n s = o.scale.copy()\n bm = bmesh.new()\n bm.from_mesh(o.data)\n for v in bm.verts:\n v.co = v.co * s\n bm.normal_update()\n sharp = [e for e in bm.edges if len(e.link_faces) == 2 and e.calc_face_angle() > math.radians(40)]\n bmesh.ops.bevel(bm, geom=sharp, offset=width, offset_type=\"OFFSET\", segments=segments, profile=0.5, affect=\"EDGES\", clamp_overlap=True)\n bm.normal_update()\n normals = []\n for v in bm.verts:\n n = mathutils.Vector((0.0, 0.0, 0.0))\n for f in v.link_faces:\n n += f.normal * f.calc_area()\n normals.append((n * s).normalized())\n v.co = mathutils.Vector((v.co.x / s.x, v.co.y / s.y, v.co.z / s.z))\n for f in bm.faces:\n f.smooth = True\n bm.to_mesh(o.data)\n bm.free()\n o.data.update()\n o.data.normals_split_custom_set_from_vertices(normals)\n\ndef paint(name, look, turn):\n o = bpy.data.objects[name]\n m, meters = looks[look]\n mesh = o.data\n s = o.scale\n layer = mesh.uv_layers.active or mesh.uv_layers.new(name=\"UVMap\")\n for p in mesh.polygons:\n n = [abs(p.normal[i] / s[i]) for i in range(3)]\n k = n.index(max(n))\n for li in p.loop_indices:\n c = mesh.vertices[mesh.loops[li].vertex_index].co * s\n a, b = ((c.y, c.z), (c.x, c.z), (c.x, c.y))[k]\n if turn:\n a, b = b, -a\n layer.data[li].uv = (a / meters, b / meters)\n mesh.materials.clear()\n mesh.materials.append(m)\n\ndef armature(name, owner, bones, heads, tails, parents):\n a = bpy.data.armatures.new(name)\n o = bpy.data.objects.new(name, a)\n scene.collection.objects.link(o)\n o.parent = owner\n bpy.context.view_layer.objects.active = o\n bpy.ops.object.mode_set(mode=\"EDIT\")\n made = []\n for b, h, t, p in zip(bones, heads, tails, parents):\n e = a.edit_bones.new(b)\n e.head = h\n e.tail = t\n if int(p[0]):\n e.parent = made[int(p[0]) - 1]\n made.append(e)\n bpy.ops.object.mode_set(mode=\"OBJECT\")\n for b in o.pose.bones:\n b.rotation_mode = \"QUATERNION\"\n return o\n\ndef bind(name, rig, bones, reach):\n o = bpy.data.objects[name]\n r = bpy.data.objects[rig]\n bpy.context.view_layer.update()\n world = o.matrix_world.copy()\n o.parent = r\n o.matrix_parent_inverse = mathutils.Matrix.Identity(4)\n o.matrix_world = world\n bpy.context.view_layer.update()\n to = r.matrix_world.inverted() @ world\n ends = [(r.data.bones[b].head_local, r.data.bones[b].tail_local) for b in bones]\n groups = [o.vertex_groups.new(name=b) for b in bones]\n for v in o.data.vertices:\n p = to @ v.co\n d = []\n for h, t in ends:\n along = t - h\n k = min(1.0, max(0.0, (p - h).dot(along) / along.length_squared))\n d.append((p - h - k * along).length)\n near = min(d)\n w = [max(0.0, 1.0 - (x - near) / reach) ** 2 if reach > 0 else float(x == near) for x in d]\n for g, x in zip(groups, w):\n if x / sum(w) > 0.01:\n g.add([v.index], x / sum(w), \"REPLACE\")\n o.modifiers.new(\"rig\", \"ARMATURE\").object = r\n\ndef pose_keys(rig, bone, clip, path, times, values):\n o = bpy.data.objects[rig]\n b = o.pose.bones[bone]\n if o.animation_data is None:\n o.animation_data_create()\n act = actions.get((rig, clip))\n if act is None:\n act = bpy.data.actions.new(rig + \" \" + clip)\n actions[(rig, clip)] = act\n o.animation_data.action = act\n rest = b.bone.matrix_local.to_3x3()\n back = rest.inverted()\n last = None\n for t, v in zip(times, values):\n frame = round(t * scene.render.fps)\n if path == \"rotation\":\n q = (back @ mathutils.Euler([math.radians(a) for a in v], \"XYZ\").to_matrix() @ rest).to_quaternion()\n if last is not None and q.dot(last) < 0:\n q.negate()\n last = q.copy()\n b.rotation_quaternion = q\n b.keyframe_insert(\"rotation_quaternion\", frame=frame)\n elif path == \"location\":\n b.location = back @ mathutils.Vector(v)\n b.keyframe_insert(\"location\", frame=frame)\n else:\n b.scale = v\n b.keyframe_insert(\"scale\", frame=frame)\n o.animation_data.action = None\n b.rotation_quaternion = (1.0, 0.0, 0.0, 0.0)\n b.location = (0.0, 0.0, 0.0)\n b.scale = (1.0, 1.0, 1.0)\n\ndef wave(name, clip, pins, wind, seconds, count):\n o = bpy.data.objects[name]\n mesh = o.data\n n = round(seconds * scene.render.fps)\n lead = 2 * scene.render.fps\n over = n // 2\n o.vertex_groups.new(name=\"pins\").add([int(i) for i in pins], 1.0, \"REPLACE\")\n c = o.modifiers.new(\"cloth\", \"CLOTH\")\n c.settings.vertex_group_mass = \"pins\"\n c.settings.quality = 8\n c.settings.mass = 0.05\n c.settings.air_damping = 2.0\n c.settings.tension_stiffness = 12.0\n c.settings.compression_stiffness = 12.0\n c.settings.shear_stiffness = 4.0\n c.settings.bending_stiffness = 0.05\n c.point_cache.frame_start = 1\n c.point_cache.frame_end = lead + n + over\n blow = mathutils.Vector(wind)\n fields = []\n for kind, strength in ((\"WIND\", 400.0), (\"TURBULENCE\", 300.0)):\n bpy.ops.object.effector_add(type=kind)\n f = bpy.context.active_object\n f.field.strength = strength * blow.length\n f.field.flow = 0.0\n if kind == \"WIND\":\n f.field.noise = 2.0 * blow.length\n f.rotation_euler = blow.to_track_quat(\"Z\", \"Y\").to_euler() if blow.length else (0.0, 0.0, 0.0)\n else:\n f.field.size = 0.6\n fields.append(f)\n first, last = scene.frame_start, scene.frame_end\n scene.frame_start = 1\n scene.frame_end = lead + n + over\n seen = []\n for frame in range(1, lead + n + over + 1):\n scene.frame_set(frame)\n if frame > lead:\n e = o.evaluated_get(bpy.context.evaluated_depsgraph_get())\n co = numpy.empty(len(mesh.vertices) * 3, dtype=numpy.float32)\n e.data.vertices.foreach_get(\"co\", co)\n seen.append(co)\n o.modifiers.remove(c)\n for f in fields:\n bpy.data.objects.remove(f)\n scene.frame_start, scene.frame_end = first, last\n scene.frame_set(first)\n def at(i):\n if i >= over:\n return seen[i]\n k = i / over\n return k * seen[i] + (1.0 - k) * seen[n + i]\n mesh.vertices.foreach_set(\"co\", at(0))\n mesh.update()\n for p in mesh.polygons:\n p.use_smooth = True\n o.shape_key_add(name=\"Basis\")\n made = []\n for k in range(1, count):\n s = o.shape_key_add(name=\"%s %d\" % (clip, k))\n s.data.foreach_set(\"co\", at(round(k * n / count)))\n made.append(s)\n keyed = mesh.shape_keys\n if keyed.animation_data is None:\n keyed.animation_data_create()\n act = bpy.data.actions.new(name + \" \" + clip + \" shape\")\n keyed.animation_data.action = act\n for k, s in enumerate(made, 1):\n for j, x in ((k - 1, 0.0), (k, 1.0), (k + 1, 0.0)):\n s.value = x\n s.keyframe_insert(\"value\", frame=round(j * n / count))\n s.value = 0.0\n keyed.animation_data.action = None\n track = keyed.animation_data.nla_tracks.new()\n track.name = clip\n track.strips.new(clip, 0, act)\n\ndef export_look(owner, path, quality):\n clips()\n bpy.ops.object.select_all(action=\"DESELECT\")\n owner.select_set(True)\n for c in owner.children_recursive:\n c.select_set(True)\n bpy.context.view_layer.objects.active = owner\n bpy.ops.export_scene.gltf(filepath=path, export_format=\"GLB\", use_selection=True, export_animations=True, export_animation_mode=\"NLA_TRACKS\", export_image_format=\"JPEG\" if quality else \"AUTO\", export_image_quality=quality or 75, export_morph_normal=True)\n\ndef picture_size(b):\n import struct\n if b[:4] == b\"\\x89PNG\":\n return struct.unpack(\">II\", b[16:24])\n i = 2\n while i < len(b):\n if 0xC0 <= b[i + 1] <= 0xC3:\n return struct.unpack(\">HH\", b[i + 5:i + 9])[::-1]\n i += 2 + struct.unpack(\">H\", b[i + 2:i + 4])[0]\n return (0, 0)\n\ndef glb_look(path):\n import json, struct\n data = open(path, \"rb\").read()\n n = struct.unpack(\"<I\", data[12:16])[0]\n g = json.loads(data[20:20 + n])\n found, held = [], 0\n for i in g.get(\"images\", []):\n v = g[\"bufferViews\"][i[\"bufferView\"]]\n b = data[28 + n + v.get(\"byteOffset\", 0):][:v[\"byteLength\"]]\n held += len(b)\n found.append(\"texture %s: %s, %d by %d, %d bytes\" % ((i.get(\"name\", \"\"), i[\"mimeType\"]) + tuple(picture_size(b)) + (len(b),)))\n def named(x):\n return g[\"images\"][g[\"textures\"][x[\"index\"]][\"source\"]].get(\"name\", \"\") if x else \"none\"\n for m in g.get(\"materials\", []):\n p = m.get(\"pbrMetallicRoughness\", {})\n if \"baseColorTexture\" in p:\n found.append(\"material %s: color %s, roughness %s, normal %s\" % (m[\"name\"], named(p[\"baseColorTexture\"]), named(p.get(\"metallicRoughnessTexture\")), named(m.get(\"normalTexture\"))))\n for s in g.get(\"skins\", []):\n found.append(\"skin %s: %d bones\" % (s.get(\"name\", \"\"), len(s[\"joints\"])))\n for m in g.get(\"meshes\", []):\n a = m[\"primitives\"][0]\n found.append(\"mesh %s: %d corners%s%s\" % (m[\"name\"], g[\"accessors\"][a[\"attributes\"][\"POSITION\"]][\"count\"], \", skinned\" if \"JOINTS_0\" in a[\"attributes\"] else \"\", \", %d shapes\" % len(a[\"targets\"]) if \"targets\" in a else \"\"))\n for a in g.get(\"animations\", []):\n times = [g[\"accessors\"][s[\"input\"]] for s in a[\"samplers\"]]\n paths = sorted(set(c[\"target\"][\"path\"] for c in a[\"channels\"]))\n nodes = set(c[\"target\"][\"node\"] for c in a[\"channels\"])\n found.append(\"clip %s %.2f-%.2f s: %s of %d nodes, %d keys\" % (a[\"name\"], min(t[\"min\"][0] for t in times), max(t[\"max\"][0] for t in times), \" \".join(paths), len(nodes), max(t[\"count\"] for t in times)))\n return [\"file: %d bytes, %d without its textures\" % (len(data), len(data) - held)] + found\n\n"
Numbers into Python
ʰn̲ums : Any c => (a, b) -> c -> Char
ʰn̲ums ← { (v, k) z → "nums(\"\"\"" c̲at (f̲ormat r̲avel v) c̲at "\"\"\", " c̲at (f̲ormat k) c̲at ")" }
ʰq̲uote : Char -> Char
ʰq̲uote ← { t → "\"" c̲at t c̲at "\"" }
ʰt̲uple : a -> Char
ʰt̲uple ← { v → "nums(\"" c̲at (f̲ormat r̲avel v) c̲at "\", " c̲at (f̲ormat t̲ally r̲avel v) c̲at ")[0]" }
Cubes
corners : Float
corners ← 8 3 r̲eshape -0.5 -0.5 -0.5 0.5 -0.5 -0.5 0.5 0.5 -0.5 -0.5 0.5 -0.5 -0.5 -0.5 0.5 0.5 -0.5 0.5 0.5 0.5 0.5 -0.5 0.5 0.5
sides : Int
sides ← 6 4 r̲eshape 0 3 2 1 4 5 6 7 0 1 5 4 2 3 7 6 3 0 4 7 1 2 6 5
ˡc̲ubeMesh : Any a => (Float, Float) -> a -> (Float, Int)
(centers, size) bp:c_ubeMesh 0: the corners (8n by 3) and faces (6n by 4, counting corners from 0) of n cubes of that size at the centers (n by 3), as one mesh
"bp:" u̲se< "Bpy"
(c, f) ← (2 3 r̲eshape 0.0 0.0 0.0 2.0 0.0 0.0, 1.0) ᵇᵖc̲ubeMesh 0
(s̲hape c) c̲at s̲hape f 16 3 12 4
ˡc̲ubeMesh ← { (cs, size) z → n ← 1 s̲elect s̲hape cs c̲ol ← { k → r̲avel (k s̲elect₂ cs) '+ t̲able size × k s̲elect₂ corners } v ← 2 1 t̲ranspose (3 c̲at 8 × n) r̲eshape (c̲ol 1) c̲at (c̲ol 2) c̲at c̲ol 3 f ← ((6 × n) c̲at 4) r̲eshape r̲avel (8 × (r̲ange n) − 1) '+ t̲able r̲avel sides (v, f) }
ˡc̲ubes : Any b => (Char, Float, Float, a) -> b -> Char
(name, centers, size, rgb) bp:c_ubes 0: Python making n cubes of that size at the centers (n by 3, z up) as one mesh object NAME, with a material of that color (red green blue, 0 to 1)
ˡc̲ubes ← { (name, cs, size, rgb) z → (v, f) ← (cs, size) ˡc̲ubeMesh 0 (("mesh = bpy.data.meshes.new(" c̲at (ʰq̲uote name) c̲at ")\n") c̲at ("mesh.from_pydata(" c̲at (((f̲loat v), 3) ʰn̲ums 0) c̲at ", [], [tuple(int(i) for i in f) for f in " c̲at ((f, 4) ʰn̲ums 0) c̲at "])\nmesh.update()\n") c̲at "link(bpy.data.objects.new(" c̲at (ʰq̲uote name) c̲at ", mesh), material(" c̲at (ʰq̲uote name) c̲at ", " c̲at (ʰt̲uple rgb) c̲at "))\n\n") }
ˡg̲round : Any b => (Float, Float, a) -> b -> Char
(center, size, rgb) bp:g_round 0: Python making a flat square ground that wide at center (x y z, its top), colored: something for shadows to fall on
ˡg̲round ← { (at, size, rgb) z → h ← size ÷ 2.0 v ← 4 3 r̲eshape (0.0 − h) c̲at (0.0 − h) c̲at 0.0 c̲at h c̲at (0.0 − h) c̲at 0.0 c̲at h c̲at h c̲at 0.0 c̲at (0.0 − h) c̲at h c̲at 0.0 placed ← v + 4 3 r̲eshape at t ← "mesh = bpy.data.meshes.new(\"ground\")\nmesh.from_pydata(" c̲at ((placed, 3) ʰn̲ums 0) c̲at ", [], [(0, 1, 2, 3)])\nmesh.update()\n" t c̲at "link(bpy.data.objects.new(\"ground\", mesh), material(\"ground\", " c̲at (ʰt̲uple rgb) c̲at "))\n\n" }
Pieces of parts
ˡp̲iece : Char -> Char
bp:p_iece name: Python starting a piece: an empty named NAME; the parts after it hang from it (until the next piece)
ˡp̲iece ← { name → "pc = piece(" c̲at (ʰq̲uote name) c̲at ")\ntop = pc\n" }
ˡg̲roup : Any c => (Char, a, b) -> c -> Char
(name, at, turn) bp:g_roup 0: Python starting a group in the piece (or the group before it): an empty named NAME at at (x y z), turned (x y z degrees), that the parts after it hang from -- their places are from its middle -- until bp:ungroup. A group turns and moves as one in a clip: a crossbow about its own pivot, a banner, a turret.
ˡg̲roup ← { (name, at, turn) z → "pc = group(" c̲at (ʰq̲uote name) c̲at ", pc, " c̲at (ʰt̲uple at) c̲at ", " c̲at (ʰt̲uple turn) c̲at ")\n" }
ˡungroup : Char
bp:ungroup: Python ending the groups: the parts after it hang from the piece again
ˡungroup ← "pc = top\n"
ʰa̲ttach : (Char, a, b, c, d) -> Char
ʰa̲ttach ← { (name, at, turn, rgb, emit) → "attach(o, pc, material(" c̲at (ʰq̲uote name) c̲at ", " c̲at (ʰt̲uple rgb) c̲at ", " c̲at (f̲ormat emit) c̲at "), " c̲at (ʰt̲uple at) c̲at ", " c̲at (ʰt̲uple turn) c̲at ")\n" }
ˡb̲ox : Any f => (Char, a, b, c, d, e) -> f -> Char
(name, at, size, turn, rgb, emit) bp:b_ox 0: a box size wide, deep and tall (x y z), its middle at at
ˡb̲ox ← { (name, at, size, turn, rgb, emit) z → "bpy.ops.mesh.primitive_cube_add(size=1.0)\no = made(" c̲at (ʰq̲uote name) c̲at ")\no.scale = " c̲at (ʰt̲uple size) c̲at "\n" c̲at ʰa̲ttach (name, at, turn, rgb, emit) }
ˡc̲ylinder : Any f => (Char, a, b, c, d, e) -> f -> Char
(name, at, size, turn, rgb, emit) bp:c_ylinder 0: a 12-sided cylinder, size its radius across x and y and its height (r r h), its middle at at
ˡc̲ylinder ← { (name, at, size, turn, rgb, emit) z → "bpy.ops.mesh.primitive_cylinder_add(vertices=12, radius=1.0, depth=1.0)\no = made(" c̲at (ʰq̲uote name) c̲at ")\no.scale = " c̲at (ʰt̲uple size) c̲at "\n" c̲at ʰa̲ttach (name, at, turn, rgb, emit) }
ˡc̲one : Any f => (Char, a, b, c, d, e) -> f -> Char
(name, at, size, turn, rgb, emit) bp:c_one 0: a 12-sided cone (or frustum), size its bottom radius, top radius and height, its middle at at
ˡc̲one ← { (name, at, size, turn, rgb, emit) z → "bpy.ops.mesh.primitive_cone_add(vertices=12, radius1=" c̲at (f̲ormat 1 s̲elect size) c̲at ", radius2=" c̲at (f̲ormat 2 s̲elect size) c̲at ", depth=" c̲at (f̲ormat 3 s̲elect size) c̲at ")\no = made(" c̲at (ʰq̲uote name) c̲at ")\n" c̲at ʰa̲ttach (name, at, turn, rgb, emit) }
ˡs̲phere : Any f => (Char, a, b, c, d, e) -> f -> Char
(name, at, size, turn, rgb, emit) bp:s_phere 0: a sphere of 12 segments and 8 rings, size its radii along x y z, its middle at at
ˡs̲phere ← { (name, at, size, turn, rgb, emit) z → "bpy.ops.mesh.primitive_uv_sphere_add(segments=12, ring_count=8, radius=1.0)\no = made(" c̲at (ʰq̲uote name) c̲at ")\no.scale = " c̲at (ʰt̲uple size) c̲at "\n" c̲at ʰa̲ttach (name, at, turn, rgb, emit) }
ˡt̲orus : Any f => (Char, a, b, c, d, e) -> f -> Char
(name, at, size, turn, rgb, emit) bp:t_orus 0: a ring, size its radius and its tube's radius (R r), lying flat, its middle at at
ˡt̲orus ← { (name, at, size, turn, rgb, emit) z → "bpy.ops.mesh.primitive_torus_add(major_segments=16, minor_segments=8, major_radius=" c̲at (f̲ormat 1 s̲elect size) c̲at ", minor_radius=" c̲at (f̲ormat 2 s̲elect size) c̲at ")\no = made(" c̲at (ʰq̲uote name) c̲at ")\n" c̲at ʰa̲ttach (name, at, turn, rgb, emit) }
ˡo̲ctahedronMesh : (Any a, Num b) => Float -> a -> (Float, b)
size bp:o_ctahedronMesh 0: the 6 corners (6 by 3) and 8 faces (8 by 3, from 0, counterclockwise from outside) of an octahedron reaching size (x y z) from its middle each way: a crystal
"bp:" u̲se< "Bpy"
(v, f) ← 1.0 1.0 2.0 ᵇᵖo̲ctahedronMesh 0
(s̲hape v) c̲at s̲hape f 6 3 8 3
ˡo̲ctahedronMesh ← { size z → v ← (6 3 r̲eshape 1.0 0.0 0.0 -1.0 0.0 0.0 0.0 1.0 0.0 0.0 -1.0 0.0 0.0 0.0 1.0 0.0 0.0 -1.0) × 6 3 r̲eshape size f ← 8 3 r̲eshape 0 2 4 2 1 4 1 3 4 3 0 4 2 0 5 1 2 5 3 1 5 0 3 5 (v, f) }
ˡo̲ctahedron : Any e => (Char, a, Float, b, c, d) -> e -> Char
(name, at, size, turn, rgb, emit) bp:o_ctahedron 0: an octahedron (a crystal), its corners worked out in X_eTaL, size its reach each way
ˡo̲ctahedron ← { (name, at, size, turn, rgb, emit) z → (v, f) ← size ˡo̲ctahedronMesh 0 "o = mesh_object(" c̲at (ʰq̲uote name) c̲at ", " c̲at (((f̲loat v), 3) ʰn̲ums 0) c̲at ", [tuple(int(i) for i in f) for f in " c̲at ((f, 3) ʰn̲ums 0) c̲at "])\n" c̲at ʰa̲ttach (name, at, turn, rgb, emit) }
ˡm̲esh : (Num b, Any g) => (Char, a, b, c, d, e, f) -> g -> Char
(name, at, corners, faces, turn, rgb, emit) bp:m_esh 0: a part of any shape: the corners (n by 3, about its middle) and faces (each a row of corner numbers from 0, all rows as long), made to face outward -- a wedge, a plate
ˡm̲esh ← { (name, at, v, f, turn, rgb, emit) z → k ← 2 s̲elect s̲hape f "o = mesh_object(" c̲at (ʰq̲uote name) c̲at ", " c̲at (((f̲loat v), 3) ʰn̲ums 0) c̲at ", [tuple(int(i) for i in f) for f in " c̲at ((f, k) ʰn̲ums 0) c̲at "])\n" c̲at ʰa̲ttach (name, at, turn, rgb, emit) }
ˡl̲atheMesh : Any a => (Float, Int) -> a -> (Float, Int)
(profile, segments) bp:l_atheMesh 0: a profile turned round the z axis: the profile is points (r z), bottom to top, each a radius and a height; the corners (segments times points, by 3) and the faces (quads, from 0, outward), worked out as arrays
"bp:" u̲se< "Bpy"
(v, f) ← (3 2 r̲eshape 0.0 0.0 1.0 0.5 0.0 1.0, 8) ᵇᵖl̲atheMesh 0
(s̲hape v) c̲at s̲hape f 24 3 16 4
ˡl̲atheMesh ← { (prof, seg) z → r ← 1 s̲elect₂ prof hz ← 2 s̲elect₂ prof m ← t̲ally r a ← (2.0 × 3.141592653589793 ÷ f̲loat seg) × f̲loat (r̲ange seg) − 1 v ← 2 1 t̲ranspose (3 c̲at seg × m) r̲eshape (r̲avel (c̲os a) '× t̲able r) c̲at (r̲avel (s̲in a) '× t̲able r) c̲at r̲avel (seg r̲eshape 0.0) '+ t̲able hz j ← (r̲ange seg) − 1 i ← (r̲ange m − 1) − 1 a0 ← r̲avel (m × j) '+ t̲able i a1 ← r̲avel (m × (j + 1) m̲od seg) '+ t̲able i k ← t̲ally a0 (v, 2 1 t̲ranspose (4 c̲at k) r̲eshape a0 c̲at a1 c̲at (a1 + 1) c̲at a0 + 1) }
ˡl̲athe : Any e => (Char, a, Float, Int, b, c, d) -> e -> Char
(name, at, profile, segments, turn, rgb, emit) bp:l_athe 0: a solid turned from a profile (points r z, bottom to top) round its upright axis, at at: a dome, a pedestal, a barrel
ˡl̲athe ← { (name, at, prof, seg, turn, rgb, emit) z → (v, f) ← (prof, seg) ˡl̲atheMesh 0 "o = mesh_object(" c̲at (ʰq̲uote name) c̲at ", " c̲at (((f̲loat v), 3) ʰn̲ums 0) c̲at ", [tuple(int(i) for i in f) for f in " c̲at ((f, 4) ʰn̲ums 0) c̲at "])\n" c̲at ʰa̲ttach (name, at, turn, rgb, emit) }
Clips
ˡk̲eys : (Num b, Any c) => (Char, Char, Char, a, b) -> c -> Char
(part, clip, what, times, values) bp:k_eys 0: Python keying the part (or piece) PART in the clip CLIP: what is "location", "rotation" (x y z degrees) or "scale", times are seconds from the clip's start, values one row of x y z for each time. The part is left as it was: a clip does not move its rest.
ˡk̲eys ← { (part, clip, what, times, values) z → path ← (what m̲atch "rotation") ʰp̲ath what "keys(" c̲at (ʰq̲uote part) c̲at ", " c̲at (ʰq̲uote clip) c̲at ", " c̲at (ʰq̲uote path) c̲at ", " c̲at (ʰt̲uple times) c̲at ", " c̲at (((f̲loat values), 3) ʰn̲ums 0) c̲at ")\n" }
ʰp̲ath : Truthy a => a -> Char -> Char
ʰp̲ath ← { r what → r ? "rotation_euler" what }
ˡc̲lips : Char -> Char
bp:c_lips name: Python reading back out/NAME.glb and writing its clips to out/NAME-clips.txt, a line each: the name, the first and last key in seconds, and what it moves (part and translation, rotation or scale) -- what a test checks
ˡc̲lips ← { name → "with open(os.path.join(out, " c̲at (ʰq̲uote name c̲at "-clips.txt") c̲at "), \"w\") as f:\n f.write(\"\".join(c + \"\\n\" for c in glb_clips(os.path.join(out, " c̲at (ʰq̲uote name c̲at ".glb") c̲at "))))\n" }
ˡe̲xportPiece : Char -> Char
bp:e_xportPiece name: Python writing the piece NAME (and its parts) as out/NAME.glb, its animations with it
ˡe̲xportPiece ← { name → "export_piece(bpy.data.objects[" c̲at (ʰq̲uote name) c̲at "], os.path.join(out, " c̲at (ʰq̲uote name c̲at ".glb") c̲at "))\n" }
ˡm̲eshToml : Any b => (Char, a) -> b -> Char
(name, most) bp:m_eshToml 0: Python writing the piece NAME at rest (its clips muted) as out/NAME-mesh.toml, a low-poly mesh for a renderer that reads TOML: top-level lists of strings -- vertices ("x y z" in meters, Z up, about the piece's origin), faces (three vertex numbers, from 1) and colors (a face's "#rrggbb", sRGB, its part's color) -- and its name and triangles; a piece of more than MOST triangles is decimated (collapsed) to about that many first
"bp:" u̲se< "Bpy"
("tower", 500) ᵇᵖm̲eshToml 0 mesh_toml(bpy.data.objects["tower"], os.path.join(out, "tower-mesh.toml"), 500)
ˡm̲eshToml ← { (name, most) z → "mesh_toml(bpy.data.objects[" c̲at (ʰq̲uote name) c̲at "], os.path.join(out, " c̲at (ʰq̲uote name c̲at "-mesh.toml") c̲at "), " c̲at (f̲ormat most) c̲at ")\n" }
The look: textures and bevels
ˡt̲exture : Any f => (Char, Char, a, b, c, d, e) -> f -> Char
(name, kind, rgb, rgb2, meters, pixels, maps) bp:t_exture 0: Python making the texture NAME: kind is "stone" (4 courses of 2 blocks, the joints rgb2), "wood" (4 planks along x, the grain rgb2), "weave" (16 threads each way, rgb2 between them), "grass", "thatch" (3 layers of reeds) or "snow"; rgb and rgb2 its two colors (red green blue, 0 to 1); meters how wide the square is that the pattern repeats over; pixels the images' side (128 to 512); maps 1 for the base color alone, 2 with roughness, 3 with roughness and normals. The images are also written to out/textures/ (PNG).
"bp:" u̲se< "Bpy"
("wall", "stone", 0.6 0.63 0.67, 0.3 0.3 0.32, 1.0, 256, 3) ᵇᵖt̲exture 0 texture("wall", "stone", nums("0.6 0.63 0.67", 3)[0], nums("0.3 0.3 0.32", 3)[0], 1.0, 256, 3)
ˡt̲exture ← { (name, kind, rgb, rgb2, meters, pixels, maps) z → "texture(" c̲at (ʰq̲uote name) c̲at ", " c̲at (ʰq̲uote kind) c̲at ", " c̲at (ʰt̲uple rgb) c̲at ", " c̲at (ʰt̲uple rgb2) c̲at ", " c̲at (f̲ormat meters) c̲at ", " c̲at (f̲ormat pixels) c̲at ", " c̲at (f̲ormat maps) c̲at ")\n" }
ˡb̲evel : Any c => (Char, a, b) -> c -> Char
(part, width, segments) bp:b_evel 0: Python beveling the part PART (a box, or any part: its edges sharper than 40 degrees): width the bevel's width in meters, segments how many faces round each edge (1 a chamfer); the part is then shaded smooth, its large faces kept flat. Bevel a part before painting it.
"bp:" u̲se< "Bpy"
("wall block", 0.03, 2) ᵇᵖb̲evel 0 bevel("wall block", 0.03, 2)
ˡb̲evel ← { (part, width, segments) z → "bevel(" c̲at (ʰq̲uote part) c̲at ", " c̲at (f̲ormat width) c̲at ", " c̲at (f̲ormat segments) c̲at ")\n" }
ˡp̲aint : Any b => (Char, Char, a) -> b -> Char
(part, texture, turn) bp:p_aint 0: Python giving the part PART the texture TEXTURE in place of its color, laid on each face along the part's own axes at the texture's meters (a face toward x shows y and z, toward y x and z, toward z x and y: courses and planks run along x); turn 0, or 1 to lay it a quarter turn round (planks upright).
"bp:" u̲se< "Bpy"
("wall block", "wall", 0) ᵇᵖp̲aint 0 paint("wall block", "wall", 0)
ˡp̲aint ← { (part, texture, turn) z → "paint(" c̲at (ʰq̲uote part) c̲at ", " c̲at (ʰq̲uote texture) c̲at ", " c̲at (f̲ormat turn) c̲at ")\n" }
The look: figures
ˡa̲rmature : (Num a, Num b, Any d) => (Char, Char, a, b, c) -> d -> Char
(name, bones, heads, tails, parents) bp:a_rmature 0: Python making the armature NAME in the piece (or the group) being made: bones their names in one text, a space between; heads and tails where each bone starts and ends (n by 3, x y z in the piece); parents each bone's parent as its number from 1, 0 for none (a parent comes before its children).
"bp:" u̲se< "Bpy"
("rig", "hip leg", 2 3 r̲eshape 0.0 0.0 0.5 0.0 0.0 0.5, 2 3 r̲eshape 0.0 0.0 0.7 0.0 0.0 0.0, 0 1) ᵇᵖa̲rmature 0 armature("rig", pc, "hip leg".split(), nums("""0.0 0.0 0.5 0.0 0.0 0.5""", 3), nums("""0.0 0.0 0.7 0.0 0.0 0.0""", 3), nums("""0 1""", 1))
ˡa̲rmature ← { (name, bones, heads, tails, parents) z → "armature(" c̲at (ʰq̲uote name) c̲at ", pc, " c̲at (ʰq̲uote bones) c̲at ".split(), " c̲at (((f̲loat heads), 3) ʰn̲ums 0) c̲at ", " c̲at (((f̲loat tails), 3) ʰn̲ums 0) c̲at ", " c̲at ((parents, 1) ʰn̲ums 0) c̲at ")\n" }
ˡb̲ind : Any b => (Char, Char, Char, a) -> b -> Char
(part, rig, bones, reach) bp:b_ind 0: Python skinning the part PART to the armature RIG: bones the names (one text, a space between) of the bones that move it -- one name binds it rigidly; with several, each corner follows the nearest bone and shares with the others within reach meters more (0: the nearest alone). The part then hangs from the armature where it was: key its bones, not the part.
"bp:" u̲se< "Bpy"
("leg", "rig", "thigh shin", 0.08) ᵇᵖb̲ind 0 bind("leg", "rig", "thigh shin".split(), 0.08)
ˡb̲ind ← { (part, rig, bones, reach) z → "bind(" c̲at (ʰq̲uote part) c̲at ", " c̲at (ʰq̲uote rig) c̲at ", " c̲at (ʰq̲uote bones) c̲at ".split(), " c̲at (f̲ormat reach) c̲at ")\n" }
ˡp̲ose : (Num b, Any c) => (Char, Char, Char, Char, a, b) -> c -> Char
(rig, bone, clip, what, times, values) bp:p_ose 0: Python keying the bone BONE of the armature RIG in the clip CLIP: what is "rotation" (x y z degrees about the piece's axes, at the bone's head, from its rest; keys less than half a turn apart), "location" (x y z meters from its rest, along the piece's axes) or "scale"; times are seconds from the clip's start, values one row of x y z for each time. A bone's keys carry its children. The rest is left as it was.
"bp:" u̲se< "Bpy"
("rig", "leg", "walk", "rotation", 0.0 0.5 1.0, 3 3 r̲eshape 0.0 0.0 0.0 30.0 0.0 0.0 0.0 0.0 0.0) ᵇᵖp̲ose 0 pose_keys("rig", "leg", "walk", "rotation", nums("0.0 0.5 1.0", 3)[0], nums("""0.0 0.0 0.0 30.0 0.0 0.0 0.0 0.0 0.0""", 3))
ˡp̲ose ← { (rig, bone, clip, what, times, values) z → "pose_keys(" c̲at (ʰq̲uote rig) c̲at ", " c̲at (ʰq̲uote bone) c̲at ", " c̲at (ʰq̲uote clip) c̲at ", " c̲at (ʰq̲uote what) c̲at ", " c̲at (ʰt̲uple times) c̲at ", " c̲at (((f̲loat values), 3) ʰn̲ums 0) c̲at ")\n" }
The look: cloth
ˡg̲ridMesh : Any a => (Float, Int) -> a -> (Float, Int)
(size, cuts) bp:g_ridMesh 0: an upright sheet, size wide and tall (x z), about its middle, cut into cuts squares (across, down): the corners ((across + 1) times (down + 1), by 3: row by row from the top, each from -x to +x, so the top row is corners 0 to across) and the faces (quads, from 0), worked out as arrays
"bp:" u̲se< "Bpy"
(v, f) ← (0.9 0.6, 3 2) ᵇᵖg̲ridMesh 0
(s̲hape v) c̲at s̲hape f 12 3 6 4
ˡg̲ridMesh ← { (size, cuts) z → nx ← 1 s̲elect cuts ny ← 2 s̲elect cuts w ← 1 s̲elect size h ← 2 s̲elect size xs ← (w × (f̲loat (r̲ange nx + 1) − 1) ÷ f̲loat nx) − w ÷ 2.0 zs ← (h ÷ 2.0) − h × (f̲loat (r̲ange ny + 1) − 1) ÷ f̲loat ny n ← (nx + 1) × ny + 1 v ← 2 1 t̲ranspose (3 c̲at n) r̲eshape (n r̲eshape xs) c̲at (n r̲eshape 0.0) c̲at r̲avel zs '+ t̲able (nx + 1) r̲eshape 0.0 a ← r̲avel ((nx + 1) × (r̲ange ny) − 1) '+ t̲able (r̲ange nx) − 1 (v, 2 1 t̲ranspose (4 c̲at t̲ally a) r̲eshape a c̲at (a + nx + 1) c̲at (a + nx + 2) c̲at a + 1) }
ˡc̲loth : Any e => (Char, a, Float, Int, b, c, d) -> e -> Char
(name, at, size, cuts, turn, rgb, emit) bp:c_loth 0: a part that is an upright sheet (bp:g_ridMesh: size wide and tall, cuts squares across and down), its middle at at: a banner, a flag, a tent flap, still until bp:w_ave moves it
ˡc̲loth ← { (name, at, size, cuts, turn, rgb, emit) z → (v, f) ← (size, cuts) ˡg̲ridMesh 0 "o = mesh_object(" c̲at (ʰq̲uote name) c̲at ", " c̲at ((v, 3) ʰn̲ums 0) c̲at ", [tuple(int(i) for i in f) for f in " c̲at ((f, 4) ʰn̲ums 0) c̲at "])\n" c̲at ʰa̲ttach (name, at, turn, rgb, emit) }
ˡw̲ave : Any e => (Char, Char, a, b, c, d) -> e -> Char
(part, clip, pins, wind, seconds, shapes) bp:w_ave 0: Python simulating the part PART as cloth and keeping it as the clip CLIP: pins the numbers (from 0) of the corners held still; wind where it blows and how hard (x y z, meters a second, with gusts); seconds the clip's length, a loop (the simulation runs 2 s first, then the clip's length and half again, its end faded into its start); shapes how many shapes the loop is kept as (the rest shape is the first; each of the others is a morph target, 12 bytes a corner, and as much again for its normals). Paint the part before waving it; times fall on frames (30 a second).
"bp:" u̲se< "Bpy"
("flag", "wave", 0 4 8, 3.0 0.5 0.0, 2.0, 8) ᵇᵖw̲ave 0 wave("flag", "wave", nums("0 4 8", 3)[0], nums("3.0 0.5 0.0", 3)[0], 2.0, 8)
ˡw̲ave ← { (part, clip, pins, wind, seconds, shapes) z → "wave(" c̲at (ʰq̲uote part) c̲at ", " c̲at (ʰq̲uote clip) c̲at ", " c̲at (ʰt̲uple pins) c̲at ", " c̲at (ʰt̲uple wind) c̲at ", " c̲at (f̲ormat seconds) c̲at ", " c̲at (f̲ormat shapes) c̲at ")\n" }
The look: files
ˡe̲xportLook : Any b => (Char, a) -> b -> Char
(name, quality) bp:e_xportLook 0: Python writing the piece NAME as out/NAME.glb as bp:e_xportPiece does -- its clips, its skin, its shapes -- with its textures as JPEG of that quality (1 to 100; 0 keeps them PNG, larger and exact)
"bp:" u̲se< "Bpy"
("wall", 85) ᵇᵖe̲xportLook 0 export_look(bpy.data.objects["wall"], os.path.join(out, "wall.glb"), 85)
ˡe̲xportLook ← { (name, quality) z → "export_look(bpy.data.objects[" c̲at (ʰq̲uote name) c̲at "], os.path.join(out, " c̲at (ʰq̲uote name c̲at ".glb") c̲at "), " c̲at (f̲ormat quality) c̲at ")\n" }
ˡc̲ontents : Char -> Char
bp:c_ontents name: Python reading back out/NAME.glb and writing what it holds to out/NAME-contents.txt, a line each: the file's bytes (and without its textures), each texture (its kind, pixels and bytes), each textured material's images, each skin's bones, each mesh's corners (skinned? how many shapes?), then its clips as bp:c_lips writes them -- what a test checks
ˡc̲ontents ← { name → "with open(os.path.join(out, " c̲at (ʰq̲uote name c̲at "-contents.txt") c̲at "), \"w\") as f:\n f.write(\"\".join(c + \"\\n\" for c in glb_look(os.path.join(out, " c̲at (ʰq̲uote name c̲at ".glb") c̲at "))))\n" }
Words, light and camera
ˡl̲abel : Any d => (Char, a, b, c) -> d -> Char
(text, place, size, rgb) bp:l_abel 0: Python making 3D text standing upright at place (x y z, its middle bottom), facing -y, that tall
ˡl̲abel ← { (body, at, size, rgb) z → t ← "curve = bpy.data.curves.new(" c̲at (ʰq̲uote "label " c̲at body) c̲at ", type=\"FONT\")\ncurve.body = " c̲at (ʰq̲uote body) c̲at "\ncurve.size = " c̲at (f̲ormat size) c̲at "\ncurve.align_x = \"CENTER\"\ncurve.extrude = 0.04\n" t c̲at "obj = link(bpy.data.objects.new(" c̲at (ʰq̲uote "label " c̲at body) c̲at ", curve), material(" c̲at (ʰq̲uote "label " c̲at body) c̲at ", " c̲at (ʰt̲uple rgb) c̲at "))\nobj.location = " c̲at (ʰt̲uple at) c̲at "\nobj.rotation_euler = (math.pi / 2, 0.0, 0.0)\n\n" }
ˡl̲ights : Any b => (Float, a) -> b -> Char
(sky rgb, sun strength) bp:l_ights 0: Python lighting the scene: the world's color and a sun from above to one side, soft shadows
ˡl̲ights ← { (sky, strength) z → t ← "world = bpy.data.worlds.new(\"world\")\nworld.use_nodes = True\nworld.node_tree.nodes[\"Background\"].inputs[\"Color\"].default_value = " c̲at (ʰt̲uple sky c̲at 1.0) c̲at "\nscene.world = world\n" t c̲at "sun = bpy.data.objects.new(\"sun\", bpy.data.lights.new(\"sun\", type=\"SUN\"))\nsun.data.energy = " c̲at (f̲ormat strength) c̲at "\nsun.data.angle = 0.2\nsun.rotation_euler = (math.radians(50), 0.0, math.radians(30))\nscene.collection.objects.link(sun)\n\n" }
ˡo̲rbit : (Num d, Any e) => (a, b, c, d) -> e -> Char
(center, radius, height, frames) bp:o_rbit 0: Python putting a camera on a circle of that radius about center (x y z), that high above it, looking at it, turned once round in the frames -- a pivot at the center keyed at 0 and a full turn, linear, so the video loops; the labels made before it turn to face the camera, so they always read
ˡo̲rbit ← { (at, radius, height, frames) z → (("pivot = bpy.data.objects.new(\"pivot\", None)\npivot.location = " c̲at (ʰt̲uple at) c̲at "\nscene.collection.objects.link(pivot)\n") c̲at ("cam = bpy.data.objects.new(\"camera\", bpy.data.cameras.new(\"camera\"))\ncam.data.lens = 35\ncam.data.clip_end = 1000\ncam.parent = pivot\ncam.location = (0.0, -" c̲at (f̲ormat radius) c̲at ", " c̲at (f̲ormat height) c̲at ")\nscene.collection.objects.link(cam)\nscene.camera = cam\n") c̲at "look = cam.constraints.new(\"TRACK_TO\")\nlook.target = pivot\nlook.track_axis = \"TRACK_NEGATIVE_Z\"\nlook.up_axis = \"UP_Y\"\n" c̲at "for o in scene.objects:\n if o.name.startswith(\"label \"):\n face = o.constraints.new(\"TRACK_TO\")\n face.target = cam\n face.track_axis = \"TRACK_Z\"\n face.up_axis = \"UP_Y\"\n" c̲at "scene.frame_start = 1\nscene.frame_end = " c̲at (f̲ormat frames) c̲at "\npivot.rotation_euler = (0.0, 0.0, 0.0)\npivot.keyframe_insert(\"rotation_euler\", frame=1)\npivot.rotation_euler = (0.0, 0.0, 2 * math.pi)\npivot.keyframe_insert(\"rotation_euler\", frame=" c̲at (f̲ormat frames + 1) c̲at ")\n\n") }
Rendering and files
ˡs̲etup : Any d => (a, b, c) -> d -> Char
(width, height, fps) bp:s_etup 0: Python setting EEVEE, the picture's size and the frame rate, colors as they are (the Standard view, not the film look) and thin dark outlines on every edge (Freestyle: a line set with a line style made, as an empty scene has none), the look of a drawing
ˡs̲etup ← { (w, h, fps) z → "scene.render.engine = \"BLENDER_EEVEE\"\nscene.view_settings.view_transform = \"Standard\"\nscene.render.use_freestyle = True\nscene.render.line_thickness = 0.8\nlines = bpy.context.view_layer.freestyle_settings.linesets\nlineset = lines[0] if len(lines) else lines.new(\"outlines\")\nif lineset.linestyle is None:\n lineset.linestyle = bpy.data.linestyles.new(\"outlines\")\nlineset.linestyle.color = (0.08, 0.08, 0.1)\nlineset.linestyle.thickness = 1.0\nscene.render.resolution_x = " c̲at (f̲ormat w) c̲at "\nscene.render.resolution_y = " c̲at (f̲ormat h) c̲at "\nscene.render.resolution_percentage = 100\nscene.render.fps = " c̲at (f̲ormat fps) c̲at "\n\n" }
ˡs̲amples : a -> Char
bp:s_amples n: Python setting how many samples EEVEE takes of each pixel (64 by default): fewer render faster and rougher -- a test's tiny frames need one
ˡs̲amples ← { n → "scene.eevee.taa_render_samples = " c̲at (f̲ormat n) c̲at "\n" }
ˡs̲till : Char -> Char
bp:s_till file: Python rendering the current frame to out/FILE (PNG)
ˡs̲till ← { file → "scene.render.image_settings.media_type = \"IMAGE\"\nscene.render.image_settings.file_format = \"PNG\"\nscene.render.filepath = os.path.join(out, " c̲at (ʰq̲uote file) c̲at ")\nbpy.ops.render.render(write_still=True)\n\n" }
ˡv̲ideo : Char -> Char
bp:v_ideo file: Python rendering every frame to out/FILE, an MP4 (H.264)
ˡv̲ideo ← { file → "scene.render.image_settings.media_type = \"VIDEO\"\nscene.render.image_settings.file_format = \"FFMPEG\"\nscene.render.ffmpeg.format = \"MPEG4\"\nscene.render.ffmpeg.codec = \"H264\"\nscene.render.ffmpeg.constant_rate_factor = \"HIGH\"\nscene.render.filepath = os.path.join(out, " c̲at (ʰq̲uote file) c̲at ")\nbpy.ops.render.render(animation=True)\n\n" }
ˡe̲xports : Char -> Char
bp:e_xports name: Python writing the scene as out/NAME.glb (glTF, binary), out/NAME.obj (with its .mtl) and out/NAME.blend
ˡe̲xports ← { name → "bpy.ops.export_scene.gltf(filepath=os.path.join(out, " c̲at (ʰq̲uote name c̲at ".glb") c̲at "), export_format=\"GLB\")\nbpy.ops.wm.obj_export(filepath=os.path.join(out, " c̲at (ʰq̲uote name c̲at ".obj") c̲at "))\nbpy.ops.wm.save_as_mainfile(filepath=os.path.join(out, " c̲at (ʰq̲uote name c̲at ".blend") c̲at "))\n\n" }
ˡreport : Char
bp:report: Python writing out/report.txt: each mesh's vertices and faces, each piece's parts and triangles, and each object, by name -- what a test checks
ˡreport ← "with open(os.path.join(out, \"report.txt\"), \"w\") as f:\n for m in sorted(bpy.data.meshes, key=lambda m: m.name):\n f.write(\"mesh %s: %d vertices, %d faces\\n\" % (m.name, len(m.vertices), len(m.polygons)))\n for o in sorted(scene.objects, key=lambda o: o.name):\n if o.type == \"EMPTY\" and o.parent is None and any(c.type == \"MESH\" for c in o.children_recursive):\n f.write(\"piece %s: %d parts, %d triangles\\n\" % (o.name, sum(c.type == \"MESH\" for c in o.children_recursive), triangles(o)))\n f.write(\"objects: \" + \" \".join(sorted(o.name for o in scene.objects)) + \"\\n\")\n"