Menu
  • HOME
  • TAGS

OpenGL ES 2D Matrix setup

Tag: matrix,vector,opengl-es,transformation,projection

I'm using OpenGL ES 2.0 to render only 2D shapes, since it's OpenGL ES 2.0 I have to create my own transformaton matrices.

Being only 2D shapes I'd like to keep all my matrices as 3x3 and my vectors with only 2 coordinates.

I also need a projection matrix as I would like to have my coordinates mapped to the screen, I don't want to specify positions from [-1.0; 1.0].

From what I've seen people still use 4x4 matrices for 2D and vectors with z set to 1, and an orthographic projection matrix.

My question is: How can I do all my transformations and the projection with only 3x3 matrices? I have all but the projection matrix set up, but the translation doesn't work.

So far I've done my translation matrix like this:

m[0][0] = 1;  m[0][1] = 0;  m[0][2] = tx;
m[1][0] = 0;  m[1][2] = 1;  m[1][2] = ty;
m[2][0] = 0;  m[2][3] = 0;  m[2][2] = 1;

And from what I can tell this should work, even with NDC coordinates, when multiplied by a vector it should result in

x+tx y+ty 1.0

But when I try to translate this triangle that goes from -1 to 1 with tx = 2f it gets squashed and doesn't move.

Before translation: enter image description here

After translation: enter image description here

for reference here is how I draw the triangle:

    GLES20.glUniformMatrix3fv(shader.GetUniform("u_transform_mat"), 1, false, Transform.GetTransformationMatrix().ToFloatBuffer()); 

    GLES20.glEnableVertexAttribArray(shader.GetAttribute("a_vert_position"));
    GLES20.glEnableVertexAttribArray(shader.GetAttribute("a_vert_color"));

    GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, VBO[0]);

    GLES20.glVertexAttribPointer(shader.GetAttribute("a_vert_position"), 2, GLES20.GL_FLOAT, false, Vertex.SIZE, 0);
    GLES20.glVertexAttribPointer(shader.GetAttribute("a_vert_color"), 4, GLES20.GL_FLOAT, false, Vertex.SIZE, Vertex.POS_SIZE);

    GLES20.glBindBuffer(GLES20.GL_ELEMENT_ARRAY_BUFFER, IBO[0]);    

    GLES20.glDrawElements(primitive, size, GLES20.GL_UNSIGNED_INT, 0);      

    GLES20.glDisableVertexAttribArray(shader.GetAttribute("a_vert_color"));
    GLES20.glDisableVertexAttribArray(shader.GetAttribute("a_vert_position"));

and my vertex shader

uniform mat3 u_transform_mat;   

attribute vec3 a_vert_position;  
attribute vec4 a_vert_color;     

varying vec4 v_vert_color;       

void main()                 
{                           
   v_vert_color = a_vert_color;       

   gl_Position = vec4(u_transform_mat * a_vert_position, 1.0);
}                                 

Best How To :

You can certainly use 3x3 matrices to apply affine transformations in 2D. You just have to be careful that you're consistent about it.

From a look at the code fragments you posted, there are two things that look problematic:

Matrices need to be column major

OpenGL expects matrices to be stored in column major order. From the way you build your matrix:

m[0][0] = 1;  m[0][1] = 0;  m[0][2] = tx;
m[1][0] = 0;  m[1][2] = 1;  m[1][2] = ty;
m[2][0] = 0;  m[2][3] = 0;  m[2][2] = 1;

this places the translation components where they would have to be for a row major matrix. It also assigns m[1][2] twice, and assigns m[2][3], which is out of range for a 3x3 matrix. In turn, it never assigns m[1][1] and m[2][1].

If you want to keep writing your matrices this way (which I agree is more readable), you can swap around the indices:

m[0][0] = 1;  m[1][0] = 0;  m[2][0] = tx;
m[0][1] = 0;  m[1][1] = 1;  m[2][1] = ty;
m[0][2] = 0;  m[1][2] = 0;  m[2][2] = 1;

3rd vector component needs to be 1.0

You're specifying two components for your vertex position attribute, which makes sense:

GLES20.glVertexAttribPointer(shader.GetAttribute("a_vert_position"), 2,
                             GLES20.GL_FLOAT, false, Vertex.SIZE, 0);

But then in the shader, you have this:

attribute vec3 a_vert_position;

