<commit_before>// =============================================================================
// sprites
// =============================================================================

//
// hero sprite
//
function Hero(game, x, y) {
    Phaser.Sprite.call(this, game, x, y, 'hero');
    this.anchor.set(0.5, 0.5);

    // physic properties
    this.game.physics.enable(this);
    this.body.collideWorldBounds = true;

    this.animations.add('stop', [0]);
    this.animations.add('run', [1, 2], 8, true); // 8fps looped
    this.animations.add('jump', [3]);
    this.animations.add('fall', [4]);
}

// inherit from Phaser.Sprite
Hero.prototype = Object.create(Phaser.Sprite.prototype);
Hero.prototype.constructor = Hero;

Hero.prototype.move = function (direction) {
    const SPEED = 200;
    this.body.velocity.x = direction * SPEED;

    // update image flipping & animations
    if (this.body.velocity.x < 0) {
        this.scale.x = -1;
    }
    else if (this.body.velocity.x > 0) {
        this.scale.x = 1;
    }
};

Hero.prototype.jump = function () {
    const JUMP_SPEED = 600;
    let canJump = this.body.touching.down;

    if (canJump) {
        this.body.velocity.y = -JUMP_SPEED;
    }

    return canJump;
};

Hero.prototype.bounce = function () {
    const BOUNCE_SPEED = 200;
    this.body.velocity.y = -BOUNCE_SPEED;
};

Hero.prototype.update = function () {
    // update sprite animation, if it needs changing
    let animationName = this._getAnimationName();
    if (this.animations.name !== animationName) {
        this.animations.play(animationName);
    }
};

Hero.prototype._getAnimationName = function () {
    let name = 'stop'; // default animation

    // jumping
    if (this.body.velocity.y < 0) {
        name = 'jump';
    }
    // falling
    else if (this.body.velocity.y >= 0 && !this.body.touching.down) {
        name = 'fall';
    }
    else if (this.body.velocity.x !== 0 && this.body.touching.down) {
        name = 'run';
    }

    return name;
};

//
// Spider (enemy)
//
function Spider(game, x, y) {
    Phaser.Sprite.call(this, game, x, y, 'spider');

    // anchor
    this.anchor.set(0.5);
    // animation
    this.animations.add('crawl', [0, 1, 2], 8, true); // 8fps, looped
    this.animations.add('die', [0, 4, 0, 4, 0, 4, 3, 3, 3, 3, 3, 3], 12);
    this.animations.play('crawl');

    // physic properties
    this.game.physics.enable(this);
    this.body.collideWorldBounds = true;
    this.body.velocity.x = Spider.SPEED;
}

Spider.SPEED = 100;

// inherit from Phaser.Sprite
Spider.prototype = Object.create(Phaser.Sprite.prototype);
Spider.prototype.constructor = Spider;

Spider.prototype.update = function () {
    // check against walls and reverse direction if necessary
    if (this.body.touching.right || this.body.blocked.right) {
        this.body.velocity.x = -Spider.SPEED; // turn left
    }
    else if (this.body.touching.left || this.body.blocked.left) {
        this.body.velocity.x = Spider.SPEED; // turn right
    }
};

Spider.prototype.die = function () {
    this.body.enable = false;

    this.animations.play('die').onComplete.addOnce(function () {
        this.kill();
    }, this);
};

// =============================================================================
// game states
// =============================================================================

PlayState = {};

const LEVEL_COUNT = 2;

PlayState.init = function (data) {
    this.game.renderer.renderSession.roundPixels = true;

    this.keys = this.game.input.keyboard.addKeys({
        left: Phaser.KeyCode.LEFT,
        right: Phaser.KeyCode.RIGHT,
        up: Phaser.KeyCode.UP
    });

    this.keys.up.onDown.add(function () {
        let didJump = this.hero.jump();
        if (didJump) {
            this.sfx.jump.play();
        }
    }, this);

    this.coinPickupCount = 0;
    this.hasKey = false;
    this.level = (data.level || 0) % LEVEL_COUNT;
};

PlayState.preload = function () {
    this.game.load.json('level:0', 'data/level00.json');
    this.game.load.json('level:1', 'data/level01.json');

    this.game.load.image('font:numbers', 'images/numbers.png');

    this.game.load.image('background', 'images/BG1.jpg');
    this.game.load.image('ground', 'images/ground.jpg');
    this.game.load.image('grass:8x1', 'images/block_8x1.jpg');
    this.game.load.image('grass:6x1', 'images/block_6x1.jpg');
    this.game.load.image('grass:4x1', 'images/block_4x1.jpg');
    this.game.load.image('grass:2x1', 'images/block_2x1.jpg');
    this.game.load.image('grass:1x1', 'images/block_1x1.jpg');
    this.game.load.image('invisible-wall', 'images/invisible_wall.png');
    this.game.load.image('icon:coin', 'images/coin_icon.png');
    this.game.load.image('key', 'images/key.png');

    this.game.load.spritesheet('coin', 'images/coin_animated.png', 25, 28);
    this.game.load.spritesheet('spider', 'images/spider.png', 42, 32);
    this.game.load.spritesheet('hero', 'images/hero_2.png', 36, 42);
    this.game.load.spritesheet('door', 'images/door.png', 42, 66);
    this.game.load.spritesheet('icon:key', 'images/key_icon.png', 34, 30);

    this.game.load.audio('sfx:jump', 'audio/jump.wav');
    this.game.load.audio('sfx:coin', 'audio/coin.wav');
    this.game.load.audio('sfx:stomp', 'audio/stomp.wav');
    this.game.load.audio('sfx:key', 'audio/key.wav');
    this.game.load.audio('sfx:door', 'audio/door.wav');
};

PlayState.create = function () {
    // create sound entities
    this.sfx = {
        jump: this.game.add.audio('sfx:jump'),
        coin: this.game.add.audio('sfx:coin'),
        stomp: this.game.add.audio('sfx:stomp'),
        key: this.game.add.audio('sfx:key'),
        door: this.game.add.audio('sfx:door')
    };

    // create level
    this.game.add.image(0, 0, 'background');
    this._loadLevel(this.game.cache.getJSON(`level:${this.level}`));

    // crete hud with scoreboards)
    this._createHud();
};

PlayState.update = function () {
    this._handleCollisions();
    this._handleInput();

    this.coinFont.text = `x${this.coinPickupCount}`;
    this.keyIcon.frame = this.hasKey ? 1 : 0;
};

PlayState._handleCollisions = function () {
    this.game.physics.arcade.collide(this.spiders, this.platforms);
    this.game.physics.arcade.collide(this.spiders, this.enemyWalls);
    this.game.physics.arcade.collide(this.hero, this.platforms);

    this.game.physics.arcade.overlap(this.hero, this.coins, this._onHeroVsCoin,
        null, this);
    this.game.physics.arcade.overlap(this.hero, this.spiders,
        this._onHeroVsEnemy, null, this);
    this.game.physics.arcade.overlap(this.hero, this.key, this._onHeroVsKey,
        null, this);
    this.game.physics.arcade.overlap(this.hero, this.door, this._onHeroVsDoor,
        // ignore if there is no key or the player is on air
        function (hero, door) {
            return this.hasKey && hero.body.touching.down;
        }, this);
};

PlayState._handleInput = function () {
    if (this.keys.left.isDown) { // move hero left
        this.hero.move(-1);
    }
    else if (this.keys.right.isDown) { // move hero right
        this.hero.move(1);
    }
    else { // stop
        this.hero.move(0);
    }
};

PlayState._loadLevel = function (data) {
    // create all the groups/layers that we need
    this.bgDecoration = this.game.add.group();
    this.platforms = this.game.add.group();
    this.coins = this.game.add.group();
    this.spiders = this.game.add.group();
    this.enemyWalls = this.game.add.group();
    this.enemyWalls.visible = false;

    // spawn all platforms
    data.platforms.forEach(this._spawnPlatform, this);
    // spawn hero and enemies
    this._spawnCharacters({hero: data.hero, spiders: data.spiders});
    // spawn important objects
    data.coins.forEach(this._spawnCoin, this);
    this._spawnDoor(data.door.x, data.door.y);
    this._spawnKey(data.key.x, data.key.y);

    // enable gravity
    const GRAVITY = 1200;
    this.game.physics.arcade.gravity.y = GRAVITY;
};

PlayState._spawnPlatform = function (platform) {
    let sprite = this.platforms.create(
        platform.x, platform.y, platform.image);

    this.game.physics.enable(sprite);
    sprite.body.allowGravity = false;
    sprite.body.immovable = true;

    this._spawnEnemyWall(platform.x, platform.y, 'left');
    this._spawnEnemyWall(platform.x + sprite.width, platform.y, 'right');
};

PlayState._spawnEnemyWall = function (x, y, side) {
    let sprite = this.enemyWalls.create(x, y, 'invisible-wall');
    // anchor and y displacement
    sprite.anchor.set(side === 'left' ? 1 : 0, 1);
    // physic properties
    this.game.physics.enable(sprite);
    sprite.body.immovable = true;
    sprite.body.allowGravity = false;
};

PlayState._spawnCharacters = function (data) {
    // spawn spiders
    data.spiders.forEach(function (spider) {
        let sprite = new Spider(this.game, spider.x, spider.y);
        this.spiders.add(sprite);
    }, this);

    // spawn hero
    this.hero = new Hero(this.game, data.hero.x, data.hero.y);
    this.game.add.existing(this.hero);
};

PlayState._spawnCoin = function (coin) {
    let sprite = this.coins.create(coin.x, coin.y, 'coin');
    sprite.anchor.set(0.5, 0.5);

    this.game.physics.enable(sprite);
    sprite.body.allowGravity = false;

    sprite.animations.add('rotate', [0, 1, 2, 1], 6, true); // 6fps, looped
    sprite.animations.play('rotate');
};

