Ejemplo n.º 1
1
int main()
{
	_CrtSetDbgFlag(_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);

	// =======================================================
	//                   INITIALIZE
	// =======================================================
	glfwInit();
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
	glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

	GLFWwindow* window = glfwCreateWindow(800, 600, "OpenGl Program", nullptr, nullptr);
	if (window == nullptr)
	{
		printf("Failed to create GLFW window\n");
		glfwTerminate();
		return false;
	}
	glfwMakeContextCurrent(window);

	glewExperimental = GL_TRUE;
	if (glewInit() != GLEW_OK)
	{
		printf("Failed to initialize GLEW\n");
		return false;
	}

	glViewport(0, 0, WIDTH, HEIGHT);
	glEnable(GL_DEPTH_TEST);

	glfwSetKeyCallback(window, Key_callback);
	glfwSetCursorPosCallback(window, mouse_callback);
	glfwSetScrollCallback(window, scroll_callback);


	// Build and compile our shader program
	Shader lightingShader("../Data/Shaders/vertexShaderLighting_nano.vs",
		"../Data/Shaders/fragmentShaderLighting_nano.frag", 2);

	Shader lampShader("../Data/Shaders/vertexShaderLighting_Lamp.vs",
		"../Data/Shaders/fragmentShaderLighting_Lamp.frag", 0);

	// set the application to capture the cursor
	glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

	glm::vec3 pointLightPositions[] =
	{
		glm::vec3(2.0f, 0.0f, 2.0f),
		glm::vec3(-2.0f, 0.0f, -2.0f),
	};



	DirLight dirlight(lightingShader, vect3(-0.2f, -1.0f, -0.3f), vect3(255, 255, 255), 0.5f);
	PointLight pointLight1(lightingShader, pointLightPositions[0], vect3(255, 255, 255), 0.5f);
	PointLight pointLight2(lightingShader, pointLightPositions[1], vect3(255, 255, 255), 0.5f);
	//PointLight pointLight3(lightingShader, pointLightPositions[2], vect3(255, 255, 255), 1.0f);
	//PointLight pointLight4(lightingShader, pointLightPositions[3], vect3(255, 255, 255), 1.0f);
	SpotLight spotLight(lightingShader, MainCamera.Position, MainCamera.Front, vect3(255, 255, 255), 1.0f);

	GLfloat time = glfwGetTime();
	Model nanosuit("../Data/Models/Box/OutPutModel.txt");
	time = glfwGetTime() - time;
	printf("Time to load: %f", time);

	nanosuit.SetPosition(glm::vec3(0.0f, 0.0f, 0.0f));
	
	// =======================================================
	//                  MAIN UPDATE LOOP
	// =======================================================
	//float count = 0;
	//GLfloat time = 0;

	while (!glfwWindowShouldClose(window))
	{

		// Update deltaTime
		GLfloat currentFrame = glfwGetTime();
		deltaTime = currentFrame - lastFrame;
		lastFrame = currentFrame;

		// FPS check
		//if (time >= 1.0f)
		//{
		//	printf("FPS: %f", count);
		//	time = 0;
		//	count = 0;
		//}

		// check and call events
		glfwPollEvents();
		UpdateCamera();

		// Rendering commands here
		//glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
		glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		// draw triangle
		lightingShader.Use();

		GLint viewPosLoc = lightingShader.GetUniformLocation("viewPos");
		glUniform3f(viewPosLoc, MainCamera.Position.x, MainCamera.Position.y, MainCamera.Position.z);

		// Directional light
		dirlight.Update();

		// Point lights		
		pointLight1.Update(0);
		pointLight2.Update(1);

		// SpotLight
		spotLight.SetPosDir(MainCamera.Position, MainCamera.Front);
		spotLight.Update();

		// Camera/View transformation
		glm::mat4 view;
		view = MainCamera.GetViewMatrix();

		// set the projection matrix (perspective)
		glm::mat4 projectionMatrix;

		// FOV, aspect ratio, near plane, far plane
		projectionMatrix = glm::perspective(glm::radians(MainCamera.Zoom), (GLfloat)WIDTH / (GLfloat)HEIGHT, 0.1f, farPlane);

		// specify matrices
		GLint modelLoc = lightingShader.GetUniformLocation("modelMat");

		GLint viewLoc = lightingShader.GetUniformLocation("viewMat");
		glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));

		GLint projLoc = lightingShader.GetUniformLocation("projectionMat");
		glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projectionMatrix));		

		//glm::mat4 model;
		//model = glm::translate(model, glm::vec3(0, -1.75f, 0.0f)); // Translate it down a bit so it's at the center of the scene
		//model += glm::translate(model, glm::vec3(0.2f, 0.0f, 0.0f));
		//model = glm::scale(model, glm::vec3(0.2f, 0.2f, 0.2f));	// It's a bit too big for our scene, so scale it down
		//glUniformMatrix4fv(glGetUniformLocation(lightingShader.Program, "modelMat"), 1, GL_FALSE, glm::value_ptr(model));

		nanosuit.Draw(lightingShader);

		
		// Swap the buffers
		glfwSwapBuffers(window);
	}

	// =======================================================
	//                     CLEANUP
	// =======================================================
	
	glfwTerminate();
	return 0;
}
Ejemplo n.º 2
0
// the program starts here
void AppMain() {
    // initialise GLFW
    glfwSetErrorCallback(OnError);
    if(!glfwInit())
        throw std::runtime_error("glfwInit failed");

    // open a window with GLFW
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);


    gWindow = glfwCreateWindow((int)SCREEN_SIZE.x, (int)SCREEN_SIZE.y, "OpenGL Tutorial", NULL, NULL);
    if(!gWindow)
        throw std::runtime_error("glfwCreateWindow failed. Can your hardware handle OpenGL 3.2?");

    // GLFW settings
    glfwMakeContextCurrent(gWindow);
    glfwSetInputMode(gWindow, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
    glfwSetCursorPos(gWindow, 0, 0);
    glfwSetScrollCallback(gWindow, OnScroll);
    glfwMakeContextCurrent(gWindow);

    // initialise GLEW
    glewExperimental = GL_TRUE; //stops glew crashing on OSX :-/
    if(glewInit() != GLEW_OK)
        throw std::runtime_error("glewInit failed");

    // GLEW throws some errors, so discard all the errors so far
    while(glGetError() != GL_NO_ERROR) {}

    // print out some info about the graphics drivers
    std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl;
    std::cout << "GLSL version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl;
    std::cout << "Vendor: " << glGetString(GL_VENDOR) << std::endl;
    std::cout << "Renderer: " << glGetString(GL_RENDERER) << std::endl;

    // make sure OpenGL version 3.2 API is available
    if(!GLEW_VERSION_3_2)
        throw std::runtime_error("OpenGL 3.2 API is not available.");

    // OpenGL settings
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    // Init camera
    gCamera.setPosition(glm::vec3(0,0,4));
    gCamera.setViewportAspectRatio(SCREEN_SIZE.x / SCREEN_SIZE.y);

    // load vertex and fragment shaders into opengl
    LoadShaders();

    // load the texture
    LoadTexture();

    // create buffer and fill it with the points of the triangle
    LoadCube();

    // run while the window is open
    double lastTime = glfwGetTime();
    while(!glfwWindowShouldClose(gWindow)){
        // process pending events
        glfwPollEvents();

        // update the scene based on the time elapsed since last update
        double thisTime = glfwGetTime();
        Update((float)(thisTime - lastTime));
        lastTime = thisTime;

        // draw one frame
        Render();

        // check for errors
        GLenum error = glGetError();
        if(error != GL_NO_ERROR)
            std::cerr << "OpenGL Error " << error << std::endl;

        if(glfwGetKey(gWindow, GLFW_KEY_ESCAPE))
            glfwSetWindowShouldClose(gWindow, GL_TRUE);
    }

    // clean up and exit
    glfwTerminate();
}
Ejemplo n.º 3
0
/* Terminate GLFW on destruvtion of the wrapepr object */
GLWrapper::~GLWrapper() {
	glfwTerminate();
}
int main(int argc, char** argv)
{
    int ch, width, height;
    thrd_t physics_thread = 0;
    GLFWwindow* window;
    GLFWmonitor* monitor = NULL;

    if (!glfwInit())
    {
        fprintf(stderr, "Failed to initialize GLFW\n");
        exit(EXIT_FAILURE);
    }

    while ((ch = getopt(argc, argv, "fh")) != -1)
    {
        switch (ch)
        {
            case 'f':
                monitor = glfwGetPrimaryMonitor();
                break;
            case 'h':
                usage();
                exit(EXIT_SUCCESS);
        }
    }

    if (monitor)
    {
        const GLFWvidmode* mode = glfwGetVideoMode(monitor);

        glfwWindowHint(GLFW_RED_BITS, mode->redBits);
        glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits);
        glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits);
        glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate);

        width  = mode->width;
        height = mode->height;
    }
    else
    {
        width  = 640;
        height = 480;
    }

    window = glfwCreateWindow(width, height, "Particle Engine", monitor, NULL);
    if (!window)
    {
        fprintf(stderr, "Failed to create GLFW window\n");
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    if (monitor)
        glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

    glfwMakeContextCurrent(window);
    gladLoadGLLoader((GLADloadproc) glfwGetProcAddress);
    glfwSwapInterval(1);

    glfwSetFramebufferSizeCallback(window, resize_callback);
    glfwSetKeyCallback(window, key_callback);

    // Set initial aspect ratio
    glfwGetFramebufferSize(window, &width, &height);
    resize_callback(window, width, height);

    // Upload particle texture
    glGenTextures(1, &particle_tex_id);
    glBindTexture(GL_TEXTURE_2D, particle_tex_id);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, P_TEX_WIDTH, P_TEX_HEIGHT,
                 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, particle_texture);

    // Upload floor texture
    glGenTextures(1, &floor_tex_id);
    glBindTexture(GL_TEXTURE_2D, floor_tex_id);
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
    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_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_LUMINANCE, F_TEX_WIDTH, F_TEX_HEIGHT,
                 0, GL_LUMINANCE, GL_UNSIGNED_BYTE, floor_texture);

    if (glfwExtensionSupported("GL_EXT_separate_specular_color"))
    {
        glLightModeli(GL_LIGHT_MODEL_COLOR_CONTROL_EXT,
                      GL_SEPARATE_SPECULAR_COLOR_EXT);
    }

    // Set filled polygon mode as default (not wireframe)
    glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
    wireframe = 0;

    // Set initial times
    thread_sync.t  = 0.0;
    thread_sync.dt = 0.001f;
    thread_sync.p_frame = 0;
    thread_sync.d_frame = 0;

    mtx_init(&thread_sync.particles_lock, mtx_timed);
    cnd_init(&thread_sync.p_done);
    cnd_init(&thread_sync.d_done);

    if (thrd_create(&physics_thread, physics_thread_main, window) != thrd_success)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwSetTime(0.0);

    while (!glfwWindowShouldClose(window))
    {
        draw_scene(window, glfwGetTime());

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    thrd_join(physics_thread, NULL);

    glfwDestroyWindow(window);
    glfwTerminate();

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 5
0
void GUI::Halt()
{
	// Cleanup
	ImGui_ImplGlfw_Shutdown();
	glfwTerminate();
}
Ejemplo n.º 6
0
int main(int argc, char** argv)
{
    Slot* slots;
    GLFWmonitor* monitor = NULL;
    int ch, i, width, height, count = 1;

    setlocale(LC_ALL, "");

    glfwSetErrorCallback(error_callback);

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

    printf("Library initialized\n");

    glfwSetMonitorCallback(monitor_callback);

    while ((ch = getopt(argc, argv, "hfn:")) != -1)
    {
        switch (ch)
        {
            case 'h':
                usage();
                exit(EXIT_SUCCESS);

            case 'f':
                monitor = glfwGetPrimaryMonitor();
                break;

            case 'n':
                count = (int) strtol(optarg, NULL, 10);
                break;

            default:
                usage();
                exit(EXIT_FAILURE);
        }
    }

    if (monitor)
    {
        const GLFWvidmode* mode = glfwGetVideoMode(monitor);

        glfwWindowHint(GLFW_REFRESH_RATE, mode->refreshRate);
        glfwWindowHint(GLFW_RED_BITS, mode->redBits);
        glfwWindowHint(GLFW_GREEN_BITS, mode->greenBits);
        glfwWindowHint(GLFW_BLUE_BITS, mode->blueBits);

        width = mode->width;
        height = mode->height;
    }
    else
    {
        width  = 640;
        height = 480;
    }

    if (!count)
    {
        fprintf(stderr, "Invalid user\n");
        exit(EXIT_FAILURE);
    }

    slots = calloc(count, sizeof(Slot));

    for (i = 0;  i < count;  i++)
    {
        char title[128];

        slots[i].closeable = GLFW_TRUE;
        slots[i].number = i + 1;

        sprintf(title, "Event Linter (Window %i)", slots[i].number);

        if (monitor)
        {
            printf("Creating full screen window %i (%ix%i on %s)\n",
                   slots[i].number,
                   width, height,
                   glfwGetMonitorName(monitor));
        }
        else
        {
            printf("Creating windowed mode window %i (%ix%i)\n",
                   slots[i].number,
                   width, height);
        }

        slots[i].window = glfwCreateWindow(width, height, title, monitor, NULL);
        if (!slots[i].window)
        {
            free(slots);
            glfwTerminate();
            exit(EXIT_FAILURE);
        }

        glfwSetWindowUserPointer(slots[i].window, slots + i);

        glfwSetWindowPosCallback(slots[i].window, window_pos_callback);
        glfwSetWindowSizeCallback(slots[i].window, window_size_callback);
        glfwSetFramebufferSizeCallback(slots[i].window, framebuffer_size_callback);
        glfwSetWindowCloseCallback(slots[i].window, window_close_callback);
        glfwSetWindowRefreshCallback(slots[i].window, window_refresh_callback);
        glfwSetWindowFocusCallback(slots[i].window, window_focus_callback);
        glfwSetWindowIconifyCallback(slots[i].window, window_iconify_callback);
        glfwSetMouseButtonCallback(slots[i].window, mouse_button_callback);
        glfwSetCursorPosCallback(slots[i].window, cursor_position_callback);
        glfwSetCursorEnterCallback(slots[i].window, cursor_enter_callback);
        glfwSetScrollCallback(slots[i].window, scroll_callback);
        glfwSetKeyCallback(slots[i].window, key_callback);
        glfwSetCharCallback(slots[i].window, char_callback);
        glfwSetCharModsCallback(slots[i].window, char_mods_callback);
        glfwSetDropCallback(slots[i].window, drop_callback);

        glfwMakeContextCurrent(slots[i].window);
        gladLoadGLLoader((GLADloadproc) glfwGetProcAddress);
        glfwSwapInterval(1);
    }

    printf("Main loop starting\n");

    for (;;)
    {
        for (i = 0;  i < count;  i++)
        {
            if (glfwWindowShouldClose(slots[i].window))
                break;
        }

        if (i < count)
            break;

        glfwWaitEvents();

        // Workaround for an issue with msvcrt and mintty
        fflush(stdout);
    }

    free(slots);
    glfwTerminate();
    exit(EXIT_SUCCESS);
}
Ejemplo n.º 7
0
void main(int argc, char ** argv)
{
	int argc_ = 1;
	char *argv_[1] = {(char *)"something"};
	//glutInit(&argc_, argv_);          // initialize the toolkit
	//GLuint glutwindow = glutCreateWindow("something"); // open the screen window
	if(!glfwInit()) {
		printf("glfwinit fail");
		return ;
	}
	CheckGlErrors("glfwInit");
	GLFWwindow *glfwwindow = glfwCreateWindow(screenWidth, screenHeight, "example", NULL, NULL);
	CheckGlErrors("glfwCreateWindow");
	if(glfwwindow == NULL) {
		printf("glfwCreateWindow fail");
		glfwTerminate();
		return ;
	}
	glfwHideWindow(glfwwindow);
	CheckGlErrors("glfwHideWindow");
	glfwMakeContextCurrent(glfwwindow);
	CheckGlErrors("glfwMakeContextCurrent");
	
#ifndef FBO
	glutDisplayFunc(renderFBO);     // register the redraw function
#endif
	GLenum err = glewInit();
	if(GLEW_OK != err) {
		printf("glewInit Error: %s\n", glewGetErrorString(err));
		getchar();
		return ;
	}
	myInit(); 
	glslProcess();
#ifdef FBO
	for(int i=1;i<3;++i) {
		char filename[30];
		sprintf(filename, "%d.png", i+1);
		img = cv::imread(filename);
		if(img.empty())
			return ;
		//cv::cvtColor(img, img, CV_BGR2RGB);
		renderFBO();
		readBack();
		//cv::cvtColor(img1, img1, CV_BGR2RGB);
		printf("output img, width is %d, height is %d, %d\n", img1.cols, img1.rows, img1.channels());
		
		sprintf(filename, "D:\\%d.bmp", 20+i);
		cv::imwrite(filename, img1);
	}
	//getchar();
#else
	glutMainLoop(); 		     // go into a perpetual loop
#endif
	glDeleteFramebuffers(1, &fb);
	glDeleteTextures(2, texId);
	//glutDestroyWindow(glutwindow);
	glfwTerminate();

	getchar();
}
Ejemplo n.º 8
0
int main(int argc, _TCHAR* argv[])
{


    int     width, height, running, frames;
    double  t, t0, fps;
    char    titlestr[ 200 ];
	int p=0;
	
	printf("BLUntrl written 2009, 2010 by Sven Killig <*****@*****.**>\n");
	printf("BLUntrl.exe [ VfWDeviceNo | MonitorNo (-1=all) Brightness (0-100%) ]\n");
//printf("argc=%i\n", argc);
	if(argc==3) {
		TAPP.setBrightness(atoi((char*)argv[1]),atoi((char*)argv[2]));
		return 0;
	} else if(argc==2) {
		// all doesn't work?!
		//printf("argv[1]='%s'\n", argv[1]);
		//p=StrToInt(argv[1]);
		/*if(StrToIntEx(argv[1], STIF_DEFAULT, &p)) printf("StrToIntEx=true\n");
		else printf("StrToIntEx=false\n");*/
		p=atoi((char*)argv[1]);
		//printf("p=%i\n", p);
	}

    // Initialise GLFW
    glfwInit();

    // Open OpenGL window    
    if (!glfwOpenWindow(160,120,    // Open window
    24, 24, 24,                                // Red, green, and blue bits for color buffer
    24,                                        // Bits for alpha buffer
    24,                                        // Bits for depth buffer (Z-buffer)
    24,                                        // Bits for stencil buffer
    GLFW_WINDOW)){
        glfwTerminate();
        return 0;
    }
    
    glfwSetKeyCallback( keyfun );
    glfwSetMouseWheelCallback( mousewheelfun );
    glfwSetWindowSizeCallback( windowsizefun );
    TAPP.init(p);
    glfwEnable( GLFW_STICKY_KEYS );
glfwDisable( GLFW_AUTO_POLL_EVENTS );
    // Disable vertical sync (on cards that support it)
    glfwSwapInterval( 1 );

    // Main loop
    running = GL_TRUE;
    frames = 0;
    t0 = glfwGetTime();
	int i=0;
    while( running ){
i++;
        // Get time and mouse position
        t = glfwGetTime();
        //glfwGetMousePos( &x, &y );
        
		if(TAPP.idle() && !glfwGetWindowParam(GLFW_ICONIFIED)) {
			frames ++;
			 
			
			// Get window size (may be different than the requested size)
			glfwGetWindowSize( &width, &height );
			height = height > 0 ? height : 1;
			// Set viewport
			glViewport( 0, 0, width, height );
			// Clear color buffer
			glClearColor( 0.0f, 0.0f, 0.0f, 0.0f );
			glClear( GL_COLOR_BUFFER_BIT );

			TAPP.draw();			
			// Swap buffers
			glfwSwapBuffers();

        // Calculate and display FPS (frames per second)
        //if( (t-t0) > 1.0 || frames == 0 )
        {
            fps = (double)frames / (t-t0);
            sprintf( titlestr, "BLUntrl (%.1f FPS); %i", fps, i );
            glfwSetWindowTitle( titlestr );
            t0 = t;
            frames = 0;
        }

		} else Sleep(1000/30);
glfwPollEvents();
		
        // Check if the ESC key was pressed or the window was closed
        running = !glfwGetKey( GLFW_KEY_ESC ) /*&&
                  glfwGetWindowParam( GLFW_OPENED )*/;
    }

    // Close OpenGL window and terminate GLFW
    glfwTerminate();
    return 0;
}
Ejemplo n.º 9
0
int main(int argc, char **argv) {
    
    int i;
    int filecount = 0;
    char* filename = NULL;
    
    {
        int c, option_index = 0;
        static struct option long_options[] = {
            {"help", 0, 0, 0},
            {"output", 2, 0, 0},
            {"size", 1, 0, 0},
            {NULL, 0, NULL, 0}
        };
        char* endptr = NULL;
        bool opt_fail = false;
        bool help = false;
        while ((c = getopt_long(argc, argv, "ho::s:",
                long_options, &option_index)) != -1) {
            switch (c) {
                case 0:
                    switch(option_index) {
                    case 0: // help
                        goto help;
                    case 1: // output
                        goto output;
                    case 2: // size
                        goto size;
                    default:
                        goto unknown;
                    }
                    break;
                help:
                case 'h':   // help
                    help = true;
                    break;
                output:
                case 'o':   // output
                    filecount = 1;
                    // avoid leakiness if the user provided multiple --output
                    // free(NULL) is a no-op, so this should be safe:
                    free(filename);
                    filename = NULL;
                    if(optarg != NULL) {
                        int tmp = strtol(optarg, &endptr, 10);
                        if (endptr == optarg || (endptr != NULL && *endptr != '\0')) {
                            int len = strlen(optarg);
                            filename = malloc(len + 1);
                            strcpy(filename, optarg);
                            filename[len] = '\0';
                        } else {
                            filecount = tmp;
                        }
                    }
                    break;
                size:
                case 's':
                    i = 0;
                    while(optarg[i] != '*' && optarg[i] != '\0') i++;
                    if(optarg[i] == '\0') {
                        goto size_fail;
                    }
                    optarg[i] = '\0';
                    width = strtol(optarg, &endptr, 10);
                    if (endptr == optarg || (endptr != NULL && *endptr != '\0')) {
                        goto size_fail;
                    }
                    height = strtol(optarg + i + 1, &endptr, 10);
                    if (endptr == optarg || (endptr != NULL && *endptr != '\0')) {
                        goto size_fail;
                    }
                    printf("width: %d, height: %d\n", width, height);
                    break;
                size_fail:
                    fprintf(stderr, "Invalid size string '%s'\n", optarg);
                    print_help(1);
                    break;
                unknown:
                case '?':
                    opt_fail = true;
                    break;
                default:
                    fprintf(stderr, "?? getopt returned character code 0%o ??\n", c);
            }
        }
        if(opt_fail) {
            print_help(1);
        }
        if(optind < argc) {
            fprintf(stderr, "%s: unrecognized option '%s'\n", argv[0], argv[optind]);
            print_help(1);
        }
        if(help) {
            print_help(0);
        }
    }
    
    scale = max(width, height);
    srand(get_time_us());

    GLFWwindow* window;

    glfwSetErrorCallback(error_callback);

    // Initialize the library
    if (!glfwInit())
        return -1;

    glfwWindowHint(GLFW_SAMPLES, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);


    // Create a windowed mode window and its OpenGL context
    if(filecount) {
        glfwWindowHint(GLFW_VISIBLE, false);
        window = glfwCreateWindow(1, 1, "SpaceScape", NULL, NULL);
    } else {
        window = glfwCreateWindow(width, height, "SpaceScape", NULL, NULL);
    }
    if (!window) {
        glfwTerminate();
        return -1;
    }

    // Make the window's context current
    glfwMakeContextCurrent(window);

    glfwSetKeyCallback(window, key_callback);

    // Init GLEW
    glewExperimental = true;
    GLenum err = glewInit();
    if (GLEW_OK != err) {
        fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
    }
    fprintf(stderr, "Using GLEW %s\n", glewGetString(GLEW_VERSION));
    if (!GLEW_ARB_vertex_buffer_object) {
        fputs("VBO not supported\n", stderr);
        exit(1);
    }

    render_init();

    if(filename) {
        render_to_png(filename);
    } else if(filecount) {
        for(i = 0; i < filecount; i++) {
            render_to_png(NULL);
        }
    } else {
        // Render to our framebuffer
        render_to_screen();

        while (!glfwWindowShouldClose(window)) {

            // Clear the screen
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

            // 1rst attribute buffer : vertices
            glEnableVertexAttribArray(0);
            glBindBuffer(GL_ARRAY_BUFFER, quad_vertexbuffer);
            glVertexAttribPointer(
                    0, // attribute 0. No particular reason for 0, but must match the layout in the shader.
                    3, // size
                    GL_FLOAT, // type
                    GL_FALSE, // normalized?
                    0, // stride
                    (void*) 0 // array buffer offset
                    );

            // Draw the triangles !
            glDrawArrays(GL_TRIANGLES, 0, 6); // 2*3 indices starting at 0 -> 2 triangles

            glDisableVertexAttribArray(0);

            // Swap buffers
            glfwSwapBuffers(window);
            glfwPollEvents();
        }
    }

    render_cleanup();

    // Close OpenGL window and terminate GLFW
    glfwTerminate();

    return 0;
}
Ejemplo n.º 10
0
// APPLICATION ENTRY
// -----------------
int main() {
  int width = 1024;
  int height = 768;
  width = 640;
  height = 480;
  sim_ptr = NULL;

  int c = 0;
  GLFWmonitor** m = glfwGetMonitors(&c);

  // init
  glfwSetErrorCallback(error_callback);
  if(!glfwInit()) {
    printf("ERROR: cannot initialize GLFW.\n");
    exit(EXIT_FAILURE);
  }

  // glfwWindowHint(GLFW_DEPTH_BITS, 16);
  // glfwWindowHint(GLFW_FSAA_SAMPLES, 4);

  GLFWwindow* window = glfwCreateWindow(width, height, "Simulation", NULL, NULL);
  if(!window) {
    printf("ERROR: cannot open window.\n");
    exit(EXIT_FAILURE);
  }
  
  glfwSetWindowSizeCallback(window, window_size_callback);
  glfwSetWindowCloseCallback(window, window_close_callback);
  glfwSetMouseButtonCallback(window, mouse_button_callback);
  glfwSetCursorPosCallback(window, cursor_callback);
  glfwSetScrollCallback(window, scroll_callback);
  glfwSetKeyCallback(window, key_callback);
  glfwSetCharCallback(window, char_callback);

  glfwMakeContextCurrent(window);

#if defined(ROXLU_GL_CORE3)
  if(glxwInit() != 0) {
    printf("ERROR: cannot init glxw\n");
    return EXIT_FAILURE;
  }
#else
  glewExperimental = true;
  GLenum err = glewInit();
  if (GLEW_OK != err) {
    fprintf(stderr, "GLEW Error: %s\n", glewGetErrorString(err));
    exit(EXIT_FAILURE);
  }
#endif

  Simulation sim;
  sim_ptr = &sim;
  sim.window = window;
  sim.window_w = width;
  sim.window_h = height;
  sim.setup();
  
  bool running = true;
  while(running) {
    glfwPollEvents();

    sim.update();
    sim.draw();

    glfwSwapBuffers(window);
    running = !(glfwGetKey(window, GLFW_KEY_ESC));
  }
  glfwTerminate();
  return EXIT_SUCCESS;
};
Ejemplo n.º 11
0
	int main()
	{
		glfwInit();
		glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
		glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
		glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
		glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

		GLFWwindow* window = glfwCreateWindow(800, 600, "Learning some OpenGL", nullptr, nullptr);
		glfwMakeContextCurrent(window);

		glfwSetKeyCallback(window, key_callback);

		//Check to make sure the window is not null. If it is, terminate.
		if (window == nullptr)
		{
			std::cout << "Failed to create GLFW window" << std::endl;
			glfwTerminate();
			return -1;
		}

		//Initialise GLEW
		//glewExperimental allows us to use modern techniques. Not setting it to true might lead to complications
		glewExperimental = GL_TRUE;
		if (glewInit() != GLEW_OK)
		{
			std::cout << "Failed to initialise GLEW" << std::endl;
			return -1;
		}

		//Tell OpenGL the size of the window, or in this case the viewport, that we wish to render to
		glViewport(0, 0, 800, 600);

		Shader shader("shaders/texture_shader.vs", "shaders/texture_shader.frag");
		//Tutorial Three
		texture_triangle();

		//Simple loop
		while (!glfwWindowShouldClose(window))
		{
			glfwPollEvents();

			//Set clear colour to ensure that we're actually rendering something
			glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
			glClear(GL_COLOR_BUFFER_BIT);

			//Bind the texture
			glBindTexture(GL_TEXTURE_2D, texture);
			glBindTexture(GL_TEXTURE_2D, texture_two);

			glActiveTexture(GL_TEXTURE0);
			glBindTexture(GL_TEXTURE_2D, texture);
			glUniform1i(glGetUniformLocation(shader.Program, "texture_one"), 0);
			glActiveTexture(GL_TEXTURE1);
			glBindTexture(GL_TEXTURE_2D, texture_two);
			glUniform1i(glGetUniformLocation(shader.Program, "texture_two"), 1);
			//Get location
			GLuint location = glGetUniformLocation(shader.Program, "mix_variable");
			glUniform1f(location, mix_variable);

			//Drawning
			shader.use();
			glBindVertexArray(VAO);
			glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
			glBindVertexArray(0);

			glfwSwapBuffers(window);
		}

		//Cleanup
		glDeleteVertexArrays(1, &VAO);
		glDeleteBuffers(1, &VBO);

		glfwTerminate();
		return 0;
	}
Ejemplo n.º 12
0
//後始末
void GLFW_deinitialize(GLFWwindow *window){
	glfwDestroyWindow(window);
	glfwTerminate();
	return;
}
Ejemplo n.º 13
0
int main(void)
{
    GLFWwindow* window;

    window = init("Billboards", 640, 480);
    if(!window)
    {
        return -1;
    }

    glEnable(GL_DEPTH_TEST);

    Camera camera(CAMERA_PERSPECTIVE, 45.0f, 0.1f, 1000.0f, 640.0f, 480.0f);
    camera.setPosition(0.0f, 0.0f, -3.0f);
    setCamera(&camera); // The camera updating is handled in ../common/util.cpp

    glm::mat4 model;

    GLuint program;
    {
        GLuint vertex = createShader(VERTEX_SRC, GL_VERTEX_SHADER);
        GLuint fragment = createShader(FRAGMENT_SRC, GL_FRAGMENT_SHADER);
        program = createShaderProgram(vertex, fragment);
        linkShader(program);
        validateShader(program);
        glDetachShader(program, vertex);
        glDeleteShader(vertex);
        glDetachShader(program, fragment);
        glDeleteShader(fragment);
    }
    GLuint billboardProgram;
    {
        GLuint vertex = createShader(VERTEX_BB_SRC, GL_VERTEX_SHADER);
        GLuint fragment = createShader(FRAGMENT_BB_SRC, GL_FRAGMENT_SHADER);
        billboardProgram = createShaderProgram(vertex, fragment);
        linkShader(billboardProgram);
        validateShader(billboardProgram);
        glDetachShader(program, vertex);
        glDeleteShader(vertex);
        glDetachShader(program, fragment);
        glDeleteShader(fragment);
    }

    glUseProgram(program);

    GLuint vao;
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);

    GLuint vbo;
    glGenBuffers(1, &vbo);

    float vertices[] =
    {
        // x   y      z     r     g     b     u     v
        -0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
         0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
         0.5f,  0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
         0.5f,  0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
        -0.5f,  0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
        -0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
    
        -0.5f, -0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
         0.5f, -0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
         0.5f,  0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
         0.5f,  0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
        -0.5f,  0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
        -0.5f, -0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
    
        -0.5f,  0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
        -0.5f,  0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
        -0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
        -0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
        -0.5f, -0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
        -0.5f,  0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
    
         0.5f,  0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
         0.5f,  0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
         0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
         0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
         0.5f, -0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
         0.5f,  0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
    
        -0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
         0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
         0.5f, -0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
         0.5f, -0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
        -0.5f, -0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
        -0.5f, -0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
    
        -0.5f,  0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f,
         0.5f,  0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f,
         0.5f,  0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
         0.5f,  0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f,
        -0.5f,  0.5f,  0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f,
        -0.5f,  0.5f, -0.5f, 1.0f, 1.0f, 1.0f, 0.0f, 1.0f
    };

    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    glEnableVertexAttribArray(0); // position
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), 0);
    glEnableVertexAttribArray(1); // color
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (void*)(3 * sizeof(GLfloat)));
    glEnableVertexAttribArray(2); // texture coordinates
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (void*)(6 * sizeof(GLfloat)));

    float verts_bb[] =
    {
        -0.5f, -0.5f,
        0.5f,  -0.5f,
        -0.5f, 0.5f,
        0.5f, 0.5f
    };
    GLuint vbo_bb;
    glGenBuffers(1, &vbo_bb);
    GLuint vao_bb;
    glGenVertexArrays(1, &vao_bb);
    glBindVertexArray(vao_bb);
    glBindBuffer(GL_ARRAY_BUFFER, vbo_bb);
    glBufferData(GL_ARRAY_BUFFER, sizeof(verts_bb), verts_bb, GL_STATIC_DRAW);
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);

    glUseProgram(billboardProgram);
    glUniform3f(glGetUniformLocation(billboardProgram, "center"), 0.0f, 2.0f, 0.0f);
    glUniform2f(glGetUniformLocation(billboardProgram, "size"), 0.5f, 0.5f);

    int w, h;
    GLuint texture = loadImage("image.png", &w, &h, 0, false);
    glUniform1i(glGetUniformLocation(billboardProgram, "tex"), 0);
    glUseProgram(program);
    glUniform1i(glGetUniformLocation(program, "tex"), 0);
    
    glClearColor(0.75f, 0.75f, 0.75f, 1.0f);

    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

    while(!glfwWindowShouldClose(window))
    {
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        updateCamera(640, 480, window);

        // Draw the cube
        glUseProgram(program);
        glBindVertexArray(vao);

        GLint modelUL = glGetUniformLocation(program, "model");
        glUniformMatrix4fv(modelUL, 1, GL_FALSE, glm::value_ptr(model));
        GLint viewUL = glGetUniformLocation(program, "view");
        glUniformMatrix4fv(viewUL, 1, GL_FALSE, glm::value_ptr(camera.getView()));
        GLint projUL = glGetUniformLocation(program, "projection");
        glUniformMatrix4fv(projUL, 1, GL_FALSE, glm::value_ptr(camera.getProjection()));

        glDrawArrays(GL_TRIANGLES, 0, 36);

        // Draw the billboard
        glBindVertexArray(vao_bb);
        glUseProgram(billboardProgram);

        viewUL = glGetUniformLocation(billboardProgram, "view");
        glUniformMatrix4fv(viewUL, 1, GL_FALSE, glm::value_ptr(camera.getView()));
        projUL = glGetUniformLocation(billboardProgram, "proj");
        glUniformMatrix4fv(projUL, 1, GL_FALSE, glm::value_ptr(camera.getProjection()));
        glUniform1i(glGetUniformLocation(billboardProgram, "fixedSize"), 0);
        glUniform3f(glGetUniformLocation(billboardProgram, "camRight"), camera.getRightVector().x, camera.getRightVector().y, camera.getRightVector().z);
        glUniform3f(glGetUniformLocation(billboardProgram, "camUp"), camera.getUpVector().x, camera.getUpVector().y, camera.getUpVector().z);

        glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    // Clean up
    glDeleteBuffers(1, &vbo);
    glDeleteVertexArrays(1, &vao);
    glDeleteBuffers(1, &vbo_bb);
    glDeleteVertexArrays(1, &vao_bb);
    glDeleteProgram(program);
    glDeleteProgram(billboardProgram);
    glDeleteTextures(1, &texture);

    glfwTerminate();
    return 0;
}
Ejemplo n.º 14
0
// The MAIN function, from here we start our application and run our Game loop
int main()
{
    // Init GLFW
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    GLFWwindow* window = glfwCreateWindow(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", nullptr, nullptr); // Windowed
    glfwMakeContextCurrent(window);

    // Set the required callback functions
    glfwSetKeyCallback(window, key_callback);
    glfwSetCursorPosCallback(window, mouse_callback);
    glfwSetScrollCallback(window, scroll_callback);

    // Options
    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

    // Initialize GLEW to setup the OpenGL Function pointers
    glewExperimental = GL_TRUE;
    glewInit();

    // Define the viewport dimensions
    glViewport(0, 0, SCR_WIDTH, SCR_HEIGHT);

    // Setup some OpenGL options
    glEnable(GL_DEPTH_TEST);

    // Setup and compile our shaders
    Shader shader("parallax_mapping.vs", "parallax_mapping.frag");

    // Load textures
    GLuint diffuseMap = loadTexture("../../../resources/textures/bricks2.jpg");
	GLuint normalMap = loadTexture("../../../resources/textures/bricks2_normal.jpg");
	GLuint heightMap = loadTexture("../../../resources/textures/bricks2_disp.jpg");
    //GLuint diffuseMap = loadTexture("../../../resources/textures/wood.png");
    //GLuint normalMap = loadTexture("../../../resources/textures/toy_box_normal.png");
    //GLuint heightMap = loadTexture("../../../resources/textures/toy_box_disp.png");

    // Set texture units 
    shader.Use();
    glUniform1i(glGetUniformLocation(shader.Program, "diffuseMap"), 0);
	glUniform1i(glGetUniformLocation(shader.Program, "normalMap"), 1);
	glUniform1i(glGetUniformLocation(shader.Program, "depthMap"), 2);

    // Light position
    glm::vec3 lightPos(0.5f, 1.0f, 0.3f);

    // Game loop
    while (!glfwWindowShouldClose(window))
    {
        // Set frame time
        GLfloat currentFrame = glfwGetTime();
        deltaTime = currentFrame - lastFrame;
        lastFrame = currentFrame;

        // Check and call events
        glfwPollEvents();
        Do_Movement();

        // Clear the colorbuffer
        glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        // Configure view/projection matrices
        shader.Use();
        glm::mat4 view = camera.GetViewMatrix();
        glm::mat4 projection = glm::perspective(camera.Zoom, (GLfloat)SCR_WIDTH / (GLfloat)SCR_HEIGHT, 0.1f, 100.0f);
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "view"), 1, GL_FALSE, glm::value_ptr(view));
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "projection"), 1, GL_FALSE, glm::value_ptr(projection));
        // Render normal-mapped quad
        glm::mat4 model;
        model = glm::rotate(model, (GLfloat)glfwGetTime() * -10, glm::normalize(glm::vec3(1.0, 0.0, 1.0))); // Rotates the quad to show parallax mapping works in all directions
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model));
        glUniform3fv(glGetUniformLocation(shader.Program, "lightPos"), 1, &lightPos[0]);
		glUniform3fv(glGetUniformLocation(shader.Program, "viewPos"), 1, &camera.Position[0]);
		glUniform1f(glGetUniformLocation(shader.Program, "height_scale"), height_scale);
		glUniform1i(glGetUniformLocation(shader.Program, "parallax"), parallax_mapping);
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, diffuseMap);
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, normalMap);
		glActiveTexture(GL_TEXTURE2);
		glBindTexture(GL_TEXTURE_2D, heightMap);
        RenderQuad();

        // render light source (simply renders a smaller plane at the light's position for debugging/visualization)
        model = glm::mat4();
        model = glm::translate(model, lightPos);
        model = glm::scale(model, glm::vec3(0.1f));
        glUniformMatrix4fv(glGetUniformLocation(shader.Program, "model"), 1, GL_FALSE, glm::value_ptr(model));
        //RenderQuad();

        // Swap the buffers
        glfwSwapBuffers(window);
    }

    glfwTerminate();
    return 0;
}
Ejemplo n.º 15
0
int main() {
    int width = 640;
    int height = 480;
    
    if(glfwInit() == GL_FALSE) {
        std::cerr << "failed to init GLFW" << std::endl;
        return 1;
    }

    // select opengl version
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
 
    // create a window
    GLFWwindow *window;
    if((window = glfwCreateWindow(width, height, "03texture", 0, 0)) == 0) {
        std::cerr << "failed to open window" << std::endl;
        glfwTerminate();
        return 1;
    }
    
    glfwMakeContextCurrent(window);

    if(glxwInit()) {
        std::cerr << "failed to init GL3W" << std::endl;
        glfwDestroyWindow(window);
        glfwTerminate();
        return 1;
    }
    
    // shader source code
    std::string vertex_source =
        "#version 330\n"
        "layout(location = 0) in vec4 vposition;\n"
        "layout(location = 1) in vec2 vtexcoord;\n"
        "out vec2 ftexcoord;\n"
        "void main() {\n"
        "   ftexcoord = vtexcoord;\n"
        "   gl_Position = vposition;\n"
        "}\n";
        
    std::string fragment_source =
        "#version 330\n"
        "uniform sampler2D tex;\n" // texture uniform
        "in vec2 ftexcoord;\n"
        "layout(location = 0) out vec4 FragColor;\n"
        "void main() {\n"
        "   FragColor = texture(tex, ftexcoord);\n"
        "}\n";
   
    // program and shader handles
    GLuint shader_program, vertex_shader, fragment_shader;
    
    // we need these to properly pass the strings
    const char *source;
    int length;

    // create and compiler vertex shader
    vertex_shader = glCreateShader(GL_VERTEX_SHADER);
    source = vertex_source.c_str();
    length = vertex_source.size();
    glShaderSource(vertex_shader, 1, &source, &length); 
    glCompileShader(vertex_shader);
    if(!check_shader_compile_status(vertex_shader)) {
        glfwDestroyWindow(window);
        glfwTerminate();
        return 1;
    }
 
    // create and compiler fragment shader
    fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
    source = fragment_source.c_str();
    length = fragment_source.size();
    glShaderSource(fragment_shader, 1, &source, &length);   
    glCompileShader(fragment_shader);
    if(!check_shader_compile_status(fragment_shader)) {
        glfwDestroyWindow(window);
        glfwTerminate();
        return 1;
    }
        
    // create program
    shader_program = glCreateProgram();
    
    // attach shaders
    glAttachShader(shader_program, vertex_shader);
    glAttachShader(shader_program, fragment_shader);
    
    // link the program and check for errors
    glLinkProgram(shader_program);
    check_program_link_status(shader_program);
    
    // get texture uniform location
    GLint texture_location = glGetUniformLocation(shader_program, "tex");
    
    // vao and vbo handle
    GLuint vao, vbo, ibo;
 
    // generate and bind the vao
    glGenVertexArrays(1, &vao);
    glBindVertexArray(vao);
    
    // generate and bind the vertex buffer object
    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
            
    // data for a fullscreen quad (this time with texture coords)
    GLfloat vertexData[] = {
    //  X     Y     Z           U     V     
       1.0f, 1.0f, 0.0f,       1.0f, 1.0f, // vertex 0
      -1.0f, 1.0f, 0.0f,       0.0f, 1.0f, // vertex 1
       1.0f,-1.0f, 0.0f,       1.0f, 0.0f, // vertex 2
      -1.0f,-1.0f, 0.0f,       0.0f, 0.0f, // vertex 3
    }; // 4 vertices with 5 components (floats) each

    // fill with data
    glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat)*4*5, vertexData, GL_STATIC_DRAW);
                    
           
    // set up generic attrib pointers
    glEnableVertexAttribArray(0);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5*sizeof(GLfloat), (char*)0 + 0*sizeof(GLfloat));
 
    glEnableVertexAttribArray(1);
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5*sizeof(GLfloat), (char*)0 + 3*sizeof(GLfloat));
    
    
    // generate and bind the index buffer object
    glGenBuffers(1, &ibo);
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
            
    GLuint indexData[] = {
        0,1,2, // first triangle
        2,1,3, // second triangle
    };

    // fill with data
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint)*2*3, indexData, GL_STATIC_DRAW);
    
    // "unbind" vao
    glBindVertexArray(0);

    // texture handle
    GLuint texture;
    
    // generate texture
    glGenTextures(1, &texture);

    // bind the texture
    glBindTexture(GL_TEXTURE_2D, texture);

    // create some image data
    std::vector<GLubyte> image(4*width*height);
    for(int j = 0;j<height;++j) {
        for(int i = 0;i<width;++i) {
            size_t index = j*width + i;
            image[4*index + 0] = 0xFF*(j/10%2)*(i/10%2); // R
            image[4*index + 1] = 0xFF*(j/13%2)*(i/13%2); // G
            image[4*index + 2] = 0xFF*(j/17%2)*(i/17%2); // B
            image[4*index + 3] = 0xFF;                   // A
        }
    }
    
    // set texture parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    
    // set texture content
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, &image[0]);
    
    while(!glfwWindowShouldClose(window)) {
        glfwPollEvents();
        
        // clear first
        glClear(GL_COLOR_BUFFER_BIT);
        
        // use the shader program
        glUseProgram(shader_program);

        // bind texture to texture unit 0
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, texture);
        
        // set texture uniform
        glUniform1i(texture_location, 0);
        
        // bind the vao
        glBindVertexArray(vao);
        
        // draw
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
       
        // check for errors
        GLenum error = glGetError();
        if(error != GL_NO_ERROR) {
            std::cerr << error << std::endl;
            break;
        }
        
        // finally swap buffers
        glfwSwapBuffers(window);     
    }
    
    // delete the created objects
    
    glDeleteTextures(1, &texture);
    
    glDeleteVertexArrays(1, &vao);
    glDeleteBuffers(1, &vbo);
    glDeleteBuffers(1, &ibo);
    
    glDetachShader(shader_program, vertex_shader);	
    glDetachShader(shader_program, fragment_shader);
    glDeleteShader(vertex_shader);
    glDeleteShader(fragment_shader);
    glDeleteProgram(shader_program);

    glfwDestroyWindow(window);
    glfwTerminate();
    return 0;
}
Ejemplo n.º 16
0
int main(int argc, char** argv)
{
    int count = 0;
    GLFWwindow* window;

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

    glfwSetErrorCallback(error_callback, NULL);

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

    for (;;)
    {
        GLFWmonitor* monitor = NULL;

        if (count & 1)
        {
            int monitorCount;
            GLFWmonitor** monitors = glfwGetMonitors(&monitorCount);
            monitor = monitors[rand() % monitorCount];
        }

        window = open_window(640, 480, monitor);
        if (!window)
        {
            glfwTerminate();
            exit(EXIT_FAILURE);
        }

        glMatrixMode(GL_PROJECTION);
        glOrtho(-1.f, 1.f, -1.f, 1.f, 1.f, -1.f);
        glMatrixMode(GL_MODELVIEW);

        glfwSetTime(0.0);

        while (glfwGetTime() < 5.0)
        {
            glClear(GL_COLOR_BUFFER_BIT);

            glPushMatrix();
            glRotatef((GLfloat) glfwGetTime() * 100.f, 0.f, 0.f, 1.f);
            glRectf(-0.5f, -0.5f, 1.f, 1.f);
            glPopMatrix();

            glfwSwapBuffers(window);
            glfwPollEvents();

            if (glfwWindowShouldClose(window))
            {
                close_window(window);
                printf("User closed window\n");

                glfwTerminate();
                exit(EXIT_SUCCESS);
            }
        }

        printf("Closing window\n");
        close_window(window);

        count++;
    }

    glfwTerminate();
}
Ejemplo n.º 17
0
 GLWindow::~GLWindow() {
     glfwTerminate();
 }
