Esempio n. 1
0
int main (int argc, char** argv) {
    // Initialize GLUT
    glutInit(&argc, argv);
    //glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);

	// Initialize GLFW
	if ( !glfwInit()) {
		std::cerr << "Failed to initialize GLFW! I'm out!" << std::endl;
		exit(-1);
	}

	// Use OpenGL 3.2 core profile
    /*
	glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
	glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
	glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3);
	glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2);
    */

	// Open a window and attach an OpenGL rendering context to the window surface
	if( !glfwOpenWindow(500, 500, 8, 8, 8, 0, 0, 0, GLFW_WINDOW)) {
		std::cerr << "Failed to open a window! I'm out!" << std::endl;
		glfwTerminate();
		exit(-1);
	}

	// Register a callback function for window resize events
	glfwSetWindowSizeCallback( window_resized );

	// Register a callback function for keyboard pressed events
	glfwSetKeyCallback(keyboard);	

	// Print the OpenGL version
	int major, minor, rev;
	glfwGetGLVersion(&major, &minor, &rev);
	std::cout << "OpenGL - " << major << "." << minor << "." << rev << std::endl;

	// Initialize GLEW
	glewExperimental = GL_TRUE;
	if(glewInit() != GLEW_OK) {
		std::cerr << "Failed to initialize GLEW! I'm out!" << std::endl;
		glfwTerminate();
		exit(-1);
	}

	// Create a rendering loop
	int running = GL_TRUE;

	while(running) {
		// Display scene
		display();

		// Pool for events
		glfwPollEvents();
		// Check if the window was closed
		running = glfwGetWindowParam(GLFW_OPENED);
	}

	// Terminate GLFW
	glfwTerminate();

	return 0;
}
Esempio n. 2
0
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
	LPSTR lpCmdLine, int nCmdShow)
{
	GameState gameState = {};
	gameState.RenderState = 0;
	gameState.State = 1;
	gameState.PlayerX = 200.0;
	gameState.PlayerY = 450.0;

	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(gameState.ScreenWidth, gameState.ScreenHeight, "Neighbors", NULL, NULL);
	glfwMakeContextCurrent(window);

	glewExperimental = GL_TRUE; 

	glewInit();
	glGetError();

	glfwSetKeyCallback(window, processWindowsCallback);

	// OpenGL configuration
	glViewport(0, 0, gameState.ScreenWidth, gameState.ScreenHeight); // Where in the window to render.
	glEnable(GL_CULL_FACE);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	// Load shaders
	ResourceManager::LoadShader("shaders/sprite.vs", "shaders/sprite.frag", nullptr, "sprite");
	// Configure shaders
	glm::mat4 projection = glm::ortho(0.0f, static_cast<GLfloat>(gameState.ScreenWidth),
		static_cast<GLfloat>(gameState.ScreenHeight), 0.0f, -1.0f, 1.0f);
	ResourceManager::GetShader("sprite").Use().SetInteger("image", 0);
	ResourceManager::GetShader("sprite").SetMatrix4("projection", projection);
	// Set render-specific controls
	Renderer = new SpriteRenderer(ResourceManager::GetShader("sprite"));
	AnimateRenderer = new AnimatedSpriteRenderer(ResourceManager::GetShader("sprite"));
	// Load textures
	ResourceManager::LoadTexture("textures/download.png", GL_TRUE, "face");
	ResourceManager::LoadTexture("textures/download.jpg", GL_TRUE, "other");
	ResourceManager::LoadTexture("textures/grass.png", GL_TRUE, "grass");
	ResourceManager::LoadTexture("textures/floor.png", GL_TRUE, "floor");
	ResourceManager::LoadTexture("textures/back_wall.png", GL_TRUE, "backwall");
	ResourceManager::LoadSpriteSheet("textures/sonic.png", GL_TRUE, "sonic");

	RenderList List;

	/* Loop until the user closes the window */
	while (!glfwWindowShouldClose(window))
	{
		// Clear IsDowns to false for incoming input and update WasDown's.
		for (int ButtonIndex = 0; ButtonIndex < ArrayCount(GlobalInput.Controller.Buttons); ButtonIndex++)
		{
			GlobalInput.Controller.Buttons[ButtonIndex].WasDown = GlobalInput.Controller.Buttons[ButtonIndex].IsDown;
			GlobalInput.Controller.Buttons[ButtonIndex].IsDown = false;
		}

		// Controller input handeling.
		if (glfwJoystickPresent(GLFW_JOYSTICK_1))
		{
			int countButtons;
			const unsigned char *button = glfwGetJoystickButtons(GLFW_JOYSTICK_1, &countButtons);
			for (int i = 0; i < countButtons; i++)
			{
				if (button[i] == GLFW_PRESS)
				{
					GlobalInput.Controller.Buttons[i].IsDown = true;
				}
			}

			int countAxes;
			const float *axes = glfwGetJoystickAxes(GLFW_JOYSTICK_1, &countAxes);
			for (int i = 0; i < countAxes; i++)
			{
				GlobalInput.Controller.Axes[i] = axes[i];
			}
		}

		/* Poll for and process events */
		glfwPollEvents();
		if (gameState.State == 0)
			glfwSetWindowShouldClose(window, 1);

		/* Render here */

		GameUpdateAndRender(&gameState, &GlobalInput, &List);

		float cameraPosX = gameState.PlayerX - 500;
		float cameraPosY = gameState.PlayerY - 400;

		glm::mat4 projection = glm::ortho(cameraPosX, cameraPosX + static_cast<GLfloat>(gameState.ScreenWidth),
			cameraPosY + static_cast<GLfloat>(gameState.ScreenHeight), cameraPosY, -1.0f, 1.0f);
		ResourceManager::GetShader("sprite").Use().SetInteger("image", 0);
		ResourceManager::GetShader("sprite").SetMatrix4("projection", projection);

		glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
		glClear(GL_COLOR_BUFFER_BIT);

		while (!List.isEmpty)
		{
			RenderObject * obj = List.Pop();
			Renderer->DrawSprite(ResourceManager::GetTexture(obj->name),
				obj->position, obj->scale, 0.0f, obj->color);
			free(obj);
		}

		AnimateRenderer->DrawSprite(ResourceManager::GetSpriteSheet("sonic"), glm::vec2(cameraPosX, cameraPosY), glm::vec2(64, 72), 0.0f, glm::vec3(1.0f, 1.0f, 1.0f), gameState.RenderState);

		/* Swap front and back buffers */
		glfwSwapBuffers(window);
	}

	glfwTerminate();
	return 0;
}
//Method initializes OpenGL for rendering to a window/viewport
bool engine_3d::Init()
{
	/// We need our GLFW function pointers to be assigned, if this process fails we cannot continue
	if ( !glfwInit() )
	{
		return false;
	}

	/// Here we query how much sampling is possible and set that to be used if possible
	GLint samples = 8;
	glGetIntegerv( GL_SAMPLES, &samples );
	if ( samples )
	{
		glEnable( GL_MULTISAMPLE );
	}
	glfwWindowHint( GLFW_SAMPLES, samples );

	GLFWmonitor** monitors;
	int count;

	monitors = glfwGetMonitors( &count );
	const GLFWvidmode* mode = glfwGetVideoMode( glfwGetPrimaryMonitor() );

	///Create a window of a particular type
	switch ( winMode )
	{
		case engine_WindowModel::FULLSCREEN:

			window = glfwCreateWindow( mode->width, mode->height, "Fullscreen", glfwGetPrimaryMonitor(), NULL );
			screenHeight = mode->height;
			screenWidth = mode->width;
			break;

		case engine_WindowModel::DECORATEDWINDOW:

			window = glfwCreateWindow( screenWidth, screenHeight, "Decorated Window", NULL, NULL );
			break;

		case engine_WindowModel::BORDERLESSFULLSCREEN:

			glfwWindowHint( GLFW_DECORATED, false );

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

			window = glfwCreateWindow( mode->width, mode->height, "Borderless Fullscreen", NULL, NULL );
			screenHeight = mode->height;
			screenWidth = mode->width;
			break;
	}

	/// If creating the window failed we need to terminate
	if ( !window )
	{
		glfwTerminate();
		return false;
	}
	/// Associates this window with OpenGL's rendering (I believe)
	glfwMakeContextCurrent( window );

	/// Sets our input processing function, all input will be passed to this function
	//glfwSetScrollCallback( window, scroll_callback );
	glfwSetKeyCallback( window, key_callback );
	glfwSetCursorPosCallback( window, cursor_position_callback );
	glfwSetMouseButtonCallback( window, mouse_button_callback );

	/// start GLEW extension handler
	glewExperimental = GL_TRUE;

	///Initialize OpenGL functions
	glewInit();
	const GLubyte* renderer = glGetString( GL_RENDERER ); /// get renderer string
	const GLubyte* version = glGetString( GL_VERSION ); /// version as a string
	///oLog( Level::Info ) << "Renderer: " << renderer;
	///oLog( Level::Info ) << "OpenGL version supported: " << version;

	projectionMatrix = glm::mat4( 1.f );
	viewMatrix = glm::mat4( 1.f );

	glEnable( GL_CULL_FACE );
	glCullFace( GL_BACK );
	glFrontFace( GL_CCW );

	glEnable( GL_BLEND );
	glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
	
	glClearColor( 0.0f, 0.0f, 0.0f, 0.0f );	///clear colour: r,g,b,a 	
	glfwSwapInterval( 1 ); ///cap FPS

	currentDC = wglGetCurrentDC();
	currentContext = wglGetCurrentContext();

	return true;
}
Esempio n. 4
0
int main(int argc, char *argv[]) {
  GLFWwindow* window;

  if(!glfwInit()) {
    return -1;
  }

  GLFWmonitor* monitor  = glfwGetPrimaryMonitor();
  const GLFWvidmode* vidmode = glfwGetVideoMode(monitor);

  window = glfwCreateWindow(vidmode->width, vidmode->height, "Box Fractal a.k.a Anticross-stitch curve", monitor, NULL);
  if(!window) {
    glfwTerminate();
    return -1;
  }

  glfwSetKeyCallback(window, key_callback);
  glfwMakeContextCurrent(window);

  int width, height;
  glfwGetFramebufferSize(window, &width, &height);
  float x = 0.0f;
  float y = 0.0f;

  glViewport(0, 0, width, height);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  glOrtho(0.0f, width, 0.0f, height, 0.0, 1.0f);
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity();

  std::string lrep = boxFractalLSystemRepresentation();

  while(!glfwWindowShouldClose(window)) {
    x = width / 3.5;
    y = height - 200.0f;
    glClear(GL_COLOR_BUFFER_BIT);
    glPushMatrix();
    for(std::string::iterator it = lrep.begin(); it != lrep.end(); it++) {
      if(*it == 'F') {
        glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
        glLineWidth(4.0f);
        
        GLfloat vertices[] = {x, y, x + LINE_LENGTH, y};
        glEnableClientState(GL_VERTEX_ARRAY);
        glVertexPointer(2, GL_FLOAT, 0, vertices);
        glDrawArrays(GL_LINES, 0, 4);
        glDisableClientState(GL_VERTEX_ARRAY);
        x = x + LINE_LENGTH;
      }

      if(*it == '-' || *it == '+') {
        glTranslatef(x, y, 0.0f);
        x = 0.0f;
        y = 0.0f;
        float angle = ((*it == '-') ? -90.0f : 90.0f);
        glRotatef(angle, 0.0f, 0.0f, 1.0f);
      }
    }
    glPopMatrix();
    glfwSwapBuffers(window);
    glfwPollEvents();
  }

  glfwTerminate();
  return 0;
}
// The MAIN function, from here we start the application and run the game loop
int main4()
{
    // Init GLFW
    glfwInit();
    // Set all the required options for GLFW
    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);
    
    // Create a GLFWwindow object that we can use for GLFW's functions
    GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr);
    glfwMakeContextCurrent(window);
    
    // Set the required callback functions
    glfwSetKeyCallback(window, key_callback);
    
    // Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions
    glewExperimental = GL_TRUE;
    // Initialize GLEW to setup the OpenGL Function pointers
    glewInit();
    
    // Define the viewport dimensions
    glViewport(0, 0, WIDTH, HEIGHT);
    
    
    // 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[] = {
        // Positions
        0.5f, -0.5f, 0.0f,  // Bottom Right
        -0.5f, -0.5f, 0.0f,  // Bottom Left
        0.0f,  0.5f, 0.0f   // Top
    };
    GLuint VBO, VAO;
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);
    // 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);
    
    // Position attribute
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(0);
    
    glBindVertexArray(0); // Unbind VAO
    
    
    // Game loop
    while (!glfwWindowShouldClose(window))
    {
        // Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions
        glfwPollEvents();
        
        // Render
        // Clear the colorbuffer
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);
        
        // Be sure to activate the shader
        glUseProgram(shaderProgram);
        
        // Update the uniform color
        GLfloat timeValue = glfwGetTime();
        GLfloat greenValue = (sin(timeValue) / 2) + 0.5;
        GLint vertexColorLocation = glGetUniformLocation(shaderProgram, "ourColor");
        glUniform4f(vertexColorLocation, 0.0f, greenValue, 0.0f, 1.0f);
        
        // Draw the triangle
        glBindVertexArray(VAO);
        glDrawArrays(GL_TRIANGLES, 0, 3);
        glBindVertexArray(0);
        
        // Swap the screen buffers
        glfwSwapBuffers(window);
    }
    // Properly de-allocate all resources once they've outlived their purpose
    glDeleteVertexArrays(1, &VAO);
    glDeleteBuffers(1, &VBO);
    // Terminate GLFW, clearing any resources allocated by GLFW.
    glfwTerminate();
    return 0;
}
// -----------------------------------------------------------------------------
WindowGLFW::WindowGLFW(int width, int height, bool invisible)
    : WindowBase(width, height)
{
    if (glfwInit() == 0) {
        std::cout << "WindowGLFW: Failed initialize GLFW " << std::endl;
        throw std::exception();
    }

    // Create a windowed mode window and its OpenGL context
    glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);
    glfwWindowHint(GLFW_SAMPLES, 0);     // Disable MSAA
    glfwWindowHint(GLFW_DEPTH_BITS, 24); // Enable

    if (invisible) {
         glfwWindowHint(GLFW_VISIBLE, GL_FALSE);
    }

#ifdef _GLESMODE
    glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
#else
    glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
#endif

    m_hWindow = glfwCreateWindow(width, height, "GLFW", NULL, NULL);

    if (!m_hWindow) {
        glfwTerminate();
        std::cout << "WindowGLFW: Failed create window" << std::endl;
        throw std::exception();
    }

    glfwMakeContextCurrent(m_hWindow);

#ifdef USE_GLEW
    // dwRenderer requires glewExperimental
    // because it calls glGenVertexArrays()
    glewExperimental = GL_TRUE;
    GLenum err = glewInit();
    if (err != GLEW_OK) {
        glfwDestroyWindow(m_hWindow);
        glfwTerminate();
        std::cout << "WindowGLFW: Failed to init GLEW: " << glewGetErrorString(err) << std::endl;
        throw std::exception();
    }
    glGetError(); // clears error on init
