Exemple #1
0
void Init()
{
  const int window_width = 800,
           window_height = 600;
 
  if (glfwInit() != GL_TRUE)
    Shut_Down(1);
  // 800 x 600, 16 bit color, no depth, alpha or stencil buffers, windowed
  if (glfwOpenWindow(window_width, window_height, 5, 6, 5,
                  0, 0, 0, GLFW_WINDOW) != GL_TRUE)
    Shut_Down(1);
  glfwSetWindowTitle("The GLFW Window");
 
  glfwSetKeyCallback( OnKeyPressed );
  glfwSetCharCallback( OnCharPressed );
  glfwSetWindowCloseCallback(OnClose);
  glfwSetWindowSizeCallback(OnResize);
  glfwSetWindowRefreshCallback(OnRefresh);
  glfwSetMouseWheelCallback(OnMouseWheel);
  glfwSetMousePosCallback(OnMouseMove);
  glfwSetMouseButtonCallback(OnMouseClick);
  
  // set the projection matrix to a normal frustum with a max depth of 50
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  float aspect_ratio = ((float)window_height) / window_width;
  glFrustum(.5, -.5, -.5 * aspect_ratio, .5 * aspect_ratio, 1, 50);
  glMatrixMode(GL_MODELVIEW);
  
  PullInfo();
}
Exemple #2
0
void Application::createDisplay(uint width, uint height,
                            uint redBits, uint greenBits, uint blueBits,
                            uint alphaBits, uint depthBits, uint stencilBits,
                            DisplayMode mode, const std::string &title)
{
    GLboolean status;
    status = glfwOpenWindow(width, height, redBits, greenBits, blueBits, 
                    alphaBits, depthBits, stencilBits,
                    mode == DISP_FULLSCREEN ? GLFW_FULLSCREEN : GLFW_WINDOW);
    if(status == GL_FALSE)
    {
        throw APIError("Failed to create display.");
    }
    
    // fetch window size (fixes X11 fullscreen bug)
    glfwGetWindowSize(reinterpret_cast<int*>(&displayWidth_), 
                        reinterpret_cast<int*>(&displayHeight_));
    
    glfwSetWindowTitle(title.c_str());  // title is set separately
    
    initOpenGL();
    setOrthoView();
    
    // register the callbacks (after a window is open)
    glfwSetKeyCallback(Application::keyCallback);
    //glfwSetCharCallback(Application::charCallback);
    glfwSetMouseButtonCallback(Application::mouseButtonCallback);
    glfwSetMousePosCallback(Application::mouseMoveCallback);
    glfwSetMouseWheelCallback(Application::mouseWheelCallback);
    
    quit_ = false;
}
Exemple #3
0
    bool initialize() {
    	BOOST_LOG_TRIVIAL(info) << "Application initialized";

        if (!glfwInit())
            return false;

        window_instance = glfwOpenWindow(window_width, window_height, color_depth,
                                         color_depth, color_depth, 0, 24, 0, GLFW_WINDOW);

        if (!window_instance)
            return false;

        glfwSetWindowTitle(window_title.c_str());
        glfwSetKeyCallback(application::key_callback);
        glfwSetMouseButtonCallback(mouse_button_callback);
        glfwSetMouseWheelCallback(mouse_wheel_callback);

        glfwSwapBuffers();

        keybindings = qts::default_keybindings::keybinding;

        game_state.active_camera.reset(new qts::camera());
        game_state.active_camera->eye = glm::vec3(0.0f, 500.0f, 0.0f);

        return true;
    }
void ShellSystemInterface::RegisterInputDevices(){
	registerKeyboardInput();
	
	glfwSetMousePosCallback(&HandleMousePosition);
	glfwSetMouseButtonCallback(&HandleMouseToggle);
	glfwSetMouseWheelCallback(&HandleScrollWheel);
	inputRegistered = true;
	
}
void ShellSystemInterface::UnRegisterInputDevices(){
	glfwSetCharCallback(NULL);
	glfwSetKeyCallback(NULL);
	
	glfwSetMousePosCallback(NULL);
	glfwSetMouseButtonCallback(NULL);
	glfwSetMouseWheelCallback(NULL);
	inputRegistered = false;
}
void setupCallbacks(){
    glfwSetWindowSizeCallback( GLFWWindowSizeCb );
    glfwSetWindowCloseCallback( GLFWWindowCloseCb );
    glfwSetWindowRefreshCallback( GLFWWindowRefreshCb );
    glfwSetKeyCallback( GLFWKeyCb );
    glfwSetCharCallback( GLFWMousePosCb );
    glfwSetMouseButtonCallback( GLFWMouseButtonCb );
    glfwSetMousePosCallback( GLFWMousePosCb );
    glfwSetMouseWheelCallback( GLFWMouseWheelCb );
};
Exemple #7
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);
}
void GLFWMouseListener::MouseInit()
{
	if (!initialised)
	{
		glfwSetMouseButtonCallback(MouseButtonCallback);
		glfwSetMousePosCallback(MouseMoveCallback);
		glfwSetMouseWheelCallback(MouseWheelCallback);
		listeners.push_back(this);
	}
	initialised = true;
}
Exemple #9
0
int main(void)
{
    GLFWvidmode mode;

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

    glfwGetDesktopMode(&mode);

    if (!glfwOpenWindow(mode.Width, mode.Height, 0, 0, 0, 0, 0, 0, GLFW_FULLSCREEN))
    {
        glfwTerminate();

        fprintf(stderr, "Failed to open GLFW window\n");
        exit(1);
    }

    glfwSetWindowTitle("Fullscreen Input Detector");
    glfwSetKeyCallback(key_callback);
    glfwSetCharCallback(char_callback);
    glfwSetMousePosCallback(mouse_position_callback);
    glfwSetMouseButtonCallback(mouse_button_callback);
    glfwSetMouseWheelCallback(mouse_wheel_callback);
    glfwSetWindowSizeCallback(window_size_callback);
    glfwSwapInterval(1);

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glfwSetTime(0.0);

    running = GL_TRUE;

    while (running)
    {
        glClearColor((GLclampf) fabs(cos(glfwGetTime() * 4.f)), 0, 0, 0);
        glClear(GL_COLOR_BUFFER_BIT);

        glfwSwapBuffers();

        if (!glfwGetWindowParam(GLFW_OPENED))
            running = GL_FALSE;

        if (glfwGetTime() > 10.0)
            running = GL_FALSE;
    }

    glfwTerminate();
    exit(0);
}
Exemple #10
0
/////////////////////////////////////////////////////////
// createMess
//
/////////////////////////////////////////////////////////
bool gemglfw2window :: create(void)
{
  int mode = GLFW_WINDOW;
  if(0!=s_window) {
    error("window already made!");
    return false;
  }

  if(m_fullscreen)
    mode=GLFW_FULLSCREEN;

  glfwOpenWindowHint(GLFW_FSAA_SAMPLES, m_fsaa);


  if(m_profile_major) {
    glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, m_profile_major); // We want OpenGL 3.3
    glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, m_profile_minor);
    glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //We don't want the old OpenGL
  }

  if (!glfwOpenWindow(m_width, m_height,
                      8, 8, 8, 8,  /* RGBA bits */
                      24, 8,       /* depth/stencil bits */
                      mode)) {
    error("glfw couldn't create window");
    return false;
  }



  // FIXXME: single/double buffering

  if(!createGemWindow()) {
    destroyMess();
    return false;
  }
  s_window=this;

  titleMess(m_title);
  offsetMess(m_xoffset, m_yoffset);
  cursorMess(m_cursor);

  glfwSetWindowSizeCallback   (windowsizeCb);
  glfwSetWindowCloseCallback  (windowcloseCb);
  glfwSetWindowRefreshCallback(windowrefreshCb);
  glfwSetKeyCallback          (keyCb);
  glfwSetCharCallback         (charCb);
  glfwSetMouseButtonCallback  (mousebuttonCb);
  glfwSetMousePosCallback     (mouseposCb);
  glfwSetMouseWheelCallback   (mousewheelCb);
  dispatch();
  return (0!=s_window);
}
Exemple #11
0
void outPut::init_Tw()
{
    ///Initialisation AntTweakBar
    TwInit(TW_OPENGL, NULL);
    TwWindowSize(_reg.WIDTH, _reg.HEIGHT);
    // redirection des callbacks GFLW sur AntTweakBar
    glfwSetMouseButtonCallback((GLFWmousebuttonfun)TwEventMouseButtonGLFW);
    glfwSetMousePosCallback((GLFWmouseposfun)TwEventMousePosGLFW);
    glfwSetMouseWheelCallback((GLFWmousewheelfun)TwEventMouseWheelGLFW);
    glfwSetKeyCallback((GLFWkeyfun)TwEventKeyGLFW);
    glfwSetCharCallback((GLFWcharfun)TwEventCharGLFW);
}
bool InputGLFW::Initialise()
{
	InitialiseKeymap();

	//init callbacks for glfw
	glfwSetCharCallback( CharCallback );
	glfwSetKeyCallback( KeyCallback );
	glfwSetMouseButtonCallback( MouseButtonCallback );
	glfwSetMousePosCallback( MousePosCallback );
	glfwSetMouseWheelCallback( MouseWheelCallback );

	return true;
}
Exemple #13
0
void RenderWindow::setCallbacks() {

	glfwEnable(GLFW_STICKY_KEYS);
	//glfwDisable( GLFW_SYSTEM_KEYS );

	// glfw callbacks ///////////////////////////////////////////////////	
	glfwSetKeyCallback(keyCB);
	glfwSetCharCallback(charCB);
	glfwSetMousePosCallback(mousePosCB);
	glfwSetMouseButtonCallback(mouseButtonCB);
	glfwSetMouseWheelCallback(mouseWheelCB);

	glfwSetWindowSizeCallback(windowSizeCB);
}
int main(void)
{
    setlocale(LC_ALL, "");

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

    printf("Library initialized\n");

    if (!glfwOpenWindow(0, 0, 0, 0, 0, 0, 0, 0, GLFW_WINDOW))
    {
        glfwTerminate();

        fprintf(stderr, "Failed to create GLFW window");
        exit(1);
    }

    printf("Window opened\n");

    glfwSetWindowTitle("Event Linter");
    glfwSwapInterval(1);

    glfwSetWindowSizeCallback(window_size_callback);
    glfwSetWindowCloseCallback(window_close_callback);
    glfwSetWindowRefreshCallback(window_refresh_callback);
    glfwSetMouseButtonCallback(mouse_button_callback);
    glfwSetMousePosCallback(mouse_position_callback);
    glfwSetMouseWheelCallback(mouse_wheel_callback);
    glfwSetKeyCallback(key_callback);
    glfwSetCharCallback(char_callback);

    printf("Key repeat should be %s\n", keyrepeat ? "enabled" : "disabled");
    printf("System keys should be %s\n", systemkeys ? "enabled" : "disabled");

    printf("Main loop starting\n");

    while (glfwGetWindowParam(GLFW_OPENED) == GL_TRUE)
    {
        glfwWaitEvents();
        glClear(GL_COLOR_BUFFER_BIT);
        glfwSwapBuffers();
    }

    glfwTerminate();
    exit(0);
}
void InputManager::RemoveGlfwCallbacks()
{
	glfwSetWindowSizeCallback(nullptr);

	glfwSetKeyCallback(nullptr);
	glfwSetCharCallback(nullptr);
	glfwSetMouseButtonCallback(nullptr);
	glfwSetMousePosCallback(nullptr);
	glfwSetMouseWheelCallback(nullptr);
#ifdef _GLFW_DMITRI_WINDOWS_TOUCH_ENABLED
	glfwSetTouchCallback(nullptr);
#endif // _GLFW_DMITRI_WINDOWS_TOUCH_ENABLED

	m_TypingPointer.reset();
	m_MousePointer.reset();
}
void InputManager::SetGlfwCallbacks()
{
	m_TypingPointer = std::unique_ptr<TypingPointer>(new TypingPointer(*m_InputHandler));
	m_MousePointer = std::unique_ptr<MousePointer>(new MousePointer(*m_InputHandler));

	glfwSetWindowSizeCallback(&InputManager::ProcessWindowSize);

	glfwSetKeyCallback(&InputManager::ProcessKey);
	glfwSetCharCallback(&InputManager::ProcessChar);
	glfwSetMouseButtonCallback(&InputManager::ProcessMouseButton);
	glfwSetMousePosCallback(&InputManager::ProcessMousePos);
	glfwSetMouseWheelCallback(&InputManager::ProcessMouseWheel);
#ifdef _GLFW_DMITRI_WINDOWS_TOUCH_ENABLED
	glfwSetTouchCallback(&InputManager::ProcessTouch);
#endif // _GLFW_DMITRI_WINDOWS_TOUCH_ENABLED
}
Exemple #17
0
/** Event handler
 */
