1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
import static org.lwjgl.opengl.GL11.*;
import static org.lwjgl.opengl.GL15.*;
import static org.lwjgl.opengl.GL20.*;
import static org.lwjgl.opengl.GL31.*;
import static org.lwjgl.opengl.GL33.*;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
import java.nio.ShortBuffer;

import javax.swing.JOptionPane;

import org.lwjgl.BufferUtils;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.DisplayMode;
import org.lwjgl.opengl.PixelFormat;
import org.lwjgl.util.Timer;

public class InstancingTest {
	
	private static final int WIDTH = 800, HEIGHT = 800;
	
	private static final int NUM_QUADS = 512*1024;
	private static final float QUAD_SIZE = 1f; //Pixel size of quads
	
	private static final int BATCH_SIZE = 512;
	
	private int mode;
	
	private int vbo, ibo;

	private int batchPseudoProgram, batchPseudoPositionsLocation;
	private int batchInstancingProgram, batchInstancingPositionsLocation;
	private int pureInstancingProgram, pureInstancingPositionsLocation;
	
	private FloatBuffer instancePositions;
	private int streamVBO;
	
	private int fpsCounter;
	private Timer timer;
	
	private InstancingTest(){
		
		mode = JOptionPane.showOptionDialog(null, "Please pick a mode", "Mode select", JOptionPane.DEFAULT_OPTION, JOptionPane.QUESTION_MESSAGE, null, new Object[]{"Batched pseudo instancing", "Batched instancing arrays", "Batched instancing indexed", "Pure instancing arrays", "Pure instancing indexed"}, 0);
		
		if(mode == JOptionPane.CLOSED_OPTION){
			System.exit(0);
		}
		
		initOGL(); //Creates the window
		createQuadVBO();
		loadShaders();
		initInstancePositions();
		
		fpsCounter = 0;
		timer = new Timer();
	}

	private void initOGL() {
		try {
			Display.setDisplayMode(new DisplayMode(WIDTH, HEIGHT));
			Display.create(new PixelFormat());
		} catch (LWJGLException ex) {
			ex.printStackTrace();
		}
	}
	
	private void createQuadVBO() {
		vbo = glGenBuffers();
		glBindBuffer(GL_ARRAY_BUFFER, vbo);
		
		//2 float positions, 1 float instance id, 1 RGBA color = 16 bytes per vert
		ByteBuffer data = BufferUtils.createByteBuffer(BATCH_SIZE * 4 * (4*2 + 4 + 4));

		//An instance ID is encoded into the position (x, y, instanceID) .
		for(int i = 0; i < BATCH_SIZE; i++){
			data.putFloat(0).putFloat(0).putFloat(i).put((byte)255).put((byte)  0).put((byte)  0).put((byte)255); //Vertex 1: (0, 0, <instance id>), red
			data.putFloat(1).putFloat(0).putFloat(i).put((byte)  0).put((byte)255).put((byte)  0).put((byte)255); //Vertex 2: (1, 0, <instance id>), green
			data.putFloat(1).putFloat(1).putFloat(i).put((byte)  0).put((byte)  0).put((byte)255).put((byte)255); //Vertex 3: (1, 1, <instance id>), blue
			data.putFloat(0).putFloat(1).putFloat(i).put((byte)255).put((byte)255).put((byte)255).put((byte)255); //Vertex 4: (0, 1, <instance id>), white
		}
		
		data.flip();
		
		glBufferData(GL_ARRAY_BUFFER, data, GL_STATIC_DRAW);

		glBindBuffer(GL_ARRAY_BUFFER, 0);
		
		ibo = glGenBuffers();
		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);

		ShortBuffer indices = BufferUtils.createShortBuffer(BATCH_SIZE * 6);
		
		int offset = 0;
		for(int i = 0; i < BATCH_SIZE; i++){
			indices.put((short)(offset + 0)).put((short)(offset + 1)).put((short)(offset + 2));
			indices.put((short)(offset + 0)).put((short)(offset + 2)).put((short)(offset + 3));
			offset += 4;
		}
		
		indices.flip();
		
		glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices, GL_STATIC_DRAW);

		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
	}

	private void loadShaders() {
		
		if(mode == 0){
			batchPseudoProgram = createShaderProgram("shaders/instancing/pseudo.vert");
			batchPseudoPositionsLocation = glGetUniformLocation(batchPseudoProgram, "instancePositions");
		}
		
		if(mode == 1 || mode == 2){
			batchInstancingProgram = createShaderProgram("shaders/instancing/batched instancing.vert");
			batchInstancingPositionsLocation = glGetUniformLocation(batchInstancingProgram, "instancePositions");
		}
		
		if(mode == 3 || mode == 4){
			pureInstancingProgram = createShaderProgram("shaders/instancing/pure instancing.vert");
			pureInstancingPositionsLocation = glGetAttribLocation(pureInstancingProgram, "instancePositions");
			streamVBO = glGenBuffers();
		}
		
	}

	private void initInstancePositions() {

		instancePositions = BufferUtils.createFloatBuffer(2 * NUM_QUADS);
		
		float x = 0, y = 0;
		for(int i = 0; i < NUM_QUADS; i++){
			
			instancePositions.put(x).put(y);
			
			x++;
			if(x * QUAD_SIZE > WIDTH){
				y++;
				x = 0;
			}
		}
		
		instancePositions.flip();
	}
	
	
	//Java-specific shader loading code, not important.
	private int createShaderProgram(String vertexShaderFile){
		int program = glCreateProgram();
		
		int vertexShader = glCreateShader(GL_VERTEX_SHADER);
        glShaderSource(vertexShader, loadFileSource(new File(vertexShaderFile)));
        glCompileShader(vertexShader);
        
        String errorLog = glGetShaderInfoLog(vertexShader, 65536);
        if(errorLog.length() != 0){
            System.out.println("\nCompiling shader " + vertexShader + "\nShader compile log: \n" + errorLog);
        }
        
        glAttachShader(program, vertexShader);
        glLinkProgram(program);
        
		return program;
	}

	//Java-specific shader loading code, not important.
	private static String loadFileSource(File file){
        if(!file.exists()){
            System.out.println("Unable to open file " + file.getAbsolutePath() + "!!!");
            return null;
        }

        StringBuilder source = new StringBuilder();
        String line;
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            while ((line = reader.readLine()) != null) {
                source.append(line).append('\n');
            }
            reader.close();
        } catch (Exception e) {
            System.out.println("Failed to read shader source!");
            e.printStackTrace();
            return null;
        }
        return source.toString();
    }

	public void gameloop(){
		while(!Display.isCloseRequested()){
			
			fpsCounter++;
			Timer.tick();
			if(timer.getTime() >= 1f){
				timer.reset();
				System.out.println("FPS: " + fpsCounter);
				fpsCounter = 0;
			}
			
			glClear(GL_COLOR_BUFFER_BIT);
			
			glLoadIdentity();
			glOrtho(0, WIDTH, HEIGHT, 0, -1, 1);
			glScalef(QUAD_SIZE, QUAD_SIZE, 1);
			
			
			glBindBuffer(GL_ARRAY_BUFFER, vbo);
			glVertexPointer(3, GL_FLOAT, 16, 0);
			glColorPointer(4, GL_UNSIGNED_BYTE, 16, 12);
			glEnableClientState(GL_VERTEX_ARRAY);
			glEnableClientState(GL_COLOR_ARRAY);

			glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
			
			switch(mode){
				case 0:
					renderPseudoInstancing();
					break;
				case 1:
				case 2:
					renderBatchedInstancing();
					break;
				case 3:
				case 4:
					renderPureInstancing();
					break;
			}
			
			
			Display.update();
			
		}
	}

	private void renderPseudoInstancing() {

		glUseProgram(batchPseudoProgram);
		
		int fullBatches = NUM_QUADS / BATCH_SIZE;
		int lastBatch = NUM_QUADS % BATCH_SIZE;
		
		for(int i = 0; i < fullBatches; i++){

			//Pick out the correct part of the instance position array.
			instancePositions.position(i * BATCH_SIZE * 2);
			instancePositions.limit((i+1) * BATCH_SIZE * 2);
			
			glUniform2(batchPseudoPositionsLocation, instancePositions);
			//glDrawArrays(GL_QUADS, 0, 4 * BATCH_SIZE);
			glDrawElements(GL_TRIANGLES, 6 * BATCH_SIZE, GL_UNSIGNED_SHORT, 0);
		}

		if(lastBatch > 0){

			//Pick out the correct part of the instance position array.
			instancePositions.position(fullBatches * BATCH_SIZE * 2);
			instancePositions.limit(instancePositions.capacity());
			
			glUniform2(batchPseudoPositionsLocation, instancePositions);
			//glDrawArrays(GL_QUADS, 0, 4 * lastBatch);
			glDrawElements(GL_TRIANGLES, 6 * lastBatch, GL_UNSIGNED_SHORT, 0);
		}
	}
	
	private void renderBatchedInstancing() {
		
		glUseProgram(batchInstancingProgram);
		
		int fullBatches = NUM_QUADS / BATCH_SIZE;
		int lastBatch = NUM_QUADS % BATCH_SIZE;
		
		for(int i = 0; i < fullBatches; i++){

			//Pick out the correct part of the instance position array.
			instancePositions.position(i * BATCH_SIZE * 2);
			instancePositions.limit((i+1) * BATCH_SIZE * 2);
			
			glUniform2(batchInstancingPositionsLocation, instancePositions);
			if(mode == 1){
				glDrawArraysInstanced(GL_QUADS, 0, 4, BATCH_SIZE);
			}else{
				glDrawElementsInstanced(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0, BATCH_SIZE);
			}
		}

		if(lastBatch > 0){

			//Pick out the correct part of the instance position array.
			instancePositions.position(fullBatches * BATCH_SIZE * 2);
			instancePositions.limit(instancePositions.capacity());
			
			glUniform2(batchInstancingPositionsLocation, instancePositions);
			if(mode == 1){
				glDrawArraysInstanced(GL_QUADS, 0, 4, lastBatch);
			}else{
				glDrawElementsInstanced(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0, lastBatch);
			}
		}
	}

	private void renderPureInstancing() {
		
		glUseProgram(pureInstancingProgram);
		
		//Upload all instance positions to a VBO
		glBindBuffer(GL_ARRAY_BUFFER, streamVBO);
		glBufferData(GL_ARRAY_BUFFER, instancePositions, GL_STREAM_DRAW);
		
		//Setup vertex attribute for instance positions
		glVertexAttribPointer(pureInstancingPositionsLocation, 2, GL_FLOAT, false, 0, 0);
		glEnableVertexAttribArray(pureInstancingPositionsLocation);
		glVertexAttribDivisor(pureInstancingPositionsLocation, 1);

		if(mode == 3){
			glDrawArraysInstanced(GL_QUADS, 0, 4, NUM_QUADS);
		}else{
			glDrawElementsInstanced(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0, NUM_QUADS);
		}
	}

	public static void main(String[] args){
		new InstancingTest().gameloop();
	}
}