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
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
use crate::prelude::{
    init_raw, BTerm, CharacterTranslationMode, FlexiConsole, Font, InitHints, SimpleConsole,
    SparseConsole, SpriteConsole, SpriteSheet, INPUT,
};
use crate::Result;
use bracket_color::prelude::RGB;
use std::collections::HashMap;
use std::convert::*;

/// Internal structure defining a font to be loaded.
struct BuilderFont {
    path: String,
    dimensions: (u32, u32),
    explicit_background: Option<RGB>,
}

/// Internal enum defining a console to be loaded.
enum ConsoleType {
    SimpleConsole {
        width: u32,
        height: u32,
        font: String,
        translator: CharacterTranslationMode,
    },
    SimpleConsoleNoBg {
        width: u32,
        height: u32,
        font: String,
        translator: CharacterTranslationMode,
    },
    SparseConsole {
        width: u32,
        height: u32,
        font: String,
        translator: CharacterTranslationMode,
    },
    SparseConsoleNoBg {
        width: u32,
        height: u32,
        font: String,
        translator: CharacterTranslationMode,
    },
    FlexiConsole {
        width: u32,
        height: u32,
        font: String,
        translator: CharacterTranslationMode,
    },
    SpriteConsole {
        width: u32,
        height: u32,
        sprite_sheet: usize,
    },
}

/// Provides a builder mechanism for initializing BTerm. You can chain builders together,
/// and and with a call to `.build()`. This allows you to provide settings if you want to,
/// or just use a simple initializer if you are in a hurry.
pub struct BTermBuilder {
    width: u32,
    height: u32,
    title: Option<String>,
    resource_path: String,
    fonts: Vec<BuilderFont>,
    consoles: Vec<ConsoleType>,
    tile_width: u32,
    tile_height: u32,
    platform_hints: InitHints,
    advanced_input: bool,
    sprite_sheets: Vec<SpriteSheet>,
}

impl Default for BTermBuilder {
    fn default() -> Self {
        Self {
            width: 80,
            height: 50,
            title: None,
            resource_path: "resources".to_string(),
            fonts: Vec::new(),
            consoles: Vec::new(),
            tile_height: 8,
            tile_width: 8,
            platform_hints: InitHints::new(),
            advanced_input: false,
            sprite_sheets: Vec::new(),
        }
    }
}

impl BTermBuilder {
    /// Provides a new, unconfigured, starting point for an BTerm session. You'll have to
    /// specify everything manually.
    pub fn new() -> Self {
        Self {
            width: 80,
            height: 50,
            title: None,
            resource_path: "resources".to_string(),
            fonts: Vec::new(),
            consoles: Vec::new(),
            tile_height: 8,
            tile_width: 8,
            platform_hints: InitHints::new(),
            advanced_input: false,
            sprite_sheets: Vec::new(),
        }
    }

    /// Provides an 80x50 console in the baked-in 8x8 terminal font as your starting point.
    pub fn simple80x50() -> Self {
        let mut cb = Self {
            width: 80,
            height: 50,
            title: None,
            resource_path: "resources".to_string(),
            fonts: Vec::new(),
            consoles: Vec::new(),
            tile_height: 8,
            tile_width: 8,
            platform_hints: InitHints::new(),
            advanced_input: false,
            sprite_sheets: Vec::new(),
        };
        cb.fonts.push(BuilderFont {
            path: "terminal8x8.png".to_string(),
            dimensions: (8, 8),
            explicit_background: None,
        });
        cb.consoles.push(ConsoleType::SimpleConsole {
            width: 80,
            height: 50,
            font: "terminal8x8.png".to_string(),
            translator: CharacterTranslationMode::Codepage437,
        });
        cb
    }

    /// Provides an 8x8 terminal font simple console, with the specified dimensions as your starting point.
    pub fn simple<T>(width: T, height: T) -> Result<Self>
    where
        T: TryInto<u32>,
    {
        let w: u32 = width.try_into().or(Err("Must be convertible to a u32"))?;
        let h: u32 = height.try_into().or(Err("Must be convertible to a u32"))?;
        let mut cb = Self {
            width: w,
            height: h,
            title: None,
            resource_path: "resources".to_string(),
            fonts: Vec::new(),
            consoles: Vec::new(),
            tile_height: 8,
            tile_width: 8,
            platform_hints: InitHints::new(),
            advanced_input: false,
            sprite_sheets: Vec::new(),
        };
        cb.fonts.push(BuilderFont {
            path: "terminal8x8.png".to_string(),
            dimensions: (8, 8),
            explicit_background: None,
        });
        cb.consoles.push(ConsoleType::SimpleConsole {
            width: w,
            height: h,
            font: "terminal8x8.png".to_string(),
            translator: CharacterTranslationMode::Codepage437,
        });
        Ok(cb)
    }

