1

我正在尝试编写一个 java opengl (JOGL) 方法,该方法写入屏幕外可绘制对象,然后将其写入图像。我已经验证了这在使用屏幕上可绘制对象和 GLP 缓冲区时有效,但当前状态下的输出图像只是纯黑色。代码如下。

GLProfile glp = GLProfile.getDefault();
GLCapabilities caps = new GLCapabilities(glp);
caps.setOnscreen(false);

// create the offscreen drawable
GLDrawableFactory factory = GLDrawableFactory.getFactory(glp);
GLOffscreenAutoDrawable drawable = factory.createOffscreenAutoDrawable(null,caps,null,width,height);
drawable.display();
drawable.getContext().makeCurrent();

// a series of x/y coordinates
FloatBuffer buffer = generateData();

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

// use pixel coordinates
gl.glMatrixMode(GLMatrixFunc.GL_PROJECTION);
gl.glLoadIdentity();    
gl.glOrtho(0d, width, height, 0d, -1d, 1d);

// draw some points to the drawable
gl.glPointSize(4f);
gl.glColor3f(1f,0f,0f);    
gl.glEnableClientState(GL2.GL_VERTEX_ARRAY);
gl.glVertexPointer(2, GL2.GL_FLOAT, 0, buffer);
gl.glDrawArrays(GL2.GL_POINTS, 0, numPoints);

BufferedImage im = new AWTGLReadBufferUtil(drawable.getGLProfile(), false).readPixelsToBufferedImage(drawable.getGL(), 0, 0, width, height, true /* awtOrientation */);
ImageIO.write(im,"png",new File("im.png"));
4

2 回答 2

1

这有点老了,但我找到了一个似乎对我有用的问题的解决方案。GLEventListener我只是在调用drawable之前添加了一个普通对象.display(),如下所示:

//...
drawable.addGLEventListener(new OffscreenJOGL());
drawable.display();

//Move drawing code to OffscreenJOGL

BufferedImage im = new AWTGLReadBufferUtil(drawable.getGLProfile(), false).readPixelsToBufferedImage(drawable.getGL(), 0, 0, width, height, true /* awtOrientation */);
ImageIO.write(im,"png",new File("im.png"));

现在要绘制的代码应该在您的自定义OffscreenJOGL类中,在init(...),reshape(...)display(...)方法下。注意,设置当前上下文必须init(...)OffscreenJOGL. 否则我会抛出异常。

class OffscreenJOGL implements GLEventListener {
    public void init(GLAutoDrawable drawable) {
        drawable.getContext().makeCurrent();
        //Other init code here
    }

    public void display(GLAutodrawable drawable) {
        //Code for drawing here
    }

    public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {
        //Called at least once after init(...) and before display(...)
    }

    public void dispose(GLAutoDrawable drawable) {
        //Dispose code here
    }
}
于 2015-05-14T09:09:27.850 回答
0

您很可能已经找到查询所需的答案。
如果没有,我建议添加一行,例如:

gl.glClearColor(GLfloat red, GLfloat green, GLfloat blue, GLfloat alpha) 

我已经对其进行了测试,并且可以正常工作。

于 2020-01-21T15:49:30.503 回答