While trying to set up a minimal reproducable example using LWJGL because my original question was closed, I ran into a problem I didn't have originally (Originally it was just not displaying), which is that the JVM now crashes with an EXCEPTION_ACCESS_VIOLATION error during the glDrawArrays() call.
I don't know what could be causing this, but I've tried for example initializing the vertex attribute pointers each frame. There is also no debug information or errors logged, while I did set up an error callback and I think a debug message callback.
All of the code:
import org.lwjgl.glfw.GLFW;
import org.lwjgl.glfw.GLFWErrorCallback;
import org.lwjgl.opengl.GL;
import org.lwjgl.opengl.GL30;
import org.lwjgl.opengl.GLUtil;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
public class MinimalExample {
private static String readResource(String res) {
try {
InputStream is = MinimalExample.class.getResourceAsStream(res);
String s = new String(is.readAllBytes(), StandardCharsets.UTF_8);
is.close();
return s;
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
// vertex data buffer
private static final ByteBuffer buf = ByteBuffer.allocateDirect(4096);
// shader program
static int program;
// render objects
static int vao;
static int vbo;
public static void main(String[] args) {
// set buffer limit
buf.limit(4096);
// init glfw and create window
GLFW.glfwInit();
long window = GLFW.glfwCreateWindow(500, 500, "Hello", 0, 0);
// create GL
GLFW.glfwMakeContextCurrent(window);
GL.createCapabilities();
GLUtil.setupDebugMessageCallback(System.out);
GLFW.glfwSetErrorCallback(GLFWErrorCallback.createPrint(System.out));
// create vertex objects
vao = GL30.glGenVertexArrays();
vbo = GL30.glGenBuffers();
GL30.glBindVertexArray(vao);
GL30.glVertexAttribPointer(0, 3, GL30.GL_FLOAT, false, 7 * 4, 0);
GL30.glVertexAttribPointer(1, 4, GL30.GL_FLOAT, false, 7 * 4, 0);
GL30.glEnableVertexAttribArray(0);
GL30.glEnableVertexAttribArray(1);
GL30.glBindVertexArray(0);
// compile and link shaders
int vertexShader = GL30.glCreateShader(GL30.GL_VERTEX_SHADER);
int fragmentShader = GL30.glCreateShader(GL30.GL_FRAGMENT_SHADER);
GL30.glShaderSource(vertexShader, readResource("/test.vsh"));
GL30.glShaderSource(fragmentShader, readResource("/test.fsh"));
GL30.glCompileShader(vertexShader);
GL30.glCompileShader(fragmentShader);
program = GL30.glCreateProgram();
GL30.glAttachShader(program, vertexShader);
GL30.glAttachShader(program, fragmentShader);
GL30.glLinkProgram(program);
// render loop
while (!GLFW.glfwWindowShouldClose(window)) {
// poll events
GLFW.glfwPollEvents();
// clear screen
GL30.glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
GL30.glClear(GL30.GL_COLOR_BUFFER_BIT);
// render
render();
// swap buffers
GLFW.glfwSwapBuffers(window);
}
}
static void render() {
// put vertex data
// manual to simulate graphics library
putVec3(0.25f, 0.25f, 1f); putVec4(1.0f, 0.0f, 0.0f, 1.0f);
putVec3(0.75f, 0.25f, 1f); putVec4(0.0f, 1.0f, 0.0f, 1.0f);
putVec3(0.50f, 0.75f, 1f); putVec4(0.0f, 0.0f, 1.0f, 1.0f);
// bind program
GL30.glUseProgram(program);
// bind vertex array
GL30.glBindVertexArray(vao);
GL30.glEnableVertexAttribArray(0);
GL30.glEnableVertexAttribArray(1);
// upload graphics data and draw
GL30.glBindBuffer(GL30.GL_ARRAY_BUFFER, vbo);
GL30.glBufferData(GL30.GL_ARRAY_BUFFER, buf, GL30.GL_STATIC_DRAW);
GL30.glDrawArrays(GL30.GL_TRIANGLES, 0, 3);
GL30.glBindBuffer(GL30.GL_ARRAY_BUFFER, 0);
GL30.glBindVertexArray(0);
// reset vertex data buffer
buf.position(0);
}
//////////////////////////////////////////
static void putVec3(float x, float y, float z) {
buf.putFloat(x).putFloat(y).putFloat(z);
}
static void putVec4(float x, float y, float z, float w) {
buf.putFloat(x).putFloat(y).putFloat(z).putFloat(z);
}
}
The full JVM error log (hs_err_pidX.log): pastes.dev
For context, I'm running this with JDK 17 from IntelliJ directly. Here is the build.gradle file if you want to check the dependencies: build.gradle (GitHub)
Related
I have managed to open a window and render a triangle on the screen in LWJGL. I have now created two external files for the vertex shader & fragment shader. However the triangle remains white.
This is the main file, where it calls the method to load the vertex shader and compile it, I have added a simple system.out line to see if this is being called, which it is.
import org.lwjgl.*;
import org.lwjgl.glfw.*;
import org.lwjgl.opengl.*;
import org.lwjgl.system.*;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.*;
import static org.lwjgl.glfw.Callbacks.*;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.system.MemoryStack.*;
import static org.lwjgl.system.MemoryUtil.*;
public class Main {
String TITLE = "f";
// The window handle
private long window;
public void run() {
System.out.println("Hello LWJGL " + Version.getVersion() + "!");
init();
loop();
// Free the window callbacks and destroy the window
glfwFreeCallbacks(window);
glfwDestroyWindow(window);
// Terminate GLFW and free the error callback
glfwTerminate();
glfwSetErrorCallback(null).free();
}
private void init() {
// Setup an error callback. The default implementation
// will print the error message in System.err.
GLFWErrorCallback.createPrint(System.err).set();
// Initialize GLFW. Most GLFW functions will not work before doing this.
if ( !glfwInit() )
throw new IllegalStateException("Unable to initialize GLFW");
// Configure GLFW
glfwDefaultWindowHints(); // optional, the current window hints are already the default
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); // the window will stay hidden after creation
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE); // the window will be resizable
// Create the window
window = glfwCreateWindow(300, 300, TITLE, NULL, NULL);
if ( window == NULL )
throw new RuntimeException("Failed to create the GLFW window");
// Setup a key callback. It will be called every time a key is pressed, repeated or released.
glfwSetKeyCallback(window, (window, key, scancode, action, mods) -> {
if ( key == GLFW_KEY_ESCAPE && action == GLFW_RELEASE )
glfwSetWindowShouldClose(window, true); // We will detect this in the rendering loop
});
// Get the thread stack and push a new frame
try ( MemoryStack stack = stackPush() ) {
IntBuffer pWidth = stack.mallocInt(1); // int*
IntBuffer pHeight = stack.mallocInt(1); // int*
// Get the window size passed to glfwCreateWindow
glfwGetWindowSize(window, pWidth, pHeight);
// Get the resolution of the primary monitor
GLFWVidMode vidmode = glfwGetVideoMode(glfwGetPrimaryMonitor());
// Center the window
glfwSetWindowPos(
window,
(vidmode.width() - pWidth.get(0)) / 2,
(vidmode.height() - pHeight.get(0)) / 2
);
} // the stack frame is popped automatically
// Make the OpenGL context current
glfwMakeContextCurrent(window);
// Enable v-sync
glfwSwapInterval(1);
// Make the window visible
glfwShowWindow(window);
}
private void loop() {
// This line is critical for LWJGL's interoperation with GLFW's
// OpenGL context, or any context that is managed externally.
// LWJGL detects the context that is current in the current thread,
// creates the GLCapabilities instance and makes the OpenGL
// bindings available for use.
GL.createCapabilities();
drawTriangle();
loadShader("screenvertfilelocation", GL30.GL_VERTEX_SHADER);
loadShader("screenvertfilelocation", GL30.GL_FRAGMENT_SHADER);
// Set the clear color
glClearColor(1.0f, 0.0f, 0.0f, 0.0f);
// Run the rendering loop until the user has attempted to close
// the window or has pressed the ESCAPE key.
while ( !glfwWindowShouldClose(window) ) {
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear the framebuffer
processTriangle();
glfwSwapBuffers(window); // swap the color buffers
// Poll for window events. The key callback above will only be
// invoked during this call.
glfwPollEvents();
}
}
public static void main(String[] args) {
new Main().run();
}
int vertexCount = 0;
int VAO = 0;
int VBO = 0;
public void drawTriangle() {
float vertices[] = {
-0.5f, -0.5f, 0.0f,
0.5f, -0.5f, 0.0f,
0.0f, 0.5f, 0.0f
};
int VBO = GL30.glGenBuffers();
int VAO = GL30.glGenBuffers();
// Sending data to OpenGL requires the usage of (flipped) byte buffers
FloatBuffer verticesBuffer = BufferUtils.createFloatBuffer(vertices.length);
verticesBuffer.put(vertices);
verticesBuffer.flip();
vertexCount = 3;
GL30.glBindVertexArray(VAO);
GL30.glBindBuffer(GL30.GL_ARRAY_BUFFER, VBO);
GL30.glBufferData(GL30.GL_ARRAY_BUFFER, verticesBuffer, GL30.GL_STATIC_DRAW);
GL30.glVertexAttribPointer(0, 3, GL30.GL_FLOAT, false, 0, 0);
GL30.glEnableVertexAttribArray(0);
GL30.glBindBuffer(GL30.GL_ARRAY_BUFFER, 0);
GL30.glBindVertexArray(0);
}
public void processTriangle() {
GL30.glBindVertexArray(VAO);
GL30.glDrawArrays(GL_TRIANGLES, 0, 3);
}
//Deals with the Shaders
private static int loadShader(String file, int type){
StringBuilder shaderSource = new StringBuilder();
try{
BufferedReader reader = new BufferedReader(new FileReader(file));
String line;
while((line = reader.readLine())!=null){
shaderSource.append(line).append("//\n");
}
reader.close();
}catch(IOException e){
e.printStackTrace();
System.exit(-1);
}
int shaderID = GL20.glCreateShader(type);
GL20.glShaderSource(shaderID, shaderSource);
GL20.glCompileShader(shaderID);
int vertexShader;
vertexShader = GL30.glCreateShader(GL30.GL_VERTEX_SHADER);
int fragmentShader;
fragmentShader = GL30.glCreateShader(GL30.GL_FRAGMENT_SHADER);
int shaderProgram;
shaderProgram = GL30.glCreateProgram();
GL30.glAttachShader(shaderProgram, vertexShader);
GL30. glAttachShader(shaderProgram, fragmentShader);
GL30.glLinkProgram(shaderProgram);
GL30.glUseProgram(shaderProgram);
GL30.glDeleteShader(vertexShader);
GL30.glDeleteShader(fragmentShader);
System.out.println("Hello");
if(GL20.glGetShaderi(shaderID, GL20.GL_COMPILE_STATUS )== GL11.GL_FALSE){
System.out.println(GL20.glGetShaderInfoLog(shaderID, 500));
System.err.println("Could not compile shader!");
System.exit(-1);
}
return shaderID;
}
}
Here is the vertex shader file:
#version 330 core
layout (location = 0) in vec3 aPos;
out vec4 vertexColor;
void main()
{
gl_Position = vec4(aPos, 1.0);
vertexColor = vec4(0.5, 4.0, 0.0, 1.0);
}
and here is the fragment shader file:
#version 330 core
out vec4 FragColor;
in vec4 vertexColor;
void main()
{
FragColor = vertexColor;
}
There are both improvements and corrections to be made here
1. Improvements
This is in your shader. After linking your shader you also need to verify it. Although your shader works fine without it for more complex programs it can reveal hidden error's
Here is the modified code[Just an suggestion take it if you wish]
private void loadProgram()
{
int vertex,fragment;
int programID=GL20.glCreateProgram(); //Step 1 create program and attach source code to it
GL20.glAttachShader(programID,vertex=loadShader("screenvertfilelocation",GL20.GL_VERTEX_SHADER));
GL20.glAttachShader(programID,fragment=loadShader("screenvertfilelocation",GL20.GL_FRAGMENT_SHADER));
GL20.glLinkProgram(programID); //Step 2 link the program
if(GL20.glGetProgrami(programID,GL20.GL_LINK_STATUS)==GL11.GL_FALSE)
{
int infoLogSize=GL20.glGetProgrami(programID,GL20.GL_INFO_LOG_LENGTH); //Get's exact error size rather than using 500
System.err.println(GL20.glGetProgramInfoLog(programID,infoLogSize));
System.err.println("COULD NOT LINK SHADER");
System.exit(-1);
}
GL20.glValidateProgram(programID); //Step 3 Validate shader
if(GL20.glGetProgrami(programID,GL20.GL_VALIDATE_STATUS)==GL11.GL_FALSE)
{
int infoLogSize=GL20.glGetProgrami(programID,GL20.GL_INFO_LOG_LENGTH); //Get exact error size
System.err.println(GL20.glGetProgramInfoLog(programID,infoLogSize));
System.err.println("COULD NOT VALIDATE SHADER");
System.exit(-1);
}
GL20.glDeleteShader(vertex); //Step 4 clean up
GL20.glDeleteShader(fragment);
GL20.glUseProgram(programID);
}
private int loadShader(String fileName,int shaderType)
{
try(BufferedReader reader = new BufferedReader(new FileReader(fileName)))
{
StringBuilder source=new StringBuilder();
String line;
while((line=reader.readLine())!=null)
{
source.append(line)
.append(System.lineSeparator());
}
int shaderID=GL20.glCreateShader(shaderType);
GL20.glShaderSource(shaderID,source);
GL20.glCompileShader(shaderID);
if(GL20.glGetShaderi(shaderID,GL20.GL_COMPILE_STATUS)==GL11.GL_FALSE)
{
int infoLogSize=GL20.glGetShaderi(shaderID,GL20.GL_INFO_LOG_LENGTH);
throw new IOException("COULD NOT COMPILE SHADER "+GL20.glGetShaderInfoLog(shaderID,infoLogSize));
}
return shaderID;
}
catch(IOException ex)
{
ex.printStackTrace(System.err);
System.exit(-1);
return -1;
}
}
Call loadProgram() after drawTriangle()
2. Your Solution
This is just a follow up from #Rabbid76 post
As soon as i copy pasted your code in my IDE i get the warning
local variable hides a field
In this code
int vertexCount = 0;
int VAO = 0;
int VBO = 0;
public void drawTriangle() {
float vertices[] =
{
-0.5f, -0.5f, 0.0f,
0.5f, -0.5f, 0.0f,
0.0f, 0.5f, 0.0f
};
//The warning here. You are redeclaring VBO & VAO
int VBO = GL15.glGenBuffers();
int VAO = GL30.glGenVertexArrays(); // #Rabbid76 original fix
Just remove the declarations
VBO = GL15.glGenBuffers();
VAO = GL30.glGenVertexArrays();
I am using LWJGL 3.1.3 and most of the gl functions and constants i use belong to an diffrent gl version for example there is no
GL30.GL_FLOAT
but
GL11.GL_FLOAT
Just to name a few
Output:
So i started to learn lwjgl recently, and quickly realized that I need to improve in OpenGL to continue. I followed tutorial here and tried to implement same code using java and lwjgl (code in tutorial is in C++). I successfully managed to replicate OpenGL calls from tutorial using lwjgl api, but when I start my program i see only black screen and nothing else =( No triangle, nothing. No errors in console ether.
My Window.java class where i perform OpenGL rendering (Never mind Spring annotations, i'm just using IoC container to manage objects, method run() is called after Spring context creation):
import com.gitlab.cvazer.dnd.map.desktop.ashlesy.Orchestrator;
import com.gitlab.cvazer.dnd.map.desktop.render.Camera;
import com.gitlab.cvazer.dnd.map.desktop.util.Shaders;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.lwjgl.Version;
import org.lwjgl.glfw.GLFWErrorCallback;
import org.lwjgl.opengl.GL;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.util.Objects;
import static org.lwjgl.glfw.Callbacks.glfwFreeCallbacks;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL30.*;
import static org.lwjgl.system.MemoryUtil.NULL;
#Slf4j
#Component
public class Window {
private #Autowired Shaders shaders;
private #Getter long window;
//START HERE!
public void run() {
new Thread(() -> {
log.info("Hello LWJGL " + Version.getVersion() + "!");
init();
try {
loop();
} catch (IOException e) {
e.printStackTrace();
}
glfwFreeCallbacks(window);
glfwDestroyWindow(window);
glfwTerminate();
Objects.requireNonNull(glfwSetErrorCallback(null)).free();
}).start();
}
private void init() {
GLFWErrorCallback.createPrint(System.err).set();
if ( !glfwInit() ) throw new IllegalStateException("Unable to initialize GLFW");
glfwDefaultWindowHints();
glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE);
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
glfwWindowHint(GLFW_SAMPLES, 8);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
window = glfwCreateWindow(800, 600, "Hello World!", NULL, NULL);
if ( window == NULL ) throw new RuntimeException("Failed to create the GLFW window");
callbacks();
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
glfwShowWindow(window);
}
private void loop() throws IOException {
GL.createCapabilities();
int vertexArray = glGenVertexArrays();
glBindVertexArray(vertexArray);
int vertexBuffer = glGenBuffers();
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
float[] data = {-1.0f, -1.0f, 0.0f,
1.0f, -1.0f, 0.0f,
0.0f, 1.0f, 0.0f};
glBufferData(GL_ARRAY_BUFFER, data, GL_STATIC_DRAW);
int program = shaders.loadShaders("vertex.glsl", "fragment.glsl");
glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
long lastTime = System.currentTimeMillis();
while ( !glfwWindowShouldClose(window) ) {
long delta = System.currentTimeMillis() - lastTime;
lastTime = System.currentTimeMillis();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(program);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glVertexAttribPointer(0,3,GL_FLOAT, false, 0, vertexBuffer);
glDrawArrays(GL_TRIANGLES, 0, 3);
glDisableVertexAttribArray(0);
glfwSwapBuffers(window); // swap the color buffers
glfwPollEvents();
}
}
}
Shaders.java class:
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import static org.lwjgl.opengl.GL30.*;
#Slf4j
#Service
public class Shaders {
public int loadShaders(String vertexFilePath, String fragmentFilePath) throws IOException {
int vertexShader = glCreateShader(GL_VERTEX_SHADER);
int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
String vertexCode = Files.lines(Paths.get(vertexFilePath))
.collect(Collectors.joining("\n"));
String fragmentCode = Files.lines(Paths.get(fragmentFilePath))
.collect(Collectors.joining("\n"));
compileShader(vertexShader, vertexCode);
compileShader(fragmentShader, fragmentCode);
int program = glCreateProgram();
glAttachShader(program, vertexShader);
glAttachShader(program, fragmentShader);
glLinkProgram(program);
glDetachShader(program, vertexShader);
glDetachShader(program, fragmentShader);
glDeleteShader(vertexShader);
glDeleteShader(fragmentShader);
return program;
}
private void compileShader(int shader, String code){
glShaderSource(shader, code);
glCompileShader(shader);
String slog = glGetShaderInfoLog(shader);
if (slog.contentEquals("")) return;
log.info(slog);
}
}
vertex.glsl file:
#version 330 core
layout(location = 0) in vec3 vertexPosition_modelspace;
void main(){
gl_Position.xyz = vertexPosition_modelspace;
gl_Position.w = 1.0;
}
fragment.glsl file:
#version 330 core
out vec3 color;
void main(){
color = vec3(1,0,0);
}
I followed part 1 (coding OpenGL calls) and 2 (coding GLSL shaders, loading them) of this tutorial, but adding shaders didn't fixed my problem
I don't think that googling further can give me answers since almost all tutorials online on topic of lwjgl use OpenGL 1 for rendering.
How can i make this work?
The issue is the line
glVertexAttribPointer(0,3,GL_FLOAT, false, 0, vertexBuffer);
If a named buffer object is bound then the last parameter of glVertexAttribPointer is treated as a byte offset into the buffer object's data store.
When you use glVertexAttribPointer then you don't have to specify the vertex buffer by a parameter. The function associates the vertex attribute to the buffer object, which is currently bound to the target GL_ARRAY_BUFFER.
It has to be:
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0);
See also Java Code Examples for org.lwjgl.opengl.GL20.glVertexAttribPointer()
GLFW.glfwMakeContextCurrent(window);
main = GLContext.createFromCurrent();
other = GLContext.createFromCurrent();
This is what I have tried so far, and in the other thread, I call
GL.setCurrent(other);
But all my OGL calls have no effect (calling genVertexArrays() returns 0).
I can't find any examples online of how to even create two different contexts let alone make one current in another thread.
Took me over 12 hours today to figure it out, but hey, it works and it's awesome. Anyways, the one thing that I lacked was ACTUAL EXAMPLES. So, for all of you who are currently in the position I was in, here you go:
import java.nio.FloatBuffer;
import nick.hacksoi.Program;
import org.lwjgl.BufferUtils;
import org.lwjgl.glfw.GLFW;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL15;
import org.lwjgl.opengl.GL20;
import org.lwjgl.opengl.GL30;
import org.lwjgl.opengl.GLContext;
import org.lwjgl.system.MemoryUtil;
public class MultiThreadTest
{
long mainWindow, otherWindow;
public void run()
{
if (GLFW.glfwInit() != GL11.GL_TRUE)
throw new IllegalStateException("Unable to initialize GLFW");
mainWindow = GLFW.glfwCreateWindow(1366, 768, "threading", MemoryUtil.NULL, MemoryUtil.NULL);
if (mainWindow == MemoryUtil.NULL)
throw new RuntimeException("Failed to create the GLFW window");
GLFW.glfwSetWindowPos(mainWindow, 1080 / 2 - 1366 / 4, 30);
GLFW.glfwShowWindow(mainWindow);
GLFW.glfwMakeContextCurrent(mainWindow);
GLContext.createFromCurrent();
GLFW.glfwWindowHint(GLFW.GLFW_VISIBLE, GL11.GL_FALSE);
otherWindow = GLFW.glfwCreateWindow(1, 1, "", MemoryUtil.NULL, mainWindow);
if (otherWindow == MemoryUtil.NULL)
throw new RuntimeException("Failed to create the GLFW window");
Runner runner = new Runner();
Thread other = new Thread(runner);
other.start();
try
{
other.join();
} catch (InterruptedException e)
{
e.printStackTrace();
}
Program program = new Program("shaders/2d/simple.vs", "shaders/2d/simple.fs");
int vao = GL30.glGenVertexArrays();
GL30.glBindVertexArray(vao);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, runner.vbo);
GL20.glEnableVertexAttribArray(0);
GL20.glVertexAttribPointer(0, 2, GL11.GL_FLOAT, false, 0, 0);
GL30.glBindVertexArray(0);
GL20.glDisableVertexAttribArray(0);
GL11.glClearColor(0.5f, 0.5f, 1f, 1);
while (GLFW.glfwWindowShouldClose(mainWindow) != GL11.GL_TRUE)
{
GLFW.glfwPollEvents();
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
program.use();
{
GL30.glBindVertexArray(vao);
GL11.glDrawArrays(GL11.GL_TRIANGLES, 0, 6);
GL30.glBindVertexArray(0);
}
program.unuse();
GLFW.glfwSwapBuffers(mainWindow);
}
}
private class Runner implements Runnable
{
public int vbo;
#Override
public void run()
{
GLFW.glfwMakeContextCurrent(otherWindow);
GLContext.createFromCurrent();
float[] vertices = new float[] { -1, -1, 0, 1, 1, -1 };
FloatBuffer vertexBuffer = BufferUtils.createFloatBuffer(6);
for (float f : vertices)
vertexBuffer.put(f);
vertexBuffer.flip();
vbo = GL15.glGenBuffers();
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, vbo);
GL15.glBufferData(GL15.GL_ARRAY_BUFFER, vertexBuffer, GL15.GL_STATIC_DRAW);
GL15.glBindBuffer(GL15.GL_ARRAY_BUFFER, 0);
}
}
public static void main(String[] args)
{
new MultiThreadTest().run();
}
}
The main caveat that I didn't realize until playing around with this test code was that VertexArrayObjects are NOT shared between contexts; so, you generate them in your rendering thread.
Anyways, hope this helps someone. It would've saved me hours of pain and suffering.
You need to create another window with glfwCreateWindow (but it does not need to be visible). See the GLFW context guide.
If I run this code as it is, I see a line from the bottom left corner of the screen to the top right corner of the screen. However, afaik I set glOrthox and glViewport, so why it's using the default projection is a mystery to me... what's wrong? the lower left of the screen should be 0,0, and 1,1 should be basically 1 pixel over and up into the screen.. not the whole screen.
package com.opengl.hello;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;
import android.opengl.GLSurfaceView.Renderer;
public class Renderer2d implements Renderer {
Context mContext;
public static ByteBuffer newByteBuffer(int size)
{ return ByteBuffer.allocateDirect(size).order(ByteOrder.nativeOrder()); }
public static FloatBuffer newFloatBuffer(int size)
{ return newByteBuffer(size * 4).asFloatBuffer(); }
public static ByteBuffer newByteBuffer(byte[] buf)
{ ByteBuffer out=newByteBuffer(buf.length); out.put(buf).position(0); return out; }
public static FloatBuffer newFloatBuffer(float[] buf)
{ FloatBuffer out=newFloatBuffer(buf.length); out.put(buf).position(0); return out; }
public Renderer2d(Context context)
{
mContext=context;
}
int mWidth;
int mHeight;
#Override
public void onDrawFrame(GL10 gl) {
gl.glViewport(0, 0, mWidth, mHeight);
// Reset projection
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
// Set up our ortho view
gl.glOrthox(0, mWidth, 0, mHeight, 0, 0);
// Reset model view
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
// Build buffers sufficient to draw a single
ByteBuffer indicesBuffer=newByteBuffer(new byte[] { 0, 1 });
// PROBLEM: I expect this to draw a small line, from the bottom left to 1,1 (a single pixel over and up into the image)..
// as well as sticking off-screen down and to the left. Instead, this covers the entire screen, corner to corner!
FloatBuffer vertexBuffer=newFloatBuffer(new float[]{ -1.f, -1.f, 1.f, 1.f });
// Enable vertex arrays, as we're about to use them
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
// Each point in the vertex buffer has two dimensions.
gl.glVertexPointer(2, GL10.GL_FLOAT, 0, vertexBuffer);
// Draw one point
gl.glDrawElements(GL10.GL_LINES, 2, GL10.GL_UNSIGNED_BYTE, indicesBuffer);
// No longer need vertex arrays
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
}
/**
* If the surface changes, reset the view.
*/
#Override
public void onSurfaceChanged(GL10 gl, int width, int height)
{
mWidth=width;
mHeight=height;
// Moved code to onDrawFrame just to group everything together
}
/**
* The Surface is created/init()
*/
#Override
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
// Yellow Background
gl.glClearColor(1.0f, 1.0f, 0.0f, 0.0f);
// Disable dithering for better performance
gl.glDisable(GL10.GL_DITHER);
// enable texture mapping
gl.glEnable(GL10.GL_TEXTURE_2D);
//enable transparency blending
gl.glEnable(GL10.GL_BLEND);
// use opaque texturing
gl.glBlendFunc(GL10.GL_ONE, GL10.GL_SRC_COLOR);
// Disable the depth buffer, we're drawing in 2D.
gl.glDisable(GL10.GL_DEPTH_TEST);
// Smooth shading
gl.glShadeModel(GL10.GL_SMOOTH);
// Really Nice Perspective Calculations
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_NICEST);
}
}
gl.glPointSize(150);
I suspect that 150 is far greater than the upper ends of GL_ALIASED_POINT_SIZE_RANGE and GL_SMOOTH_POINT_SIZE_RANGE. Try something smaller like 1 or 2.
I have an application that receives information from a database, and is used to visualize 2D bitmaps onto a GLSurfaceView. The information received will determine the x-position of the bitmap, and which bitmap image to use (there are 4 different bitmaps in my res folder to choose from).
Below are the three classes that are being used. The Activity sets the Shapes objects that need to be drawn by passing an ArrayList to the GLLayer class. This ArrayList is passed to the instance of ShapeStorage class via another setList method. This class is responsible for drawing when they are received.
The problem that I'm having is the following. Suppose I receive one object (let's say that it's a square at it's located at x=1). Some time goes by, and I receive another shape (this time, it's a triangle, and it's located at x=-1). However, when this new shape appears on the screen, the old bitmap's appearance changes to a triangle, and the new one becomes a square. In other words, the objects themselves are at the correct position that they are supposed to be at, but the bitmap being associated with them has changed. Does anyone know what the possible cause of this can be? I'm still a newbie to OpenGL-ES, and while this code looks very convoluted, it just involves setting a bunch of various properties for the View. Please help me, StackOverflow! You're my only hope.
public class GLLayer extends GLSurfaceView implements Renderer {
int onDrawFrameCounter=1;
int[] cameraTexture;
byte[] glCameraFrame=new byte[256*256]; //size of a texture must be a power of 2
private Context context;
FloatBuffer cubeBuff;
FloatBuffer texBuff;
ShapeStorage shapes;
ArrayList<Shapes> shapereceptionbuffer;
public GLLayer(Context c) {
super(c);
this.context=c;
//Initiate our stars class with the number of stars
shapes = new ShapeStorage();
shapereceptionbuffer=new ArrayList<Shapes>();
this.setEGLConfigChooser(5, 6, 5, 8, 16, 0);
this.setRenderer(this); //set the following class as a GLSurfaceView renderer
this.getHolder().setFormat(PixelFormat.TRANSPARENT); //makes the GLSurfaceView translucent
}
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
try {
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST);
gl.glShadeModel(GL10.GL_SMOOTH); //Enable Smooth Shading
gl.glEnable(GL10.GL_TEXTURE_2D); //Enable Texture Mapping
gl.glEnable(GL10.GL_BLEND); //Enable blending
gl.glClearColor(0.0f, 0.0f, 0.0f, 0.0f); //Black Background
gl.glClearDepthf(1.0f); //Depth Buffer Setup
gl.glDisable(GL10.GL_DEPTH_TEST); //Disable depth test
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE); //Set The Blending Function For Translucency
shapes.setTextures(gl,context);
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("Created",e.getMessage());
}
}//end of surfacecreated
public void setList(ArrayList<Shapes> receivedList){
synchronized(this.shapereceptionbuffer){
shapereceptionbuffer=receivedList;
}
}
public void onSurfaceChanged(GL10 gl, int width, int height) {
try {
if(height == 0) { //Prevent A Divide By Zero By
height = 1; //Making Height Equal One
}
gl.glViewport(0, 0, width, height);//specifies transformation from normalized device coordinates to window coordinates
float ratio = (float) width / height;
gl.glMatrixMode(GL11.GL_PROJECTION); //Select The Projection Matrix
gl.glLoadIdentity();//Reset The Projection Matrix
GLU.gluPerspective(gl, 45.0f, ratio, 0.1f, 100.0f);
gl.glMatrixMode(GL11.GL_MODELVIEW);//Select The Modelview Matrix
gl.glLoadIdentity();//Reset The Modelview Matrix
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("Changed",e.getMessage());
}
//GLU.gluLookAt(gl, 0, 0, 4.2f, 0, 0, 0, 0, 1, 0);//eye-point location, center of the scene and an UP vector
}//end of surfacechanged
public void onDrawFrame(GL10 gl) {
try {
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); //Clear Screen And Depth Buffer
Log.d("Buffer Size", String.valueOf(shapereceptionbuffer.size()));
synchronized(this.shapereceptionbuffer){
shapes.setShapes(shapereceptionbuffer);
shapes.draw(gl, this.context);
}
} catch (Exception e) {
Log.d("Draw",e.getMessage());
}
}//end of ondrawframe
}
This class is responsible for drawing each of the shapes that are received from the external database.
/**
* This class contains, loads, initiates textures and draws our Shapes
*/
public class ShapeStorage {
private ArrayList<Shapes> shapestoragebuffer;
private Random rand = new Random(); // Initiate Random for random values of
// stars
/** Our texture pointer */
private int[] textures = new int[4];
/**
* Constructor for our holder
*/
public ShapeStorage() {
shapestoragebuffer = new ArrayList<Shapes>();
}
public void setShapes(ArrayList<Shapes> receivedlist) {
shapestoragebuffer = receivedList;
}
public void setupTextures(GL10 gl, Context context) {
// Get the texture from the Android resource directory
InputStream is = null;
gl.glGenTextures(4, textures, 0);
for (int i = 2; i < 6; i++) {
switch (i) {
case 2:
is = context.getResources().openRawResource(R.drawable.square);
break;
case 3:
is = context.getResources().openRawResource(R.drawable.circle);
break;
case 4:
is = context.getResources().openRawResource(R.drawable.hexagon);
break;
case 5:
is = context.getResources()
.openRawResource(R.drawable.triangle);
break;
}
Bitmap bitmap = null;
try {
// BitmapFactory is an Android graphics utility for images
bitmap = BitmapFactory.decodeStream(is);
} finally {
// Always clear and close
try {
is.close();
is = null;
} catch (IOException e) {
}
}
// Generate the texture pointer
// Create Linear Filtered Texture and bind it to texture
GLUtils.texImage2D(GL11.GL_TEXTURE_2D, 0, bitmap, 0);
gl.glBindTexture(GL11.GL_TEXTURE_2D, textures[i - 2]);
gl.glTexParameterf(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER,
GL11.GL_LINEAR);
gl.glTexParameterf(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER,
GL11.GL_LINEAR);
// Clean up
bitmap.recycle();
}
}
/**
* The drawing function.
*
* #param gl
* - The GL Context
* #param twinkle
* - Twinkle on or off
*/
public void draw(GL10 gl, Context context) {
// Bind the icon texture for all Shapes
for (int loop = 0; loop < shapestoragebuffer.size(); loop++) {
// Recover the current star into an object
Shapes shape = shapestoragebuffer.get(loop);
gl.glLoadIdentity(); // Reset The Current Modelview Matrix
// gl.glRotatef(180.0f, -1.0f, 0.0f, 0.0f);
float x = shape.get_Offset_from_center();
gl.glTranslatef(x, 0.0f, -40.0f);
// Draw
switch (victim.getType()) {
// green
case 2:
shape.draw(gl, textures[0]);
break;
// red
case 3:
shape.draw(gl, textures[1]);
break;
// yellow
case 4:
shape.draw(gl, textures[2]);
break;
case 5:
shape.draw(gl, textures[3]);
break;
}
}
}
}
Here is the class that defines each of the objects that are being drawn to the GLSurfaceView; each of the shapes that are being drawn.
public class Shapes {
private int _Offset_from_center;
private int type;
Context c;
/** The buffer holding the vertices */
private FloatBuffer vertexBuffer;
/** The buffer holding the texture coordinates */
private FloatBuffer textureBuffer;
/** The initial vertex definition */
private float vertices[] = {
-1.0f, -1.0f, 0.0f, //Bottom Left
1.0f, -1.0f, 0.0f, //Bottom Right
-1.0f, 1.0f, 0.0f, //Top Left
1.0f, 1.0f, 0.0f //Top Right
};
/** The initial texture coordinates (u, v) */
private float texture[] = {
0.0f, 0.0f,
1.0f, 0.0f,
0.0f, 1.0f,
1.0f, 1.0f,
};
public Shapes() {
//
ByteBuffer byteBuf = ByteBuffer.allocateDirect(vertices.length * 4);
byteBuf.order(ByteOrder.nativeOrder());
vertexBuffer = byteBuf.asFloatBuffer();
vertexBuffer.put(vertices);
vertexBuffer.position(0);
//
byteBuf = ByteBuffer.allocateDirect(texture.length * 4);
byteBuf.order(ByteOrder.nativeOrder());
textureBuffer = byteBuf.asFloatBuffer();
textureBuffer.put(texture);
textureBuffer.position(0);
}
public int get_Offset_from_center() {
return _Offset_from_center;
}
public void set_Offset_from_center(int _Offset_from_center) {
this._Offset_from_center = _Offset_from_center;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
/**
* The object own drawing function.
* Called from the renderer to redraw this instance
* with possible changes in values.
*
* #param gl - The GL Context
*/
public void draw(GL10 gl,int texture) {
gl.glBindTexture(GL11.GL_TEXTURE_2D, texture);
//Enable the vertex, texture and normal state
gl.glEnableClientState(GL11.GL_VERTEX_ARRAY);
gl.glEnableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
//Point to our buffers
gl.glVertexPointer(3, GL11.GL_FLOAT, 0, vertexBuffer);
gl.glTexCoordPointer(2, GL11.GL_FLOAT, 0, textureBuffer);
//Draw the vertices as triangle strip
gl.glDrawArrays(GL11.GL_TRIANGLE_STRIP, 0, vertices.length / 3);
//Disable the client state before leaving
gl.glDisableClientState(GL11.GL_VERTEX_ARRAY);
gl.glDisableClientState(GL11.GL_TEXTURE_COORD_ARRAY);
}
}
You're doing something very strange with the textures. Why do you upload the texture image data for every shape on every frame, and why do you do it after you render the shape?
Here's how the usual flow of texture use in OpenGL works:
At app initialization time:
Generate a texture ID using glGenTextures.
Use glBindTexture to make that ID the current texture.
Set texture parameters.
Upload image data with texImage2D or similar.
Then, every time you need to render stuff with the texture:
Bind the texture with glBindTexture with the same ID you used above.
Render things, which will use the texture.
What I would recommend here is this:
When you activity starts up (called indirectly from onCreate or maybe onResume depending on how Android OpenGL works):
Make textures a 5-element array and pass 5 to glGenTextures
Loop through, and for each of your five resources, bind one of the four above, and upload your image with texImage2D just like you have.
Then, when you actually need to draw a shape:
Pass in an int for the texture, not an int[]; choose the right one based on the shape you want.
Call glBindTexture in your draw function, first, with that value.
Do not make any calls to texImage2D in your rendering pass.
Call glDrawArrays to draw the shape you chose with glBindTexture.
Note also that all your shapes can share the same vertex and texture buffers, since their contents are the same; that's just an efficiency thing though.