Skip to content

Instantly share code, notes, and snippets.

@diska
Last active July 28, 2019 20:00
Show Gist options
  • Select an option

  • Save diska/9162597e717b399fe6e64ffb64456fec to your computer and use it in GitHub Desktop.

Select an option

Save diska/9162597e717b399fe6e64ffb64456fec to your computer and use it in GitHub Desktop.
.obj形式の(手書き)3D頂点データをそれとなく2DにプロットするWebGLプログラム。
<style>textarea{background-color:bisque}</style>
<hr/><canvas width="300" height="300"></canvas>
<textarea id="AREA" rows="16" cols="40"></textarea>
<hr/>
scale<input id="SLID" type="range" value="90" max="100"><input id="SCALE"><br/>
dmode<input id="MODE" type="range" value="0" max="6"><input id="DMODE"><br/>
psize<input id="SIZE" type="range" value="8" max="50"><input id="PSIZE"><br/>
rotYa<input id="ROTY" type="range" min="-1" max="1" step="0.1"><input id="ROTYA"><br/>
<script>
AREA.value=`v 0 1 0\nv 1 0 0\nv -1 0 0`;
const vs0src=`attribute vec4 p;uniform float f, s, r;
void main(){gl_PointSize=s;
gl_Position=p;
gl_Position.xz*=mat2(cos(r),-sin(r), sin(r),cos(r));
gl_Position.xyz*=f/100.;
}`;
const fs0src=`void main(){gl_FragColor=vec4(1);gl_FragColor.rb*=0.5;}`;
var cx=document.querySelector("canvas").getContext("webgl");
var vs=cx.createShader(cx.VERTEX_SHADER);cx.shaderSource(vs,vs0src);
var fs=cx.createShader(cx.FRAGMENT_SHADER);cx.shaderSource(fs,fs0src);
var pg=cx.createProgram();cx.attachShader(pg, vs);cx.attachShader(pg, fs);
cx.compileShader(vs);cx.compileShader(fs);cx.linkProgram(pg);
console.log(`VERTEX_SHADER:${cx.getShaderInfoLog(vs)}`);
console.log(`FRAGMENT_SHADER:${cx.getShaderInfoLog(fs)}`);
console.log(`LINK:${cx.getProgramInfoLog(pg)}`);
//
var data=[];
function setBuf(){
data=[];
var s1=AREA.value.match(new RegExp(/v .* .* .*/g));
for(i=0; i<s1.length; i++){
var s2=s1[i].split(" ");
data.push(s2[1],s2[2],s2[3]);
}
var buf=cx.createBuffer();
cx.bindBuffer(cx.ARRAY_BUFFER, buf);
cx.enableVertexAttribArray(0);
cx.vertexAttribPointer(0, 3, cx.FLOAT, false, 0,0);
cx.bufferData(cx.ARRAY_BUFFER, new Float32Array(data), cx.STATIC_DRAW);
cx.bindBuffer(cx.ARRAY_BUFFER, null);
}; setBuf(); AREA.addEventListener("click", setBuf);
//
cx.useProgram(pg);
function draw(now){
cx.clearColor(0,0,0,1); cx.clear(cx.COLOR_BUFFER_BIT);
DMODE.value=MODE.value;
SCALE.value=SLID.value; cx.uniform1f(cx.getUniformLocation(pg, "f"), SLID.value);
PSIZE.value=SIZE.value; cx.uniform1f(cx.getUniformLocation(pg, "s"), SIZE.value);
ROTYA.value=ROTY.value; cx.uniform1f(cx.getUniformLocation(pg, "r"), ROTY.value);
cx.drawArrays(MODE.value, 0, data.length/3);
requestAnimationFrame(draw);
} requestAnimationFrame(draw);
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment