UNPKG

js-draw

Version:

Draw pictures using a pen, touchscreen, or mouse! JS-draw is a drawing library for JavaScript and TypeScript.

52 lines (51 loc) 2.22 kB
import { Rect2 } from '@js-draw/math'; import RenderingCacheNode from './RenderingCacheNode.mjs'; import { CacheRecordManager } from './CacheRecordManager.mjs'; export default class RenderingCache { constructor(cacheProps) { this.recordManager = new CacheRecordManager(cacheProps); this.sharedState = { props: cacheProps, currentRenderingCycle: 0, recordManager: this.recordManager, debugMode: false, }; this.recordManager.setSharedState(this.sharedState); } render(screenRenderer, image, viewport) { const visibleRect = viewport.visibleRect; this.sharedState.currentRenderingCycle++; // If we can't use the cache, if (!this.sharedState.props.isOfCorrectType(screenRenderer)) { image.render(screenRenderer, visibleRect); return; } if (!this.rootNode) { // Adjust the node so that it has the correct aspect ratio const res = this.sharedState.props.blockResolution; const topLeft = visibleRect.topLeft; this.rootNode = new RenderingCacheNode(new Rect2(topLeft.x, topLeft.y, res.x, res.y), this.sharedState); } while (!this.rootNode.region.containsRect(visibleRect)) { this.rootNode = this.rootNode.generateParent(); } this.rootNode = this.rootNode.smallestChildContaining(visibleRect) ?? this.rootNode; const visibleLeaves = image.getLeavesIntersectingRegion(viewport.visibleRect, (rect) => screenRenderer.isTooSmallToRender(rect)); let approxVisibleRenderTime = 0; for (const leaf of visibleLeaves) { approxVisibleRenderTime += leaf.getContent().getProportionalRenderingTime(); } if (approxVisibleRenderTime > this.sharedState.props.minProportionalRenderTimeToUseCache) { this.rootNode.renderItems(screenRenderer, [image], viewport); } else { image.render(screenRenderer, visibleRect); } } getDebugInfo() { return this.recordManager.getDebugInfo(); } setIsDebugMode(debugMode) { this.sharedState.debugMode = debugMode; } }