I have a lot of cubes (ex 100) that are all part of the same mesh, and in a vertex shader I would like to scale each cube along a given axis, so it's top is moved and the cube stretched like this:

Each cube has an `ID`

, and each vertex has a corresponding `ID`

, so each vertex knows what cube it is part of. A uniform array of vec3 normalized `cubeUps`

(the direction the cubes should be expanding) and a uniform array of vec3 `cubeOrigins`

(the base of each cube) is also passed to the shader. The indices of these uniform arrays match the `ID`

's of the cubes.

Right know the `cubeOrigins`

of the cubes are placed at the center of the bottom of each cube like the white dot here, because I think that is what's needed, but not sure:

I can very easily translate the cubes along the given `normal`

like this:

```
layout (location = 0) in vec3 vertexPos;
layout (location = 1) in vec3 vertexNor;
layout (location = 2) in float vertexCubeId;
uniform mat4 mvp;
uniform vec3 cubeUps[100];
uniform vec3 cubeOrigins[100];
void main()
{
int cubeIndex = int(vertexCubeId);
vec3 cubeUp = cubeUps[cubeIndex];
vec3 cubeOrigin = cubeOrigins[cubeIndex];
vec3 transformedPos = vertexPos;
transformedPos.x += cubeUp.x;
transformedPos.y += cubeUp.y;
transformedPos.z += cubeUp.z;
gl_Position = mvp * vec4(transformedPos, 1.0);
}
```

but my plan for doing the scaling is not working out. What I think I need to do is:

- Subtract the origin from the vertex, to use a common base for the scaling.
- Do the scaling along the 'cubeUp' vector somehow.
- Add the origin to the vertex to move away from the base again.

Something like this:

```
...
float scaleFactor = 1.5f;
vec3 scale = cubeUp * scaleFactor;
transformedPos.x -= cubeOrigin.x;
transformedPos.y -= cubeOrigin.y;
transformedPos.z -= cubeOrigin.z;
transformedPos.x *= scale.x;
transformedPos.y *= scale.y;
transformedPos.z *= scale.z;
transformedPos.x += cubeOrigin.x;
transformedPos.y += cubeOrigin.y;
transformedPos.z += cubeOrigin.z;
gl_Position = mvp * vec4(transformedPos, 1.0);
...
```

But this both moves the cubes to undesired positions, and doesn't scale them correctly.

Do I somehow need to rotate the vertex coordinates before applying the scale, in order to use the origin correctly?

How do I get from the given `cubeUp`

vector to the correct values to use for the scaling?

Answer:

Take the dot product of the vertex (after subtracting the origin) in the direction of `cubeUp`

and then scale it and add to the vertex position. This will ensure that the vertices only move in the direction of `cubeUp`

. Something like this:

```
float scaleFactor = 1.5f;
transformedPos.x -= cubeOrigin.x;
transformedPos.y -= cubeOrigin.y;
transformedPos.z -= cubeOrigin.z;
float dotProduct = dot(cubeUp, transformedPos);
dotProduct *= (scaleFactor - 1.0f); // or just set scaleFactor
// to 0.5f in the first place
vec3 offset = cubeUp * dotProduct;
transformedPos.x += offset.x;
transformedPos.y += offset.y;
transformedPos.z += offset.z;
transformedPos.x += cubeOrigin.x;
transformedPos.y += cubeOrigin.y;
transformedPos.z += cubeOrigin.z;
```

To visualize why simply multiplying by a scale vector doesn't work, imagine a vertex on the plane defined by `cubeOrigin`

and `cubeUp`

(i.e. the base of the cube). It shouldn't move at all. However each of the corner vertices is going to have a non-zero `transformedPos`

vector, which means that the values will not be the same after multiplying by `scale`

, except in the special case where `cubeUp`

points exactly along the X Y or Z axis.

You need to specifically multiply just that part of the `transformedPos`

vector that is in the direction of `cubeUp`

, which is equal to `dot(cubeUp, transformedPos) * cubeUp`

. Instead of subtracting that part then multiplying by 1.5 then re-adding it, it's more efficient to just multiply by 0.5 and add it.

c++,loops,math

I have to solve problem using c++, and can't really come up with solution. The condition is. In a skyscraper there are a lot of offices, on every office door there must be put plate with its number from 1 to the number of the last office. The plate can...

linux,bash,math

I am new to Linux, and I just want a Bash Script to do basic arithmetic operation to a text file 1 2 3 4 and the results should be addition and multiplication in separate text files say add + 5 for 1st text file and mult * 5 in...

java,math,set,linkedhashset

I am trying to do a homework in math which is find a subset of collection {1,2,..,n} where n is a number given in the code, I cannot get it done with the sublist so I need to get your help with a math programming. For example for n =...

algorithm,math,statistics,variance,standard-deviation

I'm successfully using Welford's method to compute running variance and standard deviation as described many times on Stack Overflow and John D Cook's excellent blog post. However in the stream of samples, sometimes I encounter a "rollback", or "remove sample" order, meaning that a previous sample is no longer valid...

c++,arrays,opengl

I'm trying to create a textureLoader class for my openGL project and I can't initialize an array of textures inside of my class constructor because the the array won't accept anything unless it's a const int. To paint you a simple picture... myFunction(NUM) { GLuint textures[NUM]; } My past Failures...

c++,c,opengl,shader

In OpenGL what is the difference between glUseProgram() and glUseShaderProgram()? It seems in MESA and Nvidia provided glext.h, and in GLEW, both are defined, and both seem to do basically the same thing. I find documentation for glUseProgram() but not for glUseShaderProgram(). Are they truly interchangeable?...

math,big-o,time-complexity,asymptotic-complexity

I am doing this small task which I have to arrange asymptotic runtime in ascending order. Here are the runtimes: Here is the order I believe they should go in: log10(n^4), n^3, 2^((log4n)), 2^(100n), e^pi^4096, n! + 12^1000 Is this correct? Or are there any errors? Thanks!...

opengl,glsl,webgl

I'm aiming for this effect: (horizontal-only contour lines): I did find this example, however it creates horizontal and vertical contour lines. I can't quite wrap my head around how the call to fwidth() is generating the lines. uniform float gsize;//size of the grid uniform float gwidth;//grid lines'width in pixels varying...

c++,opengl

I have a (default vertex and) fragment shader that should resize textures and scale their color by a specific factor for brightness correction. The result is rendered into an GL_UNSIGNED_INT_8_8_8_8 framebuffer. #version 330 uniform sampler2D tex; uniform vec2 screenSize; uniform float scale; layout(location = 0) out vec4 color; void main()...

java,math,multiplication,string-length

Lets see if someone can wrap their head around this: if you get the length of a String using length(), the String always being multiples of 3,(in my case: "1.02.03.04.05.06.07.0 etc.") each 3 characters representing a letter, with .1 indicating a capitol letter, how do you use the length to...

c,opengl

I'm loading a cubemap to create a skybox, everything is fine and the skybox renders properly with a correct texture application. However, I decided to check my program safety with valgrind, Valgrind gives this error: http://pastebin.com/seqmXjyx The line 53 in sky.c is: glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB, texture.width, texture.height, 0,...

java,opengl

Trying to find a way to render a simple 2D image in Java using OpenGL I stumbled upon a more or less understandable class that does all of the image loading for you which I could not understand how to do. I believe it belongs to a person named Krythic...

c,math,largenumber,integer-arithmetic

I've wrote an implementation of Murmur3 hash and have defined the 128-bit keys as hash128_t typedef struct { uint64_t p1; uint64_t p2; } hash128_t; I'm trying to write my own hashmap using these keys, but I'm not exactly sure how to do arithmetic with a struct nor a number this...

c++,algorithm,math,recursion

I'm trying to find all possible solutions to the 3X3 magic square. There should be exactly 8 solutions. My code gets them all but there are a lot of repeats. I'm having a hard time tracking the recursive steps to see why I'm getting all the repeats. // This program...

opengl,glsl

My OpenGL program, using GLSL for shaders, has a simple vertex and fragment shader (given by a tutorial). The vertex shader is: #version 330 layout (location = 0) in vec3 Position; void main() { gl_Position = vec4(0.5 * Position.x, 0.5 * Position.y, Position.z, 1.0); } And the fragment shader is:...

math,vector,3d,cube

I'm trying to figure out the math to find a random point inside a cube. I have something small but it can't take into account the rotation of the cube. Here are some images of my results. Here you can see the cube is rotated to some degree but when...

math,fpga,cordic

I'm studying the cordic. And I found the cordic gain. K=0.607XXX. From CORDIC, K_i = cos(tan^-1(2^i)). As I know the K is approched 0.607xxx.when I is going to infinity this value come up with from all K multiplying. I understand the reason of exist each k. But I am curioused...

java,math

I did a code like this: public static double myPow(double x, int n){ if(n==0) return 1; double t = myPow(x, n/2); if(n % 2 != 0){ if(n < 0){ return (1 / t * t * x); } else { return t * t * x; } } else {...

java,opengl,lwjgl

I'm following a tutorial on youtube but I have a problem with OpenGL that I'm not able to solve. I have no idea how I can fix it. Exception in thread "EndlessRunner" java.lang.IllegalStateException: No OpenGL context is current in the current thread. at org.lwjgl.opengl.GLContextWindows.createFromCurrent(GLContextWindows.java:61) at org.lwjgl.opengl.GLContext.createFromCurrent(GLContext.java:36) at net.alfredo.Main.init(Main.java:59) at net.alfredo.Main.run(Main.java:91)...

matlab,math

The follow plot shows my question: I would like to add a line between the points of 1e-1 and 1e-2. So I thought just (1e-1+1e-2)/2. But for a log scale that is not "midway". How can I calculate the "visual" midway value between these, or any two points in this...

c++,opengl,visualization,simulation,heatmap

I'm working on a simulation for clouds (actual clouds) where the clouds are simulated by 3D points, then projected into a 2D heatmap, about 640x480 units big. The number of points is about 50k, which is as small as I can go without the simulation breaking, but I can't seem...

math,javafx,geometry,coordinates

I have a line which has points (x1,y1) and (x2,y2). I wanted to attach a Button to it, it should align with the line by rotating based on the line segment points. I need some help in calculating the rotation angle for the Button.

c++,math,rotation,rotational-matrices,separating-axis-theorem

The problem is in Polygon::FindAxisLeastPenetration: double Polygon::FindAxisLeastPenetration(unsigned int *faceIndex, const Polygon &polygonA, const Polygon &polygonB) const { double bestDistance = -std::numeric_limits<double>::infinity(); unsigned int bestIndex; for (unsigned int i = 0; i < polygonA.points.size(); i++) { Vector2D n = polygonA.normals[i]; Vector2D nw = polygonA.rotationMatrix * n; //ROTATION Matrix22 buT = polygonB.rotationMatrix.Transposed();...

opengl,glsl

Ideally, what I'd like to do is draw a single quad and have GLSL handle the creation of the actual gridlines. In my attempt so far the vertex shader: #version 400 layout (location = 0) in vec4 in_position; layout (location = 2) in vec3 in_UV; uniform mat4 model; uniform mat4...

c++,opengl,opencl

I was debugging a project that depends on a set of libraries including libfreenect, OpenGL and OpenCL. The problem is that a black screen was the output. As a debugging option, I have removed the OpenCL code and the linked library completely trying to make sure that OpenGL works fine...

python,algorithm,sorting,math

I am looking for a basic algorithm that gives more weigh to the recent reviews. So, the output value of the algorithm is mutable. For example, two reviews with exactly the same score, will have a different ranking based on the timestamp of the creation. Review_1 Score 10 creation 10/5/2014...

c++,opengl,textures,texturing

I am trying to program a simple game in C++ using OpenGL for graphics. In my game, I have objects that are rendered onscreen as a white square. I would like to be able to bind an image as a texture to these objects, so that I can render an...

algorithm,math,time-complexity,computer-science,recurrence-relation

I need to solve the exact time complexity for the brute force version of the Traveling Salesman using a recurrence relation. I've worked out the recurrence relation to be as follows: T(n)=T(n-1)*(n-1)+1 But I'm having trouble reducing that that to a closed form of the function, and thus get the...

c++,opengl,glfw

I am working on a small OpenGL project using the GLFW library. Everything was fine until from one day, I can't get it to render anything except the background. So I loaded up an older version, which I am sure worked just fine and the same thing happens. I then...

python,math

I'm writing a python script to find out some things about randomization. I have the following code: from random import randint one = 0 two = 0 olddiff = 0 diff = 0 sumdiff = 0 avgdiff = 0 headcounter = 0 counter = 0 while (headcounter < 500000): while...

arrays,matlab,math,for-loop,while-loop

This is my one dimensional array A, containing 10 numbers: A = [-8.92100000000000 10.6100000000000 1.33300000000000 ... -2.57400000000000 -4.52700000000000 9.63300000000000 ... 4.26200000000000 16.9580000000000 8.16900000000000 4.75100000000000]; I want the loop to go through like this; (calculating mean interval wise) - Interval length of 2,4,8 (a(1)+a(2))/2 - value stored in one block of...

c++,opengl

Consider a situation , Case 1 : I am giving opengl calls to draw the world by drawing all polygons. So all polygons will be drawn according to all objects exist. (Considered all translation rotation). Case 2 : I will allow only polygons that are in field of view(FOV) of...

arrays,matlab,loops,math,for-loop

I want to store mean_2....mean_8, std_2....std_8, and coVariance as separate columns in a file. Help Please? This Code calculates IntervalFeatures of Erp signal with 256 time frames and plots them Datapoints are store in A ___________HowTheCodeWorks________________________________________________ each 1x4 sliding sub-matrix is made a column for eg:- if A is...

opengl,textures,scale

I have a rectangle in opengl 2 and I'm using a texture for it. It Works, but the texture is repeated over the rectangle, and what I want is to adapt to the size of the rectangle. I have read in this tutorial about the different parameters you can set...

c++,opengl,access-violation

I am making an OpenGL project in Visual Studio 2010. I am following a tutorial from youtube. I don't know where the error is, and I have this error: Unhandled exception at 0x00000000 in OpenGL First Game.exe: 0xC0000005: Access violation. Main.cpp #include <GL/glew.h> #include <iostream> #include <GL/glut.h> #include "Sprite.h" Sprite...

math,cordic

How can we use cordic to tanh(x+1)/tanh(x) I can't get a idea about how to apply cordic to above function. In other word, which point on the above function, can we apply cordic?...

opengl,state-machines,render-to-texture

I try to create a FrameBuffer with 2 textures attaching to it (Multi Render Targets). Then in every time step, both textures are cleared and painted, as following code. (Some part will be replaced as pseudo code to make it shorter.) Version 1 //beginning of the 1st time step initialize(framebufferID12)...

math,unity3d,numbers

I'm working on a project where I have a pane that goes from 0 to 500 on the x and z, but I need to convert that coordinate (from 0 to 500) to a float in the range of 0.0 to 1.0 in because it is required from some of...

math,vhdl,fpga,rtl,cordic

From CORDIC, K_i = cos(tan^-1(2^i)). As I know the K is approached 0.607xxx. How do I approach to 0.607xxx? Also does it mean that I can use 0.607xxx instead of cos(tan^-1(2^I))? I am citing from this article. I am trying to implement hyperbolic tanh function. And so far I understand...

c++,opengl,graphics,shader,shadow

I've been following a two part tutorial on shadow mapping from OGLDev (part 1, part 2) for a couple of days now, and I've nearly finished implementing it. My problem is that when I enable shadow maps the illuminated region which shadows appear in appears as a "strip" and I'm...

c++,opengl,opengl-es,integer,shader

I'm following the "OpenGL Superbible" book and I can't help but notice that when we create a shader and create the program that we attach the shaders to, we store them as GLuint which are unsigned integers. Why are they stored as numbers? What does the value of the number...

java,opengl

I am trying to write a Java programm using LWJGL 3 and so far I've made it to creating a window, rendering to it and getting basic input. But I've ran into a problem with creating GUI and namely text fields that my programm requires. I found information that there...

python,math,rounding

This question already has an answer here: How do you round UP a number in Python? 9 answers Python round up integer to next hundred 6 answers so i'm making a pizza program in Python 3.3 that takes input from the user and prints the amount of pizza's needed....

javascript,excel,math

In my javascript code I have the following Math.log(20) = 2.995732273553991 In my excel formula I try to replicate this with =LOG(20) = 1.301029996 Anyone have any idea why I'm getting two different outcomes? I'd like my excel to match my js. ...

c++,math,geometry,angle

C++, I want calculate the angle of the direction of the two points. Here is a picture which shows the two points and the direction of how to get the angle of the direction? p1 - start point. p2 - direction point. me need direction angle(facing?) from p1 to p2...

javascript,arrays,math

i was playing around in code academy and for some reason when i change the last slaying i the else statement to true instead of making the person invincible it just crashes my browser any ideas why thank you in advance var slaying = true; var youHit = Math.floor(Math.random()*2); var...

python,math,combinations,itertools

Other than doing this: from itertools import combinations def brute_force(x): for l in range (1,len(x)+1): for f in list(combinations(range(0,len(x)),l)): yield f x = range(1,18) len(list(brute_force(x))) [out]: 131071 How could I mathematically calculate the number of all possible combinations? Is there a way to do it computationally without enumerating the possible...

c,opengl,struct,code-separation

I was trying to put all GLFW3 init code from main to separate file. When I'm running the code, I get EXC_BAD_ACCESS on glew init function, because GLFW could not create window. Before code separation everything was ok. Is it possible to have GLFW setup code in other function? I'm...

html,math

Is it possible to perform math operations within HTML, like <div width="50/2">? Or can this only be done using Javascript or CSS?

c,algorithm,security,math,encryption

I'm trying to reverse the following code in order to provide a function which takes the buffer and decrypts it. void crypt_buffer(unsigned char *buffer, size_t size, char *key) { size_t i; int j; j = 0; for(i = 0; i < size; i++) { if(j >= KEY_SIZE) j = 0;...