-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExampleGraphics2D.java
More file actions
444 lines (386 loc) · 13.2 KB
/
ExampleGraphics2D.java
File metadata and controls
444 lines (386 loc) · 13.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
/*
* Copyright (c) 2010-2015 William Bittle http://www.dyn4j.org/
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted
* provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this list of conditions
* and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions
* and the following disclaimer in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of dyn4j nor the names of its contributors may be used to endorse or
* promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.sample;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferStrategy;
import javax.swing.JFrame;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import org.dyn4j.dynamics.Body;
import org.dyn4j.dynamics.BodyFixture;
import org.dyn4j.dynamics.World;
import org.dyn4j.geometry.Capsule;
import org.dyn4j.geometry.Circle;
import org.dyn4j.geometry.Convex;
import org.dyn4j.geometry.Geometry;
import org.dyn4j.geometry.MassType;
import org.dyn4j.geometry.Polygon;
import org.dyn4j.geometry.Rectangle;
import org.dyn4j.geometry.Slice;
import org.dyn4j.geometry.Triangle;
import org.dyn4j.geometry.Vector2;
/**
* Class used to show a simple example of using the dyn4j project using
* Java2D for rendering.
* <p>
* This class can be used as a starting point for projects.
* @author William Bittle
* @version 3.2.0
* @since 3.0.0
*/
public class ExampleGraphics2D extends JFrame {
/** The serial version id */
private static final long serialVersionUID = 5663760293144882635L;
/** The scale 45 pixels per meter */
public static final double SCALE = 45.0;
/** The conversion factor from nano to base */
public static final double NANO_TO_BASE = 1.0e9;
/**
* Custom Body class to add drawing functionality.
* @author William Bittle
* @version 3.0.2
* @since 3.0.0
*/
public static class GameObject extends Body {
/** The color of the object */
protected Color color;
/**
* Default constructor.
*/
public GameObject() {
// randomly generate the color
this.color = new Color(
(float)Math.random() * 0.5f + 0.5f,
(float)Math.random() * 0.5f + 0.5f,
(float)Math.random() * 0.5f + 0.5f);
}
/**
* Draws the body.
* <p>
* Only coded for polygons and circles.
* @param g the graphics object to render to
*/
public void render(Graphics2D g) {
// save the original transform
AffineTransform ot = g.getTransform();
// transform the coordinate system from world coordinates to local coordinates
AffineTransform lt = new AffineTransform();
lt.translate(this.transform.getTranslationX() * SCALE, this.transform.getTranslationY() * SCALE);
lt.rotate(this.transform.getRotation());
// apply the transform
g.transform(lt);
// loop over all the body fixtures for this body
for (BodyFixture fixture : this.fixtures) {
// get the shape on the fixture
Convex convex = fixture.getShape();
Graphics2DRenderer.render(g, convex, SCALE, color);
}
// set the original transform
g.setTransform(ot);
}
}
/** The canvas to draw to */
protected Canvas canvas;
/** The dynamics engine */
protected World world;
/** Wether the example is stopped or not */
protected boolean stopped;
/** The time stamp for the last iteration */
protected long last;
/**
* Default constructor for the window
*/
public ExampleGraphics2D() {
super("Graphics2D Example");
// setup the JFrame
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// add a window listener
this.addWindowListener(new WindowAdapter() {
/* (non-Javadoc)
* @see java.awt.event.WindowAdapter#windowClosing(java.awt.event.WindowEvent)
*/
@Override
public void windowClosing(WindowEvent e) {
// before we stop the JVM stop the example
stop();
super.windowClosing(e);
}
});
// create the size of the window
Dimension size = new Dimension(800, 600);
// create a canvas to paint to
this.canvas = new Canvas();
this.canvas.setPreferredSize(size);
this.canvas.setMinimumSize(size);
this.canvas.setMaximumSize(size);
// add the canvas to the JFrame
this.add(this.canvas);
// make the JFrame not resizable
// (this way I dont have to worry about resize events)
this.setResizable(false);
// size everything
this.pack();
// make sure we are not stopped
this.stopped = false;
// setup the world
this.initializeWorld();
}
/**
* Creates game objects and adds them to the world.
* <p>
* Basically the same shapes from the Shapes test in
* the TestBed.
*/
protected void initializeWorld() {
// create the world
this.world = new World();
// create all your bodies/joints
// create the floor
Rectangle floorRect = new Rectangle(15.0, 1.0);
GameObject floor = new GameObject();
floor.addFixture(new BodyFixture(floorRect));
floor.setMass(MassType.INFINITE);
// move the floor down a bit
floor.translate(0.0, -4.0);
this.world.addBody(floor);
// create a triangle object
Triangle triShape = new Triangle(
new Vector2(0.0, 0.5),
new Vector2(-0.5, -0.5),
new Vector2(0.5, -0.5));
GameObject triangle = new GameObject();
triangle.addFixture(triShape);
triangle.setMass(MassType.NORMAL);
triangle.translate(-1.0, 2.0);
// test having a velocity
triangle.getLinearVelocity().set(5.0, 0.0);
this.world.addBody(triangle);
// create a circle
Circle cirShape = new Circle(0.5);
GameObject circle = new GameObject();
circle.addFixture(cirShape);
circle.setMass(MassType.NORMAL);
circle.translate(2.0, 2.0);
// test adding some force
circle.applyForce(new Vector2(-100.0, 0.0));
// set some linear damping to simulate rolling friction
circle.setLinearDamping(0.05);
this.world.addBody(circle);
// try a rectangle
Rectangle rectShape = new Rectangle(1.0, 1.0);
GameObject rectangle = new GameObject();
rectangle.addFixture(rectShape);
rectangle.setMass(MassType.NORMAL);
rectangle.translate(0.0, 2.0);
rectangle.getLinearVelocity().set(-5.0, 0.0);
this.world.addBody(rectangle);
// try a polygon with lots of vertices
Polygon polyShape = Geometry.createUnitCirclePolygon(10, 1.0);
GameObject polygon = new GameObject();
polygon.addFixture(polyShape);
polygon.setMass(MassType.NORMAL);
polygon.translate(-2.5, 2.0);
// set the angular velocity
polygon.setAngularVelocity(Math.toRadians(-20.0));
this.world.addBody(polygon);
// try a compound object
Circle c1 = new Circle(0.5);
BodyFixture c1Fixture = new BodyFixture(c1);
c1Fixture.setDensity(0.5);
Circle c2 = new Circle(0.5);
BodyFixture c2Fixture = new BodyFixture(c2);
c2Fixture.setDensity(0.5);
Rectangle rm = new Rectangle(2.0, 1.0);
// translate the circles in local coordinates
c1.translate(-1.0, 0.0);
c2.translate(1.0, 0.0);
GameObject capsule = new GameObject();
capsule.addFixture(c1Fixture);
capsule.addFixture(c2Fixture);
capsule.addFixture(rm);
capsule.setMass(MassType.NORMAL);
capsule.translate(0.0, 4.0);
this.world.addBody(capsule);
GameObject issTri = new GameObject();
issTri.addFixture(Geometry.createIsoscelesTriangle(1.0, 3.0));
issTri.setMass(MassType.NORMAL);
issTri.translate(2.0, 3.0);
this.world.addBody(issTri);
GameObject equTri = new GameObject();
equTri.addFixture(Geometry.createEquilateralTriangle(2.0));
equTri.setMass(MassType.NORMAL);
equTri.translate(3.0, 3.0);
this.world.addBody(equTri);
GameObject rightTri = new GameObject();
rightTri.addFixture(Geometry.createRightTriangle(2.0, 1.0));
rightTri.setMass(MassType.NORMAL);
rightTri.translate(4.0, 3.0);
this.world.addBody(rightTri);
GameObject cap = new GameObject();
cap.addFixture(new Capsule(1.0, 0.5));
cap.setMass(MassType.NORMAL);
cap.translate(-3.0, 3.0);
this.world.addBody(cap);
GameObject slice = new GameObject();
slice.addFixture(new Slice(0.5, Math.toRadians(120)));
slice.setMass(MassType.NORMAL);
slice.translate(-3.0, 3.0);
this.world.addBody(slice);
}
/**
* Start active rendering the example.
* <p>
* This should be called after the JFrame has been shown.
*/
public void start() {
// initialize the last update time
this.last = System.nanoTime();
// don't allow AWT to paint the canvas since we are
this.canvas.setIgnoreRepaint(true);
// enable double buffering (the JFrame has to be
// visible before this can be done)
this.canvas.createBufferStrategy(2);
// run a separate thread to do active rendering
// because we don't want to do it on the EDT
Thread thread = new Thread() {
public void run() {
// perform an infinite loop stopped
// render as fast as possible
while (!isStopped()) {
gameLoop();
// you could add a Thread.yield(); or
// Thread.sleep(long) here to give the
// CPU some breathing room
}
}
};
// set the game loop thread to a daemon thread so that
// it cannot stop the JVM from exiting
thread.setDaemon(true);
// start the game loop
thread.start();
}
/**
* The method calling the necessary methods to update
* the game, graphics, and poll for input.
*/
protected void gameLoop() {
// get the graphics object to render to
Graphics2D g = (Graphics2D)this.canvas.getBufferStrategy().getDrawGraphics();
// before we render everything im going to flip the y axis and move the
// origin to the center (instead of it being in the top left corner)
AffineTransform yFlip = AffineTransform.getScaleInstance(1, -1);
AffineTransform move = AffineTransform.getTranslateInstance(400, -300);
g.transform(yFlip);
g.transform(move);
// now (0, 0) is in the center of the screen with the positive x axis
// pointing right and the positive y axis pointing up
// render anything about the Example (will render the World objects)
this.render(g);
// dispose of the graphics object
g.dispose();
// blit/flip the buffer
BufferStrategy strategy = this.canvas.getBufferStrategy();
if (!strategy.contentsLost()) {
strategy.show();
}
// Sync the display on some systems.
// (on Linux, this fixes event queue problems)
Toolkit.getDefaultToolkit().sync();
// update the World
// get the current time
long time = System.nanoTime();
// get the elapsed time from the last iteration
long diff = time - this.last;
// set the last time
this.last = time;
// convert from nanoseconds to seconds
double elapsedTime = diff / NANO_TO_BASE;
// update the world with the elapsed time
this.world.update(elapsedTime);
}
/**
* Renders the example.
* @param g the graphics object to render to
*/
protected void render(Graphics2D g) {
// lets draw over everything with a white background
g.setColor(Color.WHITE);
g.fillRect(-400, -300, 800, 600);
// lets move the view up some
g.translate(0.0, -1.0 * SCALE);
// draw all the objects in the world
for (int i = 0; i < this.world.getBodyCount(); i++) {
// get the object
GameObject go = (GameObject) this.world.getBody(i);
// draw the object
go.render(g);
}
}
/**
* Stops the example.
*/
public synchronized void stop() {
this.stopped = true;
}
/**
* Returns true if the example is stopped.
* @return boolean true if stopped
*/
public synchronized boolean isStopped() {
return this.stopped;
}
/**
* Entry point for the example application.
* @param args command line arguments
*/
public static void main(String[] args) {
// set the look and feel to the system look and feel
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (UnsupportedLookAndFeelException e) {
e.printStackTrace();
}
// create the example JFrame
ExampleGraphics2D window = new ExampleGraphics2D();
// show it
window.setVisible(true);
// start it
window.start();
}
}