Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions docs/decomp/AudioSystem.md
Original file line number Diff line number Diff line change
Expand Up @@ -159,3 +159,38 @@ The threshold balances DSound buffer allocation cost (static is cheaper but hold
## DSound Mixing Headroom

`CAudioBuf::SetAttenuation` writes attenuation in dB rather than linear. The attenuation is offset against the headroom configured by `DSoundManager` (1200 millibels by default) to leave room for mixed signal peaks. See `DSoundManager.md`.

## 5960 addresses

| Address | Function | Notes |
|---------|----------|-------|
| 0x00062750 | DSound_Init | Skipped in DVD boot mode (boot type 4). Reads `XGetAudioFlags`, `DirectSoundCreate(0, &ds, 0)`, then `SetMixBinHeadroom(bin, 0)` for all 31 mix bins and starts the DoWork thread (0x62680) |
| 0x000626b0 | XAppCreateSoundBuffer | Runs DSound_Init on first use, `CreateSoundBuffer` with a 0x18 byte desc, `SetHeadroom(1200)` |
| 0x00062960 | CAudioBuf dtor | Stop, Release |
| 0x000629a0 / 0x000629d0 | Lock / Unlock | Whole buffer from 0 |
| 0x00062a30 | CAudioBuf::Stop | Stop, then spins on GetStatus until it reports stopped |
| 0x00062ad0 | SetFrequency | `hz == 0 ? 0 : (int)hz` |
| 0x00062b90 | CAudioPump dtor | Quit event, join thread, close handles, Stop, Release, close segment events |
| 0x00062c90 | CAudioPump::ThreadProc | See below |
| 0x00062de0 | CAudioPump::Initialize | Segment events (manual reset), quit event, mutex, thread, buffer with flags 0x1a0, notify a block before each segment end |
| 0x00062fe0 | CAudioPump::Stop | Under the mutex: Stop, wait stopped, rewind, DirectSoundDoWork, reset events, zero counters |
| 0x00063060 | CAudioPump::Pause | `IDirectSoundBuffer_Pause(buf, flag)` under the mutex |
| 0x000630d0 | CAudioPump::FillBuffer | Lock a segment, GetData, zero the tail on a short read and drain |
| 0x000631c0 | CAudioPump::GetPlaybackTime | Counts cursor wraps |
| 0x00063220 / 0x00063290 / 0x000632b0 | CFilePump ctor / dtor / Initialize | Segment = whole blocks in 8 KB, 8 KB thread stack |
| 0x00061890 | CAudioClip ctor | |
| 0x000619f0 | CAudioClip::OnSetProperty | volume (0x38) and pan (0x3c) lerp when fade is set; url (0x30) dirties; isActive (0x28) |
| 0x00061ae0 | OnIsActiveChanged | |
| 0x00061b40 | Cleanup | |
| 0x00061ba0 | Initialize | `cd:` CD track, `st:` WMA soundtrack song, `.wav` file, `.wma` file |
| 0x00061d20 | wave loader | RIFF/WAVE/fmt check, up to 0x14 bytes of format, data <= 64 KB into a CAudioBuf, longer through CFilePump |
| 0x00062050 | Advance | |
| 0x00062290..0x00062420 | PlayOrPause, Play, Stop, Pause, getMinutes, getSeconds | |
| 0x000624a0 / 0x00062540 | CPeriodicAudioGroup ctor / Advance | |

The pump thread in 5960, when it finds a signaled segment that was marked filled, clears the mark
and drops the filled count before refilling it. That's how the count reaches 0 and the drain
branch stops the sound and runs OnAudioEnd. Theseus never decrements, so a stream that runs out
keeps playing silence until AudioClip notices (with sendProgress) that it played past its length.

The clip's end check in 5960 is `!playing && (!loop || !isActive) && transportMode == PLAY`.
157 changes: 140 additions & 17 deletions docs/decomp/FileOps.md
Original file line number Diff line number Diff line change
@@ -1,37 +1,160 @@
# File Operations & Copy System

File copy and filesystem nodes in the 4920-5960 retail binary.
The save copier and the file and folder nodes in the 5960 retail binary. Theseus's version is
`theseus/shared/file_ops.cpp` (Xbox build).

## Nodes

| Class | Address | FND String | Address |
|-------|---------|------------|---------|
| CCopyDestination | 0x00027878 | "CopyDestination" | 0x0002789c |
| CFile | 0x00022260 | "File" | (none) |
| CFolder | 0x000221fc | "Folder" | 0x0002220c |

CGameCopier is NOT a node (no class registration). It is a utility class used by the copy system, running file copy operations in a background thread.
| Class | Vtable | FND String |
|-------|--------|------------|
| CCopyDestination | 0x000276e8 | "CopyDestination" |
| CFile | 0x000220a0 | "File" |
| CFolder | 0x00022100 | "Folder" |

CGameCopier is not a node. It's a plain object owned by the save grid that copies saves on a
worker thread.

## CGameCopier

Fields: progress `+0x00`, error `+0x04`, done `+0x05`, thread `+0x08`, source and destination
device `+0x0c`/`+0x10`, their roots `+0x14`/`+0x18`, the queue `+0x1c` with count and capacity at
`+0x20`/`+0x24`, a 16 KB buffer `+0x28`, the internal error and already-exists flags at
`+0x2c`/`+0x2d`, the current entry `+0x30`, total and copied blocks `+0x34`/`+0x38`. A queue entry is
0x14 bytes: title id, save folder, `FILETIME`, and a copied flag.

| Address | Name | What it does |
|---------|------|--------------|
| 0x0003ec90 | RemoveAll | Frees roots, queue strings and queue, zeroes counts and block total, frees the buffer |
| 0x0003ed10 | Finish | Adds every copied save to the destination's title list (removing it first when it overwrote one), then RemoveAll |
| 0x0003eda0 | thread entry | Calls ThreadProc |
| 0x0003edb0 | CopyGame | One save, see below |
| 0x0003f420 | CreateDirectory | Narrows to 260 chars, `CreateDirectoryA`, nonzero result |
| 0x0003f480 | CopyDirectory | Creates the destination, copies every entry but `.` and `..`, recursing |
| 0x0003f700 | CopyFile | 16 KB read/write loop with progress, then copies the file times |
| 0x0003f830 | DeleteFile | `SetFileAttributesA(NORMAL)` then `DeleteFileA` |
| 0x0003f8a0 | DeleteDirectory | Deletes the contents, recursing; optionally the folder itself |
| 0x0003fae0 | ThreadProc | Runs CopyGame over the queue, stops at the first error |
| 0x0003fb40 | SetSource | Device number and a copy of its user data root |
| 0x0003fba0 | SetDestination | Same for the destination |
| 0x0003fc00 | AddGame | Queues a save, growing by 10; adds its blocks to the total |
| 0x0003fd00 | Start | Resets state, allocates the buffer, `CreateThread` (or runs inline if that fails) |

### CopyGame

```
dest = root\title; newTitle = CreateDirectory(dest);
dest += TitleImage.xbx;
if (newTitle || size(dest) == 0) CopyFile(src\title\TitleImage.xbx, dest);
if (exists(src\title\SaveImage.xbx) && size(dest\title\SaveImage.xbx) == 0) CopyFile(...);
internalError = 0; alreadyExists = 0;
dest = root\title\save;
if (!CreateDirectory(dest)) {
if (GetLastError() != 0xb7) { internalError = 1; return; } // ERROR_ALREADY_EXISTS
alreadyExists = 1; DeleteDirectory(dest, false);
}
h = CreateFile(dest, GENERIC_WRITE, 0, 0, OPEN_EXISTING, BACKUP_SEMANTICS, 0);
if (h != -1) { SetFileTime(h, &t, &t, &t); CloseHandle(h); }
if (!CopyDirectory(src\title\save, dest)) {
if (newTitle) dest = root\title;
DeleteDirectory(dest, true); return;
}
games[n].folder = copy of the name after the last '\' in dest;
dest = root\title\TitleMeta.xbx;
if (newTitle || size(dest) == 0) {
CopyFile(src\title\TitleMeta.xbx, dest);
if (internalError == 1) internalError = 0;
}
```

The sizes are read by opening the file for reading with every share flag and backup semantics;
one that won't open counts as empty. A missing title image or save image never fails the copy,
and neither does the title meta file, since the last line clears the error it would set.

### CopyFile

```
in = CreateFile(src, GENERIC_READ, SHARE_READ|SHARE_WRITE, 0, OPEN_EXISTING, SEQUENTIAL_SCAN, 0);
if (in == -1) { internalError = 1; return false; }
out = CreateFile(dest, GENERIC_WRITE, 0, 0, CREATE_ALWAYS, 0, 0);
if (out == -1) { CloseHandle(in); internalError = 1; return false; }
while (ReadFile(in, buffer, 0x4000, &n, 0)) {
if (n == 0) goto done;
if (!WriteFile(out, buffer, n, &w, 0)) break;
copied++; progress = (float)copied / (float)total;
}
internalError = 1;
done:
if (!internalError) { GetFileTime(in, &c, &a, &w); SetFileTime(out, &c, &a, &w); }
CloseHandle(in); if (!CloseHandle(out)) internalError = 1;
return !internalError;
```

### DeleteDirectory

Lists `<dir>\*.*`, skips `.` and `..`, deletes files with DeleteFile and folders with
DeleteDirectory(path, true); the first failure closes the listing, sets the internal error and
returns false. With removeSelf set it then calls `SetFileAttributesA(dir, NORMAL)` and
`RemoveDirectoryA`.

## CCopyDestination

Memory unit / HDD destination picker for game save copying.
Fields: pod `+0x1c`, (unused) `+0x20`, panelMU `+0x24`, panelMUHilite `+0x28`, panelText `+0x2c`,
panelTextHilite `+0x30`, console `+0x34`, memoryUnit `+0x38`, curDevUnit `+0x3c`, selDevUnit
`+0x40`, sourceDevUnit `+0x44`, spacing `+0x48` (0.4), isActive `+0x4c`, select `+0x50`, scroll
`+0x54`, scroll target `+0x58`, scroll start time `+0x60` (double), device list `+0x68` (9 ints),
device count `+0x8c`.

**Properties:** pod, podIcon, panelMU, panelMUHilite, panelText, panelTextHilite, console, memoryUnit, curDevUnit, selDevUnit, sourceDevUnit, spacing, isActive, select.
**Properties:** pod, panelMU, panelMUHilite, panelText, panelTextHilite, console, memoryUnit,
curDevUnit, selDevUnit, sourceDevUnit, spacing, isActive, select.

**Functions:** selectUp, selectDown.
**Functions:** selectUp (0x4d350), selectDown (0x4d380).

## CFile
### Advance (0x0004d110)

While isActive, the device list is rebuilt each frame in the order hard drive (8), then units 0..7.
The source device is left out, and so is any memory unit whose title array has no root; if that
unit was the current one it remembers the current unit was removed. If the current unit is listed
at a different row than `select`, `select`, the target and the scroll offset all jump there. Then
`select` is clamped to `0..count-1`. A new target starts a scroll at the current time; otherwise
an active scroll eases with `t = (now - start) * 4` (a quarter second), clamped to 1, which also
ends it: `scroll = target * spacing * t + (1 - t) * scroll`. Finally if `units[select]` differs from
curDevUnit it's stored and the script hears `OnDestinationUnitRemoved` (when the old one was
pulled) and then `OnCurDevUnitChange`.