PlayState._spawnDoor = function (x, y) {
    this.door = this.bgDecoration.create(x, y, 'door');
    this.door.anchor.setTo(0.5, 1);
    this.game.physics.enable(this.door);
    this.door.body.allowGravity = false;
};

PlayState._spawnKey = function (x, y) {
    this.key = this.bgDecoration.create(x, y, 'key');
    this.key.anchor.set(0.5, 0.5);
    // enable physics to detect collisions, so the hero can pick the key up
    this.game.physics.enable(this.key);
    this.key.body.allowGravity = false;
    // add a small 'up & down' animation via a tween
    this.key.y -= 3;
    this.game.add.tween(this.key)
        .to({y: this.key.y + 6}, 800, Phaser.Easing.Sinusoidal.InOut)
        .yoyo(true)
        .loop()
        .start();
};

PlayState._onHeroVsCoin = function (hero, coin) {
    this.sfx.coin.play();
    coin.kill();
    this.coinPickupCount++;
};

PlayState._onHeroVsEnemy = function (hero, enemy) {
    if (hero.body.velocity.y > 0) { // kill enemies when hero is falling
        hero.bounce();
        enemy.die();
        this.sfx.stomp.play();
    }
    else { // game over -> restart the game
        this.sfx.stomp.play();
        this.game.state.restart(true, false, {level: this.level});
    }
};

PlayState._onHeroVsKey = function (hero, key) {
    this.sfx.key.play();
    key.kill();
    this.hasKey = true;
};

PlayState._onHeroVsDoor = function (hero, door) {
    this.sfx.door.play();
    this.game.state.restart(true, false, { level: this.level + 1 });
};

PlayState._createHud = function () {
    const NUMBERS_STR = '0123456789X ';
    this.coinFont = this.game.add.retroFont('font:numbers', 20, 26,
        NUMBERS_STR);

    this.keyIcon = this.game.make.image(0, 19, 'icon:key');
    this.keyIcon.anchor.set(0, 0.5);

    let coinIcon = this.game.make.image(this.keyIcon.width + 7, 0, 'icon:coin');
    let coinScoreImg = this.game.make.image(coinIcon.x + coinIcon.width,
        coinIcon.height / 2, this.coinFont);
    coinScoreImg.anchor.set(0, 0.5);

    this.hud = this.game.add.group();
    this.hud.add(coinIcon);
    this.hud.add(coinScoreImg);
    this.hud.add(this.keyIcon);
    this.hud.position.set(10, 10);
};

// =============================================================================
// entry point
// =============================================================================

window.onload = function () {
    let game = new Phaser.Game(960, 600, Phaser.AUTO, 'game');
    game.state.add('play', PlayState);
    game.state.start('play', true, false, {level: 0});
};<commit_msg>coins<commit_after>// =============================================================================
// sprites
// =============================================================================

//
// hero sprite
//
function Hero(game, x, y) {
    Phaser.Sprite.call(this, game, x, y, 'hero');
    this.anchor.set(0.5, 0.5);

    // physic properties
    this.game.physics.enable(this);
    this.body.collideWorldBounds = true;

    this.animations.add('stop', [0]);
    this.animations.add('run', [1, 2], 8, true); // 8fps looped
    this.animations.add('jump', [3]);
    this.animations.add('fall', [4]);
}

// inherit from Phaser.Sprite
Hero.prototype = Object.create(Phaser.Sprite.prototype);
Hero.prototype.constructor = Hero;

Hero.prototype.move = function (direction) {
    const SPEED = 200;
    this.body.velocity.x = direction * SPEED;

    // update image flipping & animations
    if (this.body.velocity.x < 0) {
        this.scale.x = -1;
    }
    else if (this.body.velocity.x > 0) {
        this.scale.x = 1;
    }
};

Hero.prototype.jump = function () {
    const JUMP_SPEED = 600;
    let canJump = this.body.touching.down;

    if (canJump) {
        this.body.velocity.y = -JUMP_SPEED;
    }

    return canJump;
};

Hero.prototype.bounce = function () {
    const BOUNCE_SPEED = 200;
    this.body.velocity.y = -BOUNCE_SPEED;
};

Hero.prototype.update = function () {
    // update sprite animation, if it needs changing
    let animationName = this._getAnimationName();
    if (this.animations.name !== animationName) {
        this.animations.play(animationName);
    }
};

Hero.prototype._getAnimationName = function () {
    let name = 'stop'; // default animation

    // jumping
    if (this.body.velocity.y < 0) {
        name = 'jump';
    }
    // falling
    else if (this.body.velocity.y >= 0 && !this.body.touching.down) {
        name = 'fall';
    }
    else if (this.body.velocity.x !== 0 && this.body.touching.down) {
        name = 'run';
    }

    return name;
};

//
// Spider (enemy)
//
function Spider(game, x, y) {
    Phaser.Sprite.call(this, game, x, y, 'spider');

    // anchor
    this.anchor.set(0.5);
    // animation
    this.animations.add('crawl', [0, 1, 2], 8, true); // 8fps, looped
    this.animations.add('die', [0, 4, 0, 4, 0, 4, 3, 3, 3, 3, 3, 3], 12);
    this.animations.play('crawl');

    // physic properties
    this.game.physics.enable(this);
    this.body.collideWorldBounds = true;
    this.body.velocity.x = Spider.SPEED;
}

Spider.SPEED = 100;

// inherit from Phaser.Sprite
Spider.prototype = Object.create(Phaser.Sprite.prototype);
Spider.prototype.constructor = Spider;

Spider.prototype.update = function () {
    // check against walls and reverse direction if necessary
    if (this.body.touching.right || this.body.blocked.right) {
        this.body.velocity.x = -Spider.SPEED; // turn left
    }
    else if (this.body.touching.left || this.body.blocked.left) {
        this.body.velocity.x = Spider.SPEED; // turn right
    }
};

Spider.prototype.die = function () {
    this.body.enable = false;

    this.animations.play('die').onComplete.addOnce(function () {
        this.kill();
    }, this);
};

// =============================================================================
// game states
// =============================================================================

PlayState = {};

const LEVEL_COUNT = 2;

PlayState.init = function (data) {
    this.game.renderer.renderSession.roundPixels = true;

    this.keys = this.game.input.keyboard.addKeys({
        left: Phaser.KeyCode.LEFT,
        right: Phaser.KeyCode.RIGHT,
        up: Phaser.KeyCode.UP
    });

    this.keys.up.onDown.add(function () {
        let didJump = this.hero.jump();
        if (didJump) {
            this.sfx.jump.play();
        }
    }, this);

    this.coinPickupCount = 0;
    this.hasKey = false;
    this.level = (data.level || 0) % LEVEL_COUNT;
};

PlayState.preload = function () {
    this.game.load.json('level:0', 'data/level00.json');
    this.game.load.json('level:1', 'data/level01.json');

    this.game.load.image('font:numbers', 'images/numbers.png');

    this.game.load.image('background', 'images/BG1.jpg');
    this.game.load.image('ground', 'images/ground.jpg');
    this.game.load.image('grass:8x1', 'images/block_8x1.jpg');
    this.game.load.image('grass:6x1', 'images/block_6x1.jpg');
    this.game.load.image('grass:4x1', 'images/block_4x1.jpg');
    this.game.load.image('grass:2x1', 'images/block_2x1.jpg');
    this.game.load.image('grass:1x1', 'images/block_1x1.jpg');
    this.game.load.image('invisible-wall', 'images/invisible_wall.png');
    this.game.load.image('icon:coin', 'images/coin_icon.png');
    this.game.load.image('key', 'images/key.png');

    this.game.load.spritesheet('coin', 'images/coin_animated.png', 25, 28);
    this.game.load.spritesheet('spider', 'images/spider.png', 42, 32);
    this.game.load.spritesheet('hero', 'images/hero_2.png', 36, 42);
    this.game.load.spritesheet('door', 'images/door.png', 42, 66);
    this.game.load.spritesheet('icon:key', 'images/key_icon_2.png', 34, 30);

    this.game.load.audio('sfx:jump', 'audio/jump.wav');
    this.game.load.audio('sfx:coin', 'audio/coin.wav');
    this.game.load.audio('sfx:stomp', 'audio/stomp.wav');
    this.game.load.audio('sfx:key', 'audio/key.wav');
    this.game.load.audio('sfx:door', 'audio/door.wav');
};

PlayState.create = function () {
    // create sound entities
    this.sfx = {
        jump: this.game.add.audio('sfx:jump'),
        coin: this.game.add.audio('sfx:coin'),
        stomp: this.game.add.audio('sfx:stomp'),
        key: this.game.add.audio('sfx:key'),
        door: this.game.add.audio('sfx:door')
    };

    // create level
    this.game.add.image(0, 0, 'background');
    this._loadLevel(this.game.cache.getJSON(`level:${this.level}`));

    // crete hud with scoreboards)
    this._createHud();
};

PlayState.update = function () {
    this._handleCollisions();
    this._handleInput();

    this.coinFont.text = `x${this.coinPickupCount}`;
    this.keyIcon.frame = this.hasKey ? 1 : 0;
};

PlayState._handleCollisions = function () {
    this.game.physics.arcade.collide(this.spiders, this.platforms);
    this.game.physics.arcade.collide(this.spiders, this.enemyWalls);
    this.game.physics.arcade.collide(this.hero, this.platforms);

    this.game.physics.arcade.overlap(this.hero, this.coins, this._onHeroVsCoin,
        null, this);
    this.game.physics.arcade.overlap(this.hero, this.spiders,
        this._onHeroVsEnemy, null, this);
    this.game.physics.arcade.overlap(this.hero, this.key, this._onHeroVsKey,
        null, this);
    this.game.physics.arcade.overlap(this.hero, this.door, this._onHeroVsDoor,
        // ignore if there is no key or the player is on air
        function (hero, door) {
            return this.hasKey && hero.body.touching.down;
        }, this);
};

