Exemple #1
0
Window* Window::Create(int Width, int Height)
{
    Window* Win = new Window;

    Win->WindowHandle = glfwCreateWindow(Width, Height, "Bakge", NULL, NULL);
    if(Win->WindowHandle == NULL) {
        delete Win;
        return NULL;
    }

    /* Store pointer to Bakge window so global callbacks can access it */
    glfwSetWindowUserPointer(Win->WindowHandle, (void*)Win);

    glfwSetWindowCloseCallback(Win->WindowHandle, WindowClosed);
    glfwSetWindowSizeCallback(Win->WindowHandle, WindowResized);
    glfwSetWindowPosCallback(Win->WindowHandle, WindowMoved);

    Win->Bind();

    return Win;
}
Exemple #2
0
void* dtemu_create_context(const char* title, int width, int height, bool resizeable, void* ud)
{
    GLFWwindow* context = malloc(sizeof(GLFWwindow));

    if (!resizeable)
        glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
    *context = (GLFWwindow) glfwCreateWindow(width, height, GLFW_WINDOWED, title, NULL);
    
    if (*context == NULL)
        dhalt(ERR_COULD_NOT_CREATE_OPENGL_CONTEXT, "glfwCreateWindow returned NULL.");

    glfwSetWindowUserPointer(*context, ud);
    glfwMakeContextCurrent(*context);
    glfwSetWindowCloseCallback(&vm_hw_glfw_close_window_callback);
    glfwSetWindowSizeCallback(&vm_hw_glfw_resize_window_callback);
    glfwSwapInterval(0);

    glfwSetTime(0.0);

    return context;
}
CanvasGLFW::CanvasGLFW(std::string windowTitle, uvec2 dimensions)
    : CanvasGL(dimensions)
    , windowTitle_(windowTitle)
    , glWindow_(nullptr)
    , mouseButton_(MouseEvent::MOUSE_BUTTON_NONE)
    , mouseState_(MouseEvent::MOUSE_STATE_NONE)
    , mouseModifiers_(InteractionEvent::MODIFIER_NONE) {
    
    glfwWindowHint(GLFW_FLOATING, alwaysOnTop_ ? GL_TRUE : GL_FALSE);
    glfwWindowHint(GLFW_VISIBLE, GL_FALSE);

#ifdef __APPLE__
    if (!sharedContext_ && OpenGLCapabilities::getPreferredProfile() == "core") {
        glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
        glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    }
#endif

    glWindow_ = glfwCreateWindow(getScreenDimensions().x, getScreenDimensions().y,
                                 windowTitle_.c_str(), nullptr, sharedContext_);

    if (!glWindow_) {
        glfwTerminate();
        throw Exception("Could not create GLFW window.", IvwContext);
    }

    if (!sharedContext_) sharedContext_ = glWindow_;

    // register callbacks
    glfwSetKeyCallback(glWindow_, keyboard);
    glfwSetMouseButtonCallback(glWindow_, mouseButton);
    glfwSetCursorPosCallback(glWindow_, mouseMotion);
    glfwSetScrollCallback(glWindow_, scroll);
    glfwSetWindowCloseCallback(glWindow_, closeWindow);
    glfwSetWindowUserPointer(glWindow_, this);
    glfwSetWindowSizeCallback(glWindow_, reshape);
    glfwSetWindowPosCallback(glWindow_, move);
}
Exemple #4
0
GampyCPP::Window::Window() :
    _glfwWindow(nullptr),
    _wireMode(false)
{
    if (_referenceCount == 0) {
#ifndef NDEBUG
        std::cout << "GLFW Init" << std::endl;
#endif
        if (!glfwInit())
        {
            // Initialization failed
            throw glfwInitException;
        }
    }

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    _glfwWindow = glfwCreateWindow(800, 600, "Window Init",
                                   nullptr, nullptr);

    if (_glfwWindow == nullptr)
    {
        glfwTerminate();
        throw createWindowException;
    }
    activateContext();

    glfwSetWindowUserPointer(_glfwWindow, this);
    glfwSetKeyCallback(_glfwWindow, _glfwKeyCallback);

    glfwGetFramebufferSize(_glfwWindow, &_width, &_height);
    glViewport(0, 0, _width, _height);

    backgroundColor(0.f, 0.f, 0.f, 1.f);

    _referenceCount++;
}
Exemple #5
0
    bool Window::init() {
        if(!glfwInit()) {
            std::cout<<"Failed to initialized glfw"<<std::endl;
            return false;
        }
        else {
            std::cout<<"openGL initialized succesfully"<<std::endl;
        }
        glfwWindowHint(GLFW_SAMPLES, 4);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
        glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
        glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed
        glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
        
        window = glfwCreateWindow(width, height, title, NULL, NULL);
        if(!window) {
            glfwTerminate();
            std::cout<<"Failed to create GLFW window"<<std::endl;
            return false;
        }
		
        glfwMakeContextCurrent(window);
        glfwSetWindowUserPointer(window, this);
        glfwSetWindowSizeCallback(window, window_resize_callback);
        glfwSetKeyCallback(window, key_callback);
        glfwSetMouseButtonCallback(window, mouse_button_callback);
        glfwSetCursorPosCallback(window, cursor_position_callback);
		glfwSetScrollCallback(window, scroll_callback);
        glfwSetCursorPos(window, mouse.x, mouse.y);
        
        glewExperimental = GL_TRUE;
        if(glewInit() != GLEW_OK) {
            std::cout<<"i cri evri tiem"<<std::endl;
            std::cout<<"gleu not ok"<<std::endl;
            return false;

        }
        std::cout<<"OpenGL "<<glGetString(GL_VERSION)<<std::endl;
        return true;
    }
Exemple #6
0
			Window::Window(int w, int h, const char *t, GLFWmonitor *m, GLFWwindow *s, const Hint &hint)
				:isEnable(false), X(x), Y(y), Width(this->w), Height(this->h), fbWidth(fbw), fbHeight(fbh), Title(title)
			{
				hint.apply();
				if(!(wnd = glfwCreateWindow(w, h, t, m, s)))
				{
					std::cerr << "Createting Window is failed.\n";
					std::cerr << "Window '" << t << "' is not enable.\n";
					return;
				}
				glfwSetWindowUserPointer(wnd, this);
				glfwSetWindowPosCallback(wnd, position);
				glfwSetWindowSizeCallback(wnd, size);
				glfwSetFramebufferSizeCallback(wnd, fbsize);
				isEnable = true;
				++glfw_window_count;

				glfwGetWindowPos      (wnd, &x, &y);
				glfwGetWindowSize     (wnd, &this->w, &this->h);
				glfwGetFramebufferSize(wnd, &fbw, &fbh);
				title = t;
			}
Exemple #7
0
// --------------------------------------------------------------------------------------------------------------------
window::builder::builder(/*allocator*/)
: _win(nullptr)
, _name("Marbles")
, _width(1280)
, _height(720)
, _fullscreen(false)
, _validation(false)
{
    _pre.reserve(8);
    _pre.push_back(async(launch::deferred, [this]() -> int
    {
        glfwDefaultWindowHints();
        if (glfwVulkanSupported())
        {
            glfwWindowHint(GLFW_CLIENT_API, GLFW_NO_API); // use vulkan
        }
        return 0;
    }));

    _post.reserve(8);
    _post.push_back(async(launch::deferred, [this]() -> int
    {
        GLFWwindow* glfwWin = this->_win->_internal->_window;
        glfwSetWindowUserPointer(glfwWin, this->_win);
        glfwSetWindowPosCallback(glfwWin, [](GLFWwindow* glfwWin, int x, int y)
        {
            window* win = reinterpret_cast<window*>(glfwGetWindowUserPointer(glfwWin));
            win->onReposition(win, x, y);
        });
        glfwSetWindowCloseCallback(glfwWin, [](GLFWwindow* glfwWin)
        {
            window* win = reinterpret_cast<window*>(glfwGetWindowUserPointer(glfwWin)); 
            win->onClose(win);
        });
        

        return 0;
    }));
}
	void WindowContext::init()
	{
		ChangeManager::get().add(this, { Message::MsgType::SET_MOUSE });

		cout << "Creating window context" << endl;
		
		LOG("Creating window context");

		// Initialize GLFW
		if (!glfwInit())
		{
			LOG_ERR("Could not initialize GLFW");
			return;
		}
		// Multisampling
		glfwWindowHint(GLFW_SAMPLES, 8);

		// Create a window
		window = glfwCreateWindow(Constants::get().getNum<int>("window_width"), Constants::get().getNum<int>("window_height"), Constants::get().getString("window_title").c_str(), nullptr, nullptr);
		if (!window)
		{
			LOG_ERR("Could not create GLFW window");
			return;
		}
		glfwMakeContextCurrent(window);
		glfwSwapInterval(1);
		glfwSetWindowUserPointer(window, this);
		quit = false;

		// Initialize callbacks
		//glfwSetMouseButtonCallback(window, mouseBtnCallback);
		glfwSetCursorPosCallback(window, cursorPosCallback);
		//glfwSetCursorEnterCallback(window, cursorEnterCallback);
		//glfwSetScrollCallback(window, scrollCallback);
		glfwSetKeyCallback(window, keyCallback);
		glfwSetWindowCloseCallback(window, closeCallback);
		glfwSetWindowSizeCallback(window, sizeCallback);
		glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
	}
