Skip to main content

openblood/
main.rs

1//! OpenBlood: an open-source engine that runs the original Blood (1997) data files.
2//! You must own the original game; OpenBlood ships no game content.
3
4mod app;
5mod audio;
6mod cdaudio;
7mod config;
8mod fm;
9mod hud;
10mod menu;
11mod midi;
12mod movie;
13mod scale;
14mod tools;
15
16use config::Config;
17use ob_game::game::Game;
18use ob_game::resources::Resources;
19use std::path::{Path, PathBuf};
20
21/// Episode map order from BLOOD.INI (falls back to the maps found in BLOOD.RFF).
22fn level_list(res: &Resources) -> Vec<String> {
23    let mut out = Vec::new();
24    if let Ok(text) = std::fs::read_to_string(res.dir.join("BLOOD.INI")) {
25        let mut in_episode = false;
26        for line in text.lines() {
27            let l = line.split(';').next().unwrap_or("").trim();
28            if l.starts_with('[') {
29                in_episode = l.to_ascii_lowercase().starts_with("[episode");
30                continue;
31            }
32            if !in_episode {
33                continue;
34            }
35            if let Some((k, v)) = l.split_once('=') {
36                let k = k.trim().to_ascii_lowercase();
37                if k.starts_with("map") && k[3..].chars().all(|c| c.is_ascii_digit()) {
38                    out.push(v.trim().to_ascii_uppercase());
39                }
40            }
41        }
42    }
43    if out.is_empty() {
44        out = res
45            .blood
46            .entries
47            .iter()
48            .filter(|e| e.ext == "MAP")
49            .map(|e| e.name.clone())
50            .collect();
51        out.sort();
52    }
53    out
54}
55
56fn find_data_dir(cfg: &Config) -> Option<PathBuf> {
57    let exe_dir = std::env::current_exe()
58        .ok()
59        .and_then(|p| p.parent().map(Path::to_path_buf));
60    let mut candidates = vec![cfg.data_dir.clone(), PathBuf::from(".")];
61    if let Some(d) = &exe_dir {
62        candidates.push(d.clone());
63        candidates.push(d.join("blood"));
64    }
65    candidates
66        .into_iter()
67        .find(|d| d.join("BLOOD.RFF").exists() || d.join("blood.rff").exists())
68}
69
70fn main() {
71    let args: Vec<String> = std::env::args().collect();
72    if tools::run_tool(&args) {
73        return;
74    }
75    let exe_dir = std::env::current_exe()
76        .ok()
77        .and_then(|p| p.parent().map(Path::to_path_buf))
78        .unwrap_or_default();
79    let mut cfg = Config::load(&exe_dir.join("openblood.ini"));
80    let mut i = 1;
81    while i < args.len() {
82        match args[i].as_str() {
83            "--data" | "-data" if i + 1 < args.len() => {
84                cfg.data_dir = PathBuf::from(&args[i + 1]);
85                i += 1;
86            }
87            "--map" | "-map" if i + 1 < args.len() => {
88                cfg.start_map = Some(
89                    args[i + 1]
90                        .trim_end_matches(".map")
91                        .trim_end_matches(".MAP")
92                        .to_string(),
93                );
94                i += 1;
95            }
96            "--scale" if i + 1 < args.len() => {
97                cfg.render_scale = args[i + 1].parse().unwrap_or(1.0);
98                i += 1;
99            }
100            "--maxfps" if i + 1 < args.len() => {
101                cfg.max_fps = args[i + 1].parse().unwrap_or(0);
102                i += 1;
103            }
104            "--windowed" => cfg.fullscreen = false,
105            "--nosound" => cfg.sound = false,
106            "--help" | "-h" => {
107                println!("openblood [--data DIR] [--map E1M1] [--windowed] [--scale 0.5] [--maxfps 60] [--nosound]");
108                println!("tools: openblood rff-list FILE | rff-extract RFF NAME OUT | map-info RFF | shot DATA MAP OUT.png [W H]");
109                return;
110            }
111            _ => {}
112        }
113        i += 1;
114    }
115    let Some(dir) = find_data_dir(&cfg) else {
116        eprintln!(
117            "OpenBlood needs the files from your original Blood installation (BLOOD.RFF, SOUNDS.RFF, TILES*.ART...).\n\
118             Copy them next to openblood.exe, or set data_dir in {} or pass --data DIR.",
119            exe_dir.join("openblood.ini").display()
120        );
121        std::process::exit(1);
122    };
123    let res = match Resources::load(&dir) {
124        Ok(r) => r,
125        Err(e) => {
126            eprintln!("Failed to load game data from {}: {e}", dir.display());
127            std::process::exit(1);
128        }
129    };
130    let levels = level_list(&res);
131    let direct_map = cfg.start_map.is_some();
132    let start = cfg
133        .start_map
134        .clone()
135        .unwrap_or_else(|| levels.first().cloned().unwrap_or_else(|| "E1M1".into()));
136    let level_index = levels.iter().position(|l| l.eq_ignore_ascii_case(&start)).unwrap_or(0);
137    let game = match Game::load_level(&res, &start) {
138        Ok(g) => g,
139        Err(e) => {
140            eprintln!("Failed to load map {start}: {e}");
141            std::process::exit(1);
142        }
143    };
144    let event_loop = winit::event_loop::EventLoop::new().expect("event loop");
145    event_loop.set_control_flow(winit::event_loop::ControlFlow::Poll);
146    let show_menu = !direct_map;
147    let data_dir = res.dir.clone();
148    let mut app = app::App::new(cfg, res, game, levels, level_index);
149    app.menu_open = show_menu;
150    if show_menu {
151        app.queue_movies(movie::intro(&data_dir));
152    }
153    event_loop.run_app(&mut app).expect("run");
154}