PlayState._handleInput = function () {
    if (this.keys.left.isDown) { // move hero left
        this.hero.move(-1);
    }
    else if (this.keys.right.isDown) { // move hero right
        this.hero.move(1);
    }
    else { // stop
        this.hero.move(0);
    }
};

PlayState._loadLevel = function (data) {
    // create all the groups/layers that we need
    this.bgDecoration = this.game.add.group();
    this.platforms = this.game.add.group();
    this.coins = this.game.add.group();
    this.spiders = this.game.add.group();
    this.enemyWalls = this.game.add.group();
    this.enemyWalls.visible = false;

    // spawn all platforms
    data.platforms.forEach(this._spawnPlatform, this);
    // spawn hero and enemies
    this._spawnCharacters({hero: data.hero, spiders: data.spiders});
    // spawn important objects
    data.coins.forEach(this._spawnCoin, this);
    this._spawnDoor(data.door.x, data.door.y);
    this._spawnKey(data.key.x, data.key.y);

    // enable gravity
    const GRAVITY = 1200;
    this.game.physics.arcade.gravity.y = GRAVITY;
};

PlayState._spawnPlatform = function (platform) {
    let sprite = this.platforms.create(
        platform.x, platform.y, platform.image);

    this.game.physics.enable(sprite);
    sprite.body.allowGravity = false;
    sprite.body.immovable = true;

    this._spawnEnemyWall(platform.x, platform.y, 'left');
    this._spawnEnemyWall(platform.x + sprite.width, platform.y, 'right');
};

PlayState._spawnEnemyWall = function (x, y, side) {
    let sprite = this.enemyWalls.create(x, y, 'invisible-wall');
    // anchor and y displacement
    sprite.anchor.set(side === 'left' ? 1 : 0, 1);
    // physic properties
    this.game.physics.enable(sprite);
    sprite.body.immovable = true;
    sprite.body.allowGravity = false;
};

PlayState._spawnCharacters = function (data) {
    // spawn spiders
    data.spiders.forEach(function (spider) {
        let sprite = new Spider(this.game, spider.x, spider.y);
        this.spiders.add(sprite);
    }, this);

    // spawn hero
    this.hero = new Hero(this.game, data.hero.x, data.hero.y);
    this.game.add.existing(this.hero);
};

PlayState._spawnCoin = function (coin) {
    let sprite = this.coins.create(coin.x, coin.y, 'coin');
    sprite.anchor.set(0.5, 0.5);

    this.game.physics.enable(sprite);
    sprite.body.allowGravity = false;

    sprite.animations.add('rotate', [0, 1, 2, 1], 6, true); // 6fps, looped
    sprite.animations.play('rotate');
};

PlayState._spawnDoor = function (x, y) {
    this.door = this.bgDecoration.create(x, y, 'door');
    this.door.anchor.setTo(0.5, 1);
    this.game.physics.enable(this.door);
    this.door.body.allowGravity = false;
};

PlayState._spawnKey = function (x, y) {
    this.key = this.bgDecoration.create(x, y, 'key');
    this.key.anchor.set(0.5, 0.5);
    // enable physics to detect collisions, so the hero can pick the key up
    this.game.physics.enable(this.key);
    this.key.body.allowGravity = false;
    // add a small 'up & down' animation via a tween
    this.key.y -= 3;
    this.game.add.tween(this.key)
        .to({y: this.key.y + 6}, 800, Phaser.Easing.Sinusoidal.InOut)
        .yoyo(true)
        .loop()
        .start();
};

PlayState._onHeroVsCoin = function (hero, coin) {
    this.sfx.coin.play();
    coin.kill();
    this.coinPickupCount++;
};

PlayState._onHeroVsEnemy = function (hero, enemy) {
    if (hero.body.velocity.y > 0) { // kill enemies when hero is falling
        hero.bounce();
        enemy.die();
        this.sfx.stomp.play();
    }
    else { // game over -> restart the game
        this.sfx.stomp.play();
        this.game.state.restart(true, false, {level: this.level});
    }
};

PlayState._onHeroVsKey = function (hero, key) {
    this.sfx.key.play();
    key.kill();
    this.hasKey = true;
};

PlayState._onHeroVsDoor = function (hero, door) {
    this.sfx.door.play();
    this.game.state.restart(true, false, { level: this.level + 1 });
};

PlayState._createHud = function () {
    const NUMBERS_STR = '0123456789X ';
    this.coinFont = this.game.add.retroFont('font:numbers', 20, 26,
        NUMBERS_STR);

    this.keyIcon = this.game.make.image(0, 19, 'icon:key');
    this.keyIcon.anchor.set(0, 0.5);

    let coinIcon = this.game.make.image(this.keyIcon.width + 7, 0, 'icon:coin');
    let coinScoreImg = this.game.make.image(coinIcon.x + coinIcon.width,
        coinIcon.height / 2, this.coinFont);
    coinScoreImg.anchor.set(0, 0.5);

    this.hud = this.game.add.group();
    this.hud.add(coinIcon);
    this.hud.add(coinScoreImg);
    this.hud.add(this.keyIcon);
    this.hud.position.set(10, 10);
};

// =============================================================================
// entry point
// =============================================================================

window.onload = function () {
    let game = new Phaser.Game(960, 600, Phaser.AUTO, 'game');
    game.state.add('play', PlayState);
    game.state.start('play', true, false, {level: 0});
};<|endoftext|>


<commit_before>ig.module('game.entities.dead-zombie')
.requires(
  'impact.impact',
  'impact.entity',
  'game.effects.slime-drip'
)
.defines(function() {
  EntityDeadZombie = ig.Entity.extend({
    _wmIgnore: true, // do not show this object in weltmeister

    animSheet: new ig.AnimationSheet( 'media/zombie.png', 32, 32 ),

    // the size of our collider
    size: { x: 8, y: 32 },

    name: 'zombie',

    // the offset of collider
    offset: { x: 12, y: 0 },

    // movement variables
    maxVel: { x: 100, y: 100 },
    friction: { x: 2000, y: 0 },
    accel: { x: 0, y: 0 },
    gravityFactor: 1,

    deathTime: 1,

    // collision settings, collide against player
    type: ig.Entity.TYPE.NONE,
    checkAgainst: ig.Entity.TYPE.NONE,
    collides: ig.Entity.COLLIDES.NEVER,

    init: function( x, y, settings ) {
      this.parent( x, y, settings );

      // setup animations
      // true means do not repeat
      // idle is a system animation, called by default
      this.addAnim( 'idle', 5, [9], true);
      this.addAnim( 'dead', 0.1, [10, 11], true);
      this.deathTimer = new ig.Timer();

      this.direction = ig.game.getEntityByName('hero').pos.x < x ? 1 : -1;

      this.flip = this.direction < 0;

      this.accel = {
        x: 12000 * this.direction,
        y: -7
      };
    },

    update: function() {
      this.currentAnim.flip.x = this.flip;

      if(this.deathTimer.delta() > this.deathTime) {
        this.accel = { x: 0, y: 0 };
      }

      if(this.slimeTimer && this.slimeTimer.delta() > 0) {
        this.slimeTimer = null;
        ig.game.spawnEntity(EffectSlimeDrip, this.pos.x, this.pos.y + this.size.y);
      }

      if(this.vel.y === 0 && this.deathTimer.delta() > this.deathTime &&
        this.currentAnim === this.anims.idle) {
        this.currentAnim = this.anims.dead.rewind();
        if(ig._.coinFlip()) {
          this.slimeTimer = new ig.Timer(2);
        }
      }

      this.parent();
    }
  });
});
<commit_msg>zombies fly back faster on death<commit_after>ig.module('game.entities.dead-zombie')
.requires(
  'impact.impact',
  'impact.entity',
  'game.effects.slime-drip'
)
.defines(function() {
  EntityDeadZombie = ig.Entity.extend({
    _wmIgnore: true, // do not show this object in weltmeister

    animSheet: new ig.AnimationSheet( 'media/zombie.png', 32, 32 ),

    // the size of our collider
    size: { x: 8, y: 32 },

    name: 'zombie',

    // the offset of collider
    offset: { x: 12, y: 0 },

    // movement variables
    maxVel: { x: 100, y: 100 },
    friction: { x: 2000, y: 0 },
    accel: { x: 0, y: 0 },
    gravityFactor: 1,

    deathTime: 0.8,

    // collision settings, collide against player
    type: ig.Entity.TYPE.NONE,
    checkAgainst: ig.Entity.TYPE.NONE,
    collides: ig.Entity.COLLIDES.NEVER,

    init: function( x, y, settings ) {
      this.parent( x, y, settings );

      // setup animations
      // true means do not repeat
      // idle is a system animation, called by default
      this.addAnim( 'idle', 5, [9], true);
      this.addAnim( 'dead', 0.1, [10, 11], true);
      this.deathTimer = new ig.Timer();

      this.direction = ig.game.getEntityByName('hero').pos.x < x ? 1 : -1;

      this.flip = this.direction < 0;

      this.accel = {
        x: 14000 * this.direction,
        y: -7
      };
    },

    update: function() {
      this.currentAnim.flip.x = this.flip;

      if(this.deathTimer.delta() > this.deathTime) {
        this.accel = { x: 0, y: 0 };
      }

      if(this.slimeTimer && this.slimeTimer.delta() > 0) {
        this.slimeTimer = null;
        ig.game.spawnEntity(EffectSlimeDrip, this.pos.x, this.pos.y + this.size.y);
      }

      if(this.vel.y === 0 && this.deathTimer.delta() > this.deathTime &&
        this.currentAnim === this.anims.idle) {
        this.currentAnim = this.anims.dead.rewind();
        if(ig._.coinFlip()) {
          this.slimeTimer = new ig.Timer(2);
        }
      }

      this.parent();
    }
  });
});
<|endoftext|>


<commit_before>var element = '';
var jsid = '';

function sh(type, id) {
  $("input[name='session']").attr('value', jsid);

  if (type == 1) {
    reply_to = $("input[name='replyto']", element);
    if (reply_to.attr('value') != id) {
      element.hide();
    }

    if (element.is(':hidden')) {
      reply = $('div.reply', $('div.msg_body', $('#comment-' + id)));
      reply.append(element);
      reply_to.attr('value', id);
      element.slideDown('slow');
    } else {
      element.slideUp('slow');
    }
  } else if (type == 0) {
    topic_id = $("input[name='topic']", element).attr('value');

    reply_to = $("input[name='replyto']", element);
    if (reply_to.attr('value') != 0) {
      element.hide();
    }

    if (element.is(':hidden')) {
      reply = $('div.reply', $('div.msg_body', $('#topic-' + topic_id)));
      reply.append(element);
      reply_to.attr('value', '0');
      element.slideDown('slow');
    } else {
      element.slideUp('slow');
    }
  }
}

$(document).ready(function() {
  element = $("#commentForm").parent();

  if (document.cookie.match(/JSESSIONID\=(\w+)\;?/)) {
    jsid = document.cookie.match(/JSESSIONID\=(\w+)\;?/);
    jsid = jsid[1];
  }

  $('div.reply').each(function() {
    $('a[href^=comment-message.jsp]', this).bind("click", function() {
      sh(0, 0);
      return false;
    });

    var lnk = $("a[href^=add_comment.jsp]", this);
    if (lnk.length>0) {
      var buff = lnk.attr('href').match(/\d+/g);
      var idr = buff[1];
      lnk.bind("click", function() {
        sh(1, idr);
        return false;
      });
    }
  });
});<commit_msg>addComment.js: предупреждаем о наличии данных в форме при уходе со странички не по submit<commit_after>var element = '';
var jsid = '';

function sh(type, id) {
  $("input[name='session']").attr('value', jsid);

  if (type == 1) {
    reply_to = $("input[name='replyto']", element);
    if (reply_to.attr('value') != id) {
      element.hide();
    }

    if (element.is(':hidden')) {
      reply = $('div.reply', $('div.msg_body', $('#comment-' + id)));
      reply.append(element);
      reply_to.attr('value', id);
      element.slideDown('slow');
    } else {
      element.slideUp('slow');
    }
  } else if (type == 0) {
    topic_id = $("input[name='topic']", element).attr('value');

    reply_to = $("input[name='replyto']", element);
    if (reply_to.attr('value') != 0) {
      element.hide();
    }

    if (element.is(':hidden')) {
      reply = $('div.reply', $('div.msg_body', $('#topic-' + topic_id)));
      reply.append(element);
      reply_to.attr('value', '0');
      element.slideDown('slow');
    } else {
      element.slideUp('slow');
    }
  }
}

$(document).ready(function() {
  element = $("#commentForm").parent();

  if (document.cookie.match(/JSESSIONID\=(\w+)\;?/)) {
    jsid = document.cookie.match(/JSESSIONID\=(\w+)\;?/);
    jsid = jsid[1];
  }

  $('div.reply').each(function() {
    $('a[href^=comment-message.jsp]', this).bind("click", function() {
      sh(0, 0);
      return false;
    });

    var lnk = $("a[href^=add_comment.jsp]", this);
    if (lnk.length>0) {
      var buff = lnk.attr('href').match(/\d+/g);
      var idr = buff[1];
      lnk.bind("click", function() {
        sh(1, idr);
        return false;
      });
    }
  });

  window.onbeforeunload = function() {
    if ($("#msg").val()!='') {
      return "Вы что-то напечатали в форме. Все введенные данные будут потеряны при закрытии страницы.";
    }
  };

  $("#commentForm").bind("submit", function() {
    window.onbeforeunload = null;
  });
});<|endoftext|>


<commit_before>var element = '';
var jsid = '';

function sh(type, id) {
  $("input[name='session']").attr('value', jsid);

  if (type == 1) {
    reply_to = $("input[name='replyto']", element);
    if (reply_to.attr('value') != id) {
      element.hide();
    }

    if (element.is(':hidden')) {
      reply = $('div.reply', $('div.msg_body', $('#comment-' + id)));
      reply.append(element);
      reply_to.attr('value', id);
      element.slideDown('slow');
    } else {
      element.slideUp('slow');
    }
  } else if (type == 0) {
    topic_id = $("input[name='topic']", element).attr('value');

    reply_to = $("input[name='replyto']", element);
    if (reply_to.attr('value') != 0) {
      element.hide();
    }

    if (element.is(':hidden')) {
      reply = $('div.reply', $('div.msg_body', $('#topic-' + topic_id)));
      reply.append(element);
      reply_to.attr('value', '0');
      element.slideDown('slow');
    } else {
      element.slideUp('slow');
    }
  }
}

$(document).ready(function() {
  element = $("#commentForm").parent();

  if (document.cookie.match(/JSESSIONID\=(\w+)\;?/)) {
    jsid = document.cookie.match(/JSESSIONID\=(\w+)\;?/);
    jsid = jsid[1];
  }

  $('div.reply').each(function() {
    $('a[href^=comment-message.jsp]', this).bind("click", function() {
      sh(0, 0);
      return false;
    });

    var lnk = $("a[href^=add_comment.jsp]", this);
    if (lnk.length>0) {
      var buff = lnk.attr('href').match(/\d+/g);
      var idr = buff[1];
      lnk.bind("click", function() {
        sh(1, idr);
        return false;
      });
    }
  });

  window.onbeforeunload = function() {
    if ($("#msg").val()!='') {
      return "Вы что-то напечатали в форме. Все введенные данные будут потеряны при закрытии страницы.";
    }
  };

  $("#commentForm").bind("submit", function() {
    window.onbeforeunload = null;
  });
});<commit_msg>addComment.js: не показываем предупреждение если форма не visible<commit_after>var element = '';
var jsid = '';

function sh(type, id) {
  $("input[name='session']").attr('value', jsid);

  if (type == 1) {
    reply_to = $("input[name='replyto']", element);
    if (reply_to.attr('value') != id) {
      element.hide();
    }

    if (element.is(':hidden')) {
      reply = $('div.reply', $('div.msg_body', $('#comment-' + id)));
      reply.append(element);
      reply_to.attr('value', id);
      element.slideDown('slow');
    } else {
      element.slideUp('slow');
    }
  } else if (type == 0) {
    topic_id = $("input[name='topic']", element).attr('value');

    reply_to = $("input[name='replyto']", element);
    if (reply_to.attr('value') != 0) {
      element.hide();
    }

    if (element.is(':hidden')) {
      reply = $('div.reply', $('div.msg_body', $('#topic-' + topic_id)));
      reply.append(element);
      reply_to.attr('value', '0');
      element.slideDown('slow');
    } else {
      element.slideUp('slow');
    }
  }
}

$(document).ready(function() {
  element = $("#commentForm").parent();

  if (document.cookie.match(/JSESSIONID\=(\w+)\;?/)) {
    jsid = document.cookie.match(/JSESSIONID\=(\w+)\;?/);
    jsid = jsid[1];
  }

  $('div.reply').each(function() {
    $('a[href^=comment-message.jsp]', this).bind("click", function() {
      sh(0, 0);
      return false;
    });

    var lnk = $("a[href^=add_comment.jsp]", this);
    if (lnk.length>0) {
      var buff = lnk.attr('href').match(/\d+/g);
      var idr = buff[1];
      lnk.bind("click", function() {
        sh(1, idr);
        return false;
      });
    }
  });

  window.onbeforeunload = function() {
    if ($("#msg").val()!='' && ! $("#commentForm").parent().is(":hidden")) {
      return "Вы что-то напечатали в форме. Все введенные данные будут потеряны при закрытии страницы.";
    }
  };

  $("#commentForm").bind("submit", function() {
    window.onbeforeunload = null;
  });
});<|endoftext|>


<commit_before>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/**
 * @fileOverview
 * Register framework(s) in JS runtime. Weex supply two layers for 3rd-party
 * framework(s): one is the instance management layer, another is the
 * virtual-DOM layer.
 */

import * as shared from '../shared'

import init from './api/init'
import config from './api/config'
import { register, unregister, has } from './api/service'

/* istanbul ignore next */
function freezePrototype () {
  shared.freezePrototype()

  Object.freeze(config.Element)
  Object.freeze(config.Comment)
  Object.freeze(config.Listener)
  Object.freeze(config.Document.prototype)
  Object.freeze(config.Element.prototype)
  Object.freeze(config.Comment.prototype)
  Object.freeze(config.Listener.prototype)
}

export default {
  setNativeConsole: shared.setNativeConsole,
  resetNativeConsole: shared.resetNativeConsole,
  setNativeTimer: shared.setNativeTimer,
  resetNativeTimer: shared.resetNativeTimer,
  service: { register, unregister, has },
  freezePrototype,
  init,
  config
}
<commit_msg>* [jsfm] stop freeze Element and Element.prototype<commit_after>/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

/**
 * @fileOverview
 * Register framework(s) in JS runtime. Weex supply two layers for 3rd-party
 * framework(s): one is the instance management layer, another is the
 * virtual-DOM layer.
 */

import * as shared from '../shared'

import init from './api/init'
import config from './api/config'
import { register, unregister, has } from './api/service'

/* istanbul ignore next */
function freezePrototype () {
  shared.freezePrototype()

  // Object.freeze(config.Element)
  Object.freeze(config.Comment)
  Object.freeze(config.Listener)
  Object.freeze(config.Document.prototype)
  // Object.freeze(config.Element.prototype)
  Object.freeze(config.Comment.prototype)
  Object.freeze(config.Listener.prototype)
}

