• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Eric Shi

OpenGL
encounter weird problem when turn on the color blending.

24 posts in this topic

hi guys! I am a rookie in OpenGL, so, please do not laugh at me about my silly questions, aha.

 

here is the thing.

 

I need to turn on the color blending to deliver transparent effect. But weird thing happens, the front side, which is facing the light, looks not bad, like this:[attachment=22381:QQ??20140629143801.png]

 

but the back side looks awful, seems like some parts of surface are missing, latticed holes, like this:

[attachment=22382:QQ??20140629143822.png]

 

I tried to add another light on the back side, but both sides turn out to be awful with holes then.

 

Is it a issue related to lights? or texture? or depth test? because if I disable the GL_DEPTH_TEST, holes are gone, but the whole body looks awful, not the way I want it to be looked like.

 

Or it is something else? I even do not know where to get started to solve this problem, someone please help me!

 

 

 

 

For more details, now down to only one object in the scene.

 

This is the front side of the lung:

[attachment=22411:1.png]

 

This is the back side of the lung:

[attachment=22412:2.png]

 

 

BUT, if I change the light in the scene to pointing at the back side:

 

The front side:

[attachment=22413:3.png]

 

The back side:

[attachment=22414:4.png]

 

If I turn on two lights, one pointing at the front, the other pointing at the back, both sides of the object covered with meshes. If remove all lights in the scene, the object looks dark, which is obvious, and both sides of meshes remain. This makes me believe that the light is not the cause of the issue, right?

 

More angles of view, might help you guys to see the meshes more clearly:

[attachment=22415:333333.png]

 

[attachment=22416:QQ??20140630224309.png]

 

[attachment=22417:QQ??20140630224328.png]

Edited by eric_lie
0

Share this post


Link to post
Share on other sites

if you show us your code , we will see what is causing this trouble

we need to see something like this

 

all opengl calls [initialization and drawing)

then drawing modelitself

all glcalls after drawing

just show us your code, 

 

 

=====

try to set up only one light in the back and see if problem occurs for back of the model) (or set ambient to the same color like diffusion color)

 

its really hard to say what is causing this problem (it may be depth test, wrong order of face drawing, wrong normals for polygons etc)

0

Share this post


Link to post
Share on other sites

Sounds like you may have a culling problem.

 

Try turning on the depth buffer and setting cull mode to none and see what it looks like.

1

Share this post


Link to post
Share on other sites
 

if you show us your code , we will see what is causing this trouble
we need to see something like this
 
all opengl calls [initialization and drawing)
then drawing modelitself
all glcalls after drawing
just show us your code, 
 
 
=====
try to set up only one light in the back and see if problem occurs for back of the model) (or set ambient to the same color like diffusion color)
 
its really hard to say what is causing this problem (it may be depth test, wrong order of face drawing, wrong normals for polygons etc)

 


I set ambient to the same color like diffusion color, problem remains.

If I set a light from the back side, the back side of the model looks fine but the front face becomes the weird side instead, and if turn out all lights in the scene, then the whole model is covered with meshes. I thought the light can solve this problem someway somehow at first, but when I turn on all the lights, both in front and back, both sides of meshes remain.

So now I think may be the light is not the key point here.

My whole solution is a little bit complex, it takes time for me to the extract all OpenGL parts out, I will paste my codes here later.
0

Share this post


Link to post
Share on other sites

Sounds like you may have a culling problem.

 

Try turning on the depth buffer and setting cull mode to none and see what it looks like.

 

you mean glDisable(GL_CULL_FACE) ?

0

Share this post


Link to post
Share on other sites

The most common problem with transparency is that rendering order of faces does not match the requirements of the rendering algorithm. The simplest algorithm needs faces to be rendered in back to front order. This implies meshes to be ordered in dependence of the view, that meshes must not be concave (or else they need to be divided up if a free view is allowed), and meshes must not touch or overlap (or else z-figthing will occur).

 

As WiredCat mentioned we need more details, but also above the code level. What algorithm is used? How are the meshes organized?

 

When you have a problem with a complex scene, reducing complexity first helps to narrow down the cause. E.g. Does the problem occur even if only a single organ is rendered, ...

 

