Newshot

Making guns in Blender with LLM agents

Original text(via HN AI)

Ever missed a game from your childhood so much that you decided to try and re-make it yourself?

That is where I am currently with my Tango Down project.

It's based on the classic tactical shooter games of the late 90s and early 2000s, which fell out of fashion around 2006 or 2007.

The genre has never been revived in any serious way (the 2008 financial crisis killed off studios and projects, Call of Duty and Battlefield set a template everyone else followed, and gaming became more casual, which made niche games a harder sell).

In recent years there have been a few attempts to bring the genre back, such as Ready or Not, Squad and Ground Branch.

Screenshots from the games Ground Branch and Ready or Not

Those games are very nice visually however they don't scratch an itch in my brain which the older tactical shooter games did which was the planning aspect. They also tend to go over the top in guns and kit customisation to the extent where you feel like you are dressing up a tactical Barbie doll with Gucci kit and weapons. Rather than executing quick and precise missions before logging off the computer to get to bed at a sensible time of 10:30pm.

What I was after was a remake of the original Rainbow Six (1998) and its sequel, Rogue Spear (1999). Rogue Spear is like a cross between Football Manager and an FPS: you pick a squad of operatives and give them a mission plan based on a briefing (hostage rescue, disarm a bomb and so on), then you play it out.

It feels realistic and cerebral but, most importantly, not boring (well, not for me).

Rainbow Six: Rogue Spear in action, and its mission planner

The game is showing its age, and despite a small but not insignificant following there has only been some sporadic modding and map making in the years since.

So here we are, building a game, it might not work and I might give up but it has taught me a lot so far.

Enter LLM

For the last few years I have become immersed in using LLMs, and in my day job I can't see myself going back to mashing the keyboard and writing out for loops, maps and if/elses.

Outside of work the temptation has grown too, so much so that I have been using them to mod games and play around with ideas.

One of these ideas was to make a new tactical shooter..... in Java!

First Steps

Some screenshots from the early days of the Tango Down game. It looks a lot better now

Throwing tokens at a game is easy, and within a day or two I had a basic first person shooter working logically in code.

It looked lo-fi, though, and was barely a step up from the original Rainbow Six.

