Skip to content

Instantly share code, notes, and snippets.

@darkwave
Created January 11, 2015 21:35
Show Gist options
  • Save darkwave/969a081d4cb278309ce3 to your computer and use it in GitHub Desktop.
Save darkwave/969a081d4cb278309ce3 to your computer and use it in GitHub Desktop.
Example ScreenGraph
Game game;
Element e;
void setup() {
size(640, 480, P3D);
noStroke();
e = new MouseMoved();
//e.transformation.scale(10);
//e.transformation.rotate(PI / 4);
e.addChild(new Circle(30, 10)).transformation.scale(10);;
game = new Game(this);
game.layers.add(e);
//subElement.transformation.scale(.5);
}
void draw() {
background(66);
text(frameRate, 20, 20);
e.transformation.rotate(PI * .01);
game.run();
ellipse(0, 0, 30, 30);
}
class Circle extends Element {
Circle(float x, float y) {
super(x, y);
}
@Override
public void displayImpl(PGraphics pg) {
ellipse(0, 0, 1, 1);
}
}
class MouseMoved extends Element {
@Override
public void update() {
position.x = mouseX;
position.y = mouseY;
super.update();
}
}
class Game {
PApplet parent;
PGraphics offscreen;
ArrayList<Element> layers = new ArrayList<Element>();
Game(PApplet _parent) {
parent = _parent;
offscreen = parent.g;
}
void run() {
if (offscreen != parent.g)
offscreen.beginDraw();
for (Element layer : layers)
layer.update();
for (Element layer : layers)
layer.display(offscreen);
if (offscreen != parent.g)
offscreen.endDraw();
}
}
class Element {
PVector position;
ArrayList<Element> children;
PMatrix transformation;
int getChildrenCount() {
if (children == null)
return 0;
return children.size();
}
Element addChild(Element child) {
if (children == null)
children = new ArrayList<Element>();
children.add(child);
return child;
}
boolean removeChild(Element child) {
if (children == null || !children.contains(child))
return false;
children.remove(child);
return true;
}
Element() {
this(new PVector());
}
Element(float x, float y, float z) {
this(new PVector(x, y, z));
}
Element(float x, float y) {
this(new PVector(x, y));
}
Element(PVector _position) {
position = _position;
if (g.is3D())
transformation = new PMatrix3D();
if (g.is2D())
transformation = new PMatrix2D();
}
void update() {
if (getChildrenCount() > 0)
for (Element child : children)
child.update();
}
void display(PGraphics pg) {
//pg.beginDraw();
pg.pushMatrix();
pg.translate(position.x, position.y);
pg.applyMatrix(transformation);
displayImpl(pg);
if (getChildrenCount() > 0)
for (Element child : children) {
child.display(pg);
}
pg.popMatrix();
//pg.endDraw();
}
void displayImpl(PGraphics pg) {
if (pg.is3D()) {
box(10);
} else if (pg.is2D()) {
rect(0, 0, 10, 10);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment