• Advertisement
  • Popular Tags

  • Popular Now

  • Advertisement
  • Similar Content

    • By tj8146
      I am using immediate mode for OpenGL and I am creating a 2D top down car game. I am trying to configure my game loop in order to get my car-like physics working on a square shape. I have working code but it is not doing as I want it to. I am not sure as to whether it is my game loop that is incorrect or my code for the square is incorrect, or maybe both! Could someone help because I have been trying to work this out for over a day now
      I have attached my .cpp file if you wish to run it for yourself.. 
      WinMain code:
      /******************* WIN32 FUNCTIONS ***************************/ int WINAPI WinMain( HINSTANCE hInstance, // Instance HINSTANCE hPrevInstance, // Previous Instance LPSTR lpCmdLine, // Command Line Parameters int nCmdShow) // Window Show State { MSG msg; // Windows Message Structure bool done=false; // Bool Variable To Exit Loop Car car; car.x = 220; car.y = 140; car.dx = 0; car.dy = 0; car.ang = 0; AllocConsole(); FILE *stream; freopen_s(&stream, "CONOUT$", "w", stdout); // Create Our OpenGL Window if (!CreateGLWindow("OpenGL Win32 Example",screenWidth,screenHeight)) { return 0; // Quit If Window Was Not Created } while(!done) // Loop That Runs While done=FALSE { if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) // Is There A Message Waiting? { if (msg.message==WM_QUIT) // Have We Received A Quit Message? { done=true; // If So done=TRUE break; } else // If Not, Deal With Window Messages { TranslateMessage(&msg); // Translate The Message DispatchMessage(&msg); // Dispatch The Message } } else // If There Are No Messages { if(keys[VK_ESCAPE]) done = true; void processKeys(Car& car); //process keyboard while (game_is_running) { loops = 0; while (GetTickCount() > next_game_tick && loops < MAX_FRAMESKIP) { update(car); // update variables next_game_tick += SKIP_TICKS; loops++; } display(car); // Draw The Scene SwapBuffers(hDC); // Swap Buffers (Double Buffering) } } } // Shutdown KillGLWindow(); // Kill The Window return (int)(msg.wParam); // Exit The Program } //WIN32 Processes function - useful for responding to user inputs or other events. LRESULT CALLBACK WndProc( HWND hWnd, // Handle For This Window UINT uMsg, // Message For This Window WPARAM wParam, // Additional Message Information LPARAM lParam) // Additional Message Information { switch (uMsg) // Check For Windows Messages { case WM_CLOSE: // Did We Receive A Close Message? { PostQuitMessage(0); // Send A Quit Message return 0; // Jump Back } break; case WM_SIZE: // Resize The OpenGL Window { reshape(LOWORD(lParam),HIWORD(lParam)); // LoWord=Width, HiWord=Height return 0; // Jump Back } break; case WM_LBUTTONDOWN: { mouse_x = LOWORD(lParam); mouse_y = screenHeight - HIWORD(lParam); LeftPressed = true; } break; case WM_LBUTTONUP: { LeftPressed = false; } break; case WM_MOUSEMOVE: { mouse_x = LOWORD(lParam); mouse_y = screenHeight - HIWORD(lParam); } break; case WM_KEYDOWN: // Is A Key Being Held Down? { keys[wParam] = true; // If So, Mark It As TRUE return 0; // Jump Back } break; case WM_KEYUP: // Has A Key Been Released? { keys[wParam] = false; // If So, Mark It As FALSE return 0; // Jump Back } break; } // Pass All Unhandled Messages To DefWindowProc return DefWindowProc(hWnd,uMsg,wParam,lParam); }  
      C++ and OpenGL code:
      int mouse_x=0, mouse_y=0; bool LeftPressed = false; int screenWidth=1080, screenHeight=960; bool keys[256]; float radiansFromDegrees(float deg) { return deg * (M_PI / 180.0f); } float degreesFromRadians(float rad) { return rad / (M_PI / 180.0f); } bool game_is_running = true; const int TICKS_PER_SECOND = 50; const int SKIP_TICKS = 1000 / TICKS_PER_SECOND; const int MAX_FRAMESKIP = 10; DWORD next_game_tick = GetTickCount(); int loops; typedef struct { float x, y; float dx, dy; float ang; }Car; //OPENGL FUNCTION PROTOTYPES void display(const Car& car); //called in winmain to draw everything to the screen void reshape(int width, int height); //called when the window is resized void init(); //called in winmain when the program starts. void processKeys(Car& car); //called in winmain to process keyboard input void update(Car& car); //called in winmain to update variables /************* START OF OPENGL FUNCTIONS ****************/ void display(const Car& car) { const float w = 50.0f; const float h = 50.0f; glClear(GL_COLOR_BUFFER_BIT); glLoadIdentity(); glTranslatef(100, 100, 0); glBegin(GL_POLYGON); glVertex2f(car.x, car.y); glVertex2f(car.x + w, car.y); glVertex2f(car.x + w, car.y + h); glVertex2f(car.x, car.y + h); glEnd(); glFlush(); } void reshape(int width, int height) // Resize the OpenGL window { screenWidth = width; screenHeight = height; // to ensure the mouse coordinates match // we will use these values to set the coordinate system glViewport(0, 0, width, height); // Reset the current viewport glMatrixMode(GL_PROJECTION); // select the projection matrix stack glLoadIdentity(); // reset the top of the projection matrix to an identity matrix gluOrtho2D(0, screenWidth, 0, screenHeight); // set the coordinate system for the window glMatrixMode(GL_MODELVIEW); // Select the modelview matrix stack glLoadIdentity(); // Reset the top of the modelview matrix to an identity matrix } void init() { glClearColor(1.0, 1.0, 0.0, 0.0); //sets the clear colour to yellow //glClear(GL_COLOR_BUFFER_BIT) in the display function //will clear the buffer to this colour. } void processKeys(Car& car) { if (keys[VK_UP]) { float cdx = sinf(radiansFromDegrees(car.ang)); float cdy = -cosf(radiansFromDegrees(car.ang)); car.dx += cdx; car.dy += cdy; } if (keys[VK_DOWN]) { float cdx = sinf(radiansFromDegrees(car.ang)); float cdy = -cosf(radiansFromDegrees(car.ang)); car.dx += -cdx; car.dy += -cdy; } if (keys[VK_LEFT]) { car.ang -= 2; } if (keys[VK_RIGHT]) { car.ang += 2; } } void update(Car& car) { car.x += car.dx*next_game_tick; }  
      game.cpp
    • By tj8146
      I am using immediate mode for OpenGL and I am creating a 2D top down car game. I am trying to configure my game loop in order to get my car-like physics working on a square shape. I have working code but it is not doing as I want it to. I am not sure as to whether it is my game loop that is incorrect or my code for the square is incorrect, or maybe both! Could someone help because I have been trying to work this out for over a day now
      I have attached my .cpp file if you wish to run it for yourself.. 
       
      This is my C++ and OpenGL code:
      int mouse_x=0, mouse_y=0; bool LeftPressed = false; int screenWidth=1080, screenHeight=960; bool keys[256]; float radiansFromDegrees(float deg) { return deg * (M_PI / 180.0f); } float degreesFromRadians(float rad) { return rad / (M_PI / 180.0f); } bool game_is_running = true; const int TICKS_PER_SECOND = 50; const int SKIP_TICKS = 1000 / TICKS_PER_SECOND; const int MAX_FRAMESKIP = 10; DWORD next_game_tick = GetTickCount(); int loops; typedef struct { float x, y; float dx, dy; float ang; }Car; //OPENGL FUNCTION PROTOTYPES void display(const Car& car); //called in winmain to draw everything to the screen void reshape(int width, int height); //called when the window is resized void init(); //called in winmain when the program starts. void processKeys(Car& car); //called in winmain to process keyboard input void update(Car& car); //called in winmain to update variables /************* START OF OPENGL FUNCTIONS ****************/ void display(const Car& car) { const float w = 50.0f; const float h = 50.0f; glClear(GL_COLOR_BUFFER_BIT); glLoadIdentity(); glTranslatef(100, 100, 0); glBegin(GL_POLYGON); glVertex2f(car.x, car.y); glVertex2f(car.x + w, car.y); glVertex2f(car.x + w, car.y + h); glVertex2f(car.x, car.y + h); glEnd(); glFlush(); } void reshape(int width, int height) // Resize the OpenGL window { screenWidth = width; screenHeight = height; // to ensure the mouse coordinates match // we will use these values to set the coordinate system glViewport(0, 0, width, height); // Reset the current viewport glMatrixMode(GL_PROJECTION); // select the projection matrix stack glLoadIdentity(); // reset the top of the projection matrix to an identity matrix gluOrtho2D(0, screenWidth, 0, screenHeight); // set the coordinate system for the window glMatrixMode(GL_MODELVIEW); // Select the modelview matrix stack glLoadIdentity(); // Reset the top of the modelview matrix to an identity matrix } void init() { glClearColor(1.0, 1.0, 0.0, 0.0); //sets the clear colour to yellow //glClear(GL_COLOR_BUFFER_BIT) in the display function //will clear the buffer to this colour. } void processKeys(Car& car) { if (keys[VK_UP]) { float cdx = sinf(radiansFromDegrees(car.ang)); float cdy = -cosf(radiansFromDegrees(car.ang)); car.dx += cdx; car.dy += cdy; } if (keys[VK_DOWN]) { float cdx = sinf(radiansFromDegrees(car.ang)); float cdy = -cosf(radiansFromDegrees(car.ang)); car.dx += -cdx; car.dy += -cdy; } if (keys[VK_LEFT]) { car.ang -= 2; } if (keys[VK_RIGHT]) { car.ang += 2; } } void update(Car& car) { car.x += car.dx*next_game_tick; } My WinMain code:
      /******************* WIN32 FUNCTIONS ***************************/ int WINAPI WinMain( HINSTANCE hInstance, // Instance HINSTANCE hPrevInstance, // Previous Instance LPSTR lpCmdLine, // Command Line Parameters int nCmdShow) // Window Show State { MSG msg; // Windows Message Structure bool done=false; // Bool Variable To Exit Loop Car car; car.x = 220; car.y = 140; car.dx = 0; car.dy = 0; car.ang = 0; AllocConsole(); FILE *stream; freopen_s(&stream, "CONOUT$", "w", stdout); // Create Our OpenGL Window if (!CreateGLWindow("OpenGL Win32 Example",screenWidth,screenHeight)) { return 0; // Quit If Window Was Not Created } while(!done) // Loop That Runs While done=FALSE { if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) // Is There A Message Waiting? { if (msg.message==WM_QUIT) // Have We Received A Quit Message? { done=true; // If So done=TRUE break; } else // If Not, Deal With Window Messages { TranslateMessage(&msg); // Translate The Message DispatchMessage(&msg); // Dispatch The Message } } else // If There Are No Messages { if(keys[VK_ESCAPE]) done = true; void processKeys(Car& car); //process keyboard while (game_is_running) { loops = 0; while (GetTickCount() > next_game_tick && loops < MAX_FRAMESKIP) { update(car); // update variables next_game_tick += SKIP_TICKS; loops++; } display(car); // Draw The Scene SwapBuffers(hDC); // Swap Buffers (Double Buffering) } } } // Shutdown KillGLWindow(); // Kill The Window return (int)(msg.wParam); // Exit The Program } //WIN32 Processes function - useful for responding to user inputs or other events. LRESULT CALLBACK WndProc( HWND hWnd, // Handle For This Window UINT uMsg, // Message For This Window WPARAM wParam, // Additional Message Information LPARAM lParam) // Additional Message Information { switch (uMsg) // Check For Windows Messages { case WM_CLOSE: // Did We Receive A Close Message? { PostQuitMessage(0); // Send A Quit Message return 0; // Jump Back } break; case WM_SIZE: // Resize The OpenGL Window { reshape(LOWORD(lParam),HIWORD(lParam)); // LoWord=Width, HiWord=Height return 0; // Jump Back } break; case WM_LBUTTONDOWN: { mouse_x = LOWORD(lParam); mouse_y = screenHeight - HIWORD(lParam); LeftPressed = true; } break; case WM_LBUTTONUP: { LeftPressed = false; } break; case WM_MOUSEMOVE: { mouse_x = LOWORD(lParam); mouse_y = screenHeight - HIWORD(lParam); } break; case WM_KEYDOWN: // Is A Key Being Held Down? { keys[wParam] = true; // If So, Mark It As TRUE return 0; // Jump Back } break; case WM_KEYUP: // Has A Key Been Released? { keys[wParam] = false; // If So, Mark It As FALSE return 0; // Jump Back } break; } // Pass All Unhandled Messages To DefWindowProc return DefWindowProc(hWnd,uMsg,wParam,lParam); }  
      game.cpp
    • By lxjk
      Hi guys,
      There are many ways to do light culling in tile-based shading. I've been playing with this idea for a while, and just want to throw it out there.
      Because tile frustums are general small compared to light radius, I tried using cone test to reduce false positives introduced by commonly used sphere-frustum test.
      On top of that, I use distance to camera rather than depth for near/far test (aka. sliced by spheres).
      This method can be naturally extended to clustered light culling as well.
      The following image shows the general ideas

       
      Performance-wise I get around 15% improvement over sphere-frustum test. You can also see how a single light performs as the following: from left to right (1) standard rendering of a point light; then tiles passed the test of (2) sphere-frustum test; (3) cone test; (4) spherical-sliced cone test
       

       
      I put the details in my blog post (https://lxjk.github.io/2018/03/25/Improve-Tile-based-Light-Culling-with-Spherical-sliced-Cone.html), GLSL source code included!
       
      Eric
    • By Fadey Duh
      Good evening everyone!

      I was wondering if there is something equivalent of  GL_NV_blend_equation_advanced for AMD?
      Basically I'm trying to find more compatible version of it.

      Thank you!
    • By Jens Eckervogt
      Hello guys, 
       
      Please tell me! 
      How do I know? Why does wavefront not show for me?
      I already checked I have non errors yet.
      using OpenTK; using System.Collections.Generic; using System.IO; using System.Text; namespace Tutorial_08.net.sourceskyboxer { public class WaveFrontLoader { private static List<Vector3> inPositions; private static List<Vector2> inTexcoords; private static List<Vector3> inNormals; private static List<float> positions; private static List<float> texcoords; private static List<int> indices; public static RawModel LoadObjModel(string filename, Loader loader) { inPositions = new List<Vector3>(); inTexcoords = new List<Vector2>(); inNormals = new List<Vector3>(); positions = new List<float>(); texcoords = new List<float>(); indices = new List<int>(); int nextIdx = 0; using (var reader = new StreamReader(File.Open("Contents/" + filename + ".obj", FileMode.Open), Encoding.UTF8)) { string line = reader.ReadLine(); int i = reader.Read(); while (true) { string[] currentLine = line.Split(); if (currentLine[0] == "v") { Vector3 pos = new Vector3(float.Parse(currentLine[1]), float.Parse(currentLine[2]), float.Parse(currentLine[3])); inPositions.Add(pos); if (currentLine[1] == "t") { Vector2 tex = new Vector2(float.Parse(currentLine[1]), float.Parse(currentLine[2])); inTexcoords.Add(tex); } if (currentLine[1] == "n") { Vector3 nom = new Vector3(float.Parse(currentLine[1]), float.Parse(currentLine[2]), float.Parse(currentLine[3])); inNormals.Add(nom); } } if (currentLine[0] == "f") { Vector3 pos = inPositions[0]; positions.Add(pos.X); positions.Add(pos.Y); positions.Add(pos.Z); Vector2 tc = inTexcoords[0]; texcoords.Add(tc.X); texcoords.Add(tc.Y); indices.Add(nextIdx); ++nextIdx; } reader.Close(); return loader.loadToVAO(positions.ToArray(), texcoords.ToArray(), indices.ToArray()); } } } } } And It have tried other method but it can't show for me.  I am mad now. Because any OpenTK developers won't help me.
      Please help me how do I fix.

      And my download (mega.nz) should it is original but I tried no success...
      - Add blend source and png file here I have tried tried,.....  
       
      PS: Why is our community not active? I wait very longer. Stop to lie me!
      Thanks !
  • Advertisement
  • Advertisement
Sign in to follow this  

OpenGL Amd openGL driver crashes

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

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

Recommended Posts

Hi,

 

I'm working on a game and I added shader recompile support on it. Basically it just detects if any source code changes and it recompiles all shaders that belongs to a shader program and link it again.

 

I tried that in 3 different computers with 3 different GPU, on a linux + intel works ok, on a win 8.1 + nvidia it works ok, but on a win 8.1 + amd radeon hd 7500 the driver crashes and restarts.

 

Here's the source code, if anyone have any tips to share or if it really is a driver bug, how can i work around it?

ReloadAsset()
{
  for (U32 i=0; i<sp->len; ++i)
  {
    CompileShader(game, sp->shaders[i]);
  }

  CompileShaderProgram(game, sp);
}

The previous function compiles all shaders that belongs to a shader program and then links it. Following is the guts of these 2 functions

B32 CompileShader(Game *game, asset *a) {
	platform *OS = &game->Platform;
	char *fullpath = String(Temporary(game->Memory->System), "%s%s", game->assetsPath, a->Filepath);
	GLenum type = 0;
	 switch(a->Type)
	 {
		 case AssetType_VertexShader:
			 type = GL_VERTEX_SHADER;
		 	break;
		case AssetType_GeometryShader:
			type = GL_GEOMETRY_SHADER;
			break;
		case AssetType_FragmentShader:
			type = GL_FRAGMENT_SHADER;
			break;
		default:
			assert(false);
	}
	a->Data = (void*)(U64)glCreateShader(type);

	U32 bytesRead;
	const char *shaderData = (const char*)OS->ReadFully(Temporary(game->Memory->System), fullpath, &bytesRead);
	
	 U32 Name = (U64)a->Data;
	glShaderSource(Name, 1, &shaderData, (GLint*)&bytesRead);
	glCompileShader(Name);

	GLint status;
        glGetShaderiv(Name, GL_COMPILE_STATUS, &status);
	if (status == GL_FALSE) {
		glDeleteShader(Name);
		a->Data = 0;
		return false;
	} else {
		return true;
	}
}

Nothing fancy going on there, creating, compiling and checking for errors.

B32 CompileShaderProgram(Game *game, shader_program *program) 
{
	for (U32 i=0; i<program->len; ++i) 
	{
		U32 Name = (U64)program->shaders[i]->Data;
		glAttachShader(program->Name, Name);
	}

	const GLchar *fv[] = {"gl_Position"};
	glTransformFeedbackVaryings(program->Name, 1, fv, GL_INTERLEAVED_ATTRIBS);

	glLinkProgram(program->Name);

	for (U32 i=0; i<program->len; ++i) {
		U32 Name = (U64)program->shaders[i]->Data;
		DebugLog(game, LogType_Render, "Detaching to %d shader %d", program->Name, Name);
		glDetachShader(program->Name, Name);
		glDeleteShader(Name);
	}

	GLint status;
	glGetProgramiv(program->Name, GL_LINK_STATUS, &status);
	if (status == GL_FALSE) {
		char *errorMsg = GetCompileError(program->Name, glGetProgramInfoLog, Temporary(game->Memory->System));
		DebugText(game, 5, errorMsg);
		return false;
	} else {
		return true;
	}
}

Here it's the attaching and linking.

 

It's worth mentioning that the shaders are created at start using the same functions, the only big difference is that the creation of the shader program happens only once, and as i mentioned early that code only triggers when a shader asset is modified.

 

I've already tried a few things to work around that, and the only thing that made a difference was to create a new shader program, that worked fine, but when I tried to delete the old one, the driver crashes :(

 

Thanks in advance!

Share this post


Link to post
Share on other sites
Advertisement
Whichine of your code does it crash on, and what's the exact crash message?

In my experience, NVidia drivers tend to tolerate (and even encourage) non-standard code, whereas AMD drivers tend to follow the letter of the spec and crash if you deviate from it. So I wouldn't assume a driver bug immediately.

It's been a while since I read the GL spec... So as a guess, try getting the status of the link operation before detaching the programs, instead of after.

Share this post


Link to post
Share on other sites

a->Data = (void*)(U64)glCreateShader(type);

 

glCreateShader returns a GLuint which is mandated to be 32-bit by the spec.  It looks like you're casting it to a 64-bit type here so you've got a buffer overflow.  This might or might not be the cause of your crash, but either way you shouldn't be doing it.

 

Also, you may or may not be aware of this, but if you run a 32-bit program on 64-bit Windows, pointer types are still 32-bit.

 

I'd suggest that you hunt down and clean up anything like this first.

Share this post


Link to post
Share on other sites

It's been a while since I read the GL spec... So as a guess, try getting the status of the link operation before detaching the programs, instead of after.

 

I'll try that, there's no error messge, only an alert on the windows tray saying the driver stop responding and restarted succesfully (my program stops working after that)

The crash happens a lot after the linking, and it doesn't seem related at first because it happens when using another shader program, but if I don't glDeleteProgram nothing happens.

 

Start by enabling GL debug messages: https://www.opengl.org/registry/specs/ARB/debug_output.txt See if you get any useful information leading up to the crash.

 

I'll do that and post later if I find something useful.

 

Thanks a lot!

Share this post


Link to post
Share on other sites

Start by enabling GL debug messages: https://www.opengl.org/registry/specs/ARB/debug_output.txt

See if you get any useful information leading up to the crash. 

I got some warnings, which I fixed but sadly, the crash still happens. I also have one performance note about a vertex shader recompilation due to state change, but only happens once so I don't think that have got something to do with the crash.

 

So as a guess, try getting the status of the link operation before detaching the programs, instead of after.
I change the order but nothing else changed.

 

I tried recompiling other shader programs and I discovered that only the shader including a geometry shader crashes the driver. I'll try to make the smallest example that lead to the crash and see if that happens in others amd gpu.

 

Thanks

Share this post


Link to post
Share on other sites

You should at least see which version of opengl amd card supports(and chcek if it has gemoetry shader support etc)  then you can, write your own text file opener and chace that to char * then apply that to shaders like here

 

[spoiler]

 

text open

[spoiler]

#ifndef stringlistH
#define stringlistH

#include "FileHandling.h"
#include <vector>
#include <android/log.h>
#include <fstream>
#include <sstream>
#include "DxcMath.h"
#include "string"
#include "stdlib.h"
#include <iostream>

#define APP_LOG2 "WNB_TXTLOG"
typedef std::string AnsiString;

extern std::vector<AnsiString> w_nawiasie[10];

enum tFloatConversionRule { tFCDot, tFCcomma };

extern tFloatConversionRule FLOAT_CONVERSION;
extern void  init_string_float_conversion_rule();

inline AnsiString IntToStr(int i)
{
	std::stringstream s;

	s << i;

	AnsiString converted(s.str());
	return converted;
}

inline AnsiString FloatToStr(float i)
{
	std::stringstream s;

	s << i;

	AnsiString converted(s.str());
	return converted;
}



inline AnsiString POINT_TO_TEXT(t3dpoint<float> p)
{
	return "X "+FloatToStr(p.x) + " Y "+FloatToStr(p.y)+" Z "+FloatToStr(p.z);
}

inline AnsiString iPOINT_TO_TEXT(t3dpoint<int> p)
{
	return "X "+IntToStr(p.x) + " Y "+IntToStr(p.y)+" Z "+IntToStr(p.z);
}

inline int Pos(AnsiString sub, AnsiString str)
{
	 std::size_t found = str.find(sub,0);
	  if (found!=std::string::npos)
		  return int(found)+1;
	  else
		  return 0;
}


inline AnsiString booltostring(bool hue)
{
if (hue) return "true"; else return "false";
}

inline int pstrtoint(AnsiString num)
{
return ::atoi(num.c_str());
}


inline AnsiString StringReplace(AnsiString str, AnsiString substr, AnsiString with)
{
	AnsiString s = str;
while (Pos(substr, s) > 0)
{
	int pos = Pos(substr, s)-1;
	 s.erase(pos,substr.length());
	 s.insert(pos, with);
}
return s;
}

inline float pstrtofloat(AnsiString num)
{
	AnsiString temp = num;
	if (FLOAT_CONVERSION == tFCDot)     //English rule (floats are written as 10.25)
	temp = StringReplace(num,",",".");
									 else      //Polish rule (floats are written as 10,25)
	temp = StringReplace(num,".",",");


return ::atof(temp.c_str());
}


inline int StrToInt(AnsiString num)
{
return ::atoi(num.c_str());
}

inline AnsiString stddelete(AnsiString str, int pos, int len) //this is for std::string only because i will call only Pos()-1 from it
{
	AnsiString s = str;
	 s.erase(pos, len);
	 return s;
}






extern AnsiString LowerCase(AnsiString str);
extern AnsiString UpperCase(AnsiString str);


inline int booltoint(bool k)
{
	if (k) return 1; else return 0;
}

inline bool stringtobool(AnsiString hue)
{
	if (LowerCase(hue) == "false") return false;
	if (LowerCase(hue) == "true") return true;
	if (LowerCase(hue) == "0") return false;
	if (LowerCase(hue) == "1") return true;
		return false;
}

inline AnsiString get_text_between2(AnsiString b1, AnsiString b2, AnsiString original_str)
{

if (Pos(b1,original_str) == 0) return original_str;
if (Pos(b2,original_str) == 0) return original_str;

//float, 2, 3); ahue ahue
AnsiString temp1 = stddelete(original_str, 0, Pos(b1,original_str) + b1.length() - 1 );
int k = Pos(b2,temp1) - 1;
AnsiString temp2 = stddelete(temp1, k, temp1.length() - k);
return temp2;
}



inline AnsiString get_before_char(AnsiString text, AnsiString sign, bool casesensitive)
{
AnsiString s = text;
AnsiString tmp;
if (casesensitive == false)
	tmp = stddelete(s,Pos(LowerCase(sign),LowerCase(s))-1,s.length()-Pos(LowerCase(sign),LowerCase(s))+1);
else
	tmp = stddelete(s,Pos(sign,s)-1,s.length()-Pos(sign,s)+1);


return tmp;
}


inline AnsiString get_after_char(AnsiString text, AnsiString sign, bool casesensitive)
{
AnsiString s = text;
AnsiString tmp;
if (casesensitive == false)
	tmp = stddelete(s,0,Pos(LowerCase(sign),LowerCase(s)));
	else
		tmp = stddelete(s,0,Pos(sign,s));


return tmp;
}



inline AnsiString get_after_char2(AnsiString text, AnsiString sign, bool casesensitive)
{
AnsiString s = text;
AnsiString tmp;
if (casesensitive == false)
	tmp = stddelete(s,0,Pos(LowerCase(sign),LowerCase(s))+sign.length()-1);
	else
		tmp = stddelete(s,0,Pos(sign,s)+sign.length()-1);


return tmp;
}




inline void get_all_in_nawias(AnsiString ainput, AnsiString aznak, int index)
{
    std::string input = ainput;
    std::string delimiter = aznak;


    w_nawiasie[index].clear();

    AnsiString pikok;

    std::size_t  start = 0U;
    std::size_t end = input.find(delimiter);

    while (end != std::string::npos) {

    	pikok =  input.substr(start, end - start);
      w_nawiasie[index].push_back(pikok);

        start = end + delimiter.length();
        end = input.find(delimiter, start);
    }
  	pikok =  input.substr(start, end);
    w_nawiasie[index].push_back(pikok);

}


inline AnsiString ExtractFileName(AnsiString pikok)
{
	get_all_in_nawias(pikok,"/",0);
	return w_nawiasie[0][ w_nawiasie[0].size()-1 ];
}


inline AnsiString ExtractFilePath(AnsiString pikok)
{
	get_all_in_nawias(pikok,"/",0);
	if (w_nawiasie[0].size() <= 0) return "";
	AnsiString ahue = "";
	for (int i=0; i < w_nawiasie[0].size()-1; i++)
	ahue = ahue + w_nawiasie[0][i]+"/";

	return ahue;
}


inline AnsiString get_filename_ext(AnsiString pikok)
{
	AnsiString filename = ExtractFileName(pikok);
	return get_after_char(filename, ".", false);
}


inline AnsiString change_filename_ext(AnsiString pikok, AnsiString next) //push .extension important with dot ex. ".tga"
{
AnsiString path 	= ExtractFilePath(pikok);
AnsiString filename = ExtractFileName(pikok);
AnsiString fname	= get_before_char(filename,".", false);

return path+fname+next;

}



struct TStringList
{

	int Count;
std::vector<AnsiString> Strings;


void Add(AnsiString text)
{
AnsiString p = text;
Strings.push_back(text);
	Count = Count + 1;
}

	AnsiString GetText()
	{
	AnsiString res = "";
	int i;
	for (i=0; i < Count; i++)
		res = res + Strings[i] + "\n";
	return res;
	}

	void AddLineAtPos(int atline, int atpos)
	{
		std::vector<AnsiString> tmp;
		tmp.clear();
		for (int i=0; i < atline; i++)
			tmp.push_back(Strings[i]);

		AnsiString prefix;
		AnsiString suffix;

if (Strings[atline].length() > 0)
{
		prefix = stddelete(Strings[atline], atpos, 100000);
		suffix = stddelete(Strings[atline], 0, atpos);

tmp.push_back(prefix);
tmp.push_back(suffix);
} else
{
tmp.push_back("");
tmp.push_back("");
}


		for (int i=atline+1; i < Count; i++)
			tmp.push_back(Strings[i]);

	Strings.clear();

	Count = Count + 1;
	for (int i=0; i < Count; i++)
	Strings.push_back(tmp[i]);

	tmp.clear();
	}

	void Clear()
	{
		Count = 0;
		Strings.clear();
	}

	TStringList()
	{
		Clear();
	}

	~TStringList()
	{
		Clear();
	}


void LoadFromFile(AnsiString fname)
{

	std::ifstream file(fname.c_str());
	if (file.good() == false) {
file.close();
return;
	}

	AnsiString str;

	Count = 0;
	if (Strings.size() > 0) Strings.clear();

	while (std::getline(file, str))
	{
		Strings.push_back(str);
		Count = Count + 1;
	}

	file.close();

	//now remove next line characters from strings \n \r  \r\n
for (int i=0; i < Count; i++)
	{
		AnsiString str = Strings[i];

		 char lastChar = str.at( str.length() - 1 );
	if ( (lastChar == '\r') || (lastChar == '\n') )
	{
//		AnsiString p = "deleted newline: "+str;
//		__android_log_print(ANDROID_LOG_VERBOSE, APP_LOG2, p.c_str(), 1+1);

	str.erase(str.length()-1);
	Strings[i] = str;
	}
	}
}

//std::string p;
AnsiString pc;

void SaveToFile(AnsiString fname)
{
	pc = GetText();
	std::ofstream outfile (fname.c_str(),std::ofstream::binary);
	int len = pc.length();
	char * buff = new char[ len ];
	memcpy(buff, pc.c_str(), sizeof(char) * len);
	outfile.write (buff, len);
	outfile.close();
}




};

#endif
 

[/spoiler]

 

shader class

[spoiler]

//---------------------------------------------------------------------------

#ifndef shaderclassH
#define shaderclassH

#include "DxcMatrix.h"
#include "gl/glew.h"
#include "gl/gl.h"
#include "shadermodel_struct.h"

      #include <vector>
//template <class T>
//const T * readShaderFile( AnsiString FileName )
//{
//
//TStringList * s = new TStringList();
//
//s->LoadFromFile(FileName);
//
//AnsiString bollock = s->Text();
//
//	const T * buffer = new T[bollock.length()];
//
//											  buffer = bollock.c_str();
//
//
//											  delete s;
//
//	return buffer;
//}






struct TShaderObject
{
bool geomloaded;
	GLuint VERTEX;
	GLuint FRAGMENT;
	GLuint GEOMETRY;
	GLuint gProgram;
//	GLuint gvPositionHandle;

	AnsiString Vertexdata;
	AnsiString Fragmentdata;

TStringList * vert_prog;
TStringList * frag_prog;

char * vert;
char * frag;

GLint vertex_pos;
GLint texture_coord;
GLint vertex_normal;
GLint vertex_color;
GLint vertex_height;
GLint displacement;

GLint MVP[4];

GLint WM[4];

GLint LightAMB;
GLint LightDiff;
GLint LightPos;


//
GLint u_geometrySize;
GLint u_displacementMap;
GLint u_normalMap;
GLint u_oceanColor;
GLint u_skyColor;
GLint u_sunDirection;
GLint u_exposure;

GLint u_transformSize;
GLint u_resolution;
GLint u_initialSpectrum;


GLint u_wind;
GLint u_size;
GLint u_phases;
GLint u_deltaTime;
GLint u_choppiness;
GLint u_input;
GLint u_subtransformSize;
GLint u_cameraPosition;
GLint itex;
       GLint u_Texture;


TShaderObject()
{
    geomloaded = false;
}

void Enable()
{
glUseProgram(gProgram);
}


void Disable()
{
glUseProgram(0);
}


//bool LoadData(std::string &data, const std::string &filename)
//{
//    std::ifstream file(filename.c_str(), std::ifstream::in | std::ifstream::ate);
//    if(file.is_open())
//    {
//        std::streampos size(file.tellg());
//        file.seekg(0, std::ios::beg);
//        data.reserve(size);
//        data.append((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
//        file.close();
//        return true;
//    }
//
//    return false;
//}


void LoadGeometryShader(AnsiString fname)
{
	TStringList * s = new TStringList();
	s->LoadFromFile(fname);
	GEOMETRY 		= LoadShader(GL_GEOMETRY_SHADER, s->Text.c_str());
   delete s;
   geomloaded = true;
}


GLuint LoadShader(GLenum shaderType, const char* pSource)
{

    GLuint shader = glCreateShader(shaderType);
    if (shader) {

        glShaderSource(shader, 1, &pSource, NULL);

        glCompileShader(shader);
        GLint compiled = 0;

        glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);

        if (compiled == GL_FALSE)
        {

        	GetShaderError(shader);

                glDeleteShader(shader);
                shader = 0;
        }//!compiled



    } //shader

    return shader;
}


void GetShaderError(GLuint &shader)
{
    int logSize = 0;
    glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logSize);

    std::vector<GLchar> error(logSize);
	glGetShaderInfoLog(shader, logSize, &logSize, &error[0]);

if (logSize > 0)
{
    AnsiString str = "";
    int i;
    for (i=0; i < logSize; i++)
    	str = str + error[i];

    ShowMessage(str);
} else ShowMessage("bufflen 0 abroting - thers definetly an error during shader make");
}

void LoadVertexShader(AnsiString fname)
{
//	Vertexdata = "";
//	LoadData(Vertexdata, fname);
	TStringList * s = new TStringList();
	s->LoadFromFile(fname);
  //	ALOG("Loading vertex shader " + fname);
	VERTEX 		= LoadShader(GL_VERTEX_SHADER, s->Text.c_str());//readShaderFile<char>(fname));
   //	ALOG("done");
   delete s;
}

void LoadFragmentShader(AnsiString fname)
{
   //	ALOG("Loading fragment shader " + fname);
//	Fragmentdata = "";
//	LoadData(Fragmentdata, fname);
	TStringList * s = new TStringList();
	s->LoadFromFile(fname);
	FRAGMENT 	= LoadShader(GL_FRAGMENT_SHADER, s->Text.c_str());// readShaderFile<char>(fname));
  //	ALOG("done");
  delete s;
}


void GetAllUniformLocations()
{
    MVP[0] = glGetUniformLocation(gProgram, "MVP1");
    MVP[1] = glGetUniformLocation(gProgram, "MVP2");
    MVP[2] = glGetUniformLocation(gProgram, "MVP3");
    MVP[3] = glGetUniformLocation(gProgram, "MVP4");


	    //used for lighting shader (for transforming vertex normal)
	    WM[0] = glGetUniformLocation(gProgram, "WM1");
	    WM[1] = glGetUniformLocation(gProgram, "WM2");
	    WM[2] = glGetUniformLocation(gProgram, "WM3");
	    WM[3] = glGetUniformLocation(gProgram, "WM4");


	    LightPos = glGetUniformLocation(gProgram, "LPOS");
	    LightDiff = glGetUniformLocation(gProgram, "LDIFF");
	    LightAMB = glGetUniformLocation(gProgram, "LAMB");
        u_Texture 			= glGetUniformLocation(gProgram,"myTex");
}


void GetOceanUniforms()
{
//	oceanProgram
	u_geometrySize 		= glGetUniformLocation(gProgram,"u_geometrySize");
	u_displacementMap 	= glGetUniformLocation(gProgram,"u_displacementMap"); //used aswell in normalMapProgram
	u_normalMap 		= glGetUniformLocation(gProgram,"u_normalMap");
	u_oceanColor 		= glGetUniformLocation(gProgram,"u_oceanColor");
	u_skyColor 			= glGetUniformLocation(gProgram,"u_skyColor");
	u_sunDirection 		= glGetUniformLocation(gProgram,"u_sunDirection");
	u_exposure 			= glGetUniformLocation(gProgram,"u_exposure");



//verticalSubtransformProgram and horizontalSubtransformProgram
	u_transformSize		= glGetUniformLocation(gProgram,"u_transformSize");

//initialSpectrumProgram and phaseProgram and spectrumProgram and normalMapProgram
	u_resolution 		= glGetUniformLocation(gProgram,"u_resolution");

//spectrumProgram
	u_initialSpectrum 	= glGetUniformLocation(gProgram,"u_initialSpectrum");



	u_wind 				= glGetUniformLocation(gProgram,"u_wind");
	u_size 				= glGetUniformLocation(gProgram,"u_size");
	u_phases 			= glGetUniformLocation(gProgram,"u_phases");
	u_deltaTime 		= glGetUniformLocation(gProgram,"u_deltaTime");
	u_choppiness 		= glGetUniformLocation(gProgram,"u_choppiness");
	u_input 			= glGetUniformLocation(gProgram,"u_input");
	u_subtransformSize 	= glGetUniformLocation(gProgram,"u_subtransformSize");
	u_cameraPosition 	= glGetUniformLocation(gProgram,"u_cameraPosition");

			 itex = glGetUniformLocation(gProgram,"itex");
}

void SetLightPos(t3dpoint<float> p)
{
	glUniform3f( LightPos, p.x, p.y, p.z);
}

void SetLightAmbient(t3dpoint<float> p)
{
	glUniform3f( LightAMB, p.x, p.y, p.z);
}

void SetLightDiffuse(t3dpoint<float> p)
{
	glUniform3f( LightDiff, p.x, p.y, p.z);
}

void SendMVPtoShader(Matrix44<double> mat)
{
	glUniform4f( MVP[0], float(mat.m[0]), 	float(mat.m[1]), 	float(mat.m[2]), 	float(mat.m[3]));
	glUniform4f( MVP[1], float(mat.m[4]), 	float(mat.m[5]), 	float(mat.m[6]), 	float(mat.m[7]));
	glUniform4f( MVP[2], float(mat.m[8]), 	float(mat.m[9]), 	float(mat.m[10]), 	float(mat.m[11]));
	glUniform4f( MVP[3], float(mat.m[12]), 	float(mat.m[13]), 	float(mat.m[14]), 	float(mat.m[15]));
}

void SendMVPtoShader(Matrix44<float> mat)
{
	glUniform4f( MVP[0], float(mat.m[0]), 	float(mat.m[1]), 	float(mat.m[2]), 	float(mat.m[3]));
	glUniform4f( MVP[1], float(mat.m[4]), 	float(mat.m[5]), 	float(mat.m[6]), 	float(mat.m[7]));
	glUniform4f( MVP[2], float(mat.m[8]), 	float(mat.m[9]), 	float(mat.m[10]), 	float(mat.m[11]));
	glUniform4f( MVP[3], float(mat.m[12]), 	float(mat.m[13]), 	float(mat.m[14]), 	float(mat.m[15]));
}

void SendWorldMatrixtoShader(Matrix44<double> mat)
{
	glUniform4f( WM[0], float(mat.m[0]), 	float(mat.m[1]), 	float(mat.m[2]), 	float(mat.m[3]));
	glUniform4f( WM[1], float(mat.m[4]), 	float(mat.m[5]), 	float(mat.m[6]), 	float(mat.m[7]));
	glUniform4f( WM[2], float(mat.m[8]), 	float(mat.m[9]), 	float(mat.m[10]), 	float(mat.m[11]));
	glUniform4f( WM[3], float(mat.m[12]), 	float(mat.m[13]), 	float(mat.m[14]), 	float(mat.m[15]));
}

void Send1F(GLint pos, float p)
{
	glUniform1f( pos, p);
}

void Send1I(GLint pos, float p)
{
	glUniform1i( pos, p);
}

void Send3F(GLint pos, t3dpoint<float> p)
{
	glUniform3f( pos, p.x, p.y, p.z);
}

void Send4F(GLint pos, t4dpoint<float> p)
{
	glUniform4f( pos, p.x, p.y, p.z, p.w);
}


void Send4F3(GLint pos, t4dpoint<float> p)
{
	glUniform3f( pos, p.x, p.y, p.z);
}


void Send3F4(GLint pos, t3dpoint<float> p)
{
	glUniform4f( pos, p.x, p.y, p.z, 1.0f);
}




GLuint createProgram()
{

    GLuint program = glCreateProgram();
    if (program) {
        glAttachShader(program, VERTEX);
		glAttachShader(program, FRAGMENT);
		if (geomloaded == true)
        glAttachShader(program, GEOMETRY);
        // Bind attributes
//           GLES20.glBindAttribLocation(programHandle, 0, "a_Position");
//           GLES20.glBindAttribLocation(programHandle, 1, "a_Color");


        glLinkProgram(program);


        GLint linkStatus = GL_FALSE;

        glGetProgramiv(program, GL_LINK_STATUS, &linkStatus);


        if (linkStatus == GL_TRUE)
        {
            vertex_pos 		= glGetAttribLocation(program,"Vpos");
            texture_coord 	= glGetAttribLocation(program,"Vtexcoord");
            vertex_normal 	= glGetAttribLocation(program,"Vnormal");
            vertex_color 	= glGetAttribLocation(program,"Vcolor");
            vertex_height 	= glGetAttribLocation(program,"Vheight");
			displacement 	= glGetAttribLocation(program,"Vdisplacement");
//
//            MVP[0] = glGetUniformLocation(program, "MVP1");
//            MVP[1] = glGetUniformLocation(program, "MVP2");
//            MVP[2] = glGetUniformLocation(program, "MVP3");
//            MVP[3] = glGetUniformLocation(program, "MVP4");
        }

        if (linkStatus != GL_TRUE) {
            GLint bufLength = 0;

            glGetProgramiv(program, GL_INFO_LOG_LENGTH, &bufLength);

            if (bufLength) {
                char* buf = (char*) malloc(bufLength);
                if (buf) {
                    glGetProgramInfoLog(program, bufLength, NULL, buf);
                    free(buf);
                		 }//buff
            			   } //buffLength
            glDeleteProgram(program);
            program = 0;
        							}//linkstatus
    }//program
    return program;
}


bool LoadShaderProgram(AnsiString vp, AnsiString fp, AnsiString gp)
{
	LoadVertexShader(vp);
	LoadFragmentShader(fp);
	if (FileExists(gp))
	LoadGeometryShader(gp);

    gProgram = createProgram();
    if (!gProgram) { ShowMessage("There are errors in: "+vp); }
    GetAllUniformLocations();

    return true;
}


};






#endif 

[/spoiler]

 

[/spoiler]

 

 

but before ypou continue you check if extensions are already loaded (chaced by using wglgetprocadrees etc), if they're 0 then you cant even run your program

 

 

 

 

 

 

 

After all that you can reply here and tell us if you have everything intact, so we can move further on.

[spoiler]

 

[/spoiler]

Share this post


Link to post
Share on other sites

try to stop using shaders on rendering pass, then disable all framebuffers, shaders, 

 

then using my code:

some global 
TShaderObject * pplight_shader;


reloading_shaders = true;
disable all

delete pplight_shader;
pplight_shader = 0;


 pplight_shader = new TShaderObject();
  pplight_shader->LoadShaderProgram(appdir+"shaders/lighting/perpixel_vp.shader",
  appdir+"shaders/lighting/perpixel_fp.shader","");

reloading_shaders = false;

then you switch back rendering state to use shaders (try to stop using shaders on rendering pass,)

 

its a fkn simple bool that you use during render pass like if(!reloading_shaders) DrawMyScene();

 

heres the code with destructor

[spoiler]

#ifndef shaderclassH
#define shaderclassH

#include "txtfile\stringlist.h"
#include "logme.h"
#include "DxcMatrix.h"


template <class T>
const T * readShaderFile( AnsiString FileName )
{
	ALOG("readShaderFile const char *");
	ALOG("create tstringlist");
TStringList * s = new TStringList();
ALOG("load from file: " +FileName);
s->LoadFromFile(FileName);
ALOG("GetText");
AnsiString bollock = s->GetText();
//char* dest = new char[str.length() + 1];std::copy(str.begin(), str.end(), dest);

//now that would work
ALOG("const T * buff - new T[bollock.length()];");
	const T * buffer = new T[bollock.length()];
	ALOG("buffer = bollock.c_str()");
											  buffer = bollock.c_str();

											  ALOG("delete s");
											  delete s;
											  ALOG("return buffer");
	return buffer;
}





struct TShaderObject
{
public:
//	~TShaderObject()
//	{
//glDeleteProgram(gProgram);
//	}


	GLuint VERTEX;
	GLuint FRAGMENT;
	GLuint gProgram;
//	GLuint gvPositionHandle;

	std::string Vertexdata;
	std::string Fragmentdata;

//TStringList * vert_prog;
//TStringList * frag_prog;

//char * vert;
//char * frag;

GLint vertex_pos;
GLint texture_coord;
GLint vertex_normal;
GLint vertex_color;
GLint vertex_height;
GLint displacement;

GLint MVP[4];

GLint SMVP[4];

GLint WM[4];

GLint MV[4];
GLint ITWM[3];

GLint PROJECTION_MAT[4];

GLint cubemap;

GLint LightAMB;
GLint LightDiff;
GLint LightPos;


//
//GLint u_geometrySize;
//GLint u_displacementMap;
//GLint u_normalMap;
GLint u_oceanColor;
GLint u_skyColor;
GLint u_sunDirection;
GLint u_exposure;


GLuint amplitude;
GLuint wavelength;
GLuint speed;
GLuint direction;
//glUniform3fv
//
//GLint u_transformSize;
//GLint u_resolution;
//GLint u_initialSpectrum;
//
//
//GLint u_wind;
//GLint u_size;
//GLint u_phases;
//GLint u_deltaTime;
//GLint u_choppiness;
//GLint u_input;
//GLint u_subtransformSize;
GLint u_cameraPosition;





void Enable()
{
glUseProgram(gProgram);
}


void Disable()
{
glUseProgram(0);
}
private:

bool LoadData(std::string &data, const std::string &filename)
{
    std::ifstream file(filename.c_str(), std::ifstream::in | std::ifstream::ate);
    if(file.is_open())
    {
        std::streampos size(file.tellg());
        file.seekg(0, std::ios::beg);
        data.reserve(size);
        data.append((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
        file.close();
        return true;
    }

    return false;
}

GLuint LoadShader(GLenum shaderType, const char* pSource)
{

    GLuint shader = glCreateShader(shaderType);
    if (shader) {

        glShaderSource(shader, 1, &pSource, NULL);

        glCompileShader(shader);
        GLint compiled = 0;

        glGetShaderiv(shader, GL_COMPILE_STATUS, &compiled);

        if (compiled == GL_FALSE)
        {

        	GetShaderError(shader);


                glDeleteShader(shader);
                shader = 0;
        }//!compiled



    } //shader

    return shader;
}


void GetShaderError(GLuint &shader)
{
    int logSize = 0;
    glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &logSize);
    ALOG("Error length: "+IntToStr(logSize));
    std::vector<GLchar> error(logSize);
    glGetShaderInfoLog(shader, logSize, &logSize, &error[0]);

if (logSize > 0)
{
	ALOG("RETURNING ERROR");

    std::string str = "";
    int i;
    for (i=0; i < logSize; i++)
    	str = str + error[i];

    ALOG(str);

} else ALOG("bufflen 0 abroting - thers definetly an error during shader make");
}

void LoadVertexShader(AnsiString fname)
{
	ALOG("Loading vertex shader " + fname);
	Vertexdata = "";
	LoadData(Vertexdata, fname);
	VERTEX 		= LoadShader(GL_VERTEX_SHADER, Vertexdata.c_str());//readShaderFile<char>(fname));
//	ALOG("done");
}

void LoadFragmentShader(AnsiString fname)
{
	ALOG("Loading fragment shader " + fname);
	Fragmentdata = "";
	LoadData(Fragmentdata, fname);
	FRAGMENT 	= LoadShader(GL_FRAGMENT_SHADER,  Fragmentdata.c_str()); //readShaderFile<char>(fname));
//	ALOG("done");
}

void LoadVertexShaderStr(const char * source)
{
	VERTEX 		= LoadShader(GL_VERTEX_SHADER, source);
}

void LoadFragmentShaderStr(const char * source)
{
	FRAGMENT 	= LoadShader(GL_FRAGMENT_SHADER, source);
}

public:
void GetAllUniformLocations()
{

    MVP[0] = glGetUniformLocation(gProgram, "MVP1");
    MVP[1] = glGetUniformLocation(gProgram, "MVP2");
    MVP[2] = glGetUniformLocation(gProgram, "MVP3");
    MVP[3] = glGetUniformLocation(gProgram, "MVP4");

    SMVP[0] = glGetUniformLocation(gProgram, "SMVP1");
    SMVP[1] = glGetUniformLocation(gProgram, "SMVP2");
    SMVP[2] = glGetUniformLocation(gProgram, "SMVP3");
    SMVP[3] = glGetUniformLocation(gProgram, "SMVP4");


     amplitude 	= glGetUniformLocation(gProgram, "amplitude");
     wavelength = glGetUniformLocation(gProgram, "wavelength");
     speed 		= glGetUniformLocation(gProgram, "speed");
     direction 	= glGetUniformLocation(gProgram, "direction");


	    //used for lighting shader (for transforming vertex normal)
	    WM[0] = glGetUniformLocation(gProgram, "WM1");
	    WM[1] = glGetUniformLocation(gProgram, "WM2");
	    WM[2] = glGetUniformLocation(gProgram, "WM3");
	    WM[3] = glGetUniformLocation(gProgram, "WM4");


	    LightPos = glGetUniformLocation(gProgram, "LPOS");
	    LightDiff = glGetUniformLocation(gProgram, "LDIFF");
	    LightAMB = glGetUniformLocation(gProgram, "LAMB");


	    cubemap =  glGetUniformLocation(gProgram, "cubemap");
	    u_cameraPosition 	= glGetUniformLocation(gProgram,"u_cameraPosition");


//modelview matrix
	    MV[0] = glGetUniformLocation(gProgram, "MV1");
	    MV[1] = glGetUniformLocation(gProgram, "MV2");
	    MV[2] = glGetUniformLocation(gProgram, "MV3");
	    MV[3] = glGetUniformLocation(gProgram, "MV4");
//transpose(inverse(modelview matrix));
	    ITWM[0] = glGetUniformLocation(gProgram, "ITWM1");
	    ITWM[1] = glGetUniformLocation(gProgram, "ITWM2");
	    ITWM[2] = glGetUniformLocation(gProgram, "ITWM3");
//	    ITWM[3] = glGetUniformLocation(gProgram, "ITWM4");

	    PROJECTION_MAT[0] = glGetUniformLocation(gProgram, "PROJECTION_MAT1");
	    PROJECTION_MAT[1] = glGetUniformLocation(gProgram, "PROJECTION_MAT2");
	    PROJECTION_MAT[2] = glGetUniformLocation(gProgram, "PROJECTION_MAT3");
	    PROJECTION_MAT[3] = glGetUniformLocation(gProgram, "PROJECTION_MAT4");
}


void GetOceanUniforms()
{

    u_cameraPosition 	= glGetUniformLocation(gProgram,"u_cameraPosition");


}

void SetLightPos(t3dpoint<float> p)
{
	glUniform3f( LightPos, p.x, p.y, p.z);
}

void SetLightAmbient(t3dpoint<float> p)
{
	glUniform3f( LightAMB, p.x, p.y, p.z);
}

void SetLightDiffuse(t3dpoint<float> p)
{
	glUniform3f( LightDiff, p.x, p.y, p.z);
}


void SendProjectionMattoShader(Matrix44<float> mat)
{
	glUniform4f( PROJECTION_MAT[0], mat.m[0], 	mat.m[1], 	mat.m[2], 	mat.m[3]);
	glUniform4f( PROJECTION_MAT[1], mat.m[4], 	mat.m[5], 	mat.m[6], 	mat.m[7]);
	glUniform4f( PROJECTION_MAT[2], mat.m[8], 	mat.m[9], 	mat.m[10], 	mat.m[11]);
	glUniform4f( PROJECTION_MAT[3], mat.m[12], mat.m[13], 	mat.m[14], 	mat.m[15]);
}

void SendMVPtoShader(Matrix44<float> mat)
{
	glUniform4f( MVP[0], mat.m[0], 	mat.m[1], 	mat.m[2], 	mat.m[3]);
	glUniform4f( MVP[1], mat.m[4], 	mat.m[5], 	mat.m[6], 	mat.m[7]);
	glUniform4f( MVP[2], mat.m[8], 	mat.m[9], 	mat.m[10], 	mat.m[11]);
	glUniform4f( MVP[3], mat.m[12], mat.m[13], 	mat.m[14], 	mat.m[15]);
}


void SendShadowMVPtoShader(Matrix44<float> mat)
{
	glUniform4f( SMVP[0], mat.m[0], 	mat.m[1], 	mat.m[2], 	mat.m[3]);
	glUniform4f( SMVP[1], mat.m[4], 	mat.m[5], 	mat.m[6], 	mat.m[7]);
	glUniform4f( SMVP[2], mat.m[8], 	mat.m[9], 	mat.m[10], 	mat.m[11]);
	glUniform4f( SMVP[3], mat.m[12], 	mat.m[13], 	mat.m[14], 	mat.m[15]);
}


void SendNormalMatrixtoShader(Matrix44<float> mat) //this must be 3x3 matrix defined in 4x4 mat
{
	glUniform3f( ITWM[0], mat.m[0], 	mat.m[1], 	mat.m[2]);
	glUniform3f( ITWM[1], mat.m[4], 	mat.m[5], 	mat.m[6]);
	glUniform3f( ITWM[2], mat.m[8], 	mat.m[9], 	mat.m[10]);
}

void SendModelViewMatrixtoShader(Matrix44<float> mat)
{
	glUniform4f( MV[0], mat.m[0], 	mat.m[1], 	mat.m[2], 	mat.m[3]);
	glUniform4f( MV[1], mat.m[4], 	mat.m[5], 	mat.m[6], 	mat.m[7]);
	glUniform4f( MV[2], mat.m[8], 	mat.m[9], 	mat.m[10], 	mat.m[11]);
	glUniform4f( MV[3], mat.m[12],  mat.m[13], 	mat.m[14], 	mat.m[15]);
}

void SendWorldMatrixtoShader(Matrix44<float> mat)
{
	glUniform4f( WM[0], mat.m[0], 	mat.m[1], 	mat.m[2], 	mat.m[3]);
	glUniform4f( WM[1], mat.m[4], 	mat.m[5], 	mat.m[6], 	mat.m[7]);
	glUniform4f( WM[2], mat.m[8], 	mat.m[9], 	mat.m[10], 	mat.m[11]);
	glUniform4f( WM[3], mat.m[12],  mat.m[13], 	mat.m[14], 	mat.m[15]);
}

void Send1F(GLint pos, float p)
{
	glUniform1f( pos, p);
}

void Send1I(GLint pos, int p)
{
	glUniform1i( pos, p);
}

void Send3F(GLint pos, t3dpoint<float> p)
{
	glUniform3f( pos, p.x, p.y, p.z);
}

void Send4F(GLint pos, t4dpoint<float> p)
{
	glUniform4f( pos, p.x, p.y, p.z, p.w);
}


void Send4F3(GLint pos, t4dpoint<float> p)
{
	glUniform3f( pos, p.x, p.y, p.z);
}


void Send3F4(GLint pos, t3dpoint<float> p)
{
	glUniform4f( pos, p.x, p.y, p.z, 1.0f);
}


void GetLinkerError()
{
    GLint bufLength = 0;

           glGetProgramiv(gProgram, GL_INFO_LOG_LENGTH, &bufLength);

           ALOG("Program error length: "+IntToStr(bufLength));
           std::vector<GLchar> error(bufLength);

           glGetProgramInfoLog(gProgram, bufLength, &bufLength, &error[0]);

       if (bufLength > 0)
       {
           std::string str = "";
           int i;
           for (i=0; i < bufLength; i++)
           	str = str + error[i];

           ALOG(str);

       }
}

void createProgram()
{

	gProgram = glCreateProgram();
    if (gProgram) {
        glAttachShader(gProgram, VERTEX);
        glAttachShader(gProgram, FRAGMENT);


        glLinkProgram(gProgram);


        GLint linkStatus = GL_FALSE;

        glGetProgramiv(gProgram, GL_LINK_STATUS, &linkStatus);


        if (linkStatus == GL_TRUE)
        {
         	ALOG("LINK STATUS good ");
            vertex_pos 		= glGetAttribLocation(gProgram,"Vpos");
            texture_coord 	= glGetAttribLocation(gProgram,"Vtexcoord");
            vertex_normal 	= glGetAttribLocation(gProgram,"Vnormal");
            vertex_color 	= glGetAttribLocation(gProgram,"Vcolor");
            vertex_height 	= glGetAttribLocation(gProgram,"Vheight");
            displacement	= glGetAttribLocation(gProgram,"Vdisplacement");
//ALOG("DISPLACEMENT POS: "+IntToStr(displacement));
//
//            MVP[0] = glGetUniformLocation(program, "MVP1");
//            MVP[1] = glGetUniformLocation(program, "MVP2");
//            MVP[2] = glGetUniformLocation(program, "MVP3");
//            MVP[3] = glGetUniformLocation(program, "MVP4");
        }

        else {
        	ALOG("LINK STATUS FALSE");
       GetLinkerError();

            glDeleteProgram(gProgram);
            gProgram = 0;
      }//linkstatus

    }//program

}

bool initialized;


TShaderObject()
{
initialized = false;
}

~TShaderObject()
{
if (initialized)
glDeleteProgram(gProgram);

}

bool LoadShaderProgram(AnsiString vp, AnsiString fp)
{
	LoadVertexShader(vp);
	LoadFragmentShader(fp);

    createProgram();
    if (!gProgram) return false;
    GetAllUniformLocations();

    initialized = true;
    return true;
}

bool LoadShaderStrProgram(const char * vp, const char * fp)
{
	LoadVertexShaderStr(vp);
	LoadFragmentShaderStr(fp);

    createProgram();
    if (!gProgram) return false;
    GetAllUniformLocations();

    initialized = true;
    return true;
}


};






#endif
 

[/spoiler]

 

sinmce i see i dont have completedestructor i read your code and see:

 

GLint status;
    glGetProgramiv(program->Name, GL_LINK_STATUS, &status);
    if (status == GL_FALSE) {
        char *errorMsg = GetCompileError(program->Name, glGetProgramInfoLog, Temporary(game->Memory->System));
        DebugText(game, 5, errorMsg);
        return false;

 

shouldnt be there

 

 

anyway 

 

this line is a whole bunch of crap

 

B32 CompileShaderProgram(Game *game, shader_program *program)
{

 

  glLinkProgram(program->Name);????????

    for (U32 i=0; i<program->len; ++i)
    {
        U32 Name = (U64)program->shaders[i]->Data;
        glAttachShader(program->Name, Name);
    }

    const GLchar *fv[] = {"gl_Position"};
    glTransformFeedbackVaryings(program->Name, 1, fv, GL_INTERLEAVED_ATTRIBS);

    glLinkProgram(program->Name);

 

//you hurt here amd feelings

 

why you deattach shader while attempting to load it
    for (U32 i=0; i<program->len; ++i) {
        U32 Name = (U64)program->shaders[i]->Data;
        DebugLog(game, LogType_Render, "Detaching to %d shader %d", program->Name, Name);
        glDetachShader(program->Name, Name);
        glDeleteShader(Name); N/C
    }
N/C
    GLint status;
    glGetProgramiv(program->Name, GL_LINK_STATUS, &status);
    if (status == GL_FALSE) {
        char *errorMsg = GetCompileError(program->Name, glGetProgramInfoLog, Temporary(game->Memory->System));
        DebugText(game, 5, errorMsg);
        return false;
    } else {
        return true;
    }
}

 

 

 

withm my code you need to add another variation since there is no shader deattaching you simply deattach them while loading or or deattaching and deleting when its initialized anyway tho read some kind of shader loading tutorial

Edited by WiredCat

Share this post


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

  • Advertisement