n18tile 0.1.0

Defines 18xx tile elements and track networks.
Documentation
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
use crate::Tile;
use cairo::Context;
use n18hex::consts::PI;
use n18hex::{
    Colour, Coord, Hex, HexColour, HexCorner, HexFace, HexPosition,
    Orientation,
};

/// The different types of labels that may appear on a tile.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Label {
    /// A unique identifier for tiles that can only be placed on a single map
    /// hex, corresponding to a particular city.
    City(String),
    /// An identifier for tiles that can only be placed on a single kind of
    /// city (e.g., "Y", "YY"), which generally applies to multiple map hexes.
    CityKind(String),
    /// The tile name, typically shown in the bottom-right corner of a tile.
    TileName,
    /// A map location (i.e., city or town name), typically used to identify
    /// towns and cities on a map before they are covered with tiles.
    MapLocation(String),
    /// Tile-specific notes, such as construction costs.
    Note(String),
    /// Displays the revenue associated with the tile's nth revenue centre.
    Revenue(usize),
    /// Displays a revenue (`usize`) for each game phase (identified by
    /// [HexColour]) in a horizontal stack of boxes, and highlights the active
    /// phase (`bool`).
    PhaseRevenue(Vec<(HexColour, usize, bool)>),
    /// Displays a revenue (`usize`) for each game phase (identified by
    /// [HexColour]) in a vertical stack of boxes, and highlights the active
    /// phase (`bool`).
    PhaseRevenueVert(Vec<(HexColour, usize, bool)>),
}

impl Label {
    /// Returns a new city kind label "Y".
    pub fn y() -> Self {
        Label::CityKind("Y".to_string())
    }

    /// Returns `true` if this label restricts placing and/or upgrading tiles.
    pub fn is_tile_restriction(&self) -> bool {
        match self {
            Self::City(_) => true,
            Self::CityKind(_) => true,
            Self::TileName => false,
            Self::MapLocation(_) => false,
            Self::Revenue(_) => false,
            Self::PhaseRevenue(_) => false,
            Self::PhaseRevenueVert(_) => false,
            Self::Note(_) => false,
        }
    }

