Created
August 2, 2020 03:30
-
-
Save diska/3460013c409bc550cddfd982690c0c8b to your computer and use it in GitHub Desktop.
変換行列を理解してない学習段階で書いた円筒のWebGLコード。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <style>canvas{background-color: cornflowerblue;}</style> | |
| <canvas width="512" height="512"></canvas> | |
| <script> | |
| const opt={}; | |
| let cx=document.querySelector("canvas").getContext("webgl",opt); | |
| let pg=cx.createProgram(); | |
| let vs=cx.createShader(cx.VERTEX_SHADER); cx.attachShader(pg,vs); | |
| let fs=cx.createShader(cx.FRAGMENT_SHADER); cx.attachShader(pg,fs); | |
| let vsrc=`attribute vec4 p;uniform mat4 m4; | |
| varying float c; | |
| void main(){ | |
| gl_PointSize=4.; | |
| gl_Position=p; | |
| gl_Position.xyz*=0.5; | |
| gl_Position*=m4; | |
| gl_Position.z+=-.2; | |
| gl_Position.xyz*=2./(2.-gl_Position.z); | |
| c=1./length(gl_Position-vec4(0,0,3,1)); | |
| c*=4.; | |
| }`; | |
| let fsrc=`precision highp float; | |
| varying float c; | |
| void main(){ | |
| if(length(gl_PointCoord-0.5)>0.5)discard; | |
| gl_FragColor=vec4(1); | |
| gl_FragColor=vec4(c,c,c/2.,1); | |
| }`; | |
| cx.shaderSource(vs,vsrc); cx.compileShader(vs); | |
| cx.shaderSource(fs,fsrc); cx.compileShader(fs); cx.linkProgram(pg); | |
| console.log(`pg:${cx.getProgramInfoLog(pg)}`); | |
| cx.useProgram(pg); | |
| cx.enable(cx.DEPTH_TEST); | |
| cx.enableVertexAttribArray(0); | |
| let bf=cx.createBuffer(); | |
| cx.bindBuffer(cx.ARRAY_BUFFER,bf);{ | |
| cx.vertexAttribPointer(0,3,cx.FLOAT,false,0,0); | |
| let data=new Float32Array(10000*3); | |
| for(let i=0;i<10000;i++){ | |
| let theta=Math.random()*2*Math.PI; | |
| data[3*i+0]=Math.cos(theta); | |
| data[3*i+1]=2*Math.random()-1; | |
| data[3*i+2]=Math.sin(theta); | |
| } | |
| cx.bufferData(cx.ARRAY_BUFFER, data,cx.STATIC_DRAW); | |
| };cx.bindBuffer(cx.ARRAY_BUFFER,null); | |
| let m4loc=cx.getUniformLocation(pg,"m4"); | |
| let m4=new Float32Array(16);m4[0]=m4[5]=m4[10]=m4[15]=1; | |
| function draw(now){ | |
| m4[0]=Math.cos(now/1000), m4[2]=-Math.sin(now/1000); | |
| m4[8]=Math.sin(now/1000), m4[10]=Math.cos(now/1000); | |
| cx.uniformMatrix4fv(m4loc,false,m4); | |
| cx.clearColor(0,0.3,0,1);cx.clearDepth(1);cx.clear(0x4100); | |
| cx.drawArrays(0,0,10000); | |
| requestAnimationFrame(draw); | |
| } requestAnimationFrame(draw); | |
| </script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment