Shape object in Processing, translate individual shapes - opengl

I am facing difficulty with the translate() function for objects as well as objects in general in Processing. I went through the examples and tried to replicate the manners by which they instantiated the objects but cannot seem to even get the shapes to appear on the screen no less move them. I instantiate the objects into an array using a nested for loop and expect a grid of the objects to be rendered. However, nothing at all is rendered.
My nested for loop structure to instantiate the tiles:
for(int i=0; i<102; i++){
for(int j=0; j<102; j++){
tiles[i][j]=new tile(i,0,j);
tiles[i][j].display();
}
}
And the constructors for the tile class:
tile(int x, int y, int z){
this.x=x;
this.y=y;
this.z=z;
beginShape();
vertex(x,y,z);
vertex(x+1,y,z);
vertex(x+1,y,z-1);
vertex(x,y,z-1);
endShape();
}
Nothing is rendered at all when this runs. Furthermore, if this is of any concern, my translations(movements) are done in a method I wrote for the tile class called move which simply calls translate. Is this the correct way? How should one approach this? I can't seem to understand at all how to render/create/translate individual objects/shapes.

Transformations (such as translate, rotate, etc) do not work if you use beginShape() as you're simply specifying direct coordinates to draw to. If you're relying on the result of a translate to put an object into a visible location that could be why you're not having any results.
Also, depending on how you're looking at your scene, you probably have z coming towards the camera, so your objects are being drawn with you looking at them on the side, and since they are 2d objects you won't see anything, try using x/y or y/z instead of x/z which you are doing right now.

You can definitely use pushMatrix() and translate() with beginShape() and such, it may be not completely what you expect, but it will definitely move the things around from the default origin.
What is going wrong with your above example is that you are putting the drawing() code in the constructor where you should be putting it in the display function.
so:
public void display(Processing proc) {
proc.beginShape()
etc.
}
display() also needs to be called in the draw() loop, so initialize your tiles once and then display them in draw().

You should follow #Tyler's advice on drawing in a 2D plane(x/y, y/z, x/z).
Your shapes probably do not render because you might be drawing them once, and clearing the screen in the draw() method, but I'm not sure as I can't see the rest of your code.
Here's what I mean:
tile[][] tiles;
int numTiles = 51;//x and y number of tiles
void setup() {
size(400,400,P3D);
tiles = new tile[numTiles][numTiles];
for(int i=0; i<numTiles; i++)
for(int j=0; j<numTiles; j++)
tiles[i][j]=new tile(i,j,0,5);
}
void draw() {
background(255);
translate(width * .5,height * .5);
rotateY((float)mouseX/width * PI);
rotateX((float)mouseY/height * PI);
for(int i=0; i<numTiles; i++)
for(int j=0; j<numTiles; j++)
tiles[i][j].display();
}
class tile {
int x,y,z;
tile(int x, int y, int z,int s) {//s for size
this.x=x * s;
this.y=y * s;
this.z=z * s;
}
void display(){
beginShape(QUADS);
//XY plane
//*
vertex(x,y,z);
vertex(x+x,y,z);
vertex(x+x,y+y,z);
vertex(x,y+y,z);
//*/
endShape();
}
}
Since you're only drawing squares, you could use the rect() function.
int numSquares = 51,squareSize = 10;
void setup(){
size(400,400,P3D);
smooth();
}
void draw(){
background(255);
translate(width * .5, height * .5);
rotateY((float)mouseX/width * PI);
for(int j = 0 ; j < numSquares ; j++)
for(int i = 0 ; i < numSquares ; i++)
rect(i*squareSize,j*squareSize,squareSize,squareSize);
}
HTH

Related

C++ code for Microsoft Kinect - trying to dynamically allocate array of target positions