    /// Draw this label on a tile.
    pub fn draw(
        &self,
        ctx: &Context,
        hex: &Hex,
        pos: &HexPosition,
        tile: &Tile,
    ) {
        let style = match self {
            Self::City(_) => &hex.theme.city_label,
            Self::CityKind(_) => &hex.theme.city_kind_label,
            Self::TileName => &hex.theme.tile_label,
            Self::MapLocation(_) => &hex.theme.location_label,
            Self::Revenue(_) => &hex.theme.revenue_label,
            Self::PhaseRevenue(_) => &hex.theme.phase_revenue_label,
            Self::PhaseRevenueVert(_) => &hex.theme.phase_revenue_label,
            Self::Note(_) => &hex.theme.note_label,
        };
        let mut labeller = style.labeller(ctx, hex);
        let coord = pos.coord(hex);

        // Set horizontal/vertical alignment based on the HexPosition anchor.
        let horiz = h_align(hex, pos);
        let vert = v_align(hex, pos);
        labeller.halign(horiz);
        labeller.valign(vert);

        match self {
            Self::City(text) | Self::CityKind(text) | Self::Note(text) => {
                labeller.draw(text, coord);
            }
            Self::TileName => {
                let label_text = &tile.name;
                labeller.draw(label_text, coord);
            }
            Self::MapLocation(name) => {
                let colour = if tile.colour == HexColour::Red
                    || tile.colour == HexColour::Blue
                {
                    Colour::WHITE
                } else {
                    Colour::BLACK
                };
                labeller.colour(colour);
                labeller.draw(name, coord);
            }
            Self::Revenue(amount_ix) => {
                // Determine the text dimensions.
                let amount = tile.revenues()[*amount_ix];
                let label_text = format!("{}", amount);
                let text_size = labeller.size(&label_text);
                // Make the circle/ellipse radius a bit larger than the
                // minimum size required to include the text bounding box.
                let ratio = text_size.width / text_size.height;
                let radius = ELLIPSE_RADIUS_SCALE
                    * (0.5 * text_size.width).max(0.5 * text_size.height);
                let width = 2.0 * radius;
                let height = ellipse_height(radius, ratio);

                let ellipse_size = n18hex::theme::Size {
                    dx: 0.0,
                    dy: 0.0,
                    width,
                    height,
                };
                let origin = ellipse_size.top_left(&coord, horiz, vert);
                let centre = Coord::from((
                    origin.x + 0.5 * width,
                    origin.y + 0.5 * height,
                ));

                // Draw the surrounding circle/ellipse.
                ctx.new_path();
                define_ellipse(ctx, radius, ratio, centre);
                hex.theme.label_circle.apply_fill(ctx);
                ctx.fill_preserve().unwrap();
                hex.theme.label_circle.apply_line_and_stroke(ctx, hex);
                ctx.stroke().unwrap();
                ctx.new_path();

                // NOTE: Draw the text in the centre of the ellipse.
                labeller.halign(n18hex::theme::AlignH::Centre);
                labeller.valign(n18hex::theme::AlignV::Middle);
                labeller.draw(&label_text, centre);
            }
            Self::PhaseRevenue(amounts) => {
                let boxes = get_boxes(amounts);
                let active_box =
                    active_box_ix(amounts).expect("No active revenue box");
                let (box_width, box_height) =
                    box_dims(&boxes, hex, &labeller);
                let net_width = box_width * boxes.len() as f64;

                // Determine the top-left point of these boxes.
                let mut origin = coord;
                origin.x += horiz.hjust() * net_width;
                origin.y += vert.vjust() * box_height;

                // NOTE: override the text alignment, we will manually centre
                // the text in each box.
                labeller.halign(n18hex::theme::AlignH::Left);
                labeller.valign(n18hex::theme::AlignV::Top);

                // Draw the background and text for each box.
                boxes.iter().enumerate().for_each(
                    |(ix, (bg_colour, text))| {
                        let dx = ix as f64 * box_width;
                        let x0 = origin.x + dx;
                        let y0 = origin.y;

                        // Draw the background.
                        ctx.rectangle(x0, y0, box_width, box_height);
                        hex.theme.apply_hex_colour(ctx, *bg_colour);
                        ctx.fill().unwrap();

                        // Centre the label text in the box.
                        let size = labeller.size(text);
                        let x = x0 - size.dx + 0.5 * (box_width - size.width);
                        let y =
                            y0 - size.dy + 0.5 * (box_height - size.height);
                        labeller.draw(text, (x, y).into());
                    },
                );

                // Draw a border around the active box.
                let dx = active_box as f64 * box_width;
                ctx.rectangle(origin.x + dx, origin.y, box_width, box_height);
                Colour::BLACK.apply_colour(ctx);
                ctx.stroke().unwrap();
            }
            Self::PhaseRevenueVert(amounts) => {
                let boxes = get_boxes(amounts);
                let active_box =
                    active_box_ix(amounts).expect("No active revenue box");
                let (box_width, box_height) =
                    box_dims(&boxes, hex, &labeller);
                let net_height = box_height * boxes.len() as f64;

                // Determine the top-left point of these boxes.
                let mut origin = coord;
                origin.x += horiz.hjust() * box_width;
                origin.y += vert.vjust() * net_height;

                // NOTE: override the text alignment, we will manually centre
                // the text in each box.
                labeller.halign(n18hex::theme::AlignH::Left);
                labeller.valign(n18hex::theme::AlignV::Top);

                // Draw the background and text for each box.
                boxes.iter().enumerate().for_each(
                    |(ix, (bg_colour, text))| {
                        let dy = ix as f64 * box_height;
                        let x0 = origin.x;
                        let y0 = origin.y + dy;

                        // Draw the background.
                        ctx.rectangle(x0, y0, box_width, box_height);
                        hex.theme.apply_hex_colour(ctx, *bg_colour);
                        ctx.fill().unwrap();

                        // Centre the label text in the box.
                        let size = labeller.size(text);
                        let x = x0 - size.dx + 0.5 * (box_width - size.width);
                        let y =
                            y0 - size.dy + 0.5 * (box_height - size.height);
                        labeller.draw(text, (x, y).into());
                    },
                );

                // Draw a border around the active box.
                let dx = active_box as f64 * box_height;
                ctx.rectangle(origin.x, origin.y + dx, box_width, box_height);
                Colour::BLACK.apply_colour(ctx);
                ctx.stroke().unwrap();
            }
        };
    }

