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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
use std::cell::RefCell;
use std::rc::Rc;
use crate::console::Console;
use crate::font::FontLoader;
use crate::input::{DoryenInput, InputApi};
use crate::program::{set_texture_params, Program};
const DORYEN_VS: &str = include_str!("doryen_vs.glsl");
const DORYEN_FS: &str = include_str!("doryen_fs.glsl");
const MAX_FRAMESKIP: i32 = 5;
const TICKS_PER_SECOND: f64 = 60.0;
const SKIP_TICKS: f64 = 1.0 / TICKS_PER_SECOND;
pub const DEFAULT_CONSOLE_WIDTH: u32 = 80;
pub const DEFAULT_CONSOLE_HEIGHT: u32 = 45;
pub trait DoryenApi {
fn con(&mut self) -> &mut Console;
fn input(&mut self) -> &mut dyn InputApi;
fn fps(&self) -> u32;
fn average_fps(&self) -> u32;
fn set_font_path(&mut self, font_path: &str);
fn get_screen_size(&self) -> (u32, u32);
}
struct DoryenApiImpl {
con: Console,
input: DoryenInput,
fps: u32,
average_fps: u32,
font_path: Option<String>,
screen_size: (u32, u32),
}
impl DoryenApi for DoryenApiImpl {
fn con(&mut self) -> &mut Console {
&mut self.con
}
fn input(&mut self) -> &mut dyn InputApi {
&mut self.input
}
fn fps(&self) -> u32 {
self.fps
}
fn average_fps(&self) -> u32 {
self.average_fps
}
fn set_font_path(&mut self, font_path: &str) {
self.font_path = Some(font_path.to_owned());
}
fn get_screen_size(&self) -> (u32, u32) {
self.screen_size
}
}
impl DoryenApiImpl {
pub fn clear_font_path(&mut self) {
self.font_path = None;
}
}
pub enum UpdateEvent {
Capture(String),
Exit,
}
pub trait Engine {
fn init(&mut self, _api: &mut dyn DoryenApi) {}
fn update(&mut self, _api: &mut dyn DoryenApi) -> Option<UpdateEvent> {
None
}
fn render(&mut self, api: &mut dyn DoryenApi);
fn resize(&mut self, _api: &mut dyn DoryenApi) {}
}
pub struct AppOptions {
pub console_width: u32,
pub console_height: u32,
pub screen_width: u32,
pub screen_height: u32,
pub window_title: String,
pub font_path: String,
pub vsync: bool,
pub fullscreen: bool,
pub show_cursor: bool,
pub resizable: bool,
pub intercept_close_request: bool,
pub max_fps: usize,
}
impl Default for AppOptions {
fn default() -> Self {
Self {
console_width: DEFAULT_CONSOLE_WIDTH,
console_height: DEFAULT_CONSOLE_HEIGHT,
screen_width: DEFAULT_CONSOLE_WIDTH * 8,
screen_height: DEFAULT_CONSOLE_HEIGHT * 8,
window_title: "".to_owned(),
font_path: "terminal_8x8.png".to_owned(),
vsync: true,
fullscreen: false,
show_cursor: true,
resizable: true,
intercept_close_request: false,
max_fps: 0,
}
}
}
pub struct App {
app: Option<uni_app::App>,
gl: uni_gl::WebGLRenderingContext,
font: uni_gl::WebGLTexture,
font_loader: FontLoader,
program: Program,
options: AppOptions,
fps: Fps,
api: DoryenApiImpl,
engine: Option<Box<dyn Engine>>,
font_width: u32,
font_height: u32,
char_width: u32,
char_height: u32,
screen_resolution: (u32, u32),
}
impl App {
pub fn new(options: AppOptions) -> Self {
let con = Console::new(options.console_width, options.console_height);
let app = uni_app::App::new(uni_app::AppConfig {
size: (options.screen_width, options.screen_height),
title: options.window_title.to_owned(),
vsync: options.vsync,
show_cursor: options.show_cursor,
headless: false,
resizable: options.resizable,
fullscreen: options.fullscreen,
intercept_close_request: options.intercept_close_request,
});
let real_screen_width = (options.screen_width as f32 * app.hidpi_factor()) as u32;
let real_screen_height = (options.screen_height as f32 * app.hidpi_factor()) as u32;
let gl = uni_gl::WebGLRenderingContext::new(app.canvas());
let screen_resolution = app.get_screen_resolution();
let (x_offset, y_offset) = if options.fullscreen && cfg!(not(target_arch = "wasm32")) {
let x_offset = (screen_resolution.0 - real_screen_width) as i32 / 2;
let y_offset = (screen_resolution.1 - real_screen_height) as i32 / 2;
(x_offset, y_offset)
} else {
(0, 0)
};
uni_app::App::print(format!(
"Screen size {} x {} offset {} x {} GL viewport : {} x {} hidpi factor : {}\n",
options.screen_width,
options.screen_height,
x_offset,
y_offset,
real_screen_width,
real_screen_height,
app.hidpi_factor()
));
gl.viewport(x_offset, y_offset, real_screen_width, real_screen_height);
gl.enable(uni_gl::Flag::Blend as i32);
gl.clear_color(0.0, 0.0, 0.0, 1.0);
gl.clear(uni_gl::BufferBit::Color);
gl.blend_equation(uni_gl::BlendEquation::FuncAdd);
gl.blend_func(
uni_gl::BlendMode::SrcAlpha,
uni_gl::BlendMode::OneMinusSrcAlpha,
);
let program = Program::new(&gl, DORYEN_VS, DORYEN_FS);
let input = if cfg!(target_arch = "wasm32") {
DoryenInput::new(
(options.screen_width, options.screen_height),
(options.console_width, options.console_height),
(x_offset as u32, y_offset as u32),
)
} else {
DoryenInput::new(
(real_screen_width, real_screen_height),
(options.console_width, options.console_height),
(x_offset as u32, y_offset as u32),
)
};
let font = create_texture(&gl);
Self {
app: Some(app),
gl,
font_loader: FontLoader::new(),
font,
program,
api: DoryenApiImpl {
input,
con,
fps: 0,
average_fps: 0,
font_path: None,
screen_size: (options.screen_width, options.screen_height),
},
options,
fps: Fps::new(),
engine: None,
font_width: 0,
font_height: 0,
char_width: 0,
char_height: 0,
screen_resolution,
}
}
pub fn set_engine(&mut self, engine: Box<dyn Engine>) {
self.engine = Some(engine);
}
fn load_font_bytes(&mut self) {
let img = self.font_loader.img.take().unwrap();
if self.font_loader.char_width != 0 {
self.char_width = self.font_loader.char_width;
self.char_height = self.font_loader.char_height;
} else {
self.char_width = img.width() as u32 / 16;
self.char_height = img.height() as u32 / 16;
}
self.font_width = img.width() as u32;
self.font_height = img.height() as u32;
uni_app::App::print(format!(
"font size: {:?} char size: {:?}\n",
(self.font_width, self.font_height),
(self.char_width, self.char_height)
));
self.gl.active_texture(0);
self.gl.bind_texture(&self.font);
self.gl.tex_image2d(
uni_gl::TextureBindPoint::Texture2d, 0, img.width() as u16, img.height() as u16, uni_gl::PixelFormat::Rgba, uni_gl::PixelType::UnsignedByte, &*img, );
}
fn resize(
&mut self,
engine: &mut dyn Engine,
hidpi_factor: f32,
(real_screen_width, real_screen_height): (u32, u32),
) {
let (x_offset, y_offset) = if self.options.fullscreen && cfg!(not(target_arch = "wasm32")) {
let x_offset = (self.screen_resolution.0 - real_screen_width) as i32 / 2;
let y_offset = (self.screen_resolution.1 - real_screen_height) as i32 / 2;
(x_offset, y_offset)
} else {
(0, 0)
};
self.gl
.viewport(x_offset, y_offset, real_screen_width, real_screen_height);
self.api.screen_size = (
(real_screen_width as f32 / hidpi_factor) as u32,
(real_screen_height as f32 / hidpi_factor) as u32,
);
engine.resize(&mut self.api);
let con_size = self.api.con().get_size();
if cfg!(target_arch = "wasm32") {
self.api.input.resize(
(self.options.screen_width, self.options.screen_height),
con_size,
(x_offset as u32, y_offset as u32),
)
} else {
self.api.input.resize(
(real_screen_width, real_screen_height),
con_size,
(x_offset as u32, y_offset as u32),
)
};
}
fn handle_input(
&mut self,
engine: &mut dyn Engine,
hidpi_factor: f32,
events: Rc<RefCell<Vec<uni_app::AppEvent>>>,
) {
for evt in events.borrow().iter() {
if let uni_app::AppEvent::Resized(size) = evt {
self.resize(engine, hidpi_factor, *size);
self.program.bind(
&self.gl,
&self.api.con,
self.font_width,
self.font_height,
self.char_width,
self.char_height,
);
}
self.api.input.on_event(evt);
}
}
pub fn run(mut self) {
self.api.set_font_path(&self.options.font_path);
let app = self.app.take().unwrap();
let mut engine = self.engine.take().unwrap();
let mut next_tick: f64 = uni_app::now();
let mut next_frame = next_tick;
let mut font_loaded = false;
engine.init(&mut self.api);
app.run(move |app: &mut uni_app::App| {
if self.api.font_path.is_some() {
let font_path = self.api.font_path.clone().unwrap();
self.api.clear_font_path();
self.font_loader.load_font(&font_path);
font_loaded = false;
}
if !font_loaded {
if self.font_loader.load_font_async() {
self.load_font_bytes();
self.program.bind(
&self.gl,
&self.api.con,
self.font_width,
self.font_height,
self.char_width,
self.char_height,
);
self.program
.set_texture(&self.gl, uni_gl::WebGLTexture(self.font.0));
font_loaded = true;
}
} else {
self.handle_input(&mut *engine, app.hidpi_factor(), app.events.clone());
let mut skipped_frames: i32 = -1;
let time = uni_app::now();
while time > next_tick && skipped_frames < MAX_FRAMESKIP {
if let Some(event) = engine.update(&mut self.api) {
match event {
UpdateEvent::Capture(filepath) => capture_screen(
&self.gl,
self.options.screen_width,
self.options.screen_height,
&filepath,
),
UpdateEvent::Exit => uni_app::App::exit(),
}
}
next_tick += SKIP_TICKS;
skipped_frames += 1;
self.api.input.on_frame();
}
if skipped_frames == MAX_FRAMESKIP {
next_tick = time + SKIP_TICKS;
}
if self.options.max_fps == 0 || time > next_frame {
engine.render(&mut self.api);
self.fps.step();
self.api.fps = self.fps.fps();
self.api.average_fps = self.fps.average();
self.program.render_primitive(&self.gl, &self.api.con);
if self.options.max_fps > 0 {
next_frame += 1.0 / self.options.max_fps as f64;
}
}
}
});
}
}
fn capture_screen(gl: &uni_gl::WebGLRenderingContext, w: u32, h: u32, filepath: &str) {
let mut img = image::DynamicImage::new_rgba8(w, h);
let pixels = img.as_mut_rgba8().unwrap();
gl.pixel_storei(uni_gl::PixelStorageMode::PackAlignment, 1);
gl.read_pixels(
0,
0,
w,
h,
uni_gl::PixelFormat::Rgba,
uni_gl::PixelType::UnsignedByte,
pixels,
);
if cfg!(not(target_arch = "wasm32")) {
image::save_buffer(
filepath,
&image::imageops::flip_vertical(&img),
w,
h,
image::ColorType::Rgba8,
)
.expect("Failed to save buffer to the specified path");
}
}
fn create_texture(gl: &uni_gl::WebGLRenderingContext) -> uni_gl::WebGLTexture {
let tex = gl.create_texture();
gl.active_texture(0);
gl.bind_texture(&tex);
set_texture_params(gl, true);
tex
}
struct Fps {
counter: u32,
start: f64,
last: f64,
total_frames: u64,
fps: u32,
average: u32,
}
impl Fps {
pub fn new() -> Fps {
let now = uni_app::now();
Fps {
counter: 0,
total_frames: 0,
start: now,
last: now,
fps: 0,
average: 0,
}
}
pub fn fps(&self) -> u32 {
self.fps
}
pub fn step(&mut self) {
self.counter += 1;
self.total_frames += 1;
let curr = uni_app::now();
if curr - self.last > 1.0 {
self.last = curr;
self.fps = self.counter;
self.counter = 0;
self.average = (self.total_frames as f64 / (self.last - self.start)) as u32;
}
}
pub fn average(&self) -> u32 {
self.average
}
}