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
use std::sync::atomic::AtomicI32;
use std::sync::atomic::Ordering::*;

// mod timer {
//   pub struct Timer {
//     started: Option<f64>,
//     paused: Option<f64>,
//   }
//   // pause(f64)
//   // resume(f64)
//   // reset(f64)
//   // read() -> f64
//   // update(f64)
// }

static MOUSE_X: AtomicI32 = AtomicI32::new(0);
static MOUSE_Y: AtomicI32 = AtomicI32::new(0);

fn get_mouse() -> (i32, i32) {
  (MOUSE_X.load(Relaxed), MOUSE_Y.load(Relaxed))
}

fn set_mouse(x: i32, y: i32) {
  MOUSE_X.store(x, Relaxed);
  MOUSE_Y.store(y, Relaxed);
}

pub mod playground {
  use rgeometry::algorithms::polygonization::*;
  use rgeometry::data::*;

  use gloo_events::{EventListener, EventListenerOptions};
  use ordered_float::OrderedFloat;
  use rand::distributions::Standard;
  // use rand::distributions::Uniform;
  use rand::Rng;
  use std::ops::Deref;
  // use std::ops::DerefMut;
  use std::ops::Index;
  use std::sync::Once;
  use wasm_bindgen::{JsCast, UnwrapThrowExt};
  use web_sys::Path2d;

  use once_cell::sync::Lazy;
  use once_cell::sync::OnceCell;
  use std::sync::Mutex;

  pub type Num = OrderedFloat<f64>;

  pub fn upd_mouse(event: &web_sys::MouseEvent) {
    super::set_mouse(event.offset_x(), event.offset_y())
  }

  pub fn upd_touch(event: &web_sys::TouchEvent) {
    let x = event.touches().get(0).unwrap().client_x();
    let y = event.touches().get(0).unwrap().client_y();
    super::set_mouse(x, y)
  }

  pub fn get_device_pixel_ratio() -> f64 {
    web_sys::window().unwrap().device_pixel_ratio()
  }
  pub fn document() -> web_sys::Document {
    web_sys::window().unwrap().document().unwrap()
  }
  pub fn canvas() -> web_sys::HtmlCanvasElement {
    let canvas = document().get_element_by_id("canvas").unwrap();
    let canvas: web_sys::HtmlCanvasElement = canvas
      .dyn_into::<web_sys::HtmlCanvasElement>()
      .map_err(|_| ())
      .unwrap();
    canvas
  }

  pub fn context() -> web_sys::CanvasRenderingContext2d {
    canvas()
      .get_context("2d")
      .unwrap()
      .unwrap()
      .dyn_into::<web_sys::CanvasRenderingContext2d>()
      .unwrap()
  }

  pub fn clear_screen() {
    let canvas = canvas();
    let context = context();
    context.save();
    context.reset_transform().unwrap();
    context.clear_rect(0., 0., canvas.width() as f64, canvas.height() as f64);
    context.restore();
  }

  pub fn absolute_mouse_position() -> (i32, i32) {
    super::get_mouse()
  }

  pub fn mouse_position() -> (f64, f64) {
    let (x, y) = absolute_mouse_position();
    inv_canvas_position(x, y)
  }

  pub fn inv_canvas_position(x: i32, y: i32) -> (f64, f64) {
    let ratio = get_device_pixel_ratio();
    let context = context();
    let transform = &context.get_transform().unwrap();
    let inv = transform.inverse();
    let mut pt = web_sys::DomPointInit::new();
    pt.x(x as f64 * ratio);
    pt.y(y as f64 * ratio);
    let out = inv.transform_point_with_point(&pt);
    (out.x(), out.y())
  }