export default {
  setNativeConsole: shared.setNativeConsole,
  resetNativeConsole: shared.resetNativeConsole,
  setNativeTimer: shared.setNativeTimer,
  resetNativeTimer: shared.resetNativeTimer,
  service: { register, unregister, has },
  freezePrototype,
  init,
  config
}
<|endoftext|>


<commit_before>//***********************************************
// Obfuscated by Javascript Obfuscator
// http://javascript-source.com
//***********************************************
function wowsliderPreloader(m,d){var f=jQuery,j=d.images,n=[],q="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7";function h(t,u){var i=new Image();if(u){f(i).bind("load error abort",function(v){if(v.type=="load"){u(t,i)}})}else{n[n.length]=i}i.src=t;return i}h(q);var p=0;function b(i,t){i=(j.length+i)%j.length;if(!j[i]["noimage"]){if(t){t();b(i<p?i-1:i+1);p=i}return 0}else{h(j[i].src,function(u){j[i].image.src=u;j[i].noimage=0;if(t){setTimeout(t,40);b(i<p?i-1:i+1);p=i}});return 1}}var r=f(" .ws_images ul",m);var g=r.find("li").length;var a=r.find("img").get(0).src;for(var o=0;o<j.length;o++){if(j[o]){if(o>=g){var c=f("
"+(j[o].href?'":"")+''+(j[o].href?"":"")+"
").appendTo(r);f("img",c).attr("title",j[o].title);c.data("descr",j[o].descr||"");j[o].image=f("img",c).get(0);j[o].noimage=1;if(/^\./.test(j[o].src)){j[o].src=a.substr(0,a.lastIndexOf("/"))+j[o].src.substr(1)}}}}r.css({width:j.length+"00%"});var k=f(" .ws_bullets>div",m);if(f("img",k).length){var a=k.find("img").get(0).src;k.find(">a").each(function(u,t){if(j[u]){t.href="#";if(!j[u].thumb){j[u].thumb=j[u].src.replace(/\/images\/([^\/]+)$/,"/tooltips/$1")}if(/^\./.test(j[u].thumb)){j[u].thumb=a.substr(0,a.lastIndexOf("/"))+j[u].thumb.substr(1)}if(!f("img",t).length){j[u].nottip=1;j[u].ttip=f('').appendTo(t).get(0)}}})}h(a,function(){b(1)});this.loadTtip=function(i){if(j[i].nottip){h(j[i].thumb,function(u){var t=j[i];t.ttip.src=u;t.nottip=0;f(t.ttip).removeClass("loading")})}};var e=f("

").hide().appendTo(m);var s;var l;this.load=function(i,t){l=t;if(!b(i,function(){if(l==t){clearTimeout(s);s=0;e.hide();t()}})){return}if(!s){s=setTimeout(function(){e.show()},300)}}};
<commit_msg>Delete wowsliderPreloader.js<commit_after><|endoftext|>


<commit_before>// Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation
// used for queues. This implementation assumes that the node provided by the user can be modified
// to adjust the next and last properties. We implement only the minimal functionality
// for queue support.
export default function DLL() {
    this.head = this.tail = null;
    this.length = 0;
}

function setInitial(dll, node) {
    dll.length = 1;
    dll.head = dll.tail = node;
}

DLL.prototype.removeLink = function(node) {
    if (!node) return node;
    if (node.prev) node.prev.next = node.next;
    else this.head = node.next
    if (node.next) node.next.prev = node.prev;
    else this.tail = node.prev;

    node.prev = node.next = null;
    this.length -= 1;
    return node;
}

DLL.prototype.empty = DLL;

DLL.prototype.insertAfter = function(node, newNode) {
    newNode.prev = node;
    newNode.next = node.next;
    if (node.next) node.next.prev = newNode;
    else this.tail = newNode;
    node.next = newNode;
    this.length += 1;
}

DLL.prototype.insertBefore = function(node, newNode) {
    newNode.prev = node.prev;
    newNode.next = node;
    if (node.prev) node.prev.next = newNode;
    else this.head = newNode;
    node.prev = newNode;
    this.length += 1;
}

DLL.prototype.unshift = function(node) {
    if (this.head) this.insertBefore(this.head, node);
    else setInitial(this, node);
};

DLL.prototype.push = function(node) {
    if (this.tail) this.insertAfter(this.tail, node);
    else setInitial(this, node);
};

DLL.prototype.shift = function() {
    return this.removeLink(this.head);
};

DLL.prototype.pop = function() {
    return this.removeLink(this.tail);
};
<commit_msg>Minor cleanup<commit_after>// Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation
// used for queues. This implementation assumes that the node provided by the user can be modified
// to adjust the next and last properties. We implement only the minimal functionality
// for queue support.
export default function DLL() {
    this.head = this.tail = null;
    this.length = 0;
}

function setInitial(dll, node) {
    dll.length = 1;
    dll.head = dll.tail = node;
}

DLL.prototype.removeLink = function(node) {
    if (node.prev) node.prev.next = node.next;
    else this.head = node.next
    if (node.next) node.next.prev = node.prev;
    else this.tail = node.prev;

    node.prev = node.next = null;
    this.length -= 1;
    return node;
}

DLL.prototype.empty = DLL;

DLL.prototype.insertAfter = function(node, newNode) {
    newNode.prev = node;
    newNode.next = node.next;
    if (node.next) node.next.prev = newNode;
    else this.tail = newNode;
    node.next = newNode;
    this.length += 1;
}

DLL.prototype.insertBefore = function(node, newNode) {
    newNode.prev = node.prev;
    newNode.next = node;
    if (node.prev) node.prev.next = newNode;
    else this.head = newNode;
    node.prev = newNode;
    this.length += 1;
}

DLL.prototype.unshift = function(node) {
    if (this.head) this.insertBefore(this.head, node);
    else setInitial(this, node);
};

DLL.prototype.push = function(node) {
    if (this.tail) this.insertAfter(this.tail, node);
    else setInitial(this, node);
};

DLL.prototype.shift = function() {
    return this.head && this.removeLink(this.head);
};

DLL.prototype.pop = function() {
    return this.tail && this.removeLink(this.tail);
};
<|endoftext|>


<commit_before>/*
    © 2015  Laetitia Gangloff, Acsone SA/NV (http://www.acsone.eu)
    License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
*/

openerp.pos_cagnotte_coupon = function (instance) {
    var _t = instance.web._t,
        _lt = instance.web._lt;
    var QWeb = instance.web.qweb;
    module = instance.point_of_sale;

    // add has_cagnotte flag on product to avoid merge on it
    var _initialize_ = module.PosModel.prototype.initialize;
    module.PosModel.prototype.initialize = function(session, attributes){
        self = this;
        // Add the load of the field product_product.has_cagnotte
        for (var i = 0 ; i < this.models.length; i++){
            if (this.models[i].model == 'product.product'){
                if (this.models[i].fields.indexOf('has_cagnotte') == -1) {
                    this.models[i].fields.push('has_cagnotte');
                }
            }
        }
        return _initialize_.call(this, session, attributes);
    };

    // Add information relative to cagnotte on order line
    var OrderlineParent = module.Orderline;
    module.Orderline = module.Orderline.extend({
        initialize: function(attributes, options) {
            OrderlineParent.prototype.initialize.apply(this, arguments);
            this.coupon_code = false;
        },
        // returns the flag has_cagnotte from product
        has_cagnotte: function(){
            return this.product.has_cagnotte;
        },
        // we do not merge line with cagnotte
        can_be_merged_with: function(orderline){
            if(this.has_cagnotte()){
                return false;
            }else{
                return OrderlineParent.prototype.can_be_merged_with.apply(this, arguments);
            }
        },
        // Generates a public identification number for the coupon.
        generateUniqueId: function(base) {
            var d = new Date().getTime();
            if(window.performance && typeof window.performance.now === "function"){
                d += performance.now(); //use high-precision timer if available
            }
            var uuid = 'xxxxxxxxxxxx'.replace(/[x]/g, function(c) {
                var r = (d + Math.random()*10)%10 | 0;
                d = Math.floor(d/10);
                return (r).toString(10);
            });
            return uuid + base;
        },
        // returns the coupon on this orderline
        get_coupon_code: function(){
            if(this.has_cagnotte()){
                if(this.has_cagnotte()){
                    if(! this.coupon_code){
                        this.coupon_code = this.generateUniqueId(this.pos.pos_session.id);
                    }
                    return this.coupon_code;
                }else{
                    return false;
                }
            }
        },
        export_as_JSON: function(){
            var json = OrderlineParent.prototype.export_as_JSON.apply(this,arguments);
            json.coupon_code = this.get_coupon_code();
            return json;
        },
    });

    // Add information relative to cagnotte on payment line
    var PaymentlineParent = module.Paymentline;
    module.Paymentline = module.Paymentline.extend({
        initialize: function(attributes, options) {
            PaymentlineParent.prototype.initialize.apply(this, arguments);
            this.account_cagnotte_id = false;
            this.solde_cagnotte = 0;
        },
        //sets the account_cagnotte_id on this payment line
        set_coupon: function(coupon){
            this.account_cagnotte_id = coupon.id;
            this.solde_cagnotte = coupon.solde_cagnotte;
            if (coupon.solde_cagnotte <= 0){
                coupon.solde_cagnotte = this.get_amount();
            }
            this.set_amount(Math.min(coupon.solde_cagnotte, this.get_amount()));
        },
        // returns the coupon on this paymentline
        get_coupon: function(){
            return this.account_cagnotte_id;
        },
        get_solde_cagnotte: function(){
            return this.solde_cagnotte;
        },
        // returns the flag has_cagnotte from journal
        has_cagnotte: function(){
            return this.cashregister.journal.has_cagnotte
        },
        // returns the flag has_cagnotte from journal
        check_cagnotte_amount: function(){
            return this.cashregister.journal.check_cagnotte_amount
        },
        export_as_JSON: function(){
            var json = PaymentlineParent.prototype.export_as_JSON.apply(this,arguments);
            json.account_cagnotte_id = this.get_coupon();
            return json;
        },
    });

    module.PaymentScreenWidget.include({
        // Add behaviour on Set coupon Code button on payment line
        render_paymentline: function(line){
            el_node = this._super(line);
            var self = this;
            if (line.cashregister.journal.has_cagnotte){
                el_node.querySelector('.set-coupon-code')
                    .addEventListener('click', function(){
                        self.pos.pos_widget.screen_selector.show_popup('set-coupon-code-popup', line);});
                }
            return el_node;
        },
        // Re-check coupon usage
        validate_order: function(options) {
            var self = this;
            var cagnotte_not_ok = false;

            var currentOrder = this.pos.get('selectedOrder');
            var plines = currentOrder.get('paymentLines').models;
            for (var i = 0; i < plines.length; i++) {
                // check cagnotte have coupon attached
                if (plines[i].has_cagnotte()){
                    if (! plines[i].get_coupon()) {
                        this.pos_widget.screen_selector.show_popup('error',{
                            'message': _t('Cagnotte without coupon'),
                            'comment': _t('You cannot use cagnotte without a coupon.'),
                        });
                        return;
                    }
                    if (plines[i].check_cagnotte_amount()){
                        if (plines[i].get_amount() > plines[i].get_solde_cagnotte()) {
                            this.pos_widget.screen_selector.show_popup('error',{
                                'message': _t('Cagnotte with too big amount'),
                                'comment': _t('You cannot use cagnotte with amount too big.'),
                            });
                            return;
                        }
                    }
                }
            }
            this._super(options);
        },
    });

    module.PosWidget = module.PosWidget.extend({
        /* Overload Section */
        build_widgets: function(){
            this._super();
            this.set_coupon_code_popup = new module.SetCouponCodeWidget(this, {});
            this.set_coupon_code_popup.appendTo($(this.$el));
            this.screen_selector.popup_set['set-coupon-code-popup'] = this.set_coupon_code_popup;
            // Hide the popup because all pop up are displayed at the
            // beginning by default
            this.set_coupon_code_popup.hide();
        },
    });

    module.SetCouponCodeWidget = module.PopUpWidget.extend({
        template:'SetCouponCodeWidget',
        initialize: function() {
            this.line = false;
        },
        start: function(){
            var self = this;

            // Add behaviour on Cancel Button
            this.$('#coupon-popup-cancel').off('click').click(function(){
                this.parentElement.parentElement.children[1].value = null;
                self.hide();
            });
            // Add behaviour on Validate Button
            this.$('#coupon-popup-ok').off('click').click(function(){
                var input_coupon = this.parentElement.parentElement.children[1];
                var coupon_code = this.parentElement.parentElement.children[1].value;
                var Cagnotte = new openerp.Model('account.cagnotte');
                var currentOrder = self.pos.get('selectedOrder');
                var client_id = false;
                if (currentOrder.get_client()){
                    client_id = currentOrder.get_client().id;
                }
                Cagnotte.query(['solde_cagnotte']).
                    filter([['coupon_code','=',coupon_code],
                            ['cagnotte_type_id.journal_id', '=', self.line.cashregister.journal_id[0]],
                            '|', ['cagnotte_type_id.check_cagnotte_amount', '=', false], ['solde_cagnotte', '>', 0],
                            '|', ['partner_id', '=', false], ['partner_id', '=', client_id]]).
                    first().then(function (coupon) {
                        if(coupon){
                            var line = self.line;
                            if(line){
                                line.set_coupon(coupon);
                                line.node.querySelector('input').value = line.amount.toFixed(self.pos.currency.decimals);
                            }
                            input_coupon.value = null;
                            self.hide();
                        }else{
                            self.pos_widget.screen_selector.show_popup('error',{
                                'message': _t('Coupon not usable'),
                                'comment': _t('The coupon code ' + coupon_code + ' is not usable' +
                                              '. Check payment method : ' + self.line.cashregister.journal_id[1] +
                                              '. Check customer'),
                            });
                        return;
                        }
                }, function (err, event) {
                    event.preventDefault();
                    self.pos_widget.screen_selector.show_popup('error',{
                        message: _t('Impossible to check coupon'),
                        comment: _t('Check your internet connection and try again.'),
                    });
                });
            });
        },
        show: function(line){
            var self = this;
            this.line = line;
            this._super();
        },
    });

};
<commit_msg>pos_cagnotte_coupon : use pos decimal when set solde cagnotte<commit_after>/*
    © 2015  Laetitia Gangloff, Acsone SA/NV (http://www.acsone.eu)
    License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
*/

openerp.pos_cagnotte_coupon = function (instance) {
    var _t = instance.web._t,
        _lt = instance.web._lt;
    var QWeb = instance.web.qweb;
    module = instance.point_of_sale;

    // add has_cagnotte flag on product to avoid merge on it
    var _initialize_ = module.PosModel.prototype.initialize;
    module.PosModel.prototype.initialize = function(session, attributes){
        self = this;
        // Add the load of the field product_product.has_cagnotte
        for (var i = 0 ; i < this.models.length; i++){
            if (this.models[i].model == 'product.product'){
                if (this.models[i].fields.indexOf('has_cagnotte') == -1) {
                    this.models[i].fields.push('has_cagnotte');
                }
            }
        }
        return _initialize_.call(this, session, attributes);
    };

    // Add information relative to cagnotte on order line
    var OrderlineParent = module.Orderline;
    module.Orderline = module.Orderline.extend({
        initialize: function(attributes, options) {
            OrderlineParent.prototype.initialize.apply(this, arguments);
            this.coupon_code = false;
        },
        // returns the flag has_cagnotte from product
        has_cagnotte: function(){
            return this.product.has_cagnotte;
        },
        // we do not merge line with cagnotte
        can_be_merged_with: function(orderline){
            if(this.has_cagnotte()){
                return false;
            }else{
                return OrderlineParent.prototype.can_be_merged_with.apply(this, arguments);
            }
        },
        // Generates a public identification number for the coupon.
        generateUniqueId: function(base) {
            var d = new Date().getTime();
            if(window.performance && typeof window.performance.now === "function"){
                d += performance.now(); //use high-precision timer if available
            }
            var uuid = 'xxxxxxxxxxxx'.replace(/[x]/g, function(c) {
                var r = (d + Math.random()*10)%10 | 0;
                d = Math.floor(d/10);
                return (r).toString(10);
            });
            return uuid + base;
        },
        // returns the coupon on this orderline
        get_coupon_code: function(){
            if(this.has_cagnotte()){
                if(this.has_cagnotte()){
                    if(! this.coupon_code){
                        this.coupon_code = this.generateUniqueId(this.pos.pos_session.id);
                    }
                    return this.coupon_code;
                }else{
                    return false;
                }
            }
        },
        export_as_JSON: function(){
            var json = OrderlineParent.prototype.export_as_JSON.apply(this,arguments);
            json.coupon_code = this.get_coupon_code();
            return json;
        },
    });

    // Add information relative to cagnotte on payment line
    var PaymentlineParent = module.Paymentline;
    module.Paymentline = module.Paymentline.extend({
        initialize: function(attributes, options) {
            PaymentlineParent.prototype.initialize.apply(this, arguments);
            this.account_cagnotte_id = false;
            this.solde_cagnotte = 0;
        },
        //sets the account_cagnotte_id on this payment line
        set_coupon: function(coupon){
            this.account_cagnotte_id = coupon.id;
            this.solde_cagnotte = coupon.solde_cagnotte.toFixed(this.pos.currency.decimals);
            if (coupon.solde_cagnotte <= 0){
                coupon.solde_cagnotte = this.toFixed(this.pos.currency.decimals);
            }
            this.set_amount(Math.min(coupon.solde_cagnotte, this.get_amount()));
        },
        // returns the coupon on this paymentline
        get_coupon: function(){
            return this.account_cagnotte_id;
        },
        get_solde_cagnotte: function(){
            return this.solde_cagnotte;
        },
        // returns the flag has_cagnotte from journal
        has_cagnotte: function(){
            return this.cashregister.journal.has_cagnotte
        },
        // returns the flag has_cagnotte from journal
        check_cagnotte_amount: function(){
            return this.cashregister.journal.check_cagnotte_amount
        },
        export_as_JSON: function(){
            var json = PaymentlineParent.prototype.export_as_JSON.apply(this,arguments);
            json.account_cagnotte_id = this.get_coupon();
            return json;
        },
    });

    module.PaymentScreenWidget.include({
        // Add behaviour on Set coupon Code button on payment line
        render_paymentline: function(line){
            el_node = this._super(line);
            var self = this;
            if (line.cashregister.journal.has_cagnotte){
                el_node.querySelector('.set-coupon-code')
                    .addEventListener('click', function(){
                        self.pos.pos_widget.screen_selector.show_popup('set-coupon-code-popup', line);});
                }
            return el_node;
        },
        // Re-check coupon usage
        validate_order: function(options) {
            var self = this;
            var cagnotte_not_ok = false;

            var currentOrder = this.pos.get('selectedOrder');
            var plines = currentOrder.get('paymentLines').models;
            for (var i = 0; i < plines.length; i++) {
                // check cagnotte have coupon attached
                if (plines[i].has_cagnotte()){
                    if (! plines[i].get_coupon()) {
                        this.pos_widget.screen_selector.show_popup('error',{
                            'message': _t('Cagnotte without coupon'),
                            'comment': _t('You cannot use cagnotte without a coupon.'),
                        });
                        return;
                    }
                    if (plines[i].check_cagnotte_amount()){
                        if (plines[i].get_amount() > plines[i].get_solde_cagnotte()) {
                            this.pos_widget.screen_selector.show_popup('error',{
                                'message': _t('Cagnotte with too big amount'),
                                'comment': _t('You cannot use cagnotte with amount too big.'),
                            });
                            return;
                        }
                    }
                }
            }
            this._super(options);
        },
    });

    module.PosWidget = module.PosWidget.extend({
        /* Overload Section */
        build_widgets: function(){
            this._super();
            this.set_coupon_code_popup = new module.SetCouponCodeWidget(this, {});
            this.set_coupon_code_popup.appendTo($(this.$el));
            this.screen_selector.popup_set['set-coupon-code-popup'] = this.set_coupon_code_popup;
            // Hide the popup because all pop up are displayed at the
            // beginning by default
            this.set_coupon_code_popup.hide();
        },
    });

    module.SetCouponCodeWidget = module.PopUpWidget.extend({
        template:'SetCouponCodeWidget',
        initialize: function() {
            this.line = false;
        },
        start: function(){
            var self = this;

            // Add behaviour on Cancel Button
            this.$('#coupon-popup-cancel').off('click').click(function(){
                this.parentElement.parentElement.children[1].value = null;
                self.hide();
            });
            // Add behaviour on Validate Button
            this.$('#coupon-popup-ok').off('click').click(function(){
                var input_coupon = this.parentElement.parentElement.children[1];
                var coupon_code = this.parentElement.parentElement.children[1].value;
                var Cagnotte = new openerp.Model('account.cagnotte');
                var currentOrder = self.pos.get('selectedOrder');
                var client_id = false;
                if (currentOrder.get_client()){
                    client_id = currentOrder.get_client().id;
                }
                Cagnotte.query(['solde_cagnotte']).
                    filter([['coupon_code','=',coupon_code],
                            ['cagnotte_type_id.journal_id', '=', self.line.cashregister.journal_id[0]],
                            '|', ['cagnotte_type_id.check_cagnotte_amount', '=', false], ['solde_cagnotte', '>', 0],
                            '|', ['partner_id', '=', false], ['partner_id', '=', client_id]]).
                    first().then(function (coupon) {
                        if(coupon){
                            var line = self.line;
                            if(line){
                                line.set_coupon(coupon);
                                line.node.querySelector('input').value = line.amount.toFixed(self.pos.currency.decimals);
                            }
                            input_coupon.value = null;
                            self.hide();
                        }else{
                            self.pos_widget.screen_selector.show_popup('error',{
                                'message': _t('Coupon not usable'),
                                'comment': _t('The coupon code ' + coupon_code + ' is not usable' +
                                              '. Check payment method : ' + self.line.cashregister.journal_id[1] +
                                              '. Check customer'),
                            });
                        return;
                        }
                }, function (err, event) {
                    event.preventDefault();
                    self.pos_widget.screen_selector.show_popup('error',{
                        message: _t('Impossible to check coupon'),
                        comment: _t('Check your internet connection and try again.'),
                    });
                });
            });
        },
        show: function(line){
            var self = this;
            this.line = line;
            this._super();
        },
    });

};
<|endoftext|>


<commit_before>'use strict';
class RenderingContext {
  constructor( id ) {
    const canvas = document.getElementById( id );
    this.canvas = canvas;
    this.gl = canvas.getContext( 'webgl' ) ||
                canvas.getContext( 'experimental-webgl' );
  }

  createProgram( ids ) {
    let gl      = this.gl;
    let program = gl.createProgram();

    ids.forEach( ( id ) => {
      gl.attachShader( program, this.createShader( id ) );
    } );

    gl.linkProgram( program );

    if ( !gl.getProgramParameter( program, gl.LINK_STATUS ) ) {
      console.error( gl.getProgramInfoLog( program ) );
    }

    return program;
  }

  useProgram( program ) {
    this.gl.useProgram( program );
  }

  createShader( id ) {
    let gl     = this.gl;
    let source = document.getElementById( id );
    let shader;

    switch ( source.type ) {
    case 'x-shader/x-vertex':
      shader = gl.createShader( gl.VERTEX_SHADER );
      break;
    case 'x-shader/x-fragment':
      shader = gl.createShader( gl.FRAGMENT_SHADER );
      break;
    default :
      console.error( 'The shader type is not an accepted value.' );
    }

    gl.shaderSource( shader, source.text );
    gl.compileShader( shader );

    if ( !gl.getShaderParameter( shader, gl.COMPILE_STATUS ) ) {
      console.error( gl.getShaderInfoLog( shader ) );
    }

    return shader;
  }

  bindFramebuffer( frameBuffer ) {
    this.gl.bindFramebuffer( this.gl.FRAMEBUFFER, frameBuffer );
  }

  createFrameBuffer( width, height ) {
    let gl = this.gl;
    let frameBuffer = gl.createFramebuffer();

    gl.bindFramebuffer( gl.FRAMEBUFFER, frameBuffer);

    let renderBuffer = gl.createRenderbuffer();
    gl.bindRenderbuffer( gl.RENDERBUFFER, renderBuffer );

    gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height );
    gl.framebufferRenderbuffer(
      gl.FRAMEBUFFER,
      gl.DEPTH_ATTACHMENT,
      gl.RENDERBUFFER,
      renderBuffer
    );

    let texture = this.createFrameBufferTexture( width, height );
    gl.bindRenderbuffer( gl.RENDERBUFFER, null );
    gl.bindFramebuffer( gl.FRAMEBUFFER, null );

    return {value : frameBuffer, renderbuffer : renderBuffer, texture : texture};
  }

  createFrameBufferTexture( width, height ) {
    let gl = this.gl;
    let texture = gl.createTexture();
    gl.bindTexture( gl.TEXTURE_2D, texture );

    gl.texImage2D(
      gl.TEXTURE_2D,
      0,
      gl.RGBA,
      width,
      height,
      0,
      gl.RGBA,
      gl.UNSIGNED_BYTE,
      null);

    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR );
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR );

    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT );
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT );
    gl.framebufferTexture2D(
      gl.FRAMEBUFFER,
      gl.COLOR_ATTACHMENT0,
      gl.TEXTURE_2D,
      texture,
      0
    );

    gl.bindTexture( gl.TEXTURE_2D, null );

    return texture;
  }

  bindVbos( program, vboAttribs ) {
    vboAttribs.forEach( ( vboAttrib ) => {
      this.bindVbo( program, vboAttrib );
    });
  }

  bindVbo( program, vboAttrib ) {
    let gl       = this.gl;
    let location = gl.getAttribLocation( program, vboAttrib.name );
    gl.bindBuffer( gl.ARRAY_BUFFER, this.createVbo( vboAttrib.value ) );
    gl.enableVertexAttribArray( location );
    gl.vertexAttribPointer( location, vboAttrib.stride, gl.FLOAT, false, 0, 0 );
  }

  createVbo( value ) {
    let gl  = this.gl;
    let vbo = gl.createBuffer();
    gl.bindBuffer( gl.ARRAY_BUFFER, vbo );
    gl.bufferData( gl.ARRAY_BUFFER, new Float32Array( value ), gl.STATIC_DRAW );
    gl.bindBuffer( gl.ARRAY_BUFFER, null );
    return vbo;
  }

  bindIbo( indexes ) {
    let gl  = this.gl;
    let ibo = gl.createBuffer();
    gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, ibo );
    gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, new Int16Array( indexes ), gl.STATIC_DRAW );
    gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
    gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, ibo );
  }

  enable( cap ) {
    this.gl.enable( cap );
  }

  disable( cap ) {
    this.gl.disable( cap );
  }

  depthFunc( type ) {
    this.gl.depthFunc( type );
  }

  bindUniforms( uniformAttribs ) {
    uniformAttribs.forEach( ( uniformAttrib ) =>
                            this.bindUniform( uniformAttrib.name,
                                              uniformAttrib.type,
                                              uniformAttrib.value ) );
  }

  bindUniform( name, type, value ) {
    let gl = this.gl;
    let location = gl.getUniformLocation( this.program, name );

    switch ( type ) {
    case 'matrix4fv':
      gl.uniformMatrix4fv( location, false, value );
      break;
    case '4fv':
      gl.uniform4fv( location, value );
      break;
    case '3fv':
      gl.uniform3fv( location, value );
      break;
    case '2fv':
      gl.uniform2fv( location, value );
      break;
    case '1fv':
      gl.uniform1fv( location, value );
      break;
    case '1f':
      gl.uniform1f( location, value );
      break;
    case '1iv':
      gl.uniform1iv( location, value );
      break;
    case '1i':
      gl.uniform1i( location, value );
      break;
    default:
    }
  }

  clear( color, depth ) {
    let gl = this.gl;
    let flag = gl.COLOR_BUFFER_BIT;

    gl.clearColor( color.r, color.g, color.b, color.a );

    if ( depth ) {
      gl.clearDepth( depth );
      flag = flag | gl.DEPTH_BUFFER_BIT;
    }

    gl.clear( flag );
  }

  viewport( viewport ) {
    this.gl.viewport(
      viewport.x,
      viewport.y,
      viewport.width,
      viewport.height);
  }

  drawArrays( mode, count, first = 0 ) {
    let gl = this.gl;
    gl.drawArrays( mode, first, count );
  }

  drawElements( mode, count, offset = 0 ) {
    let gl = this.gl;
    gl.drawElements( mode, count, gl.UNSIGNED_SHORT, offset );
  }
}