    /// Provides an 80x50 terminal, in the VGA font as your starting point.
    pub fn vga80x50() -> Self {
        let mut cb = Self {
            width: 80,
            height: 50,
            title: None,
            resource_path: "resources".to_string(),
            fonts: Vec::new(),
            consoles: Vec::new(),
            tile_height: 16,
            tile_width: 8,
            platform_hints: InitHints::new(),
            advanced_input: false,
            sprite_sheets: Vec::new(),
        };
        cb.fonts.push(BuilderFont {
            path: "vga8x16.png".to_string(),
            dimensions: (8, 8),
            explicit_background: None,
        });
        cb.consoles.push(ConsoleType::SimpleConsole {
            width: 80,
            height: 50,
            font: "vga8x16.png".to_string(),
            translator: CharacterTranslationMode::Codepage437,
        });
        cb
    }

    /// Provides a VGA-font simple terminal with the specified dimensions as your starting point.
    pub fn vga<T>(width: T, height: T) -> Self
    where
        T: TryInto<u32>,
    {
        let w: u32 = width.try_into().ok().expect("Must be convertible to a u32");
        let h: u32 = height
            .try_into()
            .ok()
            .expect("Must be convertible to a u32");
        let mut cb = Self {
            width: w,
            height: h,
            title: None,
            resource_path: "resources".to_string(),
            fonts: Vec::new(),
            consoles: Vec::new(),
            tile_height: 16,
            tile_width: 8,
            platform_hints: InitHints::new(),
            advanced_input: false,
            sprite_sheets: Vec::new(),
        };
        cb.fonts.push(BuilderFont {
            path: "vga8x16.png".to_string(),
            dimensions: (8, 8),
            explicit_background: None,
        });
        cb.consoles.push(ConsoleType::SimpleConsole {
            width: w,
            height: h,
            font: "vga8x16.png".to_string(),
            translator: CharacterTranslationMode::Codepage437,
        });
        cb
    }

    /// Adds width/height dimensions to the BTerm builder.
    pub fn with_dimensions<T>(mut self, width: T, height: T) -> Self
    where
        T: TryInto<u32>,
    {
        self.width = width.try_into().ok().expect("Must be convertible to a u32");
        self.height = height
            .try_into()
            .ok()
            .expect("Must be convertible to a u32");
        self
    }

    /// Overrides the default assumption for tile sizes. Needed for a raw initialization.
    /// If you have lots of fonts, the library will pick one (generally the first) to try
    /// and determine what dimensions you want to use when figuring out your window size.
    /// This method is used to override that assumption.
    /// It's a great idea to use this when using multiple layers and fonts.
    pub fn with_tile_dimensions<T>(mut self, width: T, height: T) -> Self
    where
        T: TryInto<u32>,
    {
        self.tile_width = width.try_into().ok().expect("Must be convertible to a u32");
        self.tile_height = height
            .try_into()
            .ok()
            .expect("Must be convertible to a u32");
        self
    }

    /// Adds a window title to the BTerm builder.
    pub fn with_title<S: ToString>(mut self, title: S) -> Self {
        self.title = Some(title.to_string());
        self
    }

    /// Adds a resource path to the BTerm builder. You only need to specify this if you aren't
    /// embedding your resources.
    pub fn with_resource_path<S: ToString>(mut self, path: S) -> Self {
        self.resource_path = path.to_string();
        self
    }

    /// Adds a font registration to the BTerm builder.
    pub fn with_font<S: ToString, T>(mut self, font_path: S, width: T, height: T) -> Self
    where
        T: TryInto<u32>,
    {
        self.fonts.push(BuilderFont {
            path: font_path.to_string(),
            dimensions: (
                width.try_into().ok().expect("Must be convertible to a u32"),
                height
                    .try_into()
                    .ok()
                    .expect("Must be convertible to a u32"),
            ),
            explicit_background: None,
        });
        self
    }

