<!DOCTYPE html>
<html>
<head>
<script src="../../../resources/js-test-pre.js"></script>
</head>
<body>
<canvas id="canvas" width="40" height="40"></canvas>
<script>
description("Test that texStorage2D() works.");

var canvas = document.getElementById("canvas");
var width = canvas.width;
var height = canvas.height;
var gl = canvas.getContext("webgl2");
shouldBe("gl.getError()", "gl.NO_ERROR");

var texture = gl.createTexture();
shouldBe("gl.getError()", "gl.NO_ERROR");
gl.bindTexture(gl.TEXTURE_2D, texture);
shouldBe("gl.getError()", "gl.NO_ERROR");
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
shouldBe("gl.getError()", "gl.NO_ERROR");
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
shouldBe("gl.getError()", "gl.NO_ERROR");
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
shouldBe("gl.getError()", "gl.NO_ERROR");
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
shouldBe("gl.getError()", "gl.NO_ERROR");

var width = 4;
var height = 4;
debug("asdf");
gl.texStorage2D(gl.TEXTURE_2D, 1, gl.RGBA8, width, height);
shouldBe("gl.getError()", "gl.NO_ERROR");

var framebuffer = gl.createFramebuffer();
shouldBe("gl.getError()", "gl.NO_ERROR");
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
shouldBe("gl.getError()", "gl.NO_ERROR");
gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
shouldBe("gl.getError()", "gl.NO_ERROR");
shouldBe("gl.checkFramebufferStatus(gl.FRAMEBUFFER)", "gl.FRAMEBUFFER_COMPLETE");

var receiver = new Uint8Array(width * height * 4);
for (var i = 0; i < width * height * 4; ++i) {
    receiver[i] = 1;
}

gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, receiver);
shouldBe("gl.getError()", "gl.NO_ERROR");
for (var i = 0; i < width * height * 4; ++i) {
    shouldBe("receiver[i]", "0");
}

gl.texStorage2D(gl.TEXTURE_2D, 1, gl.RGBA8, width, height);
shouldNotBe("gl.getError()", "gl.NO_ERROR");

gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA8, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, receiver);
shouldNotBe("gl.getError()", "gl.NO_ERROR");

for (var i = 0; i < width * height * 4; ++i) {
    receiver[i] = 1;
}
gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, receiver);
shouldBe("gl.getError()", "gl.NO_ERROR");

for (var i = 0; i < width * height * 4; ++i) {
    receiver[i] = 0;
}
gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, receiver);
shouldBe("gl.getError()", "gl.NO_ERROR");

for (var i = 0; i < width * height * 4; ++i) {
    shouldBe("receiver[i]", "1");
}

gl.deleteFramebuffer(framebuffer);
shouldBe("gl.getError()", "gl.NO_ERROR");

gl.deleteTexture(texture);
shouldBe("gl.getError()", "gl.NO_ERROR");
</script>
<script src="../../../resources/js-test-post.js"></script>
</body>
</html>