static orxSTATUS orxFASTCALL orxMouse_GLFW_EventHandler(const orxEVENT *_pstEvent)
{
  orxSTATUS eResult = orxSTATUS_SUCCESS;

  /* Checks */
  orxASSERT(_pstEvent->eType == orxEVENT_TYPE_DISPLAY);

  /* Registers mouse position callback */
  glfwSetMousePosCallback(orxMouse_GLFW_MousePositionCallback);

  /* Registers mouse wheel callback */
  glfwSetMouseWheelCallback(orxMouse_GLFW_MouseWheelCallback);

  /* Asks for cursor update */
  sstMouse.bUpdateCursor = orxTRUE;

  /* Done! */
  return eResult;
}
Exemple #18
0
int openWindow(bool fullscreen)
{
	unsigned long windowFlag = (fullscreen ? GLFW_FULLSCREEN : GLFW_WINDOW);

	// load GLFW
	if (glfwInit() != GL_TRUE)
	{
		fprintf(stderr, "ERROR: Could not initialize GLFW\n");
		return EXIT_FAILURE;
	}

	// set core profile OpenGL 3.3+
	//glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3); // Set OpenGL version to 3.3+
	//glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 3);
	//glfwOpenWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); // Request core profile
	//glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // Disable legacy

	// Initialize the window & create
	if (glfwOpenWindow(RESOLUTION_X, RESOLUTION_Y,
			8, 8, 8, 8, // RGBA bits
			16, 0, // depth, stencil bits
			windowFlag) != GL_TRUE)
	{
		fprintf(stderr, "ERROR: Could not open window\n");
		glfwTerminate();
		return EXIT_FAILURE;
	}

	glfwSetWindowTitle(APP_TITLE);

	// Set up callbacks
	glfwSetKeyCallback(glfwKeyboard);
	glfwSetMousePosCallback(glfwMouseMove);
	glfwSetMouseButtonCallback(glfwMouseInput);
	glfwSetMouseWheelCallback(glfwMouseWheel);

	glfwSetWindowSizeCallback(glfwResize);
	glfwSetWindowCloseCallback(glfwWindowClosed);

	return 0;
}
Exemple #19
0
    void Root::setFullscreen(bool fullscr)
    {
        if( fullscreen == fullscr ) return; //no difference
        fullscreen = fullscr;

        glfwCloseWindow();

        if(!glfwOpenWindow(windowWidth, windowHeight, 0, 0, 0, 0, 32, 0, (fullscreen ? GLFW_FULLSCREEN : GLFW_WINDOW)))
        {
            LOG_ERROR("Could not re-create window. Closing now.");
            stopRendering();
            return;
        }

        glfwSetWindowTitle("Arya");
        glfwEnable(GLFW_MOUSE_CURSOR);
        glfwSetKeyCallback(keyCallback);
        glfwSetMouseButtonCallback(mouseButtonCallback);
        glfwSetMousePosCallback(mousePosCallback);
        glfwSetMouseWheelCallback(mouseWheelCallback);
    }
Exemple #20
0
bool GLFWWindow::open(const std::string& title, uint width, uint height)
{
	if(opened)
		return true;

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

	if(glfwInit() == GL_FALSE)
	{
		logError("cannot initialize GLFW");
		return false;
	}

	glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR,  3);
	glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR,  3);
	glfwOpenWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);

	if(!glfwOpenWindow(width, height, 8, 8, 8, 8, 24, 8, GLFW_WINDOW))
	{
		logError("cannot open the GLFW window");
		return false;
	}

	if(!glxwInit())
		return false;

	glfwSetWindowTitle(title.c_str());

	glfwSetMouseButtonCallback(&mouseButtonCallback);
	glfwSetMousePosCallback(&mousePosCallback);
	glfwSetMouseWheelCallback(&mouseWheelCallback);
	glfwSetKeyCallback(&keyCallback);

	this->opened = true;

	return true;
}
//----------------------------------------------------------------------------//
bool CEGuiGLFWSharedBase::execute_impl(CEGuiSample* sampleApp)
{
    sampleApp->initialiseSample();

    // Input callbacks of glfw for CEGUI
    glfwSetKeyCallback(glfwKeyCallback);
    glfwSetCharCallback(glfwCharCallback);
    glfwSetMouseButtonCallback(glfwMouseButtonCallback);
    glfwSetMouseWheelCallback(glfwMouseWheelCallback);
    glfwSetMousePosCallback(glfwMousePosCallback);

    //Window callbacks
    glfwSetWindowSizeCallback(glfwWindowResizeCallback);

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

    // set starting time
    d_frameTime = glfwGetTime();

    while (!isQuitting() && !glfwGetKey(GLFW_KEY_ESC) &&
           glfwGetWindowParam(GLFW_OPENED))
    {
        if (d_windowSized)
        {
            d_windowSized = false;
            CEGUI::System::getSingleton().
                notifyDisplaySizeChanged(
                    CEGUI::Sizef(static_cast<float>(d_newWindowWidth),
                                 static_cast<float>(d_newWindowHeight)));
        }
        
        drawFrame();
    }

    glfwTerminate();

    return true;
}
Exemple #22
0
    bool Root::initGLFW()
    {
        if(!glfwInit())
        {
            LOG_ERROR("Could not init glfw!");
            return false;
        }

        GLFWvidmode mode;
        glfwGetDesktopMode(&mode);
        desktopWidth = mode.Width;
        desktopHeight = mode.Height;
        if(fullscreen)
        {
            windowWidth = desktopWidth;
            windowHeight = desktopHeight;
        }

#ifdef __APPLE__
        glfwOpenWindowHint(GLFW_OPENGL_VERSION_MAJOR, 3); // Use OpenGL Core v3.2
        glfwOpenWindowHint(GLFW_OPENGL_VERSION_MINOR, 2);
#endif

        if(!glfwOpenWindow(windowWidth, windowHeight, 0, 0, 0, 0, 32, 0, (fullscreen ? GLFW_FULLSCREEN : GLFW_WINDOW)))
        {
            return false;
        }

        glfwSetWindowTitle("Arya");
        glfwEnable(GLFW_MOUSE_CURSOR);
        glfwSetKeyCallback(keyCallback);
        glfwSetMouseButtonCallback(mouseButtonCallback);
        glfwSetMousePosCallback(mousePosCallback);
        glfwSetMouseWheelCallback(mouseWheelCallback);

        return true;
    }