File metadata node.
### Render (0x0004cf80)

**Properties:** name, type, path, length, date.
For each listed device: translate by `(0, scroll - i * spacing, 0)`, push the world matrix, draw the
pod, set selDevUnit to the device and call `UpdateMemUnitText`. The current device draws
panelMUHilite and panelTextHilite, the others panelMU and panelText; the hard drive then draws
console, anything else memoryUnit. Pop the matrix.

**Functions:** readText.
### selectUp / selectDown

```
if (count > 1 && 0 <= select - 1 < count) { // + 1 for selectDown
select -= 1; curDevUnit = units[select]; CallFunction("OnCurDevUnitChange");
}
```

## CFile

Fields: name `+0x1c`, type `+0x20`, path `+0x24`, length `+0x28` (-1 until listed), date `+0x2c`.

**Properties:** name, type, path, length, date. **Functions:** readText (0x31960).

## CFolder

Directory listing node.
Fields: path `+0x1c`, name `+0x20`, files `+0x24`, subFolders `+0x30`.

**Properties:** path, name, files, subFolders.
**Functions:** sortByName, sortByType, sortByDate, sortByLength (0x31f50..0x32010), each a qsort
of the files with `_wcsicmp` on name or type, `CompareFileTime` on the date, or a size difference.

### Refresh (0x00031b50)