All organ models are 3DS files which generated by 3DS MAX, and be rendered into the scene from inside to outside, but the thing is, I am rendering a human body here, they can not be simply organized by inside and outside, or front and back, right? Just like you said, I need a free view, I need the whole body can be rotated so that you can see the body from any angle of view. So, at this point, organ A covers organ B (but you still can see organ B through organ A because of transparency), but if rotated around, organ B covers organ A instead. 

 

But if I disable the depth test, if organ A is rendered last, organ A is always covering organ B no matter which side you look at the model, then the whole body looks creepy and weird. It is totally not what I want. The funny part is, now meshes are gone.

 

What's more, if set all color alpha value to 1, which means no transparency at all, and enable the depth test back on, everything looks fine.

 

Like I said to WiredCat, I will paste codes up here after I review all over my solution.

 

Problem still remains even if only one organ in the scene.

 

thanks a lot!

Edited by eric_lie
0

Share this post


Link to post
Share on other sites
The following is not meant to turn you away, but since you described yourself as a "rookie in OpenGL", I think it should be pointed out to you to prevent any misconceptions:

OpenGL is a thin (most will argue still too thick) api towards the GPU, providing you with the most basic interface to render and shade triangles. You may have noticed, that it doesn't provide any means to load models or textures. The newer versions of OpenGL don't even support lighting out of the box. The idea is that you implement those things on top of OpenGL. This holds for transparency as well. Transparency is not as simple as enabling blending, you have to implement some form of algorithm for it on top of OpenGL. "Depth peeling", as suggested by L.Spiro, is on of those techniques. Splitting the model into parts, whose rendering order gets determined by the camera position (what haegarr suggested), is another one. There are quite a few more.

Using OpenGL (or, for that matter, OpenGL ES, Direct3D, Metal, Mantle, ...) means that you will have to write a lot of code around it,
as these are not intended to be full fledged rendering engines.
1

Share this post


Link to post
Share on other sites

so less details, but anyway try this:

divide whole model to different organs, then try to render every organ where you begin from those that are deep in the body and you end with drawing lungs

 

also glBlendFunc needs to be set properly (and sometimes glColor4f <- alpha value)

 

we also dont know if your textures have alpha channel but i guess they don't)

 

At first you need to draw parts that are not transparent and then you draw transparent organs in proper order.

 

 

if you manage to sort your faces you will get almost the same effect like disabling GL_DEPTH_TEST but you'll see properly displayed model

 

 

this also try to lower z_near value (in glFrustum) 

 

or scale in ex lungs so lungs faces wont touch other organs

 

 

 

=====================

anyway youll have to sort faces or that would be far way faster and easier -organs

 

 

this is what ahppens when you sort faces.

yu.jpg

 

 

 

 

one that i can say is i see there z fighting problem or wrong face order or wrong blending factors

Edited by WiredCat
1

Share this post


Link to post
Share on other sites

Looking at those images, I don't think sorting the meshes will help.

 

It looks like some of them actual wrap around the other sub meshes.

 

If that is the case then you have a much more complex problem.

 

I would suggest using volume rendering, but as you stated you a newb at OpenGL, that's going to be a big issue for you. You might be able to just grab an existing OpenGL volume renderer and use it without understanding it though.

 

Have a look at http://idav.ucdavis.edu/~okreylos/ResDev/VolVis/MainPage.html

 

If that seems too much for you, then see if you can split the meshes that cause problems into two, then sort them before rendering.

 

Hope this gives you some ideas.

0

Share this post


Link to post
Share on other sites

 

you mean glDisable(GL_CULL_FACE) ?

never diable cullling, instead reverse what "front face" is.

 

You have a well defined geometry (veru well :)) so:

 

gl.enable(this.m_pGL.CULL_FACE); // yes, I wish to cull
      gl.cullFace(this.m_pGL.BACK); // I want to cull back face
     gl .frontFace(this.m_pGL.CCW); // the front face is counter clock wise face

 

 

... so if after this you change fronts face difintion to

 

  gl .frontFace(this.m_pGL.CW);

 

you will establish front faces as the back faces, thus getting culled front faces "the back faces"

 

and back faces as front faces, being processed, with their vertex attributes in take

0

Share this post


Link to post
Share on other sites