    /// Draw a tile name label with custom text, in the default position of
    /// the bottom-right corner.
    pub fn draw_custom_tile_name(ctx: &Context, hex: &Hex, name: &str) {
        let mut labeller = hex.theme.tile_label.labeller(ctx, hex);
        let pos = Self::tile_name_position(hex);
        let coord = pos.coord(hex);
        let horiz = h_align(hex, &pos);
        let vert = v_align(hex, &pos);
        labeller.halign(horiz);
        labeller.valign(vert);
        labeller.draw(name, coord);
    }

    /// Returns the position of the tile name label.
    ///
    /// For [Orientation::FlatTop] this is the bottom-right corner, and for
    /// [Orientation::PointedTop] this is the bottom corner.
    pub fn tile_name_position(hex: &Hex) -> HexPosition {
        match hex.orientation() {
            Orientation::FlatTop => {
                HexPosition::Corner(HexCorner::BottomRight, None)
            }
            Orientation::PointedTop => {
                // NOTE: move the label slightly upwards, so that the bottom
                // of the label text is not clipped.
                HexPosition::from(HexCorner::BottomRight).to_centre(0.05)
            }
        }
    }
}

/// Returns a vector of `(colour, label_text)` pairs for each phase of a phase
/// revenue label.
fn get_boxes(
    amounts: &[(HexColour, usize, bool)],
) -> Vec<(HexColour, String)> {
    amounts
        .iter()
        .map(|(colour, amount, _active)| (*colour, format!("{}", amount)))
        .collect()
}

/// Returns the index of the active phase revenue box, if any.
fn active_box_ix(amounts: &[(HexColour, usize, bool)]) -> Option<usize> {
    amounts.iter().enumerate().find_map(
        |(ix, (_colour, _amount, active))| {
            if *active {
                Some(ix)
            } else {
                None
            }
        },
    )
}

/// Returns the width and height, respectively, of each phase revenue box,
/// including margins.
fn box_dims(
    boxes: &[(HexColour, String)],
    hex: &Hex,
    labeller: &n18hex::theme::Labeller<'_>,
) -> (f64, f64) {
    let (box_width, box_height) = boxes
        .iter()
        .map(|(_colour, text)| {
            let size = labeller.size(text);
            (size.width, size.height)
        })
        .fold(
            (0.0, 0.0),
            |(curr_w, curr_h): (f64, f64), (new_w, new_h)| {
                (curr_w.max(new_w), curr_h.max(new_h))
            },
        );
    let margin_width = hex.theme.phase_revenue_margin_x.absolute(hex);
    let margin_height = hex.theme.phase_revenue_margin_y.absolute(hex);
    let box_width = box_width + 2.0 * margin_width;
    let box_height = box_height + 2.0 * margin_height;
    (box_width, box_height)
}

/// The horizontal alignment for a label relative to its position coordinates.
///
/// - **Left:** corners and faces on the left half of the hex.
/// - **Centre:** [HexPosition::Centre], and the top and bottom faces.
/// - **Right:** corners and faces on the right half of the hex.
///
/// When using [Orientation::PointedTop], each face and corner is rotated 30
/// degrees clockwise.
/// This means that [HexFace::Top] is the upper-right face, [Corner::TopLeft]
/// is the top corner, and so on.
fn h_align(hex: &Hex, pos: &HexPosition) -> n18hex::theme::AlignH {
    use n18hex::theme::AlignH;
    use HexCorner::*;
    use HexFace::*;
    use HexPosition::*;

    match hex.orientation() {
        Orientation::FlatTop => match pos {
            Centre(_) => AlignH::Centre,
            Face(Bottom, _) | Face(Top, _) => AlignH::Centre,
            Face(LowerLeft, _)
            | Face(UpperLeft, _)
            | Corner(BottomLeft, _)
            | Corner(Left, _)
            | Corner(TopLeft, _) => AlignH::Left,
            Face(LowerRight, _)
            | Face(UpperRight, _)
            | Corner(BottomRight, _)
            | Corner(Right, _)
            | Corner(TopRight, _) => AlignH::Right,
        },
        Orientation::PointedTop => match pos {
            Centre(_) => AlignH::Centre,
            Corner(TopLeft, _) | Corner(BottomRight, _) => AlignH::Centre,
            Face(Bottom, _)
            | Face(LowerLeft, _)
            | Face(UpperLeft, _)
            | Corner(BottomLeft, _)
            | Corner(Left, _) => AlignH::Left,
            Face(Top, _)
            | Face(LowerRight, _)
            | Face(UpperRight, _)
            | Corner(Right, _)
            | Corner(TopRight, _) => AlignH::Right,
        },
    }
}

/// The vertical alignment for a label relative to its position coordinates.
///
/// - **Top:** corners and faces in the upper half of the hex.
/// - **Middle:** [HexPosition::Centre], and the left and right corners.
/// - **Bottom:** corners and faces in the lower half of the hex.
///
/// When using [Orientation::PointedTop], each face and corner is rotated 30
/// degrees clockwise.
/// This means that [HexFace::Top] is the upper-right face, [Corner::TopLeft]
/// is the top corner, and so on.
fn v_align(hex: &Hex, pos: &HexPosition) -> n18hex::theme::AlignV {
    use n18hex::theme::AlignV;
    use HexCorner::*;
    use HexFace::*;
    use HexPosition::*;

    match hex.orientation() {
        Orientation::FlatTop => match pos {
            Centre(_) => AlignV::Middle,
            Corner(Left, _) | Corner(Right, _) => AlignV::Middle,
            Face(UpperLeft, _)
            | Face(Top, _)
            | Face(UpperRight, _)
            | Corner(TopLeft, _)
            | Corner(TopRight, _) => AlignV::Top,
            Face(LowerLeft, _)
            | Face(Bottom, _)
            | Face(LowerRight, _)
            | Corner(BottomLeft, _)
            | Corner(BottomRight, _) => AlignV::Bottom,
        },
        Orientation::PointedTop => match pos {
            Centre(_) => AlignV::Middle,
            Face(LowerLeft, _) | Face(UpperRight, _) => AlignV::Middle,
            Face(UpperLeft, _)
            | Face(Top, _)
            | Corner(Left, _)
            | Corner(TopLeft, _)
            | Corner(TopRight, _) => AlignV::Top,
            Face(Bottom, _)
            | Face(LowerRight, _)
            | Corner(BottomLeft, _)
            | Corner(BottomRight, _)
            | Corner(Right, _) => AlignV::Bottom,
        },
    }
}
/// The ratio of text width to text height at which we switch from drawing a
/// circle around the text to drawing an ellipse around the text.
/// This improves the appearance of, e.g., revenue labels for $100 and above.
const ELLIPSE_RATIO: f64 = 1.25;

/// The scaling factor for the relationship between the text bounding box
/// dimensions and the surrounding circle/ellipse radius.
/// We want this radius to be larger than the minimum size required to include
/// the text bounding box, so that there is some space between the text and
/// the circle/ellipse border.
const ELLIPSE_RADIUS_SCALE: f64 = 4.0 / 3.0;

fn ellipse_height(radius: f64, ratio: f64) -> f64 {
    let diam = 2.0 * radius;
    if ratio >= ELLIPSE_RATIO {
        diam / ratio
    } else {
        diam
    }
}

fn define_ellipse(ctx: &Context, radius: f64, ratio: f64, centre: Coord) {
    if ratio >= ELLIPSE_RATIO {
        let matrix = ctx.matrix();
        let scale = 1.0 / ratio;
        ctx.scale(1.0, scale);
        ctx.arc(centre.x, centre.y / scale, radius, 0.0, 2.0 * PI);
        ctx.set_matrix(matrix);
    } else {
        ctx.arc(centre.x, centre.y, radius, 0.0, 2.0 * PI);
    };
}