#endif

    // No vsync
    glfwSwapInterval(0);

    glfwSetInputMode(m_hWindow, GLFW_STICKY_KEYS, GL_FALSE);

    //Callbacks
    glfwSetWindowUserPointer(m_hWindow, this);
    glfwSetKeyCallback(m_hWindow, [](GLFWwindow *win, int key, int scancode, int action, int mods) {
        WindowGLFW *window = reinterpret_cast<WindowGLFW *>(glfwGetWindowUserPointer(win));
        window->onKeyCallback(key, scancode, action, mods);
    });
    glfwSetMouseButtonCallback(m_hWindow, [](GLFWwindow *win, int button, int action, int mods) {
        WindowGLFW *window = reinterpret_cast<WindowGLFW *>(glfwGetWindowUserPointer(win));
        window->onMouseButtonCallback(button, action, mods);
    });
    glfwSetCursorPosCallback(m_hWindow, [](GLFWwindow *win, double x, double y) {
        WindowGLFW *window = reinterpret_cast<WindowGLFW *>(glfwGetWindowUserPointer(win));
        window->onMouseMoveCallback(x, y);
    });
    glfwSetScrollCallback(m_hWindow, [](GLFWwindow *win, double dx, double dy) {
        WindowGLFW *window = reinterpret_cast<WindowGLFW *>(glfwGetWindowUserPointer(win));
        window->onMouseWheelCallback(dx, dy);
    });
    glfwSetFramebufferSizeCallback(m_hWindow, [](GLFWwindow *win, int width, int height) {
        WindowGLFW *window = reinterpret_cast<WindowGLFW *>(glfwGetWindowUserPointer(win));
        window->onResizeWindowCallback(width, height);
    });
}
Esempio n. 7
0
GLFWOSPRayWindow::GLFWOSPRayWindow(const ospcommon::vec2i &windowSize,
                                   const ospcommon::box3f &worldBounds,
                                   OSPModel model,
                                   OSPRenderer renderer)
    : windowSize(windowSize),
      worldBounds(worldBounds),
      model(model),
      renderer(renderer)
{
  if (activeWindow != nullptr)
    throw std::runtime_error("Cannot create more than one GLFWOSPRayWindow!");

  activeWindow = this;

  // initialize GLFW
  if (!glfwInit())
    throw std::runtime_error("Failed to initialize GLFW!");

  // create GLFW window
  glfwWindow = glfwCreateWindow(
      windowSize.x, windowSize.y, "OSPRay Tutorial", NULL, NULL);

  if (!glfwWindow) {
    glfwTerminate();
    throw std::runtime_error("Failed to create GLFW window!");
  }

  // make the window's context current
  glfwMakeContextCurrent(glfwWindow);

  ImGui_ImplGlfwGL3_Init(glfwWindow, true);

  // set initial OpenGL state
  glEnable(GL_TEXTURE_2D);
  glDisable(GL_LIGHTING);

  // create OpenGL frame buffer texture
  glGenTextures(1, &framebufferTexture);
  glEnable(GL_TEXTURE_2D);
  glBindTexture(GL_TEXTURE_2D, framebufferTexture);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);

  // set GLFW callbacks
  glfwSetFramebufferSizeCallback(
      glfwWindow, [](GLFWwindow *, int newWidth, int newHeight) {
        activeWindow->reshape(ospcommon::vec2i{newWidth, newHeight});
      });

  glfwSetCursorPosCallback(glfwWindow, [](GLFWwindow *, double x, double y) {
    ImGuiIO &io = ImGui::GetIO();
    if (!io.WantCaptureMouse)
      activeWindow->motion(ospcommon::vec2f{float(x), float(y)});
  });

  glfwSetKeyCallback(glfwWindow,
                     [](GLFWwindow *, int key, int, int action, int) {
                       if (action == GLFW_PRESS) {
                         switch (key) {
                         case GLFW_KEY_G:
                           activeWindow->showUi = !(activeWindow->showUi);
                           break;
                         }
                       }
                     });

  // OSPRay setup

  // set the model on the renderer
  ospSetObject(renderer, "model", model);

  // create the arcball camera model
  arcballCamera = std::unique_ptr<ArcballCamera>(
      new ArcballCamera(worldBounds, windowSize));

  // create camera
  camera = ospNewCamera("perspective");
  ospSetf(camera, "aspect", windowSize.x / float(windowSize.y));

  ospSetVec3f(camera,
              "pos",
              osp::vec3f{arcballCamera->eyePos().x,
                         arcballCamera->eyePos().y,
                         arcballCamera->eyePos().z});
  ospSetVec3f(camera,
              "dir",
              osp::vec3f{arcballCamera->lookDir().x,
                         arcballCamera->lookDir().y,
                         arcballCamera->lookDir().z});
  ospSetVec3f(camera,
              "up",
              osp::vec3f{arcballCamera->upDir().x,
                         arcballCamera->upDir().y,
                         arcballCamera->upDir().z});

  ospCommit(camera);

  // set camera on the renderer
  ospSetObject(renderer, "camera", camera);

  // finally, commit the renderer
  ospCommit(renderer);

  // trigger window reshape events with current window size
  glfwGetFramebufferSize(glfwWindow, &this->windowSize.x, &this->windowSize.y);
  reshape(this->windowSize);
}
Esempio n. 8
0
int main(int argc, char **argv) {
    srand(time(NULL));
    rand();
    if (argc == 2 || argc == 3) {
        char *hostname = argv[1];
        int port = DEFAULT_PORT;
        if (argc == 3) {
            port = atoi(argv[2]);
        }
        db_disable();
        client_enable();
        client_connect(hostname, port);
        client_start();
    }
    if (!glfwInit()) {
        return -1;
    }
    create_window();
    if (!window) {
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);
    glfwSwapInterval(VSYNC);
    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
    glfwSetKeyCallback(window, on_key);
    glfwSetCharCallback(window, on_char);
    glfwSetMouseButtonCallback(window, on_mouse_button);
    glfwSetScrollCallback(window, on_scroll);

    #ifndef __APPLE__
        if (glewInit() != GLEW_OK) {
            return -1;
        }
    #endif

    if (db_init()) {
        return -1;
    }

    glEnable(GL_CULL_FACE);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_LINE_SMOOTH);
    glLogicOp(GL_INVERT);
    glClearColor(0.53, 0.81, 0.92, 1.00);

    GLuint texture;
    glGenTextures(1, &texture);
    glActiveTexture(GL_TEXTURE0);
    glBindTexture(GL_TEXTURE_2D, texture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    load_png_texture("texture.png");

    GLuint font;
    glGenTextures(1, &font);
    glActiveTexture(GL_TEXTURE1);
    glBindTexture(GL_TEXTURE_2D, font);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    load_png_texture("font.png");

    GLuint block_program = load_program(
        "shaders/block_vertex.glsl", "shaders/block_fragment.glsl");
    GLuint matrix_loc = glGetUniformLocation(block_program, "matrix");
    GLuint camera_loc = glGetUniformLocation(block_program, "camera");
    GLuint sampler_loc = glGetUniformLocation(block_program, "sampler");
    GLuint timer_loc = glGetUniformLocation(block_program, "timer");
    GLuint position_loc = glGetAttribLocation(block_program, "position");
    GLuint normal_loc = glGetAttribLocation(block_program, "normal");
    GLuint uv_loc = glGetAttribLocation(block_program, "uv");

    GLuint line_program = load_program(
        "shaders/line_vertex.glsl", "shaders/line_fragment.glsl");
    GLuint line_matrix_loc = glGetUniformLocation(line_program, "matrix");
    GLuint line_position_loc = glGetAttribLocation(line_program, "position");

    GLuint text_program = load_program(
        "shaders/text_vertex.glsl", "shaders/text_fragment.glsl");
    GLuint text_matrix_loc = glGetUniformLocation(text_program, "matrix");
    GLuint text_sampler_loc = glGetUniformLocation(text_program, "sampler");
    GLuint text_position_loc = glGetAttribLocation(text_program, "position");
    GLuint text_uv_loc = glGetAttribLocation(text_program, "uv");

    GLuint item_position_buffer = 0;
    GLuint item_normal_buffer = 0;
    GLuint item_uv_buffer = 0;
    int previous_block_type = 0;
    char messages[MAX_MESSAGES][TEXT_BUFFER_SIZE] = {0};
    int message_index = 0;

    Chunk chunks[MAX_CHUNKS];
    int chunk_count = 0;

    Player players[MAX_PLAYERS];
    int player_count = 0;

    FPS fps = {0, 0};
    float matrix[16];
    float x = (rand_double() - 0.5) * 10000;
    float z = (rand_double() - 0.5) * 10000;
    float y = 0;
    float dy = 0;
    float rx = 0;
    float ry = 0;
    double px = 0;
    double py = 0;

    int loaded = db_load_state(&x, &y, &z, &rx, &ry);
    ensure_chunks(chunks, &chunk_count, x, y, z, 1);
    if (!loaded) {
        y = highest_block(chunks, chunk_count, x, z) + 2;
    }

    glfwGetCursorPos(window, &px, &py);
    double previous = glfwGetTime();
    while (!glfwWindowShouldClose(window)) {
        int width, height;
        glfwGetFramebufferSize(window, &width, &height);
        glViewport(0, 0, width, height);

        update_fps(&fps, SHOW_FPS);
        double now = glfwGetTime();
        double dt = MIN(now - previous, 0.2);
        previous = now;

        if (exclusive && (px || py)) {
            double mx, my;
            glfwGetCursorPos(window, &mx, &my);
            float m = 0.0025;
            rx += (mx - px) * m;
            ry -= (my - py) * m;
            if (rx < 0) {
                rx += RADIANS(360);
            }
            if (rx >= RADIANS(360)){
                rx -= RADIANS(360);
            }
            ry = MAX(ry, -RADIANS(90));
            ry = MIN(ry, RADIANS(90));
            px = mx;
            py = my;
        }
        else {
            glfwGetCursorPos(window, &px, &py);
        }

        int sz = 0;
        int sx = 0;
        if (!typing) {
            float m = dt * 1.0;
            ortho = glfwGetKey(window, CRAFT_KEY_ORTHO);
            fov = glfwGetKey(window, CRAFT_KEY_ZOOM) ? 15.0 : 65.0;
            if (glfwGetKey(window, CRAFT_KEY_QUIT)) break;
            if (glfwGetKey(window, CRAFT_KEY_FORWARD)) sz--;
            if (glfwGetKey(window, CRAFT_KEY_BACKWARD)) sz++;
            if (glfwGetKey(window, CRAFT_KEY_LEFT)) sx--;
            if (glfwGetKey(window, CRAFT_KEY_RIGHT)) sx++;
            if (glfwGetKey(window, GLFW_KEY_LEFT)) rx -= m;
            if (glfwGetKey(window, GLFW_KEY_RIGHT)) rx += m;
            if (glfwGetKey(window, GLFW_KEY_UP)) ry += m;
            if (glfwGetKey(window, GLFW_KEY_DOWN)) ry -= m;
        }
        float vx, vy, vz;
        get_motion_vector(flying, sz, sx, rx, ry, &vx, &vy, &vz);
        if (!typing) {
            if (glfwGetKey(window, CRAFT_KEY_JUMP)) {
                if (flying) {
                    vy = 1;
                }
                else if (dy == 0) {
                    dy = 8;
                }
            }
            if (glfwGetKey(window, CRAFT_KEY_XM)) {
                vx = -1; vy = 0; vz = 0;
            }
            if (glfwGetKey(window, CRAFT_KEY_XP)) {
                vx = 1; vy = 0; vz = 0;
            }
            if (glfwGetKey(window, CRAFT_KEY_YM)) {
                vx = 0; vy = -1; vz = 0;
            }
            if (glfwGetKey(window, CRAFT_KEY_YP)) {
                vx = 0; vy = 1; vz = 0;
            }
            if (glfwGetKey(window, CRAFT_KEY_ZM)) {
                vx = 0; vy = 0; vz = -1;
            }
            if (glfwGetKey(window, CRAFT_KEY_ZP)) {
                vx = 0; vy = 0; vz = 1;
            }
        }
        float speed = flying ? 20 : 5;
        int step = 8;
        float ut = dt / step;
        vx = vx * ut * speed;
        vy = vy * ut * speed;
        vz = vz * ut * speed;
        for (int i = 0; i < step; i++) {
            if (flying) {
                dy = 0;
            }
            else {
                dy -= ut * 25;
                dy = MAX(dy, -250);
            }
            x += vx;
            y += vy + dy * ut;
            z += vz;
            if (collide(chunks, chunk_count, 2, &x, &y, &z)) {
                dy = 0;
            }
        }
        if (y < 0) {
            y = highest_block(chunks, chunk_count, x, z) + 2;
        }

        if (left_click) {
            left_click = 0;
            int hx, hy, hz;
            int hw = hit_test(chunks, chunk_count, 0, x, y, z, rx, ry,
                &hx, &hy, &hz);
            if (hy > 0 && is_destructable(hw)) {
                set_block(chunks, chunk_count, hx, hy, hz, 0);
                int above = get_block(chunks, chunk_count, hx, hy + 1, hz);
                if (is_plant(above)) {
                    set_block(chunks, chunk_count, hx, hy + 1, hz, 0);
                }
            }
        }

        if (right_click) {
            right_click = 0;
            int hx, hy, hz;
            int hw = hit_test(chunks, chunk_count, 1, x, y, z, rx, ry,
                &hx, &hy, &hz);
            if (is_obstacle(hw)) {
                if (!player_intersects_block(2, x, y, z, hx, hy, hz)) {
                    set_block(chunks, chunk_count, hx, hy, hz, block_type);
                }
            }
        }

        if (middle_click) {
            middle_click = 0;
            int hx, hy, hz;
            int hw = hit_test(chunks, chunk_count, 0, x, y, z, rx, ry,
                &hx, &hy, &hz);
            if (is_selectable(hw)) {
                block_type = hw;
            }
        }

        if (teleport) {
            teleport = 0;
            if (player_count) {
                int index = rand_int(player_count);
                Player *player = players + index;
                x = player->x; y = player->y; z = player->z;
                rx = player->rx; ry = player->ry;
                ensure_chunks(chunks, &chunk_count, x, y, z, 1);
            }
        }

        client_position(x, y, z, rx, ry);
        char buffer[RECV_BUFFER_SIZE];
        while (client_recv(buffer, RECV_BUFFER_SIZE)) {
            float ux, uy, uz, urx, ury;
            if (sscanf(buffer, "U,%*d,%f,%f,%f,%f,%f",
                &ux, &uy, &uz, &urx, &ury) == 5)
            {
                x = ux; y = uy; z = uz; rx = urx; ry = ury;
                ensure_chunks(chunks, &chunk_count, x, y, z, 1);
                y = highest_block(chunks, chunk_count, x, z) + 2;
            }
            int bp, bq, bx, by, bz, bw;
            if (sscanf(buffer, "B,%d,%d,%d,%d,%d,%d",
                &bp, &bq, &bx, &by, &bz, &bw) == 6)
            {
                _set_block(chunks, chunk_count, bp, bq, bx, by, bz, bw);
                if (player_intersects_block(2, x, y, z, bx, by, bz)) {
                    y = highest_block(chunks, chunk_count, x, z) + 2;
                }
            }
            int pid;
            float px, py, pz, prx, pry;
            if (sscanf(buffer, "P,%d,%f,%f,%f,%f,%f",
                &pid, &px, &py, &pz, &prx, &pry) == 6)
            {
                Player *player = find_player(players, player_count, pid);
                if (!player && player_count < MAX_PLAYERS) {
                    player = players + player_count;
                    player_count++;
                    player->id = pid;
                    player->position_buffer = 0;
                    player->normal_buffer = 0;
                    player->uv_buffer = 0;
                }
                if (player) {
                    update_player(player, px, py, pz, prx, pry);
                }
            }
            if (sscanf(buffer, "D,%d", &pid) == 1) {
                delete_player(players, &player_count, pid);
            }
            if (buffer[0] == 'T' && buffer[1] == ',') {
                char *text = buffer + 2;
                printf("%s\n", text);
                snprintf(
                    messages[message_index], TEXT_BUFFER_SIZE, "%s", text);
                message_index = (message_index + 1) % MAX_MESSAGES;
            }
        }

        int p = chunked(x);
        int q = chunked(z);
        ensure_chunks(chunks, &chunk_count, x, y, z, 0);

        // RENDER 3-D SCENE //

        glClear(GL_COLOR_BUFFER_BIT);
        glClear(GL_DEPTH_BUFFER_BIT);
        set_matrix_3d(matrix, width, height, x, y, z, rx, ry, fov, ortho);

        // render chunks
        glUseProgram(block_program);
        glUniformMatrix4fv(matrix_loc, 1, GL_FALSE, matrix);
        glUniform3f(camera_loc, x, y, z);
        glUniform1i(sampler_loc, 0);
        glUniform1f(timer_loc, glfwGetTime());
        for (int i = 0; i < chunk_count; i++) {
            Chunk *chunk = chunks + i;
            if (chunk_distance(chunk, p, q) > RENDER_CHUNK_RADIUS) {
                continue;
            }
            if (y < 100 && !chunk_visible(chunk, matrix)) {
                continue;
            }
            draw_chunk(chunk, position_loc, normal_loc, uv_loc);
        }

        // render players
        for (int i = 0; i < player_count; i++) {
            Player *player = players + i;
            draw_player(player, position_loc, normal_loc, uv_loc);
        }

        // render focused block wireframe
        int hx, hy, hz;
        int hw = hit_test(
            chunks, chunk_count, 0, x, y, z, rx, ry, &hx, &hy, &hz);
        if (is_obstacle(hw)) {
            glUseProgram(line_program);
            glLineWidth(1);
            glEnable(GL_COLOR_LOGIC_OP);
            glUniformMatrix4fv(line_matrix_loc, 1, GL_FALSE, matrix);
            GLuint wireframe_buffer = gen_wireframe_buffer(hx, hy, hz, 0.51);
            draw_lines(wireframe_buffer, line_position_loc, 3, 48);
            glDeleteBuffers(1, &wireframe_buffer);
            glDisable(GL_COLOR_LOGIC_OP);
        }

        // RENDER 2-D HUD PARTS //

        glClear(GL_DEPTH_BUFFER_BIT);
        set_matrix_2d(matrix, width, height);

        // render crosshairs
        glUseProgram(line_program);
        glLineWidth(4);
        glEnable(GL_COLOR_LOGIC_OP);
        glUniformMatrix4fv(line_matrix_loc, 1, GL_FALSE, matrix);
        GLuint crosshair_buffer = gen_crosshair_buffer(width, height);
        draw_lines(crosshair_buffer, line_position_loc, 2, 4);
        glDeleteBuffers(1, &crosshair_buffer);
        glDisable(GL_COLOR_LOGIC_OP);

        // render text
        glUseProgram(text_program);
        glUniformMatrix4fv(text_matrix_loc, 1, GL_FALSE, matrix);
        glUniform1i(text_sampler_loc, 1);
        char text_buffer[1024];
        float ts = 12;
        float tx = ts / 2;
        float ty = height - ts;
        snprintf(
            text_buffer, 1024, "%d, %d, %.2f, %.2f, %.2f [%d, %d]",
            p, q, x, y, z, player_count, chunk_count);
        print(
            text_position_loc, text_uv_loc,
            tx, ty, ts, text_buffer);
        for (int i = 0; i < MAX_MESSAGES; i++) {
            int index = (message_index + i) % MAX_MESSAGES;
            if (strlen(messages[index])) {
                ty -= ts * 2;
                print(
                    text_position_loc, text_uv_loc,
                    tx, ty, ts, messages[index]);
            }
        }
        if (typing) {
            ty -= ts * 2;
            snprintf(text_buffer, 1024, "> %s", typing_buffer);
            print(
                text_position_loc, text_uv_loc,
                tx, ty, ts, text_buffer);
        }

        // RENDER 3-D HUD PARTS //

        set_matrix_item(matrix, width, height);

        // render selected item
        if (block_type != previous_block_type) {
            previous_block_type = block_type;
            if (is_plant(block_type)) {
                gen_plant_buffers(
                    &item_position_buffer, &item_normal_buffer, &item_uv_buffer,
                    0, 0, 0, 0.5, block_type);
            }
            else {
                gen_cube_buffers(
                    &item_position_buffer, &item_normal_buffer, &item_uv_buffer,
                    0, 0, 0, 0.5, block_type);
            }
        }
        glUseProgram(block_program);
        glUniformMatrix4fv(matrix_loc, 1, GL_FALSE, matrix);
        glUniform3f(camera_loc, 0, 0, 5);
        glUniform1i(sampler_loc, 0);
        glUniform1f(timer_loc, glfwGetTime());
        if (is_plant(block_type)) {
            draw_plant(
                item_position_buffer, item_normal_buffer, item_uv_buffer,
                position_loc, normal_loc, uv_loc);
        }
        else {
            draw_cube(
                item_position_buffer, item_normal_buffer, item_uv_buffer,
                position_loc, normal_loc, uv_loc);
        }

        // swap buffers
        glfwSwapBuffers(window);
        glfwPollEvents();
    }
    client_stop();
    db_save_state(x, y, z, rx, ry);
    db_close();
    glfwTerminate();
    return 0;
}
Esempio n. 9
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
    glfwSetCursorPos(gWindow, 0, 0);
    glfwMakeContextCurrent(gWindow);
    glfwSetKeyCallback(gWindow, key_callback);

    // 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);

    // initialise the gBox asset
    LoadBoxAsset();

    // create all the instances in the 3D scene based on the gBox asset
    CreateInstances();

    // setup gCamera
    gCamera.setViewportAspectRatio(SCREEN_SIZE.x / SCREEN_SIZE.y);

    // 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;

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

    // clean up and exit
    glfwTerminate();
}
Esempio n. 10
0
void init() {
    glfwSetKeyCallback(render::getWindow(), keypress_callback);
}
Esempio n. 11
0
void			THIS::init(parent_t * const & p)
{
	printv(DEBUG, "%s\n", __PRETTY_FUNCTION__);

	if(p == NULL) return;

	setParent(p);
	
	auto app = get_fnd_app();

	if(!app->_M_flag.any(neb::fnd::app::util::flag::INIT_GLFW))
	{
		printv(WARNING, "glfw not initializaed\n");
		return;
	}
	
	auto g = std::dynamic_pointer_cast<neb::gfx::app::Base>(app->G::get_object());

	//auto self = std::dynamic_pointer_cast<THIS>(shared_from_this());
	
	if(window_) return;

	// create window
	
	glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
	//glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
	//glfwWindowHint(GLFW_VISIBLE, GL_FALSE);

	window_ = glfwCreateWindow(
			w_,
			h_,
			title_.c_str(),
			NULL,
			first_window_
			);

	if(first_window_ == NULL) {
		first_window_ = window_;
	}

	if(window_ == NULL) {
		glfwTerminate();
		printv(DEBUG, "glfwCreateWindow failed\n");
		exit(EXIT_FAILURE);
	}

	glfwSetWindowPos(window_, x_, y_);

	glfwMakeContextCurrent(window_);

	glfwSetWindowPosCallback(
			window_,
			neb::gfx::app::glfw::static_window_pos_fun);
	glfwSetWindowSizeCallback(
			window_,
			neb::gfx::app::glfw::static_window_size_fun);
	glfwSetWindowCloseCallback(
			window_,
			neb::gfx::app::glfw::static_window_close_fun);
	glfwSetWindowRefreshCallback(
			window_,
			neb::gfx::app::glfw::static_window_refresh_fun);
	glfwSetKeyCallback(
			window_,
			neb::gfx::app::glfw::static_key_fun);
	glfwSetMouseButtonCallback(
			window_,
			neb::gfx::app::glfw::static_mouse_button_fun);
	glfwSetCharCallback(
			window_,
			neb::gfx::app::glfw::staticCharFun);

	// add window to app's window map
	g->reg(shared_from_this());

	//if(all(neb::app::base::option::SHADERS)) create_programs();

	g->init_glew();

	g->create_programs();

	//printf("%s\n",glGetString(GL_SHADING_LANGUAGE_VERSION));

	//Check for necessary extensions
	if(!GL_ARB_depth_texture || !GL_ARB_shadow)
	{
		printv(CRITICAL, "I require ARB_depth_texture and ARB_shadow extensionsn\n");
		exit(0);//return false;
	}

	//Shading states
	glShadeModel(GL_SMOOTH);
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);

	//Depth states

	glClearDepth(1.0f);
	glDepthFunc(GL_LEQUAL);

	glEnable(GL_DEPTH_TEST);
	glEnable(GL_CULL_FACE);
	glEnable(GL_NORMALIZE);

	checkerror("unknown");
}
Esempio n. 12
0
        void Application::createWindow(int width, int height,
            std::string const& title)
        {
            if (mImpl->currentWindow != nullptr)
            {
                ERROR_LOG("Multiple windows are currently not supported.");
                return;
            }

            glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
            glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
            glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

#ifdef ATLAS_PLATFORM_APPLE
            glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif

            mImpl->currentWindow = glfwCreateWindow(width, height, 
                title.c_str(), NULL, NULL);
            if (!mImpl->currentWindow)
            {
                glfwTerminate();
                CRITICAL_LOG("Could not create window.");
                exit(EXIT_FAILURE);
            }

            glfwMakeContextCurrent(mImpl->currentWindow);

            GLint major, minor;
            glGetIntegerv(GL_MAJOR_VERSION, &major);
            glGetIntegerv(GL_MINOR_VERSION, &minor);

            INFO_LOG("Created OpenGL context " + std::to_string(major) +
                "." + std::to_string(minor));

            glewExperimental = GL_TRUE;
            GLenum err = glewInit();
            if (err != GLEW_OK)
            {
                CRITICAL_LOG("Could not initialize GLEW.");
                glfwDestroyWindow(mImpl->currentWindow);
                glfwTerminate();
                exit(EXIT_FAILURE);
            }

            glfwSetKeyCallback(mImpl->currentWindow, 
                keyPressCallback);
            glfwSetWindowSizeCallback(mImpl->currentWindow, 
                windowSizeCallback);
            glfwSetFramebufferSizeCallback(mImpl->currentWindow,
                frameBufferSizeCallback);
            glfwSetMouseButtonCallback(mImpl->currentWindow, 
                mousePressCallback);
            glfwSetCursorPosCallback(mImpl->currentWindow, 
                mouseMoveCallback);
            glfwSetWindowCloseCallback(mImpl->currentWindow, 
                windowCloseCallback);

            // HACK: This clears out the errors generated by glew.
            // We need to find a better way of doing this. Maybe replace
            // GLEW in its entirety?
            GL_CLEAR_ERRORS();
        }
Esempio n. 13
0
int main( int argc, char** argv )
{

    std::cout << "Starting..\n";
    std::vector<std::string> file_names;
    parse_args(argc, argv, file_names);
    file_names.push_back(std::string("b0e0.hgt"));
    InitGraphics();

    glfwSetWindowTitle( "p7" );

    // Ensure we can capture the escape key being pressed below
    glfwEnable( GLFW_STICKY_KEYS );

    // Dark blue background
    glClearColor(0.7f, 0.7f, 0.7f, 0.0f);

    // Enable depth test
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_CULL_FACE);
    // Accept fragment if it closer to the camera than the former one
    glDepthFunc(GL_LESS);
//  glFrontFace(GL_CCW);

    // Create and compile our GLSL program from the shaders
    GLuint programIDs[2] = { LoadShaders( "tvs.vertexshader", "cfs.fragmentshader" ), LoadShaders( "tvs2.vertexshader", "cfs.fragmentshader" )};
    std::cout << "Linked shaders..\n";
    // Get a handle for our "MVP" uniform
    GLuint MatrixIDs[2] = {glGetUniformLocation(programIDs[0], "MVP"), glGetUniformLocation(programIDs[1], "MVP")};
    GLuint EdgexIDs[2] = {glGetUniformLocation(programIDs[0], "Edgex"), glGetUniformLocation(programIDs[1], "Edgex")};
    GLuint EdgeyIDs[2] = {glGetUniformLocation(programIDs[0], "Edgey"), glGetUniformLocation(programIDs[1], "Edgey")};
    GLuint HeightIDs[2] = {glGetUniformLocation(programIDs[0], "height"), glGetUniformLocation(programIDs[1], "height")};
    GLuint TextureIDs[2] = {glGetUniformLocation(programIDs[0], "tex2d"), glGetUniformLocation(programIDs[1], "tex2d")};
    GLuint TimeIDs[2] = {glGetUniformLocation(programIDs[0], "time"), glGetUniformLocation(programIDs[1], "time")};
    GLuint AlphaIDs[2] = {glGetUniformLocation(programIDs[0], "alpha"), glGetUniformLocation(programIDs[1], "alpha")};
    std::cout << "Got uniforms..\n";
    std::cout << glGetString(GL_VERSION) << std::endl;

    std::cout << "Loadin textures...\n";

    char texName[] = "texture3.jpg";
    std::cout << texName << std::endl;
    int t1x,t1y,t1comp;
    FILE* t1f = fopen(texName, "rb");
    unsigned char* tex1data = stbi_load_from_file(t1f, &t1x, &t1y, &t1comp,0);
    unsigned int tex_2d;
    glGenTextures(1, &tex_2d);
    glBindTexture(GL_TEXTURE_2D, tex_2d);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, t1x, t1y, 0, GL_RGB, GL_UNSIGNED_BYTE, tex1data);
    /*
      char texNameCl[] = "textureClouds3.png";
      std::cout << texNameCl << std::endl;
      int t2x,t2y,t2comp;
      FILE* t2f = fopen(texNameCl, "rb");
      unsigned char* tex2data = stbi_load_from_file  (t2f, &t2x, &t2y, &t2comp,0);
      unsigned int tex_cl;
      glGenTextures(1, &tex_cl);
      glBindTexture(GL_TEXTURE_2D, tex_cl);
      //-->
      glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
      glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
      glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, t2x, t2y, 0, GL_RGB, GL_UNSIGNED_BYTE, tex2data);
    */
    std::cout << "Done!\n";

    const int side(1201);
    const int vBOsize(file_names.size());


    //Vertices:
    short piece_map[360][181];
    for(int i=0; i<360; i++)
        for(int y=0; y<=180; y++)
            piece_map[i][y] = -1;
    unsigned int numberOfVertices=side*side;
    GLuint vaoObjects[vBOsize+1], vertexBufferObject, vBOs[vBOsize+1];
    std::vector<std::pair<int, int> > edges(vBOsize+1);
    // -->
    std::cout << "Generating arrays...\n";
    glGenVertexArrays(vBOsize, vaoObjects);
    std::cout << "Done\n";
    glGenBuffers(vBOsize, vBOs);
    int height;
    // <---
    for(short i=0; i< vBOsize; i++)
    {
        std::vector< int > vertexPositionsVec(3*numberOfVertices);
        int* vertexPositions = &vertexPositionsVec[0];
        loadVertices(file_names[i], vertexPositionsVec, true, side, edges[i], height);
        glBindVertexArray(vaoObjects[i]);
        glBindBuffer(GL_ARRAY_BUFFER, vBOs[i]);
        glVertexAttribPointer(
            0,                  // attribute. No particular reason for 0, but must match the layout in the shader.
            3,                  // size
            GL_INT,           // type
            GL_FALSE,           // normalized?
            0,                  // stride
            (void*)0            // array buffer offset
        );
        glBufferData(GL_ARRAY_BUFFER, sizeof(int)*3*numberOfVertices, vertexPositions, GL_STATIC_DRAW);
        if(i<vBOsize-1)
        {
            piece_map[edges[i].second+180][edges[i].first+90]=i;
            std::cout << edges[i].second+180 << " " << edges[i].first+90 << std::endl;
        }
    }

    //Indices::
    GLuint indexBufferObject, iBOs[maxLoD], numberOfIndices;
    std::vector<GLuint> nOIs(maxLoD);
    glGenBuffers(maxLoD, iBOs);
    for(unsigned int density=1, i=0; i<maxLoD; i++, density*=2)
    {
        std::cout << "Entering for with i: " << i << "\n";
        nOIs[i]=(side-1)/density;
        if((side-1)%density!=0)
            nOIs[i]+=1;
        nOIs[i]=6*(nOIs[i]*(nOIs[i]));
        std::cout << "Allocating memory...\n";
        GLuint* indices = new GLuint [nOIs[i]];
        std::cout << "Done.\n";
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, iBOs[i]);
        std::cout << "Density: " << density << " Number of indices: " << nOIs[i] << std::endl;
        genIndices(indices, side, density);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLuint)*nOIs[i], indices, GL_STATIC_DRAW);
        std::cout << "Leaving for with i: " << i << "\n";
    }

    // Projection matrix : 45° Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units
    glm::mat4 Projection =
        // glm::mat4(1.0f);
        glm::perspective(45.0f, 4.0f / 3.0f, 100.f, 30000.0f);
    // Camera matrix
//  int xVw = edges[0].first*side, yVw = edges[0].second*side;
    int xVw = 6000, yVw = -6000;
    height = 3000;
    glm::mat4 View       = glm::lookAt(
                               glm::vec3(xVw,yVw,2*height), // Camera is at (4,3,-3), in World Space
                               glm::vec3(xVw,yVw,0), // and looks at the origin
                               glm::vec3(0,1,0)  // Head is up (set to 0,-1,0 to look upside-down)
                           );
    // Model matrix : an identity matrix (model will be at the origin)
    glm::mat4 Model      = glm::mat4(1.0f);
    // Our ModelViewProjection : multiplication of our 3 matrices

    glm::mat4 MVP        = Projection * View * Model; // Remember, matrix multiplication is the other way around

    std::cout << "Init done.\n";

    glfwSetKeyCallback(Key_Callback);

    double last_time = glfwGetTime(), last_reset=last_time;
    int FPScounter=0;

    x = edges[0].second*12010;
    startx=x;
    y = edges[0].first*12010;
    starty=y;
    std::cout << edges[0].first << " " << edges[0].second << std::endl;
    do {
        int ex = x/12010+180;
        int ey = y/12010+90;
        //time statistics:
        FPScounter++;
        double cur_time = glfwGetTime();
        if(cur_time-last_reset>=2)
        {
            double FPS = (float)FPScounter/(cur_time-last_reset);
            std::cout << "FPS: " << FPS << " lod: " << iBOindex << std::endl;
            std::cout << ex << " " << ey << " " << alpha <<  std::endl;
            if(autolod && abs(FPS-optfps)>4)
            {
                if(FPS<optfps && iBOindex<maxLoD)
                    iBOindex++;
                if(FPS>4*optfps && iBOindex > 0)
                    iBOindex--;
            }
            FPScounter=0;
            last_reset=cur_time;
        }
        last_time=cur_time;

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

        // Use our shader
        glUseProgram(programIDs[ball]);
        glm::mat4 Vw;
        // Send our transformation to the currently bound shader,
        // in the "MVP" uniform
        Vw=MVP * glm::translate( mat4(1.0),vec3((-x + 6000)*ball,(-y - 6000)*ball,(z - 12000)*ball))
           * glm::rotate(mat4(1.0), oz, glm::vec3(0,1,0))
           * glm::rotate(mat4(1.0), ox, glm::vec3(1,0,0))
           * glm::rotate(mat4(1.0), oy, glm::vec3(0,0,1))
           * glm::translate( mat4(1.0), vec3(-x*(1-ball), -y*(1-ball), z*(1-ball)));
        glUniformMatrix4fv(MatrixIDs[ball], 1, GL_FALSE, &Vw[0][0]);

        glUniform1i(HeightIDs[ball], 0);

        glUniform1f(TimeIDs[ball], glfwGetTime());
        glUniform1f(AlphaIDs[ball], (float)alpha*0.1);

        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, tex_2d);
        glUniform1i(TextureIDs[ball], /*GL_TEXTURE0+*/0);

        indexBufferObject=iBOs[iBOindex];
        numberOfIndices=nOIs[iBOindex];

//   std::cout << ex << " " << ey << std::endl;
        if(ball==0)
        {
            glCullFace(GL_FRONT);
            for(int i = max(ex-3,0); i<= min(ex+3,360) ; i++)
                for(int j=max(ey-3,0); j<= min(ey+3,180); j++)
                {
                    glUniform1i(EdgexIDs[ball], (i-180));
                    glUniform1i(EdgeyIDs[ball], (j-90));
                    int point;
                    if(piece_map[i][j]==-1)
                    {
                        point=vBOsize-1;
                        draw(vaoObjects[point], vBOs[point], iBOs[maxLoD-1], nOIs[maxLoD-1]);
                    }
                    else
                    {
                        point = piece_map[i][j];
                        draw(vaoObjects[point], vBOs[point], indexBufferObject, numberOfIndices);
                    }
                    //         std::cout << "Drawing " << file_names[point] << "with mods " << i-180 << " " << j-90 << std::endl
                    //           << i << " "  << ex << " " << j << " " << ey << std::endl;

                }
        }
        else
        {
            glCullFace(GL_FRONT);
            for(int i=/*edges[0].second+180+*/0; i</*edges[0].second+18*/360; i++)
                for(int j=/*edges[0].first+90+*/0; j<=/*edges[0].first+90*/180; j++)
                {

                    glUniform1i(EdgexIDs[ball], (i-180));
                    glUniform1i(EdgeyIDs[ball], (j-90));

                    int point;
                    if(piece_map[i][j]==-1)
                    {
                        point=vBOsize-1;
                        draw(vaoObjects[point], vBOs[point], iBOs[maxLoD-1], nOIs[maxLoD-1]);
                    }
                    else
                    {
                        point = piece_map[i][j];
                        draw(vaoObjects[point], vBOs[point], indexBufferObject, numberOfIndices);
                    }
                }
        }


        //CLOUDS
        /*
            Vw=MVP * glm::translate( mat4(1.0),vec3((-x + 6000)*ball,(-y - 6000)*ball,(z - 12000)*ball))
                             * glm::rotate(mat4(1.0), oz+(float)glfwGetTime(), glm::vec3(0,1,0))
                             * glm::rotate(mat4(1.0), ox, glm::vec3(1,0,0))
                             * glm::rotate(mat4(1.0), oy, glm::vec3(0,0,1))
                             * glm::translate( mat4(1.0), vec3(-x*(1-ball), -y*(1-ball), z*(1-ball)));
            glUniformMatrix4fv(MatrixIDs[ball], 1, GL_FALSE, &Vw[0][0]);

            glUniform1i(HeightIDs[ball], 100);

            glUniform1f(TimeIDs[ball], glfwGetTime());
            glUniform1f(AlphaIDs[ball], 0.25);

            glActiveTexture(GL_TEXTURE0);
            glBindTexture(GL_TEXTURE_2D, tex_cl);
            glUniform1i(TextureIDs[ball], 0);

            indexBufferObject=iBOs[iBOindex];
            numberOfIndices=nOIs[iBOindex];

         //   std::cout << ex << " " << ey << std::endl;
            if(ball==0)
            {
                glCullFace(GL_FRONT);
              for(int i = max(ex-3,0); i<= min(ex+3,360) ;i++)
                for(int j=max(ey-3,0); j<= min(ey+3,180); j++)
                {
                  glUniform1i(EdgexIDs[ball], (i-180));
                  glUniform1i(EdgeyIDs[ball], (j-90));
                  int point;
                  {
                    point=vBOsize-1;
                    draw(vaoObjects[point], vBOs[point], iBOs[maxLoD-1], nOIs[maxLoD-1]);
                  }

                }
            }
            else
            {
                glCullFace(GL_FRONT);
              for(int i=0; i<360;i++)
                for(int j=0; j<=180;j++)
                {

                  glUniform1i(EdgexIDs[ball], (i-180));
                  glUniform1i(EdgeyIDs[ball], (j-90));

                  int point;
                  {
                    point=vBOsize-1;
                    draw(vaoObjects[point], vBOs[point], iBOs[maxLoD-1], nOIs[maxLoD-1]);
                  }
                }
            }*/
        // Swap buffers
        glfwSwapBuffers();

    } // Check if the ESC key was pressed or the window was closed
    while( glfwGetKey( GLFW_KEY_ESC ) != GLFW_PRESS &&
            glfwGetWindowParam( GLFW_OPENED ) );

    // Cleanup VBO and shader
    glDeleteProgram(programIDs[0]);
    glDeleteProgram(programIDs[1]);