Ejemplo n.º 18
0
int main () {
	/*--------------------------------START OPENGL---------------------------*/
	assert (restart_gl_log ());
	// start GL context and O/S window using the GLFW helper library
	assert (start_gl ());
	glEnable (GL_DEPTH_TEST); // enable depth-testing
    // depth-testing interprets a smaller value as "closer"
	glDepthFunc (GL_LESS);
    glEnable (GL_CULL_FACE); // cull face
	glCullFace (GL_BACK); // cull back face
    // set counter-clock-wise vertex order to mean the front
	glFrontFace (GL_CCW);
    glClearColor (0.2, 0.2, 0.2, 1.0); // grey background to help spot mistakes
	glViewport (0, 0, g_gl_width, g_gl_height);
	
/*------------------------------CREATE GEOMETRY------------------------------*/
	GLfloat* vp = NULL; // array of vertex points
	GLfloat* vn = NULL; // array of vertex normals
	GLfloat* vt = NULL; // array of texture coordinates
	int g_point_count = 0;
	assert (load_obj_file (MESH_FILE, vp, vt, vn, g_point_count));

	GLuint vao;
	glGenVertexArrays (1, &vao);
	glBindVertexArray (vao);

	GLuint points_vbo;
	if (NULL != vp) {
		glGenBuffers (1, &points_vbo);
		glBindBuffer (GL_ARRAY_BUFFER, points_vbo);
		glBufferData (GL_ARRAY_BUFFER, 3 * g_point_count * sizeof (GLfloat),
                      vp, GL_STATIC_DRAW);
		glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, NULL);
		glEnableVertexAttribArray (0);
	}
	GLuint normals_vbo;
	if (NULL != vn) {
		glGenBuffers (1, &normals_vbo);
		glBindBuffer (GL_ARRAY_BUFFER, normals_vbo);
		glBufferData (GL_ARRAY_BUFFER, 3 * g_point_count * sizeof (GLfloat),
                      vn, GL_STATIC_DRAW);
		glVertexAttribPointer (1, 3, GL_FLOAT, GL_FALSE, 0, NULL);
		glEnableVertexAttribArray (1);
	}
	GLuint texcoords_vbo;
	if (NULL != vp) {
		glGenBuffers (1, &texcoords_vbo);
		glBindBuffer (GL_ARRAY_BUFFER, texcoords_vbo);
		glBufferData (GL_ARRAY_BUFFER, 2 * g_point_count * sizeof (GLfloat),
                      vp, GL_STATIC_DRAW);
		glVertexAttribPointer (2, 2, GL_FLOAT, GL_FALSE, 0, NULL);
		glEnableVertexAttribArray (2);
	}
	
/*-------------------------------CREATE SHADERS------------------------------*/
	GLuint shader_programme = create_programme_from_files (VERTEX_SHADER_FILE,
		FRAGMENT_SHADER_FILE);
	int view_mat_location = glGetUniformLocation (shader_programme, "view");
	int proj_mat_location = glGetUniformLocation (shader_programme, "proj");
	
	/* if converting to GLSL 410 do this to replace GLSL texture bindings:
	GLint diffuse_map_loc, specular_map_loc, ambient_map_loc, emission_map_loc;
	diffuse_map_loc = glGetUniformLocation (shader_programme, "diffuse_map");
	specular_map_loc = glGetUniformLocation (shader_programme, "specular_map");
	ambient_map_loc = glGetUniformLocation (shader_programme, "ambient_map");
	emission_map_loc = glGetUniformLocation (shader_programme, "emission_map");
	assert (diffuse_map_loc > -1);
	assert (specular_map_loc > -1);
	assert (ambient_map_loc > -1);
	assert (emission_map_loc > -1);
	glUseProgram (shader_programme);
	glUniform1i (diffuse_map_loc, 0);
	glUniform1i (specular_map_loc, 1);
	glUniform1i (ambient_map_loc, 2);
	glUniform1i (emission_map_loc, 3);
	*/
	
	// load texture
	GLuint tex_diff, tex_spec, tex_amb, tex_emiss;
	glActiveTexture (GL_TEXTURE0);
	assert (load_texture ("boulder_diff.png", &tex_diff));
	glActiveTexture (GL_TEXTURE1);
	assert (load_texture ("boulder_spec.png", &tex_spec));
	glActiveTexture (GL_TEXTURE2);
	assert (load_texture ("ao.png", &tex_amb));
	glActiveTexture (GL_TEXTURE3);
	assert (load_texture ("tileable9b_emiss.png", &tex_emiss));
	
	#define ONE_DEG_IN_RAD (2.0 * M_PI) / 360.0 // 0.017444444
	// input variables
	float near = 0.1f; // clipping plane
	float far = 100.0f; // clipping plane
	float fov = 67.0f * ONE_DEG_IN_RAD; // convert 67 degrees to radians
	float aspect = (float)g_gl_width / (float)g_gl_height; // aspect ratio
	// matrix components
	float range = tan (fov * 0.5f) * near;
	float Sx = (2.0f * near) / (range * aspect + range * aspect);
	float Sy = near / range;
	float Sz = -(far + near) / (far - near);
	float Pz = -(2.0f * far * near) / (far - near);
	GLfloat proj_mat[] = {
		Sx, 0.0f, 0.0f, 0.0f,
		0.0f, Sy, 0.0f, 0.0f,
		0.0f, 0.0f, Sz, -1.0f,
		0.0f, 0.0f, Pz, 0.0f
	};
	
		
	float cam_speed = 1.0f; // 1 unit per second
	float cam_yaw_speed = 10.0f; // 10 degrees per second
    // don't start at zero, or we will be too close
	float cam_pos[] = {0.0f, 0.0f, 5.0f};
	float cam_yaw = 0.0f; // y-rotation in degrees
	mat4 T = translate (identity_mat4 (), vec3 (-cam_pos[0], -cam_pos[1],
                                                -cam_pos[2]));
	mat4 R = rotate_y_deg (identity_mat4 (), -cam_yaw);
	mat4 view_mat = R * T;
	
	glUseProgram (shader_programme);
	glUniformMatrix4fv (view_mat_location, 1, GL_FALSE, view_mat.m);
	glUniformMatrix4fv (proj_mat_location, 1, GL_FALSE, proj_mat);
	
	while (!glfwWindowShouldClose (g_window)) {
		static double previous_seconds = glfwGetTime ();
		double current_seconds = glfwGetTime ();
		double elapsed_seconds = current_seconds - previous_seconds;
		previous_seconds = current_seconds;
	
		_update_fps_counter (g_window);
		// wipe the drawing surface clear
		glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		glViewport (0, 0, g_gl_width, g_gl_height);
		
		glUseProgram (shader_programme);
		glBindVertexArray (vao);
		// draw points 0-3 from the currently bound VAO with current shader
		glDrawArrays (GL_TRIANGLES, 0, g_point_count);
		// update other events like input handling 
		glfwPollEvents ();
		
		// control keys
		bool cam_moved = false;
		if (glfwGetKey (g_window, GLFW_KEY_A)) {
			cam_pos[0] -= cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_D)) {
			cam_pos[0] += cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_PAGE_UP)) {
			cam_pos[1] += cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_PAGE_DOWN)) {
			cam_pos[1] -= cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_W)) {
			cam_pos[2] -= cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_S)) {
			cam_pos[2] += cam_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_LEFT)) {
			cam_yaw += cam_yaw_speed * elapsed_seconds;
			cam_moved = true;
		}
		if (glfwGetKey (g_window, GLFW_KEY_RIGHT)) {
			cam_yaw -= cam_yaw_speed * elapsed_seconds;
			cam_moved = true;
		}
		// update view matrix
		if (cam_moved) {
			mat4 T = translate (identity_mat4 (), vec3 (-cam_pos[0],
                -cam_pos[1], -cam_pos[2])); // cam translation
			mat4 R = rotate_y_deg (identity_mat4 (), -cam_yaw); // 
			mat4 view_mat = R * T;
			glUniformMatrix4fv (view_mat_location, 1, GL_FALSE, view_mat.m);
		}
		
		
		if (GLFW_PRESS == glfwGetKey (g_window, GLFW_KEY_ESCAPE)) {
			glfwSetWindowShouldClose (g_window, 1);
		}
		// put the stuff we've been drawing onto the display
		glfwSwapBuffers (g_window);
	}
	
	// close GL context and any other GLFW resources
	glfwTerminate();
	return 0;
}
Ejemplo n.º 19
0
int main(int argc, const char * argv[]) {
    const int WIDTH = 800;
    const int HEIGHT = 600;
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    
    
    glfwSetErrorCallback(glfwErrorCallback);

    GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr);
    if (window == nullptr)
    {
        printf("Failed to create GLFW window");
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);
    
    // GLEW负责管理每个平台上应该调用哪个函数指针,所以在调用openGL之前,先初始化它
    glewExperimental = GL_TRUE;
    if (glewInit() != GLEW_OK)
    {
        std::cerr << "Failed to initialize GLEW" << std::endl;
        return -1;
    }
    // Define the viewport dimensions
    int width, height;
    glfwGetFramebufferSize(window, &width, &height);
    glViewport(0, 0, width, height);

    glfwSetKeyCallback(window, key_callback);
    
    // Build and compile our shader program
    // Vertex shader
    GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
    glCompileShader(vertexShader);
    // Check for compile time errors
    GLint success;
    GLchar infoLog[512];
    glGetShaderiv(vertexShader, GL_COMPILE_STATUS, &success);
    if (!success)
    {
        glGetShaderInfoLog(vertexShader, 512, NULL, infoLog);
        std::cout << "ERROR::SHADER::VERTEX::COMPILATION_FAILED\n" << infoLog << std::endl;
    }
    // Fragment shader
    GLuint fragmentShader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragmentShader, 1, &fragmentShaderSource, NULL);
    glCompileShader(fragmentShader);
    // Check for compile time errors
    glGetShaderiv(fragmentShader, GL_COMPILE_STATUS, &success);
    if (!success)
    {
        glGetShaderInfoLog(fragmentShader, 512, NULL, infoLog);
        std::cout << "ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n" << infoLog << std::endl;
    }
    // Link shaders
    GLuint shaderProgram = glCreateProgram();
    glAttachShader(shaderProgram, vertexShader);
    glAttachShader(shaderProgram, fragmentShader);
    glLinkProgram(shaderProgram);
    // Check for linking errors
    glGetProgramiv(shaderProgram, GL_LINK_STATUS, &success);
    if (!success) {
        glGetProgramInfoLog(shaderProgram, 512, NULL, infoLog);
        std::cout << "ERROR::SHADER::PROGRAM::LINKING_FAILED\n" << infoLog << std::endl;
    }
    glDeleteShader(vertexShader);
    glDeleteShader(fragmentShader);
    
    
    // Set up vertex data (and buffer(s)) and attribute pointers
    GLfloat vertices[] = {
        0.5f,  0.5f, 0.0f,  // Top Right
        0.5f, -0.5f, 0.0f,  // Bottom Right
        -0.5f, -0.5f, 0.0f, // bottom left
    };
    
    GLfloat vertices2[] = {
        0.8f,  0.5f, 0.0f,  // Top Right
        0.8f, -0.5f, 0.0f,  // Bottom Right
        -0.2f, -0.5f, 0.0f, // bottom left
    };

    GLuint VBO, VAO, VBO2, VAO2;
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);
    
    glGenVertexArrays(2, &VAO2);
    glGenBuffers(2, &VBO2);
    
    // Bind the Vertex Array Object first, then bind and set vertex buffer(s) and attribute pointer(s).
    glBindVertexArray(VAO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, 0); // Note that this is allowed, the call to glVertexAttribPointer registered VBO as the currently bound vertex buffer object so afterwards we can safely unbind
    glBindVertexArray(0); // Unbind VAO (it's always a good thing to unbind any buffer/array to prevent strange bugs), remember: do NOT unbind the EBO, keep it bound to this VAO
    

    glBindVertexArray(VAO2);
    glBindBuffer(GL_ARRAY_BUFFER, VBO2);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices2), vertices2, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(0);
    glBindBuffer(GL_ARRAY_BUFFER, 0); // Note that this is allowed, the call to glVertexAttribPointer registered VBO as the currently bound vertex buffer object so afterwards we can safely unbind
    glBindVertexArray(0); // Unbind VAO (it's always a good thing to unbind any buffer/array to prevent strange bugs), remember: do NOT unbind the EBO, keep it bound to this VAO
    
    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

    while(!glfwWindowShouldClose(window))
    {
        glfwPollEvents();
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        
        // Draw our first triangle
        glUseProgram(shaderProgram);
        glBindVertexArray(VAO);
        glDrawArrays(GL_TRIANGLES, 0, 3);
        glBindVertexArray(0);
        
        glBindVertexArray(VAO2);
        glDrawArrays(GL_TRIANGLES, 0, 3);
        glBindVertexArray(0);
        
        glfwSwapBuffers(window);
    }
    
    // Properly de-allocate all resources once they've outlived their purpose
    glDeleteVertexArrays(1, &VAO);
    glDeleteBuffers(1, &VBO);
    
    // Properly de-allocate all resources once they've outlived their purpose
    glDeleteVertexArrays(1, &VAO2);
    glDeleteBuffers(1, &VBO2);
    
    glfwTerminate();

    return 0;
}
Ejemplo n.º 20
0
// setup
int main(int argc, char *argv[])
{
    GLenum err = 0;
    /*********************************************
     * GLFW SETUP
     *********************************************/
    err = glfwInit();
    if (!err)
    {
        fputs("Failed to load the GLFW library", stderr);
        exit(EXIT_FAILURE);
    }

    /*********************************************
     * STATE SETUP (initialize gl context)
     *********************************************/
    // must be setup before glew so that a valid openGL
    // context exists (created with the window)

    w_state = new WorldState();
    c_state.init(*w_state);

    /*********************************************
     * GLEW SETUP
     *********************************************/
    err = glewInit();
    if (err != GLEW_OK)
    {
        fputs("Failed to initialize the GLEW library", stderr);
        exit(EXIT_FAILURE);
    }

    /*********************************************
     * STATE SETUP (construct render states)
     *********************************************/
    // must be setup after glew so that GL array
    // objects exist

    r_state[0] = new RenderState(3);
    r_state[1] = new RenderState(3);

    /*********************************************
     * SHADER SETUP
     *********************************************/
    // read default shaders from file
    GLuint shaderProgram[2] = {0};
    GLuint shaders[2] = {0};

    buildShader(GL_VERTEX_SHADER, "default.vs.glsl", shaders[0]);
    buildShader(GL_FRAGMENT_SHADER, "default.fs.glsl", shaders[1]);

    // create default shader program
    shaderProgram[0] = buildProgram(2, shaders);

    // bind shader program
    w_state->setProgram(0, shaderProgram[0]);
    w_state->useProgram(0);

    // setup the transform matrices and uniform variables
    w_state->loadTransforms();
    w_state->loadLights();
    w_state->loadMaterials();

    /*********************************************
     * LOAD MESH
     *********************************************/
    
    g_mesh = loadMeshFromFile(*r_state[0], "Mesh/arma.obj");

    /*********************************************
     * SET GL STATE
     *********************************************/ 
    glEnable(GL_DEPTH_TEST);

    /*********************************************
     * RENDER LOOP
     *********************************************/
    glfwSetTime(0.0);
    while (!glfwWindowShouldClose(c_state.window))
        display();

    /*********************************************
     * CLEAN UP
     *********************************************/
    delete g_mesh;
    glfwTerminate();

    exit(EXIT_SUCCESS);
}
Ejemplo n.º 21
0
GLContext::~GLContext()
{
    glfwTerminate();
}
Ejemplo n.º 22
0
int main(void)
{
	GLFWwindow* window;

	/* Initialize the library */
	if (!glfwInit())
		return -1;



	/* Create a windowed mode window and its OpenGL context */
	window = glfwCreateWindow(800, 600, "Hello World", NULL, NULL);
	if (!window)
	{
		glfwTerminate();
		return -1;
	}

	glfwSetScrollCallback(window, OnScroll);

	// GLFW settings
	glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
	glfwSetCursorPos(window, 0, 0);

	/* Make the window's context current */
	glfwMakeContextCurrent(window);

	if (glewInit() != GLEW_OK)
	{
		glfwTerminate();
		return -1;
	}

	// print out some info about the graphics drivers
	std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl;
	std::cout << "GLSL version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl;
	std::cout << "Vendor: " << glGetString(GL_VENDOR) << std::endl;
	std::cout << "Renderer: " << glGetString(GL_RENDERER) << std::endl;

	// OpenGL settings
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LESS);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	init();

	gCamera.setPosition(glm::vec3(0, 0, 4));
	gCamera.setViewportAspectRatio(800.0f / 600.0f);

	double lastTime = glfwGetTime();
	while (!glfwWindowShouldClose(window))
	{
		/* Poll for and process events */
		glfwPollEvents();

		double thisTime = glfwGetTime();
		Update((float)(thisTime - lastTime), window);
		lastTime = thisTime;

		Render(window);

		// check for errors
		GLenum error = glGetError();
		if (error != GL_NO_ERROR)
			std::cerr << "OpenGL Error " << error << std::endl;

		//exit program if escape key is pressed
		if (glfwGetKey(window, GLFW_KEY_ESCAPE))
			glfwSetWindowShouldClose(window, GL_TRUE);
	}

	glfwTerminate();
	return 0;
}
Ejemplo n.º 23
0
 ~glfw_context()
 {
     glfwTerminate();
 }
