Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 | 2x 2x 2x 2x 2x 7x 38x 9x 9x 9x 9x 7x 17x 14x 14x 13x 13x 10x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 48x 48x 14x 14x 14x 14x 1x 1x 1x 1x 1x 1x 1x | // The player's own courses (made on the select screen) kept across reloads in IndexedDB, as LR2 keeps them in its
// database: the courses as `.lr2crs` text plus what that format has no room for (the stage titles, the constraints,
// whether each course is flagged for IR (`release`, LR2's `ir` column) and which are a folder's last RANDOM MIX), the default NONSTOP connection and the
// RANDOM MIX settings (LR2's `config.xml` `<course>`) and the conditions the RANDOM MIX dialog last confirmed. Every
// stage of a course is kept, past the five LR2 plays (a saved RANDOM MIX may have up to 99), and a NONSTOP course's
// connections past the ten an LR2 course hash holds.
import {
LR2_NONSTOP_CONNECTIONS,
normalizeCourseConstraints,
parseLR2CourseFile,
serializeLR2CourseFile,
DEFAULT_LR2_RANDOM_MIX_SETTINGS,
normalizeLR2RandomMixSettings,
normalizeRandomMixConditions,
type CourseDefinition,
type LR2RandomMixSettings,
type NonstopConnection,
type RandomMixConditions,
} from '@be-music/player-engine/course';
/**
* The stored record's revision. `0` while the shape is still being defined: it may change incompatibly without the
* number moving. Any other stamp is unreadable. IndexedDB's database version stays {@link DB_VERSION}: `open` cannot
* be 0.
*/
const STORE_VERSION = 0;
const DB_NAME = 'be-music';
const DB_VERSION = 1;
const STORE_NAME = 'courses';
const RECORD_KEY = 'made';
/** What the course maker keeps across reloads. */
export interface MadeCourses {
/** Newest first. */
courses: CourseDefinition[];
defaultConnection: NonstopConnection;
randomMixSettings: LR2RandomMixSettings;
/** The conditions the RANDOM MIX dialog last confirmed (absent before it was ever confirmed). */
randomMixConditions?: RandomMixConditions;
/** Those of `courses` that are their folder's last RANDOM MIX, which the next draw there replaces. */
randomMixes: CourseDefinition[];
}
interface StoredMadeCourses {
version: number;
lr2crs: string;
/** Each course's stage titles, by course and stage index. */
titles: string[][];
/** Each course's constraints, which `.lr2crs` has no room for (absent in records saved before they were kept). */
constraints?: string[][];
/**
* Each course's IR flag (`release`), which `.lr2crs` has no room for either. An absent flag (the whole array in records
* saved before it was kept, or a course's entry) reads back as not flagged, so a course is only ever read-only after
* the player flagged it.
*/
release?: boolean[];
/**
* Each NONSTOP course's connections, which the LR2 hash holds for stages 1-10 only (absent in records saved before
* they were kept, and for a course that is not NONSTOP: the hash's are read).
*/
connections?: (string[] | null)[];
/** Whether each course is its folder's last RANDOM MIX (absent in records saved before RANDOM MIX). */
randomMix?: boolean[];
defaultConnection: string;
/** The RANDOM MIX settings (absent in records saved before RANDOM MIX: LR2's defaults). */
randomMixSettings?: Record<string, unknown>;
/** The RANDOM MIX dialog's conditions (absent before the dialog was confirmed: the dialog's defaults). */
randomMixConditions?: Record<string, unknown>;
}
/** The stored record of `made`. */
export function serializeMadeCourses(made: MadeCourses): StoredMadeCourses {
return {
version: STORE_VERSION,
lr2crs: serializeLR2CourseFile(made.courses),
titles: made.courses.map((course) => course.stages.map((stage) => stage.title ?? '')),
constraints: made.courses.map((course) => [...course.constraints]),
release: made.courses.map((course) => course.release),
connections: made.courses.map((course) =>
course.kind === 'nonstop' && course.connections !== undefined ? [...course.connections] : null,
),
randomMix: made.courses.map((course) => made.randomMixes.includes(course)),
defaultConnection: made.defaultConnection,
randomMixSettings: { ...made.randomMixSettings },
...(made.randomMixConditions !== undefined
? {
randomMixConditions: {
...made.randomMixConditions,
difficulties: [...made.randomMixConditions.difficulties],
},
}
: {}),
};
}
/** A NONSTOP course's kept connections, `count` of them: an unknown or missing one reads as FADE, LR2's default. */
function readConnections(values: readonly unknown[], count: number): NonstopConnection[] {
return Array.from({ length: Math.max(0, count) }, (_, index) =>
LR2_NONSTOP_CONNECTIONS.includes(values[index] as NonstopConnection)
? (values[index] as NonstopConnection)
: 'fade',
);
}
/** Reads a stored record back; anything unreadable gives no course, the FADE default and LR2's RANDOM MIX defaults. */
export function parseMadeCourses(value: unknown): MadeCourses {
const empty: MadeCourses = {
courses: [],
defaultConnection: 'fade',
randomMixSettings: { ...DEFAULT_LR2_RANDOM_MIX_SETTINGS },
randomMixes: [],
};
if (typeof value !== 'object' || value === null) return empty;
const stored = value as Partial<StoredMadeCourses>;
if (stored.version !== STORE_VERSION || typeof stored.lr2crs !== 'string') return empty;
const defaultConnection = LR2_NONSTOP_CONNECTIONS.includes(stored.defaultConnection as NonstopConnection)
? (stored.defaultConnection as NonstopConnection)
: 'fade';
const titles = Array.isArray(stored.titles) ? stored.titles : [];
const constraints = Array.isArray(stored.constraints) ? stored.constraints : [];
const releases: unknown[] = Array.isArray(stored.release) ? stored.release : [];
const connections: unknown[] = Array.isArray(stored.connections) ? stored.connections : [];
// The player's own courses are read whole, not cut to the five stages LR2 plays.
const courses = parseLR2CourseFile(stored.lr2crs, { maxStages: Number.POSITIVE_INFINITY }).map((course, index) => {
const names = titles[index];
const kept = constraints[index];
const release = releases[index];
const keptConnections = connections[index];
return {
...course,
...(Array.isArray(kept) ? { constraints: normalizeCourseConstraints(kept) } : {}),
...(course.kind === 'nonstop' && Array.isArray(keptConnections)
? { connections: readConnections(keptConnections, course.stages.length - 1) }
: {}),
// `parseLR2CourseFile` reads every course released (LR2.exe imports with `ir = 1`); a made course is not.
release: release === true,
stages: course.stages.map((stage, stageIndex) => {
const title = Array.isArray(names) ? names[stageIndex] : undefined;
return typeof title === 'string' && title.length > 0 ? { ...stage, title } : stage;
}),
};
});
const flags: unknown[] = Array.isArray(stored.randomMix) ? stored.randomMix : [];
const randomMixSettings = normalizeLR2RandomMixSettings(
typeof stored.randomMixSettings === 'object' && stored.randomMixSettings !== null ? stored.randomMixSettings : {},
);
return {
courses,
defaultConnection,
randomMixSettings,
...(typeof stored.randomMixConditions === 'object' && stored.randomMixConditions !== null
? { randomMixConditions: normalizeRandomMixConditions(stored.randomMixConditions) }
: {}),
randomMixes: courses.filter((_, index) => flags[index] === true),
};
}
function openDatabase(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME, DB_VERSION);
request.onupgradeneeded = () => {
if (!request.result.objectStoreNames.contains(STORE_NAME)) request.result.createObjectStore(STORE_NAME);
};
request.onsuccess = () => {
const db = request.result;
void migrateLegacyCourses(db).then(
() => resolve(db),
(error) => {
db.close();
reject(error);
},
);
};
request.onerror = () => reject(request.error ?? new Error('indexedDB open failed'));
});
}
/** Move the old database's course record without overwriting courses already saved under the current name. */
async function migrateLegacyCourses(db: IDBDatabase): Promise<void> {
const previous = await new Promise<IDBDatabase | undefined>((resolve, reject) => {
const request = indexedDB.open('be-music-demo');
let missing = false;
request.onupgradeneeded = () => {
missing = true;
request.transaction?.abort();
};
request.onerror = () => (missing ? resolve(undefined) : reject(request.error));
request.onsuccess = () => resolve(request.result);
});
if (!previous) return;
try {
if (!previous.objectStoreNames.contains(STORE_NAME)) return;
const value = await new Promise<unknown>((resolve, reject) => {
const transaction = previous.transaction(STORE_NAME, 'readonly');
const request = transaction.objectStore(STORE_NAME).get(RECORD_KEY);
transaction.oncomplete = () => resolve(request.result);
transaction.onabort = () => reject(transaction.error);
});
if (value === undefined) return;
await new Promise<void>((resolve, reject) => {
const transaction = db.transaction(STORE_NAME, 'readwrite');
const store = transaction.objectStore(STORE_NAME);
const request = store.get(RECORD_KEY);
request.onsuccess = () => {
if (request.result === undefined) store.put(value, RECORD_KEY);
};
transaction.oncomplete = () => resolve();
transaction.onabort = () => reject(transaction.error);
});
// Remove the source only after the destination transaction commits, so clearing courses cannot resurrect it.
await new Promise<void>((resolve, reject) => {
const transaction = previous.transaction(STORE_NAME, 'readwrite');
transaction.objectStore(STORE_NAME).delete(RECORD_KEY);
transaction.oncomplete = () => resolve();
transaction.onabort = () => reject(transaction.error);
});
} finally {
previous.close();
}
}
function run<T>(mode: IDBTransactionMode, action: (store: IDBObjectStore) => IDBRequest<T>): Promise<T> {
return openDatabase().then(
(db) =>
new Promise<T>((resolve, reject) => {
const request = action(db.transaction(STORE_NAME, mode).objectStore(STORE_NAME));
request.onsuccess = () => {
resolve(request.result);
db.close();
};
request.onerror = () => {
reject(request.error ?? new Error('indexedDB request failed'));
db.close();
};
}),
);
}
/** The saved courses, or none when IndexedDB is unavailable (a private window, blocked storage). */
export async function loadMadeCourses(): Promise<MadeCourses> {
try {
return parseMadeCourses(await run('readonly', (store) => store.get(RECORD_KEY)));
} catch {
return parseMadeCourses(undefined);
}
}
/** Saves the courses; a failure is reported to the caller, which keeps them for this session. */
export async function saveMadeCourses(made: MadeCourses): Promise<void> {
await run('readwrite', (store) => store.put(serializeMadeCourses(made), RECORD_KEY));
}
|