# AGENTS.md: working on Joint Ops maps through MED's AI Link

For AI agents helping a mapper. AI Link lets a program on the same PC edit the map open in MED through MED's own routines, so edits behave like the mapper's own: MED redraws, moves and turns can be undone, and MED does the saving. The tools in `MED_agent_tools.zip` add the eyes: they read the map out of the running MED, measure it and draw it.

Work with the mapper, not around them: they own the map and their eye in the game is the final word. Work on a copy of a map unless told otherwise.

## Turning it on

- Tick **File > AI Link** in MED, or start MED with `/AILINK`. It is off by default.
- Open the map first. There is one link per PC: only one copy of MED can have it on.
- The link is a local named pipe, `\\.\pipe\JOTACmed-link`. It can't be reached from another PC.
- While it's on, any program on this PC can edit the open map, so turn it off when you're done.
- TAC MED v2 from TEST20 onwards, and retail MED (`MED_retail.exe`) since November 2026. Older copies don't have it.
- This is new. If anything misbehaves, tell the mapper to report it where they got MED.

## Talking to it

Open the pipe, write one command, read one line back, close. Commands run between MED's window messages, so answers can take a moment. Every command except `ping` starts with `@TICK`, the PC's `GetTickCount` value. MED refuses one older than 3 seconds.

```python
import ctypes, re, time

PIPE = r'\\.\pipe\JOTACmed-link'
FX = 65536                                  # map units are 16.16 fixed point: metres * 65536


def send(cmd, wait=8):
    t0 = time.time()
    while True:
        try:
            f = open(PIPE, 'r+b', buffering=0)
            break
        except FileNotFoundError:
            raise SystemExit('AI Link is off: tick File > AI Link in MED')
        except OSError:                     # MED hasn't noticed the last client leave yet
            if time.time() - t0 > 3:
                raise
            time.sleep(0.02)
    with f:
        if cmd != 'ping':
            cmd = f'@{ctypes.windll.kernel32.GetTickCount()} {cmd}'
        f.write(cmd.encode('latin1'))
        return f.read(512).decode('latin1')


def read_items(mis_path):
    """id -> (type, x, y, height above ground, yaw) from a saved .mis. Ground tiles have name "MapTile"."""
    text = open(mis_path, encoding='latin1').read().replace('\r\n', '\n')
    out = {}
    for m in re.finditer(r'begin item \d+\n(.*?)end item\n', text, re.S):
        b = m.group(1)
        i, t = re.search(r'\n  id (-?\d+)', b), re.search(r'type_id (\d+)', b)
        p = re.search(r'position (-?\d+) (-?\d+) (-?\d+)', b)
        y = re.search(r'facing (-?\d+)', b)
        if i and t and p:
            out[int(i.group(1))] = (int(t.group(1)), *(int(v) for v in p.groups()), int(y.group(1)) if y else 0)
    return out
```

## The tools

`https://fmj-squad.com/downloads/MED_agent_tools.zip`: unpack anywhere and `pip install -r requirements.txt` (numpy, scipy, pillow). Windows, tested on 64-bit Python 3.11. Nothing from the game is in it: models, terrain and `items.def` come from the mapper's own game files.

They work on both MEDs and tell them apart by themselves. They find the running MED, the folder it runs from and the mod it was started with, so they read the same game files MED does. With no MED running, set `JO_DIR` to the game folder and, for a mod, `JO_MOD` (`revx02`, `jox01`).

Reading takes no AI Link, only one MED open: it reads MED's memory, read-only, and touches no other program. Edits need AI Link on. `medq.py` reads each edit back and checks the object again, so use it rather than the bare pipe.

