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

OpenGL
Texture Loading "Per Triangle" versus all of the Triangles Called with glDrawElements

12 posts in this topic

Hello,

 

I have this weird problem that I assume is really simple to fix but I can't figure it out. Basically my textures are being loaded per "triangle" when I use them in OpenGL.

 

Thank you in advance for any assistance you can provide.

 

Here is how I am loading them into OpenGL: 

glGenTextures(1, &TextureObject_ID);   // section being edited by CKoeber to pull in material files
		glActiveTexture(GL_TEXTURE0 + 1);
		glBindTexture(GL_TEXTURE_2D, TextureObject_ID);
		GLsizei iFormat = BytesPerPixel == 24 ? GL_BGR : BytesPerPixel == 8 ? GL_LUMINANCE : 0;
		GLsizei iInternalFormat = BytesPerPixel == 24 ? GL_RGB : GL_DEPTH_COMPONENT;
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
		             WidthOfTexture, HeightOfTexture, 0, iFormat,
		             GL_UNSIGNED_BYTE, bytesDataPointer);
		glGenerateMipmap(GL_TEXTURE_2D);
		FreeImage_Unload(loadedImage);
		glGenSamplers(1, &TextureSamplerObject_ID);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
		setFiltering(TEXTURE_FILTER_MAG_BILINEAR, TEXTURE_FILTER_MIN_BILINEAR_MIPMAP);
		HasMipsBeenGenerated = true;
		glActiveTexture(GL_TEXTURE0 + 0);
		glBindTexture(GL_TEXTURE_2D, NULL);

I am sending my UV coordinates to OpenGL like so:

		glBufferSubData(GL_ARRAY_BUFFER, UVOffset, UVBufferSize, UVs);
		glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 0, 0);
		glEnableVertexAttribArray(2);

I am buffering my vertices and normals in similar fashion as I am drawing fine.

 

Also,

 

Here is the relevant section in the graphics card:

/*

In Fragment Shader...

*/

uniform sampler2D MainTextureSampler; 
in vec2 TextureCoordinates;
out vec4 finalColor;

void Main() {

    vec4 MaterialTextureColor = texture2D(MainTextureSampler, TextureCoordinates);
    finalColor = MaterialTextureColor;

}

Below is an example image:

 

Texture_Per_Triangle.png

0

Share this post


Link to post
Share on other sites

This looks pretty much like broken tex coordinates for this triangle.

 

Do you generate the texture coordinates yourself or are you loading them from a model?

If you generate them your self, check that corresponding vertices in each triangle have the same texture coordinates assigned.

 

If the vertexbuffer of this quad looks like this  [V1/V2/V3/V1/V3/V4]

make sure the buffer for the texture coordinates is layouted the same way [T1/T2/T3/T1/T3/T4]

 

 

0

Share this post


Link to post
Share on other sites

This looks pretty much like broken tex coordinates for this triangle.

 

Do you generate the texture coordinates yourself or are you loading them from a model?

If you generate them your self, check that corresponding vertices in each triangle have the same texture coordinates assigned.

 

If the vertexbuffer of this quad looks like this  [V1/V2/V3/V1/V3/V4]

make sure the buffer for the texture coordinates is layouted the same way [T1/T2/T3/T1/T3/T4]

 

Thanks,

 

I am loading the UVs from a file. I was wondering how to generate them myself but I want to use them from the file if I can.

 

If I have to, how would I generate them?

 

Thank you for your time.

0

Share this post


Link to post
Share on other sites

Then maybe it would help to post the code where you are loading the file (what format?) and you draw call to open gl.

 

It's just a hunch, but if you have back face culling disabled and use the wrong winding order of faces, it might just generate this effect.

maybe playing a little around with glFrontFace() and glCullFace() will help.

 

 

If I have to, how would I generate them?

 

Don't even think about that then biggrin.png

0

Share this post


Link to post
Share on other sites

Then maybe it would help to post the code where you are loading the file (what format?) and you draw call to open gl.


Here is the way I am loading the texture (using FreeImage and JPEG files):

