js-draw
Version:
Draw pictures using a pen, touchscreen, or mouse! JS-draw is a drawing library for JavaScript and TypeScript.
68 lines (67 loc) • 3.05 kB
JavaScript
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.CacheRecordManager = void 0;
const CacheRecord_1 = __importDefault(require("./CacheRecord"));
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_1.default(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');
}
}
exports.CacheRecordManager = CacheRecordManager;
;