mind yet, that if you shade back faces with general set up of lighting or other parameters, you may get stranger results, unless you realy understand the geometry with its attributes. (you cannot observe back faces through culled front faces, if you get what I mean- very metaphysical stuff)

0

Share this post


Link to post
Share on other sites

was this scaned from ultra sound device, or an arbitrary artificial model being?

 

It is just a 3DS model generated by 3DS MAX.

0

Share this post


Link to post
Share on other sites

so did you make any tests?

 

I am working on it. I am sorry to say that what you mentioned did not solve my problem.

 

Now it seems like not that easy to solve this issue. Some of you guys recommend me to resort all objects in a proper way, but even if only a single organ displayed in the scene, the problem still remains. And the thing is, in my case, each object is mapping to other stuff, resorting means changing everything. It does take time to solve this. Seems like a major problem to a rookie like me. 

 

I think Ohforf sake is right, Transparency is not as simple as enabling color blending, maybe this is the key point here!

 

Thanks anyway!smile.png smile.png

0

Share this post


Link to post
Share on other sites


Now it seems like not that easy to solve this issue. Some of you guys recommend me to resort all objects in a proper way, ...

Yep. Or else you try depth peeling as is suggested above by LS.

 


... but even if only a single organ displayed in the scene, the problem still remains. ...

Maybe this is because of the already mentioned concavity of the meshes? Question is, if you simplify the scene down to a single organ, do you have a chance to notice whether the problem occurs only if you look through a concavity. If so, then we are on the right track when suspecting the drawing order. A solution then will be to use sub-meshes.

 
But if concavity is not the cause, then we need to investigate further.
 


… And the thing is, in my case, each object is mapping to other stuff, resorting means changing everything. It does take time to solve this.  ...

This isn't a problem solely related to yours. It is common in game engines and elsewhere. And hence there is a solution :)

 

It is possible to have more than a single order on objects. Notice that it is recommended to have several organizing structures, one for each task to do. It is absolutely fine to have a logical organization of the objects, a spatial organization (if collision or proximity is an issue), a render order, and perhaps more. Don't stuck with the über scene graph approach, or you will be lost sooner or later!

 

For example, you iterate the scene description and detect all objects that need to be rendered. You insert each object into a list (which is emptied before the scene is iterated). After finishing, you sort the list by some criterion, in your case using the distance from the current camera. Object rendering then is done in the order given by the list. So rendering has no influence on other aspects of object organization, and nevertheless is done in the required way.

 


I think Ohforf sake is right, Transparency is not as simple as enabling color blending, maybe this is the key point here!

Absolutely. 

1

Share this post


Link to post
Share on other sites

 

Now it seems like not that easy to solve this issue. Some of you guys recommend me to resort all objects in a proper way, but even if only a single organ displayed in the scene, the problem still remains. 

 

can you upload somewhere this model i want to see it (one organ that is not properly displayed), maybe some face normals are reversed

Edited by WiredCat
0

Share this post


Link to post
Share on other sites

 

 

Now it seems like not that easy to solve this issue. Some of you guys recommend me to resort all objects in a proper way, but even if only a single organ displayed in the scene, the problem still remains. 

 

can you upload somewhere this model i want to see it (one organ that is not properly displayed), maybe some face normals are reversed

 

 

you mean the 3DS model? I am sure that all my 3DS model are accurate. 

 

Is there any possibility that when I render a 3DS model into an OpenGL scene, the normals are reversed by some inconspicuous mistakes somehow?

 

I upload more detail images, you can check it out.rolleyes.gif rolleyes.gif

0

Share this post


Link to post
Share on other sites


Yep. Or else you try depth peeling as is suggested above by LS.

 

I am reading those articles she gives to me, I think they would be helpful.

 


if you simplify the scene down to a single organ, do you have a chance to notice whether the problem occurs only if you look through a concavity.

 

I upload some detail images.

 


This isn't a problem solely related to yours. It is common in game engines and elsewhere. And hence there is a solution
 
It is possible to have more than a single order on objects. Notice that it is recommended to have several organizing structures, one for each task to do. It is absolutely fine to have a logical organization of the objects, a spatial organization (if collision or proximity is an issue), a render order, and perhaps more. Don't stuck with the über scene graph approach, or you will be lost sooner or later!
 