The next step was free assets from the modelling sites. Plenty of what turns up on sites like 3D Warehouse or TurboSquid is of unclear origin, far too heavy, or too crude for what I wanted. The early game ran on a free, properly licensed collection from Sketchfab (that's the MP5 in the screenshots above), but those models were made low-poly and weren't rigged or animated to the detail I was after.

One of the main guns I wanted was the Heckler & Koch MP5, an iconic gun in tactical shooters and films because it's the de facto gun of police and special forces.

I could have downloaded a better one and dropped it into my game, but I had no real idea how these models work under the hood.

Some of the models online are rigged and animated in a certain way to work with a specific engine, such as Unreal Engine. Translating one of those for my rudimentary game in Java looked like a lot of effort spent learning someone else's setup rather than how a gun is made.

So the next question was: could an LLM build one for me, and if so, how well?

Python

As a complete novice to 3D modelling, my only reference point was that Blender is a popular, open source tool for designing and animating objects.

Blender does everything, which is the problem: the learning curve is a cliff. The shortcut is that everything you can click in Blender, a Python script can do instead, and an LLM is much happier writing Python than clicking.

图表:An example Python script that models a curved magazine


        """A curved box magazine, modelled entirely by code.

Run it headless, no window needed:

    blender -b --factory-startup --python magazine.py

It writes magazine.blend and magazine.glb beside this script.
"""

import math
import os

import bmesh
import bpy

MM = 0.001
RADIUS = 235 * MM  # the spine follows one constant radius, like an AK magazine
LENGTH = 200 * MM  # measured along the spine
DEPTH = 60 * MM    # from the spine (rear) to the front edge
WIDTH = 23 * MM    # side to side
STEPS = 32         # rings along the curve; more is smoother
SPAN = LENGTH / RADIUS  # the angle the body turns through


def point(t, d, x):
    """A point at angle t down the curve, d in from the spine and x across.

    The curve's centre sits RADIUS ahead of the top rear corner, so every
    point is just (RADIUS - d) out from that centre. Forward is -Y, up is +Z,
    and the top rear corner is the origin.
    """
    r = RADIUS - d
    return (x, -RADIUS + r * math.cos(t), -r * math.sin(t))


def sweep(bm, d0, d1, x0, x1, t0, t1, steps=STEPS):
    """A box section (d0..d1 deep, x0..x1 across) swept along the curve
    from angle t0 to t1, capped at both ends. Everything below is made
    from this one function."""
    corners = ((d0, x0), (d1, x0), (d1, x1), (d0, x1))
    rings = []
    for i in range(steps + 1):
        t = t0 + (t1 - t0) * i / steps
        rings.append([bm.verts.new(point(t, d, x)) for d, x in corners])
    for a, b in zip(rings, rings[1:]):
        for j in range(4):
            k = (j + 1) % 4
            bm.faces.new((a[j], a[k], b[k], b[j]))
    bm.faces.new(rings[0])
    bm.faces.new(list(reversed(rings[-1])))


def build():
    bm = bmesh.new()

    # The body.
    sweep(bm, 0, DEPTH, -WIDTH / 2, WIDTH / 2, 0, SPAN)

    # Three pressed ribs down each side, 5 mm wide, standing 1 mm proud.
    # Each starts half a millimetre inside the body so the two overlap
    # rather than touch (touching faces flicker in a renderer).
    for side in (-1, 1):
        inner, outer = side * (WIDTH / 2 - 0.5 * MM), side * (WIDTH / 2 + 1 * MM)
        for fraction in (0.3, 0.5, 0.7):
            d = fraction * DEPTH
            sweep(bm, d - 2.5 * MM, d + 2.5 * MM,
                  min(inner, outer), max(inner, outer),
                  0.15 * SPAN, 0.85 * SPAN)

    # The floor plate: a little wider and deeper than the body, carried
    # 4 mm on round the same curve.
    lip = 1.5 * MM
    sweep(bm, -lip, DEPTH + lip, -WIDTH / 2 - lip, WIDTH / 2 + lip,
          SPAN - 1 * MM / RADIUS, SPAN + 4 * MM / RADIUS, steps=2)

    # Faces were added in whatever winding was convenient; let Blender
    # point them outward. Safe here because each piece is one closed box.
    bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:])

    mesh = bpy.data.meshes.new("Magazine")
    bm.to_mesh(mesh)
    bm.free()
    return mesh


def main():
    bpy.ops.wm.read_factory_settings(use_empty=True)
    ob = bpy.data.objects.new("Magazine", build())
    bpy.context.scene.collection.objects.link(ob)

    # Soften every hard edge a little: real stamped steel has no knife edges.
    bevel = ob.modifiers.new("Bevel", "BEVEL")
    bevel.width = 0.6 * MM
    bevel.segments = 2
    bevel.limit_method = "ANGLE"

    # Dark, slightly worn enamel.
    mat = bpy.data.materials.new("Enamel")
    mat.use_nodes = True
    bsdf = next(n for n in mat.node_tree.nodes if n.type == "BSDF_PRINCIPLED")
    bsdf.inputs["Base Color"].default_value = (0.03, 0.03, 0.028, 1.0)
    bsdf.inputs["Roughness"].default_value = 0.5
    bsdf.inputs["Metallic"].default_value = 0.3
    ob.data.materials.append(mat)

    here = os.path.dirname(os.path.abspath(__file__))
    bpy.ops.wm.save_as_mainfile(filepath=os.path.join(here, "magazine.blend"))
    bpy.ops.export_scene.gltf(filepath=os.path.join(here, "magazine.glb"),
                              export_format="GLB", export_apply=True)
    print("triangles:", sum(len(p.vertices) - 2 for p in ob.data.polygons))


