UNPKG

@polygonjs/polygonjs

Version:

node-based WebGL 3D engine https://polygonjs.com

31 lines (30 loc) 893 B
"use strict"; import { arrayCopy } from "../ArrayUtils"; import { randFloat } from "../math/_Module"; export class WFCTileConfigSampler { constructor() { this._cumulativeWeights = []; this._totalWeight = 0; this._tileConfigs = []; } setItemsAndWeights(tileConfigs, weights) { if (tileConfigs.length !== weights.length) { throw new Error("there must be as many weights as tileConfigs"); } this._cumulativeWeights.length = 0; this._totalWeight = 0; for (const weight of weights) { this._totalWeight += weight; this._cumulativeWeights.push(this._totalWeight); } arrayCopy(tileConfigs, this._tileConfigs); } sample(seed) { const randomWeight = randFloat(seed) * this._totalWeight; let index = 0; while (randomWeight >= this._cumulativeWeights[index]) { index++; } return this._tileConfigs[index]; } }