Exemplo n.º 1
0
void initialize() {
	
	if(!isEnabled()) {
		return;
	}
	
	bool have_debug = ARX_HAVE_GL_VER(4, 3) || ARX_HAVE_GL_EXT(KHR_debug);
	#if ARX_HAVE_EPOXY
	have_debug = have_debug || (epoxy_is_desktop_gl() && ARX_HAVE_GL_EXT(ARB_debug_output));
	#endif
	if(!have_debug) {
		LogWarning << "OpenGL debug output not available";
		return;
	}
	
	glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
	
	// GLEW versions before 1.11.0 define GLDEBUGPROC with a non-const user pointer
	#if !ARX_HAVE_GLEW || defined(GLEW_VERSION_4_5)
	glDebugMessageCallback(gldebug::callback, NULL);
	#else
	glDebugMessageCallback((GLDEBUGPROC)gldebug::callback, NULL);
	#endif
	
	// Forward messages with high severity level
	glDebugMessageControl(GL_DONT_CARE,
	                      GL_DONT_CARE,
	                      GL_DEBUG_SEVERITY_HIGH,
	                      0,
	                      NULL,
	                      GL_TRUE);
	
	// Forward messages with medium severity level
	glDebugMessageControl(GL_DONT_CARE,
	                      GL_DONT_CARE,
	                      GL_DEBUG_SEVERITY_MEDIUM,
	                      0,
	                      NULL,
	                      GL_TRUE);
	
	// Forward messages from the application
	glDebugMessageControl(GL_DEBUG_SOURCE_APPLICATION,
	                      GL_DONT_CARE,
	                      GL_DONT_CARE,
	                      0,
	                      NULL,
	                      GL_TRUE);
	
	
	std::string strInitialized("OpenGL debug output enabled");
	glDebugMessageInsert(GL_DEBUG_SOURCE_APPLICATION,
	                     GL_DEBUG_TYPE_OTHER,
	                     1,
	                     GL_DEBUG_SEVERITY_LOW,
	                     GLsizei(strInitialized.size()), strInitialized.c_str());
}
Exemplo n.º 2
0
static void APIENTRY video_gl_debug_enable(void) {
	GLuint unused = 0;
	glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
	glDebugMessageCallback(video_gl_debug, NULL);
	glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, &unused, true);
	log_info("Enabled OpenGL debugging");
}
Exemplo n.º 3
0
void Engine::initGLUT() {
	int argc = 1;
	char *argv[] = {"Bin", NULL};
	glutInit(&argc, argv);

	if(context->core) {
		glutInitContextVersion(context->majorVersion, context->minorVersion);
		glutInitContextProfile(GLUT_CORE_PROFILE);
	} else {
		glutInitContextProfile(GLUT_COMPATIBILITY_PROFILE);
	}

	glutInitDisplayMode(framebuffer->flags);
	glutInitWindowPosition(window->positionX, window->positionY);
	glutInitWindowSize(window->width, window->height);
	// in case GL_DEBUG_OUTPUT doesn't work
	// glutInitContextFlags(GLUT_DEBUG);
	glutCreateWindow(window->name.c_str());

	std::cout << "GLUT initialized\n";
	glEnable(GL_DEBUG_OUTPUT);

	glutSetWindowData(static_cast<void *>(this));

	glutIdleFunc(idleCallback);
	glutDisplayFunc(displayCallback);
	glutReshapeFunc(reshapeCallback);
	glutCloseFunc(closeCallback);

	glutKeyboardFunc(handleKeyboardCallback);
	glutKeyboardUpFunc(handleKeyboardUpCallback);
	glutSpecialFunc(handleKeyboardSpecialCallback);
	glutSpecialUpFunc(handleKeyboardSpecialUpCallback);
	glutMotionFunc(handleMouseMovement);
	glutPassiveMotionFunc(handleMouseMovement);

	initGLEW();

	glDebugMessageCallback(DebugOutput::printDebugOutput, NULL);
	//GLenum severity = GL_DEBUG_SEVERITY_LOW | GL_DEBUG_SEVERITY_MEDIUM | GL_DEBUG_SEVERITY_HIGH | GL_DEBUG_SEVERITY_NOTIFICATION;
	glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE);
	glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_NOTIFICATION, 0, NULL, GL_FALSE);
	glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_GLUTMAINLOOP_RETURNS);

	std::cout << "Info | Vendor: " << glGetString(GL_VENDOR) << " | Renderer: " << glGetString(GL_RENDERER) << " | OpenGl version: " << glGetString(GL_VERSION) << std::endl;
}
Exemplo n.º 4
0
void RegisterErrorCallback()
{
    glDebugMessageCallback(OpenGLErrorCallback, nullptr);
    glDebugMessageControl(
        GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE);

    glEnable(GL_DEBUG_OUTPUT);
}
Exemplo n.º 5
0
// Debug context logger registration
void registerGlDebugLogger(unsigned int logLevel) {
	glDebugLogLevel = logLevel;
	glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
	glDebugMessageControl = (PFNGLDEBUGMESSAGECONTROLARBPROC) wglGetProcAddress("glDebugMessageControlARB");
	glDebugMessageCallback = (PFNGLDEBUGMESSAGECALLBACKARBPROC) wglGetProcAddress("glDebugMessageCallbackARB");
	glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE);
	glDebugMessageCallback(&debugCallback, NULL);
}
Exemplo n.º 6
0
// --------------------------------------------------------------------------------------------------------------------
bool GfxApiOpenGLBase::Init(const std::string& _title, int _x, int _y, int _width, int _height)
{
#if defined(_DEBUG)
    //glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, 1);
#endif

    mWnd = CreateGLWindow(_title.c_str(), _x, _y, _width, _height);
    if (!mWnd) {
        console::warn("Unable to create SDL Window, which is required for GL.");
        return false;
    }

    if (!GfxBaseApi::Init(_title, _x, _y, _width, _height)) {
        return false;
    }

    glfwMakeContextCurrent(mWnd);

    if (g_bInitOpenGL)
    {
        g_bInitOpenGL = false;
        GLenum err = glewInit();
        if (GLEW_OK != err)
        {
            console::error("Unable to initialize GLEW; err: %s -- required -- so exiting.", glewGetErrorString(err));
            return false;
        }
    }

    console::log("GL created successfully! Info follows.");
    console::log("Vendor: %s", glGetString(GL_VENDOR));
    console::log("Renderer: %s", glGetString(GL_RENDERER));
    console::log("Version: %s", glGetString(GL_VERSION));
    console::log("Shading Language Version: %s", glGetString(GL_SHADING_LANGUAGE_VERSION));

    glfwSwapInterval(0);

    // Default GL State
    glCullFace(GL_FRONT);
    glEnable(GL_CULL_FACE);
    glDisable(GL_SCISSOR_TEST);
    glEnable(GL_DEPTH_TEST);
    glDepthMask(1);
    glDepthFunc(GL_LESS);
    glDisable(GL_BLEND);
    glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);

#if defined(_DEBUG)
    if (glDebugMessageControl != NULL && glDebugMessageCallback != NULL) {
        glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE);
        // glDebugMessageControl(GL_DEBUG_SOURCE_API, GL_DEBUG_TYPE_OTHER, GL_DEBUG_SEVERITY_LOW, 0, nullptr, GL_FALSE);
        glDebugMessageCallback(ErrorCallback, nullptr);
        glEnable(GL_DEBUG_OUTPUT);
    }
#endif

    return true;
}
Exemplo n.º 7
0
void GlfwApp::onCreate() {
  windowAspect = glm::aspect(windowSize);
  windowAspectInverse = 1.0f / windowAspect;
  glfwSetWindowUserPointer(window, this);
  glfwSetKeyCallback(window, glfwKeyCallback);
  glfwSetMouseButtonCallback(window, glfwMouseButtonCallback);
  glfwMakeContextCurrent(window);
  glfwSwapInterval(1);

// Initialize the OpenGL bindings
// For some reason we have to set this experminetal flag to properly
// init GLEW if we use a core context.
  glewExperimental = GL_TRUE;
  if (0 != glewInit()) {
    FAIL("Failed to initialize GL3W");
  }
  glGetError();
#ifdef RIFT_DEBUG
  GL_CHECK_ERROR;
  glEnable (GL_DEBUG_OUTPUT_SYNCHRONOUS);
  GL_CHECK_ERROR;
  GLuint unusedIds = 0;
  if (glDebugMessageCallback) {
    glDebugMessageCallback(debugCallback, this);
    GL_CHECK_ERROR;
    glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE,
        0, &unusedIds, true);
    GL_CHECK_ERROR;

  } else if (glDebugMessageCallbackARB) {
    glDebugMessageCallbackARB(debugCallback, this);
    GL_CHECK_ERROR;
    glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE,
        0, &unusedIds, true);
    GL_CHECK_ERROR;
  }
#endif
  GL_CHECK_ERROR;
/*
  if (glNamedStringARB) {
    for (int i = 0;
        Resources::LIB_SHADERS[i] != Resource::NO_SHADER; ++i) {

      std::string shaderFile = getShaderPath(
          Resources::LIB_SHADERS[i]);
      std::string shaderSrc = Files::read(shaderFile);
      size_t lastSlash = shaderFile.rfind('/');
      std::string name = shaderFile.substr(lastSlash);
      glNamedStringARB(GL_SHADER_INCLUDE_ARB,
          name.length(), name.c_str(),
          shaderSrc.length(), shaderSrc.c_str());
      GL_CHECK_ERROR;
    }
  }
*/
  compileAllShaders(Resources::VERTEX_SHADERS, GL_VERTEX_SHADER);
  compileAllShaders(Resources::FRAGMENT_SHADERS, GL_FRAGMENT_SHADER);
}
Exemplo n.º 8
0
void gl_log_enable() {
#if !defined(USING_GLES2)
#if 0
	glEnable(DEBUG_OUTPUT_SYNCHRONOUS_ARB);	// TODO: Look into disabling, for more perf
	glDebugMessageCallback(&log_callback, 0);
	glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, 0, GL_TRUE);
#endif
#endif
}
Exemplo n.º 9
0
void initializeGL() {
  glDebugMessageCallback(GLUtils::debugCallback, NULL);
  glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE);
  glDebugMessageInsert(GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_MARKER, 0, 
  GL_DEBUG_SEVERITY_NOTIFICATION, -1 , "Start debugging");
  
    glClearColor(0.5f,0.5f,0.5f,1.0f);
    scene->initScene();
}
Exemplo n.º 10
0
bool initDebug()
{
	bool Validated(true);

	glEnable(GL_DEBUG_OUTPUT);
	glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
	glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE);
	glDebugMessageCallback(&glf::debugOutput, NULL);

	return Validated;
}
Exemplo n.º 11
0
void nsfw::Window::init(unsigned width, unsigned height)
{
	//TODO_D("Should create and set an active windowing context. ONLY GLFW! No GL!");

	

	//set width and height for later use
	this->width = width;
	this->height = height;

	//Initialize glfw
	glfwInit();
	//tell glfw to use debug stuff
	glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, true);
	//create title of the window
	const char* title = "nsfwgl Test";

	//create the window
	window = glfwCreateWindow(width, height, title, nullptr, nullptr);

	//check to make sure window is created and functioning
	//if window isn't creating properly then let the console know
	if (window == nullptr)
		std::cout << "\n\n\n\n ERROR: WINDOW CREATION UNSUCCESSFUL \n\n\n\n" << std::endl;

	//set window to current context
	glfwMakeContextCurrent(window);

	//load functions
	if (ogl_LoadFunctions() == ogl_LOAD_FAILED)
	{
		glfwDestroyWindow(window);
		glfwTerminate();
	}

	//this is for glfw debug 
#ifdef _DEBUG
	if (glDebugMessageCallback)
	{
		glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
		glDebugMessageCallback(oglErrorDefaultCallback, nullptr);

		GLuint unusedIDs = 0;
		glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, &unusedIDs, true);
	}
	else
	{
		std::cerr << "Failed to subscribe to glDebugMessageCallback." << std::endl;
	}
#endif
}
Exemplo n.º 12
0
/**
 * Configures GL_ARB_debug_output to give us immediate callbacks when
 * GL errors occur, so that we can log them.
 */
static void
glamor_setup_debug_output(ScreenPtr screen)
{
    if (!epoxy_has_gl_extension("GL_ARB_debug_output"))
        return;

    glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
    /* Disable debugging messages other than GL API errors */
    glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL,
                          GL_FALSE);
    glDebugMessageControl(GL_DEBUG_SOURCE_API,
                          GL_DEBUG_TYPE_ERROR,
                          GL_DONT_CARE,
                          0, NULL, GL_TRUE);
    glDebugMessageCallback(glamor_debug_output_callback,
                           screen);

    /* If KHR_debug is present, all debug output is disabled by
     * default on non-debug contexts.
     */
    if (epoxy_has_gl_extension("GL_KHR_debug"))
        glEnable(GL_DEBUG_OUTPUT);
}
Exemplo n.º 13
0
void initGL()
{
    if (is_gl_init)
        return;
        
    is_gl_init = true;
    // For Mesa extension reporting
#if !defined(USE_GLES2)
#ifndef WIN32
    glewExperimental = GL_TRUE;
#endif
    GLenum err = glewInit();
    
    if (err == GLEW_ERROR_NO_GLX_DISPLAY)
    {
        Log::info("GLEW", "Glew couldn't open glx display.");
    }
    else if (err != GLEW_OK)
    {
        Log::fatal("GLEW", "Glew initialization failed with error %s", glewGetErrorString(err));
    }
#else
#ifdef ARB_DEBUG_OUTPUT
    glDebugMessageCallbackARB = (PFNGLDEBUGMESSAGECALLBACKKHRPROC)eglGetProcAddress("glDebugMessageCallbackKHR");
#endif
#endif

#ifdef ARB_DEBUG_OUTPUT
    if (glDebugMessageCallbackARB)
        glDebugMessageCallbackARB((GLDEBUGPROCARB)debugCallback, NULL);
#endif

#ifndef ANDROID
    if (SP::sp_apitrace && hasGLExtension("GL_KHR_debug"))
    {
#ifdef USE_GLES2
        glDebugMessageControl = (void(GL_APIENTRY*)(GLenum, GLenum, GLenum, GLsizei,
            const GLuint*, GLboolean))eglGetProcAddress("glDebugMessageControlKHR");
        glDebugMessageInsert = (void(GL_APIENTRY*)(GLenum, GLenum, GLuint, GLenum,
            GLsizei, const char*))eglGetProcAddress("glDebugMessageInsertKHR");
        assert(glDebugMessageControl && glDebugMessageInsert);
#endif
        glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE);
    }
    else
    {
        SP::sp_apitrace = false;
    }
