Kaleido’s pompom engine: one Xbox player, a Python script per demo

The dump is an SVN checkout of kaleido (rev 86, Nov 2004). Every demo runs on the same demoplayer.xbe, which boots Python 2.2, executes d:\demos\demo\pompom.py, and lets that script build an effect graph and hand it to a timeline scheduler, driven by hits from the music module. Only bi-won’s script and data are in this dump; below is its full schedule as the engine plays it.

25.5klines of engine C++, plus a 14k-line baker
86SVN revisions, two authors
35effect node classes in fxlib
5:32bi-won running time, per its schedule

bi-won, as the Scheduler sees it

Every sched.schedule(start, length, node, slot, layer) call in bi-won/pompom.py, drawn at true scale. Drag the playhead to see which nodes are live and how the Scheduler wires them together at that moment.

2:30

From a 3ds Max scene to the TV, in two machines

PC build box · nmakeXbox devkit · d:\demos\demo\ xbcp: pompom.py, *.lzma, .xm, pnggetEvent("bass")joypad buttons, recorded and replayed
Top row runs on the PC with nmake (makefiles in bi-won/, fxlib/shaders/src/). run.bat copies the script, then xbreboots the devkit into demoplayer.xbe. Bottom two rows are the runtime: the module player and the joypad both feed one event manager, which effect callbacks poll every frame.

The first-party code is three libraries, a player and a tool

Line counts are wc -l over sources in trunk/. xboxcore and xgui exist only in develop/; trunk references them but lacks the folders.

ModuleRoleHighlightsLines

Third-party, vendored: libmodplug (21k lines, patched for sync), Python 2.2.1 core, libogg / libvorbis 1.0.1, LZMA SDK 4.01 decoder, a SHA-1, the 3ds Max SDK ASCII exporter sample, and the SWIG-generated demoscript_wrap.cpp (21,243 lines).

The Scheduler is a five-slot compositor, not a sequencer

fxlib/src/scheduler.cpp owns five 640×480 LIN_A8R8G8B8 render targets, one per slot. Each frame it collects the jobs active at the current time and routes them:

SI_A / SI_B are the two decks. SI_MIX is a crossfade node whose inputs a and b are force-fed the deck targets, with mix computed from how far the playhead is through the overlap. SI_POST gets the deck (or mix) output on its first free in input, searched depth-first through the node’s chain. SI_SUPER takes whatever came last and draws to the back buffer.

Seeking backwards is the clever bit. Because sliders and callbacks are stateful, the Scheduler rewinds to the earliest start among active jobs, calls notifyEffectBegin() on each, and re-simulates at a fixed 50 Hz without rendering (though, as the bug list shows, from the wrong start time).

// crossfade factor for SI_MIX (scheduler.cpp)
if (start[SI_A] < start[SI_B]) {
  float overlap = end[SI_A] - start[SI_B];
  float t0 = getTime() - start[SI_B];
  factor = t0 / overlap;
}
lv[SI_MIX][i]->mix = FixedSlider(factor, factor);
lv[SI_MIX][i]->values["a"] = targets[SI_A];
lv[SI_MIX][i]->values["b"] = targets[SI_B];

// renderEffects(): one node per slot, by design or not
// HACK only renders one effect
for (i=0; i<effects.size() && i<1; i++) {
  effects[i]->processCallbacks();     // Python runs here
  effects[i]->processUpdateParameters();
  if (!seeking) { effects[i]->render(); effects[i]->done(); }
}

The layer field is stored and sorted on but never read, and ScheduleTransition is accepted and ignored. bi-won uses only A, POST and SUPER.

Effect nodes pull their inputs and borrow render targets

Every effect derives from fxcore::EffectNode. Inputs are named (registerInput("in")), wired with connectOutput(remote, "in"), and evaluated on demand: a node’s render() asks each input to render first and receives its texture.

Targets come from a TextureSlotManager pool. Each node counts its consumers (out); every consumer calls done(), and when the count hits zero the target goes back to the pool unless keepTarget is set. A node with no consumers renders straight into whatever target is bound, which is how the root of a chain lands in a Scheduler slot.

Lifetime runs through four parallel notifications, each walking the whole input tree: schedule / unschedule (reference count), effect begin / end (reset state), and render begin / end (load or unload resources).

Texture* EffectNode::preRender() {
  if (frameProcessed()) {   // already rendered at this time?
    if (!result) throw Exception("...consistency failure");
    return result;            // shared node, reuse texture
  }
  processInputs();            // values[name] = input->render()
  return 0;
}

bool EffectNode::frameProcessed() {
  bool b = (last_rendered_time == timer::getTime());
  last_rendered_time = timer::getTime();
  return b;
}

Frame identity is float equality on the clock. It works because time is set once per frame, but two frames at the same timestamp (a pause, or seek steps) would skip rendering.

35 effect nodes, patched together like modules on a rack

fxlib has 34 concrete EffectNode subclasses plus the SceneEffect base, all with named input sockets and FixedSlider knobs. Sources make pictures from nothing, filters take one in, combiners take two or more, and transforms ride on scene meshes. Green outlined names are input sockets, grey ones are slider knobs Python can animate, and a solid green tag means bi-won uses the effect.