    /// Adds a font registration to the BTerm builder.
    pub fn with_font_bg<S: ToString, T, COLOR>(
        mut self,
        font_path: S,
        width: T,
        height: T,
        background: COLOR,
    ) -> Self
    where
        T: TryInto<u32>,
        COLOR: Into<RGB>,
    {
        self.fonts.push(BuilderFont {
            path: font_path.to_string(),
            dimensions: (
                width.try_into().ok().expect("Must be convertible to a u32"),
                height
                    .try_into()
                    .ok()
                    .expect("Must be convertible to a u32"),
            ),
            explicit_background: Some(background.into()),
        });
        self
    }

    /// Adds a simple console layer to the BTerm builder.
    pub fn with_simple_console<S: ToString, T>(mut self, width: T, height: T, font: S) -> Self
    where
        T: TryInto<u32>,
    {
        self.consoles.push(ConsoleType::SimpleConsole {
            width: width.try_into().ok().expect("Must be convertible to a u32"),
            height: height
                .try_into()
                .ok()
                .expect("Must be convertible to a u32"),
            font: font.to_string(),
            translator: CharacterTranslationMode::Codepage437,
        });
        self
    }

    /// Adds a simple console layer to the BTerm builder, with no background.
    pub fn with_simple_console_no_bg<S: ToString, T>(mut self, width: T, height: T, font: S) -> Self
    where
        T: TryInto<u32>,
    {
        self.consoles.push(ConsoleType::SimpleConsoleNoBg {
            width: width.try_into().ok().expect("Must be convertible to a u32"),
            height: height
                .try_into()
                .ok()
                .expect("Must be convertible to a u32"),
            font: font.to_string(),
            translator: CharacterTranslationMode::Codepage437,
        });
        self
    }

    /// Adds a simple console, hard-coded to the baked-in 8x8 terminal font. This does NOT register the font.
    pub fn with_simple8x8(mut self) -> Self {
        self.consoles.push(ConsoleType::SimpleConsole {
            width: self.width,
            height: self.height,
            font: "terminal8x8.png".to_string(),
            translator: CharacterTranslationMode::Codepage437,
        });
        self
    }

    /// Adds a sparse console layer to the BTerm builder.
    pub fn with_sparse_console<S: ToString, T>(mut self, width: T, height: T, font: S) -> Self
    where
        T: TryInto<u32>,
    {
        self.consoles.push(ConsoleType::SparseConsole {
            width: width.try_into().ok().expect("Must be convertible to a u32"),
            height: height
                .try_into()
                .ok()
                .expect("Must be convertible to a u32"),
            font: font.to_string(),
            translator: CharacterTranslationMode::Codepage437,
        });
        self
    }

    /// Adds a sparse console with no bg rendering layer to the BTerm builder.
    pub fn with_sparse_console_no_bg<S: ToString, T>(mut self, width: T, height: T, font: S) -> Self
    where
        T: TryInto<u32>,
    {
        self.consoles.push(ConsoleType::SparseConsoleNoBg {
            width: width.try_into().ok().expect("Must be convertible to a u32"),
            height: height
                .try_into()
                .ok()
                .expect("Must be convertible to a u32"),
            font: font.to_string(),
            translator: CharacterTranslationMode::Codepage437,
        });
        self
    }

    /// Adds a fancy (supporting per-glyph offsets, rotation, etc.) console. OpenGL only for now.
    #[cfg(feature = "opengl")]
    pub fn with_fancy_console<S: ToString, T>(mut self, width: T, height: T, font: S) -> Self
    where
        T: TryInto<u32>,
    {
        self.consoles.push(ConsoleType::FlexiConsole {
            width: width.try_into().ok().expect("Must be convertible to a u32"),
            height: height
                .try_into()
                .ok()
                .expect("Must be convertible to a u32"),
            font: font.to_string(),
            translator: CharacterTranslationMode::Codepage437,
        });
        self
    }

    /// Adds a sprite console
    #[cfg(feature = "opengl")]
    pub fn with_sprite_console<T>(mut self, width: T, height: T, sprite_sheet: usize) -> Self
    where
        T: TryInto<u32>,
    {
        self.consoles.push(ConsoleType::SpriteConsole {
            width: width.try_into().ok().expect("Must be convertible to a u32"),
            height: height
                .try_into()
                .ok()
                .expect("Must be convertible to a u32"),
            sprite_sheet,
        });
        self
    }

    /// Enables you to override the vsync default for native rendering.
    pub fn with_vsync(mut self, vsync: bool) -> Self {
        self.platform_hints.vsync = vsync;
        self
    }