//----------------------------------------------------------------------------//
void CEGuiGLFWSharedBase::run()
{
    d_sampleApp->initialise();

    // Input callbacks of glfw for CEGUI
    glfwSetKeyCallback(glfwKeyCallback);
    glfwSetCharCallback(glfwCharCallback);
    glfwSetMouseButtonCallback(glfwMouseButtonCallback);
    glfwSetMouseWheelCallback(glfwMouseWheelCallback);
    glfwSetMousePosCallback(glfwMousePosCallback);

    //Window callbacks
    glfwSetWindowCloseCallback(glfwWindowCloseCallback);
    glfwSetWindowSizeCallback(glfwWindowResizeCallback);
    d_windowSized = false; //The resize callback is being called immediately after setting it in this version of glfw
    glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

    // set starting time
    d_frameTime = glfwGetTime();

    while (!d_sampleApp->isQuitting() &&
        glfwGetWindowParam(GLFW_OPENED))
    {
        if (d_windowSized)
        {
            d_windowSized = false;
            CEGUI::System::getSingleton().
                notifyDisplaySizeChanged(
                CEGUI::Sizef(static_cast<float>(d_newWindowWidth),
                static_cast<float>(d_newWindowHeight)));
        }

        drawFrame();
    }

    d_sampleApp->deinitialise();
}
Exemple #24
0
void InputManager::subscribeMouseWheel(std::function<void(int, int)> callback) {
	glfwSetMouseWheelCallback(mouseWheelCallback);
	mouseWheelSubscriptions_.push_back(std::make_pair(callback, 0));
}
Exemple #25
0
int main(int argc, char* argv[])
{
  app_argc = argc;
  app_argv = argv;
  int     width, height, running, frames, x, y;
  double  t, t1;
  char    titlestr[ 200 ];

  // Initialise GLFW
  if (glfwInit() == GL_FALSE)
  {
    printf("could not init glfw...\n");
  }

  bool start_fullscreen = false;
  int x_res = 1280;
  int y_res = 720;
  for (int i = 1; i < argc; i++) {
    vsx_string arg1 = argv[i];
    if (arg1 == "--help")
    {
      printf(
          "Usage:\n"
          "  luna \n"
          "\n"
          "Flags: \n"
          "  -p [x,y] window position x,y \n\n"
          "  -s [x,y] window size x,y \n\n"
          "  -f fullscreen \n\n"
          );
      exit(0);
    } else
    if (arg1 == "-f") {
      start_fullscreen = true;
    } else
    if (arg1 == "-s") {
      if (i+1 < argc)
      {
        i++;
        vsx_string arg2 = argv[i];
        vsx_avector<vsx_string> parts;
        vsx_string deli = ",";
        explode(arg2, deli, parts);
        x_res = s2i(parts[0]);
        y_res = s2i(parts[1]);
      }
    }
  }

  // Open OpenGL window
  //glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 4);
  if( !glfwOpenWindow( x_res, y_res, 0,0,0,0,16,0, start_fullscreen?GLFW_FULLSCREEN:GLFW_WINDOW ) ) // GLFW_FULLSCREEN
  {
    printf("could not create glfw window...\n");
    glfwTerminate();
    return 10;
  }
  if (start_fullscreen) glfwEnable( GLFW_MOUSE_CURSOR );
  app_init(0);
  glfwEnable(GLFW_AUTO_POLL_EVENTS);
  for (int i = 1; i < argc; i++) {
    vsx_string arg1 = argv[i];
    if (arg1 == "-p") {
      if (i+1 < argc)
      {
        i++;
        vsx_string arg2 = argv[i];
        vsx_avector<vsx_string> parts;
        vsx_string deli = ",";
        explode(arg2, deli, parts);
        glfwSetWindowPos(s2i(parts[0]), s2i(parts[1]));
      }
    }
  }
  glfwSetKeyCallback(&key_event);
  glfwSetMouseButtonCallback(&mouse_button_event);
  glfwSetMousePosCallback(&mouse_pos_event);
  glfwSetCharCallback(&key_char_event);
  glfwSetMouseWheelCallback(&mouse_wheel);
    // Enable sticky keys
  glfwEnable( GLFW_STICKY_KEYS );
  glfwSwapInterval(1);
    // Main loop
  running = GL_TRUE;
  frames = 0;
    //typedef BOOL (APIENTRY * wglSwapIntervalEXT_Func)(int);
    //wglSwapIntervalEXT_Func wglSwapIntervalEXT = wglSwapIntervalEXT_Func(wglGetProcAddress("wglSwapIntervalEXT"));
    //if (wglSwapIntervalEXT) wglSwapIntervalEXT(1);

  sprintf( titlestr, "Vovoid - Luna : Reactivation");
  glfwSetWindowTitle( titlestr );
  glfwDisable( GLFW_MOUSE_CURSOR );
  
  while( running )
  {
    if (mouse_pos_type)
    {
      if (mouse_pos_type == 1) app_mouse_move(last_x,last_y);
      else app_mouse_move_passive(last_x,last_y);
      mouse_pos_type = 0;
    }
    app_pre_draw();
        // Get time and mouse position
    t = glfwGetTime();
    glfwGetMousePos( &x, &y );
    float delta = t-t1;
    t1 = t;
    if (key_pressed != -1)
    {
          //printf("%f\n", delta);
      key_time += delta;
      if (key_time > 0.3f)
      {
        key_repeat_time += delta;
        if (key_repeat_time > initial_key_delay)
        {
          key_repeat_time = 0.0f;
          if (key_character != -1)
            app_char(key_character);
          app_key_down((long)key_pressed);
          initial_key_delay *= 0.99f;
              //printf("repeating key: %d\n", key_character);
        }
      }
    }
    frames ++;
    
        // Get window size (may be different than the requested size)
    glfwGetWindowSize( &width, &height );
    height = height > 0 ? height : 1;
        // Set viewport
    glViewport( 0, 0, width, height );
        // Clear color buffer
    glClearColor( 0.0f, 0.0f, 0.0f, 0.0f );
    glClear( GL_COLOR_BUFFER_BIT );
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();                     // Reset The Modelview Matrix
    app_draw(0);
    // Swap buffers
    glfwSwapBuffers();
    // Check if the ESC key was pressed or the window was closed
    running = /*!glfwGetKey( GLFW_KEY_ESC ) &&*/
    glfwGetWindowParam( GLFW_OPENED );
  }

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

  return 0;
}
Exemple #26
0
// Main
int main() 
{
    GLFWvidmode mode;   // GLFW video mode
    TwBar *bar;         // Pointer to a tweak bar
    
    double time = 0, dt;// Current time and enlapsed time
    double turn = 0;    // Model turn counter
    double speed = 0.3; // Model rotation speed
    int wire = 0;       // Draw model in wireframe?
    float bgColor[] = { 0.1f, 0.2f, 0.4f };         // Background color 
    unsigned char cubeColor[] = { 255, 0, 0, 128 }; // Model color (32bits RGBA)

    // Intialize GLFW   
    if( !glfwInit() )
    {
        // An error occured
        fprintf(stderr, "GLFW initialization failed\n");
        return 1;
    }

    // Create a window
    glfwGetDesktopMode(&mode);
    if( !glfwOpenWindow(640, 480, mode.RedBits, mode.GreenBits, mode.BlueBits, 
                        0, 16, 0, GLFW_WINDOW /* or GLFW_FULLSCREEN */) )
    {
        // A fatal error occured    
        fprintf(stderr, "Cannot open GLFW window\n");
        glfwTerminate();
        return 1;
    }
    glfwEnable(GLFW_MOUSE_CURSOR);
    glfwEnable(GLFW_KEY_REPEAT);
    glfwSetWindowTitle("AntTweakBar simple example using GLFW");

    // Initialize AntTweakBar
    TwInit(TW_OPENGL, NULL);

    // Create a tweak bar
    bar = TwNewBar("TweakBar");
    TwDefine(" GLOBAL help='This example shows how to integrate AntTweakBar with GLFW and OpenGL.' "); // Message added to the help bar.

    // Add 'speed' to 'bar': it is a modifable (RW) variable of type TW_TYPE_DOUBLE. Its key shortcuts are [s] and [S].
    TwAddVarRW(bar, "speed", TW_TYPE_DOUBLE, &speed, 
               " label='Rot speed' min=0 max=2 step=0.01 keyIncr=s keyDecr=S help='Rotation speed (turns/second)' ");

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

    // Add 'time' to 'bar': it is a read-only (RO) variable of type TW_TYPE_DOUBLE, with 1 precision digit
    TwAddVarRO(bar, "time", TW_TYPE_DOUBLE, &time, " label='Time' precision=1 help='Time (in seconds).' ");         

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

    // Add 'cubeColor' to 'bar': it is a modifable variable of type TW_TYPE_COLOR32 (32 bits color) with alpha
    TwAddVarRW(bar, "cubeColor", TW_TYPE_COLOR32, &cubeColor, 
               " label='Cube color' alpha help='Color and transparency of the cube.' ");

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


    // Initialize time
    time = glfwGetTime();

    // Main loop (repeated while window is not closed and [ESC] is not pressed)
    while( glfwGetWindowParam(GLFW_OPENED) && !glfwGetKey(GLFW_KEY_ESC) )
    {
        // Clear frame buffer using bgColor
        glClearColor(bgColor[0], bgColor[1], bgColor[2], 1);
        glClear( GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT );

        // Rotate model
        dt = glfwGetTime() - time;
        if( dt < 0 ) dt = 0;
        time += dt;
        turn += speed*dt;
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        glRotated(360.0*turn, 0.4, 1, 0.2);
        glTranslated(-0.5, -0.5, -0.5);     
    
        // Set color and draw model
        glColor4ubv(cubeColor);
        DrawModel(wire);
        
        // Draw tweak bars
        TwDraw();

        // Present frame buffer
        glfwSwapBuffers();
    }

    // Terminate AntTweakBar and GLFW
    TwTerminate();
    glfwTerminate();

    return 0;
}
Exemple #27
0
int main(int argc, char* argv[])
{
  app_argc = argc;
  app_argv = argv;
  int     width, height, running, frames, x, y;
  double  t, t1;
  char    titlestr[ 200 ];

  // Initialise GLFW
  glfwInit();

  bool start_fullscreen = false;
  int x_res = 1280;
  int y_res = 720;
  bool manual_resolution_set = false;
  for (int i = 1; i < argc; i++)
  {
    vsx_string arg1 = argv[i];
    if (arg1 == "--help" || arg1 == "/?" || arg1 == "-help" || arg1 == "-?")
    {
      printf(
             "Usage:\n"
          "  vsxu_player [path_to_vsx_file]\n"
          "\n"
          "Flags: \n"
          "  -pl        Preload all visuals on start \n"
          "  -dr        Disable randomizer     \n"
          "  -p [x,y]   Set window position x,y \n"
          "  -s [x,y]   Set window size x,y \n\n\n"
            );
      exit(0);
    } else
    if (arg1 == "-f") {
      start_fullscreen = true;
    } else
    if (arg1 == "-pl") {
      option_preload_all = true;
    } else
    if (arg1 == "-dr") {
      disable_randomizer = true;
    } else
    if (arg1 == "-no") {
      no_overlay = true;
    } else
    if (arg1 == "-s")
    {
      if (i+1 < argc)
      {
        i++;
        vsx_string arg2 = argv[i];
        vsx_avector<vsx_string> parts;
        vsx_string deli = ",";
        explode(arg2, deli, parts);
        if (parts.size() == 2)
        {
          x_res = s2i(parts[0]);
          y_res = s2i(parts[1]);
          manual_resolution_set = true;
        } else
        {
          deli = "x";
          explode(arg2, deli, parts);
          if ( parts.size() == 2 )
          {
            x_res = s2i(parts[0]);
            y_res = s2i(parts[1]);
            manual_resolution_set = true;
          }
        }
      }
    }
  }
  if (start_fullscreen && !manual_resolution_set)
  {
    // try to get the resolution from the desktop for fullscreen
    GLFWvidmode video_mode;
    glfwGetDesktopMode(&video_mode);
    x_res = video_mode.Height;
    y_res = video_mode.Width;
  }
  
  // Open OpenGL window
  glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 4);
  if( !glfwOpenWindow( x_res, y_res, 0,0,0,0,16,0, start_fullscreen?GLFW_FULLSCREEN:GLFW_WINDOW ) ) // GLFW_FULLSCREEN
  {
    printf("Error! Could not create an OpenGL context. Please check your GPU drivers...\n");
    glfwTerminate();
    return 0;
  }
  if (start_fullscreen) glfwEnable( GLFW_MOUSE_CURSOR );
  app_init(0);

  glfwEnable(GLFW_AUTO_POLL_EVENTS);

  for (int i = 1; i < argc; i++) {
    vsx_string arg1 = argv[i];
    if (arg1 == "-p") {
      if (i+1 < argc)
      {
        i++;
        vsx_string arg2 = argv[i];
        vsx_avector<vsx_string> parts;
        vsx_string deli = ",";
        explode(arg2, deli, parts);
        glfwSetWindowPos(s2i(parts[0]), s2i(parts[1]));
      }
    }
  }

  glfwSetKeyCallback(&key_event);
  glfwSetMouseButtonCallback(&mouse_button_event);
  glfwSetMousePosCallback(&mouse_pos_event);
  glfwSetCharCallback(&key_char_event);
  glfwSetMouseWheelCallback(&mouse_wheel);
  // set window size callback function
  glfwSetWindowSizeCallback(window_size);

  // Enable sticky keys
  glfwEnable( GLFW_STICKY_KEYS );
  glfwSwapInterval(1);

  // Main loop
  running = GL_TRUE;
  frames = 0;

  #if PLATFORM_FAMILY == PLATFORM_FAMILY_UNIX
    sprintf( titlestr, "Vovoid VSXu Player %s [GNU/Linux %d-bit]", vsxu_ver, PLATFORM_BITS);
  #endif
  #if PLATFORM_FAMILY == PLATFORM_FAMILY_WINDOWS
    sprintf( titlestr, "Vovoid VSXu Player %s [Windows %d-bit]", vsxu_ver, PLATFORM_BITS);
  #endif
  glfwSetWindowTitle( titlestr );


  while( running )
  {
    if (mouse_pos_type)
    {
      if (mouse_pos_type == 1) app_mouse_move(last_x,last_y);
      else app_mouse_move_passive(last_x,last_y);
      mouse_pos_type = 0;
    }

    app_pre_draw();

    // Get time and mouse position
    t = glfwGetTime();
    glfwGetMousePos( &x, &y );
    float delta = t-t1;
    t1 = t;
    if (key_pressed != -1)
    {
          //printf("%f\n", delta);
      key_time += delta;
      if (key_time > 0.3f)
      {
        key_repeat_time += delta;
        if (key_repeat_time > initial_key_delay)
        {
          key_repeat_time = 0.0f;
          if (key_character != -1)
            app_char(key_character);
          app_key_down((long)key_pressed);
          initial_key_delay *= 0.99f;
              //printf("repeating key: %d\n", key_character);
        }
      }
    }
    frames ++;

    // Get window size (may be different than the requested size)
    glfwGetWindowSize( &width, &height );
    height = height > 0 ? height : 1;

    // Set viewport
    gl_state.viewport_set( 0, 0, width, height );

    // Clear color buffer
    glClearColor( 0.0f, 0.0f, 0.0f, 0.0f );
    glClear( GL_COLOR_BUFFER_BIT );
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    app_draw(0);

    glfwSwapBuffers();

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

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

  return 0;
}
Exemple #28
0
bool World::Initialize(unsigned int windowWidth, unsigned int windowHeight, String windowName, bool antiAliasing, bool fullScreen, bool resizable)
{
	if (_initialized)
	{
		return false;
	}
	
	_running = true;

	// Windows DLL locations
	#if defined(WIN32) && defined(NDEBUG)
		String bitsPath = "bits";
		char currentDir[MAX_PATH];
		_getcwd(currentDir, MAX_PATH);
		String currDir(currentDir);

		StringList libs;
		#if !ANGEL_DISABLE_DEVIL
			libs.push_back("DevIL.dll");
			libs.push_back("ILU.dll");
			libs.push_back("ILUT.dll");
		#endif
		#if ANGEL_DISABLE_FMOD
			libs.push_back("OpenAL32.dll");
		#else
			libs.push_back("fmodex.dll");
		#endif

		for	(int i=0; i < libs.size(); i++)
		{
			String libstring = currDir + "\\" + bitsPath + "\\" + libs[i];
			HMODULE work = LoadLibrary(libstring.c_str());
			if (work == 0)
			{
				DWORD err = GetLastError();
				_com_error error(err);
				LPCSTR errorText = error.ErrorMessage();
				sysLog.Printf("ERROR: Couldn't load DLL (%s); %s", libs[i].c_str(), errorText);
			}
		}

		// does bits directory exist?
		DWORD dwAttrib = GetFileAttributes(bitsPath.c_str());
		if (dwAttrib != INVALID_FILE_ATTRIBUTES && dwAttrib & FILE_ATTRIBUTE_DIRECTORY)
		{
			_chdir(bitsPath.c_str());
		}
	#endif
	
	// General windowing initialization
	#if !ANGEL_MOBILE
		glfwInit();
	#endif
	
	#if defined(__APPLE__)
		// Set up paths correctly in the .app bundle
		#if !ANGEL_MOBILE
			CFBundleRef mainBundle = CFBundleGetMainBundle();
			CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle);
			char path[PATH_MAX];
			if (!CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)path, PATH_MAX))
			{
				sysLog.Log("ERROR: Problem setting up working directory! Probably nothing will work!");
			}
			CFRelease(resourcesURL);
			chdir(path);
			chdir("..");
			#if DEBUG
				// set paths to the local resources rather than the copied ones
				String fileName = __FILE__;
				String dirPath = fileName.substr(0, fileName.size() - String("Angel/Infrastructure/World.cpp").size());
				CFURLRef exeURL = CFBundleCopyExecutableURL(mainBundle);
				char exePath[PATH_MAX];
				if (!CFURLGetFileSystemRepresentation(exeURL, TRUE, (UInt8 *)exePath, PATH_MAX))
				{
					sysLog.Log("ERROR: Problem setting up working directory! Probably nothing will work!");
				}
				CFRelease(exeURL);
				chdir(dirPath.c_str());
				StringList pathElements = SplitString(exePath, "/");
				String exeName = pathElements[pathElements.size()-1];
				chdir(exeName.c_str());
			#endif
		#else
			CFBundleRef mainBundle = CFBundleGetMainBundle();
			CFURLRef resourcesURL = CFBundleCopyResourcesDirectoryURL(mainBundle);
			char path[PATH_MAX];
			if (!CFURLGetFileSystemRepresentation(resourcesURL, TRUE, (UInt8 *)path, PATH_MAX))
			{
				std::cout << "Problem setting up working directory! Probably nothing will work!" << std::endl;
			}
			CFRelease(resourcesURL);
			chdir(path);
			chdir("Angel"); // the iPhone doesn't like having a "Resources" directory in the root of the .app bundle
		#endif
	#endif
	
	//Start scripting
	LuaScriptingModule::Prep();

	//Reset values based on preferences
	antiAliasing = thePrefs.OverrideInt("WindowSettings", "antiAliasing", antiAliasing);
	fullScreen = thePrefs.OverrideInt("WindowSettings", "fullScreen", fullScreen);
	resizable = thePrefs.OverrideInt("WindowSettings", "resizable", resizable);
	windowHeight = thePrefs.OverrideInt("WindowSettings", "height", windowHeight);
	windowWidth = thePrefs.OverrideInt("WindowSettings", "width", windowWidth);
	windowName = thePrefs.OverrideString("WindowSettings", "name", windowName);
	
	//Windowing system setup
	#if !ANGEL_MOBILE
		if (antiAliasing)
		{
			glfwOpenWindowHint(GLFW_FSAA_SAMPLES, 4); //4x looks pretty good
			_antiAliased = true;
		}
		else
		{
			_antiAliased = false;
		}
		int windowMode = GLFW_WINDOW;
		if (fullScreen)
		{
			windowMode = GLFW_FULLSCREEN;
		}
		if (resizable)
		{
			glfwOpenWindowHint(GLFW_WINDOW_NO_RESIZE, GL_FALSE);
		}
		else
		{
			glfwOpenWindowHint(GLFW_WINDOW_NO_RESIZE, GL_TRUE);
		}
	
		glfwOpenWindow(windowWidth, windowHeight, 8, 8, 8, 8, 8, 1, windowMode);		
		glfwSetWindowTitle(windowName.c_str());
		glfwSetWindowPos(50, 50);

		#if defined(WIN32)
			glfwSwapInterval(0); // because double-buffering and Windows don't get along apparently
		#else
			glfwSwapInterval(1);
		#endif
		glfwSetWindowSizeCallback(Camera::ResizeCallback);
		glfwSetKeyCallback(keyboardInput);
		glfwSetCharCallback(charInput);
		glfwDisable(GLFW_KEY_REPEAT);
		glfwSetMousePosCallback(MouseMotion);
		glfwSetMouseButtonCallback(MouseButton);
		glfwSetMouseWheelCallback(MouseWheel);
		glfwSetWindowCloseCallback(windowClosed);
		_prevTime = glfwGetTime();
	#else
		struct timeval tv;
		gettimeofday(&tv, NULL);
		_currTime = _startTime = tv.tv_sec + (double) tv.tv_usec / 1000000.0;
	#endif
	
	//OpenGL state setup
	#if !ANGEL_MOBILE
		glClearDepth(1.0f);
		glPolygonMode(GL_FRONT, GL_FILL);
	#else
		glEnable(GL_POLYGON_OFFSET_FILL);
		glPolygonOffset(1.0f, -1.0f);
	#endif
	glShadeModel(GL_FLAT);
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
	glEnable(GL_CULL_FACE);
	glFrontFace(GL_CCW);
	glCullFace(GL_BACK);
	glDepthFunc(GL_LEQUAL);
	glEnable(GL_DEPTH_TEST);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glClearStencil(0);
	glClearColor(1.0f, 1.0f, 1.0f, 1.0f);

	//Get textures going
	InitializeTextureLoading();
	
	//Subscribe to camera changes
	theSwitchboard.SubscribeTo(this, "CameraChange");
	
	//initialize singletons
	#if !ANGEL_MOBILE
		theInput;
		theControllerManager.Setup();
	#endif
	theSound;
	theSpatialGraph;

	#if !ANGEL_MOBILE
		RegisterConsole(new TestConsole());
	#else
		// register fonts, since we don't have the console doing it for us on the phone
		RegisterFont("Resources/Fonts/Inconsolata.otf", 24, "Console");
		RegisterFont("Resources/Fonts/Inconsolata.otf", 18, "ConsoleSmall");
	#endif
	
	LuaScriptingModule::Initialize();

	return _initialized = true;
}
Exemple #29
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);
    
}
Exemple #30
0
// Main function
int main() 
{
    // Initialize GLFW  
    if( !glfwInit() )
    {
        // A fatal error occurred
        std::cerr << "GLFW initialization failed" << std::endl;
        return 1;
    }

    // Create a window
    GLFWvidmode mode;
    glfwGetDesktopMode(&mode);
    if( !glfwOpenWindow(800, 600, mode.RedBits, mode.GreenBits, mode.BlueBits, 0, 16, 0, GLFW_WINDOW /* or GLFW_FULLSCREEN */) )
    {
        // A fatal error occurred   
        std::cerr << "Cannot open GLFW window" << std::endl;
        glfwTerminate();
        return 1;
    }
    glfwSwapInterval(0);
    glfwEnable(GLFW_MOUSE_CURSOR);
    glfwEnable(GLFW_KEY_REPEAT);
    const char title[] = "AntTweakBar example: TwAdvanced1";
    glfwSetWindowTitle(title);
    // Set GLFW event callbacks
    glfwSetWindowSizeCallback(OnWindowSize);
    glfwSetMouseButtonCallback(OnMouseButton);
    glfwSetMousePosCallback(OnMousePos);
    glfwSetMouseWheelCallback(OnMouseWheel);
    glfwSetKeyCallback(OnKey);
    glfwSetCharCallback(OnChar);

    // Initialize AntTweakBar
    TwInit(TW_OPENGL, NULL);
    // Change the font size, and add a global message to the Help bar.
    TwDefine(" GLOBAL fontSize=3 help='This example illustrates the definition of custom structure type as well as many other features.' ");

    // Initialize the 3D scene
    Scene scene;
    scene.Init(true);

    // Create a tweak bar called 'Main' and change its refresh rate, position, size and transparency
    TwBar *mainBar = TwNewBar("Main");
    TwDefine(" Main label='Main TweakBar' refresh=0.5 position='16 16' size='260 320' alpha=0");

    // Add some variables to the Main tweak bar
    TwAddVarRW(mainBar, "Wireframe", TW_TYPE_BOOLCPP, &scene.Wireframe, 
               " group='Display' key=w help='Toggle wireframe display mode.' "); // 'Wireframe' is put in the group 'Display' (which is then created)
    TwAddVarRW(mainBar, "BgTop", TW_TYPE_COLOR3F, &scene.BgColor1, 
               " group='Background' help='Change the top background color.' ");  // 'BgTop' and 'BgBottom' are put in the group 'Background' (which is then created)
    TwAddVarRW(mainBar, "BgBottom", TW_TYPE_COLOR3F, &scene.BgColor0, 
               " group='Background' help='Change the bottom background color.' ");
    TwDefine(" Main/Background group='Display' ");  // The group 'Background' of bar 'Main' is put in the group 'Display'
    TwAddVarCB(mainBar, "Subdiv", TW_TYPE_INT32, SetSubdivCB, GetSubdivCB, &scene, 
               " group='Scene' label='Meshes subdivision' min=1 max=50 keyincr=s keyDecr=S help='Subdivide the meshes more or less (switch to wireframe to see the effect).' ");
    TwAddVarRW(mainBar, "Ambient", TW_TYPE_FLOAT, &scene.Ambient, 
               " label='Ambient factor' group='Scene' min=0 max=1 step=0.001 keyIncr=a keyDecr=A help='Change scene ambient.' ");
    TwAddVarRW(mainBar, "Reflection", TW_TYPE_FLOAT, &scene.Reflection, 
               " label='Reflection factor' group='Scene' min=0 max=1 step=0.001 keyIncr=r keyDecr=R help='Change ground reflection.' ");

    // Create a new TwType called rotationType associated with the Scene::RotMode enum, and use it
    TwEnumVal rotationEV[] = { { Scene::ROT_OFF, "Stopped"}, 
                               { Scene::ROT_CW,  "Clockwise" }, 
                               { Scene::ROT_CCW, "Counter-clockwise" } };
    TwType rotationType = TwDefineEnum( "Rotation Mode", rotationEV, 3 );
    TwAddVarRW(mainBar, "Rotation", rotationType, &scene.Rotation, 
               " group='Scene' keyIncr=Backspace keyDecr=SHIFT+Backspace help='Stop or change the rotation mode.' ");

    // Add a read-only float variable; its precision is 0 which means that the fractionnal part of the float value will not be displayed
    TwAddVarRO(mainBar, "RotYAngle", TW_TYPE_DOUBLE, &scene.RotYAngle, 
               " group='Scene' label='Rot angle (degree)' precision=0 help='Animated rotation angle' ");

    // Initialize time
    double time = glfwGetTime(), dt = 0;            // Current time and elapsed time
    double frameDTime = 0, frameCount = 0, fps = 0; // Framerate

    // Main loop (repeated while window is not closed)
    while( glfwGetWindowParam(GLFW_OPENED) )
    {
        // Get elapsed time
        dt = glfwGetTime() - time;
        if (dt < 0) dt = 0;
        time += dt;

        // Rotate scene
        if( scene.Rotation==Scene::ROT_CW )
            scene.RotYAngle -= 5.0*dt;
        else if( scene.Rotation==Scene::ROT_CCW )
            scene.RotYAngle += 5.0*dt;

        // Move lights
        scene.Update(time);

        // Draw scene
        scene.Draw();

        // Draw tweak bars
        TwDraw();

        // Present frame buffer
        glfwSwapBuffers();

        // Estimate framerate
        frameCount++;
        frameDTime += dt;
        if( frameDTime>1.0 )
        {
            fps = frameCount/frameDTime;
            char newTitle[128];
            _snprintf(newTitle, sizeof(newTitle), "%s (%.1f fps)", title, fps);
            //glfwSetWindowTitle(newTitle); // uncomment to display framerate
            frameCount = frameDTime = 0;
        }
    }

    // Terminate AntTweakBar and GLFW
    TwTerminate();
    glfwTerminate();

    return 0;
}