Skip to content

Instantly share code, notes, and snippets.

@noboko
Created April 5, 2012 15:50
Show Gist options
  • Save noboko/2312068 to your computer and use it in GitHub Desktop.
Save noboko/2312068 to your computer and use it in GitHub Desktop.
Learning WebGL for Plask Lesson 09
#ifdef GL_ES
precision highp float;
#endif
varying vec2 vTextureCoord;
uniform sampler2D uSampler;
uniform vec3 uColor;
void main(void) {
vec4 textureColor = texture2D(uSampler, vec2(vTextureCoord.s, vTextureCoord.t));
gl_FragColor = textureColor * vec4(uColor, 1.0);
}
//Learning WebGL for Plask Lesson8
//Learing WebGL : http://learningwebgl.com/blog/?page_id=1217
//Github : https://github.com/gpjt/webgl-lessons (this script use 'star.gif').
//元ネタは十字カーソルとページアップダウンにボタン割り当てですが、手持ちの環境にページアップ/ダウンボタンがないので
//tilt: ws, zoom: qe, twinkle:f, reset:r
//
//あくまでsimpleWindow()でやる前提なので、prototypeの継承を一部止めてたり、実装のしかたが違ってます。
//
//Plask : http://www.plask.org/
//
var path = require('path');
var plask = require('plask');
function clone(obj){
var F = function(){};
F.prototype = obj;
return new F;
}
function degToRad(degrees) {
return degrees * Math.PI / 180;
}
function Star(startingDistance, rotationSpeed) {
this.angle = 0;
this.dist = startingDistance;
this.rotationSpeed = rotationSpeed;
// Set the colors to a starting value.
this.randomiseColors();
}
Star.prototype = {
animate : function (elapsedTime, effectiveFPMS) {
this.angle += this.rotationSpeed * effectiveFPMS * elapsedTime;
// Decrease the distance, resetting the star to the outside of
// the spiral if it's at the center.
this.dist -= 0.01 * effectiveFPMS * elapsedTime;
if (this.dist < 0.0) {
this.dist += 5.0;
this.randomiseColors();
}
},
randomiseColors : function () {
// Give the star a random color for normal
// circumstances...
this.r = Math.random();
this.g = Math.random();
this.b = Math.random();
// When the star is twinkling, we draw it twice, once
// in the color below (not spinning) and then once in the
// main color defined above.
this.twinkleR = Math.random();
this.twinkleG = Math.random();
this.twinkleB = Math.random();
}
}
var init ={
tilt : 90,
zoom : -15,
twinkle : 1,
spin : 0 //ループごとに0になっちゃうので使ってない。。
};
var spin = 0;
plask.simpleWindow({
settings: {
width: 1280,
height: 720,
type: '3d', // Create an OpenGL window.
vsync: true, // Prevent tearing.
multisample: true // Anti-alias.
},
init: function() {
var gl = this.gl;
this.framerate(60);
this.param = clone(init);
this.on('keyDown', function(e) {
// The |str| property on the key event is a string of the unicode
// translation of the key. Take bigger steps while holding shift.
switch (e.str) {
case 'w': this.param.tilt -= 2; break;
case 's': this.param.tilt += 2; break;
case 'q': this.param.zoom += 0.1; break;
case 'e': this.param.zoom -= 0.1; break;
case 'f': this.param.twinkle += 1;
this.param.twinkle = this.param.twinkle % 2;
break;
case 'r': this.param = clone(init);
spin = 0;
break;//reset
}
this.redraw();
});
// Read/compile/link the shaders into a MagicProgram. The |mprogram|
// object created has methods to set the shader uniform variables.
this.mprogram = new plask.gl.MagicProgram.createFromBasename(
gl, __dirname, 'app');
// Create the three 3d (xyz) vertices for the triangle. This creates the
// geometry and loads it into an Vertex Buffer Object (VBO).
function makeBuffer(ar,itemSize) {
var buffer = gl.createBuffer();
var data = new Float32Array(ar);
gl.bindBuffer(gl.ARRAY_BUFFER, buffer);
gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW);
return {buffer: buffer, num: data.length / itemSize, data: data, itemSize: itemSize};
}
this.starVertexPositionBuffer = makeBuffer([
-1.0, -1.0, 0.0,
1.0, -1.0, 0.0,
-1.0, 1.0, 0.0,
1.0, 1.0, 0.0
],3);
this.starVertexTextureCoordBuffer = makeBuffer([
0.0, 0.0,
1.0, 0.0,
0.0, 1.0,
1.0, 1.0
],2);
function careateTextureWithFile(fileName) {
var image = new plask.SkCanvas.createFromImage(path.join(__dirname, fileName));
var texture = gl.createTexture();
gl.activeTexture(gl.TEXTURE0);
gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texImage2DSkCanvas(gl.TEXTURE_2D, 0, image);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_NEAREST);
gl.generateMipmap(gl.TEXTURE_2D);
//textureの切り替えをしないのでnullをbindせずにそのままdrawへもってく。
//gl.bindTexture(gl.TEXTURE_2D, null);
//return{texture : texture, image : image};
}
//this.texture =
careateTextureWithFile('star.gif');
var stars = this.stars= [];
(function initWorldObjects() {
var numStars = 50;
for (var i=0; i < numStars; i++) {
stars.push(new Star((i / numStars) * 5.0, i / numStars));
}
}());
//console.log(stars);
gl.viewport(0, 0, this.width, this.height);
gl.clearColor(0.0, 0.0, 0.0, 1.0);
gl.clearDepth(1.0)
gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
gl.enable(gl.BLEND);
gl.disable(gl.DEPTH_TEST);
//gl.enable(gl.TEXTURING);gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
//gl.enable(gl.TEXTURE_2D);
gl.depthFunc(gl.LEQUAL);
},
draw: function() {
var gl = this.gl;
var starVertexPositionBuffer = this.starVertexPositionBuffer;
var starVertexTextureCoordBuffer = this.starVertexTextureCoordBuffer;
var mprogram = this.mprogram;
//var param = this.param;
//console.log(param);
var mv = this.mv;
var mvStack = this.mvStack;
var persp = this.persp;
var color = this.color;
var width = this.width;
var height = this.height;
var t = this.frametime;
var stars = this.stars;
var zoom = this.param.zoom;
var tilt = this.param.tilt;
//var spin = this.param.spin;
var twinkle = this.param.twinkle;
mv = new plask.Mat4();
mvStack = [];
persp = new plask.Mat4();
color = new plask.Vec3();
mprogram.use();
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
mv.translate(0.0, 0.0, zoom);
mv.rotate(degToRad(tilt), 1.0, 0.0, 0.0);
persp.perspective(45, width / height, 0.1, 100.0);
mprogram.set_uPMatrix(persp);
mprogram.set_uSampler(0);
gl.blendFunc(gl.SRC_ALPHA, gl.ONE);
gl.enable(gl.BLEND);
function setProg(){
mprogram.set_uMVMatrix(mv);
mprogram.set_uColor(color);
gl.enableVertexAttribArray(mprogram.location_aVertexPosition);
gl.enableVertexAttribArray(mprogram.location_aTextureCoord);
};
function drawStar(){
// Draw the geometry from the VBO, passing the vertices to the vertex
// shader as a vec3 named |a_xyz|.
gl.bindBuffer(gl.ARRAY_BUFFER, starVertexPositionBuffer.buffer);
gl.vertexAttribPointer(mprogram.location_aVertexPosition,
starVertexPositionBuffer.itemSize,
gl.FLOAT,
false, 0, 0);
gl.bindBuffer(gl.ARRAY_BUFFER, starVertexTextureCoordBuffer.buffer);
gl.vertexAttribPointer(mprogram.location_aTextureCoord,
starVertexTextureCoordBuffer.itemSize,
gl.FLOAT,
false, 0, 0);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, starVertexPositionBuffer.num);
};
function drawStars(tilt, spin, twinkle, obj){
mvStack.push(mv.dup());
mv.rotate(degToRad(obj.angle), 0.0, 1.0, 0.0);
mv.translate(obj.dist, 0, 0);
//mv.translate(0, Math.random()*2-1, -5);
// Rotate back so that the star is facing the viewer
mv.rotate(degToRad(-obj.angle), 0.0, 1.0, 0.0);
mv.rotate(degToRad(-tilt), 1.0, 0.0, 0.0);
if (twinkle) {
color.set(obj.twinkleR, obj.twinkleG, obj.twinkleB);
setProg();
drawStar();
}
// All stars spin around the Z axis at the same rate
mv.rotate(degToRad(spin), 0.0, 0.0, 1.0);
// Draw the star in its main color
color.set(obj.twinkleR, obj.twinkleG, obj.twinkleB);
setProg();
drawStar();
mv = mvStack.pop();
};
for (i=0;i<stars.length;i+=1) {
drawStars(tilt, spin, twinkle, stars[i]);
spin+=0.1;
stars[i].animate(60 / 1000 ,t*2);//なんか遅いので2倍してる。
};
}
});
attribute vec3 aVertexPosition;
attribute vec3 aVertexNormal;
attribute vec2 aTextureCoord;
uniform mat4 uMVMatrix;
uniform mat4 uPMatrix;
uniform mat3 uNMatrix;
uniform vec3 uAmbientColor;
uniform vec3 uLightingDirection;
uniform vec3 uDirectionalColor;
uniform bool uUseLighting;
varying vec2 vTextureCoord;
varying vec3 vLightWeighting;
void main(void) {
gl_Position = uPMatrix * uMVMatrix * vec4(aVertexPosition, 1.0);
vTextureCoord = aTextureCoord;
if (!uUseLighting) {
vLightWeighting = vec3(1.0, 1.0, 1.0);
} else {
vec3 transformedNormal = uNMatrix * aVertexNormal;
float directionalLightWeighting = max(dot(transformedNormal, uLightingDirection), 0.0);
vLightWeighting = uAmbientColor + uDirectionalColor * directionalLightWeighting;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment