Advertisement
codeanticode

Untitled

Feb 18th, 2012
258
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.43 KB | None | 0 0
  1. package p5.test_newt_canvas;
  2.  
  3. import java.applet.Applet;
  4. import java.awt.Frame;
  5. import java.awt.GraphicsDevice;
  6. import java.awt.GraphicsEnvironment;
  7. import java.awt.Insets;
  8. import java.awt.event.MouseEvent;
  9. import java.awt.event.MouseMotionListener;
  10. import java.awt.event.WindowAdapter;
  11. import java.awt.event.WindowEvent;
  12. import java.util.Timer;
  13. import java.util.TimerTask;
  14.  
  15. import javax.media.opengl.GL;
  16. import javax.media.opengl.GLAutoDrawable;
  17. import javax.media.opengl.GLCapabilities;
  18. import javax.media.opengl.GLProfile;
  19.  
  20. import javax.media.opengl.*;
  21.  
  22. import com.jogamp.newt.awt.NewtCanvasAWT;
  23. import com.jogamp.newt.opengl.GLWindow;
  24. import com.jogamp.opengl.util.AnimatorBase;
  25.  
  26. public class MiniPApplet extends Applet implements MouseMotionListener {
  27.   private static final long serialVersionUID = 1L;
  28.  
  29.   /////////////////////////////////////////////////////////////
  30.   //
  31.   // Test parameters  
  32.  
  33.   public int frameRate = 120;
  34.   public boolean hookToFrame = true;
  35.   public boolean printThreadInfo = false;
  36.  
  37.   /////////////////////////////////////////////////////////////
  38.   //
  39.   // Internal variables
  40.  
  41.   private Frame frame;
  42.   private GLProfile profile;
  43.   private GLCapabilities capabilities;
  44.   private NewtCanvasAWT canvas;
  45.   private GLWindow window;
  46.  
  47.   private CustomAnimator animator;
  48.  
  49.   private long beforeTime;
  50.   private long overSleepTime;
  51.   private long frameRatePeriod = 1000000000L / frameRate;
  52.  
  53.   private boolean initialized = false;  
  54.  
  55.   private double theta = 0;
  56.   private double s = 0;
  57.   private double c = 0;  
  58.  
  59.   private long millisOffset;
  60.   private int fcount, lastm;
  61.   private float frate;
  62.   private int fint = 3;
  63.  
  64.   void run() {
  65.     Thread loop = new Thread("Animation Thread") {
  66.       public void run() {        
  67.         while (true) {          
  68.           if (!initialized) {
  69.             setup();            
  70.           }
  71.          
  72.           animator.requestRender();
  73.          
  74.           clock();
  75.         }
  76.       }
  77.     };
  78.     loop.start();        
  79.   }
  80.  
  81.   void setup() {
  82.     if (printThreadInfo) System.out.println("Current thread at setup(): " + Thread.currentThread());
  83.    
  84.     millisOffset = System.currentTimeMillis();    
  85.  
  86.     GraphicsEnvironment environment =
  87.       GraphicsEnvironment.getLocalGraphicsEnvironment();
  88.     GraphicsDevice displayDevice = environment.getDefaultScreenDevice();
  89.     frame = new Frame(displayDevice.getDefaultConfiguration());
  90.    
  91.     frame.setLayout(null);
  92.     frame.setTitle("MiniPApplet");
  93.     frame.pack();
  94.     frame.setResizable(false);
  95.    
  96.     Insets insets = frame.getInsets();
  97.     int windowW = 300 + insets.left + insets.right;
  98.     int windowH = 300 + insets.top + insets.bottom;
  99.     int locationX = 100;
  100.     int locationY = 100;
  101.    
  102.     frame.setSize(windowW, windowH);    
  103.     frame.setLocation(locationX, locationY);  
  104.    
  105.     frame.add(this);
  106.     frame.setVisible(true);
  107.     frame.addWindowListener(new WindowAdapter() {
  108.       public void windowClosing(WindowEvent e) {
  109.           System.exit(0);
  110.       }
  111.     });    
  112.    
  113.     int usableWindowH = windowH - insets.top - insets.bottom;
  114.     this.setBounds((windowW - 300)/2, insets.top + (usableWindowH - 300)/2, 300, 300);
  115.    
  116.     profile = GLProfile.getMaxFixedFunc();
  117.     capabilities = new GLCapabilities(profile);
  118.     capabilities.setSampleBuffers(false);
  119.     window = GLWindow.create(capabilities);
  120.     canvas = new NewtCanvasAWT(window);
  121.      
  122.     if (hookToFrame) {
  123.       // Problems of hooking newt canvas to frame:
  124.       // 1) window looses decorations on OSX
  125.       // 2) is not logically consistent: frame contains
  126.       //    both applet and canvas as child components,
  127.       //    it should be frame -> applet -> canvas
  128.       // 3) Mouse motion events are not picked up.
  129.       frame.add(canvas, frame.getComponentCount() - 1);
  130.       frame.validate();
  131.     } else {
  132.       // Problems of hooking newt canvas to applet:
  133.       // 1) Set framerate is not honored
  134.       // 2) gives invalid drawable error  
  135.       // 3) the canvas is slightly off on the
  136.       //    vertical direction.
  137.       this.add(canvas, this.getComponentCount() - 1);
  138.       this.validate();
  139.      
  140.     }
  141.     canvas.addMouseMotionListener(this);
  142.    
  143.     // Setting up animation
  144.     window.addGLEventListener(new Renderer());
  145.     animator = new CustomAnimator(window);
  146.     animator.setThreadName("OpenGL");
  147.     animator.start();
  148.    
  149.     initialized = true;    
  150.   }  
  151.  
  152.  
  153.   void draw(GL2 gl) {
  154.     if (printThreadInfo) System.out.println("Current thread at draw(): " + Thread.currentThread());          
  155.    
  156.     gl.glClearColor(0, 0, 0, 1);
  157.     gl.glClear(GL.GL_COLOR_BUFFER_BIT);
  158.    
  159.     theta += 0.01;
  160.     s = Math.sin(theta);
  161.     c = Math.cos(theta);      
  162.    
  163.     gl.glBegin(GL.GL_TRIANGLES);
  164.     gl.glColor3f(1, 0, 0);
  165.     gl.glVertex2d(-c, -c);
  166.     gl.glColor3f(0, 1, 0);
  167.     gl.glVertex2d(0, c);
  168.     gl.glColor3f(0, 0, 1);
  169.     gl.glVertex2d(s, -s);
  170.     gl.glEnd();    
  171.    
  172.     gl.glFlush();
  173.    
  174.     fcount += 1;
  175.     int m = (int) (System.currentTimeMillis() - millisOffset);
  176.     if (m - lastm > 1000 * fint) {
  177.       frate = (float)(fcount) / fint;
  178.       fcount = 0;
  179.       lastm = m;
  180.       System.err.println("fps: " + frate);
  181.     }    
  182.   }
  183.  
  184.   void clock() {
  185.     long afterTime = System.nanoTime();
  186.     long timeDiff = afterTime - beforeTime;
  187.     long sleepTime = (frameRatePeriod - timeDiff) - overSleepTime;
  188.  
  189.     if (sleepTime > 0) {  // some time left in this cycle
  190.       try {
  191.         Thread.sleep(sleepTime / 1000000L, (int) (sleepTime % 1000000L));
  192.       } catch (InterruptedException ex) { }
  193.  
  194.       overSleepTime = (System.nanoTime() - afterTime) - sleepTime;
  195.  
  196.     } else {    // sleepTime <= 0; the frame took longer than the period
  197.       overSleepTime = 0L;
  198.     }
  199.  
  200.     beforeTime = System.nanoTime();    
  201.   }  
  202.  
  203.   class Renderer implements GLEventListener {
  204.     @Override
  205.     public void display(GLAutoDrawable drawable) {
  206.       draw(drawable.getGL().getGL2());
  207.     }
  208.  
  209.     @Override
  210.     public void dispose(GLAutoDrawable drawable) { }
  211.  
  212.     @Override
  213.     public void init(GLAutoDrawable drawable) { }
  214.  
  215.     @Override
  216.     public void reshape(GLAutoDrawable drawable, int x, int y, int w, int h) { }    
  217.   }
  218.  
  219.   public void mouseMoved(MouseEvent e) {
  220.     System.err.println("Mouse moved event: " + e.toString());
  221.   }
  222.  
  223.   public void mouseDragged(MouseEvent e) {
  224.     System.err.println("Mouse dragged event: " + e.toString());    
  225.   }  
  226.  
  227.   public static void main(String[] args) {
  228.     MiniPApplet mini;
  229.     try {
  230.       Class<?> c = Thread.currentThread().getContextClassLoader().loadClass(MiniPApplet.class.getName());
  231.       mini = (MiniPApplet) c.newInstance();
  232.     } catch (Exception e) {
  233.       throw new RuntimeException(e);
  234.     }    
  235.     if (mini != null) {
  236.       mini.run();
  237.     }
  238.   }      
  239.  
  240.   /** An Animator subclass which renders one frame at the time
  241.    *  upon calls to the requestRender() method.
  242.    **/
  243.   public class CustomAnimator extends AnimatorBase {    
  244.       private Timer timer = null;
  245.       private TimerTask task = null;
  246.       private String threadName = null;
  247.       private volatile boolean shouldRun;
  248.  
  249.       protected String getBaseName(String prefix) {
  250.           return "Custom" + prefix + "Animator" ;
  251.       }
  252.  
  253.       /** Creates an CustomAnimator with an initial drawable to
  254.        * animate. */
  255.       public CustomAnimator(GLAutoDrawable drawable) {
  256.           if (drawable != null) {
  257.               add(drawable);
  258.           }
  259.       }
  260.      
  261.       public void setThreadName(String name) {
  262.         threadName = name;
  263.       }
  264.  
  265.       public synchronized void requestRender() {
  266.           shouldRun = true;
  267.       }
  268.  
  269.       public final boolean isStarted() {
  270.           stateSync.lock();
  271.           try {
  272.               return (timer != null);
  273.           } finally {
  274.               stateSync.unlock();
  275.           }
  276.       }
  277.  
  278.       public final boolean isAnimating() {
  279.           stateSync.lock();
  280.           try {
  281.               return (timer != null) && (task != null);
  282.           } finally {
  283.               stateSync.unlock();
  284.           }
  285.       }
  286.  
  287.       private void startTask() {
  288.           if(null != task) {
  289.               return;
  290.           }
  291.          
  292.           task = new TimerTask() {
  293.               private boolean firstRun = true;
  294.               public void run() {
  295.                   if (firstRun) {
  296.                     if (threadName != null) Thread.currentThread().setName(threadName);
  297.                     firstRun = false;
  298.                   }
  299.                   if(CustomAnimator.this.shouldRun) {
  300.                      CustomAnimator.this.animThread = Thread.currentThread();
  301.                       // display impl. uses synchronized block on the animator instance
  302.                       display();                
  303.                       synchronized (this) {
  304.                         // done with current frame.
  305.                         shouldRun = false;
  306.                       }                    
  307.                   }
  308.               }
  309.           };
  310.  
  311.           fpsCounter.resetFPSCounter();
  312.           shouldRun = false;
  313.          
  314.           timer.schedule(task, 0, 1);
  315.       }
  316.      
  317.       public synchronized boolean  start() {
  318.           if (timer != null) {
  319.               return false;
  320.           }
  321.           stateSync.lock();
  322.           try {
  323.               timer = new Timer();
  324.               startTask();
  325.           } finally {
  326.               stateSync.unlock();
  327.           }
  328.           return true;
  329.       }
  330.  
  331.       /** Stops this CustomAnimator. */
  332.       public synchronized boolean stop() {
  333.           if (timer == null) {
  334.               return false;
  335.           }
  336.           stateSync.lock();
  337.           try {
  338.               shouldRun = false;
  339.               if(null != task) {
  340.                   task.cancel();
  341.                   task = null;
  342.               }
  343.               if(null != timer) {
  344.                   timer.cancel();
  345.                   timer = null;
  346.               }
  347.               animThread = null;
  348.               try {
  349.                   Thread.sleep(20); // ~ 1/60 hz wait, since we can't ctrl stopped threads
  350.               } catch (InterruptedException e) { }
  351.           } finally {
  352.               stateSync.unlock();
  353.           }
  354.           return true;
  355.       }
  356.      
  357.       public final boolean isPaused() { return false; }
  358.       public synchronized boolean resume() { return false; }
  359.       public synchronized boolean pause() { return false; }    
  360.   }
  361. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement