package tiny_libs

  1. Overview
  2. Docs
From-scratch libraries for teaching: graphics, audio, compression, crypto, networking and more

Install

dune-project
 Dependency

Authors

Maintainers

Sources

0.3.6.tar.gz
md5=7c636383d146d30ac6f2fa234a6253c8
sha512=c79f3823c5f8f57e5038eb640d487c61168b84aa07c61999d6622ef9fd0c890e2b03b4c6a7cdbbe9352a49e25dda00ac7bb14693cee8e3d7beeed251351a2af0

doc/src/tiny_libs.physics_3d/Body3d.ml.html

Source file Body3d.ml

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
(* Claude Code
 *
 * Copyright (C) 2026 Yoann Padioleau
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public License
 * (LGPL) as published by the Free Software Foundation; either version
 * 2 of the License, or (at your option) any later version.
 *)

(* See Body3d.mli *)

type t = {
  pos : Vec3.t;
  vel : Vec3.t;
  orientation : Quat.t;
  spin : Vec3.t;
  mass : float;
  inertia : Mat3.t;
  inv_inertia : Mat3.t;
}

let never_turns = Mat3.diagonal infinity infinity infinity

(* claude: a diagonal tensor is inverted entry by entry, where an
 * infinite axis gives 1/infinity = 0 ("no impulse can spin it about
 * this one"); anything else goes through the general inverse, and a
 * singular tensor means the same thing *)
let inverse_inertia (i : Mat3.t) : Mat3.t =
  let diagonal = i.Mat3.m01 = 0. && i.Mat3.m02 = 0. && i.Mat3.m10 = 0. && i.Mat3.m12 = 0. && i.Mat3.m20 = 0. && i.Mat3.m21 = 0. in
  if diagonal then Mat3.inverse_diagonal i
  else match Mat3.inverse i with Some m -> m | None -> Mat3.zero

let with_inertia i b = { b with inertia = i; inv_inertia = inverse_inertia i }

let make ?(vel = (0., 0., 0.)) ?(orientation = Quat.identity) ?(spin = (0., 0., 0.)) ?(mass = 1.) ?(inertia = never_turns) pos =
  { pos; vel; orientation; spin; mass; inertia; inv_inertia = inverse_inertia inertia }

let inertia_world b = Mat3.conjugate (Quat.to_mat3 b.orientation) b.inertia
let inv_inertia_world b = Mat3.conjugate (Quat.to_mat3 b.orientation) b.inv_inertia
let point_velocity b r = Vec3.add b.vel (Vec3.cross b.spin r)

let box ~mass (w, h, d) =
  let m = mass /. 12. in
  Mat3.diagonal (m *. ((h *. h) +. (d *. d))) (m *. ((w *. w) +. (d *. d))) (m *. ((w *. w) +. (h *. h)))

let solid_sphere ~mass ~radius =
  let i = 0.4 *. mass *. radius *. radius in
  Mat3.diagonal i i i

(* i + m (|r|^2 E - r r^T) *)
let shifted ~mass ((rx, ry, rz) as r) i =
  let r2 = Vec3.dot r r in
  let outer =
    Mat3.of_rows (rx *. rx, rx *. ry, rx *. rz) (ry *. rx, ry *. ry, ry *. rz) (rz *. rx, rz *. ry, rz *. rz)
  in
  Mat3.add i (Mat3.scale mass (Mat3.add (Mat3.scale r2 Mat3.identity) (Mat3.scale (-1.) outer)))