// Might be reduced to !double-buff
 @Test
 public void testGL2OffScreenBitmapDblBuf() throws InterruptedException {
   final GLCapabilities reqGLCaps = new GLCapabilities(GLProfile.getDefault());
   reqGLCaps.setOnscreen(false);
   reqGLCaps.setBitmap(true);
   doTest(reqGLCaps, new Gears(1));
 }
  protected static X11GLXGraphicsConfiguration chooseGraphicsConfigurationStatic(
      Capabilities capabilities, CapabilitiesChooser chooser, AbstractGraphicsScreen absScreen) {
    if (absScreen == null) {
      throw new IllegalArgumentException("AbstractGraphicsScreen is null");
    }
    if (!(absScreen instanceof X11GraphicsScreen)) {
      throw new IllegalArgumentException("Only X11GraphicsScreen are allowed here");
    }
    X11GraphicsScreen x11Screen = (X11GraphicsScreen) absScreen;

    if (capabilities != null && !(capabilities instanceof GLCapabilities)) {
      throw new IllegalArgumentException(
          "This NativeWindowFactory accepts only GLCapabilities objects");
    }

    if (chooser != null && !(chooser instanceof GLCapabilitiesChooser)) {
      throw new IllegalArgumentException(
          "This NativeWindowFactory accepts only GLCapabilitiesChooser objects");
    }

    if (capabilities == null) {
      capabilities = new GLCapabilities(null);
    }

    boolean onscreen = capabilities.isOnscreen();
    boolean usePBuffer = ((GLCapabilities) capabilities).isPBuffer();

    GLCapabilities caps2 = (GLCapabilities) capabilities.clone();
    if (!caps2.isOnscreen()) {
      // OFFSCREEN !DOUBLE_BUFFER // FIXME DBLBUFOFFSCRN
      caps2.setDoubleBuffered(false);
    }

    X11GLXGraphicsConfiguration res;
    res =
        chooseGraphicsConfigurationFBConfig(
            (GLCapabilities) caps2, (GLCapabilitiesChooser) chooser, x11Screen);
    if (null == res) {
      if (usePBuffer) {
        throw new GLException(
            "Error: Couldn't create X11GLXGraphicsConfiguration based on FBConfig");
      }
      res =
          chooseGraphicsConfigurationXVisual(
              (GLCapabilities) caps2, (GLCapabilitiesChooser) chooser, x11Screen);
    }
    if (null == res) {
      throw new GLException("Error: Couldn't create X11GLXGraphicsConfiguration");
    }
    if (DEBUG) {
      System.err.println(
          "X11GLXGraphicsConfiguration.chooseGraphicsConfigurationStatic("
              + x11Screen
              + ","
              + caps2
              + "): "
              + res);
    }
    return res;
  }
Пример #3
0
  /** Setup the avaiatrix pipeline here */
  private void setupAviatrix() {
    // Assemble a simple single-threaded pipeline.
    GLCapabilities caps = new GLCapabilities();
    caps.setDoubleBuffered(true);
    caps.setHardwareAccelerated(true);

    GraphicsCullStage culler = new NullCullStage();
    culler.setOffscreenCheckEnabled(false);

    GraphicsSortStage sorter = new SimpleTransparencySortStage();
    surface = new DebugAWTSurface(caps);
    DefaultGraphicsPipeline pipeline = new DefaultGraphicsPipeline();

    pipeline.setCuller(culler);
    pipeline.setSorter(sorter);
    pipeline.setGraphicsOutputDevice(surface);

    displayManager = new SingleDisplayCollection();
    displayManager.addPipeline(pipeline);

    // Render manager
    sceneManager = new SingleThreadRenderManager();
    sceneManager.addDisplay(displayManager);
    sceneManager.setMinimumFrameInterval(100);

    // Before putting the pipeline into run mode, put the canvas on
    // screen first.
    Component comp = (Component) surface.getSurfaceObject();
    add(comp, BorderLayout.CENTER);
  }
Пример #4
0
 protected GLCapabilities createCapabilities() {
   GLCapabilities caps = new GLCapabilities(GLProfile.get(GLProfile.GL2));
   caps.setStencilBits(1);
   caps.setDoubleBuffered(true);
   caps.setAlphaBits(8);
   return caps;
 }
Пример #5
0
 public static GLCapabilities fixCaps(
     GLCapabilities caps, boolean onscreen, boolean pbuffer, boolean undecorated) {
   GLCapabilities caps2 = (GLCapabilities) caps.clone();
   caps2.setOnscreen(onscreen);
   caps2.setPBuffer(!onscreen && pbuffer);
   caps2.setDoubleBuffered(!onscreen);
   return caps2;
 }
 static {
   caps = new GLCapabilities();
   caps.setDoubleBuffered(true);
   caps.setAlphaBits(8);
   caps.setRedBits(8);
   caps.setGreenBits(8);
   caps.setBlueBits(8);
 }
Пример #7
0
 @Override
 protected GLCanvas createDrawable() {
   GLCapabilities caps = new GLCapabilities(null);
   caps.setSampleBuffers(true);
   //
   GLCanvas panel = new GLCanvas(caps);
   panel.addGLEventListener(this);
   panel.addKeyListener(this);
   return panel;
 }
Пример #8
0
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    String[] urls0 =
        new String[] {
          System.getProperty("jnlp.media0_url2"),
          System.getProperty("jnlp.media0_url1"),
          System.getProperty("jnlp.media0_url0")
        };
    final URLConnection urlConnection0 = getResource(urls0, 0);
    if (null == urlConnection0) {
      throw new RuntimeException("no media reachable: " + Arrays.asList(urls0));
    }

    // also initializes JOGL
    final GLCapabilities capsMain = new GLCapabilities(GLProfile.getGL2ES2());
    capsMain.setBackgroundOpaque(false);

    // screen for layout params ..
    final com.jogamp.newt.Display dpy = NewtFactory.createDisplay(null);
    final com.jogamp.newt.Screen scrn = NewtFactory.createScreen(dpy, 0);
    scrn.addReference();

    try {
      final Animator animator = new Animator();

      // Main
      final MovieCube demoMain =
          new MovieCube(
              urlConnection0,
              GLMediaPlayer.STREAM_ID_AUTO,
              GLMediaPlayer.STREAM_ID_AUTO,
              -2.3f,
              0f,
              0f);
      final GLWindow glWindowMain = GLWindow.create(scrn, capsMain);
      glWindowMain.setFullscreen(true);
      setContentView(getWindow(), glWindowMain);
      glWindowMain.addMouseListener(showKeyboardMouseListener);
      glWindowMain.addGLEventListener(demoMain);
      animator.add(glWindowMain);
      glWindowMain.setVisible(true);

      // animator.setUpdateFPSFrames(60, System.err);
      animator.setUpdateFPSFrames(-1, null);
      animator.resetFPSCounter();
    } catch (IOException e) {
      e.printStackTrace();
    }

    scrn.removeReference();

    Log.d(TAG, "onCreate - X");
  }
