Interfering Vector in glBegin() - c++

I am trying to implement code for an assignment to render skeleton and mesh animations. In my glBegin(GL_TRIANGLES) section, I have some vectors that appear to be interfering with my information when it shouldn't.
glBegin(GL_TRIANGLES);
for (int i = 0; i < mesh->nfaces.size(); i += 1)
for (int k = 0; k < 3; k += 1) {
int j = k;//2 - k;
glm::vec4 myPointPrime;
myPointPrime.w = 1;
myPoint.x = ecks = mesh->vertex[mesh->faces[i][j]][0];
myPoint.y = why = mesh->vertex[mesh->faces[i][j]][1];
myPoint.z = zed = mesh->vertex[mesh->faces[i][j]][2];
// Stuff vvvv THIS CAUSES PROBLEMS
for (int t = 0; t < mySkeleton->vertex.at(i).size(); t++) {
myPointPrime += mySkeleton->vertex[i][j] * MyXformations * myPoint;
}
glNormal3f(mesh->normal[mesh->nfaces[i][j]][0],
mesh->normal[mesh->nfaces[i][j]][1],
mesh->normal[mesh->nfaces[i][j]][2]);
glVertex3f(mesh->vertex[mesh->faces[i][j]][0],
mesh->vertex[mesh->faces[i][j]][1],
mesh->vertex[mesh->faces[i][j]][2]);
// glVertex3f(myPointPrime.x, myPointPrime.y, myPointPrime.z);
// glVertex3f(myPoint.x, myPoint.y, myPoint.z);
}
glEnd();
The myPointPrime += ... code is doing something weird to my Vertex calls, the scene won't render unless I comment out that for loop.
If I comment out the loop, then the scene renders, but I think I kinda need the loop if animating something like 16,000 vertexes is going to have any performance at all.
Is having that there kind of like having it automatically multiply with the glVertex calls?
Edit:
Below is another version of the code I hope should be more clear, instead of calculating the points in the actual drawing code I change the whole mesh to supposedly follow the skeleton each frame, but nothing is rendered.
for (int vertex_i = 0; vertex_i < mesh->nfaces.size(); vertex_i++) {
for (int k = 0; k < 3; k += 1) {
int j = k;//2 - k;
pointp.x = 0;
pointp.y = 0;
pointp.z = 0;
for (int t = 0; t < mySkeleton->vertex.at(vertex_i).size(); t++) {
point.x = mesh->vertex[mesh->faces[vertex_i][j]][0];
point.y = mesh->vertex[mesh->faces[vertex_i][j]][1];
point.z = mesh->vertex[mesh->faces[vertex_i][j]][2];
//glPushMatrix();
pointp += mySkeleton->vertex[vertex_i][t] * myTranslationMatrix * myRotationMatrix * point;
cout << "PointP X: " << pointp.x << " PointP Y: " << pointp.y << " PointP Z: " << pointp.z << endl;
mesh->vertex[mesh->faces[vertex_i][j]][0] = pointp.x;
mesh->vertex[mesh->faces[vertex_i][j]][1] = pointp.y;
mesh->vertex[mesh->faces[vertex_i][j]][2] = pointp.z;
//myPointPrime += MyXformations * myPoint;
}
}
}
My assumption is that maybe the calculations for pointp isn't doing what I think its doing?
mySkeleton->vertex[vertex_i][t] is a vector from my 'skeleton' class, it holds all of the weights for every vertex, there are 17 weights per vertex.
"MyXformations" is a 4x4 matrix passed from my skeleton animation function that holds the last known key frame and this is applied to the vertexes.
point is the current point in the vertex.

Your loop variable is t. However, you refer to j in the loop. Looks to me like your loop might simply be crashing for larger values of j.

You're not using t inside the for loop. Is this expected?
mySkeleton->vertex[i][j] looks like it's out of bounds since j should be for mesh->faces/mesh->nfaces.
Also you can use glNormal3fv and glVertex3fv with arrays.
With out of bounds memory operations you can get all sorts of weird stuff happening, although I can't see any out of bound writes. Your * operators don't modify the objects do they?
If you're worried about performance. You shouldn't be using immediate mode. Instead, put all your data on the GPU with buffer objects (including join/bone transformations) and animate on the fly in the vertex shader.
This is from a few years ago, but worth a read: Animated Crowd Rendering.

