summaryrefslogtreecommitdiff
path: root/src/robotrace/Base.java
blob: e083afd31fa1ff2bb653168c053ac46e40f01075 (plain)
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
package robotrace;

import com.jogamp.opengl.util.FPSAnimator;
import com.jogamp.opengl.util.gl2.GLUT;
import com.jogamp.opengl.util.texture.Texture;
import com.jogamp.opengl.util.texture.TextureIO;
import java.awt.BorderLayout;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseWheelListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.awt.GLCanvas;
import javax.media.opengl.awt.GLJPanel;
import javax.media.opengl.glu.GLU;
import javax.swing.UIManager;

/**
 * Handles all of the RobotRace graphics functionality,
 * which should be extended per the Assignments.
 */
abstract public class Base {
    
    // Library version number.
    static public int LIBRARY_VERSION = 3;
    
    // Minimum distance of camera to center point.
    static public float MIN_CAMERA_DISTANCE = 1f;
    
    // Distance multiplier per mouse wheel tick.
    static public float MOUSE_WHEEL_FACTOR = 1.2f;
    
    // Minimum value of phi.
    static public float PHI_MIN = -(float) Math.PI / 2f + 0.01f;
    
    // Maximum value of phi.
    static public float PHI_MAX = (float) Math.PI / 2f - 0.01f;
    
    // Ratio of distance in pixels dragged and radial change of camera.
    static public float DRAG_PIXEL_TO_RADIAN = 0.025f;
    
    // Minimum value of vWidth.
    static public float VWIDTH_MIN = 1f;
    
    // Maximum value of vWidth.
    static public float VWIDTH_MAX = 1000f;
    
    // Ratio of vertical distance dragged and change of vWidth;
    static public float DRAG_PIXEL_TO_VWIDTH = 0.1f;
    
    // Extent of center point change based on key input.
    static public float CENTER_POINT_CHANGE = 1f;
    
    // Desired frames per second.
    static public int FPS = 30;
    
    
    // Global state, created at startup.
    protected GlobalState gs;
    
    // OpenGL reference, continuously updated for correct thread.
    protected GL2 gl;
    
    // OpenGL utility functions.
    protected GLU glu;
    protected GLUT glut;
    
    // Start time of animation.
    private long startTime;
    
    // Textures.
    protected Texture track, brick, head, torso;
    
    /**
     * Constructs base class.
     */
    public Base() {
        // Print library version number.
        System.out.println("Using RobotRace library version " + LIBRARY_VERSION);
        
        // Global state.
        this.gs = new GlobalState();
        
        // Enable fancy GUI theme.
        try {
            UIManager.setLookAndFeel(
                "com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
        } catch(Exception ex) {
            Logger.getLogger(Base.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        // GUI frame.
        MainFrame frame = new MainFrame(gs);
        
        // OpenGL utility functions.
        this.glu = new GLU();
        this.glut = new GLUT();
        
        // Redirect OpenGL listener to the abstract render functions.
        GLJPanel glPanel = (GLJPanel) frame.glPanel;

        // HACK: get better performance
        GLCanvas glCanvas = new GLCanvas();
        frame.remove(glPanel);
        frame.getContentPane().add(glCanvas, BorderLayout.CENTER);
        glCanvas.addGLEventListener(new GLEventDelegate());
        
        // Attach mouse and keyboard listeners.
        GLListener listener = new GLListener();
        glCanvas.addMouseListener(listener);
        glCanvas.addMouseMotionListener(listener);
        glCanvas.addMouseWheelListener(listener);
        glCanvas.addKeyListener(listener);
        glCanvas.setFocusable(true);
        glCanvas.requestFocusInWindow();

        // Attach animator to OpenGL panel and begin refresh
        // at the specified number of frames per second.
        final FPSAnimator animator =
                new FPSAnimator(glCanvas, FPS, true);
        animator.setIgnoreExceptions(false);
        animator.setPrintExceptions(true);
        
        animator.start();

        // Stop animator when window is closed.
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                animator.stop();
            }
        });       

        // Show frame.
        frame.setVisible(true);
    }
    
    /**
     * Called upon the start of the application.
     * Primarily used to configure OpenGL.
     */
    abstract public void initialize();
    
    /**
     * Configures the viewing transform.
     */
    abstract public void setView();
    
    /**
     * Draws the entire scene.
     */
    abstract public void drawScene();

    /**
     * Pass a vector as a vertex to OpenGL.
     */
    public void glVertex(Vector vector) {
        gl.glVertex3d(vector.x(),
                      vector.y(),
                      vector.z());
    }
    
    /**
     * Delegates OpenGL events to abstract methods.
     */
    private final class GLEventDelegate implements GLEventListener {

        /**
         * Initialization of OpenGL state.
         */
        @Override
        public void init(GLAutoDrawable drawable) {
            gl = drawable.getGL().getGL2();
            
            // Try to load textures.
            track = loadTexture("track.jpg");
            brick = loadTexture("brick.jpg");
            head = loadTexture("head.jpg");
            torso = loadTexture("torso.jpg");
            
            // Print library version number.
            //System.out.println("Using RobotRace library version " + LIBRARY_VERSION);
            
            initialize();
        }
    
