コード例 #1
0
int main(int argc, char *argv[]) {
    SDL_Init(SDL_INIT_VIDEO);
    SDL_Window* window = SDL_CreateWindow("Hello World",
                                           100, 100, 800, 600,
                                           SDL_WINDOW_OPENGL);
    auto context = initContext(window);
    initGlew();
    auto program = initShaders();
    initBuffers(program);

    paint();

    SDL_Event event;
    while (true) {
        if (SDL_PollEvent(&event)) {
            if (event.type == SDL_QUIT) break;
            if (event.type == SDL_KEYDOWN) break;
        }
        SDL_GL_SwapWindow(window);
    }

    SDL_GL_DeleteContext(context);
    SDL_DestroyWindow(window);
    SDL_Quit();
    return 0;
}
コード例 #2
0
ファイル: mswinogl.cpp プロジェクト: JPGygax68/GSM
void
setupWindowForOpenGL(MSWinSurface *surf, ISurface::Attributes attribs)
{
    initGlew();

    // Get a DC
    HDC hDC = GetDC(surf->windowHandle());  // TODO: is it ok to call GetDC() every time a DC is needed?

    // Select and set a pixel format
    int pixel_format = selectPixelFormat(hDC, !attribs.test(ISurface::SINGLE_BUFFERED));
    if (! SetPixelFormat(hDC, pixel_format, NULL))
        throw EMSWinError(GetLastError(), "SetPixelFormat");

    // Create an OpenGL context
    HGLRC hRC = wglCreateContext(hDC);
    if (hRC == 0) throw EMSWinError(GetLastError(), "wglCreateContext");
    surf->setOpenGLContext(hRC);

    // Try to make the Rendering Context part of a Video Context
    surf->setVideoContextID( assignToVideoContext(hRC) );

#ifdef NOT_DEFINED
    // Initialize GLEW for this context
    glewExperimental = TRUE;
    if (glewInit() != GLEW_OK)
        throw EMSWinError(GetLastError(), "glewInit()");
#endif
}
コード例 #3
0
ファイル: main.cpp プロジェクト: jhpy1024/Mazel
int main(int argc, char** argv)
{
    initGlut(argc, argv);
    initGlew();

    game.init();

    glutMainLoop();
}
コード例 #4
0
bool Window::create(const Vec2i& size, const std::string& title, uint32_t flags) {
    // Clean up
    close();

    // Make sure SDL video was initialized
    if(!SDL_WasInit(SDL_INIT_VIDEO)) {
        ERR_PRINT(priv::c_prefError, "SDL Video was not initialized yet");

        return false;
    }

    // Create the window
    m_handle = SDL_CreateWindow(title.c_str(),
                                SDL_WINDOWPOS_CENTERED,
                                SDL_WINDOWPOS_CENTERED,
                                size.w,
                                size.h,
                                flags | SDL_WINDOW_OPENGL);

    m_context = SDL_GL_CreateContext(m_handle);
    // Make sure window context was created, print errors otherwise
    if(!m_context) {
        ERR_PRINT(
                priv::c_prefError,
                "Failed to crate window context with following errors: " +
                std::string(SDL_GetError())
        );

        // Also make sure to cleanup the window
        SDL_DestroyWindow(m_handle);

        return false;
    }

    // If Glew failed to initialize
    if(!initGlew()) {
        // Clean up
        close();

        return false;
    }

    // Setup renderer buffers
    setupRenderer(size);

    // Turn off V-sync (if enabled by the graphics card)
    if(SDL_GL_SetSwapInterval(0) < 0) {
        ERR_PRINT(
                priv::c_prefError,
                "Failed to set swap interval with following errors: " +
                std::string(SDL_GetError())
        );
    }

    m_isOpen = true;
    return true;
}
コード例 #5
0
bool GLViewImpl::initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor, bool resizable)
{
    setViewName(viewName);

    _frameZoomFactor = frameZoomFactor;
    _resizable = resizable;

    glfwWindowHint(GLFW_RESIZABLE, resizable ? GL_TRUE : GL_FALSE);
    
    glfwWindowHint(GLFW_RED_BITS,_glContextAttrs.redBits);
    glfwWindowHint(GLFW_GREEN_BITS,_glContextAttrs.greenBits);
    glfwWindowHint(GLFW_BLUE_BITS,_glContextAttrs.blueBits);
    glfwWindowHint(GLFW_ALPHA_BITS,_glContextAttrs.alphaBits);
    glfwWindowHint(GLFW_DEPTH_BITS,_glContextAttrs.depthBits);
    glfwWindowHint(GLFW_STENCIL_BITS,_glContextAttrs.stencilBits);

    _mainWindow = glfwCreateWindow(rect.size.width * _frameZoomFactor,
                                   rect.size.height * _frameZoomFactor,
                                   _viewName.c_str(),
                                   _monitor,
                                   nullptr);
    glfwMakeContextCurrent(_mainWindow);

    glfwSetMouseButtonCallback(_mainWindow, GLFWEventHandler::onGLFWMouseCallBack);
    glfwSetCursorPosCallback(_mainWindow, GLFWEventHandler::onGLFWMouseMoveCallBack);
    glfwSetScrollCallback(_mainWindow, GLFWEventHandler::onGLFWMouseScrollCallback);
    glfwSetCharCallback(_mainWindow, GLFWEventHandler::onGLFWCharCallback);
    glfwSetKeyCallback(_mainWindow, GLFWEventHandler::onGLFWKeyCallback);
    glfwSetWindowPosCallback(_mainWindow, GLFWEventHandler::onGLFWWindowPosCallback);
    glfwSetFramebufferSizeCallback(_mainWindow, GLFWEventHandler::onGLFWframebuffersize);
    glfwSetWindowSizeCallback(_mainWindow, GLFWEventHandler::onGLFWWindowSizeFunCallback);
    glfwSetWindowIconifyCallback(_mainWindow, GLFWEventHandler::onGLFWWindowIconifyCallback);
    //glfwSetWindowCloseCallback(_mainWindow, GLFWEventHandler::onGLFWWindowCloseCallback);

    setFrameSize(rect.size.width, rect.size.height);

    // check OpenGL version at first
    const GLubyte* glVersion = glGetString(GL_VERSION);

    if ( utils::atof((const char*)glVersion) < 1.5 )
    {
        char strComplain[256] = {0};
        sprintf(strComplain,
                "OpenGL 1.5 or higher is required (your version is %s). Please upgrade the driver of your video card.",
                glVersion);
        MessageBox(strComplain, "OpenGL version too old");
        return false;
    }

    initGlew();

    // Enable point size by default.
    glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);

    return true;
}
コード例 #6
0
ファイル: graphics.cpp プロジェクト: bbqduc/Sheikki
	Graphics::Graphics()
{
	perspective=glm::perspective(45.0f, 4.0f/3.0f, 0.1f, 100.0f);
	initGlew();
	initGL();
	defaultShader.init();
	explosionShader.init();
	phongShader.init();
	//	initFonts();
}
コード例 #7
0
ファイル: Init.hpp プロジェクト: Rahotop/RTS
	Init() : m_initGlew(0)
	{
		GLenum initGlew(glewInit()); //On initialise glew
		
		if(initGlew != GLEW_OK)
		    std::cout << "Error : Glew init failed" << std::endl;
		else
			std::cout << "glew init ok" << std::endl;

	}
