Sign in to follow this  

OpenGL 2d with OpenGL

This topic is 3871 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello, I am pretty new to OpenGL, but I do have a history with DirectX. I am a bit lost, and do not know what i am looking for. I want to make a game, tile based, in 2d BUT my game would require a LOT of live rotating of images (turrets pointing at a target, etc etc), 360 degree movement for the character, ... I read that live rotating is a big hit on performance, and the alternative, caching the prerotated images, would just take too much memory for the things I want to do. So I was wondering, is it possible to use 3d rendering for a 2d game... eg, what if I could blit the character on a square polygon, and rotate the polygon as needed? It would be cool, because i would be able to do stuff with the lighting I think? I have no idea if this is possible, or how to do it. So does anyone have any advice? or maybe point me to the good direction, maybe even a tutorial/example? Thanks for your time, Reinout

Share this post

Link to post
Share on other sites
If you're talking about manually compute the rotation and perform it on your objects then yes it will cost some performance, but you have to do a lot. With Opengl, when you want to do something like that, you can send the transformation matrix and vertices then the hardware will do the transformation. For instance you have a turrent you want to turn 60 degree clockwise or 10 turrets, then you send the transformation for rotating 60 degree clockwise and the vertices for the turrets. It's pretty much similar to Directx. I wouldn't worry about it, unless you're planning on manually transforming thousands of vertices.

Share this post

Link to post
Share on other sites
Not only is it possible to create a 2D game using a 3D API like OpenGL or Direct3D; these days its a good idea.

Most modern 3D graphics cards have pretty poor support for 2D APIs like DirectDraw, and will often fall back to executing the rendering code on the CPU for non-trivial effects like scaling or rotation. I've also witnessed strange driver-related problems with some cards that map 2D operations onto the 3D hardware and other wierdness.

On top of poor support, 2D APIs are quite restrictive compared to their 3D counterparts. Arbitrary rotation (around all 3 axis), Depth/stencil buffers, and shaders are among the chief benefits of using a 3D API, and enable visual effects and a certain elegance of code that no 2D API simultaneously, or even seperately IMHO, matches.

There is a different mindset to developing your 2D game for the 3D pipeline. The most prominant shift in thinking is switching from the top-to-bottom-left-to-right drawing mentality towards the batched drawing mentality. On 3D hardware, its better to batch tiles by their material (A collection of common visual attributes, such as bound textures, shaders, etc) than to draw each tile in sequential order, changing the material with (more or less) each step.

There's a book called Focus on 2D in Direct3D which covers the topic. IIRC, it doesn't go into more advanced theory like optimal batching, so if you're already familiar with DirectX, it may not contain much benefit for you. The gist of using a 3D API to write a 2D game is simply: Write a 3D engine, set orthographic projection, thats it. The fact that the engine is 2D will allow you to make certain assumptions (and optimizations, accordingly) -- for example, you'll always know which direction is the up-vector, and culling the scene becomes trivial.

Good luck!

Share this post

Link to post
Share on other sites
A short definition of OpenGL is a 2D and 3D graphics API.
OpenGL provides 2D specific functions for you, for example, glDrawPixels() to draw 2D image on the screen, and glVertex2f() to draw a vertex in 2D space. So, you can do whatever you want using OpenGL.

Share this post

Link to post
Share on other sites
You received a couple of good replies already, but a few more cents from me:

* set up an orthogonal view (this means you have no perspective; your frustum is a box)
* render (textured) quads and triangles, the depth becomes the priority in ortho
* you can simply use matrices for all your 2D objects, allowing you to translate, skew, rotate and scale them

Some neat tricks you can utilize all of a sudden (which are often harder to do using old style bitblit 2D):

* fragment- and vertex shaders allow for real nice 2D effects
* full screen filters, like bloom, motion blur
* linear interpolation of vertex colors, so you can easily add gradients to your sprites
* rotation around different axii (not just the axis that points into your screen)

It is important not to switch material states very often to allow batching. So when you have a tiled background, make sure you render a huge triangle strip that fetches the tiles from a single texture by setting proper UV texture coordinates for the vertices.

Bottom line: 3D acceleration will certainly accelerate your 2D and allow new effects that were never possible before. It will require you to approach things a bit differently though.

Share this post

Link to post
Share on other sites
cool, thanks for all the great replies
I will try to do it as suggested above (textured quads).

Still have a lot to learn before i can do that though.
If anyone can point out some usefull functions to look up, feel free ;)

thanks for the replies

Share this post

Link to post
Share on other sites
Seems you're not the first one asking ;)

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Similar Content

    • By xhcao
      Does sync be needed to read texture content after access texture image in compute shader?
      My simple code is as below,
      glBindImageTexture(0, texture[0], 0, GL_FALSE, 3, GL_READ_ONLY, GL_R32UI);
      glBindImageTexture(1, texture[1], 0, GL_FALSE, 4, GL_WRITE_ONLY, GL_R32UI);
      glDispatchCompute(1, 1, 1);
      // Does sync be needed here?
      glBindFramebuffer(GL_READ_FRAMEBUFFER, framebuffer);
                                     GL_TEXTURE_CUBE_MAP_POSITIVE_X + face, texture[1], 0);
      glReadPixels(0, 0, kWidth, kHeight, GL_RED_INTEGER, GL_UNSIGNED_INT, outputValues);
      Compute shader is very simple, imageLoad content from texture[0], and imageStore content to texture[1]. Does need to sync after dispatchCompute?
    • By Jonathan2006
      My question: is it possible to transform multiple angular velocities so that they can be reinserted as one? My research is below:
      // This works quat quaternion1 = GEQuaternionFromAngleRadians(angleRadiansVector1); quat quaternion2 = GEMultiplyQuaternions(quaternion1, GEQuaternionFromAngleRadians(angleRadiansVector2)); quat quaternion3 = GEMultiplyQuaternions(quaternion2, GEQuaternionFromAngleRadians(angleRadiansVector3)); glMultMatrixf(GEMat4FromQuaternion(quaternion3).array); // The first two work fine but not the third. Why? quat quaternion1 = GEQuaternionFromAngleRadians(angleRadiansVector1); vec3 vector1 = GETransformQuaternionAndVector(quaternion1, angularVelocity1); quat quaternion2 = GEQuaternionFromAngleRadians(angleRadiansVector2); vec3 vector2 = GETransformQuaternionAndVector(quaternion2, angularVelocity2); // This doesn't work //quat quaternion3 = GEQuaternionFromAngleRadians(angleRadiansVector3); //vec3 vector3 = GETransformQuaternionAndVector(quaternion3, angularVelocity3); vec3 angleVelocity = GEAddVectors(vector1, vector2); // Does not work: vec3 angleVelocity = GEAddVectors(vector1, GEAddVectors(vector2, vector3)); static vec3 angleRadiansVector; vec3 angularAcceleration = GESetVector(0.0, 0.0, 0.0); // Sending it through one angular velocity later in my motion engine angleVelocity = GEAddVectors(angleVelocity, GEMultiplyVectorAndScalar(angularAcceleration, timeStep)); angleRadiansVector = GEAddVectors(angleRadiansVector, GEMultiplyVectorAndScalar(angleVelocity, timeStep)); glMultMatrixf(GEMat4FromEulerAngle(angleRadiansVector).array); Also how do I combine multiple angularAcceleration variables? Is there an easier way to transform the angular values?
    • By dpadam450
      I have this code below in both my vertex and fragment shader, however when I request glGetUniformLocation("Lights[0].diffuse") or "Lights[0].attenuation", it returns -1. It will only give me a valid uniform location if I actually use the diffuse/attenuation variables in the VERTEX shader. Because I use position in the vertex shader, it always returns a valid uniform location. I've read that I can share uniforms across both vertex and fragment, but I'm confused what this is even compiling to if this is the case.
      #define NUM_LIGHTS 2
      struct Light
          vec3 position;
          vec3 diffuse;
          float attenuation;
      uniform Light Lights[NUM_LIGHTS];
    • By pr033r
      I have a Bachelor project on topic "Implenet 3D Boid's algorithm in OpenGL". All OpenGL issues works fine for me, all rendering etc. But when I started implement the boid's algorithm it was getting worse and worse. I read article ( inspirate from another code (here: but it still doesn't work like in tutorials and videos. For example the main problem: when I apply Cohesion (one of three main laws of boids) it makes some "cycling knot". Second, when some flock touch to another it scary change the coordination or respawn in origin (x: 0, y:0. z:0). Just some streng things. 
      I followed many tutorials, change a try everything but it isn't so smooth, without lags like in another videos. I really need your help. 
      My code (optimalizing branch):
      Exe file (if you want to look) and models folder (for those who will download the sources):
      Thanks for any help...

    • By Andrija
      I am currently trying to implement shadow mapping into my project , but although i can render my depth map to the screen and it looks okay , when i sample it with shadowCoords there is no shadow.
      Here is my light space matrix calculation
      mat4x4 lightViewMatrix; vec3 sun_pos = {SUN_OFFSET * the_sun->direction[0], SUN_OFFSET * the_sun->direction[1], SUN_OFFSET * the_sun->direction[2]}; mat4x4_look_at(lightViewMatrix,sun_pos,player->pos,up); mat4x4_mul(lightSpaceMatrix,lightProjMatrix,lightViewMatrix); I will tweak the values for the size and frustum of the shadow map, but for now i just want to draw shadows around the player position
      the_sun->direction is a normalized vector so i multiply it by a constant to get the position.
      player->pos is the camera position in world space
      the light projection matrix is calculated like this:
      mat4x4_ortho(lightProjMatrix,-SHADOW_FAR,SHADOW_FAR,-SHADOW_FAR,SHADOW_FAR,NEAR,SHADOW_FAR); Shadow vertex shader:
      uniform mat4 light_space_matrix; void main() { gl_Position = light_space_matrix * transfMatrix * vec4(position, 1.0f); } Shadow fragment shader:
      out float fragDepth; void main() { fragDepth = gl_FragCoord.z; } I am using deferred rendering so i have all my world positions in the g_positions buffer
      My shadow calculation in the deferred fragment shader:
      float get_shadow_fac(vec4 light_space_pos) { vec3 shadow_coords = / light_space_pos.w; shadow_coords = shadow_coords * 0.5 + 0.5; float closest_depth = texture(shadow_map, shadow_coords.xy).r; float current_depth = shadow_coords.z; float shadow_fac = 1.0; if(closest_depth < current_depth) shadow_fac = 0.5; return shadow_fac; } I call the function like this:
      get_shadow_fac(light_space_matrix * vec4(position,1.0)); Where position is the value i got from sampling the g_position buffer
      Here is my depth texture (i know it will produce low quality shadows but i just want to get it working for now):
      sorry because of the compression , the black smudges are trees ...
      EDIT: Depth texture attachment:
  • Popular Now