**Functions:** sortByName, sortByType, sortByDate, sortByLength.
Setting `path` (OnSetProperty 0x31b30 checks offset 0x1c) calls Refresh. It copies at most 255
characters of the path, appends `\*.*` and lists it. When the listing opens, the folder's name
becomes whatever follows the last `\`. Entries with hidden, system (`& 6`) or temporary (`0x100`)
set are skipped. A folder entry becomes a new CFolder with `path\name` and the name. A file entry
becomes a CFile with a CDateObject holding `ftLastWriteTime`, the name up to the last `.`, the
lowercased extension as type (empty without one), `path\name` and `nFileSizeLow`.
118 changes: 118 additions & 0 deletions docs/decomp/SavedGameGrid.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
# SavedGameGrid

The Memory blade's list in the 5960 retail binary. It shows every title on one device, each with a grid of
save icons, plus a soundtrack row on the hard drive. Theseus's version is
`theseus/shared/savegame_grid.cpp` (Xbox build). Vtable 0x000267b0.

## Fields that matter

curTitle `+0x8c`, scroll `+0x88`, icons per row `+0x84` (4), last title `+0x90`, curGridItem
`+0x94`, icon row scroll `+0xa4`, curDevUnit `+0xb0`, copyProgress `+0xb4`, freeBlocks `+0xb8`,
isActive `+0xc0`, busy `+0xc1`, preferred column `+0xc4`, total blocks `+0xd0`, scroll target
`+0xd4`, scroll start `+0xd8` (double), copying `+0xe4`, soundtrack row and count `+0x100`/`+0x104`,
Live account row and count `+0x108`/`+0x10c`, cached title and item sizes `+0x110`/`+0x114`,
copy dots tick/count/text `+0x118`/`+0x11c`/`+0x120`, list thread `+0x920`, size worker thread
and events `+0x924..+0x930`, query pending `+0x934`, quit `+0x935`, list end time `+0x938`,
delete thread `+0x940`, deleting `+0x944`.

## Functions

| Address | Name | Notes |
|---------|------|-------|
| 0x00047320 | constructor | Defaults, three events, the size worker (0x47c70) |
| 0x00047520 | destructor | Releases 25 nodes, stops the worker |
| 0x000476f0 | GetTitleCount | Titles + soundtrack row + Live account row |
| 0x000477b0 | title blocks | Soundtrack row sizes `c:\tdata\fffe0000\music`; Live row its count |
| 0x00047970 | GetTitleName2 | Device row: "Xbox Hard Disk", the MU's name, or "memory unit %d%c" |
| 0x00047bb0 | TitlesEnumThread | Update the device, place the soundtrack and Live rows |
| 0x00047e50 | Advance | See below |
| 0x00048450 | GetUpdateString | "Copying" plus 0..3 dots, every 500 ms |
| 0x00048530 | OnSetProperty | curDevUnit (0xb0) selects the first row at once; curTitle (0x8c) selects; isActive (0xc0) going off cancels the size query |
| 0x00048690 | RenderIconRow | |
| 0x000488a0 | Render | |
| 0x00048910 | RenderLoop | See below |
| 0x00049410 | SelectTitle | |
| 0x00049590..0x000497b0 | selectUp/Down/Left/Right | |
| 0x00049840 | setSelImage | |
| 0x00049940..0x0004a3e0 | Format* | Name from SaveMeta.xbx `Name`, time from the folder, sizes from the cache |
| 0x0004a700 | GetSavedGamePath | `<drive>:\<save>`, U: on the hard drive |
| 0x0004aac0 | StartSavedGameCopy | Folder blocks plus whichever of TitleMeta/TitleImage/SaveImage the destination lacks |
| 0x0004b160 | title id parse | 8 hex digits |
| 0x0004b1d0 | DeleteThread | |
| 0x0004b630 | StartDelete | |
| 0x0004b6b0 | CanCopy | |

## Advance

```
CNode::Advance;
if (curDevUnit == -1 || !isActive) return;
if (!listThread) {
if (device mounted && dirty) {
rows = -1; endAt = now + 1.0; OnUpdatingTitlesBegin;
listThread = CreateThread(TitlesEnumThread);
if (listThread) return;
TitlesEnumThread(); OnUpdatingTitlesEnd;
}
} else {
if (now <= endAt || thread still running) return;
OnUpdatingTitlesEnd; CloseHandle; listThread = 0;
}
if (copying) {
progress changed -> OnCopyProgressChanged;
error -> Finish, OnCopyError; done && now >= start + 0.5 -> Finish, OnCopyComplete;
return;
}
if (deleting) { thread done -> OnDeleteEnd, OnSelChange, restart pulse; return; }
if (device unmounted) { OnDeviceRemoved; curDevUnit = -1; return; }
if (dirty) return;
... size cache upkeep, wake the worker ...
free/total blocks = ceil(bytes / 0x4000) (total - 1); a failed query is 1 total, 0 free;
change (or new language) -> OnTotalFreeChanged, OnSelChange;
if (scrollStart) { t = (now - start) * 4; clamp, stop at 1; scroll = (1-t)*scroll + t*target; }
```

Theseus splits the size cache and free space work into helpers. It also invalidates its DLC
count cache when the list is rebuilt.

## RenderLoop

The frame is a rotation of -1.571 about -x times a uniform 0.05942 scale. Starting at `y = scroll`,
each row (the device row first, except on the copy destination view) is:

- pod at (-0.3292, y, -0.0271); the selected one, once settled, from a remembered matrix;
- header at the same spot, with its name at (-0.3292 - 0.05942, y + 0.05942, -0.0271 + 0.6 * 0.05942)
scaled 0.06442, tinted 170,170,170 when selected and 140,201,25 otherwise;
- `y -= 0.0092`; first icon row at (-0.3292, y, 0.01144), `y -= 0.2455`;
- second row at (-0.3301, y, 0.01144), `y -= 0.24499`, then further rows at -0.3412, up to three
visible rows, with the more-down arrow at (-0.17, y - 0.015) and more-up at (-0.17, y - 0.07);
- `y -= 0.09` between titles.

Icons sit `smallIconSpacing` apart. Rows stop drawing below -1.25 and only draw when
`y - 0.25 < 0.5`. Unselected rows draw at half strength, easing as the selection moves. Called with
render off, it returns the selected row's offset from the top, which SelectTitle scrolls to.

## SelectTitle

```
lastTitle = curTitle; curTitle = n;
if (device mounted && dirty) return;
clamp curTitle to the row count; items = grid items; rows = ceil(items / perRow);
target = -RenderLoop(false);
if (target != scrollTarget) { scrollTarget = target; instant ? scroll = target, start = 0.001 : start = now; }
pref = (pref >= 0 && item != -1) ? item % perRow : (pref != -1 ? 0 : -1);
if (pref == -1) { item = -1; rowScroll = 0; return; }
if (curTitle > lastTitle) { item = min(pref, items - 1); rowScroll = 0; }
else { item = items ? min(pref + (rows - 1) * perRow, items - 1) : -1; rowScroll = max(rows - 3, 0); }
```

5960 counts every grid item here; Theseus counts saves only.

## DeleteThread

With no item selected, the whole row goes: all soundtracks, the Live accounts, or a title. A title
is removed from the list and from `<udata>\<id>`. The publisher's `<pub>ffff` tdata folder goes too
when it was the publisher's last title. On the hard drive, `<tdata>\<id>` and the cache partition
also go, except for `fffe0000`. The rows below move up one. With an item selected, just that
soundtrack, account or save folder goes, and the selection and row scroll are pulled back into
range. Both cases reset the cached sizes.
Loading
Loading