1import { Asset } from 'expo-asset'; 2 3import GLWrap from './GLWrap'; 4 5export default GLWrap('Basic texture use', async (gl) => { 6 const vert = gl.createShader(gl.VERTEX_SHADER)!; 7 gl.shaderSource( 8 vert, 9 ` 10 precision highp float; 11 attribute vec2 position; 12 varying vec2 uv; 13 void main () { 14 uv = position; 15 gl_Position = vec4(1.0 - 2.0 * position, 0, 1); 16 }` 17 ); 18 gl.compileShader(vert); 19 const frag = gl.createShader(gl.FRAGMENT_SHADER)!; 20 gl.shaderSource( 21 frag, 22 ` 23 precision highp float; 24 uniform sampler2D texture; 25 varying vec2 uv; 26 void main () { 27 gl_FragColor = texture2D(texture, vec2(uv.x, uv.y)); 28 }` 29 ); 30 gl.compileShader(frag); 31 32 const program = gl.createProgram()!; 33 gl.attachShader(program, vert); 34 gl.attachShader(program, frag); 35 gl.linkProgram(program); 36 gl.useProgram(program); 37 38 const buffer = gl.createBuffer(); 39 gl.bindBuffer(gl.ARRAY_BUFFER, buffer); 40 const verts = new Float32Array([-2, 0, 0, -2, 2, 2]); 41 gl.bufferData(gl.ARRAY_BUFFER, verts, gl.STATIC_DRAW); 42 const positionAttrib = gl.getAttribLocation(program, 'position'); 43 gl.enableVertexAttribArray(positionAttrib); 44 gl.vertexAttribPointer(positionAttrib, 2, gl.FLOAT, false, 0, 0); 45 46 const asset = Asset.fromModule(require('../../../assets/images/nikki.png')); 47 await asset.downloadAsync(); 48 const texture = gl.createTexture(); 49 gl.activeTexture(gl.TEXTURE0); 50 gl.bindTexture(gl.TEXTURE_2D, texture); 51 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); 52 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); 53 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, asset as any); 54 gl.uniform1i(gl.getUniformLocation(program, 'texture'), 0); 55 56 (async () => { 57 await new Promise((resolve) => setTimeout(resolve, 1000)); 58 59 const imageAsset = Asset.fromModule(require('../../../assets/images/nikki-small-purple.png')); 60 await imageAsset.downloadAsync(); 61 gl.texSubImage2D(gl.TEXTURE_2D, 0, 32, 32, gl.RGBA, gl.UNSIGNED_BYTE, imageAsset as any); 62 // Use below to test using a `TypedArray` parameter 63 // gl.texSubImage2D( 64 // gl.TEXTURE_2D, 0, 32, 32, 2, 2, gl.RGBA, gl.UNSIGNED_BYTE, 65 // new Uint8Array([ 66 // 255, 0, 0, 255, 67 // 0, 255, 0, 255, 68 // 0, 0, 255, 255, 69 // 128, 128, 0, 255, 70 // ])); 71 })(); 72 73 return { 74 onTick() { 75 gl.clearColor(0, 0, 1, 1); 76 // tslint:disable-next-line: no-bitwise 77 gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); 78 gl.drawArrays(gl.TRIANGLES, 0, verts.length / 2); 79 gl.endFrameEXP(); 80 }, 81 }; 82}); 83