export {RenderingContext};
<commit_msg>:art: Improve usability for culling and depth test.<commit_after>'use strict';
class RenderingContext {
  constructor( id ) {
    const canvas = document.getElementById( id );
    this.canvas = canvas;
    this.gl = canvas.getContext( 'webgl' ) ||
                canvas.getContext( 'experimental-webgl' );
  }

  createProgram( ids ) {
    let gl      = this.gl;
    let program = gl.createProgram();

    ids.forEach( ( id ) => {
      gl.attachShader( program, this.createShader( id ) );
    } );

    gl.linkProgram( program );

    if ( !gl.getProgramParameter( program, gl.LINK_STATUS ) ) {
      console.error( gl.getProgramInfoLog( program ) );
    }

    return program;
  }

  useProgram( program ) {
    this.gl.useProgram( program );
  }

  createShader( id ) {
    let gl     = this.gl;
    let source = document.getElementById( id );
    let shader;

    switch ( source.type ) {
    case 'x-shader/x-vertex':
      shader = gl.createShader( gl.VERTEX_SHADER );
      break;
    case 'x-shader/x-fragment':
      shader = gl.createShader( gl.FRAGMENT_SHADER );
      break;
    default :
      console.error( 'The shader type is not an accepted value.' );
    }

    gl.shaderSource( shader, source.text );
    gl.compileShader( shader );

    if ( !gl.getShaderParameter( shader, gl.COMPILE_STATUS ) ) {
      console.error( gl.getShaderInfoLog( shader ) );
    }

    return shader;
  }