So I'm trying to modify the Kinect BodyBasicsD2D code so that a fixed number of "target positions" appear on the screen (as ellipses) for the user to move his hand toward. I'm having trouble creating the initial target positions.
This is my code in the header file for the allocation of the array of target positions (these are a public field of the CBodyBasics class, already built into the original BodyToBasics program):
D2D1_POINT_2F* targetPositions = NULL;
int numTargets = 3;
Then I have a function "GenerateTargetPositions" which is supposed to generate 3, in this case, target positions to be passed into the "DrawTargetPositions" function.
void CBodyBasics::GenerateTargetPositions(D2D1_POINT_2F * targetPositions, int numTargets)
{
targetPositions = new D2D1_POINT_2F[numTargets];
RECT rct;
GetClientRect(GetDlgItem(m_hWnd, IDC_VIDEOVIEW), &rct);
int width = rct.right;
int height = rct.bottom;
FLOAT x;
FLOAT y;
D2D1_POINT_2F tempPoint;
for (int i = 0; i < numTargets; i++) {
x = 1.0f*i*width / numTargets;
y = 1.0f*i*height / numTargets;
tempPoint = D2D1::Point2F(x, y);
targetPositions[i] = tempPoint;
}
}
My DrawTargetPositions function is:
void CBodyBasics::DrawTargetPositions(D2D1_POINT_2F * targetPositions, int numTargets)
{
D2D1_ELLIPSE ellipse;
for (int i = 0; i < numTargets; i++)
{
ellipse = D2D1::Ellipse(targetPositions[i], 50.f, 50.f);
m_pRenderTarget->FillEllipse(ellipse, m_pSilverBrush);
}
}
When I try to run my code, I get the error that both "targetPositions" and "targetPositions[i]" is NULL (and thus my GenerateTargetPositions function must not be working properly). I believe that targetPositions[i] is a struct (a point with x and y values) so I am wondering if this may be the reason for my errors.
I call GenerateTargetPositions and DrawTargetPositions before the main "while" loop in my code so that each function is not being called on each iteration (there are many iterations of through the while loop because this is an interactive Microsoft Kinect, recording one's movements).
Any suggestions and advice would be greatly appreciated. Thanks so much!

c++ Opengl handle elements drawn

I am currently working on a game and I want to know if there is any way of handling with the elements i am drawing . For example : if i draw in a loop 100 cubes , how can i show / hide the cube number 15 or 63 or n ... I thought that initializing elements in a list would work , but i didn't find any property of it that could help.
GLuint cube;
cube = glGenLists(1);
glNewList(cube,GL_COMPILE);
for(int i = -30; i < 3; i++) {
for(int j = -30; j < 3; j++) {
glPushMatrix();
glTranslatef(i*2.0,0,j * 2.0);
Dcube();
glPopMatrix();
}
}
glEndList();
//something like : glDeleteList(cube); but that only works with entire list not with individual objects..
You have a display list, very good. So now you're back to using your regular language primitives to simply call that function.
std::array<bool, 100> cubes;
std::fill(cubes.begin(), cubes.end(), true);
cubes[15] = false;
cubes[63] = false;
for (bool drawCube : cubes) {
if (drawCube) {
// move a bit, perhaps using glTranslate
glCallList(cube);
}
}
OpenGL isn't your statekeeper. It just draws what you tell it to, you're responsible for keeping your objects.

SFML 2.0 c++ sprite in array/vector

I have this in my file blocks.h:
#include <vector>
class Blocks{
public:
string files_name[4];
vector < Sprite > sprites;
void load(){
for(int i=0;i<=sizeof(files_name);i++){
Texture my_texture;
my_texture.loadFromFile(this->files_name[i]);
sprites[i].setTexture( my_texture );
}
}
Blocks(){
this->files_name[0] = "wall.png";
this->files_name[1] = "floor.png";
this->files_name[2] = "live.png";
this->files_name[3] = "coins.png";
this->load();
}
void show(int id, int X, int Y){
sprites[id].setPosition(X, Y);
window.draw(sprites[id]);
}
};
I have no errors, but my game crashed. I think, the problem is in the line which reads sprites[i].setTexture(...)
I only have the message: Process terminated with status -1073741819 (0 minutes, 2 seconds)
My IDE is Code::Blocks 10.05, and I have Windows 8.
Of course, in the file main.cpp, I have defined the window:
RenderWindow window( VideoMode(920, 640, 32 ), "Game" );
#include "blocks.h"
Blocks BLOCKS;
----UPDATE:
Ok, now it's not crashing, thanks! But, now I can't see textures! I read the post by Benjamin Lindley and I added a new vector with textures. My code looks like this now:
const int arraySize = 4;
string files_name[4];
vector < Sprite > sprites;
vector < Texture > textures;
and, in load(), I have:
for(int i = 0; i < arraySize; i++){
Texture new_texture;
new_texture.loadFromFile(this->files_name[i]);
textures.push_back(new_texture);
sprites[i].setTexture(textures[i]);
and then it crashes again!
---UPDATE: Now I have again changed my code and I don't have a crash, but my textures are white squares. My texture live.png works, but the other textures are white! Here's my new code:
Sprite new_sprite;
new_sprite.setTexture(textures[i]);
sprites.push_back(new_sprite);
The problem is this line:
for(int i=0;i<=sizeof(files_name);i++){
If you print out the value of sizeof(files_name), you will find that it is 16 instead of 4! Don't use sizeof here. Also, don't use <= here, since even if you had replaced sizeof(files_name) with 4, you would have tried to access files_name[4], which would also give you an error.
Instead you could use:
const int arraySize = 4;
string files_name[arraySize];
...
for(int i = 0; i < arraySize; i++)
or something of that sort.
Also, hopefully you initialize sprites at some point. You need to fill your vector with Sprites (with something like sprites.push_back(mySprite)) before you call load().
SFML sprites store their associated textures by pointer. The textures you are creating are local to the loop, and so are destroyed at the end of each iteration, thereby invalidating the pointer in the sprite. You need to keep your textures alive for the duration of whatever sprite uses them.
Also, your sprites vector has no elements, you need to either specify a size, or use push_back in your loop.
Also, as Scott pointed out, sizeof(files_name) is not the appropriate terminating value for your loop, since that gives you sizeof(string) * number of elements in the array. You only want the number of elements in the array.
Ok, it works only in two loop: Thanks for helping :)
vector < Sprite > sprites;
vector < Texture > tekstures;
and:
for(int i = 0; i < arraySize; i++){
Texture new_texture;
new_texture.loadFromFile(this->files_name[i]);
tekstures.push_back(new_texture);
}
for(int i = 0; i < arraySize; i++){
Sprite new_sprite;
new_sprite.setTexture(tekstures[i]);
sprites.push_back(new_sprite);
}
and in one loop it doesn't work, i have white textures:
for(int i = 0; i < arraySize; i++){
Texture new_texture;
new_texture.loadFromFile(this->files_name[i]);
tekstures.push_back(new_texture);
Sprite new_sprite;
new_sprite.setTexture(tekstures[i]);
sprites.push_back(new_sprite);
}
Greetings !

std::vector memory, vector of unwanted 0's

My Code works for my purely glut implementation, but I am trying to get it to work in qt.
I have a vector of masspoints for a wire mesh system
std::vector<masspoint> m_particles;
The problem is in my qt version none of what I write really sticks and I am left with an array of zeros. Basically I am confused why the glut version has correct values but the qt one does not given that it is basically identical code. What is wrong with the qt code?
Yes I only see zeros when using qDebug. When I am calling my drawing function in the qt version all vertex points turn out to be 0 in all components so nothing is seen.
int myboog = 1;
int county = 0;
// Constructors
Cloth::Cloth(float width, float height, int particles_in_width, int particles_in_height):
m_width(particles_in_width),
m_height(particles_in_height),
m_dimensionWidth(width),
m_dimensionHeight(height),
m_distanceX(width/(float)particles_in_width),
m_distanceY(height/(float)particles_in_height)
{
//Set the particle array to the given size
//Height by width
//mparticles is the name of our vector
m_particles.resize(m_width*m_height);
qDebug() << m_particles.size();
// Create the point masses to simulate the cloth
for (int x = 0; x < m_width; ++x)
{
for (int y=0; y < m_height; ++y)
{
// Place the pointmass of the cloth, lift the edges to give the wind more effect as the cloth falls
Vector3f position = Vector3f(m_dimensionWidth * (x / (float)m_width),
((x==0)||(x==m_width-1)||(y==0)||(y==m_height-1)) ? m_distanceY/2.0f:0,
m_dimensionHeight * (y / (float)m_height));
// The gravity effect is applied to new pmasspoints
m_particles[y * m_width + x] = masspoint(position,Vector3f(0,-0.06,0));
}
}
int num = (int)m_particles.size();
for (int i=0; i<num; ++i)
{
masspoint* p = &m_particles[i];
if(myboog)
{
qDebug() << "test " << *p->getPosition().getXLocation() << county;
county++;
}
}
myboog = 0;
// Calculate the normals for the first time so the initial draw is correctly lit
calculateClothNormals();
}
Code for masspoint involved in constructor for CLoth
#ifndef MASSPOINT_H
#define MASSPOINT_H
#include <QGLWidget>
#include "vector3f.h"
class masspoint
{
private:
Vector3f m_position; // Current Location of the pointmass
Vector3f m_velocity; // Direction and speed the pointmass is traveling in
Vector3f m_acceleration; // Speed at which the pointmass is accelerating (used for gravity)
Vector3f m_forceAccumulated; // Force that has been accumulated since the last update
Vector3f m_normal; // Normal of this pointmass, used to light the cloth when drawing
float m_damping; // Amount of velocity lost per update
bool m_stationary; // Whether this pointmass is currently capible of movement
public:
masspoint& operator= (const masspoint& particle);
//Some constructors
masspoint();
masspoint(const masspoint& particle);
masspoint(Vector3f position, Vector3f acceleration);
//Like eulur integration
void integrate(float duration);
// Accessor functions
//Get the position of the point mass
inline Vector3f getPosition() const {return m_position;}
Vector stuff involved in the constructor for CLoth
#ifndef VECTOR3F_H
#define VECTOR3F_H
#include <math.h>
// Vector library to be used
class Vector3f
{
private:
float m_x, m_y, m_z;
public:
const float* getXLocation() const { return &m_x; }

Can someone explain how I am to access this array? (image processing program)

I am working on the implementation of functions for an already written image processing program. I am given explanations of functions, but not sure how they are designating pixels of the image.
In this case, I need to flip the image horizontally, i.e., rotates 180 degrees around the vertical axis
Is this what makes the "image" i am to flip?
void Image::createImage(int width_x, int height_y)
{
width = width_x;
height = height_y;
if (pixelData!=NULL)
freePixelData();
if (width <= 0 || height <= 0) {
return;
}
pixelData = new Color* [width]; // array of Pixel*
for (int x = 0; x < width; x++) {
pixelData[x] = new Color [height]; // this is 2nd dimension of pixelData
}
}
I do not know if all the functions I have written are correct.
Also, the Image class calls on a Color class
So to re-ask: what am I "flipping" here?
Prototype for function is:
void flipLeftRight();
As there is no input into the function, and I am told it modifies pixelData, how do I flip left to right?
A quick in place flip. Untested, but the idea is there.
void flipHorizontal(u8 *image, u32 width, u32 height)
{
for(int i=0; i < height; i++)
{
for(int j=0; j < width/2; j++)
{
int sourceIndex = i * width + j;
int destIndex = (i+1) * width - j - 1;
image[sourceIndex] ^= image[destIndex];
image[destIndex] ^= image[sourceIndex];
image[sourceIndex] ^= image[destIndex];
}
}
}
well, the simplest approach would be to read it 1 row at a time into a temporary buffer the same size as 1 row.
Then you could use something like std::reverse on the temporary buffer and write it back.
You could also do it in place, but this is the simplest approach.
EDIT: what i;ve described is a mirror, not a flip, to mirror you also need to reverse the order of the rows. Nothing too bad, to do that I would create a buffer the same size as the image, copy the image and then write it back with the coordinates adjusted. Something like y = height - x and x = width - x.