#endif
}
Exemplo n.º 14
0
//--------------------------------------------------------------
void ofxOpenVR::exit()
{
	if (vr::VRCompositor()->IsMirrorWindowVisible()) {
		hideMirrorWindow();
	}

	if (_pHMD)
	{
		vr::VR_Shutdown();
		_pHMD = NULL;
	}

	for (std::vector< CGLRenderModel * >::iterator i = _vecRenderModels.begin(); i != _vecRenderModels.end(); i++)
	{
		delete (*i);
	}
	_vecRenderModels.clear();

	if (_bIsGLInit)
	{
		glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_FALSE);
		glDebugMessageCallback(nullptr, nullptr);
		glDeleteBuffers(1, &_glIDVertBuffer);
		glDeleteBuffers(1, &_glIDIndexBuffer);

		glDeleteRenderbuffers(1, &leftEyeDesc._nDepthBufferId);
		glDeleteTextures(1, &leftEyeDesc._nRenderTextureId);
		glDeleteFramebuffers(1, &leftEyeDesc._nRenderFramebufferId);
		glDeleteTextures(1, &leftEyeDesc._nResolveTextureId);
		glDeleteFramebuffers(1, &leftEyeDesc._nResolveFramebufferId);

		glDeleteRenderbuffers(1, &rightEyeDesc._nDepthBufferId);
		glDeleteTextures(1, &rightEyeDesc._nRenderTextureId);
		glDeleteFramebuffers(1, &rightEyeDesc._nRenderFramebufferId);
		glDeleteTextures(1, &rightEyeDesc._nResolveTextureId);
		glDeleteFramebuffers(1, &rightEyeDesc._nResolveFramebufferId);

		if (_unLensVAO != 0)
		{
			glDeleteVertexArrays(1, &_unLensVAO);
		}

		_lensShader.unload();
		_controllersTransformShader.unload();
		_renderModelsShader.unload();
	}

	
}
Exemplo n.º 15
0
	void BaseApplication::InitDependency(vec3 a_vCamPos)
	{
		if (ogl_LoadFunctions() == ogl_LOAD_FAILED)
		{
			glfwTerminate();
			printf("<ERROR>: ogl_LoadFunctions has fail initialization. \n");
			exit(EXIT_FAILURE);
		}
		else
		{
			printf("--------------------------------------------------------------------------------");
			printf("-- OGL LOADED SUCCESSFULLY. \n");
			if (this->m_oApp->APPINFO.Flags.m_uiDebug)
			{ 
				glDebugMessageCallback(debug_callback, NULL);
				if (glDebugMessageCallback != NULL)
				{
					glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
				}
				glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE);
				glDebugMessageInsert(GL_DEBUG_SOURCE_APPLICATION, GL_DEBUG_TYPE_MARKER, 0, GL_DEBUG_SEVERITY_NOTIFICATION, -1, "START DEBUGGING\n");
			}
			//this->DATA.m_oTweeking = new Bar();
			//this->DATA.m_oTweeking->InitTweek();
			printf("-- GL DEBUG MESSAGE ENABLED. \n");
			glfwSetCharModsCallback(this->m_oApp->DATA.m_oWin, on_char_callback);
			printf("-- CHAR_CALLBACK ENABLED. \n");
			glfwSetKeyCallback(this->m_oApp->DATA.m_oWin, key_callback);
			printf("-- KEY_CALLBACK ENABLED. \n");
			glfwSetMouseButtonCallback(this->m_oApp->DATA.m_oWin, mouse_button_callback);
			glfwSetCursorPosCallback(this->m_oApp->DATA.m_oWin, mouse_callback);
			glfwSetCursorPos(this->m_oApp->DATA.m_oWin, (double)this->m_oApp->APPINFO.m_viWinSize.x / 2.0, (double)this->m_oApp->APPINFO.m_viWinSize.y / 2.0);
			printf("-- MOUSE_CALLBACK ENABLED. \n");
			glfwSetScrollCallback(this->m_oApp->DATA.m_oWin, scroll_callback);
			printf("-- SCROLL_CALLBACK ENABLED. \n");
			glfwSetFramebufferSizeCallback(this->m_oApp->DATA.m_oWin, framebuffer_size_callback);
			printf("-- WINDOW_BUFFER_CALLBACK ENABLED. \n");
			//
			this->m_oApp->DATA.m_oCurrCamera = new Camera(vec2(this->m_oApp->APPINFO.m_viWinSize.x,
				this->m_oApp->APPINFO.m_viWinSize.y));
			this->m_oApp->DATA.m_oCurrCamera->BuildCamera(a_vCamPos);
			this->m_oApp->DATA.m_oTotalCameras[0] = this->m_oApp->DATA.m_oCurrCamera;
			printf("-- CAMERA BUILT SUCCESSFULLY. \n");
			//Note: I should consider moving this function call into the appropriate application.
			//m_oTweek.InitTweek();
			printf("--------------------------------------------------------------------------------");
		}
	}
Exemplo n.º 16
0
bool Renderer_OpenGL::Initialize(const RenderInitParameter& init_param)
{
	MLOG("## Initialize OpenGL\n");

	// initialize parent member variable
	Renderer::Initialize(init_param);

	// create OpenGL context
#if MG_PLATFORM_WINDOWS
	bool result = Initialize_Windows(init_param);
	if (!result)
	{
		MASSERT_MSG(0, "Failed initialize opengl context");
		return false;
	}
#else
#endif

	// retrieve hardware and opengl information
	const GLubyte *renderer = glGetString(GL_RENDERER);
	const GLubyte *vendor = glGetString(GL_VENDOR);
	const GLubyte *version = glGetString(GL_VERSION);
	const GLubyte *glslVersion = glGetString(GL_SHADING_LANGUAGE_VERSION);
	GLint major, minor;
	glGetIntegerv(GL_MAJOR_VERSION, &major);
	glGetIntegerv(GL_MINOR_VERSION, &minor);
	MLOG("## GL Vendor : %s\n", vendor);
	MLOG("## GL Renderer : %s\n", renderer);
	MLOG("## GL Version (string) : %s\n", version);
	MLOG("## GL Version (integer) : %d.%d\n", major, minor);
	MLOG("## GLSL Version : %s\n", glslVersion);

#if MUGGLE_DEBUG
	// if gl version >= 4.3, enable debug callback
	GLint gl_version = major * 100 + minor;
	if (gl_version >= 403)
	{
		glEnable(GL_DEBUG_OUTPUT);
		glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
		glDebugMessageCallback(GLDebugCallback, nullptr);
		glDebugMessageControl(
			GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, true
		);
	}
#endif

	return true;
}
Exemplo n.º 17
0
bool Application::InitWindowAndOpenGL(const std::string & title)
{
	int32_t width = GetContext().GetApplicationSettingsManager()->GetGroup("video").GetVar("window_width").ValueI(),
		height = GetContext().GetApplicationSettingsManager()->GetGroup("video").GetVar("window_height").ValueI();
	bool windowed = GetContext().GetApplicationSettingsManager()->GetGroup("video").GetVar("windowed").ValueB();
	bool fullscreen = GetContext().GetApplicationSettingsManager()->GetGroup("video").GetVar("fullscreen").ValueB();

	if (!GetContext().GetWindow()->Init(title, width, height, fullscreen, windowed))
	{
		GetContext().GetLogger()->log(LOG_LOG, "Could not initialize ApplicationWindow with dimensions %ix%i", width, height);
		delete GetContext().p_window;
		GetContext().p_window = nullptr;
		return false;
	}

	GetContext().GetWindow()->SigWindowClosed().connect(sigc::mem_fun(this, &Application::OnWindowClose));

	///REFACTOR: Opengl initialization should have it's own place, worst case: extract method.
	GetContext().p_openGLExtensionLoader = new OpenGLExtensionLoader();

	if (!GetContext().GetOpenGLExtensionLoader()->load_extensions())
	{
		delete GetContext().p_window;
		return false;
	}


	if (0) {
		std::cout << "Register OpenGL debug callback " << std::endl;
		glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
		glDebugMessageCallback(openglCallbackFunction, nullptr);
		GLuint unusedIds = 0;
		glDebugMessageControl(GL_DONT_CARE,
			GL_DONT_CARE,
			GL_DONT_CARE,
			0,
			&unusedIds,
			true);
	}
	else
		std::cout << "glDebugMessageCallback not available" << std::endl;


	GetContext().GetLogger()->log(LOG_CRITICAL, "Shading language: %s", (const char*)glGetString(GL_SHADING_LANGUAGE_VERSION));

	return true;
}
Exemplo n.º 18
0
Arquivo: main.cpp Projeto: Nalaxon/rtg
int main(int argc, char* argv[])
{
	const char* VERTEX_SHADER_SOURCE = ".\\..\\..\\..\\..\\source\\task4\\vertexshader.glsl";
	const char* FRAGMENT_SHADER_SOURCE = ".\\..\\..\\..\\..\\source\\task4\\fragmentshader.glsl";
	//const char* VERTEX_SHADER_SOURCE = "./source/task3/vertexshader.glsl";
	//const char* FRAGMENT_SHADER_SOURCE = "./source/task3/fragmentshader.glsl";
	try
	{
		GL::platform::Window window("Assignment 4 — Complex 3D object", 800, 600, 24, 8, false, 4, 3);
		Renderer renderer(window);
		

		glDebugMessageCallback(OpenGLDebugOutputCallback, nullptr);
		glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, GL_TRUE);

		renderer.resize(800, 600);

		InputHandler input_handler;

		renderer.createShader(VERTEX_SHADER_SOURCE, FRAGMENT_SHADER_SOURCE);
		renderer.createStructure();

		window.attach(static_cast<GL::platform::KeyboardInputHandler*>(&input_handler));
		window.attach(static_cast<GL::platform::MouseInputHandler*>(&input_handler));

		GL::platform::run(renderer);

		renderer.destroyStructure();
		renderer.destroyShader();
	}
	catch (std::exception& e)
	{
		std::cout << "error: " << e.what() << std::endl;
		getchar();
		return -1;
	}
	catch (...)
	{
		std::cout << "unknown exception" << std::endl;
		getchar();
		return -128;
	}

	return 0;
}
Exemplo n.º 19
0
void nsfw::Window::init(unsigned width, unsigned height)
{
	if (glfwInit() == false) {
		return;
	}

	glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, true);

	window = glfwCreateWindow(width, height, "nsfwGL", nullptr, nullptr);

	this->width = width;
	this->height = height;

	if (window == nullptr) {
		glfwTerminate();
	}

	glfwMakeContextCurrent(window);

	if (ogl_LoadFunctions() == ogl_LOAD_FAILED) {
		glfwDestroyWindow(window);
		glfwTerminate();
		return;
	}