Ejemplo n.º 24
0
int main(int argc, char ** argv) 
{
    // 
    // Setup GLFW, glew and some initial GL state
    //
    static const char windowTitle[] = "CPU Subdivision Example";

    if (not glfwInit()) {
        printf("Failed to initialize GLFW\n");
        return 1;
    }
    
#define CORE_PROFILE
#ifdef CORE_PROFILE
    setGLCoreProfile();
#endif

    #if GLFW_VERSION_MAJOR>=3
        if (not (g_window=glfwCreateWindow(g_width, g_height, windowTitle, NULL, NULL))) {
            printf("Failed to open window.\n");
            glfwTerminate();
            return 1;
        }
        glfwMakeContextCurrent(g_window);
        glfwSetWindowSizeCallback(g_window, reshape);
        glfwSetWindowCloseCallback(g_window, windowClose);
    #else
        if (glfwOpenWindow(g_width, g_height, 8, 8, 8, 8, 24, 8, GLFW_WINDOW) == GL_FALSE) {
            printf("Failed to open window.\n");
            glfwTerminate();
            return 1;
        }
        glfwSetWindowTitle(windowTitle);
        glfwSetWindowSizeCallback(reshape);
        glfwSetWindowCloseCallback(windowClose);
    #endif

    

#if defined(OSD_USES_GLEW)
#ifdef CORE_PROFILE
    // this is the only way to initialize glew correctly under core profile context.
    glewExperimental = true;
#endif
    if (GLenum r = glewInit() != GLEW_OK) {
        printf("Failed to initialize glew. Error = %s\n", glewGetErrorString(r));
        exit(1);
    }
#ifdef CORE_PROFILE
    // clear GL errors which was generated during glewInit()
    glGetError();
#endif
#endif

    initOsd();
    
    //
    // Start the main drawing loop
    //
    while (g_running) {
        idle();
        display();
        
#if GLFW_VERSION_MAJOR>=3
        glfwPollEvents();
        glfwSwapBuffers(g_window);
#else
        glfwSwapBuffers();
#endif
        
        glFinish();
    }
}
Ejemplo n.º 25
0
int Application::run(Application* self)
{
	m_self = self;

	if (!framework::Utils::exists("data/gui"))
	{
		Logger::toLog("Error: could not find gui directory. Probably working directory has not been set correctly (especially if you are running from IDE).\n");
		return EXIT_FAILURE;
	}

	init();
	m_isRunning = true;

	glfwSetErrorCallback(&Application::errorCallback);

	if (!glfwInit())
	{
		Logger::toLog("Error: glfwInit failed");
		return EXIT_FAILURE;
	}

	glfwWindowHint(GLFW_VISIBLE, GL_TRUE);
	glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

	glfwWindowHint(GLFW_RED_BITS, 8);
	glfwWindowHint(GLFW_GREEN_BITS, 8);
	glfwWindowHint(GLFW_BLUE_BITS, 8);
	glfwWindowHint(GLFW_ALPHA_BITS, 0);
	glfwWindowHint(GLFW_DEPTH_BITS, 32);
	glfwWindowHint(GLFW_STENCIL_BITS, 0);

	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, m_info.majorVersion);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, m_info.minorVersion);
	#ifdef _DEBUG
    glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
	#endif
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_SAMPLES, m_info.samples);
    glfwWindowHint(GLFW_STEREO, m_info.flags.stereo ? GL_TRUE : GL_FALSE);

	// create window
	m_window = glfwCreateWindow(m_info.windowWidth, m_info.windowHeight, 
								m_info.title.c_str(), 
								m_info.flags.fullscreen ? glfwGetPrimaryMonitor() : NULL, 
								NULL);
	if (!m_window)
    {
        glfwTerminate();
        return EXIT_FAILURE;
    }

	glfwSetWindowSizeCallback(m_window, &Application::_setWindowSize);
    glfwSetKeyCallback(m_window, &Application::_onKey);
	glfwSetCharCallback(m_window, &Application::_onChar);
    glfwSetMouseButtonCallback(m_window, &Application::_onMouse);
    glfwSetCursorPosCallback(m_window, &Application::_onCursor);
    glfwSetScrollCallback(m_window, &Application::_onScroll);
	glfwSetInputMode(m_window, GLFW_CURSOR, m_info.flags.cursor ? GLFW_CURSOR_NORMAL : GLFW_CURSOR_HIDDEN);

	// center position
	GLFWmonitor* primary = glfwGetPrimaryMonitor();
	const GLFWvidmode* mode = glfwGetVideoMode(primary);
	int posx = (mode->width - m_info.windowWidth) >> 1;
	int posy = (mode->height - m_info.windowHeight) >> 1;
	glfwSetWindowPos(m_window, posx, posy);

	// set vsync
	glfwMakeContextCurrent(m_window);
	glfwSwapInterval((int)m_info.flags.vsync);

	// init GL3w
	gl3wInit();

	std::vector<int> multisamplingLevels;
	if (!checkOpenGLVersion() || !checkDeviceCapabilities(multisamplingLevels))
	{
		glfwDestroyWindow(m_window);
		glfwTerminate();
		return EXIT_FAILURE;
	}

	#ifdef _DEBUG
	Logger::toLogWithFormat("Video adapter: %s - %s, OpenGL: %s\n", (const char*)glGetString(GL_VENDOR), (const char*)glGetString(GL_RENDERER), (const char*)glGetString(GL_VERSION));
	#endif

    if (m_info.flags.debug)
    {
        if (gl3wIsSupported(4, 3))
        {
            glDebugMessageCallback(debugCallback, this);
            glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
        }
        else if (IsExtensionSupported("GL_ARB_debug_output"))
        {
            glDebugMessageCallbackARB(debugCallback, this);
            glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
        }
    }

	initGui();

	if (!StandardGpuPrograms::init())
	{
		glfwDestroyWindow(m_window);
		glfwTerminate();
		return EXIT_FAILURE;
	}
	initAxes();
	startup(m_rootWindow);

	do
    {
		glfwMakeContextCurrent(m_window);
		Texture::beginFrame();
		if (fabs(m_lastTime) < 1e-7)
		{
			render(0);
			Texture::endFrame();
			renderGui(0);

			m_lastTime = glfwGetTime();
		}
		else
		{
			double curTime = glfwGetTime();
			double delta = curTime - m_lastTime;
				
			// fps counter
			measureFps(delta);

			// rendering
			render(delta);
			Texture::endFrame();
			renderGui(delta);

			m_lastTime = curTime;
		}

        glfwSwapBuffers(m_window);

		glfwPollEvents();
			
		if (glfwWindowShouldClose(m_window))
		{
            m_isRunning = GL_FALSE;
		}
		m_isRunning &= (glfwGetKey(m_window, GLFW_KEY_ESCAPE) == GLFW_RELEASE);
    } 
	while(m_isRunning);

	shutdown();
	destroyAllDestroyable();
	destroyGui();

	glfwDestroyWindow(m_window);
	glfwTerminate();
	return EXIT_SUCCESS;
}
Ejemplo n.º 26
0
OculusManager& OculusManager::getOculusManager()
{

	static OculusManager* oculusManager = NULL;

	if (oculusManager == NULL)
	{
		oculusManager = new OculusManager();
		if (!ovr_Initialize()) {
			fprintf(stderr, "Failed to initialize the Oculus SDK");
		}

		//= *OculusManager::getHmd();

		g_Hmd = ovrHmd_Create(0);
		if (!g_Hmd)
		{
			printf("No Oculus Rift device attached, using virtual version...\n");
			g_Hmd = ovrHmd_CreateDebug(ovrHmd_DK2);
		}
		printf("initialized HMD: %s - %s\n", g_Hmd->Manufacturer, g_Hmd->ProductName);

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

		if (l_MultiSampling) glfwWindowHint(GLFW_SAMPLES, 4); else glfwWindowHint(GLFW_SAMPLES, 0);

		bool l_DirectMode = ((g_Hmd->HmdCaps & ovrHmdCap_ExtendDesktop) == 0);

		GLFWmonitor* l_Monitor;
		ovrSizei l_ClientSize;
		if (l_DirectMode)
		{
			printf("Running in \"Direct\" mode...\n");
			l_Monitor = NULL;

			l_ClientSize.w = g_Hmd->Resolution.w / 2; // Something reasonable, smaller, but maintain aspect ratio...
			l_ClientSize.h = g_Hmd->Resolution.h / 2; // Something reasonable, smaller, but maintain aspect ratio...
		}
		else // Extended Desktop mode...
		{
			printf("Running in \"Extended Desktop\" mode...\n");
			int l_Count;
			GLFWmonitor** l_Monitors = glfwGetMonitors(&l_Count);
			switch (l_Count)
			{
			case 0:
				printf("No monitors found, exiting...\n");
				exit(EXIT_FAILURE);
				break;
			case 1:
				printf("Two monitors expected, found only one, using primary...\n");
				l_Monitor = glfwGetPrimaryMonitor();
				break;
			case 2:
				printf("Two monitors found, using second monitor...\n");
				l_Monitor = l_Monitors[1];
				break;
			default:
				printf("More than two monitors found, using second monitor...\n");
				l_Monitor = l_Monitors[1];
			}

			l_ClientSize.w = g_Hmd->Resolution.w; // 1920 for DK2...
			l_ClientSize.h = g_Hmd->Resolution.h; // 1080 for DK2...
		}

		l_Window = glfwCreateWindow(l_ClientSize.w, l_ClientSize.h, "GLFW Oculus Rift Test", l_Monitor, NULL);

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

#if defined(_WIN32)
		if (l_DirectMode)
		{
			ovrBool l_AttachResult = ovrHmd_AttachToWindow(g_Hmd, glfwGetWin32Window(l_Window), NULL, NULL);
			if (!l_AttachResult)
			{
				printf("Could not attach to window...");
				exit(EXIT_FAILURE);
			}
		}
#endif

		glfwMakeContextCurrent(l_Window);

		glewExperimental = GL_TRUE;
		GLenum l_GlewResult = glewInit();
		if (l_GlewResult != GLEW_OK)
		{
			printf("glewInit() error.\n");
			exit(EXIT_FAILURE);
		}

		int l_Major = glfwGetWindowAttrib(l_Window, GLFW_CONTEXT_VERSION_MAJOR);
		int l_Minor = glfwGetWindowAttrib(l_Window, GLFW_CONTEXT_VERSION_MINOR);
		int l_Profile = glfwGetWindowAttrib(l_Window, GLFW_OPENGL_PROFILE);
		printf("OpenGL: %d.%d ", l_Major, l_Minor);
		if (l_Major >= 3) // Profiles introduced in OpenGL 3.0...
		{
			if (l_Profile == GLFW_OPENGL_COMPAT_PROFILE) printf("GLFW_OPENGL_COMPAT_PROFILE\n"); else printf("GLFW_OPENGL_CORE_PROFILE\n");
		}
		printf("Vendor: %s\n", (char*)glGetString(GL_VENDOR));
		printf("Renderer: %s\n", (char*)glGetString(GL_RENDERER));

		ovrSizei l_EyeTextureSizes[2];

		l_EyeTextureSizes[ovrEye_Left] = ovrHmd_GetFovTextureSize(g_Hmd, ovrEye_Left, g_Hmd->MaxEyeFov[ovrEye_Left], 1.0f);
		l_EyeTextureSizes[ovrEye_Right] = ovrHmd_GetFovTextureSize(g_Hmd, ovrEye_Right, g_Hmd->MaxEyeFov[ovrEye_Right], 1.0f);

		// Combine for one texture for both eyes...
		g_RenderTargetSize.w = l_EyeTextureSizes[ovrEye_Left].w + l_EyeTextureSizes[ovrEye_Right].w;
		g_RenderTargetSize.h = (l_EyeTextureSizes[ovrEye_Left].h > l_EyeTextureSizes[ovrEye_Right].h ? l_EyeTextureSizes[ovrEye_Left].h : l_EyeTextureSizes[ovrEye_Right].h);

		// Create the FBO being a single one for both eyes (this is open for debate)...
		glGenFramebuffers(1, &l_FBOId);
		glBindFramebuffer(GL_FRAMEBUFFER, l_FBOId);

		// The texture we're going to render to...
		glGenTextures(1, &l_TextureId);
		// "Bind" the newly created texture : all future texture functions will modify this texture...
		glBindTexture(GL_TEXTURE_2D, l_TextureId);
		// Give an empty image to OpenGL (the last "0")
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, g_RenderTargetSize.w, g_RenderTargetSize.h, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
		// Linear filtering...
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

		// Create Depth Buffer...
		glGenRenderbuffers(1, &l_DepthBufferId);
		glBindRenderbuffer(GL_RENDERBUFFER, l_DepthBufferId);
		glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, g_RenderTargetSize.w, g_RenderTargetSize.h);
		glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, l_DepthBufferId);

		// Set the texture as our colour attachment #0...
		glFramebufferTexture(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, l_TextureId, 0);

		// Set the list of draw buffers...
		GLenum l_GLDrawBuffers[1] = { GL_COLOR_ATTACHMENT0 };
		glDrawBuffers(1, l_GLDrawBuffers); // "1" is the size of DrawBuffers

		// Check if everything is OK...
		GLenum l_Check = glCheckFramebufferStatus(GL_DRAW_FRAMEBUFFER);
		if (l_Check != GL_FRAMEBUFFER_COMPLETE)
		{
			printf("There is a problem with the FBO.\n");
			exit(EXIT_FAILURE);
		}

		// Unbind...
		glBindRenderbuffer(GL_RENDERBUFFER, 0);
		glBindTexture(GL_TEXTURE_2D, 0);
		glBindFramebuffer(GL_FRAMEBUFFER, 0);

		// Setup textures for each eye...

		// Left eye...
		g_EyeTextures[ovrEye_Left].Header.API = ovrRenderAPI_OpenGL;
		g_EyeTextures[ovrEye_Left].Header.TextureSize = g_RenderTargetSize;
		g_EyeTextures[ovrEye_Left].Header.RenderViewport.Pos.x = 0;
		g_EyeTextures[ovrEye_Left].Header.RenderViewport.Pos.y = 0;
		g_EyeTextures[ovrEye_Left].Header.RenderViewport.Size = l_EyeTextureSizes[ovrEye_Left];
		((ovrGLTexture&)(g_EyeTextures[ovrEye_Left])).OGL.TexId = l_TextureId;

		// Right eye (mostly the same as left but with the viewport on the right side of the texture)...
		g_EyeTextures[ovrEye_Right] = g_EyeTextures[ovrEye_Left];
		g_EyeTextures[ovrEye_Right].Header.RenderViewport.Pos.x = (g_RenderTargetSize.w + 1) / 2;
		g_EyeTextures[ovrEye_Right].Header.RenderViewport.Pos.y = 0;

		// Oculus Rift eye configurations...
		g_Cfg.OGL.Header.API = ovrRenderAPI_OpenGL;
		g_Cfg.OGL.Header.RTSize.w = l_ClientSize.w;
		g_Cfg.OGL.Header.RTSize.h = l_ClientSize.h;
		g_Cfg.OGL.Header.Multisample = (l_MultiSampling ? 1 : 0);