main()
      

An example Python script that models a curved magazine

This series of commands starts from an empty scene and writes the finished .blend.

Chain enough of these scripts together and before long you have a small arsenal ready to go into a game. The MP5 ended up as 4,595 lines of Python that I didn't type.

The constants at the top of each script are where the tweaking happens. Change RADIUS or WIDTH, run it again, and you have a different magazine a few seconds later. The values themselves can come from Wikipedia, the Internet Movie Firearms Database (IMFDB) or a search through DuckDuckGo's MCP server.

Blender will run these scripts headless, without its interface or anyone sitting at it:


        blender -b --factory-startup --python magazine.py
blender -b --factory-startup --python build_mp5.py
blender -b --factory-startup --python build_m4.py
      

Interacting (or more accurately, having an LLM interact) with Blender this way is like DNA. There is a written code for the thing being made; you can change it, but the same code always makes the same thing.

That saved me more than once. While the MP5 was being built, a clean-up job deleted the worktree it lived in twice, and Blender crashed once for good measure. Each time the model came back from git and rebuilt in a few minutes.

Blocking it out

Every gun starts as a blockout: grey shapes at real size, in real metres, before any detail goes on. For the MP5 I gave it HK's published figures on day one (680 x 260 x 50 mm, a 225 mm barrel and a 340 mm sight radius), and the origin went on the point where the trigger hand grips, so the game knows where a hand goes.

I set the budgets at the blockout as well: no more than 25,000 triangles with a magazine fitted (the MP5A4 came in at 17,850), textures painted at 2K and shipped at 1K, and a cap on draw calls, which at 4K hurt the frame rate more than triangles do. What I forgot was a file-size budget. The MP5's first export was 17 MB, against the 250 KB download it was replacing (it's 5.5 MB now, after a bit of shame).

After that it's a pass per part. The LLM rebuilds the gun, renders it from the same cameras every time and drops a preview into a file my Blender reloads. I sit and watch the gun change, and say what's wrong with it.

There is no "oneshotting" a gun

Ask for "an AK-47 in Blender" in one short prompt and you get something AK-shaped.

It will look about 60% correct, but it will be roughly shaped, missing details, and some parts won't be connected properly. It's like a kid who has been asked to build something complicated out of Lego.

Even with a lot more help than one prompt, the first pass isn't much better.

The AKM's first blockout pass, traced from a museum photograph and built on the shared kit (more on that below)

It looks like a gun? Yes

Is it an AKM? It appears so

Is it what I want for my game? No

You soon realise you need to iterate, giving the agent small, specific checks and fixes. These are some of mine, copied from the sessions as I typed them:

