Rotation without distortion using Matrix3D - actionscript-3

How to assign a value to Matrix3D rotation about the axis Z. (li "rotation")?
The position and size are calculated correctly, but after the addition of rotation, the image is stretched.
I tried two method to rotation:
_positionMatrix.identity();
var v3:Vector.<Vector3D> = new Vector.<Vector3D>(3);
v3 = _positionMatrix.decompose();
v3[0].incrementBy(new Vector3D( x, y, 0 ));// x, y, z
v3[1].incrementBy(new Vector3D(0,0,-rotation*Math.PI/180)); // rotationX, rotationY, rotationZ
v3[2].incrementBy(new Vector3D(width,height,0)); // scaleX, scaleY, scaleZ
_positionMatrix.recompose(v3);
And:
_positionMatrix.identity();
_positionMatrix.appendScale(width,height,1);
_positionMatrix.appendTranslation(x,y,0);
_positionMatrix.appendRotation(-rotation,Vector3D.Z_AXIS );
But the effect is identical:
I find that "PerspectiveProjection" class can help, but cant to understand how to use it with rotation about the axis Z.

For start, if you have such a problem - try to eliminate matrix transforms one by one until you find which matrix is a "bad" one. For example, what will happen if you store only one transformation - scale or translation or rotation?
In your example I can't see any criminal, so the problem is further in code. I can assume that your projection matrix is wrong. Can you provide it? How do you apply final matrix to an object?

Thanks, its true, my perspective Projection matrix was "bad".
This code works perfectly:
private var _vertexData:Vector.<Number> = new <Number>[
0,0,0, 0, 0, 0, 1,// x, y, z, r, g, b,a
1, 0, 0, 0, 0, 0, 1,
1, 1, 0, 0, 0, 0, 1,
0, 1, 0,0, 0, 0,1
];
var perspectiveProjectionMatrix:Matrix3D = new Matrix3D();
var scaleX:Number = 2.0 / _stage.stageWidth; // 2.0 / 500
var scaleY:Number = -2.0 / _stage.stageHeight; // -2.0 / 375
perspectiveProjectionMatrix.copyRawDataFrom(
new <Number>[
scaleX, 0.0, 0.0, 0.0,
0.0, scaleY, 0.0, 0.0,
0.0, 0.0, -1.0, 0.0,
-1.0, 1.0, 0.0, 1.0
]
);
var modelViewMatrix:Matrix3D = trs(stage.stageWidth/2,stage.stageHeight/2, _rotation*Math.PI/180, _width*_globalScaleX, _height*_globalScaleY );
var resultMatrix:Matrix3D = new Matrix3D();
resultMatrix.prepend(perspectiveProjectionMatrix);
resultMatrix.prepend(modelViewMatrix);
_context.setProgramConstantsFromMatrix(Context3DProgramType.VERTEX, 0,resultMatrix , true);
Where "trs" is:
public function trs( tx:Number, ty:Number, rotation:Number, xScale:Number, yScale:Number ):Matrix3D {
var data:Vector.<Number> = new <Number>[1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
var sin:Number = Math.sin( rotation );
var cos:Number = Math.cos( rotation );
data[0] = cos * xScale;
data[1] = sin * xScale;
data[4] = -sin * yScale;
data[5] = cos * yScale;
data[12] = tx;
data[13] = ty;
var matrix:Matrix3D = new Matrix3D();
matrix.copyRawDataFrom(data);
return matrix;
}

Related

cocos2dx-3.10 covertToWorldSpace result is wrong when using OrbitCamera

cocos2dx-3.10 covertToWorldSpace result is wrong when using OrbitCamera
devices test on:Windows
Steps to Reproduce:
local size = cc.size(400, 400)
local layer = cc.LayerColor:create(cc.c4b(200, 0, 0, 255), size.width, size.height)
layer:setPosition(display.cx - size.width, display.cy - size.height)
self:addChild(layer)
local label = cc.Label:create()
label:setSystemFontSize(30)
label:setSystemFontName("Arial")
label:setString("XXX")
label:setColor(cc.c3b(0, 255, 100))
label:setPosition(size.width * 0.5, 0)
layer:addChild(label)
local lsize = label:getContentSize()
local action = cc.OrbitCamera:create(1, 1, 0, 0, 70, -90, 0)
local callFunc = cc.CallFunc:create(function()
local worldPos = label:convertToWorldSpace(cc.p(lsize.width * 0.5, lsize.height * 0.5))
label = cc.Label:create()
label:setSystemFontSize(30)
label:setSystemFontName("Arial")
label:setString("AAA")
label:setColor(cc.c3b(100, 0, 100))
label:setPosition(worldPos)
self:addChild(label)
end)
layer:runAction(cc.Sequence:create(action, callFunc))
I found a solution:
local mat4 = label:getNodeToParentTransform(self)
local vec4 = {x = lsize.width * 0.5, y = lsize.height * 0.5, z = 0, w = 1}
-- convert to world space (we need to calculate its Z-value)
local pos = mat4_transformVector(mat4, vec4, cc.mat4.createIdentity())
-- convert GL-screen-space coordinates
local worldPos = cc.Camera:getDefaultCamera():projectGL(pos)
enter image description here

How to create 2D shapes with n-sides in WebGL using keyboard input?

I'm trying to create a program in WebGL that allows you to draw or create shapes of n-size via keyboard input. The user enters in the number of sides to generate a shape with that many sides. So, if you press '3', you will get a triangle, if you press '4', you will get a square, if you press '5', you will get a pentagon, etc.
So far, I've been able to create seperate pieces of code that create triangles, squares, pentagons, etc. without keyboard input but I'm not sure how to go about generating shapes within the same program with n-sides via user/keyboard input. How would I go about doing this?
Examples of my code so far:
Drawing a triangle:
var VSHADER_SOURCE =
'attribute vec4 a_Position;\n' +
'void main() {\n' +
' gl_Position = a_Position;\n' +
'}\n';
var FSHADER_SOURCE =
'void main() {\n' +
' gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n' +
'}\n';
function main() {
var canvas = document.getElementById('webgl');
var gl = getWebGLContext(canvas);
if (!gl) {
console.log('Failed to get the rendering context for WebGL');
return;
}
if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
console.log('Failed to initialize shaders.');
return;
}
var n = initVertexBuffers(gl);
if (n < 0) {
console.log('Failed to set the positions of the vertices');
return;
}
gl.clearColor(0, 0, 0, 0);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLES, 0, n);
}
function initVertexBuffers(gl) {
var vertices = new Float32Array([
0, 0.5, -0.5, -0.5, 0.5, -0.5
]);
var n = 3; // The number of vertices
var vertexBuffer = gl.createBuffer();
if (!vertexBuffer) {
console.log('Failed to create the buffer object');
return -1;
}
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
if (a_Position < 0) {
console.log('Failed to get the storage location of a_Position');
return -1;
}
gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(a_Position);
return n;
}
Drawing a square:
var VSHADER_SOURCE =
'attribute vec4 a_Position;\n' +
'void main() {\n' +
' gl_Position = a_Position;\n' +
'}\n';
var FSHADER_SOURCE =
'void main() {\n' +
' gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);\n' +
'}\n';
function main() {
var canvas = document.getElementById('webgl');
var gl = getWebGLContext(canvas);
if (!gl) {
console.log('Failed to get the rendering context for WebGL');
return;
}
if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
console.log('Failed to initialize shaders.');
return;
}
var n = initVertexBuffers(gl);
if (n < 0) {
console.log('Failed to set the positions of the vertices');
return;
}
gl.clearColor(0, 0, 0, 0);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.drawArrays(gl.TRIANGLE_STRIP, 0, n);
}
function initVertexBuffers(gl) {
var vertices = new Float32Array([
-1, -1, -1, 1, 1, 1, 1, -1, -1, -1,
]);
var n = 5; // The number of vertices
var vertexBuffer = gl.createBuffer();
if (!vertexBuffer) {
console.log('Failed to create the buffer object');
return -1;
}
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer);
gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW);
var a_Position = gl.getAttribLocation(gl.program, 'a_Position');
if (a_Position < 0) {
console.log('Failed to get the storage location of a_Position');
return -1;
}
gl.vertexAttribPointer(a_Position, 2, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(a_Position);
return n;
}
You can start by writing a function computing vertices positions for a polygon with the number of sides as param.
For example, this one computes the polar coordinates of the polygon within a circle of given radius. You can write your own one.
computePolygonPositions(sides, radius)
{
let positions = []
for (let i=0; i<sides; i++)
{
let i0 = i
let i1 = (i+1) % sides
let theta0 = 2.0 * Math.PI * i0 / sides
let theta1 = 2.0 * Math.PI * i1 / sides
let x0 = radius * Math.cos(theta0)
let y0 = radius * Math.cos(theta0)
let x1 = radius * Math.cos(theta1)
let y1 = radius * Math.cos(theta1)
positions.push(0, 0)
positions.push(x0, y0)
positions.push(x1, y1)
}
return positions
}
Of course, you can upgrade this function to add indices, tex coordinates, colors or anything you need.
Once you're done with it, just call it to create a new vertex buffer that you'll bind on ARRAY_BUFFER, set the layout and enable the position attribute.