コード例 #8
0
bool GLView::initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor)
{
    setViewName(viewName);
    setFrameSize(rect.size.width, rect.size.height);
    setFrameZoomFactor(frameZoomFactor);
    
    glfwWindowHint(GLFW_RESIZABLE,GL_FALSE);
    
    _mainWindow = glfwCreateWindow(_screenSize.width * _frameZoomFactor,
                                   _screenSize.height * _frameZoomFactor,
                                   _viewName.c_str(),
                                   _primaryMonitor,
                                   NULL);
    glfwMakeContextCurrent(_mainWindow);
    
    int w, h;
    glfwGetWindowSize(_mainWindow, &w, &h);
    int frameBufferW, frameBufferH;
    glfwGetFramebufferSize(_mainWindow, &frameBufferW, &frameBufferH);
    
    if (frameBufferW == 2 * w && frameBufferH == 2 * h)
    {
        _isRetina = true;
        setFrameZoomFactor(frameZoomFactor * 2);
        glfwSetWindowSize(_mainWindow, rect.size.width/2 * _frameZoomFactor, rect.size.height/2 * _frameZoomFactor);
    }
    
    glfwSetMouseButtonCallback(_mainWindow, GLViewEventHandler::onGLFWMouseCallBack);
    glfwSetCursorPosCallback(_mainWindow, GLViewEventHandler::onGLFWMouseMoveCallBack);
    glfwSetScrollCallback(_mainWindow, GLViewEventHandler::onGLFWMouseScrollCallback);
    glfwSetCharCallback(_mainWindow, GLViewEventHandler::onGLFWCharCallback);
    glfwSetKeyCallback(_mainWindow, GLViewEventHandler::onGLFWKeyCallback);
    glfwSetWindowPosCallback(_mainWindow, GLViewEventHandler::onGLFWWindowPosCallback);
    glfwSetFramebufferSizeCallback(_mainWindow, GLViewEventHandler::onGLFWframebuffersize);
	glfwSetWindowSizeCallback(_mainWindow, GLViewEventHandler::OnGLFWWindowSizeFunCallback);
    // check OpenGL version at first
    const GLubyte* glVersion = glGetString(GL_VERSION);
    
    if ( atof((const char*)glVersion) < 1.5 )
    {
        char strComplain[256] = {0};
        sprintf(strComplain,
                "OpenGL 1.5 or higher is required (your version is %s). Please upgrade the driver of your video card.",
                glVersion);
        MessageBox(strComplain, "OpenGL version too old");
        return false;
    }
    
    initGlew();

    // Enable point size by default.
    glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
    
    return true;
}
コード例 #9
0
ファイル: main.cpp プロジェクト: freehyan/GLSL
//******************************************************************
//FUNCTION:
void init()
{
	glClearColor(0.0, 0.0, 0.0, 0.0);
	glShadeModel(GL_SMOOTH);
	glEnable(GL_DEPTH_TEST);
	initGlew();

	g_VBO->createVBO((GLfloat**)VerticesData, 9);
	g_ColorVBO->createVBO((GLfloat**)ColorData, 9);
	g_Shader->initShader("0vertex.glsl", "0fragment.glsl");
}
コード例 #10
0
bool RenderSystem::initialize()
{
	bool result = initGlew();

	if (result)
	{
		glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
	}

	return result;
}
コード例 #11
0
ファイル: main.cpp プロジェクト: Ssapo/TestOpengl
int main()
{
	if (!glfwInit())
	{
		std::cout << "glfwInit failed" << __WHERE__ << std::endl;
		exit(EXIT_FAILURE);
	}
	else std::cout << "glfwInit success" << __WHERE__ << std::endl;

	glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
	glfwWindowHint(GLFW_RED_BITS, 8);
	glfwWindowHint(GLFW_GREEN_BITS, 8);
	glfwWindowHint(GLFW_BLUE_BITS, 8);
	glfwWindowHint(GLFW_ALPHA_BITS, 8);
	glfwWindowHint(GLFW_DEPTH_BITS, 24);
	glfwWindowHint(GLFW_STENCIL_BITS, 8);

	auto glfwWindow = glfwCreateWindow(800, 600, "3D Chess", NULL, NULL);
	if (!glfwWindow)
	{
		glfwTerminate();
		std::cout << "glfwCreateWindow failed." << __WHERE__ << std::endl;
		exit(EXIT_FAILURE);
	}
	else std::cout << "glfwCreateWindow success" << __WHERE__ << std::endl;

	glfwMakeContextCurrent(glfwWindow);

	logGLVersionInfo();

	if (!initGlew())
	{
		std::cout << "initGlew failed" << __WHERE__ << std::endl;
		exit(-1);
	}
	else std::cout << "initGlew success" << __WHERE__ << std::endl;
	
	glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);

	while (!glfwWindowShouldClose(glfwWindow) && !glfwGetKey(glfwWindow, GLFW_KEY_ESCAPE))
	{
		glfwSwapBuffers(glfwWindow);
		glfwPollEvents();
	}

	glfwTerminate();

	std::cout << "\n\tBYE BYE." << std::endl;
	return EXIT_SUCCESS;
}
コード例 #12
0
MainWidget::MainWidget(int fps, QWidget *parent) : fps(fps), QWidget(parent)
{
	ui.setupUi(this);

	srand((unsigned int)time(NULL));//初始化随机数种子

	initWidgetProp();
	initOpenGLContext();
	initMultiSample();
	initGlew();
	initGLStates();
	initLabels();

	//设置绘制计时器
	connect(&drawTimer, SIGNAL(timeout()), this, SLOT(update()));
	drawTimer.start(1000 / fps);

	fpsTime = new QTime;
	fpsTime->start();

	isMousePress = false;

	pictureWidget = new PictureWidget;
	editPictureDialog = new EditPictureDialog;
	editPictureDialog->hide();
	helpDialog = new QDialog;
	QPalette palette = helpDialog->palette();
	QPixmap logo("Resources/bg/logo.jpg");
	palette.setBrush(QPalette::Window, logo);
	helpDialog->setWindowTitle(QString::fromLocal8Bit("关于"));
	helpDialog->setPalette(palette);
	helpDialog->resize(logo.size());
	helpDialog->hide();

	Scene::initSingletons(WIDTH, HEIGHT);
	scene = new Scene(WIDTH, HEIGHT);

	connect(scene, SIGNAL(setFileName(QString)), this, SLOT(setFileName(QString)));
	connect(scene, SIGNAL(setResolution(int, int)), this, SLOT(setResolution(int, int)));
	connect(scene, SIGNAL(setAlpha(float)), this, SLOT(setAlpha(float)));
	connect(scene, SIGNAL(displayCenterPicture(QString)), this, SLOT(displayCenterPicture(QString)));
	connect(scene, SIGNAL(showEditPictureDialog(QString, QString, QString, int, int)), this, SLOT(showEditPictureDialog(QString, QString, QString, int, int)));
	connect(scene, SIGNAL(showHelpDialog()), this, SLOT(showHelpDialog()));
	connect(pictureWidget, SIGNAL(closing()), this, SLOT(show()));
	connect(editPictureDialog, SIGNAL(reloadPicture(QString)), scene, SLOT(reloadPicture(QString)));
}
コード例 #13
0
ファイル: cookbook.cpp プロジェクト: rub0/GraphicsLibrary
int main(int argc, char ** argv)
{
	//init OpenGL context
	initGlut(argc, argv);
	initGlew();

	OnInit();
	glutCloseFunc(OnShutDown);
	glutDisplayFunc(OnRender);
	glutReshapeFunc(OnResize);
	glutMouseFunc(OnMouseDown);
	glutMotionFunc(OnMouseMove);
	glutKeyboardFunc(OnKeyDown);
	glutIdleFunc(OnIdle);
	glutMainLoop();
	return 0;
}
コード例 #14
0
ファイル: main.cpp プロジェクト: jporsay/gpExploration
bool initEverything() {
	app::Settings::inst()->setResourcePath("resources/");
	app::Settings::inst()->setShaderPath("resources/shaders/");
	app::Settings::inst()->setModelPath("resources/models/");
	app::Settings::inst()->setTexturePath("resources/textures/");
	Logger::inst()->setFileName("log.txt");
	eventManager = new event::Manager();
	eventManager->registerHandler(new handler::GenericHandler());
	app::GraphicSettings::screenHeight = 600;
	app::GraphicSettings::screenWidth = 800;
	if (!initSFML() || !initGlew() || !initOpenGL()) {
		return false;
	}
	cameraManager = manager::Camera::inst();
	cameraManager->add(new world::Camera(), "world");
	return true;
}
コード例 #15
0
ファイル: gfx_boilerplate.cpp プロジェクト: jellymann/shexp
void GFXBoilerplate::
init()
{
  glfwSetErrorCallback(error_callback);
  initGlfw();

  _window = glfwCreateWindow(_width, _height, "SHEXP", NULL, NULL);

  if (!_window)
  {
    glfwTerminate();
    exit(EXIT_FAILURE);
  }

  glewExperimental = GL_TRUE;
  glfwMakeContextCurrent(_window);
  initGlew();

  glfwSetKeyCallback(_window,key_callback);
}
コード例 #16
0
ファイル: GlContext.cpp プロジェクト: MrShedman/GL-Dev-2D
GlContext::GlContext()
:
m_window(NULL),
m_deviceContext(NULL),
m_context(NULL),
m_ownsWindow(true)
{
	m_window = CreateWindowA("STATIC", "", WS_POPUP | WS_DISABLED, 0, 0, 1, 1, NULL, NULL, GetModuleHandle(NULL), NULL);
	ShowWindow(m_window, SW_HIDE);
	m_deviceContext = GetDC(m_window);

	if (m_deviceContext)
	{
		createContext(VideoMode::getDesktopMode().bitsPerPixel, ContextSettings());
	}

	makeCurrent();

	//now that we have a dummy context we can initialize glew
	initGlew();
}
コード例 #17
0
ファイル: 03_triangle_v2.cpp プロジェクト: swgeek/MacOpenGL
int main(int argc, char ** argv)
{
   initGlutAndCreateWindow(argc, argv);
   initGlew();

   // compile and link shader programs, also sets program global variable
   openGLProgramObject = compileShaders();

   // get location/handle for coord variable in the vertex shader
   coordAttribute = getAttributeLocation("coord");

   // set the render function to continually call in the main loop
   glutDisplayFunc(render);

   // glClearColor only sets state, does not actually clear anything
   glClearColor(1.0f, 0.0f, 0.0f, 1.0f);

   // done with setup, now constantly loop and call render function
   glutMainLoop();

   return 1;
}
コード例 #18
0
ファイル: freeglut.cpp プロジェクト: srjek/dcpu16
void freeglut::StartMainLoop() {
    running = true;
    if (MainLoopLock->TryLock() == wxMUTEX_NO_ERROR) {
        int tmpWindow = glutCreateWindow("GLEW init");
        glutShowWindow();
        initGlew();
        std::cout << "OpenGL: " << glGetString(GL_VENDOR) << std::endl;
        std::cout << "OpenGL: " << glGetString(GL_RENDERER) << std::endl;
        std::cout << "OpenGL: " << glGetString(GL_VERSION) << std::endl;
        glutHideWindow();
        glutDestroyWindow(tmpWindow);
        
        unsigned int displayMode = GLUT_RGBA | GLUT_DOUBLE | GLUT_ALPHA | GLUT_DEPTH | GLUT_STENCIL;
        glutInitDisplayMode (displayMode);
        glutInitContextVersion (3, 0);
        glutInitContextProfile(GLUT_CORE_PROFILE);
        
        glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION);
        
        while (running) {
            glutMainLoopEvent();
            QueueLock->Lock();
            if (!callbackQueue.empty()) {
                callbackQueue.front()->callback();
                callbackQueue.pop();
            }
            QueueLock->Unlock();
        }
        
        for (std::map<int,freeglutWindow*>::iterator it=windows.begin(); it!=windows.end(); ++it) {
            glutDestroyWindow(it->first);
        }
        windows.clear();
    
        MainLoopLock->Unlock();
    }
}
コード例 #19
0
ファイル: GLView.cpp プロジェクト: wuqiang22/opengl
bool GLView::createWindow(std::string windowname)
{

	if (!glfwInit())
	{
		return false;
	}
	_glContextAttrs = { 8, 8, 8, 8, 24,8 };

	glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
	glfwWindowHint(GLFW_RED_BITS, _glContextAttrs.redBits);
	glfwWindowHint(GLFW_GREEN_BITS, _glContextAttrs.greenBits);
	glfwWindowHint(GLFW_BLUE_BITS, _glContextAttrs.blueBits);
	glfwWindowHint(GLFW_ALPHA_BITS, _glContextAttrs.alphaBits);
	glfwWindowHint(GLFW_DEPTH_BITS, _glContextAttrs.depthBits);
	glfwWindowHint(GLFW_STENCIL_BITS, _glContextAttrs.stencilBits);
	
	Size winSize = Director::getInstance()->getWinSize();
	_mainWindow = glfwCreateWindow(winSize.width, winSize.height, windowname.c_str(), nullptr, nullptr);
	glfwMakeContextCurrent(_mainWindow);  //在我们使用 GL 命令之前我们需要将创建的窗口设置为当前窗口

	//glViewport(0, 0, 480, 320);
	
	glfwSetMouseButtonCallback(_mainWindow, GLFWEventHandler::onGLFWMouseCallBack);
	glfwSetCursorPosCallback(_mainWindow, GLFWEventHandler::onGLFWMouseMoveCallBack);
	glfwSetScrollCallback(_mainWindow, GLFWEventHandler::onGLFWMouseScrollCallback);
	glfwSetCharCallback(_mainWindow, GLFWEventHandler::onGLFWCharCallback);
	glfwSetKeyCallback(_mainWindow, GLFWEventHandler::onGLFWKeyCallback);
	glfwSetWindowPosCallback(_mainWindow, GLFWEventHandler::onGLFWWindowPosCallback);
	glfwSetFramebufferSizeCallback(_mainWindow, GLFWEventHandler::onGLFWframebuffersize);
	glfwSetWindowSizeCallback(_mainWindow, GLFWEventHandler::onGLFWWindowSizeFunCallback);
	glfwSetWindowIconifyCallback(_mainWindow, GLFWEventHandler::onGLFWWindowIconifyCallback);
	
	initGlew();
	return true;
}
コード例 #20
0
int main(int argc, char* argv[]) {
    Display *display = XOpenDisplay(NULL);
    if (!display)
        fail("Failed to open X display\n");
    checkGlxVersion(display);
    auto bestFbc = chooseFBConfig(display);

    // Get a visual
    XVisualInfo *vi = glXGetVisualFromFBConfig(display, bestFbc);
    printf("Chosen visual ID = 0x%lx\n", vi->visualid);

    printf("Creating colormap\n");
    XSetWindowAttributes swa;
    Colormap cmap;
    swa.colormap = cmap = XCreateColormap(display,
            RootWindow(display, vi->screen),
            vi->visual, AllocNone);
    swa.background_pixmap = None ;
    swa.border_pixel      = 0;
    swa.event_mask        = StructureNotifyMask;

    printf("Creating window\n");
    Window win = XCreateWindow(display, RootWindow(display, vi->screen),
            0, 0, 100, 100, 0, vi->depth, InputOutput,
            vi->visual,
            CWBorderPixel|CWColormap|CWEventMask, &swa);
    if (!win)
        fail("Failed to create window.\n");

    // Done with the visual info data
    XFree(vi);
    XStoreName(display, win, "GL 3.0 Window");
    printf("Mapping window\n");
    XMapWindow(display, win);

    auto context = createContext(display, bestFbc);
    printf("Making context current\n");
    glXMakeCurrent(display, win, context);
    initGlew();

    GLuint tex_;
    GLuint fbo_;
    glGenTextures(1, &tex_);
    glBindTexture(GL_TEXTURE_2D, tex_);

    glGenFramebuffers(1, &fbo_);
    glBindFramebuffer(GL_FRAMEBUFFER, fbo_);
    glFramebufferTexture2D(GL_FRAMEBUFFER,
                           GL_COLOR_ATTACHMENT0,
                           GL_TEXTURE_2D,
                           tex_,
                           0);
    printGlErrors();

    glBindTexture(GL_TEXTURE_2D, tex_);
    glTexStorage2D(GL_TEXTURE_2D, 2, GL_RGBA8, 2, 2);
    char source_pixels[16] = {
        1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4
    };
    printGlErrors();
    printf("Crash here\n");
    glTexSubImage2D(GL_TEXTURE_2D,
                    0,
                    0, 0,
                    2, 2,
                    GL_RGBA, GL_UNSIGNED_BYTE,
                    source_pixels);
    printf("Crashed :( \n");
    printGlErrors();

    glCheckFramebufferStatus(GL_FRAMEBUFFER);

    char pixels[16] = {0};
    glReadPixels(0, 0, 2, 2, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
    glCheckFramebufferStatus(GL_FRAMEBUFFER);
    printGlErrors();

    glXMakeCurrent(display, 0, 0);
    glXDestroyContext(display, context);
    XDestroyWindow(display, win);
    XFreeColormap(display, cmap);
    XCloseDisplay(display);
    printf("Test success\n");
    return 0;
}
コード例 #21
0
bool GLViewImpl::initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor)
{
    setViewName(viewName);

    _frameZoomFactor = frameZoomFactor;

	if (s_intriGdipCanvasEnabled)
		IrregularGL::thisObject()->setupGL();
    glfwWindowHint(GLFW_RESIZABLE,GL_FALSE);
    glfwWindowHint(GLFW_RED_BITS,_glContextAttrs.redBits);
    glfwWindowHint(GLFW_GREEN_BITS,_glContextAttrs.greenBits);
    glfwWindowHint(GLFW_BLUE_BITS,_glContextAttrs.blueBits);
    glfwWindowHint(GLFW_ALPHA_BITS,_glContextAttrs.alphaBits);
    glfwWindowHint(GLFW_DEPTH_BITS,_glContextAttrs.depthBits);
    glfwWindowHint(GLFW_STENCIL_BITS,_glContextAttrs.stencilBits);
	
	// x-studio365 spec hints
    glfwWindowHint(GLFW_DECORATED, !s_intriWindowNoB);
    glfwWindowHint(GLFW_VISIBLE, s_intriWindowVisible);
	glfwWindowHint(GLFW_ALPHA_MASK, s_intriWindowAlphaEnabled);
	glfwxSetParent(s_intriWindowParent);

    int needWidth = rect.size.width * _frameZoomFactor;
    int neeHeight = rect.size.height * _frameZoomFactor;

    _mainWindow = glfwCreateWindow(needWidth, neeHeight, _viewName.c_str(), _monitor, nullptr);

    if (_mainWindow == nullptr)
    {
        std::string message = "Can't create window";
        if (!_glfwError.empty())
        {
            message.append("\nMore info: \n");
            message.append(_glfwError);
        }

        ccMessageBox(message.c_str(), "Error launch application");
        return false;
    }

    /*
    *  Note that the created window and context may differ from what you requested,
    *  as not all parameters and hints are
    *  [hard constraints](@ref window_hints_hard).  This includes the size of the
    *  window, especially for full screen windows.  To retrieve the actual
    *  attributes of the created window and context, use queries like @ref
    *  glfwGetWindowAttrib and @ref glfwGetWindowSize.
    *
    *  see declaration glfwCreateWindow
    */
    int realW = 0, realH = 0;
    glfwGetWindowSize(_mainWindow, &realW, &realH);
    if (realW != needWidth)
    {
        rect.size.width = realW / _frameZoomFactor;
    }
    if (realH != neeHeight)
    {
        rect.size.height = realH / _frameZoomFactor;
    }

    glfwMakeContextCurrent(_mainWindow);

	// x-studio365 spec: use glfwx setMouseButtonCallback ensure update mouse coord immediately.
    glfwxSetMouseButtonCallback(_mainWindow, GLFWEventHandler::onGLFWMouseCallBackEx);
    glfwSetCursorPosCallback(_mainWindow, GLFWEventHandler::onGLFWMouseMoveCallBack);
    glfwSetScrollCallback(_mainWindow, GLFWEventHandler::onGLFWMouseScrollCallback);
    glfwSetCharCallback(_mainWindow, GLFWEventHandler::onGLFWCharCallback);
    glfwSetKeyCallback(_mainWindow, GLFWEventHandler::onGLFWKeyCallback);
    glfwSetWindowPosCallback(_mainWindow, GLFWEventHandler::onGLFWWindowPosCallback);
    glfwSetFramebufferSizeCallback(_mainWindow, GLFWEventHandler::onGLFWframebuffersize);
    glfwSetWindowSizeCallback(_mainWindow, GLFWEventHandler::onGLFWWindowSizeFunCallback);
    glfwSetWindowIconifyCallback(_mainWindow, GLFWEventHandler::onGLFWWindowIconifyCallback);

    setFrameSize(rect.size.width, rect.size.height);

    // check OpenGL version at first
    const GLubyte* glVersion = glGetString(GL_VERSION);

    if ( utils::atof((const char*)glVersion) < 1.5 )
    {
        char strComplain[256] = {0};
        sprintf(strComplain,
                "OpenGL 1.5 or higher is required (your version is %s). Please upgrade the driver of your video card.",
                glVersion);
        ccMessageBox(strComplain, "OpenGL version too old");
        return false;
    }

    initGlew();

    // Enable point size by default.
    glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);

    return true;
}
コード例 #22
0
bool GLViewImpl::initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor)
{
    setViewName(viewName);

    _frameZoomFactor = frameZoomFactor;

	glfwWindowHint(GLFW_DECORATED,GL_FALSE);
    glfwWindowHint(GLFW_RESIZABLE,GL_FALSE);
    glfwWindowHint(GLFW_RED_BITS,_glContextAttrs.redBits);
    glfwWindowHint(GLFW_GREEN_BITS,_glContextAttrs.greenBits);
    glfwWindowHint(GLFW_BLUE_BITS,_glContextAttrs.blueBits);
    glfwWindowHint(GLFW_ALPHA_BITS,_glContextAttrs.alphaBits);
    glfwWindowHint(GLFW_DEPTH_BITS,_glContextAttrs.depthBits);
    glfwWindowHint(GLFW_STENCIL_BITS,_glContextAttrs.stencilBits);

    int needWidth = rect.size.width * _frameZoomFactor;
    int neeHeight = rect.size.height * _frameZoomFactor;

    _mainWindow = glfwCreateWindow(needWidth, neeHeight, _viewName.c_str(), _monitor, nullptr);
	if (!_mainWindow)
	{
		MessageBox("Window creation will fail if the Microsoft GDI software OpenGL implementation is the only one available.", "Create Window failed");
		return false;
	}

    /*
    *  Note that the created window and context may differ from what you requested,
    *  as not all parameters and hints are
    *  [hard constraints](@ref window_hints_hard).  This includes the size of the
    *  window, especially for full screen windows.  To retrieve the actual
    *  attributes of the created window and context, use queries like @ref
    *  glfwGetWindowAttrib and @ref glfwGetWindowSize.
    *
    *  see declaration glfwCreateWindow
    */
    int realW = 0, realH = 0;
    glfwGetWindowSize(_mainWindow, &realW, &realH);
    if (realW != needWidth)
    {
        rect.size.width = realW / _frameZoomFactor;
    }
    if (realH != neeHeight)
    {
        rect.size.height = realH / _frameZoomFactor;
    }

    glfwMakeContextCurrent(_mainWindow);

    glfwSetMouseButtonCallback(_mainWindow, GLFWEventHandler::onGLFWMouseCallBack);
    glfwSetCursorPosCallback(_mainWindow, GLFWEventHandler::onGLFWMouseMoveCallBack);
    glfwSetScrollCallback(_mainWindow, GLFWEventHandler::onGLFWMouseScrollCallback);
    glfwSetCharCallback(_mainWindow, GLFWEventHandler::onGLFWCharCallback);
    glfwSetKeyCallback(_mainWindow, GLFWEventHandler::onGLFWKeyCallback);
    glfwSetWindowPosCallback(_mainWindow, GLFWEventHandler::onGLFWWindowPosCallback);
    glfwSetFramebufferSizeCallback(_mainWindow, GLFWEventHandler::onGLFWframebuffersize);
    glfwSetWindowSizeCallback(_mainWindow, GLFWEventHandler::onGLFWWindowSizeFunCallback);
    glfwSetWindowIconifyCallback(_mainWindow, GLFWEventHandler::onGLFWWindowIconifyCallback);
	glfwSetWindowCloseCallback(_mainWindow, GLFWEventHandler::onGLFWWindowCloseCallback);
	glfwSetCursorEnterCallback(_mainWindow, GLFWEventHandler::onGLFWCursorEnterCallBack);

    setFrameSize(rect.size.width, rect.size.height);

    // check OpenGL version at first
    const GLubyte* glVersion = glGetString(GL_VERSION);

    if ( utils::atof((const char*)glVersion) < 1.5 )
    {
        char strComplain[256] = {0};
        sprintf(strComplain,
                "OpenGL 1.5 or higher is required (your version is %s). Please upgrade the driver of your video card.",
                glVersion);
        MessageBox(strComplain, "OpenGL version too old");
        return false;
    }

    initGlew();

    // Enable point size by default.
    glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);

    return true;
}
コード例 #23
0
ファイル: Server.cpp プロジェクト: BSkin/Rune
int Server::run(const char * ini)
{
	readServerData(ini);

	//clients = new Client[maxPlayers];
	clients = vector<Client*>();
	clients.reserve(maxPlayers);
	for (int i = 0; i < maxPlayers; i++) {
		clients.push_back(new Client());
		clients[i]->setID(i);
	}
		
	double elapsedTime = 0.0;
	double timePerFrame = 1000.0 / updateRate;
	double timePerRenderFrame = 1000.0 / renderRefreshRate;
	static double timeSinceLastRender = 0.0;
	long lastTime = 0;

	double targetSleep = 0.0;
	double sleepRemainder = 0.0;
	double startSleep = 0.0;
	double sleepTime = 0.0;

	loadConfig();
	initSDL();
	initGlew();
	initBullet();
	initGLContexts();
	initObjects();
	
	running = true;
	HANDLE listenThreadHandle = HostListener::start();

	loadResources();
	loadLevel("asdf");

	while (running) {
		frameCount++;
		if (GetAsyncKeyState(VK_ESCAPE) && (GetForegroundWindow() == consoleWindow) &&
			MessageBox(0, "Shutdown the Server?", "Rune Server Shutdown", MB_YESNO) == IDYES) break;

		lastTime = lastTime = SDL_GetTicks();

		serverEventsTCP->clearSendBuffer();
		serverEventsTCP->clearReceiveBuffer();
		serverEventsUDP->clearSendBuffer();
		serverEventsUDP->clearReceiveBuffer();

		//Get all commands from clients
		for (int i = 0; i < maxPlayers; i++) {
			DataBuffer * temp;
			aquireClientsMutex(i);
				temp = clients[i]->popReceiveData();
				if (!clients[i]->isConnected() && playerObjects->at(i) != NULL) {
					int index = -1;
					int x = 0;
					for (list<pair<unsigned long, GameObject*>>::iterator iter = gameObjects->begin(); iter != gameObjects->end(); iter++) {
						if (playerObjects->at(i) == iter->second) {
							index = x;
							break;
						}
						x++;
					}
					/*for (int x = 0; x < gameObjects->size(); x++) {
						if (playerObjects->at(i) == gameObjects->at(x))
							index = x;
					}*/
					gameObjects->remove(playerObjects->at(i)->getNetID());
					delete playerObjects->at(i);
					playerObjects->at(i) = NULL;
					//gameObjects->erase(gameObjects->begin() + index);
					serverEventsTCP->appendToSendBuffer(NetworkFunctions::createDeleteObjectBuffer(index));
				}
			releaseClientsMutex(i);
			serverEventsTCP->appendToReceiveBuffer(temp);
		}

		//Receive All UDP Events
		sockaddr_in * originAddress = NULL;
		DataBuffer * udpBuffer = UDPManager::recvDatagram(&originAddress);
		while (udpBuffer != NULL) {
			//origin Address matches client address?
			unsigned long packetFrameCount = 0;
			memcpy(&packetFrameCount, udpBuffer->getData(), 4);

			int clientID = getClientIDByAddress(originAddress->sin_addr.s_addr, originAddress->sin_port);
			if (clientID == -1) {
				int asdfadsfasdf = 123123;
			}
			else {
				//compare clientFrameCount to client->frameCount
				unsigned long clientFrameCount;
				aquireClientsMutex(clientID);
					clientFrameCount = clients[clientID]->getFrameCount();
				releaseClientsMutex(clientID);

				if (packetFrameCount < clientFrameCount) {
					//discard
					printf("Packet from Client %d discarded\n", clientID);
				}
				else {
					serverEventsUDP->appendToReceiveBuffer(udpBuffer->getData() + 4, udpBuffer->getSize() - 4);
					aquireClientsMutex(clientID);
						clients[clientID]->setFrameCount(packetFrameCount);
					releaseClientsMutex(clientID);
				}

			}
			
			delete udpBuffer; udpBuffer = NULL;
			delete originAddress; originAddress = NULL;
			udpBuffer = UDPManager::recvDatagram(&originAddress);
		}

		NetworkFunctions::translateReceivedEvents(serverEventsTCP);
		NetworkFunctions::translateReceivedEvents(serverEventsUDP);
		
		//Execute my own gamelogic commands
		SDL_Event e;
		while (SDL_PollEvent(&e)) { 
			if (e.key.keysym.sym == SDLK_ESCAPE)
						running = false;
			if (e.key.keysym.sym == SDLK_m) {
				((RigidObject*)gameObjects->getValue(2))->setPosition(5, 10, 0);
				((RigidObject*)gameObjects->getValue(3))->setPosition(0, 10, 0);
				((RigidObject*)gameObjects->getValue(4))->setPosition(-5, 10, 0);
				((RigidObject*)gameObjects->getValue(2))->setVelocity(0, 0, 0);
				((RigidObject*)gameObjects->getValue(3))->setVelocity(0, 0, 0);
				((RigidObject*)gameObjects->getValue(4))->setVelocity(0, 0, 0);
				((RigidObject*)gameObjects->getValue(2))->setGravity(0, -9.81f*4.0f, 0);
				((RigidObject*)gameObjects->getValue(3))->setGravity(0, -9.81f*4.0f, 0);
				((RigidObject*)gameObjects->getValue(4))->setGravity(0, -9.81f*4.0f, 0);
				printf("reset boxes\n");
			}
		}

		//if (update((long)(elapsedTime + sleepTime)) == -1) break;

		//dynamicsWorld->stepSimulation((float)(elapsedTime + sleepTime)*0.001f, 50, (float)(elapsedTime + sleepTime)*0.001f);
		dynamicsWorld->stepSimulation(1.0f / 64.0f, 100, 1.0f / 64.0f); //1.0f/(float)Settings::getMaxFPS());

		list<pair<unsigned long, GameObject*>>::iterator iter = gameObjects->begin();
		while (iter != gameObjects->end())
		{
			iter->second->update(elapsedTime);
			if (!iter->second->isAlive()) {
				serverEventsTCP->appendToSendBuffer(NetworkFunctions::createDeleteObjectBuffer(iter->second->getNetID()));
				for (int p = 0; p < maxPlayers; p++) {
					if (playerObjects->at(p) != NULL && playerObjects->at(p) == iter->second) {
						playerObjects->at(p) = NULL;
					}
				}

				GameObject * tempObject = iter->second;
				iter = gameObjects->erase(iter);
				delete tempObject;
			}
			else iter++;
		}

		/*for (list<pair<unsigned long, GameObject*>>::iterator iter = gameObjects->begin(); iter != gameObjects->end(); iter++) {
			iter->second->update(elapsedTime);
			if (!iter->second->isAlive()) {
				serverEventsTCP->appendToSendBuffer(NetworkFunctions::createDeleteObjectBuffer(iter->second->getNetID()));
				for (int p = 0; p < maxPlayers; p++) {
					if (playerObjects->at(p) != NULL && playerObjects->at(p) == iter->second) {
						playerObjects->at(p) = NULL;
					}
				}

				gameObjects->remove(iter->first, iter->second);
				delete (*gameObjects)[i];
				gameObjects->erase(gameObjects->begin() + i);
				i--;
			}
		}*/

		/*for (int i = 0; i < (int)gameObjects->size(); i++) {
			(*gameObjects)[i]->update(elapsedTime);
			if (!(*gameObjects)[i]->isAlive()) {
				serverEventsTCP->appendToSendBuffer(NetworkFunctions::createDeleteObjectBuffer(i));
				for (int p = 0; p < maxPlayers; p++) {
					if (playerObjects->at(p) != NULL && playerObjects->at(p) == (*gameObjects)[i]) {
						playerObjects->at(p) = NULL;
					}
				}
				delete (*gameObjects)[i];
				gameObjects->erase(gameObjects->begin() + i);
				i--;
			}
		}*/
		
		//Update each client
		//for (int i = 0; i < gameObjects->size(); i++)
		//	serverEvents->appendToSendBuffer(NetworkFunctions::createUpdateObjectBuffer(i));

		for (int i = 0; i < maxPlayers; i++) {
			aquireClientsMutex(i);
				if (clients[i]->isConnected()) {
					if (clients[i]->requiresSynch()) {
						synchClient(i);
						clients[i]->setSynch(false);
					}
					else {
						clients[i]->pushSendData(serverEventsTCP->getSendBuffer(), serverEventsTCP->getSendBufferSize());
					}
				}
			releaseClientsMutex(i);
		}
		
		for (int i = 0; i < maxPlayers; i++) {
			aquireClientsMutex(i);
			if (clients[i]->isConnected()) {
				//unsigned long clientPortUDP = clients[i]->getPortUDP();
				if (!clients[i]->requiresSynch()) {
					serverEventsUDP->clearSendBuffer();
					for (list<pair<unsigned long, GameObject*>>::iterator iter = gameObjects->begin(); iter != gameObjects->end(); iter++) {
						if (playerObjects->at(i) != iter->second /* && dont force player */) {
							DataBuffer * temp = NetworkFunctions::createUpdateObjectBuffer(iter->second->getNetID());
							serverEventsUDP->appendToSendBuffer(temp);
						}
					}
					UDPManager::sendDatagram(serverEventsUDP->getSendBuffer(), serverEventsUDP->getSendBufferSize(), clients[i]->getIPAddress(), clients[i]->getPortUDP(), frameCount);
				}
			}
			releaseClientsMutex(i);
		}

		/*timeSinceLastRender += elapsedTime;
		if (timeSinceLastRender >= timePerRenderFrame) {
			timeSinceLastRender = 0.0;
			renderFrame();
		}*/
		renderFrame();

		//Update Rate Calculations
		//Framerate Limit Calculations
		elapsedTime = SDL_GetTicks() - lastTime;
		targetSleep = timePerFrame - elapsedTime + sleepRemainder;
		if (targetSleep > 0) sleepRemainder = targetSleep - (Uint32)targetSleep;

		//Sleep(1000.0 / 64.0);
		
		startSleep = SDL_GetTicks();
		while ((Uint32)(startSleep + targetSleep) > SDL_GetTicks());
		sleepTime = SDL_GetTicks() - startSleep;
	}

	cout << "Shutting Down\n";
	HostThread::stopAll();
	HostListener::stop();
	UDPManager::cleanup();
	WSACleanup();
	WaitForSingleObject(listenThreadHandle, INFINITE);

	saveConfig();

	cleanupObjects();
	//saveConfig();
	killBullet();
		
	//delete [] clients;
	
	return 0;
}
コード例 #24
0
bool GLViewImpl::initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor, HWND hParentWnd)
{
    setViewName(viewName);

    _frameZoomFactor = frameZoomFactor;

    glfwWindowHint(GLFW_RESIZABLE,GL_FALSE);
    glfwWindowHint(GLFW_RED_BITS,_glContextAttrs.redBits);
    glfwWindowHint(GLFW_GREEN_BITS,_glContextAttrs.greenBits);
    glfwWindowHint(GLFW_BLUE_BITS,_glContextAttrs.blueBits);
    glfwWindowHint(GLFW_ALPHA_BITS,_glContextAttrs.alphaBits);
    glfwWindowHint(GLFW_DEPTH_BITS,_glContextAttrs.depthBits);
    glfwWindowHint(GLFW_STENCIL_BITS,_glContextAttrs.stencilBits);
	if (hParentWnd){
		glfwWindowHint(GLFW_VISIBLE, GL_FALSE);
	}
    int needWidth = rect.size.width * _frameZoomFactor;
    int neeHeight = rect.size.height * _frameZoomFactor;

    _mainWindow = glfwCreateWindow(needWidth, neeHeight, _viewName.c_str(), _monitor, nullptr);

    if (_mainWindow == nullptr)
    {
        std::string message = "Can't create window";
        if (!_glfwError.empty())
        {
            message.append("\nMore info: \n");
            message.append(_glfwError);
        }

        MessageBox(message.c_str(), "Error launch application");
        return false;
    }

    /*
    *  Note that the created window and context may differ from what you requested,
    *  as not all parameters and hints are
    *  [hard constraints](@ref window_hints_hard).  This includes the size of the
    *  window, especially for full screen windows.  To retrieve the actual
    *  attributes of the created window and context, use queries like @ref
    *  glfwGetWindowAttrib and @ref glfwGetWindowSize.
    *
    *  see declaration glfwCreateWindow
    */
    int realW = 0, realH = 0;
    glfwGetWindowSize(_mainWindow, &realW, &realH);
    if (realW != needWidth)
    {
        rect.size.width = realW / _frameZoomFactor;
    }
    if (realH != neeHeight)
    {
        rect.size.height = realH / _frameZoomFactor;
    }

    glfwMakeContextCurrent(_mainWindow);

    glfwSetMouseButtonCallback(_mainWindow, GLFWEventHandler::onGLFWMouseCallBack);
    glfwSetCursorPosCallback(_mainWindow, GLFWEventHandler::onGLFWMouseMoveCallBack);
    glfwSetScrollCallback(_mainWindow, GLFWEventHandler::onGLFWMouseScrollCallback);
    glfwSetCharCallback(_mainWindow, GLFWEventHandler::onGLFWCharCallback);
    glfwSetKeyCallback(_mainWindow, GLFWEventHandler::onGLFWKeyCallback);
    glfwSetWindowPosCallback(_mainWindow, GLFWEventHandler::onGLFWWindowPosCallback);
    glfwSetFramebufferSizeCallback(_mainWindow, GLFWEventHandler::onGLFWframebuffersize);
    glfwSetWindowSizeCallback(_mainWindow, GLFWEventHandler::onGLFWWindowSizeFunCallback);
    glfwSetWindowIconifyCallback(_mainWindow, GLFWEventHandler::onGLFWWindowIconifyCallback);

    setFrameSize(rect.size.width, rect.size.height);

    // check OpenGL version at first
    const GLubyte* glVersion = glGetString(GL_VERSION);

    if ( utils::atof((const char*)glVersion) < 1.5 )
    {
        char strComplain[256] = {0};
        sprintf(strComplain,
                "OpenGL 1.5 or higher is required (your version is %s). Please upgrade the driver of your video card.",
                glVersion);
        MessageBox(strComplain, "OpenGL version too old");
        return false;
    }

    initGlew();

    // Enable point size by default.
    glEnable(GL_VERTEX_PROGRAM_POINT_SIZE);
	m_hwnd = glfwGetWin32Window(_mainWindow);
	if (hParentWnd){
		::SetParent(m_hwnd, hParentWnd);
		//改变当前窗口的样式,去掉标题
		SetWindowLong(m_hwnd, GWL_STYLE, GetWindowLong(m_hwnd, GWL_STYLE) & ~WS_CAPTION);
		//设置位置
		::SetWindowPos(m_hwnd, HWND_TOP, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height,
			SWP_NOCOPYBITS | SWP_HIDEWINDOW);
	}
    return true;
}
コード例 #25
0
ファイル: Main.cpp プロジェクト: GregJo/BA-Framework
int main()
{
	// Create and initialize window.
	setErrorCallbackAndInit(error_callback);
	GraphicsWindow* window = new GraphicsWindow(1200,800,"Test Window",NULL,NULL,key_callback);
	window->makeContextCurrent();

	// Initalize glew.
	initGlew();

	// Create and initialize Camera
	FreeCamera* camera = new FreeCamera(45.0f, 16.0f/9.0f, 
					0.0f, 0.0f, 
					0.1f, 10000.0f, 
					0.0004f, 3.0f,
					glm::vec3(0,0,-50), 
					glm::vec3(0,1,0), 
					glm::vec3(0,0,0), 
					true);

	camera->setViewport(window->getWindowWidth(),window->getWindowHeight(),0.5f,0.5f);

	// Load accumulation shader for accumulating all the transparent matrials, as well as their alphas.
	GLSLProgram* defaultShader = new GLSLProgram();
	defaultShader->initShaderProgram("Vert.glsl","","","","Frag.glsl");

	// Load screen filling quad shader.
	GLSLProgram* screenFillingQuadShader = new GLSLProgram();
	screenFillingQuadShader->initShaderProgram("screenFillingQuadVert.glsl","","","","screenFillingQuadFrag.glsl");

	// Load accumulation shader for accumulating all the transparent matrials, as well as their alphas.
	GLSLProgram* accumTransparencyRevealageShader = new GLSLProgram();
	accumTransparencyRevealageShader->initShaderProgram("AccumTransparencyRevealageVert.glsl","","","","AccumTransparencyRevealageFrag.glsl");

	// Load Weighted Average shader, which will be used for final compositing (a variation of screen filling quad shader using multiple textures).
	GLSLProgram* newOITCoverageShader = new GLSLProgram();
	newOITCoverageShader->initShaderProgram("NewOITCoverageVert.glsl","","","","NewOITCoverageFrag.glsl");

	// Create screen filling quad.
	Quad* screenFillingQuad = new Quad(glm::vec3(-1.0,1.0,0), glm::vec3(-1.0,-1.0,0), glm::vec3(1.0,-1.0,0), glm::vec3(1.0,1.0,0), glm::vec3(0), 0, 0, 0);
	
	screenFillingQuad->initQuad();
	screenFillingQuad->setGLSLProgram(*newOITCoverageShader);

	TextureManager::GetInstance().loadTexture("../Content/Textures/Particle_Smoke/smoke_particle_red_base.png");
	TextureManager::GetInstance().loadTexture("../Content/Textures/Particle_Smoke/smoke_particle_grey_base_2.png");
	TextureManager::GetInstance().loadTexture("../Content/Textures/Particle_Smoke/smoke_particle_grey_base_3.png");

	Quad* quad1 = new Quad(glm::vec3(100+100,100+100,-1), glm::vec3(100+100,-100+100,-1), glm::vec3(-100+100,-100+100,-1), glm::vec3(-100+100,100+100,-1), glm::vec3(0), 10, 10, 0);
	quad1->initQuad();
	quad1->initDefaultTexture(255,0,0,89);
	quad1->setTexture(TextureManager::GetInstance().getTextureHandle("../Content/Textures/Particle_Smoke/smoke_particle_grey_base_3.png"));

	Quad* quad2 = new Quad(glm::vec3(100+100,100+100,-20), glm::vec3(100+100,-100+100,-20), glm::vec3(-100+100,-100+100,-20), glm::vec3(-100+100,100+100,-20), glm::vec3(0), 10, 10, 0);
	quad2->initQuad();
	quad2->initDefaultTexture(0,255,0,89);
	quad2->setTexture(TextureManager::GetInstance().getTextureHandle("../Content/Textures/Particle_Smoke/smoke_particle_grey_base_2.png"));

	Quad* quad3 = new Quad(glm::vec3(100+100,100+100,20), glm::vec3(100+100,-100+100,20), glm::vec3(-100+100,-100+100,20), glm::vec3(-100+100,100+100,20), glm::vec3(0), 10, 10, 0);
	quad3->initQuad();
	quad3->initDefaultTexture(0,0,255,89);
	quad3->setTexture(TextureManager::GetInstance().getTextureHandle("../Content/Textures/Particle_Smoke/smoke_particle_red_base.png"));

	Quad* quad4 = new Quad(glm::vec3(100+100,100+100,-40), glm::vec3(100+100,-100+100,-40), glm::vec3(-100+100,-100+100,-40), glm::vec3(-100+100,100+100,-40), glm::vec3(0), 10, 10, 0);
	quad4->initQuad();
	quad4->initDefaultTexture(255,0,127,50);

	Quad* quad5 = new Quad(glm::vec3(100+100,100+100,40), glm::vec3(100+100,-100+100,40), glm::vec3(-100+100,-100+100,40), glm::vec3(-100+100,100+100,40), glm::vec3(0), 10, 10, 0);
	quad5->initQuad();
	quad5->initDefaultTexture(255,127,0,50);

	ModelLoader* modelImporter = new ModelLoader();
	modelImporter->importModel("../Content/Models/crytek-sponza/sponza.obj", processFlagsOnModelImport);

	// Create and initialize model
	Model* model = new Model(glm::vec3(0,0,0), "../Content/Models/crytek-sponza/");
	model->loadModel(modelImporter->getScene());

	// Create framebuffers
	std::vector<unsigned int> activeColorAttachmentsOpaque;
	std::vector<unsigned int> activeColorAttachmentsTransparent;

	Framebuffer* opaqueFrameBuffer = new Framebuffer(window->getWindowWidth(),window->getWindowHeight());
	
	activeColorAttachmentsOpaque.push_back(0);

	opaqueFrameBuffer->setColorAttachment(0);

	//frameBuffer->setDepthAttachment();
	opaqueFrameBuffer->setDepthStencilTexture();

	opaqueFrameBuffer->unbind();

	Framebuffer* accumFrameBuffer = new Framebuffer(window->getWindowWidth(),window->getWindowHeight());
	
	activeColorAttachmentsTransparent.push_back(0);
	activeColorAttachmentsTransparent.push_back(1);

	accumFrameBuffer->setColorAttachment(0);
	accumFrameBuffer->setColorAttachment(1);

	//frameBuffer->setDepthAttachment();
	accumFrameBuffer->setDepthStencilTexture();

	accumFrameBuffer->unbind();

	// Additional textures to pass for the second transparency render pass.
	std::vector<GLuint> additionalTextureHandles;
	additionalTextureHandles.push_back(accumFrameBuffer->getColorAttachment(0));
	additionalTextureHandles.push_back(accumFrameBuffer->getColorAttachment(1));

	std::vector<GLuint> opaqueTextureHandle;
	opaqueTextureHandle.push_back(opaqueFrameBuffer->getColorAttachment(0));

	// Move this to "GraphicsWindow" 
	glfwSetCursorPos(window->getWindowHandle(), (double) (window->getWindowWidth()/2.0), (double) (window->getWindowHeight()/2.0));
	
	// Move this to "Camera"
	//glClearColor(0.4f,0.6f,0.94f,0.0f);
	glClearColor(0.0f,0.0f,0.0f,0.0f);

	const float clearColorWhite = 1.0f;
	const float clearColorBlack = 0.0f;

	// Sampler
	GLuint sampler = 0;
	glGenSamplers(1, &sampler);

	glSamplerParameteri(sampler, GL_TEXTURE_WRAP_S, GL_REPEAT);  
	glSamplerParameteri(sampler, GL_TEXTURE_WRAP_T, GL_REPEAT);
	glSamplerParameteri(sampler, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glSamplerParameteri(sampler, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

	check_gl_error();

	// Render Loop
	while(!window->shouldClose())
	{
		//glClearColor(0.0f,0.0f,0.0f,0.0f);
		glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

		glEnable(GL_DEPTH_TEST);
		glDepthFunc(GL_LEQUAL);
		glEnable(GL_CULL_FACE);
		glCullFace(GL_BACK);

		// Update camera
		camera->camControll(window->getWindowHandle());
		camera->update();
		
		// Update shader uniforms
		model->getCurrentGLSLProgram()->use();
		model->getCurrentGLSLProgram()->setUniform("lightPosition", camera->getCamPos());
		model->getCurrentGLSLProgram()->setUniform("camPosition", camera->getCamPos());
		model->getCurrentGLSLProgram()->setUniform("viewMatrix", camera->getVMatrix());
		model->getCurrentGLSLProgram()->setUniform("normalMatrix", camera->getTranspInvMVMatrix()); // Change this!
		model->getCurrentGLSLProgram()->setUniform("VPMatrix", camera->getVPMatrix());

		opaqueFrameBuffer->clean();
		opaqueFrameBuffer->bind();
		opaqueFrameBuffer->bindForRenderPass(activeColorAttachmentsOpaque);

		model->renderOpaque();
		//quad4->render();
		//quad5->render();

		//opaqueFrameBuffer->unbind();

		//// Blitting the opaque scene depth to propperly depth test the transparen against it.
		//opaqueFrameBuffer->bindForReading();

		//accumFrameBuffer->bindForWriting();
		//glBlitFramebuffer(0, 0, window->getWindowWidth(), window->getWindowHeight(), 0, 0, window->getWindowWidth(), window->getWindowHeight(), 
		//				  GL_DEPTH_BUFFER_BIT, GL_NEAREST);

		//opaqueFrameBuffer->unbind();

		//_______________________________________________________________________________________________________________________________________________________________________________
		// Acuumulation pass
		accumTransparencyRevealageShader->use();
		accumTransparencyRevealageShader->setUniform("VPMatrix", camera->getVPMatrix());

		model->setGLSLProgram(accumTransparencyRevealageShader);
		quad1->setGLSLProgram(*accumTransparencyRevealageShader);
		quad2->setGLSLProgram(*accumTransparencyRevealageShader);
		quad3->setGLSLProgram(*accumTransparencyRevealageShader);
		quad4->setGLSLProgram(*accumTransparencyRevealageShader);
		quad5->setGLSLProgram(*accumTransparencyRevealageShader);

		accumFrameBuffer->clean();
		accumFrameBuffer->bind();
		accumFrameBuffer->bindForRenderPass(activeColorAttachmentsTransparent);
		accumFrameBuffer->cleanColorAttachment(1,clearColorWhite);

		opaqueFrameBuffer->unbind();

		// Blitting the opaque scene depth to propperly depth test the transparen against it.
		opaqueFrameBuffer->bindForReading();

		accumFrameBuffer->bindForWriting();
		glBlitFramebuffer(0, 0, window->getWindowWidth(), window->getWindowHeight(), 0, 0, window->getWindowWidth(), window->getWindowHeight(), 
						  GL_DEPTH_BUFFER_BIT, GL_NEAREST);

		opaqueFrameBuffer->unbind();

		accumFrameBuffer->bind();
		accumFrameBuffer->bindForRenderPass(activeColorAttachmentsTransparent);

		glEnable(GL_BLEND);
		glBlendFunci(0, GL_ONE, GL_ONE);
		glBlendFunci(1, GL_ZERO, GL_ONE_MINUS_SRC_ALPHA);
		//glEnable(GL_DEPTH_TEST);
		glDepthMask(GL_FALSE);
		glDisable(GL_CULL_FACE);

		model->renderTransparent();
		quad1->render();
		quad2->render();
		quad3->render();
		//quad4->render();
		//quad5->render();

		accumFrameBuffer->unbind();

		model->setGLSLProgram(defaultShader);
		quad1->setGLSLProgram(*defaultShader);
		quad2->setGLSLProgram(*defaultShader);
		quad3->setGLSLProgram(*defaultShader);
		quad4->setGLSLProgram(*defaultShader);
		quad5->setGLSLProgram(*defaultShader);

		glDisable(GL_BLEND);
		//glEnable(GL_DEPTH_TEST);
		glDepthMask(GL_TRUE);
		glEnable(GL_CULL_FACE);
		glCullFace(GL_BACK);

		//_______________________________________________________________________________________________________________________________________________________________________________
		// Final compositing pass

		//screenFillingQuad->setGLSLProgram(*screenFillingQuadShader);
		//screenFillingQuad->getCurrentShaderProgram()->use();
		//screenFillingQuad->renderWithAdditionalTextures(opaqueTextureHandle,sampler);

		newOITCoverageShader->use();

		glDepthMask(GL_FALSE);
		glEnable(GL_BLEND);
		glBlendFunc(GL_ONE_MINUS_SRC_ALPHA, GL_SRC_ALPHA);

		screenFillingQuad->renderWithAdditionalTextures(additionalTextureHandles,sampler);

		glDepthMask(GL_TRUE);
		glDisable(GL_BLEND);
		//_______________________________________________________________________________________________________________________________________________________________________________

		// For debug!
		//screenFillingQuad->setGLSLProgram(*screenFillingQuadShader);
		//screenFillingQuad->getCurrentShaderProgram()->use();
		//screenFillingQuad->setTexture(opaqueFrameBuffer->getColorAttachment(0));
		//screenFillingQuad->render();

		accumFrameBuffer->clean();

		window->swapBuffers();

		glfwPollEvents();

		check_gl_error();
	}

	glfwTerminate();
	window->release();
	
	return 0;
}
コード例 #26
0
ファイル: main.c プロジェクト: MarkKerner/RotatingBox
int main() {

    GLFWwindow* window = initGlfwWindow();
    if (window == NULL) {
        printf("Window init failed");
        return 1;
    }

    initGlew();

    GLuint mainVertexShader = createShader(GL_VERTEX_SHADER, mainVertexSource);
    GLuint mainFragmentShader = createShader(GL_FRAGMENT_SHADER, mainFragmentSource);

    GLuint mainShaderProgram = createShaderProgram(mainVertexShader, mainFragmentShader);

    GLuint boxVao;
    GLuint floorVao;
    glGenVertexArrays(1, &floorVao);
    glGenVertexArrays(1, &boxVao);
    createMainBufferObjects(boxVao, floorVao, mainShaderProgram);


    GLuint gridVertexShader = createShader(GL_VERTEX_SHADER, gridVertexSource);
    GLuint gridFragmentShader = createShader(GL_FRAGMENT_SHADER, gridFragmentSource);

    GLuint gridShaderProgram = createShaderProgram(gridVertexShader, gridFragmentShader);

    GLuint gridBoxVao;
    glGenVertexArrays(1, &gridBoxVao);

    createGridBufferObject(gridBoxVao, boxVertices, sizeof(boxVertices), gridShaderProgram);

    //Create texture
    loadBoxTexture(mainShaderProgram);

    //Enable depth test
    glEnable(GL_DEPTH_TEST);

    TransformationMatrix transformationMatrix;
    setupTransformationMatrix(&transformationMatrix);

    GLint uniTransf = glGetUniformLocation(mainShaderProgram, "transf");
    GLint uniColor = glGetUniformLocation(mainShaderProgram, "overrideColor");
    GLint uniTransfGrid = glGetUniformLocation(gridShaderProgram, "transf");
    glUseProgram(0);

    float currentTime;
    while (!glfwWindowShouldClose(window)) {
        glfwPollEvents();

        //Clear the screen to white
        glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        currentTime = (float) glfwGetTime();

        amat4_identity(&transformationMatrix.model);
        mat4RotationZ(&transformationMatrix.model, currentTime * 0.2f * degreesToRadians(180.0f));

        calculateTransformationMatrix(&transformationMatrix);

        glUseProgram(mainShaderProgram);

        glUniformMatrix4fv(uniTransf, 1, GL_FALSE, &transformationMatrix.transf.mat[0]);

        //Start with drawing functions

        glBindVertexArray(boxVao);
        glDrawArrays(GL_TRIANGLES, 0, 36);
        glBindVertexArray(0);

        if (drawGrid) {
            glUseProgram(gridShaderProgram);
            glUniformMatrix4fv(uniTransfGrid, 1, GL_FALSE, &transformationMatrix.transf.mat[0]);
            glUniform3f(uniColor, 1.0f, 0.0f, 0.0f);
            glBindVertexArray(gridBoxVao);
            glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
            glDrawArrays(GL_TRIANGLES, 0, 36);
            glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
            glBindVertexArray(0);
            glUseProgram(mainShaderProgram);
        }

        //
        glEnable(GL_STENCIL_TEST);

        // Draw floor
        glStencilFunc(GL_ALWAYS, 1, 0xFF);
        glStencilOp(GL_KEEP, GL_KEEP, GL_REPLACE);
        glStencilMask(0xFF);
        glDepthMask(GL_FALSE);
        glClear(GL_STENCIL_BUFFER_BIT);

        glBindVertexArray(floorVao);
        glDrawArrays(GL_TRIANGLES, 0, 6);
        glBindVertexArray(0);

        //Draw refelction
        glStencilFunc(GL_EQUAL, 1, 0xFF);
        glStencilMask(0x00);
        glDepthMask(GL_TRUE);

        mat4 transl, scaling;
        amat4_translation(&transl, 0.0f, 0.0f, -1.0f);
        amat4_scaling(&scaling, 1.0f, 1.0f, -1.0f);
        mat4Multiply(&transformationMatrix.model, &transformationMatrix.model, &transl);
        mat4Multiply(&transformationMatrix.model, &transformationMatrix.model, &scaling);
        calculateTransformationMatrix(&transformationMatrix);
        glUniformMatrix4fv(uniTransfGrid, 1, GL_FALSE, &transformationMatrix.transf.mat[0]);
        glUniform3f(uniColor, 0.3f, 0.3f, 0.3f);

        glBindVertexArray(boxVao);
        glDrawArrays(GL_TRIANGLES, 0, 36);
        glBindVertexArray(0);

        glUniform3f(uniColor, 1.0f, 1.0f, 1.0f);
        //
        glDisable(GL_STENCIL_TEST);

        glfwSwapBuffers(window);
    }

    glfwTerminate();

    return 0;
}
コード例 #27
0
ファイル: main.cpp プロジェクト: srjek/dcpu16
int emulatorApp::OnRun() {
    initGlew();

    environment->Run();
    return wxApp::OnRun();
}
コード例 #28
0
void Tutorial::Run()
{
#ifdef __TUT_VERSION

#if __TUT_VERSION >= 17
  if (_tutorialID >= 17) {
    char windowName[255];
    sprintf(&windowName[0], "Tutorial %d", _tutorialID);
    if (!GLUTBackendCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, false, windowName)) {
      return;
    }
#if __TUT_VERSION == 17
    _tutorial = new Tutorial17();
#elif __TUT_VERSION == 18
    _tutorial = new Tutorial18();
#elif __TUT_VERSION == 19
    _tutorial = new Tutorial19();
#elif __TUT_VERSION == 20
    _tutorial = new Tutorial20();
#elif __TUT_VERSION == 21
    _tutorial = new Tutorial21();
#elif __TUT_VERSION == 22
    _tutorial = new Tutorial22();
#elif __TUT_VERSION == 23
    _tutorial = new Tutorial23();
#endif

    if (!_tutorial->Init(pVSFileName, pFSFileName)) {
      return;
    }

    char* version = (char*)glGetString(GL_VERSION);
    fprintf(stdout, "Version: '%s'\n", version);
    _tutorial->Run();
    delete _tutorial;
    return;
  }
#endif

#endif



  initGlut();
  initGlew();

  glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

  if (_tutorialID == 16) {
    glFrontFace(GL_CW);
    glCullFace(GL_BACK);
    glEnable(GL_CULL_FACE);
  }

  char* version = (char*)glGetString(GL_VERSION);
  fprintf(stdout, "Version: '%s'\n", version);

  ///
  /// Create vertex buffer: glGenBuffers, glBindBuffer, glBufferData.
  ///
  createVertexBuffer();

  ///
  /// Create the index buffer: glGenBuffers, glBindBuffer, glBufferData.
  ///
  createIndexBuffer();

  ///
  /// Read shaders from file, compile, verify and add to shader program.
  ///
  compileShaders();

  if (_tutorialID == 16) {
    glUniform1i(_gSampler, 0);

    _pTexture = new Texture(GL_TEXTURE_2D, "/home/lparkin/Projects/S3/OpenGlDirsProject/LearnOpenGL-nonQt/Project/Content/test.png");

    if (!_pTexture->Load()) {
      exit(1);
    }
  }

  ///
  /// Setup the perspective projection information.
  ///
  _gPersProjInfo.FOV = 60.0f;
  _gPersProjInfo.Height = WINDOW_HEIGHT_1_14;
  _gPersProjInfo.Width = WINDOW_WIDTH_1_14;
  _gPersProjInfo.zNear = 1.0f;
  _gPersProjInfo.zFar = 100.0f;

  ///
  /// Start the rendering loop.
  ///
  glutMainLoop();
}