Пример #9
0
 @Override
 protected GLJPanel createDrawable() {
   GLCapabilities caps = new GLCapabilities(null);
   caps.setSampleBuffers(true); // enable sample buffers for aliasing
   caps.setNumSamples(2);
   //
   GLJPanel panel = new GLJPanel(caps);
   panel.addGLEventListener(this);
   panel.addKeyListener(this);
   return panel;
 }
 GLFrame(JTextArea outputArea) {
   this.outputArea = outputArea;
   GLCapabilities caps = new GLCapabilities(Configuration.getMaxCompatibleGLProfile());
   caps.setAlphaBits(8);
   caps.setRedBits(8);
   caps.setGreenBits(8);
   caps.setBlueBits(8);
   GLCanvas glCanvas = new GLCanvas(caps);
   glCanvas.addGLEventListener(this);
   this.add(glCanvas);
   this.setSize(200, 200);
 }
Пример #11
0
 @Override
 protected GLJPanel createDrawable() {
   GLCapabilities caps = new GLCapabilities(null);
   // Be certain you request an accumulation buffer.
   caps.setAccumBlueBits(16);
   caps.setAccumGreenBits(16);
   caps.setAccumRedBits(16);
   caps.setAccumAlphaBits(16);
   //
   GLJPanel panel = new GLJPanel(caps);
   panel.addGLEventListener(this);
   panel.addKeyListener(this);
   return panel;
 }
Пример #12
0
  public static void main(String[] args) {
    GLCapabilities caps = new GLCapabilities(null);
    caps.setSampleBuffers(true); // enable sample buffers for aliasing
    caps.setNumSamples(2);

    varray demo = new varray();

    JFrame.setDefaultLookAndFeelDecorated(true);
    JFrame frame = new JFrame("varray");
    frame.setSize(512, 256);
    frame.setLocationRelativeTo(null);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    frame.getContentPane().add(demo.drawable);
    frame.setVisible(true);
    demo.drawable.requestFocusInWindow();
  }
Пример #13
0
  public DrawByLevelFractal() {
    baseDir = "CS371/assignments/assignment02/ifs/";

    ifsFiles = new ArrayList<String>();
    ifsFiles.add("carpet.ifs");
    ifsFiles.add("chaos.ifs");
    ifsFiles.add("coral.ifs");
    ifsFiles.add("curl.ifs");
    ifsFiles.add("four.ifs");
    ifsFiles.add("galaxy.ifs");
    ifsFiles.add("dragon.ifs");
    ifsFiles.add("leady.ifs");
    ifsFiles.add("koch.ifs");
    ifsFiles.add("mouse.ifs");
    ifsFiles.add("leaf.ifs");
    ifsFiles.add("seven.ifs");
    ifsFiles.add("three.ifs");
    ifsFiles.add("tri.ifs");

    pointsToDraw = 80000;
    left = -7;
    right = 7;
    bottom = -7;
    top = 11;
    xOrigin = 0;
    yOrigin = 0;

    rotate_scale_xx = new double[maximumTransitions];
    rotate_scale_xy = new double[maximumTransitions];
    rotate_scale_yx = new double[maximumTransitions];
    rotate_scale_yy = new double[maximumTransitions];
    trans_x = new double[maximumTransitions];
    trans_y = new double[maximumTransitions];
    prob = new double[maximumTransitions];

    caps = new GLCapabilities(GLProfile.getGL2GL3());
    caps.setDoubleBuffered(true); // request double buffer display mode
    caps.setHardwareAccelerated(true);
    canvas = new GLJPanel();
    // canvas.setOpaque(true);
    canvas.addGLEventListener(this);
    canvas.addKeyListener(this);
    animator = new FPSAnimator(canvas, 60);

    getContentPane().add(canvas);
  }
Пример #14
0
  private void run(int type, PerfModule pm) {
    int width = 800;
    int height = 480;
    pmod = pm;
    System.err.println("Perftst.run()");
    try {
      GLCapabilities caps = new GLCapabilities(GLProfile.getGL2ES2());
      // For emulation library, use 16 bpp
      caps.setRedBits(5);
      caps.setGreenBits(6);
      caps.setBlueBits(5);
      caps.setDepthBits(16);

      Window nWindow = null;
      if (0 != (type & USE_AWT)) {
        Display nDisplay =
            NewtFactory.createDisplay(NativeWindowFactory.TYPE_AWT, null); // local display
        Screen nScreen =
            NewtFactory.createScreen(NativeWindowFactory.TYPE_AWT, nDisplay, 0); // screen 0
        nWindow = NewtFactory.createWindow(NativeWindowFactory.TYPE_AWT, nScreen, caps);
        window = GLWindow.create(nWindow);
      } else {
        window = GLWindow.create(caps);
      }

      window.addMouseListener(this);
      window.addGLEventListener(this);
      // window.setEventHandlerMode(GLWindow.EVENT_HANDLER_GL_CURRENT); // default
      // window.setEventHandlerMode(GLWindow.EVENT_HANDLER_GL_NONE); // no current ..

      // Size OpenGL to Video Surface
      window.setSize(width, height);
      window.setFullscreen(true);
      window.setVisible(true);

      window.display();

      // Shut things down cooperatively
      window.destroy();
      window.getFactory().shutdown();
      System.out.println("Perftst shut down cleanly.");
    } catch (Throwable t) {
      t.printStackTrace();
    }
  }
Пример #15
0
 private static GLCapabilities stdcaps() {
   GLProfile prof = GLProfile.getDefault();
   GLCapabilities cap = new GLCapabilities(prof);
   cap.setDoubleBuffered(true);
   cap.setAlphaBits(8);
   cap.setRedBits(8);
   cap.setGreenBits(8);
   cap.setBlueBits(8);
   cap.setSampleBuffers(true);
   cap.setNumSamples(4);
   return (cap);
 }
Пример #16
0
  /** Run the game. */
  public void run() {
    GLProfile glProfile = GLProfile.getDefault();
    GLCapabilities glCapabilities = new GLCapabilities(glProfile);
    glCapabilities.setSampleBuffers(true);
    glCapabilities.setNumSamples(4);

    GLJPanel gamePanel = new GLJPanel(glCapabilities);
    JFrame gameFrame = new JFrame("3D Game");

    GameEngine gameEngine = new GameEngine(myTerrain, gamePanel);

    gameEngine.start();

    gameFrame.getContentPane().add(gamePanel, BorderLayout.CENTER);
    gameFrame.setSize(1024, 768);
    gameFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    gameFrame.setVisible(true);

    gamePanel.requestFocusInWindow();
  }