#ifdef _DEBUG
	if (glDebugMessageCallback)
	{
		glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
		glDebugMessageCallback(oglErrorDefaultCallback, nullptr);

		GLuint unusedIDs = 0;
		glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, &unusedIDs, true);
	}
	else
	{
		std::cerr << "Failed to subscribe to glDebugMessageCallback." << std::endl;
	}
#endif

	//TODO_D("Should create and set an active windowing context. ONLY GLFW! No GL!");
}
Exemplo n.º 20
0
	void initGLDebug(const OpenGL::Format &fmt, GLDEBUGPROC callback, void* userparam)
	{
		assert( fmt.versionMajor >= 3 );

		if ( (fmt.versionMajor > 4) || (fmt.versionMajor == 4 && fmt.versionMinor >= 3) )
		{
			glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
			glDebugMessageCallback(callback, userparam);
			glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, true);
		}
		else if ( glewIsSupported("GL_ARB_debug_output") )
		{
			glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
			glDebugMessageCallbackARB(callback, userparam);
			glDebugMessageControlARB(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, true);
		}
		else
		{
			// Log(LogType::Warning, LogSource::Engine, LogSeverity::Medium, "OpenGL API debug output is not supported on this system.");
		}
	}
Exemplo n.º 21
0
void nsfw::Window::init(unsigned a_width, unsigned a_height)
{
	//TODO_D("Should create and set an active windowing context. ONLY GLFW! No GL!");
	// initialize
	glfwInit();
	
	width = a_width;
	height = a_height;

	glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, true);
	glfwWindowHint(GLFW_SAMPLES, 4);

	window = glfwCreateWindow(width, height, "NSFWGL", NULL, NULL);
	glfwMakeContextCurrent(window);
	if (ogl_LoadFunctions() == ogl_LOAD_FAILED)
	{
		glfwDestroyWindow(window);
		glfwTerminate();
	}

	// TODO: only do this on ogl4.3+
#ifdef _DEBUG
	if (glDebugMessageCallback)
	{
		glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
		glDebugMessageCallback(oglErrorDefaultCallback, nullptr);

		GLuint unusedIDs = 0;
		glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, &unusedIDs, true);
	}
	else
	{
		std::cerr << "Failed to subscribe to glDebugMessageCallback." << std::endl;
	}
#endif

	auto major = ogl_GetMajorVersion();
	auto minor = ogl_GetMinorVersion();
	printf("GL: %i.%i\n", major, minor);
}
Exemplo n.º 22
0
	void Window::makeContextCurrent() {
		glfwMakeContextCurrent(m_handle);
		WindowData *wd = getWindowData(m_handle);
		// init glaer
		if (!wd->init_done) {
			gecom::log("Window") << "GLAER initializing...";
			//GLenum t_err = glGetError();
			//gecom::log("Window") << "GLEW t_err: " << t_err;
			if (!glaerInitCurrentContext()) {
				gecom::log("Window").error() << "GLAER initialization failed:";
				glfwTerminate();
				std::abort();
			}
			// clear any GL errors from init
			GLenum gl_err = glGetError();
			while (gl_err) {
				gecom::log("Window") << "GLAER initialization left GL error " << gl_err;
				gl_err = glGetError();
			}
			//gecom::log("Window") << "GL Error: " << gluErrorString(gl_err);
			gecom::log("Window") << "GL version string: " << glGetString(GL_VERSION);
			gecom::log("Window").information(0) << "GLAER initialized";
			wd->init_done = true;
			// enable GL_ARB_debug_output if available
			if (glfwExtensionSupported("GL_ARB_debug_output")) {
				// this allows the error location to be determined from a stacktrace
				glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
				// set the callback
				glDebugMessageCallback(callbackDebugGL, this);
				glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, nullptr, true);
				log("Window") << "GL debug callback installed";
			} else {
				log("Window") << "GL_ARB_debug_output not available";
			}
		}
	}
Exemplo n.º 23
0
void get_error_log() {
    glutInitContextFlags(GLUT_FORWARD_COMPATIBLE
#if _DEBUG
                         | GLUT_DEBUG
#endif
                        );

#if _DEBUG
    if (glDebugMessageCallback) {
        cout << "Register OpenGL debug callback " << endl;
        glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
        glDebugMessageCallback(openglCallbackFunction, nullptr);
        GLuint unusedIds = 0;
        glDebugMessageControl(GL_DONT_CARE,
                              GL_DONT_CARE,
                              GL_DONT_CARE,
                              0,
                              &unusedIds,
                              true);
    }
    else
        cout << "glDebugMessageCallback not available" << endl;
#endif
}
Exemplo n.º 24
0
bool InitScene()
{
	SetWindowText(hwnd, TITLE);
	Quadron::qGLExtensions::QueryFeatures(hdc);

	if( !Quadron::qGLExtensions::ARB_shader_storage_buffer_object )
		return false;

#ifdef _DEBUG
	if( Quadron::qGLExtensions::ARB_debug_output )
	{
		glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, 0, GL_TRUE);
		glDebugMessageCallback(ReportGLError, 0);
	}