  pub fn from_pixels(pixels: u32) -> f64 {
    let (vw, vh) = get_viewport();
    let canvas = canvas();
    let ratio = get_device_pixel_ratio();
    if vw < vh {
      (vw / canvas.width() as f64) * pixels as f64 * ratio
    } else {
      (vh / canvas.height() as f64) * pixels as f64 * ratio
    }
  }
  pub fn get_viewport() -> (f64, f64) {
    let canvas = canvas();
    let context = context();
    let transform = context.get_transform().unwrap();
    let scale = transform.a();
    // let ratio = get_device_pixel_ratio();
    (
      canvas.width() as f64 / scale,
      canvas.height() as f64 / scale,
    )
  }
  pub fn set_viewport(width: f64, height: f64) {
    let pixel_ratio = get_device_pixel_ratio();
    let canvas = canvas();
    let context = context();

    context.reset_transform().unwrap();

    let ratio_width = canvas.width() as f64 / width;
    let ratio_height = canvas.height() as f64 / height;
    let ratio = if ratio_width < ratio_height {
      ratio_width
    } else {
      ratio_height
    };
    context.scale(ratio, -ratio).unwrap();
    context
      .translate(
        canvas.width() as f64 / ratio / 2.,
        -(canvas.height() as f64 / ratio / 2.),
      )
      .unwrap();
    context.set_line_width(2. / ratio * pixel_ratio);
  }

  pub fn render_polygon(poly: &Polygon<Num>) {
    let context = context();

    context.begin_path();
    context.set_line_join("round");
    let mut iter = poly.iter_boundary().map(|pt| pt.point());
    if let Some(origin) = iter.next() {
      let [x, y] = origin.array;
      context.move_to(*x, *y);
      for pt in iter {
        let [x2, y2] = pt.array;
        context.line_to(*x2, *y2);
      }
    }
    context.close_path();
    context.fill();
    context.stroke();
  }

  pub fn render_line(pts: &[Point<Num, 2>]) {
    let context = context();

    context.begin_path();
    context.set_line_join("round");
    let mut iter = pts.iter();
    if let Some(origin) = iter.next() {
      let [x, y] = origin.array;
      context.move_to(*x, *y);
      for pt in iter {
        let [x2, y2] = pt.array;
        context.line_to(*x2, *y2);
      }
    }
    context.stroke();
  }

  pub fn point_path_2d(pt: &Point<Num, 2>, scale: f64) -> Path2d {
    let path = Path2d::new().unwrap();
    path
      .arc(
        **pt.x_coord(),
        **pt.y_coord(),
        scale * from_pixels(15), // radius
        0.0,
        std::f64::consts::PI * 2.,
      )
      .unwrap();
    path
  }

  pub fn at_point<F: FnOnce()>(pt: &Point<Num, 2>, cb: F) {
    let context = context();
    context.save();
    context.translate(**pt.x_coord(), **pt.y_coord()).unwrap();
    cb();
    context.restore();
  }

  pub fn circle(radius: u32) -> Path2d {
    let path = Path2d::new().unwrap();
    path
      .arc(
        0.0,
        0.0,
        from_pixels(radius), // radius
        0.0,
        std::f64::consts::PI * 2.,
      )
      .unwrap();
    path
  }

  pub fn render_point(pt: &Point<Num, 2>) {
    let path = point_path_2d(pt, 1.0);

    set_fill_style("green");
    fill_with_path_2d(&path);
    stroke_with_path(&path);
  }

  pub fn render_fixed_point(pt: &Point<Num, 2>) {
    let path = point_path_2d(pt, 0.5);

    set_fill_style("grey");
    stroke_with_path(&path);
    fill_with_path_2d(&path);
  }

  // #[deprecated(since = "0.1.0", note = "Please use the get_points function instead")]
  pub fn with_points(n: usize) -> Vec<Point<Num, 2>> {
    get_points(n)
  }