Пример #17
0
  public static void main(String[] args) {
    GLProfile glp = GLProfile.getGL2ES2();
    GLCapabilities caps = new GLCapabilities(glp);
    caps.setAlphaBits(4);
    caps.setSampleBuffers(true);
    caps.setNumSamples(4);
    System.out.println("Requested: " + caps);

    final GLWindow window = GLWindow.create(caps);
    window.setPosition(10, 10);
    window.setSize(800, 400);
    window.setTitle("GPU UI Newt Demo 01");
    RenderState rs = RenderState.createRenderState(new ShaderState(), SVertex.factory());
    UIGLListener01 uiGLListener = new UIGLListener01(rs, DEBUG, TRACE);
    uiGLListener.attachInputListenerTo(window);
    window.addGLEventListener(uiGLListener);

    window.setUpdateFPSFrames(FPSCounter.DEFAULT_FRAMES_PER_INTERVAL, System.err);
    window.setVisible(true);

    final Animator animator = new Animator();
    animator.setUpdateFPSFrames(FPSCounter.DEFAULT_FRAMES_PER_INTERVAL, System.err);
    animator.add(window);

    window.addKeyListener(
        new KeyAdapter() {
          public void keyPressed(KeyEvent arg0) {
            if (arg0.getKeyCode() == KeyEvent.VK_F4) {
              window.destroy();
            }
          }
        });
    window.addWindowListener(
        new WindowAdapter() {
          public void windowDestroyed(WindowEvent e) {
            animator.stop();
          }
        });

    animator.start();
  }
Пример #18
0
  public static void main(String[] args) {

    final Configuration config = Configuration.loadFromFile();

    GLProfile glp = GLProfile.get(GLProfile.GL2);
    final GLCapabilities caps = new GLCapabilities(glp);
    caps.setStereo(config.graphics.useStereo);
    if (config.graphics.useFsaa) {
      caps.setSampleBuffers(true);
      caps.setNumSamples(config.graphics.fsaaSamples);
    }

    final String[] arguments = args;

    SwingUtilities.invokeLater(
        new Runnable() {
          public void run() {
            new Viewer(config, caps, arguments);
          }
        });
  }
Пример #19
0
  private void initGL() {
    GLProfile profile = GLProfile.getDefault();
    GLCapabilities caps = new GLCapabilities(profile);
    caps.setBackgroundOpaque(true);
    caps.setOnscreen(true);
    caps.setSampleBuffers(false);

    if (TOOLKIT == AWT) {
      awtCanvas = new GLCanvas(caps);
      awtCanvas.setBounds(0, 0, applet.width, applet.height);
      awtCanvas.setBackground(new Color(0xFFCCCCCC, true));
      awtCanvas.setFocusable(true);

      applet.setLayout(new BorderLayout());
      applet.add(awtCanvas, BorderLayout.CENTER);

      if (MANUAL_FRAME_HANDLING) {
        awtCanvas.setIgnoreRepaint(true);
        awtCanvas.setAutoSwapBufferMode(false);
      }
    } else if (TOOLKIT == NEWT) {
      newtWindow = GLWindow.create(caps);
      newtCanvas = new NewtCanvasAWT(newtWindow);
      newtCanvas.setBounds(0, 0, applet.width, applet.height);
      newtCanvas.setBackground(new Color(0xFFCCCCCC, true));
      newtCanvas.setFocusable(true);

      applet.setLayout(new BorderLayout());
      applet.add(newtCanvas, BorderLayout.CENTER);

      if (MANUAL_FRAME_HANDLING) {
        newtCanvas.setIgnoreRepaint(true);
        newtWindow.setAutoSwapBufferMode(false);
      }
    }
  }
Пример #20
0
 public GLPbufferImpl(GLDrawableImpl pbufferDrawable, GLContext parentContext) {
   GLCapabilities caps =
       (GLCapabilities)
           pbufferDrawable
               .getNativeWindow()
               .getGraphicsConfiguration()
               .getNativeGraphicsConfiguration()
               .getChosenCapabilities();
   if (caps.isOnscreen()) {
     if (caps.isPBuffer()) {
       throw new IllegalArgumentException(
           "Error: Given drawable is Onscreen and Pbuffer: " + pbufferDrawable);
     }
     throw new IllegalArgumentException("Error: Given drawable is Onscreen: " + pbufferDrawable);
   } else {
     if (!caps.isPBuffer()) {
       throw new IllegalArgumentException(
           "Error: Given drawable is not Pbuffer: " + pbufferDrawable);
     }
   }
   this.pbufferDrawable = pbufferDrawable;
   context = (GLContextImpl) pbufferDrawable.createContext(parentContext);
   context.setSynchronized(true);
 }
Пример #21
0
  private void testMultiSampleAAImpl(
      final boolean useFBO, final boolean usePBuffer, final int reqSamples)
      throws InterruptedException {
    final GLReadBufferUtil screenshot = new GLReadBufferUtil(true, false);
    final GLProfile glp = GLProfile.getGL2ES2();
    final GLCapabilities caps = new GLCapabilities(glp);
    final GLCapabilitiesChooser chooser = new MultisampleChooser01();

    caps.setAlphaBits(1);
    caps.setFBO(useFBO);
    caps.setPBuffer(usePBuffer);

    if (reqSamples > 0) {
      caps.setSampleBuffers(true);
      caps.setNumSamples(reqSamples);
    }

    final GLWindow window = GLWindow.create(caps);
    window.setCapabilitiesChooser(chooser);
    window.addGLEventListener(new MultisampleDemoES2(reqSamples > 0 ? true : false));
    window.addGLEventListener(
        new GLEventListener() {
          int displayCount = 0;

          public void init(final GLAutoDrawable drawable) {}

          public void dispose(final GLAutoDrawable drawable) {}

          public void display(final GLAutoDrawable drawable) {
            snapshot(displayCount++, null, drawable.getGL(), screenshot, TextureIO.PNG, null);
          }

          public void reshape(
              final GLAutoDrawable drawable,
              final int x,
              final int y,
              final int width,
              final int height) {}
        });
    window.setSize(512, 512);
    window.setVisible(true);
    window.requestFocus();

    Thread.sleep(durationPerTest);

    window.destroy();
  }
Пример #22
0
  void doTest(
      final boolean onscreen, final GLEventListener demo, final GLProfile glp, final int msaaCount)
      throws IOException {
    final GLCapabilities caps = new GLCapabilities(glp);
    caps.setDoubleBuffered(onscreen);
    if (msaaCount > 0) {
      caps.setSampleBuffers(true);
      caps.setNumSamples(msaaCount);
    }

    final int maxTileSize = 256;
    final GLAutoDrawable glad;
    if (onscreen) {
      final GLWindow glWin = GLWindow.create(caps);
      glWin.setSize(maxTileSize, maxTileSize);
      glWin.setVisible(true);
      glad = glWin;
    } else {
      final GLDrawableFactory factory = GLDrawableFactory.getFactory(glp);
      glad = factory.createOffscreenAutoDrawable(null, caps, null, maxTileSize, maxTileSize);
    }

    glad.addGLEventListener(demo);

    // Fix the image size for now
    final int imageWidth = glad.getSurfaceWidth() * 6;
    final int imageHeight = glad.getSurfaceHeight() * 4;

    final String filename =
        this.getSnapshotFilename(
            0,
            "-tile",
            glad.getChosenGLCapabilities(),
            imageWidth,
            imageHeight,
            false,
            TextureIO.PNG,
            null);
    final File file = new File(filename);

    // Initialize the tile rendering library
    final TileRenderer renderer = new TileRenderer();
    renderer.setImageSize(imageWidth, imageHeight);
    renderer.setTileSize(glad.getSurfaceWidth(), glad.getSurfaceHeight(), 0);
    renderer.attachAutoDrawable(glad);

    final GLPixelBuffer.GLPixelBufferProvider pixelBufferProvider =
        GLPixelBuffer.defaultProviderWithRowStride;
    final boolean[] flipVertically = {false};

    final GLEventListener preTileGLEL =
        new GLEventListener() {
          @Override
          public void init(final GLAutoDrawable drawable) {
            final GL gl = drawable.getGL();
            final GLPixelAttributes pixelAttribs = pixelBufferProvider.getAttributes(gl, 3);
            final GLPixelBuffer pixelBuffer =
                pixelBufferProvider.allocate(gl, pixelAttribs, imageWidth, imageHeight, 1, true, 0);
            renderer.setImageBuffer(pixelBuffer);
            if (drawable.isGLOriented()) {
              flipVertically[0] = false;
            } else {
              flipVertically[0] = true;
            }
          }

          @Override
          public void dispose(final GLAutoDrawable drawable) {}

          @Override
          public void display(final GLAutoDrawable drawable) {}

          @Override
          public void reshape(
              final GLAutoDrawable drawable,
              final int x,
              final int y,
              final int width,
              final int height) {}
        };
    renderer.setGLEventListener(preTileGLEL, null);

    while (!renderer.eot()) {
      renderer.display();
    }

    renderer.detachAutoDrawable();

    // Restore viewport and Gear's PMV matrix
    // .. even though we close the demo, this is for documentation!
    glad.invoke(
        true,
        new GLRunnable() {
          @Override
          public boolean run(final GLAutoDrawable drawable) {
            drawable
                .getGL()
                .glViewport(0, 0, drawable.getSurfaceWidth(), drawable.getSurfaceHeight());
            demo.reshape(drawable, 0, 0, drawable.getSurfaceWidth(), drawable.getSurfaceHeight());
            return false;
          }
        });

    final GLPixelBuffer imageBuffer = renderer.getImageBuffer();
    final TextureData textureData =
        new TextureData(
            caps.getGLProfile(),
            0 /* internalFormat */,
            imageWidth,
            imageHeight,
            0,
            imageBuffer.pixelAttributes,
            false,
            false,
            flipVertically[0],
            imageBuffer.buffer,
            null /* Flusher */);

    TextureIO.write(textureData, file);

    glad.destroy();
  }
