• 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
Jossos

OpenGL
A couple of small problems

8 posts in this topic

Hi,

 

I'm having a few issues with my application, and have a few queries. If you can help with any of them it would be greatly appreciated (These were all problems I gathered from not being able to find a solution on google).

 

I will list them here tl;dr version - maybe you can see what you might know:

 

1. Mipmapping isn't working

2. blending textures/quads to make a smooth transition between separate textures - not sure how to approach this

3. Being able layer 2 textures, or one texture with transparent parts showing a unique color (need multiple possible colors for a single object)

4. Importing Maya/3dsMax animation - More looking for guidance - will not attempt this in the next few months, but maybe after.

 

 

(Not OpenGL related, but I don't want to make too many topics - let me know if I should put these in a seperate thread)

 

5. How to determine if a chunk is in camera view - i.e. what to not render.

6. RTS drag selection - I know how to do one selection (with unit represented as a sphere and raysphering with the mouse), but how to drag a box like in all rts games, and have all units within that selected? I'm sure the math is really simple but I can't think of it.

 

 

 

Ok here are the questions in full:

__________________________________________________________________

 

 

1. Firstly, when I load a texture with mipmapping it just gives me a plain white texture (with value of -1). If I don't use mipmapping (enter mipmap as false), the texture renders fine, but looks like crap a long distance away.

 

My code is here:

int GRAPHICS::LoadTexture(const char *filename, bool mipmap, bool repeat)
{
	glEnable(GL_TEXTURE_2D);
	unsigned int id;
	glGenTextures(1, &id);
	SDL_Surface* img = IMG_Load(filename);

	if (img == NULL) 
	{
		OutputDebugString("\"");
		OutputDebugString(filename);
		OutputDebugString("\" failed to load.\n");
		return -1;
	}

	SDL_PixelFormat form = {NULL, 32, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0xff000000, 0x00ff0000, 0x0000ff00, 0x000000ff, 0, 255};
	SDL_Surface *img2 = SDL_ConvertSurface(img, &form, SDL_SWSURFACE);

	if (img2 == NULL)
	{
		OutputDebugString("\"");
		OutputDebugString(filename);
		OutputDebugString("\" failed to load. img2 == -1\n");
		return -1;
	}

	glBindTexture(GL_TEXTURE_2D, id);

	glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MAG_FILTER,GL_LINEAR);

	// Mipmapping
	if (mipmap)
		gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, img2->w, img2->h, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, img2->pixels);
	else
		glTexImage2D(GL_TEXTURE_2D,0,GL_RGBA,img2->w,img2->h,0,GL_RGBA,GL_UNSIGNED_INT_8_8_8_8,img2->pixels);

	// Min Filter
	if (mipmap)
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR_MIPMAP_NEAREST);
	else
		glTexParameteri(GL_TEXTURE_2D,GL_TEXTURE_MIN_FILTER,GL_LINEAR);

	// Repeat
	glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, repeat ? GL_REPEAT : GL_CLAMP );
	glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, repeat ? GL_REPEAT : GL_CLAMP );

	SDL_FreeSurface(img);
	SDL_FreeSurface(img2);

	return id;
}

Here's my Init function if you want to know that:

void GRAPHICS::Init(int width, int height, bool fullscreen)
{
	SDL_Init(SDL_INIT_EVERYTHING);
	glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
	Refresh(width, height, 45.0f, fullscreen);
	glMatrixMode(GL_MODELVIEW);
	glEnable(GL_DEPTH_TEST);
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);	// Really Nice Perspective Calculations
	glEnable(GL_TEXTURE_2D);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glEnable(GL_NORMALIZE);
	glEnable(GL_COLOR_MATERIAL);

	glLoadIdentity();
}

And the refresh function:

void GRAPHICS::Refresh(int width, int height, float fov, bool fullscreen)
{
	if (fullscreen)
		SDL_SetVideoMode(width, height, 32, SDL_SWSURFACE | SDL_OPENGL | SDL_FULLSCREEN);
	else
		SDL_SetVideoMode(width, height, 32, SDL_SWSURFACE | SDL_OPENGL);
	glViewport(0, 0, width, height);
	glMatrixMode(GL_PROJECTION);
		glLoadIdentity();
		gluPerspective(fov, ((float)width*2) / (float)height, 0.1, 500.0);
}

2. Secondly, I need to have my textures blend together. I can't really describe it with words so I will post an image:

 

Jos_Game_Scr_Shot.jpg

 

Left is my game so far, you can see the tiles don't blend, on the right is empire earth, the kind of thing I'm wanting to do. It's early enough that I can restructure my tile system. but I am not wanting to make a unique texture for blending every combination of tiles (coz there's a tonne if I want many variants of the tiles)

 

 

 

3. Thirdly, I want part of a texture to change color. I'm wanting to make an RTS - meaning many players can use the same units, but each unit needs to have part of their texture be a different colour. I do not know how to do this. I want to only need to load each object once. Look at right image above, see the blue on the little man, you can make this color anything in that game. That is what I am wanting.

 