| Run | Gives |
|---|---|
| `medq.py scene` | Which MED, the map, object count, limit, models not loaded |
| `medq.py inspect ID`, `near X Y R`, `ground X Y` | One object, what's around a spot, ground height exactly as MED has it (metres) |
| `medq.py clearance ID` | For each piece of the model, how far its foot floats or sits buried |
| `medq.py hits ID` | What it cuts through, and at what height |
| `medq.py verify ID [ID..]` | All of that as a list of problems: FLOATS, BURIED, CLIPS, tilted |
| `medq.py watch SECONDS` | Prints what the mapper moves, adds and deletes as it happens |
| `medq.py view FROM_X FROM_Y LOOK_X LOOK_Y OUT.png` | A picture at eye height, with textures |
| `medq.py card ID OUT.png` | Close views round one object, and the same with the ground taken away to show what's buried |
| `medq.py move ID X Y [ABOVE]`, `raise ID METRES`, `turn ID YAW`, `add TYPE X Y [ABOVE] [YAW]`, `delete ID`, `undo`, `redo`, `select ID`, `saveexport` | Edits, in metres. Saveexport also closes the log box |
| `place.py ID [RADIUS]` | The nearest spots where this object would sit right, keeping clear of others. Moves nothing |
| `map_inspect.py MAP.bms --trn T.trn [--at X Y --radius R] [--png OUT.png]` | A saved map, no MED needed: floats and clips, with a site drawing |
| `pieces.py MAP.bms --trn T.trn [--at X Y --radius R]`, `buried.py MAP.bms --trn T.trn --at X Y` | Saved map: piece by piece, and what's buried |
| `eye.py MAP.bms --trn T.trn --id ID --png OUT.png`, or `--from X Y --look X Y` | Saved map: the same pictures |
| `survey_models.py` | Writes `models.tsv`: every building, decoration and plant with type number and real size. Run it first, type numbers differ between TAC and retail |
| `survey2.py [T.trn WIDE LONG X0 X1 Y0 Y1]` | From `models.tsv`: buildings with stairs and two floors (`houses.png`), long vehicles, low fences; with the numbers, the flattest ground that size |
| `decor_sheet.py OUT.png MODEL [MODEL..]`, `house_sides.py MODEL` | Textured views of models beside a soldier, to choose by eye. `MODEL` = its `graphic` name |
| `furn_fit.py MODEL [MODEL..]`, `furn_fit.py --walls MODEL Z [Z..]` | Which sides of a model are see-through; inside wall faces of a house at a height |

What they can't see: tilted objects are checked as if flat, and the pictures are our own renderer, not the game's: no shadows, grass or game lighting. "No problems" means nothing floats or clips, not that it looks right.

`medlink.py` is the reader underneath. Its header lists MED's memory layout if you need more than the tools give, and it's the place to fix if a future MED build moves something.

## Commands

The pipe's own commands, for anything the tools don't do.

X, Y and ABOVE are 16.16 values. ABOVE is height above the ground under the object, the way MED stores it. Yaw is whole degrees.

| Command | Answer | Does |
|---|---|---|
| `ping` | `ok PID PAGE OBJECTS MODIFIED` | Checks the link. `MODIFIED` 1 = unsaved changes |
| `select ID` | `ok` | Selects one object |
| `move ID X Y ABOVE` | `ok` | Moves it, can be undone |
| `turn ID YAW` | `ok` | Turns it to that yaw, can be undone. Stock maps hold yaws like -271: compare them modulo 360 |
| `add TYPE X Y ABOVE YAW` | `ok NEWID` | Adds an object and loads its model. **Clears MED's undo list**, as MED's own Insert does |
| `delete ID` | `ok posted` | Runs MED's Delete, can be undone |
| `undo`, `redo` | `ok posted` | MED's menu commands |
| `saveexport` | `ok posted` | MED's Save and Export: writes `.mis .til .ifl .bms`, then shows an Export Log box |
| `closelog` | `ok` | Closes that Export Log box, and no other dialog |

Errors: `err busy` (a dialog is open: nothing happened, try later), `err stale`, `err no such id`, `err pseudo item`, `err bad args`, `err unknown command`, `err no log box`, `err add failed`.

`ok posted` only means the request was sent. Check it took effect: `ping` for the object count and `MODIFIED`, or save and read the `.mis`. After `saveexport`, poll `closelog` until it answers `ok`; edits answer `err busy` until the box is closed. Save only when the mapper wants it saved.

## Finding things out

Use the tools above. The pipe itself edits and doesn't list objects; without the tools, save and read the `.mis` with `read_items`. Don't rely on slot order: Save and Export re-sorts the object list, so use ids. MED leaves a facing of 0 out of the `.mis`.

`TYPE` = the `id` in `items.def` minus 100000 (`100888` = `888`). Start markers: `6002` deathmatch, `6003` blue, `6004` red.

The tools measure; they can't tell you how anything looks in the game. Ask the mapper to check in MED's 3D view and in the game, and say plainly what you haven't seen.

## Placing objects

