<!DOCTYPE html>
<html>
<head>
<script src="../../../resources/js-test-pre.js"></script>
</head>
<body>
<canvas id="canvas" width="40" height="40"></canvas>
<script>
description("Make sure that reading from WebGL2 buffers into offset ArrayBufferView works as expected.");

var arrayBuffer = new ArrayBuffer(40);
var fullArrayView = new Float32Array(arrayBuffer); // [15, 16, 17, 18, 19, 20, 21, 22, 23, 24], 40 bytes

var receiverBuffer = new ArrayBuffer(1024);
var receiver = new Float32Array(receiverBuffer, 40, 20); // 20 floats, 80 bytes
for (var i = 0; i < 10; ++i)
    fullArrayView[i] = 15 + i;

var sentinel = 100;
function fillReceiver() {
    var filler = new Float32Array(receiverBuffer);
    filler.fill(sentinel);
}

var canvas = document.getElementById("canvas");
var context = canvas.getContext("webgl2");

runTests(context.ARRAY_BUFFER);
runTests(context.COPY_READ_BUFFER);
runTests(context.COPY_WRITE_BUFFER);
runTests(context.ELEMENT_ARRAY_BUFFER);
runTests(context.PIXEL_PACK_BUFFER);
runTests(context.PIXEL_UNPACK_BUFFER);
runTests(context.TRANSFORM_FEEDBACK_BUFFER);
runTests(context.UNIFORM_BUFFER);

function runTests(target) {
    var buffer = context.createBuffer();
    shouldBe("context.getError()", "context.NO_ERROR");
    context.bindBuffer(target, buffer);
    shouldBe("context.getError()", "context.NO_ERROR");
    context.bufferData(target, arrayBuffer, context.STATIC_DRAW);
    shouldBe("context.getError()", "context.NO_ERROR");

    fillReceiver();
    context.getBufferSubData(target, 0, receiver, 0, 10);
    shouldBe("context.getError()", "context.NO_ERROR");
    for (var i = 0; i < 10; ++i)
        shouldBe("receiver[" + i + "]", "fullArrayView[" + i + "]");

    fillReceiver();
    context.getBufferSubData(target, 0, receiver, 1, 10);
    shouldBe("context.getError()", "context.NO_ERROR");
    shouldBe("receiver[0]", "sentinel");
    for (var i = 0; i < 10; ++i)
        shouldBe("receiver[" + (i + 1) + "]", "fullArrayView[" + i + "]");

    fillReceiver();
    context.getBufferSubData(target, 4, receiver, 0, 9);
    shouldBe("context.getError()", "context.NO_ERROR");
    for (var i = 0; i < 9; ++i)
        shouldBe("receiver[" + i + "]", "fullArrayView[" + (i + 1) + "]");

    fillReceiver();
    context.getBufferSubData(target, 8, receiver, 1, 8);
    shouldBe("context.getError()", "context.NO_ERROR");
    shouldBe("receiver[0]", "sentinel");
    for (var i = 0; i < 8; ++i)
        shouldBe("receiver[" + (i + 1) + "]", "fullArrayView[" + (i + 2) + "]");

    context.deleteBuffer(buffer);
    shouldBe("context.getError()", "context.NO_ERROR");
}
</script>
<script src="../../../resources/js-test-post.js"></script>
</body>
</html>
