js-draw
Version:
Draw pictures using a pen, touchscreen, or mouse! JS-draw is a drawing library for JavaScript and TypeScript.
61 lines (60 loc) • 2.73 kB
JavaScript
import CacheRecord from './CacheRecord.mjs';
export class CacheRecordManager {
constructor(cacheProps) {
// Fixed-size array: Cache blocks are assigned indicies into [cachedCanvases].
this.cacheRecords = [];
this.maxCanvases = Math.ceil(
// Assuming four components per pixel:
cacheProps.cacheSize / 4 / cacheProps.blockResolution.x / cacheProps.blockResolution.y);
}
setSharedState(state) {
this.cacheState = state;
}
allocCanvas(drawTo, onDealloc) {
if (this.cacheRecords.length < this.maxCanvases) {
const record = new CacheRecord(onDealloc, this.cacheState);
record.setRenderingRegion(drawTo);
this.cacheRecords.push(record);
if (this.cacheState.debugMode) {
console.log('[Cache] Cache spaces used: ', this.cacheRecords.length, ' of ', this.maxCanvases);
}
return record;
}
else {
const lru = this.getLeastRecentlyUsedRecord();
if (this.cacheState.debugMode) {
console.log('[Cache] Re-alloc. Times allocated: ', lru.allocCount, '\nLast used cycle: ', lru.getLastUsedCycle(), '\nCurrent cycle: ', this.cacheState.currentRenderingCycle);
}
lru.realloc(onDealloc);
lru.setRenderingRegion(drawTo);
if (this.cacheState.debugMode) {
console.log("[Cache] Now re-alloc'd. Last used cycle: ", lru.getLastUsedCycle());
console.assert(lru['cacheState'] === this.cacheState, '[Cache] Unequal cache states! cacheState should be a shared object!');
}
return lru;
}
}
// Returns null if there are no cache records. Returns an unalloc'd record if one exists.
getLeastRecentlyUsedRecord() {
this.cacheRecords.sort((a, b) => a.getLastUsedCycle() - b.getLastUsedCycle());
return this.cacheRecords[0];
}
// Returns information to (hopefully) help debug performance issues
getDebugInfo() {
let numberAllocd = 0;
let averageReassignedCount = 0;
for (const cacheRecord of this.cacheRecords) {
averageReassignedCount += cacheRecord.allocCount;
if (cacheRecord.isAllocd()) {
numberAllocd++;
}
}
averageReassignedCount /= Math.max(this.cacheRecords.length, 1);
const debugInfo = [
`${this.cacheRecords.length} cache records (max ${this.maxCanvases})`,
`${numberAllocd} assigned to screen regions`,
`Average number of times reassigned: ${Math.round(averageReassignedCount * 100) / 100}`,
];
return debugInfo.join('\n');
}
}