  pub fn get_points(n: usize) -> Vec<Point<Num, 2>> {
    static SELECTED: Lazy<Mutex<Option<(usize, i32, i32)>>> = Lazy::new(|| Mutex::new(None));
    static POINTS: Lazy<Mutex<Vec<Point<Num, 2>>>> = Lazy::new(|| Mutex::new(vec![]));

    static START: Once = Once::new();

    START.call_once(|| {
      {
        let mut pts = POINTS.lock().unwrap();
        let mut rng = rand::thread_rng();
        let (width, height) = get_viewport();
        let t = Transform::scale(Vector([
          OrderedFloat(width * 0.8),
          OrderedFloat(height * 0.8),
        ]))
          * Transform::translate(Vector([OrderedFloat(-0.5), OrderedFloat(-0.5)]));
        while pts.len() < n {
          let pt: Point<Num, 2> = rng.sample(Standard);
          let pt = &t * pt;
          pts.push(pt)
        }
      }

      let handle_select = || {
        let (x, y) = absolute_mouse_position();
        let ratio = get_device_pixel_ratio();
        let context = context();
        let pts = POINTS.lock().unwrap();

        for (i, pt) in pts.deref().iter().enumerate() {
          let path = point_path_2d(pt, 1.0);
          let in_path = context.is_point_in_path_with_path_2d_and_f64(
            &path,
            x as f64 * ratio,
            y as f64 * ratio,
          );
          let in_stroke = context.is_point_in_stroke_with_path_and_x_and_y(
            &path,
            x as f64 * ratio,
            y as f64 * ratio,
          );
          if in_path || in_stroke {
            let mut selected = SELECTED.lock().unwrap();
            *selected = Some((i, x, y));
            break;
          }
        }
      };
      on_mousedown(move |event| {
        upd_mouse(event);
        handle_select();
      });
      on_touchstart(move |event| {
        upd_touch(event);
        handle_select();
      });
      on_mouseup(|_event| *SELECTED.lock().unwrap() = None);
      on_touchend(|_event| *SELECTED.lock().unwrap() = None);
      on_touchmove(move |event| {
        if SELECTED.lock().unwrap().is_some() {
          event.prevent_default();
        }
      });
    });

    // Update points if mouse moved.
    {
      let mut selected = SELECTED.lock().unwrap();

      let (mouse_x, mouse_y) = absolute_mouse_position();
      if let Some((i, x, y)) = *selected {
        let (x, y) = inv_canvas_position(x, y);
        let (ox, oy) = inv_canvas_position(mouse_x, mouse_y);
        let dx = (ox - x) as f64;
        let dy = (oy - y) as f64;
        *selected = Some((i, mouse_x, mouse_y));

        let mut pts = POINTS.lock().unwrap();
        let pt = pts.index(i);
        let vector: Vector<Num, 2> = Vector([OrderedFloat(dx), OrderedFloat(dy)]);
        pts[i] = pt + &vector;
      }
    }

    POINTS.lock().unwrap().clone()
  }

  pub fn with_polygon(n: usize) -> Polygon<Num> {
    get_polygon(n)
  }

  pub fn get_polygon(n: usize) -> Polygon<Num> {
    static POLYGON: OnceCell<Mutex<Polygon<Num>>> = OnceCell::new();
    let mut p = POLYGON
      .get_or_init(|| {
        let pts = with_points(n);
        let p = two_opt_moves(pts, &mut rand::thread_rng()).unwrap();
        Mutex::new(p)
      })
      .lock()
      .unwrap();

    let pts = with_points(n);

    for (idx, pt) in p.iter_mut().enumerate() {
      *pt = pts[idx].clone();
    }
    resolve_self_intersections(&mut p, &mut rand::thread_rng()).unwrap();
    p.clone()
  }

  pub fn on_canvas_click<F>(callback: F)
  where
    F: Fn() + 'static,
  {
    let canvas = super::playground::canvas();
    let listener = EventListener::new(&canvas, "click", move |_event| callback());
    listener.forget();
  }

  pub fn on_mousemove<F>(callback: F)
  where
    F: Fn(&web_sys::MouseEvent) + 'static,
  {
    let canvas = super::playground::canvas();
    let listener = EventListener::new(&canvas, "mousemove", move |event| {
      let event = event.dyn_ref::<web_sys::MouseEvent>().unwrap_throw();
      callback(event)
    });
    listener.forget();
  }
  pub fn on_mousedown<F>(callback: F)
  where
    F: Fn(&web_sys::MouseEvent) + 'static,
  {
    let canvas = super::playground::canvas();
    let listener = EventListener::new(&canvas, "mousedown", move |event| {
      let event = event.dyn_ref::<web_sys::MouseEvent>().unwrap_throw();
      callback(event)
    });
    listener.forget();
  }
  pub fn on_mouseup<F>(callback: F)
  where
    F: Fn(&web_sys::MouseEvent) + 'static,
  {
    let canvas = super::playground::canvas();
    let listener = EventListener::new(&canvas, "mouseup", move |event| {
      let event = event.dyn_ref::<web_sys::MouseEvent>().unwrap_throw();
      callback(event)
    });
    listener.forget();
  }

