How expensive is glBindTexture? - Optimizing rendering of sprites.

Alright, I’m going to try to be as a direct as possible as I’m new to openGl and I may be using the wrong terminology.

Essentially, what I’m doing is modifying a custom Java2D pipeline (GLG2D) to add some hardware accelerated shader rendering features support to my current application (which uses the Java2D framework to render images etc.)

To keep it brief here, Java2D exposes a Graphics2D object, through which you can invoke methods like drawImage (which draws an image to the surface specified when the Graphics2D was instantiated.)

The GLG2D custom pipeline overrides the implementation of Graphics2D to route all rendering directly to an OpenGL implementations. I am overriding the way GLG2D renders images (by default it uses the fixed function pipeline, but I am going to be using shaders.)

I have everything working perfectly - the problems is that I noticed a huge increase in CPU consumption by the rendering routine. After profiling, I noticed this was very largely consumed by calls to glBindTexture.

Here is a snippet of my rendering routine (it’s built around JOGL - but really it’s the same thing.) [m_shader.begin just switches the active shader.]

Every-time some invokes a drawImage routine, it is translated into this (with a small amount of indirection.)


		if(m_lastTexture != texture)
		{
			m_glContext.glActiveTexture(GL.GL_TEXTURE0);
			texture.bind(m_glContext);
		}

		m_shader.begin(m_glContext);
		
		m_lastTexture = texture;

                //(Draw QUAD HERE
                
		m_shader.end(); //restore previous shader

Here are some questions I have that would help me optimize this:

  • Is it expensive to invoke glUseProgram & glGetIntegerv(GL2.GL_CURRENT_PROGRAM, …) this frequently? Is this something I should look into optimizing?

  • I know I can use more than one texture unit. Would it help performance if I measured how many times a texture was rendered per render-cycle and prioritized which to keep bound to the available units? Is the glBindTexture overhead relative to any property of the image (i.e. its size - should that be factored in when depending which ones to keep bound?)

  • How expensive is glUniform1i(to pass data to shader uniforms)? Should I be worried about how many times this method is invoked per render-cycle as well?

Thanks!

Wow - I did shader.begin() once at the start of the application (and removed the constant swapping for every call to draw image) and it dramatically increased performance. Now that I think of it, that was a really stupid thing for me to do!

Thanks for anyone who read this.