Skip to content

Instantly share code, notes, and snippets.

@aita
Last active December 17, 2023 15:25
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aita/28fef7fa91fce3122b1005ae5d34a7ef to your computer and use it in GitHub Desktop.
Save aita/28fef7fa91fce3122b1005ae5d34a7ef to your computer and use it in GitHub Desktop.
SDL2の手引き with Rust

RustでSDL2を使う

https://github.com/Rust-SDL2/rust-sdl2 を使う

sdl2のインストール

macならbrewで入る

brew install sdl2 sdl2_gfx sdl2_image sdl2_ttf

rust-sdl2を使う

Cargo.tomlに sdl2 を追加する

sdl2 = "0.31.0"

拡張を使う場合はfeaturesを指定する

    [dependencies.sdl2]
    version = "0.31.0"
    default-features = false
    features = ["image"]

SDL2の基本

描画に関わるオブジェクト

  • SDL_Window
  • SDL_Surface
  • SDL_Renderer
  • SDL_Texture

rust-sdl2

rust-sdl2はSDL2のCのAPIがラップされていて、オブジェクト指向っぽく使える

描画は sdl2::render::Canvas から行う https://docs.rs/sdl2/0.30.0/sdl2/render/index.html

テクスチャの描画

Canvas.texture_creatorからTextureCreatorを取得する。 画像を読み込む場合はsdl2_imageのラッパーである、sdl2::imageを初期化して、TextureCreatorload_textureに渡す。

let _image_context = sdl2::image::init(INIT_PNG | INIT_JPG).unwrap();

let texture_creator = canvas.texture_creator();
let texture = texture_creator.load_texture(png).unwrap();

描画はCanvas.copyでおこなう。

canvas.copy(&texture, None, None).expect("Render failed");

Reference

extern crate sdl2;
use sdl2::event::Event;
use sdl2::image::{LoadTexture, INIT_JPG, INIT_PNG};
use sdl2::keyboard::Keycode;
use sdl2::pixels::Color;
use std::env;
use std::thread;
use std::time::Duration;
pub fn main() {
let args: Vec<_> = env::args().collect();
if args.len() < 2 {
println!("Usage: cargo run /path/to/image.(png|jpg)")
}
let png = &args[1];
// SDLの初期化
let sdl_context = sdl2::init().unwrap();
// Videoサブシステムの取得
let video_subsystem = sdl_context.video().unwrap();
// sdl2_imageの初期化
let _image_context = sdl2::image::init(INIT_PNG | INIT_JPG).unwrap();
// Widnowの作成
let window = video_subsystem
.window("hello", 800, 600)
.position_centered()
.opengl()
.build()
.unwrap();
// Canvasの作成
let mut canvas = window.into_canvas().build().unwrap();
// テクスチャの初期化
let texture_creator = canvas.texture_creator();
let texture = texture_creator.load_texture(png).unwrap();
// ゲームループ
let mut event_pump = sdl_context.event_pump().unwrap();
'running: loop {
// Canvasのクリア(塗りつぶし)
canvas.set_draw_color(Color::RGB(200, 200, 200));
canvas.clear();
// テクスチャの描画
canvas.copy(&texture, None, None).expect("Render failed");
// スクリーンの更新
canvas.present();
// イベント処理
for event in event_pump.poll_iter() {
match event {
Event::Quit { .. }
| Event::KeyDown {
keycode: Some(Keycode::Escape),
..
} => break 'running,
_ => {}
}
}
thread::sleep(Duration::new(0, 1_000_000_000u32 / 60));
// TODO: ゲーム処理
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment