view game/js/util.js @ 13:8df95050fc8b

no more build during pause; tower popup closes on any click outside it
author ark
date 2026-10-19 21:59 +0200
parents 5492efd60e2c
children
line wrap: on
line source

// vector maths, random numbers, easing

window.MM = window.MM || {};

MM.util = (function () {
    "use strict";

    function clamp(v, lo, hi) {
        return v < lo ? lo : v > hi ? hi : v;
    }

    function lerp(a, b, t) {
        return a + (b - a) * t;
    }

    function dist(ax, ay, bx, by) {
        return Math.hypot(bx - ax, by - ay);
    }

    function deg(d) {
        return d * Math.PI / 180;
    }

    function easeIn(t) {
        return t * t;
    }

    function easeOut(t) {
        return 1 - (1 - t) * (1 - t);
    }

    // seeded random numbers (mulberry32): returns a function giving [0, 1)
    function rng(seed) {
        var a = seed >>> 0;
        return function () {
            a = (a + 0x6d2b79f5) >>> 0;
            var t = a;
            t = Math.imul(t ^ (t >>> 15), t | 1);
            t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
            return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
        };
    }

    // pick an index from a list of weights with the random function r
    function pick(weights, r) {
        var total = 0, i;
        for (i = 0; i < weights.length; i++) total += weights[i];
        var x = r() * total;
        for (i = 0; i < weights.length; i++) {
            x -= weights[i];
            if (x < 0) return i;
        }
        return weights.length - 1;
    }

    return { clamp: clamp, lerp: lerp, dist: dist, deg: deg, easeIn: easeIn,
             easeOut: easeOut, rng: rng, pick: pick };
})();