    /// Enables you to override the full screen setting for native rendering.
    pub fn with_fullscreen(mut self, fullscreen: bool) -> Self {
        self.platform_hints.fullscreen = fullscreen;
        self
    }

    /// Push platform-specific initialization hints to the builder. THIS REMOVES CROSS-PLATFORM COMPATIBILITY
    pub fn with_platform_specific(mut self, hints: InitHints) -> Self {
        self.platform_hints = hints;
        self
    }

    /// Instructs the back-end (not all of them honor it; WASM and Amethyst do their own thing) to try to limit frame-rate and CPU utilization.
    pub fn with_fps_cap(mut self, fps: f32) -> Self {
        self.platform_hints.frame_sleep_time = Some(1.0 / fps);
        self
    }

    /// Enables input event queue
    pub fn with_advanced_input(mut self, advanced_input: bool) -> Self {
        self.advanced_input = advanced_input;
        self
    }

    /// Enable resize changing console size, rather than scaling. Native OpenGL only.
    #[cfg(all(feature = "opengl", not(target_arch = "wasm32")))]
    pub fn with_automatic_console_resize(mut self, resize_scaling: bool) -> Self {
        self.platform_hints.resize_scaling = resize_scaling;
        self
    }

    /// Register a sprite sheet
    #[cfg(feature = "opengl")]
    pub fn with_sprite_sheet(mut self, ss: SpriteSheet) -> Self {
        self.sprite_sheets.push(ss);
        self
    }

    /// Combine all of the builder parameters, and return an BTerm context ready to go.
    pub fn build(self) -> Result<BTerm> {
        let mut context = init_raw(
            self.width * self.tile_width,
            self.height * self.tile_height,
            self.title.unwrap_or_else(|| "BTerm Window".to_string()),
            self.platform_hints,
        )?;

        let mut font_map: HashMap<String, usize> = HashMap::new();
        for font in &self.fonts {
            let font_path = format!("{}/{}", self.resource_path, font.path);
            let font_id = context.register_font(Font::load(
                font_path.clone(),
                font.dimensions,
                font.explicit_background,
            ));
            font_map.insert(font_path, font_id?);
        }

        #[cfg(feature = "opengl")]
        for ss in self.sprite_sheets {
            context.register_spritesheet(ss);
        }

        for console in &self.consoles {
            match console {
                ConsoleType::SimpleConsole {
                    width,
                    height,
                    font,
                    translator,
                } => {
                    let font_path = format!("{}/{}", self.resource_path, font);
                    let font_id = font_map[&font_path];
                    let cid =
                        context.register_console(SimpleConsole::init(*width, *height), font_id);
                    context.set_translation_mode(cid, *translator);
                }
                ConsoleType::SimpleConsoleNoBg {
                    width,
                    height,
                    font,
                    translator,
                } => {
                    let font_path = format!("{}/{}", self.resource_path, font);
                    let font_id = font_map[&font_path];
                    let cid = context
                        .register_console_no_bg(SimpleConsole::init(*width, *height), font_id);
                    context.set_translation_mode(cid, *translator);
                }
                ConsoleType::SparseConsole {
                    width,
                    height,
                    font,
                    translator,
                } => {
                    let font_path = format!("{}/{}", self.resource_path, font);
                    let font_id = font_map[&font_path];
                    let cid =
                        context.register_console(SparseConsole::init(*width, *height), font_id);
                    context.set_translation_mode(cid, *translator);
                }
                ConsoleType::SparseConsoleNoBg {
                    width,
                    height,
                    font,
                    translator,
                } => {
                    let font_path = format!("{}/{}", self.resource_path, font);
                    let font_id = font_map[&font_path];
                    let cid = context
                        .register_console_no_bg(SparseConsole::init(*width, *height), font_id);
                    context.set_translation_mode(cid, *translator);
                }
                ConsoleType::FlexiConsole {
                    width,
                    height,
                    font,
                    translator,
                } => {
                    let font_path = format!("{}/{}", self.resource_path, font);
                    let font_id = font_map[&font_path];
                    let cid = context
                        .register_fancy_console(FlexiConsole::init(*width, *height), font_id);
                    context.set_translation_mode(cid, *translator);
                }
                ConsoleType::SpriteConsole {
                    width,
                    height,
                    sprite_sheet,
                } => {
                    context.register_sprite_console(SpriteConsole::init(
                        *width,
                        *height,
                        *sprite_sheet,
                    ));
                }
            }
        }

        if self.advanced_input {
            INPUT.lock().activate_event_queue();
        }

        Ok(context)
    }
}