JOGL v2.6.0-rc-20250706
JOGL, High-Performance Graphics Binding for Java™ (public API).
TrianglesInstancedRendererHardcoded.java
Go to the documentation of this file.
1package com.jogamp.opengl.test.junit.jogl.demos.gl4;
2
3import java.io.File;
4import java.io.FileOutputStream;
5import java.io.IOException;
6import java.io.PrintStream;
7import java.nio.FloatBuffer;
8import java.util.Random;
9
10import com.jogamp.opengl.DebugGL4;
11import com.jogamp.opengl.GL;
12import com.jogamp.opengl.GL2ES2;
13import com.jogamp.opengl.GL4;
14import com.jogamp.opengl.GLAutoDrawable;
15import com.jogamp.opengl.GLEventListener;
16import com.jogamp.opengl.TraceGL4;
17import com.jogamp.opengl.fixedfunc.GLMatrixFunc;
18import com.jogamp.common.nio.Buffers;
19import com.jogamp.math.FloatUtil;
20import com.jogamp.math.Matrix4f;
21import com.jogamp.math.Vec3f;
22import com.jogamp.opengl.util.PMVMatrix;
23
25 private float aspect;
26
27 private int shaderProgram;
28 private int vertShader;
29 private int fragShader;
30 private int projectionMatrixLocation;
31 private int transformMatrixLocation;
32 private static final int locPos = 1;
33 private static final int locCol = 2;
34 private PMVMatrix projectionMatrix;
35
36 private static final int NO_OF_INSTANCE = 30;
37 private final FloatBuffer triangleTransform = FloatBuffer.allocate(16 * NO_OF_INSTANCE);
38 private final Matrix4f[] mat = new Matrix4f[NO_OF_INSTANCE];
39 private final float[] rotationSpeed = new float[NO_OF_INSTANCE];
40
41 private int[] vbo;
42 private int[] vao;
43 private PrintStream stream;
44 private final IInstancedRenderingView view;
45
46 private static final boolean useTraceGL = false;
47
49 this.view = view;
50 initTransform();
51
52 if(useTraceGL) {
53 try {
54 stream = new PrintStream(new FileOutputStream(new File("instanced.txt")));
55 } catch (final IOException e1) {
56 e1.printStackTrace();
57 }
58 }
59 }
60
61 @Override
62 public void init(final GLAutoDrawable drawable) {
63 final GL4 gl = drawable.getGL().getGL4();
64 drawable.setGL(new DebugGL4(gl));
65 if(useTraceGL) {
66 drawable.setGL(new TraceGL4(gl, stream));
67 }
68
69 gl.glClearColor(1, 1, 1, 1); //white background
70 // gl.glClearColor(0, 0, 0, 1); //black background
71 gl.glClearDepth(1.0f);
72
73 System.err.println("Chosen GLCapabilities: " + drawable.getChosenGLCapabilities());
74 System.err.println("INIT GL IS: " + gl.getClass().getName());
75 System.err.println("GL_VENDOR: " + gl.glGetString(GL.GL_VENDOR));
76 System.err.println("GL_RENDERER: " + gl.glGetString(GL.GL_RENDERER));
77 System.err.println("GL_VERSION: " + gl.glGetString(GL.GL_VERSION));
78
79 try {
80 initShaders(gl);
81 } catch (final IOException e) {
82 e.printStackTrace();
83 }
84 initVBO(gl);
85 }
86
87 @Override
88 public void display(final GLAutoDrawable drawable) {
89
90 final GL4 gl = drawable.getGL().getGL4();
92
93 gl.glUseProgram(shaderProgram);
94
95 projectionMatrix.glMatrixMode(GLMatrixFunc.GL_PROJECTION);
96
97 projectionMatrix.glPushMatrix();
98 float winScale = 0.1f;
99 if(view != null) {
100 winScale = view.getScale();
101 }
102 projectionMatrix.glScalef(winScale, winScale, winScale);
103 gl.glUniformMatrix4fv(projectionMatrixLocation, 1, false, projectionMatrix.getSyncP().getSyncFloats());
104 projectionMatrix.glPopMatrix();
105 generateTriangleTransform();
106 gl.glUniformMatrix4fv(transformMatrixLocation, NO_OF_INSTANCE, false, triangleTransform);
107
108 gl.glBindVertexArray(vao[0]);
109 gl.glDrawArraysInstanced(GL.GL_TRIANGLES, 0, 3, NO_OF_INSTANCE);
110 gl.glBindVertexArray(0);
111 gl.glUseProgram(0);
112 }
113
114 @Override
115 public void reshape(final GLAutoDrawable drawable, final int x, final int y, final int width, final int height) {
116 System.out.println("Window resized to width=" + width + " height=" + height);
117 final GL4 gl3 = drawable.getGL().getGL4();
118 gl3.glViewport(0, 0, width, height);
119 aspect = (float) width / (float) height;
120
121 projectionMatrix = new PMVMatrix();
122 projectionMatrix.glMatrixMode(GLMatrixFunc.GL_PROJECTION);
123 projectionMatrix.glLoadIdentity();
124 projectionMatrix.gluPerspective(FloatUtil.QUARTER_PI, aspect, 0.001f, 20f);
125 projectionMatrix.gluLookAt(new Vec3f(0, 0, -10), new Vec3f(0, 0, 0), new Vec3f(0, 1, 0));
126 }
127
128 @Override
129 public void dispose(final GLAutoDrawable drawable){
130 final GL4 gl = drawable.getGL().getGL4();
131 gl.glUseProgram(0);
132 gl.glDeleteBuffers(2, vbo, 0);
133 gl.glDetachShader(shaderProgram, vertShader);
134 gl.glDeleteShader(vertShader);
135 gl.glDetachShader(shaderProgram, fragShader);
136 gl.glDeleteShader(fragShader);
137 gl.glDeleteProgram(shaderProgram);
138 }
139
140 private void initTransform() {
141 final Random rnd = new Random();
142 final Matrix4f tmp = new Matrix4f();
143 for(int i = 0; i < NO_OF_INSTANCE; i++) {
144 rotationSpeed[i] = 0.3f * rnd.nextFloat();
145 mat[i] = new Matrix4f();
146 mat[i].loadIdentity();
147 final float scale = 1f + 4 * rnd.nextFloat();
148 mat[i].scale(scale, tmp);
149 //setup initial position of each triangle
150 mat[i].translate(20f * rnd.nextFloat() - 10f,
151 10f * rnd.nextFloat() - 5f,
152 0f, tmp);
153 }
154 }
155
156 private void initVBO(final GL4 gl) {
157 final FloatBuffer interleavedBuffer = Buffers.newDirectFloatBuffer(vertices.length + colors.length);
158 for(int i = 0; i < vertices.length/3; i++) {
159 for(int j = 0; j < 3; j++) {
160 interleavedBuffer.put(vertices[i*3 + j]);
161 }
162 for(int j = 0; j < 4; j++) {
163 interleavedBuffer.put(colors[i*4 + j]);
164 }
165 }
166 interleavedBuffer.flip();
167
168 vao = new int[1];
169 gl.glGenVertexArrays(1, vao , 0);
170 gl.glBindVertexArray(vao[0]);
171 vbo = new int[1];
172 gl.glGenBuffers(1, vbo, 0);
173 gl.glBindBuffer(GL.GL_ARRAY_BUFFER, vbo[0]);
174 gl.glBufferData(GL.GL_ARRAY_BUFFER, interleavedBuffer.limit() * Buffers.SIZEOF_FLOAT, interleavedBuffer, GL.GL_STATIC_DRAW);
175
176 gl.glEnableVertexAttribArray(locPos);
177 gl.glEnableVertexAttribArray(locCol);
178
179 final int stride = Buffers.SIZEOF_FLOAT * (3+4);
180 gl.glVertexAttribPointer( locPos, 3, GL.GL_FLOAT, false, stride, 0);
181 gl.glVertexAttribPointer( locCol, 4, GL.GL_FLOAT, false, stride, Buffers.SIZEOF_FLOAT * 3);
182 }
183
184 private void initShaders(final GL4 gl) throws IOException {
185 vertShader = gl.glCreateShader(GL2ES2.GL_VERTEX_SHADER);
186 fragShader = gl.glCreateShader(GL2ES2.GL_FRAGMENT_SHADER);
187
188 final String[] vlines = new String[] { vertexShaderString };
189 final int[] vlengths = new int[] { vlines[0].length() };
190 gl.glShaderSource(vertShader, vlines.length, vlines, vlengths, 0);
191 gl.glCompileShader(vertShader);
192
193 final int[] compiled = new int[1];
194 gl.glGetShaderiv(vertShader, GL2ES2.GL_COMPILE_STATUS, compiled, 0);
195 if(compiled[0] != 0) {
196 System.out.println("Vertex shader compiled");
197 } else {
198 final int[] logLength = new int[1];
199 gl.glGetShaderiv(vertShader, GL2ES2.GL_INFO_LOG_LENGTH, logLength, 0);
200
201 final byte[] log = new byte[logLength[0]];
202 gl.glGetShaderInfoLog(vertShader, logLength[0], (int[])null, 0, log, 0);
203
204 System.err.println("Error compiling the vertex shader: " + new String(log));
205 System.exit(1);
206 }
207
208 final String[] flines = new String[] { fragmentShaderString };
209 final int[] flengths = new int[] { flines[0].length() };
210 gl.glShaderSource(fragShader, flines.length, flines, flengths, 0);
211 gl.glCompileShader(fragShader);
212
213 gl.glGetShaderiv(fragShader, GL2ES2.GL_COMPILE_STATUS, compiled, 0);
214 if(compiled[0] != 0){
215 System.out.println("Fragment shader compiled.");
216 } else {
217 final int[] logLength = new int[1];
218 gl.glGetShaderiv(fragShader, GL2ES2.GL_INFO_LOG_LENGTH, logLength, 0);
219
220 final byte[] log = new byte[logLength[0]];
221 gl.glGetShaderInfoLog(fragShader, logLength[0], (int[])null, 0, log, 0);
222
223 System.err.println("Error compiling the fragment shader: " + new String(log));
224 System.exit(1);
225 }
226
227 shaderProgram = gl.glCreateProgram();
228 gl.glAttachShader(shaderProgram, vertShader);
229 gl.glAttachShader(shaderProgram, fragShader);
230
231 gl.glBindAttribLocation(shaderProgram, locPos, "mgl_Vertex");
232 gl.glBindAttribLocation(shaderProgram, locCol, "mgl_Color");
233
234 gl.glLinkProgram(shaderProgram);
235
236 projectionMatrixLocation = gl.glGetUniformLocation(shaderProgram, "mgl_PMatrix");
237 System.out.println("projectionMatrixLocation:" + projectionMatrixLocation);
238 transformMatrixLocation = gl.glGetUniformLocation(shaderProgram, "mgl_MVMatrix");
239 System.out.println("transformMatrixLocation:" + transformMatrixLocation);
240 }
241
242 private void generateTriangleTransform() {
243 triangleTransform.clear();
244 final Matrix4f tmp = new Matrix4f();
245 for(int i = 0; i < NO_OF_INSTANCE; i++) {
246 // mat[i].translate(0.1f, 0.1f, 0);
247 mat[i].rotate(rotationSpeed[i], 0, 0, 1, tmp);
248 // mat[i].translate(-0.1f, -0.1f, 0);
249 mat[i].get(triangleTransform);
250 }
251 triangleTransform.flip();
252 }
253
254 private final String vertexShaderString =
255 "#version 410 \n" +
256 "\n" +
257 "uniform mat4 mgl_PMatrix; \n" +
258 "uniform mat4 mgl_MVMatrix[" + NO_OF_INSTANCE + "]; \n" +
259 "in vec3 mgl_Vertex; \n" +
260 "in vec4 mgl_Color; \n" +
261 "out vec4 frontColor; \n" +
262 "void main(void) \n" +
263 "{ \n" +
264 " frontColor = mgl_Color; \n" +
265 " gl_Position = mgl_PMatrix * mgl_MVMatrix[gl_InstanceID] * vec4(mgl_Vertex, 1);" +
266 "} ";
267
268 private final String fragmentShaderString =
269 "#version 410\n" +
270 "\n" +
271 "in vec4 frontColor; \n" +
272 "out vec4 mgl_FragColor; \n" +
273 "void main (void) \n" +
274 "{ \n" +
275 " mgl_FragColor = frontColor; \n" +
276 "} ";
277
278 private final float[] vertices = {
279 1.0f, 0.0f, 0,
280 -0.5f, 0.866f, 0,
281 -0.5f, -0.866f, 0
282 };
283
284 private final float[] colors = {
285 1.0f, 0.0f, 0.0f, 1.0f,
286 0.0f, 1.0f, 0.0f, 1.0f,
287 0f, 0f, 1.0f, 1f
288 };
289}
Basic Float math utility functions.
Definition: FloatUtil.java:83
static final float QUARTER_PI
The value PI/4, i.e.
Basic 4x4 float matrix implementation using fields for intensive use-cases (host operations).
Definition: Matrix4f.java:89
final Matrix4f loadIdentity()
Set this matrix to identity.
Definition: Matrix4f.java:172
final Matrix4f rotate(final float ang_rad, final float x, final float y, final float z, final Matrix4f tmp)
Rotate this matrix about give axis and angle in radians, i.e.
Definition: Matrix4f.java:1525
final Matrix4f scale(final float x, final float y, final float z, final Matrix4f tmp)
Scale this matrix, i.e.
Definition: Matrix4f.java:1580
final Matrix4f translate(final float x, final float y, final float z, final Matrix4f tmp)
Translate this matrix, i.e.
Definition: Matrix4f.java:1558
float get(final int i)
Gets the ith component, 0 <= i < 16.
Definition: Matrix4f.java:279
3D Vector based upon three float components.
Definition: Vec3f.java:37
final SyncMatrix4f getSyncP()
Returns the SyncMatrix of projection matrix (P).
void dispose(final GLAutoDrawable drawable)
Notifies the listener to perform the release of all OpenGL resources per GLContext,...
void reshape(final GLAutoDrawable drawable, final int x, final int y, final int width, final int height)
Called by the drawable during the first repaint after the component has been resized.
void display(final GLAutoDrawable drawable)
Called by the drawable to initiate OpenGL rendering by the client.
void init(final GLAutoDrawable drawable)
Called by the drawable immediately after the OpenGL context is initialized.
PMVMatrix implements a subset of the fixed function pipeline GLMatrixFunc using PMVMatrix4f.
Definition: PMVMatrix.java:62
final void glScalef(final float x, final float y, final float z)
Scale the current matrix.
Definition: PMVMatrix.java:396
final void glMatrixMode(final int matrixName)
Sets the current matrix mode.
Definition: PMVMatrix.java:218
final void gluPerspective(final float fovy_rad, final float aspect, final float zNear, final float zFar)
Multiply the current matrix with the perspective/frustum matrix.
Definition: PMVMatrix.java:499
final void glPushMatrix()
Push the current matrix to it's stack, while preserving it's values.
Definition: PMVMatrix.java:458
final void gluLookAt(final Vec3f eye, final Vec3f center, final Vec3f up)
Multiply the current matrix with the eye, object and orientation, i.e.
Definition: PMVMatrix.java:507
final void glPopMatrix()
Pop the current matrix from it's stack.
Definition: PMVMatrix.java:447
final void glLoadIdentity()
Load the current matrix with the identity matrix.
Definition: PMVMatrix.java:325
FloatBuffer getSyncFloats()
Return the FloatBuffer after synchronizing it w/ the underlying getMatrix().
void glVertexAttribPointer(int index, int size, int type, boolean normalized, int stride, long pointer_buffer_offset)
Entry point to C language function: void {@native glVertexAttribPointer}(GLuint index,...
void glClearDepth(double depth)
Aliased entrypoint of void {@native glClearDepth}(GLclampd depth); and void {@native glClearDepthf...
void glBindAttribLocation(int program, int index, String name)
Entry point to C language function: void {@native glBindAttribLocation}(GLuint program,...
void glEnableVertexAttribArray(int index)
Entry point to C language function: void {@native glEnableVertexAttribArray}(GLuint index) Part of...
void glCompileShader(int shader)
Entry point to C language function: void {@native glCompileShader}(GLuint shader) Part of GL_ES_VE...
void glDeleteShader(int shader)
Entry point to C language function: void {@native glDeleteShader}(GLuint shader) Part of GL_ES_VER...
void glDetachShader(int program, int shader)
Entry point to C language function: void {@native glDetachShader}(GLuint program,...
int glCreateProgram()
Entry point to C language function: GLuint {@native glCreateProgram}() Part of GL_ES_VERSION_2_0,...
void glUseProgram(int program)
Entry point to C language function: void {@native glUseProgram}(GLuint program) Part of GL_ES_VERS...
void glGetShaderiv(int shader, int pname, IntBuffer params)
Entry point to C language function: void {@native glGetShaderiv}(GLuint shader, GLenum pname,...
int glGetUniformLocation(int program, String name)
Entry point to C language function: GLint {@native glGetUniformLocation}(GLuint program,...
void glShaderSource(int shader, int count, String[] string, IntBuffer length)
Entry point to C language function: void {@native glShaderSource}(GLuint shader, GLsizei count,...
void glAttachShader(int program, int shader)
Entry point to C language function: void {@native glAttachShader}(GLuint program,...
void glUniformMatrix4fv(int location, int count, boolean transpose, FloatBuffer value)
Entry point to C language function: void {@native glUniformMatrix4fv}(GLint location,...
void glDeleteProgram(int program)
Entry point to C language function: void {@native glDeleteProgram}(GLuint program) Part of GL_ES_V...
int glCreateShader(int type)
Entry point to C language function: GLuint {@native glCreateShader}(GLenum type) Part of GL_ES_VER...
void glGetShaderInfoLog(int shader, int bufSize, IntBuffer length, ByteBuffer infoLog)
Entry point to C language function: void {@native glGetShaderInfoLog}(GLuint shader,...
void glLinkProgram(int program)
Entry point to C language function: void {@native glLinkProgram}(GLuint program) Part of GL_ES_VER...
void glGenVertexArrays(int n, IntBuffer arrays)
Entry point to C language function: void {@native glGenVertexArrays}(GLsizei n, GLuint * arrays) P...
void glBindVertexArray(int array)
Entry point to C language function: void {@native glBindVertexArray}(GLuint array) Part of GL_ARB_...
void glDrawArraysInstanced(int mode, int first, int count, int instancecount)
Entry point to C language function: void {@native glDrawArraysInstanced}(GLenum mode,...
A higher-level abstraction than GLDrawable which supplies an event based mechanism (GLEventListener) ...
GL getGL()
Returns the GL pipeline object this GLAutoDrawable uses.
GL setGL(GL gl)
Sets the GL pipeline object this GLAutoDrawable uses.
GL4 getGL4()
Casts this object to the GL4 interface.
GLCapabilitiesImmutable getChosenGLCapabilities()
Fetches the GLCapabilitiesImmutable corresponding to the chosen OpenGL capabilities (pixel format / v...
Declares events which client code can use to manage OpenGL rendering into a GLAutoDrawable.
void glGenBuffers(int n, IntBuffer buffers)
Entry point to C language function: void {@native glGenBuffers}(GLsizei n, GLuint * buffers) Part ...
static final int GL_STATIC_DRAW
GL_VERSION_1_5, GL_ES_VERSION_2_0, GL_VERSION_ES_1_0, GL_ARB_vertex_buffer_object Alias for: GL_STATI...
Definition: GL.java:673
static final int GL_TRIANGLES
GL_ES_VERSION_2_0, GL_VERSION_1_1, GL_VERSION_1_0, GL_VERSION_ES_1_0 Define "GL_TRIANGLES" with expre...
Definition: GL.java:145
static final int GL_VERSION
GL_ES_VERSION_2_0, GL_VERSION_1_1, GL_VERSION_1_0, GL_VERSION_ES_1_0 Define "GL_VERSION" with express...
Definition: GL.java:190
static final int GL_FLOAT
GL_ES_VERSION_2_0, GL_VERSION_1_1, GL_VERSION_1_0, GL_VERSION_ES_1_0 Define "GL_FLOAT" with expressio...
Definition: GL.java:786
static final int GL_COLOR_BUFFER_BIT
GL_ES_VERSION_2_0, GL_VERSION_1_1, GL_VERSION_1_0, GL_VERSION_ES_1_0 Define "GL_COLOR_BUFFER_BIT" wit...
Definition: GL.java:390
void glClearColor(float red, float green, float blue, float alpha)
Entry point to C language function: void {@native glClearColor}(GLfloat red, GLfloat green,...
String glGetString(int name)
Entry point to C language function: const GLubyte * {@native glGetString}(GLenum name) Part of GL_...
static final int GL_RENDERER
GL_ES_VERSION_2_0, GL_VERSION_1_1, GL_VERSION_1_0, GL_VERSION_ES_1_0 Define "GL_RENDERER" with expres...
Definition: GL.java:662
void glClear(int mask)
Entry point to C language function: void {@native glClear}(GLbitfield mask) Part of GL_ES_VERSION_...
static final int GL_VENDOR
GL_ES_VERSION_2_0, GL_VERSION_1_1, GL_VERSION_1_0, GL_VERSION_ES_1_0 Define "GL_VENDOR" with expressi...
Definition: GL.java:607
void glViewport(int x, int y, int width, int height)
Entry point to C language function: void {@native glViewport}(GLint x, GLint y, GLsizei width,...
static final int GL_DEPTH_BUFFER_BIT
GL_ES_VERSION_2_0, GL_VERSION_1_1, GL_VERSION_1_0, GL_VERSION_ES_1_0 Define "GL_DEPTH_BUFFER_BIT" wit...
Definition: GL.java:738
void glDeleteBuffers(int n, IntBuffer buffers)
Entry point to C language function: void {@native glDeleteBuffers}(GLsizei n, const GLuint * buffers...
void glBindBuffer(int target, int buffer)
Entry point to C language function: void {@native glBindBuffer}(GLenum target, GLuint buffer) Part...
void glBufferData(int target, long size, Buffer data, int usage)
Entry point to C language function: void {@native glBufferData}(GLenum target, GLsizeiptr size,...
static final int GL_ARRAY_BUFFER
GL_VERSION_1_5, GL_ES_VERSION_2_0, GL_VERSION_ES_1_0, GL_ARB_vertex_buffer_object Alias for: GL_ARRAY...
Definition: GL.java:633
Subset of OpenGL fixed function pipeline's matrix operations.
static final int GL_PROJECTION
Matrix mode projection.