//  CleanVBOs(vaoObjects, vBOs, vBOsize+1, iBOs, tex_2d);

    std::cout << "Cleaning done, terminating..\n";
    // Close OpenGL window and terminate GLFW
    glfwTerminate();

    return 0;
}
bool GLViewImpl::initWithRect(const std::string& viewName, Rect rect, float frameZoomFactor, bool resizable)
{
    setViewName(viewName);

    _frameZoomFactor = frameZoomFactor;

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

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

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

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

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

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

    glfwMakeContextCurrent(_mainWindow);

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

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

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

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

    initGlew();

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

    return true;
}
Esempio n. 15
0
int main()
{
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    //glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr);

    if (window == nullptr)
    {
        std::cout << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);

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

    glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

    glewExperimental = GL_TRUE;
    if (glewInit() != GLEW_OK)
    {
        std::cout << "Failed to initialize GLEW" << std::endl;
        return -1;
    }
    glViewport(0, 0, WIDTH, HEIGHT);
    glEnable(GL_DEPTH_TEST);

    Shader lightingShader("./lighting.vs", "./lighting.frag");
    Shader lampShader("./lamp.vs", "./lamp.frag");


    // Set up vertex data (and buffer(s)) and attribute pointers
    GLfloat vertices[] = {
        -0.5f, -0.5f, -0.5f,  0.0f,  0.0f, -1.0f,
         0.5f, -0.5f, -0.5f,  0.0f,  0.0f, -1.0f,
         0.5f,  0.5f, -0.5f,  0.0f,  0.0f, -1.0f,
         0.5f,  0.5f, -0.5f,  0.0f,  0.0f, -1.0f,
        -0.5f,  0.5f, -0.5f,  0.0f,  0.0f, -1.0f,
        -0.5f, -0.5f, -0.5f,  0.0f,  0.0f, -1.0f,

        -0.5f, -0.5f,  0.5f,  0.0f,  0.0f,  1.0f,
         0.5f, -0.5f,  0.5f,  0.0f,  0.0f,  1.0f,
         0.5f,  0.5f,  0.5f,  0.0f,  0.0f,  1.0f,
         0.5f,  0.5f,  0.5f,  0.0f,  0.0f,  1.0f,
        -0.5f,  0.5f,  0.5f,  0.0f,  0.0f,  1.0f,
        -0.5f, -0.5f,  0.5f,  0.0f,  0.0f,  1.0f,

        -0.5f,  0.5f,  0.5f, -1.0f,  0.0f,  0.0f,
        -0.5f,  0.5f, -0.5f, -1.0f,  0.0f,  0.0f,
        -0.5f, -0.5f, -0.5f, -1.0f,  0.0f,  0.0f,
        -0.5f, -0.5f, -0.5f, -1.0f,  0.0f,  0.0f,
        -0.5f, -0.5f,  0.5f, -1.0f,  0.0f,  0.0f,
        -0.5f,  0.5f,  0.5f, -1.0f,  0.0f,  0.0f,

         0.5f,  0.5f,  0.5f,  1.0f,  0.0f,  0.0f,
         0.5f,  0.5f, -0.5f,  1.0f,  0.0f,  0.0f,
         0.5f, -0.5f, -0.5f,  1.0f,  0.0f,  0.0f,
         0.5f, -0.5f, -0.5f,  1.0f,  0.0f,  0.0f,
         0.5f, -0.5f,  0.5f,  1.0f,  0.0f,  0.0f,
         0.5f,  0.5f,  0.5f,  1.0f,  0.0f,  0.0f,

        -0.5f, -0.5f, -0.5f,  0.0f, -1.0f,  0.0f,
         0.5f, -0.5f, -0.5f,  0.0f, -1.0f,  0.0f,
         0.5f, -0.5f,  0.5f,  0.0f, -1.0f,  0.0f,
         0.5f, -0.5f,  0.5f,  0.0f, -1.0f,  0.0f,
        -0.5f, -0.5f,  0.5f,  0.0f, -1.0f,  0.0f,
        -0.5f, -0.5f, -0.5f,  0.0f, -1.0f,  0.0f,

        -0.5f,  0.5f, -0.5f,  0.0f,  1.0f,  0.0f,
         0.5f,  0.5f, -0.5f,  0.0f,  1.0f,  0.0f,
         0.5f,  0.5f,  0.5f,  0.0f,  1.0f,  0.0f,
         0.5f,  0.5f,  0.5f,  0.0f,  1.0f,  0.0f,
        -0.5f,  0.5f,  0.5f,  0.0f,  1.0f,  0.0f,
        -0.5f,  0.5f, -0.5f,  0.0f,  1.0f,  0.0f
    };

    GLuint VBO, containerVAO;
    glGenVertexArrays(1, &containerVAO);
    glGenBuffers(1, &VBO);

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

    glBindVertexArray(containerVAO);
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(0);

    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
    glEnableVertexAttribArray(1);
    glBindVertexArray(0);

    GLuint lightVAO;
    glGenVertexArrays(1, &lightVAO);
    glBindVertexArray(lightVAO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);

    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(0);
    glBindVertexArray(0);


    while(!glfwWindowShouldClose(window))
    {
        GLfloat currentFrame = glfwGetTime();
        deltaTime = currentFrame - lastFrame;
        lastFrame = currentFrame;

        glfwPollEvents();
        do_movement();

        glClearColor(0.1f, 0.1f, 0.1f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        lightingShader.Use();

        GLint objectColorLoc = glGetUniformLocation(lightingShader.Program, "objectColor");
        GLint lightColorLoc = glGetUniformLocation(lightingShader.Program, "lightColor");
        GLint lightLoc = glGetUniformLocation(lightingShader.Program, "lightPos");
        glUniform3f(objectColorLoc, 1.0f, 0.5f, 0.31f);
        glUniform3f(lightColorLoc, 1.0f, 0.5f, 1.0f);
        glUniform3f(lightLoc, lightPos.x, lightPos.y, lightPos.z);

        glm::mat4 view;
        view = camera.GetViewMatrix();
        glm::mat4 projection = glm::perspective(camera.Zoom, (GLfloat)WIDTH / (GLfloat)HEIGHT, 0.1f, 100.0f);

        GLint modelLoc = glGetUniformLocation(lightingShader.Program, "model");
        GLint viewLoc = glGetUniformLocation(lightingShader.Program, "view");
        GLint projLoc = glGetUniformLocation(lightingShader.Program, "projection");

        glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
        glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection));

        glBindVertexArray(containerVAO);
        glm::mat4 model;
        glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
        glDrawArrays(GL_TRIANGLES, 0, 36);
        glBindVertexArray(0);

        // Also draw the lamp object, again binding the appropriate shader
        lampShader.Use();
        // Get location objects for the matrices on the lamp shader (these could be different on a different shader)
        modelLoc = glGetUniformLocation(lampShader.Program, "model");
        viewLoc  = glGetUniformLocation(lampShader.Program, "view");
        projLoc  = glGetUniformLocation(lampShader.Program, "projection");
        // Set matrices
        glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
        glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection));
        model = glm::mat4();
        model = glm::translate(model, lightPos);
        model = glm::scale(model, glm::vec3(0.2f)); // Make it a smaller cube
        glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
        // Draw the light object (using light's vertex attributes)
        glBindVertexArray(lightVAO);
        glDrawArrays(GL_TRIANGLES, 0, 36);
        glBindVertexArray(0);

        glfwSwapBuffers(window);
    }
    glDeleteVertexArrays(1, &containerVAO);
    glDeleteVertexArrays(1, &lightVAO);
    glDeleteBuffers(1, &VBO);

    glfwTerminate();

    return 0;
}
Esempio n. 16
0
int main(int argc, char** argv)
{
    int ch, samples = 4;
    GLFWwindow* window;
    GLuint vertex_buffer, vertex_shader, fragment_shader, program;
    GLint mvp_location, vpos_location;

    while ((ch = getopt(argc, argv, "hs:")) != -1)
    {
        switch (ch)
        {
            case 'h':
                usage();
                exit(EXIT_SUCCESS);
            case 's':
                samples = atoi(optarg);
                break;
            default:
                usage();
                exit(EXIT_FAILURE);
        }
    }

    glfwSetErrorCallback(error_callback);

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

    if (samples)
        printf("Requesting MSAA with %i samples\n", samples);
    else
        printf("Requesting that MSAA not be available\n");

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

    window = glfwCreateWindow(800, 400, "Aliasing Detector", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwSetKeyCallback(window, key_callback);

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

    glGetIntegerv(GL_SAMPLES, &samples);
    if (samples)
        printf("Context reports MSAA is available with %i samples\n", samples);
    else
        printf("Context reports MSAA is unavailable\n");

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

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

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

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

    mvp_location = glGetUniformLocation(program, "MVP");
    vpos_location = glGetAttribLocation(program, "vPos");

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

    while (!glfwWindowShouldClose(window))
    {
        float ratio;
        int width, height;
        mat4x4 m, p, mvp;
        const double angle = glfwGetTime() * M_PI / 180.0;

        glfwGetFramebufferSize(window, &width, &height);
        ratio = width / (float) height;

        glViewport(0, 0, width, height);
        glClear(GL_COLOR_BUFFER_BIT);

        glUseProgram(program);

        mat4x4_ortho(p, -ratio, ratio, -1.f, 1.f, 0.f, 1.f);

        mat4x4_translate(m, -1.f, 0.f, 0.f);
        mat4x4_rotate_Z(m, m, (float) angle);
        mat4x4_mul(mvp, p, m);

        glUniformMatrix4fv(mvp_location, 1, GL_FALSE, (const GLfloat*) mvp);
        glDisable(GL_MULTISAMPLE);
        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);

        mat4x4_translate(m, 1.f, 0.f, 0.f);
        mat4x4_rotate_Z(m, m, (float) angle);
        mat4x4_mul(mvp, p, m);

        glUniformMatrix4fv(mvp_location, 1, GL_FALSE, (const GLfloat*) mvp);
        glEnable(GL_MULTISAMPLE);
        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);

        glfwSwapBuffers(window);
        glfwPollEvents();
    }

    glfwDestroyWindow(window);

    glfwTerminate();
    exit(EXIT_SUCCESS);
}
Esempio n. 17
0
int main() {

	// Init GLFW
	glfwInit();
	// Set all the required options for GLFW
	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(WIDTH, HEIGHT, "Assignment1", nullptr, nullptr);
	if (window == nullptr)
	{
		std::cout << "Failed to created GLFW window" << std::endl;
		glfwTerminate();
		return -1;
	}
	glfwMakeContextCurrent(window);

	glfwSetKeyCallback(window, key_callback);

	glewExperimental = GL_TRUE;

	glewInit();
	if (glewInit() != GLEW_OK)
	{
		std::cout << "Failed to initialized GLEW" << std::endl;
		return -1;
	}

	int width, height;
	glfwGetFramebufferSize(window, &width, &height);

	glViewport(0, 0, width, height);

	glEnable(GL_DEPTH_TEST);


	GLuint vertexShader = glCreateShader(GL_VERTEX_SHADER);
	glShaderSource(vertexShader, 1, &vertexShaderSource, NULL);
	glCompileShader(vertexShader);

	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);

	GLfloat vertices[] = {
		
		0.5f,  0.5f, 0.5f,  //0
		0.5f, -0.5f, 0.5f,  //1
		-0.5f,  0.5f, 0.5f, //2
		-0.5f, -0.5f, 0.5f, //3

		0.5f,  0.5f, -0.5f, //4
		0.5f, -0.5f, -0.5f, //5
		-0.5f,  0.5f, -0.5f,//6
		-0.5f, -0.5f, -0.5f,//7
	};

	GLuint indices[] = {  
		0, 1, 2,				//front
		2, 1, 3,

		0, 4, 5,				//right
		1, 0, 5,

		4, 5, 7,				//back
		4, 7, 6,

		2, 3, 6,				//left
		3, 6, 7,

		0, 2, 4,				//top
		2, 4, 6,

		1, 5, 7,				//bottom
		1, 7, 3,
	};
	


	GLuint VBO, VAO, EBO;
	glGenVertexArrays(1, &VAO);
	glGenBuffers(1, &VBO);
	glGenBuffers(1, &EBO);
	// 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);

	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
	glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, 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


	projection = glm::perspective(45.0f, 1.0f, 0.1f, 20.0f);
	view = glm::lookAt(glm::vec3(0, 10, zoom), glm::vec3(0, 0, 0), glm::vec3(0, 1, 0));

	//model2 = glm::translate(model2, glm::vec3(3, 0, 4));
	//model2 = glm::mat4();

	// Uncommenting this call will result in wireframe polygons.
	//glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);

						  // Game loop
						  // Clear the colorbuffer
	glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
	while (!glfwWindowShouldClose(window))
	{
		// Render
		glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

		glBindVertexArray(VAO);
		// Draw our first triangle
		glUseProgram(shaderProgram);
		glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "projection"), 1, GL_FALSE, &(projection)[0][0]);
		glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "view"), 1, GL_FALSE, &(view)[0][0]);

		glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "model"), 1, GL_FALSE, &(model1)[0][0]); //blue
		glUniform4fv(glGetUniformLocation(shaderProgram, "myColor"), 1, &(glm::vec4(0, 0, 1, 1))[0]);

		//glDrawArrays(GL_TRIANGLES, 0, 6);

		if (!points) {
		glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0);
		}

		if (points) {
		glDrawElements(GL_POINTS, 36, GL_UNSIGNED_INT,0);
		glEnable(GL_PROGRAM_POINT_SIZE);
		glPointSize(5.0);
		}
		glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "model"), 1, GL_FALSE, &(model2)[0][0]); //red
		glUniform4fv(glGetUniformLocation(shaderProgram, "myColor"), 1, &(glm::vec4(1, 0, 0, 1))[0]);

		if (!points) {
		glDrawElements(GL_TRIANGLES, 36, GL_UNSIGNED_INT, 0);

		}

		if (points) {
			glDrawElements(GL_POINTS, 36, GL_UNSIGNED_INT, 0);
			glEnable(GL_PROGRAM_POINT_SIZE);
			glPointSize(5.0);
		}

		glBindVertexArray(0);

		if(lines){ glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); }
		if (fill) { glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); }
		


		// Swap the screen buffers
		glfwSwapBuffers(window);
		// Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions
		glfwPollEvents();

		model1 = glm::rotate(model1, 0.001f, glm::vec3(0, 1, 0));

		glm::mat3 conv;
		ang -= 0.001f;

		conv[0] = glm::vec3(cos(ang), 0 , sin(ang));
		conv[1] = glm::vec3(0,1,0);
		conv[2] = glm::vec3(-sin(ang), 0, cos(ang));

		glm::vec3 rotVec = glm::vec3(3, 0, 4);
		rotVec = conv * rotVec;
		//model2 = glm::translate(glm::scale(glm::mat4(), model2[0][0] * glm::vec3(1,1,1)), rotVec);
		model2 = glm::scale(glm::translate(glm::mat4() , rotVec), glm::vec3(redB, redB, redB));
		//model2 = glm::translate(model2);

		view = glm::lookAt(glm::vec3(0, zoom, 10), glm::vec3(0, 0, 0), glm::vec3(0, up, 0));
		//model2 = glm::scale(glm::translate(glm::mat4(), glm::vec3(-sin(ang), 0, cos(ang))),glm::vec3(redB,redB,redB));
		//model2 = glm::rotate(model2, 0.001f, glm::vec3(0, 1, 0));


		//model1 = glm::rotate(model1, 0.001f, glm::vec3(0, 1, 0));
		//model2 = glm::translate(model2, rotVec);
		//model2 = glm::rotate(model2, 0.001f, glm::vec3(0, 1, 0));
		//model2 = glm::translate(model2, glm::vec3(3, 0, 4));
	}

	glDeleteVertexArrays(1, &VAO);
	glDeleteBuffers(1, &VBO);
	glDeleteBuffers(1, &EBO);

	glfwTerminate();
	return 0;
}
// The MAIN function, from here we start the application and run the game loop
int main()
{
    // Init GLFW
    glfwInit();
    // Set all the required options for GLFW
    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);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

    // Create a GLFWwindow object that we can use for GLFW's functions
    GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr);
    glfwMakeContextCurrent(window);

    // Set the required callback functions
    glfwSetKeyCallback(window, key_callback);

    // Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions
    glewExperimental = GL_TRUE;
    // Initialize GLEW to setup the OpenGL Function pointers
    glewInit();

    // Define the viewport dimensions
    glViewport(0, 0, WIDTH, HEIGHT);

    // Setup OpenGL options
    glEnable(GL_DEPTH_TEST);


    // Build and compile our shader program
    Shader ourShader("coordinate_systems.vs", "coordinate_systems.frag");


    // Set up vertex data (and buffer(s)) and attribute pointers
    GLfloat vertices[] = {
        -0.5f, -0.5f, -0.5f,  0.0f, 0.0f,
         0.5f, -0.5f, -0.5f,  1.0f, 0.0f,
         0.5f,  0.5f, -0.5f,  1.0f, 1.0f,
         0.5f,  0.5f, -0.5f,  1.0f, 1.0f,
        -0.5f,  0.5f, -0.5f,  0.0f, 1.0f,
        -0.5f, -0.5f, -0.5f,  0.0f, 0.0f,

        -0.5f, -0.5f,  0.5f,  0.0f, 0.0f,
         0.5f, -0.5f,  0.5f,  1.0f, 0.0f,
         0.5f,  0.5f,  0.5f,  1.0f, 1.0f,
         0.5f,  0.5f,  0.5f,  1.0f, 1.0f,
        -0.5f,  0.5f,  0.5f,  0.0f, 1.0f,
        -0.5f, -0.5f,  0.5f,  0.0f, 0.0f,

        -0.5f,  0.5f,  0.5f,  1.0f, 0.0f,
        -0.5f,  0.5f, -0.5f,  1.0f, 1.0f,
        -0.5f, -0.5f, -0.5f,  0.0f, 1.0f,
        -0.5f, -0.5f, -0.5f,  0.0f, 1.0f,
        -0.5f, -0.5f,  0.5f,  0.0f, 0.0f,
        -0.5f,  0.5f,  0.5f,  1.0f, 0.0f,

         0.5f,  0.5f,  0.5f,  1.0f, 0.0f,
         0.5f,  0.5f, -0.5f,  1.0f, 1.0f,
         0.5f, -0.5f, -0.5f,  0.0f, 1.0f,
         0.5f, -0.5f, -0.5f,  0.0f, 1.0f,
         0.5f, -0.5f,  0.5f,  0.0f, 0.0f,
         0.5f,  0.5f,  0.5f,  1.0f, 0.0f,

        -0.5f, -0.5f, -0.5f,  0.0f, 1.0f,
         0.5f, -0.5f, -0.5f,  1.0f, 1.0f,
         0.5f, -0.5f,  0.5f,  1.0f, 0.0f,
         0.5f, -0.5f,  0.5f,  1.0f, 0.0f,
        -0.5f, -0.5f,  0.5f,  0.0f, 0.0f,
        -0.5f, -0.5f, -0.5f,  0.0f, 1.0f,

        -0.5f,  0.5f, -0.5f,  0.0f, 1.0f,
         0.5f,  0.5f, -0.5f,  1.0f, 1.0f,
         0.5f,  0.5f,  0.5f,  1.0f, 0.0f,
         0.5f,  0.5f,  0.5f,  1.0f, 0.0f,
        -0.5f,  0.5f,  0.5f,  0.0f, 0.0f,
        -0.5f,  0.5f, -0.5f,  0.0f, 1.0f
    };
    // World space positions of our cubes
    glm::vec3 cubePositions[] = {
        glm::vec3( 0.0f,  0.0f,  0.0f),
        glm::vec3( 2.0f,  5.0f, -15.0f),
        glm::vec3(-1.5f, -2.2f, -2.5f),
        glm::vec3(-3.8f, -2.0f, -12.3f),
        glm::vec3( 2.4f, -0.4f, -3.5f),
        glm::vec3(-1.7f,  3.0f, -7.5f),
        glm::vec3( 1.3f, -2.0f, -2.5f),
        glm::vec3( 1.5f,  2.0f, -2.5f),
        glm::vec3( 1.5f,  0.2f, -1.5f),
        glm::vec3(-1.3f,  1.0f, -1.5f)
    };
    GLuint VBO, VAO;
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);

    glBindVertexArray(VAO);

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

    // Position attribute
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(0);
    // TexCoord attribute
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
    glEnableVertexAttribArray(2);

    glBindVertexArray(0); // Unbind VAO


    // Load and create a texture 
    GLuint texture1;
    GLuint texture2;
    // ====================
    // Texture 1
    // ====================
    glGenTextures(1, &texture1);
    glBindTexture(GL_TEXTURE_2D, texture1); // All upcoming GL_TEXTURE_2D operations now have effect on our texture object
    // Set our texture parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);	// Set texture wrapping to GL_REPEAT
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    // Set texture filtering
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    // Load, create texture and generate mipmaps
    int width, height;
    unsigned char* image = SOIL_load_image("../../../resources/textures/container.jpg", &width, &height, 0, SOIL_LOAD_RGB);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
    glGenerateMipmap(GL_TEXTURE_2D);
    SOIL_free_image_data(image);
    glBindTexture(GL_TEXTURE_2D, 0); // Unbind texture when done, so we won't accidentily mess up our texture.
    // ===================
    // Texture 2
    // ===================
    glGenTextures(1, &texture2);
    glBindTexture(GL_TEXTURE_2D, texture2);
    // Set our texture parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    // Set texture filtering
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    // Load, create texture and generate mipmaps
    image = SOIL_load_image("../../../resources/textures/awesomeface.png", &width, &height, 0, SOIL_LOAD_RGB);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
    glGenerateMipmap(GL_TEXTURE_2D);
    SOIL_free_image_data(image);
    glBindTexture(GL_TEXTURE_2D, 0);


    // Game loop
    while (!glfwWindowShouldClose(window))
    {
        // Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions
        glfwPollEvents();

        // Render
        // Clear the colorbuffer
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);


        // Bind Textures using texture units
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, texture1);
        glUniform1i(glGetUniformLocation(ourShader.Program, "ourTexture1"), 0);
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, texture2);
        glUniform1i(glGetUniformLocation(ourShader.Program, "ourTexture2"), 1);

        // Activate shader
        ourShader.Use();

        // Create transformations
        glm::mat4 view;
        glm::mat4 projection;
        view = glm::translate(view, glm::vec3(0.0f, 0.0f, -3.0f));
        projection = glm::perspective(45.0f, (GLfloat)WIDTH / (GLfloat)HEIGHT, 0.1f, 100.0f);
        // Get their uniform location
        GLint modelLoc = glGetUniformLocation(ourShader.Program, "model");
        GLint viewLoc = glGetUniformLocation(ourShader.Program, "view");
        GLint projLoc = glGetUniformLocation(ourShader.Program, "projection");
        // Pass the matrices to the shader
        glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
        // Note: currently we set the projection matrix each frame, but since the projection matrix rarely changes it's often best practice to set it outside the main loop only once.
        glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection));

        glBindVertexArray(VAO);
        for (GLuint i = 0; i < 10; i++)
        {
            // Calculate the model matrix for each object and pass it to shader before drawing
            glm::mat4 model;
            model = glm::translate(model, cubePositions[i]);
            GLfloat angle = 20.0f * i;
            model = glm::rotate(model, angle, glm::vec3(1.0f, 0.3f, 0.5f));
            glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));

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

        // Swap the screen buffers
        glfwSwapBuffers(window);
    }
    // Properly de-allocate all resources once they've outlived their purpose
    glDeleteVertexArrays(1, &VAO);
    glDeleteBuffers(1, &VBO);
    // Terminate GLFW, clearing any resources allocated by GLFW.
    glfwTerminate();
    return 0;
}
Esempio n. 19
0
void InitWindow()
{
    const int width  = GetConfigInt("window.width",  640);
    const int height = GetConfigInt("window.height", 480);
    const char* title = GetConfigString("window.title", "Konstrukt");

    const bool debug = GetConfigBool("opengl.debug", false);
    const bool vsync = GetConfigBool("opengl.vsync", true);

    LogInfo("Compiled with GLFW %d.%d.%d",
             GLFW_VERSION_MAJOR,
             GLFW_VERSION_MINOR,
             GLFW_VERSION_REVISION);
    LogInfo("Using GLFW %s", glfwGetVersionString());

    assert(g_Window == NULL);
    glfwSetErrorCallback(OnGLFWError);
    if(!glfwInit())
        FatalError("GLFW init failed.");

    glfwDefaultWindowHints();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_DEPTH_BITS, GetConfigInt("opengl.depth-bits", 24));
    glfwWindowHint(GLFW_STENCIL_BITS, 0);
    glfwWindowHint(GLFW_SAMPLES, GetConfigInt("opengl.samples", 0));
    glfwWindowHint(GLFW_SRGB_CAPABLE, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, debug ? GL_TRUE : GL_FALSE);

    g_Window = glfwCreateWindow(width, height, title, NULL, NULL);
    if(!g_Window)
        FatalError("Window creation failed.");

    glfwGetWindowSize(g_Window, &g_WindowWidth, &g_WindowHeight);
    glfwGetFramebufferSize(g_Window, &g_FramebufferWidth, &g_FramebufferHeight);

    glfwMakeContextCurrent(g_Window);

    if(!flextInit(g_Window))
        FatalError("Failed to load OpenGL extensions.");

    LogInfo("Using OpenGL %s\n"
            "Vendor: %s\n"
            "Renderer: %s\n"
            "GLSL: %s",
            glGetString(GL_VERSION),
            glGetString(GL_VENDOR),
            glGetString(GL_RENDERER),
            glGetString(GL_SHADING_LANGUAGE_VERSION));

    if(vsync)
    {
        if(glfwExtensionSupported("GLX_EXT_swap_control_tear") ||
           glfwExtensionSupported("WGL_EXT_swap_control_tear"))
            glfwSwapInterval(-1); // enable vsync (allow the driver to swap even if a frame arrives a little bit late)
        else
            glfwSwapInterval(1); // enable vsync
    }
    else
    {
        glfwSwapInterval(0); // disable vsync
    }

    glfwSetInputMode(g_Window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
    glfwSetInputMode(g_Window, GLFW_STICKY_KEYS, GL_FALSE);
    glfwSetInputMode(g_Window, GLFW_STICKY_MOUSE_BUTTONS, GL_FALSE);

    if(debug)
    {
        if(!FLEXT_ARB_debug_output)
            FatalError("Debug output requested, but it's not supported!");

        glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB);
        glDebugMessageCallbackARB(OnDebugEvent, NULL);
        LogInfo("Debug output supported! You may receive debug messages from your OpenGL driver.");
    }

    glfwSetWindowSizeCallback(g_Window, OnWindowResize);
    glfwSetFramebufferSizeCallback(g_Window, OnFramebufferResize);
    glfwSetMouseButtonCallback(g_Window, OnMouseButtonAction);
    glfwSetScrollCallback(g_Window, OnMouseScroll);
    glfwSetCursorPosCallback(g_Window, OnCursorMove);
    glfwSetKeyCallback(g_Window, OnKeyAction);
}
Esempio n. 20
0
void texture() {
    // Init GLFW
    glfwInit();
    // Set all the required options for GLFW
    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);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);


    // Create a GLFWwindow object that we can use for GLFW's functions
    GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr);
    glfwMakeContextCurrent(window);

    // Set the required callback functions
    glfwSetKeyCallback(window, key_callback);

    // Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions
    glewExperimental = GL_TRUE;
    // Initialize GLEW to setup the OpenGL Function pointers
    glewInit();

    // Define the viewport dimensions
    glViewport(0, 0, WIDTH, HEIGHT);


    // Build and compile our shader program
    Shader ourShader(vertexShaderSource1, fragmentShaderSource1);


    // Set up vertex data (and buffer(s)) and attribute pointers
    GLfloat vertices[] = {
        //--Positions---- //--Colors------//--Texture Coords
        0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 2.0f, 2.0f, // Top Right
        0.5f, -0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 2.0f, 0.0f, // Bottom Right
        -0.5f, -0.5f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, // Bottom Left
        -0.5f, 0.5f, 0.0f, 1.0f, 1.0f, 0.0f, 0.0f, 2.0f  // Top Left
        //x y z   R G B    S T
    };
    GLuint indices[] = {  // Note that we start from 0!
        0, 1, 3, // First Triangle
        1, 2, 3  // Second Triangle
    };
    GLuint VBO, VAO, EBO;
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);
    glGenBuffers(1, &EBO);

    glBindVertexArray(VAO);

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

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, GL_STATIC_DRAW);

    // Position attribute  8:≤Ω≥§
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0);
    glEnableVertexAttribArray(0);
    // Color attribute
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
    glEnableVertexAttribArray(1);
    // TexCoord attribute
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat)));
    glEnableVertexAttribArray(2);

    glBindVertexArray(0); // Unbind VAO


    // Load and create a texture
    GLuint texture1;
    GLuint texture2;
    // ======================================
    // Texture 1     texture1---GL_TEXTURE_2D----image
    // ======================================
    glGenTextures(1, &texture1);
    glBindTexture(GL_TEXTURE_2D, texture1); // All upcoming GL_TEXTURE_2D operations now have effect on our texture object
    // Set our texture parameters Œ™S∫ÕTŒ∆¿Ì◊¯±Í÷·…Ë÷√ª∑»∆∑Ω Ω
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);	// Set texture wrapping to GL_REPEAT
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
    // Set texture filtering Œ™∑≈¥ÛÀı–°÷∏∂®π˝¬À∑Ω Ω
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    // Load, create texture and generate mipmaps
    int width, height;
    unsigned char* image = SOIL_load_image("/Users/cc_xueqin/programming/learning/opengl/project/learn_opengl/res/container.jpg", &width, &height, 0, SOIL_LOAD_RGB);
    if (image == NULL) {
        std::cout << "ERROR::image is null\n"  << std::endl;
    }
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
    glGenerateMipmap(GL_TEXTURE_2D);
    SOIL_free_image_data(image);
    glBindTexture(GL_TEXTURE_2D, 0); // Unbind texture when done, so we won't accidentily mess up our texture.
    // ===================
    // Texture 2
    // ===================
    glGenTextures(1, &texture2);
    glBindTexture(GL_TEXTURE_2D, texture2);
    // Set our texture parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    // Set texture filtering
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    // Load, create texture and generate mipmaps
    image = SOIL_load_image("/Users/cc_xueqin/programming/learning/opengl/project/learn_opengl/res/awesomeface.png", &width, &height, 0, SOIL_LOAD_RGB);
    if (image == NULL) {
        std::cout << "ERROR::image is null\n" << std::endl;
    }
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
    glGenerateMipmap(GL_TEXTURE_2D);
    SOIL_free_image_data(image);
    glBindTexture(GL_TEXTURE_2D, 0);


    // Game loop
    while (!glfwWindowShouldClose(window))
    {
        // Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions
        glfwPollEvents();

        // Render
        // Clear the colorbuffer
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT);



        // Activate shader
        ourShader.Use();

        //1. ∞Û∂®Œ∆¿ÌµΩŒ∆¿Ìµ•‘™
        //2. ∂®“Â≤…—˘∆˜∂‘”¶µƒŒ∆¿Ìµ•‘™
        // Bind Textures using texture units
        glActiveTexture(GL_TEXTURE0);
        glBindTexture(GL_TEXTURE_2D, texture1);
        glUniform1i(glGetUniformLocation(ourShader.Program, "ourTexture1"), 0);
        glActiveTexture(GL_TEXTURE1);
        glBindTexture(GL_TEXTURE_2D, texture2);
        glUniform1i(glGetUniformLocation(ourShader.Program, "ourTexture2"), 1);

        // Draw container
        glBindVertexArray(VAO);
        // GL_ELEMENT_ARRAY_BUFFER ≈‰Ã◊ π”√ –ßπ˚∏¸∫√≈∂£°£°
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, 0);
        glBindVertexArray(0);

        // Swap the screen buffers
        glfwSwapBuffers(window);
    }
    // Properly de-allocate all resources once they've outlived their purpose
    glDeleteVertexArrays(1, &VAO);
    glDeleteBuffers(1, &VBO);
    glDeleteBuffers(1, &EBO);
    // Terminate GLFW, clearing any resources allocated by GLFW.
    glfwTerminate();
}
Esempio n. 21
0
// The MAIN function, from here we start the application and run the game loop
int main()
{
    std::cout << "Starting GLFW context, OpenGL 3.3" << std::endl;
    // Init GLFW
    glfwInit();
    // Set all the required options for GLFW
    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);

    // Create a GLFWwindow object that we can use for GLFW's functions
    GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr);
    glfwMakeContextCurrent(window);

    // Set the required callback functions
    glfwSetKeyCallback(window, key_callback);

    // Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions
    glewExperimental = GL_TRUE;
    // Initialize GLEW to setup the OpenGL Function pointers
    glewInit();

    // Define the viewport dimensions
    glViewport(0, 0, WIDTH, HEIGHT);

    std::string vertexshader = getFileContent("test_vs.glsl");
    vertexShaderSource = (GLchar *) vertexshader.c_str();
    std::string fragmentshader = getFileContent("test_fs.glsl");
    fragmentShaderSource = (GLchar *) fragmentshader.c_str();

    // Build and compile our shader program
    // Vertex shader
    GLint 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
    GLint 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
    GLint 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[] = {
    //  // First triangle
    //   0.5f,  0.5f,  // Top Right
    //   0.5f, -0.5f,  // Bottom Right
    //  -0.5f,  0.5f,  // Top Left 
    //  // Second triangle
    //   0.5f, -0.5f,  // Bottom Right
    //  -0.5f, -0.5f,  // Bottom Left
    //  -0.5f,  0.5f   // Top Left
    //}; 
    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
        -0.5f,  0.5f, 0.0f,   // Top Left 
        -0.5f, -1.0f, 0.0f,
         0.5f, -1.0f, 0.0f,
         0.0f,  1.0f, 0.0f
    };
    GLuint indices[] = {  // Note that we start from 0!
        0, 1, 3,  // First Triangle
        1, 2, 3,   // Second Triangle
        4, 5, 6
    };
    GLuint VBO, VAO, EBO;
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);
    glGenBuffers(1, &EBO);
    // 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);

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, 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


    // Uncommenting this call will result in wireframe polygons.
    glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
    //other option
    //glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);


    // Game loop
    while (!glfwWindowShouldClose(window))
    {
        // Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions
        glfwPollEvents();

        // Render
        // Clear the colorbuffer
        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, 9);
        //glDrawElements(GL_TRIANGLES, 9, GL_UNSIGNED_INT, 0);
        glBindVertexArray(0);

        // Swap the screen buffers
        glfwSwapBuffers(window);
    }
    // Properly de-allocate all resources once they've outlived their purpose
    glDeleteVertexArrays(1, &VAO);
    glDeleteBuffers(1, &VBO);
    glDeleteBuffers(1, &EBO);
    // Terminate GLFW, clearing any resources allocated by GLFW.
    glfwTerminate();
    return 0;
}
Esempio n. 22
0
// The MAIN function, from here we start the application and run the 
// game loop
int main()
{
    std::cout << "Starting GLFW context, OpenGL 3.3" << std::endl;
    // Init GLFW
    glfwInit();
    // Set all the required options for GLFW
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    // OS X requests 3.3 differently.
#ifdef __APPLEOS__
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    // Create a GLFWwindow object that we can use for GLFW's functions
    GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", 
                                          nullptr, nullptr);    
    if (window == nullptr)
    {
        std::cout << "Failed to create GLFW window" << std::endl;
        glfwTerminate();
        return -1;
    }
    glfwMakeContextCurrent(window);
    // Set the required callback functions
    glfwSetKeyCallback(window, key_callback);

    // Set this to true so GLEW knows to use a modern approach to retrieving
    // function pointers and extensions
    // More hacking for my autocomplete.