#endif

	glClearColor(0.0f, 0.125f, 0.3f, 1.0f);
	//glClearColor(1, 1, 1, 1);
	glClearDepth(1.0);

	glEnable(GL_CULL_FACE);
	glCullFace(GL_BACK);

	glDepthFunc(GL_LEQUAL);
	glEnable(GL_DEPTH_TEST);

	screenquad = new OpenGLScreenQuad();

	// load objects
	if( !GLCreateMeshFromQM("../media/meshes/cube.qm", &box) )
	{
		MYERROR("Could not load box");
		return false;
	}

	if( !GLCreateMeshFromQM("../media/meshes/dragon.qm", &dragon) )
	{
		MYERROR("Could not load dragon");
		return false;
	}

	if( !GLCreateMeshFromQM("../media/meshes/happy1.qm", &buddha) )
	{
		MYERROR("Could not load buddha");
		return false;
	}

	// create texture
	glGenTextures(1, &white);
	glBindTexture(GL_TEXTURE_2D, white);
	{
		unsigned int wondercolor = 0xffffffff;
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_UNSIGNED_INT_8_8_8_8, &wondercolor);

		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	}

	// create buffers
	size_t headsize = 16;	// start, count, pad, pad
	size_t nodesize = 16;	// color, depth, next, pad
	size_t numlists = screenwidth * screenheight;

	glGenBuffers(1, &headbuffer);
	glGenBuffers(1, &nodebuffer);
	glGenBuffers(1, &counterbuffer);

	glBindBuffer(GL_SHADER_STORAGE_BUFFER, headbuffer);
	glBufferData(GL_SHADER_STORAGE_BUFFER, numlists * headsize, 0, GL_STATIC_DRAW);

	glBindBuffer(GL_SHADER_STORAGE_BUFFER, nodebuffer);
	glBufferData(GL_SHADER_STORAGE_BUFFER, numlists * 4 * nodesize, 0, GL_STATIC_DRAW);	// 120 MB @ 1080p

	glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);

	glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, counterbuffer);
	glBufferData(GL_ATOMIC_COUNTER_BUFFER, sizeof(GLuint), 0, GL_DYNAMIC_DRAW);
	glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, 0);

	// calculate scene bounding box
	OpenGLAABox tmpbox;
	float world[16];
	float tmp[16];

	GLMatrixIdentity(world);

	for( int i = 0; i < numobjects; ++i )
	{
		const SceneObject& obj = objects[i];

		// scaling * rotation * translation
		GLMatrixScaling(tmp, obj.scale[0], obj.scale[1], obj.scale[2]);
		GLMatrixRotationAxis(world, obj.angle, 0, 1, 0);
		GLMatrixMultiply(world, tmp, world);

		GLMatrixTranslation(tmp, obj.position[0], obj.position[1], obj.position[2]);
		GLMatrixMultiply(world, world, tmp);

		if( obj.type == 0 )
			tmpbox = box->GetBoundingBox();
		else if( obj.type == 1 )
			tmpbox = dragon->GetBoundingBox();
		else if( obj.type == 2 )
			tmpbox = buddha->GetBoundingBox();

		tmpbox.TransformAxisAligned(world);

		scenebox.Add(tmpbox.Min);
		scenebox.Add(tmpbox.Max);
	}

	// head pointer initializer
	if( !GLCreateEffectFromFile("../media/shadersGL/basic2D.vert", 0, "../media/shadersGL/initheadpointers.frag", &init) )
	{
		MYERROR("Could not load initializer shader");
		return false;
	}

	// renderer shader
	if( !GLCreateEffectFromFile("../media/shadersGL/basic2D.vert", 0, "../media/shadersGL/renderfragments.frag", &render) )
	{
		MYERROR("Could not load rendering shader");
		return false;
	}

	// fragment collector shader
	if( !GLCreateEffectFromFile("../media/shadersGL/collectfragments.vert", 0, "../media/shadersGL/collectfragments.frag", &collect) )
	{
		MYERROR("Could not load collector shader");
		return false;
	}

	float angles[2] = { 0.25f, -0.7f };
	cameraangle = angles;

	return true;
}
Exemplo n.º 25
0
int main()
{
	hmk::Logger::get_instance().initialize("engine.txt");
	if (glfwInit() == GL_FALSE)
	{
		HMK_LOG_ERROR("failed glfwInit")
		hmk::Logger::get_instance().shutdown();
		return -1;
	}

	glfwSetErrorCallback(ErrorCallback);

	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
	glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
	glfwWindowHint(GLFW_SAMPLES, 8);

	GLFWwindow* window = glfwCreateWindow(800, 600, "HMK", nullptr, nullptr);
	if (window == nullptr)
	{
		HMK_LOG_ERROR("failed glfwCreateWindow")
		hmk::Logger::get_instance().shutdown();
		glfwTerminate();
		return -1;
	}
	glfwSetWindowPos(window, 500, 30);
	glfwMakeContextCurrent(window);

	if (gl3wInit() == -1) // 0 success
	{
		HMK_LOG_ERROR("failed gl3wInit")
		hmk::Logger::get_instance().shutdown();
		glfwTerminate();
		return -1;
	}

	if (!gl3wIsSupported(3, 3))
	{
		HMK_LOG_ERROR("Upgrade your graphic card!")
		hmk::Logger::get_instance().shutdown();
		glfwTerminate();
		return -1;
	}

#if _DEBUG
	if (glDebugMessageCallback)
	{
		glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
		glDebugMessageCallback(glErrorCallback, nullptr);
		GLuint unused = 0;
		glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, &unused, true);
	}
#endif

	ImGui_ImplGlfwGL3_Init(window, false);

	Game *game = new Game();
	game->initialize();

	glfwSetKeyCallback(window, KeyCallback);
	glfwSetCursorPosCallback(window, CursorPosCallback);
	glfwSetMouseButtonCallback(window, MouseButtonCallback);
	glfwSetDropCallback(window, DropCallback);

	keyCallback = HMK_CALLBACK_4(Game::key_input, game);
	cursorPosCallback = HMK_CALLBACK_2(Game::cursor_pos_input, game);
	mouseButtonCallback = HMK_CALLBACK_3(Game::mouse_button_input, game);
	dropCallback = HMK_CALLBACK_2(Game::drop_files_callback, game);

	double lastTime = glfwGetTime();

	glEnable(GL_DEPTH_TEST);
	glDepthMask(GL_TRUE);
	glDepthFunc(GL_LEQUAL);
	glDepthRange(0.0f, 1.0f);
	glEnable(GL_CULL_FACE);
	glCullFace(GL_BACK);
	glFrontFace(GL_CW);
	glEnable(GL_FRAMEBUFFER_SRGB);
	glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS); // https://www.opengl.org/wiki/Cubemap_Texture#Seamless_cubemap
	glEnable(GL_MULTISAMPLE);
	glClearColor(0.2f, 0.3f, 0.2f, 1.0f);

	double fps = 0.0;
	double acc = 0.0;
	while (!glfwWindowShouldClose(window))
	{
		glfwPollEvents();
		ImGui_ImplGlfwGL3_NewFrame();

		double now = glfwGetTime();
		double delta = now - lastTime;
		lastTime = now;

		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		game->update((float)delta);
		game->render();

		fps++;
		acc += delta;
		if (acc > 1.0)
		{
			acc = 0.0;
			fps = 0.0;
		}

		ImGui::Render();
		glfwSwapBuffers(window);
	}

	delete game;
	hmk::Logger::get_instance().shutdown();
	glfwDestroyWindow(window);
	ImGui_ImplGlfwGL3_Shutdown();
	glfwTerminate();
	return 0;
}
Exemplo n.º 26
0
Window::Window(int width, int height, const std::string& title) :
	 width(width),
	 height(height),
	 title(title),
	 isCloseRequested(false)
{
	SDL_Init(SDL_INIT_EVERYTHING);

	SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
	SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE,32);
	SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE,16);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER,1);
	
