1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
#![feature(conservative_impl_trait)]

extern crate gl;
extern crate glfw;
extern crate luminance;

use glfw::{Context, CursorMode, SwapInterval, Window, WindowMode};
pub use glfw::{Action, InitError, Key, MouseButton, WindowEvent};
use std::os::raw::c_void;
use std::sync::mpsc::Receiver;

/// Error that can be risen while creating a `Device` object.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DeviceError {
  InitError(InitError),
  WindowCreationFailed,
  NoPrimaryMonitor,
  NoVideoMode
}

/// Dimension of the window to create.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum WindowDim {
  Windowed(u32, u32),
  Fullscreen,
  FullscreenRestricted(u32, u32)
}

/// Device object.
///
/// Upon window and context creation, this type is used to add interaction and context handling.
pub struct Device {
  /// Window.
  window: Window,
  /// Window events queue.
  events: Receiver<(f64, WindowEvent)>
}

impl Device {
  /// Give the size of the framebuffer attached to the window.
  pub fn size(&self) -> [u32; 2] {
    let (w, h) = self.window.get_framebuffer_size();
    [w as u32, h as u32]
  }

  /// Retrieve an iterator over any pulled events.
  pub fn events<'a>(&'a mut self) -> impl Iterator<Item = (f64, WindowEvent)> + 'a {
    self.window.glfw.poll_events();
    glfw::flush_messages(&self.events)
  }

  /// Perform a draw. You should recall that function each time you want to draw a single frame to
  /// the screen.
  pub fn draw<F>(&mut self, f: F) where F: FnOnce() {
    f();
    self.window.swap_buffers();
  }

  /// Create a device and bootstrap a luminance environment that lives as long as thdevice
  /// lives.
  pub fn new(dim: WindowDim, title: &str, win_opt: WindowOpt) -> Result<Self, DeviceError> {
    let mut glfw = glfw::init(glfw::FAIL_ON_ERRORS).map_err(DeviceError::InitError)?;

    // OpenGL hints
    glfw.window_hint(glfw::WindowHint::OpenGlProfile(glfw::OpenGlProfileHint::Core));
    glfw.window_hint(glfw::WindowHint::OpenGlForwardCompat(true));
    glfw.window_hint(glfw::WindowHint::ContextVersionMajor(3));
    glfw.window_hint(glfw::WindowHint::ContextVersionMinor(3));

    // open a window in windowed or fullscreen mode
    let (mut window, events) = match dim {
      WindowDim::Windowed(w, h) => {
        glfw.create_window(w,
                           h,
                           title,
                           WindowMode::Windowed).ok_or(DeviceError::WindowCreationFailed)?
      },
      WindowDim::Fullscreen => {
        glfw.with_primary_monitor(|glfw, monitor| {
          let monitor = monitor.ok_or(DeviceError::NoPrimaryMonitor)?;
          let vmode = monitor.get_video_mode().ok_or(DeviceError::NoVideoMode)?;
          let (w, h) = (vmode.width, vmode.height);

          Ok(glfw.create_window(w,
                                h,
                                title,
                                WindowMode::FullScreen(monitor)).ok_or(DeviceError::WindowCreationFailed)?)
        })?
      },
      WindowDim::FullscreenRestricted(w, h) => {
        glfw.with_primary_monitor(|glfw, monitor| {
          let monitor = monitor.ok_or(DeviceError::NoPrimaryMonitor)?;

          Ok(glfw.create_window(w,
                                h,
                                title,
                                WindowMode::FullScreen(monitor)).ok_or(DeviceError::WindowCreationFailed)?)
        })?
      }
    };

    window.make_current();

    if win_opt.hide_cursor {
      window.set_cursor_mode(CursorMode::Disabled);
    }

    window.set_all_polling(true);
    glfw.set_swap_interval(SwapInterval::Sync(1));

    // init OpenGL
    gl::load_with(|s| window.get_proc_address(s) as *const c_void);

    Ok(Device {
      window: window,
      events: events
    })
  }
}

/// Different window options.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct WindowOpt {
  hide_cursor: bool
}

impl Default for WindowOpt {
  fn default() -> Self {
    WindowOpt {
      hide_cursor: false
    }
  }
}

impl WindowOpt {
  /// Hide or unhide the cursor. Default to `false`.
  #[inline]
  pub fn hide_cursor(self, hide: bool) -> Self {
    WindowOpt { hide_cursor: hide, ..self }
  }

  #[inline]
  pub fn is_cursor_hidden(&self) -> bool {
    self.hide_cursor
  }
}