FIBITMAP *loadedImage = NULL;
		FREE_IMAGE_FORMAT CurrentFormat = FIF_UNKNOWN;
		CurrentFormat = FreeImage_GetFileType(MaterialFile.c_str(), 0);

		if (CurrentFormat == FIF_UNKNOWN) {
			FREE_IMAGE_FORMAT CurrentFormat = FreeImage_GetFIFFromFilename(MaterialFile.c_str());
		}

		if (CurrentFormat == FIF_UNKNOWN) {
			return false;
		}

		if (FreeImage_FIFSupportsReading(CurrentFormat)) {
			loadedImage = FreeImage_Load(CurrentFormat, MaterialFile.c_str());
		}

		if (!loadedImage) {
			return false;
		}

		BYTE* bytesDataPointer = FreeImage_GetBits(loadedImage);
		WidthOfTexture = FreeImage_GetWidth(loadedImage);
		HeightOfTexture = FreeImage_GetHeight(loadedImage);
		BytesPerPixel = FreeImage_GetBPP(loadedImage);

		if (WidthOfTexture == 0 || HeightOfTexture == 0 || BytesPerPixel == 0) {
			return false;
		}

		glGenTextures(1, &TextureObject_ID);   // section being edited by CKoeber to pull in material files
		glActiveTexture(GL_TEXTURE0 + 1);
		glBindTexture(GL_TEXTURE_2D, TextureObject_ID);
		GLsizei iFormat = BytesPerPixel == 24 ? GL_BGR : BytesPerPixel == 8 ? GL_LUMINANCE : 0;
		GLsizei iInternalFormat = BytesPerPixel == 24 ? GL_RGB : GL_DEPTH_COMPONENT;
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB,
		             WidthOfTexture, HeightOfTexture, 0, iFormat,
		             GL_UNSIGNED_BYTE, bytesDataPointer);
		glGenerateMipmap(GL_TEXTURE_2D);
		FreeImage_Unload(loadedImage);
		glGenSamplers(1, &TextureSamplerObject_ID);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
		setFiltering(TEXTURE_FILTER_MAG_BILINEAR, TEXTURE_FILTER_MIN_BILINEAR_MIPMAP);
		HasMipsBeenGenerated = true;
		glActiveTexture(GL_TEXTURE0 + 0);
		glBindTexture(GL_TEXTURE_2D, NULL);
And here is the way I am drawing the OpenGL quad with materials:

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		
glUseProgram(g_StandardShaderProgram_ID);

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

glEnable(GL_TEXTURE_2D);
glUniform1i(GetEnableWireframeID(), 0);
glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);

for (GLuint i = 0; i < CurrentMeshCache.size(); i++) {

/*

Inside my object that has my mesh/quad/material data...

/*

glBindVertexArray(Pointer_VAO);

for (int i = 0; i < ModelMatrixInstances.size(); i++) {
	glm::mat4 ModelViewMatrix = CurrentOpenGLController->GetViewMatrix() * ModelMatrixInstances[i];
	glm::mat3 NormalMatrix = glm::transpose(glm::inverse(glm::mat3(ModelViewMatrix)));
	glm::mat4 ModelViewProjectionMatrix = CurrentOpenGLController->GetProjectionViewMatrix() * ModelMatrixInstances[i];
	glBindBuffer(GL_ARRAY_BUFFER, MVP_VBO);
	glBufferSubData(GL_ARRAY_BUFFER, (i * (sizeof(glm::mat4))), sizeof(glm::mat4), glm::value_ptr(ModelViewProjectionMatrix));
	glBindBuffer(GL_ARRAY_BUFFER, NormalMatrix_VBO);
	glBufferSubData(GL_ARRAY_BUFFER, (i * (sizeof(glm::mat3))), sizeof(glm::mat3), glm::value_ptr(NormalMatrix));
}

glUniform4fv(CurrentOpenGLController->GetMaterialColorID(), 1, Materials[0].ObjectColor);
glUniform4fv(CurrentOpenGLController->GetAmbientMeshColorID(), 1, Materials[0].AmbientColor);
glUniform4fv(CurrentOpenGLController->GetEmmissiveMeshColorID(), 1, Materials[0].EmissiveColor);
glUniform4fv(CurrentOpenGLController->GetSpecularMeshColorID(), 1, Materials[0].SpecularColor);
glUniform4fv(CurrentOpenGLController->GetDiffuseMeshColorID(), 1, Materials[0].DiffuseColor);
glUniform1fv(CurrentOpenGLController->GetMeshShininessID(), 1, &Materials[0].Shininess);

if (Materials[0].HasMaterialFile == true) {
	GLfloat ObjectHasMaterial = 1.0f;
	glUniform1fv(CurrentOpenGLController->GetObjectHasMaterialFileID(), 1, &ObjectHasMaterial);
	glUniform1i(CurrentOpenGLController->GetMainTextureID(), 1);
	Materials[0].bindTexture(1);
}
else {
	GLfloat ObjectDoesNotHaveMaterial = 0.0f;
	glUniform1fv(CurrentOpenGLController->GetObjectHasMaterialFileID(), 1, &ObjectDoesNotHaveMaterial);
	glBindTexture(GL_TEXTURE_2D, NULL);
}

glDrawElementsInstanced(GL_TRIANGLES, TotalVertexCount,
	GL_UNSIGNED_INT, NULL, NumberOfChildItems + 1);

if (Materials[0].HasMaterialFile == true) {
	glActiveTexture(GL_TEXTURE0 + NULL);
	glBindTexture(GL_TEXTURE_2D, NULL);
}

/*

Now out of my object...

*/
}

glBindVertexArray(0);
0

Share this post


Link to post
Share on other sites

It's just a hunch, but if you have back face culling disabled and use the wrong winding order of faces, it might just generate this effect.
maybe playing a little around with glFrontFace() and glCullFace() will help.


Tried this; same results. Thank you for the suggestion though.
0

Share this post


Link to post
Share on other sites

If I have to, how would I generate them?

 
Don't even think about that then biggrin.png


Darn, it's OK, I can learn smile.png
0

Share this post


Link to post
Share on other sites

Darn, it's OK, I can learn

 

 

Naa, thats not what I mean. This would just be a hack and not a solution to your problem in the first place.

 

I am sorry, I think I was not clear enough, but with file I didn't mean the image but the geometry you are loading. I think you have to look for the error in how you set up your vertex/normal/texcoord/index buffers.

 

Have you ever tried to render a simpler scene (just one quad maybe?) to make it easier to narrow down the error?

 

 

Do you really want to draw glDrawElementsInstanced ()???   this would mean that you would render the same geometry over and over again and you need an instance buffer with appropriate glVertexAttribDivisor() set (have a look at instanced rendering then: http://en.wikipedia.org/wiki/Geometry_instancing)

Second I noticed, that you call glDrawElements* with TotalVertexCount  I dont know what this variable contains but you should call this function with the number of indices not vertices.

0

Share this post


Link to post
Share on other sites
From what type of file are you loading the model data?
Some file formats are obnoxious and use 1-based indices or have other quirks when indexing into UV/normal/vertex pools.


L. Spiro
0

Share this post


Link to post
Share on other sites

From what type of file are you loading the model data?
Some file formats are obnoxious and use 1-based indices or have other quirks when indexing into UV/normal/vertex pools.


L. Spiro


I am loading the data from an FBX file.

Specifically, I am using Autodesk's FBX SDK.
0

Share this post


Link to post
Share on other sites

So you are covering all 4 methods for creating indices into the pools, right?


L. Spiro


Hello,

Perhaps I am an amateur but I don't get this. "Creating indices into the pools"?

I don't know what that means.

Thank you for your time. Edited by tmason
0

Share this post


Link to post
Share on other sites
Look at any sample that runs over the faces of each mesh.
You have FbxGeometryElement::eByControlPoint or FbxGeometryElement::eByPolygonVertex.
In both cases you have either GetReferenceMode() == FbxLayerElement::eDirect or FbxLayerElement::eIndexToDirect.

This snippet gets the proper normal index (ffvThisVert.u32NormalIndex) under these considerations:
	// Go over each vertex in the face.
	for ( u32 I = 0UL; I < ui32PolyTotal; ++I ) {
		FC_FACE::FC_FACE_VERTEX ffvThisVert;
		u32 u32VertIndex = piFacePool[ui32PolyStart+I];
		ffvThisVert.u32VertexIndex = u32VertIndex;

		if ( m_u32Flags & FC_NORMALS ) {
			ffvThisVert.u32NormalIndex = 0UL;
			const FbxLayerElementNormal * plenNormals = m_pfmMesh->GetLayer( 0 )->GetNormals();
			switch ( plenNormals->GetMappingMode() ) {
				case FbxGeometryElement::eByControlPoint : {
					// The normal index is based on the vertex index.
					if ( plenNormals->GetReferenceMode() == FbxLayerElement::eDirect ) {
						// The normal index is the same as the vertex index.
						ffvThisVert.u32NormalIndex = u32VertIndex;
					}
					else if ( plenNormals->GetReferenceMode() == FbxLayerElement::eIndexToDirect ) {
						// The normal index is found by plugging the vertex index into an array of indices.
						ffvThisVert.u32NormalIndex = plenNormals->GetIndexArray().GetAt( u32VertIndex );
					}
					if ( ffvThisVert.u32NormalIndex >= static_cast<u32>(plenNormals->GetDirectArray().GetCount()) ) {
						std::cout << "Invalid normal index." << std::endl;
					}
					break;
				}
				case FbxGeometryElement::eByPolygonVertex : {
					// The normal index is based off _favAddVert.u32IndexCount, which is
					//	incremented once for each vertex over which we loop.
					if ( plenNormals->GetReferenceMode() == FbxLayerElement::eDirect ) {
						// It is just _favAddVert.u32IndexCount.
						ffvThisVert.u32NormalIndex = _favAddVert.u32IndexCount;
					}
					else if ( plenNormals->GetReferenceMode() == FbxLayerElement::eIndexToDirect ) {
						// The normal index is found by plugging _favAddVert.u32IndexCount into an array of indices.
						ffvThisVert.u32NormalIndex = plenNormals->GetIndexArray().GetAt( _favAddVert.u32IndexCount );
					}
					break;
				}
				default : {
					std::cout << "Unsupported normal mapping mode." << std::endl;
				}
			}
		}
Vertices, vertex, colors, and UV coordinates all work the same way, though you can go over more layers if you want more UV sets (or you can just ignore all but the base layer).


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 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
    • By afraidofdark
      I have just noticed that, in quake 3 and half - life, dynamic models are effected from light map. For example in dark areas, gun that player holds seems darker. How did they achieve this effect ? I can use image based lighting techniques however (Like placing an environment probe and using it for reflections and ambient lighting), this tech wasn't used in games back then, so there must be a simpler method to do this.
      Here is a link that shows how modern engines does it. Indirect Lighting Cache It would be nice if you know a paper that explains this technique. Can I apply this to quake 3' s light map generator and bsp format ?
  • Popular Now