  bindFramebuffer( frameBuffer ) {
    this.gl.bindFramebuffer( this.gl.FRAMEBUFFER, frameBuffer );
  }

  createFrameBuffer( width, height ) {
    let gl = this.gl;
    let frameBuffer = gl.createFramebuffer();

    gl.bindFramebuffer( gl.FRAMEBUFFER, frameBuffer);

    let renderBuffer = gl.createRenderbuffer();
    gl.bindRenderbuffer( gl.RENDERBUFFER, renderBuffer );

    gl.renderbufferStorage( gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height );
    gl.framebufferRenderbuffer(
      gl.FRAMEBUFFER,
      gl.DEPTH_ATTACHMENT,
      gl.RENDERBUFFER,
      renderBuffer
    );

    let texture = this.createFrameBufferTexture( width, height );
    gl.bindRenderbuffer( gl.RENDERBUFFER, null );
    gl.bindFramebuffer( gl.FRAMEBUFFER, null );

    return {value : frameBuffer, renderbuffer : renderBuffer, texture : texture};
  }

  createFrameBufferTexture( width, height ) {
    let gl = this.gl;
    let texture = gl.createTexture();
    gl.bindTexture( gl.TEXTURE_2D, texture );

    gl.texImage2D(
      gl.TEXTURE_2D,
      0,
      gl.RGBA,
      width,
      height,
      0,
      gl.RGBA,
      gl.UNSIGNED_BYTE,
      null);

    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR );
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR );

    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT );
    gl.texParameteri( gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT );
    gl.framebufferTexture2D(
      gl.FRAMEBUFFER,
      gl.COLOR_ATTACHMENT0,
      gl.TEXTURE_2D,
      texture,
      0
    );

    gl.bindTexture( gl.TEXTURE_2D, null );

    return texture;
  }

  bindVbos( program, vboAttribs ) {
    vboAttribs.forEach( ( vboAttrib ) => {
      this.bindVbo( program, vboAttrib );
    });
  }

  bindVbo( program, vboAttrib ) {
    let gl       = this.gl;
    let location = gl.getAttribLocation( program, vboAttrib.name );
    gl.bindBuffer( gl.ARRAY_BUFFER, this.createVbo( vboAttrib.value ) );
    gl.enableVertexAttribArray( location );
    gl.vertexAttribPointer( location, vboAttrib.stride, gl.FLOAT, false, 0, 0 );
  }

  createVbo( value ) {
    let gl  = this.gl;
    let vbo = gl.createBuffer();
    gl.bindBuffer( gl.ARRAY_BUFFER, vbo );
    gl.bufferData( gl.ARRAY_BUFFER, new Float32Array( value ), gl.STATIC_DRAW );
    gl.bindBuffer( gl.ARRAY_BUFFER, null );
    return vbo;
  }

  bindIbo( indexes ) {
    let gl  = this.gl;
    let ibo = gl.createBuffer();
    gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, ibo );
    gl.bufferData( gl.ELEMENT_ARRAY_BUFFER, new Int16Array( indexes ), gl.STATIC_DRAW );
    gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, null );
    gl.bindBuffer( gl.ELEMENT_ARRAY_BUFFER, ibo );
  }

  enable( cap ) {
    this.gl.enable( cap );
  }

  disable( cap ) {
    this.gl.disable( cap );
  }

  toggleCulFace( enable ) {
    let gl = this.gl;
    if ( enable ) {
      gl.enable( gl.CULL_FACE );
    } else {
      gl.disable( gl.CULL_FACE );
    }
  }

  toggleDepthFunc( enable ) {
    let gl = this.gl;
    if ( enable ) {
      gl.enable( gl.DEPTH_TEST );
    } else {
      gl.disable( gl.DEPTH_TEST );
    }
  }

  depthFunc() {
    let gl = this.gl;
    gl.depthFunc( gl.LEQUAL );
  }

  bindUniforms( program, uniformAttribs ) {
    uniformAttribs.forEach( ( uniformAttrib ) => {
      this.bindUniform( program, uniformAttrib );
    });
  }

  bindUniform( program, uniformAttrib ) {
    let gl = this.gl;
    let {name, type, value} = uniformAttrib;
    let location = gl.getUniformLocation( program, name );

    switch ( type ) {
    case 'matrix4fv':
      gl.uniformMatrix4fv( location, false, value );
      break;
    case '4fv':
      gl.uniform4fv( location, value );
      break;
    case '3fv':
      gl.uniform3fv( location, value );
      break;
    case '2fv':
      gl.uniform2fv( location, value );
      break;
    case '1fv':
      gl.uniform1fv( location, value );
      break;
    case '1f':
      gl.uniform1f( location, value );
      break;
    case '1iv':
      gl.uniform1iv( location, value );
      break;
    case '1i':
      gl.uniform1i( location, value );
      break;
    default:
    }
  }

  clear( color, depth ) {
    let gl = this.gl;
    let flag = gl.COLOR_BUFFER_BIT;

    gl.clearColor( color.r, color.g, color.b, color.a );

    if ( depth ) {
      gl.clearDepth( depth );
      flag = flag | gl.DEPTH_BUFFER_BIT;
    }

    gl.clear( flag );
  }

  viewport( viewport ) {
    this.gl.viewport(
      viewport.x,
      viewport.y,
      viewport.width,
      viewport.height);
  }

  drawArrays( mode, count, first = 0 ) {
    let gl = this.gl;
    gl.drawArrays( mode, first, count );
  }

  drawElements( mode, count, offset = 0 ) {
    let gl = this.gl;
    gl.drawElements( mode, count, gl.UNSIGNED_SHORT, offset );
  }
}

