Esempio n. 1
0
void obp_trackball_rot () {

    int xpos, ypos;
    glfwGetMousePos(&xpos, &ypos);

    glfwSetMousePos(obp_window_width /2, obp_window_height /2);

    verticalAngle   += mouseRotateSpeed * float(obp_window_width  /2 - xpos);
    horizontalAngle += mouseRotateSpeed * float(obp_window_height /2 - ypos);
        
    if (horizontalAngle >=  89.99) horizontalAngle =  89.99;
    if (horizontalAngle <= -89.99) horizontalAngle = -89.99;

    float initial_distance = 10;

    float distance = initial_distance - 1.0f * glfwGetMouseWheel();

    float camX =  distance * -sinf(verticalAngle     * (PI / 180)) * cosf((horizontalAngle) * (PI / 180));
    float camY =  distance * -sinf((horizontalAngle) * (PI / 180));
    float camZ = -distance *  cosf((verticalAngle)   * (PI / 180)) * cosf((horizontalAngle) * (PI / 180));

    ProjectionMatrix = glm::perspective(initial_fov, float(obp_window_width) / float(obp_window_height), 0.1f, 100.0f);

    ViewMatrix       = glm::lookAt(
                            glm::vec3(camX, camY, camZ),           
                            glm::vec3(0.0f, 0.0f, 0.0f), 
                            glm::vec3(0.0f, 1.0f, 0.0f));            
}
Esempio n. 2
0
InputHandler::InputHandler(View* v):
    view(v)
{
#ifndef __glfw3_h__
    mouse_wheel = glfwGetMouseWheel();
#else
    mouse_wheel = 0;
#endif
}
Esempio n. 3
0
//SGenum SG_EXPORT sgmCoreMouseSetWheel(void* mouse, SGint w);
SGenum SG_EXPORT sgmCoreMouseGetWheel(void* mouse, SGint* w)
{
    if(mouse == NULL)
        return SG_OK; // SG_INVALID_VALUE

    *w = glfwGetMouseWheel();

    return SG_OK;
}
Esempio n. 4
0
void xpl_input_get_scroll_deltas(xivec2 *deltas) {
	int scroll_position = glfwGetMouseWheel();
	if (last_scroll_position == INT16_MIN) {
		deltas->x = 0;
		deltas->y = 0;
	}
	deltas->x = 0;
	deltas->y = scroll_position - last_scroll_position;
	last_scroll_position = scroll_position;
}
Esempio n. 5
0
void init_events()
{
  last_wheel_pos = glfwGetMouseWheel();
  glfwSetKeyCallback(keycallback);
  glfwSetMouseButtonCallback(mousebuttoncallback);
  glfwSetMousePosCallback(mouse_move_callback);
  glfwSetCharCallback(charcallback);
  glfwSetMouseWheelCallback(mouse_wheel_callback);
  glfwSetWindowSizeCallback(window_size_callback);
}
Esempio n. 6
0
// update the scene based on the time elapsed since last update
static void Update(float secondsElapsed) {
    //rotate the first instance in `gInstances`
    const GLfloat degreesPerSecond = 180.0f;
    gDegreesRotated += secondsElapsed * degreesPerSecond;
    while(gDegreesRotated > 360.0f) gDegreesRotated -= 360.0f;
    gInstances.front().transform = glm::rotate(glm::mat4(), gDegreesRotated, glm::vec3(0,1,0));

    //move position of camera based on WASD keys, and XZ keys for up and down
    const float moveSpeed = 4.0; //units per second
    if(glfwGetKey('S')){
        gCamera.offsetPosition(secondsElapsed * moveSpeed * -gCamera.forward());
    } else if(glfwGetKey('W')){
        gCamera.offsetPosition(secondsElapsed * moveSpeed * gCamera.forward());
    }
    if(glfwGetKey('A')){
        gCamera.offsetPosition(secondsElapsed * moveSpeed * -gCamera.right());
    } else if(glfwGetKey('D')){
        gCamera.offsetPosition(secondsElapsed * moveSpeed * gCamera.right());
    }
    if(glfwGetKey('Z')){
        gCamera.offsetPosition(secondsElapsed * moveSpeed * -glm::vec3(0,1,0));
    } else if(glfwGetKey('X')){
        gCamera.offsetPosition(secondsElapsed * moveSpeed * glm::vec3(0,1,0));
    }

    //move light
    if(glfwGetKey('1'))
        gLight.position = gCamera.position();

    // change light color
    if(glfwGetKey('2'))
        gLight.intensities = glm::vec3(1,0,0); //red
    else if(glfwGetKey('3'))
        gLight.intensities = glm::vec3(0,1,0); //green
    else if(glfwGetKey('4'))
        gLight.intensities = glm::vec3(1,1,1); //white


    //rotate camera based on mouse movement
    const float mouseSensitivity = 0.1f;
    int mouseX, mouseY;
    glfwGetMousePos(&mouseX, &mouseY);
    gCamera.offsetOrientation(mouseSensitivity * mouseY, mouseSensitivity * mouseX);
    glfwSetMousePos(0, 0); //reset the mouse, so it doesn't go out of the window

    //increase or decrease field of view based on mouse wheel
    const float zoomSensitivity = -0.2f;
    float fieldOfView = gCamera.fieldOfView() + zoomSensitivity * (float)glfwGetMouseWheel();
    if(fieldOfView < 5.0f) fieldOfView = 5.0f;
    if(fieldOfView > 130.0f) fieldOfView = 130.0f;
    gCamera.setFieldOfView(fieldOfView);
    glfwSetMouseWheel(0);
}
Esempio n. 7
0
// update the scene based on the time elapsed since last update
void Update(float secondsElapsed) {
    //rotate the cube
    const GLfloat degreesPerSecond = 180.0f;
    gDegreesRotated += secondsElapsed * degreesPerSecond;
    while(gDegreesRotated > 360.0f) gDegreesRotated -= 360.0f;

    //move position of camera based on WASD keys, and XZ keys for up and down
    const float moveSpeed = 2.0; //units per second
    if(glfwGetKey('S')){
        gCamera.offsetPosition(secondsElapsed * moveSpeed * -gCamera.forward());
    } else if(glfwGetKey('W')){
        gCamera.offsetPosition(secondsElapsed * moveSpeed * gCamera.forward());
    }
    if(glfwGetKey('A')){
        gCamera.offsetPosition(secondsElapsed * moveSpeed * -gCamera.right());
    } else if(glfwGetKey('D')){
        gCamera.offsetPosition(secondsElapsed * moveSpeed * gCamera.right());
    }
    if(glfwGetKey('Z')){
        gCamera.offsetPosition(secondsElapsed * moveSpeed * -glm::vec3(0,1,0));
    } else if(glfwGetKey('X')){
        gCamera.offsetPosition(secondsElapsed * moveSpeed * glm::vec3(0,1,0));
    }

    //rotate camera based on mouse movement
    const float mouseSensitivity = 0.1;
    int mouseX, mouseY;
    glfwGetMousePos(&mouseX, &mouseY);
    gCamera.offsetOrientation(mouseSensitivity * mouseY, mouseSensitivity * mouseX);
    glfwSetMousePos(0, 0); //reset the mouse, so it doesn't go out of the window

    //increase or decrease field of view based on mouse wheel
    const float zoomSensitivity = -0.2;
    float fieldOfView = gCamera.fieldOfView() + zoomSensitivity * (float)glfwGetMouseWheel();
    if(fieldOfView < 5.0f) fieldOfView = 5.0f;
    if(fieldOfView > 130.0f) fieldOfView = 130.0f;
    gCamera.setFieldOfView(fieldOfView);
    glfwSetMouseWheel(0);
}
Esempio n. 8
0
void Input::update()
{
    m_mouse.z = glfwGetMouseWheel();
    glfwSetMouseWheel(0);
    if (m_mouseVisible == false)
    {
#ifdef __APPLE__
 		CGGetLastMouseDelta(&m_mouse.x, &m_mouse.y);
        GLFWvidmode mode;
        glfwGetDesktopMode(&mode);
	    CGPoint p;
		p.x = m_mouseMiddleX;
		p.y = m_mouseMiddleY;
		CGWarpMouseCursorPosition(p);
#else
        glfwGetMousePos(&m_mouse.x, &m_mouse.y);
        m_mouse.x -= m_mouseMiddleX;
        m_mouse.y -= m_mouseMiddleY;
        glfwSetMousePos(m_mouseMiddleX, m_mouseMiddleY);
#endif
    }
    else
    {
        glfwGetMousePos(&m_mouse.x, &m_mouse.y);
    }
    
    m_mouse.b = 0;
    if (glfwGetMouseButton(GLFW_MOUSE_BUTTON_1))
    {
        m_mouse.b |= 1;
    }
    if (glfwGetMouseButton(GLFW_MOUSE_BUTTON_2))
    {
        m_mouse.b |= 2;
    }
}
Esempio n. 9
0
float diddy_mouseZ() {
	float ret = glfwGetMouseWheel() - diddy_mouseWheel;
	diddy_mouseWheel = glfwGetMouseWheel();
	return ret;
}
Esempio n. 10
0
int main( int argc, char **argv )
{
    int width = 1024, height=768;

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

    // Open a window and create its OpenGL context
    if( !glfwOpenWindow( width, height, 0,0,0,0, 24,0, GLFW_WINDOW ) )
    {
        fprintf( stderr, "Failed to open GLFW window\n" );
        glfwTerminate();
        exit( EXIT_FAILURE );
    }

    glfwSetWindowTitle( "imgui sample imguiRenderGL2" );
    GLenum err = glewInit();
    if (GLEW_OK != err)
    {
          /* Problem: glewInit failed, something is seriously wrong. */
          fprintf(stderr, "Error: %s\n", glewGetErrorString(err));
          exit( EXIT_FAILURE );
    }

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

    // Enable vertical sync (on cards that support it)
    glfwSwapInterval( 1 );

    // Init UI
    if (!imguiRenderGLInit("DroidSans.ttf"))
    {
        fprintf(stderr, "Could not init GUI renderer.\n");
        exit(EXIT_FAILURE);
    }

    glClearColor(0.8f, 0.8f, 0.8f, 1.f);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
    glDisable(GL_DEPTH_TEST);

    // imgui states
    bool checked1 = false;
    bool checked2 = false;
    bool checked3 = true;
    bool checked4 = false;
    float value1 = 50.f;
    float value2 = 30.f;
    int scrollarea1 = 0;
    int scrollarea2 = 0;

    // glfw scrolling
    int glfwscroll = 0;
    do
    {
        glfwGetWindowSize(&width, &height);
        glViewport(0, 0, width, height);

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        // Mouse states
        unsigned char mousebutton = 0;
        int currentglfwscroll = glfwGetMouseWheel();
        int mscroll = 0;
        if (currentglfwscroll < glfwscroll)
            mscroll = 2;
         if (currentglfwscroll > glfwscroll)
            mscroll = -2;
        glfwscroll = currentglfwscroll;
        int mousex; int mousey;
        glfwGetMousePos(&mousex, &mousey);
        mousey = height - mousey;
        int leftButton = glfwGetMouseButton( GLFW_MOUSE_BUTTON_LEFT );
        int rightButton = glfwGetMouseButton( GLFW_MOUSE_BUTTON_RIGHT );
        int middleButton = glfwGetMouseButton( GLFW_MOUSE_BUTTON_MIDDLE );
        int toggle = 0;
        if( leftButton == GLFW_PRESS )
            mousebutton |= IMGUI_MBUT_LEFT;
    
        // Draw UI
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        float projection[16] = { 2.f/width, 0.f, 0.f,  0.f,
                                 0.f, 2.f/height,  0.f,  0.f,
                                 0.f,  0.f, -2.f, 0.f,
                                 -1.f, -1.f,  -1.f,  1.f };
        glLoadMatrixf(projection);
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        glUseProgram(0);


        imguiBeginFrame(mousex, mousey, mousebutton, mscroll);

        imguiBeginScrollArea("Scroll area", 10, 10, width / 5, height - 20, &scrollarea1);
        imguiSeparatorLine();
        imguiSeparator();

        imguiButton("Button");
        imguiButton("Disabled button", false);
        imguiItem("Item");
        imguiItem("Disabled item", false);
        toggle = imguiCheck("Checkbox", checked1);
        if (toggle)
            checked1 = !checked1;
        toggle = imguiCheck("Disabled checkbox", checked2, false);
        if (toggle)
            checked2 = !checked2;
        toggle = imguiCollapse("Collapse", "subtext", checked3);
        if (checked3)
        {
            imguiIndent();
            imguiLabel("Collapsible element");
            imguiUnindent();
        }
        if (toggle)
            checked3 = !checked3;
        toggle = imguiCollapse("Disabled collapse", "subtext", checked4, false);
        if (toggle)
            checked4 = !checked4;
        imguiLabel("Label");
        imguiValue("Value");
        imguiSlider("Slider", &value1, 0.f, 100.f, 1.f);
        imguiSlider("Disabled slider", &value2, 0.f, 100.f, 1.f, false);
        imguiIndent();
        imguiLabel("Indented");
        imguiUnindent();
        imguiLabel("Unindented");

        imguiEndScrollArea();

        imguiBeginScrollArea("Scroll area", 20 + width / 5, 500, width / 5, height - 510, &scrollarea2);
        imguiSeparatorLine();
        imguiSeparator();
        for (int i = 0; i < 100; ++i)
            imguiLabel("A wall of text");

        imguiEndScrollArea();
        imguiEndFrame();

        imguiDrawText(30 + width / 5 * 2, height - 20, IMGUI_ALIGN_LEFT, "Free text",  imguiRGBA(32,192, 32,192));
        imguiDrawText(30 + width / 5 * 2 + 100, height - 40, IMGUI_ALIGN_RIGHT, "Free text",  imguiRGBA(32, 32, 192, 192));
        imguiDrawText(30 + width / 5 * 2 + 50, height - 60, IMGUI_ALIGN_CENTER, "Free text",  imguiRGBA(192, 32, 32,192));

        imguiDrawLine(30 + width / 5 * 2, height - 80, 30 + width / 5 * 2 + 100, height - 60, 1.f, imguiRGBA(32,192, 32,192));
        imguiDrawLine(30 + width / 5 * 2, height - 100, 30 + width / 5 * 2 + 100, height - 80, 2.f, imguiRGBA(32, 32, 192, 192));
        imguiDrawLine(30 + width / 5 * 2, height - 120, 30 + width / 5 * 2 + 100, height - 100, 3.f, imguiRGBA(192, 32, 32,192));

        imguiDrawRoundedRect(30 + width / 5 * 2, height - 240, 100, 100, 5.f, imguiRGBA(32,192, 32,192));
        imguiDrawRoundedRect(30 + width / 5 * 2, height - 350, 100, 100, 10.f, imguiRGBA(32, 32, 192, 192));
        imguiDrawRoundedRect(30 + width / 5 * 2, height - 470, 100, 100, 20.f, imguiRGBA(192, 32, 32,192));
        
        imguiDrawRect(30 + width / 5 * 2, height - 590, 100, 100, imguiRGBA(32, 192, 32, 192));
        imguiDrawRect(30 + width / 5 * 2, height - 710, 100, 100, imguiRGBA(32, 32, 192, 192));
        imguiDrawRect(30 + width / 5 * 2, height - 830, 100, 100, imguiRGBA(192, 32, 32,192));

        imguiRenderGLDraw(width, height); 

        // Check for errors
        GLenum err = glGetError();
        if(err != GL_NO_ERROR)
        {
            fprintf(stderr, "OpenGL Error : %s\n", gluErrorString(err));
        }

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

    // Clean UI
    imguiRenderGLDestroy();

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

    exit( EXIT_SUCCESS );
}
Esempio n. 11
0
//rotated and add keyboard and mouse callback
void Update(float secondsElapsed) {
    //change the axis that rotated
    if (glfwGetKey('7')){
        Axis =glm::vec3(1,0,0);
    }
    if (glfwGetKey('8')){
        Axis =glm::vec3(0,0,1);
    }
    if (glfwGetKey('9')){
        Axis =glm::vec3(0,1,0);
    }
    //press "T" to stop rotate
    GLfloat degreesPerSecond = 20.0f;
    if (glfwGetKey('T')){
        degreesPerSecond = 0.0f;
    }

    gDegreesRotated += secondsElapsed * degreesPerSecond;
    while (gDegreesRotated > 360.0f) gDegreesRotated -= 360.0f;
    
    
    const float moveSpeed = 3.0;
    if (glfwGetKey('S')) {
        gCamera.offsetPositon(secondsElapsed * moveSpeed * -gCamera.forward());
    } else if (glfwGetKey('W')){
        gCamera.offsetPositon(secondsElapsed * moveSpeed * gCamera.forward());
    } else if (glfwGetKey('A')) {
        gCamera.offsetPositon(secondsElapsed * moveSpeed * -gCamera.right());
    } else if (glfwGetKey('D')) {
        gCamera.offsetPositon(secondsElapsed * moveSpeed * gCamera.right());
    }
    if (glfwGetKey('Z')) {
        gCamera.offsetPositon(secondsElapsed* moveSpeed * -glm::vec3(0,1,0));
    } else if (glfwGetKey('X')) {
        gCamera.offsetPositon(secondsElapsed * moveSpeed * glm::vec3(0,1,0));
    }
    
    // change light color
    if(glfwGetKey('1'))
        gLight.intensities = glm::vec3(0.8, 0.3, 0.0); //red
    else if(glfwGetKey('2'))
        gLight.intensities = glm::vec3(0.0, 0.8, 0.2); //green
    else if (glfwGetKey('3'))
        gLight.intensities = glm::vec3(0.1, 0.3, 0.8);
    else if(glfwGetKey('4'))
        gLight.intensities = glm::vec3(1,1,1); //white
    
    //mouse movement with camera
    const float mouseSensitivity = 0.1;
    int mouseX, mouseY;
    glfwGetMousePos(&mouseX, &mouseY);
    gCamera.offsetOrientation(mouseSensitivity* mouseY, mouseSensitivity* mouseX);
    glfwSetMousePos(0,0);
    
    
    //mouse wheel with field of view
    const float zoomSensitivity = -0.8;
    float fieldOfView = gCamera.fieldOfView() + zoomSensitivity *(float)glfwGetMouseWheel();
    if(fieldOfView < 5.0f) fieldOfView = 5.0f;
    if(fieldOfView > 130.0f) fieldOfView = 130.0f;
    gCamera.setFieldOfView(fieldOfView);
    if (glfwGetMouseButton(0))          //press left button to reset the Fov;
        gCamera.setFieldOfView(50.0f);
    glfwSetMouseWheel(0);
    
}
Esempio n. 12
0
void PullInfo(){
  printf("================================================================================\n");
  
  int major, minor, rev;
  glfwGetVersion(&major, &minor, &rev);
  printf("GLFW version is %i.%i.%i\n", major, minor, rev);
  
  int width, height;
  glfwGetWindowSize(&width, &height);
  printf("Window size is %i %i\n", width, height);
  
  int status = glfwGetKey(GLFW_KEY_LCTRL);
  if(status == GLFW_PRESS)
    printf("Left control is pressed\n");
  else
    printf("Left control is released\n");
    
  status = glfwGetMouseButton(GLFW_MOUSE_BUTTON_1);
  if(status == GLFW_PRESS)
    printf("Mouse button 1 is pressed\n");
  else
    printf("Mouse button 1 is released\n");
    
  int x, y;
  glfwGetMousePos(&x, &y);
  printf("Mouse position is %i %i\n", x, y);
  
  int wheel = glfwGetMouseWheel();
  printf("Mouse wheel pos is %i\n", wheel);
  
  double time = glfwGetTime();
  printf("Time is %f\n", time);
  
  glfwGetGLVersion(&major, &minor, &rev);
  printf("GL version is %i.%i.%i\n", major, minor, rev);
  
  int proc = glfwGetNumberOfProcessors();
  printf("%i processors are available\n", proc);
  
  unsigned int i;
  for(i = 0; i<nb_params; i++)
    printf(" - %-27s : %i\n", GetParamName(params[i]), glfwGetWindowParam(params[i]));
  
  const char* extension = "MOZ_WEBGL_compressed_texture_s3tc";
  printf("'%s' extension is %s.\n", extension, glfwExtensionSupported(extension) ? "supported" : "not supported");  
  
  extension = "GL_EXT_framebuffer_object";
  printf("'%s' extension is %s.\n", extension, glfwExtensionSupported(extension) ? "supported" : "not supported");
  
  extension = "glBindBuffer";
  void* proc_addr = glfwGetProcAddress(extension);
  printf("'%s' extension proc address is %p.\n", extension, proc_addr);
  
  printf("Sleeping 1 sec...\n");
  glfwSleep(1);
  printf("...Done.\n");
  
  printf("================================================================================\n");
  
#ifdef REPORT_RESULT  
  int result = 1;
  REPORT_RESULT();
#endif
}
Esempio n. 13
0
int Application::getMouseWheelPos()
{
    return glfwGetMouseWheel();
}
Esempio n. 14
0
int GLFWApp::GetMouseWheel()
{
	return glfwGetMouseWheel();
}
Esempio n. 15
0
void update(){
    //update time

    frames++;
    thisTime = glfwGetTime();
    diff = thisTime - lastTime;
    if(doRotate){
        degree += diff * 180.0f;
        if(degree > 360.0f){
            degree -= 360.0f;
        }
    }
    lastTime = thisTime;
    seconds += diff;
    if( seconds > 1.0){

        fps = frames;
        frames = 0;
        seconds = 0;
    }


    //handle keys
    //forward, back
    if(glfwGetKey('S')){
        camera.offsetPosition( diff * moveSpeed * -camera.forward());
    } else if(glfwGetKey('W')){
        camera.offsetPosition( diff * moveSpeed * camera.forward());
    }

    //left, right
    if(glfwGetKey('A')){
        camera.offsetPosition( diff * moveSpeed * -camera.right());
    } else if(glfwGetKey('D')){
        camera.offsetPosition( diff * moveSpeed * camera.right());
    }

    //up, down
    if(glfwGetKey('Z')){
        camera.offsetPosition( diff * moveSpeed * -glm::vec3(0,1,0));
    }else if(glfwGetKey('X')){
        camera.offsetPosition( diff * moveSpeed * glm::vec3(0,1,0));
    }

    if(glfwGetKey(GLFW_KEY_SPACE)){
        doRotate = false;
    }else{
        doRotate = true;
    }

    if(glfwGetKey('1')){
        light.intensities = glm::vec3(1,1,1);
    }

    if(glfwGetKey('2')){
        light.intensities = glm::vec3(1,0,0);
    }

    if(glfwGetKey('3')){
        light.intensities = glm::vec3(0,1,0);
    }

    if(glfwGetKey('4')){
        light.intensities = glm::vec3(0,0,1);
    }

    if(glfwGetKey('5')){
        light.intensities = glm::vec3(0,0,0);
    }

    const float mouseSensitivity = 0.1;
    int mouseX, mouseY;
    glfwGetMousePos(&mouseX, &mouseY);
    camera.offsetOrientation(mouseSensitivity * mouseY, mouseSensitivity * mouseX);
    glfwSetMousePos(0, 0);

    const float zoomSensitivity = -0.2;
    float fieldOfView = camera.fieldOfView() + zoomSensitivity * (float)glfwGetMouseWheel();
    if(fieldOfView < 5.0f) fieldOfView = 5.0f;
    if(fieldOfView > 130.0f) fieldOfView = 130.0f;
    camera.setFieldOfView(fieldOfView);
    glfwSetMouseWheel(0);

}
Esempio n. 16
0
void obp_fps () {

    static double lastTime = glfwGetTime();

    double currentTime = glfwGetTime();
    float deltaTime = float(currentTime - lastTime);

    int xpos, ypos;
    glfwGetMousePos(&xpos, &ypos);

    glfwSetMousePos(obp_window_width /2, obp_window_height /2);

    horizontalAngle += mouseSpeed * float(obp_window_width  /2 - xpos);
    verticalAngle   += mouseSpeed * float(obp_window_height /2 - ypos);

    glm::vec3 direction(

        cos(verticalAngle) * sin(horizontalAngle), 
        sin(verticalAngle),
        cos(verticalAngle) * cos(horizontalAngle)
    );
    
    glm::vec3 right = glm::vec3(
        sin(horizontalAngle - (PI /2.0f)), 
        0.0f,
        cos(horizontalAngle - (PI /2.0f))
    );
    
    glm::vec3 up = glm::cross(right, direction);

    if (glfwGetKey('W') == GLFW_PRESS) {

        position += direction * deltaTime * speed;
    }

    if (glfwGetKey('S') == GLFW_PRESS) {

        position -= direction * deltaTime * speed;
    }

    if (glfwGetKey('D') == GLFW_PRESS) {

        position += right * deltaTime * speed;
    }

    if (glfwGetKey('A') == GLFW_PRESS) {

        position -= right * deltaTime * speed;
    }
    
    if (glfwGetKey(GLFW_KEY_LSHIFT) == GLFW_PRESS) {

        speed = 10.0f;

    } else {

        speed = 3.0f;
    }

    float fov = initial_fov - 5 * glfwGetMouseWheel();

    ProjectionMatrix = glm::perspective(fov, float(obp_window_width) / float(obp_window_height), 0.1f, 100.0f);
    ViewMatrix       = glm::lookAt(
        position,           
        position + direction, 
        up                  
    );

    lastTime = currentTime;
}
Esempio n. 17
0
void InputHandler::handleKeys()
{

    if(!view -> getFocus())
    {
        if(glfwGetKey(GLFW_KEY_RIGHT))
        {
            view -> setX(view -> getX() + SPEED);
        }
        if(glfwGetKey(GLFW_KEY_LEFT))
        {
            view -> setX(view -> getX() - SPEED);
        }
        if(glfwGetKey(GLFW_KEY_DOWN))
        {
            view -> setY(view -> getY() - SPEED);
        }
        if(glfwGetKey(GLFW_KEY_UP))
        {
            view -> setY(view -> getY() + SPEED);
        }
        if(glfwGetKey('P') && !key_was_pressed[static_cast<uint>('P')])
        {
            view -> setPaused(!view -> isPaused());
        }
        if(glfwGetKey('R') && !key_was_pressed[static_cast<uint>('R')])
        {
            view -> setReset(true);
        }

#ifdef VIEW_DEBUG
        if(glfwGetKey('G') && !key_was_pressed[static_cast<uint>('G')])
        {
            view -> display_grid = !view -> display_grid;
        }
#endif
#ifndef __glfw3_h__
        int tmp = glfwGetMouseWheel();
        if(mouse_wheel != tmp)
        {
            view -> setDistance(view -> getDistance() - VIEW_Z_SPEED * (tmp-mouse_wheel));
            mouse_wheel = tmp;
        }
#else
        double tmpx, tmpy;
        glfwGetScrollOffset(view -> getWindow(), &tmpx, &tmpy);
        if (tmpy)
        { 
            view -> setDistance(view -> getDistance() - VIEW_Z_SPEED * tmpy);
        }
#endif
    }
    else
    {
        TextField* focus = view -> getFocus();
        if(glfwGetKey(GLFW_KEY_BACKSPACE) && !key_was_pressed[GLFW_KEY_BACKSPACE])
        {
            std::string text = focus -> getText();
            if(text.length() > 0)
            {
                focus -> setText( text.erase(text.length()-1) );
            }
        }
        else if(glfwGetKey(GLFW_KEY_ENTER) && !key_was_pressed[GLFW_KEY_ENTER])
        {
            view -> setUserInput(focus -> getText());
            focus -> setText("");
        }
        else
        {
            char tempChar = '\0';
            for(int c = 'A'; c<='Z'; ++c)
            {
                if(isCharPressed(c)) tempChar = c;
                if(isCharPressed(c - 'A' + 'a')) tempChar = c - 'A' + 'a';
            }
            for(int c = '0'; c<='9'; ++c)
            {
                if(isCharPressed(c)) tempChar = c;
            }
            if(isCharPressed(' ')) tempChar = ' ';
            if(isCharPressed('.')) tempChar = '.';
            if(isCharPressed('-')) tempChar = '-';
            if(isCharPressed('_')) tempChar = '_';

            // Print symbol that is pressed last by index.
            if(tempChar != '\0') focus -> setText(focus -> getText() + tempChar);
        }
    }

    for(int i = 0; i < GLFW_KEY_LAST; ++i)
    {
        key_was_pressed[i] = glfwGetKey(i) ? true : false;
    }
}
Esempio n. 18
0
void gameDialog::Update() {
	static int wheel = 0;
	static bool inWater = false;
	static bool inAir = false;

	unsigned char bl;

	// Detect usage of the mouse wheel
	int newWheel = glfwGetMouseWheel();
	if (newWheel != wheel) {
		if (gMode.Get() == GameMode::CONSTRUCT) {
			fBuildingBlocks->UpdateSelection(newWheel);
		} else if (fDrawMap) {
			float fact = 1.0f + (wheel-newWheel)/10.0f;
			fMapWidth = fMapWidth * fact;
			if (fMapWidth < 100)
				fMapWidth = 100;
		} else {
			this->fRequestedCameraDistance += wheel-newWheel;
			if (this->fRequestedCameraDistance < 0.0f)
				this->fRequestedCameraDistance = 0.0f;
			if (this->fRequestedCameraDistance > 20.0f)
				this->fRequestedCameraDistance = 20.0f; // Don't allow unlimited third person view distance
		}
		wheel = newWheel;
	}
	if (gMode.Get() == GameMode::CONSTRUCT && (glfwGetKey(GLFW_KEY_DEL) == GLFW_PRESS || glfwGetKey('V') == GLFW_PRESS) && glfwGetMouseButton(GLFW_MOUSE_BUTTON_1) == GLFW_PRESS) {
		int x, y;
		glfwGetMousePos(&x, &y);
		this->ClickOnBlock(x, y);
	}
	gMonsters.Cleanup();
	gOtherPlayers.Cleanup();
	while (ListenForServerMessages())
		continue;

	// Determine if player head is under water
	bl = chunk::GetChunkAndBlock(gPlayer.x, gPlayer.y, gPlayer.z);
	if (bl == BT_Air && fUnderWater) {
		gSoundControl.SetSoundFxStatus(SoundControl::SEnvironmentUnderWater,false);
		fUnderWater = false;
	}
	if ((bl == BT_Water || bl == BT_BrownWater) && !fUnderWater) {
		gSoundControl.SetSoundFxStatus(SoundControl::SEnvironmentUnderWater,true);
		fUnderWater = true;
		// Not in water when under water
		gSoundControl.SetSoundFxStatus(SoundControl::SPlayerFeetInWater,false);
		inWater = false;
	}

	// Determine if feet are wet
	// TODO: Change "magic number" for player height!
	bl = chunk::GetChunkAndBlock(gPlayer.x, gPlayer.y, gPlayer.z-350);
	if ((bl != BT_Water && bl != BT_BrownWater) && inWater && !fUnderWater) {
		gSoundControl.SetSoundFxStatus(SoundControl::SPlayerFeetInWater,false);
		inWater = false;
	}
	if ((bl == BT_Water || bl == BT_BrownWater) && !inWater && !fUnderWater) {
		gSoundControl.SetSoundFxStatus(SoundControl::SPlayerFeetInWater,true);
		inWater = true;
	}

	// TODO: Change "magic number" for player height!
	bl = chunk::GetChunkAndBlock(gPlayer.x, gPlayer.y, gPlayer.z-400);
	if (bl != BT_Air && inAir) {
		gSoundControl.SetSoundFxStatus(SoundControl::SPlayerInAir,false);
		inAir = false;
	}
	if (bl == BT_Air && !inAir) {
		gSoundControl.SetSoundFxStatus(SoundControl::SPlayerInAir,true);
		inAir = true;
	}

	this->UpdateCameraPosition();
	gGameDialog.UpdateRunningStatus(false);

	if (Options::fgOptions.fFullScreen) {
		// Full screen, which means mouse is usually disabled. But there are cases when it is needed.
		bool showMouseFullscreen = false;
		static bool wasShowingMouse = false;
		if ((fShowMainDialog && !fHideDialog) || gMode.Get() == GameMode::CONSTRUCT || fShowInventory)
			showMouseFullscreen = true;
		if (wasShowingMouse && !showMouseFullscreen) {
			glfwDisable(GLFW_MOUSE_CURSOR);
			wasShowingMouse = false;
		}
		if (!wasShowingMouse && showMouseFullscreen) {
			glfwEnable(GLFW_MOUSE_CURSOR);
			wasShowingMouse = true;
		}
	}

	this->UpdateEffect();
	gChunkProcess.Poll(); // Update all results
}
Esempio n. 19
0
// Moves the camera based on what keypresses and mouse movements have happened
void Fengine_camera::move_camera()
{
	// glfwGetTime is called only once, the first time this function is called
	static double last_time = glfwGetTime();

	// Compute time difference between current and last frame
	double current_time = glfwGetTime();
	float delta_time = float(current_time - last_time);

	// Get mouse position
	int xpos = 0;
	int ypos = 0;
	glfwGetMousePos(&xpos, &ypos);

	int width = 0;
	int height = 0;
	glfwGetWindowSize(&width, &height);

	// Reset mouse position for next frame
	glfwSetMousePos(width/2, height/2);

	// Compute new orientation
	m_horizontal_angle += m_mouse_speed * float(width/2 - xpos);
	m_vertical_angle   += m_mouse_speed * float(height/2 - ypos);

	// Direction : Spherical coordinates to Cartesian coordinates conversion
	vec3 direction(
			cos(m_vertical_angle) * sin(m_horizontal_angle),
			sin(m_vertical_angle),
			cos(m_vertical_angle) * cos(m_horizontal_angle)
			);

	// Right vector
	vec3 right = vec3(
			sin(m_horizontal_angle - 3.14f/2.0f),
			0,
			cos(m_horizontal_angle - 3.14f/2.0f)
			);

	// Up vector
	m_up = cross( right, direction );

	// Move forward
	if (glfwGetKey( 'W' ) == GLFW_PRESS)
	{
		m_position += direction * delta_time * m_speed;
	}
	// Move backward
	if (glfwGetKey( 'S' ) == GLFW_PRESS)
	{
		m_position -= direction * delta_time * m_speed;
	}
	// Strafe right
	if (glfwGetKey( 'D' ) == GLFW_PRESS)
	{
		m_position += right * delta_time * m_speed;
	}
	// Strafe left
	if (glfwGetKey( 'A' ) == GLFW_PRESS)
	{
		m_position -= right * delta_time * m_speed;
	}

	float fov = m_initial_fov - 5 * glfwGetMouseWheel();

	// Projection matrix : 45° Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units
	m_projection_mat = perspective(fov, m_perspective, 0.1f, 100.0f);

	//cout << "Position of cam: " <<m_position.x << " " << m_position.y << " " << m_position.z << endl;
	//cout << "Last time:" << last_time << endl;
	//cout << "Direction" << direction.x << " " << direction.y << " " << direction.z << endl;

	// Camera matrix
	m_object_matrix = lookAt(
			m_position,				//Set the cameras position
			m_position + direction,	//Looks at the same position but in the direction we calculated
			m_up
			);

	// For the next frame, the "last time" will be "now"
	last_time = current_time;
}
Esempio n. 20
0
int main (int argc, const char * argv[])
{

	TwBar *myBar;
	float bgColor[] = { 0.0f, 0.0f, 0.0f, 0.1f };

	glm::mat4 mat;
	float axis[] = { 0.7f, 0.7f, 0.7f }; // initial model rotation
    float angle = 0.8f;

	double FT  = 0;
	double FPS = 0;

	double starting = 0.0;
	double ending   = 0.0;
	int rate = 0;
	int fr = 0;

	zNear = 0.1f;
	zFar  = 100.0f;
	FOV   = 45.0f; 

	// Current time
	double time = 0;

	 // initialise GLFW
    int running = GL_TRUE;

    if (!glfwInit()) {
        exit(EXIT_FAILURE);
    }
    
    //only for OpenGL 2.1
#ifdef USE_OPENGL21
    glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 2);
    glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 1);
#endif
    
    //Only for OpenGL 3.2
#ifdef USE_OPENGL32
    glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 4);
    glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3);
    glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2);
    glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwOpenWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, 1);
#endif

	GLFWvidmode mode;
    glfwGetDesktopMode(&mode);
    if( !glfwOpenWindow(windowWidth, windowHeight, mode.RedBits, mode.GreenBits, mode.BlueBits, 0, 32, 0, GLFW_WINDOW /* or GLFW_FULLSCREEN */) )
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }
    glfwEnable(GLFW_MOUSE_CURSOR);
    glfwEnable(GLFW_KEY_REPEAT);
    // Ensure we can capture the escape key being pressed below
	glfwEnable( GLFW_STICKY_KEYS );
	glfwSetMousePos(windowWidth/2, windowHeight/2);
    glfwSetWindowTitle("Chapter-11");

	// Initialize AntTweakBar
    if ( !TwInit(TW_OPENGL_CORE, NULL))
	{
		fprintf(stderr,"AntweakBar initialiazation failed: %s\n",TwGetLastError());
		exit(1);
	}

    // Create a tweak bar
	myBar = TwNewBar("TweakBar");

    //init GLEW and basic OpenGL information
    // VERY IMPORTANT OTHERWISE GLEW CANNOT HANDLE GL3
#ifdef USE_OPENGL32
    glewExperimental = true; 
#endif
    glewInit();
    std::cout<<"\nUsing GLEW "<<glewGetString(GLEW_VERSION)<<std::endl;
    if (GLEW_VERSION_2_1)
    {
        std::cout<<"\nYay! OpenGL 2.1 is supported and GLSL 1.2!\n"<<std::endl;
    }
    if (GLEW_VERSION_3_2)
    {
        std::cout<<"Yay! OpenGL 3.2 is supported and GLSL 1.5!\n"<<std::endl;
    }
    
    /*
     This extension defines an interface that allows various types of data
     (especially vertex array data) to be cached in high-performance
     graphics memory on the server, thereby increasing the rate of data
     transfers.
     Chunks of data are encapsulated within "buffer objects", which
     conceptually are nothing more than arrays of bytes, just like any
     chunk of memory.  An API is provided whereby applications can read
     from or write to buffers, either via the GL itself (glBufferData,
     glBufferSubData, glGetBufferSubData) or via a pointer to the memory.
     */
	if (glewIsSupported("GL_ARB_vertex_buffer_object"))
		std::cout<<"ARB VBO's are supported"<<std::endl;
    else if (glewIsSupported("GL_APPLE_vertex_buffer_object"))
		std::cout<<"APPLE VBO's are supported"<<std::endl;
	else
		std::cout<<"VBO's are not supported,program will not run!!!"<<std::endl; 
    
    /* 
     This extension introduces named vertex array objects which encapsulate
     vertex array state on the client side. The main purpose of these 
     objects is to keep pointers to static vertex data and provide a name 
     for different sets of static vertex data.  
     By extending vertex array range functionality this extension allows multiple
     vertex array ranges to exist at one time, including their complete sets of
     state, in manner analogous to texture objects. 
     GenVertexArraysAPPLE creates a list of n number of vertex array object
     names.  After creating a name, BindVertexArrayAPPLE associates the name with
     a vertex array object and selects this vertex array and its associated
     state as current.  To get back to the default vertex array and its
     associated state the client should bind to vertex array named 0.
     */
    
	if (glewIsSupported("GL_ARB_vertex_array_object"))
        std::cout<<"ARB VAO's are supported\n"<<std::endl;
    else if (glewIsSupported("GL_APPLE_vertex_array_object"))//this is the name of the extension for GL2.1 in MacOSX
		std::cout<<"APPLE VAO's are supported\n"<<std::endl;
	else
		std::cout<<"VAO's are not supported, program will not run!!!\n"<<std::endl;
    
    
    std::cout<<"Vendor: "<<glGetString (GL_VENDOR)<<std::endl;
    std::cout<<"Renderer: "<<glGetString (GL_RENDERER)<<std::endl;
    std::cout<<"Version: "<<glGetString (GL_VERSION)<<std::endl;
   
	std::ostringstream stream1,stream2;

	stream1 << glGetString(GL_VENDOR);
	stream2 << glGetString(GL_RENDERER);

	std::string vendor ="Title : Chapter-11   Vendor : " + stream1.str() + "   Renderer : " +stream2.str();

	const char *tit = vendor.c_str();
	glfwSetWindowTitle(tit);
    // Set GLFW event callbacks
    // - Redirect window size changes to the callback function WindowSizeCB
    glfwSetWindowSizeCallback(WindowSizeCB);
    
    // - Directly redirect GLFW mouse button events to AntTweakBar
    glfwSetMouseButtonCallback((GLFWmousebuttonfun)TwEventMouseButtonGLFW);
    
    // - Directly redirect GLFW mouse position events to AntTweakBar
    glfwSetMousePosCallback((GLFWmouseposfun)TwEventMousePosGLFW);
    
    // - Directly redirect GLFW mouse wheel events to AntTweakBar
    glfwSetMouseWheelCallback((GLFWmousewheelfun)TwEventMouseWheelGLFW);
    
    // - Directly redirect GLFW key events to AntTweakBar
    glfwSetKeyCallback((GLFWkeyfun)TwEventKeyGLFW);
    
    // - Directly redirect GLFW char events to AntTweakBar
    glfwSetCharCallback((GLFWcharfun)TwEventCharGLFW);


	TwDefine("TweakBar label='Main TweakBar' alpha=0 help='Use this bar to control the objects of the scene.' ");

	// Add 'wire' to 'myBar': it is a modifable variable of type TW_TYPE_BOOL32 (32 bits boolean). Its key shortcut is [w].
    TwAddVarRW(myBar, "wireframe mode", TW_TYPE_BOOL32, &wireFrame," label='Wireframe mode' key=w help='Toggle wireframe display mode.' ");

	// Add 'bgColor' to 'myBar': it is a modifable variable of type TW_TYPE_COLOR3F (3 floats color)
    TwAddVarRW(myBar, "bgColor", TW_TYPE_COLOR3F, &bgColor, " label='Background color' ");

	// Add 'Rotation' to 'myBar': this is a variable of type TW_TYPE_QUAT4F which defines the scene's orientation
    TwAddVarRW(myBar, "SceneRotation", TW_TYPE_QUAT4F, &Rotation," label='Scene rotation' opened=true help='Change the scenes orientation.' ");

	TwAddButton(myBar, "Reset", ResetView,NULL," label='Reset View' ");

	TwAddVarRW(myBar, "Near Clip Plane", TW_TYPE_FLOAT, &zNear,"min=0.5 max=100 step=0.5 label='Near Clip' group='Projection Properties'");

	TwAddVarRW(myBar, "Far Clip Plane", TW_TYPE_FLOAT, &zFar," min=0.5 max=1000 step=0.5 label='Far Clip' group='Projection Properties'");

	TwAddVarRW(myBar, "Field of View", TW_TYPE_FLOAT, &FOV," label='FoV' readonly=true group='Projection Properties'");

	TwAddVarRW(myBar, "MS per 1 Frame" , TW_TYPE_DOUBLE, &FPS, "label='MS per 1 Frame' readonly=true group='Frame Rate'");

	TwAddVarRW(myBar, "Frames Per Second" , TW_TYPE_INT32, &rate, "label='FPS' readonly=true group='Frame Rate'");

	TwAddVarRW(myBar, "vSYNC" , TW_TYPE_BOOL8, &SYNC, "label='vSync' readonly=true group='Frame Rate'");
	
	 // Enable depth test
	glEnable(GL_DEPTH_TEST);
	// Accept fragment if it closer to the camera than the former one
	glDepthFunc(GL_LESS);

	initPlane(); //initialize Plane

	init3Dmodel(); // initialize 3D model

	create_Bump_bar();

	GLfloat rat = 0.001f;

	if(SYNC == false)
	{
		rat = 0.001f;
	}
	else
	{
		rat = 0.01f;
	}

	// Initialize time
    time = glfwGetTime();
	double currentTime;
	float lastTime = 0.0f;

	int Frames = 0;
	double LT = glfwGetTime();
	starting = glfwGetTime();

	setVSync(SYNC);

	while (running) {

		glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT );
        glClearColor( bgColor[0], bgColor[1], bgColor[2], bgColor[3]); //black color

		FOV = initialFoV - 5 * glfwGetMouseWheel();

		if(camera == true)
		{
			glfwGetMousePos(&xpos,&ypos);
			glfwSetMousePos(windowWidth/2, windowHeight/2);
		
			horizAngle  += mouseSpeedo * float(windowWidth/2 - xpos );
			verticAngle += mouseSpeedo * float( windowHeight/2 - ypos );
		}

		glm::vec3 direction(cos(verticAngle) * sin(horizAngle),sin(verticAngle),cos(verticAngle) * cos(horizAngle));

		glm::vec3 right = glm::vec3(sin(horizAngle - 3.14f/2.0f),0,cos(horizAngle - 3.14f/2.0f));

		glm::vec3 up = glm::cross( right, direction );

		currentTime = glfwGetTime();
		float dTime = float(currentTime - lastTime);
		lastTime = (float)currentTime;

		// Move forward
		if (glfwGetKey( GLFW_KEY_UP ) == GLFW_PRESS){
			pos += direction * dTime* speedo;
		}
		// Move backward
		if (glfwGetKey( GLFW_KEY_DOWN ) == GLFW_PRESS){
			pos -= direction * dTime * speedo;
		}
		// Strafe right
		if (glfwGetKey( GLFW_KEY_RIGHT ) == GLFW_PRESS){
			pos += right * dTime * speedo;
		}
		//Strafe left
		if (glfwGetKey( GLFW_KEY_LEFT ) == GLFW_PRESS){
				pos -= right * dTime * speedo;
		}

		if (glfwGetKey(GLFW_KEY_SPACE) == GLFW_PRESS){

			if(camera == false)
			{
				camera=true;
				glfwSetMousePos(windowWidth/2, windowHeight/2);
				glfwGetMousePos(&xpos,&ypos);
			}
			else
			{
				camera=false;
				glfwSetMousePos(windowWidth/2, windowHeight/2);
				glfwGetMousePos(&xpos,&ypos);
			}
		}

		mat = ConvertQuaternionToMatrix(Rotation, mat);

		glm::mat4 cube;

		glm::mat4 translateMat = glm::mat4();
		translateMat = glm::translate(translateMat,glm::vec3(5.0,3.0,4.0));

		cube  = mat * translateMat;

		displayPlane(mat,pos,direction,up);

		display3Dmodel(cube,mat,pos,direction,up);

		// drawing the AntWeakBar
		if (wireFrame)
		{
			glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
			TwDraw();
		}
		else
		{
			glPolygonMode(GL_FRONT_AND_BACK, GL_FILL);
			TwDraw();
		}
		fr++;
		ending = glfwGetTime();

		if(ending - starting >= 1)
		{
			rate = fr;
			fr = 0;
			starting = glfwGetTime();
		}

		double CT = glfwGetTime();
		Frames++;
		if(CT -LT >= 1.0)
		{
			FPS = 1000.0 / (double)Frames;
			Frames = 0;
			LT += 1.0f;
		}

        glfwSwapBuffers();
        //check if ESC was pressed
        running=!glfwGetKey(GLFW_KEY_ESC) && glfwGetWindowParam(GLFW_OPENED);
    }

	//close OpenGL window and  terminate AntTweakBar and GLFW
    TwTerminate();
    glfwTerminate();
    
    
    exit(EXIT_SUCCESS);
    
}
Esempio n. 21
0
void AIE::FreeMovement(float a_fDeltaTime, AIE::mat4& a_rmFrame, float a_fSpeed, const AIE::vec4& a_rvUp /* = vec4 */)
{
	// update mouse wheel
	static int siPrevMouseWheel = 0;
	int iMouseWheel = glfwGetMouseWheel();
	int iMouseWheelDelta = iMouseWheel - siPrevMouseWheel;
	siPrevMouseWheel = iMouseWheel;

	// Get the camera's forward, right, up, and location vectors
	AIE::vec4 vForward = a_rmFrame.row2;
	AIE::vec4 vRight = a_rmFrame.row0;
	AIE::vec4 vUp = a_rmFrame.row1;
	AIE::vec4 vTranslation = a_rmFrame.row3;

	// Translate camera
	float fSpeed = glfwGetKey(GLFW_KEY_LSHIFT) == GLFW_PRESS ? a_fSpeed * 2 : a_fSpeed;	

	if (glfwGetKey('W') == GLFW_PRESS)
	{
		vTranslation += vForward * (a_fDeltaTime * fSpeed);
	}
	if (glfwGetKey('S') == GLFW_PRESS)
	{
		vTranslation -= vForward * (a_fDeltaTime * fSpeed);
	}
	if (glfwGetKey('D') == GLFW_PRESS)
	{
		vTranslation += vRight * (a_fDeltaTime * fSpeed);
	}
	if (glfwGetKey('A') == GLFW_PRESS)
	{
		vTranslation -= vRight * (a_fDeltaTime * fSpeed);
	}
	if (glfwGetKey('Q') == GLFW_PRESS)
	{
		vTranslation += vUp * (a_fDeltaTime * fSpeed);
	}
	if (glfwGetKey('E') == GLFW_PRESS)
	{
		vTranslation -= vUp * (a_fDeltaTime * fSpeed);
	}
	if (iMouseWheelDelta != 0)
	{
		vTranslation += vForward * (a_fDeltaTime * fSpeed * iMouseWheelDelta);
	}

	a_rmFrame.row3 = vTranslation;

	// check for camera rotation
	static bool sbMouseButtonDown = false;
	if (glfwGetMouseButton(GLFW_MOUSE_BUTTON_2) == GLFW_PRESS)
	{
		static int siPrevMouseX = 0;
		static int siPrevMouseY = 0;

		if (sbMouseButtonDown == false)
		{
			sbMouseButtonDown = true;
			glfwGetMousePos(&siPrevMouseX,&siPrevMouseY);
		}

		int iMouseX = 0, iMouseY = 0;
		glfwGetMousePos(&iMouseX,&iMouseY);

		int iDeltaX = iMouseX - siPrevMouseX;
		int iDeltaY = iMouseY - siPrevMouseY;

		siPrevMouseX = iMouseX;
		siPrevMouseY = iMouseY;

		AIE::mat4 mMat;
		
		// pitch
		if (iDeltaY != 0)
		{
			mMat.RotateAxis(-iDeltaY / 150.f, vRight);
			vForward = mMat * vForward;
			vUp = mMat * vUp;
			vRight = mMat * vRight;
		}

		// yaw
		if (iDeltaX != 0)
		{
			mMat.RotateAxis(-iDeltaX / 150.0f, a_rvUp);
			vForward = mMat * vForward;
			vUp = mMat * vUp;
			vRight = mMat * vRight;
		}

		a_rmFrame.row0 = vRight;
		a_rmFrame.row1 = vUp;
		a_rmFrame.row2 = vForward;
	}
	else
	{
		sbMouseButtonDown = false;
	}
}
Esempio n. 22
0
void computeMatricesFromInputs(){

	// glfwGetTime is called only once, the first time this function is called
	static double lastTime = glfwGetTime();

	// Compute time difference between current and last frame
	double currentTime = glfwGetTime();
	float deltaTime = float(currentTime - lastTime);

	// Get mouse position
	int xpos, ypos;
	glfwGetMousePos(&xpos, &ypos);

	// Reset mouse position for next frame
	glfwSetMousePos(1024/2, 768/2);

	// Compute new orientation
	horizontalAngle += mouseSpeed * float(1024/2 - xpos );
	verticalAngle   += mouseSpeed * float( 768/2 - ypos );

	// Direction : Spherical coordinates to Cartesian coordinates conversion
	glm::vec3 direction(
		cos(verticalAngle) * sin(horizontalAngle), 
		sin(verticalAngle),
		cos(verticalAngle) * cos(horizontalAngle)
	);
	
	// Right vector
	glm::vec3 right = glm::vec3(
		sin(horizontalAngle - 3.14f/2.0f), 
		0,
		cos(horizontalAngle - 3.14f/2.0f)
	);
	
	// Up vector
	glm::vec3 up = glm::cross( right, direction );

	multi = 1.f;
	if (glfwGetKey( GLFW_KEY_LSHIFT ) == GLFW_PRESS)
	{
		multi = 3.f;
	}
	// Move forward
	if (glfwGetKey( GLFW_KEY_UP ) == GLFW_PRESS || glfwGetKey( 'W' ) == GLFW_PRESS){
		position += direction * deltaTime * speed * multi;
	}
	// Move backward
	if (glfwGetKey( GLFW_KEY_DOWN ) == GLFW_PRESS || glfwGetKey( 'S' ) == GLFW_PRESS){
		position -= direction * deltaTime * speed * multi;
	}
	// Strafe right
	if (glfwGetKey( GLFW_KEY_RIGHT ) == GLFW_PRESS || glfwGetKey( 'D' ) == GLFW_PRESS){
		position += right * deltaTime * speed * multi;
	}
	// Strafe left
	if (glfwGetKey( GLFW_KEY_LEFT ) == GLFW_PRESS || glfwGetKey( 'A' ) == GLFW_PRESS){
		position -= right * deltaTime * speed * multi;
	}

	float FoV = initialFoV - 5 * glfwGetMouseWheel();

	// Projection matrix : 45° Field of View, 4:3 ratio, display range : 0.1 unit <-> 100 units
	ProjectionMatrix = glm::perspective(FoV, 4.0f / 3.0f, 0.1f, 100.0f);
	// Camera matrix
	ViewMatrix       = glm::lookAt(
								position,           // Camera is here
								position+direction, // and looks here : at the same position, plus "direction"
								up                  // Head is up (set to 0,-1,0 to look upside-down)
						   );

	// For the next frame, the "last time" will be "now"
	lastTime = currentTime;
}
Esempio n. 23
0
int main(int argc, char *argv[])
{
    char *shader = "mandelbrot (copy).frag";
    if (argc > 1)
    {
        shader = argv[1];
    }

    glfwInit();



    /*int major, minor, rev;
    glfwGetGLVersion(&major, &minor, &rev);
    printf("using openGL %d.%d.%d\n", major, minor, rev);*/

    GLFWvidmode mode;
    glfwGetDesktopMode( &mode );

    window_width = mode.Width;
    window_height = mode.Height;

    printf("%dx%d\n", window_width, window_height);
    //glfwOpenWindow(window_width, window_height, 5, 6, 5, 0, 8, 0, GLFW_FULLSCREEN);
    glfwOpenWindow(mode.Width, mode.Height, mode.RedBits,  mode.GreenBits, mode.BlueBits, 0, 0, 0, GLFW_FULLSCREEN);

    // setup opengl perspective stuff.
    glMatrixMode(GL_PROJECTION);
    float aspect_ratio = ((float)window_height) / window_width;
    glFrustum(.5, -.5, -.5 * aspect_ratio, .5 * aspect_ratio, 1, 50);
    glDisable( GL_DEPTH_TEST );
    glTranslatef(0.0, 0.0, -1.00);
    glClearColor(0.0, 1.0, 1.0, 0.0);


    // will create and set shader program.
    GLhandleARB program = SetupFragmentShader(shader);
    // get the location of all the uniforms
    prepareUniforms(program);
    // must call use program before setting uniforms values
    glUseProgram(program);

    uint param_i = 0;
    parameters[WIDTH]   = createParameter1i(program, "wW", window_width );
    parameters[HEIGHT]  = createParameter1i(program, "wH", window_height );
    parameters[TIME]    = createParameter1f(program, "time", 0.0 );
    parameters[MINX]    = createParameter1f(program, "minx", -2.0);
    parameters[MINY]    = createParameter1f(program, "miny", 1.0);
    parameters[DELTA]   = createParameter1f(program, "deltax", 3.0);
    parameters[THETA]   = createParameter1f(program, "theta", 1.0);
    //synchParameters ( parameters );

    /*for ( param_i = 0; param_i < NPARAMS; param_i++ )
    {
        Parameter *param = &parameters[param_i];
        switch ( param->utype )
        {
            case INT:
                glUniform1i(param->loc, param->u.ival);
                break;
            case FLOAT:
                glUniform1f(param->loc, param->u.fval);
                break;
            default:
                break;
        }
    }*/

    // set the dimension, must be after program is used.
    //glUniform1i(wWLoc, window_width );
    //glUniform1i(wHLoc, window_height );

    printInstructions();

    double frame_start = glfwGetTime();
    double frame_time = 0.0;
    double temp_time = 0.0;

    //bool need_draw = true;
    bool need_view_synch = true;


    int mouseWheel = 0;
    int mouseWheelDelta = 0;

    double fIterations = (double)(iterations);

    int mouseX, mouseY, curMouseX, curMouseY;
    mouseX = mouseY = 0;

    bool joystickPresent = glfwGetJoystickParam( GLFW_JOYSTICK_1, GLFW_PRESENT );
    if(joystickPresent)
    {
        printf("Joystick present. Can be used to navigate in addition to mouse.\n");
    }else
    {
        printf("no joystick present.\n");
    }

    // set up fonts

    FTGLfont *font = NULL;
    //font = ftglCreateBufferFont("/usr/share/fonts/truetype/freefont/FreeMono.ttf");
    font = ftglCreatePixmapFont("/usr/share/fonts/truetype/freefont/FreeMono.ttf");
    if( !font )
    {
        printf("failed to load font.");
    }
    ftglSetFontFaceSize(font, 50, 50);
    //printf("%d\n", ftglGetFontError(font));
    //ftglSetFontCharMap(font, ft_encoding_unicode);
    //printf("%d\n", ftglGetFontError(font));

    bool show_fps = true;
    char text[256];

    // keep on rendering the frame until escape is pressed.
    while(glfwGetKey(GLFW_KEY_ESC) != GLFW_PRESS)
    {
        temp_time = glfwGetTime();
        frame_time = temp_time - frame_start;
        frame_start = temp_time;

        // process input
        if(glfwGetKey('E') == GLFW_PRESS)
        {
            printf("minx: %.31f\n", minx);
            printf("miny: %.31f\n", miny);
            printf("deltax: %.31f\n",deltax);
            printf("deltay: %.31f\n",deltay);
            printf("====================================\n");
        }else if(glfwGetKey('P') == GLFW_PRESS)
        {
            saveFrameBuffer();
        }else if(glfwGetKey('R') == GLFW_PRESS)
        {
            minx = -2.0;
            miny = -1.0;
            deltax = 3.0;
            deltay = 2.0;
            need_view_synch = true;
        }else if(glfwGetKey('F') == GLFW_PRESS)
        {
            show_fps=~show_fps;
            //printf("fps display toggled to: %d\n", show_fps);
        }

        else if(glfwGetKey(GLFW_KEY_RIGHT) == GLFW_PRESS)
        {
            fIterations += 5*(60*frame_time);
            iterations = floor(fIterations);
            need_view_synch = true;
        }else if(glfwGetKey(GLFW_KEY_LEFT) == GLFW_PRESS)
        {
            if(iterations>1)
            {
                fIterations -= 5*(60*frame_time);
            }
            iterations = floor(fIterations);
            need_view_synch = true;
        }
        // zooming using the arrow keys
        if(glfwGetKey(GLFW_KEY_UP) == GLFW_PRESS)
        {
            zoomIn(2.0*zoom_factor*(frame_time*60.0));
            need_view_synch = true;
        }else if(glfwGetKey(GLFW_KEY_DOWN) == GLFW_PRESS)
        {
            zoomIn(-2.0*zoom_factor*(frame_time*60.0));
            need_view_synch = true;
        }

        //changing the julia set constant
        if(glfwGetKey('W') == GLFW_PRESS)
        {
            realc += .0025*frame_time*60.0;
            need_view_synch = true;
        }else if(glfwGetKey('S') == GLFW_PRESS)
        {
            realc -= .0025*frame_time*60.0;
            need_view_synch = true;
        }
        if(glfwGetKey('A') == GLFW_PRESS)
        {
            imagc += .0025*frame_time*60.0;
            need_view_synch = true;
        }else if(glfwGetKey('D') == GLFW_PRESS)
        {
            imagc -= .0025*frame_time*60.0;
            need_view_synch = true;
        }

        // changing the area visible (panning left and right)
        glfwGetMousePos(&curMouseX, &curMouseY);
        int mouseDeltax = curMouseX - mouseX;
        int mouseDeltay = curMouseY - mouseY;

        if(mouseDeltax||mouseDeltay)//if one of them is different
        {
            //printf("delta coordinates: (%d, %d)\n", mouseDeltax, mouseDeltay);
            mouseX=curMouseX;
            mouseY=curMouseY;
            //printf("new mouse coordinates: (%d, %d)\n", x, y);
            pan(zoom_factor*deltax*mouseDeltax/20.0, -1*zoom_factor*deltay*mouseDeltay/20.0);
            need_view_synch = true;
        }
        if(joystickPresent)
        {
            float pos[4];
            glfwGetJoystickPos(GLFW_JOYSTICK_1, pos, 4);
            //the above function gives us bad results for my particular joystick :(, must fiddle around with numbers to get correct answer.
            float xJoyPos = pos[0];//(pos[0]*32767)/128.0 - 1.0;
            float yJoyPos = pos[1];//(pos[1]*32767)/128.0 + 1.0;
            float zJoyPos = -1*pos[2];//-1*((pos[2]*32767)/128.0 - 1.0);
            float rJoyPos = pos[3];
            float temp = 0.0;
            //printf("%f\n", xJoyPos);

            if(xJoyPos>.02||xJoyPos<-.02)
            {
                temp = zoom_factor*xJoyPos*deltax*1.0*frame_time*60.0;
                pan(temp, 0);
                need_view_synch = true;
            }
            if(yJoyPos>.02||yJoyPos<-.02)
            {
                temp = zoom_factor*yJoyPos*deltay*1.0*frame_time*60.0;
                pan(0, temp);
                need_view_synch = true;
            }
            if(zJoyPos>.04||zJoyPos<-.04)
            {
                zoomIn(zJoyPos*scroll_zoom_factor*(frame_time*10.0));
                need_view_synch = true;
            }
            if(rJoyPos>.02 || rJoyPos<-.02)
            {
                rotate( rJoyPos/5.0*frame_time );
                need_view_synch = true;
            }
            unsigned char buttons[5];

            glfwGetJoystickButtons(GLFW_JOYSTICK_1, buttons, 4);
            if(buttons[0]==GLFW_PRESS)
            {
                saveFrameBuffer();
            }
            if(buttons[1]==GLFW_PRESS)
            {
                rotate( 0.35*frame_time );
                need_view_synch = true;
            }else if(buttons[2]==GLFW_PRESS)
            {
                rotate( -0.35*frame_time );
                need_view_synch = true;
            }

            //printf("x:%f, y:%f\n", xJoyPos, yJoyPos);
        }

        // zooming using the mouse scroll
        mouseWheelDelta = glfwGetMouseWheel() - mouseWheel;
        mouseWheel = mouseWheel+mouseWheelDelta;
        if(mouseWheelDelta != 0)
        {
            zoomIn(mouseWheelDelta*scroll_zoom_factor*(frame_time*60.0));
            need_view_synch = true;
        }

        //printf("mouse wheel: %d\n", mouseWheelDelta);

        if(need_view_synch)
        {
            synchVariableUniforms();
            need_view_synch = false;
        }

        // update the time inside the shader for cool animations.

        parameters[2].val.fval = frame_start;
        parameters[2].needs_update = true;

        synchParameters ( parameters );

        //glUniform1f(timeLoc, frame_start);

        // write fps and iterations to a string.
        sprintf(text, "FPS: %4.1d; ITER: %d; ZOOMX: %-10.1f", (int)(floor(1.0/frame_time)), iterations, (3.0/deltax));

        //sprintf("fps %f\n", 1.0/frame_time);

        // clear the buffer
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        //since all calculations are being done in the fragment shader, all we draw is a surface.
        glUseProgram(program);
        glRects(-1, -1, 1, 1);

        // render font on top of this?
        if(show_fps != 0){
            glUseProgram(0);
            glColor3f(0.0f, 0.0f, 0.0f);
            ftglRenderFont(font, text, FTGL_RENDER_ALL);
            glUseProgram(program);
        }
        // note: swap buffers also updates the input events for glfw
        glfwSwapBuffers();
    }
    // clean up the font and exit.
    ftglDestroyFont(font);
    return 1;
}