For example, you iterate the scene description and detect all objects that need to be rendered. You insert each object into a list (which is emptied before the scene is iterated). After finishing, you sort the list by some criterion, in your case using the distance from the current camera. Object rendering then is done in the order given by the list. So rendering has no influence on other aspects of object organization, and nevertheless is done in the required way.

 

This is quite inspiring, I will try it out! thanks!biggrin.png

0

Share this post


Link to post
Share on other sites

 

haegarr, on 30 Jun 2014 - 10:45 AM, said:

snapback.png


This isn't a probl.......he required way.

 

This is quite inspiring, I will try it out! thanks!biggrin.png

 

 

few post earilier you said that you already checked this solution.

You lie and post another images that say nothing.

I cut out of this topic,

0

Share this post


Link to post
Share on other sites

I am reading those articles she gives to me, I think they would be helpful.

She is actually a he. Just pointing out.

The problem you are seeing stems from the nature of your blend operation. Every surface slightly darkens what lies behind them, which allows the user to percieve an order of the surfaces, but also means that the order of mixing together the colors is important. There are other blend operations, like additive blending (glBlendFunc(GL_ONE, GL_ONE);) where the order doesn't matter. Can you get away with additive blending?

If not, mixing the colors of different surfaces seen on top of each other must be performed in the correct order: Mixing from back to front. As you already know, there are multiple, very different approaches, to achieving this. Some require you to write shaders, some only require you to do s.th. with your meshes, some work in all cases, some only if you can make certain geometric assumptions for your modell or allow for certain artifacts.

For example, consider a single convex object. If you render the back facing triangles first, their color will get blended with the background color. If you now render the front facing triangles, their color will get blended with the result of the previous blending operation and you get the correct result. So for a single convex object, you can get away with the simple trick of rendering the back faces first, and then the front faces which will, for each pixel, always be closer to the camera. Automatic and perfect back to front sorting. Sadly, you have more than one object, and those intestines are far from convex.

So exploiting convexity is out of the question, at least directly. Which leaves you with 2 questions: Do you want "perfect" results? Do you want to use shaders, or do you prefer a geometric solution?

Haegarr is suggesting a geometric solution: Cut your scene into pieces (or your objects into subobjects) and sort them back to front. But what pieces? Is it enough to cut them into convex pieces? The answer is no, just cutting them into convex pieces will not guarentee artifact free pictures. For example, assume that you make one subobject out of each triangle (a single triangle is convex). Then there are certain situations where you can not find an ordering for the triangles, that lead to a back to front rendering. For example, consider these 4 quads (also works with 3 triangles), where each quad has one end in front of the previous but behind the next.
  DD        BB
AAAAAAAAAAAABBAA
AAAAAAAAAAAABBAA
  DD        BB
  DD        BB
  DD        BB
  DD        BB
CCDDCCCCCCCCCCCC
CCDDCCCCCCCCCCCC
  DD        BB
For these, no correct rendering order exists. At least one of the quads has to be split. This is the point, where you have to decide, if you can live with the occasional artifact, or if you want to descend into the ugliness of splitting faces, and inserting them into a BSP-tree or s.th. similar.

If you go the geometric route, I would follow haegarr's advise: Automatically cut the objects into smaller, approximately convex and not elongated pieces, sort those pieces back to front then render each object twice, first by culling away the front faces (only rendering back faces) then by culling away the back faces (only rendering front faces). Then take a look at it and decide, if the remaining artifacts are acceptable, preferably while experimenting with different parameters for your cutting algorithm. However, keep in mind, that the geometric sorting approach can get very ugly, so if you have the compute power to spare, and the time to read further into OpenGL, then Depth-peeling and other "order independent transparency" techniques can be a reasonable choice.
0

Share this post


Link to post
Share on other sites


few post earilier you said that you already checked this solution.
You lie and post another images that say nothing.
I cut out of this topic,

 

I am really really sorry if I said or did something to upset you. If so, I have to say I definitely didn't mean it! there must be some misunderstanding between us.sad.png

I deeply appreciate your help here, why would I lie about anything?

 

 

 


try to set up only one light in the back and see if problem occurs for back of the model) (or set ambient to the same color like diffusion color)

 

I tried, problem does still remain. I already upload the images.

 


divide whole model to different organs, then try to render every organ where you begin from those that are deep in the body and you end with drawing lungs

 

I have not tried this yet, as I said before, my objects are all mapping other stuff, I need to figure it out how to do it in a proper way before I do any modification on models.

 


also glBlendFunc needs to be set properly (and sometimes glColor4f <- alpha value)

 

I tried a couple in glBlendFunc, and also tried change the alpha value. If I use a lower value, like 0.3, the meshes looks thinner but still exist.

 


we also dont know if your textures have alpha channel but i guess they don't)

 

Yes, my textures have no alpha channel, I got bitmap files, I just load the texture by gluBuild2DMipmaps. If there has any alpha channel in texture, I don't know where to modify it.

 


At first you need to draw parts that are not transparent and then you draw transparent organs in proper order.

 

This is still about resorting, I have to say again, I will try it, since modifying my model is a little bit complex, I prefer to try other way first. And I have no non-transparent objects in the scene.

 


this also try to lower z_near value (in glFrustum) 

 

I use gluPerspective, the near value is already 0.01f.

 


anyway youll have to sort faces or that would be far way faster and easier -organs
 
 
this is what ahppens when you sort faces.

 

I will try it later.

 

 

 

 

 

Again, I am really sorry.

0

Share this post


Link to post
Share on other sites

I use gluPerspective, the near value is already 0.01f.

A low near value is the main reason behind z-fighting (which manifests as flickering between objects near each other).
Always use the highest value possible that does not cause visual artifacts with near-clipping.
If the far plane is at 1,000.0 for example then a good near might be 10.0 or 5.0.


L. Spiro
0

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  
Followers 0

  • Similar Content

    • By Solid_Spy
      Hello, I have been working on SH Irradiance map rendering, and I have been using a GLSL pixel shader to render SH irradiance to 2D irradiance maps for my static objects. I already have it working with 9 3D textures so far for the first 9 SH functions.
      In my GLSL shader, I have to send in 9 SH Coefficient 3D Texures that use RGBA8 as a pixel format. RGB being used for the coefficients for red, green, and blue, and the A for checking if the voxel is in use (for the 3D texture solidification shader to prevent bleeding).
      My problem is, I want to knock this number of textures down to something like 4 or 5. Getting even lower would be a godsend. This is because I eventually plan on adding more SH Coefficient 3D Textures for other parts of the game map (such as inside rooms, as opposed to the outside), to circumvent irradiance probe bleeding between rooms separated by walls. I don't want to reach the 32 texture limit too soon. Also, I figure that it would be a LOT faster.
      Is there a way I could, say, store 2 sets of SH Coefficients for 2 SH functions inside a texture with RGBA16 pixels? If so, how would I extract them from inside GLSL? Let me know if you have any suggestions ^^.
    • By DaniDesu
      #include "MyEngine.h" int main() { MyEngine myEngine; myEngine.run(); return 0; } MyEngine.h
      #pragma once #include "MyWindow.h" #include "MyShaders.h" #include "MyShapes.h" class MyEngine { private: GLFWwindow * myWindowHandle; MyWindow * myWindow; public: MyEngine(); ~MyEngine(); void run(); }; MyEngine.cpp
      #include "MyEngine.h" MyEngine::MyEngine() { MyWindow myWindow(800, 600, "My Game Engine"); this->myWindow = &myWindow; myWindow.createWindow(); this->myWindowHandle = myWindow.getWindowHandle(); // Load all OpenGL function pointers for use gladLoadGLLoader((GLADloadproc)glfwGetProcAddress); } MyEngine::~MyEngine() { this->myWindow->destroyWindow(); } void MyEngine::run() { MyShaders myShaders("VertexShader.glsl", "FragmentShader.glsl"); MyShapes myShapes; GLuint vertexArrayObjectHandle; float coordinates[] = { 0.5f, 0.5f, 0.0f, 0.5f, -0.5f, 0.0f, -0.5f, 0.5f, 0.0f }; vertexArrayObjectHandle = myShapes.drawTriangle(coordinates); while (!glfwWindowShouldClose(this->myWindowHandle)) { glClearColor(0.5f, 0.5f, 0.5f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Draw something glUseProgram(myShaders.getShaderProgram()); glBindVertexArray(vertexArrayObjectHandle); glDrawArrays(GL_TRIANGLES, 0, 3); glfwSwapBuffers(this->myWindowHandle); glfwPollEvents(); } } MyShaders.h
      #pragma once #include <glad\glad.h> #include <GLFW\glfw3.h> #include "MyFileHandler.h" class MyShaders { private: const char * vertexShaderFileName; const char * fragmentShaderFileName; const char * vertexShaderCode; const char * fragmentShaderCode; GLuint vertexShaderHandle; GLuint fragmentShaderHandle; GLuint shaderProgram; void compileShaders(); public: MyShaders(const char * vertexShaderFileName, const char * fragmentShaderFileName); ~MyShaders(); GLuint getShaderProgram(); const char * getVertexShaderCode(); const char * getFragmentShaderCode(); }; MyShaders.cpp
      #include "MyShaders.h" MyShaders::MyShaders(const char * vertexShaderFileName, const char * fragmentShaderFileName) { this->vertexShaderFileName = vertexShaderFileName; this->fragmentShaderFileName = fragmentShaderFileName; // Load shaders from files MyFileHandler myVertexShaderFileHandler(this->vertexShaderFileName); this->vertexShaderCode = myVertexShaderFileHandler.readFile(); MyFileHandler myFragmentShaderFileHandler(this->fragmentShaderFileName); this->fragmentShaderCode = myFragmentShaderFileHandler.readFile(); // Compile shaders this->compileShaders(); } MyShaders::~MyShaders() { } void MyShaders::compileShaders() { this->vertexShaderHandle = glCreateShader(GL_VERTEX_SHADER); this->fragmentShaderHandle = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(this->vertexShaderHandle, 1, &(this->vertexShaderCode), NULL); glShaderSource(this->fragmentShaderHandle, 1, &(this->fragmentShaderCode), NULL); glCompileShader(this->vertexShaderHandle); glCompileShader(this->fragmentShaderHandle); this->shaderProgram = glCreateProgram(); glAttachShader(this->shaderProgram, this->vertexShaderHandle); glAttachShader(this->shaderProgram, this->fragmentShaderHandle); glLinkProgram(this->shaderProgram); return; } GLuint MyShaders::getShaderProgram() { return this->shaderProgram; } const char * MyShaders::getVertexShaderCode() { return this->vertexShaderCode; } const char * MyShaders::getFragmentShaderCode() { return this->fragmentShaderCode; } MyWindow.h
      #pragma once #include <glad\glad.h> #include <GLFW\glfw3.h> class MyWindow { private: GLFWwindow * windowHandle; int windowWidth; int windowHeight; const char * windowTitle; public: MyWindow(int windowWidth, int windowHeight, const char * windowTitle); ~MyWindow(); GLFWwindow * getWindowHandle(); void createWindow(); void MyWindow::destroyWindow(); }; MyWindow.cpp
      #include "MyWindow.h" MyWindow::MyWindow(int windowWidth, int windowHeight, const char * windowTitle) { this->windowHandle = NULL; this->windowWidth = windowWidth; this->windowWidth = windowWidth; this->windowHeight = windowHeight; this->windowTitle = windowTitle; glfwInit(); } MyWindow::~MyWindow() { } GLFWwindow * MyWindow::getWindowHandle() { return this->windowHandle; } void MyWindow::createWindow() { // Use OpenGL 3.3 and GLSL 3.3 glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3); glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3); // Limit backwards compatibility glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // Prevent resizing window glfwWindowHint(GLFW_RESIZABLE, GL_FALSE); // Create window this->windowHandle = glfwCreateWindow(this->windowWidth, this->windowHeight, this->windowTitle, NULL, NULL); glfwMakeContextCurrent(this->windowHandle); } void MyWindow::destroyWindow() { glfwTerminate(); } MyShapes.h
      #pragma once #include <glad\glad.h> #include <GLFW\glfw3.h> class MyShapes { public: MyShapes(); ~MyShapes(); GLuint & drawTriangle(float coordinates[]); }; MyShapes.cpp
      #include "MyShapes.h" MyShapes::MyShapes() { } MyShapes::~MyShapes() { } GLuint & MyShapes::drawTriangle(float coordinates[]) { GLuint vertexBufferObject{}; GLuint vertexArrayObject{}; // Create a VAO glGenVertexArrays(1, &vertexArrayObject); glBindVertexArray(vertexArrayObject); // Send vertices to the GPU glGenBuffers(1, &vertexBufferObject); glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObject); glBufferData(GL_ARRAY_BUFFER, sizeof(coordinates), coordinates, GL_STATIC_DRAW); // Dertermine the interpretation of the array buffer glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3*sizeof(float), (void *)0); glEnableVertexAttribArray(0); // Unbind the buffers glBindBuffer(GL_ARRAY_BUFFER, 0); glBindVertexArray(0); return vertexArrayObject; } MyFileHandler.h
      #pragma once #include <cstdio> #include <cstdlib> class MyFileHandler { private: const char * fileName; unsigned long fileSize; void setFileSize(); public: MyFileHandler(const char * fileName); ~MyFileHandler(); unsigned long getFileSize(); const char * readFile(); }; MyFileHandler.cpp
      #include "MyFileHandler.h" MyFileHandler::MyFileHandler(const char * fileName) { this->fileName = fileName; this->setFileSize(); } MyFileHandler::~MyFileHandler() { } void MyFileHandler::setFileSize() { FILE * fileHandle = NULL; fopen_s(&fileHandle, this->fileName, "rb"); fseek(fileHandle, 0L, SEEK_END); this->fileSize = ftell(fileHandle); rewind(fileHandle); fclose(fileHandle); return; } unsigned long MyFileHandler::getFileSize() { return (this->fileSize); } const char * MyFileHandler::readFile() { char * buffer = (char *)malloc((this->fileSize)+1); FILE * fileHandle = NULL; fopen_s(&fileHandle, this->fileName, "rb"); fread(buffer, this->fileSize, sizeof(char), fileHandle); fclose(fileHandle); buffer[this->fileSize] = '\0'; return buffer; } VertexShader.glsl
      #version 330 core layout (location = 0) vec3 VertexPositions; void main() { gl_Position = vec4(VertexPositions, 1.0f); } FragmentShader.glsl
      #version 330 core out vec4 FragmentColor; void main() { FragmentColor = vec4(1.0f, 0.0f, 0.0f, 1.0f); } I am attempting to create a simple engine/graphics utility using some object-oriented paradigms. My first goal is to get some output from my engine, namely, a simple red triangle.
      For this goal, the MyShapes class will be responsible for defining shapes such as triangles, polygons etc. Currently, there is only a drawTriangle() method implemented, because I first wanted to see whether it works or not before attempting to code other shape drawing methods.
      The constructor of the MyEngine class creates a GLFW window (GLAD is also initialized here to load all OpenGL functionality), and the myEngine.run() method in Main.cpp is responsible for firing up the engine. In this run() method, the shaders get loaded from files via the help of my FileHandler class. The vertices for the triangle are processed by the myShapes.drawTriangle() method where a vertex array object, a vertex buffer object and vertrex attributes are set for this purpose.
      The while loop in the run() method should be outputting me the desired red triangle, but all I get is a grey window area. Why?
      Note: The shaders are compiling and linking without any errors.
      (Note: I am aware that this code is not using any good software engineering practices (e.g. exceptions, error handling). I am planning to implement them later, once I get the hang of OpenGL.)

       
    • By KarimIO
      EDIT: I thought this was restricted to Attribute-Created GL contexts, but it isn't, so I rewrote the post.
      Hey guys, whenever I call SwapBuffers(hDC), I get a crash, and I get a "Too many posts were made to a semaphore." from Windows as I call SwapBuffers. What could be the cause of this?
      Update: No crash occurs if I don't draw, just clear and swap.
      static PIXELFORMATDESCRIPTOR pfd = // pfd Tells Windows How We Want Things To Be { sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor 1, // Version Number PFD_DRAW_TO_WINDOW | // Format Must Support Window PFD_SUPPORT_OPENGL | // Format Must Support OpenGL PFD_DOUBLEBUFFER, // Must Support Double Buffering PFD_TYPE_RGBA, // Request An RGBA Format 32, // Select Our Color Depth 0, 0, 0, 0, 0, 0, // Color Bits Ignored 0, // No Alpha Buffer 0, // Shift Bit Ignored 0, // No Accumulation Buffer 0, 0, 0, 0, // Accumulation Bits Ignored 24, // 24Bit Z-Buffer (Depth Buffer) 0, // No Stencil Buffer 0, // No Auxiliary Buffer PFD_MAIN_PLANE, // Main Drawing Layer 0, // Reserved 0, 0, 0 // Layer Masks Ignored }; if (!(hDC = GetDC(windowHandle))) return false; unsigned int PixelFormat; if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd))) return false; if (!SetPixelFormat(hDC, PixelFormat, &pfd)) return false; hRC = wglCreateContext(hDC); if (!hRC) { std::cout << "wglCreateContext Failed!\n"; return false; } if (wglMakeCurrent(hDC, hRC) == NULL) { std::cout << "Make Context Current Second Failed!\n"; return false; } ... // OGL Buffer Initialization glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT); glBindVertexArray(vao); glUseProgram(myprogram); glDrawElements(GL_TRIANGLES, indexCount, GL_UNSIGNED_SHORT, (void *)indexStart); SwapBuffers(GetDC(window_handle));  
    • By Tchom
      Hey devs!
       
      I've been working on a OpenGL ES 2.0 android engine and I have begun implementing some simple (point) lighting. I had something fairly simple working, so I tried to get fancy and added color-tinting light. And it works great... with only one or two lights. Any more than that, the application drops about 15 frames per light added (my ideal is at least 4 or 5). I know implementing lighting is expensive, I just didn't think it was that expensive. I'm fairly new to the world of OpenGL and GLSL, so there is a good chance I've written some crappy shader code. If anyone had any feedback or tips on how I can optimize this code, please let me know.
       
      Vertex Shader
      uniform mat4 u_MVPMatrix; uniform mat4 u_MVMatrix; attribute vec4 a_Position; attribute vec3 a_Normal; attribute vec2 a_TexCoordinate; varying vec3 v_Position; varying vec3 v_Normal; varying vec2 v_TexCoordinate; void main() { v_Position = vec3(u_MVMatrix * a_Position); v_TexCoordinate = a_TexCoordinate; v_Normal = vec3(u_MVMatrix * vec4(a_Normal, 0.0)); gl_Position = u_MVPMatrix * a_Position; } Fragment Shader
      precision mediump float; uniform vec4 u_LightPos["+numLights+"]; uniform vec4 u_LightColours["+numLights+"]; uniform float u_LightPower["+numLights+"]; uniform sampler2D u_Texture; varying vec3 v_Position; varying vec3 v_Normal; varying vec2 v_TexCoordinate; void main() { gl_FragColor = (texture2D(u_Texture, v_TexCoordinate)); float diffuse = 0.0; vec4 colourSum = vec4(1.0); for (int i = 0; i < "+numLights+"; i++) { vec3 toPointLight = vec3(u_LightPos[i]); float distance = length(toPointLight - v_Position); vec3 lightVector = normalize(toPointLight - v_Position); float diffuseDiff = 0.0; // The diffuse difference contributed from current light diffuseDiff = max(dot(v_Normal, lightVector), 0.0); diffuseDiff = diffuseDiff * (1.0 / (1.0 + ((1.0-u_LightPower[i])* distance * distance))); //Determine attenuatio diffuse += diffuseDiff; gl_FragColor.rgb *= vec3(1.0) / ((vec3(1.0) + ((vec3(1.0) - vec3(u_LightColours[i]))*diffuseDiff))); //The expensive part } diffuse += 0.1; //Add ambient light gl_FragColor.rgb *= diffuse; } Am I making any rookie mistakes? Or am I just being unrealistic about what I can do? Thanks in advance
    • By yahiko00
      Hi,
      Not sure to post at the right place, if not, please forgive me...
      For a game project I am working on, I would like to implement a 2D starfield as a background.
      I do not want to deal with static tiles, since I plan to slowly animate the starfield. So, I am trying to figure out how to generate a random starfield for the entire map.
      I feel that using a uniform distribution for the stars will not do the trick. Instead I would like something similar to the screenshot below, taken from the game Star Wars: Empire At War (all credits to Lucasfilm, Disney, and so on...).

      Is there someone who could have an idea of a distribution which could result in such a starfield?
      Any insight would be appreciated
  • Popular Now