<!--
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 Texture Switch Conformance Tests</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>
<div id="description"></div>
<div id="console"></div>
<script>
"use strict";
description("Ensures that switching the texture referenced by a sampler uniform performs reasonably well.");
var wtu = WebGLTestUtils;
var canvas = document.createElement('canvas');
canvas.width = 32;
canvas.height = 32;
var gl = wtu.create3DContext(canvas);
if (!gl) {
  testFailed("context does not exist");
  finishTest();
} else {
  var program = wtu.setupTexturedQuad(gl);
  var tex = gl.createTexture();
  gl.activeTexture(gl.TEXTURE0);
  gl.bindTexture(gl.TEXTURE_2D, tex);
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);

  var tex2 = gl.createTexture();
  gl.activeTexture(gl.TEXTURE1);
  gl.bindTexture(gl.TEXTURE_2D, tex);
  gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);

  var loc = gl.getUniformLocation(program, "tex");

  var RUNTIME = 2000;
  var THRESHOLD = 0.8;
  var baseStartTime = 0;
  var baseFrameCount = 0;
  var testStartTime = 0;
  var testFrameCount = 0;

  baseStartTime = Date.now();
  function drawBaseline() {
    for (var i = 0; i < 400; ++i) {
      gl.uniform1i(loc, 0);
      gl.drawArrays(gl.TRIANGLES, 0, 6);
      gl.uniform1i(loc, 0);
      gl.drawArrays(gl.TRIANGLES, 0, 6);
    }

    ++baseFrameCount;

    if (Date.now() - baseStartTime > RUNTIME) {
      testStartTime = Date.now();
      requestAnimationFrame(drawTest);
    } else {
      requestAnimationFrame(drawBaseline);
    }
  }

  function drawTest() {
    for (var i = 0; i < 400; ++i) {
      gl.uniform1i(loc, 0);
      gl.drawArrays(gl.TRIANGLES, 0, 6);
      gl.uniform1i(loc, 1);
      gl.drawArrays(gl.TRIANGLES, 0, 6);
    }

    ++testFrameCount;

    if (Date.now() - testStartTime > RUNTIME) {
      var perfString = " - achieved " + testFrameCount + " frames in " + ((Date.now() - testStartTime) / 1000.0) +
        " seconds (" + (testFrameCount / baseFrameCount).toFixed(2) + " times baseline performance)";
      if (testFrameCount > baseFrameCount * THRESHOLD) {
        testPassed("Texture switching did not significantly hurt performance" + perfString);
      } else {
        testFailed("Texture switching significantly hurt performance" + perfString);
      }
      console.log(testFrameCount);
      finishTest();
    } else {
      requestAnimationFrame(drawTest);
    }
  }

  requestAnimationFrame(drawBaseline);
}
var successfullyParsed = true;
</script>
</body>
</html>

