Skip to content

Commit

Permalink
[init]
Browse files Browse the repository at this point in the history
  • Loading branch information
NaokiHori committed Feb 17, 2024
0 parents commit f01bc03
Show file tree
Hide file tree
Showing 26 changed files with 2,181 additions and 0 deletions.
73 changes: 73 additions & 0 deletions .github/workflows/deploy.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
name: Deploy

on:
push:
branches:
- main
paths:
- Cargo.toml
- index.html
- src/**
- style.css
- tsconfig.json
- typescript/**
workflow_dispatch:

jobs:

deploy:
name: Deploy page
permissions:
contents: read
pages: write
id-token: write
concurrency:
group: "pages"
cancel-in-progress: true
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@main
- name: Setup node
uses: actions/setup-node@main
- name: Install TypeScript
run: |
npm install -g typescript
- name: Install wasm-pack
run: |
cargo install wasm-pack
- name: Perform unit tests
run: |
cargo test --bin=collision
cargo test --lib
- name: Build and execute binary crate
run: |
cargo run --release
- name: Build library crate
run: |
dest="built"
wasm-pack build --target web
mkdir ${dest}
cp pkg/*.js ${dest}/
cp pkg/*.wasm ${dest}/
cp pkg/*.ts typescript/
tsc --outDir ${dest}
- name: Prepare directory to be deployed
run: |
mkdir package
cp -r \
style.css thumbnail.jpg index.html built \
package/
- name: Setup GitHub Pages
uses: actions/configure-pages@main
- name: Upload HTML
uses: actions/upload-pages-artifact@main
with:
path: package
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@main

22 changes: 22 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
[package]
name = "collision"
version = "0.1.0"
authors = ["Naoki Hori"]
description = "Event-driven collision simulator"
repository = "https://github.com/NaokiHori/Collision"
edition = "2021"
publish = false
license-file = "LICENSE"

[[bin]]
name = "collision"
path = "src/main.rs"

[lib]
crate-type = ["cdylib"]
path = "src/lib.rs"

[dependencies]
js-sys = { version = "0.3.67" }
web-sys = { version = "0.3.67", features = ["CanvasRenderingContext2d", "Document", "HtmlCanvasElement", "Window", "console", ] }
wasm-bindgen = { version = "0.2.90" }
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 NaokiHori

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
48 changes: 48 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
#########
Collision
#########

|License|_ |LastCommit|_ |Deploy|_

.. |License| image:: https://img.shields.io/github/license/NaokiHori/Collision
.. _License: https://opensource.org/licenses/MIT

.. |LastCommit| image:: https://img.shields.io/github/last-commit/NaokiHori/Collision/main
.. _LastCommit: https://github.com/NaokiHori/Collision/commits/main

.. |Deploy| image:: https://github.com/NaokiHori/Collision/actions/workflows/deploy.yml/badge.svg?branch=main
.. _Deploy: https://github.com/NaokiHori/Collision/actions/workflows/deploy.yml

.. image:: https://img.shields.io/badge/youtube-%23EE4831.svg?&style=for-the-badge&logo=youtube&logoColor=white
:target: https://youtu.be/k8hbpa3CsCg
:width: 10%

.. image:: https://github.com/NaokiHori/Collision/blob/main/thumbnail.jpg
:target: https://youtu.be/k8hbpa3CsCg
:width: 100%

********
Overview
********

Event-driven simulation of many colliding particles.

******
Method
******

All inter-particle collision events are considered, which requires essentially O(N_p^2) operations, where N_p is the number of particles.
To drop the cost, the so-called event-driven approach combined with the cell method is used, which leads to the cost of O(N_p^2 / N_c) where N_c is the number of cells.

Scheduling requests O(N_c) operations if implemented naively.
To reduce the cost, a minimum binary heap with the cost of O(log N_c) for insertions and deletions is adopted.

Updating particle positions and velocities requests O(N_p) operations.
This is mitigated by introducing particle-based local time, so that particles are only synchronised when drawn.

***************
Acknowledgement
***************

I would like to thank Prof. Stefan Luding for his stimulating lecture in a JMBC course *Particle-based modeling techniques*.

33 changes: 33 additions & 0 deletions index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<!DOCTYPE html>
<html lang="en-US">

<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width"/>
<meta property="og:site_name" content="Collision - Event-driven collision simulator">
<meta property="og:title" content="Collision - Event-driven collision simulator">
<meta property="og:url" content="https://naokihori.github.io/Collision/index.html">
<meta property="og:type" content="website">
<meta property="og:image" content="https://naokihori.github.io/Collision/thumbnail.jpg">
<link rel="stylesheet" href="./style.css"/>
<title>
Event-driven Collision Simulator
</title>
<script type="module" src="./built/main.js"></script>
</head>

<body>
<div class="header">
<a href="https://github.com/NaokiHori/Collision" target="_blank">
Event-driven Collision Simulator
</a>
</div>
<canvas id="my-canvas">
This browser does not support canvas element.
</canvas>
<div class="footer">
Copyright 2024, Naoki Hori.
</div>
</body>

</html>
77 changes: 77 additions & 0 deletions src/drawer.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
use wasm_bindgen::prelude::*;

use std::cell::{Ref, RefCell};
use std::rc::Rc;

use crate::simulator::particle::Particle;

const YELLOW: &str = "#888844";

pub struct Drawer {
canvas: web_sys::HtmlCanvasElement,
context: web_sys::CanvasRenderingContext2d,
}

impl Drawer {
pub fn new() -> Drawer {
// Document object
let document: web_sys::Document = web_sys::window().unwrap().document().unwrap();
// HTML canvas element
let canvas: web_sys::HtmlCanvasElement = document
.get_element_by_id("my-canvas")
.unwrap()
.dyn_into::<web_sys::HtmlCanvasElement>()
.map_err(|_| ())
.unwrap();
// HTML canvas context object
let context: web_sys::CanvasRenderingContext2d = canvas
.get_context("2d")
.unwrap()
.unwrap()
.dyn_into::<web_sys::CanvasRenderingContext2d>()
.unwrap();
Drawer { canvas, context }
}

pub fn draw(&mut self, lengths: &[f64], particles: &[Rc<RefCell<Particle>>]) {
let canvas: &web_sys::HtmlCanvasElement = &self.canvas;
let context: &web_sys::CanvasRenderingContext2d = &self.context;
// get canvas size
let w: f64 = canvas.client_width() as f64;
let h: f64 = canvas.client_height() as f64;
// NOTE: assume squared domain
let screen_size: f64 = w.min(h);
let domain_size: f64 = {
let lx: f64 = lengths[0];
let ly: f64 = lengths[1];
lx.min(ly)
};
// clean canvas
context.clear_rect(0., 0., screen_size, screen_size);
// map physical coordinate to screen coordinate
// horizontal / vertical scaling
let scale: f64 = screen_size / domain_size;
// draw circles
context.set_fill_style(&JsValue::from_str(YELLOW));
for particle in particles.iter() {
let particle: Ref<Particle> = particle.borrow();
const ARCS: [f64; 2] = [0., 2. * std::f64::consts::PI];
let r: f64 = particle.rad;
let x: f64 = particle.pos[0];
let y: f64 = particle.pos[1];
context.begin_path();
context
.arc(scale * x, scale * y, scale * r, ARCS[0], ARCS[1])
.unwrap();
context.fill();
}
}

pub fn update_canvas_size(&self) {
let canvas: &web_sys::HtmlCanvasElement = &self.canvas;
let w: i32 = canvas.client_width();
let h: i32 = canvas.client_height();
canvas.set_width(w as u32);
canvas.set_height(h as u32);
}
}
36 changes: 36 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
mod drawer;
mod myvec;
mod random;
mod simulator;

use crate::drawer::Drawer;
use crate::simulator::{Simulator, NDIMS};

#[wasm_bindgen::prelude::wasm_bindgen]
pub struct Collision {
simulator: crate::simulator::Simulator,
drawer: crate::drawer::Drawer,
}

#[wasm_bindgen::prelude::wasm_bindgen]
impl Collision {
pub fn new(length: f64, nitems: usize, rate: f64) -> Collision {
let lengths: [f64; NDIMS] = [length, length];
let simulator = Simulator::new(rate, lengths, nitems);
let drawer = Drawer::new();
Collision { simulator, drawer }
}

pub fn update(&mut self) {
self.simulator.integrate();
self.drawer
.draw(self.simulator.get_lengths(), self.simulator.get_particles());
}

pub fn update_canvas_size(&self) {
self.drawer.update_canvas_size();
}
}

#[wasm_bindgen::prelude::wasm_bindgen(start)]
pub fn init() {}
24 changes: 24 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
mod myvec;
mod random;
mod simulator;

use crate::simulator::{Simulator, NDIMS};

fn main() {
let mut time: f64 = 0.;
let time_max: f64 = 100.;
let sync_rate: f64 = 1.;
let lengths: [f64; NDIMS] = [32., 32.];
let nparticles: usize = 256;
let mut simulator = Simulator::new(sync_rate, lengths, nparticles);
let ncells: &[usize; NDIMS] = simulator.get_ncells();
println!("number of cells: ({}, {})", ncells[0], ncells[1]);
loop {
simulator.integrate();
time += sync_rate;
println!("time: {:8.2e}", time);
if time_max < time {
break;
}
}
}
Loading

0 comments on commit f01bc03

Please sign in to comment.