        /**
         * Try to load a texture from the given file. The file
         * should be located in the same folder as RobotRace.java.
         */
        private Texture loadTexture(String file) {
            Texture result = null;

            try {
                // Try to load from local folder.
                result = TextureIO.newTexture(new File(file), false);
            } catch(Exception e1) {
                // Try to load from /src folder instead.
                try {
                    result = TextureIO.newTexture(new File("src/" + file), false);
                } catch(Exception e2) {
                    
                }
            }
            
            if(result != null) {
                System.out.println("Loaded " + file);
                result.enable(gl);
            }

            return result;
        }

        /**
         * Render scene.
         */
        @Override
        public void display(GLAutoDrawable drawable) {
            gl = drawable.getGL().getGL2();
            
            // Update wall time, and reset if required.
            if(gs.tAnim < 0) {
                startTime = System.currentTimeMillis();
            }
            gs.tAnim = (float) (System.currentTimeMillis() - startTime) / 1000f;
            
            // Also update view, because global state may have changed.
            setView();
            drawScene();
            
            // Report OpenGL errors.
            int errorCode = gl.glGetError();
            while(errorCode != GL.GL_NO_ERROR) {
                System.err.println(errorCode + " " +
                                   glu.gluErrorString(errorCode));
                errorCode = gl.glGetError();
            }
        }

        /**
         * Canvas reshape.
         */
        @Override
        public void reshape(GLAutoDrawable drawable,
                            int x, int y,
                            int width, int height) {
            gl = drawable.getGL().getGL2();
            
            // Update state.
            gs.w = width;
            gs.h = height;
            
            setView();
        }

        @Override
        public void dispose(GLAutoDrawable drawable) {
            
        }

    }
    
    /**
     * Handles mouse events of the GLJPanel to support the interactive
     * change of camera angles and distance in the global state.
     */
    private final class GLListener implements MouseMotionListener,
                                              MouseListener,
                                              MouseWheelListener,
                                              KeyListener {
        // Position of mouse drag source.
        private int dragSourceX, dragSourceY;
        
        // Last mouse button pressed.
        private int mouseButton;

        @Override
        public void mouseDragged(MouseEvent e) {
            float dX = e.getX() - dragSourceX;
            float dY = e.getY() - dragSourceY;
            
            // Change camera angle when left button is pressed.
            if(mouseButton == MouseEvent.BUTTON1) {
                gs.theta += dX * DRAG_PIXEL_TO_RADIAN;
                gs.phi = Math.max(PHI_MIN,
                                    Math.min(PHI_MAX,
                                             gs.phi + dY * DRAG_PIXEL_TO_RADIAN));
            }
            // Change vWidth when right button is pressed.
            else if(mouseButton == MouseEvent.BUTTON3) {
                gs.vWidth = Math.max(VWIDTH_MIN,
                                     Math.min(VWIDTH_MAX,
                                              gs.vWidth + dY * DRAG_PIXEL_TO_VWIDTH));
            }
            
            dragSourceX = e.getX();
            dragSourceY = e.getY();
        }

        @Override
        public void mouseMoved(MouseEvent e) {
        }

        @Override
        public void mouseWheelMoved(MouseWheelEvent e) {
            gs.vDist = (float) Math.max(MIN_CAMERA_DISTANCE,
                                        gs.vDist *
                                        Math.pow(MOUSE_WHEEL_FACTOR,
                                                 e.getWheelRotation()));
        }

        @Override
        public void mouseClicked(MouseEvent e) {
        }

        @Override
        public void mousePressed(MouseEvent e) {
            dragSourceX = e.getX();
            dragSourceY = e.getY();
            mouseButton = e.getButton();
        }

        @Override
        public void mouseReleased(MouseEvent e) {
        }

        @Override
        public void mouseEntered(MouseEvent e) {
        }

        @Override
        public void mouseExited(MouseEvent e) {
        }

        @Override
        public void keyTyped(KeyEvent e) {
        }

        @Override
        public void keyPressed(KeyEvent e) {
            // Move center point.
            double phiQ = gs.theta + Math.PI / 2.0;
            
            switch(e.getKeyChar()) {
                // Right.
                case 'a':   gs.cnt = gs.cnt.subtract(
                                        new Vector(Math.cos(phiQ), Math.sin(phiQ), 0)
                                        .scale(CENTER_POINT_CHANGE));
                            break;
                // Left.
                case 'd':   gs.cnt = gs.cnt.add(
                                        new Vector(Math.cos(phiQ), Math.sin(phiQ), 0)
                                        .scale(CENTER_POINT_CHANGE));
                            break;
                // Forwards.
                case 'w':   gs.cnt = gs.cnt.subtract(
                                        new Vector(Math.cos(gs.theta), Math.sin(gs.theta), 0)
                                        .scale(CENTER_POINT_CHANGE));
                            break;
                // Backwards.
                case 's':   gs.cnt = gs.cnt.add(
                                        new Vector(Math.cos(gs.theta), Math.sin(gs.theta), 0)
                                        .scale(CENTER_POINT_CHANGE));
                            break;
                // Up.
                case 'q':   gs.cnt = new Vector(gs.cnt.x,
                                                gs.cnt.y,
                                                gs.cnt.z + CENTER_POINT_CHANGE);
                            break;
                // Down.
                case 'z':   gs.cnt = new Vector(gs.cnt.x,
                                                gs.cnt.y,
                                                gs.cnt.z - CENTER_POINT_CHANGE);
                            break;
            }
        }

        @Override
        public void keyReleased(KeyEvent e) {
        }
        
    }
    
}