  pub fn on_touchstart<F>(callback: F)
  where
    F: Fn(&web_sys::TouchEvent) + 'static,
  {
    let options = EventListenerOptions::enable_prevent_default();
    let canvas = super::playground::canvas();
    let listener = EventListener::new_with_options(&canvas, "touchstart", options, move |event| {
      let event = event.dyn_ref::<web_sys::TouchEvent>().unwrap_throw();
      callback(event)
    });
    listener.forget();
  }

  pub fn on_touchend<F>(callback: F)
  where
    F: Fn(&web_sys::TouchEvent) + 'static,
  {
    let options = EventListenerOptions::enable_prevent_default();
    let canvas = super::playground::canvas();
    let listener = EventListener::new_with_options(&canvas, "touchend", options, move |event| {
      let event = event.dyn_ref::<web_sys::TouchEvent>().unwrap_throw();
      callback(event)
    });
    listener.forget();
  }

  pub fn on_touchmove<F>(callback: F)
  where
    F: Fn(&web_sys::TouchEvent) + 'static,
  {
    let options = EventListenerOptions::enable_prevent_default();
    let canvas = super::playground::canvas();
    let listener = EventListener::new_with_options(&canvas, "touchmove", options, move |event| {
      let event = event.dyn_ref::<web_sys::TouchEvent>().unwrap_throw();
      callback(event)
    });
    listener.forget();
  }

  mod context {
    use super::{context, from_pixels, Num};
    use js_sys::Array;
    use rgeometry::data::*;
    use web_sys::Path2d;

    pub fn set_font(font: &str) {
      context().set_font(font)
    }

    pub fn set_text_align(align: &str) {
      context().set_text_align(align)
    }

    pub fn set_text_baseline(baseline: &str) {
      context().set_text_baseline(baseline)
    }

    pub fn set_fill_style(style: &str) {
      context().set_fill_style(&style.into())
    }

    pub fn set_stroke_style(style: &str) {
      context().set_stroke_style(&style.into())
    }

    pub fn fill() {
      context().fill()
    }

    pub fn stroke() {
      context().stroke()
    }

    pub fn fill_text(text: &str) {
      context().save();
      let factor = from_pixels(1);
      context().scale(factor, -factor).unwrap();
      context().fill_text(text, 0.0, 0.0).unwrap();
      context().restore();
    }

    pub fn stroke_text(text: &str) {
      context().save();
      let factor = from_pixels(1);
      context().scale(factor, -factor).unwrap();
      context().stroke_text(text, 0.0, 0.0).unwrap();
      context().restore();
    }

    pub fn fill_with_path_2d(path: &Path2d) {
      context().fill_with_path_2d(path)
    }

    pub fn stroke_with_path(path: &Path2d) {
      context().stroke_with_path(path)
    }

    pub fn begin_path() {
      context().begin_path();
    }

    pub fn close_path() {
      context().close_path();
    }

    pub fn set_line_join(join: &str) {
      context().set_line_join(join)
    }

    pub fn move_to(x: f64, y: f64) {
      context().move_to(x, y)
    }

    pub fn move_to_point(pt: &Point<Num, 2>) {
      move_to(**pt.x_coord(), **pt.y_coord())
    }

    pub fn line_to(x: f64, y: f64) {
      context().line_to(x, y)
    }

    pub fn line_to_point(pt: &Point<Num, 2>) {
      line_to(**pt.x_coord(), **pt.y_coord())
    }

    pub fn set_line_dash(dash: &[f64]) {
      let arr = Array::new();
      for (nth, &dash_len) in dash.iter().enumerate() {
        arr.set(nth as u32, dash_len.into());
      }
      context().set_line_dash(arr.as_ref()).unwrap()
    }
  }
  pub use context::*;
}