#ifndef CLANG_COMPLETE_ONLY
    glewExperimental = GL_TRUE;
    // Initialize GLEW to setup the OpenGL Function pointers
    if (glewInit() != GLEW_OK)
    {
        std::cout << "Failed to initialize GLEW" << std::endl;
        return -1;
    }    
#endif

    // Define the viewport dimensions
    // Corrected from the tutorial, should request framebuffer size instead.
    // Technically should also write a callback when the window is resized
    // with framebuffer_size_callback. See GLFW docs. This will do for now.
    int fbwidth, fbheight;
    glfwGetFramebufferSize(window, &fbwidth, &fbheight);

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

    // ---------- BEGIN OPENGL ----------- //
    
    // Shader creation
    Shader edgeShader("vertex_shader_unsliced.glsl", "fragment_shader_unsliced.glsl");

    // Data
    GLfloat vertices[] = {
        // Positions           
         0.6f,   0.6f,   0.6f,   0.6f,
         0.6f,  -0.6f,   0.6f,   0.6f,  
        -0.6f,  -0.6f,   0.6f,   0.6f,
        -0.6f,   0.6f,   0.6f,   0.6f,

         0.6f,   0.6f,  -0.6f,   0.6f,
         0.6f,  -0.6f,  -0.6f,   0.6f,
        -0.6f,  -0.6f,  -0.6f,   0.6f,
        -0.6f,   0.6f,  -0.6f,   0.6f,

         0.8f,   0.8f,   0.8f,  -0.8f,
         0.8f,  -0.8f,   0.8f,  -0.8f,  
        -0.8f,  -0.8f,   0.8f,  -0.8f,
        -0.8f,   0.8f,   0.8f,  -0.8f,

         0.8f,   0.8f,  -0.8f,  -0.8f,
         0.8f,  -0.8f,  -0.8f,  -0.8f,
        -0.8f,  -0.8f,  -0.8f,  -0.8f,
        -0.8f,   0.8f,  -0.8f,  -0.8f
    };

    GLuint indices[] = {
        // Near Cube
         0,  2,  1,
         0,  3,  2,
         7,  5,  6,
         7,  4,  5,
         3,  4,  7,
         3,  0,  4,
         6,  1,  2,
         6,  5,  1,
         6,  3,  7,
         6,  2,  3,
         1,  4,  0,
         1,  5,  4,
        // Far Cube
         8, 10,  9,
         8, 11, 10,
        15, 13, 14,
        15, 12, 13,
        11, 12, 15,
        11,  8, 12,
        14,  9, 10,
        14, 13,  9,
        14, 11, 15,
        14, 10, 11,
         9, 12,  8,
         9, 13, 12,
        // Front Cube
         0,  2,  1,
         0,  3,  2,
        11,  9, 10,
        11,  8,  9,
         3,  0,  8,
         3,  8, 11,
        10,  1,  2,
        10,  9,  1,
        10,  3, 11,
        10,  2,  3,
         1,  8,  0,
         1,  9,  8,
        // Back Cube
         5,  7,  4,
         5,  6,  7,
        14, 12, 15,
        14, 13, 12,
         6,  5, 13,
         6, 13, 14,
        15,  4,  7,
        15, 12,  4,
        15,  6, 14,
        15,  7,  6,
         4, 13,  5,
         4, 12, 13,
        // Top Cube
         4,  7,  3,
         4,  3,  0,
        15,  8, 11,
        15, 12,  8,
         7, 12, 15,
         7,  4, 12,
         0, 11,  8,
         0,  3, 11,
         3,  7, 15,
         3, 15, 11,
         4,  0,  8,
         4,  8, 12,
        // Bottom Cube
         1,  2,  6,
         1,  6,  5,
        10, 13, 14,
        10,  9, 13,
         2,  9, 10,
         2,  1,  9,
         5, 14, 13,
         5,  6, 14,
         6,  2, 10,
         6, 10, 14,
         1,  5, 13,
         1, 13,  9,
        // Left Cube
         3,  7,  6,
         3,  6,  2,
        15, 11, 10,
        15, 10, 14,
        11, 15,  7,
        11,  7,  3,
        14,  2,  6,
        14, 10,  2,
         7, 15, 14,
         7, 14,  6,
        11,  3,  2,
        11,  2, 10,
        // Right Cube
         1,  5,  4,
         1,  4,  0,
        13,  9,  8,
        13,  8, 12,
         9, 13,  5,
         9,  5,  1,
        12,  0,  4,
        12,  8,  0,
         5, 13, 12,
         5, 12,  4,
         9,  1,  0,
         9,  0,  8
    };

    // Textures

    // Set up buffer stuff
    GLuint VAO, VBO, EBO;
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);
    glGenBuffers(1, &EBO);
    
    // Game loop
    while (!glfwWindowShouldClose(window))
    {
        // Check if any events have been activated (key pressed, mouse moved
        // etc.) and call corresponding response functions
        glfwPollEvents();

        // Setup stuff
        glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        glEnable(GL_BLEND);
        glLineWidth(3);

        // 4D-3D Transformations
        glm::mat4 model4D(1.0f), view4D;
        GLfloat theta = glm::radians((GLfloat)glfwGetTime() * 50.0f);
        GLfloat cs = cos(theta), sn = sin(theta);
        model4D[0][0] = cs;
        model4D[0][3] = -sn;
        model4D[3][0] = sn;
        model4D[3][3] = cs;
        glm::mat4x3 projection4D;
        glm::vec4 from(0.0f, 0.0f, 0.0f, 4.0f), to(0.0f, 0.0f, 0.0f, 0.0f); 
        glm::vec4 up(0.0f, 1.0f, 0.0f, 0.0f), over(0.0f, 0.0f, 1.0f, 0.0f);
        view4D = lookAt4D(from, to, up, over);
        std::cout << "Proj Mat: " << std::endl;
        printMat(view4D, 4, 4);
        projection4D = proj4D();

        GLfloat *projVert = new GLfloat[16*7];
        std::cout << "--------------------------------" << std::endl;
        for(int i = 0; i != 16; i++) {
            // Project each vertex to the 3D space
            glm::vec4 vert4(vertices[i*4], vertices[i*4+1],
                            vertices[i*4+2], vertices[i*4+3]);
            glm::vec4 viewVert = view4D * (model4D * vert4 - from); 
            printVec(viewVert, 4);
            glm::vec3 vert3 = projection4D * view4D * (model4D * vert4 - from);
            projVert[i*7] = vert3.x;
            projVert[i*7+1] = vert3.y;
            projVert[i*7+2] = vert3.z;
            if (i < 8) {
                projVert[i*7+3] = 1.0f;
                projVert[i*7+4] = 0.0f;
                projVert[i*7+5] = 0.0f;
            } else {
                projVert[i*7+3] = 0.0f;
                projVert[i*7+4] = 0.0f;
                projVert[i*7+5] = 1.0f;
            }
            projVert[i*7+6] = (viewVert.w + 5.0f)/2.0f;
        }

        // 3D-2D Transformations
        glm::mat4 view3D = glm::lookAt(glm::vec3(3.0f, 1.2f, 2.0f),
                                       glm::vec3(0.0f, 0.0f, 0.0f),
                                       glm::vec3(0.0f, 1.0f, 0.0f));
        glm::mat4 proj3D = glm::perspective(glm::radians(45.0f),
                                            (float)WIDTH/(float)HEIGHT,
                                            0.1f, 100.0f);
        // Shader Uniforms
        edgeShader.Use();

        GLint viewLoc = glGetUniformLocation(edgeShader.Program,
                                             "view3D");
        GLint projectionLoc = glGetUniformLocation(edgeShader.Program,
                                                   "projection3D");
        glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view3D));
        glUniformMatrix4fv(projectionLoc, 1, GL_FALSE, glm::value_ptr(proj3D));

        // Load Vertices
        glBindVertexArray(VAO);
        glBindBuffer(GL_ARRAY_BUFFER, VBO);
        glBufferData(GL_ARRAY_BUFFER, 16*7*sizeof(GL_FLOAT), projVert, GL_DYNAMIC_DRAW);
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO);
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices, 
                     GL_DYNAMIC_DRAW);
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 7*sizeof(GL_FLOAT), 
                              (GLvoid*)0);
        glEnableVertexAttribArray(0);
        glVertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, 7*sizeof(GL_FLOAT), 
                              (GLvoid*)(3*sizeof(GL_FLOAT)));
        glEnableVertexAttribArray(1);

        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
        glDrawElements(GL_TRIANGLES, 8*12*3, GL_UNSIGNED_INT, 0);
        glBindVertexArray(0);

        // Swap the screen buffers
        glfwSwapBuffers(window);

        delete[] projVert;
    }

    // Terminate GLFW, clearing any resources allocated by GLFW.
    glfwTerminate();
    glDeleteVertexArrays(1, &VAO);
    glDeleteBuffers(1, &VBO);
    glDeleteBuffers(1, &EBO);
    return 0;
}
Esempio n. 23
0
GameEngine::GameEngine(const std::string& application_name, WindowMode windowMode) {
  glfwSetErrorCallback(ErrorCallback);

  if (!glfwInit()) {
    std::terminate();
  }

  // Window creation
  GLFWmonitor *monitor = glfwGetPrimaryMonitor();
  const GLFWvidmode *vidmode = glfwGetVideoMode(monitor);

#ifdef USE_DEBUG_CONTEXT
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
  glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE);
