Advertisement
codeanticode

Untitled

Mar 19th, 2012
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.03 KB | None | 0 0
  1. package p5.test_newt_applet;
  2.  
  3. import java.applet.Applet;
  4. import java.awt.BorderLayout;
  5. import java.awt.Frame;
  6. import java.awt.GraphicsDevice;
  7. import java.awt.GraphicsEnvironment;
  8. import java.awt.Insets;
  9. import java.awt.event.MouseEvent;
  10. import java.awt.event.MouseMotionListener;
  11. import java.awt.event.WindowAdapter;
  12. import java.awt.event.WindowEvent;
  13. import java.util.Timer;
  14. import java.util.TimerTask;
  15.  
  16. import javax.media.opengl.*;
  17.  
  18. import com.jogamp.newt.awt.NewtCanvasAWT;
  19. import com.jogamp.newt.opengl.GLWindow;
  20. import com.jogamp.opengl.util.AnimatorBase;
  21.  
  22. public class MiniPApplet extends Applet implements MouseMotionListener {
  23.   private static final long serialVersionUID = 1L;
  24.  
  25.   /////////////////////////////////////////////////////////////
  26.   //
  27.   // Test parameters  
  28.  
  29.   public int frameRate = 120;
  30.   public int numSamples = 2;
  31.  
  32.   /////////////////////////////////////////////////////////////
  33.   //
  34.   // Internal variables
  35.  
  36.   int width;
  37.   int height;  
  38.  
  39.   private Frame frame;
  40.   private GLProfile profile;
  41.   private GLCapabilities capabilities;
  42.   private NewtCanvasAWT canvas;
  43.   private GLWindow window;
  44.  
  45.   private SimpleListener listener;
  46.   private CustomAnimator animator;
  47.  
  48.   private long beforeTime;
  49.   private long overSleepTime;
  50.   private long frameRatePeriod = 1000000000L / frameRate;
  51.  
  52.   private boolean initialized = false;  
  53.  
  54.   private double theta = 0;
  55.   private double s = 0;
  56.   private double c = 0;  
  57.  
  58.   private long millisOffset;
  59.   private int fcount, lastm;
  60.   private float frate;
  61.   private int fint = 3;
  62.  
  63.   private boolean setFramerate = false;
  64.  
  65.   void run() {
  66.     Thread loop = new Thread("Animation Thread") {
  67.       public void run() {        
  68.         while (true) {          
  69.           if (!initialized) {
  70.             setup();            
  71.           }
  72.          
  73.           animator.requestRender();
  74.          
  75.           clock();
  76.         }
  77.       }
  78.     };
  79.     loop.start();        
  80.   }
  81.  
  82.   void setup() {
  83.     millisOffset = System.currentTimeMillis();    
  84.  
  85.     // Frame setup ----------------------------------------------------------
  86.    
  87.     width = 300;
  88.     height = 300;    
  89.     MiniPApplet applet = this;
  90.    
  91.     GraphicsEnvironment environment =
  92.       GraphicsEnvironment.getLocalGraphicsEnvironment();
  93.     GraphicsDevice displayDevice = environment.getDefaultScreenDevice();
  94.     frame = new Frame(displayDevice.getDefaultConfiguration());
  95.    
  96.     frame.setTitle("MiniPApplet");
  97.     frame.setLayout(null);
  98.     frame.add(applet);
  99.     frame.pack();
  100.     frame.setResizable(false);
  101.    
  102.     Insets insets = frame.getInsets();
  103.  
  104.     int windowW = applet.width + insets.left + insets.right;
  105.     int windowH = applet.height + insets.top + insets.bottom;
  106.     int locationX = 100;
  107.     int locationY = 100;
  108.    
  109.     frame.setSize(windowW, windowH);
  110.     frame.setLocation(locationX, locationY);
  111.    
  112.     int usableWindowH = windowH - insets.top - insets.bottom;
  113.     applet.setBounds((windowW - width)/2, insets.top + (usableWindowH - height)/2, width, height);      
  114.    
  115.     frame.add(this);
  116.     frame.addWindowListener(new WindowAdapter() {
  117.       public void windowClosing(WindowEvent e) {
  118.           System.exit(0);
  119.       }
  120.     });    
  121.    
  122.     frame.setVisible(true);
  123.  
  124.     // Canvas setup ----------------------------------------------------------
  125.    
  126.     profile = GLProfile.getDefault();
  127.     capabilities = new GLCapabilities(profile);
  128.     capabilities.setSampleBuffers(true);
  129.     capabilities.setNumSamples(numSamples);
  130.    
  131.     window = GLWindow.create(capabilities);
  132.     canvas = new NewtCanvasAWT(window);
  133.    
  134.     this.setLayout(new BorderLayout());
  135.     this.add(canvas, BorderLayout.CENTER);
  136.     canvas.addMouseMotionListener(this);
  137.    
  138.     // Setting up animation
  139.     listener = new SimpleListener();
  140.     window.addGLEventListener(listener);
  141.     animator = new CustomAnimator(window);
  142.     animator.start();
  143.    
  144.     initialized = true;    
  145.   }
  146.    
  147.   void draw(GL2 gl) {
  148.     if (!setFramerate) {      
  149.       if (60 < frameRate) {
  150.         // Disables vsync
  151.         gl.setSwapInterval(0);  
  152.       } else if (30 < frameRate) {        
  153.         gl.setSwapInterval(1);
  154.       } else {
  155.         gl.setSwapInterval(2);
  156.       }      
  157.       setFramerate = true;      
  158.     }
  159.    
  160.     int[] temp = { 0 };
  161.     gl.glGetIntegerv(GL.GL_SAMPLES, temp, 0);    
  162.     if (numSamples != temp[0]) {
  163.       System.err.println("Multisampling level requested " + numSamples + " not supported. Using " + temp[0] + " samples instead.");
  164.     }    
  165.        
  166.     gl.glClearColor(0, 0, 0, 1);
  167.     gl.glClear(GL.GL_COLOR_BUFFER_BIT);
  168.    
  169.     theta += 0.01;
  170.     s = Math.sin(theta);
  171.     c = Math.cos(theta);      
  172.    
  173.     gl.glBegin(GL.GL_TRIANGLES);
  174.     gl.glColor3f(1, 0, 0);
  175.     gl.glVertex2d(-c, -c);
  176.     gl.glColor3f(0, 1, 0);
  177.     gl.glVertex2d(0, c);
  178.     gl.glColor3f(0, 0, 1);
  179.     gl.glVertex2d(s, -s);
  180.     gl.glEnd();    
  181.    
  182.     gl.glFlush();
  183.    
  184.     fcount += 1;
  185.     int m = (int) (System.currentTimeMillis() - millisOffset);
  186.     if (m - lastm > 1000 * fint) {
  187.       frate = (float)(fcount) / fint;
  188.       fcount = 0;
  189.       lastm = m;
  190.       System.err.println("fps: " + frate);
  191.     }    
  192.   }
  193.  
  194.   void clock() {
  195.     long afterTime = System.nanoTime();
  196.     long timeDiff = afterTime - beforeTime;
  197.     long sleepTime = (frameRatePeriod - timeDiff) - overSleepTime;
  198.  
  199.     if (sleepTime > 0) {  // some time left in this cycle
  200.       try {
  201.         Thread.sleep(sleepTime / 1000000L, (int) (sleepTime % 1000000L));
  202.       } catch (InterruptedException ex) { }
  203.  
  204.       overSleepTime = (System.nanoTime() - afterTime) - sleepTime;
  205.  
  206.     } else {    // sleepTime <= 0; the frame took longer than the period
  207.       overSleepTime = 0L;
  208.     }
  209.  
  210.     beforeTime = System.nanoTime();    
  211.   }  
  212.  
  213.   class SimpleListener implements GLEventListener {
  214.     @Override
  215.     public void display(GLAutoDrawable drawable) {
  216.       draw(drawable.getGL().getGL2());
  217.     }
  218.  
  219.     @Override
  220.     public void dispose(GLAutoDrawable drawable) { }
  221.  
  222.     @Override
  223.     public void init(GLAutoDrawable drawable) { }
  224.  
  225.     @Override
  226.     public void reshape(GLAutoDrawable drawable, int x, int y, int w, int h) { }    
  227.   }
  228.  
  229.   public void mouseDragged(MouseEvent ev) {
  230.     System.err.println("Mouse dragged event: " + ev);    
  231.   }
  232.  
  233.   public void mouseMoved(MouseEvent ev) {
  234.     System.err.println("Mouse moved event: " + ev);    
  235.   }    
  236.  
  237.   public static void main(String[] args) {
  238.     MiniPApplet mini;
  239.     try {
  240.       Class<?> c = Thread.currentThread().getContextClassLoader().loadClass(MiniPApplet.class.getName());
  241.       mini = (MiniPApplet) c.newInstance();
  242.     } catch (Exception e) {
  243.       throw new RuntimeException(e);
  244.     }    
  245.     if (mini != null) {
  246.       mini.run();
  247.     }
  248.   }      
  249.  
  250.   /** An Animator subclass which renders one frame at the time
  251.    *  upon calls to the requestRender() method.
  252.    **/
  253.   public class CustomAnimator extends AnimatorBase {    
  254.       private Timer timer = null;
  255.       private TimerTask task = null;
  256.       private volatile boolean shouldRun;
  257.  
  258.       protected String getBaseName(String prefix) {
  259.           return "Custom" + prefix + "Animator" ;
  260.       }
  261.  
  262.       /** Creates an CustomAnimator with an initial drawable to
  263.        * animate. */
  264.       public CustomAnimator(GLAutoDrawable drawable) {
  265.           if (drawable != null) {
  266.               add(drawable);
  267.           }
  268.       }
  269.      
  270.       public synchronized void requestRender() {
  271.           shouldRun = true;
  272.       }
  273.  
  274.       public final boolean isStarted() {
  275.           stateSync.lock();
  276.           try {
  277.               return (timer != null);
  278.           } finally {
  279.               stateSync.unlock();
  280.           }
  281.       }
  282.  
  283.       public final boolean isAnimating() {
  284.           stateSync.lock();
  285.           try {
  286.               return (timer != null) && (task != null);
  287.           } finally {
  288.               stateSync.unlock();
  289.           }
  290.       }
  291.  
  292.       private void startTask() {
  293.           if(null != task) {
  294.               return;
  295.           }
  296.          
  297.           task = new TimerTask() {
  298.               public void run() {
  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