Exemple #9
0
    Window::Window(int width, int height, std::string title, bool fullScreen) :
            _inputManagerUPtr(std::unique_ptr<InputManager>(new InputManager())) {
        glfwSetErrorCallback(OnError);
        glfwInit();
        glfwWindowHint (GLFW_CONTEXT_VERSION_MAJOR, 3);
        glfwWindowHint (GLFW_CONTEXT_VERSION_MINOR, 3);
        glfwWindowHint (GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
        glfwWindowHint (GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
        if (!fullScreen)
            _glfwWindowPtr = glfwCreateWindow(width, height, title.c_str(), NULL, NULL);
        else
            _glfwWindowPtr = glfwCreateWindow(width, height, title.c_str(), glfwGetPrimaryMonitor(), NULL);

        glfwMakeContextCurrent(_glfwWindowPtr);

        glewExperimental = GL_TRUE;
        glewInit();
        glEnable(GL_DEPTH_TEST);
        glDepthFunc(GL_LEQUAL);


        glfwSetWindowUserPointer(_glfwWindowPtr, this);
        glfwSetWindowCloseCallback(_glfwWindowPtr, _inputManagerUPtr->OnWindowClosed);
        glfwSetWindowFocusCallback(_glfwWindowPtr, _inputManagerUPtr->OnWindowFocused);
        glfwSetWindowSizeCallback(_glfwWindowPtr, _inputManagerUPtr->OnWindowResized);
        glfwSetWindowIconifyCallback(_glfwWindowPtr, _inputManagerUPtr->OnWindowIconify);
        glfwSetWindowPosCallback(_glfwWindowPtr, _inputManagerUPtr->OnWindowPositionChanged);
        glfwSetFramebufferSizeCallback(_glfwWindowPtr, _inputManagerUPtr->OnWindowFramebufferResized);
        glfwSetWindowRefreshCallback(_glfwWindowPtr, _inputManagerUPtr->OnWindowRefreshed);
        glfwSetKeyCallback(_glfwWindowPtr, _inputManagerUPtr->OnKeyPressed);
        glfwSetMouseButtonCallback(_glfwWindowPtr, _inputManagerUPtr->OnMouseButton);
        glfwSetScrollCallback(_glfwWindowPtr, _inputManagerUPtr->OnScroll);
        glfwSetCursorEnterCallback(_glfwWindowPtr, _inputManagerUPtr->OnCursorEnter);
        glfwSetCursorPosCallback(_glfwWindowPtr, _inputManagerUPtr->OnCursorPositionChanged);

        _inputManagerUPtr->OnWindowResized(_glfwWindowPtr, width, height);

    }
Exemple #10
0
int gameloop(GLFWwindow* window)
{
  GLFWControlContext controlContext(window);
  GlhckGLFWRenderContext renderContext(window);
  GLFWTimeContext timeContext;
  ew::Engine engine(&controlContext, &renderContext, &timeContext);

  glfwSetWindowUserPointer(window, &engine);
  glfwSetWindowSizeCallback(window, windowResizeCallback);

  GameState::init();
  GameState game(&engine);
  engine.addState(0, &game);
  engine.setState(0);

  glhckMemoryGraph();

  engine.run();

  GameState::term();

  return EXIT_SUCCESS;
}
Exemple #11
0
// uiloop
void
ui_loop(int nimgs, view_img* imgs) {
    // view params
    view_params* view = init_view_params(nimgs, imgs);

    // window
    if (!glfwInit()) exit(EXIT_FAILURE);
    GLFWwindow* window = glfwCreateWindow(view->w, view->h, "imview", 0, 0);
    glfwMakeContextCurrent(window);
    glfwSetWindowUserPointer(window, view);

    // callbacks
    glfwSetCharCallback(window, text_callback);
    glfwSetWindowSizeCallback(window, window_size_callback);
    glfwSetFramebufferSizeCallback(window, framebuffer_size_callback);
    glfwSetMouseButtonCallback(window, mouse_button_callback);
    glfwSetCursorPosCallback(window, mouse_pos_callback);
    glfwSetWindowRefreshCallback(window, window_refresh_callback);

    // load textures
    for (int i = 0; i < nimgs; i++) {
        imgs[i].tex_glid = yg_make_texture(imgs[i].pixels, imgs[i].w, imgs[i].h,
                                           imgs[i].nc, true, false);
    }

    // ui loop
    while (!glfwWindowShouldClose(window)) {
        window_refresh_callback(window);
        glfwWaitEvents();
    }

    glfwDestroyWindow(window);
    glfwTerminate();

    free(view);
}
Exemple #12
0
int main() {
  srand(time(NULL));

  // Setup window and give pointer
  GLFWwindow *window = setupWindow();

  // Initialise tree variables
  node *treeRoot;
  bounds *initial = malloc(sizeof(bounds));

  // Setup initial bounds
  initial->centerX = 0;
  initial->centerY = 0;
  initial->halfDistance = squareSize / 2;

  // Create tree root
  treeRoot = createNode(initial);
  glfwSetWindowUserPointer(window, treeRoot);

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

    drawTree(treeRoot, 0);

    glfwSwapBuffers(window);
    glfwPollEvents();
  }

  // Free tree memory
  delTree(treeRoot);

  glfwDestroyWindow(window);
  glfwTerminate();

  return 0;
}
	bool Window::init()
	{
		if (!glfwInit())
			std::cerr << "ERROR: glfw init failed" << std::endl;
		m_Window = glfwCreateWindow(m_Width, m_Height, m_Title, NULL/*glfwGetPrimaryMonitor()*/, NULL);
		if (!m_Window)
		{
			std::cerr << "ERROR: Failed to create GLFW Window" << std::endl;
			return false;
		}
		glfwMakeContextCurrent(m_Window);
		glfwSetWindowUserPointer(m_Window, this);
		glfwSetWindowSizeCallback(m_Window, window_resize);
		glfwSetKeyCallback(m_Window, key_callback);
		glfwSetMouseButtonCallback(m_Window, mouse_button_callback);
		glfwSetCursorPosCallback(m_Window, mouse_position_callback);
		if (glewInit() != GLEW_OK)
		{
			std::cerr << "ERROR: Glew failed to initialise";
			return false;
		}
		std::cout << glGetString(GL_VERSION) << std::endl;
		return true;
	}
Exemple #14
0
//
// コンストラクタ
//
Window::Window(int width, int height, const char *title, GLFWmonitor *monitor, GLFWwindow *share)
  : window(glfwCreateWindow(width, height, title, monitor, share))
  , ex(startPosition[0])                  // カメラの x 座標
  , ey(startPosition[1])                  // カメラの y 座標
  , ez(startPosition[2])                  // カメラの z 座標
  , threshold(0.5f)                       // 閾値
  , blend(true)                           // アルファブレンディング
#if STEREO != OCULUS && STEREO != NONE
  , parallax(initialParallax)
#endif
#if STEREO != OCULUS
  , scrH(zNear * screenCenter / screenDistance)
#endif
{
  if (!window) return;

  // 現在のウィンドウを処理対象にする
  glfwMakeContextCurrent(window);

  // 作成したウィンドウに対する設定
  glfwSwapInterval(1);

  // ウィンドウのサイズ変更時に呼び出す処理の登録
  glfwSetFramebufferSizeCallback(window, resize);

  // マウスボタンを操作したときの処理
  glfwSetMouseButtonCallback(window, mouse);

  // マウスホイール操作時に呼び出す処理
  glfwSetScrollCallback(window, wheel);

  // キーボードを操作した時の処理
  glfwSetKeyCallback(window, keyboard);

  // マウスカーソルを表示する
  glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);

  // このインスタンスの this ポインタを記録しておく
  glfwSetWindowUserPointer(window, this);

  // ゲームグラフィックス特論の都合にもとづく初期化
  if (!glCreateProgram) ggInit();

  // ジョイステックの有無を調べて番号を決める
  joy = glfwJoystickPresent(count) ? count : -1;

  // スティックの中立位置を求める
  if (joy >= 0)
  {
    int axesCount;
    const float *const axes(glfwGetJoystickAxes(joy, &axesCount));

    if (axesCount > 3 + axesOffset)
    {
      // 起動直後のスティックの位置を基準にする
      origin[0] = axes[0];
      origin[1] = axes[1];
      origin[2] = axes[2 + axesOffset];
      origin[3] = axes[3 + axesOffset];
    }
  }

#if STEREO == OCULUS
  // プログラムオブジェクト, VAO / VBO, Oculus Rift のデバイスマネージャーの作成は最初一度だけ行う
  if (count == 0)
  {
    // Oculus Rift のレンズの歪みを補正するシェーダプログラム
    ocuProgram = ggLoadShader("oculus.vert", "oculus.frag");
    ocuFboColorLoc = glGetUniformLocation(ocuProgram, "ocuFboColor");
    ocuAspectLoc = glGetUniformLocation(ocuProgram, "ocuAspect");
    projectionCenterOffsetLoc = glGetUniformLocation(ocuProgram, "projectionCenterOffset");
    lensDistortionLoc = glGetUniformLocation(ocuProgram, "lensDistortion");
    lensScaleLoc = glGetUniformLocation(ocuProgram, "lensScale");

    // Oculus Rift 表示に使う矩形
    glGenVertexArrays(1, &ocuVao);
    glBindVertexArray(ocuVao);
    glGenBuffers(1, &ocuVbo);
    glBindBuffer(GL_ARRAY_BUFFER, ocuVbo);
    static const GLfloat rect[] = { -1.0f, -1.0f, 1.0f, -1.0f, 1.0f, 1.0f, -1.0f, 1.0f };
    glBufferData(GL_ARRAY_BUFFER, sizeof rect, rect, GL_STATIC_DRAW);
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
    glEnableVertexAttribArray(0);

    // Oculus Rift のデバイスマネージャーの作成
    pManager = *DeviceManager::Create();
  }

  // Oculus Rift のデバイスマネージャーが作成できたら情報を取得する
  if (pManager
    && (pHmd = *pManager->EnumerateDevices<HMDDevice>().CreateDevice())
    && pHmd->GetDeviceInfo(&hmdInfo)
    )
  {
#  if defined(_DEBUG)
    // 取得した情報を表示する
    std::cout << hmdInfo.DisplayDeviceName << std::endl;
    std::cout << "\nResolution:"
      << hmdInfo.HResolution << ", "
      << hmdInfo.VResolution << std::endl;
    std::cout << "\nScreen size: "
      << hmdInfo.HScreenSize << ", "
      << hmdInfo.VScreenSize << std::endl;
    std::cout << "\nVertical Screen Center: "
      << hmdInfo.VScreenCenter << std::endl;
    std::cout << "\nEye to Screen Distance: "
      << hmdInfo.EyeToScreenDistance << std::endl;
    std::cout << "\nLens Separation Distance: "
      << hmdInfo.LensSeparationDistance << std::endl;
    std::cout << "\nInterpupillary Distance: "
      << hmdInfo.InterpupillaryDistance << std::endl;
    std::cout << "\nDistortion: "
      << hmdInfo.DistortionK[0] << ", "
      << hmdInfo.DistortionK[1] << ", "
      << hmdInfo.DistortionK[2] << ", "
      << hmdInfo.DistortionK[3] << std::endl;
    std::cout << std::endl;
#  endif

    // レンズの中心の画面の中心からのずれ
    projectionCenterOffset = 1.0f - 2.0f * hmdInfo.LensSeparationDistance / hmdInfo.HScreenSize;

    // スクリーンの幅と高さ
    scrW = scrH = zNear * hmdInfo.VScreenCenter / hmdInfo.EyeToScreenDistance;

    // 視差
    parallax = hmdInfo.InterpupillaryDistance * 0.5f;

    // レンズの歪みの補正係数
    lensDistortion[0] = hmdInfo.DistortionK[0];
    lensDistortion[1] = hmdInfo.DistortionK[1];
    lensDistortion[2] = hmdInfo.DistortionK[2];
    lensDistortion[3] = hmdInfo.DistortionK[3];

    // 片目の表示領域のアスペクト比
    ocuAspect = hmdInfo.HScreenSize * 0.5f / hmdInfo.VScreenSize;

    // Oculus Rift のセンサの取得
    pSensor = *pHmd->GetSensor();

    // センサーを登録する
    if (pSensor) sensorFusion.AttachToSensor(pSensor);
  }
  else
  {
    // Oculus Rift をつながずにデバッグする時の設定
    scrW = scrH = zNear * 0.0468f / 0.041f;
    parallax = 0.064f * 0.5f;
    projectionCenterOffset = 1.0f - 2.0f * 0.0635f / 0.14976f;
    lensDistortion[0] = 1.0f;
    lensDistortion[1] = 0.2f;
    lensDistortion[2] = 0.24f;
    lensDistortion[3] = 0.0f;
    ocuAspect = 0.14976f * 0.5f / 0.0936f;
    pSensor = nullptr;
  }

  // レンズの歪み補正に伴う拡大率の補正
  lensScale = 1.0f / (lensDistortion[0] + lensDistortion[1] + lensDistortion[2] + lensDistortion[3]);

  // Oculus Rift の左目用と右目用の FBO の準備
  glGenFramebuffers(2, ocuFbo);

  // Oculus Rift 表示用の FBO のデプスバッファとして使うレンダーバッファの作成
  glGenRenderbuffers(1, &ocuFboDepth);
  glBindRenderbuffer(GL_RENDERBUFFER, ocuFboDepth);
  glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, fboWidth, fboHeight);

  // Oculus Rift 表示用の FBO のカラーバッファとして使うカラーテクスチャの作成
  glGenTextures(2, ocuFboColor);
  for (int i = 0; i < 2; ++i)
  {
    // 左右の目のそれぞれの表示サイズより少し大きなテクスチャメモリの確保
    glBindTexture(GL_TEXTURE_2D, ocuFboColor[i]);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, fboWidth, fboHeight, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
    glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, border);

    // 左右の目のそれぞれについて FBO を作成する
    glBindFramebuffer(GL_FRAMEBUFFER, ocuFbo[i]);
    glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0,
      GL_TEXTURE_2D, ocuFboColor[i], 0);
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
      GL_RENDERBUFFER, ocuFboDepth);
  }