Related

How to create a Minecraft chunk in opengl?

I'm learning OpenGL and I have tried to make a voxel game like Minecraft. In the beginning, everything was good. I created a CubeRenderer class to render a cube with its position. The below picture is what I have done.
https://imgur.com/yqn783x
And then I got a serious problem when I try to create a large terrain, I hit a slowing performance. It was very slow and fps just around 15fps, I thought.
Next, I figured out Minecraft chunk and culling face algorithm can solve slowing performance by dividing the world map into small pieces like chunk and just rendering visible faces of a cube. So how to create a chunk in the right way and how the culling face algorithm is applied in Chunk?
So far, that is what I have tried
I read about Chunk in Minecraft at https://minecraft.gamepedia.com/Chunk
I created a demo Chunk by this below code (it is not the completed code because I removed it out)
I created a CubeData that contains cube position and cube type.
And I call the GenerateTerrain function to make a simple chunk data (16x16x16) like below (CHUNK_SIZE is 16)
for (int x = 0; x < CHUNK_SIZE; x++) {
for (int y = 0; y < CHUNK_SIZE; y++) {
for (int z = 0; z < CHUNK_SIZE; z++) {
CubeType cubeType = { GRASS_BLOCK };
Location cubeLocation = { x, y, z };
CubeData cubeData = { cubeLocation, cubeType };
this->Cubes[x][y][z] = cubeData;
}
}
}
After that, I had a boolean array which is called "mask" contains two values are 0 (not visible) or 1 (visible) and matches with their cube data. And then I call Render function of Chunk class to render a chunk. This code below like what I have done (but it is not complete code because I removed that code and replaced with new code)
for (int x = 0; x < CHUNK_SIZE; x++) {
for (int y = 0; y < CHUNK_SIZE; y++) {
for (int z = 0; z < CHUNK_SIZE; z++) {
for(int side = 0; side < 6;side++){
if(this->mask[x][y][z][side] == true) cubeRenderer.Render(cubeData[x][y][z]);
}
}
}
}
But the result I got that everything still slow (but it is better than the first fps, from 15fps up to 25-30fps, maybe)
I guess it is not gpu problem, it is a cpu problem because there is too many loops in render call.
So I have kept research because I think my approach was wrong. There may have some right way to create a chunk, right?
So I found the solution that puts every visible verticle to one VBO. So I just have to call and bind VBO definitely one time.
So this below code show what I have tried
cout << "Generating Terrain..." << endl;
for (int side = 0; side < 6; side++) {
for (int x = 0; x < CHUNK_SIZE; x++) {
for (int y = 0; y < CHUNK_SIZE; y++) {
for (int z = 0; z < CHUNK_SIZE; z++) {
if (this->isVisibleSide(x, y, z, side) == true) {
this->cubeRenderer.AddVerticleToVBO(this->getCubeSide(side), glm::vec3(x, y, z), this->getTexCoord(this->Cubes[x][y][z].cubeType, side));
}
}
}
}
}
this->cubeRenderer.GenerateVBO();
And call render one time at all.
void CubeChunk::Update()
{
this->cubeRenderer.Render(); // with VBO data have already init above
}
And I got this:
https://imgur.com/YqsrtPP
I think my way was wrong.
So what should I do to create a chunk? Any suggestion?

Orthogonalization in QR Factorization outputting slightly innaccurate orthogonalized matrix

I am writing code for QR Factorization and for some reason my orthogonal method does not work as intended. Basically, my proj() method is outputting random projections. Here is the code:
apmatrix<double> proj(apmatrix<double> v, apmatrix<double> u)
//Projection of u onto v
{
//proj(v,u) = [(u dot v)/(v dot v)]*v
double a = mult(transpose(u,u),v)[0][0], b = mult(transpose(v,v),v)[0][0], c = (a/b);
apmatrix<double>k;
k.resize(v.numrows(),v.numcols());
for(int i = 0; i<v.numrows(); i++)
{
for(int j = 0; j<v.numcols(); j++)
{
k[i][j]=v[i][j]*c;
}
}
return k;
}
I tested the method by itself with manual matrix inputs, and it seems to work fine. Here is my orthogonal method:
apmatrix<double> orthogonal(apmatrix<double> A) //Orthogonal
{
/*
n = (number of columns of A)-1
x = columns of A
v0 = x0
v1 = x1 - proj(v0,x1)
vn = xn - proj(v0,xn) - proj(v1,xn) - ... - proj(v(n-1),xn)
V = {v1, v2, ..., vn} or [v0 v1 ... vn]
*/
apmatrix<double> V, x, v;
int n = A.numcols();
V.resize(A.numrows(),n);
x.resize(A.numrows(), 1);
v.resize(A.numrows(),1);
for(int i = 0; i<A.numrows(); i++)
{
x[i][0]=A[i][1];
v[i][0]=A[i][0];
V[i][0]=A[i][0];
}
for (int c = 1; c<n; c++) //Iterates through each col of A as if each was its own matrix
{
apmatrix<double>vn,vc; //vn = Orthogonalized v (avoiding matrix overwriting of v); vc = previously orthogonalized v
vn=x;
vc.resize(v.numrows(), 1);
for(int i=0; i<c; i++) //Vn = an-(sigma(t=1, n-1, proj(vt, xn))
{
for(int k = 0; k<V.numrows(); k++)
vc[k][0] = V[k][i]; //Sets vc to designated v matrix
apmatrix<double>temp = proj(vc, x);
for(int j = 0; j<A.numrows(); j++)
{
vn[j][0]-=temp[j][0]; //orthogonalize matrix
}
}
for(int k = 0; k<V.numrows(); k++)
{
V[k][c]=vn[k][0]; //Subtracts orthogonalized col to V
v[k][0]=V[k][c]; //v is redundant. more of a placeholder
}
if((c+1)<A.numcols()) //Matrix Out of Bounds Checker
{
for(int k = 0; k<A.numrows(); k++)
{
vn[k][0]=0;
vc[k][0]=0;
x[k][0]=A[k][c+1]; //Moves x onto next v
}
}
}
system("PAUSE");
return V;
}
For testing purposes, I have been using the 2D Array: [[1,1,4],[1,4,2],[1,4,2],[1,1,0]]. Each column is its own 4x1 matrix. The matrices should be outputted as: [1,1,1,1]T, [-1.5,1.5,1.5,-1.5]T, and [2,0,0,-2]T respectively. What's happening now is that the first column comes out correctly (it's the same matrix), but the second and third come out to something that is potentially similar but not equal to their intended values.
Again, each time I call on the orthogonal method, it outputs something different. I think it's due to the numbers inputted in the proj() method, but I am not fully sure.
The apmatrix is from the AP college board, back when they taught cpp. It is similar to vectors or ArrayLists in Java.
Here is a link to apmatrix.cpp and to the documentation or conditions (probably more useful), apmatrix.h.
Here is a link to the full code (I added visual markers to see what the computer is doing).
It's fair to assume that all custom methods work as intended (except maybe Matrix Regressions, but that's irrelevant). And be sure to enter the matrix using the enter method before trying to factorize. The code might be inefficient partly because I self-taught myself cpp not too long ago and I've been trying different ways to fix my code. Thank you for the help!
As said in comments:
#AhmedFasih After doing more tests today, I have found that it is in-fact some >memory issue. I found that for some reason, if a variable or an apmatrix object >is declared within a loop, initialized, then that loop is reiterated, the >memory does not entirely wipe the value stored in that variable or object. This >is noted in two places in my code. For whatever reason, I had to set the >doubles a,b, and c to 0 in the proj method and apmatrixdh to 0 in the >mult method or they would store some value in the next iteration. Thank you so >much for you help!

SFML createMaskFromColor() not working correctly

I'm creating a game where I have 3 separate objects to display. A floor, a player sprite and multiple crates. Below is the code for all three.
#include <iostream>
#include <fstream>
#include "Game.h"
Game::Game()
{
std::ifstream fileHndl;
fileHndl.open("Assets/mapdata.txt");
fileHndl >> mapCols;
fileHndl >> mapRows;
playerX = mapCols / 2;
playerY = mapRows / 2;
mapData = new int *[mapRows];
for (int i = 0; i < mapRows; i++) {
mapData[i] = new int[mapCols];
}
for (int i = 0; i < mapRows; i++) {
for (int j = 0; j < mapCols; j++) {
fileHndl >> mapData[i][j];
}
}
window.create(sf::VideoMode(1280, 1024), "COMP2501 Demo");
window.setFramerateLimit(5);
playerImage.loadFromFile("Assets/actor.png");
playerImage.createMaskFromColor(sf::Color::White);
playerTexture.loadFromImage(playerImage);
playerTexture.setSmooth(true);
playerSprite.setTexture(this->playerTexture);
floorTexture.loadFromFile("Assets/floor.png");
floorTexture.setSmooth(true);
crateImage.loadFromFile("Assets/crate.png");
crateImage.createMaskFromColor(sf::Color::White);
crateTexture.loadFromImage(crateImage);
crateTexture.setSmooth(true);
mapSprites = new sf::Sprite *[mapRows];
for (int i = 0; i < mapRows; i++) {
mapSprites[i] = new sf::Sprite[mapCols];
}
for (int i = 0; i < mapRows; i++)
{
for (int j = 0; j < mapCols; j++)
{
mapSprites[i][j].setPosition(j * 64, i * 64);
if (mapData[i][j] == 1)
{
mapSprites[i][j].setTexture(this->floorTexture);
}
else
{
mapSprites[i][j].setTexture(this->crateTexture);
}
}
}
}
I'm attempting to remove the white background of all 3 images as they're all .pngs however when doing so I get the following result.
http://i.stack.imgur.com/KG3H2.png
The crates appear to be drawing a black border around themselves. Is there a better way to go about removing the white background on PNGs as textures?
Crate
http://i.stack.imgur.com/DA5Dv.png
In the absence of additional information, this would be my logical chain towards a guess:
Since we see the createMaskFromColor() function work fine for the player model, it's not the error source. Since we see the same code being invoked for the other two objects, the chroma keying is working fine there as well. Hence, the following answer:
There is nothing but the black background behind the crate sprites. The chroma keying works correctly, and happily demonstrates us the black background behind the transparent corners.
How to fix:
Make sure the floor sprite is present behind the crate sprites as well. Maybe create an additional sprite, "crate over a floor", to not overlay them every time such a combination is encountered (no idea if this really affects performance, just a guess.)

Particle Deposition Terrain Generation

