A simple map viewer

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. #[macro_use]
  2. extern crate clap;
  3. extern crate env_logger;
  4. extern crate glutin;
  5. extern crate image;
  6. extern crate linked_hash_map;
  7. #[macro_use]
  8. extern crate log;
  9. extern crate reqwest;
  10. extern crate toml;
  11. extern crate xdg;
  12. #[macro_use]
  13. pub mod context;
  14. pub mod buffer;
  15. pub mod config;
  16. pub mod coord;
  17. pub mod map_view;
  18. pub mod map_view_gl;
  19. pub mod program;
  20. pub mod texture;
  21. pub mod tile;
  22. pub mod tile_cache;
  23. pub mod tile_atlas;
  24. pub mod tile_loader;
  25. pub mod tile_source;
  26. use clap::Arg;
  27. use coord::ScreenCoord;
  28. use glutin::{ControlFlow, ElementState, Event, GlContext, MouseButton, MouseScrollDelta, VirtualKeyCode, WindowEvent};
  29. use map_view_gl::MapViewGl;
  30. use std::time::{Duration, Instant};
  31. use tile_source::TileSource;
  32. #[derive(Copy, Clone, Debug, PartialEq, Eq)]
  33. enum Action {
  34. Nothing,
  35. Redraw,
  36. Close,
  37. }
  38. #[derive(Copy, Clone, Debug, PartialEq)]
  39. struct InputState {
  40. mouse_position: (f64, f64),
  41. mouse_pressed: bool,
  42. }
  43. fn handle_event(event: &Event, map: &mut MapViewGl, input_state: &mut InputState, sources: &mut TileSources) -> Action {
  44. match *event {
  45. Event::Awakened => Action::Redraw,
  46. Event::WindowEvent{ref event, ..} => match *event {
  47. WindowEvent::Closed => Action::Close,
  48. WindowEvent::MouseInput { state: ElementState::Pressed, button: MouseButton::Left, .. } => {
  49. input_state.mouse_pressed = true;
  50. Action::Nothing
  51. },
  52. WindowEvent::MouseInput { state: ElementState::Released, button: MouseButton::Left, .. } => {
  53. input_state.mouse_pressed = false;
  54. Action::Nothing
  55. },
  56. WindowEvent::CursorMoved { position: (x, y), .. } => {
  57. if input_state.mouse_pressed {
  58. map.move_pixel(
  59. input_state.mouse_position.0 - x,
  60. input_state.mouse_position.1 - y,
  61. );
  62. input_state.mouse_position = (x, y);
  63. Action::Redraw
  64. } else {
  65. input_state.mouse_position = (x, y);
  66. Action::Nothing
  67. }
  68. },
  69. WindowEvent::MouseWheel { delta, modifiers, .. } => {
  70. let (dx, dy) = match delta {
  71. MouseScrollDelta::LineDelta(dx, dy) => {
  72. // filter strange wheel events with huge values.
  73. // (maybe this is just a personal touchpad driver issue)
  74. if dx.abs() < 16.0 && dy.abs() < 16.0 {
  75. //TODO find a sensible line height value (servo (the glutin port) uses 38)
  76. (dx, dy * 38.0)
  77. } else {
  78. (0.0, 0.0)
  79. }
  80. },
  81. MouseScrollDelta::PixelDelta(dx, dy) => (dx, dy),
  82. };
  83. //TODO add option for default mouse wheel behavior (scroll or zoom?)
  84. //TODO add option to reverse scroll/zoom direction
  85. if modifiers.ctrl {
  86. map.move_pixel(f64::from(-dx), f64::from(-dy));
  87. } else {
  88. map.zoom_at(
  89. ScreenCoord::new(
  90. input_state.mouse_position.0,
  91. input_state.mouse_position.1,
  92. ),
  93. f64::from(dy) * (1.0 / 320.0),
  94. );
  95. }
  96. Action::Redraw
  97. },
  98. WindowEvent::KeyboardInput {
  99. input: glutin::KeyboardInput {
  100. state: glutin::ElementState::Pressed,
  101. virtual_keycode: Some(keycode),
  102. modifiers,
  103. .. },
  104. .. } => {
  105. match keycode {
  106. VirtualKeyCode::Escape => {
  107. Action::Close
  108. },
  109. VirtualKeyCode::PageUp => {
  110. sources.switch_to_prev();
  111. Action::Redraw
  112. },
  113. VirtualKeyCode::PageDown => {
  114. sources.switch_to_next();
  115. Action::Redraw
  116. },
  117. VirtualKeyCode::Left => {
  118. map.move_pixel(-50.0, 0.0);
  119. Action::Redraw
  120. },
  121. VirtualKeyCode::Right => {
  122. map.move_pixel(50.0, 0.0);
  123. Action::Redraw
  124. },
  125. VirtualKeyCode::Up => {
  126. map.move_pixel(0.0, -50.0);
  127. Action::Redraw
  128. },
  129. VirtualKeyCode::Down => {
  130. map.move_pixel(0.0, 50.0);
  131. Action::Redraw
  132. },
  133. VirtualKeyCode::Add => {
  134. if modifiers.ctrl {
  135. map.change_tile_zoom_offset(1.0);
  136. } else {
  137. map.step_zoom(1, 0.5);
  138. }
  139. Action::Redraw
  140. },
  141. VirtualKeyCode::Subtract => {
  142. if modifiers.ctrl {
  143. map.change_tile_zoom_offset(-1.0);
  144. } else {
  145. map.step_zoom(-1, 0.5);
  146. }
  147. Action::Redraw
  148. },
  149. _ => Action::Nothing,
  150. }
  151. },
  152. WindowEvent::Refresh => {
  153. Action::Redraw
  154. },
  155. WindowEvent::Resized(w, h) => {
  156. map.set_viewport_size(w, h);
  157. Action::Redraw
  158. },
  159. _ => Action::Nothing,
  160. },
  161. _ => Action::Nothing,
  162. }
  163. }
  164. fn dur_to_sec(dur: Duration) -> f64 {
  165. dur.as_secs() as f64 + f64::from(dur.subsec_nanos()) * 1e-9
  166. }
  167. fn main() {
  168. env_logger::init();
  169. let matches = clap::App::new("DeltaMap")
  170. .version(crate_version!())
  171. .author(crate_authors!())
  172. .about(crate_description!())
  173. .arg(Arg::with_name("config")
  174. .short("c")
  175. .long("config")
  176. .value_name("FILE")
  177. .help("Set a custom config file")
  178. .takes_value(true))
  179. .arg(Arg::with_name("fps")
  180. .long("fps")
  181. .value_name("FPS")
  182. .validator(|s| {
  183. s.parse::<f64>()
  184. .map(|_| ())
  185. .map_err(|e| format!("{}", e))
  186. })
  187. .help("Set target frames per second (default is 60). \
  188. This should equal the refresh rate of the display.")
  189. .takes_value(true))
  190. .arg(Arg::with_name("offline")
  191. .long("offline")
  192. .help("Do not use the network. \
  193. Try to load tiles from the offline file system cache."))
  194. .arg(Arg::with_name("sync")
  195. .long("sync")
  196. .help("Load tiles in a synchronous fashion. \
  197. Interaction is not possible while tiles are loading."))
  198. .get_matches();
  199. let config = if let Some(config_path) = matches.value_of_os("config") {
  200. config::Config::from_toml_file(config_path).unwrap()
  201. } else {
  202. config::Config::load().unwrap()
  203. };
  204. let mut sources = TileSources::new(config.tile_sources()).unwrap();
  205. let mut events_loop = glutin::EventsLoop::new();
  206. let builder = glutin::WindowBuilder::new()
  207. .with_title(format!("DeltaMap - {}", sources.current_name()));
  208. let gl_context = glutin::ContextBuilder::new();
  209. let gl_window = glutin::GlWindow::new(builder, gl_context, &events_loop).unwrap();
  210. let window = gl_window.window();
  211. let _ = unsafe { gl_window.make_current() };
  212. let cx = context::Context::from_gl_window(&gl_window);
  213. let mut map = {
  214. let proxy = events_loop.create_proxy();
  215. map_view_gl::MapViewGl::new(
  216. &cx,
  217. window.get_inner_size().unwrap(),
  218. move || { proxy.wakeup().unwrap(); },
  219. !matches.is_present("offline"),
  220. !matches.is_present("sync"),
  221. )
  222. };
  223. let mut input_state = InputState {
  224. mouse_position: (0.0, 0.0),
  225. mouse_pressed: false,
  226. };
  227. let fps: f64 = matches.value_of("fps").map(|s| s.parse().unwrap()).unwrap_or_else(|| config.fps());
  228. let duration_per_frame = Duration::from_millis((1000.0 / fps - 0.5).max(0.0).floor() as u64);
  229. info!("milliseconds per frame: {}", dur_to_sec(duration_per_frame) * 1000.0);
  230. // estimated draw duration
  231. let mut est_draw_dur = duration_per_frame;
  232. let mut last_draw = Instant::now();
  233. let mut increase_atlas_size = true;
  234. loop {
  235. let start_source_id = sources.current().id();
  236. let mut redraw = false;
  237. let mut close = false;
  238. events_loop.run_forever(|event| {
  239. match handle_event(&event, &mut map, &mut input_state, &mut sources) {
  240. Action::Close => close = true,
  241. Action::Redraw => redraw = true,
  242. Action::Nothing => {},
  243. }
  244. ControlFlow::Break
  245. });
  246. if close {
  247. break;
  248. }
  249. events_loop.poll_events(|event| {
  250. match handle_event(&event, &mut map, &mut input_state, &mut sources) {
  251. Action::Close => {
  252. close = true;
  253. return;
  254. },
  255. Action::Redraw => {
  256. redraw = true;
  257. },
  258. Action::Nothing => {},
  259. }
  260. });
  261. if close {
  262. break;
  263. }
  264. {
  265. let diff = last_draw.elapsed();
  266. if diff + est_draw_dur * 2 < duration_per_frame {
  267. if let Some(dur) = duration_per_frame.checked_sub(est_draw_dur * 2) {
  268. std::thread::sleep(dur);
  269. events_loop.poll_events(|event| {
  270. match handle_event(&event, &mut map, &mut input_state, &mut sources) {
  271. Action::Close => {
  272. close = true;
  273. return;
  274. },
  275. Action::Redraw => {
  276. redraw = true;
  277. },
  278. Action::Nothing => {},
  279. }
  280. });
  281. if close {
  282. break;
  283. }
  284. }
  285. }
  286. }
  287. if redraw {
  288. let draw_start = Instant::now();
  289. let draw_result = map.draw(sources.current());
  290. let draw_dur = draw_start.elapsed();
  291. let _ = gl_window.swap_buffers();
  292. //TODO increase atlas size earlier to avoid excessive copying to the GPU
  293. //TODO increase max tile cache size?
  294. increase_atlas_size = {
  295. match (draw_result, increase_atlas_size) {
  296. (Err(draws), true) if draws > 1 => {
  297. map.increase_atlas_size().is_ok()
  298. },
  299. (Ok(draws), true) if draws > 1 => {
  300. map.increase_atlas_size().is_ok()
  301. },
  302. _ => increase_atlas_size,
  303. }
  304. };
  305. last_draw = Instant::now();
  306. debug!("draw: {} sec (est {} sec)", dur_to_sec(draw_dur), dur_to_sec(est_draw_dur));
  307. est_draw_dur = if draw_dur > est_draw_dur {
  308. draw_dur
  309. } else {
  310. (draw_dur / 4) + ((est_draw_dur / 4) * 3)
  311. };
  312. }
  313. // set window title
  314. if sources.current().id() != start_source_id {
  315. window.set_title(&format!("DeltaMap - {}", sources.current_name()));
  316. }
  317. }
  318. }
  319. struct TileSources<'a> {
  320. current_index: usize,
  321. sources: &'a [(String, TileSource)],
  322. }
  323. impl<'a> TileSources<'a> {
  324. pub fn new(sources: &'a [(String, TileSource)]) -> Option<TileSources> {
  325. if sources.is_empty() {
  326. None
  327. } else {
  328. Some(TileSources {
  329. current_index: 0,
  330. sources: sources,
  331. })
  332. }
  333. }
  334. pub fn current(&self) -> &TileSource {
  335. &self.sources[self.current_index].1
  336. }
  337. pub fn current_name(&self) -> &str {
  338. &self.sources[self.current_index].0
  339. }
  340. pub fn switch_to_next(&mut self) {
  341. self.current_index = (self.current_index + 1) % self.sources.len();
  342. }
  343. pub fn switch_to_prev(&mut self) {
  344. self.current_index = (self.current_index + self.sources.len().saturating_sub(1)) % self.sources.len();
  345. }
  346. }