How to use Matrix3D.appendTranslation()?

With stage 3d I set up a basic triangle, and I can use append rotation and append scale and everything works, but using append translation on the z axis, the triangle will dissapear with the translation being 1 or higher. With other shapes it would dissapear with only 3 or higher. And it doesn't look like the triangle is getting any smaller/farther away between 0 and 0.9 translation. The translation on the x and y axis do work though.
Here are my shader codes:
private static const VERTEX_SHADER_SOURCE:String = "m44 op, va0, vc1";
private static const FRAGMENT_SHADER_SOURCE:String = "mov oc, fc0";
my render loop:
addEventListener(Event.ENTER_FRAME, enter);
var t:Number=0;
function enter():void {
context3D.clear();
context3D.setProgram(program);
var m:Matrix3D = new Matrix3D;
m.appendTranslation(0, 0, t);
t+=0.01;
context3D.setProgramConstantsFromMatrix(Context3DProgramType.VERTEX, 1, m, true);
context3D.setVertexBufferAt(0, buffer, 0, Context3DVertexBufferFormat.FLOAT_3);
context3D.setProgramConstantsFromVector(Context3DProgramType.FRAGMENT, 0, color);
context3D.drawTriangles(indexBuffer);
context3D.present();
}
my full code:
var assembler:AGALMiniAssembler = new AGALMiniAssembler();
assembler.assemble(Context3DProgramType.VERTEX, VERTEX_SHADER_SOURCE);
if (assembler.error) {
trace("vertex shader error " +assembler.error);
return;
}
var vertexShaderByteCode:ByteArray = assembler.agalcode;
assembler.assemble(Context3DProgramType.FRAGMENT, FRAGMENT_SHADER_SOURCE);
if (assembler.error) {
trace("fragment shader error " + assembler.error);
return;
}
var fragmentShaderByteCode:ByteArray = assembler.agalcode;
var program:Program3D = context3D.createProgram();
try {
program.upload(vertexShaderByteCode, fragmentShaderByteCode);
}
catch (err:Error) {
trace("couldnt upload shader program" + err);
return;
}
color = new <Number>[0.9296875, 0.9140625, 0.84765625, 1];
var verts:Vector.<Number> = Vector.<Number>([
0.5, 0, 0,
-0.5, 0, 0,
0, 0.5, 0
]);
var buffer:VertexBuffer3D = context3D.createVertexBuffer(3, 3);
buffer.uploadFromVector(verts, 0, 3);
var indices:Vector.<uint> = Vector.<uint>([0, 1, 2])
var indexBuffer:IndexBuffer3D = context3D.createIndexBuffer(3);
indexBuffer.uploadFromVector(indices, 0, 3);
addEventListener(Event.ENTER_FRAME, enter);
var t:Number=0;
function enter():void {
context3D.clear();
context3D.setProgram(program);
var m:Matrix3D = new Matrix3D;
m.appendTranslation(0, 0, t);
t+=0.01;
context3D.setProgramConstantsFromMatrix(Context3DProgramType.VERTEX, 1, m, true);
context3D.setVertexBufferAt(0, buffer, 0, Context3DVertexBufferFormat.FLOAT_3);
context3D.setProgramConstantsFromVector(Context3DProgramType.FRAGMENT, 0, color);
context3D.drawTriangles(indexBuffer);
context3D.present();
}

Switching Gouraud and Phong Shading

