"use strict";

class BonyScene extends BaseScene {

    _particles = [];

    // Load resources here
    load(loadingContext) {
        const ctx = loadingContext;
        ctx.loadSprite("skull", "skull.png");
        // ctx.loadSprite("jaw", "jaw.png");
        ctx.loadSprite("particle", "particle.png");
        // ctx.loadShader("shiny", "fullscreen.vert", "shiny.frag");
        ctx.loadShader("bones", "fullscreen.vert", "bones.frag");
        ctx.loadShader("vignette", "fullscreen.vert", "sketchedvignette.frag");
    }

    initialize() {   
        for (var i = 0; i < 1500; i++) {
            this._particles.push(this._createParticle());
        }
    }

    update(renderContext, time) {
        const ctx = renderContext;
        ctx.backgroundShader("bones");
        ctx.postShader("vignette");
        const sin = Math.sin;

        const skullX = 120 + 8 * sin(time * 0.95);
        const skullY = 68 + 4 * sin(time * 1.1);
        const skullScale = 1 + 0.2 * sin(time / 2.7);

        for (var i = 0; i < this._particles.length; i++) {
            var p = this._particles[i];
            ctx.sprite(p);
            p.localX += p.dx;
            p.localY += p.dy;
            p.position.x = skullX + p.localX;
            p.position.y = skullY + p.localY * 1.35;
            const radius = 28 * skullScale;
            p.color.a = Math.max(radius - Math.sqrt(p.localX * p.localX + 0.87 * p.localY * p.localY), 0) / radius 
            if (p.color.a <= 0) {
                this._particles[i] = this._createParticle();
            }
        }

        this._drawSkull(skullX, skullY, skullScale, ctx);
    }

    _createParticle() {
        const item = new SpriteItem();
        item.width = 8;
        item.name = "particle";
        item.localX = 0;
        item.localY = 0;
        item.dx = Math.random() - 0.5;
        item.dy = Math.random() - 0.5;
        item.color = { r: 1, g: 0.8, b: 0.2, a: 0.5 };
        item.blendMode = BlendMode.add;
        return item;
    }


    _drawSkull(x, y, scale, ctx) {
        // ctx.sprite("jaw", x, y - 8 + 30 * scale, 50 * scale);
        ctx.sprite("skull", x, y, 50 * scale);
    }
}