"use strict";
cc._RF.push(module, '1c26dVSok5E7o2PwD2sGBJa', 'Game');
// Script/Game.ts

"use strict";
// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html
var __extends = (this && this.__extends) || (function () {
    var extendStatics = function (d, b) {
        extendStatics = Object.setPrototypeOf ||
            ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
            function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
        return extendStatics(d, b);
    };
    return function (d, b) {
        extendStatics(d, b);
        function __() { this.constructor = d; }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };
})();
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
Object.defineProperty(exports, "__esModule", { value: true });
var DrawingBoard_1 = require("./DrawingBoard");
var _a = cc._decorator, ccclass = _a.ccclass, property = _a.property;
var GameState;
(function (GameState) {
    GameState[GameState["drawing"] = 1] = "drawing";
    GameState[GameState["erasing"] = 2] = "erasing";
})(GameState || (GameState = {}));
var Game = /** @class */ (function (_super) {
    __extends(Game, _super);
    function Game() {
        var _this = _super !== null && _super.apply(this, arguments) || this;
        _this.drawNode = null;
        _this.captureCamera = null;
        _this.mainCamera = null;
        _this.db = null;
        _this.gameState = GameState.drawing;
        _this.texture = null;
        _this.prePos = cc.Vec2.ZERO;
        _this.startPos = cc.Vec2.ZERO;
        _this.lastColor = cc.Color.BLUE;
        _this.errColor = cc.Color.RED;
        _this.lastLineWidth = 1;
        _this.history = [];
        _this.touchId = -1;
        _this.touchScale = false;
        return _this;
    }
    Game.prototype.start = function () {
        var _this = this;
        this.initDb();
        this.initTexture();
        this.initRead();
        setTimeout(function () {
            _this.drawNode.on("touchstart", _this.onTouchStart, _this);
            _this.drawNode.on("touchmove", _this.onTouchMove, _this);
            _this.drawNode.on("touchend", _this.onTouchEnd, _this);
            _this.drawNode.on("touchcancel", _this.onTouchEnd, _this);
        }, 2000);
    };
    Game.prototype.initDb = function () {
        //创建一个画板(需传入画板尺寸，将自动初始化)
        this.db = new DrawingBoard_1.default(this.drawNode.width, this.drawNode.height);
        //设置画板的绘图颜色（每次绘制前都可以重新设置）
        this.lastLineWidth = 15;
        this.db.setLineWidth(this.lastLineWidth);
        // this.db.setColor(this.lastColor.r, this.lastColor.g, this.lastColor.b, this.lastColor.a);
        //线条端点以圆角结尾
        this.db.setLineCircleEnd(true);
    };
    Game.prototype.initTexture = function () {
        this.texture = new cc.RenderTexture();
        this.texture.initWithSize(this.drawNode.width, this.drawNode.height, cc.RenderTexture.DepthStencilFormat.RB_FMT_S8);
        var spf = new cc.SpriteFrame(this.texture);
        this.drawNode.getComponent(cc.Sprite).spriteFrame = spf;
    };
    Game.prototype.initRead = function () {
        this.targetCamera = this.node.getChildByName("tagCamera").getComponent(cc.Camera);
        var rander = new cc.RenderTexture();
        rander.initWithSize(this.node.width, this.node.height, cc.RenderTexture.DepthStencilFormat.RB_FMT_S8);
        this.targetCamera.targetTexture = rander;
        this.targetCamera.render();
        console.log("完成");
    };
    Game.prototype.onTouchStart = function (e) {
        //将触摸位置作为线条的起点
        //画板中使用的坐标系，与图片坐标系一样，原点在左上角，X轴向右为正，Y轴向下为正
        //所以Y轴坐标应反过来, 这里用getLocationInView而不是getLocation
        this.touchId = e.getID();
        if (this.touchId == 1) {
            this.touchScale = true;
            return;
        }
        var pos = e.getLocation();
        this.prePos = this.convertToDrawNodePos(pos);
        this.startPos = this.convertToDrawNodePos(pos);
        this.db.moveTo(this.prePos.x, this.prePos.y);
    };
    Game.prototype.onTouchMove = function (e) {
        var touches = e.getTouches();
        var touch1 = touches[0];
        var delta1 = touch1.getDelta();
        var pos = e.getLocation();
        var pos1 = this.convertToDrawNodePos(touch1.getLocation());
        var dst = this.startPos.sub(pos1).mag();
        // this.label.string = touches.length + "";
        if (touches.length == 1 && this.touchId < 1 && !this.touchScale && dst > 7) {
            // alert("不该进来");
            this.prePos = this.convertToDrawNodePos(pos);
            var jg = this.pd(e);
            this.changeColor(jg);
            if (this.gameState == GameState.drawing) {
                //从上一次绘制线条后的终点开始向鼠标当前位置绘制线条
                this.db.lineTo(this.prePos.x, this.prePos.y);
            }
            else if (this.gameState == GameState.erasing) {
                // 橡皮擦
                this.db.circle(this.prePos.x, this.prePos.y, 10);
            }
            //每次画板中的数据有变化后，及时将数据应用到贴图上，在屏幕上显示出来
            this.drawToImg();
        }
        else if (touches.length == 2) {
            var touch1 = touches[0], touch2 = touches[1];
            var delta1 = touch1.getDelta(), delta2 = touch2.getDelta();
            var touchPoint1 = this.node.parent.convertToNodeSpaceAR(touch1.getLocation());
            var touchPoint2 = this.node.parent.convertToNodeSpaceAR(touch2.getLocation());
            var distance = touchPoint1.sub(touchPoint2);
            var delta = delta1.sub(delta2);
            var scale = 1;
            if (Math.abs(distance.x) > Math.abs(distance.y)) {
                scale = (distance.x + delta.x) / distance.x * this.node.scale;
            }
            else {
                scale = (distance.y + delta.y) / distance.y * this.node.scale;
            }
            if (scale > 2)
                scale = 2;
            this.node.scale = scale <= 0.1 ? 0.1 : scale;
        }
    };
    Game.prototype.onTouchEnd = function (e) {
        this.touchId = e.getID();
        if (this.touchId == 1)
            this.touchScale = false;
        this.addHistory();
    };
    Game.prototype.pd = function (event) {
        var cha = 2;
        var pos = event.getLocation();
        var jg = false;
        for (var i = -cha; i < cha; i++) {
            var postion = cc.v2();
            postion.x = pos.x + i;
            for (var j = -cha; j < cha; j++) {
                postion.y = pos.y + j;
                // console.log("检测点:",postion.x,postion.y);
                var img = this.getGraphisData(postion);
                if ((img[0] != 255 && img[1] != 255 && img[2] != 255)) {
                    jg = true;
                    j = 10000;
                    i = 10000;
                }
            }
        }
        //
        return jg;
    };
    Game.prototype.convertToDrawNodePos = function (worldPos) {
        var pos = this.drawNode.convertToNodeSpaceAR(worldPos);
        pos.x += this.drawNode.width * this.drawNode.anchorX;
        pos.y += this.drawNode.height * this.drawNode.anchorY;
        pos.y = this.drawNode.height - pos.y;
        return pos;
    };
    Game.prototype.addHistory = function () {
        var copy = this.db.copyData();
        var ucopy = new Uint8Array(copy);
        this.history.push({ data: ucopy });
        // cc.log('历史步骤: ', this.history.length);
    };
    Game.prototype.drawToImg = function () {
        //获取画板中绘制的图案数据
        var data = this.db.getData();
        //将数据传递给贴图对象
        this.texture.initWithData(data, cc.Texture2D.PixelFormat.RGBA8888, this.db.width, this.db.height);
    };
    Game.prototype.changeColor = function (red) {
        if (!red)
            this.db.setColor(this.errColor.r, this.errColor.g, this.errColor.b, this.errColor.a);
        else
            this.db.setColor(this.lastColor.r, this.lastColor.g, this.lastColor.b, this.lastColor.a);
    };
    Game.prototype.getGraphisData = function (point) {
        var Uint8 = new Uint8Array(4);
        Uint8 = this.targetCamera.targetTexture.readPixels(Uint8, point.x, point.y, 1, 1);
        return Uint8;
    };
    Game.prototype.onBtnDraw = function () {
        this.db.setLineWidth(this.lastLineWidth);
        this.db.setColor(this.lastColor.r, this.lastColor.g, this.lastColor.b, this.lastColor.a);
        this.gameState = GameState.drawing;
    };
    Game.prototype.onBtnErase = function () {
        this.db.setLineWidth(this.lastLineWidth * 3);
        // 橡皮擦的颜色不能是(0,0,0,0),因为这样会和DrawingBoard里的默认颜色相同导致绘制跳过
        this.db.setColor(255, 255, 255, 0);
        this.gameState = GameState.erasing;
    };
    Game.prototype.onBtnClear = function () {
        this.db.reset();
        this.drawToImg();
        this.history.splice(0, this.history.length);
    };
    Game.prototype.onBtnRevoke = function () {
        this.history.pop();
        if (this.history.length) {
            var data = this.history[this.history.length - 1].data;
            this.db.setData(data.buffer);
            this.texture.initWithData(this.db.getData(), cc.Texture2D.PixelFormat.RGBA8888, this.db.width, this.db.height);
        }
        else {
            this.onBtnClear();
        }
        cc.log('历史记录剩余: ', this.history.length);
    };
    Game.prototype.onBtnSave = function () {
        var _this = this;
        if (cc.sys.isBrowser) {
            var width = this.drawNode.width;
            var height = this.drawNode.height;
            this.captureCamera.enabled = true;
            var texture = new cc.RenderTexture();
            texture.initWithSize(width, height, cc.RenderTexture.DepthStencilFormat.RB_FMT_S8);
            this.captureCamera.targetTexture = texture;
            var canvas = document.createElement('canvas');
            canvas.width = width;
            canvas.height = height;
            var ctx = canvas.getContext('2d');
            this.captureCamera.render();
            var data = texture.readPixels();
            // write the render data
            var rowBytes = width * 4;
            for (var row = 0; row < height; row++) {
                var srow = height - 1 - row;
                var imageData = ctx.createImageData(width, 1);
                var start = srow * width * 4;
                for (var i = 0; i < rowBytes; i++) {
                    imageData.data[i] = data[start + i];
                }
                ctx.putImageData(imageData, 0, row);
            }
            //
            var dataUrl = canvas.toDataURL('image/png');
            // cc.log('iamge-base64:', dataUrl);
            var saveLink = document.createElementNS('http://www.w3.org/1999/xhtml', 'a');
            saveLink.href = dataUrl;
            saveLink.download = String(Date.now()) + '.png';
            var event = document.createEvent('MouseEvents');
            event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
            saveLink.dispatchEvent(event);
            this.scheduleOnce(function (t) {
                _this.captureCamera.enabled = false;
            }, 0.1);
        }
        else {
            cc.warn('暂时只支持web端保存图片');
        }
    };
    Game.prototype.update = function (dt) {
    };
    __decorate([
        property(cc.Node)
    ], Game.prototype, "drawNode", void 0);
    __decorate([
        property(cc.Camera)
    ], Game.prototype, "captureCamera", void 0);
    __decorate([
        property(cc.Camera)
    ], Game.prototype, "mainCamera", void 0);
    Game = __decorate([
        ccclass
    ], Game);
    return Game;
}(cc.Component));
exports.default = Game;

cc._RF.pop();