#else
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
#endif

  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, true);
  glfwWindowHint(GLFW_DEPTH_BITS, 24);
  glfwWindowHint(GLFW_STENCIL_BITS, 8);

  if (windowMode == WindowMode::kFullScreen) {
    window_ = glfwCreateWindow(vidmode->width, vidmode->height,
                               application_name.c_str(), monitor, nullptr);
  } else {
    window_ = glfwCreateWindow(vidmode->width, vidmode->height,
                               application_name.c_str(), nullptr, nullptr);
  }

  if (!window_) {
    std::cerr << "FATAL: Couldn't create a glfw window. Aborting now." << std::endl;
    glfwTerminate();
    std::terminate();
  }

  // Check the created OpenGL context's version
  int ogl_major_version = glfwGetWindowAttrib(window_, GLFW_CONTEXT_VERSION_MAJOR);
  int ogl_minor_version = glfwGetWindowAttrib(window_, GLFW_CONTEXT_VERSION_MINOR);
  std::cout << "OpenGL version: "  << ogl_major_version << '.' << ogl_minor_version << std::endl;
  int width, height;
  glfwGetFramebufferSize(window_, &width, &height);
  std::cout << "Resolution: "  << width << " x " << height << std::endl;

  if (ogl_major_version < 4 || (ogl_major_version == 4 && ogl_minor_version < 5)) {
    std::cerr << "At least OpenGL version 4.5 is required to run this program\n";
    std::terminate();
  }

  glfwMakeContextCurrent(window_);

  // No V-sync needed.
  glfwSwapInterval(0);

  bool success = gladLoadGL();
  if (!success) {
    std::cerr << "gladLoadGL failed" << std::endl;
    std::terminate();
  }

#ifdef USE_DEBUG_CONTEXT
  glDebugMessageCallback(&DebugCallback, nullptr);
