From f7df05accbbe872c593dc0624cb77dae00a421cb Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:25:03 -0500 Subject: [PATCH 1/6] Rebuilt the title list from the binary Rewrote CTitleArray from the 5960 title collection code and folded the desktop copy of its header into the shared one. An old vs new harness over 400 generated memory unit and hard drive layouts printed the same 218,941 lines. --- docs/decomp/TitleCollection.md | 107 ++++- theseus/desktop/desktop_stubs.cpp | 2 +- theseus/desktop/titlecollection.h | 131 ------ theseus/engine/locale_node.cpp | 4 - theseus/shared/title_collection.cpp | 700 +++++++++++++--------------- theseus/shared/title_collection.h | 90 ++-- 6 files changed, 470 insertions(+), 564 deletions(-) delete mode 100755 theseus/desktop/titlecollection.h diff --git a/docs/decomp/TitleCollection.md b/docs/decomp/TitleCollection.md index 352e1b4..6e99118 100644 --- a/docs/decomp/TitleCollection.md +++ b/docs/decomp/TitleCollection.md @@ -1,25 +1,102 @@ # TitleCollection -Title and saved game scanner. Enumerates installed titles and their save data from the Xbox HDD. Backed by `title_collection.cpp` in the active source tree. +The list of game titles and their saves on one storage device, as the 5960 retail binary keeps +it for the memory screens. Nine arrays sit side by side: slots 0..7 are the memory units, slot 8 +the hard drive. Theseus's version is `theseus/shared/title_collection.cpp` (Xbox build); desktop +links empty stubs against the same header. -## CTitleArray +## Layout -The primary class. Scans title directories on the Xbox hard drive, reading metadata from the standard Xbox title files: +5960's array object is a lot bigger than Theseus's: past the root, dirty flag, count, capacity and +title pointer at `+0x00..+0x14` it carries a 0x700 byte Xbox Live account table at `+0x224` and its +count at `+0x924`, and the critical section at `+0x928`. Each title record is 0x28 bytes: id, name, +save count, saves (0x30 each), save blocks, content count, content list (0x34 each), content blocks, +total blocks, broken flag. A save record is the folder name (16 wide chars) at `+4`, the write time +at `+0x24`, flags at `+0x2c`. Theseus keeps only the title and save parts; Live accounts and +downloadable content are read by the save grid. -- **TitleMeta.xbx**: title name and publisher info -- **TitleImage.xbx**: title icon / thumbnail image -- **SaveMeta.xbx**: individual saved game name and timestamp -- **SaveImage.xbx**: saved game icon +## Functions -Each title entry maintains a sub-array of its saved games. The dashboard uses this to populate the Memory management screens. +| Address | Name | What it does | +|---------|------|--------------| +| 0x00041dd0 | constructor | Critical section, root `{0, ':', '\\'}`, empty list, dirty, Live account count -1 | +| 0x00041e40 | DeleteAll | Frees every title's id, name, saves and content, empties the list, marks dirty, optionally runs Update | +| 0x00041f20 | AddTitle | Reads `TitleName` (64 chars) from `\\TitleMeta.xbx`; "Broken Game" (translated) and the broken flag when that fails. Grows the list by 50 | +| 0x00042230 | Update | Lists `\*.*` under the lock and adds each folder, then sorts by name and scans every title's saves and content | +| 0x00042740 | GetSavedGameCount | Scans a title's saves the first time it is asked | +| 0x00042c20 | FindTitle | First id that matches with `_wcsicmp`, else -1 | +| 0x00042cb0 | AddSavedGame | Adds a save (and its title if new), resorts, resets the title's sizes | +| 0x00042e40 | RemoveTitle | Frees one title and closes the gap | +| 0x00042ef0 | RemoveSavedGame(n, s) | Closes the gap in the save list, resets sizes | +| 0x00042f40 | RemoveSavedGame(id, dir) | Finds the title and the save by folder name, then removes it | +| 0x00043390 | GetTitleTotalBlocks | Cached udata count plus tdata on the hard drive | +| 0x00043460 | ComputeTitleTotalBlocks | `GetDirectoryBlocks(\, 0x4000, recursive, cancel)` | +| 0x000434f0 | ScanSavedGames | Lists a title folder for save folders, newest first | +| 0x00043c30 | GetUData | Root, `c:\udata` for the hard drive, `""` when unmounted | +| 0x00043c50 | IsDirty | Mounted and dirty | +| 0x00043d00 | GetSavedGameImageName | Save image, title's save image, or the Xbox logo | +| 0x00044240 | IsPublisherExists | Any title id that shares the first 4 characters (`_wcsnicmp`) | -## Features +## Update -- **Sorted enumeration**: Titles can be retrieved in alphabetical order for display. -- **Block size calculation**: Computes the storage size of each title and save in blocks (the Xbox's user-facing unit of HDD space, 16KB per block). -- **Title image lookup**: Retrieves the icon texture for a given title ID. -- **Background update**: Directory scanning can run on a background thread with critical section protection around the title/save arrays. This keeps the UI responsive while the HDD is being enumerated. +``` +EnterCriticalSection(&lock); +if (root[0] == 0) { LeaveCriticalSection(&lock); dirty = 0; return; } +... Live accounts for this device ... +h = FindFirstFileA(narrow(udata + "\\*.*"), &fd); +if (h == -1) { + if (GetLastError() != 0x48f) dirty = 0; // ERROR_DEVICE_NOT_CONNECTED + LeaveCriticalSection(&lock); return; +} +do { if (fd.attrib & 0x10) AddTitle(widen(fd.cFileName)); } while (FindNextFileA(h, &fd)); +if (GetLastError() == 0x48f) { CloseHandle(h); DeleteAll(false); Leave...; return; } +CloseHandle(h); +qsort(titles, count, 0x28, by name); +for each title { + scratch = new CSave[0x1000]; + title.saveCount = ScanSavedGames(udata, title.id, scratch, NULL); + title.saves = new CSave[title.saveCount]; memcpy(...); delete[] scratch; + ... the same for downloadable content under tdata ... +} +LeaveCriticalSection(&lock); dirty = 0; +``` -## Integration +A device that drops out while being listed is treated as not there; anything else that stops the +listing still counts as a finished scan. Theseus leaves out the Live account and content parts, +and skips the `fffe0000` folder (the dashboard's own data), which 5960 lists like any title. -Not a node class. Used directly by `SavedGameGrid` and `CopyGames` to provide data for the memory management and file copy UI screens. +## ScanSavedGames + +Returns -1 straight away if the cancel event is set. Lists `\\*.*`; for each entry it +checks the cancel event (-1 when set), stops at 0x1000 saves, skips files, and for a folder zeroes +the record, keeps it only when `wcslen(name) + 1 < 0x11`, copies the name and `ftLastWriteTime` and +sets flag 2 (image unknown). The result is sorted with the newest save first. + +## GetTitleTotalBlocks + +``` +if (n < 0 || n >= count) return 0; +if (title.blocks == -1) { + title.blocks = ComputeTitleTotalBlocks(udata, title.id, cancel); + if (root[0] == 'c' && title.blocks >= 0 && wcscmp(title.id, L"fffe0000") != 0) + title.blocks += ComputeTitleTotalBlocks(tdata, title.id, cancel); +} +if (cancel && WaitForSingleObject(cancel, 0) == 0) title.blocks = -1; +return title.blocks; +``` + +The last line makes a count that was cut short get taken again next time. + +## GetSavedGameImageName + +``` +if (save.flags & 2) { + save.flags &= ~2; + path = udata\id\save\SaveImage.xbx; + if (DoesFileExist(path)) { save.flags |= 1; return; } +} +path = udata\id; +if (save.flags & 1) path += \save; +path += \SaveImage.xbx; +if (!DoesFileExist(path)) path = ; +``` diff --git a/theseus/desktop/desktop_stubs.cpp b/theseus/desktop/desktop_stubs.cpp index 04c13e0..efb29ab 100644 --- a/theseus/desktop/desktop_stubs.cpp +++ b/theseus/desktop/desktop_stubs.cpp @@ -6,7 +6,7 @@ #include "dashapp.h" #include "node.h" #include "runner.h" -#include "titlecollection.h" +#include "title_collection.h" #include "discmanager.h" #include "network.h" diff --git a/theseus/desktop/titlecollection.h b/theseus/desktop/titlecollection.h deleted file mode 100755 index 67be329..0000000 --- a/theseus/desktop/titlecollection.h +++ /dev/null @@ -1,131 +0,0 @@ -// titlecollection.h: desktop CTitleArray declarations. Counterpart -// to shared/title_collection.h; some Xbox-side fields are stubbed -// or backed by qcow2 reads through xbox_hdd.cpp. - -#pragma once - -#define MAX_SAVED_GAMES 4096 - -#define Dev1Unit1 0 -#define Dev1Unit2 1 -#define Dev2Unit1 2 -#define Dev2Unit2 3 -#define Dev3Unit1 4 -#define Dev3Unit2 5 -#define Dev4Unit1 6 -#define Dev4Unit2 7 -#define Dev0 8 - - - -#define BLOCK_SIZE 16384 // Should be max of hard drive and flash block size... - - -struct CSave -{ -// uint32_t m_dwID; - char m_szDirName[16]; - FILETIME m_filetime; - uint32_t m_dwFlags; - - bool SetDirName(const char* szDirName); - const char* GetDirName(); -}; - -#define SAVEFLAG_HASIMAGE 0x00000001 -#define SAVEFLAG_UNKIMAGE 0x00000002 - -class CTitle -{ -public: - char* m_szID; - char* m_szName; - int m_nSavedGameCount; - CSave* m_rgsaves; - int m_nSavedGameBlocks; - int m_nTotalBlocks; - bool m_bBroken; -}; - -class CTitleArray -{ -public: - CTitleArray(); - ~CTitleArray(); - - void Update(); - void DeleteAll(bool bUpdate = true); - - void SetRoot(char chNewRoot, bool bUpdate = true); - - int GetTitleCount(); - int GetTitleCount2(); - bool IsBroken(int nTitle); - const char* GetTitleID(int nTitle); - const char* GetTitleName(int nTitle); - const char* GetTitleName2(int nTitle); - int GetTitleTotalBlocks(int nTitle, HANDLE hCancelEvent); - - int GetSavedGameCount(int nTitle, HANDLE hCancelEvent = NULL); - const char* GetSavedGameID(int nTitle, int nSavedGame); - void GetSavedGameImageName(int nTitle, int nSavedGame, char* szPath/*[MAX_PATH]*/); - FILETIME GetSavedGameTime(int nTitle, int nSavedGame); - - void AddSavedGame(const char* szTitleID, const char* szDirName, FILETIME saveTime); - - bool IsValid() const; - bool IsDirty() const; - const char* GetTData() const; - const char* GetUData() const; - - void RemoveTitle(int nTitle); - void RemoveSavedGame(int nTitle, int nSavedGame); - void RemoveSavedGame(const char* szTitleID, const char* szDirName); - bool IsPublisherExists(const char* szPublisherID) const; - -protected: - int FindTitle(const char* szTitleID); - void AddTitle(const char* szTitleID); - - char m_szRoot [4]; - bool m_bDirty; - int m_nTitleCount; - int m_nTitleAlloc; - CTitle* m_rgtitle; - - CRITICAL_SECTION m_RootLock; - - friend class CTitleCollection; - friend void TitleArray_Init(); -}; - -/* -class CTitleCollection : public CNode -{ - DECLARE_NODE(CTitleCollection, CNode) -public: - CTitleCollection(); - ~CTitleCollection(); - - void Advance(float nSeconds); - - void SetLanguage(int nLanguage); - int GetTitleCount(); - CStrObject* GetTitleID(int nTitle); - CStrObject* GetTitleName(int nTitle); - - int GetSavedGameCount(int nTitle); - CStrObject* GetSavedGameID(int nTitle, int nSavedGame); - -// int GetTitleSavedGameBlocks(int nTitle); - int GetTitleTotalBlocks(int nTitle); - -protected: - int m_nCurLanguage; - - DECLARE_NODE_FUNCTIONS() -}; -*/ - - -extern CTitleArray g_titles [9]; diff --git a/theseus/engine/locale_node.cpp b/theseus/engine/locale_node.cpp index 123e56a..b967b34 100755 --- a/theseus/engine/locale_node.cpp +++ b/theseus/engine/locale_node.cpp @@ -10,11 +10,7 @@ #include "std.h" #include "theseus.h" -#ifdef _XBOX #include "title_collection.h" -#else -#include "titlecollection.h" -#endif #include "node.h" #include "runner.h" #include "locale_node.h" diff --git a/theseus/shared/title_collection.cpp b/theseus/shared/title_collection.cpp index b2787b0..8d9b602 100755 --- a/theseus/shared/title_collection.cpp +++ b/theseus/shared/title_collection.cpp @@ -1,8 +1,9 @@ -// title_collection.cpp: CTitleArray, the title-and-saved-game scanner. -// Walks installed title directories, parses TitleMeta.xbx / -// TitleImage.xbx / SaveMeta.xbx / SaveImage.xbx, supports background -// scanning with critical-section locking. Decompiled from the 5960 -// retail XBE; see docs/decomp/TitleCollection.md. +// title_collection.cpp: CTitleArray, the list of title folders and their +// saves on one device (U:\ style root on a memory unit, e:\udata on the +// hard drive). Rebuilt function by function from the 5960 retail XBE +// (0x41dd0..0x44240); see docs/decomp/TitleCollection.md. Theseus keeps a +// slimmer CTitle than 5960 (no Live account or content lists; those live in +// the save grid) and reads the hard drive from e:\ instead of c:\. #include "std.h" #include "theseus.h" @@ -13,29 +14,32 @@ #include "title_collection.h" #include "locale_node.h" - - CTitleArray g_titles [9]; +// TitleArray_Init() +// 5960 @ 0x41dd0 is the array constructor run over all nine slots at +// startup; the hard drive slot then gets its root. Memory units get theirs +// from the memory monitor as they're mounted. void TitleArray_Init() { - g_titles[8].SetRoot('c', false); - // NOTE: Memory units will be set as they are mounted... + g_titles[Dev0].SetRoot('c', false); } +// CTitleArray::CTitleArray +// Reconstructed from 5960 retail XBE @ 0x41dd0: +// InitializeCriticalSection(&lock); root = {0, ':', '\\', 0}; +// count = capacity = list = 0; dirty = 1; CTitleArray::CTitleArray() { - InitializeCriticalSection(&m_rootLock); - + InitializeCriticalSection(&m_lock); m_root[0] = 0; m_root[1] = ':'; m_root[2] = '\\'; m_root[3] = 0; - m_dirty = true; - m_titleCount = 0; - m_titleCapacity = 0; - m_titles = NULL; + m_count = 0; + m_capacity = 0; + m_list = NULL; } CTitleArray::~CTitleArray() @@ -43,485 +47,455 @@ CTitleArray::~CTitleArray() DeleteAll(false); } -void CTitleArray::DeleteAll(bool bUpdate /* = true */) +// CTitleArray::DeleteAll(bUpdate) +// Reconstructed from 5960 retail XBE @ 0x41e40: +// for each title: free(id); free(name); delete[] saves; +// free(list); list = count = capacity = 0; dirty = 1; if (bUpdate) Update(); +void CTitleArray::DeleteAll(bool bUpdate) { - for (int i = 0; i < m_titleCount; i += 1) + for (CTitle* t = m_list; t < m_list + m_count; t++) { - delete [] m_titles[i].m_id; - delete [] m_titles[i].m_name; - delete [] m_titles[i].m_saves; + delete [] t->m_titleID; + delete [] t->m_displayName; + delete [] t->m_saveList; } - - delete [] m_titles; - m_titles = NULL; - - m_titleCount = 0; - m_titleCapacity = 0; + delete [] m_list; + m_list = NULL; + m_count = 0; + m_capacity = 0; m_dirty = true; - if (bUpdate) - { - Update(); - } + if (bUpdate) + Update(); } -void CTitleArray::SetRoot(TCHAR chNewRoot, bool bUpdate /* = true */) +// CTitleArray::SetRoot(drive, bUpdate) +// Inlined into its callers in 5960: swap the drive letter under the lock +// (the scan thread reads it), then drop the list. +void CTitleArray::SetRoot(TCHAR chNewRoot, bool bUpdate) { - EnterCriticalSection(&m_rootLock); + EnterCriticalSection(&m_lock); m_root[0] = chNewRoot; - LeaveCriticalSection(&m_rootLock); + LeaveCriticalSection(&m_lock); DeleteAll(bUpdate); } -static int __cdecl SortTitleCompare(const void *elem1, const void *elem2) +// Titles sort by display name, ignoring case. +static int __cdecl CompareTitleNames(const void* a, const void* b) { - const CTitle* pTitle1 = (const CTitle*)elem1; - const CTitle* pTitle2 = (const CTitle*)elem2; - return _tcsicmp(pTitle1->m_name, pTitle2->m_name); + return _tcsicmp(((const CTitle*)a)->m_displayName, ((const CTitle*)b)->m_displayName); } -void CTitleArray::AddTitle(const TCHAR* szTitleID) +// Saves sort newest first. +static int __cdecl CompareSaveTimes(const void* a, const void* b) { - TCHAR szXbxFile[MAX_PATH]; - TCHAR szTranslate[MAX_TRANSLATE_LEN]; - MakePath(szXbxFile, GetUData(), szTitleID); - MakePath(szXbxFile, szXbxFile, szTitleDataXBX); + return CompareFileTime(&((const CSave*)b)->m_written, &((const CSave*)a)->m_written); +} - TCHAR szTitleName[64]; +static TCHAR* DupString(const TCHAR* s) +{ + int n = (int)_tcslen(s) + 1; + TCHAR* copy = new TCHAR [n]; + CopyChars(copy, s, n); + return copy; +} - TCHAR szLanguageCode[MAX_LANGUAGE_CODE_LEN]; - GetLanguageCode(szLanguageCode); +// CTitleArray::AddTitle(id) +// Reconstructed from 5960 retail XBE @ 0x41f20. Reads TitleName out of +// \\TitleMeta.xbx (64 chars); if the file or the key is missing +// the title shows as the translated "Broken Game" and is flagged broken. +// The list grows 50 entries at a time. Counts start at -1 (not scanned). +// Theseus reads the name from the current language's section. +void CTitleArray::AddTitle(const TCHAR* szTitleID) +{ + TCHAR metaPath[MAX_PATH]; + MakePath(metaPath, GetUData(), szTitleID); + MakePath(metaPath, metaPath, szTitleDataXBX); - CSettingsFile settings; + TCHAR lang[MAX_LANGUAGE_CODE_LEN]; + GetLanguageCode(lang); + + TCHAR name[64]; bool broken = false; - if (!settings.Open(szXbxFile) || !settings.GetValue(szLanguageCode, _T("TitleName"), szTitleName, countof(szTitleName))) + CSettingsFile meta; + if (!meta.Open(metaPath) || !meta.GetValue(lang, _T("TitleName"), name, countof(name))) { - _tcscpy(szTitleName, Translate(_T("Broken Game"), szTranslate)); + TCHAR translated[MAX_TRANSLATE_LEN]; + _tcscpy(name, Translate(_T("Broken Game"), translated)); broken = true; } - if (m_titleCount == m_titleCapacity) + if (m_count == m_capacity) { - m_titleCapacity += 50; - - CTitle* rgtitle = new CTitle [m_titleCapacity]; - CopyMemory(rgtitle, m_titles, m_titleCount * sizeof (CTitle)); - delete [] m_titles; - m_titles = rgtitle; + m_capacity += 50; + CTitle* grown = new CTitle [m_capacity]; + CopyMemory(grown, m_list, m_count * sizeof (CTitle)); + delete [] m_list; + m_list = grown; } - int cch = _tcslen(szTitleID) + 1; - m_titles[m_titleCount].m_id = new TCHAR [cch]; - CopyChars(m_titles[m_titleCount].m_id, szTitleID, cch); - - cch = _tcslen(szTitleName) + 1; - m_titles[m_titleCount].m_name = new TCHAR [cch]; - CopyChars(m_titles[m_titleCount].m_name, szTitleName, cch); - - m_titles[m_titleCount].m_savedGameCount = -1; - m_titles[m_titleCount].m_savedGameBlocks = -1; // 'unknown' - m_titles[m_titleCount].m_totalBlocks = -1; // 'unknown' - m_titles[m_titleCount].m_saves = NULL; - m_titles[m_titleCount].m_broken = broken; - - m_titleCount += 1; -} - + CTitle& t = m_list[m_count++]; + t.m_titleID = DupString(szTitleID); + t.m_displayName = DupString(name); + t.m_saveCount = -1; + t.m_saveList = NULL; + t.m_saveBlocks = -1; + t.m_blocks = -1; + t.m_broken = broken; +} + +// Scans one title's saves into a fresh array sized to fit. +static CSave* ScanSavesToFit(const TCHAR* root, const TCHAR* titleID, HANDLE cancel, int* count) +{ + CSave* scratch = new CSave [MAX_SAVED_GAMES]; + *count = ScanSavedGames(root, titleID, scratch, cancel); + CSave* saves = new CSave [*count]; + CopyMemory(saves, scratch, *count * sizeof (CSave)); + delete [] scratch; + return saves; +} + +// CTitleArray::Update() +// Reconstructed from 5960 retail XBE @ 0x42230. With no root it just marks +// itself clean. Otherwise it lists \*.* and adds every folder as a +// title. A failed listing marks it clean unless the device is gone +// (ERROR_DEVICE_NOT_CONNECTED, 0x48f), so it's tried again; losing the +// device mid listing drops everything. Then the titles sort by name and +// each one's saves are scanned. All of it runs under the root lock. +// 5960 also loads Live accounts and content lists here; Theseus doesn't, +// and skips the fffe0000 dashboard folder. void CTitleArray::Update() { - EnterCriticalSection(&m_rootLock); + EnterCriticalSection(&m_lock); if (m_root[0] == 0) { - LeaveCriticalSection(&m_rootLock); + LeaveCriticalSection(&m_lock); m_dirty = false; return; } - TCHAR szFileName [MAX_PATH]; - WIN32_FIND_DATA fd; - - MakePath(szFileName, GetUData(), _T("*.*")); - FSCHAR szBuf [MAX_PATH]; - Ansi(szBuf, szFileName, countof (szBuf)); - HANDLE hFind = TheseusFindFirstFile(szBuf, &fd); - - if (hFind == INVALID_HANDLE_VALUE) - { - if (ERROR_DEVICE_NOT_CONNECTED != GetLastError()) - { - m_dirty = false; - } - LeaveCriticalSection(&m_rootLock); - return; - } - - do - { - if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) - continue; + TCHAR path[MAX_PATH]; + MakePath(path, GetUData(), _T("*.*")); + FSCHAR pattern[MAX_PATH]; + Ansi(pattern, path, countof(pattern)); - Unicode(szFileName, fd.cFileName, countof(szFileName)); + WIN32_FIND_DATA found; + HANDLE find = TheseusFindFirstFile(pattern, &found); + if (find == INVALID_HANDLE_VALUE) + { + if (GetLastError() != ERROR_DEVICE_NOT_CONNECTED) + m_dirty = false; + LeaveCriticalSection(&m_lock); + return; + } - // Ignore the Xbox default title... - if (_tcsicmp(szFileName, _T("fffe0000")) == 0) + do + { + if ((found.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) continue; + Unicode(path, found.cFileName, countof(path)); + if (_tcsicmp(path, _T("fffe0000")) != 0) + AddTitle(path); + } + while (TheseusFindNextFile(find, &found)); - AddTitle(szFileName); - } - while (TheseusFindNextFile(hFind, &fd)); - - if (ERROR_DEVICE_NOT_CONNECTED == GetLastError()) - { - TheseusFindClose(hFind); - DeleteAll(false); - LeaveCriticalSection(&m_rootLock); - return; - } - - TheseusFindClose(hFind); - - qsort(m_titles, m_titleCount, sizeof (CTitle), SortTitleCompare); + bool unplugged = GetLastError() == ERROR_DEVICE_NOT_CONNECTED; + TheseusFindClose(find); + if (unplugged) + { + DeleteAll(false); + LeaveCriticalSection(&m_lock); + return; + } - // Enumerate saved game count - for (int i=0; im_saveList = ScanSavesToFit(GetUData(), t->m_titleID, NULL, &t->m_saveCount); - LeaveCriticalSection(&m_rootLock); + LeaveCriticalSection(&m_lock); m_dirty = false; } +// CTitleArray::GetTitleCount / GetTitleCount2 +// Nothing to show while the list is stale. int CTitleArray::GetTitleCount() { - if (m_dirty) - return 0; - - return m_titleCount; + return m_dirty ? 0 : m_count; } int CTitleArray::GetTitleCount2() { - if (m_dirty) - return 0; - - return m_titleCount; + return m_dirty ? 0 : m_count; } bool CTitleArray::IsBroken(int nTitle) { - return m_titles[nTitle].m_broken; + return m_list[nTitle].m_broken; } +// GetTitleID / GetTitleName +// 5960 inlines this test everywhere: "" unless the list is current and +// the index is in range. const TCHAR* CTitleArray::GetTitleID(int nTitle) { - const TCHAR* sz = _T(""); - - if (!m_dirty && nTitle >= 0 && nTitle < m_titleCount) - sz = m_titles[nTitle].m_id; - - return sz; + if (m_dirty || nTitle < 0 || nTitle >= m_count) + return _T(""); + return m_list[nTitle].m_titleID; } const TCHAR* CTitleArray::GetTitleName(int nTitle) { - const TCHAR* sz = _T(""); - - if (!m_dirty && nTitle >= 0 && nTitle < m_titleCount) - sz = m_titles[nTitle].m_name; - - return sz; + if (m_dirty || nTitle < 0 || nTitle >= m_count) + return _T(""); + return m_list[nTitle].m_displayName; } + const TCHAR* CTitleArray::GetTitleName2(int nTitle) { - const TCHAR* sz = _T(""); - - if (!m_dirty && nTitle >= 0 && nTitle < m_titleCount) - sz = m_titles[nTitle].m_name; - - return sz; + return GetTitleName(nTitle); } -int CTitleArray::GetSavedGameCount(int nTitle, HANDLE hCancelEvent /*= NULL*/) -{ - int nSavedGameCount = 0; - - if (!m_dirty && nTitle >= 0 && nTitle < m_titleCount) - { - nSavedGameCount = m_titles[nTitle].m_savedGameCount; - - if (nSavedGameCount == -1) - { - CSave* rgsaves = new CSave [MAX_SAVED_GAMES]; - - nSavedGameCount = ScanSavedGames(GetUData(), m_titles[nTitle].m_id, rgsaves, hCancelEvent); - m_titles[nTitle].m_savedGameCount = nSavedGameCount; - m_titles[nTitle].m_saves = new CSave [nSavedGameCount]; - CopyMemory(m_titles[nTitle].m_saves, rgsaves, sizeof (CSave) * nSavedGameCount); - - delete [] rgsaves; - } - } +// CTitleArray::GetSavedGameCount(title, cancel) +// Reconstructed from 5960 retail XBE @ 0x42740: +// if (dirty || n out of range) return 0; +// if (title.saveCount == -1) { scan into a 4096 entry scratch array, +// store the count, copy into an array of exactly that size } +// return title.saveCount; +int CTitleArray::GetSavedGameCount(int nTitle, HANDLE hCancelEvent) +{ + if (m_dirty || nTitle < 0 || nTitle >= m_count) + return 0; - return nSavedGameCount; + CTitle& t = m_list[nTitle]; + if (t.m_saveCount == -1) + t.m_saveList = ScanSavesToFit(GetUData(), t.m_titleID, hCancelEvent, &t.m_saveCount); + return t.m_saveCount; } -bool InitSave(CSave* pSave, const TCHAR* szRoot, const TCHAR* szTitleID, const TCHAR* szSaveDirName, FILETIME saveTime) +// Fills one save record; false when the folder name won't fit (16 chars +// with the terminator). The image is unknown until someone asks for it. +static bool InitSave(CSave* pSave, const TCHAR* szDirName, FILETIME written) { ZeroMemory(pSave, sizeof (CSave)); - - if (!pSave->SetDirName(szSaveDirName)) - { + if (!pSave->SetDirName(szDirName)) return false; - } - - pSave->m_fileTime = saveTime; + pSave->m_written = written; pSave->m_flags |= SAVEFLAG_UNKIMAGE; - return true; } +// CTitleArray::FindTitle(id) +// Reconstructed from 5960 retail XBE @ 0x42c20: first title whose id +// matches ignoring case, else -1. int CTitleArray::FindTitle(const TCHAR* szTitleID) { - int nTitle; - for (nTitle = 0; nTitle < m_titleCount; nTitle += 1) + for (int i = 0; i < m_count; i++) { - if (_tcsicmp(szTitleID, m_titles[nTitle].m_id) == 0) - return nTitle; + if (_tcsicmp(szTitleID, m_list[i].m_titleID) == 0) + return i; } - return -1; } -static int __cdecl SortSaveCompare(const void *elem1, const void *elem2) -{ - // Reversed these to go from newest -> oldest - const CSave* pSave2 = (const CSave*)elem1; - const CSave* pSave1 = (const CSave*)elem2; - return CompareFileTime(&pSave1->m_fileTime, &pSave2->m_fileTime); -} - +// CTitleArray::AddSavedGame(id, folder, time) +// Reconstructed from 5960 retail XBE @ 0x42cb0. Ignored while stale. A +// title not in the list yet is added with zero saves and the list resorted. +// The save list grows by one; if the folder name fits it's appended and +// the saves resorted newest first. Either way the title's sizes are reset +// so they get counted again. void CTitleArray::AddSavedGame(const TCHAR* szTitleID, const TCHAR* szDirName, FILETIME saveTime) { - if (m_dirty) - return; + if (m_dirty) + return; - int nTitle = FindTitle(szTitleID); - if (nTitle == -1) + int n = FindTitle(szTitleID); + if (n == -1) { AddTitle(szTitleID); - - m_titles[m_titleCount - 1].m_savedGameCount = 0; - - qsort(m_titles, m_titleCount, sizeof (CTitle), SortTitleCompare); - - // start search over because of sort... - nTitle = FindTitle(szTitleID); + m_list[m_count - 1].m_saveCount = 0; + qsort(m_list, m_count, sizeof (CTitle), CompareTitleNames); + n = FindTitle(szTitleID); } - CTitle* pTitle = &m_titles[nTitle]; + CTitle& t = m_list[n]; + if (t.m_saveCount == -1) + GetSavedGameCount(n); - if (pTitle->m_savedGameCount == -1) - GetSavedGameCount(nTitle); + CSave* grown = new CSave [t.m_saveCount + 1]; + CopyMemory(grown, t.m_saveList, t.m_saveCount * sizeof (CSave)); + delete [] t.m_saveList; + t.m_saveList = grown; - CSave* rgsaves = new CSave [pTitle->m_savedGameCount + 1]; - CopyMemory(rgsaves, pTitle->m_saves, sizeof (CSave) * pTitle->m_savedGameCount); - delete [] pTitle->m_saves; - pTitle->m_saves = rgsaves; - - if (InitSave(&pTitle->m_saves[pTitle->m_savedGameCount], GetUData(), pTitle->m_id, szDirName, saveTime)) + if (InitSave(&t.m_saveList[t.m_saveCount], szDirName, saveTime)) { - pTitle->m_savedGameCount += 1; - qsort(pTitle->m_saves, pTitle->m_savedGameCount, sizeof (CSave), SortSaveCompare); + t.m_saveCount++; + qsort(t.m_saveList, t.m_saveCount, sizeof (CSave), CompareSaveTimes); } - pTitle->m_totalBlocks = -1; // recalculate this - pTitle->m_savedGameBlocks = -1; // recalculate this + t.m_blocks = -1; + t.m_saveBlocks = -1; } +// CTitleArray::RemoveTitle(n) +// Reconstructed from 5960 retail XBE @ 0x42e40: free the title's strings +// and saves, close the gap, one fewer title. void CTitleArray::RemoveTitle(int nTitle) { - CTitle* pTitle = &m_titles[nTitle]; - delete [] pTitle->m_id; - delete [] pTitle->m_name; - delete [] pTitle->m_saves; - - MoveMemory(&m_titles[nTitle], &m_titles[nTitle + 1], sizeof (CTitle) * (m_titleCount - nTitle - 1)); - m_titleCount -= 1; + CTitle& t = m_list[nTitle]; + delete [] t.m_titleID; + delete [] t.m_displayName; + delete [] t.m_saveList; + MoveMemory(&m_list[nTitle], &m_list[nTitle + 1], (m_count - nTitle - 1) * sizeof (CTitle)); + m_count--; } +// CTitleArray::RemoveSavedGame(n, save) +// Reconstructed from 5960 retail XBE @ 0x42ef0: close the gap, one fewer +// save, sizes reset to -1. void CTitleArray::RemoveSavedGame(int nTitle, int nSavedGame) { - CTitle* pTitle = &m_titles[nTitle]; - MoveMemory(&pTitle->m_saves[nSavedGame], &pTitle->m_saves[nSavedGame + 1], sizeof (CSave) * (pTitle->m_savedGameCount - nSavedGame - 1)); - pTitle->m_savedGameCount -= 1; - - pTitle->m_totalBlocks = -1; // recalculate this - pTitle->m_savedGameBlocks = -1; // recalculate this + CTitle& t = m_list[nTitle]; + MoveMemory(&t.m_saveList[nSavedGame], &t.m_saveList[nSavedGame + 1], (t.m_saveCount - nSavedGame - 1) * sizeof (CSave)); + t.m_saveCount--; + t.m_blocks = -1; + t.m_saveBlocks = -1; } +// CTitleArray::RemoveSavedGame(id, folder) +// Reconstructed from 5960 retail XBE @ 0x42f40: find the title, then the +// save by folder name ignoring case, and remove it if both are there. void CTitleArray::RemoveSavedGame(const TCHAR* szTitleID, const TCHAR* szDirName) { - int nTitle = FindTitle(szTitleID); - if (nTitle == -1) - { - return; - } - - int i, nSavedGame = -1; - CTitle* pTitle = &m_titles[nTitle]; - - // Search for the matching saved game - for (int i=0; im_savedGameCount; i++) - { - if (_tcsicmp(pTitle->m_saves[i].m_dirName, szDirName) == 0) - { - nSavedGame = i; - break; - } - } + int n = FindTitle(szTitleID); + if (n == -1) + return; - if (nSavedGame != -1) - { - RemoveSavedGame(nTitle, nSavedGame); - } + CTitle& t = m_list[n]; + for (int i = 0; i < t.m_saveCount; i++) + { + if (_tcsicmp(t.m_saveList[i].m_folder, szDirName) == 0) + { + RemoveSavedGame(n, i); + return; + } + } } +// GetSavedGameID / GetSavedGameTime +// Both scan the title first if needed; out of range gives "" or a zero time. const TCHAR* CTitleArray::GetSavedGameID(int nTitle, int nSavedGame) { - int nSavedGameCount = GetSavedGameCount(nTitle); - if (nSavedGame < 0 || nSavedGame >= nSavedGameCount) - { + if (nSavedGame < 0 || nSavedGame >= GetSavedGameCount(nTitle)) return _T(""); - } - - return m_titles[nTitle].m_saves[nSavedGame].GetDirName(); // NOTE: Temporary access! + return m_list[nTitle].m_saveList[nSavedGame].GetDirName(); } FILETIME CTitleArray::GetSavedGameTime(int nTitle, int nSavedGame) { - int nSavedGameCount = GetSavedGameCount(nTitle); - if (nSavedGame < 0 || nSavedGame >= nSavedGameCount) + if (nSavedGame < 0 || nSavedGame >= GetSavedGameCount(nTitle)) { - static FILETIME filetime; - return filetime; + FILETIME never = { 0, 0 }; + return never; } - - return m_titles[nTitle].m_saves[nSavedGame].m_fileTime; + return m_list[nTitle].m_saveList[nSavedGame].m_written; } +// CTitleArray::GetTitleTotalBlocks(n, cancel) +// Reconstructed from 5960 retail XBE @ 0x43390. Counted once and cached: +// the title's udata folder, plus its tdata folder on the hard drive. int CTitleArray::GetTitleTotalBlocks(int nTitle, HANDLE hCancelEvent) { - if (nTitle < 0 || nTitle >= m_titleCount) + if (nTitle < 0 || nTitle >= m_count) return 0; - if (m_titles[nTitle].m_totalBlocks == -1) + CTitle& t = m_list[nTitle]; + if (t.m_blocks == -1) { - m_titles[nTitle].m_totalBlocks = ComputeTitleTotalBlocks(GetUData(), m_titles[nTitle].m_id, hCancelEvent); - if (m_root[0] == 'c' && m_titles[nTitle].m_totalBlocks >= 0) - m_titles[nTitle].m_totalBlocks += ComputeTitleTotalBlocks(GetTData(), m_titles[nTitle].m_id, hCancelEvent); + t.m_blocks = ComputeTitleTotalBlocks(GetUData(), t.m_titleID, hCancelEvent); + if (m_root[0] == 'c' && t.m_blocks >= 0) + t.m_blocks += ComputeTitleTotalBlocks(GetTData(), t.m_titleID, hCancelEvent); } - - return m_titles[nTitle].m_totalBlocks; + return t.m_blocks; } - - +// ComputeTitleTotalBlocks(root, id, cancel) +// Reconstructed from 5960 retail XBE @ 0x43460: \ counted in +// 16 KB blocks, subfolders included. int ComputeTitleTotalBlocks(const TCHAR* szRoot, const TCHAR* szTitleID, HANDLE hCancelEvent) { - TCHAR szDir [MAX_PATH]; - MakePath(szDir, szRoot, szTitleID); - return GetDirectoryBlocks(szDir, BLOCK_SIZE, true, hCancelEvent); + TCHAR dir[MAX_PATH]; + MakePath(dir, szRoot, szTitleID); + return GetDirectoryBlocks(dir, BLOCK_SIZE, true, hCancelEvent); } -bool InitSave(CSave* pSave, const TCHAR* szRoot, const TCHAR* szTitleID, const TCHAR* szSaveDirName, FILETIME saveTime); - -int ScanSavedGames(const TCHAR* szRoot, const TCHAR* szTitleID, CSave* rgsaves /*[MAX_SAVED_GAMES]*/, HANDLE hCancelEvent) +static bool CancelSignaled(HANDLE cancel) { - if (hCancelEvent && WaitForSingleObject(hCancelEvent, 0) == WAIT_OBJECT_0) - { - return -1; - } - - int nSavedGameCount = 0; - bool bCancel = false; - - // scan for saves... - HANDLE hFind; - WIN32_FIND_DATA fd; + return cancel != NULL && WaitForSingleObject(cancel, 0) == WAIT_OBJECT_0; +} - { - TCHAR szTitleDirWild [MAX_PATH]; - MakePath(szTitleDirWild, szRoot, szTitleID); - MakePath(szTitleDirWild, szTitleDirWild, _T("*.*")); +// ScanSavedGames(root, id, out, cancel) +// Reconstructed from 5960 retail XBE @ 0x434f0. Lists \\*.* and +// records every folder whose name fits, up to 4096, with its last write +// time and the image marked unknown. -1 if cancel is signaled before or +// during the walk; otherwise the saves are sorted newest first. +int ScanSavedGames(const TCHAR* szRoot, const TCHAR* szTitleID, CSave* rgsaves, HANDLE hCancelEvent) +{ + if (CancelSignaled(hCancelEvent)) + return -1; - char szBuf [MAX_PATH]; - Ansi(szBuf, szTitleDirWild, MAX_PATH); - hFind = TheseusFindFirstFile(szBuf, &fd); - } + TCHAR path[MAX_PATH]; + MakePath(path, szRoot, szTitleID); + MakePath(path, path, _T("*.*")); + char pattern[MAX_PATH]; + Ansi(pattern, path, MAX_PATH); - if (hFind != INVALID_HANDLE_VALUE) + int count = 0; + WIN32_FIND_DATA found; + HANDLE find = TheseusFindFirstFile(pattern, &found); + if (find != INVALID_HANDLE_VALUE) { + bool cancelled = false; do { - if (hCancelEvent && WaitForSingleObject(hCancelEvent, 0) == WAIT_OBJECT_0) - { - bCancel = true; - break; - } - - if (nSavedGameCount == MAX_SAVED_GAMES) + if (CancelSignaled(hCancelEvent)) { + cancelled = true; break; } - - if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) - continue; - - TCHAR szFileName [MAX_PATH]; - Unicode(szFileName, fd.cFileName, countof(szFileName)); - - if (!InitSave(&rgsaves[nSavedGameCount], szRoot, szTitleID, szFileName, fd.ftLastWriteTime)) + if (count == MAX_SAVED_GAMES) + break; + if ((found.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) continue; - nSavedGameCount += 1; + Unicode(path, found.cFileName, countof(path)); + if (InitSave(&rgsaves[count], path, found.ftLastWriteTime)) + count++; } - while (TheseusFindNextFile(hFind, &fd)); - TheseusFindClose(hFind); - } + while (TheseusFindNextFile(find, &found)); + TheseusFindClose(find); - if (!bCancel) - { - qsort(rgsaves, nSavedGameCount, sizeof (CSave), SortSaveCompare); - } + if (cancelled) + return -1; + } - return bCancel ? -1 : nSavedGameCount; + qsort(rgsaves, count, sizeof (CSave), CompareSaveTimes); + return count; } - - +// CTitleArray::GetTData / GetUData +// Reconstructed from 5960 retail XBE @ 0x43c30: a memory unit's root is +// its drive; the hard drive keeps title data and user data in two folders. +// 5960 uses c:\tdata and c:\udata, Theseus the e:\ ones. const TCHAR* CTitleArray::GetTData() const { - if (m_root[0] != 'c') - return m_root; - - return _T("e:\\tdata"); + return m_root[0] == 'c' ? _T("e:\\tdata") : m_root; } const TCHAR* CTitleArray::GetUData() const { - if (m_root[0] != 'c') - return m_root; - - return _T("e:\\udata"); + return m_root[0] == 'c' ? _T("e:\\udata") : m_root; } bool CTitleArray::IsValid() const @@ -529,68 +503,68 @@ bool CTitleArray::IsValid() const return m_root[0] != 0; } +// CTitleArray::IsDirty +// Reconstructed from 5960 retail XBE @ 0x43c50: mounted and stale. bool CTitleArray::IsDirty() const { - return (m_root[0] && m_dirty); + return m_root[0] != 0 && m_dirty; } -void CTitleArray::GetSavedGameImageName(int nTitle, int nSavedGame, TCHAR* szPath/*[MAX_PATH]*/) +// CTitleArray::GetSavedGameImageName(n, save, out) +// Reconstructed from 5960 retail XBE @ 0x43d00. The first time a save is +// asked about, look for \\\SaveImage.xbx and remember +// whether it's there. Saves without their own image use the title's +// \\SaveImage.xbx, and when that's missing too the Xbox logo. +void CTitleArray::GetSavedGameImageName(int nTitle, int nSavedGame, TCHAR* szPath) { - if ((m_titles[nTitle].m_saves[nSavedGame].m_flags & SAVEFLAG_UNKIMAGE) != 0) - { - m_titles[nTitle].m_saves[nSavedGame].m_flags &= ~SAVEFLAG_UNKIMAGE; + DWORD& flags = m_list[nTitle].m_saveList[nSavedGame].m_flags; + if (flags & SAVEFLAG_UNKIMAGE) + { + flags &= ~SAVEFLAG_UNKIMAGE; MakePath(szPath, GetUData(), GetTitleID(nTitle)); MakePath(szPath, szPath, GetSavedGameID(nTitle, nSavedGame)); MakePath(szPath, szPath, szSaveImageXBX); - if (DoesFileExist(szPath)) { - m_titles[nTitle].m_saves[nSavedGame].m_flags |= SAVEFLAG_HASIMAGE; + flags |= SAVEFLAG_HASIMAGE; return; } } MakePath(szPath, GetUData(), GetTitleID(nTitle)); - - if ((m_titles[nTitle].m_saves[nSavedGame].m_flags & SAVEFLAG_HASIMAGE) != 0) - { - // This save has its own image; use it... + if (flags & SAVEFLAG_HASIMAGE) MakePath(szPath, szPath, GetSavedGameID(nTitle, nSavedGame)); - } - MakePath(szPath, szPath, szSaveImageXBX); - if (!DoesFileExist(szPath)) //saved game doesn't have any associated images - { + if (!DoesFileExist(szPath)) _tcscpy(szPath, _T("xboxlogo64.xbx")); - } } +// CTitleArray::IsPublisherExists(publisher) +// Reconstructed from 5960 retail XBE @ 0x44240: any title id starting with +// the same four hex digits, ignoring case. bool CTitleArray::IsPublisherExists(const TCHAR* szPublisherID) const { - for (int i=0; i countof (m_dirName)) + if (_tcslen(szDirName) + 1 > countof(m_folder)) return false; - - _tcscpy(m_dirName, szDirName); + _tcscpy(m_folder, szDirName); return true; } const TCHAR* CSave::GetDirName() { - return m_dirName; + return m_folder; } - diff --git a/theseus/shared/title_collection.h b/theseus/shared/title_collection.h index c0416d6..895e71c 100755 --- a/theseus/shared/title_collection.h +++ b/theseus/shared/title_collection.h @@ -1,18 +1,11 @@ -// title_collection.h: CTitleArray and the on-disk save-game record -// types used by the memory pane. CSave is one save directory entry, -// CTitle is one game-with-saves bucket, CTitleArray is the full -// per-device list. Companion to shared/title_collection.cpp. +// title_collection.h: the per-device list of game titles and their saves +// that the memory screens read. One CTitleArray per device slot in g_titles: +// slots 0..7 are the memory units, slot 8 is the hard drive. Built by +// shared/title_collection.cpp; desktop links empty stubs instead. #pragma once -#define MAX_SAVED_GAMES 4096 - -extern const TCHAR szTitleDataXBX []; -extern const TCHAR szTitleImageXBX []; -extern const TCHAR szSaveDataXBX []; -extern const TCHAR szSaveImageXBX []; - - +// Device slots, as the memory screens and g_titles index them. #define Dev1Unit1 0 #define Dev1Unit2 1 #define Dev2Unit1 2 @@ -23,39 +16,42 @@ extern const TCHAR szSaveImageXBX []; #define Dev4Unit2 7 #define Dev0 8 +// The dashboard counts space in 16 KB blocks on every device. +#define BLOCK_SIZE 16384 +// Most saves one title folder is scanned for. +#define MAX_SAVED_GAMES 4096 -#define BLOCK_SIZE 16384 // Should be max of hard drive and flash block size... +extern const TCHAR szTitleDataXBX []; +extern const TCHAR szTitleImageXBX []; +extern const TCHAR szSaveDataXBX []; +extern const TCHAR szSaveImageXBX []; +// Save flag bits: the folder has its own SaveImage.xbx, or that's not known yet. +#define SAVEFLAG_HASIMAGE 0x00000001 +#define SAVEFLAG_UNKIMAGE 0x00000002 -// One persisted save record on disk: a directory name (the FATX -// directory the save lives in), the file timestamp, and a small flags -// bitfield (currently SAVEFLAG_HASIMAGE / SAVEFLAG_UNKIMAGE). +// One save folder under a title. struct CSave { - TCHAR m_dirName[16]; - FILETIME m_fileTime; + TCHAR m_folder[16]; + FILETIME m_written; DWORD m_flags; bool SetDirName(const TCHAR* szDirName); const TCHAR* GetDirName(); }; -#define SAVEFLAG_HASIMAGE 0x00000001 -#define SAVEFLAG_UNKIMAGE 0x00000002 - -// One title (game) the save-game grid knows about. Holds the title id -// and display name, the array of CSave records that belong to it, and -// some block-count caches the grid uses to render storage usage. +// One title folder and the saves found in it. Counts are -1 until scanned. class CTitle { public: - TCHAR* m_id; - TCHAR* m_name; - int m_savedGameCount; - CSave* m_saves; - int m_savedGameBlocks; - int m_totalBlocks; + TCHAR* m_titleID; + TCHAR* m_displayName; + int m_saveCount; + CSave* m_saveList; + int m_saveBlocks; + int m_blocks; bool m_broken; }; @@ -65,10 +61,14 @@ class CTitleArray CTitleArray(); ~CTitleArray(); + void SetRoot(TCHAR chNewRoot, bool bUpdate = true); void Update(); void DeleteAll(bool bUpdate = true); - void SetRoot(TCHAR chNewRoot, bool bUpdate = true); + bool IsValid() const; + bool IsDirty() const; + const TCHAR* GetTData() const; + const TCHAR* GetUData() const; int GetTitleCount(); int GetTitleCount2(); @@ -77,41 +77,31 @@ class CTitleArray const TCHAR* GetTitleName(int nTitle); const TCHAR* GetTitleName2(int nTitle); int GetTitleTotalBlocks(int nTitle, HANDLE hCancelEvent); + bool IsPublisherExists(const TCHAR* szPublisherID) const; int GetSavedGameCount(int nTitle, HANDLE hCancelEvent = NULL); const TCHAR* GetSavedGameID(int nTitle, int nSavedGame); - void GetSavedGameImageName(int nTitle, int nSavedGame, TCHAR* szPath/*[MAX_PATH]*/); FILETIME GetSavedGameTime(int nTitle, int nSavedGame); + void GetSavedGameImageName(int nTitle, int nSavedGame, TCHAR* szPath); void AddSavedGame(const TCHAR* szTitleID, const TCHAR* szDirName, FILETIME saveTime); - - bool IsValid() const; - bool IsDirty() const; - const TCHAR* GetTData() const; - const TCHAR* GetUData() const; - void RemoveTitle(int nTitle); void RemoveSavedGame(int nTitle, int nSavedGame); void RemoveSavedGame(const TCHAR* szTitleID, const TCHAR* szDirName); - bool IsPublisherExists(const TCHAR* szPublisherID) const; protected: int FindTitle(const TCHAR* szTitleID); void AddTitle(const TCHAR* szTitleID); - TCHAR m_root [4]; // drive letter prefix, e.g. "U:\" - bool m_dirty; // titles need re-scan since last Update - int m_titleCount; - int m_titleCapacity; - CTitle* m_titles; - - CRITICAL_SECTION m_rootLock; - - friend class CTitleCollection; - friend void TitleArray_Init(); + TCHAR m_root[4]; // "x:\" with x = 0 when nothing is mounted + bool m_dirty; // list is stale until the next Update + int m_count; + int m_capacity; + CTitle* m_list; + CRITICAL_SECTION m_lock; // guards m_root against the scan thread }; -extern int ScanSavedGames(const TCHAR* szRoot, const TCHAR* szTitleID, CSave* rgsaves /*[MAX_SAVED_GAMES]*/, HANDLE hCancelEvent); +extern int ScanSavedGames(const TCHAR* szRoot, const TCHAR* szTitleID, CSave* rgsaves, HANDLE hCancelEvent); extern int ComputeTitleTotalBlocks(const TCHAR* szRoot, const TCHAR* szTitleID, HANDLE hCancelEvent); extern CTitleArray g_titles [9]; From 5f3383a3cebfab84c836718a5d2e612f686edc61 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:30:30 -0500 Subject: [PATCH 2/6] Rebuilt the save copier and file nodes from the binary Rewrote CGameCopier, CopyDestination, File and Folder from the 5960 code. A harness copying generated saves between a fake hard drive and memory unit, with failures thrown in, plus the destination picker and folder listing, printed the same 217,258 lines old and new over 500 runs. --- docs/decomp/FileOps.md | 157 +++++- theseus/shared/file_ops.cpp | 1058 +++++++++++++++-------------------- 2 files changed, 596 insertions(+), 619 deletions(-) diff --git a/docs/decomp/FileOps.md b/docs/decomp/FileOps.md index b847f16..e4ed52a 100644 --- a/docs/decomp/FileOps.md +++ b/docs/decomp/FileOps.md @@ -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 `\*.*`, 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`. diff --git a/theseus/shared/file_ops.cpp b/theseus/shared/file_ops.cpp index bc45ffc..835d6c1 100755 --- a/theseus/shared/file_ops.cpp +++ b/theseus/shared/file_ops.cpp @@ -1,11 +1,9 @@ -// file_ops.cpp: file operations, game copying, and copy-destination -// selection. -// -// CGameCopier Threaded game-save copier between storage devices -// CCopyDestination Node for selecting the copy destination device -// CFile / CFolder File-system browsing nodes -// -// Decompiled from the 5960 retail XBE; see docs/decomp/FileOps.md. +// file_ops.cpp: the memory screens' file work. CGameCopier copies saves +// from one device to another on a worker thread, CCopyDestination is the +// node that lists where they can go, and CFile / CFolder let scripts list +// a folder. Rebuilt from the 5960 retail XBE (copier 0x3ec90..0x3fd00, +// File/Folder 0x31800..0x32010, CopyDestination 0x4ce40..0x4d380); see +// docs/decomp/FileOps.md. #include "std.h" #include "theseus.h" @@ -16,45 +14,53 @@ #include "title_collection.h" #include "copy_games.h" -extern const TCHAR* g_szCurTitleImage; - -// ===== Constants ===== - +// The metadata files every title and save folder may carry. const TCHAR szTitleDataXBX [] = _T("TitleMeta.xbx"); const TCHAR szTitleImageXBX [] = _T("TitleImage.xbx"); const TCHAR szSaveDataXBX [] = _T("SaveMeta.xbx"); const TCHAR szSaveImageXBX [] = _T("SaveImage.xbx"); -// ===== CCopyGame ===== - +// One save queued for copying (0x14 bytes in 5960). copied is set once the +// save is on the destination and still needs adding to its title list. struct CCopyGame { - TCHAR* m_titleId; - TCHAR* m_gameDir; - FILETIME m_time; - bool m_needToAdd; + TCHAR* titleID; + TCHAR* folder; + FILETIME written; + bool copied; }; -// ===== CGameCopier ===== +static TCHAR* NewString(const TCHAR* s) +{ + TCHAR* copy = new TCHAR [_tcslen(s) + 1]; + _tcscpy(copy, s); + return copy; +} + +// ========================================================================= +// CGameCopier +// ========================================================================= +// 5960 builds the copier inline as part of its owner; everything starts +// empty with no devices picked. CGameCopier::CGameCopier() { - m_thread = NULL; m_progress = 0.0f; - m_internalError = false; - m_alreadyExists = false; m_error = false; m_done = false; - m_totalBlocks = 0; - m_copiedBlocks = 0; - m_destRoot = NULL; + m_thread = NULL; + m_srcDevUnit = -1; + m_destDevUnit = -1; m_srcRoot = NULL; + m_destRoot = NULL; m_copyGames = NULL; - m_copyGameCapacity = 0; m_copyGameCount = 0; + m_copyGameCapacity = 0; m_buffer = NULL; - m_srcDevUnit = -1; - m_destDevUnit = -1; + m_internalError = false; + m_alreadyExists = false; + m_totalBlocks = 0; + m_copiedBlocks = 0; } CGameCopier::~CGameCopier() @@ -62,21 +68,22 @@ CGameCopier::~CGameCopier() RemoveAll(); } +// CGameCopier::RemoveAll +// Reconstructed from 5960 retail XBE @ 0x3ec90: frees both roots, every +// queued save and the list, zeroes the counts and the block total, frees +// the copy buffer. void CGameCopier::RemoveAll() { delete [] m_destRoot; m_destRoot = NULL; - delete [] m_srcRoot; m_srcRoot = NULL; - int i; - for (i = 0; i < m_copyGameCount; i += 1) + for (CCopyGame* g = m_copyGames; g < m_copyGames + m_copyGameCount; g++) { - delete [] m_copyGames[i].m_titleId; - delete [] m_copyGames[i].m_gameDir; + delete [] g->titleID; + delete [] g->folder; } - delete [] m_copyGames; m_copyGames = NULL; m_copyGameCapacity = 0; @@ -87,448 +94,356 @@ void CGameCopier::RemoveAll() m_buffer = NULL; } +// CGameCopier::Finish +// Reconstructed from 5960 retail XBE @ 0x3ed10. Every save that made it +// across goes into the destination's title list (an overwritten one is +// taken out first so it isn't listed twice), then the queue is emptied. void CGameCopier::Finish() { - for (int i = 0; i < m_copyGameCount; i += 1) + CTitleArray& dest = g_titles[m_destDevUnit]; + for (CCopyGame* g = m_copyGames; g < m_copyGames + m_copyGameCount; g++) { - if (m_copyGames[i].m_needToAdd) - { - if (m_alreadyExists) - { - g_titles[m_destDevUnit].RemoveSavedGame(m_copyGames[i].m_titleId, m_copyGames[i].m_gameDir); - } - - g_titles[m_destDevUnit].AddSavedGame(m_copyGames[i].m_titleId, m_copyGames[i].m_gameDir, m_copyGames[i].m_time); - m_copyGames[i].m_needToAdd = false; - } + if (!g->copied) + continue; + if (m_alreadyExists) + dest.RemoveSavedGame(g->titleID, g->folder); + dest.AddSavedGame(g->titleID, g->folder, g->written); + g->copied = false; } - RemoveAll(); } +// 5960 @ 0x3eda0: the thread entry just forwards to ThreadProc. DWORD CALLBACK CGameCopier::StartThread(LPVOID pvContext) { - CGameCopier *pThis = (CGameCopier*)pvContext; - return pThis->ThreadProc(); + return ((CGameCopier*)pvContext)->ThreadProc(); } -// Copy a single saved-game record from source device to destination, -// staging the surrounding title directory and metadata files alongside -// the game data. The order matters: the title meta file (TitleMeta.xbx) -// is the very last write so a hot-removed memory card mid-copy leaves -// the destination in a "no game here" state instead of a half-written -// title with no payload. -void CGameCopier::CopyGame(int nCopyGame) +// \ and <root>\<title>\<name>. +static void TitlePath(TCHAR* out, const TCHAR* root, const TCHAR* titleID, const TCHAR* name = NULL) { - const TCHAR* szTitleID = m_copyGames[nCopyGame].m_titleId; - const TCHAR* szGameDir = m_copyGames[nCopyGame].m_gameDir; - - TRACE(_T("CopyGame(%s, %s)\n"), szTitleID, szGameDir); - ASSERT(!m_internalError); + MakePath(out, root, titleID); + if (name != NULL) + MakePath(out, out, name); +} - TCHAR szSrcPath [MAX_PATH]; - TCHAR szDestPath [MAX_PATH]; +// CGameCopier::CopyGame(n) +// Reconstructed from 5960 retail XBE @ 0x3edb0. Makes the title folder on +// the destination; copies TitleImage.xbx if the title is new or its image +// is empty there, and SaveImage.xbx if the source has one and the +// destination's is empty. Those two don't count as failures. The save +// folder is created; if it's already there it's emptied and reused, any +// other failure stops this save. The folder gets the save's time, then +// its files are copied. A failed copy deletes what was written (the whole +// title folder when it was new). On success the queued folder name is +// replaced with what's on disk and TitleMeta.xbx is copied last, so a +// memory unit pulled mid copy doesn't end up with a title but no save. +// See docs/decomp/FileOps.md for the decompile. +void CGameCopier::CopyGame(int nCopyGame) +{ + CCopyGame& game = m_copyGames[nCopyGame]; + TCHAR src[MAX_PATH]; + TCHAR dest[MAX_PATH]; - // Stage 1: ensure the title's destination directory exists. - MakePath(szDestPath, m_destRoot, szTitleID); - bool bNewTitle = CreateDirectory(szDestPath); + TitlePath(dest, m_destRoot, game.titleID); + bool newTitle = CreateDirectory(dest); - // Stage 2: copy the title image (TitleImage.xbx). Skip if already - // present and non-empty (a previous copy session staged it). - MakePath(szDestPath, m_destRoot, szTitleID); - MakePath(szDestPath, szDestPath, szTitleImageXBX); - if (bNewTitle || GetFileSize(szDestPath) == 0) + TitlePath(dest, m_destRoot, game.titleID, szTitleImageXBX); + if (newTitle || GetFileSize(dest) == 0) { - MakePath(szSrcPath, m_srcRoot, szTitleID); - MakePath(szSrcPath, szSrcPath, szTitleImageXBX); - CopyFile(szSrcPath, szDestPath); + TitlePath(src, m_srcRoot, game.titleID, szTitleImageXBX); + CopyFile(src, dest); } - // Stage 3: copy the title's default save image (SaveImage.xbx) if - // the source has one and the destination doesn't. - MakePath(szDestPath, m_destRoot, szTitleID); - MakePath(szDestPath, szDestPath, szSaveImageXBX); - MakePath(szSrcPath, m_srcRoot, szTitleID); - MakePath(szSrcPath, szSrcPath, szSaveImageXBX); - if (DoesFileExist(szSrcPath) && GetFileSize(szDestPath) == 0) - { - CopyFile(szSrcPath, szDestPath); - } + TitlePath(dest, m_destRoot, game.titleID, szSaveImageXBX); + TitlePath(src, m_srcRoot, game.titleID, szSaveImageXBX); + if (DoesFileExist(src) && GetFileSize(dest) == 0) + CopyFile(src, dest); - // Stages 2 and 3 are best-effort. A missing title image isn't a - // reason to abort the actual save copy. Reset the error flags - // before the load-bearing work below. m_internalError = false; m_alreadyExists = false; - // Stage 4: create (or clear) the saved-game directory and stamp it - // with the original save's timestamp. ERROR_ALREADY_EXISTS means - // the user is overwriting an existing save: delete its contents - // and reuse the directory; any other failure is fatal for this game. - MakePath(szDestPath, m_destRoot, szTitleID); - MakePath(szDestPath, szDestPath, szGameDir); - if (!CreateDirectory(szDestPath)) + TitlePath(dest, m_destRoot, game.titleID, game.folder); + if (!CreateDirectory(dest)) { - if (GetLastError() == ERROR_ALREADY_EXISTS) - { - m_alreadyExists = true; - DeleteDirectory(szDestPath, false); - } - else + if (GetLastError() != ERROR_ALREADY_EXISTS) { m_internalError = true; return; } + m_alreadyExists = true; + DeleteDirectory(dest, false); } - TRACE(_T("Creating game in %s\n"), szDestPath); - - HANDLE hFile = TheseusCreateFile(szDestPath, GENERIC_WRITE, 0, NULL, - OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); - if (hFile != INVALID_HANDLE_VALUE) - { - FILETIME* pTime = &m_copyGames[nCopyGame].m_time; - VERIFY(SetFileTime(hFile, pTime, pTime, pTime)); - VERIFY(CloseHandle(hFile)); - } -#ifdef _DEBUG - else + HANDLE folder = TheseusCreateFile(dest, GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); + if (folder != INVALID_HANDLE_VALUE) { - TRACE(_T("Cannot open directory (%s) to set times (%d)\n"), szDestPath, GetLastError()); + SetFileTime(folder, &game.written, &game.written, &game.written); + CloseHandle(folder); } -#endif - - // Stage 5: copy the actual save game file tree. If this fails the - // destination directory we just created is partially populated -- - // roll it back, plus the parent title directory if we created it - // fresh in stage 1. - MakePath(szSrcPath, m_srcRoot, szTitleID); - MakePath(szSrcPath, szSrcPath, szGameDir); - if (!CopyDirectory(szSrcPath, szDestPath)) + + TitlePath(src, m_srcRoot, game.titleID, game.folder); + if (!CopyDirectory(src, dest)) { - TRACE(_T("\001The copy didn't complete; removing what we did copy...\n")); - if (bNewTitle) - { - TRACE(_T("it was a new title; deleting: %s %s\n"), m_destRoot, szTitleID); - MakePath(szDestPath, m_destRoot, szTitleID); - } - DeleteDirectory(szDestPath); + if (newTitle) + TitlePath(dest, m_destRoot, game.titleID); + DeleteDirectory(dest); return; } - // Stage 6: capture the destination's actual basename in case the - // filesystem renamed it during creation (FATX truncation, etc) and - // keep the in-memory copy table in sync with what's on disk. - { - TCHAR* pch = _tcsrchr(szDestPath, '\\'); - ASSERT(pch != NULL); - pch += 1; - - delete [] m_copyGames[nCopyGame].m_gameDir; - m_copyGames[nCopyGame].m_gameDir = new TCHAR [_tcslen(pch) + 1]; - _tcscpy(m_copyGames[nCopyGame].m_gameDir, pch); - } + const TCHAR* onDisk = _tcsrchr(dest, '\\') + 1; + delete [] game.folder; + game.folder = NewString(onDisk); - // Stage 7 (last on purpose): copy the title's meta file. If a memory - // card is pulled mid-copy *before* this write, the destination is - // left looking like "no save here" rather than a half-installed - // title we can't clean up. - MakePath(szDestPath, m_destRoot, szTitleID); - MakePath(szDestPath, szDestPath, szTitleDataXBX); - if (bNewTitle || GetFileSize(szDestPath) == 0) + TitlePath(dest, m_destRoot, game.titleID, szTitleDataXBX); + if (newTitle || GetFileSize(dest) == 0) { - MakePath(szSrcPath, m_srcRoot, szTitleID); - MakePath(szSrcPath, szSrcPath, szTitleDataXBX); - CopyFile(szSrcPath, szDestPath); + TitlePath(src, m_srcRoot, game.titleID, szTitleDataXBX); + CopyFile(src, dest); } } +// CGameCopier::CreateDirectory(path) +// Reconstructed from 5960 retail XBE @ 0x3f420: narrow to 260 chars, +// CreateDirectoryA, true when it made one. bool CGameCopier::CreateDirectory(const TCHAR* szDir) { - TRACE(_T("CreateDirectory(%s)\n"), szDir); - - char szDir2 [MAX_PATH]; - Ansi(szDir2, szDir, MAX_PATH); + char narrow[MAX_PATH]; + Ansi(narrow, szDir, MAX_PATH); + return TheseusCreateDirectory(narrow, NULL) != FALSE; +} - return TheseusCreateDirectory(szDir2, NULL) != FALSE; +static bool IsDotEntry(const TCHAR* name) +{ + return _tcscmp(name, _T(".")) == 0 || _tcscmp(name, _T("..")) == 0; } +// CGameCopier::CopyDirectory(src, dest) +// Reconstructed from 5960 retail XBE @ 0x3f480. Makes dest (an existing +// one is fine), then copies each entry of src except . and .., recursing +// into folders. The first failure closes the listing, flags the error and +// returns false. bool CGameCopier::CopyDirectory(const TCHAR* szSrcPath, const TCHAR* szDestPath) { - TRACE(_T("CopyDirectory(%s, %s)\n"), szSrcPath, szDestPath); - CreateDirectory(szDestPath); - TCHAR szBuf [MAX_PATH]; - MakePath(szBuf, szSrcPath, _T("*.*")); + TCHAR from[MAX_PATH]; + MakePath(from, szSrcPath, _T("*.*")); + char pattern[MAX_PATH]; + Ansi(pattern, from, MAX_PATH); - WIN32_FIND_DATA fd; - char szBufX [MAX_PATH]; - Ansi(szBufX, szBuf, MAX_PATH); - HANDLE h = TheseusFindFirstFile(szBufX, &fd); - if (h != INVALID_HANDLE_VALUE) - { - do - { - TCHAR szFileName [MAX_PATH]; - Unicode(szFileName, fd.cFileName, MAX_PATH); - - if (_tcscmp(szFileName, _T(".")) == 0 || _tcscmp(szFileName, _T("..")) == 0) - continue; + WIN32_FIND_DATA found; + HANDLE find = TheseusFindFirstFile(pattern, &found); + if (find == INVALID_HANDLE_VALUE) + return true; - MakePath(szBuf, szSrcPath, szFileName); + do + { + TCHAR name[MAX_PATH]; + Unicode(name, found.cFileName, MAX_PATH); + if (IsDotEntry(name)) + continue; - TCHAR szBuf2 [MAX_PATH]; - MakePath(szBuf2, szDestPath, szFileName); + TCHAR to[MAX_PATH]; + MakePath(from, szSrcPath, name); + MakePath(to, szDestPath, name); - if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) - { - if (!CopyDirectory(szBuf, szBuf2)) - { - TRACE(_T("CopyDirectory(%s, %s) failed\n"), szBuf, szBuf2); - TheseusFindClose(h); - m_internalError = true; - return false; - } - } - else - { - if (!CopyFile(szBuf, szBuf2)) - { - TRACE(_T("CopyFile(%s, %s) failed\n"), szBuf, szBuf2); - TheseusFindClose(h); - m_internalError = true; - return false; - } - } + bool ok = (found.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? CopyDirectory(from, to) : CopyFile(from, to); + if (!ok) + { + TheseusFindClose(find); + m_internalError = true; + return false; } - while (TheseusFindNextFile(h, &fd)); - TheseusFindClose(h); } + while (TheseusFindNextFile(find, &found)); + TheseusFindClose(find); return true; } +// CGameCopier::CopyFile(src, dest) +// Reconstructed from 5960 retail XBE @ 0x3f700. Opens src (read, sequential) +// and creates dest, then moves 16 KB at a time, counting each block toward +// m_progress. A read or write failure flags the error. When it all went +// through, dest gets src's three file times. A failed close of dest also +// counts. Returns whether there was no error. bool CGameCopier::CopyFile(const TCHAR* szSrcFile, const TCHAR* szDestFile) { - TRACE(_T("CopyFile(%s, %s)\n"), szSrcFile, szDestFile); - - HANDLE hSrcFile = TheseusCreateFile(szSrcFile, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL); - if (hSrcFile == INVALID_HANDLE_VALUE) + HANDLE in = TheseusCreateFile(szSrcFile, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL); + if (in == INVALID_HANDLE_VALUE) { - TRACE(_T("OpenFile(%s) failed\n"), szSrcFile); m_internalError = true; return false; } - HANDLE hDestFile = TheseusCreateFile(szDestFile, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL); - if (hDestFile == INVALID_HANDLE_VALUE) + HANDLE out = TheseusCreateFile(szDestFile, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, NULL); + if (out == INVALID_HANDLE_VALUE) { - CloseHandle(hSrcFile); - TRACE(_T("CreateFile(%s) failed\n"), szDestFile); + CloseHandle(in); m_internalError = true; return false; } for (;;) { - DWORD dwRead, dwWrite; - - if (!ReadFile(hSrcFile, m_buffer, BLOCK_SIZE, &dwRead, NULL)) + DWORD got, put; + if (!ReadFile(in, m_buffer, BLOCK_SIZE, &got, NULL)) { - TRACE(_T("ReadFile(%s) failed (%d)\n"), szSrcFile, GetLastError()); m_internalError = true; break; } - - if (dwRead == 0) + if (got == 0) break; - - if (!WriteFile(hDestFile, m_buffer, dwRead, &dwWrite, NULL)) + if (!WriteFile(out, m_buffer, got, &put, NULL)) { - TRACE(_T("WriteFile(%s) failed (%d)\n"), szDestFile, GetLastError()); m_internalError = true; break; } - m_copiedBlocks += 1; + m_copiedBlocks++; m_progress = (float)m_copiedBlocks / (float)m_totalBlocks; - TRACE(_T("copy progress: %f block %d of %d\n"), m_progress, m_copiedBlocks, m_totalBlocks); } if (!m_internalError) { - FILETIME create, access, write; - GetFileTime(hSrcFile, &create, &access, &write); - SetFileTime(hDestFile, &create, &access, &write); + FILETIME created, accessed, written; + GetFileTime(in, &created, &accessed, &written); + SetFileTime(out, &created, &accessed, &written); } - CloseHandle(hSrcFile); - - if (!CloseHandle(hDestFile)) - { - TRACE(_T("CloseHandle(%s) failed\n"), szDestFile); + CloseHandle(in); + if (!CloseHandle(out)) m_internalError = true; - } return !m_internalError; } +// CGameCopier::DeleteFile(path) +// Reconstructed from 5960 retail XBE @ 0x3f830: clear the attributes so a +// read-only file goes too, then delete. bool CGameCopier::DeleteFile(const TCHAR* szFile) { - char szFileA [MAX_PATH]; - Ansi(szFileA, szFile, MAX_PATH); - TheseusSetFileAttributes(szFileA, FILE_ATTRIBUTE_NORMAL); - return TheseusDeleteFile(szFileA) != FALSE; + char narrow[MAX_PATH]; + Ansi(narrow, szFile, MAX_PATH); + TheseusSetFileAttributes(narrow, FILE_ATTRIBUTE_NORMAL); + return TheseusDeleteFile(narrow) != FALSE; } -bool CGameCopier::DeleteDirectory(const TCHAR* szDir, bool RemoveSelf /*= true*/) +// CGameCopier::DeleteDirectory(path, removeSelf) +// Reconstructed from 5960 retail XBE @ 0x3f8a0. Deletes everything inside +// (recursing into folders, . and .. skipped); the first failure flags the +// error and returns false. With removeSelf the emptied folder goes too. +bool CGameCopier::DeleteDirectory(const TCHAR* szDir, bool RemoveSelf) { - TCHAR szBuf [MAX_PATH]; - MakePath(szBuf, szDir, _T("*.*")); - - WIN32_FIND_DATA fd; - char szBufX [MAX_PATH]; - Ansi(szBufX, szBuf, MAX_PATH); - HANDLE h = TheseusFindFirstFile(szBufX, &fd); - if (h != INVALID_HANDLE_VALUE) + TCHAR path[MAX_PATH]; + MakePath(path, szDir, _T("*.*")); + char narrow[MAX_PATH]; + Ansi(narrow, path, MAX_PATH); + + WIN32_FIND_DATA found; + HANDLE find = TheseusFindFirstFile(narrow, &found); + if (find != INVALID_HANDLE_VALUE) { do { - TCHAR szFileName [MAX_PATH]; - Unicode(szFileName, fd.cFileName, MAX_PATH); - - if (_tcscmp(szFileName, _T(".")) == 0 || _tcscmp(szFileName, _T("..")) == 0) + TCHAR name[MAX_PATH]; + Unicode(name, found.cFileName, MAX_PATH); + if (IsDotEntry(name)) continue; - MakePath(szBuf, szDir, szFileName); - - if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) + MakePath(path, szDir, name); + bool ok = (found.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ? DeleteDirectory(path) : DeleteFile(path); + if (!ok) { - if (!DeleteDirectory(szBuf)) - { - TheseusFindClose(h); - m_internalError = true; - return false; - } - } - else - { - if (!DeleteFile(szBuf)) - { - TheseusFindClose(h); - m_internalError = true; - return false; - } + TheseusFindClose(find); + m_internalError = true; + return false; } } - while (TheseusFindNextFile(h, &fd)); - TheseusFindClose(h); + while (TheseusFindNextFile(find, &found)); + TheseusFindClose(find); } if (!RemoveSelf) - { return true; - } - char szDirA [MAX_PATH]; - Ansi(szDirA, szDir, MAX_PATH); - return TheseusRemoveDirectory(szDirA) != FALSE; + Ansi(narrow, szDir, MAX_PATH); + return TheseusRemoveDirectory(narrow) != FALSE; } +// CGameCopier::ThreadProc +// Reconstructed from 5960 retail XBE @ 0x3fae0: +// while (cur < count) { CopyGame(cur); if (internalError) break; +// games[cur].copied = 1; cur++; } +// done = 1; free(buffer); thread = 0; error = internalError; return 1; DWORD CGameCopier::ThreadProc() { - ASSERT(m_buffer != NULL); - - while (m_copyGameCur < m_copyGameCount) + for (; m_copyGameCur < m_copyGameCount; m_copyGameCur++) { CopyGame(m_copyGameCur); if (m_internalError) break; - - m_copyGames[m_copyGameCur].m_needToAdd = true; - m_copyGameCur += 1; + m_copyGames[m_copyGameCur].copied = true; } m_done = true; - delete [] m_buffer; m_buffer = NULL; - m_thread = NULL; m_error = m_internalError; - - TRACE(_T("CGameCopier::ThreadProc terminating; error=%d\n"), m_error); - return 1; } +// SetSource / SetDestination(device) +// Reconstructed from 5960 retail XBE @ 0x3fb40 / 0x3fba0: remember the +// device and keep a copy of its user data root. +static void ReplaceString(TCHAR*& field, const TCHAR* value) +{ + delete [] field; + field = NewString(value); +} + void CGameCopier::SetSource(int nDevUnit) { m_srcDevUnit = nDevUnit; - - const TCHAR* szRoot = g_titles[nDevUnit].GetUData(); - - TRACE(_T("SetSource(%s)\n"), szRoot); - delete [] m_srcRoot; - m_srcRoot = new TCHAR [_tcslen(szRoot) + 1]; - _tcscpy(m_srcRoot, szRoot); - - ASSERT(m_totalBlocks == 0); - ASSERT(m_copyGameCount == 0); + ReplaceString(m_srcRoot, g_titles[nDevUnit].GetUData()); } void CGameCopier::SetDestination(int nDevUnit) { m_destDevUnit = nDevUnit; - - const TCHAR* szRoot = g_titles[nDevUnit].GetUData(); - - TRACE(_T("SetDestination(%s)\n"), szRoot); - delete [] m_destRoot; - m_destRoot = new TCHAR [_tcslen(szRoot) + 1]; - _tcscpy(m_destRoot, szRoot); - - ASSERT(m_totalBlocks == 0); - ASSERT(m_copyGameCount == 0); + ReplaceString(m_destRoot, g_titles[nDevUnit].GetUData()); } +// CGameCopier::AddGame(title, folder, time, blocks) +// Reconstructed from 5960 retail XBE @ 0x3fc00: queue grows 10 at a time; +// the save's blocks add to the total progress is measured against. void CGameCopier::AddGame(const TCHAR* szTitleID, const TCHAR* szGameDir, FILETIME saveTime, int nBlocks) { - TRACE(_T("CGameCopier::AddGame: %s %s %d blocks\n"), szTitleID, szGameDir, nBlocks); - if (m_copyGameCount == m_copyGameCapacity) { m_copyGameCapacity += 10; - CCopyGame* rgCopyGame = new CCopyGame [m_copyGameCapacity]; - CopyMemory(rgCopyGame, m_copyGames, m_copyGameCount * sizeof (CCopyGame)); + CCopyGame* grown = new CCopyGame [m_copyGameCapacity]; + CopyMemory(grown, m_copyGames, m_copyGameCount * sizeof (CCopyGame)); delete [] m_copyGames; - m_copyGames = rgCopyGame; + m_copyGames = grown; } - m_copyGames[m_copyGameCount].m_titleId = new TCHAR [_tcslen(szTitleID) + 1]; - _tcscpy(m_copyGames[m_copyGameCount].m_titleId, szTitleID); - - m_copyGames[m_copyGameCount].m_gameDir = new TCHAR [_tcslen(szGameDir) + 1]; - _tcscpy(m_copyGames[m_copyGameCount].m_gameDir, szGameDir); - - m_copyGames[m_copyGameCount].m_time = saveTime; - - m_copyGames[m_copyGameCount].m_needToAdd = false; - - m_copyGameCount += 1; - + CCopyGame& g = m_copyGames[m_copyGameCount++]; + g.titleID = NewString(szTitleID); + g.folder = NewString(szGameDir); + g.written = saveTime; + g.copied = false; m_totalBlocks += nBlocks; } +// CGameCopier::Start +// Reconstructed from 5960 retail XBE @ 0x3fd00. Resets progress and flags, +// makes sure there's a 16 KB buffer and starts the copy thread; if no +// thread can be made the copy runs right here. void CGameCopier::Start() { - ASSERT(m_srcDevUnit >= 0 && m_srcDevUnit <= 8); - ASSERT(m_destDevUnit >= 0 && m_destDevUnit <= 8); - ASSERT(m_srcDevUnit != m_destDevUnit); - - TRACE(_T("Start game copy: %d blocks\n"), m_totalBlocks); - m_progress = 0.0f; m_internalError = false; m_error = false; @@ -540,18 +455,15 @@ void CGameCopier::Start() m_buffer = new BYTE [BLOCK_SIZE]; m_thread = CreateThread(NULL, 0, StartThread, this, 0, 0); - - if (m_thread) - { + if (m_thread != NULL) CloseHandle(m_thread); - } else - { StartThread(this); - } } -// ===== CCopyDestination ===== +// ========================================================================= +// CCopyDestination +// ========================================================================= class CCopyDestination : public CNode { @@ -560,10 +472,13 @@ class CCopyDestination : public CNode CCopyDestination(); ~CCopyDestination(); - void Render(); void Advance(float nSeconds); + void Render(); bool OnSetProperty(const PRD* pprd, const void* pvValue); + void selectUp(); + void selectDown(); + CNode* m_pod; CNode* m_podIcon; CNode* m_panelMU; @@ -580,23 +495,18 @@ class CCopyDestination : public CNode bool m_isActive; int m_select; - float m_nScroll; - int m_nScrollTo; - XTIME m_nScrollTime; + float m_scroll; // current list offset + int m_scrollTarget; // row the list is easing toward + XTIME m_scrollStart; // 0 when not easing - void selectUp(); - void selectDown(); - - int m_rgDevUnit [9]; - int m_nDevUnitCount; + int m_units[9]; // devices listed, hard drive first + int m_unitCount; DECLARE_NODE_PROPS(); DECLARE_NODE_FUNCTIONS(); protected: - - const TCHAR* GetTitleID2(int nTitle); - CStrObject* GetTitleID(int nTitle); + void Pick(int row); }; IMPLEMENT_NODE("CopyDestination", CCopyDestination, CNode) @@ -624,228 +534,185 @@ START_NODE_FUN(CCopyDestination, CNode) END_NODE_FUN() #undef _FND_CLASS - -CCopyDestination::CCopyDestination() : - m_pod(NULL), - m_panelMU(NULL), - m_panelMUHilite(NULL), - m_panelText(NULL), - m_panelTextHilite(NULL), - m_console(NULL), - m_memoryUnit(NULL), - m_curDevUnit(-1), - m_selDevUnit(-1), - m_sourceDevUnit(-1), - m_spacing(0.4f), - m_isActive(false), - m_select(-1) -{ - m_nScroll = 0.0f; - m_nScrollTo = 0; - m_nScrollTime = 0.0f; - m_nDevUnitCount = 0; -} - +// CCopyDestination::CCopyDestination +// Reconstructed from 5960 retail XBE @ 0x4ce40: node pointers null, +// devices and selection -1, spacing 0.4, inactive, nothing listed. +CCopyDestination::CCopyDestination() +{ + m_pod = NULL; + m_podIcon = NULL; + m_panelMU = NULL; + m_panelMUHilite = NULL; + m_panelText = NULL; + m_panelTextHilite = NULL; + m_console = NULL; + m_memoryUnit = NULL; + m_curDevUnit = -1; + m_selDevUnit = -1; + m_sourceDevUnit = -1; + m_spacing = 0.4f; + m_isActive = false; + m_select = -1; + m_scroll = 0.0f; + m_scrollTarget = 0; + m_scrollStart = 0.0f; + m_unitCount = 0; +} + +// Reconstructed from 5960 retail XBE @ 0x4cee0: releases the seven nodes +// the script handed it. CCopyDestination::~CCopyDestination() { - if (m_pod != NULL) - m_pod->Release(); - - if (m_panelMU != NULL) - m_panelMU->Release(); - - if (m_panelMUHilite != NULL) - m_panelMUHilite->Release(); - - if (m_panelText != NULL) - m_panelText->Release(); - - if (m_panelTextHilite != NULL) - m_panelTextHilite->Release(); - - if (m_console != NULL) - m_console->Release(); - - if (m_memoryUnit != NULL) - m_memoryUnit->Release(); + CNode* held[] = { m_pod, m_panelMU, m_panelMUHilite, m_panelText, m_panelTextHilite, m_console, m_memoryUnit }; + for (int i = 0; i < (int)countof(held); i++) + { + if (held[i] != NULL) + held[i]->Release(); + } } +// CCopyDestination::Render +// Reconstructed from 5960 retail XBE @ 0x4cf80. One pod per listed device, +// stacked downward by spacing from the scroll offset. Before each pod is +// drawn selDevUnit is set to that device and UpdateMemUnitText runs so +// the script can fill in its label. The current device gets the +// highlighted panel and text; the hard drive shows the console model, +// anything else the memory unit. void CCopyDestination::Render() { if (m_pod == NULL) return; - float y = m_nScroll; - int i; - for (i = 0; i < m_nDevUnitCount; i += 1) + float y = m_scroll; + for (int i = 0; i < m_unitCount; i++, y -= m_spacing) { - D3DXMATRIX mat; - D3DXMatrixTranslation(&mat, 0.0f, y, 0.0f); + D3DXMATRIX offset; + D3DXMatrixTranslation(&offset, 0.0f, y, 0.0f); TheseusPushWorld(); - TheseusMultWorld(&mat); + TheseusMultWorld(&offset); TheseusUpdateWorld(); + m_pod->Render(); - // update the text rendered under each MU - m_selDevUnit = m_rgDevUnit[i]; + m_selDevUnit = m_units[i]; CallFunction(this, _T("UpdateMemUnitText")); - if (m_rgDevUnit[i] == m_curDevUnit) - { - if(m_selDevUnit == 8) - { - m_panelMUHilite->Render(); - m_panelTextHilite->Render(); - m_console->Render(); - } - else - { - m_panelMUHilite->Render(); - m_panelTextHilite->Render(); - m_memoryUnit->Render(); - } - } - else - { - if(m_selDevUnit == 8) - { - m_panelMU->Render(); - m_panelText->Render(); - m_console->Render(); - } - else - { - m_panelMU->Render(); - m_panelText->Render(); - m_memoryUnit->Render(); - } - } + bool current = m_units[i] == m_curDevUnit; + (current ? m_panelMUHilite : m_panelMU)->Render(); + (current ? m_panelTextHilite : m_panelText)->Render(); + (m_selDevUnit == Dev0 ? m_console : m_memoryUnit)->Render(); TheseusPopWorld(); - - y -= m_spacing; } } +// CCopyDestination::Advance +// Reconstructed from 5960 retail XBE @ 0x4d110. While active it rebuilds +// the device list every frame: the hard drive, then memory units 0..7, +// leaving out the source and any unit that isn't mounted. If the current +// device moved rows the selection jumps with it; otherwise the list eases +// toward the selected row over a quarter second. When the selected device +// changes the script hears OnCurDevUnitChange, after +// OnDestinationUnitRemoved if the old one was pulled. void CCopyDestination::Advance(float nSeconds) { CNode::Advance(nSeconds); - bool fCurDevUnitRemoved = false; if (!m_isActive) return; - int nDevUnitIndex = -1; - - // Look for memory units... - m_nDevUnitCount = 0; - for (int i = 0; i < 9; i += 1) + bool curRemoved = false; + int curRow = -1; + m_unitCount = 0; + for (int i = 0; i < 9; i++) { - int devUnit = (i == 0) ? 8 : (i - 1); - - // Ignore the source unit - if (devUnit == m_sourceDevUnit) + int unit = (i == 0) ? Dev0 : i - 1; + if (unit == m_sourceDevUnit) continue; - // Ignore missing units - if (devUnit != 8 && !g_titles[devUnit].IsValid()) + if (unit != Dev0 && !g_titles[unit].IsValid()) { - if(devUnit == m_curDevUnit) - { - fCurDevUnitRemoved = true; - } + if (unit == m_curDevUnit) + curRemoved = true; continue; } - m_rgDevUnit[m_nDevUnitCount] = devUnit; - - if (devUnit == m_curDevUnit) - nDevUnitIndex = m_nDevUnitCount; - - m_nDevUnitCount += 1; + if (unit == m_curDevUnit) + curRow = m_unitCount; + m_units[m_unitCount++] = unit; } - if (nDevUnitIndex != -1 && m_select != nDevUnitIndex) + if (curRow != -1 && curRow != m_select) { - // The current unit switched positions; scroll immediately - m_select = nDevUnitIndex; - m_nScrollTo = m_select; - m_nScroll = m_spacing * m_select; + m_select = curRow; + m_scrollTarget = curRow; + m_scroll = m_spacing * curRow; } if (m_select < 0) m_select = 0; - if (m_select > m_nDevUnitCount - 1) - m_select = m_nDevUnitCount - 1; + if (m_select > m_unitCount - 1) + m_select = m_unitCount - 1; - if (m_nScrollTo != m_select) + if (m_scrollTarget != m_select) { - m_nScrollTo = m_select; - m_nScrollTime = TheseusGetNow(); + m_scrollTarget = m_select; + m_scrollStart = TheseusGetNow(); } - else if (m_nScrollTime != 0.0f) + else if (m_scrollStart != 0.0f) { - float t = (float) (TheseusGetNow() - m_nScrollTime) / 0.25f; + float t = (float)(TheseusGetNow() - m_scrollStart) * 4.0f; if (t >= 1.0f) { - m_nScrollTime = 0.0f; t = 1.0f; + m_scrollStart = 0.0f; } - - float t1 = 1.0f - t; - m_nScroll = t1 * m_nScroll + t * (m_spacing * m_nScrollTo); + m_scroll = (1.0f - t) * m_scroll + t * (m_spacing * m_scrollTarget); } - int curDevUnit = -1; - if (m_select != -1) - curDevUnit = m_rgDevUnit[m_select]; - - if (curDevUnit != m_curDevUnit) - { - m_curDevUnit = curDevUnit; + int unit = (m_select == -1) ? -1 : m_units[m_select]; + if (unit == m_curDevUnit) + return; - if(fCurDevUnitRemoved) - { - CallFunction(this, _T("OnDestinationUnitRemoved")); - } - CallFunction(this, _T("OnCurDevUnitChange")); - } + m_curDevUnit = unit; + if (curRemoved) + CallFunction(this, _T("OnDestinationUnitRemoved")); + CallFunction(this, _T("OnCurDevUnitChange")); } +// 5960 shares the plain CNode answer here (0x4d340: return true). bool CCopyDestination::OnSetProperty(const PRD* pprd, const void* pvValue) { return CNode::OnSetProperty(pprd, pvValue); } -void CCopyDestination::selectUp() +// Moves the selection to row when there's somewhere to move. +void CCopyDestination::Pick(int row) { - if (m_nDevUnitCount < 2) + if (m_unitCount < 2 || row < 0 || row >= m_unitCount) return; + m_select = row; + m_curDevUnit = m_units[row]; + CallFunction(this, _T("OnCurDevUnitChange")); +} - int nSel = m_select - 1; - if (nSel >= 0 && nSel < m_nDevUnitCount) - { - m_select = nSel; - m_curDevUnit = m_rgDevUnit[nSel]; - CallFunction(this, _T("OnCurDevUnitChange")); - } +// CCopyDestination::selectUp / selectDown [script fns 'selectUp' / 'selectDown'] +// Reconstructed from 5960 retail XBE @ 0x4d350 / 0x4d380: +// if (count > 1 && 0 <= select -/+ 1 < count) { select = it; +// curDevUnit = units[select]; CallFunction("OnCurDevUnitChange"); } +void CCopyDestination::selectUp() +{ + Pick(m_select - 1); } void CCopyDestination::selectDown() { - if (m_nDevUnitCount < 2) - return; - - int nSel = m_select + 1; - if (nSel >= 0 && nSel < m_nDevUnitCount) - { - m_select = nSel; - m_curDevUnit = m_rgDevUnit[nSel]; - CallFunction(this, _T("OnCurDevUnitChange")); - } + Pick(m_select + 1); } -// ===== CFile ===== +// ========================================================================= +// CFile +// ========================================================================= class CFile : public CNode { @@ -882,15 +749,20 @@ START_NODE_FUN(CFile, CNode) END_NODE_FUN() #undef _FND_CLASS -CFile::CFile() : - m_name(NULL), - m_type(NULL), - m_path(NULL), - m_length(-1), - m_date(NULL) +// CFile::CFile +// Reconstructed from 5960 retail XBE @ 0x31800: no strings, no date, +// length -1 until a folder listing fills it in. +CFile::CFile() { + m_name = NULL; + m_type = NULL; + m_path = NULL; + m_length = -1; + m_date = NULL; } +// Reconstructed from 5960 retail XBE @ 0x318e0: frees the three strings +// and deletes the date. CFile::~CFile() { delete [] m_name; @@ -921,7 +793,9 @@ CStrObject* CFile::readText() return pText; } -// ===== CFolder ===== +// ========================================================================= +// CFolder +// ========================================================================= class CFolder : public CNode { @@ -936,7 +810,6 @@ class CFolder : public CNode CNodeArray m_subFolders; bool OnSetProperty(const PRD* pprd, const void* pvValue); - void Refresh(const TCHAR* szPath); void sortByName(); @@ -966,10 +839,12 @@ START_NODE_FUN(CFolder, CNode) END_NODE_FUN() #undef _FND_CLASS -CFolder::CFolder() : - m_path(NULL), - m_name(NULL) +// Reconstructed from 5960 retail XBE @ 0x31a50 / 0x31ab0: path and name +// start empty; the destructor frees them (the arrays release themselves). +CFolder::CFolder() { + m_path = NULL; + m_name = NULL; } CFolder::~CFolder() @@ -978,154 +853,133 @@ CFolder::~CFolder() delete [] m_name; } +// CFolder::OnSetProperty +// Reconstructed from 5960 retail XBE @ 0x31b30: setting path lists that +// folder; the value is stored either way. bool CFolder::OnSetProperty(const PRD* pprd, const void* pvValue) { if (PTR2INT(pprd->pbOffset) == offsetof(m_path)) - { - const TCHAR* szPath = *((const TCHAR**)pvValue); - Refresh(szPath); - } - + Refresh(*(const TCHAR**)pvValue); return true; } -void CFolder::Refresh(const TCHAR* szPath) +// <dir>\<name> in a fresh string. +static TCHAR* JoinPath(const TCHAR* dir, const TCHAR* name) { - TCHAR szWild [MAX_PATH]; - WIN32_FIND_DATA fd; - HANDLE h; - - lstrcpyn(szWild, szPath, MAX_PATH - sizeof("\\*.*")); - _tcscat(szWild, _T("\\*.*")); + TCHAR* joined = new TCHAR [_tcslen(dir) + 1 + _tcslen(name) + 1]; + _stprintf(joined, _T("%s\\%s"), dir, name); + return joined; +} - char szWildA [MAX_PATH]; - Ansi(szWildA, szWild, MAX_PATH); - h = TheseusFindFirstFile(szWildA, &fd); +// CFolder::Refresh(path) +// Reconstructed from 5960 retail XBE @ 0x31b50. Lists <path>\*.* (the path +// is cut to 255 chars). If that works, the folder's name becomes the part +// after the last '\'. Hidden, system and temporary entries are skipped. +// Each subfolder becomes a Folder with its path and name; each file a +// File with its write time as a Date, name without the extension, the +// extension lowercased as type, full path, and size. +void CFolder::Refresh(const TCHAR* szPath) +{ + TCHAR pattern[MAX_PATH]; + lstrcpyn(pattern, szPath, 255); + _tcscat(pattern, _T("\\*.*")); + char narrow[MAX_PATH]; + Ansi(narrow, pattern, MAX_PATH); - if (h == INVALID_HANDLE_VALUE) - { - TRACE(_T("\001Cannot read directory: \"%s\" (%d)\n"), szPath, GetLastError()); + WIN32_FIND_DATA found; + HANDLE find = TheseusFindFirstFile(narrow, &found); + if (find == INVALID_HANDLE_VALUE) return; - } - - // Cache the trailing path component as the folder's display name. - const TCHAR* pchName = _tcsrchr(szPath, '\\'); - pchName = (pchName == NULL) ? _T("") : pchName + 1; + const TCHAR* last = _tcsrchr(szPath, '\\'); delete [] m_name; - m_name = new TCHAR [_tcslen(pchName) + 1]; - _tcscpy(m_name, pchName); - + m_name = NewString(last != NULL ? last + 1 : _T("")); + const DWORD skip = FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM | FILE_ATTRIBUTE_TEMPORARY; do { - if (fd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) + if (found.dwFileAttributes & skip) continue; - if (fd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) - continue; - - if (fd.dwFileAttributes & FILE_ATTRIBUTE_TEMPORARY) - continue; + TCHAR entry[MAX_PATH]; + Unicode(entry, found.cFileName, countof(entry)); - TCHAR szFileName [MAX_PATH]; - Unicode(szFileName, fd.cFileName, countof(szFileName)); - - if (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) + if (found.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { - CFolder* pFolder = new CFolder; - m_subFolders.AddNode(pFolder); - - pFolder->m_path = new TCHAR [_tcslen(szPath) + 1 + _tcslen(szFileName) + 1]; - _stprintf(pFolder->m_path, _T("%s\\%s"), szPath, szFileName); - - pFolder->m_name = new TCHAR [_tcslen(szFileName) + 1]; - _tcscpy(pFolder->m_name, szFileName); + CFolder* sub = new CFolder; + m_subFolders.AddNode(sub); + sub->m_path = JoinPath(szPath, entry); + sub->m_name = NewString(entry); + continue; } - else - { - CFile* pFile = new CFile; - m_files.AddNode(pFile); - - pFile->m_date = new CDateObject; - pFile->m_date->m_time = fd.ftLastWriteTime; - const TCHAR* pch = _tcsrchr(szFileName, '.'); + CFile* file = new CFile; + m_files.AddNode(file); - int cchName = _tcslen(szFileName); - if (pch != NULL) - cchName -= _tcslen(pch); - pFile->m_name = new TCHAR [cchName + 1]; - CopyChars(pFile->m_name, szFileName, cchName); - pFile->m_name[cchName] = 0; + file->m_date = new CDateObject; + file->m_date->m_time = found.ftLastWriteTime; - if (pch != NULL) - pch += 1; - else - pch = _T(""); - pFile->m_type = new TCHAR [_tcslen(pch) + 1]; - _tcscpy(pFile->m_type, pch); - _tcslwr(pFile->m_type); + const TCHAR* dot = _tcsrchr(entry, '.'); + int stem = (int)_tcslen(entry) - (dot != NULL ? (int)_tcslen(dot) : 0); + file->m_name = new TCHAR [stem + 1]; + CopyChars(file->m_name, entry, stem); + file->m_name[stem] = 0; - pFile->m_path = new TCHAR [_tcslen(szPath) + 1 + _tcslen(szFileName) + 1]; - _stprintf(pFile->m_path, _T("%s\\%s"), szPath, szFileName); + file->m_type = NewString(dot != NULL ? dot + 1 : _T("")); + _tcslwr(file->m_type); - pFile->m_length = fd.nFileSizeLow; - } + file->m_path = JoinPath(szPath, entry); + file->m_length = found.nFileSizeLow; } - while (TheseusFindNextFile(h, &fd)); + while (TheseusFindNextFile(find, &found)); - TheseusFindClose(h); + TheseusFindClose(find); } -static int __cdecl CmpName(const void* p1, const void* p2) +// CFolder::sortByName / Type / Date / Length [script fns] +// Reconstructed from 5960 retail XBE @ 0x31f30..0x32010: qsort the files +// by name or type ignoring case, by write time, or by size. +static CFile* FileAt(const void* p) { - const CFile* pFile1 = *(CFile**)p1; - const CFile* pFile2 = *(CFile**)p2; - - return _tcsicmp(pFile1->m_name, pFile2->m_name); + return *(CFile* const*)p; } -void CFolder::sortByName() +static int __cdecl ByName(const void* a, const void* b) { - m_files.Sort(&CmpName); + return _tcsicmp(FileAt(a)->m_name, FileAt(b)->m_name); } -static int __cdecl CmpType(const void* p1, const void* p2) +static int __cdecl ByType(const void* a, const void* b) { - const CFile* pFile1 = *(CFile**)p1; - const CFile* pFile2 = *(CFile**)p2; - - return _tcsicmp(pFile1->m_type, pFile2->m_type); + return _tcsicmp(FileAt(a)->m_type, FileAt(b)->m_type); } -void CFolder::sortByType() +static int __cdecl ByDate(const void* a, const void* b) { - m_files.Sort(CmpType); + return CompareFileTime(&FileAt(a)->m_date->m_time, &FileAt(b)->m_date->m_time); } -static int __cdecl CmpDate(const void* p1, const void* p2) +static int __cdecl ByLength(const void* a, const void* b) { - const CFile* pFile1 = *(CFile**)p1; - const CFile* pFile2 = *(CFile**)p2; - - return CompareFileTime(&pFile1->m_date->m_time, &pFile2->m_date->m_time); + return FileAt(a)->m_length - FileAt(b)->m_length; } -void CFolder::sortByDate() +void CFolder::sortByName() { - m_files.Sort(CmpDate); + m_files.Sort(ByName); } -static int __cdecl CmpLength(const void* p1, const void* p2) +void CFolder::sortByType() { - const CFile* pFile1 = *(CFile**)p1; - const CFile* pFile2 = *(CFile**)p2; + m_files.Sort(ByType); +} - return pFile1->m_length - pFile2->m_length; +void CFolder::sortByDate() +{ + m_files.Sort(ByDate); } void CFolder::sortByLength() { - m_files.Sort(CmpLength); + m_files.Sort(ByLength); } From 1311151b57719316541d83704d559a391b71d98f Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:42:49 -0500 Subject: [PATCH 3/6] Rebuilt the audio clip and sound buffers from the binary Rewrote AudioClip, PeriodicAudioGroup and the buffer and stream classes from the 5960 code. The MP3 pump is Theseus's own and stays as it was. A harness driving clips through random property changes, wave files good and broken, and the stream thread printed the same 140,755 lines old and new over 500 runs. Needs a console run. --- docs/decomp/AudioSystem.md | 35 + theseus/engine/audio_pump.h | 113 ++- theseus/shared/audio.h | 23 +- theseus/shared/audio_system.cpp | 1424 +++++++++++++------------------ 4 files changed, 708 insertions(+), 887 deletions(-) diff --git a/docs/decomp/AudioSystem.md b/docs/decomp/AudioSystem.md index 5f9f1fe..44278ae 100644 --- a/docs/decomp/AudioSystem.md +++ b/docs/decomp/AudioSystem.md @@ -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`. diff --git a/theseus/engine/audio_pump.h b/theseus/engine/audio_pump.h index 9521a4d..60ca49c 100755 --- a/theseus/engine/audio_pump.h +++ b/theseus/engine/audio_pump.h @@ -1,8 +1,8 @@ -// audio_pump.h: DirectSound buffer class hierarchy used by the audio -// system. CAudioBuf is the static-buffer base used for short SFX; -// streaming subclasses (CAudioPump, CFilePump, etc.) layer worker-thread -// segment-fed playback on top. Companion to shared/audio_system.cpp. -// See docs/decomp/AudioSystem.md. +// audio_pump.h: the sound buffers behind an AudioClip. CAudioBuf holds a +// whole short sound in one DirectSound buffer; CAudioPump streams through +// a ring of segments refilled by a worker thread, and CFilePump (wave +// files) and CMP3Pump (soundtracks) feed it. Built by +// shared/audio_system.cpp. See docs/decomp/AudioSystem.md. #pragma once @@ -11,7 +11,7 @@ #include <dsound.h> #endif -// Static audio buffer for short SFX clips. +// A whole sound in one buffer. class CAudioBuf { public: @@ -24,24 +24,23 @@ class CAudioBuf virtual bool Play(bool bLoop = false); virtual void Stop(); - virtual float GetPlaybackTime(); - virtual float GetPlaybackLength(); // NOTE: will return 0 if unknown! - virtual bool IsPlaying(); - virtual void Pause(bool bPause); - inline bool IsPaused() const { return m_paused; } - + virtual bool IsPlaying(); + virtual float GetPlaybackTime(); + virtual float GetPlaybackLength(); // 0 when the length isn't known virtual void* GetSampleBuffer(); virtual DWORD GetSampleBufferSize(); - void SetAttenuation(float nAttenuation); // 0..100 dB - void SetPan(float nPan); // -100..100 dB - void SetFrequency(float nFrequency); // 0 (normal), or 100..100,000 + bool IsPaused() const { return m_paused; } + + void SetAttenuation(float nAttenuation); // dB down, 0..100 + void SetPan(float nPan); + void SetFrequency(float nFrequency); // 0 plays at the recorded rate protected: bool m_loop; bool m_paused; - int m_bufferBytes; + int m_bufferBytes; // one segment for a pump int m_bytesPerSecond; #ifdef _XBOX LPDIRECTSOUNDBUFFER m_dsBuffer; @@ -50,8 +49,7 @@ class CAudioBuf #endif }; - -// Double-buffered Audio Buffer for streaming... +// A ring of segments a worker thread keeps filled from GetData. class CAudioPump : public CAudioBuf { public: @@ -62,48 +60,36 @@ class CAudioPump : public CAudioBuf virtual bool Play(bool bLoop = false); virtual void Stop(); + virtual void Pause(bool bPause); virtual bool IsPlaying(); virtual float GetPlaybackTime(); - virtual void Pause(bool bPause); - virtual float GetPlaybackLength(); // NOTE: will return 0 if unknown! - - - int m_segmentsPerBuffer; + virtual float GetPlaybackLength(); protected: - enum - { - PUMPSTATE_STOPPED, - PUMPSTATE_BUFFERING, - PUMPSTATE_RUNNING, - PUMPSTATE_STOPPING, - }; - - static DWORD CALLBACK StartThread(LPVOID pvContext); - DWORD ThreadProc(); + enum { PUMP_STOPPED, PUMP_BUFFERING, PUMP_RUNNING, PUMP_DRAINING }; - HANDLE m_playThread; - HANDLE m_terminateEvent; - HANDLE m_runEvent; - HANDLE* m_notifyEvents; // m_segmentsPerBuffer events - HANDLE m_mutex; - - DWORD m_prevCursor; - int m_completedBuffers; - int m_filledBuffers; - bool* m_bufferFilled; // m_segmentsPerBuffer bools - int m_pumpState; - - int m_prebufferSegments; + static DWORD CALLBACK ThreadEntry(LPVOID pvContext); + DWORD ThreadProc(); + bool FillBuffer(int nSegment); - bool FillBuffer(int nBuffer); + // Fills up to cbBuffer bytes; fewer means the sound has ended. virtual int GetData(BYTE* pbBuffer, int cbBuffer) = 0; - virtual void OnAudioEnd() {} - + virtual void OnAudioEnd() {} + + int m_segments; + int m_prebuffer; + int m_state; + int m_filled; // segments filled since the last stop + int m_wraps; // times the play cursor went round + DWORD m_lastCursor; + bool* m_segmentFilled; + HANDLE* m_segmentEvents; // set as playback crosses each segment end + HANDLE m_quit; + HANDLE m_lock; + HANDLE m_worker; }; - -// Audio Buffer for streaming large files... +// Streams the data chunk of an open wave file. class CFilePump : public CAudioPump { public: @@ -111,26 +97,23 @@ class CFilePump : public CAudioPump virtual ~CFilePump(); HRESULT Initialize(HANDLE hFile, int nFileBytes, WAVEFORMATEX* pFormat); - virtual void Stop(); + virtual void Stop(); virtual float GetPlaybackLength(); - virtual void* GetSampleBuffer(); virtual DWORD GetSampleBufferSize(); protected: virtual int GetData(BYTE* pbBuffer, int cbBuffer); + HANDLE m_file; - void* m_buffer; - float m_playbackLength; - DWORD m_startPos; - DWORD m_bufferSize; + DWORD m_dataStart; // file offset of the first sample + float m_seconds; + void* m_lastBlock; + DWORD m_blockBytes; }; -// MP3 streaming decoder for soundtrack playback -// mp3dec_t is defined in minimp3.h; include it before audio_pump.h -// or use an opaque pointer (we use void* internally, cast in .cpp) - +// Decodes an MP3 soundtrack with minimp3 (see minimp3_decode.cpp). class CMP3Pump : public CAudioPump { public: @@ -139,18 +122,18 @@ class CMP3Pump : public CAudioPump HRESULT Initialize(const char* szFilePath); + virtual void Stop(); virtual float GetPlaybackLength(); virtual void* GetSampleBuffer(); virtual DWORD GetSampleBufferSize(); - virtual void Stop(); protected: virtual int GetData(BYTE* pbBuffer, int cbBuffer); - BYTE* m_fileData; // entire MP3 file in memory + BYTE* m_fileData; // the whole file int m_fileSize; - int m_fileOffset; // current read position - void* m_decoder; // mp3dec_t*, opaque here to avoid header dep + int m_fileOffset; // next byte to decode + void* m_decoder; // mp3dec_t, kept opaque so callers needn't include minimp3.h void* m_buffer; DWORD m_bufferSize; float m_playbackLength; diff --git a/theseus/shared/audio.h b/theseus/shared/audio.h index f2954aa..1c4a3fa 100755 --- a/theseus/shared/audio.h +++ b/theseus/shared/audio.h @@ -1,9 +1,11 @@ -// audio.h: CAudioClip XAP node, the script-facing audio player. -// Wraps CAudioBuf (DirectSound voice) plus the MP3 / WAV file -// loaders. Companion to shared/audio_system.cpp. +// audio.h: the AudioClip node scripts use to play a sound: a wave file, +// or a soundtrack song as st:<id>. Built by shared/audio_system.cpp. +// render/tmap_system.cpp reads m_transportMode and the sample buffer for +// the visualizer, so the member order here is load bearing. #pragma once +// transportMode values the scripts see. #define TRANSPORT_STOP 0 #define TRANSPORT_PLAY 1 #define TRANSPORT_PAUSE 2 @@ -18,14 +20,12 @@ class CAudioClip : public CTimeDepNode ~CAudioClip(); TCHAR* m_url; - void SetUrl(const TCHAR* AudioFile); - bool m_capturedLoop; // local copy of CTimeDepNode::m_loop captured at Play() time + bool m_capturedLoop; // m_loop as it was when Play started bool m_isActive; - - bool m_sendProgress; - bool m_pause_on_moving; + bool m_sendProgress; // keep m_progress updated and fire OnProgressChanged + bool m_pause_on_moving; // hold the sound while the menus change level float m_progress; bool m_removeVoice; int m_transportMode; @@ -35,7 +35,6 @@ class CAudioClip : public CTimeDepNode void Pause(); void PlayOrPause(); void Stop(); - int getMinutes(); int getSeconds(); @@ -46,12 +45,12 @@ class CAudioClip : public CTimeDepNode HRESULT Cleanup(); protected: - bool m_dirty; - bool m_unpauseNeeded; + bool m_dirty; // url changed; the sound gets loaded again + bool m_unpauseNeeded; // paused for a level change, resume after float m_lastVolume; float m_lastPan; float m_lastFrequency; - float m_fade; + float m_fade; // seconds a volume or pan change glides over float m_volume; float m_pan; float m_frequency; diff --git a/theseus/shared/audio_system.cpp b/theseus/shared/audio_system.cpp index c213331..358f88c 100755 --- a/theseus/shared/audio_system.cpp +++ b/theseus/shared/audio_system.cpp @@ -1,8 +1,10 @@ -// audio_system.cpp: DirectSound-based audio pipeline. Three layers: -// CAudioBuf (static buffer), CAudioPump (streaming base with worker -// thread), and the script-callable CAudioClip / CMusicCollection / -// CFilePump nodes. Decompiled from the 5960 retail XBE; see -// docs/decomp/AudioSystem.md. +// audio_system.cpp: sound playback for the Xbox build. CAudioBuf holds a +// short sound whole, CAudioPump streams a long one through a ring of +// segments, CFilePump reads wave data for it and CMP3Pump decodes +// soundtrack MP3s (Theseus's, 5960 streams WMA). On top sit the AudioClip +// and PeriodicAudioGroup nodes. Rebuilt from the 5960 retail XBE +// (0x61890..0x63320); see docs/decomp/AudioSystem.md. Theseus creates +// buffers through DSoundManager instead of 5960's XAppCreateSoundBuffer. #include "std.h" #include "theseus.h" @@ -19,117 +21,113 @@ #include "toolbox/xboxinternals.h" #include "minimp3.h" -// Latches the most recently active CAudioClip's removeVoice setting so the -// audio mixer can decide whether to keep the voice channel allocated when -// the clip stops. Set every Advance pass; read by the dsound pump on the -// next buffer notify. +// removeVoice of the clip that advanced last (5960 keeps it at 0x17e768). bool g_removeVoice = false; extern bool g_bLevelTransition; +static DWORD LoopFlag(bool loop) +{ + return loop ? DSBPLAY_LOOPING : 0; +} + // ========================================================================= -// CAudioBuf: single-shot sound buffer +// CAudioBuf // ========================================================================= +// 5960 builds these inline where a short wave file is loaded (0x61d20): +// no buffer yet, not looping, not paused. CAudioBuf::CAudioBuf() { - m_dsBuffer = NULL; - m_paused = false; m_loop = false; + m_paused = false; m_bufferBytes = 0; + m_dsBuffer = NULL; } +// CAudioBuf::~CAudioBuf +// Reconstructed from 5960 retail XBE @ 0x62960: stop and release the buffer. CAudioBuf::~CAudioBuf() { - if (m_dsBuffer != NULL) - { - m_dsBuffer->Stop(); - m_dsBuffer->Release(); - } + if (m_dsBuffer == NULL) + return; + m_dsBuffer->Stop(); + m_dsBuffer->Release(); } -HRESULT CAudioBuf::Initialize(WAVEFORMATEX* pWaveFormat, int nBufferBytes, const void* pvSamples/*=NULL*/) +// CAudioBuf::Initialize(format, bytes, samples) +// 5960 inlines this into the wave loader: remember the size and byte rate, +// make a buffer with volume and frequency control. Theseus can also hand +// the samples over up front. +HRESULT CAudioBuf::Initialize(WAVEFORMATEX* pWaveFormat, int nBufferBytes, const void* pvSamples) { m_bufferBytes = nBufferBytes; m_bytesPerSecond = pWaveFormat->nAvgBytesPerSec; - HRESULT hr = DSoundManager::Instance()->DSoundCreateSoundBuffer( - pWaveFormat, nBufferBytes, - DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLFREQUENCY, - &m_dsBuffer); - if (FAILED(hr) || m_dsBuffer == NULL) - { - DbgPrint("CAudioBuf::Initialize - fail to create sound buffer"); - return FAILED(hr) ? hr : E_INVALIDARG; - } + DSoundManager* ds = DSoundManager::Instance(); + HRESULT hr = ds->DSoundCreateSoundBuffer(pWaveFormat, nBufferBytes, DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLFREQUENCY, &m_dsBuffer); + if (FAILED(hr)) + return hr; + if (m_dsBuffer == NULL) + return E_INVALIDARG; if (pvSamples != NULL) { - hr = DSoundManager::Instance()->DSoundSetSoundBufferData( - m_dsBuffer, 0, nBufferBytes, pvSamples); + hr = ds->DSoundSetSoundBufferData(m_dsBuffer, 0, nBufferBytes, pvSamples); if (FAILED(hr)) - { - DbgPrint("CAudioBuf::Initialize - fail to set sound buffer"); return hr; - } } - return S_OK; } +// CAudioBuf::Lock / Unlock +// Reconstructed from 5960 retail XBE @ 0x629a0 / 0x629d0: the whole buffer +// from offset 0. void* CAudioBuf::Lock() { - LPVOID pvBuffer; - DWORD dwBufferLength; - - ASSERT(m_dsBuffer != NULL); - - VERIFYHR(m_dsBuffer->Lock(0, m_bufferBytes, &pvBuffer, &dwBufferLength, NULL, NULL, 0L)); - ASSERT(dwBufferLength == (DWORD)m_bufferBytes); - return pvBuffer; + void* data; + DWORD bytes; + m_dsBuffer->Lock(0, m_bufferBytes, &data, &bytes, NULL, NULL, 0); + return data; } void CAudioBuf::Unlock(void* pvBuffer) { - VERIFYHR(m_dsBuffer->Unlock(pvBuffer, m_bufferBytes, NULL, 0)); + m_dsBuffer->Unlock(pvBuffer, m_bufferBytes, NULL, 0); } -bool CAudioBuf::Play(bool bLoop/*=false*/) +// Rewind and start, looping if asked. False with no buffer. +bool CAudioBuf::Play(bool bLoop) { m_paused = false; m_loop = bLoop; - if (m_dsBuffer == NULL) return false; - VERIFYHR(m_dsBuffer->SetCurrentPosition(0)); - VERIFYHR(m_dsBuffer->Play(0, 0, m_loop ? DSBPLAY_LOOPING : 0)); - + m_dsBuffer->SetCurrentPosition(0); + m_dsBuffer->Play(0, 0, LoopFlag(m_loop)); return true; } +// CAudioBuf::Stop +// 5960 @ 0x62a30 stops the buffer (and then waits for it to report +// stopped; Theseus doesn't wait). void CAudioBuf::Stop() { if (m_dsBuffer != NULL) - { - VERIFYHR(m_dsBuffer->Stop()); - } + m_dsBuffer->Stop(); } +// Theseus pauses by stopping in place and resumes with Play. void CAudioBuf::Pause(bool bPause) { if (m_dsBuffer == NULL) return; + m_paused = bPause; if (bPause) - { - m_paused = true; - VERIFYHR(m_dsBuffer->Stop()); - } + m_dsBuffer->Stop(); else - { - m_paused = false; - VERIFYHR(m_dsBuffer->Play(0, 0, m_loop ? DSBPLAY_LOOPING : 0)); - } + m_dsBuffer->Play(0, 0, LoopFlag(m_loop)); } bool CAudioBuf::IsPlaying() @@ -137,26 +135,29 @@ bool CAudioBuf::IsPlaying() if (m_dsBuffer == NULL) return false; - DWORD dwStatus; - VERIFYHR(m_dsBuffer->GetStatus(&dwStatus)); - return (dwStatus & DSBSTATUS_PLAYING) != 0; + DWORD status; + m_dsBuffer->GetStatus(&status); + return (status & DSBSTATUS_PLAYING) != 0; } +// Attenuation in dB to DirectSound's hundredths of a dB, negative. void CAudioBuf::SetAttenuation(float nAttenuation) { - ASSERT(m_dsBuffer != NULL); - VERIFYHR(m_dsBuffer->SetVolume(-(int)(nAttenuation * 100.0f))); + m_dsBuffer->SetVolume(-(int)(nAttenuation * 100.0f)); } +// 5960's clip remembers pan but never applies it. void CAudioBuf::SetPan(float nPan) { - ASSERT(m_dsBuffer != NULL); } +// CAudioBuf::SetFrequency(hz) +// Reconstructed from 5960 retail XBE @ 0x62ad0: +// SetFrequency(buffer, hz == 0 ? 0 : (int)hz); +// 0 is DSBFREQUENCY_ORIGINAL. void CAudioBuf::SetFrequency(float nFrequency) { - ASSERT(m_dsBuffer != NULL); - VERIFYHR(m_dsBuffer->SetFrequency(nFrequency == 0.0f ? DSBFREQUENCY_ORIGINAL : (DWORD)nFrequency)); + m_dsBuffer->SetFrequency(nFrequency == 0.0f ? DSBFREQUENCY_ORIGINAL : (DWORD)nFrequency); } float CAudioBuf::GetPlaybackTime() @@ -164,10 +165,9 @@ float CAudioBuf::GetPlaybackTime() if (m_dsBuffer == NULL) return 0.0f; - DWORD dwPlayCursor; - VERIFYHR(m_dsBuffer->GetCurrentPosition(&dwPlayCursor, NULL)); - - return (float)dwPlayCursor / m_bytesPerSecond; + DWORD cursor; + m_dsBuffer->GetCurrentPosition(&cursor, NULL); + return (float)cursor / m_bytesPerSecond; } float CAudioBuf::GetPlaybackLength() @@ -175,45 +175,55 @@ float CAudioBuf::GetPlaybackLength() return (float)m_bufferBytes / m_bytesPerSecond; } -void* CAudioBuf::GetSampleBuffer() { return NULL; } -DWORD CAudioBuf::GetSampleBufferSize() { return 0; } +void* CAudioBuf::GetSampleBuffer() +{ + return NULL; +} + +DWORD CAudioBuf::GetSampleBufferSize() +{ + return 0; +} // ========================================================================= -// CAudioPump: streaming audio with threaded buffer fill +// CAudioPump // ========================================================================= +// 5960's pump constructor is folded into its subclasses (0x63220, +// 0x63430): everything zero and stopped. CAudioPump::CAudioPump() { - m_playThread = NULL; - m_terminateEvent = NULL; - m_mutex = NULL; m_bufferBytes = 0; - m_completedBuffers = 0; - m_prevCursor = 0; - m_filledBuffers = 0; - m_pumpState = PUMPSTATE_STOPPED; - - m_notifyEvents = NULL; - m_segmentsPerBuffer = 0; - m_bufferFilled = 0; + m_segments = 0; + m_prebuffer = 0; + m_state = PUMP_STOPPED; + m_filled = 0; + m_wraps = 0; + m_lastCursor = 0; + m_segmentFilled = NULL; + m_segmentEvents = NULL; + m_quit = NULL; + m_lock = NULL; + m_worker = NULL; } +// CAudioPump::~CAudioPump +// Reconstructed from 5960 retail XBE @ 0x62b90: tell the worker to quit +// and wait for it, close the quit event and the lock, stop and release +// the buffer, close the segment events, free the arrays. CAudioPump::~CAudioPump() { - if (m_terminateEvent != NULL) - SetEvent(m_terminateEvent); - - if (m_playThread != NULL) + if (m_quit != NULL) + SetEvent(m_quit); + if (m_worker != NULL) { - WaitForSingleObject(m_playThread, INFINITE); - CloseHandle(m_playThread); + WaitForSingleObject(m_worker, INFINITE); + CloseHandle(m_worker); } - - if (m_terminateEvent != NULL) - CloseHandle(m_terminateEvent); - - if (m_mutex != NULL) - CloseHandle(m_mutex); + if (m_quit != NULL) + CloseHandle(m_quit); + if (m_lock != NULL) + CloseHandle(m_lock); if (m_dsBuffer != NULL) { @@ -222,466 +232,365 @@ CAudioPump::~CAudioPump() m_dsBuffer = NULL; } - if(m_notifyEvents){ - int i; - for (i = 0; i < m_segmentsPerBuffer; i++) - { - if (m_notifyEvents[i]) - CloseHandle(m_notifyEvents[i]); - } - delete [] m_notifyEvents; - } - if(m_bufferFilled){ - delete [] m_bufferFilled; - } + if (m_segmentEvents != NULL) + { + for (int i = 0; i < m_segments; i++) + { + if (m_segmentEvents[i] != NULL) + CloseHandle(m_segmentEvents[i]); + } + delete [] m_segmentEvents; + } + delete [] m_segmentFilled; } -DWORD CALLBACK CAudioPump::StartThread(LPVOID pvContext) +DWORD CALLBACK CAudioPump::ThreadEntry(LPVOID pvContext) { - CAudioPump *pThis = (CAudioPump*)pvContext; - return pThis->ThreadProc(); + return ((CAudioPump*)pvContext)->ThreadProc(); } +// CAudioPump::ThreadProc +// Reconstructed from 5960 retail XBE @ 0x62c90. Waits on the quit event +// plus every segment event, then on quit or the lock. Quit stops playback +// and ends the thread. Holding the lock: nothing to do when stopped; while +// buffering the next segment in order is filled; once draining with no +// filled segments left it stops and runs OnAudioEnd; otherwise the first +// signaled segment is refilled. The lock is let go before waiting again. +// 5960 also clears a segment's filled mark and drops the count when it +// comes round; Theseus doesn't (see the doc). DWORD CAudioPump::ThreadProc() { - const HANDLE ahMutex[] = { m_terminateEvent, m_mutex }; - HANDLE* ahNotify = new HANDLE[1 + m_segmentsPerBuffer]; - if(!ahNotify){ - return -1; - } - int nBuffer; - bool fMutex = false; - DWORD dwWaitObj; - - ahNotify[0] = m_terminateEvent; + HANDLE* waitList = new HANDLE [m_segments + 1]; + if (waitList == NULL) + return (DWORD)-1; - for (int i = 0; i < m_segmentsPerBuffer; i++) - { - ahNotify[i + 1] = m_notifyEvents[i]; - } + waitList[0] = m_quit; + for (int i = 0; i < m_segments; i++) + waitList[i + 1] = m_segmentEvents[i]; + const HANDLE quitOrLock[] = { m_quit, m_lock }; + bool locked = false; for (;;) { - if (fMutex) - { - ReleaseMutex(m_mutex); - fMutex = false; - } - - dwWaitObj = WaitForMultipleObjects(1 + m_segmentsPerBuffer, ahNotify, FALSE, INFINITE); - if (dwWaitObj == WAIT_OBJECT_0) - { - break; - } - - dwWaitObj = WaitForMultipleObjects(2, ahMutex, FALSE, INFINITE); - if (dwWaitObj == WAIT_OBJECT_0) - { + if (locked) + { + ReleaseMutex(m_lock); + locked = false; + } + + if (WaitForMultipleObjects(m_segments + 1, waitList, FALSE, INFINITE) == WAIT_OBJECT_0) break; - } - - fMutex = true; - - if (m_pumpState == PUMPSTATE_STOPPED) - { - continue; - } - - if (m_pumpState == PUMPSTATE_BUFFERING) - { - FillBuffer(m_filledBuffers); - continue; - } - - if ((m_pumpState == PUMPSTATE_STOPPING) && (m_filledBuffers <= 0)) - { - Stop(); - OnAudioEnd(); // check if smthng to be done at the end of the play, - // eg. change track to the next one for the CD player - continue; - } - - int i; - for (i = 0; i < m_segmentsPerBuffer; i++) - { - if (WAIT_OBJECT_0 == WaitForSingleObject(m_notifyEvents[i], 0)) - { - nBuffer = i; - - break; - } - } - - if (i >= m_segmentsPerBuffer) - { - continue; - } - - // We start the ball rolling by signaled all events. This - // wakes us enough times that we can fill up all our buffers. - // But, a side effect is that we get a bunch of false - // signals. When we are playing very short audio clips, there may - // actually be more false signals than there is data to play. - // To keep this case from confusing us, we need to keep track - // of which buffers actually have data in them. - // - // The m_bufferFilled array keeps track of which buffers are - // actually filled. This allows us to distinguish the initial - // false signals from the normal signals. - - FillBuffer(nBuffer); - } + if (WaitForMultipleObjects(2, quitOrLock, FALSE, INFINITE) == WAIT_OBJECT_0) + break; + locked = true; - Stop(); + if (m_state == PUMP_STOPPED) + continue; + + if (m_state == PUMP_BUFFERING) + { + FillBuffer(m_filled); + continue; + } - if (fMutex) - { - ReleaseMutex(m_mutex); - } + if (m_state == PUMP_DRAINING && m_filled <= 0) + { + Stop(); + OnAudioEnd(); + continue; + } - if(ahNotify){ - delete [] ahNotify; - } + int seg = 0; + while (seg < m_segments && WaitForSingleObject(m_segmentEvents[seg], 0) != WAIT_OBJECT_0) + seg++; + if (seg < m_segments) + FillBuffer(seg); + } + Stop(); + if (locked) + ReleaseMutex(m_lock); + delete [] waitList; return 0; } +// CAudioPump::Initialize(stack, format, segmentBytes, segments, prebuffer) +// Reconstructed from 5960 retail XBE @ 0x62de0. Keeps the segment size and +// byte rate, makes one manual reset event per segment, an auto reset quit +// event, the lock and the worker thread, then a buffer of segments * +// segmentBytes with position notify, volume and frequency control. Each +// segment's event fires a block before its end. Theseus reports which step +// failed instead of a bool. HRESULT CAudioPump::Initialize(DWORD dwStackSize, WAVEFORMATEX* pWaveFormat, int nBufferBytes, int nSegmentsPerBuffer, int nPrebufferSegments) { - m_bytesPerSecond = pWaveFormat->nAvgBytesPerSec; m_bufferBytes = nBufferBytes; + m_segments = nSegmentsPerBuffer; + m_prebuffer = nPrebufferSegments; - m_segmentsPerBuffer = nSegmentsPerBuffer; - m_prebufferSegments = nPrebufferSegments; - - ASSERT((m_prebufferSegments <= m_segmentsPerBuffer)); + m_segmentEvents = new HANDLE [m_segments]; + if (m_segmentEvents == NULL) + return E_OUTOFMEMORY; + for (int i = 0; i < m_segments; i++) + m_segmentEvents[i] = NULL; - m_notifyEvents = new HANDLE[m_segmentsPerBuffer]; - if(m_notifyEvents == NULL) - { - return E_OUTOFMEMORY; - } - - int i; - for (i = 0; i < m_segmentsPerBuffer; i++) - { - m_notifyEvents[i] = NULL; - } - - m_terminateEvent = CreateEvent(NULL, FALSE, FALSE, NULL); - ASSERT( m_terminateEvent != INVALID_HANDLE_VALUE); - if(m_terminateEvent == INVALID_HANDLE_VALUE) - { + m_quit = CreateEvent(NULL, FALSE, FALSE, NULL); + if (m_quit == INVALID_HANDLE_VALUE) return ERROR_INVALID_HANDLE; - } - - m_mutex = CreateMutex(NULL, FALSE, NULL); - ASSERT(m_mutex != INVALID_HANDLE_VALUE ); - if(m_mutex == INVALID_HANDLE_VALUE) - { + m_lock = CreateMutex(NULL, FALSE, NULL); + if (m_lock == INVALID_HANDLE_VALUE) return ERROR_INVALID_HANDLE; - } - - for (i = 0; i < m_segmentsPerBuffer; i++) - { - m_notifyEvents[i] = CreateEvent(NULL, TRUE, FALSE, NULL); - if(m_notifyEvents[i] == INVALID_HANDLE_VALUE) - { + for (int i = 0; i < m_segments; i++) + { + m_segmentEvents[i] = CreateEvent(NULL, TRUE, FALSE, NULL); + if (m_segmentEvents[i] == INVALID_HANDLE_VALUE) return E_OUTOFMEMORY; - } - } - - m_bufferFilled = new bool[m_segmentsPerBuffer]; - if(!m_bufferFilled){ - return E_OUTOFMEMORY; - } + } - DWORD dwThreadId; - m_playThread = CreateThread(NULL, dwStackSize, StartThread, this, 0, &dwThreadId); + m_segmentFilled = new bool [m_segments]; + if (m_segmentFilled == NULL) + return E_OUTOFMEMORY; - ASSERT(m_playThread!= INVALID_HANDLE_VALUE); - if(m_playThread == INVALID_HANDLE_VALUE) - { + DWORD id; + m_worker = CreateThread(NULL, dwStackSize, ThreadEntry, this, 0, &id); + if (m_worker == INVALID_HANDLE_VALUE) return ERROR_INVALID_HANDLE; - } - HRESULT hr = DSoundManager::Instance()->DSoundCreateSoundBuffer(pWaveFormat, m_segmentsPerBuffer * m_bufferBytes, DSBCAPS_CTRLPOSITIONNOTIFY | DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLFREQUENCY, &m_dsBuffer); - - if (m_dsBuffer == NULL) - { - DbgPrint("CAudioPump::Initialize - fail to create sound buffer"); + DSoundManager* ds = DSoundManager::Instance(); + HRESULT hr = ds->DSoundCreateSoundBuffer(pWaveFormat, m_segments * m_bufferBytes, + DSBCAPS_CTRLPOSITIONNOTIFY | DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLFREQUENCY, &m_dsBuffer); + if (m_dsBuffer == NULL) return hr; - } - // Wire each segment boundary to its corresponding notify event so the - // pump thread wakes up exactly when a buffer slot is ready to be refilled. - DSBPOSITIONNOTIFY* dsbpn = new DSBPOSITIONNOTIFY[m_segmentsPerBuffer]; - if (dsbpn == NULL) + DSBPOSITIONNOTIFY* marks = new DSBPOSITIONNOTIFY [m_segments]; + if (marks == NULL) return E_OUTOFMEMORY; - - for (i = 0; i < m_segmentsPerBuffer; i++) + for (int i = 0; i < m_segments; i++) { - dsbpn[i].dwOffset = m_bufferBytes * (i + 1) - pWaveFormat->nBlockAlign; - dsbpn[i].hEventNotify = m_notifyEvents[i]; + marks[i].dwOffset = (i + 1) * m_bufferBytes - pWaveFormat->nBlockAlign; + marks[i].hEventNotify = m_segmentEvents[i]; } - - hr = DSoundManager::Instance()->DSoundSetSoundBufferNotify(m_dsBuffer, m_segmentsPerBuffer, dsbpn); - if (FAILED(hr)) - DbgPrint("CAudioPump::Initialize - fail to set sound buffer notify"); - - delete [] dsbpn; + hr = ds->DSoundSetSoundBufferNotify(m_dsBuffer, m_segments, marks); + delete [] marks; return hr; } -bool CAudioPump::Play(bool bLoop/*=false*/) +// Theseus's Play: under the lock, stop, then start buffering with every +// segment event set so the worker fills them all, fill the prebuffer +// segments here, and start the ring looping. +bool CAudioPump::Play(bool bLoop) { - m_loop = bLoop; - + m_loop = bLoop; if (m_dsBuffer == NULL) return false; - WaitForSingleObject(m_mutex, INFINITE); - - Stop(); - - m_pumpState = PUMPSTATE_BUFFERING; - - int i; - for (i = 0; i < m_segmentsPerBuffer; i++) - { - SetEvent(m_notifyEvents[i]); - m_bufferFilled[i] = false; - } - - for (i = 0; i < m_prebufferSegments; i++) - { - FillBuffer(i); - } - - VERIFYHR(m_dsBuffer->Play(0, 0, DSBPLAY_LOOPING)); - - ReleaseMutex(m_mutex); - + WaitForSingleObject(m_lock, INFINITE); + Stop(); + m_state = PUMP_BUFFERING; + for (int i = 0; i < m_segments; i++) + { + SetEvent(m_segmentEvents[i]); + m_segmentFilled[i] = false; + } + for (int i = 0; i < m_prebuffer; i++) + FillBuffer(i); + m_dsBuffer->Play(0, 0, DSBPLAY_LOOPING); + ReleaseMutex(m_lock); return true; } +// CAudioPump::Stop +// Reconstructed from 5960 retail XBE @ 0x62fe0. Under the lock: stop, +// rewind, let DirectSound catch up, clear every segment event, and reset +// the counters to stopped. void CAudioPump::Stop() { if (m_dsBuffer == NULL) return; - WaitForSingleObject(m_mutex, INFINITE); - - VERIFYHR(m_dsBuffer->Stop()); - VERIFYHR(m_dsBuffer->SetCurrentPosition(0)); - - DirectSoundDoWork(); - - int i; - for (i = 0; i < m_segmentsPerBuffer; i++) - { - ResetEvent(m_notifyEvents[i]); - } - - m_completedBuffers = 0; - m_filledBuffers = 0; - m_pumpState = PUMPSTATE_STOPPED; - - ReleaseMutex(m_mutex); + WaitForSingleObject(m_lock, INFINITE); + m_dsBuffer->Stop(); + m_dsBuffer->SetCurrentPosition(0); + DirectSoundDoWork(); + for (int i = 0; i < m_segments; i++) + ResetEvent(m_segmentEvents[i]); + m_wraps = 0; + m_filled = 0; + m_state = PUMP_STOPPED; + ReleaseMutex(m_lock); } +// CAudioPump::Pause(pause) +// Reconstructed from 5960 retail XBE @ 0x63060: flag and buffer under the +// lock. 5960 calls IDirectSoundBuffer_Pause; Theseus stops and replays. void CAudioPump::Pause(bool bPause) { if (m_dsBuffer == NULL) return; - WaitForSingleObject(m_mutex, INFINITE); - + WaitForSingleObject(m_lock, INFINITE); + m_paused = bPause; if (bPause) - { - m_paused = true; - VERIFYHR(m_dsBuffer->Stop()); - } + m_dsBuffer->Stop(); else - { - m_paused = false; - VERIFYHR(m_dsBuffer->Play(0, 0, DSBPLAY_LOOPING)); - } - - ReleaseMutex(m_mutex); + m_dsBuffer->Play(0, 0, DSBPLAY_LOOPING); + ReleaseMutex(m_lock); } bool CAudioPump::IsPlaying() { - return (PUMPSTATE_STOPPED != m_pumpState); + return m_state != PUMP_STOPPED; } -bool CAudioPump::FillBuffer(int nBuffer) +// CAudioPump::FillBuffer(segment) +// Reconstructed from 5960 retail XBE @ 0x630d0. Under the lock: clear the +// segment's event, lock its bytes and ask GetData for them (nothing once +// draining). A short read means the sound is ending: drain, and zero the +// rest. A segment that got data is marked filled and counted; when +// buffering has filled the whole ring the pump is running. True when +// there was data. +bool CAudioPump::FillBuffer(int nSegment) { - int nBytes; + WaitForSingleObject(m_lock, INFINITE); + ResetEvent(m_segmentEvents[nSegment]); - ASSERT(m_dsBuffer != NULL); + void* data; + DWORD bytes; + m_dsBuffer->Lock(nSegment * m_bufferBytes, m_bufferBytes, &data, &bytes, NULL, NULL, 0); - LPVOID pvBuffer; - DWORD dwBufferLength; - - WaitForSingleObject(m_mutex, INFINITE); - - ResetEvent(m_notifyEvents[nBuffer]); - - VERIFYHR(m_dsBuffer->Lock(nBuffer * m_bufferBytes, m_bufferBytes, &pvBuffer, &dwBufferLength, NULL, NULL, 0L)); - ASSERT(dwBufferLength == (DWORD)m_bufferBytes); - - if (PUMPSTATE_STOPPING == m_pumpState) - { - nBytes = 0; - } - else - { - nBytes = GetData((BYTE*)pvBuffer, m_bufferBytes); - } - - if (nBytes < m_bufferBytes) - { - m_pumpState = PUMPSTATE_STOPPING; - - if (nBytes > 0) - { - ZeroMemory(((BYTE*)pvBuffer) + nBytes, m_bufferBytes - nBytes); - } - else - { - ZeroMemory(pvBuffer, m_bufferBytes); - } - } - - VERIFYHR(m_dsBuffer->Unlock(pvBuffer, dwBufferLength, NULL, 0)); - - if (nBytes > 0) - { - m_bufferFilled[nBuffer] = true; - m_filledBuffers++; + int got = (m_state == PUMP_DRAINING) ? 0 : GetData((BYTE*)data, m_bufferBytes); + if (got < m_bufferBytes) + { + m_state = PUMP_DRAINING; + int keep = got > 0 ? got : 0; + ZeroMemory((BYTE*)data + keep, m_bufferBytes - keep); + } - if (PUMPSTATE_BUFFERING == m_pumpState) - { - if(m_filledBuffers >= m_segmentsPerBuffer) - { - m_pumpState = PUMPSTATE_RUNNING; - } - } - } + m_dsBuffer->Unlock(data, bytes, NULL, 0); - ReleaseMutex(m_mutex); + if (got > 0) + { + m_segmentFilled[nSegment] = true; + m_filled++; + if (m_state == PUMP_BUFFERING && m_filled >= m_segments) + m_state = PUMP_RUNNING; + } - return nBytes > 0; + ReleaseMutex(m_lock); + return got > 0; } +// CAudioPump::GetPlaybackTime +// Reconstructed from 5960 retail XBE @ 0x631c0. The cursor going backwards +// means it went round the ring once more: +// if (cursor < last) wraps++; last = cursor; +// return (wraps * segments * segmentBytes + cursor) / bytesPerSecond; float CAudioPump::GetPlaybackTime() { if (m_dsBuffer == NULL) return 0.0f; - DWORD dwPlayCursor; - VERIFYHR(m_dsBuffer->GetCurrentPosition(&dwPlayCursor, NULL)); - - if( dwPlayCursor < m_prevCursor ) - { - m_completedBuffers++; - } + DWORD cursor; + m_dsBuffer->GetCurrentPosition(&cursor, NULL); + if (cursor < m_lastCursor) + m_wraps++; + m_lastCursor = cursor; - m_prevCursor = dwPlayCursor; - - return (float)(m_completedBuffers * ( m_bufferBytes * m_segmentsPerBuffer ) + dwPlayCursor) / m_bytesPerSecond; + return (float)(m_wraps * (m_bufferBytes * m_segments) + cursor) / m_bytesPerSecond; } +// A stream doesn't know its length; subclasses that do override this. float CAudioPump::GetPlaybackLength() { return 0.0f; } // ========================================================================= -// CFilePump: WAV file streaming via CAudioPump +// CFilePump // ========================================================================= +// Reconstructed from 5960 retail XBE @ 0x63220: no file yet. CFilePump::CFilePump() { - m_buffer = NULL; m_file = INVALID_HANDLE_VALUE; - m_startPos = 0; - m_bufferSize = 0; + m_dataStart = 0; + m_lastBlock = NULL; + m_blockBytes = 0; } +// Reconstructed from 5960 retail XBE @ 0x63290: close the file. CFilePump::~CFilePump() { if (m_file != INVALID_HANDLE_VALUE) CloseHandle(m_file); } +// CFilePump::Initialize(file, dataBytes, format) +// Reconstructed from 5960 retail XBE @ 0x632b0. Segments are the most +// whole blocks that fit in 8 KB; the pump gets an 8 KB stack. The pump +// takes the open file, works out the length in seconds and remembers where +// the samples start. HRESULT CFilePump::Initialize(HANDLE hFile, int nFileBytes, WAVEFORMATEX* pFormat) { - HRESULT hr = S_OK; - m_bufferSize = (0x2000/pFormat->nBlockAlign) * pFormat->nBlockAlign; + m_blockBytes = (0x2000 / pFormat->nBlockAlign) * pFormat->nBlockAlign; - hr = CAudioPump::Initialize(8192, pFormat, m_bufferSize); + HRESULT hr = CAudioPump::Initialize(0x2000, pFormat, m_blockBytes); if (FAILED(hr)) - { - DbgPrint("CFilePump::Initialize - fail to init CAudioPump"); return hr; - } m_file = hFile; - m_playbackLength = (float)nFileBytes / m_bytesPerSecond; - m_startPos = SetFilePointer(m_file, 0, NULL, FILE_CURRENT); - + m_seconds = (float)nFileBytes / m_bytesPerSecond; + m_dataStart = SetFilePointer(m_file, 0, NULL, FILE_CURRENT); return hr; } +// Stop and wind the file back to the first sample. void CFilePump::Stop() { if (m_file == INVALID_HANDLE_VALUE) return; - CAudioPump::Stop(); + SetFilePointer(m_file, m_dataStart, NULL, FILE_BEGIN); +} - SetFilePointer(m_file, m_startPos, NULL, FILE_BEGIN); +float CFilePump::GetPlaybackLength() +{ + return m_seconds; } -float CFilePump::GetPlaybackLength() { return m_playbackLength; } -void* CFilePump::GetSampleBuffer() { return m_buffer; } -DWORD CFilePump::GetSampleBufferSize() { return m_bufferSize; } +void* CFilePump::GetSampleBuffer() +{ + return m_lastBlock; +} -int CFilePump::GetData(BYTE* pbBuffer, int cbBuffer) +DWORD CFilePump::GetSampleBufferSize() { - DWORD dwRead; + return m_blockBytes; +} - if (!ReadFile(m_file, pbBuffer, cbBuffer, &dwRead, NULL)) - { - DbgPrint("CFilePump::GetData ReadFile failed (%d)\n", GetLastError()); +// Reads the next block. When looping, a short read wraps to the first +// sample and tops the block up. -1 on a read error. +int CFilePump::GetData(BYTE* pbBuffer, int cbBuffer) +{ + DWORD got; + if (!ReadFile(m_file, pbBuffer, cbBuffer, &got, NULL)) return -1; - } - if (m_loop && dwRead != (DWORD)cbBuffer) + if (m_loop && got != (DWORD)cbBuffer) { - SetFilePointer(m_file, m_startPos, NULL, FILE_BEGIN); - - DWORD dwRead2; - if (!ReadFile(m_file, pbBuffer + dwRead, cbBuffer - dwRead, &dwRead2, NULL)) - { - DbgPrint("CFilePump::GetData ReadFile failed (%d)\n", GetLastError()); + SetFilePointer(m_file, m_dataStart, NULL, FILE_BEGIN); + DWORD more; + if (!ReadFile(m_file, pbBuffer + got, cbBuffer - got, &more, NULL)) return -1; - } - - dwRead += dwRead2; + got += more; } - m_buffer = pbBuffer; - - return (int)dwRead; + m_lastBlock = pbBuffer; + return (int)got; } // ========================================================================= -// CMP3Pump: streaming MP3 decode via minimp3 +// CMP3Pump: Theseus's soundtrack decoder, not in 5960 // ========================================================================= extern void mp3dec_init_s(mp3dec_t* dec); @@ -831,8 +740,9 @@ int CMP3Pump::GetData(BYTE* pbBuffer, int cbBuffer) return bytesWritten; } + // ========================================================================= -// CAudioClip: XAP AudioClip node +// CAudioClip // ========================================================================= IMPLEMENT_NODE("AudioClip", CAudioClip, CTimeDepNode) @@ -861,77 +771,78 @@ START_NODE_FUN(CAudioClip, CTimeDepNode) END_NODE_FUN() #undef _FND_CLASS -CAudioClip::CAudioClip() : - m_fade(0.0f), - m_volume(1.0f), - m_pan(0.0f), - m_frequency(0.0f), - m_url(NULL), - m_transportMode(TRANSPORT_STOP) +// CAudioClip::CAudioClip +// Reconstructed from 5960 retail XBE @ 0x61890: invisible, full volume, +// centered, recorded rate, no fade, no url, stopped, and dirty so the +// first use loads the sound. The last applied volume starts at 1. +CAudioClip::CAudioClip() { + m_visible = false; + m_url = NULL; + m_capturedLoop = false; + m_sendProgress = false; + m_pause_on_moving = false; + m_progress = 0.0f; m_removeVoice = false; - m_sendProgress = false; - m_pause_on_moving = false; - m_unpauseNeeded = false; - m_progress = 0; - - m_dirty = true; + m_transportMode = TRANSPORT_STOP; m_lastTransportMode = -1; + m_dirty = true; + m_unpauseNeeded = false; m_lastVolume = 1.0f; m_lastPan = 0.0f; m_lastFrequency = 0.0f; - + m_fade = 0.0f; + m_volume = 1.0f; + m_pan = 0.0f; + m_frequency = 0.0f; m_sound = NULL; - m_visible = false; - m_capturedLoop = false; } +// Reconstructed from 5960 retail XBE @ 0x61940: stop and drop the sound, +// free the url. CAudioClip::~CAudioClip() { Cleanup(); delete [] m_url; } +// CAudioClip::OnSetProperty +// Reconstructed from 5960 retail XBE @ 0x619f0. With a fade set, a new +// volume or pan isn't stored; a lerper glides the field there over fade +// seconds instead (replacing any running one on this clip). A new url +// marks the clip dirty, and isActive starts or stops it. Theseus also +// takes sendProgress here. bool CAudioClip::OnSetProperty(const PRD* pprd, const void* pvValue) { - if (PTR2INT(pprd->pbOffset) == offsetof(m_sendProgress)) - { - m_sendProgress = *(bool*)pvValue; - } + int field = PTR2INT(pprd->pbOffset); - if (PTR2INT(pprd->pbOffset) == offsetof(m_volume)) - { - if (m_fade != 0.0f) - { - float volume = *(float*)pvValue; - CLerper::RemoveObject(this); - new CLerper(this, &m_volume, volume, m_fade); - return false; - } - } - if (PTR2INT(pprd->pbOffset) == offsetof(m_pan)) + if (field == offsetof(m_sendProgress)) + m_sendProgress = *(const bool*)pvValue; + + if ((field == offsetof(m_volume) || field == offsetof(m_pan)) && m_fade != 0.0f) { - if (m_fade != 0.0f) - { - float pan = *(float*)pvValue; - CLerper::RemoveObject(this); - new CLerper(this, &m_pan, pan, m_fade); - return false; - } + float* target = (field == offsetof(m_volume)) ? &m_volume : &m_pan; + float value = *(const float*)pvValue; + CLerper::RemoveObject(this); + new CLerper(this, target, value, m_fade); + return false; } - else if (PTR2INT(pprd->pbOffset) == offsetof(m_url)) + + if (field == offsetof(m_url)) { m_dirty = true; } - else if (PTR2INT(pprd->pbOffset) == offsetof(m_isActive)) + else if (field == offsetof(m_isActive)) { - m_isActive = *(bool*)pvValue; + m_isActive = *(const bool*)pvValue; OnIsActiveChanged(); } - return true; } +// CAudioClip::OnIsActiveChanged +// Reconstructed from 5960 retail XBE @ 0x61ae0: load if dirty, then Play +// when active, Stop when not. void CAudioClip::OnIsActiveChanged() { if (m_dirty) @@ -943,11 +854,12 @@ void CAudioClip::OnIsActiveChanged() Stop(); } - +// CAudioClip::Cleanup +// Reconstructed from 5960 retail XBE @ 0x61b40: Stop, delete the sound, +// and forget the volume, pan and rate last applied. HRESULT CAudioClip::Cleanup() { Stop(); - delete m_sound; m_sound = NULL; m_lastVolume = 1.0f; @@ -956,22 +868,20 @@ HRESULT CAudioClip::Cleanup() return S_OK; } - - +// CAudioClip::Initialize +// Reconstructed from 5960 retail XBE @ 0x61ba0. Drops the old sound and +// clears dirty. An empty url plays nothing. Then by url: "cd:" is an audio +// CD track, "st:" a soundtrack song, and otherwise the extension picks the +// loader. 5960 plays CDs and WMA soundtracks and files; Theseus has no CD +// playback, streams soundtrack MP3s and loads only .wav files here. HRESULT CAudioClip::Initialize() { - ASSERT(m_dirty); - - // Drop any prior sound buffer before we wire a new one in. Cleanup(); m_dirty = false; if (m_url == NULL || m_url[0] == 0) return S_FALSE; - // Dispatch on URL scheme: cd:* (legacy CD playback, removed), - // st:<id> (MP3 soundtrack streamed from disk), or any other path - // is treated as a sample-based wave file. if (_tcsnicmp(m_url, _T("cd:"), 3) == 0) { DbgPrint("CD playback not supported\n"); @@ -984,202 +894,138 @@ HRESULT CAudioClip::Initialize() return S_OK; } - { - char dbgUrl[256]; - WideCharToMultiByte(CP_ACP, 0, m_url, -1, dbgUrl, sizeof(dbgUrl), NULL, NULL); - DbgPrint("[AudioClip] url = \"%s\"\n", dbgUrl); - } + char narrowUrl[256]; + WideCharToMultiByte(CP_ACP, 0, m_url, -1, narrowUrl, sizeof(narrowUrl), NULL, NULL); + DbgPrint("[AudioClip] url = \"%s\"\n", narrowUrl); const TCHAR* ext = _tcsrchr(m_url, '.'); if (ext != NULL && _tcsicmp(ext + 1, _T("wav")) == 0) - { OpenWaveFile(); - } else - { - char dbgUrl[256]; - WideCharToMultiByte(CP_ACP, 0, m_url, -1, dbgUrl, sizeof(dbgUrl), NULL, NULL); - DbgPrint("Invalid AudioClip url: %s\n", dbgUrl); - } + DbgPrint("Invalid AudioClip url: %s\n", narrowUrl); return S_OK; } -struct WAVFILE1 +// The RIFF header up to the format chunk's size, and the head of every +// chunk after it. +struct RiffWaveHead { - BYTE riff [4]; - DWORD dwSize; - BYTE wave [4]; - BYTE fmt [4]; - DWORD dwFormatSize; + char riff[4]; + DWORD fileBytes; + char wave[4]; + char fmt[4]; + DWORD formatBytes; }; -struct WAVFILE2 +struct RiffChunkHead { - BYTE data [4]; - DWORD dwDataSize; + DWORD id; + DWORD bytes; }; -typedef struct +static bool TagIs(const char* tag, const char* want) { - FOURCC fccChunkId; - DWORD dwDataSize; -} RIFFHEADER, *LPRIFFHEADER; - -#ifndef FOURCC_RIFF -#define FOURCC_RIFF 'FFIR' -#endif // FOURCC_RIFF - -#ifndef FOURCC_WAVE -#define FOURCC_WAVE 'EVAW' -#endif // FOURCC_WAVE - -#ifndef FOURCC_FORMAT -#define FOURCC_FORMAT ' tmf' -#endif // FOURCC_FORMAT - -#ifndef FOURCC_DATA -#define FOURCC_DATA 'atad' -#endif // FOURCC_DATA + return tag[0] == want[0] && tag[1] == want[1] && tag[2] == want[2] && tag[3] == want[3]; +} +// CAudioClip::OpenWaveFile +// Reconstructed from 5960 retail XBE @ 0x61d20. Finds the file the url +// names and checks for "RIFF....WAVEfmt ". The format chunk is read into +// m_format (as much as fits; the rest is skipped), then chunks are skipped +// until "data". Up to 64 KB of samples load into a CAudioBuf; anything +// longer streams from the file through a CFilePump, which then owns it. bool CAudioClip::OpenWaveFile() { - TCHAR szBuf [MAX_PATH]; - FindFilePath(szBuf, m_url); - HANDLE hFile = TheseusCreateFile(szBuf, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL); - if (hFile == INVALID_HANDLE_VALUE) - { - DbgPrint("\001Cannot open wave file: %s\n", m_url); - return false; - } - - DWORD dwRead; - WAVFILE1 header; - RIFFHEADER RiffHeader; - - if (!ReadFile(hFile, &header, sizeof (header), &dwRead, NULL) || dwRead != sizeof (header)) - { - DbgPrint("\001%s is not a valid wave file...\n", m_url); - CloseHandle(hFile); + TCHAR path[MAX_PATH]; + FindFilePath(path, m_url); + HANDLE file = TheseusCreateFile(path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL); + if (file == INVALID_HANDLE_VALUE) return false; - } - if (header.riff[0] != 'R' || header.riff[1] != 'I' || header.riff[2] != 'F' || header.riff[3] != 'F' || - header.wave[0] != 'W' || header.wave[1] != 'A' || header.wave[2] != 'V' || header.wave[3] != 'E' || - header.fmt[0] != 'f' || header.fmt[1] != 'm' || header.fmt[2] != 't' || header.fmt[3] != ' ') + DWORD got; + RiffWaveHead head; + if (!ReadFile(file, &head, sizeof (head), &got, NULL) || got != sizeof (head) || + !TagIs(head.riff, "RIFF") || !TagIs(head.wave, "WAVE") || !TagIs(head.fmt, "fmt ")) { - DbgPrint("\001%s is not a valid wave file (bad header chunk)\n", m_url); - CloseHandle(hFile); + CloseHandle(file); return false; } - DWORD dwFormatSize = header.dwFormatSize; - ZeroMemory(&m_format, sizeof(m_format)); - - if (dwFormatSize > sizeof(m_format)) - { - dwFormatSize = sizeof(m_format); - } - - if (!ReadFile(hFile, &m_format, dwFormatSize, &dwRead, NULL) || dwRead != dwFormatSize) + ZeroMemory(&m_format, sizeof (m_format)); + DWORD formatBytes = head.formatBytes < sizeof (m_format) ? head.formatBytes : sizeof (m_format); + if (!ReadFile(file, &m_format, formatBytes, &got, NULL) || got != formatBytes) { - DbgPrint("\001%s is not a valid wave file (bad format chunk)\n", m_url); - CloseHandle(hFile); + CloseHandle(file); return false; } + if (head.formatBytes != formatBytes) + SetFilePointer(file, head.formatBytes - formatBytes, 0, FILE_CURRENT); - if (header.dwFormatSize != dwFormatSize) - { - SetFilePointer(hFile, header.dwFormatSize - dwFormatSize, 0, FILE_CURRENT); - } - - DWORD dwDataSize = 0; - - ASSERT(m_format.wfx.wFormatTag == WAVE_FORMAT_PCM || m_format.wfx.wFormatTag == WAVE_FORMAT_XBOX_ADPCM); - - // Walk RIFF chunks until we hit FOURCC_DATA, skipping anything else. - for (;;) + DWORD dataBytes = 0; + RiffChunkHead chunk; + while (ReadFile(file, &chunk, sizeof (chunk), &got, NULL)) { - if (!ReadFile(hFile, &RiffHeader, sizeof(RiffHeader), &dwRead, NULL)) - break; - - if (RiffHeader.fccChunkId == FOURCC_DATA) + if (chunk.id == 'atad') { - dwDataSize = RiffHeader.dwDataSize; + dataBytes = chunk.bytes; break; } - - if (!SetFilePointer(hFile, RiffHeader.dwDataSize, 0, FILE_CURRENT)) + if (!SetFilePointer(file, chunk.bytes, 0, FILE_CURRENT)) break; } - - if (dwDataSize == 0) - { - DbgPrint("\001%s is not a valid wave file (bad data chunk)\n", m_url); - CloseHandle(hFile); - return false; - } - - HRESULT hr = S_OK; - ASSERT(m_sound == NULL); - if (dwDataSize > 65536) + if (dataBytes == 0) { - CFilePump* pSound = new CFilePump; - m_sound = pSound; - hr = pSound->Initialize(hFile, dwDataSize, &m_format.wfx); - if (FAILED(hr)) - { - DbgPrint("Could not initialize CFilePump for %s\n", m_url); - CloseHandle(hFile); - delete pSound; - m_sound = NULL; - return false; - } - - // NOTE: File will be closed by CFilePump when it's done... + CloseHandle(file); + return false; } - else + + if (dataBytes > 65536) { - m_sound = new CAudioBuf; - hr = m_sound->Initialize(&m_format.wfx, dwDataSize); - if(FAILED(hr)) + CFilePump* pump = new CFilePump; + m_sound = pump; + if (FAILED(pump->Initialize(file, dataBytes, &m_format.wfx))) { - DbgPrint("Could not initialize CAudioBuf for %s\n", m_url); - CloseHandle(hFile); - delete m_sound; + CloseHandle(file); + delete pump; m_sound = NULL; return false; } + return true; + } - void* pvBuffer = m_sound->Lock(); - bool bError = !ReadFile(hFile, pvBuffer, dwDataSize, &dwRead, NULL) || dwRead != dwDataSize; - m_sound->Unlock(pvBuffer); - - CloseHandle(hFile); + m_sound = new CAudioBuf; + if (FAILED(m_sound->Initialize(&m_format.wfx, dataBytes))) + { + CloseHandle(file); + delete m_sound; + m_sound = NULL; + return false; + } - if (bError) - { - DbgPrint("\001%s is not a valid wave file...\n", m_url); - delete m_sound; - m_sound = NULL; + void* samples = m_sound->Lock(); + bool bad = !ReadFile(file, samples, dataBytes, &got, NULL) || got != dataBytes; + m_sound->Unlock(samples); + CloseHandle(file); - return false; - } + if (bad) + { + delete m_sound; + m_sound = NULL; + return false; } - return true; } -// MP3 soundtrack via streaming pump (CMP3Pump). The pump owns the file -// data and runs decode on its worker thread; no full-song PCM ever lives -// in RAM. +// Theseus: st:<id> is a song from music_collection.cpp's MP3 scan, +// decoded on the pump's thread so the song never sits in RAM as PCM. extern const char* MusicCollection_FindSongByID(int songID); bool CAudioClip::OpenMP3Soundtrack() { - int songID = _ttoi(m_url + 3); // skip "st:" + int songID = _ttoi(m_url + 3); const char* songPath = MusicCollection_FindSongByID(songID); - if (!songPath) + if (songPath == NULL) { DbgPrint("[AudioClip] st: song ID %d not found\n", songID); return false; @@ -1187,53 +1033,63 @@ bool CAudioClip::OpenMP3Soundtrack() DbgPrint("[AudioClip] Loading MP3: %s\n", songPath); - ASSERT(m_sound == NULL); - CMP3Pump* pPump = new CMP3Pump; - m_sound = pPump; - - HRESULT hr = pPump->Initialize(songPath); - if (FAILED(hr)) + CMP3Pump* pump = new CMP3Pump; + m_sound = pump; + if (FAILED(pump->Initialize(songPath))) { DbgPrint("[AudioClip] CMP3Pump init failed for %s\n", songPath); - delete pPump; + delete pump; m_sound = NULL; return false; } - return true; } +// Fraction of the sound played, 0 when the length isn't known. +static float PlayedFraction(CAudioBuf* sound) +{ + float length = sound->GetPlaybackLength(); + return length != 0.0f ? sound->GetPlaybackTime() / length : 0.0f; +} + +// CAudioClip::Advance(seconds) +// Reconstructed from 5960 retail XBE @ 0x62050. Loads if dirty. With +// pause_on_moving and a sound that isn't muted, a level change pauses it +// (and skips the rest of the frame) and the end of one resumes it. After +// the time-dependent base advance it publishes removeVoice. With no sound +// the clip is inactive and stopped. While active it applies volume +// changes, pausing at zero volume and resuming when it comes back, plus +// pan and rate; sends OnProgressChanged when sendProgress is on and the +// fraction moved; and tracks pause and play state, firing OnEndOfAudio +// when a playing sound stops. Any transport change fires +// OnTransportModeChanged. 5960 only ends a looping clip when it's also +// inactive; Theseus ends any that stops, and with sendProgress also one +// that has played past its length. void CAudioClip::Advance(float nSeconds) { - if (m_dirty) - Initialize(); - - // Pause this audio clip if we are in the middle of level transition - if (m_pause_on_moving && m_sound && m_volume != 0.0f) - { - if (g_bLevelTransition) - { - if (!m_sound->IsPaused()) - { - m_sound->Pause(true); - m_unpauseNeeded = true; - } - return; - } - - if (!g_bLevelTransition && m_unpauseNeeded) - { - if (m_sound->IsPaused()) - { - m_sound->Pause(false); - } - - m_unpauseNeeded = false; - } - } + if (m_dirty) + Initialize(); - CTimeDepNode::Advance(nSeconds); + if (m_pause_on_moving && m_sound != NULL && m_volume != 0.0f) + { + if (g_bLevelTransition) + { + if (!m_sound->IsPaused()) + { + m_sound->Pause(true); + m_unpauseNeeded = true; + } + return; + } + if (m_unpauseNeeded) + { + if (m_sound->IsPaused()) + m_sound->Pause(false); + m_unpauseNeeded = false; + } + } + CTimeDepNode::Advance(nSeconds); g_removeVoice = m_removeVoice; if (m_sound == NULL) @@ -1246,89 +1102,60 @@ void CAudioClip::Advance(float nSeconds) if (m_volume != m_lastVolume) { if (m_lastVolume == 0.0f && m_transportMode == TRANSPORT_PAUSE) - { - TRACE(_T("Un-Pausing %s due to non-zero volume...\n"), m_url); Pause(); - } - m_lastVolume = m_volume; - m_sound->SetAttenuation((1.0f - m_volume) * 100.0f); - if (m_volume == 0.0f && m_transportMode == TRANSPORT_PLAY) - { - TRACE(_T("Pausing %s due to zero volume...\n"), m_url); Pause(); - } } if (m_pan != m_lastPan) { m_lastPan = m_pan; - m_sound->SetPan(m_pan); } if (m_frequency != m_lastFrequency) { m_lastFrequency = m_frequency; - m_sound->SetFrequency(m_frequency); } - // Update the script-visible progress fraction if the clip - // has opted in via sendProgress. Skipped by default to avoid - // per-frame property writes that would re-fire OnProgressChanged - // every Advance. - if (m_sendProgress) + if (m_sendProgress) { - float progress = 0.0f; - - float nLength = m_sound->GetPlaybackLength(); - if (nLength != 0.0f) - progress = m_sound->GetPlaybackTime() / nLength; - - if (progress != m_progress) + float fraction = PlayedFraction(m_sound); + if (fraction != m_progress) { - m_progress = progress; + m_progress = fraction; CallFunction(this, _T("OnProgressChanged")); } } + bool ended = false; if (m_sound->IsPaused()) { m_transportMode = TRANSPORT_PAUSE; } - else if( m_sound->IsPlaying() ) + else if (m_sound->IsPlaying()) { m_transportMode = TRANSPORT_PLAY; - - if( m_sendProgress ) + if (m_sendProgress) { - float progress = 0.0f; - float nLength = m_sound->GetPlaybackLength(); - if (nLength != 0.0f) - { - progress = m_sound->GetPlaybackTime(); - } - - if(progress > nLength) - { - m_transportMode = TRANSPORT_STOP; - m_isActive = false; - CallFunction(this, _T("OnEndOfAudio")); - } + float length = m_sound->GetPlaybackLength(); + float played = length != 0.0f ? m_sound->GetPlaybackTime() : 0.0f; + ended = played > length; } } else { - if (m_transportMode == TRANSPORT_PLAY) - { - m_transportMode = TRANSPORT_STOP; - m_isActive = false; + ended = m_transportMode == TRANSPORT_PLAY; + } - CallFunction(this, _T("OnEndOfAudio")); - } + if (ended) + { + m_transportMode = TRANSPORT_STOP; + m_isActive = false; + CallFunction(this, _T("OnEndOfAudio")); } } @@ -1339,90 +1166,81 @@ void CAudioClip::Advance(float nSeconds) } } +// CAudioClip::PlayOrPause [script fn 'PlayOrPause', FND 0x00188720, sig 1] +// Reconstructed from 5960 retail XBE @ 0x62290: +// if (transportMode is PLAY or PAUSE) Pause(); else Play(); void CAudioClip::PlayOrPause() { - switch (m_transportMode) - { - case TRANSPORT_PLAY: - case TRANSPORT_PAUSE: + if (m_transportMode == TRANSPORT_PLAY || m_transportMode == TRANSPORT_PAUSE) Pause(); - break; - - default: + else Play(); - break; - } } -void CAudioClip::Play(/*bool bLoop*/) +// CAudioClip::Play [script fn 'Play', FND 0x001886a8, sig 1] +// Reconstructed from 5960 retail XBE @ 0x622b0. Loads if dirty, applies +// volume, pan and rate, and starts the sound looping when the clip loops; +// if it started the clip is playing and active. +void CAudioClip::Play() { if (m_dirty) Initialize(); m_capturedLoop = m_loop; + if (m_sound == NULL) + return; - if (m_sound != NULL) + m_sound->SetAttenuation((1.0f - m_volume) * 100.0f); + m_sound->SetPan(m_pan); + m_sound->SetFrequency(m_frequency); + if (m_sound->Play(m_capturedLoop)) { - m_sound->SetAttenuation((1.0f - m_volume) * 100.0f); - m_sound->SetPan(m_pan); - m_sound->SetFrequency(m_frequency); - - if (m_sound->Play(m_capturedLoop)) - { - m_transportMode = TRANSPORT_PLAY; - m_isActive = true; - } - else DbgPrint("Play failed!\n"); + m_transportMode = TRANSPORT_PLAY; + m_isActive = true; } - } +// CAudioClip::Stop [script fn 'Stop', FND 0x001886c0, sig 1] +// Reconstructed from 5960 retail XBE @ 0x62350. Unless already stopped: +// stop and delete the sound, go inactive and mark dirty so the next play +// loads it fresh from the start. void CAudioClip::Stop() { if (m_transportMode == TRANSPORT_STOP) return; m_transportMode = TRANSPORT_STOP; - if (m_sound != NULL) m_sound->Stop(); - delete m_sound; m_sound = NULL; - m_isActive = false; - m_dirty = true; // so audio buffer is re-created and will start over + m_dirty = true; } +// CAudioClip::Pause [script fn 'Pause', FND 0x001886d8, sig 1] +// Reconstructed from 5960 retail XBE @ 0x62390: loads if dirty, then +// toggles between paused and playing. void CAudioClip::Pause() { if (m_dirty) Initialize(); - if (m_transportMode == TRANSPORT_PAUSE) - { - m_transportMode = TRANSPORT_PLAY; - - if (m_sound != NULL) - m_sound->Pause(false); - } - else - { - m_transportMode = TRANSPORT_PAUSE; - - if (m_sound != NULL) - m_sound->Pause(true); - } + bool pausing = m_transportMode != TRANSPORT_PAUSE; + m_transportMode = pausing ? TRANSPORT_PAUSE : TRANSPORT_PLAY; + if (m_sound != NULL) + m_sound->Pause(pausing); } +// CAudioClip::getMinutes / getSeconds [script fns, FND 0x001886f0 / 0x00188708, sig 2] +// Reconstructed from 5960 retail XBE @ 0x623e0 / 0x62420: whole seconds +// played, / 60 or % 60; 0 without a sound. int CAudioClip::getMinutes() { if (m_dirty) Initialize(); - if (m_sound == NULL) return 0; - return (int)m_sound->GetPlaybackTime() / 60; } @@ -1430,48 +1248,40 @@ int CAudioClip::getSeconds() { if (m_dirty) Initialize(); - if (m_sound == NULL) return 0; - return (int)m_sound->GetPlaybackTime() % 60; } +// Theseus: the visualizer reads the block the sound played last. void* CAudioClip::GetSampleBuffer() { - if (m_sound == NULL) - return NULL; - - return m_sound->GetSampleBuffer(); + return m_sound != NULL ? m_sound->GetSampleBuffer() : NULL; } int CAudioClip::GetSampleBufferSize() { - if (m_sound == NULL) - return 0; - - return m_sound->GetSampleBufferSize(); + return m_sound != NULL ? m_sound->GetSampleBufferSize() : 0; } +// Theseus: lets native code point a clip at a file. void CAudioClip::SetUrl(const TCHAR* pszAudioFile) { - if(m_url) - { - delete [] m_url; - } + delete [] m_url; m_dirty = true; - if(pszAudioFile) + if (pszAudioFile != NULL) { - m_url = new TCHAR[_tcslen(pszAudioFile)+1]; + m_url = new TCHAR [_tcslen(pszAudioFile) + 1]; _tcscpy(m_url, pszAudioFile); } - } // ========================================================================= -// CPeriodicAudioGroup: timed random audio clip playback +// CPeriodicAudioGroup // ========================================================================= +// Plays its AudioClip children one after another, every period seconds +// plus up to periodNoise more. class CPeriodicAudioGroup : public CGroup { DECLARE_NODE(CPeriodicAudioGroup, CGroup) @@ -1481,13 +1291,13 @@ class CPeriodicAudioGroup : public CGroup void Advance(float nSeconds); bool m_isActive; - bool m_pause_on_moving; + bool m_pause_on_moving; float m_period; float m_periodNoise; - XTIME m_timeOfNextEvent; - int m_nextClipIndex; - CAudioClip* m_currentClip; + XTIME m_nextPlay; // 0 until the next one is scheduled + int m_nextChild; // -1 until a random first pick + CAudioClip* m_playing; DECLARE_NODE_PROPS() }; @@ -1500,72 +1310,66 @@ START_NODE_PROPS(CPeriodicAudioGroup, CGroup) NODE_PROP(pt_number, CPeriodicAudioGroup, periodNoise) END_NODE_PROPS() - -CPeriodicAudioGroup::CPeriodicAudioGroup() : - m_isActive(false), - m_pause_on_moving(true), - m_period(10.0f), - m_periodNoise(0.0f) +// CPeriodicAudioGroup::CPeriodicAudioGroup +// Reconstructed from 5960 retail XBE @ 0x624a0: invisible, inactive, holds +// still through level changes, a 10 second period with no noise, nothing +// scheduled or picked. +CPeriodicAudioGroup::CPeriodicAudioGroup() { m_visible = false; - - m_timeOfNextEvent = 0.0f; - m_nextClipIndex = -1; - m_currentClip = NULL; + m_isActive = false; + m_pause_on_moving = true; + m_period = 10.0f; + m_periodNoise = 0.0f; + m_nextPlay = 0.0f; + m_nextChild = -1; + m_playing = NULL; } +// CPeriodicAudioGroup::Advance(seconds) +// Reconstructed from 5960 retail XBE @ 0x62540. During a level change the +// clip it started is stopped. Inactive, the schedule is cleared. Otherwise, +// with children: the first time it picks a random one to start at; with +// nothing scheduled it schedules now + period + noise; once that time +// passes it plays the next child (wrapping to the first), if that child is +// an AudioClip. void CPeriodicAudioGroup::Advance(float nSeconds) { CGroup::Advance(nSeconds); - // Stop this background audio group if we are in the middle of level transition - if (m_pause_on_moving && g_bLevelTransition) - { - if (m_currentClip && m_currentClip->IsKindOf(NODE_CLASS(CAudioClip))) - { - m_currentClip->Stop(); - } - - return; - } + if (m_pause_on_moving && g_bLevelTransition) + { + if (m_playing != NULL && m_playing->IsKindOf(NODE_CLASS(CAudioClip))) + m_playing->Stop(); + return; + } if (!m_isActive) { - m_timeOfNextEvent = 0.0f; + m_nextPlay = 0.0f; return; } - int nChildCount = m_children.GetLength(); - if (nChildCount == 0) + int count = m_children.GetLength(); + if (count == 0) return; - if (m_nextClipIndex < 0) - m_nextClipIndex = rand() % nChildCount; + if (m_nextChild < 0) + m_nextChild = rand() % count; - if (m_timeOfNextEvent == 0.0f) + if (m_nextPlay == 0.0f) { - m_timeOfNextEvent = TheseusGetNow() + m_period + rnd(m_periodNoise); - TRACE(_T("Next clip will play in %0.2f seconds...\n"), m_timeOfNextEvent - TheseusGetNow()); + m_nextPlay = TheseusGetNow() + m_period + rnd(m_periodNoise); return; } - if (TheseusGetNow() > m_timeOfNextEvent) - { - m_timeOfNextEvent = 0.0f; - - if (m_nextClipIndex >= nChildCount) - m_nextClipIndex = 0; - - m_currentClip = (CAudioClip*)m_children.GetNode(m_nextClipIndex); - m_nextClipIndex += 1; - - if (!m_currentClip->IsKindOf(NODE_CLASS(CAudioClip))) - { - TRACE(_T("CPeriodicAudioGroup: child %d is not an AudioClip!\n"), m_nextClipIndex-1); - return; - } + if (TheseusGetNow() <= m_nextPlay) + return; - TRACE(_T("CPeriodicAudioGroup: playing clip %d (%s)\n"), m_nextClipIndex-1, m_currentClip->m_url); - m_currentClip->Play(); - } + m_nextPlay = 0.0f; + if (m_nextChild >= count) + m_nextChild = 0; + m_playing = (CAudioClip*)m_children.GetNode(m_nextChild++); + if (m_playing->IsKindOf(NODE_CLASS(CAudioClip))) + m_playing->Play(); } From 199c7a2313d1c384b7631d1f4ee7e7af297276cb Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:43:40 -0500 Subject: [PATCH 4/6] Save copy and title sizes behave like 5960 on the edges A save copy no longer fails just because the title's meta file didn't copy, a folder is made writable before it's removed, and a title size cut short by cancel gets counted again instead of being cached wrong. All three are what 5960 does. Needs a console test. --- theseus/shared/file_ops.cpp | 3 +++ theseus/shared/title_collection.cpp | 14 +++++++++----- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/theseus/shared/file_ops.cpp b/theseus/shared/file_ops.cpp index 835d6c1..97b87da 100755 --- a/theseus/shared/file_ops.cpp +++ b/theseus/shared/file_ops.cpp @@ -200,6 +200,8 @@ void CGameCopier::CopyGame(int nCopyGame) { TitlePath(src, m_srcRoot, game.titleID, szTitleDataXBX); CopyFile(src, dest); + // The save is across; a missing meta file doesn't undo that. + m_internalError = false; } } @@ -369,6 +371,7 @@ bool CGameCopier::DeleteDirectory(const TCHAR* szDir, bool RemoveSelf) return true; Ansi(narrow, szDir, MAX_PATH); + TheseusSetFileAttributes(narrow, FILE_ATTRIBUTE_NORMAL); return TheseusRemoveDirectory(narrow) != FALSE; } diff --git a/theseus/shared/title_collection.cpp b/theseus/shared/title_collection.cpp index 8d9b602..7e27042 100755 --- a/theseus/shared/title_collection.cpp +++ b/theseus/shared/title_collection.cpp @@ -402,9 +402,15 @@ FILETIME CTitleArray::GetSavedGameTime(int nTitle, int nSavedGame) return m_list[nTitle].m_saveList[nSavedGame].m_written; } +static bool CancelSignaled(HANDLE cancel) +{ + return cancel != NULL && WaitForSingleObject(cancel, 0) == WAIT_OBJECT_0; +} + // CTitleArray::GetTitleTotalBlocks(n, cancel) // Reconstructed from 5960 retail XBE @ 0x43390. Counted once and cached: // the title's udata folder, plus its tdata folder on the hard drive. +// A cancel during the count leaves it unknown. int CTitleArray::GetTitleTotalBlocks(int nTitle, HANDLE hCancelEvent) { if (nTitle < 0 || nTitle >= m_count) @@ -417,6 +423,9 @@ int CTitleArray::GetTitleTotalBlocks(int nTitle, HANDLE hCancelEvent) if (m_root[0] == 'c' && t.m_blocks >= 0) t.m_blocks += ComputeTitleTotalBlocks(GetTData(), t.m_titleID, hCancelEvent); } + // A count cut short by cancel is taken again next time. + if (CancelSignaled(hCancelEvent)) + t.m_blocks = -1; return t.m_blocks; } @@ -430,11 +439,6 @@ int ComputeTitleTotalBlocks(const TCHAR* szRoot, const TCHAR* szTitleID, HANDLE return GetDirectoryBlocks(dir, BLOCK_SIZE, true, hCancelEvent); } -static bool CancelSignaled(HANDLE cancel) -{ - return cancel != NULL && WaitForSingleObject(cancel, 0) == WAIT_OBJECT_0; -} - // ScanSavedGames(root, id, out, cancel) // Reconstructed from 5960 retail XBE @ 0x434f0. Lists <root>\<id>\*.* and // records every folder whose name fits, up to 4096, with its last write From 85778c01b78175faf778ee19084707caf8956166 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:55:42 -0500 Subject: [PATCH 5/6] Rebuilt the save grid from the binary Rewrote SavedGameGrid's list, layout, selection, sizing, copy and delete code from the 5960 code. The DLC items, ContentMeta reader and Live account calls are Theseus's and stay as they were. A harness driving random devices, titles and saves through selection, scrolling, rendering, copy and delete printed the same 630,872 lines old and new over 400 runs. --- docs/decomp/SavedGameGrid.md | 118 ++ theseus/shared/savegame_grid.cpp | 2088 +++++++++++++----------------- 2 files changed, 1022 insertions(+), 1184 deletions(-) create mode 100644 docs/decomp/SavedGameGrid.md diff --git a/docs/decomp/SavedGameGrid.md b/docs/decomp/SavedGameGrid.md new file mode 100644 index 0000000..be5e6e6 --- /dev/null +++ b/docs/decomp/SavedGameGrid.md @@ -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. diff --git a/theseus/shared/savegame_grid.cpp b/theseus/shared/savegame_grid.cpp index 79880f1..a73e756 100644 --- a/theseus/shared/savegame_grid.cpp +++ b/theseus/shared/savegame_grid.cpp @@ -1,7 +1,10 @@ -// savegame_grid.cpp: CSavedGameGrid, the Memory panel's grid of saved- -// game tiles. Walks the title collection, paginates entries, resolves -// per-title icons, and dispatches selection / copy / delete actions. -// Decompiled from the 5960 retail XBE. +// savegame_grid.cpp: SavedGameGrid, the Memory blade's list of titles on a +// device with a grid of save icons under each. Lays the list out, moves +// the selection, sizes things on a worker thread and starts copies and +// deletes. Rebuilt from the 5960 retail XBE (0x47320..0x4bc60); see +// docs/decomp/SavedGameGrid.md. DLC items, the ContentMeta reader and the +// Live account calls below are Theseus's own. + #include "std.h" #include "theseus.h" @@ -86,8 +89,8 @@ class CSavedGameGrid : public CNode int m_iconsPerRow; float m_scroll; int m_curTitle; - int m_curTitleCache; - int m_curGridItemCache; + int m_sizedTitle; + int m_sizedItem; int m_iconRowScroll; float m_smallIconSpacing; bool m_detachIcon; @@ -96,7 +99,7 @@ class CSavedGameGrid : public CNode int m_freeBlocks; int m_gameBlocks; bool m_isActive; - bool m_busy; + bool m_listing; int m_nPrefColumn; void selectUp(); @@ -141,22 +144,22 @@ class CSavedGameGrid : public CNode void StartXboxLiveAccountCopy(int destDevUnit); protected: - int m_language; - int m_totalBlocks; - float m_scrollTo; - XTIME m_timeScroll; - int m_curTitleLast; - bool m_copying; - XTIME m_timeCopyingStarted; - bool m_copyError; - int m_deletedTitle; - XTIME m_timeOfDelete; - int m_soundtrackTitle; - int m_soundtrackCount; - int m_xboxLiveAccountTitle; // 5960: index in title list where Live accounts start (-1 = none) - - int m_cacheTitleSize; - int m_cacheSavedGameSize; + int m_shownLanguage; + int m_deviceBlocks; + float m_scrollTarget; + XTIME m_scrollStart; + int m_prevTitle; + bool m_copyRunning; + XTIME m_copyStart; + bool m_copyFailed; + int m_fadingTitle; + XTIME m_fadeStart; + int m_soundtrackRow; + int m_soundtracks; + int m_liveAccountRow; // 5960: index in title list where Live accounts start (-1 = none) + + int m_titleBlocks; + int m_itemBlocks; void RenderIconRow(D3DXMATRIX *pMatrix, float y, int nTitle, int nFirstSavedGame, int nSavedGameCount); float RenderLoop(bool bRender); @@ -173,27 +176,27 @@ class CSavedGameGrid : public CNode CStrObject *GetTitleID(int nTitle); CStrObject *GetTitleName(int nTitle); - DWORD m_lastUpdateTick; - int m_periodStatus; - TCHAR m_statusText[MAX_TRANSLATE_LEN]; + DWORD m_dotsTick; + int m_dots; + TCHAR m_copyingText[MAX_TRANSLATE_LEN]; DECLARE_NODE_PROPS(); DECLARE_NODE_FUNCTIONS(); private: - HANDLE m_titlesEnumThread; - HANDLE m_savedGameEnumThread; - HANDLE m_cancelEvent; - HANDLE m_startEvent, m_stopEvent; - bool m_savedGameQueryPending; - volatile bool m_done; - XTIME m_timeToSendEnd; + HANDLE m_listThread; + HANDLE m_sizeThread; + HANDLE m_sizeCancel; + HANDLE m_sizeStart, m_sizeIdle; + bool m_sizing; + volatile bool m_sizeQuit; + XTIME m_listEndAt; static void WINAPI TitlesEnumThread(CSavedGameGrid *p); static void WINAPI SavedGameEnumThread(CSavedGameGrid *p); // Background delete thread and flag - HANDLE m_deleteThread; - bool m_deleting; + HANDLE m_deleter; + bool m_deleteRunning; static void WINAPI DeleteThread(CSavedGameGrid *p); // DeleteThread helpers split by case. @@ -233,6 +236,7 @@ class CSavedGameGrid : public CNode bool ResolveDLCFolder(int nTitle, int dlcIndex, char *outTitleIDChar, int titleIDBufSize, char *outDLCFolder, int dlcFolderBufSize); + bool GetDLCImagePath(int nTitle, int dlcIndex, TCHAR *out); // Device-unit classification. Dev units 0..7 are physical storage // (Dev0 = HDD, 1..7 = MU slots). Dev unit 8 is the synthetic @@ -413,422 +417,348 @@ bool CSavedGameGrid::ResolveDLCFolder(int nTitle, int dlcIndex, return FindDLCFolderByIndex(outTitleIDChar, dlcIndex, outDLCFolder, dlcFolderBufSize); } -CSavedGameGrid::CSavedGameGrid() : m_language(0), - m_pod(NULL), - m_podRing(NULL), - // Xbox Live Accounts Panel - m_podXboxLiveAccountsPanel(NULL), - m_XboxLiveAccountsIconPanel(NULL), - m_iconBumpRing(NULL), - m_iconArrow(NULL), - m_iconCheck(NULL), - m_curGridItem(-1), - - m_podSavePanel(NULL), - m_podSoundtrackPanel(NULL), - m_podHilite(NULL), - m_MUheader(NULL), - m_MUhiliteHeader(NULL), - m_firstMURow(NULL), - m_header(NULL), - m_hiliteHeader(NULL), - m_firstRow(NULL), - m_secondRow(NULL), - m_otherRow(NULL), - m_moreUp(NULL), - m_moreDown(NULL), - m_renderIcons(true), - m_iconsPerRow(4), - m_scroll(0.0f), - m_curTitle(-1), - m_curTitleCache(-1), - m_curGridItemCache(-1), - m_smallIcon(NULL), - m_SavedIconPanel(NULL), - m_SoundtrackIconPanel(NULL), - m_iconRing(NULL), - m_smallIconHilite(NULL), - m_smallIconSpacing(1.0f), - m_detachIcon(false), - m_isActive(false), - m_busy(false), - m_deleteThread(NULL), - m_deleting(false), - m_titlesEnumThread(NULL), - m_savedGameEnumThread(NULL), - m_cacheSavedGameSize(-1), - m_cacheTitleSize(-1), - m_savedGameQueryPending(false), - m_done(false), - m_copying(false), - m_timeCopyingStarted(0.0f), - m_curDevUnit(-1), - m_iconRowScroll(0), - m_nPrefColumn(-1) -{ - m_scrollTo = 0.0f; - m_timeScroll = 0.0f; - m_curTitleLast = -1; - m_totalBlocks = -1; +// ============================================================================= +// Setup and title access +// ============================================================================= + +// CSavedGameGrid::CSavedGameGrid +// Reconstructed from 5960 retail XBE @ 0x47320. Every node pointer null, +// icons rendered four to a row, no device, title or item picked, sizes and +// counts unknown (-1), no scroll. Three events (start auto reset, stop and +// cancel manual reset) and the size worker thread are made up front. +// Theseus adds the focused pod matrix cache and the DLC count cache. +CSavedGameGrid::CSavedGameGrid() +{ + m_pod = m_podRing = m_podSavePanel = NULL; + m_podXboxLiveAccountsPanel = m_XboxLiveAccountsIconPanel = NULL; + m_iconBumpRing = m_iconArrow = m_iconCheck = NULL; + m_podSoundtrackPanel = m_podHilite = NULL; + m_MUheader = m_MUhiliteHeader = m_firstMURow = NULL; + m_header = m_hiliteHeader = NULL; + m_firstRow = m_secondRow = m_otherRow = NULL; + m_smallIcon = m_SavedIconPanel = m_SoundtrackIconPanel = NULL; + m_iconRing = m_smallIconHilite = NULL; + m_moreUp = m_moreDown = NULL; + + m_renderIcons = true; + m_iconsPerRow = 4; + m_smallIconSpacing = 1.0f; + m_detachIcon = false; + m_isActive = false; + m_listing = false; + + m_curDevUnit = -1; + m_curTitle = -1; + m_sizedTitle = -1; + m_prevTitle = -1; + m_curGridItem = -1; + m_sizedItem = -1; + m_nPrefColumn = -1; + m_iconRowScroll = 0; + m_scroll = 0.0f; + m_scrollTarget = 0.0f; + m_scrollStart = 0.0f; + + m_shownLanguage = 0; + m_deviceBlocks = -1; m_freeBlocks = -1; m_gameBlocks = -1; - m_deletedTitle = -1; - m_timeOfDelete = 0.0f; - m_soundtrackTitle = -1; - m_soundtrackCount = 0; - m_xboxLiveAccountTitle = -1; + m_titleBlocks = -1; + m_itemBlocks = -1; + + m_copyRunning = false; + m_copyStart = 0.0f; + m_deleteRunning = false; + m_deleter = NULL; + m_fadingTitle = -1; + m_fadeStart = 0.0f; + + m_soundtrackRow = -1; + m_soundtracks = 0; + m_liveAccountRow = -1; + m_focusPodMatrixValid = false; D3DXMatrixIdentity(&m_focusPodMatrix); m_dlcCountCacheSize = 0; - VERIFY(m_startEvent = CreateEvent(0, FALSE, FALSE, 0)); - VERIFY(m_stopEvent = CreateEvent(0, TRUE, FALSE, 0)); - VERIFY(m_cancelEvent = CreateEvent(0, TRUE, FALSE, 0)); - VERIFY(m_savedGameEnumThread = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)SavedGameEnumThread, (LPVOID)this, 0, 0)); + m_listThread = NULL; + m_sizing = false; + m_sizeQuit = false; + m_sizeStart = CreateEvent(0, FALSE, FALSE, 0); + m_sizeIdle = CreateEvent(0, TRUE, FALSE, 0); + m_sizeCancel = CreateEvent(0, TRUE, FALSE, 0); + m_sizeThread = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)SavedGameEnumThread, (LPVOID)this, 0, 0); } +// CSavedGameGrid::~CSavedGameGrid +// Reconstructed from 5960 retail XBE @ 0x47520. Releases the 25 nodes the +// script handed it. If a size query is running the worker is told to quit +// and cancel; then it's waited for and the events and thread closed. CSavedGameGrid::~CSavedGameGrid() { - if (m_pod != NULL) - m_pod->Release(); - - if (m_podRing != NULL) - m_podRing->Release(); - - // Xbox Live Accounts Panel - if (m_podXboxLiveAccountsPanel != NULL) - m_podXboxLiveAccountsPanel->Release(); - if (m_XboxLiveAccountsIconPanel != NULL) - m_XboxLiveAccountsIconPanel->Release(); - if (m_iconBumpRing != NULL) - m_iconBumpRing->Release(); - if (m_iconArrow != NULL) - m_iconArrow->Release(); - if (m_iconCheck != NULL) - m_iconCheck->Release(); - - if (m_podSavePanel != NULL) - m_podSavePanel->Release(); - - if (m_podSoundtrackPanel != NULL) - m_podSoundtrackPanel->Release(); - - if (m_podHilite != NULL) - m_podHilite->Release(); - - if (m_MUheader != NULL) - m_MUheader->Release(); - - if (m_MUhiliteHeader != NULL) - m_MUhiliteHeader->Release(); - - if (m_firstMURow != NULL) - m_firstMURow->Release(); - - if (m_header != NULL) - m_header->Release(); - - if (m_hiliteHeader != NULL) - m_hiliteHeader->Release(); - - if (m_firstRow != NULL) - m_firstRow->Release(); - - if (m_secondRow != NULL) - m_secondRow->Release(); - - if (m_otherRow != NULL) - m_otherRow->Release(); - - if (m_smallIcon != NULL) - m_smallIcon->Release(); - - if (m_SavedIconPanel != NULL) - m_SavedIconPanel->Release(); - - if (m_SoundtrackIconPanel != NULL) - m_SoundtrackIconPanel->Release(); - - if (m_iconRing != NULL) - m_iconRing->Release(); - - if (m_smallIconHilite != NULL) - m_smallIconHilite->Release(); - - if (m_moreUp != NULL) - m_moreUp->Release(); - - if (m_moreDown != NULL) - m_moreDown->Release(); - - // Tear down the background enumeration thread before closing its events. - if (m_savedGameQueryPending) + CNode* held[] = + { + m_pod, m_podRing, + m_podXboxLiveAccountsPanel, m_XboxLiveAccountsIconPanel, m_iconBumpRing, m_iconArrow, m_iconCheck, + m_podSavePanel, m_podSoundtrackPanel, m_podHilite, + m_MUheader, m_MUhiliteHeader, m_firstMURow, m_header, m_hiliteHeader, + m_firstRow, m_secondRow, m_otherRow, + m_smallIcon, m_SavedIconPanel, m_SoundtrackIconPanel, m_iconRing, m_smallIconHilite, + m_moreUp, m_moreDown, + }; + for (int i = 0; i < (int)countof(held); i++) { - m_done = true; - SetEvent(m_cancelEvent); + if (held[i] != NULL) + held[i]->Release(); } - WaitForSingleObject(m_savedGameEnumThread, INFINITE); - - VERIFY(CloseHandle(m_startEvent)); - VERIFY(CloseHandle(m_stopEvent)); - VERIFY(CloseHandle(m_cancelEvent)); - VERIFY(CloseHandle(m_savedGameEnumThread)); + if (m_sizing) + { + m_sizeQuit = true; + SetEvent(m_sizeCancel); + } + WaitForSingleObject(m_sizeThread, INFINITE); + CloseHandle(m_sizeStart); + CloseHandle(m_sizeIdle); + CloseHandle(m_sizeCancel); + CloseHandle(m_sizeThread); } +// Whether a title index is a game rather than the soundtrack row. +#define IS_GAME_ROW(n) (m_soundtrackRow < 0 || (n) < m_soundtrackRow) + +// CSavedGameGrid::GetTitleCount [script fn 'GetTitleCount', FND 0x00187998, sig 2] +// Reconstructed from 5960 retail XBE @ 0x476f0. The device's titles, plus +// one soundtrack row after them on the hard drive when there are any +// soundtracks. 5960 also adds a Live accounts row; Theseus keeps those on +// the copy destination view instead. int CSavedGameGrid::GetTitleCount() { - ASSERT(IsValidDevUnit()); + int titles = g_titles[m_curDevUnit].GetTitleCount(); - int nTitleCount = g_titles[m_curDevUnit].GetTitleCount(); - if (IsHDD()) - { - m_soundtrackCount = GetSoundtrackCount(); - m_soundtrackTitle = nTitleCount; - } - else - { - m_soundtrackCount = 0; - m_soundtrackTitle = -1; - } - - if (IsHDD() && m_soundtrackCount > 0) - { - ASSERT(nTitleCount == m_soundtrackTitle); - nTitleCount += 1; - } + m_soundtracks = IsHDD() ? GetSoundtrackCount() : 0; + m_soundtrackRow = IsHDD() ? titles : -1; - return nTitleCount; + if (IsHDD() && m_soundtracks > 0) + titles++; + return titles; } +// Blocks a title row takes: the title's folders, or every soundtrack. +// 5960 @ 0x477b0. inline int CSavedGameGrid::GetTitleTotalBlocks(int nTitle, HANDLE hCancelEvent) { - ASSERT(IsValidDevUnit()); - if (nTitle < 0) return 0; - - if (m_soundtrackTitle < 0 || nTitle < m_soundtrackTitle) + if (IS_GAME_ROW(nTitle)) return g_titles[m_curDevUnit].GetTitleTotalBlocks(nTitle, hCancelEvent); - return GetSoundtrackSize(-1); } inline const TCHAR *CSavedGameGrid::GetTitleID2(int nTitle) { - ASSERT(IsValidDevUnit()); - - ASSERT(nTitle >= 0 && (m_soundtrackTitle < 0 || nTitle < m_soundtrackTitle)); return g_titles[m_curDevUnit].GetTitleID(nTitle); } +// CSavedGameGrid::GetTitleID [script fn 'GetTitleID', FND 0x00187848, sig 4] +// 5960 @ 0x478d0: the title array's id as a string. inline CStrObject *CSavedGameGrid::GetTitleID(int nTitle) { - ASSERT(nTitle >= 0 && (m_soundtrackTitle < 0 || nTitle < m_soundtrackTitle)); return new CStrObject(GetTitleID2(nTitle)); } +// CSavedGameGrid::GetTitleName2(n, out) +// Reconstructed from 5960 retail XBE @ 0x47970. The device row (-1) is +// "Xbox Hard Disk", or the memory unit's own name, or failing that +// "memory unit <port><A|B>" from its slot. The soundtrack row is +// "Soundtracks"; anything else is the title's name. void CSavedGameGrid::GetTitleName2(int nTitle, TCHAR *szBuf) { - TCHAR sz[MAX_TRANSLATE_LEN]; - ASSERT(IsValidDevUnit()); + TCHAR translated[MAX_TRANSLATE_LEN]; - if (nTitle < 0) + if (nTitle >= 0) { - if (IsHDD()) - _tcscpy(szBuf, Translate(_T("Xbox Hard Disk"), sz)); + if (IS_GAME_ROW(nTitle)) + _tcscpy(szBuf, g_titles[m_curDevUnit].GetTitleName(nTitle)); else - { - FormatDeviceName(m_curDevUnit, szBuf); - if (szBuf[0] == 0) - { - TCHAR ch = _T('B'); - - // Generate a name based on location of slot... - int nGamePad = (m_curDevUnit + 1) % 2; - if (nGamePad) - ch = _T('A'); - - Translate(_T("memory unit"), sz); - swprintf(szBuf, _T("%s %d%c"), sz, (m_curDevUnit / 2) + 1, ch); - } - } + _tcscpy(szBuf, Translate(_T("Soundtracks"), translated)); return; } - if (m_soundtrackTitle < 0 || nTitle < m_soundtrackTitle) + if (IsHDD()) { - _tcscpy(szBuf, g_titles[m_curDevUnit].GetTitleName(nTitle)); + _tcscpy(szBuf, Translate(_T("Xbox Hard Disk"), translated)); return; } - _tcscpy(szBuf, Translate(_T("Soundtracks"), sz)); + FormatDeviceName(m_curDevUnit, szBuf); + if (szBuf[0] != 0) + return; + + TCHAR slot = ((m_curDevUnit + 1) % 2) ? _T('A') : _T('B'); + Translate(_T("memory unit"), translated); + swprintf(szBuf, _T("%s %d%c"), translated, m_curDevUnit / 2 + 1, slot); } +// CSavedGameGrid::GetTitleName [script fn 'GetTitleName', FND 0x00187830, sig 4] +// 5960 @ 0x47ab0. inline CStrObject *CSavedGameGrid::GetTitleName(int nTitle) { - TCHAR szBuf[256]; - GetTitleName2(nTitle, szBuf); - return new CStrObject(szBuf); + TCHAR name[256]; + GetTitleName2(nTitle, name); + return new CStrObject(name); } inline const TCHAR *CSavedGameGrid::GetSavedGameID2(int nTitle, int nSavedGame) { - ASSERT(IsValidDevUnit()); - - ASSERT(nTitle >= 0 && (m_soundtrackTitle < 0 || nTitle < m_soundtrackTitle)); return g_titles[m_curDevUnit].GetSavedGameID(nTitle, nSavedGame); } inline FILETIME CSavedGameGrid::GetSavedGameTime(int nTitle, int nSavedGame) { - ASSERT(IsValidDevUnit()); - - ASSERT(nTitle >= 0 && (m_soundtrackTitle < 0 || nTitle < m_soundtrackTitle)); return g_titles[m_curDevUnit].GetSavedGameTime(nTitle, nSavedGame); } +// CSavedGameGrid::TitlesEnumThread +// Reconstructed from 5960 retail XBE @ 0x47bb0. Busy while the device's +// title list is rebuilt; on the hard drive the soundtrack row goes after +// the titles if there are soundtracks. void WINAPI CSavedGameGrid::TitlesEnumThread(CSavedGameGrid *p) { - p->m_busy = true; - - // Enumerate all titles on current device unit + p->m_listing = true; g_titles[p->m_curDevUnit].Update(); - // Also enumerate soundtrack if it's a hard disk - if (p->IsHDD() && p->m_soundtrackTitle == -1) + if (p->IsHDD() && p->m_soundtrackRow == -1) { - int nSoundtrackCount = GetSoundtrackCount(); - if (nSoundtrackCount > 0) + int soundtracks = GetSoundtrackCount(); + if (soundtracks > 0) { - p->m_soundtrackTitle = p->GetTitleCount(); - p->m_soundtrackCount = nSoundtrackCount; + p->m_soundtrackRow = p->GetTitleCount(); + p->m_soundtracks = soundtracks; } } - - p->m_busy = false; + p->m_listing = false; } +// CSavedGameGrid::SavedGameEnumThread +// 5960 @ 0x47c70. Sleeps until Advance asks (start event), signaling stop +// while it waits, then fills whichever size is missing: the selected save +// (or soundtrack), else the selected title. The cancel event cuts a count +// short. void WINAPI CSavedGameGrid::SavedGameEnumThread(CSavedGameGrid *p) { - while (!p->m_done) + while (!p->m_sizeQuit) { - ASSERT(p->m_startEvent); - ASSERT(p->m_stopEvent); + SignalObjectAndWait(p->m_sizeIdle, p->m_sizeStart, INFINITE, FALSE); + ResetEvent(p->m_sizeIdle); - SignalObjectAndWait(p->m_stopEvent, p->m_startEvent, INFINITE, FALSE); - ResetEvent(p->m_stopEvent); - - ASSERT(!g_titles[p->m_curDevUnit].IsDirty()); - - if (p->m_cacheSavedGameSize < 0 && p->m_curTitle >= 0 && p->m_curGridItem >= 0) + if (p->m_itemBlocks < 0 && p->m_curTitle >= 0 && p->m_curGridItem >= 0) { - if (p->m_soundtrackTitle < 0 || p->m_curTitle < p->m_soundtrackTitle) + if (p->m_soundtrackRow >= 0 && p->m_curTitle >= p->m_soundtrackRow) { - TCHAR szSavedGameDir[MAX_PATH]; - if (p->GetSavedGamePath(szSavedGameDir, p->m_curTitle, p->m_curGridItem)) - { - p->m_cacheSavedGameSize = GetDirectoryBlocks(szSavedGameDir, BLOCK_SIZE, true, p->m_cancelEvent); - } - else - { - p->m_cacheSavedGameSize = 0; - } - } - else - { - p->m_cacheSavedGameSize = GetSoundtrackSize(p->m_curGridItem); + p->m_itemBlocks = GetSoundtrackSize(p->m_curGridItem); + continue; } + + TCHAR dir[MAX_PATH]; + p->m_itemBlocks = p->GetSavedGamePath(dir, p->m_curTitle, p->m_curGridItem) + ? GetDirectoryBlocks(dir, BLOCK_SIZE, true, p->m_sizeCancel) : 0; } - else if (p->m_cacheTitleSize < 0) + else if (p->m_titleBlocks < 0) { - p->m_cacheTitleSize = p->GetTitleTotalBlocks(p->m_curTitle, p->m_cancelEvent); + p->m_titleBlocks = p->GetTitleTotalBlocks(p->m_curTitle, p->m_sizeCancel); } } } +// Theseus's size cache upkeep (5960 does the same work inline in Advance): +// collect a finished query, drop the sizes the selection change made stale, +// and start the worker when one is missing. void CSavedGameGrid::RefreshSizeCaches() { - // Drain a completed background size query if one was running. - if (m_savedGameQueryPending && WaitForSingleObject(m_stopEvent, 0) == WAIT_OBJECT_0) - m_savedGameQueryPending = false; - - // Detect selection changes and invalidate the affected caches. - bool needQuery = false; + if (m_sizing && WaitForSingleObject(m_sizeIdle, 0) == WAIT_OBJECT_0) + m_sizing = false; - if (m_curGridItem != m_curGridItemCache) + bool ask; + if (m_curGridItem != m_sizedItem) { - m_curGridItemCache = m_curGridItem; - m_cacheSavedGameSize = -1; - needQuery = true; + m_sizedItem = m_curGridItem; + m_itemBlocks = -1; + ask = true; } - else if (m_curTitle != m_curTitleCache) + else if (m_curTitle != m_sizedTitle) { - m_curTitleCache = m_curTitle; - m_curGridItemCache = m_curGridItem; - m_cacheTitleSize = -1; - m_cacheSavedGameSize = -1; - needQuery = true; + m_sizedTitle = m_curTitle; + m_sizedItem = m_curGridItem; + m_titleBlocks = -1; + m_itemBlocks = -1; + ask = true; } - else if (!m_savedGameQueryPending && (m_cacheTitleSize < 0 || m_cacheSavedGameSize < 0)) + else { - needQuery = true; + ask = !m_sizing && (m_titleBlocks < 0 || m_itemBlocks < 0); } - // Kick off a new background query if there's a missing cache and a - // real title to query. - if (!needQuery || m_curTitle < 0) + if (!ask || m_curTitle < 0) return; - - const bool wantTitleSize = (m_cacheTitleSize < 0); - const bool wantSaveSize = (m_cacheSavedGameSize < 0 && m_curGridItem >= 0); - if (!wantTitleSize && !wantSaveSize) + if (m_titleBlocks >= 0 && (m_itemBlocks >= 0 || m_curGridItem < 0)) return; - // Cancel any in-flight query before starting the new one. - if (m_savedGameQueryPending) - SignalObjectAndWait(m_cancelEvent, m_stopEvent, INFINITE, FALSE); - - ResetEvent(m_cancelEvent); - SetEvent(m_startEvent); - m_savedGameQueryPending = true; + if (m_sizing) + SignalObjectAndWait(m_sizeCancel, m_sizeIdle, INFINITE, FALSE); + ResetEvent(m_sizeCancel); + SetEvent(m_sizeStart); + m_sizing = true; } +// From the end of 5960's Advance (0x47e50): the device's size and free +// space in blocks, rounded up, less the root folder's block. A failed +// query reads as one block, none free. A change (or a new language) is +// announced with OnTotalFreeChanged and OnSelChange. void CSavedGameGrid::RefreshDiskFreeSpace() { #ifdef _XBOX - FSCHAR path[MAX_PATH]; - Ansi(path, g_titles[m_curDevUnit].GetUData(), MAX_PATH); + FSCHAR root[MAX_PATH]; + Ansi(root, g_titles[m_curDevUnit].GetUData(), MAX_PATH); #else - const FSCHAR *path = g_titles[m_curDevUnit].GetUData(); + const FSCHAR *root = g_titles[m_curDevUnit].GetUData(); #endif - ULARGE_INTEGER availBytes, totalBytes, freeBytes; - if (!TheseusGetDiskFreeSpaceEx(path, &availBytes, &totalBytes, &freeBytes)) + ULARGE_INTEGER avail, total, free; + if (!TheseusGetDiskFreeSpaceEx(root, &avail, &total, &free)) { - // Treat query failures as a "full empty disk" so the UI shows - // 0 free instead of stale values from the previous device. - freeBytes.QuadPart = 0; - totalBytes.QuadPart = BLOCK_SIZE; - TRACE(_T("GetDiskFreeSpaceEx %s failed: %d\n"), g_titles[m_curDevUnit].GetUData(), GetLastError()); + free.QuadPart = 0; + total.QuadPart = BLOCK_SIZE; } - int totalBlocks = (int)((totalBytes.QuadPart + BLOCK_SIZE - 1) / BLOCK_SIZE); - int freeBlocks = (int)((freeBytes.QuadPart + BLOCK_SIZE - 1) / BLOCK_SIZE); - - // One block is always consumed by the volume root directory. - totalBlocks -= 1; - - if (totalBlocks == m_totalBlocks && freeBlocks == m_freeBlocks && g_nCurLanguage == m_language) + int totalBlocks = (int)((total.QuadPart + BLOCK_SIZE - 1) / BLOCK_SIZE) - 1; + int freeBlocks = (int)((free.QuadPart + BLOCK_SIZE - 1) / BLOCK_SIZE); + if (totalBlocks == m_deviceBlocks && freeBlocks == m_freeBlocks && g_nCurLanguage == m_shownLanguage) return; - m_language = g_nCurLanguage; - m_totalBlocks = totalBlocks; + m_shownLanguage = g_nCurLanguage; + m_deviceBlocks = totalBlocks; m_freeBlocks = freeBlocks; CallFunction(this, _T("OnTotalFreeChanged")); CallFunction(this, _T("OnSelChange")); } +// Fires OnSelChange and restarts the highlight pulse. +void CSavedGameGrid::NotifySelectionChanged() +{ + CallFunction(this, _T("OnSelChange")); + g_pulseStartTime = TheseusGetNow(); +} + +// CSavedGameGrid::Advance(seconds) +// Reconstructed from 5960 retail XBE @ 0x47e50. Nothing without a device or +// while inactive. A stale title list is rebuilt on a thread between +// OnUpdatingTitlesBegin and OnUpdatingTitlesEnd (the end held back at least +// a second; run inline if no thread). A copy reports progress and finishes +// with OnCopyError or, half a second in at the earliest, OnCopyComplete. A +// delete finishes with OnDeleteEnd and OnSelChange. A pulled device sends +// OnDeviceRemoved and drops it. Then sizes and free space are kept current +// and the list eases toward its scroll target over a quarter second. void CSavedGameGrid::Advance(float nSeconds) { CNode::Advance(nSeconds); @@ -836,50 +766,34 @@ void CSavedGameGrid::Advance(float nSeconds) if (m_curDevUnit == -1 || !m_isActive) return; - ASSERT(IsValidDevUnit()); + CTitleArray& titles = g_titles[m_curDevUnit]; - // Enumerating all titles in UDATA - if (m_titlesEnumThread) + if (m_listThread != NULL) { - if (TheseusGetNow() > m_timeToSendEnd && WaitForSingleObject(m_titlesEnumThread, 0) == WAIT_OBJECT_0) - { - VERIFY(CallFunction(this, _T("OnUpdatingTitlesEnd"))); - VERIFY(CloseHandle(m_titlesEnumThread)); - m_titlesEnumThread = NULL; - InvalidateDLCCache(); - } - else - { + if (TheseusGetNow() <= m_listEndAt || WaitForSingleObject(m_listThread, 0) != WAIT_OBJECT_0) return; - } + CallFunction(this, _T("OnUpdatingTitlesEnd")); + CloseHandle(m_listThread); + m_listThread = NULL; + InvalidateDLCCache(); } - else if (g_titles[m_curDevUnit].IsDirty()) + else if (titles.IsDirty()) { - if (!m_titlesEnumThread) - { - m_soundtrackTitle = -1; - m_soundtrackCount = 0; - - m_timeToSendEnd = TheseusGetNow() + 1.0f; - VERIFY(CallFunction(this, _T("OnUpdatingTitlesBegin"))); + m_soundtrackRow = -1; + m_soundtracks = 0; + m_listEndAt = TheseusGetNow() + 1.0f; + CallFunction(this, _T("OnUpdatingTitlesBegin")); - m_titlesEnumThread = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)TitlesEnumThread, (LPVOID)this, 0, 0); + m_listThread = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)TitlesEnumThread, (LPVOID)this, 0, 0); + if (m_listThread != NULL) + return; - // If the CreateThread failed, call it directly - if (!m_titlesEnumThread) - { - TitlesEnumThread(this); - VERIFY(CallFunction(this, _T("OnUpdatingTitlesEnd"))); - InvalidateDLCCache(); - goto next; - } - } - return; + TitlesEnumThread(this); + CallFunction(this, _T("OnUpdatingTitlesEnd")); + InvalidateDLCCache(); } -next: - - if (m_copying) + if (m_copyRunning) { if (m_copyProgress != theGameCopier.m_progress) { @@ -889,84 +803,73 @@ void CSavedGameGrid::Advance(float nSeconds) if (theGameCopier.m_error) { - m_copying = false; + m_copyRunning = false; theGameCopier.Finish(); - TRACE(_T("OnCopyError\n")); CallFunction(this, _T("OnCopyError")); } - else if (theGameCopier.m_done && TheseusGetNow() >= m_timeCopyingStarted + 0.5f) + else if (theGameCopier.m_done && TheseusGetNow() >= m_copyStart + 0.5f) { - m_copying = false; + m_copyRunning = false; theGameCopier.Finish(); - TRACE(_T("OnCopyComplete\n")); CallFunction(this, _T("OnCopyComplete")); } return; } - if (m_deleting) + if (m_deleteRunning) { - ASSERT(m_deleteThread); - if (WaitForSingleObject(m_deleteThread, 0) == WAIT_OBJECT_0) + if (WaitForSingleObject(m_deleter, 0) == WAIT_OBJECT_0) { - CloseHandle(m_deleteThread); - m_deleteThread = NULL; - m_deleting = false; + CloseHandle(m_deleter); + m_deleter = NULL; + m_deleteRunning = false; InvalidateDLCCache(); - VERIFY(CallFunction(this, _T("OnDeleteEnd"))); - VERIFY(CallFunction(this, _T("OnSelChange"))); - g_pulseStartTime = TheseusGetNow(); + CallFunction(this, _T("OnDeleteEnd")); + NotifySelectionChanged(); } return; } - if (!g_titles[m_curDevUnit].IsValid()) + if (!titles.IsValid()) { CallFunction(this, _T("OnDeviceRemoved")); m_curDevUnit = -1; return; } - - if (g_titles[m_curDevUnit].IsDirty()) - { + if (titles.IsDirty()) return; - } RefreshSizeCaches(); RefreshDiskFreeSpace(); - if (m_timeScroll != 0.0f) - { - float t = (float)(TheseusGetNow() - m_timeScroll) / 0.25f; - if (t >= 1.0f) - { - m_timeScroll = 0.0f; - t = 1.0f; - } - - float t1 = 1.0f - t; - m_scroll = t1 * m_scroll + t * m_scrollTo; + if (m_scrollStart == 0.0f) + return; - m_focusPodMatrixValid = false; + float t = (float)(TheseusGetNow() - m_scrollStart) / 0.25f; + if (t >= 1.0f) + { + t = 1.0f; + m_scrollStart = 0.0f; } + m_scroll = (1.0f - t) * m_scroll + t * m_scrollTarget; + m_focusPodMatrixValid = false; } +// CSavedGameGrid::GetUpdateString [script fn 'GetUpdateString', FND 0x001879b0, sig 8] +// Reconstructed from 5960 retail XBE @ 0x48450: every half second the +// translated "Copying" gets one more dot, cycling 0..3. CStrObject *CSavedGameGrid::GetUpdateString(void) { - if ((GetTickCount() - m_lastUpdateTick) > 500) + if (GetTickCount() - m_dotsTick > 500) { - m_lastUpdateTick = GetTickCount(); - m_periodStatus++; - if (m_periodStatus > 3) - m_periodStatus = 0; - - Translate(_T("Copying"), m_statusText); + m_dotsTick = GetTickCount(); + m_dots = (m_dots + 1 > 3) ? 0 : m_dots + 1; - for (int i = 0; i < m_periodStatus; i++) - _tcscat(m_statusText, _T(".")); + Translate(_T("Copying"), m_copyingText); + for (int dots = 0; dots < m_dots; dots++) + _tcscat(m_copyingText, _T(".")); } - - return new CStrObject(m_statusText); + return new CStrObject(m_copyingText); } void CSavedGameGrid::InvalidateDLCCache() @@ -974,252 +877,210 @@ void CSavedGameGrid::InvalidateDLCCache() m_dlcCountCacheSize = 0; } +// curDevUnit set: select the device row (the first title on the copy +// destination view) at once and forget cached sizes. 5960 @ 0x48530. void CSavedGameGrid::OnDevUnitChanged(int newDevUnit) { m_curDevUnit = newDevUnit; - - // Focus the first row by default; on the MU selector view focus the - // first MU slot instead. SelectTitle(IsMUSelector() ? 0 : -1, true); - - // Cached sizes belong to the previous device; drop them. - m_cacheSavedGameSize = -1; - m_cacheTitleSize = -1; + m_itemBlocks = -1; + m_titleBlocks = -1; InvalidateDLCCache(); } +// isActive cleared on an active grid: cancel a running size query, forget +// sizes, and (Theseus) flush the texture cache so save icons don't stay. void CSavedGameGrid::OnIsActiveChanged(bool active) { - if (active) - return; - - // Only run deactivation cleanup on a real active->inactive transition, - // not during initial scene setup when isActive is first set to false. - if (!m_isActive) + if (active || !m_isActive) return; - // Going inactive while a query is in flight: cancel it and let the - // worker drop back to its idle wait state before we touch the cache. - if (m_savedGameQueryPending) + if (m_sizing) { - SignalObjectAndWait(m_cancelEvent, m_stopEvent, INFINITE, FALSE); - m_savedGameQueryPending = false; + SignalObjectAndWait(m_sizeCancel, m_sizeIdle, INFINITE, FALSE); + m_sizing = false; } - - m_cacheTitleSize = -1; - m_cacheSavedGameSize = -1; - - // Flush the texture cache so save game thumbnails don't linger and - // consume RAM after we leave the Memory blade. + m_titleBlocks = -1; + m_itemBlocks = -1; FlushTextureCache(); } +// CSavedGameGrid::OnSetProperty +// Reconstructed from 5960 retail XBE @ 0x48530: curDevUnit and curTitle go +// through their handlers instead of being stored; isActive is watched for +// going off. bool CSavedGameGrid::OnSetProperty(const PRD *pprd, const void *pvValue) { - const int offset = PTR2INT(pprd->pbOffset); + int field = PTR2INT(pprd->pbOffset); - if (offset == offsetof(m_curDevUnit)) + if (field == offsetof(m_curDevUnit)) { - OnDevUnitChanged(*(int *)pvValue); + OnDevUnitChanged(*(const int *)pvValue); return false; } - if (offset == offsetof(m_curTitle)) + if (field == offsetof(m_curTitle)) { - SelectTitle(*(int *)pvValue); + SelectTitle(*(const int *)pvValue); return false; } - if (offset == offsetof(m_isActive)) - { - OnIsActiveChanged(*(bool *)pvValue); - } - + if (field == offsetof(m_isActive)) + OnIsActiveChanged(*(const bool *)pvValue); return true; } +// ============================================================================= +// Drawing +// ============================================================================= + +// Draws one node under an extra transform. static void RenderNodeAt(CNode *pNode, D3DXMATRIX *pMatrix) { if (pNode == NULL) return; - TheseusPushWorld(); TheseusMultWorld(pMatrix); - TheseusUpdateWorld(); - pNode->Render(); - TheseusPopWorld(); } -void CSavedGameGrid::RenderIconRow(D3DXMATRIX *pMatrix, float y, int nTitle, int nFirstSavedGame, int nSavedGames) +// Theseus: the ContentImage.xbx of a title's Nth DLC, false when there's +// no such folder. +bool CSavedGameGrid::GetDLCImagePath(int nTitle, int dlcIndex, TCHAR *out) { - bool isDLC = false; - if (m_smallIcon == NULL) - return; + char titleID[9]; + char folder[17]; + if (!ResolveDLCFolder(nTitle, dlcIndex, titleID, sizeof(titleID), folder, sizeof(folder))) + return false; - if (nTitle < 0) - { - // Device-level row (memory unit selector); no icon row to draw. - return; - } + char path[MAX_PATH]; + _snprintf(path, MAX_PATH, "E:\\TDATA\\%s\\$c\\%s\\ContentImage.xbx", titleID, folder); + MultiByteToWideChar(CP_ACP, 0, path, -1, out, MAX_PATH); + return true; +} - int nLim = nFirstSavedGame + m_iconsPerRow; - if (nLim > nSavedGames) - nLim = nSavedGames; +// CSavedGameGrid::RenderIconRow(parent, y, title, first, count) +// Reconstructed from 5960 retail XBE @ 0x48690. One row of up to +// iconsPerRow small icons starting at item first, spaced smallIconSpacing +// apart. A save shows its image through SavedIconPanel, a soundtrack the +// soundtrack icon through SoundtrackIconPanel. The selected item gets the +// ring unless its icon is lifted out. Theseus: items past the saves are +// DLC, drawn from the content's image with a check mark. +void CSavedGameGrid::RenderIconRow(D3DXMATRIX *pMatrix, float y, int nTitle, int nFirstSavedGame, int nSavedGames) +{ + if (m_smallIcon == NULL || nTitle < 0) + return; - ASSERT(nFirstSavedGame == 0 || nFirstSavedGame < nLim); + int end = nFirstSavedGame + m_iconsPerRow; + if (end > nSavedGames) + end = nSavedGames; + bool isDLC = false; float x = 0.0f; - for (int i = nFirstSavedGame; i < nLim; i += 1) + for (int item = nFirstSavedGame; item < end; item++, x += m_smallIconSpacing) { - D3DXMATRIX mat2; - D3DXMatrixTranslation(&mat2, x, y, 0.0f); - D3DXMatrixMultiply(&mat2, pMatrix, &mat2); + D3DXMATRIX at; + D3DXMatrixTranslation(&at, x, y, 0.0f); + D3DXMatrixMultiply(&at, pMatrix, &at); - TCHAR szBuf[MAX_PATH]; - if (m_soundtrackTitle < 0 || nTitle < m_soundtrackTitle) + TCHAR image[MAX_PATH]; + if (IS_GAME_ROW(nTitle)) { - int nSavedCount = GetSavedGameCount(nTitle); - if (i < nSavedCount) - { - g_titles[m_curDevUnit].GetSavedGameImageName(nTitle, i, szBuf); - } + int saves = GetSavedGameCount(nTitle); + if (item < saves) + g_titles[m_curDevUnit].GetSavedGameImageName(nTitle, item, image); + else if (GetDLCImagePath(nTitle, item - saves, image)) + isDLC = true; else - { - // DLC item: load the Nth DLC folder's ContentImage.xbx - // (small icon variant), or fall back to the placeholder. - char titleIDChar[9]; - char dlcFolder[17]; - if (ResolveDLCFolder(nTitle, i - nSavedCount, - titleIDChar, sizeof(titleIDChar), - dlcFolder, sizeof(dlcFolder))) - { - char dlcImagePath[MAX_PATH]; - _snprintf(dlcImagePath, MAX_PATH, "E:\\TDATA\\%s\\$c\\%s\\ContentImage.xbx", - titleIDChar, dlcFolder); - MultiByteToWideChar(CP_ACP, 0, dlcImagePath, -1, szBuf, MAX_PATH); - isDLC = true; // show m_iconCheck overlay - } - else - { - _tcscpy(szBuf, _T("dlcitem64.xbx")); - } - } + _tcscpy(image, _T("dlcitem64.xbx")); - g_szCurTitleImage = szBuf; - RenderNodeAt(m_SavedIconPanel, &mat2); + g_szCurTitleImage = image; + RenderNodeAt(m_SavedIconPanel, &at); } - else // is a soundtrack + else { - _tcscpy(szBuf, _T("soundtracksave64.tga")); - g_szCurTitleImage = szBuf; - RenderNodeAt(m_SoundtrackIconPanel, &mat2); + _tcscpy(image, _T("soundtracksave64.tga")); + g_szCurTitleImage = image; + RenderNodeAt(m_SoundtrackIconPanel, &at); } - g_szCurTitleImage = NULL; - if (!m_detachIcon && m_smallIconHilite != NULL && nTitle == m_curTitle && i == m_curGridItem) - RenderNodeAt(m_iconRing, &mat2); - if (isDLC && m_iconCheck) - RenderNodeAt(m_iconCheck, &mat2); - x += m_smallIconSpacing; + if (!m_detachIcon && m_smallIconHilite != NULL && nTitle == m_curTitle && item == m_curGridItem) + RenderNodeAt(m_iconRing, &at); + if (isDLC && m_iconCheck != NULL) + RenderNodeAt(m_iconCheck, &at); } } +// The big icon on a title's pod: the memory unit for the device row, the +// soundtrack art, the lifted item's own image while an icon is detached, +// else the title's TitleImage.xbx or the Xbox logo. (5960 RenderLoop, +// 0x48910; the DLC images are Theseus's.) void CSavedGameGrid::ResolveTitlePodImageName(int nTitle, TCHAR *outBuf) { - // Memory unit row. if (nTitle == -1) { _tcscpy(outBuf, _T("memoryUnit128.tga")); return; } - - // Soundtrack row sits at the end of the title list on HDD. - if (m_soundtrackTitle >= 0 && nTitle >= m_soundtrackTitle) + if (!IS_GAME_ROW(nTitle)) { _tcscpy(outBuf, _T("soundtracksave3.tga")); return; } - // Game title with detached icon: the lifted pod shows the icon for - // whichever grid item is currently selected (saved game or DLC). if (nTitle == m_curTitle && m_detachIcon && m_curGridItem != -1) { - const int nSavedGames = GetSavedGameCount(nTitle); - const int nDLC = GetDLContentCount(nTitle); - - if (m_curGridItem < nSavedGames) - { + int saves = GetSavedGameCount(nTitle); + int dlc = GetDLContentCount(nTitle); + if (m_curGridItem < saves) g_titles[m_curDevUnit].GetSavedGameImageName(nTitle, m_curGridItem, outBuf); - return; - } - - if (m_curGridItem - nSavedGames < nDLC) - { - char titleIDChar[9]; - char dlcFolder[17]; - if (ResolveDLCFolder(nTitle, m_curGridItem - nSavedGames, - titleIDChar, sizeof(titleIDChar), - dlcFolder, sizeof(dlcFolder))) - { - char contentImagePath[MAX_PATH]; - _snprintf(contentImagePath, MAX_PATH, - "E:\\TDATA\\%s\\$c\\%s\\ContentImage.xbx", - titleIDChar, dlcFolder); - MultiByteToWideChar(CP_ACP, 0, contentImagePath, -1, outBuf, MAX_PATH); - return; - } + else if (m_curGridItem - saves >= dlc) + _tcscpy(outBuf, _T("xboxlogo128.xbx")); + else if (!GetDLCImagePath(nTitle, m_curGridItem - saves, outBuf)) _tcscpy(outBuf, _T("dlcitem128.xbx")); - return; - } - - // Out-of-range grid item: fall back to the generic logo. - _tcscpy(outBuf, _T("xboxlogo128.xbx")); return; } - // Default: the title's own 128px icon, falling back to the logo if - // the title doesn't ship one. MakePath(outBuf, g_titles[m_curDevUnit].GetUData(), GetTitleID2(nTitle)); MakePath(outBuf, outBuf, szTitleImageXBX); if (!DoesFileExist(outBuf)) _tcscpy(outBuf, _T("xboxlogo128.xbx")); } +// A title's pod and its save (or soundtrack) panel. Once the list has +// settled, the selected pod is drawn from a remembered world matrix so it +// can be lifted independently of the list, with the ring when the title +// itself is selected. A title just deleted fades out over a second through +// the ordinary path. (5960 RenderLoop, 0x48910.) void CSavedGameGrid::RenderTitlePodAt(int nTitle, float y, const D3DXMATRIX *parentMat) { if (m_pod == NULL) return; - TCHAR imageName[MAX_PATH]; - ResolveTitlePodImageName(nTitle, imageName); - g_szCurTitleImage = imageName; - - const float effectAlphaSave = g_nEffectAlpha; + TCHAR image[MAX_PATH]; + ResolveTitlePodImageName(nTitle, image); + g_szCurTitleImage = image; - bool renderNormal = true; - bool renderHack = false; - bool renderHilite = false; - const bool renderSoundtrack = (nTitle == m_soundtrackTitle); + const float alphaBefore = g_nEffectAlpha; + CNode *panel = (nTitle == m_soundtrackRow) ? m_podSoundtrackPanel : m_podSavePanel; - // Selected pod takes the captured-matrix path so it can lift up - // independent of the row scroll position. - if (nTitle == m_curTitle && m_scroll == m_scrollTo) + bool lifted = false; + bool ring = false; + bool plain = true; + if (nTitle == m_curTitle && m_scroll == m_scrollTarget) { - renderNormal = false; - renderHack = true; - renderHilite = !m_detachIcon && m_podHilite != NULL && m_curGridItem == -1; + lifted = true; + plain = false; + ring = !m_detachIcon && m_podHilite != NULL && m_curGridItem == -1; - // Mid-delete fade: collapse to the normal pod path with alpha - // decay so the pod fades out instead of jumping. - if (nTitle > -1 && nTitle == m_deletedTitle) + if (nTitle > -1 && nTitle == m_fadingTitle) { - const float t = (float)(TheseusGetNow() - m_timeOfDelete) / 1.0f; + float t = (float)(TheseusGetNow() - m_fadeStart) / 1.0f; if (t >= 1.0f) { - m_timeOfDelete = 0.0f; - m_deletedTitle = -1; + m_fadeStart = 0.0f; + m_fadingTitle = -1; m_focusPodMatrixValid = false; } else @@ -1227,15 +1088,14 @@ void CSavedGameGrid::RenderTitlePodAt(int nTitle, float y, const D3DXMATRIX *par g_nEffectAlpha *= 1.0f - t; g_szCurTitleImage = NULL; m_focusPodMatrixValid = true; - renderHilite = false; - renderNormal = true; + ring = false; + plain = true; } } } - if (renderHack) + if (lifted) { - D3DXMATRIX mat; TheseusPushWorld(); if (m_focusPodMatrixValid) { @@ -1244,388 +1104,298 @@ void CSavedGameGrid::RenderTitlePodAt(int nTitle, float y, const D3DXMATRIX *par } else { - D3DXMatrixTranslation(&mat, -0.3292f, y, -0.0271f); - D3DXMatrixMultiply(&mat, parentMat, &mat); - TheseusMultWorld(&mat); + D3DXMATRIX at; + D3DXMatrixTranslation(&at, -0.3292f, y, -0.0271f); + D3DXMatrixMultiply(&at, parentMat, &at); + TheseusMultWorld(&at); m_focusPodMatrix = *TheseusGetWorld(); m_focusPodMatrixValid = true; } - TheseusUpdateWorld(); m_pod->Render(); - if (renderSoundtrack) - m_podSoundtrackPanel->Render(); - else - m_podSavePanel->Render(); - if (renderHilite) + panel->Render(); + if (ring) m_podRing->Render(); TheseusPopWorld(); } - g_nEffectAlpha = effectAlphaSave; - g_szCurTitleImage = imageName; + g_nEffectAlpha = alphaBefore; + g_szCurTitleImage = image; - if (renderNormal) + if (plain) { - D3DXMATRIX mat; - D3DXMatrixTranslation(&mat, -0.3292f, y, -0.0271f); - D3DXMatrixMultiply(&mat, parentMat, &mat); - RenderNodeAt(m_pod, &mat); - if (renderSoundtrack) - RenderNodeAt(m_podSoundtrackPanel, &mat); - else - RenderNodeAt(m_podSavePanel, &mat); + D3DXMATRIX at; + D3DXMatrixTranslation(&at, -0.3292f, y, -0.0271f); + D3DXMatrixMultiply(&at, parentMat, &at); + RenderNodeAt(m_pod, &at); + RenderNodeAt(panel, &at); } - g_szCurTitleImage = NULL; } +// CSavedGameGrid::Render +// Reconstructed from 5960 retail XBE @ 0x488a0: only with the row nodes +// set, a mounted and current device, active and not rebuilding. void CSavedGameGrid::Render() { if (m_header == NULL || m_firstRow == NULL || m_secondRow == NULL || m_otherRow == NULL) return; - if (m_curDevUnit == -1 || !g_titles[m_curDevUnit].IsValid() || g_titles[m_curDevUnit].IsDirty()) return; - - if (!m_isActive || m_busy) + if (!m_isActive || m_listing) return; - RenderLoop(true); } +// CSavedGameGrid::RenderLoop(render) +// Reconstructed from 5960 retail XBE @ 0x48910. Lays the list out top +// down from the scroll offset in a frame turned a quarter turn about -x +// and scaled 0.05942: the device row first (not on the copy destination +// view), then each title. A title is its pod, a header (highlighted when +// selected) with its name tinted gray when selected and green otherwise, +// and up to three icon rows with more-up and more-down arrows. Rows above +// the selected one show their last icon rows. Unselected titles fade to +// half strength as the selection moves. With render off it only measures: +// the offset of the selected title, which SelectTitle scrolls to. Drawing +// stops below -1.25. Spacing constants and the layout are in +// docs/decomp/SavedGameGrid.md. float CSavedGameGrid::RenderLoop(bool bRender) { - D3DXMATRIX mat, mat2, scrollMat; - D3DXVECTOR3 v(-1.0f, 0.0f, 0.0f); - D3DXMatrixRotationAxis(&mat, &v, -1.571f); - D3DXMatrixScaling(&mat2, 0.05942f, 0.05942f, 0.05942f); - D3DXMatrixMultiply(&mat, &mat, &mat2); + D3DXMATRIX frame, at, upArrow; + D3DXVECTOR3 axis(-1.0f, 0.0f, 0.0f); + D3DXMatrixRotationAxis(&frame, &axis, -1.571f); + D3DXMatrixScaling(&at, 0.05942f, 0.05942f, 0.05942f); + D3DXMatrixMultiply(&frame, &frame, &at); + const float bottom = -1.25f; float y = m_scroll; - float yLimit = -1.25f; - - int nTitleCount = GetTitleCount(); - - int initLoop; - if (IsMUSelector()) // do we render the memory panel at the top of the memory list - initLoop = 0; - else - initLoop = -1; + int titleCount = GetTitleCount(); - int nTitle; - for (nTitle = initLoop; nTitle < nTitleCount && (!bRender || y > yLimit); nTitle += 1) + for (int nTitle = IsMUSelector() ? 0 : -1; nTitle < titleCount && (!bRender || y > bottom); nTitle++) { - float nEffectAlphaSave = g_nEffectAlpha; - int nSavedGames = 0; + const float alphaBefore = g_nEffectAlpha; - // Check how many saved games (or soundtracks) this title has + int items = 0; if (nTitle >= 0) - { - if (m_soundtrackTitle < 0 || nTitle < m_soundtrackTitle) - { - nSavedGames = GetSavedGameCount(nTitle); - nSavedGames += GetDLContentCount(nTitle); - } - else - { - nSavedGames = m_soundtrackCount; - } - } - - int nRowCount = (nSavedGames + m_iconsPerRow - 1) / m_iconsPerRow; + items = IS_GAME_ROW(nTitle) ? GetSavedGameCount(nTitle) + GetDLContentCount(nTitle) : m_soundtracks; + int rows = (items + m_iconsPerRow - 1) / m_iconsPerRow; - int nIconRowScroll = 0; + int firstRow = 0; if (nTitle == m_curTitle) + firstRow = m_iconRowScroll; + else if (nTitle < m_curTitle && rows > VISIBLE_ICON_ROWS) + firstRow = rows - VISIBLE_ICON_ROWS; + + if (!bRender) { - // we keep track of the scroll position for the current title - nIconRowScroll = m_iconRowScroll; - } - else if (nTitle < m_curTitle) - { - // this title is above the current one; show it scrolled to its bottom - nIconRowScroll = nRowCount - VISIBLE_ICON_ROWS; - if (nIconRowScroll < 0) - nIconRowScroll = 0; + if (nTitle == m_curTitle) + return y - m_scroll; } - - if (bRender) + else { - float nSelectedAmount = 0.0f; - float t = (float)(TheseusGetNow() - m_timeScroll) / 0.25f; + float t = (float)(TheseusGetNow() - m_scrollStart) / 0.25f; if (t > 1.0f) t = 1.0f; + float selected = 0.0f; if (nTitle == m_curTitle) - { - if (m_timeScroll != 0.0f) - nSelectedAmount = t; - else - nSelectedAmount = 1.0f; - } - else if (nTitle == m_curTitleLast) - { - if (m_timeScroll != 0.0f) - nSelectedAmount = 1.0f - t; - } - - g_nEffectAlpha *= 0.5f + (0.5f * nSelectedAmount); - } - else if (nTitle == m_curTitle) - { - return y - m_scroll; + selected = (m_scrollStart != 0.0f) ? t : 1.0f; + else if (nTitle == m_prevTitle && m_scrollStart != 0.0f) + selected = 1.0f - t; + g_nEffectAlpha *= 0.5f + (0.5f * selected); } - // Title pod (the orb-and-panel widget for this title row). - if (bRender && y - 0.25f < 0.5f) - RenderTitlePodAt(nTitle, y, &mat); + bool onScreen = bRender && y - 0.25f < 0.5f; + + if (onScreen) + RenderTitlePodAt(nTitle, y, &frame); - // Draw header + // Header and name. + if (onScreen) { - if (bRender && y - 0.25f < 0.5f) - { - D3DXMatrixTranslation(&mat2, -0.3292f, y, -0.0271f); - D3DXMatrixMultiply(&mat2, &mat, &mat2); - - if (nTitle >= 0 && nTitle == m_curTitle) // is a game title or soundtrack - RenderNodeAt(m_hiliteHeader, &mat2); - else if (nTitle >= 0) - RenderNodeAt(m_header, &mat2); - else if (nTitle < 0 && nTitle == m_curTitle) // the title is the memory unit - RenderNodeAt(m_MUhiliteHeader, &mat2); - else if (nTitle < 0) - RenderNodeAt(m_MUheader, &mat2); - - // Draw text - if (m_renderIcons) // are we on the proper screen? - { - TheseusSetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1); - TheseusSetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR); - TheseusSetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE); - TheseusSetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE); - TheseusSetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_TFACTOR); - TheseusSetRenderState(D3DRS_TEXTUREFACTOR, (nTitle == m_curTitle) ? D3DCOLOR_RGBA(170, 170, 170, 255) : D3DCOLOR_RGBA(140, 201, 25, 255)); - - D3DXMATRIX mat3; - // D3DXMatrixScaling(&mat3, 0.05942f, 0.05942f, 0.05942f); - D3DXMatrixScaling(&mat3, 0.06442f, 0.06442f, 0.06442f); - D3DXMatrixTranslation(&mat2, -0.3292f - 0.05942f, y + 0.05942f, -0.0271f + (0.6f * 0.05942f)); - D3DXMatrixMultiply(&mat2, &mat3, &mat2); - - TCHAR szBuf[256]; - GetTitleName2(nTitle, szBuf); - RenderNodeAt(GetTextNode(szBuf, -11.2f), &mat2); - } + D3DXMatrixTranslation(&at, -0.3292f, y, -0.0271f); + D3DXMatrixMultiply(&at, &frame, &at); + bool selectedRow = nTitle == m_curTitle; + if (nTitle >= 0) + RenderNodeAt(selectedRow ? m_hiliteHeader : m_header, &at); + else + RenderNodeAt(selectedRow ? m_MUhiliteHeader : m_MUheader, &at); - if (nIconRowScroll > 0) - { - // Draw the up arrow - D3DXMatrixTranslation(&mat2, -0.17f, (y - 0.07f), 0.0f); - D3DXMatrixMultiply(&mat2, &mat, &mat2); - scrollMat = mat2; - // RenderNodeAt(m_moreUp, &mat2); - } + if (m_renderIcons) + { + TheseusSetTextureStageState(0, D3DTSS_COLOROP, D3DTOP_SELECTARG1); + TheseusSetTextureStageState(0, D3DTSS_COLORARG1, D3DTA_TFACTOR); + TheseusSetTextureStageState(0, D3DTSS_ALPHAOP, D3DTOP_MODULATE); + TheseusSetTextureStageState(0, D3DTSS_ALPHAARG1, D3DTA_DIFFUSE); + TheseusSetTextureStageState(0, D3DTSS_ALPHAARG2, D3DTA_TFACTOR); + TheseusSetRenderState(D3DRS_TEXTUREFACTOR, selectedRow ? D3DCOLOR_RGBA(170, 170, 170, 255) : D3DCOLOR_RGBA(140, 201, 25, 255)); + + D3DXMATRIX textScale; + D3DXMatrixScaling(&textScale, 0.06442f, 0.06442f, 0.06442f); + D3DXMatrixTranslation(&at, -0.3292f - 0.05942f, y + 0.05942f, -0.0271f + (0.6f * 0.05942f)); + D3DXMatrixMultiply(&at, &textScale, &at); + + TCHAR name[256]; + GetTitleName2(nTitle, name); + RenderNodeAt(GetTextNode(name, -11.2f), &at); } - y -= 0.0092f; - } - - // Draw first icon row - { - if (bRender && y - 0.25f < 0.5f) + if (firstRow > 0) { - D3DXMatrixTranslation(&mat2, -0.3292f, y, 0.01144f); - D3DXMatrixMultiply(&mat2, &mat, &mat2); - if (nTitle >= 0) // is a game title or soundtrack - RenderNodeAt(m_firstRow, &mat2); - else // the title is a memory unit - RenderNodeAt(m_firstMURow, &mat2); - - if (nIconRowScroll > 0) - { - // Draw the up arrow - RenderNodeAt(m_moreUp, &scrollMat); - } - - RenderIconRow(&mat, y, nTitle, nIconRowScroll * m_iconsPerRow, nSavedGames); + D3DXMatrixTranslation(&at, -0.17f, (y - 0.07f), 0.0f); + D3DXMatrixMultiply(&upArrow, &frame, &at); } + } + y -= 0.0092f; - y -= 0.2455f; + // First icon row (the device row has its own). + if (bRender && y - 0.25f < 0.5f) + { + D3DXMatrixTranslation(&at, -0.3292f, y, 0.01144f); + D3DXMatrixMultiply(&at, &frame, &at); + RenderNodeAt(nTitle >= 0 ? m_firstRow : m_firstMURow, &at); + if (firstRow > 0) + RenderNodeAt(m_moreUp, &upArrow); + RenderIconRow(&frame, y, nTitle, firstRow * m_iconsPerRow, items); } + y -= 0.2455f; - if (nSavedGames > m_iconsPerRow) + if (items > m_iconsPerRow) { if (bRender && y - 0.25f < 0.5f) { - D3DXMatrixTranslation(&mat2, -0.3301f, y, 0.01144f); - D3DXMatrixMultiply(&mat2, &mat, &mat2); - RenderNodeAt(m_secondRow, &mat2); - RenderIconRow(&mat, y, nTitle, (nIconRowScroll + 1) * m_iconsPerRow, nSavedGames); + D3DXMatrixTranslation(&at, -0.3301f, y, 0.01144f); + D3DXMatrixMultiply(&at, &frame, &at); + RenderNodeAt(m_secondRow, &at); + RenderIconRow(&frame, y, nTitle, (firstRow + 1) * m_iconsPerRow, items); } - y -= 0.24499f; - if (nSavedGames > m_iconsPerRow * 2) + if (items > m_iconsPerRow * 2) { - for (int nRow = 2; nRow < (nRowCount - nIconRowScroll) && nRow < VISIBLE_ICON_ROWS && (!bRender || y > yLimit); nRow += 1) + for (int row = 2; row < rows - firstRow && row < VISIBLE_ICON_ROWS && (!bRender || y > bottom); row++) { if (bRender && y - 0.25f < 0.5f) { - D3DXMatrixTranslation(&mat2, -0.3412f, y, 0.01144f); - D3DXMatrixMultiply(&mat2, &mat, &mat2); - RenderNodeAt(m_otherRow, &mat2); - if (nRow == VISIBLE_ICON_ROWS - 1 && (nIconRowScroll + nRow) < nRowCount - 1) + D3DXMatrixTranslation(&at, -0.3412f, y, 0.01144f); + D3DXMatrixMultiply(&at, &frame, &at); + RenderNodeAt(m_otherRow, &at); + if (row == VISIBLE_ICON_ROWS - 1 && firstRow + row < rows - 1) { - D3DXMatrixTranslation(&mat2, -0.17f, (y - 0.015f), 0.0f); - D3DXMatrixMultiply(&mat2, &mat, &mat2); - RenderNodeAt(m_moreDown, &mat2); + D3DXMatrixTranslation(&at, -0.17f, (y - 0.015f), 0.0f); + D3DXMatrixMultiply(&at, &frame, &at); + RenderNodeAt(m_moreDown, &at); } - RenderIconRow(&mat, y, nTitle, (nIconRowScroll + nRow) * m_iconsPerRow, nSavedGames); + RenderIconRow(&frame, y, nTitle, (firstRow + row) * m_iconsPerRow, items); } - y -= 0.24499f; } } } - // Prepare for next title area y -= 0.09f; - g_nEffectAlpha = nEffectAlphaSave; + g_nEffectAlpha = alphaBefore; } return 0.0f; } -void CSavedGameGrid::SelectTitle(int nTitle, bool bInstantScroll /*=false*/) -{ - m_curTitleLast = m_curTitle; - m_curTitle = nTitle; +// ============================================================================= +// Selection +// ============================================================================= +// CSavedGameGrid::SelectTitle(n, instant) +// Reconstructed from 5960 retail XBE @ 0x49410. Remembers the last title +// and takes the new one (clamped to the list) unless the list is stale. +// Scrolls so it's at the top, at once or eased from now. Inside the title +// the item follows the preferred column: none keeps the title itself +// selected; moving down lands on that column in the first row, moving up +// on that column in the last row, clamped to the last item, with the icon +// rows scrolled to show it. 5960 sizes the grid from all of its items; +// Theseus from the saves alone. +void CSavedGameGrid::SelectTitle(int nTitle, bool bInstantScroll) +{ + m_prevTitle = m_curTitle; + m_curTitle = nTitle; if (g_titles[m_curDevUnit].IsDirty()) - { return; - } - /* - if (m_curTitle < 0) - { - m_curTitle = -1; - m_curGridItem = -1; - m_nPrefColumn = -1; - m_scrollTo = 0.0f; - m_scroll = 0.0f; - m_timeScroll = 0.0f; - m_iconRowScroll = 0; - m_detachIcon = false; - m_totalBlocks = -1; - m_freeBlocks = -1; - } - else - */ - { - int nTitleCount = GetTitleCount(); - if (m_curTitle >= nTitleCount) - m_curTitle = nTitleCount - 1; + int titleCount = GetTitleCount(); + if (m_curTitle >= titleCount) + m_curTitle = titleCount - 1; - int nSavedGames = GetSavedGameCount(m_curTitle); - int nRowCount = (nSavedGames + m_iconsPerRow - 1) / m_iconsPerRow; + int items = GetSavedGameCount(m_curTitle); + int rows = (items + m_iconsPerRow - 1) / m_iconsPerRow; + float target = -RenderLoop(false); + if (target != m_scrollTarget) + { + m_scrollTarget = target; + if (bInstantScroll) { - float y = -RenderLoop(false); - - if (y != m_scrollTo) - { - if (bInstantScroll) - { - m_scrollTo = m_scroll = y; - m_timeScroll = 0.001f; - } - else - { - m_scrollTo = y; - m_timeScroll = TheseusGetNow(); - } - } - } - - // Select the right save icon based on the preferred column and - // the direction the selection moved.. - if ((m_nPrefColumn > -1) && (m_curGridItem != -1)) - { - m_nPrefColumn = m_curGridItem % m_iconsPerRow; + m_scroll = target; + m_scrollStart = 0.001f; } - else if (m_nPrefColumn != -1) + else { - m_nPrefColumn = 0; + m_scrollStart = TheseusGetNow(); } + } - if (m_nPrefColumn == -1) - { - m_curGridItem = -1; - m_iconRowScroll = 0; - } - else - { - if (m_curTitle > m_curTitleLast) - { - m_curGridItem = m_nPrefColumn; + if (m_nPrefColumn != -1) + m_nPrefColumn = (m_curGridItem != -1) ? m_curGridItem % m_iconsPerRow : 0; - if (m_curGridItem > nSavedGames - 1) - m_curGridItem = nSavedGames - 1; + if (m_nPrefColumn == -1) + { + m_curGridItem = -1; + m_iconRowScroll = 0; + return; + } - m_iconRowScroll = 0; - } - else - { - if (nSavedGames == 0) - { - m_curGridItem = -1; - } - else - { - m_curGridItem = m_nPrefColumn + (nRowCount - 1) * m_iconsPerRow; - ASSERT(m_curGridItem >= 0); - if (m_curGridItem > nSavedGames - 1) - m_curGridItem = nSavedGames - 1; - } + if (m_curTitle > m_prevTitle) + { + m_curGridItem = m_nPrefColumn; + if (m_curGridItem > items - 1) + m_curGridItem = items - 1; + m_iconRowScroll = 0; + return; + } - m_iconRowScroll = nRowCount - VISIBLE_ICON_ROWS; - if (m_iconRowScroll < 0) - m_iconRowScroll = 0; - } - } + if (items == 0) + { + m_curGridItem = -1; + } + else + { + m_curGridItem = m_nPrefColumn + (rows - 1) * m_iconsPerRow; + if (m_curGridItem > items - 1) + m_curGridItem = items - 1; } + m_iconRowScroll = rows > VISIBLE_ICON_ROWS ? rows - VISIBLE_ICON_ROWS : 0; } -void CSavedGameGrid::NotifySelectionChanged() -{ - CallFunction(this, _T("OnSelChange")); - g_pulseStartTime = TheseusGetNow(); -} +// Saves plus DLC under a title (Theseus counts DLC as grid items). +#define GRID_ITEMS(n) (GetSavedGameCount(n) + GetDLContentCount(n)) +// CSavedGameGrid::selectUp [script fn 'selectUp', FND 0x00187698, sig 1] +// Reconstructed from 5960 retail XBE @ 0x49590. Up a row inside the grid +// (keeping the column, scrolling the rows if needed); from the top row or +// the title itself, the title above. Either way OnSelChange fires and the +// column is remembered. void CSavedGameGrid::selectUp() { - // First try moving up within the current title's icon grid. - if (m_curGridItem != -1) + if (m_curGridItem != -1 && m_curGridItem / m_iconsPerRow > 0) { - const int curRow = m_curGridItem / m_iconsPerRow; - if (curRow > 0) - { - const int newRow = curRow - 1; - m_curGridItem = newRow * m_iconsPerRow + m_nPrefColumn; - if (newRow < m_iconRowScroll) - m_iconRowScroll = newRow; - m_nPrefColumn = m_curGridItem % m_iconsPerRow; - NotifySelectionChanged(); - return; - } + int row = m_curGridItem / m_iconsPerRow - 1; + m_curGridItem = row * m_iconsPerRow + m_nPrefColumn; + if (row < m_iconRowScroll) + m_iconRowScroll = row; + m_nPrefColumn = m_curGridItem % m_iconsPerRow; + NotifySelectionChanged(); + return; } - // At the top of the grid (or no grid item selected): walk up to the - // previous title row. The MU selector view starts at row 0 instead - // of -1 because there's no "device" pseudo-row above it. - const int topRow = IsMUSelector() ? 0 : -1; - if (m_curTitle > topRow) + if (m_curTitle > (IsMUSelector() ? 0 : -1)) { SelectTitle(m_curTitle - 1); NotifySelectionChanged(); @@ -1633,31 +1403,29 @@ void CSavedGameGrid::selectUp() m_nPrefColumn = m_curGridItem % m_iconsPerRow; } +// CSavedGameGrid::selectDown [script fn 'selectDown', FND 0x001876b0, sig 1] +// Reconstructed from 5960 retail XBE @ 0x49650. Down a row inside the grid +// (clamped to the last item, scrolling the rows), else the next title. void CSavedGameGrid::selectDown() { - // First try moving down within the current title's icon grid. if (m_curGridItem != -1) { - const int totalItems = GetSavedGameCount(m_curTitle) + GetDLContentCount(m_curTitle); - const int curRow = m_curGridItem / m_iconsPerRow; - const int rowCount = (totalItems + m_iconsPerRow - 1) / m_iconsPerRow; - - if (curRow < rowCount - 1) + int items = GRID_ITEMS(m_curTitle); + int row = m_curGridItem / m_iconsPerRow; + if (row < (items + m_iconsPerRow - 1) / m_iconsPerRow - 1) { - const int newRow = curRow + 1; + row++; m_curGridItem += m_iconsPerRow; - // Bottom row may be partially filled; clamp to last valid item. - if (m_curGridItem > totalItems - 1) - m_curGridItem = totalItems - 1; - if (newRow >= m_iconRowScroll + VISIBLE_ICON_ROWS - 1) - m_iconRowScroll = newRow - (VISIBLE_ICON_ROWS - 1); + if (m_curGridItem > items - 1) + m_curGridItem = items - 1; + if (row >= m_iconRowScroll + VISIBLE_ICON_ROWS - 1) + m_iconRowScroll = row - (VISIBLE_ICON_ROWS - 1); m_nPrefColumn = m_curGridItem % m_iconsPerRow; NotifySelectionChanged(); return; } } - // At the bottom of the grid: walk down to the next title row. if (m_curTitle < GetTitleCount() - 1) { SelectTitle(m_curTitle + 1); @@ -1666,102 +1434,77 @@ void CSavedGameGrid::selectDown() m_nPrefColumn = m_curGridItem % m_iconsPerRow; } +// CSavedGameGrid::selectLeft [script fn 'selectLeft', FND 0x001876c8, sig 1] +// Reconstructed from 5960 retail XBE @ 0x49740: from the first column back +// out to the title, else one item left. OnSelChange only on a change. void CSavedGameGrid::selectLeft() { - const int oldTitle = m_curTitle; - const int oldGridItem = m_curGridItem; - + int before = m_curGridItem; if (m_curGridItem >= 0) { if (m_nPrefColumn == 0) { - // Leftmost column: jump out of the grid back to the title orb. m_nPrefColumn = -1; m_curGridItem = -1; m_iconRowScroll = 0; } else { - m_curGridItem -= 1; + m_curGridItem--; m_nPrefColumn = m_curGridItem % m_iconsPerRow; } } - - if (m_curTitle != oldTitle || m_curGridItem != oldGridItem) + if (m_curGridItem != before) NotifySelectionChanged(); } +// CSavedGameGrid::selectRight [script fn 'selectRight', FND 0x001876e0, sig 1] +// Reconstructed from 5960 retail XBE @ 0x497b0: one item right while there +// is one and the column is under 3, scrolling the rows to keep it shown. void CSavedGameGrid::selectRight() { - const int oldTitle = m_curTitle; - const int oldGridItem = m_curGridItem; - - const int totalItems = GetSavedGameCount(m_curTitle) + GetDLContentCount(m_curTitle); - if (m_curGridItem < totalItems - 1 && m_nPrefColumn < VISIBLE_ICON_ROWS) + int before = m_curGridItem; + if (m_curGridItem < GRID_ITEMS(m_curTitle) - 1 && m_nPrefColumn < VISIBLE_ICON_ROWS) { - m_curGridItem += 1; + m_curGridItem++; m_nPrefColumn = m_curGridItem % m_iconsPerRow; - - // Scroll the icon view if we just moved off the bottom-visible row. if (m_curGridItem >= (m_iconRowScroll + VISIBLE_ICON_ROWS) * m_iconsPerRow) m_iconRowScroll = m_curGridItem / m_iconsPerRow - (VISIBLE_ICON_ROWS - 1); } - - if (m_curTitle != oldTitle || m_curGridItem != oldGridItem) + if (m_curGridItem != before) NotifySelectionChanged(); } +// CSavedGameGrid::setSelImage [script fn 'setSelImage'] +// Reconstructed from 5960 retail XBE @ 0x49840: points the selection image +// at the memory unit art, the selected save's image, the title's +// TitleImage.xbx (or the logo), or the soundtrack art. Theseus adds DLC. void CSavedGameGrid::setSelImage() { g_szSelTitleImage = NULL; - if (m_curTitle == -1) // Memory Unit + if (m_curTitle == -1) { _tcscpy(szSelectionBuf, _T("memoryUnit128.tga")); } - else if (m_curTitle >= 0 && (m_soundtrackTitle < 0 || m_curTitle < m_soundtrackTitle)) // Game title + else if (m_curTitle < 0 || !IS_GAME_ROW(m_curTitle)) { - if (m_curGridItem != -1) - { - int nSavedGames = GetSavedGameCount(m_curTitle); - if (m_curGridItem < nSavedGames) - { - g_titles[m_curDevUnit].GetSavedGameImageName(m_curTitle, m_curGridItem, szSelectionBuf); - } - else - { - // DLC item: locate the Nth DLC folder and load its 128px image. - char titleIDChar[9]; - char dlcFolder[17]; - if (ResolveDLCFolder(m_curTitle, m_curGridItem - nSavedGames, - titleIDChar, sizeof(titleIDChar), - dlcFolder, sizeof(dlcFolder))) - { - char dlcImagePath[MAX_PATH]; - _snprintf(dlcImagePath, MAX_PATH, "E:\\TDATA\\%s\\$c\\%s\\ContentImage.xbx", - titleIDChar, dlcFolder); - MultiByteToWideChar(CP_ACP, 0, dlcImagePath, -1, szSelectionBuf, MAX_PATH); - } - else - { - _tcscpy(szSelectionBuf, _T("dlcitem128.xbx")); - } - } - } - else // Title image - { - MakePath(szSelectionBuf, g_titles[m_curDevUnit].GetUData(), GetTitleID2(m_curTitle)); - MakePath(szSelectionBuf, szSelectionBuf, szTitleImageXBX); - - if (!DoesFileExist(szSelectionBuf)) - { - _tcscpy(szSelectionBuf, _T("xboxlogo128.xbx")); - } - } + _tcscpy(szSelectionBuf, _T("soundtracksave3.tga")); } - else // soundtrack + else if (m_curGridItem == -1) { - _tcscpy(szSelectionBuf, _T("soundtracksave3.tga")); + MakePath(szSelectionBuf, g_titles[m_curDevUnit].GetUData(), GetTitleID2(m_curTitle)); + MakePath(szSelectionBuf, szSelectionBuf, szTitleImageXBX); + if (!DoesFileExist(szSelectionBuf)) + _tcscpy(szSelectionBuf, _T("xboxlogo128.xbx")); + } + else + { + int saves = GetSavedGameCount(m_curTitle); + if (m_curGridItem < saves) + g_titles[m_curDevUnit].GetSavedGameImageName(m_curTitle, m_curGridItem, szSelectionBuf); + else if (!GetDLCImagePath(m_curTitle, m_curGridItem - saves, szSelectionBuf)) + _tcscpy(szSelectionBuf, _T("dlcitem128.xbx")); } g_szSelTitleImage = szSelectionBuf; @@ -1836,214 +1579,204 @@ bool ContentMetaParse(const TCHAR *wszMetaPath, TCHAR *outName, int outLen) } +// ============================================================================= +// What the panel shows +// ============================================================================= + +// CSavedGameGrid::FormatGridItemName [script fn 'FormatGridItemName'] +// Reconstructed from 5960 retail XBE @ 0x49940 / 0x49aa0. Nothing without +// an item; a soundtrack's name; otherwise the Name in the save's +// SaveMeta.xbx for the current language, or "Broken Save". Theseus names +// DLC from its ContentMeta.xbx. CStrObject *CSavedGameGrid::FormatGridItemName() { if (m_curGridItem < 0) - return new CStrObject; // empty string - - if (m_soundtrackTitle >= 0 && m_curTitle == m_soundtrackTitle) + return new CStrObject; + if (IsSoundtrackSelected()) return new CStrObject(GetSoundtrackName(m_curGridItem)); - // Calculate total saved games - int savedGameCount = GetSavedGameCount(m_curTitle); - int dlcCount = GetDLContentCount(m_curTitle); - - // Set DLC flag based on grid index - m_isCurGridItemDLC = (m_curGridItem >= savedGameCount && m_curGridItem < savedGameCount + dlcCount); + int saves = GetSavedGameCount(m_curTitle); + int dlc = GetDLContentCount(m_curTitle); + m_isCurGridItemDLC = m_curGridItem >= saves && m_curGridItem < saves + dlc; - // If it's a DLC grid item, locate the Nth DLC folder and parse its - // ContentMeta.xbx for a localized name. Three fallbacks: parse failure - // returns "Unnamed DLC", missing folder returns "Downloadable Content N". if (m_isCurGridItemDLC) { - int dlcIndex = m_curGridItem - savedGameCount; - char titleIDChar[9]; - char dlcFolder[17]; - - if (ResolveDLCFolder(m_curTitle, dlcIndex, - titleIDChar, sizeof(titleIDChar), - dlcFolder, sizeof(dlcFolder))) + int dlcIndex = m_curGridItem - saves; + char titleID[9]; + char folder[17]; + if (!ResolveDLCFolder(m_curTitle, dlcIndex, titleID, sizeof(titleID), folder, sizeof(folder))) { - char metaPath[MAX_PATH]; - _snprintf(metaPath, MAX_PATH, "E:\\TDATA\\%s\\$c\\%s\\ContentMeta.xbx", - titleIDChar, dlcFolder); - - TCHAR wszMetaPath[MAX_PATH]; - MultiByteToWideChar(CP_ACP, 0, metaPath, -1, wszMetaPath, MAX_PATH); - - TCHAR szSaveName[64]; - if (ContentMetaParse(wszMetaPath, szSaveName, countof(szSaveName))) - return new CStrObject(szSaveName); - - TCHAR szTranslate[MAX_TRANSLATE_LEN] = _T(""); - return new CStrObject(Translate(_T("Unnamed DLC"), szTranslate)); + TCHAR numbered[64]; + _stprintf(numbered, _T("Downloadable Content %d"), dlcIndex + 1); + return new CStrObject(numbered); } - // Fallback: numbered placeholder when no DLC folder exists for this index - TCHAR szBuf[64]; - _stprintf(szBuf, _T("Downloadable Content %d"), dlcIndex + 1); - return new CStrObject(szBuf); - } + char metaPath[MAX_PATH]; + _snprintf(metaPath, MAX_PATH, "E:\\TDATA\\%s\\$c\\%s\\ContentMeta.xbx", titleID, folder); + TCHAR wideMeta[MAX_PATH]; + MultiByteToWideChar(CP_ACP, 0, metaPath, -1, wideMeta, MAX_PATH); - // Normal saved game - TCHAR szSavedGamePath[MAX_PATH]; - if (!GetSavedGamePath(szSavedGamePath, m_curTitle, m_curGridItem)) - { - //OutputDebugStringA("[SavedGameGrid] FormatGridItemName: Failed to get save path\n"); - return new CStrObject; // empty string + TCHAR name[64]; + if (ContentMetaParse(wideMeta, name, countof(name))) + return new CStrObject(name); + + TCHAR translated[MAX_TRANSLATE_LEN] = _T(""); + return new CStrObject(Translate(_T("Unnamed DLC"), translated)); } - MakePath(szSavedGamePath, szSavedGamePath, szSaveDataXBX); + TCHAR meta[MAX_PATH]; + if (!GetSavedGamePath(meta, m_curTitle, m_curGridItem)) + return new CStrObject; + MakePath(meta, meta, szSaveDataXBX); - TCHAR szSaveName[64]; - TCHAR szLangCode[MAX_LANGUAGE_CODE_LEN]; - TCHAR szTranslate[MAX_TRANSLATE_LEN]; + TCHAR name[64]; + TCHAR lang[MAX_LANGUAGE_CODE_LEN]; + TCHAR translated[MAX_TRANSLATE_LEN]; CSettingsFile settings; - if (!settings.Open(szSavedGamePath) || !settings.GetValue(GetLanguageCode(szLangCode), _T("Name"), szSaveName, countof(szSaveName))) - { - //OutputDebugStringA("[SavedGameGrid] FormatGridItemName: Broken or missing name field\n"); - return new CStrObject(Translate(_T("Broken Save"), szTranslate)); - } - - return new CStrObject(szSaveName); + if (!settings.Open(meta) || !settings.GetValue(GetLanguageCode(lang), _T("Name"), name, countof(name))) + return new CStrObject(Translate(_T("Broken Save"), translated)); + return new CStrObject(name); } +// CSavedGameGrid::FormatGridItemTime [script fn 'FormatGridItemTime'] +// Reconstructed from 5960 retail XBE @ 0x49ca0: the save folder's last +// write time in local time, formatted for the current locale. Empty for +// soundtracks, no item, or a folder that won't open. CStrObject *CSavedGameGrid::FormatGridItemTime() { - if (m_soundtrackTitle >= 0 && m_curTitle == m_soundtrackTitle) - return new CStrObject; // empty string - - TCHAR szPath[MAX_PATH]; - if (m_curGridItem < 0 || !GetSavedGamePath(szPath, m_curTitle, m_curGridItem)) - return new CStrObject; // empty string - - HANDLE hFile = TheseusCreateFile(szPath, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); - if (hFile == INVALID_HANDLE_VALUE) - return new CStrObject; // empty string - - FILETIME ft; - VERIFY(GetFileTime(hFile, NULL, NULL, &ft)); - CloseHandle(hFile); + if (IsSoundtrackSelected()) + return new CStrObject; - FILETIME lft; - VERIFY(FileTimeToLocalFileTime(&ft, &lft)); + TCHAR path[MAX_PATH]; + if (m_curGridItem < 0 || !GetSavedGamePath(path, m_curTitle, m_curGridItem)) + return new CStrObject; - SYSTEMTIME st; - VERIFY(FileTimeToSystemTime(&lft, &st)); + HANDLE folder = TheseusCreateFile(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, NULL); + if (folder == INVALID_HANDLE_VALUE) + return new CStrObject; - TCHAR szBuf[32]; - FormatTime(szBuf, countof(szBuf), &st); + FILETIME written, local; + GetFileTime(folder, NULL, NULL, &written); + CloseHandle(folder); + FileTimeToLocalFileTime(&written, &local); - return new CStrObject(szBuf); + SYSTEMTIME when; + FileTimeToSystemTime(&local, &when); + TCHAR text[32]; + FormatTime(text, countof(text), &when); + return new CStrObject(text); } +// CSavedGameGrid::GetSavedGameCount [script fn 'GetSavedGameCount'] +// Reconstructed from 5960 retail XBE @ 0x49e70: 0 for the device row or a +// stale list, the soundtrack count for the soundtrack row, else the +// title's saves. int CSavedGameGrid::GetSavedGameCount(int nTitle) { - ASSERT(IsValidDevUnit()); - - if (nTitle < 0) - return 0; - - if (g_titles[m_curDevUnit].IsDirty()) - { + if (nTitle < 0 || g_titles[m_curDevUnit].IsDirty()) return 0; - } - - if (m_soundtrackTitle < 0 || nTitle < m_soundtrackTitle) + if (IS_GAME_ROW(nTitle)) return g_titles[m_curDevUnit].GetSavedGameCount(nTitle); - - return m_soundtrackCount; + return m_soundtracks; } +// CSavedGameGrid::FormatGridItemSize [script fn 'FormatGridItemSize'] +// Reconstructed from 5960 retail XBE @ 0x49f70: the soundtrack's size, or +// the cached size of the selected save (empty with none). Kept in +// gameBlocks for the scripts. CStrObject *CSavedGameGrid::FormatGridItemSize() { - int nBlocks; - - if (m_soundtrackTitle >= 0 && m_curTitle == m_soundtrackTitle) + int blocks; + if (IsSoundtrackSelected()) { - nBlocks = GetSoundtrackSize(m_curGridItem); + blocks = GetSoundtrackSize(m_curGridItem); } else { - TCHAR szSavedGameDir[MAX_PATH]; - - if (m_curGridItem < 0 || !GetSavedGamePath(szSavedGameDir, m_curTitle, m_curGridItem)) - return new CStrObject; // empty string - - nBlocks = m_cacheSavedGameSize; + TCHAR path[MAX_PATH]; + if (m_curGridItem < 0 || !GetSavedGamePath(path, m_curTitle, m_curGridItem)) + return new CStrObject; + blocks = m_itemBlocks; } - m_gameBlocks = nBlocks; - - TCHAR szBuf[16]; - FormatInteger(szBuf, nBlocks); - return new CStrObject(szBuf); + m_gameBlocks = blocks; + TCHAR text[16]; + FormatInteger(text, blocks); + return new CStrObject(text); } +// CSavedGameGrid::FormatTitleSize [script fn 'FormatTitleSize'] +// 5960 @ 0x4a3e0: the cached size of the selected title. CStrObject *CSavedGameGrid::FormatTitleSize() { - int nBlocks = m_cacheTitleSize; - - TCHAR szBuf[16]; - FormatInteger(szBuf, nBlocks); - return new CStrObject(szBuf); + TCHAR text[16]; + FormatInteger(text, m_titleBlocks); + return new CStrObject(text); } +// <udata>\<title>\<save> on the current device; false when unmounted. bool CSavedGameGrid::GetSavedGamePath(TCHAR *szBuf, int nTitle, int nSavedGame) { - if (!g_titles[m_curDevUnit].IsValid()) - { + CTitleArray& titles = g_titles[m_curDevUnit]; + if (!titles.IsValid()) return false; - } - - MakePath(szBuf, g_titles[m_curDevUnit].GetUData(), GetTitleID2(nTitle)); + MakePath(szBuf, titles.GetUData(), GetTitleID2(nTitle)); MakePath(szBuf, szBuf, GetSavedGameID2(nTitle, nSavedGame)); return true; } +// CSavedGameGrid::GetSavedGamePath [script fn 'GetSavedGamePath'] +// Reconstructed from 5960 retail XBE @ 0x4a700: the save as the game sees +// it, "<drive>:\<save>", U: on the hard drive. CStrObject *CSavedGameGrid::GetSavedGamePath(int nTitle, int nSavedGame) { - TCHAR szBuf[MAX_PATH]; - - szBuf[0] = IsHDD() ? 'U' : g_titles[m_curDevUnit].GetUData()[0]; - szBuf[1] = ':'; - szBuf[2] = '\\'; - _tcscpy(szBuf + 3, GetSavedGameID2(nTitle, nSavedGame)); - - return new CStrObject(szBuf); + TCHAR path[MAX_PATH]; + path[0] = IsHDD() ? 'U' : g_titles[m_curDevUnit].GetUData()[0]; + path[1] = ':'; + path[2] = '\\'; + _tcscpy(path + 3, GetSavedGameID2(nTitle, nSavedGame)); + return new CStrObject(path); } +// CSavedGameGrid::FormatFreeBlocks / FormatTotalBlocks / GetTotalBlocks +// 5960 @ 0x4a820 / 0x4a8d0 / 0x4a980: the device's free and usable blocks. CStrObject *CSavedGameGrid::FormatFreeBlocks() { - TCHAR szBuf[16]; - FormatBlocks(szBuf, m_freeBlocks); - return new CStrObject(szBuf); + TCHAR text[16]; + FormatBlocks(text, m_freeBlocks); + return new CStrObject(text); } CStrObject *CSavedGameGrid::FormatTotalBlocks() { - TCHAR szBuf[16]; - FormatBlocks(szBuf, m_totalBlocks); - return new CStrObject(szBuf); + TCHAR text[16]; + FormatBlocks(text, m_deviceBlocks); + return new CStrObject(text); } int CSavedGameGrid::GetTotalBlocks() { - return m_totalBlocks; + return m_deviceBlocks; } +// CSavedGameGrid::CanDetachIcon [script fn 'CanDetachIcon'] +// 5960 @ 0x4a990: once the list has stopped scrolling. Theseus also waits +// for the lifted pod's matrix. int CSavedGameGrid::CanDetachIcon() { - return m_timeScroll == 0.0f && m_focusPodMatrixValid; + return m_scrollStart == 0.0f && m_focusPodMatrixValid; } +// ============================================================================= +// Copy and delete +// ============================================================================= + +// Blocks a title file adds to a copy: none if the destination has it. int CSavedGameGrid::CountSupportFileIfMissing(int destDevUnit, const TCHAR *fileName) { TCHAR path[MAX_PATH]; - MakePath(path, g_titles[destDevUnit].GetUData(), GetTitleID2(m_curTitle)); MakePath(path, path, fileName); - if (DoesFileExist(path)) return 0; @@ -2052,164 +1785,156 @@ int CSavedGameGrid::CountSupportFileIfMissing(int destDevUnit, const TCHAR *file return GetFileBlocks(path, BLOCK_SIZE); } +// CSavedGameGrid::StartCopy(dest) [script fn 'StartCopy'] +// Reconstructed from 5960 retail XBE @ 0x4aac0 (StartSavedGameCopy). With +// no save selected it just reports OnCopyComplete. Otherwise the copy is +// sized (the save folder plus whichever title files the destination +// lacks), the status text reset, and the copier started on the one save. void CSavedGameGrid::StartCopy(int destDevUnit) { if (m_curGridItem == -1) { - TRACE(_T("Attempted to copy a title!\n")); CallFunction(this, _T("OnCopyComplete")); return; } - // Total block budget for the copy: the saved game directory itself, - // plus any per-title support XBX files the destination is missing. - TCHAR szBuf[MAX_PATH]; - VERIFY(GetSavedGamePath(szBuf, m_curTitle, m_curGridItem)); - int nBlocks = GetDirectoryBlocks(szBuf, BLOCK_SIZE, true, NULL); - - nBlocks += CountSupportFileIfMissing(destDevUnit, szTitleDataXBX); - nBlocks += CountSupportFileIfMissing(destDevUnit, szTitleImageXBX); - nBlocks += CountSupportFileIfMissing(destDevUnit, szSaveImageXBX); + TCHAR folder[MAX_PATH]; + GetSavedGamePath(folder, m_curTitle, m_curGridItem); + int blocks = GetDirectoryBlocks(folder, BLOCK_SIZE, true, NULL); + blocks += CountSupportFileIfMissing(destDevUnit, szTitleDataXBX); + blocks += CountSupportFileIfMissing(destDevUnit, szTitleImageXBX); + blocks += CountSupportFileIfMissing(destDevUnit, szSaveImageXBX); - m_copying = true; - m_timeCopyingStarted = TheseusGetNow(); + m_copyRunning = true; + m_copyStart = TheseusGetNow(); m_copyProgress = 0.0f; - m_lastUpdateTick = GetTickCount(); - m_periodStatus = 0; - m_statusText[0] = 0; - Translate(_T("Copying"), m_statusText); + m_dotsTick = GetTickCount(); + m_dots = 0; + m_copyingText[0] = 0; + Translate(_T("Copying"), m_copyingText); theGameCopier.SetSource(m_curDevUnit); theGameCopier.SetDestination(destDevUnit); - theGameCopier.AddGame(GetTitleID2(m_curTitle), - GetSavedGameID2(m_curTitle, m_curGridItem), - GetSavedGameTime(m_curTitle, m_curGridItem), - nBlocks); + theGameCopier.AddGame(GetTitleID2(m_curTitle), GetSavedGameID2(m_curTitle, m_curGridItem), + GetSavedGameTime(m_curTitle, m_curGridItem), blocks); theGameCopier.Start(); } +// 8 hex digits to a title id, 0xffffffff when it isn't one. 5960 @ 0x4b160. static DWORD ParseTitleID(const TCHAR *szID) { if (_tcslen(szID) != 8) - return 0xffffffff; // Invalid ID - - DWORD dw = 0; - const TCHAR *pch = szID; - while (*pch != 0) - { - DWORD dwDigit; - - if (*pch >= '0' && *pch <= '9') - dwDigit = *pch - '0'; - else if (*pch >= 'a' && *pch <= 'f') - dwDigit = 10 + *pch - 'a'; - else if (*pch >= 'A' && *pch <= 'F') - dwDigit = 10 + *pch - 'A'; + return 0xffffffff; + + DWORD id = 0; + for (const TCHAR *p = szID; *p != 0; p++) + { + int digit; + if (*p >= '0' && *p <= '9') + digit = *p - '0'; + else if (*p >= 'a' && *p <= 'f') + digit = *p - 'a' + 10; + else if (*p >= 'A' && *p <= 'F') + digit = *p - 'A' + 10; else - return 0xffffffff; // Invalid ID - - dw = (dw << 4) + dwDigit; - - pch += 1; + return 0xffffffff; + id = id * 16 + digit; } - - return dw; + return id; } +// From 5960's DeleteThread (0x4b1d0): a whole title goes from the list and +// from <udata>; the publisher's shared <pub>ffff folder in tdata too when +// it was that publisher's last title; on the hard drive also its tdata +// folder and cache partition. The soundtrack row moves up one. void CSavedGameGrid::DeleteGameTitleFiles() { + CTitleArray& titles = g_titles[m_curDevUnit]; TCHAR titleID[MAX_PATH]; - TCHAR publisherID[16]; + TCHAR publisher[16]; TCHAR path[MAX_PATH]; lstrcpyn(titleID, GetTitleID2(m_curTitle), countof(titleID)); - lstrcpyn(publisherID, titleID, countof(publisherID)); - - // Truncate to the 4-character publisher prefix. - publisherID[4] = 0; + lstrcpyn(publisher, titleID, countof(publisher)); + publisher[4] = 0; - g_titles[m_curDevUnit].RemoveTitle(m_curTitle); + titles.RemoveTitle(m_curTitle); - // If this was the last title from this publisher, sweep the shared - // publisher directory ("<pub>ffff" under TDATA). - if (!g_titles[m_curDevUnit].IsPublisherExists(publisherID)) + if (!titles.IsPublisherExists(publisher)) { - lstrcat(publisherID, _T("ffff")); - MakePath(path, g_titles[m_curDevUnit].GetTData(), publisherID); + lstrcat(publisher, _T("ffff")); + MakePath(path, titles.GetTData(), publisher); theGameCopier.DeleteDirectory(path); } - // Delete the title's UDATA tree (saved games + title metadata). - MakePath(path, g_titles[m_curDevUnit].GetUData(), titleID); + MakePath(path, titles.GetUData(), titleID); theGameCopier.DeleteDirectory(path); if (IsHDD()) { - // HDD only: also wipe TDATA and the title's cache partition. - MakePath(path, g_titles[m_curDevUnit].GetTData(), titleID); + MakePath(path, titles.GetTData(), titleID); theGameCopier.DeleteDirectory(path); XapiDeleteCachePartition(ParseTitleID(titleID)); } - if (m_soundtrackTitle >= 0) - m_soundtrackTitle -= 1; + if (m_soundtrackRow >= 0) + m_soundtrackRow--; } +// Deleting the title row: all soundtracks, or the game's files. The pod +// fades out from now and the list reselects in place. void CSavedGameGrid::DeleteCurrentTitle() { - if (m_curTitle == m_soundtrackTitle) + if (m_curTitle == m_soundtrackRow) { DeleteAllSoundtracks(); - m_soundtrackTitle = -1; - m_soundtrackCount = 0; + m_soundtrackRow = -1; + m_soundtracks = 0; } else { DeleteGameTitleFiles(); } - m_timeOfDelete = TheseusGetNow(); - m_deletedTitle = m_curTitle; - ASSERT(m_focusPodMatrixValid); - + m_fadeStart = TheseusGetNow(); + m_fadingTitle = m_curTitle; SelectTitle(m_curTitle, true); } +// Deleting one item: a soundtrack, or a save's folder and list entry. The +// selection stays in range and the rows scroll back if the last one went. void CSavedGameGrid::DeleteCurrentGridItem() { - if (m_curTitle == m_soundtrackTitle) + if (m_curTitle == m_soundtrackRow) { DeleteSoundtrack(m_curGridItem); - m_soundtrackCount -= 1; + m_soundtracks--; } else { - TCHAR path[MAX_PATH]; - VERIFY(GetSavedGamePath(path, m_curTitle, m_curGridItem)); - + TCHAR folder[MAX_PATH]; + GetSavedGamePath(folder, m_curTitle, m_curGridItem); theGameCopier.m_error = false; - theGameCopier.DeleteDirectory(path); - + theGameCopier.DeleteDirectory(folder); g_titles[m_curDevUnit].RemoveSavedGame(m_curTitle, m_curGridItem); } - // Fixup selection within the (now smaller) title. - int nSavedGameCount = GetSavedGameCount(m_curTitle); - if (m_curGridItem > nSavedGameCount - 1) - m_curGridItem = nSavedGameCount - 1; - m_nPrefColumn = (m_curGridItem % m_iconsPerRow); + int saves = GetSavedGameCount(m_curTitle); + if (m_curGridItem > saves - 1) + m_curGridItem = saves - 1; + m_nPrefColumn = m_curGridItem % m_iconsPerRow; - if (m_iconRowScroll && ((m_iconRowScroll + VISIBLE_ICON_ROWS - 1) * m_iconsPerRow >= nSavedGameCount)) - { + if (m_iconRowScroll != 0 && (m_iconRowScroll + VISIBLE_ICON_ROWS - 1) * m_iconsPerRow >= saves) m_iconRowScroll--; - } } +// CSavedGameGrid::DeleteThread +// Reconstructed from 5960 retail XBE @ 0x4b1d0: the last soundtrack takes +// the whole row with it; no item means the whole title; then the sizes are +// counted again. void WINAPI CSavedGameGrid::DeleteThread(CSavedGameGrid *p) { - ASSERT(p->m_curTitle >= 0); - - if (p->m_curTitle == p->m_soundtrackTitle && p->m_soundtrackCount == 1) + if (p->m_curTitle == p->m_soundtrackRow && p->m_soundtracks == 1) p->m_curGridItem = -1; if (p->m_curGridItem == -1) @@ -2217,93 +1942,88 @@ void WINAPI CSavedGameGrid::DeleteThread(CSavedGameGrid *p) else p->DeleteCurrentGridItem(); - p->m_cacheTitleSize = -1; - p->m_cacheSavedGameSize = -1; + p->m_titleBlocks = -1; + p->m_itemBlocks = -1; } +// CSavedGameGrid::StartDelete [script fn 'StartDelete'] +// Reconstructed from 5960 retail XBE @ 0x4b630: cancel a running size +// query, then delete on a thread; without one, delete here and report +// OnDeleteEnd and OnSelChange straight away. void CSavedGameGrid::StartDelete() { - ASSERT(m_deleteThread == NULL); - ASSERT(!m_deleting); + if (m_sizing) + SignalObjectAndWait(m_sizeCancel, m_sizeIdle, INFINITE, FALSE); - // Cancel previous pending query - if (m_savedGameQueryPending) + m_deleter = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)DeleteThread, this, 0, 0); + if (m_deleter != NULL) { - SignalObjectAndWait(m_cancelEvent, m_stopEvent, INFINITE, FALSE); + m_deleteRunning = true; + return; } - m_deleteThread = CreateThread(0, 0, (LPTHREAD_START_ROUTINE)DeleteThread, this, 0, 0); - - if (!m_deleteThread) - { - DeleteThread(this); - VERIFY(CallFunction(this, _T("OnDeleteEnd"))); - VERIFY(CallFunction(this, _T("OnSelChange"))); - g_pulseStartTime = TheseusGetNow(); - } - else - { - m_deleting = true; - } + DeleteThread(this); + CallFunction(this, _T("OnDeleteEnd")); + NotifySelectionChanged(); } +// CSavedGameGrid::CanCopy [script fn 'CanCopy', FND 0x001878f0, sig 2] +// Reconstructed from 5960 retail XBE @ 0x4b6b0. Not the device row, not +// soundtracks, and only a save whose SaveMeta.xbx has a Name; then yes +// unless its NoCopy is nonzero. Theseus also refuses saves of a broken +// title. int CSavedGameGrid::CanCopy() { if (m_curTitle < 0 || IsSoundtrackSelected()) - return false; // can't copy devices or soundtracks - - TCHAR szSavedGamePath[MAX_PATH]; - - if (m_curGridItem < 0 || !GetSavedGamePath(szSavedGamePath, m_curTitle, m_curGridItem)) - return false; // can't copy saves when one isn't selected + return false; - MakePath(szSavedGamePath, szSavedGamePath, szSaveDataXBX); + TCHAR meta[MAX_PATH]; + if (m_curGridItem < 0 || !GetSavedGamePath(meta, m_curTitle, m_curGridItem)) + return false; + MakePath(meta, meta, szSaveDataXBX); CSettingsFile settings; - if (!settings.Open(szSavedGamePath)) - return false; // can't copy broken saves - - TCHAR szSaveName[64]; - TCHAR szLangCode[MAX_LANGUAGE_CODE_LEN]; - if (!settings.GetValue(GetLanguageCode(szLangCode), _T("Name"), szSaveName, countof(szSaveName))) - return false; // can't copy broken saved game + if (!settings.Open(meta)) + return false; + TCHAR lang[MAX_LANGUAGE_CODE_LEN]; + TCHAR value[64]; + if (!settings.GetValue(GetLanguageCode(lang), _T("Name"), value, countof(value))) + return false; if (g_titles[m_curDevUnit].IsBroken(m_curTitle)) - return false; // can't copy a saved game in a broken title - - TCHAR szNoCopy[64]; - if (!settings.GetValue(GetLanguageCode(szLangCode), _T("NoCopy"), szNoCopy, countof(szNoCopy))) - return true; // can copy if it doesn't say otherwise - - return _ttoi(szNoCopy) == 0; + return false; + if (!settings.GetValue(GetLanguageCode(lang), _T("NoCopy"), value, countof(value))) + return true; + return _ttoi(value) == 0; } +// CSavedGameGrid::IsSoundtrackSelected [script fn 'IsSoundtrackSelected'] +// 5960 @ 0x4b870. int CSavedGameGrid::IsSoundtrackSelected() { - return (m_soundtrackTitle >= 0 && m_curTitle == m_soundtrackTitle); + return m_soundtrackRow >= 0 && m_curTitle == m_soundtrackRow; } +// CSavedGameGrid::IsDevUnitReady [script fn 'IsDevUnitReady'] +// 5960 @ 0x4bab0: the device's list isn't being rebuilt. int CSavedGameGrid::IsDevUnitReady(int nUnit) { return !g_titles[nUnit].IsDirty(); } +// CSavedGameGrid::DoesSavedGameExists [script fn 'DoesSavedGameExists'] +// 5960 @ 0x4bc60: whether the selected save is already on the destination. int CSavedGameGrid::DoesSavedGameExists(int destDevUnit) { if (m_curGridItem < 0) - { return false; - } - - const TCHAR *szRoot = g_titles[destDevUnit].GetUData(); - ASSERT(szRoot[0] != 0); - - TCHAR szBuf[MAX_PATH]; - MakePath(szBuf, g_titles[destDevUnit].GetUData(), GetTitleID2(m_curTitle)); - MakePath(szBuf, szBuf, GetSavedGameID2(m_curTitle, m_curGridItem)); - return DoesFileExist(szBuf); + TCHAR path[MAX_PATH]; + MakePath(path, g_titles[destDevUnit].GetUData(), GetTitleID2(m_curTitle)); + MakePath(path, path, GetSavedGameID2(m_curTitle, m_curGridItem)); + return DoesFileExist(path); } + static int ScanDLContentCount(const char *titleID) { char dlcPath[MAX_PATH]; @@ -2371,9 +2091,9 @@ extern "C" { extern DWORD g_NumUsers; } int CSavedGameGrid::IsXboxLiveAccountSelected() { // Returns 1 if curTitle points to the Xbox Live accounts entry. - // m_xboxLiveAccountTitle is the title index where Live accounts appear, + // m_liveAccountRow is the title index where Live accounts appear, // or -1 if no Live accounts entry exists on the current device. - return (m_xboxLiveAccountTitle >= 0 && m_curTitle == m_xboxLiveAccountTitle) ? 1 : 0; + return (m_liveAccountRow >= 0 && m_curTitle == m_liveAccountRow) ? 1 : 0; } int CSavedGameGrid::IsGameTitleSelected() @@ -2381,9 +2101,9 @@ int CSavedGameGrid::IsGameTitleSelected() // Returns 1 if curTitle is a real game title (not soundtracks, not Live accounts). if (m_curTitle < 0) return 0; - if (m_soundtrackTitle >= 0 && m_curTitle == m_soundtrackTitle) + if (m_soundtrackRow >= 0 && m_curTitle == m_soundtrackRow) return 0; - if (m_xboxLiveAccountTitle >= 0 && m_curTitle == m_xboxLiveAccountTitle) + if (m_liveAccountRow >= 0 && m_curTitle == m_liveAccountRow) return 0; return 1; } @@ -2419,7 +2139,7 @@ int CSavedGameGrid::GetGridItemCount(int nTitle) return 0; // Don't count for soundtracks (they use a different system) - if (m_soundtrackTitle >= 0 && nTitle >= m_soundtrackTitle) + if (m_soundtrackRow >= 0 && nTitle >= m_soundtrackRow) return 0; int nCount = GetSavedGameCount(nTitle); From a66d52e3346ef4e28b74d65bbf797a761d83ea28 Mon Sep 17 00:00:00 2001 From: Milenko <39630670+MrMilenko@users.noreply.github.com> Date: Wed, 18 Nov 2026 23:56:03 -0500 Subject: [PATCH 6/6] Fixed a cancelled save scan allocating a negative sized list GetSavedGameCount stored the -1 a cancelled scan returns and then did new CSave[-1]. Now a cancelled title stays unscanned and reads as no saves until the next scan. Nothing passes a cancel event today, so it was latent. Needs a console test. --- theseus/shared/title_collection.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/theseus/shared/title_collection.cpp b/theseus/shared/title_collection.cpp index 7e27042..b325914 100755 --- a/theseus/shared/title_collection.cpp +++ b/theseus/shared/title_collection.cpp @@ -149,6 +149,12 @@ static CSave* ScanSavesToFit(const TCHAR* root, const TCHAR* titleID, HANDLE can { CSave* scratch = new CSave [MAX_SAVED_GAMES]; *count = ScanSavedGames(root, titleID, scratch, cancel); + if (*count < 0) + { + // Cancelled: stays unscanned (-1) with no list. + delete [] scratch; + return NULL; + } CSave* saves = new CSave [*count]; CopyMemory(saves, scratch, *count * sizeof (CSave)); delete [] scratch; @@ -271,7 +277,7 @@ int CTitleArray::GetSavedGameCount(int nTitle, HANDLE hCancelEvent) CTitle& t = m_list[nTitle]; if (t.m_saveCount == -1) t.m_saveList = ScanSavesToFit(GetUData(), t.m_titleID, hCancelEvent, &t.m_saveCount); - return t.m_saveCount; + return t.m_saveCount < 0 ? 0 : t.m_saveCount; } // Fills one save record; false when the folder name won't fit (16 chars