<!--
Copyright (c) 2019 The Khronos Group Inc.
Use of this source code is governed by an MIT-style license that can be
found in the LICENSE.txt file.
-->

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>WebGL framebuffer texture attachment switching conformance test.</title>
<link rel="stylesheet" href="../../resources/js-test-style.css"/>
<script src="../../js/js-test-pre.js"></script>
<script src="../../js/webgl-test-utils.js"> </script>
</head>
<body>
<canvas id="canvas" width="64" height="64"></canvas>
<div id="description"></div>
<div id="console"></div>
<script>
"use strict";
description("Test framebuffer texture attachment switching. The test uses one framebuffer object and switches its color attachment.");
var wtu = WebGLTestUtils;
var canvas = document.getElementById("canvas");

var gl = wtu.create3DContext("canvas");
var program = wtu.setupTexturedQuad(gl);

var fb = gl.createFramebuffer();
gl.bindFramebuffer(gl.FRAMEBUFFER, fb);

var tex2 = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex2);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, canvas.width, canvas.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);

var tex1 = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex1);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, canvas.width, canvas.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);

gl.clearColor(1.0, 1.0, 1.0, 1.0);

wtu.glErrorShouldBe(gl, gl.NO_ERROR, "Should be no errors from setup.");

var iterate = function(checkFBOs, iterations) {
    for (var i = 0; i < iterations; ++i) {
        debug("Clearing tex1 to white");
        gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex1, 0);
        if (checkFBOs)
            shouldBe("gl.checkFramebufferStatus(gl.FRAMEBUFFER)", "gl.FRAMEBUFFER_COMPLETE");
        gl.clear(gl.COLOR_BUFFER_BIT);

        debug("Copying tex1 to tex2");
        gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex2, 0);
        if (checkFBOs)
            shouldBe("gl.checkFramebufferStatus(gl.FRAMEBUFFER)", "gl.FRAMEBUFFER_COMPLETE");
        gl.drawArrays(gl.TRIANGLES, 0, 6);
    }
    // Read what is in tex2
    wtu.checkCanvas(gl, [255,255,255,255], "tex2 should be white");
};

debug("");
debug("Warm-up iteration");
iterate(true, 1);

debug("");
debug("Iterating the test a few times since at least one bug it has exposed is somewhat flaky.");
for (var i = 0; i < 3; ++i) {
    debug("");
    debug("Iteration " + (i + 1));
    iterate(false, 2);
}

debug("");
wtu.glErrorShouldBe(gl, gl.NO_ERROR, "Should be no errors at the end of the test.");

finishTest();

var successfullyParsed = true;
</script>
</body>
</html>

