Advertisement

Efficiently draw multiple opengl elements

Started by December 19, 2017 08:12 PM
2 comments, last by alex1997 7 years, 1 month ago

I'm currently learning opengl and started to make  my own 2D engine. So far I've managed to render an rectangle made out of 2 triangles with `glDrawElements()` and apply it a custom shader. 

This is how my code looks like so far:

 


	#include <all>
	
	int main() {
	    Window window("OpenGL", 800, 600);
	    Shader shader1("./file.shader");
	
	    float vt[8] = {  -0.5f, -0.5f,    0.5f, -0.5f,     0.5f, 0.5f,    -0.5f, 0.5f };
	    const GLuint indices[6] = { 0, 1, 2, 2, 3, 0 };
	
	    GLuint vao, vbo, ebo;
	    glGenVertexArrays(1, &vao);
	    glBindVertexArray(vao);
	
	    glGenBuffers(1, &vbo);
	    glBindBuffer(GL_ARRAY_BUFFER, vbo);
	    glBufferData(GL_ARRAY_BUFFER, sizeof(vt), vertices, GL_STATIC_DRAW);
	
	    glEnableVertexAttribArray(0);
	    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
	
	    glGenBuffers(1, &ebo);
	    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo);
	    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);
	
	
	    while(window.isOpen()) {
	        window.clear(0.0, 0.5, 1.0);
	        
	        shader1.use();
	        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, NULL);
	        
	        window.update();
	    }
	
	    glDeleteBuffers(1, &vbo);
	    glDeleteBuffers(1, &ebo);
	    glDeleteVertexArrays(1, &vao);
	
	    return 0;
	}

 

There multiple way to do it, but I've heard that drawing and switching shaders one by one is pretty expensive. I'm looking to preload all the data, vertices, shaders in one buffer or what's more efficient and when it's all ready start drawing them in one call, similar to a batch. Thanks!

Always keep going, no matter what

Your example will probably run at 500+ FPS so efficiency is not an issue at this stage. Far from it.

Checkout the site learnopengl.com it goes through everything step by step. 

Forget efficiency for the moment - you'll want to texture the cube, then move the cube around, read an OBJ file to move beyond cubes and then render that model, maybe a few instances of it, a camera, matrix transforms, basic lighting .... that or similar is the usual order of things. 

Do work out how to calculate FPS and display it in the Window.title bar or Console - that way you'll know where you really stand as far as efficiency goes and if / when you need to do something about it. Meantime over thinking it all will just cripple your progress.

(Sooner or later google "bunny.obj", download it, read it into as a mesh and render that ...)

my 2 cents worth.

 

Advertisement

Man, I'm targetting drawin 2d, no bunny object, not fancy cubes, wanna draw 2d rectangles with custom shaders effeciently and after that to implement functionality on them... my 3cents..

Always keep going, no matter what

This topic is closed to new replies.

Advertisement