#endif

  success = Label::InitializeTextRendering();
  if (!success) {
    std::cerr << "Label::InitializeTextRendering failed" << std::endl;
    std::terminate();
  }

  MeshRenderer::InitializeMeshDataStorage();

  // Only initialize after the OpenGL context has been created
  shader_manager_ = make_unique<ShaderManager>();

  // OpenGL initialization
  gl::Enable(gl::kDepthTest);
  glClipControl(GL_LOWER_LEFT, GL_ZERO_TO_ONE);

  // GLFW callbacks
  glfwSetWindowUserPointer(window_, this);
  glfwSetKeyCallback(window_, KeyCallback);
  glfwSetCharCallback(window_, CharCallback);
  glfwSetFramebufferSizeCallback(window_, ScreenResizeCallback);
  glfwSetScrollCallback(window_, MouseScrolledCallback);
  glfwSetMouseButtonCallback(window_, MouseButtonPressed);
  glfwSetCursorPosCallback(window_, MouseMoved);
}
Esempio n. 24
0
//********************//
//Engine Display Class//
//********************//
void Engine_Init::RunDisplay()
{
	//GLFW Initiate
	errchk(glfwInit());
	cout << glfwGetVersionString() << endl;

	//GLFW Set Window Properties
	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
	glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
	glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
	glfwWindowHint(GLFW_SAMPLES, props.MSAA);

	props.init(); //Initialize the engine properties from the properties input file "Settings."
	camera.init(props); //Initialize the camera class.

	//Initialize Window
	switch(props.FullScreen)
	{
	 case 0: 
	 {window = glfwCreateWindow(props.WinWidth, props.WinHeight, "GameEngine Test", nullptr, nullptr);break;}
	 case 1: 
	 {window = glfwCreateWindow(props.WinWidth, props.WinHeight, "GameEngine Test", glfwGetPrimaryMonitor(), nullptr);break;}
	}

	if( window == NULL ){
        	fprintf( stderr, "Failed to open GLFW window.\n" );
        	glfwTerminate();
    	}

	glfwMakeContextCurrent(window);
	glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);

	//Set the call back functions
	setEventHandling();
        glfwSetKeyCallback(window, StateBase::keycallback_dispatch);
        glfwSetCursorPosCallback(window, StateBase::mousecallback_dispatch);
        glfwSetScrollCallback(window, StateBase::scrollcallback_dispatch);

	//Initialize Glew
	glewExperimental = GL_TRUE;
	glewInit();

	//Set view port dimensions
	glViewport(0, 0, props.WinWidth, props.WinHeight); 

	//Setup OpenGL Options
	glEnable(GL_DEPTH_TEST);
	glEnable(GL_MULTISAMPLE);
    	glEnable(GL_CULL_FACE);
    	glEnable(GL_BLEND);
    	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

	//Poly Fill Mode	
	glPolygonMode(GL_FRONT_AND_BACK,GL_FILL);

	//System Processors
	int NProc = sysconf( _SC_NPROCESSORS_ONLN );
	cout << "Number of System Processors: " << NProc << endl;

	//Max Number of Attributes
	GLint nrAttributes;
	glGetIntegerv(GL_MAX_VERTEX_ATTRIBS, &nrAttributes);
	cout << "Maximum nr of vertex attributes supported: " << nrAttributes << std::endl;

	GLErrorCatch("GL Preamble");

	//Set the frames per second timer
	fpsTimer ft;

	//This sets the View and Projection "Matrices" Uniform Buffer Object at global location 0;
	//TM.SetViewUniformBufferObject();

	//Setup screen text writing
	SW.Setup("bin/fonts/FreeSans.ttf",props.WinWidth,props.WinHeight);//Setup screen font
	GLErrorCatch("Screen Writer Setup");

	//Initialize Shaders
	SCC.ShaderLoader();
	GLErrorCatch("Shader Handling");

	//Initialize SolarSystem
	double TIMECHECK = glfwGetTime();
	solarsystem.SetupClass(OPC);
	cout << "SolarSys CLASS SETUP TIME: " << glfwGetTime() - TIMECHECK  << "\n";
	cout << "SolarSystem class Setup...\n";
	solarsystem.GenerateSolarSystem(OPC,0,0);
	cout << "SolarSystem Generated...\n";
	GLErrorCatch("SolarSystem Generation");

	//Setup Global Uniform Handler
	GGUBO.SetGlobalUBO(SCC);
	camera.SetProjViewUBO(SCC);
	
	GLErrorCatch("Uniform Handling");

	//Setup Timing Stats
	TimingStats TS(SW,props);
	TS.SetObject("Preamble");
	TS.SetObject("camera.PrepareCameraData");
	TS.SetObject("GGUBO.UpdateGlobalUBO");
	TS.SetObject("solarsystem.PrepareData");
	TS.SetObject("ProcessDrawArray");
	TS.SetObject("PrintScreenTimers");
	TS.SetObject("Screen_Console");
	TS.SetObject("glfwSwapBuffers");
	TS.SetObject("drawArray.ClearDrawArrays");
	TS.SetObject("EventPolling");
	TS.SetObject("Skybox Drawing");

	while(!glfwWindowShouldClose(window))
	{
                //*********************
                //Frame Timer
                //*********************
		TS.TS(0);
                dt.SetTime();

		//*************************
		//Sets the background color
                //*************************
                glClearColor(Env.bgColor.x, Env.bgColor.y, Env.bgColor.z, 0.0f);
                glClear(GL_COLOR_BUFFER_BIT  | GL_DEPTH_BUFFER_BIT);
		TS.TE(0);

		//***************
		//Setup Scene
		//***************
		//Prepare the camera class for the frame
		//cout << "***TEST1***" << endl;
		TS.TS(1);
		camera.PrepareCameraData();
		TS.TE(1);
		//Update the global uniform buffer objects
		TS.TS(2);
		GGUBO.UpdateGlobalUBO(camera);
		TS.TE(2);
		//Prepare the solarsystem data
		//cout << "***TEST2***" << endl;
		TS.TS(3);
		solarsystem.PrepareData(OPC,drawArray,drawInstArray,camera,dt,false);
		TS.TE(3);

		//***************
                //Scene Rendering
                //***************
		//cout << "***TEST3***" << endl;
		//Draw all objects

		TS.TS(10);
		skybox.DrawSkybox(camera,props);
		TS.TE(10);

		TS.TS(4);
		ProcessDrawArray();
		TS.TE(4);

		//*******************
		//Interface Rendering
		//*******************
		//Render Frame Timer
		TS.TS(5);
		PrintScreenTimers(SW,ft);
		TS.TE(5);
		//cout << "***TEST4***" << endl;
		//Console Functions
		TS.TS(6);
		Screen_Console(SW);
		TS.TE(6);

		//Statistics Rendering
		TS.CalcAndRenderStats();

		//*************
		//Swap Buffers
		//*************
		TS.TS(7);
		//glfwSwapInterval(1); //Seems to slow the program to 30fps
		glfwSwapBuffers(window);//Something is wrong here, SUPER expensive
		TS.TE(7);

                //*********************
                //Check and call events
                //*********************
                TS.TS(9);
                glfwPollEvents();
                //glfwWaitEvents();
                Do_Movement();
                TS.TE(9);

                //*************
                //Frame Cleanup
                //*************
		TS.TS(8);
		drawArray.DrawArrayReset();
		drawInstArray.ClearInstDrawArrays();
		TS.TE(8);
		//cout << "FRAME END\n";

		//GLErrorCatch("MainLoop");
	}

	drawArray.ClearDrawArrays();
	glfwTerminate();
}
Esempio n. 25
0
int
main(int argc, char **argv)
{
    /* Options */
    bool fullscreen = false;
    const char *title = "OpenGL 3.3 Demo";

    int opt;
    while ((opt = getopt(argc, argv, "f")) != -1) {
        switch (opt) {
        case 'f':
            fullscreen = true;
            break;
        default:
            exit(EXIT_FAILURE);
        }
    }

    /* Create window and OpenGL context */
    struct graphics_context context;
    if (!glfwInit()) {
        fprintf(stderr, "GLFW3: failed to initialize\n");
        exit(EXIT_FAILURE);
    }
    glfwWindowHint(GLFW_SAMPLES, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    if (fullscreen) {
        GLFWmonitor *monitor = glfwGetPrimaryMonitor();
        const GLFWvidmode *m = glfwGetVideoMode(monitor);
        context.window =
            glfwCreateWindow(m->width, m->height, title, monitor, NULL);
    } else {
        context.window =
            glfwCreateWindow(640, 640, title, NULL, NULL);
    }
    glfwMakeContextCurrent(context.window);
    glfwSwapInterval(1);

    /* Initialize gl3w */
    if (gl3wInit()) {
        fprintf(stderr, "gl3w: failed to initialize\n");
        exit(EXIT_FAILURE);
    }

    /* Shader sources */
    const GLchar *vert_shader =
        "#version 330\n"
        "layout(location = 0) in vec2 point;\n"
        "uniform float angle;\n"
        "void main() {\n"
        "    mat2 rotate = mat2(cos(angle), -sin(angle),\n"
        "                       sin(angle), cos(angle));\n"
        "    gl_Position = vec4(0.75 * rotate * point, 0.0, 1.0);\n"
        "}\n";
    const GLchar *frag_shader =
        "#version 330\n"
        "out vec4 color;\n"
        "void main() {\n"
        "    color = vec4(1, 0.15, 0.15, 0);\n"
        "}\n";

    /* Compile and link OpenGL program */
    GLuint vert = compile_shader(GL_VERTEX_SHADER, vert_shader);
    GLuint frag = compile_shader(GL_FRAGMENT_SHADER, frag_shader);
    context.program = link_program(vert, frag);
    context.uniform_angle = glGetUniformLocation(context.program, "angle");
    glDeleteShader(frag);
    glDeleteShader(vert);

    /* Prepare vertex buffer object (VBO) */
    glGenBuffers(1, &context.vbo_point);
    glBindBuffer(GL_ARRAY_BUFFER, context.vbo_point);
    glBufferData(GL_ARRAY_BUFFER, sizeof(SQUARE), SQUARE, GL_STATIC_DRAW);
    glBindBuffer(GL_ARRAY_BUFFER, 0);

    /* Prepare vertrex array object (VAO) */
    glGenVertexArrays(1, &context.vao_point);
    glBindVertexArray(context.vao_point);
    glBindBuffer(GL_ARRAY_BUFFER, context.vbo_point);
    glVertexAttribPointer(ATTRIB_POINT, 2, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttribArray(ATTRIB_POINT);
    glBindBuffer(GL_ARRAY_BUFFER, 0);
    glBindVertexArray(0);

    /* Start main loop */
    glfwSetKeyCallback(context.window, key_callback);
    context.lastframe = glfwGetTime();
    context.framecount = 0;
    while (!glfwWindowShouldClose(context.window)) {
        render(&context);
        glfwPollEvents();
    }
    fprintf(stderr, "Exiting ...\n");

    /* Cleanup and exit */
    glDeleteVertexArrays(1, &context.vao_point);
    glDeleteBuffers(1, &context.vbo_point);
    glDeleteProgram(context.program);

    glfwTerminate();
    return 0;
}
Esempio n. 26
0
	void mutipleLight()
	{
		// Init GLFW
		glfwInit();
		// Set all the required options for GLFW
		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);
        glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

		// Create a GLFWwindow object that we can use for GLFW's functions
		GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr);
		glfwMakeContextCurrent(window);

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

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

		// Set this to true so GLEW knows to use a modern approach to retrieving function pointers and extensions
		glewExperimental = GL_TRUE;
		// Initialize GLEW to setup the OpenGL Function pointers
		glewInit();

		// Define the viewport dimensions
		glViewport(0, 0, WIDTH, HEIGHT);

		// OpenGL options
		glEnable(GL_DEPTH_TEST);


		// Build and compile our shader program
        Shader2 lightingShader("/Users/cc_xueqin/programming/learning/opengl/project/learn_opengl/learn_opengl/shader/light_mutiple.vs", "/Users/cc_xueqin/programming/learning/opengl/project/learn_opengl/learn_opengl/shader/light_mutiple.frag");

        Shader2 lampShader("/Users/cc_xueqin/programming/learning/opengl/project/learn_opengl/learn_opengl/shader/lamp.vs", "/Users/cc_xueqin/programming/learning/opengl/project/learn_opengl/learn_opengl/shader/lamp.frag");


		// Set up vertex data (and buffer(s)) and attribute pointers
		GLfloat vertices[] = {
			// Positions          // Normals           // Texture Coords
			-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f,
			0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 0.0f,
			0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f,
			0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 1.0f, 1.0f,
			-0.5f, 0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 1.0f,
			-0.5f, -0.5f, -0.5f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f,

			-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
			0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f,
			0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f,
			0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f,
			-0.5f, 0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f,
			-0.5f, -0.5f, 0.5f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,

			-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
			-0.5f, 0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 1.0f,
			-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
			-0.5f, -0.5f, -0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
			-0.5f, -0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
			-0.5f, 0.5f, 0.5f, -1.0f, 0.0f, 0.0f, 1.0f, 0.0f,

			0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,
			0.5f, 0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 1.0f,
			0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
			0.5f, -0.5f, -0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
			0.5f, -0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 0.0f, 0.0f,
			0.5f, 0.5f, 0.5f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f,

			-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f,
			0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 1.0f,
			0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f,
			0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 1.0f, 0.0f,
			-0.5f, -0.5f, 0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f,
			-0.5f, -0.5f, -0.5f, 0.0f, -1.0f, 0.0f, 0.0f, 1.0f,

			-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f,
			0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f,
			0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f,
			0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 1.0f, 0.0f,
			-0.5f, 0.5f, 0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f,
			-0.5f, 0.5f, -0.5f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f
		};
		// Positions all containers
		glm::vec3 cubePositions[] = {
			glm::vec3(0.0f, 0.0f, 0.0f),
			glm::vec3(2.0f, 5.0f, -15.0f),
			glm::vec3(-1.5f, -2.2f, -2.5f),
			glm::vec3(-3.8f, -2.0f, -12.3f),
			glm::vec3(2.4f, -0.4f, -3.5f),
			glm::vec3(-1.7f, 3.0f, -7.5f),
			glm::vec3(1.3f, -2.0f, -2.5f),
			glm::vec3(1.5f, 2.0f, -2.5f),
			glm::vec3(1.5f, 0.2f, -1.5f),
			glm::vec3(-1.3f, 1.0f, -1.5f)
		};
		// Positions of the point lights
		glm::vec3 pointLightPositions[] = {
			glm::vec3(0.7f, 0.2f, 2.0f),
			glm::vec3(2.3f, -3.3f, -4.0f),
			glm::vec3(-4.0f, 2.0f, -12.0f),
			glm::vec3(0.0f, 0.0f, -3.0f)
		};
		// First, set the container's VAO (and VBO)
		GLuint VBO, containerVAO;
		glGenVertexArrays(1, &containerVAO);
		glGenBuffers(1, &VBO);

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

		glBindVertexArray(containerVAO);
		glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0);
		glEnableVertexAttribArray(0);
		glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
		glEnableVertexAttribArray(1);
		glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)(6 * sizeof(GLfloat)));
		glEnableVertexAttribArray(2);
		glBindVertexArray(0);

		// Then, we set the light's VAO (VBO stays the same. After all, the vertices are the same for the light object (also a 3D cube))
		GLuint lightVAO;
		glGenVertexArrays(1, &lightVAO);
		glBindVertexArray(lightVAO);
		// We only need to bind to the VBO (to link it with glVertexAttribPointer), no need to fill it; the VBO's data already contains all we need.
		glBindBuffer(GL_ARRAY_BUFFER, VBO);
		// Set the vertex attributes (only position data for the lamp))
		glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * sizeof(GLfloat), (GLvoid*)0); // Note that we skip over the other data in our buffer object (we don't need the normals/textures, only positions).
		glEnableVertexAttribArray(0);
		glBindVertexArray(0);


		// Load textures
		GLuint diffuseMap, specularMap, emissionMap;
		glGenTextures(1, &diffuseMap);
		glGenTextures(1, &specularMap);
		glGenTextures(1, &emissionMap);
		int width, height;
		unsigned char* image;
		// Diffuse map
		image = SOIL_load_image("/Users/cc_xueqin/programming/learning/opengl/project/learn_opengl/res/container2.png", &width, &height, 0, SOIL_LOAD_RGB);
		glBindTexture(GL_TEXTURE_2D, diffuseMap);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
		glGenerateMipmap(GL_TEXTURE_2D);
		SOIL_free_image_data(image);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST_MIPMAP_NEAREST);
		// Specular map
		image = SOIL_load_image("/Users/cc_xueqin/programming/learning/opengl/project/learn_opengl/res/container2_specular.png", &width, &height, 0, SOIL_LOAD_RGB);
		glBindTexture(GL_TEXTURE_2D, specularMap);
		glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, image);
		glGenerateMipmap(GL_TEXTURE_2D);
		SOIL_free_image_data(image);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
		glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST_MIPMAP_NEAREST);
		glBindTexture(GL_TEXTURE_2D, 0);


		// Set texture units
		lightingShader.Use();
		glUniform1i(glGetUniformLocation(lightingShader.Program, "material.diffuse"), 0);
		glUniform1i(glGetUniformLocation(lightingShader.Program, "material.specular"), 1);


		// Game loop
		while (!glfwWindowShouldClose(window))
		{
			// Calculate deltatime of current frame
			GLfloat currentFrame = glfwGetTime();
			deltaTime = currentFrame - lastFrame;
			lastFrame = currentFrame;

			// Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions
			glfwPollEvents();
			do_movement();

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


			// Use cooresponding shader when setting uniforms/drawing objects
			lightingShader.Use();
			GLint viewPosLoc = glGetUniformLocation(lightingShader.Program, "viewPos");
			glUniform3f(viewPosLoc, camera.Position.x, camera.Position.y, camera.Position.z);
			// Set material properties
			glUniform1f(glGetUniformLocation(lightingShader.Program, "material.shininess"), 32.0f);
			// == ==========================
			// Here we set all the uniforms for the 5/6 types of lights we have. We have to set them manually and index 
			// the proper PointLight struct in the array to set each uniform variable. This can be done more code-friendly
			// by defining light types as classes and set their values in there, or by using a more efficient uniform approach
			// by using 'Uniform buffer objects', but that is something we discuss in the 'Advanced GLSL' tutorial.
			// == ==========================
			//// Directional light
			//glUniform3f(glGetUniformLocation(lightingShader.Program, "dirLight.direction"), -0.2f, -1.0f, -0.3f);
			//glUniform3f(glGetUniformLocation(lightingShader.Program, "dirLight.ambient"), 0.05f, 0.05f, 0.05f);
			//glUniform3f(glGetUniformLocation(lightingShader.Program, "dirLight.diffuse"), 0.4f, 0.4f, 0.4f);
			//glUniform3f(glGetUniformLocation(lightingShader.Program, "dirLight.specular"), 0.5f, 0.5f, 0.5f);

			//// Point light 1
			//glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[0].position"), pointLightPositions[2].x, pointLightPositions[2].y, pointLightPositions[2].z);
			//glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[0].ambient"), 0.1745f, 0.1175f, 0.1175f);
			//glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[0].diffuse"), 0.61424f, 0.04136f, 0.04136f);
			//glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[0].specular"), 0.727811f, 0.626959f, 0.626959f);
			//glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[0].constant"), 1.0f);
			//glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[0].linear"), 0.09);
			//glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[0].quadratic"), 0.032);
			//// Point light 2
			//glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[1].position"), pointLightPositions[1].x, pointLightPositions[1].y, pointLightPositions[1].z);
			//glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[1].ambient"), 0.2125, 0.1275, 0.054);
			//glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[1].diffuse"), 0.714, 0.4284, 0.1814f);
			//glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[1].specular"), 0.3935f, 0.271f, 0.167f);
			//glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[1].constant"), 1.0f);
			//glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[1].linear"), 0.09);
			//glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[1].quadratic"), 0.032);
			//// Point light 3
			//glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[2].position"), pointLightPositions[0].x, pointLightPositions[0].y, pointLightPositions[0].z);
			//glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[2].ambient"), 0.0f, 0.05f, 0.0f);
			//glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[2].diffuse"), 0.4f, 0.5f, 0.4f);
			//glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[2].specular"), 0.04f, 0.7f, 0.04f);
			//glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[2].constant"), 1.0f);
			//glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[2].linear"), 0.09);
			//glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[2].quadratic"), 0.032);
			//// Point light 4
			//glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[3].position"), pointLightPositions[3].x, pointLightPositions[3].y, pointLightPositions[3].z);
			//glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[3].ambient"), 0.05f, 0.05f, 0.05f);
			//glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[3].diffuse"), 0.8f, 0.8f, 0.8f);
			//glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[3].specular"), 1.0f, 1.0f, 1.0f);
			//glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[3].constant"), 1.0f);
			//glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[3].linear"), 0.09);
			//glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[3].quadratic"), 0.032);
			//// SpotLight
		 //   glUniform3f(glGetUniformLocation(lightingShader.Program, "spotLight.position"), camera.Position.x, camera.Position.y, camera.Position.z);
			//glUniform3f(glGetUniformLocation(lightingShader.Program, "spotLight.direction"), camera.Front.x, camera.Front.y, camera.Front.z);
			//glUniform3f(glGetUniformLocation(lightingShader.Program, "spotLight.ambient"), 0.0f, 0.0f, 0.0f);
			//glUniform3f(glGetUniformLocation(lightingShader.Program, "spotLight.diffuse"), 1.0f, 1.0f, 1.0f);
			//glUniform3f(glGetUniformLocation(lightingShader.Program, "spotLight.specular"), 1.0f, 1.0f, 1.0f);
			//glUniform1f(glGetUniformLocation(lightingShader.Program, "spotLight.constant"), 1.0f);
			//glUniform1f(glGetUniformLocation(lightingShader.Program, "spotLight.linear"), 0.09);
			//glUniform1f(glGetUniformLocation(lightingShader.Program, "spotLight.quadratic"), 0.032);
			//glUniform1f(glGetUniformLocation(lightingShader.Program, "spotLight.cutOff"), glm::cos(glm::radians(12.5f)));
			//glUniform1f(glGetUniformLocation(lightingShader.Program, "spotLight.outerCutOff"), glm::cos(glm::radians(15.0f)));

			// == ==============================================================================================
			//       FACTORY
			// == ==============================================================================================
			glm::vec3 pointLightColors[] = {
				glm::vec3(0.2f, 0.2f, 0.6f),
				glm::vec3(0.3f, 0.3f, 0.7f),
				glm::vec3(0.0f, 0.0f, 0.3f),
				glm::vec3(0.4f, 0.4f, 0.4f)
			};

			// Directional light
			glUniform3f(glGetUniformLocation(lightingShader.Program, "dirLight.direction"), -0.2f, -1.0f, -0.3f);
			glUniform3f(glGetUniformLocation(lightingShader.Program, "dirLight.ambient"), 0.05f, 0.05f, 0.1f);
			glUniform3f(glGetUniformLocation(lightingShader.Program, "dirLight.diffuse"), 0.2f, 0.2f, 0.7);
			glUniform3f(glGetUniformLocation(lightingShader.Program, "dirLight.specular"), 0.7f, 0.7f, 0.7f);
			// Point light 1
			glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[0].position"), pointLightPositions[0].x, pointLightPositions[0].y, pointLightPositions[0].z);
			glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[0].ambient"), pointLightColors[0].x * 0.1, pointLightColors[0].y * 0.1, pointLightColors[0].z * 0.1);
			glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[0].diffuse"), pointLightColors[0].x, pointLightColors[0].y, pointLightColors[0].z);
			glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[0].specular"), pointLightColors[0].x, pointLightColors[0].y, pointLightColors[0].z);
			glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[0].constant"), 1.0f);
			glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[0].linear"), 0.09);
			glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[0].quadratic"), 0.032);
			// Point light 2
			glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[1].position"), pointLightPositions[1].x, pointLightPositions[1].y, pointLightPositions[1].z);

			glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[1].ambient"), pointLightColors[1].x * 0.1, pointLightColors[1].y * 0.1, pointLightColors[1].z * 0.1);

			glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[1].diffuse"), pointLightColors[1].x, pointLightColors[1].y, pointLightColors[1].z);

			glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[1].specular"), pointLightColors[1].x, pointLightColors[1].y, pointLightColors[1].z);

			glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[1].constant"), 1.0f);

			glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[1].linear"), 0.09);

			glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[1].quadratic"), 0.032);
			// Point light 3

			glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[2].position"), pointLightPositions[2].x, pointLightPositions[2].y, pointLightPositions[2].z);

			glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[2].ambient"), pointLightColors[2].x * 0.1, pointLightColors[2].y * 0.1, pointLightColors[2].z * 0.1);

			glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[2].diffuse"), pointLightColors[2].x, pointLightColors[2].y, pointLightColors[2].z);

			glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[2].specular"), pointLightColors[2].x, pointLightColors[2].y, pointLightColors[2].z);

			glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[2].constant"), 1.0f);

			glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[2].linear"), 0.09);

			glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[2].quadratic"), 0.032);
			// Point light 4

			glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[3].position"), pointLightPositions[3].x, pointLightPositions[3].y, pointLightPositions[3].z);

			glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[3].ambient"), pointLightColors[3].x * 0.1, pointLightColors[3].y * 0.1, pointLightColors[3].z * 0.1);

			glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[3].diffuse"), pointLightColors[3].x, pointLightColors[3].y, pointLightColors[3].z);

			glUniform3f(glGetUniformLocation(lightingShader.Program, "pointLights[3].specular"), pointLightColors[3].x, pointLightColors[3].y, pointLightColors[3].z);

			glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[3].constant"), 1.0f);

			glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[3].linear"), 0.09);

			glUniform1f(glGetUniformLocation(lightingShader.Program, "pointLights[3].quadratic"), 0.032);
			// SpotLight

			glUniform3f(glGetUniformLocation(lightingShader.Program, "spotLight.position"), camera.Position.x, camera.Position.y, camera.Position.z);

			glUniform3f(glGetUniformLocation(lightingShader.Program, "spotLight.direction"), camera.Front.x, camera.Front.y, camera.Front.z);

			glUniform3f(glGetUniformLocation(lightingShader.Program, "spotLight.ambient"), 0.0f, 0.0f, 0.0f);

			glUniform3f(glGetUniformLocation(lightingShader.Program, "spotLight.diffuse"), 1.0f, 1.0f, 1.0f);

			glUniform3f(glGetUniformLocation(lightingShader.Program, "spotLight.specular"), 1.0f, 1.0f, 1.0f);

			glUniform1f(glGetUniformLocation(lightingShader.Program, "spotLight.constant"), 1.0f);

			glUniform1f(glGetUniformLocation(lightingShader.Program, "spotLight.linear"), 0.009);

			glUniform1f(glGetUniformLocation(lightingShader.Program, "spotLight.quadratic"), 0.0032);

			glUniform1f(glGetUniformLocation(lightingShader.Program, "spotLight.cutOff"), glm::cos(glm::radians(10.0f)));

			glUniform1f(glGetUniformLocation(lightingShader.Program, "spotLight.outerCutOff"), glm::cos(glm::radians(12.5f)));


			// Create camera transformations
			glm::mat4 view;
			view = camera.GetViewMatrix();
			glm::mat4 projection = glm::perspective(camera.Zoom, (GLfloat)WIDTH / (GLfloat)HEIGHT, 0.1f, 100.0f);
			// Get the uniform locations
			GLint modelLoc = glGetUniformLocation(lightingShader.Program, "model");
			GLint viewLoc = glGetUniformLocation(lightingShader.Program, "view");
			GLint projLoc = glGetUniformLocation(lightingShader.Program, "projection");
			// Pass the matrices to the shader
			glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
			glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection));

			// Bind diffuse map
			glActiveTexture(GL_TEXTURE0);
			glBindTexture(GL_TEXTURE_2D, diffuseMap);
			// Bind specular map
			glActiveTexture(GL_TEXTURE1);
			glBindTexture(GL_TEXTURE_2D, specularMap);

			// Draw 10 containers with the same VAO and VBO information; only their world space coordinates differ
			glm::mat4 model;
			glBindVertexArray(containerVAO);
			for (GLuint i = 0; i < 10; i++)
			{
				model = glm::mat4();
				model = glm::translate(model, cubePositions[i]);
				GLfloat angle = 20.0f * i;
				model = glm::rotate(model, angle, glm::vec3(1.0f, 0.3f, 0.5f));
				glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));

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


			// Also draw the lamp object, again binding the appropriate shader
			lampShader.Use();
			// Get location objects for the matrices on the lamp shader (these could be different on a different shader)
			modelLoc = glGetUniformLocation(lampShader.Program, "model");
			viewLoc = glGetUniformLocation(lampShader.Program, "view");
			projLoc = glGetUniformLocation(lampShader.Program, "projection");
			// Set matrices
			glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
			glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection));

			// We now draw as many light bulbs as we have point lights.
			glBindVertexArray(lightVAO);
			for (GLuint i = 0; i < 4; i++)
			{
				model = glm::mat4();
				model = glm::translate(model, pointLightPositions[i]);
				model = glm::scale(model, glm::vec3(0.2f)); // Make it a smaller cube
				glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
				glDrawArrays(GL_TRIANGLES, 0, 36);
			}
			glBindVertexArray(0);


			// Swap the screen buffers
			glfwSwapBuffers(window);
		}

		// Terminate GLFW, clearing any resources allocated by GLFW.
		glfwTerminate();

	}