Пример #23
0
  public void testImpl(
      final int sceneMSAASamples, final int graphMSAASamples, final int graphVBAASamples)
      throws InterruptedException {
    GLProfile glp = GLProfile.get(GLProfile.GL2ES2);
    GLCapabilities caps = new GLCapabilities(glp);
    caps.setAlphaBits(4);
    if (0 < sceneMSAASamples) {
      caps.setSampleBuffers(true);
      caps.setNumSamples(sceneMSAASamples);
    }
    System.err.println(
        "Requested: "
            + caps
            + ", graph[msaaSamples "
            + graphMSAASamples
            + ", vbaaSamples "
            + graphVBAASamples
            + "]");

    GLWindow window =
        createWindow(
            "text-gvbaa"
                + graphVBAASamples
                + "-gmsaa"
                + graphMSAASamples
                + "-smsaa"
                + sceneMSAASamples,
            caps,
            1024,
            640);
    window.display();
    System.err.println("Chosen: " + window.getChosenGLCapabilities());
    if (WaitStartEnd) {
      UITestCase.waitForKey("Start");
    }

    final RenderState rs = RenderState.createRenderState(SVertex.factory());
    final int renderModes, sampleCount;
    if (graphVBAASamples > 0) {
      renderModes = Region.VBAA_RENDERING_BIT;
      sampleCount = graphVBAASamples;
    } else if (graphMSAASamples > 0) {
      renderModes = Region.MSAA_RENDERING_BIT;
      sampleCount = graphMSAASamples;
    } else {
      renderModes = 0;
      sampleCount = 0;
    }
    final TextRendererGLEL textGLListener = new TextRendererGLEL(rs, renderModes, sampleCount);
    System.err.println(textGLListener.getFontInfo());

    window.addGLEventListener(textGLListener);

    Animator anim = new Animator();
    anim.add(window);
    anim.start();
    anim.setUpdateFPSFrames(60, null);
    sleep();
    window.invoke(
        true,
        new GLRunnable() {
          @Override
          public boolean run(GLAutoDrawable drawable) {
            try {
              textGLListener.printScreen(
                  renderModes,
                  drawable,
                  "./",
                  "TestTextRendererNEWT00-snap" + screenshot_num,
                  false);
              screenshot_num++;
            } catch (Exception e) {
              e.printStackTrace();
            }
            return true;
          }
        });
    anim.stop();
    if (WaitStartEnd) {
      UITestCase.waitForKey("Stop");
    }
    destroyWindow(window);
  }
  @Test
  public void compileShader() throws InterruptedException {
    GLProfile glp = GLProfile.get(GLProfile.GL2GL3);
    GLCapabilities caps = new GLCapabilities(glp);
    // commenting out this line makes it work
    caps.setStencilBits(8);

    // commenting in this line also makes it work
    // caps.setSampleBuffers(true);

    final Frame frame = new Frame("Bug 459 shader compilation test");
    Assert.assertNotNull(frame);

    final GLCanvas glCanvas = new GLCanvas(caps);
    Assert.assertNotNull(glCanvas);
    frame.add(glCanvas);

    glCanvas.addGLEventListener(
        new GLEventListener() {
          /* @Override */
          public void init(GLAutoDrawable drawable) {
            String code = "void main(void){gl_Position = vec4(0,0,0,1);}";

            GL2GL3 gl = drawable.getGL().getGL2GL3();
            int id = gl.glCreateShader(GL2GL3.GL_VERTEX_SHADER);

            try {
              gl.glShaderSource(id, 1, new String[] {code}, (int[]) null, 0);
              gl.glCompileShader(id);

              int[] compiled = new int[1];
              gl.glGetShaderiv(id, GL2GL3.GL_COMPILE_STATUS, compiled, 0);
              if (compiled[0] == GL2GL3.GL_FALSE) {
                int[] logLength = new int[1];
                gl.glGetShaderiv(id, GL2GL3.GL_INFO_LOG_LENGTH, logLength, 0);

                byte[] log = new byte[logLength[0]];
                gl.glGetShaderInfoLog(id, logLength[0], (int[]) null, 0, log, 0);

                System.err.println("Error compiling the shader: " + new String(log));

                gl.glDeleteShader(id);
              } else {
                System.out.println("Shader compiled: id=" + id);
              }
            } catch (GLException e) {
              glexception = e;
            }
          }

          /* @Override */
          public void dispose(GLAutoDrawable drawable) {}

          /* @Override */
          public void display(GLAutoDrawable drawable) {}

          /* @Override */
          public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {}
        });

    Animator animator = new Animator(glCanvas);
    try {
      javax.swing.SwingUtilities.invokeAndWait(
          new Runnable() {
            public void run() {
              frame.setSize(512, 512);
              frame.setVisible(true);
            }
          });
    } catch (Exception ex) {
      throw new RuntimeException(ex);
    }
    animator.setUpdateFPSFrames(1, null);
    animator.start();

    while (animator.isAnimating() && animator.getTotalFPSDuration() < duration) {
      Thread.sleep(100);
    }

    Assert.assertTrue(glexception != null ? glexception.getMessage() : "", glexception == null);
    Assert.assertNotNull(frame);
    Assert.assertNotNull(glCanvas);
    Assert.assertNotNull(animator);

    animator.stop();
    Assert.assertEquals(false, animator.isAnimating());
    try {
      javax.swing.SwingUtilities.invokeAndWait(
          new Runnable() {
            public void run() {
              frame.setVisible(false);
              frame.remove(glCanvas);
              frame.dispose();
            }
          });
    } catch (Throwable throwable) {
      throwable.printStackTrace();
      Assume.assumeNoException(throwable);
    }
  }
  protected static X11GLXGraphicsConfiguration chooseGraphicsConfigurationXVisual(
      GLCapabilities capabilities, GLCapabilitiesChooser chooser, X11GraphicsScreen x11Screen) {
    if (chooser == null) {
      chooser = new DefaultGLCapabilitiesChooser();
    }

    // Until we have a rock-solid visual selection algorithm written
    // in pure Java, we're going to provide the underlying window
    // system's selection to the chooser as a hint

    GLProfile glProfile = capabilities.getGLProfile();
    boolean onscreen = capabilities.isOnscreen();
    GLCapabilities[] caps = null;
    int recommendedIndex = -1;
    XVisualInfo retXVisualInfo = null;
    int chosen = -1;

    AbstractGraphicsDevice absDevice = x11Screen.getDevice();
    long display = absDevice.getHandle();
    try {
      NativeWindowFactory.getDefaultFactory().getToolkitLock().lock();
      X11Lib.XLockDisplay(display);
      int screen = x11Screen.getIndex();
      boolean isMultisampleAvailable = GLXUtil.isMultisampleAvailable(display);
      int[] attribs =
          X11GLXGraphicsConfiguration.GLCapabilities2AttribList(
              capabilities, false, isMultisampleAvailable, display, screen);
      XVisualInfo[] infos = null;

      XVisualInfo recommendedVis = GLX.glXChooseVisualCopied(display, screen, attribs, 0);
      if (DEBUG) {
        System.err.print("!!! glXChooseVisual recommended ");
        if (recommendedVis == null) {
          System.err.println("null visual");
        } else {
          System.err.println("visual id 0x" + Long.toHexString(recommendedVis.getVisualid()));
        }
      }
      int[] count = new int[1];
      XVisualInfo template = XVisualInfo.create();
      template.setScreen(screen);
      infos = X11Lib.XGetVisualInfoCopied(display, X11Lib.VisualScreenMask, template, count, 0);
      if (infos == null || infos.length < 1) {
        throw new GLException("Error while enumerating available XVisualInfos");
      }
      caps = new GLCapabilities[infos.length];
      for (int i = 0; i < infos.length; i++) {
        caps[i] =
            X11GLXGraphicsConfiguration.XVisualInfo2GLCapabilities(
                glProfile, display, infos[i], onscreen, false, isMultisampleAvailable);
        // Attempt to find the visual chosen by glXChooseVisual
        if (recommendedVis != null && recommendedVis.getVisualid() == infos[i].getVisualid()) {
          recommendedIndex = i;
        }
      }
      try {
        chosen = chooser.chooseCapabilities(capabilities, caps, recommendedIndex);
      } catch (NativeWindowException e) {
        if (DEBUG) {
          e.printStackTrace();
        }
        chosen = -1;
      }
      if (chosen < 0) {
        // keep on going ..
        if (DEBUG) {
          System.err.println(
              "X11GLXGraphicsConfiguration.chooseGraphicsConfigurationXVisual Failed .. unable to choose config, using first");
        }
        chosen = 0; // default ..
      } else if (chosen >= caps.length) {
        throw new GLException(
            "GLCapabilitiesChooser specified invalid index (expected 0.."
                + (caps.length - 1)
                + ")");
      }
      if (infos[chosen] == null) {
        throw new GLException("GLCapabilitiesChooser chose an invalid visual");
      }
      retXVisualInfo = XVisualInfo.create(infos[chosen]);
    } finally {
      X11Lib.XUnlockDisplay(display);
      NativeWindowFactory.getDefaultFactory().getToolkitLock().unlock();
    }
    return new X11GLXGraphicsConfiguration(
        x11Screen, caps[chosen], capabilities, chooser, retXVisualInfo, 0, -1);
  }
  protected static X11GLXGraphicsConfiguration chooseGraphicsConfigurationFBConfig(
      GLCapabilities capabilities, GLCapabilitiesChooser chooser, X11GraphicsScreen x11Screen) {
    int recommendedIndex = -1;
    GLCapabilities[] caps = null;
    PointerBuffer fbcfgsL = null;
    int chosen = -1;
    int retFBID = -1;
    XVisualInfo retXVisualInfo = null;
    GLProfile glProfile = capabilities.getGLProfile();
    boolean onscreen = capabilities.isOnscreen();
    boolean usePBuffer = capabilities.isPBuffer();

    // Utilizing FBConfig
    //
    AbstractGraphicsDevice absDevice = x11Screen.getDevice();
    long display = absDevice.getHandle();
    try {
      NativeWindowFactory.getDefaultFactory().getToolkitLock().lock();
      X11Lib.XLockDisplay(display);
      int screen = x11Screen.getIndex();
      boolean isMultisampleAvailable = GLXUtil.isMultisampleAvailable(display);
      int[] attribs =
          X11GLXGraphicsConfiguration.GLCapabilities2AttribList(
              capabilities, true, isMultisampleAvailable, display, screen);
      int[] count = {-1};

      fbcfgsL = GLX.glXChooseFBConfigCopied(display, screen, attribs, 0, count, 0);
      if (fbcfgsL == null || fbcfgsL.limit() < 1) {
        if (DEBUG) {
          System.err.println(
              "X11GLXGraphicsConfiguration.chooseGraphicsConfigurationFBConfig: Failed glXChooseFBConfig ("
                  + x11Screen
                  + ","
                  + capabilities
                  + "): "
                  + fbcfgsL
                  + ", "
                  + count[0]);
        }
        return null;
      }
      if (!X11GLXGraphicsConfiguration.GLXFBConfigValid(display, fbcfgsL.get(0))) {
        if (DEBUG) {
          System.err.println(
              "X11GLXGraphicsConfiguration.chooseGraphicsConfigurationFBConfig: Failed - GLX FBConfig invalid: ("
                  + x11Screen
                  + ","
                  + capabilities
                  + "): "
                  + fbcfgsL
                  + ", fbcfg: 0x"
                  + Long.toHexString(fbcfgsL.get(0)));
        }
        return null;
      }
      recommendedIndex = 0; // 1st match is always recommended ..
      caps = new GLCapabilities[fbcfgsL.limit()];
      for (int i = 0; i < fbcfgsL.limit(); i++) {
        caps[i] =
            X11GLXGraphicsConfiguration.GLXFBConfig2GLCapabilities(
                glProfile,
                display,
                fbcfgsL.get(i),
                false,
                onscreen,
                usePBuffer,
                isMultisampleAvailable);
      }

      if (null == chooser) {
        chosen = recommendedIndex;
      } else {
        try {
          chosen = chooser.chooseCapabilities(capabilities, caps, recommendedIndex);
        } catch (NativeWindowException e) {
          if (DEBUG) {
            e.printStackTrace();
          }
          chosen = -1;
        }
      }
      if (chosen < 0) {
        // keep on going ..
        if (DEBUG) {
          System.err.println(
              "X11GLXGraphicsConfiguration.chooseGraphicsConfigurationFBConfig Failed .. unable to choose config, using first");
        }
        chosen = 0; // default ..
      } else if (chosen >= caps.length) {
        throw new GLException(
            "GLCapabilitiesChooser specified invalid index (expected 0.."
                + (caps.length - 1)
                + ")");
      }

      retFBID = X11GLXGraphicsConfiguration.glXFBConfig2FBConfigID(display, fbcfgsL.get(chosen));

      retXVisualInfo = GLX.glXGetVisualFromFBConfigCopied(display, fbcfgsL.get(chosen));
      if (retXVisualInfo == null) {
        if (DEBUG) {
          System.err.println(
              "X11GLXGraphicsConfiguration.chooseGraphicsConfigurationFBConfig: Failed glXGetVisualFromFBConfig ("
                  + x11Screen
                  + ", "
                  + fbcfgsL.get(chosen)
                  + " (Continue: "
                  + (false == caps[chosen].isOnscreen())
                  + "):\n\t"
                  + caps[chosen]);
        }
        if (caps[chosen].isOnscreen()) {
          // Onscreen drawables shall have a XVisual ..
          return null;
        }
      }
    } finally {
      X11Lib.XUnlockDisplay(display);
      NativeWindowFactory.getDefaultFactory().getToolkitLock().unlock();
    }

    return new X11GLXGraphicsConfiguration(
        x11Screen,
        caps[chosen],
        capabilities,
        chooser,
        retXVisualInfo,
        fbcfgsL.get(chosen),
        retFBID);
  }
