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
//! The [`App`] struct and some constants.

use graphics::color::{BLACK, TRANSPARENT, WHITE};
use graphics::types::Color;
use opengl_graphics::{GlGraphics, GlyphCache};
use piston::input::*;

use std::thread;

use crate::algorithms::Algorithm;
use crate::array::Array;

use crate::state::*;

/// Color that is used to clear the window before [drawing](App::render).
pub const BACKGROUND_COLOR: Color = BLACK;

/// Color of rectangles that represent the array values.
pub const VALUE_COLOR: Color = WHITE;

/// Color of the values that have been recently accessed.
///
/// _See_ [`State.array_accesses`](State::array_accesses)
pub const ACCESSED_VALUE_COLOR: Color = [1.0, 0.0, 0.0, 1.0];

/// Time in seconds after which array accesses are removed.
///
/// _See_ [`State.array_accesses`](State::array_accesses)
pub const ACCESSED_VALUE_TIMEOUT: f64 = 0.25;

/// Font size of the status text in pixels.
pub const STATUS_TEXT_FONT_SIZE: u32 = 16;

/// Margins between the status text and window borders.
pub const STATUS_TEXT_MARGIN: f64 = 8.0;

/// Factor for increasing / decreasing speed of sorting array
pub const SPEED_FACTOR: f64 = 2.0;

/// This struct contains all [rendering](App::render), [updating](App::update)
/// and [input handling](App::button) logic.
#[derive(Debug)]
pub struct App {
  state: SharedState,
  algorithm_thread: thread::JoinHandle<()>,
}

impl App {
  /// Creates a new app (with a state constructed from the given `array`) and
  /// starts an algorithm thread. This function is called `init` instead of
  /// `new` because it has side effects.
  pub fn init(
    algorithm: Box<dyn Algorithm + Send>,
    array: Vec<u32>,
    speed: f64,
  ) -> Self {
    let array_len = array.len();
    let colors = vec![TRANSPARENT; array_len];

    let state = SharedState::new(State {
      time: 0.0,
      speed,
      paused: true,
      array,
      colors,
      array_accesses: vec![NO_ARRAY_ACCESS; array_len],
    });

    let algorithm_state = state.clone();

    let algorithm_thread = thread::Builder::new()
      .name("algorithm".to_string())
      .spawn(move || {
        let array = Array::new(algorithm_state);
        array.wait(500);
        algorithm.sort(array);
      })
      .unwrap();

    Self {
      state,
      algorithm_thread,
    }
  }

  /// Draws the current [state](State).
  pub fn render(
    &mut self,
    args: RenderArgs,
    gl: &mut GlGraphics,
    glyphs: &mut GlyphCache<'_>,
  ) {
    gl.draw(args.viewport(), |ctx, gl| {
      use graphics::*;

      clear(BACKGROUND_COLOR, gl);

      // lock the state for the whole rendering cycle so that the algorithm
      // thread doesn't change something while the main thread is doing
      // rendering
      let state = self.state.get();

      // transform of the bottom left point of the status text
      let status_text_transform = ctx.transform.trans(
        STATUS_TEXT_MARGIN,
        STATUS_TEXT_MARGIN + f64::from(STATUS_TEXT_FONT_SIZE),
      );

      let status_text = format!(
        "paused = {}, speed = {}%",
        state.paused,
        state.speed * 100.0
      );

      // draw the status text
      text::Text::new_color(WHITE, STATUS_TEXT_FONT_SIZE)
        .draw(
          &status_text,
          glyphs,
          &ctx.draw_state,
          status_text_transform,
          gl,
        )
        .unwrap();

      let len = state.array.len();
      let max_value = *state.array.iter().max().unwrap_or(&0);

      // draws a rectangle with a given color which represents a value at a
      // specified index
      let mut draw_value = |index: usize, color: Color| {
        let value = state.array[index];

        let window_w: f64 = args.width;
        let window_h: f64 = args.height;

        let array_y =
          STATUS_TEXT_MARGIN * 2.0 + f64::from(STATUS_TEXT_FONT_SIZE);

        let array_h = window_h - array_y;

        let w = window_w / (len as f64);
        let h = f64::from(value) * array_h / f64::from(max_value);
        let x = (index as f64) * w;
        let y = window_h - h;

        rectangle(color, [x, y, w, h], ctx.transform, gl);
      };

      // draw all values
      for index in 0..len {
        draw_value(index, VALUE_COLOR);
      }

      // draw array accesses
      for (index, access_time) in state.array_accesses.iter().enumerate() {
        if *access_time < 0.0 {
          continue;
        }

        let mut color = ACCESSED_VALUE_COLOR;

        let access_age = state.time - access_time;
        // map age of this access to the [1.0, 0.0] interval of the alpha (transparency) component
        // so that new accesses are opaque and old ones are transparent
        let alpha = (1.0 - access_age / ACCESSED_VALUE_TIMEOUT) as f32;

        color[color.len() - 1] = alpha;
        draw_value(index, color);
      }

      // draw colored overlays (marks) for some values
      for (index, color) in state.colors.iter().enumerate() {
        draw_value(index, *color);
      }
    });
  }

  /// Advances the [state](State) by a given amount of [time](UpdateArgs::dt).
  pub fn update(&mut self, args: UpdateArgs) {
    let mut state = self.state.get();

    if !state.paused {
      state.time += args.dt * state.speed;
    }

    // time is copied (f64 implements the Copy trait) to a variable because it
    // can't be accessed when array_accesses is borrowed mutably
    let time = state.time;
    for access_time in state.array_accesses.iter_mut() {
      if time - *access_time > ACCESSED_VALUE_TIMEOUT {
        *access_time = NO_ARRAY_ACCESS;
      }
    }
  }

  /// Handles user input and updates the [state](State).
  ///
  /// # Controls
  ///
  /// | Key                    | Action       |
  /// | ---------------------- | ------------ |
  /// | <kbd>Space</kbd>       | pause/resume |
  /// | <kbd>&uparrow;</kbd>   | 2x faster    |
  /// | <kbd>&downarrow;</kbd> | 2x slower    |
  pub fn button(&mut self, args: ButtonArgs) {
    let mut state = self.state.get();

    // import commonly used enum values in the current scope
    use self::Button::Keyboard;
    use self::ButtonState::Press;

    match (args.button, args.state) {
      (Keyboard(Key::Space), Press) => {
        state.paused = !state.paused;
        self.algorithm_thread.thread().unpark();
      }

      (Keyboard(Key::Up), Press) => state.speed *= SPEED_FACTOR,
      (Keyboard(Key::Down), Press) => state.speed /= SPEED_FACTOR,

      _ => {}
    };
  }
}