#endif

  // 投影変換行列・ビューポートを初期化する
  resize(window, width, height);

#if BENCHMARK
  // 時間計測用の Query Object を作成する
  glGenQueries(1, &query);
#endif

  // 参照カウントを増す
  ++count;
}
Exemple #15
0
  // ******************************************************** Figure::creation
  FigureAnt( std::string title = "Figure",
             const int width=640, const int height=400,
             const bool offscreen=false,
             const int posx=-1, const int posy = -1,
             const Range& x_range = {-1.0, 1.0, 10, 2},
             const Range& y_range = {-1.0, 1.0, 10, 2} ) :
    _title( title ), _width(width), _height(height),
    _offscreen(offscreen),
    _window(nullptr), _bar(nullptr), _curves(),
    _draw_axes( true ),
    _axis_x( "X", x_range),
    _axis_y( "Y", y_range),
    _text_list()
  {
    // Create window _________________________________________________
    glfwSetErrorCallback(error_callback);

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

    if( _offscreen) {
      glfwWindowHint(GLFW_VISIBLE, false );
    }
    _window = glfwCreateWindow(_width, _height, _title.c_str(), NULL, NULL);
    if (! _window ) {
      glfwTerminate();
      exit(EXIT_FAILURE);
    }
    glfwSetWindowPos( _window, posx, posy );
    glfwMakeContextCurrent( _window );
    // TODO can also be set to another DataStructure
    glfwSetWindowUserPointer( _window, this);
    glfwSetKeyCallback( _window, key_callback);
    glfwSetWindowSizeCallback( _window, window_size_cbk );
    /** Init Fonts */
    _font = new FTGLTextureFont( FONT_PATH );
    if (! _font) {
      std::cerr << "ERROR: Unable to open file " << FONT_PATH << std::endl;
    }
    else {
      if (!_font->FaceSize(FONT_SIZE)) {
	std::cerr << "ERROR: Unable to set font face size " << FONT_SIZE << std::endl;
      }
    }

    /** offscreen => need RenderBuffer in FrameBufferObject */
    if( _offscreen ) {
      GLenum error = glewInit();
      if (error != GLEW_OK) {
	std::cout << "error with glew init() : " << glewGetErrorString(error) << std::endl;
      } else {
        std::cout << "glew is ok\n\n";
      }
      // std::cout << "__CREATE RenderBuffer" << std::endl;
      glGenRenderbuffers( 1 /* nb buffer */, &_render_buf);
      utils::gl::check_error();
      glBindRenderbuffer( GL_RENDERBUFFER, _render_buf );
      utils::gl::check_error();
      glRenderbufferStorage(GL_RENDERBUFFER, GL_RGB32F, width, height);
      utils::gl::check_error();
      glBindRenderbuffer( GL_RENDERBUFFER, 0 );
      utils::gl::check_error();

      // std::cout << "__CREATE FrameBufferObject"  << std::endl;
      glGenFramebuffers(1 /* nb objects*/, &_fbo);
      utils::gl::check_error();
      glBindFramebuffer( GL_FRAMEBUFFER, _fbo );
      utils::gl::check_error();
      glFramebufferRenderbuffer( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, /* attach point */
				 GL_RENDERBUFFER, _render_buf );
      utils::gl::check_error();
      
      // switch back to window-system-provided framebuffer
      glBindFramebuffer(GL_FRAMEBUFFER, 0);
      utils::gl::check_error();
    }

    // std::cout << "__AntTWEAK" << std::endl;
    // Initialize AntTweakBar
    TwInit(TW_OPENGL, NULL);
    TwWindowSize( _width, _height);

    // Create AntTweakBar
    _bar = TwNewBar( "TweakBar" );
    TwDefine(" GLOBAL help='Parameters of the Application' ");

    //std::cout << "__SET Callback" << std::endl;
    // - Directly redirect GLFW mouse button events to AntTweakBar
    glfwSetMouseButtonCallback( _window,
                                (GLFWmousebuttonfun) TwEventMouseButtonGLFW3 );
    // - Directly redirect GLFW mouse position events to AntTweakBar
    glfwSetCursorPosCallback( _window,
                              (GLFWcursorposfun) TwEventCursorPosGLFW3 );
    // - Directly redirect GLFW mouse wheel events to AntTweakBar
    glfwSetScrollCallback( _window,
                           (GLFWscrollfun) TwEventScrollGLFW3 );
    // - Directly redirect GLFW key events to AntTweakBar
    // glfwSetKeyCallback( _window,
    //                     (GLFWkeyfun) TwEventKeyGLFW3 );
    // - Directly redirect GLFW key events to AntTweakBar */
    glfwSetCharModsCallback( _window,
                             (GLFWcharmodsfun) TwEventCharModsGLFW3 );
    
  }
Exemple #16
0
  // ********************************************************** Figure::render
  void render( bool update_axes_x=false, bool update_axes_y=false )
  {
    glfwMakeContextCurrent( _window );
    // TODO can also be set to another DataStructure
    glfwSetWindowUserPointer( _window, this);

    if( _offscreen ) {
      // set rendering destination to FBO
      glBindFramebuffer(GL_FRAMEBUFFER, _fbo);
      utils::gl::check_error();
    }
    
    if( update_axes_x || update_axes_y ) {
      // Build proper axis by finding min/max on each axe
      BoundingBox bbox{ std::numeric_limits<double>::max(),
	  (-std::numeric_limits<double>::max()),
	  std::numeric_limits<double>::max(),
	  -std::numeric_limits<double>::max() };
      
      for( const auto& curve: _curves ) {
	auto b = curve->get_bbox();
	if( b.x_min < bbox.x_min ) bbox.x_min = b.x_min;
	if( b.x_max > bbox.x_max ) bbox.x_max = b.x_max;
	if( b.y_min < bbox.y_min ) bbox.y_min = b.y_min;
	if( b.y_max > bbox.y_max ) bbox.y_max = b.y_max;
      }
      if( update_axes_x) 
	_axis_x = Axis( "X", {bbox.x_min,bbox.x_max, 10, 2});
      if( update_axes_y )
	_axis_y = Axis( "Y", {bbox.y_min,bbox.y_max, 10, 2});
    }
    
    // get window size
    if( _offscreen ) {
      glBindRenderbuffer( GL_RENDERBUFFER, _render_buf );
      utils::gl::check_error();
      glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_WIDTH, &_width);
      glGetRenderbufferParameteriv(GL_RENDERBUFFER, GL_RENDERBUFFER_HEIGHT, &_height);
      utils::gl::check_error();
      glBindRenderbuffer( GL_RENDERBUFFER, 0 );
      utils::gl::check_error();
    }
    else {
      glfwGetFramebufferSize( _window, &_width, &_height);
    }
    // Info for scaling View and axes
    auto x_min_win = _axis_x.get_range()._min
      - 0.08 * (_axis_x.get_range()._max - _axis_x.get_range()._min);
    auto x_max_win = _axis_x.get_range()._max
      + 0.08 * (_axis_x.get_range()._max - _axis_x.get_range()._min);
    auto ratio_x = (x_max_win-x_min_win) / (double) _width;
    auto y_min_win = _axis_y.get_range()._min
      - 0.08 * (_axis_y.get_range()._max - _axis_y.get_range()._min);
    auto y_max_win = _axis_y.get_range()._max
      + 0.08 * (_axis_y.get_range()._max - _axis_y.get_range()._min);
    auto ratio_y = (y_max_win-y_min_win) / (double) _height;

    glViewport(0, 0, _width, _height);
    glClearColor( 1.0, 1.0, 1.0, 1.0);
    glClear(GL_COLOR_BUFFER_BIT);

    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho( x_min_win, x_max_win, y_min_win, y_max_win, 1.f, -1.f);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    // Basic axes
    if( _draw_axes ) {
      _axis_x.render( ratio_x, ratio_y );
      glPushMatrix(); // AXE_Y
      glRotated( 90.0, 0.0, 0.0, 1.0 );
      _axis_y.render( ratio_y, ratio_x);
      glPopMatrix(); // AXE_Y
    }
    // All other objects
    for( const auto& curve: _curves) {
      curve->render();
    }

    // GraphicText
    for( auto& txt: _text_list) {
      glPushMatrix(); {
        glTranslated( txt.x, txt.y, 0.0);
        glScaled( ratio_x, ratio_y, 1.0 );
        _font->Render( txt.msg.c_str() );
      } glPopMatrix();
    }

    if( not _offscreen ) {
      // Draw tweak bars
      TwDraw();
      
      glfwSwapBuffers( _window );
      glfwPollEvents();
    }
  }