//	SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
//	SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
	
	//SDL_GL_SetAttribute( SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE );
	//SDL_GL_SetAttribute( SDL_GL_CONTEXT_MAJOR_VERSION, 4 );
	//SDL_GL_SetAttribute( SDL_GL_CONTEXT_MINOR_VERSION, 2 );
	bool DebugMode = true;
	if(DebugMode)
	{
		SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS, SDL_GL_CONTEXT_DEBUG_FLAG);
	}
	//Initialize SDL
    SDL_Init(SDL_INIT_EVERYTHING);
	SDL_ShowCursor(SDL_FALSE); 	
	if (glDebugMessageCallbackARB != NULL && DebugMode) 
	{

		float i;
		glGetFloatv(GL_MAJOR_VERSION,&i);
		if(i >= 4.0f)
		{
			glEnable(GL_DEBUG_OUTPUT);
			glDebugMessageCallback(Core::DebugOutput::myCallback, NULL);
			glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE,
							  GL_DONT_CARE, 0, NULL, GL_TRUE);
		}
		else
		{
			glEnable(GL_ARB_debug_output);
			glDebugMessageCallback(Core::DebugOutput::myCallback, NULL);
			glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE,
							  GL_DONT_CARE, 0, NULL, GL_TRUE);
		};
	}


	 window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_OPENGL);
	if (window == nullptr)
	{
        fatalError("SDL Window could not be created!");
    }
	glContext = SDL_GL_CreateContext( window);
	if (glContext == nullptr) 
	{
        fatalError("SDL_GL context could not be created!");
    }
	SDL_SetHint(SDL_HINT_RENDER_VSYNC, "1");
	SDL_GL_SetSwapInterval(1);

	//Apparently this is necessary to build with Xcode
	glewExperimental = GL_TRUE;
	
	GLenum res = glewInit();
	if(res != GLEW_OK)
	{
		fprintf(stderr, "Error: '%s'\n", glewGetErrorString(res));
	}
	SDL_GL_SwapWindow( window);
}
Exemplo n.º 27
0
bool InitScene()
{
	SetWindowText(hwnd, TITLE);
	Quadron::qGLExtensions::QueryFeatures(hdc);

	hascompute = (Quadron::qGLExtensions::ARB_compute_shader && Quadron::qGLExtensions::ARB_shader_storage_buffer_object);

#ifdef _DEBUG
	if( Quadron::qGLExtensions::ARB_debug_output )
	{
		glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, 0, GL_TRUE);
		glDebugMessageCallback(ReportGLError, 0);
	}
