Rust gliumでウィンドウを表示させる

序文

RustのOpenGLライブラリである glium を使ってウィンドウを表示させてみた。
本記事では特に高度な技術や知識が書かれているわけではないが、 Rust記事に少ない"初心者にやさしいRust記事"であるよう配慮する。

私の失敗例

先ずはターミナルにてcargo new --bin gliumと入力し、生成されたsrc/main.rsで以下の文章を~コピペ~入力する。
引用元(2017/12/25)

extern crate glium;

fn main() {
    use glium::DisplayBuild;

    let display = glium::glutin::WindowBuilder::new()
        .with_dimensions(1024, 768)
        .with_title(format!("Hello world"))
        .build_glium()
        .unwrap();
}

ここで忘れてはならないのが、先程生成されたCargo.tomlファイルを開き、外部クレートのバージョン依存を記述する。
~私も何を言っているのかよくわからないが~要は以下のように書けば良い。

[package]
name = "glium"
version = "0.1.0"
authors = ["*あなたの名前*"]

[dependencies]
glium = "*"

ここでglium = "*"は「gliumクレートの最新版を持ってこい」という意味(と私は解釈している)。
ちなみに2017年12月25日現在で最新版はglium = "0.19.0"である。

最新版はcrates.ioで調べられる。

ここでターミナル上でcargo runを入力すると以下のエラーを吐かれる。

error[E0432]: unresolved import `glium::DisplayBuild`
 --> src/main.rs:3:5
  |
3 | use glium::DisplayBuild;
  |     ^^^^^^^^^^^^^^^^^^^ no `DisplayBuild` in the root

warning: unused import: `glium::DisplayBuild`
 --> src/main.rs:3:5
  |
3 | use glium::DisplayBuild;
  |     ^^^^^^^^^^^^^^^^^^^
  |
  = note: #[warn(unused_imports)] on by default

error[E0599]: no method named `build_glium` found for type `glium::<unnamed>::WindowBuilder` 
in the current scope
  --> src/main.rs:10:10
   |
10 |         .build_glium()
   |          ^^^^^^^^^^^

error: aborting due to 2 previous errors

error: Could not compile `glium`.

To learn more, run the command again with --verbose.

なんか DisplayBuild がルートに存在しないだの何だので怒られる。
warningはそんな気にしなくても良い。一応出ても動く。)

解決法をどうやって見つけたか

基本的にエラーを吐かれたらターミナル上の文章をコピペして、Google先生に聞いてみると良い。
私の場合は^^^^^^^^^^^^^^^^^^^ no `DisplayBuild` in the rootの部分をコピペしてググってみた。
そしてたどり着いたこのページによると、どうもglium/src/main.rsに書いた文法は古いとのこと。
たどり着いたページによると、ここ(gliumのGithubのページ)に最新版に対応した記述例が見つかるとのこと。
tuto-01-getting-started.mdに書かれている通りに書いていけば、ようやく目標を達成できる。

書いて走らせてみよう

先ずはglium/src/main.rsに以下のコードを~コピペ~記述する。
引用元(2017/12/25)

fn main() {
    use glium::glutin;

    let mut events_loop = glutin::EventsLoop::new();
    let window = glutin::WindowBuilder::new();
    let context = glutin::ContextBuilder::new();
    let display = glium::Display::new(window, context, &events_loop).unwrap();
}

しかしこれでは表示されたウィンドウが直ぐに消えてしまう。 そこで以下の文をfn main() {}の中に書き足す。

let mut closed = false;
while !closed {
    // listing the events produced by application and waiting to be received
    events_loop.poll_events(|ev| {
        match ev {
            glutin::Event::WindowEvent { event, .. } => match event {
                glutin::WindowEvent::Closed => closed = true,
                _ => (),
            },
            _ => (),
        }
    });
}

そしてターミナル上でcargo runと入力する。

f:id:mukichem24:20171225181705p:plain

やったぜ。

結論

調べた記事が古かった故動かなかった。 困ったときはエラー文をコピペしてググろう。