Пример #27
0
  /**
   * Creates and initializes an appropriate OpenGl Context (NS). Should only be called by {@link
   * makeCurrentImpl()}.
   */
  protected boolean create(boolean pbuffer, boolean floatingPoint) {
    MacOSXCGLContext other = (MacOSXCGLContext) GLContextShareSet.getShareContext(this);
    long share = 0;
    if (other != null) {
      if (!other.isNSContext()) {
        throw new GLException("GLContextShareSet is not a NS Context");
      }
      share = other.getHandle();
      if (share == 0) {
        throw new GLException("GLContextShareSet returned a NULL OpenGL context");
      }
    }
    MacOSXCGLGraphicsConfiguration config =
        (MacOSXCGLGraphicsConfiguration)
            drawable.getNativeSurface().getGraphicsConfiguration().getNativeGraphicsConfiguration();
    GLCapabilitiesImmutable capabilitiesRequested =
        (GLCapabilitiesImmutable) config.getRequestedCapabilities();
    GLProfile glProfile = capabilitiesRequested.getGLProfile();
    if (glProfile.isGL3()) {
      throw new GLException(
          "GL3 profile currently not supported on MacOSX, due to the lack of a OpenGL 3.1 implementation");
    }
    // HACK .. bring in OnScreen/PBuffer selection to the DrawableFactory !!
    GLCapabilities capabilities = (GLCapabilities) capabilitiesRequested.cloneMutable();
    capabilities.setPBuffer(pbuffer);
    capabilities.setPbufferFloatingPointBuffers(floatingPoint);

    long pixelFormat = MacOSXCGLGraphicsConfiguration.GLCapabilities2NSPixelFormat(capabilities);
    if (pixelFormat == 0) {
      throw new GLException("Unable to allocate pixel format with requested GLCapabilities");
    }
    config.setChosenPixelFormat(pixelFormat);
    try {
      int[] viewNotReady = new int[1];
      // Try to allocate a context with this
      contextHandle = CGL.createContext(share, drawable.getHandle(), pixelFormat, viewNotReady, 0);
      if (contextHandle == 0) {
        if (viewNotReady[0] == 1) {
          if (DEBUG) {
            System.err.println("!!! View not ready for " + getClass().getName());
          }
          // View not ready at the window system level -- this is OK
          return false;
        }
        throw new GLException("Error creating NSOpenGLContext with requested pixel format");
      }

      if (!pbuffer && !capabilities.isBackgroundOpaque()) {
        // Set the context opacity
        CGL.setContextOpacity(contextHandle, 0);
      }

      GLCapabilitiesImmutable caps =
          MacOSXCGLGraphicsConfiguration.NSPixelFormat2GLCapabilities(glProfile, pixelFormat);
      config.setChosenCapabilities(caps);
    } finally {
      CGL.deletePixelFormat(pixelFormat);
    }
    if (!CGL.makeCurrentContext(contextHandle)) {
      throw new GLException("Error making Context (NS) current");
    }
    isNSContext = true;
    setGLFunctionAvailability(true, 0, 0, CTX_PROFILE_COMPAT | CTX_OPTION_ANY);
    GLContextShareSet.contextCreated(this);
    return true;
  }
Пример #28
0
  private boolean mapAvailableEGLESConfig(
      AbstractGraphicsDevice adevice,
      int esProfile,
      boolean[] hasPBuffer,
      GLRendererQuirks[] rendererQuirks,
      int[] ctp) {
    final String profileString;
    switch (esProfile) {
      case 3:
        profileString = GLProfile.GLES3;
        break;
      case 2:
        profileString = GLProfile.GLES2;
        break;
      case 1:
        profileString = GLProfile.GLES1;
        break;
      default:
        throw new GLException("Invalid ES profile number " + esProfile);
    }
    if (!GLProfile.isAvailable(adevice, profileString)) {
      if (DEBUG) {
        System.err.println(
            "EGLDrawableFactory.mapAvailableEGLESConfig: " + profileString + " n/a on " + adevice);
      }
      return false;
    }
    final GLProfile glp = GLProfile.get(adevice, profileString);
    final GLDrawableFactoryImpl desktopFactory =
        (GLDrawableFactoryImpl) GLDrawableFactory.getDesktopFactory();
    final boolean mapsADeviceToDefaultDevice =
        !QUERY_EGL_ES_NATIVE_TK || null == desktopFactory || adevice instanceof EGLGraphicsDevice;
    if (DEBUG) {
      System.err.println(
          "EGLDrawableFactory.mapAvailableEGLESConfig: "
              + profileString
              + " ( "
              + esProfile
              + " ), "
              + "defaultSharedResourceSet "
              + (null != defaultSharedResource)
              + ", mapsADeviceToDefaultDevice "
              + mapsADeviceToDefaultDevice
              + " (QUERY_EGL_ES_NATIVE_TK "
              + QUERY_EGL_ES_NATIVE_TK
              + ", hasDesktopFactory "
              + (null != desktopFactory)
              + ", isEGLGraphicsDevice "
              + (adevice instanceof EGLGraphicsDevice)
              + ")");
    }

    EGLGraphicsDevice eglDevice = null;
    NativeSurface surface = null;
    ProxySurface upstreamSurface = null; // X11, GLX, ..
    boolean success = false;
    boolean deviceFromUpstreamSurface = false;
    try {
      final GLCapabilities reqCapsAny = new GLCapabilities(glp);
      reqCapsAny.setRedBits(5);
      reqCapsAny.setGreenBits(5);
      reqCapsAny.setBlueBits(5);
      reqCapsAny.setAlphaBits(0);
      reqCapsAny.setDoubleBuffered(false);

      if (mapsADeviceToDefaultDevice) {
        // In this branch, any non EGL device is mapped to EGL default shared resources (default
        // behavior).
        // Only one default shared resource instance is ever be created.
        final GLCapabilitiesImmutable reqCapsPBuffer =
            GLGraphicsConfigurationUtil.fixGLPBufferGLCapabilities(reqCapsAny);
        final List<GLCapabilitiesImmutable> availablePBufferCapsL =
            getAvailableEGLConfigs(defaultDevice, reqCapsPBuffer);
        hasPBuffer[0] = availablePBufferCapsL.size() > 0;

        // 1st case: adevice is not the EGL default device, map default shared resources
        if (adevice != defaultDevice) {
          if (null == defaultSharedResource) {
            return false;
          }
          switch (esProfile) {
            case 3:
              if (!defaultSharedResource.wasES3ContextCreated) {
                return false;
              }
              rendererQuirks[0] = defaultSharedResource.rendererQuirksES3ES2;
              ctp[0] = defaultSharedResource.ctpES3ES2;
              break;
            case 2:
              if (!defaultSharedResource.wasES2ContextCreated) {
                return false;
              }
              rendererQuirks[0] = defaultSharedResource.rendererQuirksES3ES2;
              ctp[0] = defaultSharedResource.ctpES3ES2;
              break;
            case 1:
              if (!defaultSharedResource.wasES1ContextCreated) {
                return false;
              }
              rendererQuirks[0] = defaultSharedResource.rendererQuirksES1;
              ctp[0] = defaultSharedResource.ctpES1;
              break;
          }
          EGLContext.mapStaticGLVersion(adevice, esProfile, 0, ctp[0]);
          return true;
        }

        // attempt to created the default shared resources ..

        eglDevice = defaultDevice; // reuse

        if (hasPBuffer[0]) {
          // 2nd case create defaultDevice shared resource using pbuffer surface
          surface =
              createDummySurfaceImpl(
                  eglDevice,
                  false,
                  reqCapsPBuffer,
                  reqCapsPBuffer,
                  null,
                  64,
                  64); // egl pbuffer offscreen
          upstreamSurface = (ProxySurface) surface;
          upstreamSurface.createNotify();
          deviceFromUpstreamSurface = false;
        } else {
          // 3rd case fake creation of defaultDevice shared resource, no pbuffer available
          final List<GLCapabilitiesImmutable> capsAnyL =
              getAvailableEGLConfigs(eglDevice, reqCapsAny);
          if (capsAnyL.size() > 0) {
            final GLCapabilitiesImmutable chosenCaps = capsAnyL.get(0);
            EGLContext.mapStaticGLESVersion(eglDevice, chosenCaps);
            success = true;
          }
          if (DEBUG) {
            System.err.println(
                "EGLDrawableFactory.mapAvailableEGLESConfig() no pbuffer config available, detected !pbuffer config: "
                    + success);
            EGLGraphicsConfigurationFactory.printCaps("!PBufferCaps", capsAnyL, System.err);
          }
        }
      } else {
        // 4th case always creates a true mapping of given device to EGL
        surface =
            desktopFactory.createDummySurface(
                adevice, reqCapsAny, null, 64, 64); // X11, WGL, .. dummy window
        upstreamSurface = (surface instanceof ProxySurface) ? (ProxySurface) surface : null;
        if (null != upstreamSurface) {
          upstreamSurface.createNotify();
        }
        eglDevice = EGLDisplayUtil.eglCreateEGLGraphicsDevice(surface);
        deviceFromUpstreamSurface = true;
        hasPBuffer[0] = true;
      }

      if (null != surface) {
        final EGLDrawable drawable =
            (EGLDrawable)
                createOnscreenDrawableImpl(
                    surface); // works w/ implicit pbuffer surface via proxy-hook
        drawable.setRealized(true);
        final EGLContext context = (EGLContext) drawable.createContext(null);
        if (null != context) {
          try {
            context.makeCurrent(); // could cause exception
            if (context.isCurrent()) {
              final String glVersion = context.getGL().glGetString(GL.GL_VERSION);
              if (null != glVersion) {
                context.mapCurrentAvailableGLVersion(eglDevice);
                if (eglDevice != adevice) {
                  context.mapCurrentAvailableGLVersion(adevice);
                }
                rendererQuirks[0] = context.getRendererQuirks();
                ctp[0] = context.getContextOptions();
                success = true;
              } else {
                // Oops .. something is wrong
                if (DEBUG) {
                  System.err.println(
                      "EGLDrawableFactory.mapAvailableEGLESConfig: "
                          + eglDevice
                          + ", "
                          + context.getGLVersion()
                          + " - VERSION is null, dropping availability!");
                }
              }
            }
          } catch (GLException gle) {
            if (DEBUG) {
              System.err.println(
                  "EGLDrawableFactory.mapAvailableEGLESConfig: INFO: context create/makeCurrent failed");
              gle.printStackTrace();
            }
          } finally {
            context.destroy();
          }
        }
        drawable.setRealized(false);
      }
    } catch (Throwable t) {
      if (DEBUG) {
        System.err.println("Catched Exception on thread " + getThreadName());
        t.printStackTrace();
      }
      success = false;
    } finally {
      if (eglDevice == defaultDevice) {
        if (null != upstreamSurface) {
          upstreamSurface.destroyNotify();
        }
      } else if (deviceFromUpstreamSurface) {
        if (null != eglDevice) {
          eglDevice.close();
        }
        if (null != upstreamSurface) {
          upstreamSurface.destroyNotify();
        }
      } else {
        if (null != upstreamSurface) {
          upstreamSurface.destroyNotify();
        }
        if (null != eglDevice) {
          eglDevice.close();
        }
      }
    }
    return success;
  }
  public void testImpl(boolean useFFP, final InputStream istream)
      throws InterruptedException, IOException {
    final GLReadBufferUtil screenshot = new GLReadBufferUtil(true, false);
    GLProfile glp;
    if (useFFP && GLProfile.isAvailable(GLProfile.GL2)) {
      glp = GLProfile.getMaxFixedFunc(true);
    } else if (!useFFP && GLProfile.isAvailable(GLProfile.GL2ES2)) {
      glp = GLProfile.getGL2ES2();
    } else {
      System.err.println(getSimpleTestName(".") + ": GLProfile n/a, useFFP: " + useFFP);
      return;
    }
    final GLCapabilities caps = new GLCapabilities(glp);
    caps.setAlphaBits(1);

    final TextureData texData =
        TextureIO.newTextureData(glp, istream, false /* mipmap */, TextureIO.TGA);
    System.err.println("TextureData: " + texData);

    final GLWindow glad = GLWindow.create(caps);
    glad.setTitle("TestTGATextureGL2FromFileNEWT");
    // Size OpenGL to Video Surface
    glad.setSize(texData.getWidth(), texData.getHeight());

    // load texture from file inside current GL context to match the way
    // the bug submitter was doing it
    final GLEventListener gle =
        useFFP ? new TextureDraw01GL2Listener(texData) : new TextureDraw01ES2Listener(texData, 0);
    glad.addGLEventListener(gle);
    glad.addGLEventListener(
        new GLEventListener() {
          boolean shot = false;

          @Override
          public void init(GLAutoDrawable drawable) {}

          public void display(GLAutoDrawable drawable) {
            // 1 snapshot
            if (null != ((TextureDraw01Accessor) gle).getTexture() && !shot) {
              shot = true;
              snapshot(0, null, drawable.getGL(), screenshot, TextureIO.PNG, null);
            }
          }

          @Override
          public void dispose(GLAutoDrawable drawable) {}

          @Override
          public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {}
        });

    Animator animator = new Animator(glad);
    animator.setUpdateFPSFrames(60, showFPS ? System.err : null);
    QuitAdapter quitAdapter = new QuitAdapter();
    glad.addKeyListener(quitAdapter);
    glad.addWindowListener(quitAdapter);
    glad.setVisible(true);
    animator.start();

    while (!quitAdapter.shouldQuit()
        && animator.isAnimating()
        && animator.getTotalFPSDuration() < duration) {
      Thread.sleep(100);
    }

    animator.stop();
    glad.destroy();
  }