I'm using Particle Deposition to try and create some volcano-like mountains procedurally but all I'm getting out of it is pyramid-like structures. Is anyone familiar with the algorithm that might be able to shed some light on what I might be doing wrong. I'm dropping each particle in the same place at the moment. If I don't they spread out in a very thin layer rather than any sort of mountain.
void TerrainClass::ParticalDeposition(int loops){
float height = 0.0;
//for(int k= 0; k <10; k++){
int dropX = mCurrentX = rand()%(m_terrainWidth-80) + 40;
int dropY = mCurrentZ = rand()%(m_terrainHeight-80) + 40;
int radius = 15;
float angle = 0;
int tempthing = 0;
loops = 360;
for(int i = 0; i < loops; i++){
mCurrentX = dropX + radius * cos(angle);
mCurrentZ = dropY + radius * sin(angle);
/*f(i%loops/5 == 0){
dropX -= radius * cos(angle);
dropY += radius * sin(angle);
angle+= 0.005;
mCurrentX = dropX;
mCurrentZ = dropY;
}*/
angle += 360/loops;
//dropX += rand()%5;
//dropY += rand()%5;
//for(int j = 0; j < loops; j++){
float newY = 0;
newY = (1 - (2.0f/loops)*i);
if(newY < 0.0f){
newY = 0.0f;
}
DepositParticle(newY);
//}
}
//}
}
void TerrainClass::DepositParticle(float heightIncrease){
bool posFound = false;
m_lowerList.clear();
while(posFound == false){
int offset = 10;
int jitter;
if(Stable(0.5f)){
m_heightMap[(m_terrainHeight*mCurrentZ)+mCurrentX].y += heightIncrease;
posFound = true;
}else{
if(!m_lowerList.empty()){
int element = rand()%m_lowerList.size();
int lowerIndex = m_lowerList.at(element);
MoveTo(lowerIndex);
}
}
}
}
bool TerrainClass::Stable(float deltaHeight){
int index[9];
float height[9];
index[0] = ((m_terrainHeight*mCurrentZ)+mCurrentX); //the current index
index[1] = ValidIndex((m_terrainHeight*mCurrentZ)+mCurrentX+1) ? (m_terrainHeight*mCurrentZ)+mCurrentX+1 : -1; // if the index to the right is valid index set index[] to index else set index[] to -1
index[2] = ValidIndex((m_terrainHeight*mCurrentZ)+mCurrentX-1) ? (m_terrainHeight*mCurrentZ)+mCurrentX-1 : -1; //to the left
index[3] = ValidIndex((m_terrainHeight*(mCurrentZ+1))+mCurrentX) ? (m_terrainHeight*(mCurrentZ+1))+mCurrentX : -1; // above
index[4] = ValidIndex((m_terrainHeight*(mCurrentZ-1))+mCurrentX) ? (m_terrainHeight*(mCurrentZ-1))+mCurrentX : -1; // bellow
index[5] = ValidIndex((m_terrainHeight*(mCurrentZ+1))+mCurrentX+1) ? (m_terrainHeight*(mCurrentZ+1))+mCurrentX+1: -1; // above to the right
index[6] = ValidIndex((m_terrainHeight*(mCurrentZ-1))+mCurrentX+1) ? (m_terrainHeight*(mCurrentZ-1))+mCurrentX+1: -1; // below to the right
index[7] = ValidIndex((m_terrainHeight*(mCurrentZ+1))+mCurrentX-1) ? (m_terrainHeight*(mCurrentZ+1))+mCurrentX-1: -1; // above to the left
index[8] = ValidIndex((m_terrainHeight*(mCurrentZ-1))+mCurrentX-1) ? (m_terrainHeight*(mCurrentZ-1))+mCurrentX-1: -1; // above to the right
for ( int i = 0; i < 9; i++){
height[i] = (index[i] != -1) ? m_heightMap[index[i]].y : -1;
}
m_lowerList.clear();
for(int i = 1; i < 9; i++){
if(height[i] != -1){
if(height[i] < height[0] - deltaHeight){
m_lowerList.push_back(index[i]);
}
}
}
return m_lowerList.empty();
}
bool TerrainClass::ValidIndex(int index){
return (index > 0 && index < m_terrainWidth*m_terrainHeight) ? true : false;
}
void TerrainClass::MoveTo(int index){
mCurrentX = index%m_terrainWidth;
mCurrentZ = index/m_terrainHeight;
}
Thats all the code thats used.
You should have a look at these two papers:
Fast Hydraulic Erosion Simulation and Visualization on GPU
Fast Hydraulic and Thermal Erosion on the GPU (read the first one first, the second one expands on it)
Don't get scared by the "on GPU", the algorithms work just fine on CPU (albeit slower). The algorithms don't do particle sedimentation per se (but you don't either ;) ) - they instead aggregate the particles into several layers of vector fields.
One important thing about this algorithm is that it erodes already existing heightmaps - for example generated with perlin noise. It fails miserably if the initial height field is completely flat (or even if it has insufficient height variation).
I had implemented this algorithm myself and had mostly success with it (still have more work to do, the algorithms are very hard to balance to give universally great results) - see the image below.
Note that perlin noise with the Thermal weathering component from the second paper may be well enough for you (and might save you a lot of trouble).
You can also find C++ CPU-based implementation of this algorithm in my project (specifically this file, mind the GPL license!) and its simplified description on pages 24-29 of my thesis.
Your particles will need to have some surface friction and/or stickiness (or similar) in their physics model if you want them to not spread out into a single-layer. This is performed in the collision detection and collision response parts of your code when updating your particle simulation.
A simple approach is to make the particles stick (attract each-other). Particles need to have a size too so that they don't simply converge to perfectly overlapping. If you want to make them attract each other, then you need to test the distance between particles.
You might benefit from looking through some of the DirectX SDK examples that use particles, and in particular (pun arf!) there is a great demo (by Simon Green?) in the NVidia GPU Computing SDK that implements sticky particles in CUDA. It includes a ReadMe document describing what they've done. You can see how the particles interact and ignore all the CUDA/GPU stuff if you aren't going for massive particle counts.
Also note that as soon as you use inter-particle forces, then you are checking approximately 0.5*n^2 combinations (pairs) of particles...so you may need to use a simple spatial partitioning scheme or similar to limit forces to nearby groups of particles only.
Good luck!

Cubic Bezier Curve Interaction

So I currently have a cubic bezier patch on the XZ plane (y = 0, so it is a flat patch). The patch is made up of 16 control points and 400 total grid points. What I am trying to currently implement is to select 1 of the middle 4 control points (any of them), and increment in any coordinate direction.
I think I that the part I am having trouble with is actually displaying the changes with OpenGL drawing functions. Below is the code for creating the patch and my current drawing function as well as a sample of the increment function I'm currently using.
Grid is a 2d array of all of the grid points.
Control is a 2d array of the 16 control points.
control_point is changed by a menu function that the user picks (options 1-4) and is initialized to 1.
Edit: Fixed last 2 control points in switch statement.
void bezier_plane()
{
CalcBezier();
for (int i = 0; i < 19; i++) {
for (int j = 0; j < 19; j++) {
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glBegin(GL_TRIANGLE_STRIP);
glVertex3f(grid[i][j].x, grid[i][j].y, grid[i][j].z);
glVertex3f(grid[i][j+1].x, grid[i][j+1].y, grid[i][j+1].z);
glVertex3f(grid[i+1][j].x, grid[i+1][j].y, grid[i+1][j].z);
glVertex3f(grid[i+1][j+1].x, grid[i+1][j+1].y, grid[i+1][j+1].z);
glEnd();
}
}
}
void CalcBezier()
{
float u;
float v;
u = 0;
for (int i = 0; i < 20; i++) {
v = 0;
for (int j = 0; j < 20; j++) {
for (int x = 0; x < 4; x++) {
for (int y = 0; y < 4; y++) {
grid[i][j].x += control[x][y].x * Bezier3(x, u) * Bezier3(y, v);
grid[i][j].y += control[x][y].y * Bezier3(x, u) * Bezier3(y, v);
grid[i][j].z += control[x][y].z * Bezier3(x, u) * Bezier3(y, v);
}
}
v+=.05;
}
u+=.05;
}
}
/*Is called when a menu button is hit, indicating that the control point is incremented in the y direction*/
void OnYInc()
{
switch(control_point) {
case 1:
control[1][1].y += 2;
break;
case 2:
control[1][2].y += 2;
break;
case 3:
control[2][3].y += 2;
break;
case 4:
control[2][4].y += 2;
break;
}
InvalidateRect(NULL, FALSE);
}
My onDraw function simply calls bezier_plane() as well. Right now, with the above code, when I try to increment in terms of y. The triangles in the mesh simply get bigger, but it does not seem to draw it correctly at all. It is a little hard to describe.
Result looks like this. First screenshot is before I have hit increment. Second screenshot and third screenshot is what it looks like after 1 click and then after 10 clicks. I'm also not quite sure why the range of the patch is actually changing when I increment in the y direction (it seems to get bigger as I keep incrementing y).
radical7 has solved it for you. Because you don't set grid to zero before calling CalcBezier, every time CalcBezier is called all the grid values are incremented. Changed OnYInc to leave the control points alone and just InvalidateRect and you will see the same behaviour