Declaring the attribute variable larger than the number of components passed into the shader is perfectly legal. Unspecified components are filled with 0.0 for components y and z, and 1.0 for w. Therefore, in your shader code, a_vert_position.z will be filled with 0.0. If you then multiply it with the 3x3 transformation matrix:

u_transform_mat * a_vert_position

This means that the translation part will not be applied. Just like the 4th component needs to 1.0 when applying 4x4 matrices to 4 component vectors for an affine transformation in 3D space, the 3rd component needs to be 1.0 when applying 3x3 matrices to 3 component vectors for an affine transformation in 2D space.

The easiest way to fix this is to declare the attribute as vec2, and add 1.0 as the 3rd component when applying the transformation matrix:

attribute vec2 a_vert_position;
...
   gl_Position = vec4(u_transform_mat * vec3(a_vert_position, 1.0), 1.0);

How to print the right hemisphere of a square matrix

c++,algorithm,matrix

I think this should work for square matrices: void printHemisphere(int matrix[N][M], int n, int m) { int mid = n / 2; for(int i = 1; i < mid; i++) { for (int j = n - i; j < m; ++j) { std::cout << matrix[i][j] << " "; }...

How to calculate a random point inside a cube

math,vector,3d,cube

Generate the points in the straight position then apply the rotation (also check the origin of the coordinates).

MATLAB removing rows which has duplicates in sequence

arrays,matlab,matrix

So you want to remove rows of A that contain at least t zeros in sequence. How about a single line? B = A(~any(conv2(1,ones(1,t),2*A-1,'valid')==-t, 2),:); How this works: Transform A to bipolar form (2*A-1) Convolve each row with a sequence of t ones (conv2(...)) Keep only rows for which the...

Creating a matrix based on a function in R

r,matrix,data.frame

Is that what you want? 1-cov2cor(A) [,1] [,2] [,3] [,4] [,5] [1,] 0.0000000 0.5232687 0.6348516 0.7000000 0.8174258 [2,] 0.5232687 0.0000000 0.5648059 0.6186150 0.7388835 [3,] 0.6348516 0.5648059 0.0000000 0.5435645 0.5000000 [4,] 0.7000000 0.6186150 0.5435645 0.0000000 0.8174258 [5,] 0.8174258 0.7388835 0.5000000 0.8174258 0.0000000 ...

I can't fix camera to any object in a 2D Matrix

c#,matrix,camera,xna,viewport

The reason you are getting NullReferenceException is because GraphicsDevice is not initialized yet. Instead of creating your Camera in the TheGame constructor, create it in the Initialize method: protected override void Initialize() { base.Initialize(); camera = new Camera(GraphicsDevice); } How to make camera fixed on any object in the Matrix...

Matlab - Multiply specific entries by a scalar in multidimensional matrix

matlab,matrix,multidimensional-array,scalar

Errr, why you multiply indexes instead of values? I tried this: comDatabe(:,:,[1 2 3],:,8) = comDatabe(:,:,[1 2 3],:,8)*-1 And it worked....

What is an efficient way of multiplying massive polynomials in Java?

java,matrix,polynomials

Maybe this idea will help you to solve your problem: int result = 1; int x = 2; int y = 3; Integer [][] polynomials = new Integer[x][y]; polynomials[0][0] = 1; polynomials[0][1] = 2; polynomials[0][2] = 3; polynomials[1][0] = 4; polynomials[1][1] = 5; polynomials[1][2] = 6; for(int i = 0;...

Is it bad (or even dangerous) to random_shuffle vector of shared_ptrs?

c++,vector,shared-ptr,smart-pointers,shuffle

No, there is nothing bad or inefficient in this. std::random_shuffle only swaps the elements of the cointainer in some random way. std::swap is specialized for std::shared_ptr's, so it is safe and as efficient as swapping two pairs of raw pointers, without lots of reference counts could be going up and...

Sending vector data in the bus

vector,simulink,bus

The main idea is to create Bus of type you need. I did it this way: num = zeros(15,15,15); move = zeros(15,15,15); a = struct('number',num,'movement', move); busInfo = Simulink.Bus.createObject(a); You can see it's possible to create any data structure, array, vector anything you want and then create Bus Signal of...

How to solve for matrix in Matlab?

matlab,matrix,least-squares

Rewrite the quantity to minimise as ||Xa - b||^2 = (definition of the Frobenius norm) Tr{(Xa - b) (Xa - b)'} = (expand matrix-product expression) Tr{Xaa'X' - ba'X' - Xab' + bb'} = (linearity of the trace operator) Tr{Xaa'X'} - Tr{ba'X'} - Tr{Xab'} + Tr{bb'} = (trace of transpose of...

Inserting One Row Each Time in a Sequence from Matrix into Another Matrix After Every nth Row in Matlab

arrays,matlab,matrix

Here's another indexing-based approach: n = 10; C = [A; B]; [~, ind] = sort([1:size(A,1) n*(1:size(B,1))+.5]); C = C(ind,:); ...

C language, vector of struct, miss something?

c,vector,struct

What is happening is that tPeca pecaJogo[tam]; is a local variable, and as such the whole array is allocated in the stack frame of the function, which means that it will be deallocated along with the stack frame where the function it self is loaded. The reason it's working is...

Storing columns on disk and reading rows

c++,file,matrix,io

Mentioned solution with fseek is good. However, it can be very slow for large matrices (as disks don't like random access, especially very far away). To speed up things, you should use blocking. I'll show a basic concept, and can explain it further if you need. First, you split your...

How do I apply multiple matrices in spriteBatch.Draw()?

c#,matrix,xna

Simply multiply the matrices before passing to spriteBatch.Begin. Matrix multiplication allows the effects of both matrices appended into a single matrix. Note that this operation is not commutative, meaning that A * B != B * A. In your case, you should probably multiply scaling matrix with the camera matrix....

R: recursive function to give groups of consecutive numbers

r,if-statement,recursion,vector,integer

Your sapply call is applying fun across all values of x, when you really want it to be applying across all values of i. To get the sapply to do what I assume you want to do, you can do the following: sapply(X = 1:length(x), FUN = fun, x =...

Computing time complexity of the sparse matrix (2)

r,matlab,matrix,sparse-matrix

For every (i, j) pair (there are n^2 in total), you reach the inner part of the loop where you find the similarity and then conditionally add elements to your sparse matrix. Finding the similarity takes "d" operations (because you need to loop through each of your dimensions) and conditionally...

R Program Vector, record Column Percent

r,vector,percentage

Assuming that you want to get the rowSums of columns that have 'Windows' as column names, we subset the dataset ("sep1") using grep. Then get the rowSums(Sub1), divide by the rowSums of all the numeric columns (sep1[4:7]), multiply by 100, and assign the results to a new column ("newCol") Sub1...

create vector of objects on the stack ? (c++)

c++,vector,heap-memory

Yes, those objects still exist and you must delete them. Alternatively you could use std::vector<std::unique_ptr<myObject>> instead, so that your objects are deleted automatically. Or you could just not use dynamic allocation as it is more expensive and error-prone. Also note that you are misusing reserve. You either want to use...

Factorial of a matrix elementwise with Numpy

python,numpy,matrix,factorial

There's a factorial function in scipy.misc which allows element-wise computations on arrays: >>> from scipy.misc import factorial >>> factorial(mat) array([[ 1., 2., 6.], [ 2., 6., 24.]]) The function returns an array of float values and so can compute "larger" factorials up to the accuracy floating point numbers allow: >>>...

TypeError: zip argument #1 must support iteration (Vector sum for Ipython)

python,vector,ipython,linear-algebra,ipython-notebook

If you do vector_sum(a) the local variable result will be the integer "1" in your first step which is not iterable. So I guess you simply should call your function vector_sum like vector_sum([a,b,a]) to sum up multiple vectors. Latter gives [4,7,10] on my machine. If you want to sum up...

Cannot Properly Print Contents of Vector

c++,arrays,string,vector,segmentation-fault

You said: I have some C++ code where I'm taking input from a user, adding it to a vector splitting the string by delimiter, and for debugging purposes, printing the vector's contents. And your code does: while (true) { //Prints current working directory cout<<cCurrentPath<<": "; /// /// This line of...

decltype does not resolve nested vectors. How can I use templates for nested vectors?

c++,templates,vector,nested

My other answer on here explains why your approach failed and one possible approach for a solution. I just thought of a much, much simpler one that I thought was worth sharing. The problem is that you can't use a trailing return type because the function name itself isn't in...

Have an if statement look ONLY at the first word in a string [duplicate]

c++,string,if-statement,vector

The first line places string beginning with 'abc' at the end, and the second erases them from the vector. auto end_it = std::remove_if(myvec.begin(), myvec.end(), [](const string &str){ return str.find("abc") == 0 ;}) ; myvec.erase(end_it, myvec.end()) ; ...

Who should clear a vector retrieved by reference?

c++,vector,pass-by-reference

In you first example the function is called "getVector" which is appropriate to describe what the function does. It returns a vector with a certain number of elements, as expected. In the second example the same does not apply. The function is still called "getVector" but now you want to...

complexity of generating a sparse matrix

r,matlab,matrix,sparse-matrix

When converting from a full representation of a symmetric matrix to a sparse representation, you will need to scan all the elements on the main diagonal and above (or symmetrically on the main diagonal and below). For an (n x n) matrix matrix this is (n^2+n)/2 entries that need to...

How can I generate all the possible combinations of a vector

r,vector

Try combn(v1, 2, FUN=function(x) paste(rev(x), collapse="-")) #[1] "B-A" "C-A" "D-A" "E-A" "C-B" "D-B" "E-B" "D-C" "E-C" "E-D" If you want in the default order combn(v1, 2, FUN=paste, collapse="-") #[1] "A-B" "A-C" "A-D" "A-E" "B-C" "B-D" "B-E" "C-D" "C-E" "D-E" Update For a faster option, you can use combnPrim from grBase....

find indices x,y of a matrix of specific values in python

python,matrix,multidimensional-array,indices

You need to change your where line to something like: data_indices = numpy.where((data<=obj_value_max) & (data>=obj_value_min)) Notice the ()s around each conditional clause and the use of & (meaning "and"). This works because in numpy, <,<=,>,>=,&,|,... are overridden, i.e. they act differently than in native python. and and or cannot be...

Create a Triangular Matrix from a Vector performing sequential operations

r,for-loop,matrix,vector,conditional

Using sapply and ifelse : sapply(head(vv[vv>0],-1),function(y)ifelse(vv-y>0,vv-y,NA)) You loop over the positive values (you should also remove the last element), then you extract each value from the original vector. I used ifelse to replace negative values. # [,1] [,2] [,3] [,4] [,5] # [1,] NA NA NA NA NA # [2,]...

How to set first column to a constant value of an empty np.zeros numPy matrix?

python,numpy,matrix,modeling

All you have to do is to change head[0][0:] to head[:,0]=16 If you want to change the first row you can just do: head[0,:] = 16 EDIT: Just in case you also wonder how you can change an arbitrary amount of values in an arbitrary row/column: myArray = np.zeros((6,6)) Now...

program failed. sharedPtr vector c++

c++,vector

The error location is 0x00000044, which usually means that this was NULL in the method call, while it is trying to access a member variable (at location this+0x44 in this case). Check that you are not calling addArtist() on a NULL Company* pointer....

Numpy and dot products of multiple vector pairs: how can it be done?

python,numpy,matrix,scipy

np.einsum would do it: np.einsum('ij,ij->i', a_vec, b_vec) ...

Sum of n-1 columns of a double matrix in MATLAB

matlab,matrix

You can do that by using the function cumsum: A = [1 2 3 4 5 6]; C = cumsum(A); out = [0 C(1:end-1)] now out is: [0 1 3 6 10 15]...

Unable to convert between 1d and 2d array values

java,arrays,matrix,2d

All arrays start by 0, try this: public static void main(String[] args) { int testSize = 4; Test test = new Test(testSize); for (int i = 0; i < testSize; i++) { for (int j = 0; j < testSize; j++) { int index = test.toIndex(i, j); int coordinates[] =...

Reordering vector of vectors based on input vector

c++,c++11,vector,stl,idioms

If you transpose the data, it's as easy as sorting the vectors by the index of the first element in them. This will be slower than your solution but may be more readable: void fix_order(std::vector<std::vector<std::string>>& data, const std::vector<std::string>& correct) { // setup index map, e.g. "first" --> 0 std::unordered_map<std::string, size_t>...

Add same value multiple times to std::vector (repeat)

c++,vector,std

It really depends what you want to do. Make a vector of length 5, filled with ones: std::vector<int> vec(5, 1); Grow a vector by 5 and fill it with ones: std::vector<int> vec; // ... vec.insert(vec.end(), 5, 1); Or resize it (if you know the initial size): std::vector<int> vec(0); vec.resize(5, 1);...

Interpolation inside a matrix. Matlab

matlab,matrix

M =[0 0 0 0 0 1 0 0 0 0 0 2 0 0 0 0 0 2 0 0 0 0 0 1 0 1 0 0 0 1 0 4 0 0 0 0 0 3 0 0 6 0 0 4 0 0 3 0 0...

Sorting vector of Pointers of Custom Class

c++,sorting,c++11,vector

The only error that I see is this>current_generation_.end() instead that ->. In addition you should consider declaring your compare fuction as accepting two const FPGA* instead that just FPGA*. This will force you to declare fitness() as const int fitness() const but it makes sense to have it const. Mind...

how to sort this vector including pairs

c++,vector

You forgot the return statement in the function bool func(const pair<int,pair<int,int> >&i , const pair<int,pair<int,int> >&j ) { i.second.first < j.second.first ; } Write instead bool func(const pair<int,pair<int,int> >&i , const pair<int,pair<int,int> >&j ) { return i.second.first < j.second.first ; } Also you should include header <utility> where class std::pair...

How to render a matrix of objects to table with combined cells

javascript,html,css,arrays,matrix

Solved with code below var data = [[ {"value": "1"}, {"value": "1"}, {"value": "1"} ], [ {"value": "2"}, {"value": "2"}, {"value": "3"} ], [ {"value": "2"}, {"value": "2"}, {"value": "3"} ], [ {"value": "4"}, {"value": "4"}, {"value": "5"} ]]; function renderCombinedTable(data) { var cell = []; var rows = data.length...

Analytical solution for Linear Regression using Python vs. Julia

python,matrix,julia-lang

A more numerically robust approach in Python, without having to do the matrix algebra yourself is to use numpy.linalg.lstsq to do the regression: In [29]: np.linalg.lstsq(X, y) Out[29]: (array([[ 188.40031942], [ 0.3866255 ], [ -56.13824955], [ -92.9672536 ], [ -3.73781915]]), array([], dtype=float64), 4, array([ 3.08487554e+03, 1.88409728e+01, 1.37100414e+00, 1.97618336e-01])) (Compare the...

sorting vector of pointers by two parameters

c++,sorting,vector

(b->y < a->y - offset) || (b->y > a->y + offset) These are two different cases, which should have different results. I suppose that b is "less" then a in first case, and "greater" in the other case, but your code returns false for both cases. See @Jonathan's answer on...

OpenLayers 3: simple LineString example

javascript,vector,openlayers,openlayers-3

Just change this: var points = [ new ol.geom.Point([78.65, -32.65]), new ol.geom.Point([-98.65, 12.65]) ]; To: var points = [ [78.65, -32.65], [-98.65, 12.65] ]; The ol.geom.LineString constructor accept an array of coordinates....

Extract raw model matrix of random effects from lmer objects (lme4, R)

r,matrix,sparse-matrix,lme4,lmer

If mmList is there, then it's not going away (however poorly documented it may be -- feel free to suggest documentation improvements ...). How about do.call(cbind,getME(m2,"mmList")) (which would seem to generalize correctly for multi-term models)? I agree that it's a bit of a pain that Zt doesn't distinguish correctly between...

reinterpret_cast vector of derived class to vector of base class

c++,vector,c++03

To answer the question from your code : No, it's actually a very bad practice , and it will lead to undefined behavior. If sizeof(A) is equal to sizeof(B) your code might end up working ,considering that all functions derived in B and used inside f3 are virtual and non...

Add a matrix of 2x2 into a vector in c++

c++,matrix,vector

You cannot push back a matrix into a vector. What you can do is preallocate memory for your vector (for speeding things up) then use the std::vector<>::assign member function to "copy" from the matrix into the vector: vector<int> collectionSum(gray.rows * gray.cols); // reserve memory, faster collectionSum.assign(*auxMat, *auxMat + gray.rows *...

Debug error: Vector iterator not dereferencable and Vector subscript out of range [closed]

c++,vector,stl,iterator

Just need to add after if (!found) { break; } that else { found = false; } If it is equal relationship.size() that means that no one item has been found. Anyway, found was not updated to false after each for loop, so if it find just one time an...

Join matrices with same values in different vectors in MATLAB

matlab,matrix,merge

You don't need to use a loop, use intersect instead. [~,ic,ip] = intersect(c(:, 1:3),p(:, 1:3),'rows'); m = [c(ic, :), p(ip,end)]; Edit: If you want to include NaNs where they don't intersect like the above poster. function m = merge(c, p, nc, np) %check for input arg errors if nargin ==...

Modify a matrix in ocaml

matrix,ocaml

In an expression the = operator in OCaml is a comparison operator that tests for equality. To assign to an array, use the <- operator. The compiler is complaining because your expression has type bool (i.e., the result of the comparison). The expression in a for should have type unit...