What I was thinking with this is that If I could somehow just apply first a color (like blue or red), and on top of that apply the normal texture, and that texture's transparent parts will show through the color underneath. (For example, I could do glColor3f(1.0f, 0.0f, 0.0f) then glCallList of the object)

 

 

 

4. Fourthly, this is not so urgent, as I don't think I will implement this anytime soon, but is there a way to export animation the same way I export obj files? obj files are so good because they display each vertex, and I just read this data in. That's how I got the trees and the white dude in my scene, but I can't bring in any animation unless I export each frame as an object - something I'm not wanting to do.

 

I use Maya/3dsMax, any guidance is appreciated.

 

 

 

5. In my game, I have the world made of chunks, and each chunk contains 4x4 reference to tiles(I think it's better than just tiles on their own, maybe not feel free to give your opinion - I'm sure they might be helpful) - Is there a way to determine if one of these areas is not in view? At the moment I just draw everything, even if I can only see a few tiles.

 

 

 

 

6. RTS drag selection - Most info given in tl;dr -  I already have a way to get opengl positions from the mouse (close and far to cast ray in right direction), I'm just not sure of how to draw a box (which would be 2D for the player) and have it know everything inside. I mean, the camera can rotate, then might start dragging from a spot, and drag across many screens, making the start point actually off screen. So many problems, not sure how to solve.

 

 

 

Any help/or suggestions with any of these things will be greatly appreciated. I will tend to this thread when I'm not working. I am not a good programmer, so some of these might be really obvious, and I'm sorry if that is so.

1

Share this post


Link to post
Share on other sites

Maybe I can aswer to question #1:

 

gluBuild2DMipmaps will create the mipmaps, not send the actual texture data to the gpu. In the if(mipmap) you have to do both glTexImage2D and gluBuild2DMipmaps.

 

Am I wrong?

Edited by arka80
0

Share this post


Link to post
Share on other sites

gluBuild2DMipmaps calls glTexImage2D itself as it needs to upload each level.

 

The only thing that comes to mind is the glut function doesnt like GL_UNSIGNED_INT_8_8_8_8

 

Looking at my old code I dont otherwise see why the OP's code doesnt work.

 

I also notice that I have switched to using glGenerateMipmap perhaps the OP could try that?

 

As for Q5: Google for occlusion culling

0

Share this post


Link to post
Share on other sites

1. Do you mean you're returning -1 (error loading img or img2), you get -1 as a texture ID, or you have 0xFF in every byte of data in the resulting image? Or something else? Have you checked for errors with glGetError()?

 

2. Multitexturing. At least it looks like that's what the Empire Earth screenshot you provided is doing.

 

3. You can use different uv coordinates if it's viable and easy to accomplish, then just point to a different subtexture for the different player color. You can also point to an altogether different texture. Those two should be very obvious how they work. You can also pass in a uniform to the shader and do the same modify in the shader. I'm sure there are other approaches as well, but those come to mind at the moment. Passing in a "playerNumber" and doing calculations in the shader usually reduces vertex count and texture count and binding changes and such over doing the same in source code. (p.s. don't use glColor. Video cards can handle textures, and textures give you much better flexibility.)

 

4. You need to export animations in whatever format that is accepted by the library you use in your code to import the animations. If you hand-coded the obj importing code, you might try just using a library. You can obviously hand-code more complicated import code, but you could also spend that time coding something unique and valuable.

 

5. If you're using a grid, it's very easy to know which tiles are visible. You can use projection and camera matrices to know which coordinates are on the screen, and model matrix will tell you where the center of each grid square is. If your data structures are set up reasonably, you can skip the model matrix and just calculate the range of tiles visible since they're all predictable sizes and you should know which tile is at the origin (model matrix with no transform).

 

6. If you are able to calculate a 3D coordinate from the click already, just record both the start and stop coordinates. Maybe you're getting tripped up if you're recording the coordinates in screen space?

 

I know the answers are brief, but the questions could have really long answers if I went into too much detail for each. If some answer didn't make sense or you're still getting tripped up on something, that's why you're allowed to post more than once =)

0

Share this post


Link to post
Share on other sites

Stuff

 

Thanks so much, really awesome answers. Ill respond to each part.

 

1. The funciton returns -1, meaning the texture didn't load properly along the way

 

2. Multitexturing - will look into that

 

3. Hmm I would really like to just be able to put a texture over a color and have transparencies show through. that would be the cleanest way but stuff I don't understand always seems simple from afar.

 

4. Well then I probably will use a library in future. Might get my hands dirty with the 3ds max library if it's royalty free.

 

5. Thanks empirical2, I will search that. To richardurich: That stuff seems a bit confusing to me. What terms should I search for to found out how to do all this?

 

6. Might look into this later.

 

Thanks for answers really appreciate it.

0

Share this post


Link to post
Share on other sites

1. If it's returning -1 from IMG_Load() failing or SDL_ConvertSurface() failing, you're definitely leaving out some relevant code.

 

3. You can definitely color the texture and use transparency, but you can also texture the polygon with your color (allowing patterns and such instead of just flat colors) and then use transparency in the exact same way for a 2nd texture. Maybe once you check out multitexturing it will make more sense what options are available. If you already know how to do the coloring thing, just do that until later. It's easy enough to change after the fact since you'd just add a texture. I was just thinking it would be easier to stick with a single thing (textures), especially since you already need to learn multitexturing for the blending you want in 2.

 

5. For grids, let's take a simple example where every tile is 10x10 pixels, and your screen is 800x600 (0,0 corner and 800,600 opposite corner). So you know you're displaying 80x60 tiles. Now you use the projection matrix to determine where the origin gets transformed. Let's say you discover that is at 1200,-100 in pixel terms (off-screen). And let's assume tile[200][200] is the one at the origin, and that tile array is 400x400 tiles total. So 1200 (x of origin tile) / 10 (pixel width per tile) = 120. So tile[200-120][*] is at x=0. For Y, -100/10=-10. That means tile[80][210] starts at 0,0 pixel coordinate. Since you display 80x60 tiles, you'll be displaying tile[80][210] through tile[160][270]. (note: the math described is conflating 1-base/0-base counting constantly and ignoring a few things, but hopefully you get the basic idea)

 

If you don't understand how model, view, projection matrices work, poke around for tutorials on that until you find one that clicks. If you don't understand how the math works for isometric, there are tutorials on that too. If my example just plain didn't make sense, hopefully someone else can help out with the explanation since I know I suck at explaining math.

0

Share this post


Link to post
Share on other sites

I'm having a lot of trouble with #2. I need the texture to blend with the 8 surrounding texture, and I have no idea how to do this. I don't think multitexturing can this many textures. Really needing help with this one

0

Share this post


Link to post
Share on other sites

I'm having a lot of trouble with #2. I need the texture to blend with the 8 surrounding texture, and I have no idea how to do this. I don't think multitexturing can this many textures. Really needing help with this one

You can definitely account for 8 surrounding textures in your blending. It's still just one texture, just 8 pieces of data telling you which part of the texture was used in the surrounding tiles.

 

But let's look at this in a simpler and more explicit way. Let's say you have only 2 types of terrain: grass (G) and dirt (D). Let's say you have the following 9 bytes of data and are working on rendering the middle tile:

GGG

GDD

DDD

 

We'll assume 100x100 pixel tiles so they're big enough to see the effects. Let's use a static dropoff instead of quadratic so the math is easier: (sizeOfInfluence - distanceFromEdge)/sizeOfInfluence. Here's simple code:

sizeOfInfluence = 25;//blend for 25 pixels out of the 100, so the left 25% of the tile will have bleed-in from the left texture,
                     //middle 50% is 100% our own tile, right 25% bleeds with right texture, etc.
for (edge=0;edge<4;edge++){
  if ((distanceFromEdge[edge] >= 0) & (distanceFromEdge[edge] < sizeOfInfluence)){//only blend if we're in the area of influence
    blendIntensity = (sizeOfInfluence - distanceFromEdge[edge]) / sizeOfInfluence;
    blendAmount += blendIntensity * texture[edge];
  }
}

If you implement that, you'll notice the corners don't look nice. The upper-left is adding G+G at 100% each, so we're not really getting green any more. We can fix that by figuring out total blend intensity. Basically, this would be the alpha channel if we were making an overlay for blending the relies on transparency.

sizeOfInfluence = 25;
for (edge=0;edge<4;edge++){
  if ((distanceFromEdge[edge] >= 0) & (distanceFromEdge[edge] < sizeOfInfluence)){
    blendIntensity = (sizeOfInfluence - distanceFromEdge[edge]) / sizeOfInfluence;
    totalIntensity += blendIntensity;
    blendAmount += blendIntensity * texture[edge];
  }
}
if (totalIntensity > 100%){
  blendAmount = blendAmount / (totalIntensity / 100%);
  totalIntensity = 100%;
}
finalColor = blendAmount + texture[currentTile] * (100% - totalIntensity);

Now we're looking better, but the upper-right corner is wrong since we basically want a horizontal line of grass and want to ignore the dirt on the right side. In the Empire Earth screenshot, it looks like they solve this by also including the corner tile in the calculation so

GD

DD

winds up with grass on the diagonal D even though it doesn't directly border grass, and they seem to only blend on grass (not dirt). You can also trail off before the edge, which the lower-left corner should show the general concept. Remember all of this is using a linear approach, so you can get much better effects using more complicated approaches.

 

Warning! I wrote the above code in this reply while trying to use algorithms and terminology I think are more friendly to learning. I didn't copy/paste it from real code nor type it into a compiler. It will have bugs and things I left out. Hopefully the concepts you need to learn still got through.

0

Share this post


Link to post
Share on other sites

I'm having a lot of trouble with #2. I need the texture to blend with the 8 surrounding texture, and I have no idea how to do this. I don't think multitexturing can this many textures. Really needing help with this one

A possible implementation for #2 feature.

 

Need to render twice.

 

1: At first time rendering, output depth to a texture.

2: In fragment shader of second time rendering, check the depth to see if it belong to an edge. (like a jump of depth )

3: If this pixel belong to an edge, do a low-pass filter with texture from its own tile and neighboring tile.

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