export {RenderingContext};
<|endoftext|>


<commit_before>'use strict';

const logger = require('heroku-logger');

function parseRetryCount(req) {
  const retryCountFromHeader = Number(req.get('x-blink-retry-count')) || 0;
  const retryCountFromQuery = Number(req.query['x-blink-retry-count']) || 0;
  const retryCount = retryCountFromHeader || retryCountFromQuery || 0;

  if (retryCount) {
    req.metadata.retryCount = retryCount;
    logger.info('Blink retry count', { retryCount });
  }
}

function parseRequestId(req) {
  const requestIdFromHeader = req.get('x-request-id');
  const requestIdFromQuery = req.query['x-request-id'];
  const requestId = requestIdFromHeader || requestIdFromQuery;

  if (requestId) {
    req.metadata.requestId = requestId;
    logger.info('Request ID', { requestId });
  }
}

function registerIsARetryRequestFunction(req) {
  req.isARetryRequest = () => !!req.metadata.retryCount;
}

/**
 * parseMetadata - Here we parse global properties. All requests to Conversations API will run
 * through this middleware. Most parsing should be done at the specific route's middleware.
 * You should have a good reason to parse it here.
 *
 * @return {type}  description
 */
module.exports = function parseMetadata() {
  return (req, res, next) => {
    req.metadata = {};
    // This is being defined at the global level to support attachments for all routes.
    req.attachments = {
      inbound: [],
      outbound: [],
    };
    parseRetryCount(req);
    parseRequestId(req);
    registerIsARetryRequestFunction(req);
    return next();
  };
};
<commit_msg>set X-Request-Id on each request to Convo API<commit_after>'use strict';

const logger = require('heroku-logger');

function parseRetryCount(req) {
  const retryCountFromHeader = Number(req.get('x-blink-retry-count')) || 0;
  const retryCountFromQuery = Number(req.query['x-blink-retry-count']) || 0;
  const retryCount = retryCountFromHeader || retryCountFromQuery || 0;

  if (retryCount) {
    req.metadata.retryCount = retryCount;
    logger.info('Blink retry count', { retryCount });
  }
}

function parseRequestId(req, res) {
  const requestIdFromHeader = req.get('x-request-id');
  const requestIdFromQuery = req.query['x-request-id'];
  const requestId = requestIdFromHeader || requestIdFromQuery;

  if (requestId) {
    req.metadata.requestId = requestId;
    res.set('X-Request-Id', requestId);
    logger.info('Request ID', { requestId });
  }
}

function registerIsARetryRequestFunction(req) {
  req.isARetryRequest = () => !!req.metadata.retryCount;
}

/**
 * parseMetadata - Here we parse global properties. All requests to Conversations API will run
 * through this middleware. Most parsing should be done at the specific route's middleware.
 * You should have a good reason to parse it here.
 *
 * @return {type}  description
 */
module.exports = function parseMetadata() {
  return (req, res, next) => {
    req.metadata = {};
    // This is being defined at the global level to support attachments for all routes.
    req.attachments = {
      inbound: [],
      outbound: [],
    };
    parseRetryCount(req);
    parseRequestId(req, res);
    registerIsARetryRequestFunction(req);
    return next();
  };
};
<|endoftext|>