"The foregrip is too squarish, it should be more moulded at the top around the barrel (tapered)" (MP5, 28 November)"Still too chonky and thick, a little bit thinner" (the MP5's sliding stock, 29 November)"We have this same issue as always with the buttstocks (since MP5) they are too square at the tops and not rounded" (AKM, 4 December)"The barrel and the gas bit above the barrel seem too blocky still. They should be more chamfered, I think would be the word." (AKM, 4 December)"the actual barrel doesn't have a hole in it. It's just a solid bit of metal" (AKM, 4 December)"The safety selector is a bit too primitive ... it's not a straight piece of metal as you have modelled it, it's got more of a shape to it with a piece of metal sticking out so that it can catch a finger to move it" (AKM, 5 December)

The first gun I modelled was the MP5, and that took thirteen stages and 35 commits over a day and a half. It was a lot of watching and waiting and giving it nudges.

After that I tried making some harnesses and tooling to help the LLMs understand what they were looking at:

  • Virtual callipers: the LLM measures a reference photo (at a known scale, where there is one) and compares the model's parts against it, then adjusts.
  • Silhouetting: the model is laid over a photo or diagram, so you can see which parts fall short of the outline or overshoot it, and trim them.

With those, each pass could trim and make small tweaks without me doing it by hand, which meant fewer rounds of me pointing at things.

The morning after the MP5 was finished, I asked for a retrospective on what had gone well and what hadn't, and for the skills to be updated so the same mistakes wouldn't happen again. Since then, after every gun the LLM writes down what it got wrong, in a skill file the next session reads before it starts. The MP5's mistakes became the M4's checklist. It doesn't stop new mistakes (as the C-Mag proved), but it does stop the old ones coming back.

The C-Mag arrived on the MP5's first evening, as one of its options: a Beta C-Mag, the hundred-round double drum. About fifty minutes after it landed I opened it in Blender, and one line of my note back was "The C Mag is incorrect orientation of the drums". They were on sideways.

A real C-Mag, then ours from behind: the drums as first built, after passing their checks (left), and after I'd looked at them (right). More fixes came after this

The fix had its own twist. The commit that came back said the drums had been turned. They hadn't (the file on disk was out of date), and the only reason I didn't hear "fixed" was that the coordinating agent measured which way the drums' faces pointed before telling me.

Over the two days, two independent reviewers raised 45 findings on the MP5. The six biggest fixes of the session (the C-Mag among them, along with a handguard that was a box and a grip with no shape) came from me looking at it, and no reviewer raised any of them. The LLM can do the geometry. What it can't do is look at a C-Mag and think "that's daft"; it has no taste, and it doesn't always have common sense.

Using reference photos or specs

The biggest lesson from the MP5 was that one picture isn't enough. I gave it a single side view, and every defect I found afterwards was in something a side view can't show: a cross-section, the underside, a join. The LLM had guessed, and the guesses were where it went wrong. Now every gun needs references from at least three views before the blockout starts.

The research is scripted too. A small Node tool pulls the specification from Wikipedia and IMFDB with a source against every number, fetches reference images along with their licences, and lists the views it still hasn't found. That last part matters more than I expected: free pictures of long guns are nearly all of the right-hand side (for the M4, the best left side I could find was a Tokyo Marui product shot).

Published figures disagree with each other as well, and the agents kept stopping to ask me about a few millimetres here and there. On 4 December I told them "I don't think at that length we should be precious", and it became a rule: a length within 25 mm or 5% of the published figure is close enough. A stock that still folds matters more than an exact overall length.

Photos can mislead in subtler ways. One M4 blockout, traced from a single photograph, put the takedown pin 21 mm out and still scored well against it, because it had faithfully traced the photo's blur and shadow along with the gun. My verdict on the M4 on 3 December was "Its outline is sort of good but it's very blocky still".

The AK family came last, and by then the method had settled. The stock went from a box with 8 mm corners to a properly rounded comb, measured at four depths in from the edge. One pass it refused to take: two of my references disagreed about the shape of the top cover, so it backed the change out and asked me which to believe. I picked one and it carried on.

Componentisation

This bit is where the software engineer in me had too much fun.

Like any other engineered product, guns are assembled from components, and the same components get reused across many variants and families.

The M16 and the AK-47 each started a family: the M4 is a shorter M16, and the AK-74 and AKS-74U are AKs with a smaller round (and in the 74U's case, a lot less of everything).

Across families the jobs are the same anyway. Everything has a receiver, a barrel, a grip, a magazine and something for your shoulder.

So rather than having an LLM model each gun from nothing, once the MP5 was done we lifted everything that wasn't MP5-specific into a shared kit. Think of it as a library: the kit knows how to make a rounded slab, loft a section, bake a texture and export a rigged gun, and each new gun only brings its own parts. The P90 doesn't copy a line from the MP5; it calls the same functions.

Shared magazines are models in their own right (the STANAG is one), and no gun's build is allowed to touch them. That came from me asking, when I found out that rebaking the M4 also rebaked the shared magazines, "surely the magazine should be its own model that is independent of baking?" Rigs come from a template per class: HK sub-machine gun, M4-style rifle, bullpup, pistol.

The first thing I asked of the refactor was to prove the MP5 hadn't changed. So every change to the kit is now checked against a fingerprint of the MP5's output, which is a regression test for a 3D model (I enjoyed that more than I should have).

Modelling Love Language

Talking an LLM through how to model something takes a good vocabulary and a clear way of describing what you want.

If you are vague, chances are it will change a part of the model you didn't want changed, or change the right part in a way you don't like.

To make it more complicated (and more fun), words mean different things in modelling. When you see the word "furniture" you think of sofas and tables. On a gun, furniture means the parts that aren't mechanical, like the grip and the wooden handguards.

These are some of the words I've had to pick up along the way.

TermDefinition & Project Context
FurnitureA gun's wooden or plastic parts: the stock, grip and handguards. An AK's "plum furniture" is not a sideboard.
ChamferA flat cut across an edge, at an angle, in place of the sharp corner. The word I was reaching for when I asked for the AK's barrel to be "more chamfered, I think would be the word".
LoftA shape pulled through a series of cross-sections, like a boat's hull through its frames. The MP5's handguard was a box until it was lofted.
KnurlingA grip pattern rolled or cut into metal, as small diamonds or straight ridges. The AK's selector has it on its finger tab.
Slant brakeThe AKM's muzzle device, cut at an angle so the escaping gas pushes the muzzle down against the climb.
Z-fightingTwo surfaces in the same place, flickering because the renderer can't decide which one is in front. The AK selector's first bake failed its checks on fourteen of them.
Texel densityHow many texture pixels cover each metre of the model. It's the difference between a sharp gun and a blurry one.

The rest are in the cloud below, sized by how often each word turns up in the project's commit messages and logs.

Gun Variations

Once the base model of a gun and its components are in decent shape, the fun starts: variations. Swapping the stock, the grips, the magazines, the accessories.

Each variant is a few lines of TOML.


        [[variant]]
name = "mp5a5_od"
flags = ["--stock", "slide", "--furniture", "od"]
template = "smg_hk_a5"
      

The MP5 has ten: the A4 and A5 (fixed and sliding stock), each in black, in olive drab and with the light forend (the one with a torch built in), plus the K, the K-PDW, the SD6 and the SD5. On top of those sit the option parts: the C-Mag, a windowed magazine, a dot sight and a suppressor.

Variants are where I did most of my correcting. The PDW's stock was wrong until I pointed out that "The stock on the PDW is different with a triangular butt, it should also be thinner". The correcting went the other way too: when I asked for the SD6 with the fixed stock, the LLM told me HK calls that gun the SD5, which I'd never have known.

I'd also said that "I don't think torch or suppressor should be mutually exclusive, they should be allowed", so every pair of options now has to pass an overlap test on the meshes. The torch clears the suppressor by 0.7 mm.

The M4 followed the same pattern, with an M68 sight, a KAC suppressor, a torch, the C-Mag and a windowed magazine. Its C-Mag got off no more lightly than the MP5's: "It just looks like a magazine rectangle with two cylinders just next to it. They don't even look attached or anything." (3 December)

Is there a better way than Python?

For Blender and making guns, there doesn't appear to be a better way at the moment, whether you drive Blender through the MCP plugin or through its command line.

The MCP route is still Python, just typed into the running session.

Text-to-3D generators like Meshy.ai or Tripo skip all of this and hand you a textured model in a couple of minutes. For detailed animation, or parts that have to move and fit together, they fall short. I still use Meshy for objects and clutter on the maps.

So for guns in Blender I'd still pick Python. What I like most is that every tweak to a model is a diff in git, and reading those diffs, slowly, I've picked up how those shapes are made.

What it cost

This is not wholly scientific, but the MP5 came to about £134 and the M4A1 to about £79. After that, with the shared kit and a written method in place, each gun came to between £9 and £28 (about £19 is typical). It's a step, not a slope: the drop came from moving off long conversational builds, not from each gun being cheaper than the last.

The figures come from the session logs on my Mac (Claude Code's transcripts, and pi's sessions, which ran through GitHub Copilot), counted by a few Python scripts. I also used Opencode, but on a different machine, so none of its usage is in these numbers.

Gun (variants)WhenTokens in and outCache readsCostPer variant
MP5 family (7)28 Nov to 3 Dec15.9M294M£134£19
M4A1 (1)29 Nov to 3 Dec5.8M271M£79£79
HK USP (1)2 to 4 Dec1.2M63M£18£18
Glock 17 (1)3 to 4 Dec0.7M30M£9£9
HK PSG1 (1)3 to 4 Dec1.5M103M£28£28
Steyr AUG A1 (1)3 to 4 Dec1.3M66M£21£21
Makarov PM (1)4 Dec0.7M47M£13£13
AK family (3)4 Dec3.4M287M£71£24
FN FAL (2)4 Dec0.7M49M£14£7
Skorpion vz. 61 (1)4 Dec1.1M67M£19£19
IMI Uzi (1)4 Dec0.8M50M£14£14
Remington 870 (1)4 Dec1.3M72M£20£20
FN P90 (1)4 Dec1.0M70M£19£19
Shared: weapon kit, rig templates, holds2 to 4 Dec10.3M308M£91

The cost column is what the same tokens would cost at Anthropic's published API list prices, converted at $1 = £0.79. It isn't what I paid: Claude Code ran on a subscription and pi through GitHub Copilot. Variants count models, not finishes (the MP5's seven are the A4, A5, K, K-PDW, SD5, SD6 and MP5/10). The AK row was measured on 4 December, partway through; the second round that went into the game on 5 December isn't in it.

How efficient you are depends on reusing knowledge through skills, and on how well your harness handles caching and prompts. There's probably an element of diminishing returns here too, but I'll keep modelling more weapons and see where the costs go.

Conclusion

Against the reference photos, the published specs (where there are any) and a fair amount of guesswork, I'd put the guns at 80 to 90% accurate.

For a game, and for what I'm after, I'm happy with that.

Are other games' guns 100% accurate? I'm not sure. I suspect every modelling artist works the same way and fills the gaps between the references with judgement; I just had an LLM do the filling.

This worked for me because I'm a developer. I don't know modelling, and I don't have the time to learn it properly. I didn't want to steal a model, or just copy one I'd found online.

What I wanted was a small taste of how a gun gets authored, and having it built as code meant I could follow every change the way I'd follow a pull request.

On 29 November the LLM asked whether I wanted knurling on the MP5's torch. My entire reply was "Knurling?"

Downloading or buying an MP5 model would have been quicker, but I wouldn't know my new favourite word.

Credits

  • Feature image: a still from The Matrix (Warner Bros., 1999).
  • Ground Branch screenshot: BlackFoot Studios (early access, 2018).
  • Ready or Not screenshot: VOID Interactive (2023; early access 2021).
  • Rainbow Six: Rogue Spear screenshots: Red Storm Entertainment (1999).
  • Java installer screenshot: Oracle.
  • Horse meme: original artist unknown.
  • The MP5 in the September screenshots: "Low-Poly HK MP5" by TastyTony, licensed CC BY 4.0, modified for the game (rest pose baked in, rig removed, materials converted).
  • MP5A3 photograph: Dybdal / Mattes, CC BY-SA 3.0, via Wikimedia Commons.
  • AKM photograph, and the silhouette composite made from it: Armémuseum (The Swedish Army Museum), CC BY-SA 4.0, via Wikimedia Commons. The composite is shared under the same licence.
  • M4A1 photograph: Jackolmos, CC BY-SA 3.0, via Wikimedia Commons.
  • C-Mag photograph: from Wikipedia's "Beta C-Mag" article.

The text above was extracted automatically from the source page and may miss images, tables or code blocks. The original is authoritative.

Published by HN AI
This site only summarises and aggregates; copyright stays with the original author. Headlines and summaries follow the source — where they differ, the original wins.
Read the original ↗