Пример #30
0
  public static void main(String _args[]) {

    final NBodyKernel kernel =
        new NBodyKernel(Range.create(Integer.getInteger("bodies", 8192), 256));

    final JFrame frame = new JFrame("NBody");

    final JPanel panel = new JPanel(new BorderLayout());
    final JPanel controlPanel = new JPanel(new FlowLayout());
    panel.add(controlPanel, BorderLayout.SOUTH);

    final JButton startButton = new JButton("Start");

    startButton.addActionListener(
        new ActionListener() {
          @Override
          public void actionPerformed(ActionEvent e) {
            running = true;
            startButton.setEnabled(false);
          }
        });
    controlPanel.add(startButton);
    controlPanel.add(new JLabel(kernel.getExecutionMode().toString()));

    controlPanel.add(new JLabel("   Particles"));
    controlPanel.add(new JTextField("" + kernel.range.getGlobalSize(0), 5));

    controlPanel.add(new JLabel("FPS"));
    final JTextField framesPerSecondTextField = new JTextField("0", 5);

    controlPanel.add(framesPerSecondTextField);
    controlPanel.add(new JLabel("Score("));
    final JLabel miniLabel =
        new JLabel("<html><small>calcs</small><hr/><small>&micro;sec</small></html>");

    controlPanel.add(miniLabel);
    controlPanel.add(new JLabel(")"));

    final JTextField positionUpdatesPerMicroSecondTextField = new JTextField("0", 5);

    controlPanel.add(positionUpdatesPerMicroSecondTextField);
    final GLCapabilities caps = new GLCapabilities(null);
    caps.setDoubleBuffered(true);
    caps.setHardwareAccelerated(true);
    final GLCanvas canvas = new GLCanvas(caps);
    final Dimension dimension =
        new Dimension(Integer.getInteger("width", 742), Integer.getInteger("height", 742));
    canvas.setPreferredSize(dimension);

    canvas.addGLEventListener(
        new GLEventListener() {
          private double ratio;

          private final float xeye = 0f;

          private final float yeye = 0f;

          private final float zeye = 100f;

          private final float xat = 0f;

          private final float yat = 0f;

          private final float zat = 0f;

          public final float zoomFactor = 1.0f;

          private int frames;

          private long last = System.currentTimeMillis();

          @Override
          public void dispose(GLAutoDrawable drawable) {}

          @Override
          public void display(GLAutoDrawable drawable) {

            final GL2 gl = drawable.getGL().getGL2();

            gl.glLoadIdentity();
            gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
            gl.glColor3f(1f, 1f, 1f);

            final GLU glu = new GLU();
            glu.gluPerspective(45f, ratio, 0f, 1000f);

            glu.gluLookAt(xeye, yeye, zeye * zoomFactor, xat, yat, zat, 0f, 1f, 0f);
            if (running) {
              kernel.execute(kernel.range);
              if (kernel.isExplicit()) {
                kernel.get(kernel.xyz);
              }
              final List<ProfileInfo> profileInfo = kernel.getProfileInfo();
              if ((profileInfo != null) && (profileInfo.size() > 0)) {
                for (final ProfileInfo p : profileInfo) {
                  System.out.print(
                      " "
                          + p.getType()
                          + " "
                          + p.getLabel()
                          + ((p.getEnd() - p.getStart()) / 1000)
                          + "us");
                }
                System.out.println();
              }
            }
            kernel.render(gl);

            final long now = System.currentTimeMillis();
            final long time = now - last;
            frames++;

            if (time > 1000) { // We update the frames/sec every second
              if (running) {
                final float framesPerSecond = (frames * 1000.0f) / time;
                final int updatesPerMicroSecond =
                    (int)
                        ((framesPerSecond
                                * kernel.range.getGlobalSize(0)
                                * kernel.range.getGlobalSize(0))
                            / 1000000);
                framesPerSecondTextField.setText(String.format("%5.2f", framesPerSecond));
                positionUpdatesPerMicroSecondTextField.setText(
                    String.format("%4d", updatesPerMicroSecond));
              }
              frames = 0;
              last = now;
            }
            gl.glFlush();
          }

          @Override
          public void init(GLAutoDrawable drawable) {
            final GL2 gl = drawable.getGL().getGL2();

            gl.glShadeModel(GLLightingFunc.GL_SMOOTH);
            gl.glEnable(GL.GL_BLEND);
            gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE);
            try {
              final InputStream textureStream = Local.class.getResourceAsStream("particle.jpg");
              final Texture texture = TextureIO.newTexture(textureStream, false, null);
              texture.enable(gl);
            } catch (final IOException e) {
              e.printStackTrace();
            } catch (final GLException e) {
              e.printStackTrace();
            }
          }

          @Override
          public void reshape(GLAutoDrawable drawable, int x, int y, int _width, int _height) {
            width = _width;
            height = _height;

            final GL2 gl = drawable.getGL().getGL2();
            gl.glViewport(0, 0, width, height);

            ratio = (double) width / (double) height;
          }
        });

    panel.add(canvas, BorderLayout.CENTER);
    frame.getContentPane().add(panel, BorderLayout.CENTER);

    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);

    final FPSAnimator animator = new FPSAnimator(canvas, 100);
    animator.start();
  }