Related
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.
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();
}
I'm converting a Flash application to HTML5 Canvas. Most of the development is finished but for handling the colors there is a code like this in the flash application:
matrix = new Matrix ();
matrix.createGradientBox (600, ColorHeight * 1200, 0, 80, ColorHeight * -600);
Animation_gradient_mc.clear ();
Animation_gradient_mc.beginGradientFill (fillType, colors, alphas, ratios, matrix, spreadMethod, interpolationMethod, focalPointRatio);
The declaration for a radial gradient in CreateJS is the following:
beginRadialGradientFill(colors, ratios, x0, y0, r0, x1, y1, r1 )
Does anyone know a method to apply a Matrix to a gradient fill?
Any help would be appreciated.
Thanks in advance
Edit
Here are some examples of the gradient I'm trying to reproduce:
As you can see it starts off as a standard radial gradient.
However, it can also appear stretched, I think this is where the matrix helps.
I've attempted to create the same effect by creating a createjs.Graphics.Fill with a matrix but it doesn't seem to be doing anything:
var matrix = new VacpMatrix();
matrix.createGradientBox(
600,
discharge_gradient.color_height * 1200,
0,
80,
discharge_gradient.color_height * -600
);
// test_graphics.append(new createjs.Graphics.Fill('#0000ff', matrix));
console.log('matrix', matrix);
test_graphics.append(new createjs.Graphics.Fill('#ff0000', matrix).radialGradient(
discharge_gradient.colors,
discharge_gradient.ratios,
discharge_gradient.x0,
discharge_gradient.y0,
discharge_gradient.r0,
discharge_gradient.x1,
discharge_gradient.y1,
discharge_gradient.r1
));
var discharge_shape = new createjs.Shape(test_graphics);
I extended the Matrix2d class to add a createGradientBox method using code from the openfl project:
p.createGradientBox = function (width, height, rotation, tx, ty) {
if (_.isUndefined(rotation) || _.isNull(rotation)) {
rotation = 0;
}
if (_.isUndefined(tx) || _.isNull(tx)) {
tx = 0;
}
if (_.isUndefined(ty) || _.isNull(ty)) {
ty = 0;
}
var a = width / 1638.4,
d = height / 1638.4;
// Rotation is clockwise
if (rotation != 0) {
var cos = math.cos(rotation),
sin = math.sin(rotation);
this.b = sin * d;
this.c = -sin * a;
this.a = a * cos;
this.d = d * cos;
} else {
this.b = 0;
this.c = 0;
}
this.tx = tx + width / 2;
this.ty = ty + height / 2;
}
I hope the extra information is useful.
I don't know createJS enough, nor Flash Matrix object, but to make this kind of ovalGradient with the native Canvas2d API, you will need to transform the context's matrix.
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var horizontalScale = .3;
var verticalScale = 1;
var gradient = ctx.createRadialGradient(100/horizontalScale, 100/verticalScale, 100, 100/horizontalScale,100/verticalScale,0);
gradient.addColorStop(0,"green");
gradient.addColorStop(1,"red");
// shrink the context's matrix
ctx.scale(horizontalScale, verticalScale)
// draw your gradient
ctx.fillStyle = gradient;
// stretch the rectangle which contains the gradient accordingly
ctx.fillRect(0,0, 200/horizontalScale, 200/verticalScale);
// reset the context's matrix
ctx.setTransform(1,0,0,1,0,0);
canvas{ background-color: ivory;}
<canvas id="canvas" width="200" height="200"></canvas>
So if you are planning to write some kind of a function to reproduce it, have a look at ctx.scale(), ctx.transform() and ctx.setTransform().
EDIT
As you noticed, this will also shrink your drawn shapes, also, you will have to calculate how much you should "unshrink" those at the drawing, just like I did with the fillRect. (agreed, this one was an easy one)
Here is a function that could help you with more complicated shapes. I didn't really tested it (only with the given example), so it may fail somehow, but it can also give you an idea on how to deal with it :
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
function shrinkedRadial(ctx, shapeArray, xScale, yScale, gradientOpts) {
// scaling by 0 is like not drawing
if (!xScale || !yScale) return;
var gO = gradientOpts;
// apply our scale on the gradient options we passed
var gradient = ctx.createRadialGradient(gO.x0 / xScale, gO.y0 / yScale, gO.r0, gO.x1 / xScale, gO.y1 / yScale, gO.r1);
gradient.addColorStop(gO.c1_pos, gO.c1_fill);
gradient.addColorStop(gO.c2_pos, gO.c2_fill);
// shrink the context's matrix
ctx.scale(xScale, yScale);
ctx.fillStyle = gradient;
// execute the drawing operations' string
shapeArray.forEach(function(str) {
var val = str.split(' ');
var op = shapesRef[val[0]];
if (val[1]) {
var pos = val[1].split(',').map(function(v, i) {
// if even, it should be an y axis, otherwise an x one
return i % 2 ? v / yScale : v / xScale;
});
ctx[op].apply(ctx, pos);
} else {
// no parameters
ctx[op]();
}
});
// apply our gradient
ctx.fill();
// reset the transform matrix
ctx.setTransform(1, 0, 0, 1, 0, 0);
}
// just for shortening our shape drawing operations
// notice how arc operations are omitted, it could be implemented but...
var shapesRef = {
b: 'beginPath',
fR: 'fillRect',
m: 'moveTo',
l: 'lineTo',
bC: 'bezierCurveTo',
qC: 'quadraticCurveTo',
r: 'rect',
c: 'closePath'
};
var gradientOpts = {
x0: 232,
y0: 55,
r0: 70,
x1: 232,
y1: 55,
r1: 0,
c1_fill: 'red',
c1_pos: 0,
c2_fill: 'green',
c2_pos: 1
}
var shapes = ['b', 'm 228,133', 'bC 209,121,154,76,183,43', 'bC 199,28,225,34,233,59', 'bC 239,34,270,29,280,39', 'bC 317,76,248,124,230,133']
// our shape is drawn at 150px from the right so we do move the context accordingly, but you won't have to.
ctx.translate(-150, 0);
shrinkedRadial(ctx, shapes, .3, 1, gradientOpts);
ctx.font = '15px sans-serif';
ctx.fillStyle = 'black';
ctx.fillText('shrinked radialGradient', 3, 20);
// how it looks like without scaling :
ctx.translate(50, 0)
var gO = gradientOpts;
var gradient = ctx.createRadialGradient(gO.x0, gO.y0, gO.r0, gO.x1, gO.y1, gO.r1);
gradient.addColorStop(gO.c1_pos, gO.c1_fill);
gradient.addColorStop(gO.c2_pos, gO.c2_fill);
ctx.fillStyle = gradient;
shapes.forEach(function(str) {
var val = str.split(' ');
var op = shapesRef[val[0]];
if (val[1]) {
var pos = val[1].split(',');
ctx[op].apply(ctx, pos);
} else {
ctx[op]();
}
});
ctx.fill();
ctx.font = '15px sans-serif';
ctx.fillStyle = 'black';
ctx.fillText('normal radialGradient', 160, 20);
<canvas id="canvas" width="400" height="150"></canvas>
A standard matrix would adjust inputs:
Width, angle Horizontal, angle Vertical, Height, pos X, pos Y in that order,
Here you are using gradientBox which is not the usual type of AS3 matrix. Expected input:Width, Height, Rotation, pos X, pos Y
I don't use createJS so I'm gunna guess this (you build on it)...
Your usual beginRadialGradientFill(colors, ratios, x0, y0, r0, x1, y1, r1 )
becomes like below (as though gradientBox matrix is involved):
beginRadialGradientFill(colors, ratios, posX, posY, Rotation, Width, Height, Rotation )
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;
}
I have the following problem: I have this multi-level array (nested array) which contains two rows of bitmapData. Row 1:360 rotated bitmapData objects; row 2: 360 rotated and colored bitmapData objects.
I try to access row 2 but that doesn't work. There are some mysterious error messages coming up ("TypeError: Error #1034: Type Coercion failed: cannot convert []#36d7e9e9 to flash.display.BitmapData. at BasicBlitArrayObject/updateFrame()").
Please can someone help me out with this problem? Thank you very much.
this function rotates and colors bitmapData; the rotated bitmapData is thrown into an array and the colored bitmapData is thrown into another array; a third array is used as a level array for nesting the other two arrays inside of it
public function createColoredRotationBlitArrayFromBD(sourceBitmapData:BitmapData, inc:int, offset:int = 0, color:Number = 1, $alpha:Number = 1):Array
{
tileList = [];
tileListSec = [];
levelArray = [tileList, tileListSec];
var rotation:int = offset;
while (rotation < (360 + offset))
{
var angleInRadians:Number = Math.PI * 2 * (rotation / 360);
var rotationMatrix:Matrix = new Matrix();
rotationMatrix.translate(-sourceBitmapData.width * .5, -sourceBitmapData.height * .5);
rotationMatrix.rotate(angleInRadians);
rotationMatrix.translate(sourceBitmapData.width * .5, sourceBitmapData.height * .5);
var matrixImage:BitmapData = new BitmapData(sourceBitmapData.width, sourceBitmapData.height,
true, 0x00000000);
matrixImage.draw(sourceBitmapData, rotationMatrix);
tileList.push(matrixImage.clone());
bitmapData = new BitmapData(matrixImage.width, matrixImage.height, true, 0x00000000);
bitmapData = matrixImage;
var colorMatrix:ColorMatrixFilter = new ColorMatrixFilter (
[color, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, 0, 0,
0, 0, 0, $alpha, 0]);
matrixImage.applyFilter(bitmapData, bitmapData.rect, point0, colorMatrix);
tileListSec.push(matrixImage.clone());
rotation += inc;
matrixImage.dispose();
matrixImage = null;
rotationMatrix = null;
bitmapData.dispose();
bitmapData = null;
colorMatrix = null;
}
return(levelArray);
}
creating my rotated and colored bitmapData
animationFrames = tempBlitArrayAsset.createRotationBlitArrayFromBD($bitmapData, 1, 270);
here I try to access the first row of my level array (that doesn't work; I can't access it)
tempEnemy.animationList = animationFrames;
tempEnemy.bitmapData = tempEnemy.animationList[1][tempEnemy.frame];
This function is for updating the frames
public function updateFrame(inc:int, row:int = 0):void
{
frame += inc;
if (frame > animationList.length - 1){
frame = 0;
}
bitmapData = animationList[row][frame];
}
}
this is a line showing how the updateFrame-function is used in my game (trueRotation is 0)
tempEnemy.updateFrame(tempEnemy.trueRotation);
I can't find anything wrong with createColoredRotationBlitArrayFromBD
var $bitmapData:BitmapData = new BitmapData(40,40,false, 0x7f7f7f);
var animationFrames:Array = createColoredRotationBlitArrayFromBD($bitmapData, 1, 270);
trace(animationFrames.length); // 2
trace(animationFrames[0].length); // 360
trace(animationFrames[1].length); // 360
var bitmap:Bitmap = new Bitmap();
this.addChild(bitmap);
bitmap.bitmapData = animationFrames[1][0]; // works..
That seems correct. Right? I get a red tinted bitmap.
The only 'bug' I see in the code you listed is in updateFrame
if (frame > animationList.length - 1){
frame = 0;
}
should probably be:
if (frame > animationList[row].length - 1){
frame = 0;
}
because animationList.length == 2
But everything else looks okay in the code you've provided, so without more code, i'm not sure there is anything to help.