2013-11-25 82 views
1

我使用JOGL與OpenGL一起工作,我無法獲得像素顏色。方法glReadPixels()總是返回一個全零的數組。glReadPixels()返回零數組

這就是我如何使用它:

private static GL2 gl; 

static Color getPixel(final int x, final int y) { 
    ByteBuffer buffer = ByteBuffer.allocate(4); 
    gl.glReadBuffer(GL.GL_FRONT); 
    gl.glReadPixels(x, y, 1, 1, GL2.GL_RGB, GL2.GL_UNSIGNED_BYTE, buffer); 
    byte[] rgb = buffer.array(); 

    return new Color(rgb[0], rgb[1], rgb[2]); 
} 

在重繪(在display()法)我填滿窗口爲灰色,然後測試結果,當用戶單擊窗口中的任意:

@Override 
public void mouseClicked(MouseEvent e) { 
    // On mouse click.. 
    for (int j = 0; j < this.getWidth(); ++j) 
     for (int i = 0; i < this.getHeight(); ++i) { 
      // ..I iterate through all pixels.. 
      Color pxl = Algorithm.getPixel(j, i); //! pxl should be GRAY, but it is BLACK (0,0,0) 
      if (pxl.getRGB() != Color.BLACK.getRGB()) 
       // ..and print to console only if a point color differs from BLACK 
       System.out.println("r:" + pxl.getRed() + " g:" + pxl.getGreen() + " b:" + pxl.getBlue()); 
     } 
} 

但是在控制檯中沒有輸出。我已經在離散和集成的圖形上進行了測試。結果是一樣的。

告訴我我做錯了什麼。或者分享一個工作的例子,如果你有任何使用JOGL和方法glReadPixel()的程序僥倖。

+1

-1,歸結代碼以一個[SSCCE](http://sscce.org/)並對其進行編輯進入問題。隨機Dropboxes死亡,SO永遠。 – genpfault

+0

@genpfault,我將代碼縮短到SSCCE後發現問題的根源。我應該重新上傳代碼並將其替換爲正在運行的項目嗎? – naXa

+0

太棒了!這是SSCCE真棒的原因之一:)你應該在錯誤的SSCCE中編輯問題,然後將修正的SSCCE編輯到你的答案中。 – genpfault

回答

0

問題是我打電話getPixel()mouseClicked()(即從另一個線程)。 OpenGL上下文一次只能在單個線程中處於活動狀態。解決方案討論here

例如,它是更正確的使用OpenGL上下文在該方法中:

/** 
* Called back by the animator to perform per-frame rendering. 
*/ 
@Override 
public void display(GLAutoDrawable glAutoDrawable) { 
    GL2 gl = glAutoDrawable.getGL().getGL2(); // get the OpenGL 2 graphics context 

    gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT); // clear background 
    gl.glLoadIdentity();     // reset the model-view matrix 

    // Rendering code 
    /* There you can fill the whole window with a color, 
     or draw something more beautiful... */ 

    gl.glFlush(); 

    /* Here goes testing cycle from mouseClicked(); and it works! */ 
}