- A model turns by `a = 90 - yaw` degrees: its +x points along `(cos a, sin a)` in map x, y.
- A record's height is the model's origin, not its feet, and differs per model. `add` allows for a model's Ground point if it has one, but some models still sit a little high or low.
- On a slope, set objects by the lowest ground under them, so they dig into the uphill side instead of floating on the downhill side.
- One model can be several separate things on different ground. A row of stones can float at one end and be buried at the other.
- Models don't scale. A bigger map only spreads them out.
- TAC MED holds 49,152 objects, retail 8,096. Past that, `add` answers `err add failed` and changes nothing.
- A fence with its long axis along model y: `yaw = 180 - direction`.
- Some models don't load in MED (`scene` lists them under `models_not_loaded`): don't build on those.

## Getting a map right

- **Scale to the player, not the models.** Decide run times first. A soldier runs about 6-7 m a second. Add a person to any plan before judging it.
- **Stock models only** unless the mapper says otherwise. Custom models have to reach every player. If stock models can't do what's asked, say so before building.
- **Look before choosing a building.** Two floors on paper can still look like an outpost.
- **JO draws faces from one side only.** Furniture and models can be see-through from behind: put open backs against walls.
- **Measure real floors and walls** before furnishing. Don't guess, and don't ignore "small" contacts with walls.
- **"Nothing clips" doesn't mean "looks right".** Only playing it shows that.
- **Say what's been tested:** seen in game, or only worked out. So far maps built this way have only been played on TAC. On retail the edits and tools are tested in MED, but no edited map has been played yet.

A way of working that held up: fix run times; choose flat ground by scanning heights (terrain can't be sculpted, only chosen); choose models by looking; measure each building's real floors with a ray straight down and walls with rays sideways, because flat-face lists mistake a ceiling's underside for a floor; build through MED; `verify` and fix until clean; look at eye height with a soldier in the picture, and check the camera isn't inside a wall; save through MED; tell the mapper exactly what changed and what to check.

Stock models that worked on TAC (metres; on retail check with `survey_models.py`):

| Use | Type | Model | Size | Notes |
|---|---|---|---|---|
| Two-floor house | 806 | dperu3 Wooden House #1 | 18.5 x 20.3 x 15 | Floors 0.18 and 4.41. Inside stairs, door + porch on +x |
| House | 10401 | dom02 Soviet House #3 | 10.6 x 21.8 x 7.8 | Door on its -y end |
| Shed | 2034 | imstal5 Market Building #5 | 6.3 x 6.5 x 4.8 | |
| Long vehicles | 10408, 888 | Trolley Bus, Fuel Truck | 15.3, 10.8 long | The Fuel Truck explodes, the Trolley Bus can't |
| Cars | 976, 9624 | Blue Pickup (explodes), Parked Blue Truck | about 6 long | |
| Low fence | 2150, 2142 | Fence #2, #1 | 17.9, 4.5 long, 1.7 high | |
| Fountain | 9628 | Large Fountain | 7.2 x 7.1 x 2.7 | |
| Trees | 9044, 5101, 12093, 5118 | Green Tree Two, Mango, Large Green, small-tree group | | Wide low groups sink on slopes |
| Plants | 2255, 2259, 2252, 2230 | Jungle Bush 6, 9, 4, 2 | | JO has no flower models |
| Sofas | 11551, 5133, 9649 | divan, Red Couch, Old Sofa | | Backs: divan +x, mcou01 -x, sofa01 -x |
| Beds | 21647, 9637 | k_koika, bed + dresser | | k_koika headboard -x is see-through |

## Things only the .mis can do

With the map closed in MED, edit the `.mis` as text and reopen it. MED then keeps them and saves them. Back it up first.

- **Game type:** header `attrib`: deathmatch `33554435`, team deathmatch `536870915`.
- **Ground tiles** (items named `MapTile`): 16 m squares that only turn in 90 degree steps. `type_id` = cell number + 3, `extra_bheight` = cell number, `extra_val2` = tile number, position = tile centre. In `trntile10`, cells 27-29 are grass (speckled and see-through, so stack several), 24 asphalt, 20 concrete slab, 23 a curved kerb (see-through, put asphalt under it). MED writes the `.til` itself on save if the `.mis` has MapTile items. A map started from a copy brings its old tiles along.
- **Indestructible object:** add the line `bmsi_attributes 2097152` to the item. Not yet confirmed by shooting one in play.

## Putting a map on a server

Maps are not downloaded to the client: no map file goes to a player's PC. Map files go in the server's game folder only, so never make a map zip for players. Ask the server's admin before changing anything there, because the server may need stopping first.

A load screen is different. `<map>.pcx` (800x600, 8-bit) is read from the player's own game files and isn't sent by the server, so players only see it if it reaches them some other way. 24-bit images make maps load much more slowly. The game writes its own text across the top of the picture, so keep the top 56 pixels clear.