#endif

	glClearColor(0.0f, 0.125f, 0.3f, 1.0f);
	glClearDepth(1.0);

	glEnable(GL_CULL_FACE);
	glCullFace(GL_BACK);

	glDepthFunc(GL_LEQUAL);
	glEnable(GL_DEPTH_TEST);

	// load objects
	if( !GLCreateMeshFromQM("../media/meshes/teapot.qm", &teapot) )
	{
		MYERROR("Could not load teapot");
		return false;
	}

	if( !GLCreateMeshFromQM("../media/meshes/cube.qm", &box) )
	{
		MYERROR("Could not load box");
		return false;
	}

	// calculate scene bounding box
	OpenGLAABox tmpbox;
	float world[16];
	float tmp[16];

	GLMatrixIdentity(world);

	for( int i = 0; i < numobjects; ++i )
	{
		const SceneObject& obj = objects[i];

		// scaling * rotation * translation
		GLMatrixScaling(tmp, obj.scale[0], obj.scale[1], obj.scale[2]);
		GLMatrixRotationAxis(world, obj.angle, 0, 1, 0);
		GLMatrixMultiply(world, tmp, world);

		GLMatrixTranslation(tmp, obj.position[0], obj.position[1], obj.position[2]);
		GLMatrixMultiply(world, world, tmp);

		if( obj.type == 0 )
			tmpbox = box->GetBoundingBox();
		else if( obj.type == 1 )
			tmpbox = teapot->GetBoundingBox();

		tmpbox.TransformAxisAligned(world);

		scenebox.Add(tmpbox.Min);
		scenebox.Add(tmpbox.Max);
	}

	// create render targets
	framebuffer = new OpenGLFramebuffer(screenwidth, screenheight);
	framebuffer->AttachTexture(GL_COLOR_ATTACHMENT0, GLFMT_A16B16G16R16F);
	framebuffer->AttachTexture(GL_DEPTH_ATTACHMENT, GLFMT_D32F);
	
	if( !framebuffer->Validate() )
		return false;

	shadowmap = new OpenGLFramebuffer(SHADOWMAP_SIZE, SHADOWMAP_SIZE);
	shadowmap->AttachTexture(GL_COLOR_ATTACHMENT0, GLFMT_G32R32F, GL_LINEAR);
	shadowmap->AttachRenderbuffer(GL_DEPTH_ATTACHMENT, GLFMT_D24S8);

	if( !shadowmap->Validate() )
		return false;

	blurredshadow = new OpenGLFramebuffer(SHADOWMAP_SIZE, SHADOWMAP_SIZE);
	blurredshadow->AttachTexture(GL_COLOR_ATTACHMENT0, GLFMT_G32R32F, GL_LINEAR);

	if( !blurredshadow->Validate() )
		return false;

	screenquad = new OpenGLScreenQuad();

	// textures
	if( !GLCreateTextureFromFile("../media/textures/wood2.jpg", true, &texture1) )
	{
		MYERROR("Could not load texture");
		return false;
	}

	if( !GLCreateTextureFromFile("../media/textures/marble2.png", true, &texture2) )
	{
		MYERROR("Could not load texture");
		return false;
	}

	if( !GLCreateTextureFromFile("../media/textures/static_sky.jpg", true, &texture3, GLTEX_FLIPX) )
	{
		MYERROR("Could not load texture");
		return false;
	}

	// create buffers
	workgroupsx = (screenwidth + (screenwidth % 16)) / 16;
	workgroupsy = (screenheight + (screenheight % 16)) / 16;

	size_t numtiles = workgroupsx * workgroupsy;
	size_t headsize = 16;	// start, count, pad, pad
	size_t nodesize = 16;	// light index, next, pad, pad

	if( hascompute )
	{
		glGenBuffers(1, &headbuffer);
		glGenBuffers(1, &nodebuffer);
		glGenBuffers(1, &lightbuffer);
		glGenBuffers(1, &counterbuffer);

		glBindBuffer(GL_SHADER_STORAGE_BUFFER, headbuffer);
		glBufferData(GL_SHADER_STORAGE_BUFFER, numtiles * headsize, 0, GL_STATIC_DRAW);

		glBindBuffer(GL_SHADER_STORAGE_BUFFER, nodebuffer);
		glBufferData(GL_SHADER_STORAGE_BUFFER, numtiles * nodesize * 1024, 0, GL_STATIC_DRAW);	// 4 MB

		glBindBuffer(GL_SHADER_STORAGE_BUFFER, lightbuffer);
		glBufferData(GL_SHADER_STORAGE_BUFFER, NUM_LIGHTS * sizeof(LightParticle), 0, GL_DYNAMIC_DRAW);

		UpdateParticles(0, true);

		glBindBuffer(GL_SHADER_STORAGE_BUFFER, 0);

		glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, counterbuffer);
		glBufferData(GL_ATOMIC_COUNTER_BUFFER, sizeof(GLuint), 0, GL_DYNAMIC_DRAW);
		glBindBuffer(GL_ATOMIC_COUNTER_BUFFER, 0);
	}

	// load effects
	if( !GLCreateEffectFromFile("../media/shadersGL/basic2D.vert", 0, "../media/shadersGL/basic2D.frag", &basic2D) )
	{
		MYERROR("Could not load basic 2D shader");
		return false;
	}

	if( !GLCreateEffectFromFile("../media/shadersGL/basic2D.vert", 0, "../media/shadersGL/boxblur3x3.frag", &boxblur3x3) )
	{
		MYERROR("Could not load blur shader");
		return false;
	}

	if( !GLCreateEffectFromFile("../media/shadersGL/basic2D.vert", 0, "../media/shadersGL/gammacorrect.frag", &gammacorrect) )
	{
		MYERROR("Could not load gamma correction shader");
		return false;
	}

	if( !GLCreateEffectFromFile("../media/shadersGL/shadowmap_variance.vert", 0, "../media/shadersGL/shadowmap_variance.frag", &varianceshadow) )
	{
		MYERROR("Could not load shadowmap shader");
		return false;
	}

	if( !GLCreateEffectFromFile("../media/shadersGL/blinnphong_variance.vert", 0, "../media/shadersGL/blinnphong_variance.frag", &shadowedlight) )
	{
		MYERROR("Could not load shadowed light shader");
		return false;
	}

	if( !GLCreateEffectFromFile("../media/shadersGL/ambient.vert", 0, "../media/shadersGL/ambient.frag", &ambient) )
	{
		MYERROR("Could not load ambient shader");
		return false;
	}

	if( hascompute )
	{
		// light accumulation shader
		if( !GLCreateEffectFromFile("../media/shadersGL/lightaccum.vert", 0, "../media/shadersGL/lightaccum.frag", &lightaccum) )
		{
			MYERROR("Could not load light accumulation shader");
			return false;
		}

		// light culling shader
		if( !GLCreateComputeProgramFromFile("../media/shadersGL/lightcull.comp", &lightcull) )
		{
			MYERROR("Could not load light culling shader");
			return false;
		}

		lightcull->SetInt("depthSampler", 0);
		lightcull->SetInt("numLights", NUM_LIGHTS);
		lightaccum->SetInt("sampler0", 0);
	}

	float white[] = { 1, 1, 1, 1 };
	
	shadowedlight->SetVector("matSpecular", white);
	shadowedlight->SetInt("sampler0", 0);
	shadowedlight->SetInt("sampler1", 1);

	boxblur3x3->SetInt("sampler0", 0);
	basic2D->SetInt("sampler0", 0);
	gammacorrect->SetInt("sampler0", 0);

	float angles[2] = { 0.25f, -0.7f };
	cameraangle = angles;

	return true;
}
Exemplo n.º 28
0
void set_debug_log_filters(GLenum source, GLenum type, const std::vector<GLuint>& ids, GLenum severity, bool enabled)
{
  glDebugMessageControl(source, type, severity, static_cast<GLsizei>(ids.size()), ids.data(), enabled);
}
Exemplo n.º 29
0
int main(int argc, char** argv)
{
    int ch;
    GLFWwindow* windows[2];
    GLuint texture, program, vertex_buffer;
    GLint mvp_location, vpos_location, color_location, texture_location;

    srand((unsigned int) time(NULL));

    glfwSetErrorCallback(error_callback);

    if (!glfwInit())
        exit(EXIT_FAILURE);

    while ((ch = getopt(argc, argv, "d")) != -1)
    {
        switch (ch)
        {
            case 'd':
                glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE);
                break;
        }
    }

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);

    windows[0] = glfwCreateWindow(400, 400, "First", NULL, NULL);
    if (!windows[0])
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwSetKeyCallback(windows[0], key_callback);

    glfwMakeContextCurrent(windows[0]);

    // Only enable vsync for the first of the windows to be swapped to
    // avoid waiting out the interval for each window
    glfwSwapInterval(1);

    // The contexts are created with the same APIs so the function
    // pointers should be re-usable between them
    gladLoadGLLoader((GLADloadproc) glfwGetProcAddress);

    if (GLAD_GL_KHR_debug)
    {
        glDebugMessageCallback(debug_callback, NULL);
        glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DONT_CARE, 0, NULL, GL_TRUE);
    }

    // Create the OpenGL objects inside the first context, created above
    // All objects will be shared with the second context, created below
    {
        int x, y;
        char pixels[16 * 16];
        GLuint vertex_shader, fragment_shader;

        glGenTextures(1, &texture);
        glBindTexture(GL_TEXTURE_2D, texture);

        for (y = 0;  y < 16;  y++)
        {
            for (x = 0;  x < 16;  x++)
                pixels[y * 16 + x] = rand() % 256;
        }

        glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, 16, 16, 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, pixels);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);

        vertex_shader = glCreateShader(GL_VERTEX_SHADER);
        glShaderSource(vertex_shader, 1, &vertex_shader_text, NULL);
        glCompileShader(vertex_shader);

        fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
        glShaderSource(fragment_shader, 1, &fragment_shader_text, NULL);
        glCompileShader(fragment_shader);

        program = glCreateProgram();
        glAttachShader(program, vertex_shader);
        glAttachShader(program, fragment_shader);
        glLinkProgram(program);

        mvp_location = glGetUniformLocation(program, "MVP");
        color_location = glGetUniformLocation(program, "color");
        texture_location = glGetUniformLocation(program, "texture");
        vpos_location = glGetAttribLocation(program, "vPos");

        glGenBuffers(1, &vertex_buffer);
        glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
        glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    }

    glUseProgram(program);
    glUniform1i(texture_location, 0);

    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, texture);

    glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
    glEnableVertexAttribArray(vpos_location);
    glVertexAttribPointer(vpos_location, 2, GL_FLOAT, GL_FALSE,
                          sizeof(vertices[0]), (void*) 0);

    windows[1] = glfwCreateWindow(400, 400, "Second", NULL, windows[0]);
    if (!windows[1])
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    // Place the second window to the right of the first
    {
        int xpos, ypos, left, right, width;

        glfwGetWindowSize(windows[0], &width, NULL);
        glfwGetWindowFrameSize(windows[0], &left, NULL, &right, NULL);
        glfwGetWindowPos(windows[0], &xpos, &ypos);

        glfwSetWindowPos(windows[1], xpos + width + left + right, ypos);
    }

    glfwSetKeyCallback(windows[1], key_callback);

    glfwMakeContextCurrent(windows[1]);

    // While objects are shared, the global context state is not and will
    // need to be set up for each context

    glUseProgram(program);

    glEnable(GL_TEXTURE_2D);
    glBindTexture(GL_TEXTURE_2D, texture);

    glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
    glEnableVertexAttribArray(vpos_location);
    glVertexAttribPointer(vpos_location, 2, GL_FLOAT, GL_FALSE,
                          sizeof(vertices[0]), (void*) 0);

    while (!glfwWindowShouldClose(windows[0]) &&
           !glfwWindowShouldClose(windows[1]))
    {
        int i;
        const vec3 colors[2] =
        {
            { 0.3f, 0.4f, 1.f },
            { 0.8f, 0.4f, 1.f }
        };

        for (i = 0;  i < 2;  i++)
        {
            int width, height;
            mat4x4 mvp;

            glfwGetFramebufferSize(windows[i], &width, &height);
            glfwMakeContextCurrent(windows[i]);

            glViewport(0, 0, width, height);

            mat4x4_ortho(mvp, 0.f, 1.f, 0.f, 1.f, 0.f, 1.f);
            glUniformMatrix4fv(mvp_location, 1, GL_FALSE, (const GLfloat*) mvp);
            glUniform3fv(color_location, 1, colors[i]);
            glDrawArrays(GL_TRIANGLE_FAN, 0, 4);

            glfwSwapBuffers(windows[i]);
        }

        glfwWaitEvents();
    }

    glfwTerminate();
    exit(EXIT_SUCCESS);
}
Exemplo n.º 30
0
/* Initialise the double buffered display */
bool screenInitialise()
{
	GLint glMaxTUs;
	GLenum err;

	glErrors();

	err = glewInit();
	if (GLEW_OK != err)
	{
		debug(LOG_FATAL, "Error: %s", glewGetErrorString(err));
		exit(1);
	}

	/* Dump general information about OpenGL implementation to the console and the dump file */
	ssprintf(opengl.vendor, "OpenGL Vendor: %s", glGetString(GL_VENDOR));
	addDumpInfo(opengl.vendor);
	debug(LOG_3D, "%s", opengl.vendor);
	ssprintf(opengl.renderer, "OpenGL Renderer: %s", glGetString(GL_RENDERER));
	addDumpInfo(opengl.renderer);
	debug(LOG_3D, "%s", opengl.renderer);
	ssprintf(opengl.version, "OpenGL Version: %s", glGetString(GL_VERSION));
	addDumpInfo(opengl.version);
	debug(LOG_3D, "%s", opengl.version);
	ssprintf(opengl.GLEWversion, "GLEW Version: %s", glewGetString(GLEW_VERSION));
	if (strncmp(opengl.GLEWversion, "1.9.", 4) == 0) // work around known bug with KHR_debug extension support in this release
	{
		debug(LOG_WARNING, "Your version of GLEW is old and buggy, please upgrade to at least version 1.10.");
		khr_debug = false;
	}
	else
	{
		khr_debug = GLEW_KHR_debug;
	}
	addDumpInfo(opengl.GLEWversion);
	debug(LOG_3D, "%s", opengl.GLEWversion);

	GLubyte const *extensionsBegin = glGetString(GL_EXTENSIONS);
	if (extensionsBegin == nullptr)
	{
		static GLubyte const emptyString[] = "";
		extensionsBegin = emptyString;
	}
	GLubyte const *extensionsEnd = extensionsBegin + strlen((char const *)extensionsBegin);
	std::vector<std::string> glExtensions;
	for (GLubyte const *i = extensionsBegin; i < extensionsEnd;)
	{
		GLubyte const *j = std::find(i, extensionsEnd, ' ');
		glExtensions.push_back(std::string(i, j));
		i = j + 1;
	}

	/* Dump extended information about OpenGL implementation to the console */

	std::string line;
	for (unsigned n = 0; n < glExtensions.size(); ++n)
	{
		std::string word = " ";
		word += glExtensions[n];
		if (n + 1 != glExtensions.size())
		{
			word += ',';
		}
		if (line.size() + word.size() > 160)
		{
			debug(LOG_3D, "OpenGL Extensions:%s", line.c_str());
			line.clear();
		}
		line += word;
	}
	debug(LOG_3D, "OpenGL Extensions:%s", line.c_str());
	debug(LOG_3D, "Notable OpenGL features:");
	debug(LOG_3D, "  * OpenGL 1.2 %s supported!", GLEW_VERSION_1_2 ? "is" : "is NOT");
	debug(LOG_3D, "  * OpenGL 1.3 %s supported!", GLEW_VERSION_1_3 ? "is" : "is NOT");
	debug(LOG_3D, "  * OpenGL 1.4 %s supported!", GLEW_VERSION_1_4 ? "is" : "is NOT");
	debug(LOG_3D, "  * OpenGL 1.5 %s supported!", GLEW_VERSION_1_5 ? "is" : "is NOT");
	debug(LOG_3D, "  * OpenGL 2.0 %s supported!", GLEW_VERSION_2_0 ? "is" : "is NOT");
	debug(LOG_3D, "  * OpenGL 2.1 %s supported!", GLEW_VERSION_2_1 ? "is" : "is NOT");
	debug(LOG_3D, "  * OpenGL 3.0 %s supported!", GLEW_VERSION_3_0 ? "is" : "is NOT");
	debug(LOG_3D, "  * Texture compression %s supported.", GLEW_ARB_texture_compression ? "is" : "is NOT");
	debug(LOG_3D, "  * Two side stencil %s supported.", GLEW_EXT_stencil_two_side ? "is" : "is NOT");
	debug(LOG_3D, "  * ATI separate stencil is%s supported.", GLEW_ATI_separate_stencil ? "" : " NOT");
	debug(LOG_3D, "  * Stencil wrap %s supported.", GLEW_EXT_stencil_wrap ? "is" : "is NOT");
	debug(LOG_3D, "  * Anisotropic filtering %s supported.", GLEW_EXT_texture_filter_anisotropic ? "is" : "is NOT");
	debug(LOG_3D, "  * Rectangular texture %s supported.", GLEW_ARB_texture_rectangle ? "is" : "is NOT");
	debug(LOG_3D, "  * FrameBuffer Object (FBO) %s supported.", GLEW_EXT_framebuffer_object ? "is" : "is NOT");
	debug(LOG_3D, "  * ARB Vertex Buffer Object (VBO) %s supported.", GLEW_ARB_vertex_buffer_object ? "is" : "is NOT");
	debug(LOG_3D, "  * NPOT %s supported.", GLEW_ARB_texture_non_power_of_two ? "is" : "is NOT");
	debug(LOG_3D, "  * texture cube_map %s supported.", GLEW_ARB_texture_cube_map ? "is" : "is NOT");
	glGetIntegerv(GL_MAX_TEXTURE_UNITS, &glMaxTUs);
	debug(LOG_3D, "  * Total number of Texture Units (TUs) supported is %d.", (int) glMaxTUs);
	debug(LOG_3D, "  * GL_ARB_timer_query %s supported!", GLEW_ARB_timer_query ? "is" : "is NOT");
	debug(LOG_3D, "  * KHR_DEBUG support %s detected", khr_debug ? "was" : "was NOT");

	if (!GLEW_VERSION_2_0)
	{
		debug(LOG_FATAL, "OpenGL 2.0 not supported! Please upgrade your drivers.");
		return false;
	}

	screenWidth = MAX(screenWidth, 640);
	screenHeight = MAX(screenHeight, 480);

	std::pair<int, int> glslVersion(0, 0);
	sscanf((char const *)glGetString(GL_SHADING_LANGUAGE_VERSION), "%d.%d", &glslVersion.first, &glslVersion.second);

	/* Dump information about OpenGL 2.0+ implementation to the console and the dump file */
	GLint glMaxTIUs, glMaxTCs, glMaxTIUAs, glmaxSamples, glmaxSamplesbuf;

	debug(LOG_3D, "  * OpenGL GLSL Version : %s", glGetString(GL_SHADING_LANGUAGE_VERSION));
	ssprintf(opengl.GLSLversion, "OpenGL GLSL Version : %s", glGetString(GL_SHADING_LANGUAGE_VERSION));
	addDumpInfo(opengl.GLSLversion);

	glGetIntegerv(GL_MAX_TEXTURE_IMAGE_UNITS, &glMaxTIUs);
	debug(LOG_3D, "  * Total number of Texture Image Units (TIUs) supported is %d.", (int) glMaxTIUs);
	glGetIntegerv(GL_MAX_TEXTURE_COORDS, &glMaxTCs);
	debug(LOG_3D, "  * Total number of Texture Coords (TCs) supported is %d.", (int) glMaxTCs);
	glGetIntegerv(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB, &glMaxTIUAs);
	debug(LOG_3D, "  * Total number of Texture Image Units ARB(TIUAs) supported is %d.", (int) glMaxTIUAs);
	glGetIntegerv(GL_SAMPLE_BUFFERS, &glmaxSamplesbuf);
	debug(LOG_3D, "  * (current) Max Sample buffer is %d.", (int) glmaxSamplesbuf);
	glGetIntegerv(GL_SAMPLES, &glmaxSamples);
	debug(LOG_3D, "  * (current) Max Sample level is %d.", (int) glmaxSamples);

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT | GL_STENCIL_BUFFER_BIT);

	pie_Skybox_Init();

	// Generate backdrop render
	backdropGfx = new GFX(GFX_TEXTURE, GL_TRIANGLE_STRIP, 2);

	if (GLEW_ARB_timer_query)
	{
		glGenQueries(PERF_COUNT, perfpos);
	}

	if (khr_debug)
	{
		glDebugMessageCallback((GLDEBUGPROC)khr_callback, NULL);
		glEnable(GL_DEBUG_OUTPUT);
		// Do not want to output notifications. Some drivers spam them too much.
		glDebugMessageControl(GL_DONT_CARE, GL_DONT_CARE, GL_DEBUG_SEVERITY_NOTIFICATION, 0, NULL, GL_FALSE);
		debug(LOG_3D, "Enabling KHR_debug message callback");
	}

	glErrors();
	return true;
}