Esempio n. 27
0
int main() {

  rx_log_init();
 
  glfwSetErrorCallback(error_callback);
 
  if(!glfwInit()) {
    printf("Error: cannot setup glfw.\n");
    exit(EXIT_FAILURE);
  }
 
  glfwWindowHint(GLFW_SAMPLES, 4);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
  glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  
  GLFWwindow* win = NULL;
  int w = 1280;
  int h = 720;
  win_w = w;
  win_h = h;
 
  win = glfwCreateWindow(w, h, "//_ - tracker test - //__ ", NULL, NULL);
  if(!win) {
    glfwTerminate();
    exit(EXIT_FAILURE);
  }
 
  glfwSetFramebufferSizeCallback(win, resize_callback);
  glfwSetKeyCallback(win, key_callback);
  glfwSetCharCallback(win, char_callback);
  glfwSetCursorPosCallback(win, cursor_callback);
  glfwSetMouseButtonCallback(win, button_callback);
  glfwMakeContextCurrent(win);
  glfwSwapInterval(1);

  if (!gladLoadGL()) {
    printf("Cannot load GL.\n");
    exit(1);
  }

  // ----------------------------------------------------------------
  // THIS IS WHERE YOU START CALLING OPENGL FUNCTIONS, NOT EARLIER!!
  // ----------------------------------------------------------------

  std::string files_path = rx_get_exe_path() +"/../data/input_mosaic/";
  image_files = rx_get_files(files_path, "png");
  if (0 == image_files.size()) {
    RX_ERROR("Cannot find the image files: %lu", image_files.size());
    ::exit(1);
  }

  mos::config.webcam_width = 320;
  mos::config.webcam_height = 240;
  fex::config.rows = 4;
  fex::config.cols = 10;

  track::TrackingSettings cfg;
  cfg.webcam_width = mos::config.webcam_width;
  cfg.webcam_height = mos::config.webcam_height;
  cfg.webcam_device = 0;

#if USE_POLAROID
  cfg.tile_width = 284;
  cfg.tile_height = 347;
  cfg.tile_nlayers = 10;
#else 
  cfg.tile_width = 64;
  cfg.tile_height = 64;
  cfg.tile_nlayers = 100;
#endif

  track::Tracking tracking;
  tracking_ptr = &tracking;

  if (0 != tracking.init(cfg)) {
    RX_ERROR("Cannot setup tracking.");
    exit(EXIT_FAILURE);
  }

  while(!glfwWindowShouldClose(win)) {
    glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    
    tracking.update();
    tracking.draw();

    glfwSwapBuffers(win);
    glfwPollEvents();
  }

  tracking.shutdown();
  
  glfwTerminate();
 
  return EXIT_SUCCESS;
}
Esempio n. 28
0
static void WIN_Show( DaoProcess *proc, DaoValue *p[], int N )
{
	DaoxWindow *self = (DaoxWindow*) p[0];
	DaoxCanvas *canvas = (DaoxCanvas*) DaoValue_CastCstruct( p[1], daox_type_canvas );
	DaoxScene *scene = (DaoxScene*) DaoValue_CastCstruct( p[1], daox_type_scene );
	DaoxFont *font = DaoxFont_GetDefault();
	int fpsLimit = p[2]->xInteger.value;
	int fpsTest = p[3]->xBoolean.value;
	double fpsTestTime = 0.0;
	double timeInterval = 0.0;
	double lastFrameStart = 0.0;
	float currentFPS = 0.0;
	size_t fpsCount = 0;
	char chars[32];

	if( fpsTest && self->widget == NULL ){
		char *fpsText = "FPS:       ";
		DaoxColor bgcolor = {0.0,0.0,0.0,0.0};
		DaoxBrush *brush;
		self->widget = DaoxCanvas_New( NULL );
		self->widget->viewport.right = self->width;
		self->widget->viewport.top = self->height;
		DaoGC_IncRC( (DaoValue*) self->widget );
		DaoxCanvas_SetBackground( self->widget, bgcolor );
		brush = DaoxCanvas_PushBrush( self->widget, 0 );
		brush->strokeColor.blue = 1.0;
		brush->fillColor.blue = 1.0;
		brush->fillColor.alpha = 1.0;
		brush->fontSize = 20;
		self->fpsLabel = DaoxCanvas_AddText( self->widget, fpsText, 10, self->height - 20, 0 );
	}
	if( self->painter == NULL && (canvas != NULL || self->widget != NULL) ){
		self->painter = DaoxPainter_New( self->context );
		DaoGC_IncRC( (DaoValue*) self->painter );
	}
	if( self->renderer == NULL && scene != NULL ){
		self->renderer = DaoxRenderer_New( self->context );
		DaoGC_IncRC( (DaoValue*) self->renderer );
	}
	if( canvas != NULL ){
		float dm = sqrt(self->width*self->width + self->height*self->height );
		float cx = 0.5*(canvas->viewport.left + canvas->viewport.right);
		float cy = 0.5*(canvas->viewport.top + canvas->viewport.bottom);
		float w = canvas->viewport.right - canvas->viewport.left;
		float h = canvas->viewport.top - canvas->viewport.bottom;
		float d = sqrt(w*w + h*h);
		w = 0.5 * self->width * d / dm;
		h = 0.5 * self->height * d / dm;
		canvas->viewport.left = cx - w;
		canvas->viewport.right = cx + w;
		canvas->viewport.bottom = cy - h;
		canvas->viewport.top = cy + h;
	}
	GC_Assign( & self->model, p[1] );
	self->visible = 1;

	glfwShowWindow( self->handle );
	glfwMakeContextCurrent( self->handle );
	glfwSetKeyCallback( self->handle, DaoxWindow_KeyCallback );
	glfwSetCursorPosCallback( self->handle, DaoxWindow_CursorMoveCallback );
	glfwSetCursorEnterCallback( self->handle, DaoxWindow_CursorEnterCallback );
	glfwSetWindowFocusCallback( self->handle, DaoxWindow_FocusCallback );

#ifdef SAVE_RENDERED_SCENE
	char name[50];
	int frame = 1;
	DaoxImage *image = DaoxImage_New();
	image->depth = DAOX_IMAGE_BIT32;
	DaoxImage_Resize( image, self->width, self->height );
#endif
	while( self->visible && ! glfwWindowShouldClose( self->handle ) ){
		double frameStartTime = 0.0;
		double frameEndTime = 0.0;
		frameStartTime = glfwGetTime();
		if( canvas ) DaoxPainter_Paint( self->painter, canvas, canvas->viewport );
		if( scene ){
#ifdef SAVE_RENDERED_SCENE
			DaoxScene_Update( scene, 1.0/30.0 );
			glReadBuffer( GL_BACK );
			glPixelStorei( GL_UNPACK_ALIGNMENT, 4 );
			glPixelStorei( GL_PACK_ROW_LENGTH, image->width );
			DaoxRenderer_Render( self->renderer, scene, scene->camera );
			glReadPixels( 0, 0, self->width, self->height, GL_RGBA, GL_UNSIGNED_BYTE, image->imageData );
			sprintf( name, "rama_attack_frame_%03i.png", frame );
			DaoxImage_SavePNG( image, name );
			frame += 1;
			if( frame > 155 ) break;
#else
			DaoxScene_Update( scene, frameStartTime - lastFrameStart );
			DaoxRenderer_Render( self->renderer, scene, scene->camera );
#endif
		}
		lastFrameStart = frameStartTime;
		if( fpsTest ){
			if( fpsCount % 10 == 0 ){
				int i, n = sprintf( chars, "%.1f", currentFPS );
				for(i=0; i<n; ++i){
					DaoxGlyph *glyph = DaoxFont_GetGlyph( font, chars[i] );
					DaoxCanvasNode *chnode = self->fpsLabel->children->items.pCanvasNode[i+5];
					DaoxPath *path = DaoxPathCache_FindPath( self->widget->pathCache, glyph->shape );
					GC_Assign( & chnode->path, path );
					DaoxCanvasNode_MarkDataChanged( chnode );
				}
			}
			DaoxPainter_Paint( self->painter, self->widget, self->widget->viewport );
		}
		glfwSwapBuffers( self->handle );
		glfwPollEvents();

		if( fpsTest == 0 ) continue;
		frameEndTime = glfwGetTime();
		timeInterval = frameEndTime - frameStartTime;
		if( timeInterval < 1.0/fpsLimit ) usleep( 1000000 * (1.0/fpsLimit -  timeInterval) );

		fpsCount += 1;
		currentFPS = fpsCount / (frameEndTime - fpsTestTime);
		if( frameEndTime > (fpsTestTime + 3) ){
			fpsTestTime = frameEndTime - 1.0;
			fpsCount = currentFPS; /* Frame count estimation in the past second; */
		}
	}
	glfwHideWindow( self->handle );
}
Esempio n. 29
0
int main()
{

	if (!glfwInit())
	{
		fprintf(stderr, "Failed to initialize GLFW\n");
		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);

	//int w = 1024;
	int w = 768;
	int h = 768;
	window = glfwCreateWindow(w, h,
		"Cyborg-Engine", NULL, NULL);
	if (window == NULL){
		fprintf(stderr, "Failed to open GLFW window.");
		glfwTerminate();
		return -1;
	}
	glfwMakeContextCurrent(window);
	glfwSetFramebufferSizeCallback(window, Renderer::FramebufferSizeCallback);
	glfwSetKeyCallback(window, Renderer::key_callback);
	Renderer::FramebufferSizeCallback(window, w, h);
	glewExperimental = true; // Needed for core profile
	if (glewInit() != GLEW_OK) {
		fprintf(stderr, "Failed to initialize GLEW\n");
		return -1;
	}

	glfwSetInputMode(window, GLFW_STICKY_KEYS, GL_TRUE);

	Renderer::initRender(window);

	//load resources:
	TextureManager* TM = TextureManager::getInstance();

	TM->loadTexture("testi", "./textures/polygon.png");
	TM->loadTexture("part", "./textures/particle2.png");
	TM->loadTexture("sheet","./textures/spriteSheetTest.png");
	float a = 0;
	float b = 0;			// For rotation
	float spriteTimer = 0;
	int spriteNumber = 0;

	PointSprite ps(0, 0, "part");
	
	//sprite stuff
	Sprite aa;
	aa.setUp(6,5);
	glm::vec2 rain[50];
	for (int i = 0; i < 50; i++)
	{
		rain[i] = glm::vec2((float)(rand() % 2000) / 1000 - 1.0, (float)(rand() % 2000) / 1000 - 1.2);
	}

	Polygon p;
	
	glm::vec2 points[]
	{

		glm::vec2(0.0, 0.21),
			glm::vec2(0.05, 0.05),
			glm::vec2(0.4, 0.0),
			glm::vec2(0.05, -0.05),
			glm::vec2(0.0, -0.21),
			glm::vec2(-0.05, -0.05),
			glm::vec2(-0.4, 0.0),
			glm::vec2(-0.05, 0.05),
	};
	p.setPoints(points, 8);
	p.setOrigin(-0.5, 0.0);

	Circle c;
	c.setPrecision(8);

	bool isEnterPressed = false;
	int scene = 0;

    //INITIALIZATION FOR NP_PHYSICS STUFF -------------------------------------------------------------------- START
    // Creating physics world
    NP_World world;
    // Creating objects
    NP_Object testObj, testObj2, testObj3, testObj4, testObj5, testObj6;
    // Creating bodies to the world
    NP_Body testBody(world, 2.f), testBody2(world, 1.f), testBody3(world, 1.f), testBody4(world, 0.5f), testBody5(world, 0.5f), testBody6(world, 100.f);

    //testBody3.m_mass = 10.f;
    


    // Binding objects to bodies
    testObj.bindBody(&testBody);
    testObj2.bindBody(&testBody2);
    testObj3.bindBody(&testBody3);
    testObj4.bindBody(&testBody4);
    testObj5.bindBody(&testBody5);
    testObj6.bindBody(&testBody6);


    testBody.addBoxCollider(0.5f);
    testBody2.addBoxCollider(0.5f);
    testBody3.addBoxCollider(0.5f);  
    testBody4.addBoxCollider(.25f);
    testBody5.addBoxCollider(.25f);
    testBody6.addBoxCollider(0.5f);

    Polygon poly1, poly2, poly3, poly4, poly5, poly6;
    glm::vec2 pointsp[] =
    {
        // Box collider size
        glm::vec2(-0.25, 0.25),
        glm::vec2(-0.25, -0.25),
        glm::vec2(0.25, -0.25),
        glm::vec2(0.25, 0.25)
    };
    glm::vec2 pointsp123[] =
    {
        // Box collider size
        glm::vec2(-0.125, 0.125),
        glm::vec2(-0.125, -0.125),
        glm::vec2(0.125, -0.125),
        glm::vec2(0.125, 0.125)
    };
    poly1.setPoints(pointsp, 4);
    poly2.setPoints(pointsp, 4);
    poly3.setPoints(pointsp, 4);
    poly4.setPoints(pointsp123, 4);
    poly5.setPoints(pointsp123, 4);
    poly6.setPoints(pointsp, 4);



    testObj.bindPolygon(&poly1);
    testObj2.bindPolygon(&poly2);
    testObj3.bindPolygon(&poly3);
    testObj4.bindPolygon(&poly4);
    testObj5.bindPolygon(&poly5);
    testObj6.bindPolygon(&poly6);

	// Adding objects to the wold
    
    world.addObject(&testObj);
	world.addObject(&testObj2);
    world.addObject(&testObj3);
  //  world.addObject(&testObj4);
  //  world.addObject(&testObj5);
  //  world.addObject(&testObj6);
    

    testObj3.getBody()->setPos(glm::vec2(-1.f, 0.4f));
    testObj2.getBody()->setPos(glm::vec2(0.0f, 0.75f));
    testObj.getBody()->setPos(glm::vec2(1.0f, 0.f));

    testObj4.getBody()->setPos(glm::vec2(-0.35f, 1.f));
    testObj5.getBody()->setPos(glm::vec2(0.35f, 1.f));
    testObj6.getBody()->setPos(glm::vec2(0.0f, -0.25f));
    
    testObj.getBody()->setVelocity(glm::vec2(-25.0f, 1.f));
	testObj3.getBody()->setVelocity(glm::vec2(5.0f, 1.f));
    testObj2.getBody()->setVelocity(glm::vec2(0.f, -5.f));

    testObj4.getBody()->setVelocity(glm::vec2(.0f, -3.0f));
    testObj5.getBody()->setVelocity(glm::vec2(.0f, -3.0f));
    testObj6.getBody()->setVelocity(glm::vec2(0.f, 2.f));

    //testObj.getBody()->m_orientation = glm::radians(30.f);
    //testObj3.getBody()->m_orientation = glm::radians(-45.f);
    //testObj3.getBody()->m_angularVelocity = 10.0f;
    //testObj2.getBody()->m_angularVelocity = 2.5f;
    //testObj.getBody()->m_angularVelocity = -2.f;
    //testObj4.getBody()->m_angularVelocity = -10.f;
    //testObj5.getBody()->m_angularVelocity = 10.f;

    //INITIALIZATION FOR NP_PHYSICS STUFF -------------------------------------------------------------------- END

	do{
		Renderer::do_movement();
		if (isEnterPressed == false)
		{
			if (glfwGetKey(window, GLFW_KEY_ENTER) == GLFW_PRESS)
			{
				isEnterPressed = true;
				scene = (scene+1) % 2;		// SCENEJEN MÄÄRÄ
				a = 0.0f;
                
                if (scene == 0)
                {
                    world.removeObjects();

                    world.addObject(&testObj);
                    world.addObject(&testObj2);
                    world.addObject(&testObj3);
                }
                else if (scene == 1)

                {
                    world.removeObjects();

                    world.addObject(&testObj4);
                    world.addObject(&testObj5);
                    world.addObject(&testObj6);
                }

			}
		}
		else
		{
			if (glfwGetKey(window, GLFW_KEY_ENTER) != GLFW_PRESS)
			{
				isEnterPressed = false;
			}
		}
		
		a += 0.02;
		//clear screen
		Renderer::initDraw();

		//--------------------draw--------------------

		if (scene == 0)
		{     

			Renderer::setColor(1, 1, 1, 0.5);

            Renderer::drawPolygon(&poly1, testObj.getBody()->m_collider.position.x, testObj.getBody()->m_collider.position.y);
            Renderer::drawPolygon(&poly2, testObj2.getBody()->m_collider.position.x, testObj2.getBody()->m_collider.position.y);
            Renderer::drawPolygon(&poly3, testObj3.getBody()->m_collider.position.x, testObj3.getBody()->m_collider.position.y);

            /*
            Renderer::drawCircle(testObj.getBody()->m_collider.corner[0].x, testObj.getBody()->m_collider.corner[0].y, 0.01f);
            Renderer::drawCircle(testObj.getBody()->m_collider.corner[1].x, testObj.getBody()->m_collider.corner[1].y, 0.01f);
            Renderer::drawCircle(testObj.getBody()->m_collider.corner[2].x, testObj.getBody()->m_collider.corner[2].y, 0.01f);
            Renderer::drawCircle(testObj.getBody()->m_collider.corner[3].x, testObj.getBody()->m_collider.corner[3].y, 0.01f);

            Renderer::drawCircle(testObj3.getBody()->m_collider.corner[0].x, testObj3.getBody()->m_collider.corner[0].y, 0.01f);
            Renderer::drawCircle(testObj3.getBody()->m_collider.corner[1].x, testObj3.getBody()->m_collider.corner[1].y, 0.01f);
            Renderer::drawCircle(testObj3.getBody()->m_collider.corner[2].x, testObj3.getBody()->m_collider.corner[2].y, 0.01f);
            Renderer::drawCircle(testObj3.getBody()->m_collider.corner[3].x, testObj3.getBody()->m_collider.corner[3].y, 0.01f);

            Renderer::drawCircle(testObj2.getBody()->m_collider.corner[0].x, testObj2.getBody()->m_collider.corner[0].y, 0.01f);
            Renderer::drawCircle(testObj2.getBody()->m_collider.corner[1].x, testObj2.getBody()->m_collider.corner[1].y, 0.01f);
            Renderer::drawCircle(testObj2.getBody()->m_collider.corner[2].x, testObj2.getBody()->m_collider.corner[2].y, 0.01f);
            Renderer::drawCircle(testObj2.getBody()->m_collider.corner[3].x, testObj2.getBody()->m_collider.corner[3].y, 0.01f);
            */
            //std::cout << testObj.getBody()->m_collider.corner[0].x << std::endl;

			//testObj.getBody()->setOrient(a);

            world.update(a / 10000);
		}
        else if (scene == 1)
        {
            Renderer::setColor(1, 0.5, 0.75, 0.5);

            

            Renderer::drawPolygon(&poly4, testObj4.getBody()->m_collider.position.x, testObj4.getBody()->m_collider.position.y);
            Renderer::drawPolygon(&poly5, testObj5.getBody()->m_collider.position.x, testObj5.getBody()->m_collider.position.y);
            Renderer::drawPolygon(&poly6, testObj6.getBody()->m_collider.position.x, testObj6.getBody()->m_collider.position.y);
            /*
            Renderer::drawCircle(testObj4.getBody()->m_collider.corner[0].x, testObj4.getBody()->m_collider.corner[0].y, 0.01f);
            Renderer::drawCircle(testObj4.getBody()->m_collider.corner[1].x, testObj4.getBody()->m_collider.corner[1].y, 0.01f);
            Renderer::drawCircle(testObj4.getBody()->m_collider.corner[2].x, testObj4.getBody()->m_collider.corner[2].y, 0.01f);
            Renderer::drawCircle(testObj4.getBody()->m_collider.corner[3].x, testObj4.getBody()->m_collider.corner[3].y, 0.01f);

            Renderer::drawCircle(testObj5.getBody()->m_collider.corner[0].x, testObj5.getBody()->m_collider.corner[0].y, 0.01f);
            Renderer::drawCircle(testObj5.getBody()->m_collider.corner[1].x, testObj5.getBody()->m_collider.corner[1].y, 0.01f);
            Renderer::drawCircle(testObj5.getBody()->m_collider.corner[2].x, testObj5.getBody()->m_collider.corner[2].y, 0.01f);
            Renderer::drawCircle(testObj5.getBody()->m_collider.corner[3].x, testObj5.getBody()->m_collider.corner[3].y, 0.01f);
            */
            world.update(a / 5000);
            
        }


		//--------------------end draw--------------------
		//swap buffers
		Renderer::render();
		glfwPollEvents();
	} while (glfwGetKey(window, GLFW_KEY_ESCAPE) != GLFW_PRESS &&
		glfwWindowShouldClose(window) == 0);

	Renderer::uninitRender();
	glfwTerminate();
	return 0;
}
Esempio n. 30
0
bool CCEGLView::Create(const char* pTitle, int iPixelWidth, int iPixelHeight, int iWidth, int iHeight, int iDepth) {
	bool eResult;
	int u32GLFWFlags = GLFW_WINDOW;
	//create the window by glfw.

	//check
	CCAssert(iPixelWidth!=0&&iPixelHeight!=0, "invalid window's size equal 0");
	CCAssert(iWidth!=0&&iHeight!=0, "invalid the size in points equal 0");

	//Inits GLFW
	eResult = glfwInit() != GL_FALSE;

	if (!eResult) {
		CCAssert(0, "fail to init the glfw");
	}

	/* Updates window hint */
	glfwOpenWindowHint(GLFW_WINDOW_NO_RESIZE, GL_TRUE);

	/* Depending on video depth */
	switch(iDepth)
	{
		/* 16-bit */
		case 16:
		{
			/* Updates video mode */
			eResult = (glfwOpenWindow(iPixelWidth, iPixelHeight, 5, 6, 5, 0, 16, 0, (int)u32GLFWFlags) != false) ? true : false;

			break;
		}

		/* 24-bit */
		case 24:
		{
			/* Updates video mode */
			eResult = (glfwOpenWindow(iPixelWidth, iPixelHeight, 8, 8, 8, 0, 16, 0, (int)u32GLFWFlags) != false) ? true : false;

			break;
		}

		/* 32-bit */
		default:
		case 32:
		{
			/* Updates video mode */
			eResult = (glfwOpenWindow(iPixelWidth, iPixelHeight, 8, 8, 8, 8, 16, 0, (int)u32GLFWFlags) != GL_FALSE) ? true :false;
			break;
		}
	}

	/* Success? */
	if(eResult)
	{

		/* Updates actual size */
		glfwGetWindowSize(&iPixelWidth, &iPixelHeight);

		//assign screen size and point's size
		m_sSizeInPixel.width = iPixelWidth;
		m_sSizeInPixel.height = iPixelHeight;

		m_sSizeInPoint.width = iWidth;
		m_sSizeInPoint.height = iHeight;

		// calculate the factor and the rect of viewport
		m_fScreenScaleFactor = MIN((float)m_sSizeInPixel.width / m_sSizeInPoint.width,
				(float)m_sSizeInPixel.height / m_sSizeInPoint.height);

		int viewPortW = (int)(m_sSizeInPoint.width * m_fScreenScaleFactor);
		int viewPortH = (int)(m_sSizeInPoint.height * m_fScreenScaleFactor);
		m_rcViewPort.origin.x = (m_sSizeInPixel.width - viewPortW) / 2;
		m_rcViewPort.origin.y = (m_sSizeInPixel.height - viewPortH) / 2;
		m_rcViewPort.size.width = viewPortW;
		m_rcViewPort.size.height = viewPortH;

		/* Updates its title */
		glfwSetWindowTitle(pTitle);

		//set the init flag
		bIsInit = true;
		s_pMainWindow = this;

		//register the glfw key event
		glfwSetKeyCallback(keyEventHandle);
		//register the glfw char event
		glfwSetCharCallback(charEventHandle);
		//register the glfw mouse event
		glfwSetMouseButtonCallback(mouseButtonEventHandle);
		//register the glfw mouse pos event
		glfwSetMousePosCallback(mousePosEventHandle);

		//Inits extensions
		eResult = initExtensions();

		if (!eResult) {
			CCAssert(0, "fail to init the extensions of opengl");
		}

	}
	return true;
}