开发者

How to store OpenGL Primitives in a tree data structure in C++?

I'm new to OpenGL and C++. Say I start with a 2D square (on the very left) like shown in the picture below. I want to make it interactive with the glutKeyboardFunc() so when I press a number a new box will draw next to the corresponding edge.

How to store OpenGL Primitives in a tree data structure in C++?

Figure the best way to do this is to have a tree structure that hold all the boxes. But I'm not sure how I can hold basic primitives into a data structure, a tree, for instance.

I'm aware that I can only call the glutDisplayFunc(myDisplay) once开发者_StackOverflow中文版, and the rest should handle by the glutKeyboardFunc()

Any help would be appreciated :)

Update: thanks for pointing out glutPostRedisplay() but what if I want to make the box selectable and keep tracking the current selected box with glutMouseFunc(), and from there when I add more boxes, I need to know how many child box it has created, so I can provide the right position when new box is drawn. Seems that makes more sense now to use a tree data structure ? Just not sure how I can store the information I need into a tree.


If I understand your question, you can make a class that represents the box, such as:

class Box {
public:
  void Move(int newx, int newy) {
    x = newx;
    y = newy;
  }
  void Resize(int newx, int newy) {
    w = newx;
    h = newy;
  }
  int getX() { return x; }
  int getY() { return y; }
  int getW() { return w; }
  int getH() { return h; }
private:
  int x, y, w, h;
};

Then, you can have a global vector to hold all the boxes:

#include <vector>

vector<Box> box;

You can then add a box like this:

Box newbox;
newbox.Move(40,50);
newbox.Resize(10,10);
box.push_back(newbox);

And move an existing one like this:

box[3].Move(70,20);

I'm sorry I cannot answer your question completely, but I hope you know have an idea on how to accomplish your project.

EDIT: To achieve a tree structure, you could add these variables to the Box class:

private:
  Box* parent;
  vector<Box*> child;

This would allow you to keep track of the tree structure. Then doing something like:

myBox->getChild(0)->getChild(1)

would retrieve the second child of the first child of myBox. I hope this makes sense to you.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