UNPKG

@woosh/meep-engine

Version:

Pure JavaScript game engine. Fully featured and production ready.

81 lines (62 loc) 1.88 kB
import { assert } from "../../../assert.js"; /** * @template T * @param {number} width * @param {number} height * @param {QuadTreeNode<T>} boxes * @param {function(containerWidth:number, containerHeight:number, childWidth:number, childHeight:number):number} costFunction * @returns {QuadTreeDatum<T>} suitable container box */ export function findBestContainer( width, height, boxes, costFunction ) { assert.isNumber(width,'width'); assert.isNumber(height,'height'); assert.defined(boxes,'boxes'); assert.isFunction(costFunction,'costFunction'); let best = null; let bestScore = Number.POSITIVE_INFINITY; /** * * @param {QuadTreeNode} node * @return {boolean} */ function visitor(node){ if (node.getWidth() < width) { //too small, don't traverse deeper return false; } if (node.getHeight() < height) { //too small, don't traverse deeper return false; } const data = node.data; const box_count = data.length; for (let i = 0; i < box_count; i++) { const box = data[i]; const bW = box.getWidth(); if (bW < width) { //too small continue; } const bH = box.getHeight(); if (bH < height) { //too small continue; } const cost = costFunction(bW, bH, width, height); assert.isNumber(cost,'cost'); assert.notNaN(cost,'cost'); if (cost < bestScore) { bestScore = cost; best = box; } } return true; } boxes.traversePreOrder(visitor); return best; }