#if defined(_WIN32)
		g_Cfg.OGL.Window = glfwGetWin32Window(l_Window);
		g_Cfg.OGL.DC = GetDC(g_Cfg.OGL.Window);
#elif defined(__linux__)
		l_Cfg.OGL.Win = glfwGetX11Window(l_Window);
		l_Cfg.OGL.Disp = glfwGetX11Display();
#endif

		// Enable capabilities...
		// ovrHmd_SetEnabledCaps(g_Hmd, ovrHmdCap_LowPersistence | ovrHmdCap_DynamicPrediction);

		ovrBool l_ConfigureResult = ovrHmd_ConfigureRendering(g_Hmd, &g_Cfg.Config, g_DistortionCaps, g_Hmd->MaxEyeFov, g_EyeRenderDesc);
		glUseProgram(0); // Avoid OpenGL state leak in ovrHmd_ConfigureRendering...
		if (!l_ConfigureResult)
		{
			printf("Configure failed.\n");
			exit(EXIT_FAILURE);
		}

		// Start the sensor which provides the Rift’s pose and motion...
		uint32_t l_SupportedSensorCaps = ovrTrackingCap_Orientation | ovrTrackingCap_MagYawCorrection | ovrTrackingCap_Position;
		uint32_t l_RequiredTrackingCaps = 0;
		ovrBool l_TrackingResult = ovrHmd_ConfigureTracking(g_Hmd, l_SupportedSensorCaps, l_RequiredTrackingCaps);
		if (!l_TrackingResult)
		{
			printf("Could not start tracking...");
			exit(EXIT_FAILURE);
		}

		// Projection matrici for each eye will not change at runtime, we can set them here...
		g_ProjectionMatrici[ovrEye_Left] = ovrMatrix4f_Projection(g_EyeRenderDesc[ovrEye_Left].Fov, 0.3f, 100.0f, true);
		g_ProjectionMatrici[ovrEye_Right] = ovrMatrix4f_Projection(g_EyeRenderDesc[ovrEye_Right].Fov, 0.3f, 100.0f, true);

		// IPD offset values will not change at runtime, we can set them here...
		g_EyeOffsets[ovrEye_Left] = g_EyeRenderDesc[ovrEye_Left].HmdToEyeViewOffset;
		g_EyeOffsets[ovrEye_Right] = g_EyeRenderDesc[ovrEye_Right].HmdToEyeViewOffset;

		ovrHmd_RecenterPose(g_Hmd);


		return *oculusManager;
	}
}
Ejemplo n.º 27
0
	//--------------------------------------------------------------------------
	bool Run(	int argc, 
				char* argv[], 
				const glm::ivec2 & size, 
				int major, 
				int minor)
	{
		glfwSetErrorCallback(error);

		// GLFW initialization
		if (!glfwInit())
			exit(-1);

		glfwSetErrorCallback(error);

		// Configure the window
		glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
		glfwWindowHint(GLFW_VISIBLE, GL_TRUE);
		glfwWindowHint(GLFW_DECORATED, GL_TRUE);
		glfwWindowHint(GLFW_FOCUSED, GL_TRUE);

		glfwWindowHint(GLFW_RED_BITS, 8);
		glfwWindowHint(GLFW_GREEN_BITS, 8);
		glfwWindowHint(GLFW_BLUE_BITS, 8);
		glfwWindowHint(GLFW_ALPHA_BITS, 8);
		glfwWindowHint(GLFW_DEPTH_BITS, 32);

		glfwWindowHint(GLFW_SAMPLES, 0); // (no msaa)
		glfwWindowHint(GLFW_DOUBLEBUFFER, GL_TRUE);

		glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API);
		glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, major);
		glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, minor);
		glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

		GLFWwindow* window = glfwCreateWindow(size.x, size.y, "PBC", nullptr, nullptr);
		if (!window)
		{
			glfwTerminate();
			glf::Error("Window creation failed");
			exit(-1);
		}
		glfwSetWindowPos(window, 64, 64);
		glfwMakeContextCurrent(window);
    	glfwSwapInterval(1);
    	glfwSetKeyCallback(window, keyboard);
		glfwSetWindowSizeCallback(window, reshape);
		glfwSetCursorPosCallback(window, motion);
		glfwSetMouseButtonCallback(window, mouse);
		glfwSetScrollCallback(window, wheel);

		glGetError();
		glf::init();
		ctx::ui = new glui::GlfwContext();
		ctx::ui->Initialize(size.x, size.y);

		KeyboardAdapter::window = window;

		// Render loop
		double previousInSecond = glfwGetTime();
		bool validRun = false;
		glEnable(GL_DEPTH_TEST);
		glEnable(GL_CULL_FACE);
		if (begin())
		{
			validRun = true;
			while (!glfwWindowShouldClose(window))
			{
				double currentInSecond = glfwGetTime();
				double dt = currentInSecond - previousInSecond;

				// Camera keyboard input are handled by pooling event rather than callback in order to have smoother response
				ctx::camera->KeyboardEvent((float)dt, KeyboardAdapter::evaluator);

				display();
				glfwSwapBuffers(window);
				glGetError(); // 'glutSwapBuffers' generates an here with OpenGL 3 > core profile ... :/

				glfwPollEvents();

				previousInSecond = currentInSecond;
			}
			end();
		}

    	glfwDestroyWindow(window);

		delete ctx::ui;
		return validRun;
	}
Ejemplo n.º 28
0
// Main entry point
int main (int argc, char** argv)
{
  std::string pathToThisFile=__FILE__;

  if(gDataPath.empty())
    gDataPath=rt::Math::getParentDirectoryFromFilePath(pathToThisFile);
  std::cerr<<"Using data path: "<<gDataPath<<std::endl;

  std::cerr<<"Use your mouse to rotate,pan and zoom the camera"<<std::endl;
  std::cerr<<"left mouse button + drag -> rotate"<<std::endl;
  std::cerr<<"middle mouse button + drag -> pan"<<std::endl;
  std::cerr<<"scroll wheel up / down -> zoom in / out"<<std::endl;

  if( !glfwInit() )
  {
    std::cerr<<"Failed to initialize GLFW\n"<<std::endl;
    return -1;
  }

  glfwSetErrorCallback(glfwErrorCallback);

  // Create the OpenGL window
  glfwWindowHint(GLFW_DEPTH_BITS, 16);
  glfwWindowHint(GLFW_SAMPLES, 4);

  //Those stop GLFW from initializing successfully?
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
  glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

  // Open OpenGL fullscreen window
  gGLFWWindow = glfwCreateWindow(gWidth,gHeight,"GLFW OpenGL Window",nullptr,nullptr);

  //// Open OpenGL fullscreen window
  //if( !glfwOpenWindow( gWidth, gHeight, 0,0,0,0, 16,0, GLFW_WINDOW ) )
  //{
  //  fprintf( stderr, "Failed to open GLFW window\n" );
  //  glfwTerminate();
  //  exit( EXIT_FAILURE );
  //}

  if(!gGLFWWindow)
  {
    std::cerr<<"Failed to open GLFW window\n"<<std::endl;
    glfwTerminate();
    return -1;
  }

  // Disable VSync (we want to get as high FPS as possible!)

  glfwMakeContextCurrent(gGLFWWindow);
  glfwSwapInterval( 1 );

  // Setting this is necessary for core profile (tested with MSVC 2013 x64, Windows 7)
  glewExperimental = GL_TRUE;
  // GLEW wraps all OpenGL functions and extensions
  GLenum err = glewInit();
  if(err != GLEW_OK)
  {
    std::cerr<<"Failed to initialize GLEW"<<std::endl;
    std::cerr<<(char*)glewGetErrorString(err)<<std::endl;
    glfwTerminate();
    return -1;
  }
  glGetError(); //GLEW might cause an 'invalid enum' error, safely ignore it?

  // Print OpenGL context information to console
  ogl::printContextInformation();

  // Perform our initialization (OpenGL states, shader, camera, geometry)
  if(!init())
    return -1;

  // Set the appropriate callback functions
  // Window resize callback function
  glfwSetFramebufferSizeCallback(gGLFWWindow,resizeCB);
  glfwSetMouseButtonCallback(gGLFWWindow,mouseCB);
  glfwSetScrollCallback(gGLFWWindow,wheelCB);
  glfwSetCursorPosCallback(gGLFWWindow,motionCB);


  while( !glfwWindowShouldClose(gGLFWWindow) )
  {
    // Get the current time (in milliseconds since program start)
    double t0 =glfwGetTime();

    // Clear frame and depth buffers
    glClearColor(gBackgroundColor[0],gBackgroundColor[1],gBackgroundColor[2], 1.f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // Draw...
    displayCB();

    // Hopefully there hasn't been any mistake?
    ogl::printOpenGLError();

    // Swap the rendering target with the frame buffer shown on the monitor
    glfwSwapBuffers(gGLFWWindow);

    glfwPollEvents() ;

    // Compute rendering time in seconds by taking difference to current time
    double t1=glfwGetTime();
    gLastFrameTime = float(t1-t0);
  }

  // Terminate OpenGL
  glfwTerminate();
  return 0;
}
Ejemplo n.º 29
0
Archivo: cube.c Proyecto: hialin/hialin
int main(void)
{
    glfwSetErrorCallback(error_callback);

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

    GLFWmonitor *monitor = glfwGetPrimaryMonitor();
    const GLFWvidmode *mode = glfwGetVideoMode(monitor);
    printf("monitor mode: %d, %d\n", mode->width, mode->height);

    // if DEBUG {
    //     glfw.WindowHint(glfw.OpenGLDebugContext, gl.TRUE)
    // }

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, 1);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

    GLFWwindow *window = glfwCreateWindow(mode->width, mode->height, "Hialin", NULL, NULL);
    if (!window) {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwSetKeyCallback(window, key_callback);

    glfwMakeContextCurrent(window);
    glfwSwapInterval(0);

    p_glBindFragDataLocation = (glBindFragDataLocation_t)glfwGetProcAddress("glBindFragDataLocation");
    if (!p_glBindFragDataLocation) {
        printf("\n failed glBindFragDataLocation");
        glfwTerminate();
        exit(EXIT_FAILURE);
    }
    p_glGenVertexArrays = (glGenVertexArrays_t)glfwGetProcAddress("glGenVertexArrays");
    if (!p_glGenVertexArrays) {
        printf("\n failed glGenVertexArrays");
        glfwTerminate();
        exit(EXIT_FAILURE);
    }
    p_glBindVertexArray = (glBindVertexArray_t)glfwGetProcAddress("glBindVertexArray");
    if (!p_glBindVertexArray) {
        printf("\n failed glBindVertexArray");
        glfwTerminate();
        exit(EXIT_FAILURE);
    }


    GLuint vsh = glCreateShader(GL_VERTEX_SHADER);
    {
        glShaderSource(vsh, 1, &vertex_shader_text, NULL);
        glCompileShader(vsh);
        int result;
        glGetShaderiv(vsh, GL_COMPILE_STATUS, &result );
        if (result == GL_FALSE) {
            int logLength;
            glGetShaderiv(vsh, GL_INFO_LOG_LENGTH, &logLength);
            char log[10*1024] = {0};
            glGetShaderInfoLog(vsh, logLength, NULL, log);
            printf("\nvertex shader compile: %s", log);
            glfwTerminate();
            exit(EXIT_FAILURE);
        }
    }
    glCheck();

    GLuint fsh = glCreateShader(GL_FRAGMENT_SHADER);
    {
        glShaderSource(fsh, 1, &fragment_shader_text, NULL);
        glCompileShader(fsh);
        int result;
        glGetShaderiv(fsh, GL_COMPILE_STATUS, &result);
        if (result == GL_FALSE) {
            int logLength;
            glGetShaderiv(fsh, GL_INFO_LOG_LENGTH, &logLength);
            char log[10*1024] = {0};
            glGetShaderInfoLog(fsh, logLength, NULL, log);
            printf("\nfragment shader compile: %s", log);
            glfwTerminate();
            exit(EXIT_FAILURE);
        }
    }
    glCheck();

    GLuint program = glCreateProgram();
    {
        glAttachShader(program, vsh);
        glAttachShader(program, fsh);
        glLinkProgram(program);
        int result;
        glGetProgramiv(program, GL_LINK_STATUS, &result);
        if (result == GL_FALSE) {
            int logLength;
            glGetProgramiv(program, GL_INFO_LOG_LENGTH, &logLength);
            char log[10*1024] = {0};
            glGetProgramInfoLog(program, logLength, NULL, log);
            printf("\nprogram link: \n%s", log);
            glfwTerminate();
            exit(EXIT_FAILURE);
        }
    }
    glCheck();
    glUseProgram(program);
    glCheck();

    GLint projectionU = glGetUniformLocation(program, "projection");

    mat4x4 camera;
    vec3 eye = {3, 3, 3}, center = {0, 0, 0}, up = {0, 1, 0};
    mat4x4_look_at(camera, eye, center, up);
    GLint cameraU = glGetUniformLocation(program, "camera");
    glUniformMatrix4fv(cameraU, 1, GL_FALSE, (const float*)camera);
    glCheck();

    mat4x4 model;
    mat4x4_identity(model);
    GLint modelU = glGetUniformLocation(program, "model");
    glUniformMatrix4fv(modelU, 1, GL_FALSE, (const float*)model);
    glCheck();

    GLint texU = glGetUniformLocation(program, "tex");
    glUniform1i(texU, 0);
    p_glBindFragDataLocation(program, 0, "outputColor");
    glCheck();

    // Load the texture
    // char *texturePath = "./Resources/code.png"
    // GLuint texture = MakeTexture(0, texturePath);
    GLuint texture = MakeTexture(0);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, texture);
    glCheck();

    // Configure the vertex data
    GLuint vao;
    p_glGenVertexArrays(1, &vao);
    p_glBindVertexArray(vao);
    glCheck();

    GLuint vbo;
    glGenBuffers(1, &vbo);
    glBindBuffer(GL_ARRAY_BUFFER, vbo);
    glBufferData(GL_ARRAY_BUFFER, sizeof(cube_vertices), cube_vertices, GL_STATIC_DRAW);
    glCheck();

    GLuint val = glGetAttribLocation(program, "vert");
    glEnableVertexAttribArray(val);
    glVertexAttribPointer(val, 3, GL_FLOAT, GL_FALSE, 5*4, (const void *)(0*4));
    glCheck();

    GLuint valTC = glGetAttribLocation(program, "vertTexCoord");
    glEnableVertexAttribArray(valTC);
    glVertexAttribPointer(valTC, 2, GL_FLOAT, GL_FALSE, 5*4, (const void *)(3*4));
    glCheck();

    // Configure global settings
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);
    glClearColor(0.0, 0.0, 0.0, 1.0);
    glCheck();

    long time0 = tick();

    float angle = 0.01;

    int width = 0, height = 0;
    int i = 0;
    while (!glfwWindowShouldClose(window))
    {
        int w, h;
        glfwGetFramebufferSize(window, &w, &h);
        if (w != width || h != height) {
            width = w;
            height = h;
            glViewport(0, 0, width, height);
            printf("buffer size: %d %d\n", w, h);
        }
        float ratio = width/(float)height;

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        mat4x4_rotate_Y(model, model, angle);

        mat4x4 projection;
        mat4x4_perspective(projection, 0.785, ratio, 0.1, 10.0); // 45 degrees == 0.785 radians

        glUniformMatrix4fv(projectionU, 1, GL_FALSE, (const float*)projection);
        glUniformMatrix4fv(modelU, 1, GL_FALSE, (const float*)model);

        for (int i = 0; i < 1*1000; i++) {
            glDrawArrays(GL_TRIANGLES, 0, 6*2*3); // 12 triangles
        }

        i++;
        if (i == 100) {
            printf("time for 100 frames: %ld\n", tick()-time0);
        } else if (i == 1000) {
            printf("time for 1000 frames: %ld\n", tick()-time0);
            break;
        }

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwDestroyWindow(window);

    glfwTerminate();
    exit(EXIT_SUCCESS);
}
Ejemplo n.º 30
0
int main(void)
{
	GLFWwindow* window;

	/* Initialize the library */
	if (!glfwInit())
		return -1;

    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    //glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    /* Create a windowed mode window and its OpenGL context */
	window = glfwCreateWindow(800, 600, "Hello World", NULL, NULL);
	if (!window)
	{
		glfwTerminate();
		return -1;
	}

	glfwSetScrollCallback(window, OnScroll);

	// GLFW settings
	glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
	glfwSetCursorPos(window, 0, 0);

	/* Make the window's context current */
	glfwMakeContextCurrent(window);

    glewExperimental = GL_TRUE; //stops glew crashing on OSX :-/
	if (glewInit() != GLEW_OK)
	{
		glfwTerminate();
		return -1;
	}

	// print out some info about the graphics drivers
	std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl;
	std::cout << "GLSL version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl;
	std::cout << "Vendor: " << glGetString(GL_VENDOR) << std::endl;
	std::cout << "Renderer: " << glGetString(GL_RENDERER) << std::endl;

	// OpenGL settings
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LESS);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	LoadWoodenCrateAsset();

	CreateInstances();

	//glClearColor(0.196078431372549f, 0.3137254901960784f, 0.5882352941176471f, 1);
	glClearColor(0.0f, 0.0f, 0.0f, 1);


	gCamera.setPosition(glm::vec3(-4, 0, 17));
	gCamera.setViewportAspectRatio(800.0f / 600.0f);
	gCamera.setNearAndFarPlanes(0.5f, 100.0f);

	gLight.position = glm::vec3(-4, 0, 4);
	gLight.intensities = glm::vec3(1, 1, 1); //white
	gLight.attenuation = 0.2f;
	gLight.ambientCoefficient = 0.005f;

	double lastTime = glfwGetTime();
	while (!glfwWindowShouldClose(window))
	{
		/* Poll for and process events */
		glfwPollEvents();

		double thisTime = glfwGetTime();
		Update((float)(thisTime - lastTime), window);
		lastTime = thisTime;

		Render(window);

		// check for errors
		GLenum error = glGetError();
		if (error != GL_NO_ERROR)
			std::cerr << "OpenGL Error " << error << std::endl;

		//exit program if escape key is pressed
		if (glfwGetKey(window, GLFW_KEY_ESCAPE))
			glfwSetWindowShouldClose(window, GL_TRUE);
	}

	glfwTerminate();
	return 0;
}