I'm writing an application where I need to switch these two shading techniques.
The program starts applying the Gouraud shading , and there are no problem.
When I click the button to switch the shading my object (a rotating cube) became all violet , like there is no light. Does anyone see the problem ?
Here is the code :
JavaScript
"use strict";
var canvas;
var gl;
var numVertices = 36;
var numChecks = 8;
var program;
var program2;
var c;
var flag = true;
var direction = true;
var rx;
var ry;
var rz;
var traslation_loc;
var tx = 0 ;
var ty = 0;
var tz = 0;
var scaling_loc;
var sx = 1.0;
var sy = 1.0;
var sz = 1.0;
var pointsArray = [];
var colorsArray = [];
//Point 4
// cambia eventualmente near e far per vedere gli effetti
var near = 0.3;
var far = 3.0;
var phi = 0.0;
var radius = 1.5;
var left = -1.0;
var right = 1.0;
var ytop = 1.0;
var bottom = -1.0;
var mvMatrix, pMatrix;
var modelView, projection;
var eye;
const at = vec3(0.0, 0.0, 0.0);
const up = vec3(0.0, 1.0, 0.0);
//var eye = vec3(1, 1, 1);
//var eye = vec3(0.02, 0.02, 0.02);
//
//Point 5
var fovy = 45.0;
var aspect;
var orthoBool = true;
var aspect = 1.0;
//
//Poinit 6
var lightAmbient = vec4(0.2, 0.2, 0.2, 1.0);
var lightDiffuse = vec4(1.0, 1.0, 1.0, 1.0);
var lightSpecular = vec4(1.0, 1.0, 1.0, 1.0);
var lightPosition = vec4(0.3, 0.2, 0.8,0.0);
var materialAmbient = vec4(1.0, 0.0, 1.0, 1.0);
var materialDiffuse = vec4(1.0, 0.8, 0.0, 1.0);
var materialSpecular = vec4(1.0, 0.8, 0.0, 1.0);
var materialShininess = 100.0;
var normalsArray = [];
// Point 7
var changeShading = true;
//
var vertices = [
vec4( -0.5, -0.5, 0.5, 1.0 ),
vec4( -0.5, 0.5, 0.5, 1.0 ),
vec4( 0.5, 0.5, 0.5, 1.0 ),
vec4( 0.5, -0.5, 0.5, 1.0 ),
vec4( -0.5, -0.5, -0.5, 1.0 ),
vec4( -0.5, 0.5, -0.5, 1.0 ),
vec4( 0.5, 0.5, -0.5, 1.0 ),
vec4( 0.5, -0.5, -0.5, 1.0 )
];
/* rimossi per il punto 6
var vertexColors = [
vec4( 0.0, 0.0, 0.0, 1.0 ), // black
vec4( 1.0, 0.0, 0.0, 1.0 ), // red
vec4( 1.0, 1.0, 0.0, 1.0 ), // yellow
vec4( 0.0, 1.0, 0.0, 1.0 ), // green
vec4( 0.0, 0.0, 1.0, 1.0 ), // blue
vec4( 1.0, 0.0, 1.0, 1.0 ), // magenta
vec4( 0.0, 1.0, 1.0, 1.0 ), // white
vec4( 0.0, 1.0, 1.0, 1.0 ) // cyan
];
*/
var xAxis = 0;
var yAxis = 1;
var zAxis = 2;
var axis = xAxis;
var theta = [45.0, 45.0, 45.0];
//var thetaLoc;
function quad(a, b, c, d) {
// Point 6
var t1 = subtract(vertices[b], vertices[a]);
var t2 = subtract(vertices[c], vertices[b]);
var normal = cross(t1, t2);
var normal = vec3(normal);
// *****
//*** Abbiamo rimpizzato i colori on queli del materiale per svolgere il punto 6
pointsArray.push(vertices[a]);
//colorsArray.push(vertexColors[a]);
normalsArray.push(normal);
pointsArray.push(vertices[b]);
//colorsArray.push(vertexColors[a]);
normalsArray.push(normal);
pointsArray.push(vertices[c]);
//colorsArray.push(vertexColors[a]);
normalsArray.push(normal);
pointsArray.push(vertices[a]);
//colorsArray.push(vertexColors[a]);
normalsArray.push(normal);
pointsArray.push(vertices[c]);
//colorsArray.push(vertexColors[a]);
normalsArray.push(normal);
pointsArray.push(vertices[d]);
//colorsArray.push(vertexColors[a]);
normalsArray.push(normal);
}
function colorCube()
{
quad( 1, 0, 3, 2 );
quad( 2, 3, 7, 6 );
quad( 3, 0, 4, 7 );
quad( 6, 5, 1, 2 );
quad( 4, 5, 6, 7 );
quad( 5, 4, 0, 1 );
}
window.onload = function init() {
canvas = document.getElementById( "gl-canvas" );
gl = WebGLUtils.setupWebGL( canvas );
if ( !gl ) { alert( "WebGL isn't available" ); }
gl.viewport( 0, 0, canvas.width, canvas.height );
// Point 5 -> define aspect
aspect = canvas.width/canvas.height;
gl.clearColor( 1.0, 1.0, 1.0, 1.0 );
gl.enable(gl.DEPTH_TEST);
//
// Load shaders and initialize attribute buffers
//
program = initShaders( gl, "vertex-shader", "fragment-shader" );
gl.useProgram(program);
colorCube();
//Point 6
var nBuffer = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, nBuffer );
gl.bufferData( gl.ARRAY_BUFFER, flatten(normalsArray), gl.STATIC_DRAW );
var vNormal = gl.getAttribLocation( program, "vNormal" );
gl.vertexAttribPointer( vNormal, 3, gl.FLOAT, false, 0, 0 );
gl.enableVertexAttribArray( vNormal );
//*************
// RIMPIAZZATI I COLORI PER IL PUNTO 6
//var cBuffer = gl.createBuffer();
//gl.bindBuffer( gl.ARRAY_BUFFER, cBuffer );
//gl.bufferData( gl.ARRAY_BUFFER, flatten(colorsArray), gl.STATIC_DRAW );
//var vColor = gl.getAttribLocation( program, "vColor" );
//gl.vertexAttribPointer( vColor, 4, gl.FLOAT, false, 0, 0 );
//gl.enableVertexAttribArray( vColor );
var vBuffer = gl.createBuffer();
gl.bindBuffer( gl.ARRAY_BUFFER, vBuffer);
gl.bufferData( gl.ARRAY_BUFFER, flatten(pointsArray), gl.STATIC_DRAW );
var vPosition = gl.getAttribLocation( program, "vPosition" );
gl.vertexAttribPointer( vPosition, 4, gl.FLOAT, false, 0, 0 );
gl.enableVertexAttribArray( vPosition );
// Possiamo commentare quello che riguarda il theta per il punto 2
//thetaLoc = gl.getUniformLocation(program, "theta");
// Point 2 - Rotation
//X AXIS
rx = gl.getUniformLocation(program, "rx");
//Y AXIS
ry = gl.getUniformLocation(program, "ry");
//Z AXIS
rz = gl.getUniformLocation(program, "rz");
// Traslation Matrix
traslation_loc = gl.getUniformLocation(program , "traslation");
// Scaling Matrix
scaling_loc = gl.getUniformLocation(program , "scaling");
// Projection and Model matrix
modelView = gl.getUniformLocation( program, "modelView" );
projection = gl.getUniformLocation( program, "projection" );
//**************
document.getElementById("ButtonX").onclick = function(){axis = xAxis;};
document.getElementById("ButtonY").onclick = function(){axis = yAxis;};
document.getElementById("ButtonZ").onclick = function(){axis = zAxis;};
document.getElementById("ButtonT").onclick = function(){flag = !flag;};
document.getElementById("Direction").onclick = function() { direction = !direction;};
document.getElementById( "slideX" ).oninput = function(){ tx = parseFloat(event.target.value,10); };
document.getElementById( "slideY" ).oninput = function(){ ty = parseFloat(event.target.value,10); };
document.getElementById( "slideZ" ).oninput = function(){ tz = parseFloat(event.target.value,10); };
document.getElementById( "ScalingX" ).oninput = function(){ sx = parseFloat(event.target.value,10); };
document.getElementById( "ScalingY" ).oninput = function(){ sy = parseFloat(event.target.value,10); };
document.getElementById( "ScalingZ" ).oninput = function(){ sz = parseFloat(event.target.value,10); };
// Point 5
document.getElementById("OrthoPersp").onclick = function(){orthoBool = !orthoBool;};
// Point 4
// per documentazine leggi la parte sotto il codice a pag 244 con spiegazione sul clip out
// cambiato inserito due sliders // perspective -> ortho -> + lontano
document.getElementById("zFarSlider").onchange = function() {
far = event.srcElement.value;
};
document.getElementById("zNearSlider").onchange = function() {
near = event.srcElement.value;
};
// POINT 7
document.getElementById("ShadingButton").onclick = function(){changeShading = !changeShading;};
//Point 6
var ambientProduct = mult(lightAmbient, materialAmbient);
var diffuseProduct = mult(lightDiffuse, materialDiffuse);
var specularProduct = mult(lightSpecular, materialSpecular);
gl.uniform4fv(gl.getUniformLocation(program, "ambientProduct"),
flatten(ambientProduct));
gl.uniform4fv(gl.getUniformLocation(program, "diffuseProduct"),
flatten(diffuseProduct) );
gl.uniform4fv(gl.getUniformLocation(program, "specularProduct"),
flatten(specularProduct) );
gl.uniform4fv(gl.getUniformLocation(program, "lightPosition"),
flatten(lightPosition) );
gl.uniform1f(gl.getUniformLocation(program, "shininess"),materialShininess);
//*************************************
render();
}
var render = function() {
gl.clear( gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
// Point 4
//*************************************
//eye = vec3(radius*Math.sin(phi), radius*Math.sin(theta),
// radius*Math.cos(phi)); RIMANE COMMENTATO
//mvMatrix = lookAt(eye, at , up);
//pMatrix = ortho(left, right, bottom, ytop, near, far);
//gl.uniformMatrix4fv( modelView, false, flatten(mvMatrix) );
//gl.uniformMatrix4fv( projection, false, flatten(pMatrix) );
//*************************************
//Point 7
gl.uniform1f(gl.getUniformLocation(program, "changeShading"),changeShading);
// Point 3 -> Scaling
var scaling = [sx , 0.0 , 0.0 , 0.0,
0.0 , sy, 0.0 , 0.0,
0.0 , 0.0 , sz , 0.0,
0.0 , 0.0 , 0.0 , 1];
gl.uniformMatrix4fv(scaling_loc,false,scaling);
// ****************************************
//X AXIS - Point 2
var theta_x_degree = theta[0];
var theta_x_radians = theta_x_degree * Math.PI / 180;
var s_x = Math.sin(theta_x_radians);
var c_x = Math.cos(theta_x_radians);
var rx_loc = [ 1.0, 0.0, 0.0, 0.0,
0.0, c_x, s_x, 0.0,
0.0, -s_x, c_x, 0.0,
0.0, 0.0, 0.0, 1.0 ];
gl.uniformMatrix4fv(rx, false, rx_loc);
//Y AXIS - Point 2
var theta_y_degree = theta[1];
var theta_y_radians = theta_y_degree * Math.PI / 180;
var s_y = Math.sin(theta_y_radians);
var c_y = Math.cos(theta_y_radians);
var ry_loc = [ c_y, 0.0, -s_y, 0.0,
0.0, 1.0, 0.0, 0.0,
s_y, 0.0, c_y, 0.0,
0.0, 0.0, 0.0, 1.0 ];
gl.uniformMatrix4fv(ry, false, ry_loc);
//Z AXIS - Point 2
var theta_z_degree = theta[2];
var theta_z_radians = theta_z_degree * Math.PI / 180;
var s_z = Math.sin(theta_z_radians);
var c_z = Math.cos(theta_z_radians);
var rz_loc = [ c_z, s_z, 0.0, 0.0,
-s_z, c_z, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0 ];
gl.uniformMatrix4fv(rz, false, rz_loc);
// ****************************************
// Point 3 -> Traslation
var traslation = [1.0 , 0.0 , 0.0 , 0.0,
0.0 , 1.0 , 0.0 , 0.0,
0.0 , 0.0 , 1.0 , 0.0,
tx , ty , tz , 1.0];
gl.uniformMatrix4fv(traslation_loc,false,traslation);
// ****************************************
//Point 4-5
//*************************************
//eye = vec3(0.02, 0.02, 0.02); // se lasciassi questo , non mi si sposterebbero le normali per la luce
eye = vec3(radius*Math.sin(theta_x_radians)*Math.cos(phi),
radius*Math.sin(theta_y_radians)*Math.sin(phi), radius*Math.cos(theta_z_radians));
mvMatrix = lookAt(eye, at , up);
if (orthoBool) {
pMatrix = ortho(left, right, bottom, ytop, near, far); }
else {
pMatrix=perspective(fovy , aspect , near , far); }
gl.uniformMatrix4fv( modelView, false, flatten(mvMatrix) );
gl.uniformMatrix4fv( projection, false, flatten(pMatrix) );
//*************************************
// ****************************************
// Point 1 --> Change and Toggle Rotation
if((direction)&&(!flag)) theta[axis] += -1.0;
if((!direction)&&(!flag)) theta[axis] += +1.0;
if(!direction) {theta[axis] += -1.0; }
if(direction) {theta[axis] += 1.0 ; }
// ****************************************
//gl.uniform3fv(thetaLoc, theta);
gl.drawArrays( gl.TRIANGLES, 0, numVertices );
requestAnimFrame(render);
}
HTML
<!DOCTYPE html>
<html>
<button id = "ButtonX">Rotate X</button>
<button id = "ButtonY">Rotate Y</button>
<button id = "ButtonZ">Rotate Z</button>
<button id = "ButtonT">Toggle Rotation</button>
<button id="Direction">Change Direction</button>
<button id="OrthoPersp">Change Parall/Persp</button>
<button id="ShadingButton">Change Shading</button>
<div>Traslation on X <input id="slideX" type="range"
min="-1" max="1" step="0.1" value="0" />
</div>
<div>Traslation on Y <input id="slideY" type="range"
min="-1" max="1" step="0.1" value="0" />
</div>
<div>Traslation on Z <input id="slideZ" type="range"
min="-1" max="1" step="0.1" value="0" />
</div>
<div>Scaling on X <input id="ScalingX" type="range"
min="0" max="1" step="0.1" value="0" />
</div>
<div>Scaling on Y <input id="ScalingY" type="range"
min="0" max="1" step="0.1" value="0" />
</div>
<div>Scaling on Z <input id="ScalingZ" type="range"
min="0" max="1" step="0.1" value="0" />
</div>
<div>
zNear Min<input id="zNearSlider" type="range" min="0.00" max="2.8" step="0.1" value="0.3">
Max
</div>
<div>
zFar Min<input id="zFarSlider" type="range" min="3" max="10" step="3.0" value="3">
Max
</div>
<script id="vertex-shader" type="x-shader/x-vertex">
precision mediump float;
attribute vec4 vPosition;
attribute vec4 vColor;
varying vec4 fColor;
//uniform vec3 theta;
// Point 2 -> Move the matrices
// Per spostare le matrici le abbiamo dovuto dichiarare nel file GLSL come uniform
// le matrici rx ry e rz sono rispettivamente le matrici di rotazione sugli assi
uniform mat4 rx;
uniform mat4 ry;
uniform mat4 rz;
// Points 3 -> Traslation Matrix
uniform mat4 traslation;
// Points 3 -> Scaling Matrix
uniform mat4 scaling;
//Point 4 -> MV and P matrices
uniform mat4 modelView;
uniform mat4 projection;
//Poinit 6 -> Light Source
attribute vec4 vNormal;
uniform vec4 ambientProduct, diffuseProduct, specularProduct;
uniform vec4 lightPosition;
uniform float shininess;
varying vec3 N,L,E;
uniform bool changeShading;
void main()
{
// Compute the sines and cosines of theta for each of
// the three axes in one computation.
//vec3 angles = radians( theta );
//vec3 c = cos( angles );
//vec3 s = sin( angles );
// Remember: the matrices are column-major
/*
mat4 rx = mat4( 1.0, 0.0, 0.0, 0.0,
0.0, c.x, s.x, 0.0,
0.0, -s.x, c.x, 0.0,
0.0, 0.0, 0.0, 1.0 );
mat4 ry = mat4( c.y, 0.0, -s.y, 0.0,
0.0, 1.0, 0.0, 0.0,
s.y, 0.0, c.y, 0.0,
0.0, 0.0, 0.0, 1.0 );
mat4 rz = mat4( c.z, s.z, 0.0, 0.0,
-s.z, c.z, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0 );
*/
//fColor = vColor;
// ORDINE : scaling -> rotazione -> traslation
//gl_Position = projection*modelView*scaling *rz * ry * rx * traslation *vPosition ;
//gl_Position.z = -gl_Position.z;
//Point 6
vec3 pos = -(modelView * vPosition).xyz;
if(changeShading) {
vec3 light = lightPosition.xyz;
vec3 L = normalize( light - pos );
vec3 E = normalize( -pos );
vec3 H = normalize( L + E );
vec3 N = normalize( (modelView*vNormal).xyz);
vec4 ambient = ambientProduct;
float Kd = max( dot(L, N), 0.0 );
vec4 diffuse = Kd*diffuseProduct;
float Ks = pow( max(dot(N, H), 0.0), shininess );
vec4 specular = Ks * specularProduct;
if( dot(L, N) < 0.0 ) {
specular = vec4(0.0, 0.0, 0.0, 1.0);
}
fColor = ambient + diffuse + specular;
fColor.a = 1.0;
gl_Position = projection*modelView*scaling *rz * ry * rx * traslation *vPosition ;
gl_Position.z = -gl_Position.z;
}
else {
vec3 light = lightPosition.xyz;
vec3 L = normalize( light - pos );
vec3 E = normalize( -pos );
vec3 H = normalize( L + E );
vec3 N = normalize( (modelView*vNormal).xyz);
gl_Position = projection*modelView*scaling *rz * ry * rx * traslation *vPosition ;
gl_Position.z = -gl_Position.z;
}
// *******************
}
</script>
<script id="fragment-shader" type="x-shader/x-fragment">
precision mediump float;
varying vec4 vPosition;
varying vec4 vColor;
varying vec4 fColor;
uniform mat4 rx;
uniform mat4 ry;
uniform mat4 rz;
uniform mat4 traslation;
uniform mat4 scaling;
uniform mat4 modelView;
uniform mat4 projection;
varying vec4 vNormal;
uniform vec4 ambientProduct, diffuseProduct, specularProduct;
uniform vec4 lightPosition;
uniform float shininess;
varying vec3 N,L,E;
uniform bool changeShading;
void main()
{
if(changeShading) {gl_FragColor = fColor;}
else {vec4 fColor;
vec3 H = normalize( L + E );
vec4 ambient = ambientProduct;
float Kd = max( dot(L, N), 0.0 );
vec4 diffuse = Kd*diffuseProduct;
float Ks = pow( max(dot(N, H), 0.0), shininess );
vec4 specular = Ks * specularProduct;
if( dot(L, N) < 0.0 ) specular = vec4(0.0, 0.0, 0.0, 1.0);
fColor = ambient + diffuse +specular;
fColor.a = 1.0;
gl_FragColor = fColor;}
}
</script>
<script type="text/javascript" src="../Common/webgl-utils.js"></script>
<script type="text/javascript" src="../Common/initShaders.js"></script>
<script type="text/javascript" src="../Common/MV.js"></script>
<script type="text/javascript" src="Homework1.js"></script>
<body>
<canvas id="gl-canvas" width="1024" height="1024">
Oops ... your browser doesn't support the HTML5 canvas element
</canvas>
</body>
</html>
In the vertex shader are declared the varying (output) variables N, L, E. But they are never set, because there are identically named local variables which are set.
This causes that the values of the varying (input) variables N, L, E in the fragment shader are always (0, 0, 0).
The issue can be fixed by removing the declaration of the local variables and setting the varying outputs:
L = normalize( light - pos );
E = normalize( -pos );
N = normalize( (modelView*vNormal).xyz);

Adding contrast and brightness to image in flex

How can i implement brightness and contrast changes for image in flex
I need to develop a tool for adding brightness or contrast and reducing it
Use ColorMatrixFilter and assigned below matrix to its matrix property
var contrastAdj:ColorMatrixFilter = ColorMatrixFilter(filters.getItemAt(0));
contrastAdj.matrix = getContrastMatrix(value);
private static function getContrastMatrix(value:Number):Array
{
value /= 100;
var s: Number = value + 1;
var o : Number = 128 * (1 - s);
var m:Array = new Array();
m = m.concat([s, 0, 0, 0, o]); // red
m = m.concat([0, s, 0, 0, o]); // green
m = m.concat([0, 0, s, 0, o]); // blue
m = m.concat([0, 0, 0, 1, 0]); // alpha
return m;
}
for brightness matrix use this function
private static function getBrightnessMatrix(value:Number):Array
{
var m:Array = new Array();
m = m.concat([1, 0, 0, 0, value]); // red
m = m.concat([0, 1, 0, 0, value]); // green
m = m.concat([0, 0, 1, 0, value]); // blue
m = m.concat([0, 0, 0, 1, 0]); // alpha
return m;
}
pass values between -100 to 100 to functions.
You might use flash.geom.ColorTransform against an image, at least for previewing. If you need to have your image's pixels changed, I'd say use a Pixel Bender shader that will do what you need. Note however, you will need a backup copy should you desire to change the parameters of that shader.