Sign in to follow this  
XTAL256

OpenGL Transparency using glDrawPixels

Recommended Posts

Does OpenGL use pre-multiplied alpha? I can't find anything about it in the red book or even on google but i have been using the SOIL library with my game for a while now an i use it with the flag SOIL_FLAG_MULTIPLY_ALPHA. When i use it without this some of my images have while where it should be transparent. That was for my GUI, now i am up to writing the code for the game maps and (for various reasons) i am using raw pixel data instead of GL textures. But i don't know if i need to pre-multiply the pixel data. I tried with and without and it definitely seems to use pre-multiplied alpha. But the background of the image is still black. I am drawing the pixel data over the top of a textured quad and the image should show the texture through the transparent parts. Well, i'll just show you... The blend function is (GL_ONE, GL_ONE_MINUS_SRC_ALPHA). [Edited by - XTAL256 on July 27, 2008 9:50:09 PM]

Share this post


Link to post
Share on other sites
Quote:
Original post by XTAL256
Does OpenGL use pre-multiplied alpha?

No, it doesn't.

As to why you don't get transparency, there can be lots of reasons - blending not enabled, alpha channel not transferred, incorrectly configured pixel transfer pipeline, etc. You don't provide enough information to proceed any further than pure speculation.

Share this post


Link to post
Share on other sites
Gl uses whatever blend mode you tell it to. By looking at your blend function it seems like you are using pre-multiplied alpha. Make sure you have all relevant alpha options turned on, and that you are using alpha format for your texture.

Share this post


Link to post
Share on other sites
Oh yeah, I didn't notice that you use a strange blending mode.

The best and most straightforward way is to use (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA). Your alpha value then simply represents opacity.

Share this post


Link to post
Share on other sites
Quote:
Original post by Yann L
Oh yeah, I didn't notice that you use a strange blending mode.

The best and most straightforward way is to use (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA). Your alpha value then simply represents opacity.



That's not "the best", it has all sorts of problems compared to premultiplied: http://home.comcast.net/~tom_forsyth/blog.wiki.html#%5B%5BPremultiplied%20alpha%5D%5D

Both are equally straightforward as they involve setting the blending mode.

I'm guessing previous posters are correct and part of the state is missing (i.e blending disabled, etc).

Share this post


Link to post
Share on other sites
Quote:
Original post by raigan
That's not "the best", it has all sorts of problems compared to premultiplied: http://home.comcast.net/~tom_forsyth/blog.wiki.html#%5B%5BPremultiplied%20alpha%5D%5D

And premultiplied alpha has even more problems that (conveniently) aren't mentioned in that article. Standard alpha blending is the 'best' in the sense that it is the easiest, most intuitive and most flexible method that is achievable with todays' non-programmable blending stages.

Premultiplied alpha is in no way more 'correct' than standard alpha blending. Physically, they're both entirely wrong. However, while premultiplied alpha can have its uses in image composition (keep in mind that it was originally designed to speed up CPU blending !), it is often more incorrect than standard alpha blending when introducing concepts such as HDR, non-linear blending or the dreaded HDR-MSAA-Tonemapping combo. And with modern programmable pipelines, what do you call 'pre'-multiplied alpha anyway ? When does the post-multiply become a pre-multiply ? It doesn't really make any sense.

This article cites the whole DXT compression deal as an advantage for premultiplied alpha. That is entirely incorrect. This is strictly a question about the behaviour of lossy compression algorithms regarding to edge cases, especially colour values that are totally transparent. Premultiplying them with alpha is in no way a guarantee to increase DXT compression quality. Infact, while it might improve quality on some images, it can seriously degrade quality on others. And beside doing nothing (ie. leaving the colour values as-is) or multiplying with alpha, there are a whole pile of other techniques that consistently improve quality on almost all cases, and that have absolutely nothing to do with premultiplied alpha.

Whether or not this is what the OP is after is another question. I have personally never felt the need for PM alpha. If you don't need physically correct blending, then standard alpha is perfectly fine and gives you the option to modify transparency on the fly. If you need physically correct transparency, then you can't use the standard blending pipeline anyway.

Share this post


Link to post
Share on other sites
I'm kind of a n00b when it comes to OpenGL. I am just making this game as a hobby, i never took any courses on OGL and i haven't read all of the red book. I know the basics of OGL and i even made a Windows Media Player visualisation using it but i never understood how to do alpha blending. When i tried the mode that i thought would work, i just got black where it should have been transparent. So when i started making my game i used SOIL for loading images and for reasons i can no longer remember i used GL_ONE, GL_ONE_MINUS_SRC_ALPHA as the blend mode. I just set blend mode to what you said (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA without pre-multiplied alpha) and it works just the same, so i'll use that.
But i still can't get the map to draw properly. I worked out (before i posted this) that i needed to disable textures before drawing pixels but do i also need to turn off alpha blending? Because it still doesn't work if i do. I know it's hard to help me if i don't provide much info but i don't know where the problem is. Here is some of the code:

/// Map.h /////////////////////////
class Map {
public:
static Vector<Map*> maps; // List of all Maps
static void loadMaps(); // Load Maps from Map directory

public:
bool isCreated; // If the map has been created
String name, description;
String dir; // Directory where map data is
Image* preview; // Preview image to show in GUI
int width, height; // Size of map (px)
Rect view; // Area in view on screen
int maxPlayers; // Maximum number of players
Image* background; // Background image
int bgTileMode; // Whether to tile or stretch background
unsigned char* image; // Map image
unsigned char* terrain; // Terrain map

Map() : isCreated(false) {}
~Map();
void load(String &filename);
void create();
void distroy();
void draw();
};

/// Map.cpp ///////////////////////
void Map::draw() {
drawImage(background, 0, 0, 800, 450); // Draws a texture mapped quad with background image on it
glDisable(GL_BLEND);
glDisable(GL_TEXTURE_2D);
glRasterPos2i(100, 300); // These values are just for debugging
glDrawPixels(width, height, GL_RGBA, GL_UNSIGNED_BYTE, image);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
}


The image is made up of smaller tile images but basically the image data is loaded using SOIL_load_image (see SOIL docs). When i don't use pre-multiplied alpha (and using the blend mode you guys suggested) the transparent areas are white but when i do use it the transparent areas are black, which i assume is transparent because the background is black.

Share this post


Link to post
Share on other sites
Quote:
Original post by Yann L
And premultiplied alpha has even more problems that (conveniently) aren't mentioned in that article. Standard alpha blending is the 'best' in the sense that it is the easiest, most intuitive and most flexible method that is achievable with todays' non-programmable blending stages.



Having to resort to complex, ad-hoc pre-processing in order to avoid weird halos around the edges of transparent textures is what makes the standard method awkward, non-intuitive (especially for beginners) and pretty damn stupid: http://www.robinwood.com/Catalog/Technical/SL-Tuts/SLPages/WhiteHalo2.html

Compression aside, what are the "even more" problems with PM?

Share this post


Link to post
Share on other sites
Quote:
Original post by raigan
Quote:
Original post by Yann L
And premultiplied alpha has even more problems that (conveniently) aren't mentioned in that article. Standard alpha blending is the 'best' in the sense that it is the easiest, most intuitive and most flexible method that is achievable with todays' non-programmable blending stages.



Having to resort to complex, ad-hoc pre-processing in order to avoid weird halos around the edges of transparent textures is what makes the standard method awkward, non-intuitive (especially for beginners) and pretty damn stupid: http://www.robinwood.com/Catalog/Technical/SL-Tuts/SLPages/WhiteHalo2.html

That's a photoshop/content creation issue that has nothing to do with pre-multiplied vs. non-pre-multiplied. PEBKAC.

Share this post


Link to post
Share on other sites
I guess I wasn't clear -- this image on that page specifically shows the sort of thing you have to do (either via the plugin on that page OR your own pre-process) to make sure that fully transparent pixels are colored to avoid haloing: http://www.robinwood.com/Catalog/Technical/SL-Tuts/SLGraphics/Halo/Halo12-Solidified.jpg

Color from fully transparent pixels being "pulled in" by texture filtering isn't a Photoshop/content creation issue, it's a direct result of the non-PM blending formula.

Another way to look at it is that non-PM will always lerp both color and alpha channels at the same time, which is not what you want at the edges of transparencies -- you want the alpha to lerp to 0 while the color stays constant. This is impossible to achieve with non-PM blending, and pre-processing images to "bleed" the correct color into fully transparent texels is a common work-around, not a proper solution.

PM lets you avoid this problem, which is the main reason to use it IMHO; I thought this was a well-known issue, or else I would have been more specific with the example link.. it was just the first one I came across.

Share this post


Link to post
Share on other sites
Quote:
Original post by raigan
Color from fully transparent pixels being "pulled in" by texture filtering isn't a Photoshop/content creation issue, it's a direct result of the non-PM blending formula.

No, it's a direct result of incorrectly using the blending stage (or the whole pixel pipeline).

Quote:
Original post by raigan
Another way to look at it is that non-PM will always lerp both color and alpha channels at the same time, which is not what you want at the edges of transparencies -- you want the alpha to lerp to 0 while the color stays constant. This is impossible to achieve with non-PM blending, and pre-processing images to "bleed" the correct color into fully transparent texels is a common work-around, not a proper solution.

Blatantly incorrect. Infact, flood filling around transparent texel is one correct solution (although others exist). Premultiplied alpha is essentially nothing but a (bad) hack, that will fail in many occasions, and that was developed in a time where fully programmable image manipulation hardware, that operates with full floating point precision and without clamping/saturating, simply didn't exist.

In fact, you asked where else PM alpha would create problems other than with (compressed) textures. Well, actually, nowhere - because premultiplied alpha doesn't even exist anywhere else on modern hardware ! This whole pre- versus post- multiply will only make a difference when information gets lost somewhere in the middle - if it is clamped, saturated, or non-linearily combined without user control. Guess what - the whole graphics pipeline of a modern 3D card is both fully programmable and doesn't lose information (except for numerical rounding errors, but these are irrelevant for image blending). Pre or post alpha, it doesn't make a difference in a floating point pipeline, because they're mathematically the same !

So the only point where you can still use them is with LDR textures. And even there, it doesn't make sense, as I outlined above. Take FP16/32 textures and/or shader filtering, and PM-alpha completely disappears from this plane of existance.

Quote:
Original post by raigan
PM lets you avoid this problem, which is the main reason to use it IMHO; I thought this was a well-known issue,

Yes, this is a well known issue. And PM alpha is an incorrect way of addressing it.

Share this post


Link to post
Share on other sites
Uh, guys, back to my problem. I have already realised that i don't need to use pre-multiplied alpha, my other problem (which at first i thought was related to PM alpha) is that i get black where it should be transparent when i draw the pixels on top of a textured quad. You can see what i am doing in the code i posted for Map::draw, as for creating the image, well, here is the code for loading the "composite images" that contains all of the tiles:

void CompositeImage::load(XMLNode node) {
numTiles = node.numChild("tile");
tiles = new MapTile[numTiles];
int ch; // Number of channels the original image had

// Load image data
String imgFile = node.getAttribute("img");
image = SOIL_load_image(imgFile.c_str(),&width,&height,&ch,SOIL_LOAD_RGBA);
if (image == NULL) // Throw error if load fails
throw ImageError("Could not load map image \"" + imgFile +
"\"\nReason: " + SOIL_last_result());
Image::invertY(image, width, height, 4); // Need to flip image vertically
Image::premultAlpha(image, width, height, 4);

... // Create terrain data then create tiles
}

/// Image.cpp //////////////////////

/* Converts an image with an regular alpha channel to pre-multiplied alpha */
/* Taken from the SOIL code (../soil/soil.c, line 1004) */
void Image::premultAlpha(unsigned char* img, int w, int h, int channels) {
int i;
switch(channels) {
case 2:
for(i = 0; i < 2*w*h; i += 2) {
img[i] = (img[i] * img[i+1] + 128) >> 8;
}
break;
case 4:
for(i = 0; i < 4*w*h; i += 4) {
img[i+0] = (img[i+0] * img[i+3] + 128) >> 8;
img[i+1] = (img[i+1] * img[i+3] + 128) >> 8;
img[i+2] = (img[i+2] * img[i+3] + 128) >> 8;
}
break;
default:
/* no other number of channels contains alpha data */
break;
}
}


There is nothing that i can see in that code that would cause the problem. SOIL_load_image just loads an image in RGBA format. Although i said i wasn't going to use PM alpha, for some reason i still get different results with and without it.

The area that is white in the second pic should be transparent and the whole black background rectangle should also. The coloured squiggly lines are semi-transparent in the original image, you can see that the colours overlap but only show the black background behind it instead of the proper background image (the city, see my first post for a better view of it).

Share this post


Link to post
Share on other sites
can anyone help me? I can't seem to find anything wrong with my code so it must be some sort of OpenGL related thing that i am not aware of, like not being able to use glDrawPixels with textures. And if that is the case then how else can i do it?
thanks

Share this post


Link to post
Share on other sites
Can it be a depth test problem? If you enable depth testing and leave it at the default depth test function (GL_LESS), you cannot draw two images at exactly the same depth becuase the second one will fail the depth test.

Share this post


Link to post
Share on other sites
Ah, thank you. I would have never thought of that. Oh, but i disabled depth testing:
glDisable(GL_DEPTH_TEST);
when i init my graphics routines. I never really thought that i would need depth testing with a 2D game but i didn't know what would happen if i left it on (which i didn't). Well just in case the problem is similar to that i will post the code for initiating GL:

/* Intialise the graphics routines and pixel format */
void graphics::initGraphics() {
glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClearDepth(1.0f);
glShadeModel(GL_FLAT);
glEnable(GL_POINT_SMOOTH);
glEnable(GL_TEXTURE_2D);
glDisable(GL_DEPTH_TEST);
glEnable(GL_BLEND);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_COLOR_LOGIC_OP);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_FASTEST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);

// Set up orthographic view
glMatrixMode(GL_PROJECTION);
glPushMatrix();
glLoadIdentity();
glOrtho(0, screenWidth, screenHeight, 0, -1, 1);
glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();

// Create bitmap fonts from images
Font::initFonts();
}


But i doubt that anything there would cause my problem.
Just to make sure, colour (0,0,0,0) is transparent when GL_BLEND is enabled with GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA? I will double-check the image data to make sure it is 0,0,0,0 and not 0,0,0,255 or something.

Share this post


Link to post
Share on other sites
I googled my problem and found this post at gamedev. One of the guys there said that glDrawPixels can be used with alpha but he didn't really go into it any more. One of the quotes he posted mentioned that "you may need to control the current drawing buffers". I don't know that much about OpenGL so maybe someone could explain why that is needed (it sounds like OGL uses two or more buffers where it can write images to and then blend the pixels from each buffer).
Also, does anyone know of any websites that have a tutorial or a "dumbed-down" explanation of some of these OGL functions like blending, working with pixel data, and the framebuffer. Or will i have to read all of the red book [depressed]. I'm sorry but i just can't sit down and read that thing, i prefer a more practical learning approach (that i'm sure many people do).

Share this post


Link to post
Share on other sites
I was just reading the OpenGL red book and i remembered that i am using double buffering, i wondered if i needed to select the correct buffer for reading/writing to. I set the buffer to GL_FRONT and GL_BACK but neither had any affect. I don't think i need double buffering anyway so i might disable it, i should also mention that i am using SDL with OpenGL so i use SDL commands to do it (i.e. SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);), still, i don't think that would make any difference.

Share this post


Link to post
Share on other sites
Since OpenGL is designed to be a 3d API, it generally doesnt handle constant-depth (2d) over-draw in a predictable manner. Rather than relying on OpenGL to simulate transparency with alpha blending, you might want to just manipulate the raw image data yourself.

i.e. assuming you have 2 images stored in arrays of RGBA values

for each pixel in image array:
__if overlapping image alpha = 1:
____current pixel red = overlapping red
____current pixel blue = overlapping blue
____current pixel green = overlapping green
__else if overlapping alpha = 0:
____dont change current pixel, the overlapping image is transparent here

draw the resulting texture to the screen


This is probably the complete-noob way to do it, but at least Im fairly confident it will work. If it doesnt, your image's alpha values are probably messed up.

Share this post


Link to post
Share on other sites
Well that would only account for opaque or transparent images (i.e. alpha of 1 or 0), not varying degrees of transparency. I'm also not sure if that will be slower than having OpenGL do it.
Quote:
Since OpenGL is designed to be a 3d API, it generally doesnt handle constant-depth (2d) over-draw in a predictable manner.

I did not know that. But i even tried drawing the map image twice slightly overlapping each other and transparency didn't even work then. i.e. using glDrawPixels to draw a transparent image over another image drawn with glDrawPixels didn't work.

And as i asked before, would double buffering have any affect? EDIT: i just disables double buffering and i didn't notice any difference.

[Edited by - XTAL256 on August 4, 2008 3:16:57 AM]

Share this post


Link to post
Share on other sites
/// Map.cpp ///////////////////////
void Map::draw() {
drawImage(background, 0, 0, 800, 450); // Draws a texture mapped quad with background image on it
glDisable(GL_BLEND);
glDisable(GL_TEXTURE_2D);
glRasterPos2i(100, 300); // These values are just for debugging
glDrawPixels(width, height, GL_RGBA, GL_UNSIGNED_BYTE, image);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
}



Looks like you are disabling blending(glDisable(GL_BLEND)) right before drawing your pixels. That could be the problem.

Share this post


Link to post
Share on other sites
Na, i think that is for textures only and has no effect on glDrawPixels. I don't know for sure but i have tried with and without GL_BLEND and neither work.
In case anyone wants have a thorough look through my code (i'm not saying you have to, just if you have nothing else to do) i have uploaded my source code here. The code in question is in map/Map.cpp functions Map::create() and Map::draw(). Also look at the other files in that directory.

Share this post


Link to post
Share on other sites
Quote:
Original post by XTAL256
Na, i think that is for textures only and has no effect on glDrawPixels. I don't know for sure but i have tried with and without GL_BLEND and neither work.
In case anyone wants have a thorough look through my code (i'm not saying you have to, just if you have nothing else to do) i have uploaded my source code here. The code in question is in map/Map.cpp functions Map::create() and Map::draw(). Also look at the other files in that directory.


Wrong, Blending is part of the pipeline, and works whatever your fragments come from textures, or from glDrawPixels.

So enable it to achieve transparency. (And setup the blend equation)

Share this post


Link to post
Share on other sites
Oh, ok. For some reason i got the impression that i had to disable GL_BLEND for glDrawPixels, i must have just been thinking of GL_TEXTURE_2D.
But even if i do that it still doesn't have transparency.

Share this post


Link to post
Share on other sites
Now that you've got blend back on i suggest commenting out
"Image::premultAlpha(image, width, height, 4);"
And see if that helps.

If not i cant really guess at why it wouldn't be working. I get alpha blending just fine with glDrawPixels using pretty much just:

glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

...

glWindowPos2i(50,400);
glDrawPixels(imagewidth, imageheight, 0x1908, GL_UNSIGNED_BYTE, imagedata);

Share this post


Link to post
Share on other sites
Oh yeah, i forgot i still had pre-multiplied alpha on. Actually, i thought i already commented it out, i must have missed it. Oh, i remember why i kept it. For some reason, it doesn't have any transparency at all if i don't pre-multiply alpha. When i use it, the image is blended with the black background but not with the texture behind it.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this  

  • Forum Statistics

    • Total Topics
      628291
    • Total Posts
      2981863
  • Similar Content

    • By mellinoe
      Hi all,
      First time poster here, although I've been reading posts here for quite a while. This place has been invaluable for learning graphics programming -- thanks for a great resource!
      Right now, I'm working on a graphics abstraction layer for .NET which supports D3D11, Vulkan, and OpenGL at the moment. I have implemented most of my planned features already, and things are working well. Some remaining features that I am planning are Compute Shaders, and some flavor of read-write shader resources. At the moment, my shaders can just get simple read-only access to a uniform (or constant) buffer, a texture, or a sampler. Unfortunately, I'm having a tough time grasping the distinctions between all of the different kinds of read-write resources that are available. In D3D alone, there seem to be 5 or 6 different kinds of resources with similar but different characteristics. On top of that, I get the impression that some of them are more or less "obsoleted" by the newer kinds, and don't have much of a place in modern code. There seem to be a few pivots:
      The data source/destination (buffer or texture) Read-write or read-only Structured or unstructured (?) Ordered vs unordered (?) These are just my observations based on a lot of MSDN and OpenGL doc reading. For my library, I'm not interested in exposing every possibility to the user -- just trying to find a good "middle-ground" that can be represented cleanly across API's which is good enough for common scenarios.
      Can anyone give a sort of "overview" of the different options, and perhaps compare/contrast the concepts between Direct3D, OpenGL, and Vulkan? I'd also be very interested in hearing how other folks have abstracted these concepts in their libraries.
    • By aejt
      I recently started getting into graphics programming (2nd try, first try was many years ago) and I'm working on a 3d rendering engine which I hope to be able to make a 3D game with sooner or later. I have plenty of C++ experience, but not a lot when it comes to graphics, and while it's definitely going much better this time, I'm having trouble figuring out how assets are usually handled by engines.
      I'm not having trouble with handling the GPU resources, but more so with how the resources should be defined and used in the system (materials, models, etc).
      This is my plan now, I've implemented most of it except for the XML parts and factories and those are the ones I'm not sure of at all:
      I have these classes:
      For GPU resources:
      Geometry: holds and manages everything needed to render a geometry: VAO, VBO, EBO. Texture: holds and manages a texture which is loaded into the GPU. Shader: holds and manages a shader which is loaded into the GPU. For assets relying on GPU resources:
      Material: holds a shader resource, multiple texture resources, as well as uniform settings. Mesh: holds a geometry and a material. Model: holds multiple meshes, possibly in a tree structure to more easily support skinning later on? For handling GPU resources:
      ResourceCache<T>: T can be any resource loaded into the GPU. It owns these resources and only hands out handles to them on request (currently string identifiers are used when requesting handles, but all resources are stored in a vector and each handle only contains resource's index in that vector) Resource<T>: The handles given out from ResourceCache. The handles are reference counted and to get the underlying resource you simply deference like with pointers (*handle).  
      And my plan is to define everything into these XML documents to abstract away files:
      Resources.xml for ref-counted GPU resources (geometry, shaders, textures) Resources are assigned names/ids and resource files, and possibly some attributes (what vertex attributes does this geometry have? what vertex attributes does this shader expect? what uniforms does this shader use? and so on) Are reference counted using ResourceCache<T> Assets.xml for assets using the GPU resources (materials, meshes, models) Assets are not reference counted, but they hold handles to ref-counted resources. References the resources defined in Resources.xml by names/ids. The XMLs are loaded into some structure in memory which is then used for loading the resources/assets using factory classes:
      Factory classes for resources:
      For example, a texture factory could contain the texture definitions from the XML containing data about textures in the game, as well as a cache containing all loaded textures. This means it has mappings from each name/id to a file and when asked to load a texture with a name/id, it can look up its path and use a "BinaryLoader" to either load the file and create the resource directly, or asynchronously load the file's data into a queue which then can be read from later to create the resources synchronously in the GL context. These factories only return handles.
      Factory classes for assets:
      Much like for resources, these classes contain the definitions for the assets they can load. For example, with the definition the MaterialFactory will know which shader, textures and possibly uniform a certain material has, and with the help of TextureFactory and ShaderFactory, it can retrieve handles to the resources it needs (Shader + Textures), setup itself from XML data (uniform values), and return a created instance of requested material. These factories return actual instances, not handles (but the instances contain handles).
       
       
      Is this a good or commonly used approach? Is this going to bite me in the ass later on? Are there other more preferable approaches? Is this outside of the scope of a 3d renderer and should be on the engine side? I'd love to receive and kind of advice or suggestions!
      Thanks!
    • By nedondev
      I 'm learning how to create game by using opengl with c/c++ coding, so here is my fist game. In video description also have game contain in Dropbox. May be I will make it better in future.
      Thanks.
    • By Abecederia
      So I've recently started learning some GLSL and now I'm toying with a POM shader. I'm trying to optimize it and notice that it starts having issues at high texture sizes, especially with self-shadowing.
      Now I know POM is expensive either way, but would pulling the heightmap out of the normalmap alpha channel and in it's own 8bit texture make doing all those dozens of texture fetches more cheap? Or is everything in the cache aligned to 32bit anyway? I haven't implemented texture compression yet, I think that would help? But regardless, should there be a performance boost from decoupling the heightmap? I could also keep it in a lower resolution than the normalmap if that would improve performance.
      Any help is much appreciated, please keep in mind I'm somewhat of a newbie. Thanks!
    • By test opty
      Hi,
      I'm trying to learn OpenGL through a website and have proceeded until this page of it. The output is a simple triangle. The problem is the complexity.
      I have read that page several times and tried to analyse the code but I haven't understood the code properly and completely yet. This is the code:
       
      #include <glad/glad.h> #include <GLFW/glfw3.h> #include <C:\Users\Abbasi\Desktop\std_lib_facilities_4.h> using namespace std; //****************************************************************************** void framebuffer_size_callback(GLFWwindow* window, int width, int height); void processInput(GLFWwindow *window); // settings const unsigned int SCR_WIDTH = 800; const unsigned int SCR_HEIGHT = 600; const char *vertexShaderSource = "#version 330 core\n" "layout (location = 0) in vec3 aPos;\n" "void main()\n" "{\n" " gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);\n" "}\0"; const char *fragmentShaderSource = "#version 330 core\n" "out vec4 FragColor;\n" "void main()\n" "{\n" " FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);\n" "}\n\0"; //******************************* int main() { // glfw: initialize and configure // ------------------------------ glfwInit(); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // glfw window creation GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "My First Triangle", nullptr, nullptr); if (window == nullptr) { cout << "Failed to create GLFW window" << endl; glfwTerminate(); return -1; } glfwMakeContextCurrent(window); glfwSetFramebufferSizeCallback(window, framebuffer_size_callback); // glad: load all OpenGL function pointers if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress)) { cout << "Failed to initialize GLAD" << endl; return -1; } // build and compile our shader program // vertex shader int vertexShader = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertexShader, 1, &vertexShaderSource, nullptr); glCompileShader(vertexShader); // check for shader compile errors int success; char infoLog[512]; glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(vertexShader, 512, nullptr, infoLog); cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << endl; } // fragment shader int fragmentShader = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragmentShader, 1, &fragmentShaderSource, nullptr); glCompileShader(fragmentShader); // check for shader compile errors glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(fragmentShader, 512, nullptr, infoLog); cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << endl; } // link shaders int shaderProgram = glCreateProgram(); glAttachShader(shaderProgram, vertexShader); glAttachShader(shaderProgram, fragmentShader); glLinkProgram(shaderProgram); // check for linking errors glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(shaderProgram, 512, nullptr, infoLog); cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << endl; } glDeleteShader(vertexShader); glDeleteShader(fragmentShader); // set up vertex data (and buffer(s)) and configure vertex attributes float vertices[] = { -0.5f, -0.5f, 0.0f, // left 0.5f, -0.5f, 0.0f, // right 0.0f, 0.5f, 0.0f // top }; unsigned int VBO, VAO; glGenVertexArrays(1, &VAO); glGenBuffers(1, &VBO); // bind the Vertex Array Object first, then bind and set vertex buffer(s), //and then configure vertex attributes(s). glBindVertexArray(VAO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void*)0); glEnableVertexAttribArray(0); // note that this is allowed, the call to glVertexAttribPointer registered VBO // as the vertex attribute's bound vertex buffer object so afterwards we can safely unbind glBindBuffer(GL_ARRAY_BUFFER, 0); // You can unbind the VAO afterwards so other VAO calls won't accidentally // modify this VAO, but this rarely happens. Modifying other // VAOs requires a call to glBindVertexArray anyways so we generally don't unbind // VAOs (nor VBOs) when it's not directly necessary. glBindVertexArray(0); // uncomment this call to draw in wireframe polygons. //glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); // render loop while (!glfwWindowShouldClose(window)) { // input // ----- processInput(window); // render // ------ glClearColor(0.2f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); // draw our first triangle glUseProgram(shaderProgram); glBindVertexArray(VAO); // seeing as we only have a single VAO there's no need to // bind it every time, but we'll do so to keep things a bit more organized glDrawArrays(GL_TRIANGLES, 0, 3); // glBindVertexArray(0); // no need to unbind it every time // glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.) glfwSwapBuffers(window); glfwPollEvents(); } // optional: de-allocate all resources once they've outlived their purpose: glDeleteVertexArrays(1, &VAO); glDeleteBuffers(1, &VBO); // glfw: terminate, clearing all previously allocated GLFW resources. glfwTerminate(); return 0; } //************************************************** // process all input: query GLFW whether relevant keys are pressed/released // this frame and react accordingly void processInput(GLFWwindow *window) { if (glfwGetKey(window, GLFW_KEY_ESCAPE) == GLFW_PRESS) glfwSetWindowShouldClose(window, true); } //******************************************************************** // glfw: whenever the window size changed (by OS or user resize) this callback function executes void framebuffer_size_callback(GLFWwindow* window, int width, int height) { // make sure the viewport matches the new window dimensions; note that width and // height will be significantly larger than specified on retina displays. glViewport(0, 0, width, height); } As you see, about 200 lines of complicated code only for a simple triangle. 
      I don't know what parts are necessary for that output. And also, what the correct order of instructions for such an output or programs is, generally. That start point is too complex for a beginner of OpenGL like me and I don't know how to make the issue solved. What are your ideas please? What is the way to figure both the code and the whole program out correctly please?
      I wish I'd read a reference that would teach me OpenGL through a step-by-step method. 
  • Popular Now