Every node follows the same render ritual

Update the knobs, return the cached texture if this frame was already drawn, bind a pooled target, push render states, draw a full-screen grid through a vertex shader, pop everything, then tell the inputs they’re done. The state stacks on Renderer are what keep 35 effects from leaking blend or z settings into each other.

Texture* Blur::render() {
  mix.update(); spread.update();      // knobs
  if (Texture* r = preRender()) return r;  // cached / pull inputs
  setupTarget();                      // pooled 640×480 slot
  r.zBufferState.push(noZ);  r.cullState.push(ccw);
  blurUniform4(values["in"], targets[0], spread);
  blurUniform4(targets[0], targets[1], spread);
  blurUniform4(targets[1], r.targetState.top(), spread);
  fx::tools::mix(values["in"], r.targetState.top(), 1-mix);
  r.zBufferState.pop(); r.cullState.pop();
  restoreTarget(); postRender();      // inputs: done()
  return result;
}

The palette trick: RGBMap plus a generated curve

MGGamma draws no picture. Its vertex shader paints a full-screen gradient whose channels follow pow(x, gamma), which turns the target into a lookup table. RGBMap then does a dependent texture read, using each pixel’s own colour as coordinates into that table. Animate the three gamma sliders on a bass hit and the whole frame’s colour grade swings, at the cost of one extra quad.

// rgbmap.ps
float4 color = tex2D(tMap,  I.tex0.xy);
float4 c0    = tex2D(cMap0, color.ar);   // red from (a,r)
float4 c1    = tex2D(cMap1, color.gb);   // green, blue from (g,b)
result = float4(c0.r, c1.g, c1.b, 1);

# util.py: SimpleGamma wires it up
self.gamma = MGGamma()
self.gamma.connectOutput(self, "map")

The 2-component lookups map onto the NV2A’s texreg2ar / texreg2gb pixel-shader ops, which is why red is indexed by alpha.

The renderer defers every state change until a draw call

pompom::Renderer is a 722-line singleton over the Xbox’s Direct3D 8: a 640×480 A8R8G8B8 back buffer, a D24S8 depth-stencil, hardware vertex processing and a present locked to vsync. It never lets callers touch the device. Instead it holds 14 stacks, one per kind of state, and effects push what they need and pop it afterwards.

The stacks are std::touchstack, a copy of Dinkumware’s <stack> header with one addition: a touched flag that every push and pop sets. Nothing reaches the GPU until renderMesh() calls applyRenderStates(), which only re-sends the stacks whose flag is set and then clears them. A pop restores the previous state for free, and an effect that pushes and pops without drawing costs nothing.

Step through fx::Overflow::render() on the right: two draws with a blend change in between. The second draw only re-sends the blend state, plus the four kinds that are sent on every draw no matter what.

    The 14 stacks and what a draw sends from each

    StackHoldsSent to the deviceOn draw

    Convolution on the register combiners

    pompom::texturefx runs every blur as a filter of taps. Each pass binds the source texture to all four texture stages, each with its own UV offset, and writes the tap weights into the NV2A register-combiner constants c0/c1. Negative weights use the combiners’ signed-negate input mapping. Filters with more than four taps take extra passes, additively blended. blurUniform4 is a 4-tap cross, blurUniform8 a 3×3, and blurRadial stacks scaled copies for zoom blur.

    // texturefx.cpp: weights become combiner constants
    rPSInput[l] = PS_INPUTMAPPING_SIGNED_IDENTITY
                | ((l % 2) ? PS_REGISTER_C1 : PS_REGISTER_C0);
    blurPixelShader->rgbIn[0] = PS_COMBINERINPUTS(
        rPSInput[0]|PS_CHANNEL_RGB, PS_REGISTER_T0|PS_CHANNEL_RGB|...,
        rPSInput[1]|PS_CHANNEL_RGB, PS_REGISTER_T1|PS_CHANNEL_RGB|...);
    // stage 1 does t2*w2 + t3*w3 the same way

    Pixel shaders are raw D3DPIXELSHADERDEF structs, so the renderer sets their constants as render states (D3DRS_PSCONSTANT0_0 + i), only for the slots a bitmask marks as used.

    Where the Xbox shows through

    Chunked draws. Meshes are drawn without index buffers. The vertex buffer is locked once and re-registered in windows of 65,535 vertices with XGSetVertexBufferHeader, then drawn as triangle lists, so a scene of any size goes out in a few big batches.

    A stall after every mesh. renderMesh ends with D3DDevice_BlockUntilIdle() and the comment “DEZE LATEN STAAN ANDERS WERKT DE BLUR NIET!!!”, which means “leave this in or the blur doesn’t work”. Each draw waits for the GPU to finish, probably because an effect reads a target the previous draw is still writing.

    Linear and swizzled textures. Render targets are LIN_ formats, which the NV2A samples with pixel coordinates rather than 0 to 1, so effects check isLinear() and scale UVs by width−1. Loaded images are swizzled. Idle 2D textures can swapOut() to the Z: cache partition as XPR files (refusing, for a texture it doesn’t own, with “Look, it’s drinking the water!”).

    Fixed constant layout. World goes in c0, view×projection in c4, view in c8, transposed; effect parameters live from c89. Point sprites use texture stage 3, where the hardware generates their coordinates. CullState has a CM_FLIP mode that inverts whatever winding is current, for mirrored transforms.

    FixedSlider is the whole animation system

    Nearly every parameter Python touches (blur mix, gamma, mesh colour, noise amplitude, curve length) is a FixedSlider: a current value chasing a target that itself relaxes toward a fixpoint. A music hit sets the target; the slider springs there and drifts home. No keyframes anywhere.

    Mode 0 is the original double exponential, made frame-rate independent with pow(d, Δt·1500). Mode 1 steps linearly by damping per frame. Mode 2 is a damped spring with velocity. The presets below use values straight from bi-won.

    Simulated at 60 Hz. Orange is the value effects read; dashed is the target. The hit lands at 0.5 s.

    The event system: one list per frame, pushed to some and polled by the rest

    Everything that can trigger a visual, whether a module instrument, a pad button or a replayed recording, becomes the same pompom::Event. Nine classes in about 700 lines of pompom carry it. Each frame the EventGeneratorManager singleton rebuilds one list of events. Engine objects are handed every event as it arrives, and effects and Python ask the list by name.

    GENERATORS · update(events) EVENTGENERATORMANAGER · once a frame LISTENERS · processEvent()
    Generators are kept in a std::set ordered by pointer address, listeners in a hash_set, so the order of events within a frame depends on where the heap put each object. Every generator and listener registers itself in its base-class constructor. The EventCacher is both: it hears live presses and plays them back after a rewind (dashed).

    One event

    FieldTypeWhat fills it

    On disk, recorded_events holds each one as raw memory: six 4-byte fields, then the name as a length byte and its characters. A “bass” record is 29 bytes. recorded is not stored; the player sets it on load. The name is stored after mapping, so a replay is never re-translated: change an addMapping line and old recordings keep their old names.

    Names are the interface

    addMapping(channel, note, name) fills a std::map from (channel, note) to a name, and the manager names every event that arrives without one. Many keys can share a name (bi-won’s “bass” covers six instruments), but a key has one name, so a second mapping overwrites the first. That is why instrument 23 ends up as only “revbass”.

    Python never sees instrument numbers. Of the 21 getEvent calls in bi-won’s scripts, 20 ask “did a NOTE_ON named X happen this frame?” Each call scans the frame’s list from the start and returns the first match. A list lives until the next updateGenerators(), so every effect polling during one frame sees the same answer, however many ask.

    Push and poll split the work. Things that must see every event, such as the recorder, the cacher, the timeline and the rumble, are listeners. Everything that only wants to react, which is every effect, polls.

    The one call that reads a value

    The twenty-first call is different. Inside SimpleScene.callback, run by every 3D scene in bi-won, sits:

    # hmhmhm, it worked a moment ago
    # if this works I'll eat my shoe
    event = Event()
    if getEvent(EC_NOTE_CONTROL, 0, 6, event):
        # maybe this should be more!
        for mesh in meshes:
            mesh.red.setTargetValue(1.0 - event.volume)
            ...

    (The comments are Dutch in the source.) Channel 0 is the first pad and analog button 6 is its left trigger, held. So the released demo carries a live dimmer: squeeze the left trigger during any scene and every mesh fades toward black in proportion to the pressure, and stays there after release until a colour cue resets it. It works because NOTE_CONTROL carries volume as 0 to 1. The pad’s NOTE_ON sends the raw 0 to 255 reading instead, so the same field means two different things depending on the command.

    Loose ends

    • Fields nobody sets. EC_MODIFIER and the wheel, wheelx and wheely fields were for the analog sticks; the code that sent them is commented out in the pad generator, though SWIG still exports them to Python.
    • Stamped one frame late. Generators run before timer::update(), so every event carries the previous frame’s time.
    • Generators never leave. EventListener’s destructor unregisters it; EventGenerator’s is empty, and nothing calls removeGenerator. Deleting a generator would leave a dangling pointer to be called next frame. The player never deletes one, so it never bites.
    • Recording on a disc. The recorder appends to d:\demos\demo\. That works on a devkit’s hard disk; from a DVD the stream fails, and the recorder quietly checks good() and drops everything.
    • Ordering by typo. EventLess, used by every event set, compares velocity to volume in one branch (already in the bug list), so sets of events with equal times are not reliably ordered.

    Sync comes from patching libmodplug

    There is no sync track. In modplayer/snd_fx.cpp the player’s note-processing loop was patched to call mpeg.injectInstrumentEvent(instr) whenever an instrument is triggered. Those surface as EC_NOTE_ON events on channel 32, and addMapping names them, so the musician’s instrument choices become the demo’s cue sheet.

    The same manager takes joypad events. EventRecorder appends live presses to recorded_events and EventPlayer replays them, so a coder could jam cues on the pad and keep them. The D-pad is meant to seek ±3 s and holding BACK to delete recorded events; the navigation section shows what actually happens.

    NameXM instrumentsUsed for in bi-won
    # bi-won/pompom.py
    modplayer = 32
    addMapping(modplayer, 23, "bass")
    addMapping(modplayer, 3,  "bass")
    addMapping(modplayer, 23, "revbass")   # overwrites 23
    ...
    # bi-won/util.py, SimpleBlur
    def callback(self):
      for event in self.m_events:
        if getEvent(EC_NOTE_ON, event):
          self.mix.setTargetValue(self.highv)
          self.mix.setFixPointDamping(0.9995)
          self.mix.setDamping(0.97)

    Module position is also exposed: getModuleOrder() gates effects to song sections, e.g. the coat overlays only fire in orders 9–18 and the credits scroller starts at order 36.

    A RumbleListener in the player shakes all four pads on any event named "blur", decaying by 0.9 a frame. bi-won never maps that name.

    The sync patch: libmodplug announces every instrument it triggers

    bi-won’s music is _rf02701.xm, a FastTracker 2 module titled “_funk classics part1”: 24 channels, 49 patterns, 59 orders, at speed 3 and 140 BPM throughout the demo. That makes a row 53.6 ms and every 128-row pattern exactly 6.857 s. Below is every hit the patched player reports for the six mapped names, in the demo’s 5:32, counted from the module’s instrument column.

    Grey lines are pattern boundaries (every 8th labelled with its order number); shaded bands are the SI_A scenes. Every scene start in pompom.py sits on a pattern boundary: blob at order 1 (6.9 s), city at 9 (61.7 s), scene1 at 19 (130.3 s), tunnel at 27 (185.1 s), origblob at 35 (240.0 s), blob again at 39 (267.4 s). The second-based schedule is the song’s structure, rounded.

    Three edits to the player, one new class in the engine

    snd_fx.cpp, in CSoundFile::ProcessEffects. Where the mixer handles an instrument change on a channel, it now calls mpeg.injectInstrumentEvent(instr). The commented-out line above it shows an earlier attempt: a 32-bit mask, which would have capped sync at 32 instruments.

    modplug.cpp. A new ModPlug_getPosition() returns order, pattern and row, which the player exposes to Python as getModuleOrder() and getModuleRow().

    sound_player.cpp. A new Xbox streamer: one looping DirectSound buffer of 14,112 bytes, refilled half at a time when the play cursor crosses the midpoint.

    pompom::ModulePlayerEventGenerator. Collects injected instruments in a std::set and, on the next updateGenerators(), emits each as an EC_NOTE_ON on channel 32 with velocity and volume fixed at 1 and recorded=true, so the joypad recorder never writes module hits to disk.

    // modplayer/snd_fx.cpp, ProcessEffects()
    pompom::ModulePlayerEventGenerator& mpeg =
        pompom::ModulePlayerEventGenerator::instance();
    ...
    if (instr) {
    //  if (instr<32)
    //      instrumentMask|=1<<(instr-1);
        mpeg.injectInstrumentEvent(instr);
        InstrumentChange(pChn, instr, bPorta, TRUE);
        ...
    }
    
    // pompom/src/modplayereventgenerator.cpp
    for (it = instruments.begin(); ...) {
        Event e;
        e.channel = 32;  e.note = *it;
        e.command = EC_NOTE_ON;
        e.volume = e.velocity = 1.0f;
        e.recorded = true;
        e.time = timer::getTime();
        events.push_back(e);
    }
    instruments.clear();

    How a hit travels from the mixer to the screen

    Each frame the main loop runs nav.update() (which calls updateGenerators()) and then modplayer_update(). When the play cursor has crossed into one half, the player mixes the other half, which plays after the current one ends. Rows mixed in that pass inject their instruments then, and the effects see them one frame later. By the code’s arithmetic the picture leads the sound by roughly 45 to 145 ms, before any DAC latency, which only widens the lead.

    What the design implies

    • Instruments, not notes. Pitch, channel and volume are dropped, so a cue is “instrument 3 played somewhere”. The volume-to-colour code in util.py (“if this works I’ll eat my shoe”) can never get a real volume from the module.
    • Hits are quantised to 80 ms. One mix pass covers about 1.5 rows, and the std::set keeps one hit per instrument per pass. In bi-won, 30 pairs of “bass” hits sit one row apart and can arrive as one.
    • Events last exactly one frame. updateGenerators() clears the list first; every node that polls getEvent during that frame’s render sees the same hits.
    • Two clocks. The scheduler runs on timeGetTime(); the music runs on the audio hardware. They stay together only while every frame finishes inside 80 ms.

    Where it slips

    • Seeking leaves the music behind. Nothing calls a ModPlug seek. The D-pad asks the WMA player for the new time, gets 0 back, and restarts the visuals at 0:00 while the song plays on; the scheduler’s 50 Hz re-simulation after a backward seek gets no module cues at all.
    • A slow frame stalls the song. If a frame takes longer than the 80 ms half-buffer, the looping buffer replays stale audio and the module falls behind the schedule for good. The main loop’s “! Low framerate” warning was meant to catch this at 100 ms, but a type error means it never fires.
    • Mono played as stereo. ModPlug renders 16-bit mono at 44.1 kHz into a buffer declared as 16-bit stereo at 22.05 kHz. The byte rates match, so tempo and pitch are right, but alternate samples go to the left and right speakers.
    • The song outlives the demo. At constant tempo the module runs 6:56; the player stops at the schedule’s 5:32 and never refills the looping buffer again.

    The xgui timeline: the editor screen that was never switched on

    xgui is 780 lines in develop/ only: a Window base class, a WindowManager that draws every registered window, one pass-through vertex shader and the 456-line TimeLine. The navigation code above drives it, but the call that draws it is commented out, so nobody watching the demo has seen it. Below it is rebuilt from generateTimeLine(), with the same layout, colours and rules, fed with bi-won’s real schedule and the cues its module fires.

    Play, then hold BACK to sweep a selection on the highlighted lane; on release the ticks in it are deleted, as TimeLine::deleteEvents does. The timeline only knows cues it has already received, so the part right of the red playhead stays empty unless you tick “after a rewind”. Lanes appear, and squeeze, as new event names arrive. Bar labels are the C++ effect names; the real overlay adds each effect’s usage count in brackets. The free-memory figure was read live from the console, so it is left blank here.

    How it draws

    Everything is a flat-coloured rectangle. addRect writes six vertices, position and RGBA, straight into a vertex buffer, and window.hl copies the position to the output unchanged. Coordinates are therefore clip space, −1 to 1 with y pointing up, and the layout is in those units. The timeline is built at (−0.75, −0.75), 1.5 wide and 0.65 high: the middle three quarters of the screen, along the bottom. The header still has the older size in a comment.

    Inside that box the left 10% is lane names and the rest is time, 10 seconds back and 10 ahead of the scheduler’s clock. The bottom 30% holds the five scheduler slots, SI_A at the bottom and SI_SUPER at the top. Colours come from a counter that steps through seven RGB combinations per job, in the scheduler’s start-time order. A job that is running gets its bottom edge pulsing with a cosine of about three seconds. The top 70% holds one lane per event name with a white tick for each NOTE_ON. A darker grid line every five seconds carries the time label, and the free-memory bar sits above the box.

    The whole mesh is rebuilt every frame into a buffer of 24,000 vertices, room for 4,000 rectangles, with no bounds check. bi-won’s busiest 20 seconds hold 392 cue ticks plus a few dozen bars and grid lines, so it would have held.

    What it knows, and what it costs

    TimeLine is an event listener, so it sees every named event: module cues, live pad presses and recorded playback. It keeps them all in a std::set and never removes one except through a selection. By the end of bi-won that is 3,279 module cues, and every frame it walks all of them to find the few in the 20-second window. Lanes are numbered in the order names first arrive: in bi-won revbass at 0:00, then bass, chat, strings, bright and finally schuif at 2:08.

    Deleting works on the timeline’s own copy as well as on the recorded events. Sweep across the bass lane and the module’s bass ticks vanish from the screen, though the module keeps firing them and the effects keep reacting.

    Some of xgui was abandoned partway. drawable.h is an empty file. windowdraw.h declares a WindowDrawer singleton whose only member is void drawWindow, with no parameter list or semicolon; it would not compile, and nothing includes it. Trunk’s player includes the xgui headers and its project lists ../../xgui/include, but trunk has no xgui folder, so trunk’s player only builds next to a develop checkout.

    The Python layer: a demo is one script plus a kit of subclasses

    The engine has no demo-specific C++. A demo is d:\demos\demo\pompom.py, run once by an embedded Python 2.2.1 to build the effect graph, load the scenes, book the scheduler and start the music. From then on C++ calls back into Python every frame. bi-won is 338 lines of script on top of util.py, a 515-line kit of reusable subclasses.

    Boot to first frame

    1. Redirect output. initScripting() reopens stderr as d:\python_errors.txt and stdout as d:\python_out.txt, because there is no console.
    2. Start Python. Py_Initialize(), then init_demoscript() registers the SWIG module, which is linked into the .xbe rather than loaded from a DLL.
    3. Run the script. PyRun_SimpleFile executes all of pompom.py while the loading screen shows. This is where every texture, scene pack and module gets loaded.
    4. Hand over. The render loop starts. Each frame the scheduler calls processCallbacks() on the root effect of each slot, which calls callback() on that node and recurses through its inputs, so every connected Python subclass runs once a frame.
    5. Stop. After the schedule’s length, Py_Finalize() runs, wrapped in a try whose comment reads “probably some jokes about resources not being destroyed properly” (in Dutch).

    What is on the D: drive

    d:\demoplayer.xbe          the player, Python compiled in
    d:\script\demoscript.py    SWIG shadow module, 3,011 lines
    d:\lib\util.py             bi-won’s kit, plus stdlib .py files
    d:\demos\demo\pompom.py    the demo
    d:\demos\demo\*.lzma *.png *.xm
    d:\python_errors.txt       stderr
    d:\python_out.txt          stdout
    d:\python_exception.txt    meant for runtime errors

    The port is small. getpath.c hard-wires the search path to D:\script and /lib, the program name to D:\default.xbe and the current directory to D:\. 23 C modules are compiled in (math, struct, time, cPickle, cStringIO and others); os, signal and sha are commented out. There is no site.py, so every boot logs “'import site' failed”. bi-won’s run.bat shows the loop: nmake, copy pompom.py and util.py to the devkit, reboot it.

    How Python subclasses C++

    demoplayer/scripting/demoscript.i is 187 lines; SWIG turns it into 21,243 lines of C++ wrapper. It exposes pompom’s textures and events, fxlib’s sliders, scheduler and effects, liblib’s scene objects and the module player. On 23 classes it switches on directors: SWIG generates a C++ subclass whose virtual methods call a Python method of the same name if one exists. So a Python class can inherit Blur or Scene, override callback(), and C++ calls it as if it were native.

    %module(directors="1") demoscript
    %feature("director") Scene;
    %feature("director") fx::Blur;
    %feature("director") fxcore::EffectNode;
    ...
    #define dynamic_cast reinterpret_cast   // !

    That last line is there because both the player and fxlib build with RTTI switched off, and SWIG’s wrapper needs dynamic_cast 73 times. With the redefinition every check “is this C++ object a Python director?” succeeds, and the wrapper reads director fields from wherever they would sit in an ordinary effect. SWIG uses that check to stop a Python override that calls its own C++ base method from calling itself forever. bi-won never makes such a call, so the garbage read never matters.

    util.py, the kit

    ClassInheritsWhat its callback does

    Highlighted rows are the seven classes bi-won uses. SimpleScene, the biggest, carries a Dutch comment: “NOT SIMPLE AT ALL!”

    When the script breaks

    A failure while pompom.py is loading reads python_errors.txt back (up to 10,000 bytes) and shows it on a blue screen headed “Script breakage (Someone should fix detailed information:))”.

    A failure inside a callback() takes another path. SWIG’s director:except hook points stdout at python_exception.txt and calls PyErr_Print(), but that function writes to stderr, so the traceback goes to python_errors.txt and python_exception.txt stays empty, as bi-won’s copy is. The screen then shows only a chain of file:line:function entries. They come from a patch in Python’s own traceback.c that copies each frame into a global buffer:

    // AVOOZL HACK
    global_error_hack = malloc(10000); // MEMORY LEAK, BUG! JAY! (AVOOZL)

    The screen shows where it broke, never what the error was. bi-won’s log has the real case: pompom.log ends with “Director method exception, util.py:515 callback, pompom.py:196 onCityBass”, and only the text file says AttributeError: 'module' object has no attribute 'sample'. random.sample arrived in Python 2.3, and the script now picks with random.choice five times.

    The patch has a gap. The buffer is only allocated when a traceback is printed. A syntax error in pompom.py prints none, leaving the pointer null, and building a std::string from it would crash the player instead of showing the error.

    Reading the script

    # bi-won: the whole timeline
    sched = SchedulerSingleton_instance()
    sched.schedule(7,  62-7, blob,   SI_A, 0)
    sched.schedule(62, 67,   city,   SI_A, 0)
    dist.connectOutput(blur, "in")
    sched.schedule(0,  32,   blur,   SI_POST, 0)
    sched.schedule(7, 5*60+21+2+2, imgSeq, SI_SUPER, 0)
    playModule("d:\\demos\\demo\\_rf02701.xm")

    The arithmetic left in the lengths (5*60+21+2+2, 328-184+2+2) reads like timing nudged by ear on the devkit. pompom.py.bak shows an earlier pass: instrument 4 was mapped to "bass2", a koru_drinker.tga overlay and a back1.png background were in. When 4 was folded into “bass”, every "bass2" listener in the current script went dead.

    SimpleScene takes a probability p. Each frame it rolls once; if the roll misses, that frame’s cue is skipped and a “miss” callback runs instead (the city blacks out its buildings). A miss is never followed by another. The roll uses the engine’s frand(), a wrapper on C rand() that nothing ever seeds, so every boot starts from the same sequence. The outcome still drifts, because the number of rolls depends on the frame rate.

    3ds_build turns a Max export into baked meshes and a shader per material

    The artists’ scenes never reach the Xbox as models. A makefile rule (.ase.lzma in bi-won/makefile) runs two command-line tools and a compressor over each ASCII export. Every runtime look, from transparency to wobbling noise to growing curves, is decided here and compiled into a vertex shader.

      Parsing: an LLgen grammar and a global scene

      aseparse.g (1,025 lines) is an LL(1) grammar for the LLgen parser generator, paired with a 252-line flex scanner, asetok.lex. Parse actions build straight into a global Scene* the_scene (“thanks to some global magic we now have a scene”). Any syntax error prints >> BREAKAGE AT LINE n and exits. If a .skn file of the same name exists, its bone weights are loaded too; bi-won’s blob.skn is one.

      The tool is plain C++ with POSIX headers (a stand-in unistd.h sits in the folder for Windows). Trunk holds a Linux build: .o files and libscene.so.

      Baking is ambient occlusion, not radiosity

      The function is called simpleradiositytest, but it measures how open each vertex is. For meshes whose name contains _R_, it nudges each vertex 0.1 units along its normal, fires random rays into the hemisphere through an octree, and stores 1 − hits/rays as that corner’s brightness. Results are cached by position, so shared vertices are traced once.

      /PP 50 rays/P 250 rays/F 2,500 rays/E expensive view direction

      bi-won’s makefile always passes /P. A full photon mapper (4M-photon kd-tree, 256k photons per spot or omni light) and rectangle and triangle packers for lightmap atlases are in scenelib, but only test functions call them, so no lightmaps ship.

      Max settings become render flags

      Materials are classified in scenelib/scene.cpp from what the artist set in Max. Flags change the generated shader and the submesh sort order; at the 2004 snapshot several are no longer acted on when drawing.

      In 3ds MaxFlagEffect at runtime

      One generated shader per material, skin and pass

      savertest() (despite its name, the real exporter) writes geometry_only.pck, then walks the materials. Each gets a base shader, plus a variant for every skinned object that uses it (with its bone list and the most bones any vertex uses), plus extra passes when the material needs them. The Shader class (1,174 lines) assembles HLSL from parts: per-light blocks for omni and spot lights with attenuation, diffuse and specular, reflection and refraction coordinates, bone skinning, Perlin noise displacement built from noise tables in constants, and a curve renderer that turns splines into tapered, bumpy ribbons.

      Every constant the shader needs is allocated by a ConstManager and recorded in a matching .nfo: register, object number, attribute. At runtime fx::Scene reads that map and fills the registers each frame, several of them straight from the mesh’s FixedSliders. That’s the wire that lets one line of Python warp a mesh.

      # bi-won/util.py, on a cue
      mesh.noiseAmplitude.setTargetValue(25)
      mesh.curveLength.setTargetValue(frand(0,1))
      
      // fxlib/src/scene.cpp, every frame, per .nfo entry
      case CM_NOISE_PARAMETERS:
        shader->vectorConstants[reg] = Vec4(mesh->noiseAmplitude,
                           mesh->noiseFreq, mesh->noiseOffset, 0);
      case CM_CURVE_PARAMETERS:
        shader->vectorConstants[reg] = Vec4(mesh->curveTaper,
                           mesh->curveLength, mesh->curveWidth, 0);
      
      // shad_NNNN.hl, generated
      float curve_length = gen_c3.y;   // CurveParameters

      Attributes the generator knows: WorldEyePosition, LightPosition, DiffuseColor, AttenuationPair, SpotAnglePair, SpotDireciton (sic), BonesMatrix, GlobalTextureTransform, 1D/2D/3D NoiseTable, NoiseParameters, ColorModulation, CurveParameters, CurveBumpParameters.

      An IFF-style pack, written by destructors

      Every block in a pack is a four-letter tag, a 32-bit length and a body. llStreamPos writes the tag and a placeholder xxxx in its constructor; its destructor seeks back and patches in the real length. Nesting chunks is just nesting C++ scopes.

      {
        llStreamPos lsp("SHD1", outstr);  // "SHD1" + "xxxx"
        llserialize(outstr, asm_code);
      }                                   // ~llStreamPos patches size

      shaderpacker compiles each shad_NNNN.hl with NVIDIA’s Cg runtime to the vs_1_1 profile and stores the assembly text, not bytecode; the Xbox assembles it at load time with XGAssembleShader. It then concatenates the shaders with the geometry into geometry.pck.

      bi-won’s five scenes shrink 18× on the way to the box

      Bytes on disk in trunk/bi-won: Max ASCII export, packed geometry with shaders, and the shipped LZMA (-lp2 -lc7 -pb4, tuned away from the defaults for binary float data). The binary pack alone is 3.3× smaller than the text; LZMA takes it another 5.6×.

      liblib’s scene format: a chunked triangle soup that carries its own shaders

      liblib is the 3,194-line loader for the packs 3ds_build writes. Writer and reader were meant to share headers, with #ifdef LL_LOADER switching on the loading half, but the copies have drifted: llobject.h, llmesh.h, lltriangle.h, llscene.h and llanimation.h all differ between liblib/include and 3ds_build/scenelib. The breakdown below comes from parsing bi-won’s five packs with a reader written from the loader code; every chunk length checked out to the byte.

      The grammar

      SCNE
        int nTextures   TXTR × n   string file, int w, h, slot, len, JPEG bytes
        int nMaterials  MATR × n   ambient, diffuse, specular (3f each),
                                     shine, strength, opacity, map strengths, map indexes
        int nObjects    OBJC × n   string name, int nr, parent, mirror
                          KEYS        position, rotation, scale keys
                          MESH | CAMS | LGHT | SHPE
      MESH  string name, int nTris
        TRIS × k   int usage, lightmap, material, difmap, refmap
                   [int nBones, bone object × nBones]   if usage has SKIN
                   int n, then n triangles × 3 vertices
      SHDR  int n
        SNFO { MSHD material, skinObject, pass, override,
                 nConst × (register, object, attribute) }
        SHD1   string: vs_1_1 assembly from Cg

      Every chunk is a tag and a 32-bit length. On load, llReadPos checks the tag in its constructor and, in its destructor, that exactly that many bytes were consumed; otherwise it throws. Its Dutch comment: “crack. Hint (if readsize=0): check you didn’t make an anonymous instance, idiot.” A nameless llReadPos(...) is destroyed on the same line.

      Where the bytes go

      Triangle data is 72% to 97% of every pack. origblob has the lowest share: 264 KB of animation keys, a quarter of the file.

      One vertex, from usage bits

      BitOn diskIn the vertex bufferGPU bytes

      bi-won uses usage 43 (position, normal, UV, radiance) almost everywhere: 40 bytes a vertex on disk, 32 in memory, with the baked occlusion riding in position.w. Skinned blob parts use 59. Nothing is indexed: each triangle owns three vertices, copied straight into a Direct3D vertex buffer, which is also why LZMA finds so much to squeeze.

      Loading, linking, looking up shaders

      A .lzma name is first decompressed to a temporary file, z:\banaan.pck (“banana”), on the cache partition, then read with an ordinary ifstream. Objects are built by a factory that peeks at the next tag (typeLookAhead) and seeks back. After loading, the scene links parents, submesh materials and texture maps by index, and fetches each submesh’s shader by (material, skinned object, pass), falling back to (material, −1, pass) for unskinned use.

      The writer stores “no parent” as 0, not −1, and the loader throws on −1. All of bi-won’s objects have parent 0, there is no object 0, so objects[0] quietly inserts a null and every object ends up a root.

      Textures are embedded through ImageMagick’s Magick++. The writer works out PNG or JPEG from the extension, then encodes JPEG regardless, so alpha never survives. A texture whose filename contains input_a or input_b becomes a live slot instead (slot −2/−3) that fx::Scene fills from its a and b inputs, putting another effect chain onto a 3D surface.

      Animation and cameras

      KEYS holds three key lists. Positions are interpolated linearly; rotations are stored as axis and angle and slerped as quaternions; scale keys carry their own axis. Each list remembers its last key, so forward playback never searches, and each object caches its world matrix per timestamp so a parent shared by many children is evaluated once a frame. A hard-coded sign flip on the translation row converts Max’s coordinates, with an extra_mirror_transform flag for mirrored objects. Cameras store time and field of view per key (1,680 bytes each in city).

      Runtime extras hang off every object, not just meshes: the 12 FixedSliders from the shader section and a list of Transformations that Python can append, multiplied in before the animated transform.

      Python addresses objects by position, and city’s index 1 is a light

      getObjects() returns every object in node-number order (numbered from 1), meshes, cameras and lights mixed. bi-won’s script picks city objects by index. The pillars (12, 13, 15, 16, 17) are right, skipping index 14, a plane. But the six “buildings” the script colours and scales on bass include index 1, which is Omni01, the scene’s only light. Colour sliders on a light are never read, and the Scaling transform it receives moves the light itself, so the bass most likely nudges the city’s lighting too.

      IndexObjectTypeTrianglesbi-won’s script uses it as

      Which demos this code can account for

      The player is generic: it always loads d:\demos\demo\pompom.py, so a demo is a script, a data folder and a module. What the dump itself shows about the four titles:

      DemoEvidence in this dumpStatus
      bi-wonFull folder: pompom.py, util.py, 5 compressed scenes, 13 .max sources, 27 PNG/TGA overlays, XM module _rf02701.xm, logs and captures.Rebuildable
      Polar Bear AlertOnly a commented-out loading caption in demoplayer/src/main.cpp:93: “loading `polar bear alert` by kaleido”. So the player was used for it.Engine only
      MicheraNo mention in any file.Not in dump
      Harry BoterhamNo mention in any file.Not in dump

      If those demos shipped on this engine, their scripts would look like bi-won’s: same util.py vocabulary, different scenes and cue mappings. Their data folders would have to come from elsewhere.

      Thirty-one bugs and traps found reading it

      The comments, translated from Dutch

      History, from the SVN metadata

      Repository svn://wagnya.demon.nl/var/services/svn/kaleido, working copy at revision 86. The .svn/entries files name two authors, Edwin (2,008 entries) and jrk (3,074), with file commits dated June to November 2004: 2,515 in June, 2,390 in July, 38 in August, 139 on 21 November. The last commit, r86, is 21 Nov 2004 21:43 UTC.

      bi-won/pompom.log opens on 25 Jan 2004, so the engine ran on the devkit months before this repository existed. develop/ was last touched in early August and still carries xboxcore, xgui and the solution file; trunk/ was updated in November and gained bi-won.

      The developer’s own TODO (develop/TODO.txt)

      Translated: clear render states before showing thrown errors; named Python variables you can tweak live on the Xbox with an on-screen slider; a pause button that keeps re-rendering the current scene with updated shaders; curves for rings in 3ds_build; shader sync without repacking; better “magic” materials in MaxScript; a one-button save-and-nmake; versioned pack files; and a file watcher so the demo reloads changed assets.

      In 2004 they were asking for live-coding hot reload on a console.