Exemple #17
0
void Viewer::initialize()
{
    // setup context
    glfwDefaultWindowHints();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
#ifdef __APPLE__
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
#endif
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    //glfwWindowHint(GLFW_VISIBLE, debug ? GL_TRUE : GL_FALSE);

    window = glfwCreateWindow(1280, 800, "Viewer", 0, NULL);
    glfwMakeContextCurrent(window);
    OpenGLBindings *b = new OpenGLBindings();
    flextInit(window, b);
    gl(b);

    std::string vertexshadersrc = ""
        "#version 330\n"
                                                
        "in vec2 Position;"
        "in vec2 TexCoord;"
                    
        "out VertexData{"
        "vec2 TexCoord;" 
        "} VertexOut;"  
                    
        "void main(void)"
        "{"
        "    gl_Position = vec4(Position, 0.0, 1.0);"
        "    VertexOut.TexCoord = TexCoord;"
        "}";
    std::string grayfragmentshader = ""
        "#version 330\n"
        
        "uniform sampler2DRect Data;"
        
        "vec4 tempColor;"
        "in VertexData{"
        "    vec2 TexCoord;"
        "} FragmentIn;"
        
        "layout(location = 0) out vec4 Color;"
        
        "void main(void)"
        "{"
            "ivec2 uv = ivec2(FragmentIn.TexCoord.x, FragmentIn.TexCoord.y);"
            "tempColor = texelFetch(Data, uv);"
            "Color = vec4(tempColor.x/4500, tempColor.x/4500, tempColor.x/4500, 1);"
        "}";
    std::string fragmentshader = ""
        "#version 330\n"
        
        "uniform sampler2DRect Data;"
        
        "in VertexData{"
        "    vec2 TexCoord;"
        "} FragmentIn;"
       
        "layout(location = 0) out vec4 Color;"
        
        "void main(void)"
        "{"
        "    ivec2 uv = ivec2(FragmentIn.TexCoord.x, FragmentIn.TexCoord.y);"

        "    Color = texelFetch(Data, uv);"
        "}";

    renderShader.setVertexShader(vertexshadersrc);
    renderShader.setFragmentShader(fragmentshader);
    renderShader.build();

    renderGrayShader.setVertexShader(vertexshadersrc);
    renderGrayShader.setFragmentShader(grayfragmentshader);
    renderGrayShader.build();


    glfwSetWindowUserPointer(window, this);
    glfwSetKeyCallback(window, Viewer::key_callbackstatic);

    shouldStop = false;
}
/*-------------------------------------------------------------------------------
*	関数説明
*	 ウィンドウを作成する
*	 ※ ウィンドウを複数生成することにはまだ対応していないので注意 ※
*	引数
*	 p_Width	:[I/ ] ウィンドウの幅
*	 p_Height	:[I/ ] ウィンドウの高さ
*	 p_Title	:[I/ ] ウィンドウの名前(ウィンドウ左上やタスクバーに表示される)
*	戻り値
*	 なし
*-------------------------------------------------------------------------------*/
void WindowManager::CreateNewWindow(const uint16_t p_Width, const uint16_t p_Height, const string &p_Title)
{
    //引数チェック
    if (0 == p_Width || 0 == p_Height || true == p_Title.empty())
    {
        ERROR_MESSAGE("ウィンドウを作成する 引数エラー\n" \
                      "p_Width = %d, p_Height = %d, p_Title = %s\n", p_Width, p_Height, p_Title.c_str());
        return;
    }

    //////////////////////////////////////////////////////
    //	GLFW初期化

    // GLFW初期化とエラーチェック
    printf("GLFWの初期化を開始します... ");
    if (GL_TRUE != glfwInit())
    {
        ERROR_MESSAGE("GLFWの初期化に失敗しました");
    }
    else
    {
        printf("完了\n");
    }

    //プログラム終了時の処理を登録する(GLFWの終了処理をする)
    atexit(glfwTerminate);

    //OpenGLのバージョン及びプロファイル指定
    //OpenGLES3.0を指定したいところだが、NSIGHT(デバッカツール)を使用するために、GLES3.0に対応するGL4.3を指定する
    //バージョン等を変更したいときは「glfwWindowHint」で検索すればわかると思います。
    glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_COMPAT_PROFILE);


    //////////////////////////////////////////////////////
    //	ウィンドウ生成

    //ここでウィンドウサイズも指定しています。サイズを変更したい場合はDefine値を変更してください。
    printf("ウィンドウ(%d × %d)の生成を開始します... ", p_Width, p_Height);
    GLFWwindow *const window = glfwCreateWindow(p_Width, p_Height, p_Title.c_str(), NULL, NULL);

    //ウィンドウが生成できているかチェック
    if (NULL == window)
    {
        printf("失敗\n");
        ERROR_MESSAGE("ウィンドウ生成に失敗しました。\n"\
                      "グラフィックがOpenGLESに対応していない可能性があります。\n"\
                      "グラフィックドライバを最新にしてみてください。\n"\
                      "それでもダメな場合は、残念ながらお使いの環境では使用することができません。\n"\
                      "設定では、OpenGLES3.0に対応するOpenGL4.3を設定しています。\n"\
                      "お使いの環境が対応しているかネットなどで調べてみてください。");
    }
    else
    {
        printf("完了\n");
    }

    //ウィンドウの最低サイズを設定([0 * 0]になると処理上 0除算などがありえるのでここでブロックしておく)
    glfwSetWindowSizeLimits(window, 1, 1, GLFW_DONT_CARE, GLFW_DONT_CARE);

    // 作成したウィンドウをOpenGLの処理対象にする
    glfwMakeContextCurrent(window);

    // カラーバッファの入れ替えタイミング(垂直同期のタイミングを待つ)
    glfwSwapInterval(1);

    //////////////////////////////////////////////////////
    //	ウィンドウサイズが変化した時用のコールバックを登録

    glfwSetWindowSizeCallback(window, WindowManager::WindowSizeCallback);

    // GLFWのハンドルに自分自身を登録(マルチウィンドウを実現するため)
    glfwSetWindowUserPointer(window, this);

    //////////////////////////////////////////////////////
    //	GLEW初期化

    // GLEWを初期化する
    printf("GLEWの初期化を開始します... ");
    glewExperimental = GL_TRUE;
    if (GLEW_OK != glewInit())
    {
        printf("失敗\n");
        ERROR_MESSAGE("GLEWの初期化に失敗しました。");
    }
    else
    {
        printf("完了\n");
    }

    //////////////////////////////////////////////////////
    //	生成した情報を保存

    //生成したウィンドウハンドルを保存
    m_window = window;

    //生成した時のウィンドウの幅高さを保存
    m_WindowSize.x = p_Width;
    m_WindowSize.y = p_Height;

    //////////////////////////////////////////////////////
    //	デバイス管理オブジェクトの初期化

    //デバイス管理用のオブジェクト初期化(マウスやキーボード制御のコールバックなどを登録)
    //この関数コールの前にウィンドウが生成されている必要がある
    m_Device->Initialize(m_window);
}
Exemple #19
0
int main(void)
{
    Context ctx;

    // Create a GLFW window
    glfwSetErrorCallback(errorCallback);
    glfwInit();
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    ctx.width = 800;
    ctx.height = 600;
    ctx.aspect = float(ctx.width) / float(ctx.height);
    ctx.window = glfwCreateWindow(ctx.width, ctx.height, "Model viewer", nullptr, nullptr);
    glfwMakeContextCurrent(ctx.window);
    glfwSetWindowUserPointer(ctx.window, &ctx);
    glfwSetKeyCallback(ctx.window, keyCallback);
    glfwSetMouseButtonCallback(ctx.window, mouseButtonCallback);
    glfwSetCursorPosCallback(ctx.window, cursorPosCallback);
	glfwSetScrollCallback(ctx.window, scrollCallback);
    glfwSetFramebufferSizeCallback(ctx.window, resizeCallback);

    // Load OpenGL functions
    glewExperimental = true;
    GLenum status = glewInit();
    if (status != GLEW_OK) {
        std::cerr << "Error: " << glewGetErrorString(status) << std::endl;
        std::exit(EXIT_FAILURE);
    }
    std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl;

    // Initialize AntTweakBar (if enabled)
#ifdef WITH_TWEAKBAR
    TwInit(TW_OPENGL_CORE, nullptr);
    TwWindowSize(ctx.width, ctx.height);
    TwBar *tweakbar = TwNewBar("Settings");
	TwDefine("Settings size='300 500'");
	TwDefine("Settings refresh=0.1");
	TwDefine("Settings valueswidth=fit");
	TwEnumVal lensEV[] = {
		{ORTOGRAPHIC, "Orthographic"}, 
		{PERSPECTIVE, "Perspective"}
	};
	TwType lensType = TwDefineEnum("LensType", lensEV, 2);
	TwAddVarRW(tweakbar, "Lens / Projection", lensType, &ctx.lensType, NULL);
	TwAddSeparator(tweakbar, NULL, NULL);
	TwAddVarRW(tweakbar, "Background color", TW_TYPE_COLOR3F, &ctx.background_color[0], "colormode=hls");
	TwAddSeparator(tweakbar, NULL, NULL);
	TwAddVarRW(tweakbar, "Ambient light color", TW_TYPE_COLOR3F, &ctx.ambient_light[0], "colormode=hls");
	TwAddVarRW(tweakbar, "Point light color", TW_TYPE_COLOR3F, &ctx.light_color[0], "colormode=hls");
	TwAddVarRW(tweakbar, "Point light position", TW_TYPE_DIR3F, &ctx.light_position[0], NULL);
	//TwAddVarRW(tweakbar, "Point light x", TW_TYPE_FLOAT, &ctx.light_position[0], NULL);
	//TwAddVarRW(tweakbar, "Point light y", TW_TYPE_FLOAT, &ctx.light_position[1], NULL);
	//TwAddVarRW(tweakbar, "Point light z", TW_TYPE_FLOAT, &ctx.light_position[2], NULL);
	TwAddSeparator(tweakbar, NULL, NULL);
	TwAddVarRW(tweakbar, "Material diffuse color", TW_TYPE_COLOR3F, &ctx.diffuse_color[0], "colormode=hls");
	TwAddVarRW(tweakbar, "Material specular color", TW_TYPE_COLOR3F, &ctx.specular_color[0], "colormode=hls");
	TwAddVarRW(tweakbar, "Material specular power", TW_TYPE_FLOAT, &ctx.specular_power, NULL);
	TwAddSeparator(tweakbar, NULL, NULL);
	TwEnumVal colorModeEV[] = {
		{NORMAL_AS_RGB, "Normal as RGB"}, 
		{BLINN_PHONG, "Blinn-Phong"}, 
		{REFLECTION, "Reflection"}
	};
	TwType colorModeType = TwDefineEnum("ColorMode", colorModeEV, ColorMode::SIZE);
	TwAddVarRW(tweakbar, "Color mode", colorModeType, &ctx.color_mode, NULL);
	TwAddVarRW(tweakbar, "Use gamma correction", TW_TYPE_BOOL32, &ctx.use_gamma_correction, NULL);
	TwAddVarRW(tweakbar, "Use color inversion", TW_TYPE_BOOL32, &ctx.use_color_inversion, NULL);
	TwAddSeparator(tweakbar, NULL, NULL);
	TwAddVarRW(tweakbar, "Ambient weight", TW_TYPE_FLOAT, &ctx.ambient_weight, NULL);
	TwAddVarRW(tweakbar, "Diffuse weight", TW_TYPE_FLOAT, &ctx.diffuse_weight, NULL);
	TwAddVarRW(tweakbar, "Specular weight", TW_TYPE_FLOAT, &ctx.specular_weight, NULL);
#endif // WITH_TWEAKBAR

    // Initialize rendering
    glGenVertexArrays(1, &ctx.defaultVAO);
    glBindVertexArray(ctx.defaultVAO);
    glEnable(GL_TEXTURE_CUBE_MAP_SEAMLESS);
    init(ctx);

    // Start rendering loop
    while (!glfwWindowShouldClose(ctx.window)) {
        glfwPollEvents();
        ctx.elapsed_time = glfwGetTime();
        display(ctx);
#ifdef WITH_TWEAKBAR
        TwDraw();
#endif // WITH_TWEAKBAR
        glfwSwapBuffers(ctx.window);
    }

    // Shutdown
#ifdef WITH_TWEAKBAR
    TwTerminate();
#endif // WITH_TWEAKBAR
    glfwDestroyWindow(ctx.window);
    glfwTerminate();
    std::exit(EXIT_SUCCESS);
}
Exemple #20
0
Runner::Runner(float windowWidth, float windowHeight, int frameRate,const char* title,BaseCore* c){
    Runner::windowWidth = windowWidth;
    Runner::windowHeight = windowHeight;
    //assign the core to the pointer
    this->c = c;
        //sets the event call back method in basecore
    //set the error method in basecore
    glfwSetErrorCallback(errorCallback);
    //if it fails then exit
    if (!glfwInit()){
        exit(EXIT_FAILURE);
    }
    //stop the window from being resizeable
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
    //create the window using the height and stuff
    c->getWindow() = glfwCreateWindow(windowWidth, windowHeight, title, NULL, NULL);
    GLFWwindow* window = c->getWindow();
    //set a userpointer for the window to this version of Runner
    glfwSetWindowUserPointer(window, this);
    //set the key_callback method
    glfwSetKeyCallback(window, keyCallback);
    //set mousepressed callback
    glfwSetMouseButtonCallback(window, mouseCallback);
    //set cursor call back
    glfwSetCursorPosCallback(window, cursorCallback);
    //if the window is dead, stop the program
    if (!window)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }
    //sets the context to the window
    glfwMakeContextCurrent(window);
    //sets the intervals of buffer swaps
    glfwSwapInterval(1);
    //call setup for first time run
    c->setup();
    //the game loop
    while (!glfwWindowShouldClose(window))
    {
        int iconified = glfwGetWindowAttrib(window, GLFW_ICONIFIED);
        int focused = glfwGetWindowAttrib(window, GLFW_FOCUSED);
        
        if(iconified || !focused){
            glfwWaitEvents();
        
        }
        if(fps(frameRate)){
            continue;
        }
        glClearColor(r, g, b, a);
        int width, height;
        //this allows GLtransparancy
        glEnable (GL_BLEND);
        glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
        //set view port, allows pixeltopixel things
        glfwGetFramebufferSize(window, &width, &height);
        glViewport(0, 0, width, height);
        //clear the buffer
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        glMatrixMode(GL_PROJECTION);
        glLoadIdentity();
        //set the ortho to pixels so it can be used like processing
        glOrtho(0.f, windowWidth, windowHeight, 0.f, -1.f, 1.f);
        glMatrixMode(GL_MODELVIEW);
        glLoadIdentity();
        //call update and then draw if the window isn't iconified
        if(!iconified && focused){
            //draw
            c->draw();
        }
        //swap the buffers
        glfwSwapBuffers(window);
        if(!iconified && focused){
            c->update();
        }
        glfwPollEvents();
    }
    glfwDestroyWindow(window);
    glfwTerminate();
    exit(EXIT_SUCCESS);
}
GLFWView::GLFWView(bool fullscreen_, bool benchmark_)
    : fullscreen(fullscreen_), benchmark(benchmark_) {
    glfwSetErrorCallback(glfwError);

    std::srand(std::time(0));

    if (!glfwInit()) {
        mbgl::Log::Error(mbgl::Event::OpenGL, "failed to initialize glfw");
        exit(1);
    }

    GLFWmonitor *monitor = nullptr;
    if (fullscreen) {
        monitor = glfwGetPrimaryMonitor();
        auto videoMode = glfwGetVideoMode(monitor);
        width = videoMode->width;
        height = videoMode->height;
    }

#ifdef DEBUG
    glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
#endif

#ifdef GL_ES_VERSION_2_0
    glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_ES_API);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
#endif

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

    window = glfwCreateWindow(width, height, "Mapbox GL", monitor, NULL);
    if (!window) {
        glfwTerminate();
        mbgl::Log::Error(mbgl::Event::OpenGL, "failed to initialize window");
        exit(1);
    }

    glfwSetWindowUserPointer(window, this);
    glfwMakeContextCurrent(window);
    if (benchmark) {
        // Disables vsync on platforms that support it.
        glfwSwapInterval(0);
    } else {
        glfwSwapInterval(1);
    }


    glfwSetCursorPosCallback(window, onMouseMove);
    glfwSetMouseButtonCallback(window, onMouseClick);
    glfwSetWindowSizeCallback(window, onWindowResize);
    glfwSetFramebufferSizeCallback(window, onFramebufferResize);
    glfwSetScrollCallback(window, onScroll);
    glfwSetKeyCallback(window, onKey);

    mbgl::gl::InitializeExtensions(glfwGetProcAddress);

    glfwGetWindowSize(window, &width, &height);
    glfwGetFramebufferSize(window, &fbWidth, &fbHeight);
    pixelRatio = static_cast<float>(fbWidth) / width;

    glfwMakeContextCurrent(nullptr);

    printf("\n");
    printf("================================================================================\n");
    printf("\n");
    printf("- Press `S` to cycle through bundled styles\n");
    printf("- Press `X` to reset the transform\n");
    printf("- Press `N` to reset north\n");
    printf("- Press `R` to toggle any available `night` style class\n");
    printf("\n");
    printf("- Press `1` through `6` to add increasing numbers of point annotations for testing\n");
    printf("- Press `7` through `0` to add increasing numbers of shape annotations for testing\n");
    printf("\n");
    printf("- Press `Q` to remove annotations\n");
    printf("- Press `P` to add a random custom runtime imagery annotation\n");
    printf("- Press `W` to pop the last-added annotation off\n");
    printf("\n");
    printf("- `Control` + mouse drag to rotate\n");
    printf("- `Shift` + mouse drag to tilt\n");
    printf("\n");
    printf("- Press `Tab` to cycle through the map debug options\n");
    printf("- Press `Esc` to quit\n");
    printf("\n");
    printf("================================================================================\n");
    printf("\n");
}
Exemple #22
0
Viewer::Viewer(int width, int height, const std::string title) : window(NULL), close(false), color_index(0),
    nb_faces(0), azimut(0.0), elevation(0.0), twist(0.0), distance(0.0), draw_normals(false),
    draw_mode(DRAW_MODE::TRIANGLES), smooth_mode(SMOOTH_MODE::NO_SMOOTH), lighting_mode(LIGHTING_MODE::CONSTANT)
{
	std::cout << "Constructor !!\n" << std::endl;
	if(!glfwInit())
	{
		std::cerr << "Error initialisaing GLFW" << std::endl;
		return ;
	}

	window = glfwCreateWindow(width, height,title.c_str(), NULL, NULL);

	if(!window)
	{
		std::cerr << "Error creating window" << std::endl;
		glfwTerminate();
		return ;
	}

	glfwMakeContextCurrent(window);

	GLenum state = glewInit();
	if(state != GLEW_OK)
	{
		std::cerr<<"Error initializing OpenGL" << std::endl;
		return ;
	}

	std::cout << "width = " << width << std::endl;
	std::cout << "height = " << height << std::endl;

	glViewport(0,0,width,height);
	this->setPerspective(90,1.0,0.1,50);

	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
	this->polarView(10,45,45,0);
	//gluLookAt(2,2,2,0,0,0,0,0,1);
	//glTranslatef(0.0,0.0,-10.0);

	/*float azimut = 45.0;
	float elevation = 45.0;
	float twist = 0.0;

	Matrixh mat1;
	mat1.setRotationZ(PI/2-TO_RADIANS(azimut));
	Matrixh mat2;
	mat2.setRotationX(-PI/2-TO_RADIANS(elevation));
	Matrixh mat3;	glfwTerminate();

	mat3.setRotationY(PI);
	Matrixh mat4;
	mat4.setTranslation(0.0,0.0,-10.0);

	//Matrixh res = mat1 * mat2 * mat3 * mat4;
	Matrixh res = mat4 * mat3 * mat2 * mat1;
	glMultMatrixf(res.toColMajorMatrix());
	std::cout << "mymatrix = " << res;
*/

	/*float temp[16];

	glTranslatef(0.0,0.0,-10.0);

	glRotatef(TO_DEGRES(PI),0.0,1.0,0.0);

	glGetFloatv(GL_MODELVIEW_MATRIX,temp);
	Matrixh mata;
	mata.fromColMajorMatrix(temp);
	std::cout << "gl matrix = " << mata;

	glLoadIdentity();

	glRotatef(TO_DEGRES(-PI/2)-elevation,1.0,0.0,0.0);

	glGetFloatv(GL_MODELVIEW_MATRIX,temp);
	Matrixh mat;
	mat.fromColMajorMatrix(temp);
	std::cout << "gl matrix = " << mat;
	std::cout << "cos(-3pi/4) = " << cos(TO_RADIANS(TO_DEGRES(-PI/2-PI/4))) << std::endl;

	glRotatef(TO_DEGRES(PI/2)-azimut,0.0,0.0,1.0);
*/


	/* ======test ==========
	float temp[16];
	glMatrixMode(GL_MODELVIEW_MATRIX);
	glLoadIdentity();
	glRotatef(45,1,0,0);
	glRotatef(45,0,1,0);
	glGetFloatv(GL_MODELVIEW_MATRIX,temp);
	print(temp);


	Matrixh mx;
	mx.setRotationX(TO_RADIANS(45));
	Matrixh my;
	my.setRotationY(TO_RADIANS(45));
	Matrixh mm = mx * my;
	std::cout << mm;

	 ------------------------- */



	glEnable(GL_LIGHTING);
	glEnable(GL_DEPTH_TEST);
	glDepthFunc(GL_LESS);

// ---------------test lighting --------------


	//GLfloat mat_ambient[] = { 0.0, 0.0, 0.0, 1.0 };
	//GLfloat mat_diffuse[] = { 0.9, 0.2, 0.1, 1.0 };
	//GLfloat mat_specular[] = { 0.9, 0.9, 0.9, 1.0 };
	//GLfloat mat_emission[] = { 0.0, 0.0, 0.0, 0.0};
	//
	//
    //glMaterialfv(GL_FRONT, GL_AMBIENT,mat_ambient);
	//glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
	//glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
	//glMaterialfv(GL_FRONT, GL_EMISSION, mat_emission);
    //glMaterialf(GL_FRONT, GL_SHININESS, 100.0);


	GLfloat light_ambient[] =  {0.4,0.4,0.4,1.0};
	GLfloat light_diffuse[] =  {0.4,0.4,0.4,1.0};
	GLfloat light_specular[] = {0.4,0.4,0.4,1.0};
	GLfloat light_position[] = {0,0,50,1};
	GLfloat light_direction[] = {0,0,-1,1};


	glLightfv(GL_LIGHT0,GL_AMBIENT, light_ambient);
	glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
	glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
	glLightfv(GL_LIGHT0, GL_POSITION, light_position);
	glLightf(GL_LIGHT0, GL_SPOT_CUTOFF, 90.0);
	glLightf(GL_LIGHT0, GL_SPOT_EXPONENT, 10);
	glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, light_direction);


	glEnable(GL_LIGHT0);
	glLightModeli(GL_LIGHT_MODEL_LOCAL_VIEWER,GL_TRUE);


	glfwSetInputMode(window,GLFW_STICKY_KEYS,GL_FALSE);
	glfwSetWindowUserPointer(window,this); //store this viewer

	// use C function as callback and they call instance methods
	glfwSetWindowSizeCallback(window,reshape_callback);
	glfwSetScrollCallback(window, zoom_callback);
	glfwSetMouseButtonCallback(window,mouse_button_callback);
	glfwSetKeyCallback(window, key_callback);


	/* ---- init colors ----- */
	color_tab[0] = 1.0;
	color_tab[1] = 0.0;
	color_tab[2] = 0.0;
	color_tab[3] = 1.0;
	color_tab[4] = 1.0;
	color_tab[5] = 1.0;
	color_tab[6] = 1.0;
	color_tab[7] = 1.0;
	color_tab[8] = 0.0;
	color_tab[9] = 0.0;
	color_tab[10] = 1.0;
	color_tab[11] = 1.0;
	color_tab[12] = 1.0;
	color_tab[13] = 0.0;
	color_tab[14] = 1.0;

}
//////////////// initialize ////////////////
bool fw::Window::
init(int argc, char* argv[], const char* title, int width, int height, bool fullscreen)
{
	{	/* init GLFW */
		if (!glfwInit()) {
			Log::Err("GLFW:: failed to initialize.");
			return false;
		}

		glfwWindowHint(GLFW_SAMPLES, 4);				// 4x antialiasing
		glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);	// We want OpenGL 3.3
		glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
		glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE); //We don't want the old OpenGL 

		_Window = glfwCreateWindow(width, height, title, NULL, NULL);
		if (_Window == nullptr) {
			Log::Err("GLFW:: failed to create a window.");
			glfwTerminate();
			return false;
		}
		
		/* some operations for glfwWindow */
		glfwSetWindowUserPointer(_Window, this);
		glfwMakeContextCurrent(_Window);
		glfwSetInputMode(_Window, GLFW_STICKY_KEYS, GL_TRUE);
		glfwSwapInterval(1);
		
		_Controller.input_handler.setWindow(_Window);

		/* [Tutorial 1: Opening a window]
		 * (http://www.opengl-tutorial.org/beginners-tutorials/tutorial-1-opening-a-window/) 
		 */
	}

	if (fullscreen) {
		// TODO: fullscreen
	}

	{	/* set callbacks */
	
		// TODO: 非线程安全
		static int cnt = 0;
		if (!cnt++) {
			/* callback for error messages (set only once) */
			glfwSetErrorCallback([](int err_code, const char* msg) {
				Log::Err("GLFW::ERROR - ", msg);
			});
		}

		/* callback for keyboard */
		glfwSetKeyCallback(_Window, [](GLFWwindow * glfwwindow, int key, int scancode, int action, int mods) {
			auto window = static_cast<Window *>(glfwGetWindowUserPointer(glfwwindow));
			if (!window)
				Log::Err("glfwSetKeyCallback:: invalid Window.");
			else 
				window->_Controller.input_handler.sendKeyboardEvent(key, action == GLFW_PRESS);
		});

		/* callback for mouse button */
		glfwSetMouseButtonCallback(_Window, [](GLFWwindow * glfwwindow, int button, int action, int modes) {
			auto window = static_cast<Window *>(glfwGetWindowUserPointer(glfwwindow));
			if (!window)
				Log::Err("glfwSetMouseButtonCallback:: invalid Window.");
			else 
				window->_Controller.input_handler.sendMouseEvent(button, action == GLFW_PRESS);
		});

		/* callback for resize window */
		glfwSetFramebufferSizeCallback(_Window, [](GLFWwindow * window, int width, int height) {
			auto current = glfwGetCurrentContext();
			if (current != window)
				glfwMakeContextCurrent(window);
			glViewport(0, 0, width, height);
			if (current != window)
				glfwMakeContextCurrent(current);
		});
	}

	{	/* initialize GLEW  */
		glewExperimental = true;
		auto code = glewInit();
		if (code != GLEW_OK) {
			Log::Err("GLEW:: failed to initialize - ", glewGetErrorString(code));
			return false;
		}

		Log::Msg(
			"OpenGL::", 
			"\n\tVendor  : ", glGetString(GL_VENDOR), 
			"\n\tRenderer: ", glGetString(GL_RENDERER),
			"\n\tVersion : ", glGetString(GL_VERSION)
			);
	}

	{	/* initialize OpenGL */
		glShadeModel(GL_SMOOTH);
		//glEnable(GL_CULL_FACE);
		glEnable(GL_DEPTH_TEST);
		glEnable(GL_RGBA);
		glDepthFunc(GL_LESS);
		glClearColor(0.0f, 0.0f, 0.4f, 0.0f);
	}

	/* initialization complete */
	return (_IsReady = true);
}
Exemple #24
0
int main(void) {
	if(!glfwInit()) {
		fputs("Can not init GLFW !\n", stderr);
		return 1;
	}

	game_t g = {0};
	if(!load_game(&g)) {
		fputs("Can not load game\n", stderr);

		glfwTerminate();
		return 1;
	}

	// TODO: Proper resolution settings
	g.width = 1280;
	g.height = 720;

	glfwWindowHint(GLFW_RESIZABLE, false);

	GLFWwindow* w = glfwCreateWindow(g.width, g.height, "Game", 0, 0);
	if(!w) {
		fputs("Can not create window", stderr);

		glfwTerminate();
		return 1;
	}

	glfwMakeContextCurrent(w);
	glfwSwapInterval(1);
	glfwSetKeyCallback(w, key_pressed);
	glfwSetMouseButtonCallback(w, mouse);
	glfwSetWindowUserPointer(w, &g);
	glfwSetInputMode(w, GLFW_STICKY_MOUSE_BUTTONS, 1);

	if(glewInit() != GLEW_OK) {
		fputs("Can not initialize OpenGL !\n", stderr);

		glfwTerminate();
		return 1;
	}

	if(!GLEW_VERSION_2_0) {
		fputs("OpenGL 2.0 or higher required, upgrade your graphic card or it's driver\n", stderr);

		glfwTerminate();
		return 1;
	}

	g.c.size = 10000000; // 10MB
	g.c.storage = malloc(g.c.size);

	g.init(&g.c, g.width, g.height);

	float dt = 0.f;

	while(!glfwWindowShouldClose(w)) {
		double start = glfwGetTime();

		if(!load_game(&g)) {
			break;
		}

		g.update(&g.c, (float)dt);
		g.render(&g.c);

		glfwSwapBuffers(w);
		glfwPollEvents();

		double end = glfwGetTime();
		dt = (float)(end - start);
	}

	free(g.c.storage);
	dlclose(g.app);
	glfwTerminate();

	return 0;
}
void GlfwAppWindow::SetUserPointer(UI::LayoutManager *inputSink)
{
	glfwSetWindowUserPointer(m_window, inputSink);
}
Exemple #26
0
void Viewer::initialize()
{
    glfwMakeContextCurrent(window);
    OpenGLBindings *b = new OpenGLBindings();
    flextInit(window, b);
    gl(b);

    std::string vertexshadersrc = ""
        "#version 330\n"
                                                
        "in vec2 Position;"
        "in vec2 TexCoord;"
                    
        "out VertexData{"
        "vec2 TexCoord;" 
        "} VertexOut;"  
                    
        "void main(void)"
        "{"
        "    gl_Position = vec4(Position, 0.0, 1.0);"
        "    VertexOut.TexCoord = TexCoord;"
        "}";
    std::string grayfragmentshader = ""
        "#version 330\n"
        
        "uniform sampler2DRect Data;"
        
        "vec4 tempColor;"
        "in VertexData{"
        "    vec2 TexCoord;"
        "} FragmentIn;"
        
        "layout(location = 0) out vec4 Color;"
        
        "void main(void)"
        "{"
            "ivec2 uv = ivec2(FragmentIn.TexCoord.x, FragmentIn.TexCoord.y);"
            "tempColor = texelFetch(Data, uv);"
            "Color = vec4(tempColor.x/4500, tempColor.x/4500, tempColor.x/4500, 1);"
        "}";
    std::string fragmentshader = ""
        "#version 330\n"
        
        "uniform sampler2DRect Data;"
        
        "in VertexData{"
        "    vec2 TexCoord;"
        "} FragmentIn;"
       
        "layout(location = 0) out vec4 Color;"
        
        "void main(void)"
        "{"
        "    ivec2 uv = ivec2(FragmentIn.TexCoord.x, FragmentIn.TexCoord.y);"

        "    Color = texelFetch(Data, uv);"
        "}";

    renderShader.setVertexShader(vertexshadersrc);
    renderShader.setFragmentShader(fragmentshader);
    renderShader.build();

    renderGrayShader.setVertexShader(vertexshadersrc);
    renderGrayShader.setFragmentShader(grayfragmentshader);
    renderGrayShader.build();


    glfwSetWindowUserPointer(window, this);
    glfwSetKeyCallback(window, Viewer::key_callbackstatic);

    shouldStop = false;
}
Exemple #27
0
int main(int argc, char** argv)
{
    Slot* slots;
    GLFWmonitor* monitor = NULL;
    int ch, i, width, height, count = 1;

    setlocale(LC_ALL, "");

    glfwSetErrorCallback(error_callback);

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

    printf("Library initialized\n");

    glfwSetMonitorCallback(monitor_callback);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    printf("Main loop starting\n");

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

        if (i < count)
            break;

        glfwWaitEvents();

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

    free(slots);
    glfwTerminate();
    exit(EXIT_SUCCESS);
}
Exemple #28
0
int main(int argc, char * argv[]) try
{
    rs::log_to_console(rs::log_severity::warn);
    //rs::log_to_file(rs::log_severity::debug, "librealsense.log");

    rs::context ctx;
    if(ctx.get_device_count() == 0) throw std::runtime_error("No device detected. Is it plugged in?");
    rs::device & dev = *ctx.get_device(0);

    dev.enable_stream(rs::stream::depth, rs::preset::best_quality);
    dev.enable_stream(rs::stream::color, rs::preset::best_quality);
    dev.enable_stream(rs::stream::infrared, rs::preset::best_quality);
    try {
        dev.enable_stream(rs::stream::infrared2, 0, 0, rs::format::any, 0);
    }
    catch(...) {}

    // Compute field of view for each enabled stream
    for(int i = 0; i < 4; ++i)
    {
        auto stream = rs::stream(i);
        if(!dev.is_stream_enabled(stream)) continue;
        auto intrin = dev.get_stream_intrinsics(stream);
        std::cout << "Capturing " << stream << " at " << intrin.width << " x " << intrin.height;
        std::cout << std::setprecision(1) << std::fixed << ", fov = " << intrin.hfov() << " x " << intrin.vfov() << ", distortion = " << intrin.model() << std::endl;
    }

    // Start our device
    dev.start();

    // For the libuvc backend, this sleep is required before touching any of the camera
    // options after a device has been .start()'d
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));

    // Report the status of each supported option
    /*for(int i = 0; i < RS_OPTION_COUNT; ++i)
    {
        auto option = rs::option(i);
        if(dev.supports_option(option))
        {
            std::cout << "Option " << option << ": ";
            try { std::cout << dev.get_option(option) << std::endl; }
            catch(const std::exception & e) { std::cout << e.what() << std::endl; }
        }
    }*/

    // Open a GLFW window
    glfwInit();
    std::ostringstream ss;
    ss << "CPP Capture Example (" << dev.get_name() << ")";
    GLFWwindow * win = glfwCreateWindow(1280, 960, ss.str().c_str(), 0, 0);
    glfwSetWindowUserPointer(win, &dev);
    glfwSetKeyCallback(win, [](GLFWwindow * win, int key, int scancode, int action, int mods)
    {
        auto dev = reinterpret_cast<rs::device *>(glfwGetWindowUserPointer(win));
        if(action != GLFW_RELEASE) switch(key)
            {
            case GLFW_KEY_R:
                color_rectification_enabled = !color_rectification_enabled;
                break;
            case GLFW_KEY_C:
                align_color_to_depth = !align_color_to_depth;
                break;
            case GLFW_KEY_D:
                align_depth_to_color = !align_depth_to_color;
                break;
            case GLFW_KEY_E:
                if(dev->supports_option(rs::option::r200_emitter_enabled))
                {
                    int value = !dev->get_option(rs::option::r200_emitter_enabled);
                    std::cout << "Setting emitter to " << value << std::endl;
                    dev->set_option(rs::option::r200_emitter_enabled, value);
                }
                break;
            case GLFW_KEY_A:
                if(dev->supports_option(rs::option::r200_lr_auto_exposure_enabled))
                {
                    int value = !dev->get_option(rs::option::r200_lr_auto_exposure_enabled);
                    std::cout << "Setting auto exposure to " << value << std::endl;
                    dev->set_option(rs::option::r200_lr_auto_exposure_enabled, value);
                }
                break;
            }
    });
    glfwMakeContextCurrent(win);

    while (!glfwWindowShouldClose(win))
    {
        // Wait for new images
        glfwPollEvents();
        dev.wait_for_frames();

        // Clear the framebuffer
        int w,h;
        glfwGetFramebufferSize(win, &w, &h);
        glViewport(0, 0, w, h);
        glClear(GL_COLOR_BUFFER_BIT);

        // Draw the images
        glPushMatrix();
        glfwGetWindowSize(win, &w, &h);
        glOrtho(0, w, h, 0, -1, +1);
        buffers[0].show(dev, align_color_to_depth ? rs::stream::color_aligned_to_depth : (color_rectification_enabled ? rs::stream::rectified_color : rs::stream::color), 0, 0, w/2, h/2);
        buffers[1].show(dev, align_depth_to_color ? (color_rectification_enabled ? rs::stream::depth_aligned_to_rectified_color : rs::stream::depth_aligned_to_color) : rs::stream::depth, w/2, 0, w-w/2, h/2);
        buffers[2].show(dev, rs::stream::infrared, 0, h/2, w/2, h-h/2);
        buffers[3].show(dev, rs::stream::infrared2, w/2, h/2, w-w/2, h-h/2);
        glPopMatrix();
        glfwSwapBuffers(win);
    }

    glfwDestroyWindow(win);
    glfwTerminate();
    return EXIT_SUCCESS;
}
catch(const rs::error & e)
{
    std::cerr << "RealSense error calling " << e.get_failed_function() << "(" << e.get_failed_args() << "):\n    " << e.what() << std::endl;
    return EXIT_FAILURE;
}
catch(const std::exception & e)
{
    std::cerr << e.what() << std::endl;
    return EXIT_FAILURE;
}
void GlfwWindow::open() {
  glfwSetErrorCallback(error_callback);

  int monitor_count(0);
  auto monitors(glfwGetMonitors(&monitor_count));

  if (monitor_count == 0) {
    Logger::LOG_WARNING << "Failed to open GlfwWindow: No monitor found!" << std::endl;
    glfwTerminate();
    return;
  }

  if (config.monitor() >= monitor_count) {
    Logger::LOG_WARNING << "Failed to open GlfwWindow: There is no monitor with the number " << config.monitor() << "!" << std::endl;
    glfwTerminate();
    return;
  }

  glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
  glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 4);
  glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
  glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, config.get_debug());

  if (config.get_stereo_mode() == StereoMode::QUAD_BUFFERED) {
    glfwWindowHint(GLFW_STEREO, GL_TRUE);
  }

  glfw_window_ = glfwCreateWindow(
    config.get_size().x, config.get_size().y,
    config.get_title().c_str(),
    config.get_fullscreen_mode()? glfwGetPrimaryMonitor(): nullptr, nullptr
  );
  if (!glfw_window_) {
    throw std::runtime_error("GlfwWindow::open() : unable to create window");
  }

  glfwSetWindowUserPointer(glfw_window_, this);
  glfwSetWindowSizeCallback(glfw_window_, &on_window_resize);

  glfwSetKeyCallback(         glfw_window_, &on_window_key_press);
  glfwSetCharCallback(        glfw_window_, &on_window_char);
  glfwSetMouseButtonCallback( glfw_window_, &on_window_button_press);
  glfwSetCursorPosCallback(   glfw_window_, &on_window_move_cursor);
  glfwSetScrollCallback(      glfw_window_, &on_window_scroll);
  glfwSetCursorEnterCallback( glfw_window_, &on_window_enter);

  switch(cursor_mode_) {
    case CursorMode::NORMAL:
     glfwSetInputMode(glfw_window_, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
    break;
    case CursorMode::HIDDEN:
     glfwSetInputMode(glfw_window_, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
    break;
    case CursorMode::DISABLED:
     glfwSetInputMode(glfw_window_, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
    break;
  }

  if (!glfw_window_) {
    Logger::LOG_WARNING << "Failed to open GlfwWindow: Could not create glfw3 window!" << std::endl;
    glfwTerminate();
    return;
  }


}
Exemple #30
0
        Main() 
        {
            mScale = 0.1f;
            mOffset = 1.0f;
            mDataOffset = 0;
            isClicked = false;
            screen = Vec2<unsigned int>(800, 600);
            std::setlocale(LC_ALL, "en_US.UTF-8");
            glfwInit();
            glfwWindowHint(GLFW_CLIENT_API, GLFW_OPENGL_API);
            glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
            //glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GL_TRUE);
            glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
            GLFWwindow* window = glfwCreateWindow(screen.x, screen.y, "test", nullptr, nullptr);
            if (window == nullptr)
            {
                printf("cant create window");
                return;
            }
            
            glfwSetWindowSizeCallback(window, windowSizeCallback);
            glfwSetKeyCallback(window, keyCallback);
            glfwSetMouseButtonCallback(window, clickCallback);
            glfwSetCursorPosCallback(window, mouseCallback);
            glfwMakeContextCurrent(window);
            glewExperimental = true;
            glewInit();
            
            int tmp;

            glGetIntegerv(GL_MAX_ELEMENTS_VERTICES , &tmp);

            std::cout << "GL_MAX_ELEMENTS_VERTICES: " << tmp << std::endl;
            
            int err = Pa_Initialize();
            if (err != paNoError)
                printf("error");
            
            int num = Pa_GetDeviceCount();
            const PaDeviceInfo* devInfo;
            const PaHostApiInfo* apiInfo;
            for (int i = 0; i < num; ++i) {
                devInfo = Pa_GetDeviceInfo(i);
                apiInfo = Pa_GetHostApiInfo(devInfo->hostApi);
                printf("%i, %s on %s\n", i, devInfo->name, apiInfo->name);
            }
            
            
            float sampleRate = 44100.0f;
            
            
            double t = glfwGetTime();
            Kern k(sampleRate, 12, 4 * 16.352f, sampleRate / 2);
            BlockMatrix<std::complex<double>> b(k.K, k.mN0, k.mB, 0.01);
            mAudioData = new double[b.getWidth()];
            mAudioLength = b.getWidth();
            for (unsigned int i = 0; i < mAudioLength; ++i) {
                mAudioData[i] = wave(55, sampleRate, i) + wave(110, sampleRate, i) + wave(220, sampleRate, i)
                        + wave(440, sampleRate, i) + wave(880, sampleRate, i) + wave(1760, sampleRate, i)
                        + wave(3520, sampleRate, i) + wave(7040, sampleRate, i);
            }
            
            printf("kernel time:%f\n", glfwGetTime() - t);
            float drawArray[k.mB * 2];
            std::complex<double> out[k.mB];
            CQT::transform(mAudioData, out, b, mAudioLength);
            t = glfwGetTime();
            
            printf("transform time:%f\n", glfwGetTime() - t);
            
            //glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS);
            glDebugMessageCallback(debugCallback, nullptr);
            //glEnable(GL_DEBUG_OUTPUT);
                        
            printf("%s\n", glGetString(GL_VERSION));
            Shader fs("res/shader/fragment.c", true, GL_FRAGMENT_SHADER);
            Shader vs("res/shader/vertex.c", true, GL_VERTEX_SHADER);
            Program* p = new Program();
            p->attach(fs);
            p->attach(vs);
            p->build();
            p->use();
            
            Program p2;
            Shader fs2("res/shader/fragment2.c", true, GL_FRAGMENT_SHADER);
            Shader vs2("res/shader/vertex2.c", true, GL_VERTEX_SHADER);
            p2.attach(fs2);
            p2.attach(vs2);
            p2.build();
            p2.use();
            
            int uniformData = p2.getUniformLocation("data");
            
            unsigned int waterfallSize = 512;
            
            tm = new TextureManager();
            
            unsigned int waterfallTexture;
            unsigned int waterfallId = tm->getFreeTexture();
            
            glGenTextures(1, &waterfallTexture);
            glActiveTexture(GL_TEXTURE0 + waterfallId);
            
            glBindTexture( GL_TEXTURE0, waterfallTexture );

            glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
            glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
            
            unsigned char* textureTmp = new unsigned char[waterfallSize * b.getWidth()];
            
            glTexImage2D( GL_TEXTURE_2D_ARRAY, 0, GL_R8, b.getWidth(), waterfallSize, 0, GL_RED, GL_UNSIGNED_BYTE, textureTmp);
            
            delete textureTmp;
            
            float max = 0;
            for (unsigned int i = 0; i < k.mB; ++i) {
                    drawArray[2 * i + 0] = (float)i / k.mB * 2.0f - 1.0f;
                    float tmp = std::abs(out[i]);
                    drawArray[2 * i + 1] = tmp;
                    max = std::max(tmp, max);

                }
            
            font = new Font(512, "res/font/DroidSans.woff", 32, tm);
            print = new Print(font);
            //print.set(&font, "res/shader/fontVertex.c", "res/shader/fontFragment.c");
            print->setScreenSize(screen);
            glm::vec2* vert = new glm::vec2[1024];
            
            glm::vec2* debug = new glm::vec2[b.getWidth()];
            for (unsigned int i = 0; i < b.getWidth(); ++i) {
                debug[i].x = (float)i / b.getWidth() * 2.0f - 1.0f;
            }
            uint32_t vao;
            glGenVertexArrays(1, &vao);
            glBindVertexArray(vao);
            uint32_t vbo[2];
            glGenBuffers(1, vbo);
            glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
            glEnableVertexAttribArray(0);
            glBufferData(GL_ARRAY_BUFFER, k.mB * sizeof(glm::vec2), drawArray, GL_DYNAMIC_DRAW);
            glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, 0);
            glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
            glEnable(GL_BLEND);
            glfwSetWindowUserPointer(window, this);
            glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
            
            double time, timeo;
            glfwSwapInterval(1);
            PaStream* stream;
            PaStreamParameters params;
            params.device = 21;
            params.channelCount = 1;
            params.sampleFormat = paFloat32;
            params.hostApiSpecificStreamInfo = nullptr;
            params.suggestedLatency = 0.5;
            
            
            err =  Pa_OpenStream(&stream, &params, nullptr, sampleRate, paFramesPerBufferUnspecified, 0, paCallback, this);
            if (err != paNoError)
                printf("error %i", err);
            Pa_StartStream(stream);
            while(!glfwWindowShouldClose(window))
            {
                timeo = time;
                time = glfwGetTime();
                CQT::transform(mAudioData, out, b, mAudioLength);
            
            
                max = 0.0f;
                for (unsigned int i = 0; i < k.mB; ++i) {
                    drawArray[2 * i + 0] = (float)i / k.mB * 2.0f - 1.0f;
                    float tmp = std::abs(out[i]);
                    drawArray[2 * i + 1] = tmp;
                    max = std::max(tmp, max);

                }
                for (unsigned int i = 0; i < k.mB; ++i) {
                    drawArray[2 * i + 1] = std::log(drawArray[2 * i +1]) * mScale + mOffset;
                }
                //printf("%f\n", drawArray[1]);
                glBindVertexArray(vao);
                glBindBuffer(GL_ARRAY_BUFFER, vbo[0]);
                glBufferData(GL_ARRAY_BUFFER, k.mB * sizeof(glm::vec2), drawArray, GL_DYNAMIC_DRAW);
                p->use();
                glDrawArrays(GL_LINE_STRIP, 0, k.mB);
                for (unsigned int i = 0; i < b.getWidth(); ++i) {
                    debug[i].y = mAudioData[i] / 15.0;
                }
                glBufferData(GL_ARRAY_BUFFER, b.getWidth() * sizeof(glm::vec2), debug, GL_DYNAMIC_DRAW);
                glDrawArrays(GL_LINE_STRIP, 0, b.getWidth());
               print->printfAt(-300.0f, 100.0f, 16.0f, 16.0f, u8"Fps:%03.3f", 1/(time-timeo));
                
                glfwSwapBuffers(window);
                glClear(GL_COLOR_BUFFER_BIT);
                glfwPollEvents();
                
            }
            Pa_StopStream(stream);
            Pa_CloseStream(stream);
            Pa_Terminate();

            std::cout << "Hello World. I'm Peach." << std::endl;

        }