sourceextensions/blender/lib/Bpy.xtl
1⍝│ Bpy.xtl -- Blender's Python (bpy) written by X_eTaL: each function
2⍝│ returns a piece of a script as text, and a program joins the pieces
3⍝│ into the script Blender runs inside (written with bl:w_rite!, run by
4⍝│ the launcher bp:launcher through bl:r_un!). The geometry is X_eTaL's:
5⍝│ a set of cubes is worked out as arrays -- every corner, every face --
6⍝│ and written into the script as numbers, one mesh for them all.
7⍝│ Written for Blender 5.1 (EEVEE is BLENDER_EEVEE; video output is
8⍝│ media_type VIDEO).
9⍝│ Import: "bp:" u_se< "Bpy"
10
11⍝━━ The two scripts
12
13⍝│ bp:launcher: the outer script. python3 run.py SCRIPT ARGS runs Blender
14⍝│ (XETAL_BLENDER, set by bl:r_un!) in the background with its factory
15⍝│ settings on SCRIPT, passing ARGS after "--"; a Python error inside
16⍝│ makes the run fail. Audio is disabled; XETAL_BLENDER_ARGS supplies
17⍝│ optional command-line arguments (shell quoting, without a shell),
18⍝│ for example --gpu-backend vulkan on a Linux NVIDIA machine.
19ˡ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"
20
21⍝│ bp:head: the inner script's start: an empty scene, the output
22⍝│ directory (the first argument after "--", made), keyframes linear (an
23⍝│ orbit at an even speed), 30 frames a second (bp:s_etup may change
24⍝│ it), and helpers: nums(text, k) reads numbers
25⍝│ written by X_eTaL k to a row; material, link; piece, made, attach,
26⍝│ mesh_object (outward normals) and group build a piece of parts; keys keys a part into a named
27⍝│ clip, clips makes each clip a track (NLA) so it exports by its name;
28⍝│ export_piece writes one piece as glTF, its clips with it; glb_clips
29⍝│ reads a .glb's clips back; mesh_toml writes a piece as a low-poly
30⍝│ mesh in TOML (bp:m_eshToml); triangles counts a piece's triangles
31ˡ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"
32
33⍝│ bp:look: more of the inner script, joined after bp:head by a program
34⍝│ that uses the look's functions (bp:t_exture to bp:c_ontents): the
35⍝│ procedural textures (stone, wood, weave, grass, thatch, snow: shader
36⍝│ nodes that repeat over a square, baked with Cycles into images, the
37⍝│ normals worked out from the baked height), bevel, paint; armature,
38⍝│ bind, pose_keys; wave (a cloth simulated and kept as shapes);
39⍝│ export_look and glb_look (a .glb's textures, skins, shapes and clips
40⍝│ read back). bp:head is as it was, so a script without the look is
41⍝│ unchanged.
42ˡ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"
43
44⍝━━ Numbers into Python
45
46⍝ (values, k) h:n_ums 0: the values as Python reading them k to a row
47ʰn̲ums ← { (v, k) z → "nums(\"\"\"" c̲at (f̲ormat r̲avel v) c̲at "\"\"\", " c̲at (f̲ormat k) c̲at ")" }
48
49⍝ a Python string
50ʰq̲uote ← { t → "\"" c̲at t c̲at "\"" }
51
52⍝ a Python tuple of the numbers of v (read by nums)
53ʰ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]" }
54
55⍝━━ Cubes
56
57⍝ the 8 corners of a unit cube about its center, -0.5 to 0.5: the bottom
58⍝ four counterclockwise, then the top four
59corners ← 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
60⍝ its 6 faces, the corners of each counterclockwise seen from outside:
61⍝ bottom, top, front (-y), back (+y), left (-x), right (+x)
62sides ← 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
63
64⍝│ (centers, size) bp:c_ubeMesh 0: the corners (8n by 3) and faces (6n
65⍝│ by 4, counting corners from 0) of n cubes of that size at the centers
66⍝│ (n by 3), as one mesh
67⍝│ >> "bp:" u_se< "Bpy"
68⍝│ >> (c, f) := (2 3 r_eshape 0.0 0.0 0.0 2.0 0.0 0.0, 1.0) bp:c_ubeMesh 0
69⍝│ >> (s_hape c) c_at s_hape f
70⍝│ 16 3 12 4
71ˡc̲ubeMesh ← { (cs, size) z →
72 n ← 1 s̲elect s̲hape cs
73 c̲ol ← { k → r̲avel (k s̲elect₂ cs) '+ t̲able size × k s̲elect₂ corners }
74 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
75 f ← ((6 × n) c̲at 4) r̲eshape r̲avel (8 × (r̲ange n) − 1) '+ t̲able r̲avel sides
76 (v, f)
77}
78
79⍝│ (name, centers, size, rgb) bp:c_ubes 0: Python making n cubes of
80⍝│ that size at the centers (n by 3, z up) as one mesh object NAME, with
81⍝│ a material of that color (red green blue, 0 to 1)
82ˡc̲ubes ← { (name, cs, size, rgb) z →
83 (v, f) ← (cs, size) ˡc̲ubeMesh 0
84 (("mesh = bpy.data.meshes.new(" c̲at (ʰq̲uote name) c̲at ")\n") c̲at
85 ("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
86 "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")
87}
88
89⍝│ (center, size, rgb) bp:g_round 0: Python making a flat square ground
90⍝│ that wide at center (x y z, its top), colored: something for shadows
91⍝│ to fall on
92ˡg̲round ← { (at, size, rgb) z →
93 h ← size ÷ 2.0
94 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
95 placed ← v + 4 3 r̲eshape at
96 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"
97 t c̲at "link(bpy.data.objects.new(\"ground\", mesh), material(\"ground\", " c̲at (ʰt̲uple rgb) c̲at "))\n\n"
98}
99
100⍝━━ Pieces of parts
101
102⍝│ A piece is an empty at the middle of its base (the tile's middle, z
103⍝│ 0), and its parts hang from it, so it moves, turns and exports as one.
104⍝│ A part is placed (at, x y z), sized (size: what it means is the
105⍝│ part's own), turned (turn, x y z degrees), colored (rgb) and may glow
106⍝│ (emit, 0 for none). Low-poly throughout: what a game shows small.
107
108⍝│ bp:p_iece name: Python starting a piece: an empty named NAME; the
109⍝│ parts after it hang from it (until the next piece)
110ˡp̲iece ← { name → "pc = piece(" c̲at (ʰq̲uote name) c̲at ")\ntop = pc\n" }
111
112⍝│ (name, at, turn) bp:g_roup 0: Python starting a group in the piece
113⍝│ (or the group before it): an empty named NAME at at (x y z), turned
114⍝│ (x y z degrees), that the parts after it hang from -- their places
115⍝│ are from its middle -- until bp:ungroup. A group turns and moves as
116⍝│ one in a clip: a crossbow about its own pivot, a banner, a turret.
117ˡ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" }
118
119⍝│ bp:ungroup: Python ending the groups: the parts after it hang from
120⍝│ the piece again
121ˡungroup ← "pc = top\n"
122
123⍝ the end of every part: hung from the piece, placed, turned, colored
124ʰa̲ttach ← { (name, at, turn, rgb, emit) →
125 "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"
126}
127
128⍝│ (name, at, size, turn, rgb, emit) bp:b_ox 0: a box size wide, deep
129⍝│ and tall (x y z), its middle at at
130ˡb̲ox ← { (name, at, size, turn, rgb, emit) z →
131 "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)
132}
133
134⍝│ (name, at, size, turn, rgb, emit) bp:c_ylinder 0: a 12-sided cylinder,
135⍝│ size its radius across x and y and its height (r r h), its middle at
136⍝│ at
137ˡc̲ylinder ← { (name, at, size, turn, rgb, emit) z →
138 "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)
139}
140
141⍝│ (name, at, size, turn, rgb, emit) bp:c_one 0: a 12-sided cone (or
142⍝│ frustum), size its bottom radius, top radius and height, its middle
143⍝│ at at
144ˡc̲one ← { (name, at, size, turn, rgb, emit) z →
145 "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)
146}
147
148⍝│ (name, at, size, turn, rgb, emit) bp:s_phere 0: a sphere of 12
149⍝│ segments and 8 rings, size its radii along x y z, its middle at at
150ˡs̲phere ← { (name, at, size, turn, rgb, emit) z →
151 "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)
152}
153
154⍝│ (name, at, size, turn, rgb, emit) bp:t_orus 0: a ring, size its
155⍝│ radius and its tube's radius (R r), lying flat, its middle at at
156ˡt̲orus ← { (name, at, size, turn, rgb, emit) z →
157 "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)
158}
159
160⍝│ size bp:o_ctahedronMesh 0: the 6 corners (6 by 3) and 8 faces (8 by
161⍝│ 3, from 0, counterclockwise from outside) of an octahedron reaching
162⍝│ size (x y z) from its middle each way: a crystal
163⍝│ >> "bp:" u_se< "Bpy"
164⍝│ >> (v, f) := 1.0 1.0 2.0 bp:o_ctahedronMesh 0
165⍝│ >> (s_hape v) c_at s_hape f
166⍝│ 6 3 8 3
167ˡo̲ctahedronMesh ← { size z →
168 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
169 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
170 (v, f)
171}
172
173⍝│ (name, at, size, turn, rgb, emit) bp:o_ctahedron 0: an octahedron (a
174⍝│ crystal), its corners worked out in X_eTaL, size its reach each way
175ˡo̲ctahedron ← { (name, at, size, turn, rgb, emit) z →
176 (v, f) ← size ˡo̲ctahedronMesh 0
177 "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)
178}
179
180⍝│ (name, at, corners, faces, turn, rgb, emit) bp:m_esh 0: a part of
181⍝│ any shape: the corners (n by 3, about its middle) and faces (each a
182⍝│ row of corner numbers from 0, all rows as long), made to face
183⍝│ outward -- a wedge, a plate
184ˡm̲esh ← { (name, at, v, f, turn, rgb, emit) z →
185 k ← 2 s̲elect s̲hape f
186 "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)
187}
188
189⍝│ (profile, segments) bp:l_atheMesh 0: a profile turned round the z
190⍝│ axis: the profile is points (r z), bottom to top, each a radius and
191⍝│ a height; the corners (segments times points, by 3) and the faces
192⍝│ (quads, from 0, outward), worked out as arrays
193⍝│ >> "bp:" u_se< "Bpy"
194⍝│ >> (v, f) := (3 2 r_eshape 0.0 0.0 1.0 0.5 0.0 1.0, 8) bp:l_atheMesh 0
195⍝│ >> (s_hape v) c_at s_hape f
196⍝│ 24 3 16 4
197ˡl̲atheMesh ← { (prof, seg) z →
198 r ← 1 s̲elect₂ prof
199 hz ← 2 s̲elect₂ prof
200 m ← t̲ally r
201 a ← (2.0 × 3.141592653589793 ÷ f̲loat seg) × f̲loat (r̲ange seg) − 1
202 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
203 j ← (r̲ange seg) − 1
204 i ← (r̲ange m − 1) − 1
205 a0 ← r̲avel (m × j) '+ t̲able i
206 a1 ← r̲avel (m × (j + 1) m̲od seg) '+ t̲able i
207 k ← t̲ally a0
208 (v, 2 1 t̲ranspose (4 c̲at k) r̲eshape a0 c̲at a1 c̲at (a1 + 1) c̲at a0 + 1)
209}
210
211⍝│ (name, at, profile, segments, turn, rgb, emit) bp:l_athe 0: a solid
212⍝│ turned from a profile (points r z, bottom to top) round its upright
213⍝│ axis, at at: a dome, a pedestal, a barrel
214ˡl̲athe ← { (name, at, prof, seg, turn, rgb, emit) z →
215 (v, f) ← (prof, seg) ˡl̲atheMesh 0
216 "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)
217}
218
219⍝━━ Clips
220
221⍝│ A clip is a named animation of a piece -- idle, walk, fire, hit --
222⍝│ that a game plays by its name. Each part keyed in a clip gets an
223⍝│ action of its own; when the piece is exported each action becomes a
224⍝│ track named for its clip (NLA), and the glTF file has one animation
225⍝│ for each name, made of every part's keys under it. Keys are linear;
226⍝│ a loop ends where it starts. Part names must be unique in a script.
227⍝│ A key lands on a frame (the exporter samples frames): at 30 a second,
228⍝│ the head's, a tenth of a second is 3 frames, so give bp:s_etup a rate
229⍝│ that makes the times whole frames, before the keys.
230
231⍝│ (part, clip, what, times, values) bp:k_eys 0: Python keying the part
232⍝│ (or piece) PART in the clip CLIP: what is "location", "rotation" (x y
233⍝│ z degrees) or "scale", times are seconds from the clip's start, values
234⍝│ one row of x y z for each time. The part is left as it was: a clip
235⍝│ does not move its rest.
236ˡk̲eys ← { (part, clip, what, times, values) z →
237 path ← (what m̲atch "rotation") ʰp̲ath what
238 "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"
239}
240
241⍝ bpy's name for what is keyed: rotation is rotation_euler
242ʰp̲ath ← { r what →
243 r ? "rotation_euler"
244 what
245}
246
247⍝│ bp:c_lips name: Python reading back out/NAME.glb and writing its clips
248⍝│ to out/NAME-clips.txt, a line each: the name, the first and last key
249⍝│ in seconds, and what it moves (part and translation, rotation or
250⍝│ scale) -- what a test checks
251ˡ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" }
252
253⍝│ bp:e_xportPiece name: Python writing the piece NAME (and its parts) as
254⍝│ out/NAME.glb, its animations with it
255ˡ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" }
256
257⍝│ (name, most) bp:m_eshToml 0: Python writing the piece NAME at rest
258⍝│ (its clips muted) as out/NAME-mesh.toml, a low-poly mesh for a
259⍝│ renderer that reads TOML: top-level lists of strings -- vertices
260⍝│ ("x y z" in meters, Z up, about the piece's origin), faces (three
261⍝│ vertex numbers, from 1) and colors (a face's "#rrggbb", sRGB, its
262⍝│ part's color) -- and its name and triangles; a piece of more than
263⍝│ MOST triangles is decimated (collapsed) to about that many first
264⍝│ >> "bp:" u_se< "Bpy"
265⍝│ >> ("tower", 500) bp:m_eshToml 0
266⍝│ mesh_toml(bpy.data.objects["tower"], os.path.join(out, "tower-mesh.toml"), 500)
267ˡ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" }
268
269⍝━━ The look: textures and bevels
270
271⍝│ A texture is a named material made once and shared by every part
272⍝│ painted with it: a procedural pattern of Blender's shader nodes that
273⍝│ repeats over a square METERS wide, baked into images PIXELS square
274⍝│ (base color; roughness and normal too, by maps) that the exported
275⍝│ .glb carries, each image once however many parts use it. A script
276⍝│ that uses these joins bp:look after bp:head.
277
278⍝│ (name, kind, rgb, rgb2, meters, pixels, maps) bp:t_exture 0: Python
279⍝│ making the texture NAME: kind is "stone" (4 courses of 2 blocks, the
280⍝│ joints rgb2), "wood" (4 planks along x, the grain rgb2), "weave" (16
281⍝│ threads each way, rgb2 between them), "grass", "thatch" (3 layers of
282⍝│ reeds) or "snow"; rgb and rgb2 its two colors (red green blue, 0 to
283⍝│ 1); meters how wide the square is that the pattern repeats over;
284⍝│ pixels the images' side (128 to 512); maps 1 for the base color
285⍝│ alone, 2 with roughness, 3 with roughness and normals. The images are
286⍝│ also written to out/textures/ (PNG).
287⍝│ >> "bp:" u_se< "Bpy"
288⍝│ >> ("wall", "stone", 0.6 0.63 0.67, 0.3 0.3 0.32, 1.0, 256, 3) bp:t_exture 0
289⍝│ 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)
290ˡt̲exture ← { (name, kind, rgb, rgb2, meters, pixels, maps) z →
291 "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"
292}
293
294⍝│ (part, width, segments) bp:b_evel 0: Python beveling the part PART (a
295⍝│ box, or any part: its edges sharper than 40 degrees): width the
296⍝│ bevel's width in meters, segments how many faces round each edge (1 a
297⍝│ chamfer); the part is then shaded smooth, its large faces kept flat.
298⍝│ Bevel a part before painting it.
299⍝│ >> "bp:" u_se< "Bpy"
300⍝│ >> ("wall block", 0.03, 2) bp:b_evel 0
301⍝│ bevel("wall block", 0.03, 2)
302ˡ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" }
303
304⍝│ (part, texture, turn) bp:p_aint 0: Python giving the part PART the
305⍝│ texture TEXTURE in place of its color, laid on each face along the
306⍝│ part's own axes at the texture's meters (a face toward x shows y and
307⍝│ z, toward y x and z, toward z x and y: courses and planks run along
308⍝│ x); turn 0, or 1 to lay it a quarter turn round (planks upright).
309⍝│ >> "bp:" u_se< "Bpy"
310⍝│ >> ("wall block", "wall", 0) bp:p_aint 0
311⍝│ paint("wall block", "wall", 0)
312ˡ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" }
313
314⍝━━ The look: figures
315
316⍝│ A figure is parts skinned to an armature: bones given as arrays, each
317⍝│ part bound to one bone (rigid) or shared between several (smooth),
318⍝│ and clips keyed on the bones. The exported .glb has a skin and each
319⍝│ clip as an animation of the bones' nodes, played by name. A script
320⍝│ that uses these joins bp:look after bp:head.
321
322⍝│ (name, bones, heads, tails, parents) bp:a_rmature 0: Python making
323⍝│ the armature NAME in the piece (or the group) being made: bones their
324⍝│ names in one text, a space between; heads and tails where each bone
325⍝│ starts and ends (n by 3, x y z in the piece); parents each bone's
326⍝│ parent as its number from 1, 0 for none (a parent comes before its
327⍝│ children).
328⍝│ >> "bp:" u_se< "Bpy"
329⍝│ >> ("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) bp:a_rmature 0
330⍝│ 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))
331ˡa̲rmature ← { (name, bones, heads, tails, parents) z →
332 "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"
333}
334
335⍝│ (part, rig, bones, reach) bp:b_ind 0: Python skinning the part PART
336⍝│ to the armature RIG: bones the names (one text, a space between) of
337⍝│ the bones that move it -- one name binds it rigidly; with several,
338⍝│ each corner follows the nearest bone and shares with the others
339⍝│ within reach meters more (0: the nearest alone). The part then hangs
340⍝│ from the armature where it was: key its bones, not the part.
341⍝│ >> "bp:" u_se< "Bpy"
342⍝│ >> ("leg", "rig", "thigh shin", 0.08) bp:b_ind 0
343⍝│ bind("leg", "rig", "thigh shin".split(), 0.08)
344ˡ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" }
345
346⍝│ (rig, bone, clip, what, times, values) bp:p_ose 0: Python keying the
347⍝│ bone BONE of the armature RIG in the clip CLIP: what is "rotation" (x
348⍝│ y z degrees about the piece's axes, at the bone's head, from its
349⍝│ rest; keys less than half a turn apart), "location" (x y z meters
350⍝│ from its rest, along the piece's axes) or "scale"; times are seconds
351⍝│ from the clip's start, values one row of x y z for each time. A
352⍝│ bone's keys carry its children. The rest is left as it was.
353⍝│ >> "bp:" u_se< "Bpy"
354⍝│ >> ("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) bp:p_ose 0
355⍝│ 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))
356ˡp̲ose ← { (rig, bone, clip, what, times, values) z →
357 "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"
358}
359
360⍝━━ The look: cloth
361
362⍝│ A cloth is a sheet of squares, some corners pinned, that Blender
363⍝│ simulates in a wind; the loop it finds is kept as shapes of the mesh
364⍝│ (glTF morph targets) and a clip that passes from each to the next,
365⍝│ so a game plays it by name as any clip. A script that uses these
366⍝│ joins bp:look after bp:head.
367
368⍝│ (size, cuts) bp:g_ridMesh 0: an upright sheet, size wide and tall (x
369⍝│ z), about its middle, cut into cuts squares (across, down): the
370⍝│ corners ((across + 1) times (down + 1), by 3: row by row from the
371⍝│ top, each from -x to +x, so the top row is corners 0 to across) and
372⍝│ the faces (quads, from 0), worked out as arrays
373⍝│ >> "bp:" u_se< "Bpy"
374⍝│ >> (v, f) := (0.9 0.6, 3 2) bp:g_ridMesh 0
375⍝│ >> (s_hape v) c_at s_hape f
376⍝│ 12 3 6 4
377ˡg̲ridMesh ← { (size, cuts) z →
378 nx ← 1 s̲elect cuts
379 ny ← 2 s̲elect cuts
380 w ← 1 s̲elect size
381 h ← 2 s̲elect size
382 xs ← (w × (f̲loat (r̲ange nx + 1) − 1) ÷ f̲loat nx) − w ÷ 2.0
383 zs ← (h ÷ 2.0) − h × (f̲loat (r̲ange ny + 1) − 1) ÷ f̲loat ny
384 n ← (nx + 1) × ny + 1
385 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
386 a ← r̲avel ((nx + 1) × (r̲ange ny) − 1) '+ t̲able (r̲ange nx) − 1
387 (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)
388}
389
390⍝│ (name, at, size, cuts, turn, rgb, emit) bp:c_loth 0: a part that is
391⍝│ an upright sheet (bp:g_ridMesh: size wide and tall, cuts squares
392⍝│ across and down), its middle at at: a banner, a flag, a tent flap,
393⍝│ still until bp:w_ave moves it
394ˡc̲loth ← { (name, at, size, cuts, turn, rgb, emit) z →
395 (v, f) ← (size, cuts) ˡg̲ridMesh 0
396 "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)
397}
398
399⍝│ (part, clip, pins, wind, seconds, shapes) bp:w_ave 0: Python
400⍝│ simulating the part PART as cloth and keeping it as the clip CLIP:
401⍝│ pins the numbers (from 0) of the corners held still; wind where it
402⍝│ blows and how hard (x y z, meters a second, with gusts); seconds the
403⍝│ clip's length, a loop (the simulation runs 2 s first, then the
404⍝│ clip's length and half again, its end faded into its start); shapes
405⍝│ how many shapes the loop is kept as (the rest shape is the first;
406⍝│ each of the others is a morph target, 12 bytes a corner, and as much
407⍝│ again for its normals). Paint the part before waving it; times fall
408⍝│ on frames (30 a second).
409⍝│ >> "bp:" u_se< "Bpy"
410⍝│ >> ("flag", "wave", 0 4 8, 3.0 0.5 0.0, 2.0, 8) bp:w_ave 0
411⍝│ wave("flag", "wave", nums("0 4 8", 3)[0], nums("3.0 0.5 0.0", 3)[0], 2.0, 8)
412ˡw̲ave ← { (part, clip, pins, wind, seconds, shapes) z →
413 "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"
414}
415
416⍝━━ The look: files
417
418⍝│ (name, quality) bp:e_xportLook 0: Python writing the piece NAME as
419⍝│ out/NAME.glb as bp:e_xportPiece does -- its clips, its skin, its
420⍝│ shapes -- with its textures as JPEG of that quality (1 to 100; 0
421⍝│ keeps them PNG, larger and exact)
422⍝│ >> "bp:" u_se< "Bpy"
423⍝│ >> ("wall", 85) bp:e_xportLook 0
424⍝│ export_look(bpy.data.objects["wall"], os.path.join(out, "wall.glb"), 85)
425ˡ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" }
426
427⍝│ bp:c_ontents name: Python reading back out/NAME.glb and writing what
428⍝│ it holds to out/NAME-contents.txt, a line each: the file's bytes
429⍝│ (and without its textures), each texture (its kind, pixels and
430⍝│ bytes), each textured material's images, each skin's bones, each
431⍝│ mesh's corners (skinned? how many shapes?), then its clips as
432⍝│ bp:c_lips writes them -- what a test checks
433ˡ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" }
434
435⍝━━ Words, light and camera
436
437⍝│ (text, place, size, rgb) bp:l_abel 0: Python making 3D text standing
438⍝│ upright at place (x y z, its middle bottom), facing -y, that tall
439ˡl̲abel ← { (body, at, size, rgb) z →
440 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"
441 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"
442}
443
444⍝│ (sky rgb, sun strength) bp:l_ights 0: Python lighting the scene: the
445⍝│ world's color and a sun from above to one side, soft shadows
446ˡl̲ights ← { (sky, strength) z →
447 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"
448 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"
449}
450
451⍝│ (center, radius, height, frames) bp:o_rbit 0: Python putting a camera
452⍝│ on a circle of that radius about center (x y z), that high above it,
453⍝│ looking at it, turned once round in the frames -- a pivot at the
454⍝│ center keyed at 0 and a full turn, linear, so the video loops; the
455⍝│ labels made before it turn to face the camera, so they always read
456ˡo̲rbit ← { (at, radius, height, frames) z →
457 (("pivot = bpy.data.objects.new(\"pivot\", None)\npivot.location = " c̲at (ʰt̲uple at) c̲at "\nscene.collection.objects.link(pivot)\n") c̲at
458 ("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
459 "look = cam.constraints.new(\"TRACK_TO\")\nlook.target = pivot\nlook.track_axis = \"TRACK_NEGATIVE_Z\"\nlook.up_axis = \"UP_Y\"\n" c̲at
460 "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
461 "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")
462}
463
464⍝━━ Rendering and files
465
466⍝│ (width, height, fps) bp:s_etup 0: Python setting EEVEE, the picture's
467⍝│ size and the frame rate, colors as they are (the Standard view, not
468⍝│ the film look) and thin dark outlines on every edge (Freestyle: a
469⍝│ line set with a line style made, as an empty scene has none), the
470⍝│ look of a drawing
471ˡ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" }
472
473⍝│ bp:s_amples n: Python setting how many samples EEVEE takes of each
474⍝│ pixel (64 by default): fewer render faster and rougher -- a test's
475⍝│ tiny frames need one
476ˡs̲amples ← { n → "scene.eevee.taa_render_samples = " c̲at (f̲ormat n) c̲at "\n" }
477
478⍝│ bp:s_till file: Python rendering the current frame to out/FILE (PNG)
479ˡ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" }
480
481⍝│ bp:v_ideo file: Python rendering every frame to out/FILE, an MP4
482⍝│ (H.264)
483ˡ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" }
484
485⍝│ bp:e_xports name: Python writing the scene as out/NAME.glb (glTF,
486⍝│ binary), out/NAME.obj (with its .mtl) and out/NAME.blend
487ˡ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" }
488
489⍝│ bp:report: Python writing out/report.txt: each mesh's vertices and
490⍝│ faces, each piece's parts and triangles, and each object, by name --
491⍝│ what a test checks
492ˡ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"