Compare commits

..

719 Commits
tire ... master

Author SHA1 Message Date
11e53383c7 feat: deterministic natural logarithm
The rocket equation produces par-fuel and delta-v figures that ship inside
level data. A value that differs between platforms is the same class of bug
as a desynced replay, so log belongs in the kernel rather than falling back
to the host libm.

Reduce x = m*2^k with m in [2/3, 4/3), then ln(m) = 2*atanh((m-1)/(m+1)).
Accurate to <1e-13 against the host libm across the tested range.
2026-09-15 01:05:10 +03:00
4c82aabc5d feat: deterministic cross-platform math kernel
Replaces every host-libm call in the physics source with a kernel built from
IEEE-754-exact operations only, so simulation results are bit-identical on
ARM64/JavaScriptCore and x86-64/V8.

ECMAScript permits Math.sin/cos/atan2 to be implementation-dependent
approximations, and Rot.setAngle and Sweep.getTransform call them for every
rotating body on every step. Without this, a replay recorded on mobile does
not reproduce on desktop, which breaks replay verification and leaderboards.

- add src/common/DeterministicMath.ts (fdlibm-derived polynomials and
  Cody-Waite range reduction, plus a seeded mulberry32 PRNG)
- rewire the nine hoisted aliases in Math, Matrix, Rot, Sweep and
  dynamics/Position; no host libm call remains in src/
- export DeterministicMath and seedRandom for consumers
- add determinism tests, incl. a free fall matching the analytic solution

All 14 upstream tests still pass (22 total).
2026-09-15 00:52:19 +03:00
Ali Shakiba
93dd64df0f v1.5.0 2026-04-07 15:59:37 +03:30
Ali Shakiba
6ede4f3d2d Publish add-body, add-fixture, add-joint events 2026-04-07 15:16:03 +03:30
Ali Shakiba
86c9079d69 Remove hasVertex0 and hasVertex3 from serialize Edge 2026-04-07 15:15:48 +03:30
Ali Shakiba
7791ea1f1b Remove temp fields from distance-joint serialization 2026-04-07 15:15:40 +03:30
Ali Shakiba
9415379691 Add fixedRotation to body serialize 2026-04-07 15:15:31 +03:30
Ali Shakiba
4fc10a7fee In polygon and chain deserialize use Vec2Value 2026-04-07 15:14:59 +03:30
Ali Shakiba
c96feaccea v1.4.3 2026-02-10 15:31:37 +03:30
Ali Shakiba
0bba3b2911 Bug fix addVec2 2026-02-10 15:30:00 +03:30
Ali Shakiba
f6d90c2703 Cleanup eslint, upgrade dev deps 2026-02-08 23:08:31 +03:30
Ali Shakiba
83e5f622be remove api doc, ignore docs/dist 2026-02-08 20:15:49 +03:30
Ali Shakiba
18a00bdcf6 use vitepress 2026-02-08 20:00:27 +03:30
Ali Shakiba
cdbf302d41 update docs 2025-10-21 14:05:17 -05:00
Ali Shakiba
3b561c1880 fix example 2025-06-06 07:21:41 +03:30
Ali Shakiba
724e410c8f fix example 2025-06-01 21:38:46 +03:30
Ali Shakiba
cbec05b7e8 v1.4.2 2025-06-01 21:33:59 +03:30
Ali Shakiba
9343ffc8ec fix testbed drawing 2025-06-01 21:32:45 +03:30
Ali Shakiba
be9b789942 clean up assert and unused statements 2025-06-01 11:24:41 +03:30
Ali Shakiba
3aee543586 fix testbed page 2025-06-01 11:03:05 +03:30
Ali Shakiba
23e89ec1f7 v1.4.1 2025-05-30 16:16:08 +03:30
Ali Shakiba
d12d0cc9df fix shape name export 2025-05-30 16:14:31 +03:30
Ali Shakiba
54cfa2d206 add setup and teardown to benchmark 2025-05-29 21:14:22 +03:30
Ali Shakiba
37414c7dad v1.4.0 2025-05-26 19:43:18 +03:30
Ali Shakiba
97e4fcd011 change changesets scripts 2025-05-26 19:41:16 +03:30
Ali Shakiba
75ece37751 pretty code 2025-05-26 19:41:12 +03:30
Ali Shakiba
0dcc98b053 split TestbedInterface and Testbed class 2025-05-26 19:41:05 +03:30
Ali Shakiba
e1a271755d mark serialize and deserialize as hidden instead of internal 2025-05-26 17:31:08 +03:30
Ali Shakiba
3446820c88 fix aabb raycast 2025-05-26 17:25:07 +03:30
Ali Shakiba
1999deb142
fix typo in contacts doc 2025-04-28 15:18:15 -05:00
Ali Shakiba
02600898af update docs 2025-04-14 21:28:32 +03:30
Ali Shakiba
ffc8cb316d change local dev testbed url format and handling 2025-04-13 13:24:34 +03:30
Ali Shakiba
f628eabc36
Update limitations.md 2025-02-10 01:31:52 +03:30
Ali Shakiba
6cfb385214 update docs, use object literal 2025-01-29 19:25:02 +03:30
Ali Shakiba
8416d7b516 Add playground link to docs 2024-12-28 02:26:06 +03:30
Ali Shakiba
1c50a3f381 build v1.3.0 2024-12-28 02:03:06 +03:30
Ali Shakiba
ce1c486efa No pointer interaction when mouseForce===0 2024-12-28 02:00:31 +03:30
Ali Shakiba
56193e788c Add DataDriver (experimental) 2024-12-27 22:42:56 +03:30
Ali Shakiba
bb9bb873fc Testbed rendering rewrite 2024-12-27 22:41:01 +03:30
Ali Shakiba
7c400fa896 build v1.2.0 2024-12-24 20:11:59 +03:30
Ali Shakiba
97bb79eb94 Improve queueUpdate 2024-12-24 20:09:56 +03:30
Ali Shakiba
4b06bb31bd Unify createFixture usage in examples 2024-12-24 19:58:07 +03:30
Ali Shakiba
f0127f4fe6
Add world.queueUpdate 2024-12-24 17:41:58 +03:30
Ali Shakiba
5b611d70fb Unify createBody usage in examples 2024-12-24 15:07:16 +03:30
Ali Shakiba
3b496b846c migrate examples to Vec2Value 2024-12-23 18:57:15 +03:30
Ali Shakiba
0b31620212 build v1.1.6 2024-12-23 18:30:56 +03:30
Ali Shakiba
922ff97583 Add static Vec2.normalize 2024-12-23 18:29:40 +03:30
Ali Shakiba
bee0e1609a Change clampVec2 arg to Vec2Value 2024-12-23 18:25:46 +03:30
Ali Shakiba
fe31a9101e fix api docs links 2024-12-20 15:08:27 +03:30
Ali Shakiba
97b1a8387d v1.1.5 2024-12-19 23:15:21 +03:30
Ali Shakiba
fbd0021e30 Un-hidden style field type 2024-12-19 23:13:52 +03:30
Ali Shakiba
50ce8a971a add changesets 2024-12-19 23:12:55 +03:30
Ali Shakiba
bdbac53347 add noEmit to eslint 2024-12-19 23:09:21 +03:30
Ali Shakiba
a1753d5a1d build v1.1.4 2024-12-18 15:24:45 +03:30
Ali Shakiba
a7a62dddd8 update examples 2024-12-18 15:23:07 +03:30
Ali Shakiba
cc7fde175f fix testbed style 2024-12-18 15:21:38 +03:30
Ali Shakiba
e2c850a5d4 allow style in fixture/body/joint def 2024-12-18 15:21:21 +03:30
Ali Shakiba
22541bc6e6 migrate examples to ts 2024-12-18 14:18:45 +03:30
Ali Shakiba
9604296ed3 rename examples to .ts 2024-12-18 14:18:44 +03:30
Ali Shakiba
c11f0493f6 build v1.1.3 2024-12-18 14:17:43 +03:30
Ali Shakiba
7d09b35cea update eslint 2024-12-18 13:02:16 +03:30
Ali Shakiba
fa2112ffc1 add clampVec2 2024-12-18 13:00:20 +03:30
Ali Shakiba
3cf402108c update optional joint props type 2024-12-18 13:00:14 +03:30
Ali Shakiba
c08580cd36 fix typedoc 2024-12-15 14:41:31 +03:30
Ali Shakiba
92ce0d1080 examples: use vite-alias planck, and lint pretty 2024-12-15 13:30:32 +03:30
Ali Shakiba
71f4e5c286 v1.1.2: add body.setTransform(xf) signature 2024-12-03 22:19:17 +03:30
Ali Shakiba
0e58a85d1a v1.1.1: fix serializing chain with loop 2024-11-30 23:31:39 +03:30
Ali Shakiba
b4d7ffa0ee v1.1.0 2024-11-24 09:31:10 +03:30
Ali Shakiba
cbaf2299c4 simplify license notice 2024-11-23 16:32:23 +03:30
Ali Shakiba
e5048fe80d
v1.1.0-alpha: vite build migration 2024-11-23 16:08:24 +03:30
Ali Shakiba
514a34b23f
remove year from license 2024-11-23 12:46:32 +03:30
Ali Shakiba
d87394b2e4
bump actions/checkout@v4 and actions/setup-node@v4 2024-11-22 22:26:59 +03:30
Ali Shakiba
9930e2174d lint testbed 2024-11-22 13:24:52 +03:30
Ali Shakiba
a4fbc31180 fix collide circle types 2024-11-22 13:23:28 +03:30
Ali Shakiba
733e30b659 v1.0.9: fix exported internal.Settings and hide internal, stats 2024-11-19 12:57:40 +03:30
Ali Shakiba
b6883d0723 Fix api index 2024-11-18 17:54:19 +03:30
Ali Shakiba
0e0bef9c1e v1.0.8: lint 2024-11-18 11:29:36 +03:30
Ali Shakiba
55a9b170d2 Build v1.0.7: testbed minor update 2024-11-17 23:03:44 +03:30
Ali Shakiba
50ff5fd0f9 add lineWidth to style 2024-11-10 19:01:27 +03:30
Ali Shakiba
4cd1883c2f clean up testbed class 2024-11-10 19:01:21 +03:30
Ali Shakiba
56f0d71814 add eslint quotes and semi rules 2024-10-27 23:41:00 +03:30
Ali Shakiba
404ebd14e2
exclude examples from tsconfig 2024-10-12 14:09:31 +03:30
Ali Shakiba
a9f23fa414 Fix wheel-joint doc 2024-09-30 23:53:02 +03:30
Ali Shakiba
9e20146bc5 Build v1.0.6: use es5 stage.js 2024-09-30 23:38:39 +03:30
Ali Shakiba
fb79f188fa
Update wheel-joint.md 2024-09-30 22:27:14 +03:30
Ali Shakiba
4b6d6ec0ab build v1.0.5 2024-08-17 01:40:15 +03:30
Ali Shakiba
363f566ce3 mv stage-js to peerDependencies 2024-08-17 01:40:15 +03:30
ArShAm
11d3966c1a
add utility iframe messenger to docs 2024-08-13 15:09:31 +03:30
Wojciech Maj
8ef74eca53 Remove unnecessary dependency on is-core-module 2024-08-09 22:41:03 +03:30
Ali Shakiba
ca98be96ae update docs 2024-07-23 23:10:43 +03:30
Ali Shakiba
0d2efe6ae0 replace vec2 with vec2value in the api, update docs 2024-05-23 23:07:21 +03:30
Ali Shakiba
293c0c6d1d update docs 2024-05-13 16:44:09 +03:30
James Stanley
fe829184b3 Example renderer: refer to this.world instead of global world 2024-05-02 14:39:39 +03:30
Ali Shakiba
09cf743d5e clean up docs 2024-05-02 12:50:37 +03:30
Ali Shakiba
3d9286bd81 migrate docs to vocs 2024-05-02 00:05:28 +03:30
James Stanley
e8e3ff9b3c
Documentation cleanup (#278)
documentation cleanup
2024-04-30 22:17:38 +03:30
James Stanley
fc913b1f22 Don't dereference null pointer if elements don't exist 2024-04-29 20:30:22 +03:30
Ali Shakiba
7caf1509c2 add docs pages 2024-04-29 20:07:45 +03:30
Ali Shakiba
f089bb0c66 use new stage version 2024-04-24 23:38:42 +03:30
Ali Shakiba
34e256609a update ray cast docs and minor bug fix 2024-04-01 16:55:16 +03:30
Ali Shakiba
2b0dd3d0e9 build 1.0.2 2024-03-13 16:49:16 +03:30
Ali Shakiba
4fc3e0325d clean up serializer code 2024-03-12 16:00:30 +03:30
Ali Shakiba
c2c482fd8b fix types 2024-03-12 16:00:30 +03:30
Ali Shakiba
6de9126f75 build 1.0.1 2024-01-01 20:01:49 -08:00
Ali Shakiba
af22d7c3d1 minor fix api visibility 2024-01-01 20:01:39 -08:00
Ali Shakiba
282c3fac45 build v1.0.0 2023-12-30 16:09:06 -08:00
Ali Shakiba
041726a83f build v1.0-beta.20 2023-12-26 19:39:48 -08:00
Ali Shakiba
b205657281 normalize joints _reset 2023-12-26 19:37:24 -08:00
Ali Shakiba
3e1f0bc74e add appData 2023-12-26 19:09:49 -08:00
Ali Shakiba
0a2556722b build beta.18 2023-12-25 19:04:39 -08:00
Ali Shakiba
ba52e0c9ff rename matrix functions 2023-12-25 18:50:41 -08:00
Ali Shakiba
eade1934a0 build v1.0.0-beta.18 2023-12-24 23:22:20 -08:00
Ali Shakiba
1ea2ddd477 update docs 2023-12-24 23:19:11 -08:00
Ali Shakiba
4de71d9038 build v1.0.0-beta.17 2023-12-24 22:33:09 -08:00
Ali Shakiba
1bbdadc890 add style for debugging 2023-12-20 23:24:43 -08:00
Ali Shakiba
dc63010b82 add Testbed.start() shortcut 2023-12-20 22:52:01 -08:00
Ali Shakiba
4830ce50cf use Vec2Value interface in the api 2023-12-20 22:48:53 -08:00
Ali Shakiba
3c6390079f update testbed types 2023-12-20 22:47:10 -08:00
Ali Shakiba
a714319f6c fix json schema 2023-12-20 22:35:09 -08:00
Oliver Zell
80803cbca4
fix: fix numerical stability for area weighted centroid 2023-12-20 21:00:57 +01:00
Ali Shakiba
820f6105d7 fix setMassData 2023-09-09 11:54:00 -07:00
Oliver Zell
3efc9234ff
feat: set sideEffects to false for planck.js (#262) 2023-08-28 18:58:54 +02:00
Ali Shakiba
1aa9fb300a remove unfinished rope 2023-08-26 21:33:07 -07:00
Ali Shakiba
fcfec569be clean up step functions 2023-08-26 21:25:45 -07:00
Ali Shakiba
6b3113eb57 build v1.0.0-beta.15 2023-08-26 16:42:08 -07:00
Ali Shakiba
7f82dc49f3 fix api doc 2023-08-26 16:41:20 -07:00
Ali Shakiba
83e71a3339 add npm preflight 2023-08-26 15:43:36 -07:00
Ali Shakiba
b42b76f4bc update api-doc 2023-08-26 15:43:19 -07:00
Ali Shakiba
6ab76c7b21 fix example 2023-08-26 15:42:09 -07:00
Ali Shakiba
71cb8243bf use vec2value in joints api 2023-08-26 15:41:59 -07:00
Ali Shakiba
4a54360b54 build v1-beta.14 2023-08-26 11:56:32 -07:00
Ali Shakiba
ae249043ed call refilter after updating filter data 2023-08-26 11:51:58 -07:00
Ali Shakiba
f190017c19 update WorldRayCastCallback doc 2023-08-24 23:44:58 -07:00
Ali Shakiba
25074e5ff3
Update README.md 2023-08-24 23:24:44 -07:00
Ali Shakiba
2edd8a14ed add js-doc for rot fields 2023-08-24 17:26:02 -07:00
Ali Shakiba
ee8785ff30 build v1-beta.13 2023-08-24 12:29:59 -07:00
Ali Shakiba
549e597d11 add template testbed example 2023-08-24 12:28:21 -07:00
Ali Shakiba
cb7052f1c1 fix velocity shift on mass data change 2023-08-24 12:26:43 -07:00
Ali Shakiba
57d8126998 remove old build files 2023-08-24 11:55:03 -07:00
Ali Shakiba
33eabb680c build v1-beta.12 2023-08-23 21:58:00 -07:00
Ali Shakiba
a29feef14f functional change from box2d #582 2023-08-23 21:57:17 -07:00
Ali Shakiba
cfc9102453 awake body on setTransform 2023-08-23 21:53:37 -07:00
Ali Shakiba
9d86ecc65b convert MassData to interface 2023-08-23 02:34:55 -07:00
Ali Shakiba
5b96d954b7 update Body.shouldCollide docs 2023-08-23 00:42:52 -07:00
Ali Shakiba
d43d2c1919 update api doc 2023-08-22 12:40:19 -07:00
Ali Shakiba
e957136800 fix typo in Settings 2023-08-22 12:23:12 -07:00
harun
a69b20475a
docs: Update Body class documentation (#259)
Added information about the setType and getType methods in the Body class documentation.
2023-08-20 09:28:08 -07:00
Ali Shakiba
a971fb7908 refactor testbed api 2023-08-20 09:23:47 -07:00
Ali Shakiba
ce047fa2e9 build v1.0-beta.9 2023-08-16 19:50:00 -07:00
Ali Shakiba
edd5883795 set v1-beta to umd, with es option 2023-08-16 19:43:31 -07:00
Ali Shakiba
80a5693796 refactor math functions 2023-08-16 19:43:31 -07:00
Ali Shakiba
48f873e6ea clean up revolute joint 2023-08-16 19:42:58 -07:00
Ali Shakiba
c7e93407f5 testbed use canvas drawing for joints 2023-08-16 19:42:58 -07:00
Ali Shakiba
5dafb74b72 fix fixture proxies reactivation 2023-08-16 19:41:42 -07:00
Ali Shakiba
1d77eb8e90 update api docs and examples 2023-08-14 13:59:23 -07:00
Ali Shakiba
2b297519d9 update build v1-beta.8 2023-08-11 09:54:13 -07:00
Ali Shakiba
46aea292e5 add lengthUnitsPerMeter to settings 2023-08-11 09:40:52 -07:00
Ali Shakiba
277f60eb13 update build v1-beta.7 2023-08-11 08:15:49 -07:00
Ali Shakiba
6090cc44a7 initialize DistanceInput 2023-08-11 08:11:10 -07:00
Ali Shakiba
b7ce8be80e
optimize matrix functions (#255) 2023-08-10 20:55:02 -07:00
Ali Shakiba
9bc1bc03dc fix node benchmark 2023-08-09 23:53:44 -07:00
Oliver Zell
652eb41563
test: switch to vitest (#252)
* test: switch to vitest

* docs: exclude tests from typedocs

* chore: remove ts-node dependency

* test: remove chai dependency
2023-08-07 13:32:29 -07:00
Ali Shakiba
e942302745 add git info to benchmark page 2023-08-06 23:41:04 -07:00
Ali Shakiba
322bdaf42b improve memory allocation 2023-08-06 22:20:43 -07:00
Ali Shakiba
500bb9c71e
fix benchmark link 2023-08-06 22:13:14 -07:00
Ali Shakiba
3aa18f07b6 add benchmark 2023-08-06 21:56:56 -07:00
Ali Shakiba
2ca89b0ad2 update stage.js version 2023-08-06 19:55:25 -07:00
Oliver Zell
849f0e7f9b fix: fix testbed findBody function 2023-08-06 19:29:11 -07:00
Ali Shakiba
1a4b19d3ee fix build, js files default to esm 2023-08-06 19:16:45 -07:00
Ali Shakiba
c2877d248c update pool class 2023-08-06 12:22:21 -07:00
Ali Shakiba
0d4e72564a remove duplicate type 2023-08-05 21:38:22 -07:00
Oliver Zell
a904b1fdb3
Merge pull request #247 from piqnt/shape-cast
feat: add ShapeCast function
2023-08-05 10:15:42 +02:00
Oliver Zell
05352bd7b6 docs: make ShapeCast example more interesting 2023-08-05 10:14:42 +02:00
Oliver Zell
bbcdc54da4 feat: add ShapeCast function 2023-08-05 09:29:46 +02:00
Oliver Zell
65eaf4d858 refactor: use early returns 2023-08-04 16:27:56 -07:00
Oliver Zell
c76525ba24 fix: fix anchor A formula for MotorJoint to include the offset 2023-08-04 16:27:56 -07:00
Oliver Zell
5ed20efedb docs: added documentation of damping parameter units 2023-08-04 16:27:56 -07:00
Oliver Zell
09b41946e3 refactor!: remove getVertex method on shapes 2023-08-04 16:27:56 -07:00
Oliver Zell
bfd859669b feat: body.setAwake now resets the sleep timer even if the body is awake 2023-08-04 16:27:56 -07:00
Oliver Zell
c7e33ee2d1 refactor: polygonal radius clarity 2023-08-04 16:27:56 -07:00
Oliver Zell
af01b2921d refactor: remove dead code 2023-08-04 16:27:56 -07:00
Oliver Zell
3ccbd84dc4 refactor: minor refactorings 2023-08-04 16:27:56 -07:00
Ali Shakiba
39a983b7c5
make build backward compatible (#245) 2023-08-01 14:30:08 -07:00
Ali Shakiba
cbfba8ccc8
typescript testbed and vite build (#244) 2023-07-31 21:47:06 -07:00
Ali Shakiba
499075d715
refactor exports and add esm export (#243) 2023-07-31 19:35:10 -07:00
Ali Shakiba
c8e7407241
update links 2023-07-28 19:02:24 -07:00
Ali Shakiba
f41da62e94
update links 2023-07-28 19:00:59 -07:00
Ali Shakiba
836cdb0d5f fix typo 2023-07-28 02:05:59 -07:00
harun
2d69c7727b Update OneSidedPlatform.js
Added comments for clarification of if(0) { ... } else { ... } usage
2023-07-23 22:34:22 -07:00
Ali Shakiba
298d7dd6d4
move docs to new site 2023-07-09 01:06:21 -07:00
Jean Saint Fleur
9ae39ce602 remove userData exception when he has falsy value "0" 2023-07-06 18:14:37 -07:00
Ali Shakiba
26b6185f95
remove install instruction 2023-07-04 23:55:51 -07:00
Ali Shakiba
29d2462eb3
fix DistanceJoint typing 2023-06-13 15:51:55 -07:00
Ali Shakiba
1702647e06 move initialization after factory call check 2023-06-12 11:17:29 -07:00
Ali Shakiba
889236ea3c move build-utils 2023-06-09 08:19:20 -07:00
Ali Shakiba
361199edae update license and changes 2023-06-09 08:19:20 -07:00
Ali Shakiba
04e9f70561 remove babel 2023-06-09 08:19:20 -07:00
Ali Shakiba
83eb157c73
remove bower.json 2023-06-08 18:09:06 -07:00
Ali Shakiba
83e3e33295
Update README.md 2023-06-02 23:08:58 -07:00
Oliver Zell
3b262124ce alpha.4 2022-03-29 12:23:36 +02:00
Oliver Zell
3fef1b9423
Merge pull request #212 from matthewvroman/hotfix/prismatic-joint-constraints
Include missing instantiation of m_K matrix
2022-03-04 19:53:23 +01:00
Matt Vroman
8c9c84220c Merge branch 'master' of https://github.com/shakiba/planck.js into hotfix/prismatic-joint-constraints 2022-03-03 18:50:59 -08:00
Matt Vroman
0015f7f50e Include missing instantiation of m_K matrix 2022-03-03 18:50:03 -08:00
Oliver Zell
158e5eb65c
Merge pull request #213 from shakiba/clean-up 2022-02-20 08:30:49 +01:00
Oliver Zell
8c61838d08 delete webpack config 2022-02-19 16:48:46 +01:00
Oliver Zell
22549b433a remove nodemon dependency 2022-02-19 16:44:17 +01:00
Oliver Zell
16995c4e4e fix test coverage scripts 2022-02-19 16:36:38 +01:00
Oliver Zell
f305373809 migrate to @rollup/plugin-babel 2022-02-19 16:00:02 +01:00
Oliver Zell
1229528e05 alpha.3 2022-01-23 09:51:49 +01:00
Oliver Zell
4c759066ea
Merge pull request #211 from shakiba/types-fix
Types fix
2022-01-23 09:43:37 +01:00
Oliver Zell
94b4d42dc4 Merge branch 'master' into types-fix 2022-01-21 20:42:02 +01:00
Oliver Zell
ac608af813 fix styling 2022-01-21 20:33:11 +01:00
Oliver Zell
159a3f9c4c export ContactImpulse type 2022-01-21 20:29:48 +01:00
Oliver Zell
95e155c282 declare static properties on Manifold directly 2022-01-21 20:03:48 +01:00
Oliver Zell
c10131b107
Merge pull request #210 from shakiba/reduce-function-overloading
Reduce function overloading
2022-01-20 20:16:21 +01:00
Oliver Zell
35717114ea make vec2.set and transform.set backward compatible 2021-12-23 19:42:08 +01:00
Oliver Zell
dcb32dd60c use Num in method names 2021-12-23 19:35:22 +01:00
Oliver Zell
52bd011de0 remove overloading of transform.set 2021-12-18 10:58:31 +01:00
Oliver Zell
e12acfe42b remove usage of overloaded functions in Rot 2021-12-18 10:51:55 +01:00
Oliver Zell
df092ddfeb remove usage of Vec3 object constructor 2021-12-17 20:55:20 +01:00
Oliver Zell
57b4379809 remove function overloads in Vec2 2021-12-17 20:50:53 +01:00
Oliver Zell
fd16eba95c
Merge pull request #202 from shakiba/types-fix
split class declarations into interface and object
2021-11-20 16:27:32 +01:00
Oliver Zell
cb32abaff6 fix typedoc 2021-11-20 16:16:20 +01:00
Oliver Zell
4604db1dfb exclude .test-d.ts files from typedoc 2021-11-20 14:13:25 +01:00
Oliver Zell
6d2fb83af3 Merge branch 'master' into types-fix 2021-11-20 13:46:24 +01:00
Oliver Zell
23e8d7b3fc add note to ts issue 2021-11-20 13:31:37 +01:00
Oliver Zell
a96bb35b8d
Merge pull request #206 from shakiba/eslint
migrate to eslint
2021-11-20 11:35:13 +01:00
Oliver Zell
116b5bc6c7 add types test 2021-11-03 20:16:39 +01:00
Oliver Zell
b10aace4d7 migrate to eslint 2021-10-31 15:18:32 +01:00
Oliver Zell
1685b7f367 use as const syntax 2021-10-30 22:23:03 +02:00
Oliver Zell
a4b5ce2b11 preserve constructor comments in declaration transformation 2021-10-30 21:56:10 +02:00
Dylan Greene
cb9fb5f27a Set awake param to true by default 2021-10-15 23:20:13 -07:00
Oliver Zell
cb585d699d preserve comments in declaration transformation 2021-10-10 17:10:00 +02:00
Oliver Zell
238fa1e8c1 use typescript guards in declaration transformer 2021-10-04 12:04:11 +02:00
Oliver Zell
cb9ec02f44 use name of nodes directly 2021-10-04 11:28:55 +02:00
Oliver Zell
97c029dff8 split class declarations into interface and object 2021-09-24 20:53:08 +02:00
Ali Shakiba
01dce1c8f4
Update README.md 2021-05-27 20:02:55 -07:00
Ali Shakiba
e12818409a remove abstract deserialize and serialize from Join/Shape 2021-05-11 22:00:37 -07:00
Ali Shakiba
d88d1498d5 clean up _deserialize typedef 2021-05-11 21:32:43 -07:00
Ali Shakiba
2ddac881d4 fix aabb 2021-05-11 20:53:07 -07:00
Ali Shakiba
7fd9c8605e tslint props typedef 2021-05-11 20:14:11 -07:00
Ali Shakiba
59c714c3ca mark toStrings as internal 2021-05-11 19:22:07 -07:00
Ali Shakiba
b1d7cd786c clean up isValid 2021-05-11 18:57:12 -07:00
Ali Shakiba
3d92e64398 generate typedocs 2021-05-11 18:30:36 -07:00
Ali Shakiba
c255e2aa41 mark Body and Fixture constructor as internal 2021-05-11 18:28:41 -07:00
Ali Shakiba
acc3bd8330 typescript tests 2021-05-11 16:03:26 -07:00
Ali Shakiba
00c08cf986 enable tslint typedef for functions 2021-05-08 18:26:16 -07:00
Ali Shakiba
25bb24cb04 update typedocs 2021-05-08 11:13:58 -07:00
Ali Shakiba
1523746162 clean up chain/edge next/prev vertex methods 2021-05-08 11:05:41 -07:00
Ali Shakiba
641bcd930f clean up types and docs 2021-05-08 10:57:45 -07:00
Ali Shakiba
f39e62ec1c alpha.2 2021-05-07 18:32:14 -07:00
Ali Shakiba
2597dc1897
update package name to planck (#195)
update package name
2021-05-07 16:44:05 -07:00
Ali Shakiba
ba823df7fc
update readme 2021-05-07 16:01:06 -07:00
Ali Shakiba
3f89cb77bc clean up package 2021-05-06 16:22:43 -07:00
Ali Shakiba
d28ef22c51 add testbed to docs 2021-05-06 16:22:31 -07:00
Ali Shakiba
eb47c5c1e4 update test script patch 2021-05-06 16:22:12 -07:00
Ali Shakiba
5a917f0bb1
Migrate Testbed to TypeScript (#191)
migrate testbed to typescript
2021-05-05 14:55:10 -07:00
Oliver Zell
a7b3fc766b
Merge pull request #188 from shakiba/fix-breakable-example
Fix breakable example
2021-05-04 19:30:02 +02:00
Oliver Zell
96eb5fb546 Merge branch 'master' into fix-breakable-example 2021-05-04 19:27:47 +02:00
Ali Shakiba
cc121fb192
Add build action 2021-05-02 19:42:23 -07:00
Ali Shakiba
cc2ddee17a
Update README.md 2021-05-02 18:40:36 -07:00
Ali Shakiba
9a212b0832 don't include generated declarations in api doc 2021-05-02 17:19:54 -07:00
Ali Shakiba
8127f05df5 fix testbed 2021-05-02 16:25:37 -07:00
Ali Shakiba
357956f66b use whitelist for declarationTransformer 2021-05-02 16:11:49 -07:00
Ali Shakiba
b78eb45745 minor fix ts 2021-05-02 15:23:36 -07:00
Oliver Zell
c1149fc65e Merge branch 'master' into fix-breakable-example 2021-05-01 18:51:54 +02:00
Oliver Zell
132bda2371 build dist files 2021-05-01 18:37:09 +02:00
Ali Shakiba
1b3d313372 convert Settings to class 2021-04-30 16:24:24 -07:00
Oliver Zell
c3bc2986f3 initialize normals and tangents in ContactImpulse 2021-04-30 20:54:30 +02:00
Ali Shakiba
6a5d3be431 tag serializer fuctions as internal 2021-04-30 10:56:21 -07:00
Ali Shakiba
3ede11b420 clean up body def docs 2021-04-23 21:05:37 -07:00
Ali Shakiba
2a3930dc0b remove addPair 2021-04-23 21:01:46 -07:00
Oliver Zell
63e787bb7c fix this binding 2021-04-23 21:01:46 -07:00
Ali Shakiba
696ed13eef
Create README.md 2021-04-17 11:09:11 -07:00
Oliver Zell
cfcb332665
Merge pull request #169 from shakiba/typescript
Migrate to TS
2021-04-16 17:11:31 +02:00
Oliver Zell
3aab68f578 Merge branch 'typescript' of https://github.com/shakiba/planck.js into typescript 2021-04-16 17:10:20 +02:00
Oliver Zell
bdc1c848d2 generate API docs 2021-04-16 17:10:15 +02:00
Oliver Zell
799dc7326c
Merge branch 'master' into typescript 2021-04-16 17:04:06 +02:00
Oliver Zell
7e469c4d4b add testbed to types 2021-04-15 20:04:02 +02:00
Oliver Zell
9b7f55c676 generate function declarations in type definitions 2021-04-14 22:16:57 +02:00
Oliver Zell
2696078864
Merge pull request #173 from shakiba/rollup-plugin-ts
Generate declaration file
2021-04-13 20:00:16 +02:00
Oliver Zell
6d0bbc5143 fix redeclarations of Joint in typings 2021-04-13 19:51:59 +02:00
Oliver Zell
8644019fd2 update dist files 2021-04-12 08:05:02 +02:00
Oliver Zell
fa1988a4a5 generate declaration file on build 2021-04-11 11:39:33 +02:00
Oliver Zell
e7d79dd36d use rollup-plugin-ts 2021-04-11 11:37:19 +02:00
Ali Shakiba
a360a037df change version to v1.0 2021-04-10 17:38:41 -07:00
Ali Shakiba
74bc4e8f74 cleanup types and docs 2021-04-10 17:36:20 -07:00
Ali Shakiba
4b5d9d79b9 optimize contact impulse reporting 2021-04-10 17:34:57 -07:00
Oliver Zell
d3141c289f minor TS fixes 2021-04-10 13:45:04 +02:00
Oliver Zell
61b7585bc2 fix TS error in PolygonShape 2021-04-10 13:36:52 +02:00
Oliver Zell
ea7accf940 fix rollup build 2021-04-10 13:33:50 +02:00
Ali Shakiba
6813d89e66 reorg files, lib to src 2021-03-28 23:57:16 -07:00
Ali Shakiba
d188285ad9 cleanup types and docs 2021-03-28 23:13:16 -07:00
Ali Shakiba
67a2978edb merge math d.ts 2021-03-28 23:08:45 -07:00
Ali Shakiba
73978694e2 improve types 2021-03-28 15:38:57 -07:00
Ali Shakiba
373abafdf5 auto-fix lint, and clean up comments 2021-03-28 15:25:55 -07:00
Ali Shakiba
32313e917f fix import 2021-03-28 15:22:23 -07:00
Ali Shakiba
3ba5d1bda7 auto-fix lint, and clean up docs 2021-03-28 15:17:45 -07:00
Ali Shakiba
830815a22b minor fix for joints 2021-03-28 15:07:44 -07:00
Ali Shakiba
3fb115bad9 typescript rope 2021-03-28 14:46:49 -07:00
Ali Shakiba
cfee322b90 typescript shape collision files 2021-03-28 14:33:09 -07:00
Ali Shakiba
2500d559cf cleanup types 2021-03-28 14:18:16 -07:00
Oliver Zell
ea06f27da2 set ts lib to ES2015 for Object.assign 2021-03-28 17:35:30 +02:00
Oliver Zell
97ac52a6f2 ts fixes for shape/* 2021-03-28 15:53:03 +02:00
Oliver Zell
e4f52f319e typescript joint/* 2021-03-28 15:37:52 +02:00
Ali Shakiba
02901c554f cleanup types 2021-03-28 01:22:28 -07:00
Ali Shakiba
4964479bf2 ts config 2021-03-28 00:31:56 -07:00
Ali Shakiba
c32a1e228d typescript serializer 2021-03-27 22:38:50 -07:00
Ali Shakiba
56445ed2e6 lint auto-fix 2021-03-27 22:28:04 -07:00
Ali Shakiba
fc8a1c4eaf typescript dynamics 2021-03-27 18:22:31 -07:00
Ali Shakiba
bf71dd7e5e declare debug/assert types 2021-03-27 16:07:26 -07:00
Ali Shakiba
564c486002 typescript collision and util 2021-03-27 15:43:15 -07:00
Oliver Zell
98cc48f9d8 typescript Shape classes 2021-03-27 15:51:40 +01:00
Oliver Zell
5e476a7abb add empty tsconfig 2021-03-27 15:51:03 +01:00
Ali Shakiba
9515e4c72c typescript common/* 2021-03-27 00:48:21 -07:00
Ali Shakiba
c028854af2
Update README.md 2021-03-26 22:04:05 -07:00
Ali Shakiba
f9a12c1879 typescript Sweep, Matt22, Matt33 2021-03-26 21:49:29 -07:00
Ali Shakiba
f14921dffb typescript index, Settings 2021-03-26 21:49:29 -07:00
Ali Shakiba
1cc26433a0 add typescript to build 2021-03-26 18:36:39 -07:00
Ali Shakiba
abfd3390ea
Update README.md 2021-03-21 17:30:24 -07:00
Ali Shakiba
e188b6c5b2
Update README.md 2021-03-21 14:46:25 -07:00
Ali Shakiba
86608052ca
Update README.md 2021-03-21 14:27:20 -07:00
Ali Shakiba
775b338630
Migrate to ESM and Rollup (#168)
migrate to esm and rollup
2021-03-21 14:09:03 -07:00
Ali Shakiba
81614c1600
Update README.md 2021-03-15 20:57:52 -07:00
Ali Shakiba
22141d72ec small refactoring in d.ts 2021-03-13 21:44:35 -08:00
Ali Shakiba
6b71ae175d use Object.create 2021-03-06 15:31:29 -08:00
Ali Shakiba
ec47900ed8 fix serializer 2021-03-06 15:19:30 -08:00
Ali Shakiba
ec1ef8cd99 v0.3.28 2021-03-05 16:59:46 -08:00
Ali Shakiba
09a54dbd20 add root files to npm 2021-03-05 16:59:13 -08:00
Ali Shakiba
1064476440 v0.3.27 2021-02-25 22:04:08 -08:00
Ali Shakiba
c285ddd875 fix settings type 2021-02-24 22:08:18 -08:00
Ali Shakiba
5917d6bdfb bug fix 2021-02-24 18:38:03 -08:00
Ali Shakiba
f9b134cf97
Merge pull request #163 from shakiba/refactor-types
refactor index.d.ts
2021-02-24 18:35:46 -08:00
Ali Shakiba
69ba8b2a89 move settings to main namespace 2021-02-24 18:34:44 -08:00
Ali Shakiba
e572856b6a fix typo in types 2021-02-24 18:07:53 -08:00
Ali Shakiba
32a96540b4 refactor index.d.ts 2021-02-24 00:03:36 -08:00
Ali Shakiba
4afb814435 fix world ts constructor signature 2021-02-07 23:24:46 -08:00
Ali Shakiba
047cd23a85 v0.3.26 2021-02-07 19:04:16 -08:00
Ali Shakiba
211b04e2da add pre-step and post-step events to World 2021-02-07 19:03:01 -08:00
Ali Shakiba
feaa5a6128 add testbed find placeholders 2021-02-07 17:43:01 -08:00
Ali Shakiba
48de6c1faa v0.3.25 2021-02-07 13:42:48 -08:00
Ali Shakiba
2e3b2cbf22 fix typo 2021-02-07 13:42:47 -08:00
Ali Shakiba
900191d9da fix serializer 2021-02-07 13:42:47 -08:00
Ali Shakiba
3b8b172e40
Update README.md 2021-02-03 19:20:00 -08:00
Ali Shakiba
a54383ee8b
Update README.md 2021-02-01 20:21:48 -08:00
Ali Shakiba
380783dd3f
Update API.md 2021-02-01 20:20:41 -08:00
Ali Shakiba
9b687ecb6d
Update README.md 2021-01-30 16:03:34 -08:00
Ali Shakiba
ec0f326856
Update README.md 2021-01-30 15:22:19 -08:00
Ali Shakiba
dec239dd02
Update README.md 2021-01-28 22:20:08 -08:00
Ali Shakiba
df27e76fa0
Update README.md 2021-01-28 22:02:15 -08:00
Ali Shakiba
eb3465b5d2
Update README.md 2021-01-28 21:46:12 -08:00
Ali Shakiba
4951c667b7 add HelloWorld 2021-01-27 01:27:42 -08:00
Ali Shakiba
e1cc75327c v0.3.24 2021-01-25 22:53:14 -08:00
Ali Shakiba
fb058eec8d remove unused fields from testbed type 2021-01-25 22:48:47 -08:00
Ali Shakiba
e117b2fd6c update license 2021-01-25 22:41:21 -08:00
Ali Shakiba
14dda6d63c update readme 2021-01-25 22:41:06 -08:00
Ali Shakiba
f90dd8c74a fix serializer 2021-01-21 21:10:14 -08:00
Ali Shakiba
bee82201a5
Merge pull request #156 from zOadT/master
embed standard Math in typings
2021-01-16 10:53:03 -08:00
Oliver Zell
016289f614 embed standard Math in typings 2021-01-16 16:47:47 +01:00
Ali Shakiba
c72e7bde61
Update README.md 2021-01-12 17:49:12 -08:00
Ali Shakiba
f63462302b update readme with wiki link 2021-01-11 20:37:42 -08:00
Ali Shakiba
152002a8ae move api docs to docs/api 2021-01-11 20:32:57 -08:00
Ali Shakiba
ed0360436d refactor fixture 2021-01-11 20:25:29 -08:00
Ali Shakiba
72e4e7ad40 make chain setNextVertex setPrevVertex 2021-01-11 20:25:17 -08:00
Ali Shakiba
19e4dc0d53 remove stepCount from world 2021-01-11 20:25:10 -08:00
Ali Shakiba
cff5250417 v0.3.22 2021-01-07 17:15:09 -08:00
Ali Shakiba
7b07c36dff add shape to serializer ref types 2021-01-07 17:09:24 -08:00
Ali Shakiba
e96af44c8e add bullet to serializer 2021-01-07 17:09:24 -08:00
Ali Shakiba
238d47b285 change library target to umd 2021-01-07 17:09:23 -08:00
Ali Shakiba
8ef09a649f serialize to json instead of string 2021-01-07 17:09:23 -08:00
Ali Shakiba
4df04f0e36 add chain reset 2021-01-07 17:09:23 -08:00
Ali Shakiba
43ddb9d320 improve join serializer 2021-01-07 17:09:23 -08:00
Ali Shakiba
2dd37b969f bug fix chain shape 2021-01-07 17:09:23 -08:00
Ali Shakiba
0199983f58
Update README.md 2021-01-06 00:07:27 -08:00
Oliver Zell
a1d7030f6e
Merge pull request #153 from zOadT/master
Fix #152
2020-11-13 19:35:29 +01:00
Oliver Zell
c5bd8c9571 export Shape interface in typings 2020-11-09 18:18:16 +01:00
Oliver Zell
d2b9c86c84
Merge pull request #148 from zOadT/master
Fix #147
2020-10-10 08:25:19 +02:00
Oliver Zell
0713e6bd4f split joint classes in static and non-static interfaces again 2020-10-09 15:47:11 +02:00
Oliver Zell
db55b9e20e fix optional parameters in types of joint definitions 2020-10-09 14:55:32 +02:00
Oliver Zell
9fc64b8c10
Merge pull request #146 from zOadT/master
Fix #144
2020-10-05 17:00:55 +02:00
Oliver Zell
c86b574640 split shape classes in static and non-static interface again 2020-09-27 16:25:18 +02:00
Oliver Zell
70aee9feff make properties of FixtureOpt optional in typings 2020-09-27 16:03:18 +02:00
Oliver Zell
6e9af37223
Merge pull request #3 from shakiba/master
merge master
2020-09-27 15:07:57 +02:00
Ali Shakiba
838eba9d8f
Update README.md 2020-09-25 22:01:36 -07:00
Ali Shakiba
f5777884f5 v0.3.21 2020-08-23 18:55:51 -07:00
Ali Shakiba
c40d9190d7 fix shape types 2020-08-23 18:54:15 -07:00
Oliver Zell
dadf0629af
Merge pull request #141 from bystrano/patch-1
fix a typo in a type declaration
2020-08-23 20:34:33 +02:00
bystrano
6322496688
fix typo 2020-08-23 17:56:45 +02:00
Ali Shakiba
4b7564b44f
Merge pull request #135 from zOadT/master
Add some serializers for joints
2020-08-19 00:42:18 -07:00
Ali Shakiba
f82bcf4cee
Merge pull request #140 from Feavy/master
Great, thanks!
2020-08-16 20:38:37 -07:00
Feavy
8e9e020119 Fixed shapes' creation function declaration in TypeScript definition 2020-08-16 21:49:07 +02:00
Ali Shakiba
6d99866214 remove internal fields from doc 2020-08-03 20:19:01 -07:00
Ali Shakiba
038d4250bc v0.3.21 2020-08-02 13:54:46 -07:00
Ali Shakiba
be43ac39b2 remove doc from serializer 2020-08-02 13:46:16 -07:00
Ali Shakiba
2a79ae0d55 add callback to serializer 2020-08-02 13:46:16 -07:00
Ali Shakiba
11afb0278c add setter for fixture filters 2020-08-02 13:46:16 -07:00
Oliver Zell
8cbb48dfae keep m_constant in GearJoint serializer 2020-08-02 09:33:02 +02:00
Oliver Zell
e66588e8c3 add GearJoint serializer 2020-08-02 09:20:47 +02:00
Ali Shakiba
c879d3aead
Update README.md 2020-07-28 20:30:27 -07:00
Ali Shakiba
4697668f95 fix doc links 2020-07-28 20:27:37 -07:00
Ali Shakiba
9a1fbe4d34
Merge pull request #138 from shakiba/api-doc
Update Typescript Definitions
2020-07-28 20:23:33 -07:00
Ali Shakiba
9b2a46bed7 update docs 2020-07-28 20:21:55 -07:00
Ali Shakiba
39a42f0c12 use classes for types 2020-07-28 20:16:19 -07:00
Ali Shakiba
046ec8fcd3
Update README.md 2020-07-27 00:21:50 -07:00
Ali Shakiba
6a2d470783 remove old doc 2020-07-27 00:15:36 -07:00
Ali Shakiba
2f82b369fd update typedoc 2020-07-27 00:14:18 -07:00
Ali Shakiba
4d56b067a8 v0.3.20 2020-07-26 22:53:47 -07:00
Ali Shakiba
f836481831 bug fix chain serialize 2020-07-26 22:53:47 -07:00
Ali Shakiba
0ae0b81577 bug fix convex hull 2020-07-26 22:53:47 -07:00
Oliver Zell
8e41dbfcba Serializer: handle properties of joints which are not in def 2020-07-26 14:41:27 +02:00
Oliver Zell
840c1cb518 quick fix PrismaticJoint serializer 2020-07-26 14:26:28 +02:00
Oliver Zell
cd2eb8789e register missing joint types 2020-07-26 13:27:57 +02:00
Ali Shakiba
51c4a32fd6
Update README.md 2020-07-25 20:43:25 -07:00
Oliver Zell
cb87a7d819 add WeldJoint serializer 2020-07-23 19:40:35 +02:00
Oliver Zell
30c613ca88 add MouseJoint serializer 2020-07-23 19:33:24 +02:00
Oliver Zell
8cf27e4086 add RopeJoint serializer 2020-07-23 19:23:20 +02:00
Oliver Zell
a16abb792e add PulleyJoint serializer 2020-07-23 19:17:02 +02:00
Oliver Zell
860d974f46 add PrismaticJoint serializer 2020-07-21 20:02:06 +02:00
Oliver Zell
6c6a7b2336 add MotorJoint serializer 2020-07-20 21:57:29 +02:00
Oliver Zell
71b02fb93c FrictionJoint serializer 2020-07-20 21:44:05 +02:00
Ali Shakiba
aa08a1d756
Update README.md 2020-06-30 03:12:36 -07:00
Ali Shakiba
f196c29310
Update README.md 2020-06-30 03:12:06 -07:00
Ali Shakiba
35874c7c49
Update README.md 2020-06-30 03:08:54 -07:00
Ali Shakiba
7f3bccddc6
Update README.md 2020-06-24 22:53:52 -07:00
Ilya
308acbbec8 issue #130 fix comments for WorldDef defaults 2020-06-23 23:31:20 -07:00
Ali Shakiba
97375ac799
Update README.md 2020-06-23 20:03:49 -07:00
Ali Shakiba
1e4de69e7c set joint anchors 2020-06-23 19:46:54 -07:00
Ali Shakiba
32eddf9a64 v0.3.19 2020-06-23 19:46:54 -07:00
Ali Shakiba
4adc465210 fix serialization 2020-06-23 19:46:54 -07:00
Ali Shakiba
a652ce0b0c reorganize schema 2020-06-23 19:46:54 -07:00
Ali Shakiba
5cda122a4d
Update README.md 2020-06-14 19:03:19 -07:00
Ali Shakiba
db284f6275 v0.3.18 2020-06-04 20:39:46 -07:00
Ali Shakiba
13cb1d8893 serialize WheelJoint 2020-06-04 20:38:22 -07:00
Ali Shakiba
ca53731cb9 v0.3.17 2020-06-02 21:09:32 -07:00
Ali Shakiba
00c41f2682 serialize RevoluteJoint 2020-06-02 21:06:10 -07:00
s.iaroshenko
c2a64b6287 Recreated package-lock.json from scratch using npm i & npm audit fix 2020-06-02 21:05:19 -07:00
s.iaroshenko
6769248934 Added test coverage commands
Updated version of dev modules
Fixed old versions with npm audit fix
2020-06-02 21:05:19 -07:00
s.iaroshenko
cc95a18614 Added tests for DistanceJoint class 2020-06-02 21:05:19 -07:00
Ali Shakiba
51afad07f4 fix test glob 2020-06-01 22:33:01 -07:00
Ali Shakiba
91baefc564 v0.3.16 2020-05-31 20:21:40 -07:00
Ali Shakiba
90a5e123d2 update readme 2020-05-31 20:21:22 -07:00
Ali Shakiba
6f05a200a1 minor fix 2020-05-31 18:48:39 -07:00
s.iaroshenko
ba791af25f Running tests from subfolders
Updated references
2020-05-31 18:43:39 -07:00
Ali Shakiba
6aaac1e78f mv serialize test 2020-05-31 14:56:02 -07:00
s.iaroshenko
93f56b4ed9 Moved all tests to lib/__test
Added the unit test from Box2D C++ source
Removed memo.js since it's not used
Removed unused referenced and an empty test (CCD/Solver)
Updated description for some tests (still needs refactoring)
2020-05-31 14:53:23 -07:00
s.iaroshenko
d871cf9b4c Moved tests out of source folder
Replaced be.ok as it's not recommended: https://www.chaijs.com/api/bdd/#method_ok
Fixed order in _setAsBox to be consistent with wrapping algorithm (so vertices are not reordered for Box fixture)
Commented out some debug output
2020-05-31 14:53:23 -07:00
Ali Shakiba
79c650c447 add package-lock 2020-05-31 14:05:25 -07:00
s.iaroshenko
d2a0f98d9b Explicitly specified sinon library version 2020-05-31 04:34:09 -07:00
s.iaroshenko
9161f6ad2c Fixed tests:
- for BasicTest, need to register collision type
- for CollisionTest, only sinon.stub() has reset() method, not sinon.spy()
2020-05-30 19:31:10 -07:00
Ali Shakiba
c85903f9e7 v0.3.15 2020-05-29 23:25:33 -07:00
Ali Shakiba
16e2d42e63 update validator 2020-05-29 23:24:03 -07:00
Ali Shakiba
8897dc7b08 v0.3.14 2020-05-29 20:34:34 -07:00
Ali Shakiba
8eb489d02a serialize world in document 2020-05-29 20:26:36 -07:00
Ali Shakiba
15e64fb683 drink chai, fix tests 2020-05-29 20:26:30 -07:00
Ali Shakiba
0a06264241 v0.3.13 2020-05-10 20:08:08 -07:00
Oliver Zell
f8b58eb8b6
Merge pull request #122 from Feavy/master
Fixed ContactEdge prev and next types
2020-05-08 20:59:34 +02:00
Feavy
ace4a6b395 Fixed ContactEdge prev and next types 2020-05-07 18:04:42 +02:00
Jan Engehausen
42fb50c4ff link to Zzzone! game 2020-04-10 17:04:35 -07:00
Oliver Zell
76785dfc7c
Merge pull request #117 from zOadT/master
more fixes in collision
2020-04-06 18:30:45 +02:00
Oliver Zell
3c40ee73e4 use id in DynamicTree.computeHeight again 2020-04-06 18:27:29 +02:00
Oliver Zell
fa4c5c66bb update collision typings 2020-04-03 19:28:33 +02:00
Oliver Zell
a60e94df7c fix use of node.id in DynamicTree 2020-04-02 15:31:01 +02:00
Oliver Zell
f0944c57d6 import common in AABB.js 2020-03-26 11:48:21 +01:00
Oliver Zell
cacd54d6e3 fix iterations in DynamicTree 2020-03-25 22:41:46 +01:00
Oliver Zell
c5911d64b4
Merge pull request #115 from zOadT/master
minor fixes in collision
2020-03-18 17:27:47 +01:00
Oliver Zell
c077949339 minor fixes in collision 2020-03-17 19:39:58 +01:00
Oliver Zell
c5e7033c1f
Merge pull request #113 from zOadT/master
minor fixes in Mat22
2020-03-03 19:36:00 +01:00
Oliver Zell
a48c0845e6 keep previous code as comment 2020-03-03 14:24:01 +01:00
Oliver Zell
19f0201ff0 minor fixes in Mat22 2020-03-02 18:05:59 +01:00
Oliver Zell
2ceb43bd93 Extend typings of planck.internal 2020-01-12 23:08:14 -08:00
Ali Shakiba
eca0c235dc
Update README.md 2020-01-03 17:46:31 -08:00
Ali Shakiba
8d7cec72d4 v0.3.12 2020-01-02 20:17:41 -08:00
Ali Shakiba
91a8d68878 add json schema for serializer 2020-01-02 20:16:32 -08:00
Ali Shakiba
034fdfe873 refactoring 2020-01-02 18:24:59 -08:00
Ali Shakiba
111ef00f3f v0.3.11 2019-12-31 15:42:21 -08:00
Ali Shakiba
d1f34521ab update test 2019-12-31 15:27:43 -08:00
Ali Shakiba
430751f805 change deserialize signature 2019-12-31 15:27:43 -08:00
Ali Shakiba
0eee4ae4cf bug fix deserializer 2019-12-31 15:27:43 -08:00
Ali Shakiba
03a799ab36 flat serializer 2019-12-31 15:27:43 -08:00
Ali Shakiba
2b7c063634 serialize distance joint 2019-12-31 15:27:43 -08:00
Ali Shakiba
a9c1fae8e7 change deserialize signature 2019-12-31 15:27:43 -08:00
Ali Shakiba
36fbd54230 add serializer test 2019-12-31 15:27:43 -08:00
Ali Shakiba
37fd66be29
Update README.md 2019-10-14 09:06:50 -07:00
Ali Shakiba
d323220d6d
Update README.md 2019-10-13 13:14:08 -07:00
Ali Shakiba
81d31c8556
Update README.md 2019-09-29 12:32:13 -07:00
Oliver Zell
b9ef0bd90b
Fix typo in README.md 2019-09-17 22:25:45 +02:00
Ali Shakiba
620a43a4ff
Update README.md 2019-09-08 01:48:27 -07:00
Ali Shakiba
77be420712
Update README.md 2019-09-08 01:39:25 -07:00
Ali Shakiba
497e1ccdbd
Update README.md 2019-09-08 01:12:14 -07:00
Ali Shakiba
20b4b37772
Update README.md 2019-09-04 01:20:05 -07:00
Ali Shakiba
4b32aad224 v0.3.10 2019-08-28 00:08:55 -07:00
Ali Shakiba
827e2f76e2 add readonly key to ContactID 2019-08-26 19:39:18 -07:00
Stéphane Magnenat
375e38df61 Use namespace for internal stuff. 2019-08-26 19:39:18 -07:00
Stéphane Magnenat
b266364dc9 Added TS types for Manifold and WorldManifold and dependee types. 2019-08-26 19:39:18 -07:00
Ali Shakiba
144cd9ff6a v0.3.9 2019-08-10 18:03:26 -07:00
Ali Shakiba
8a36b71cd8 bugfix scaleY 2019-08-10 18:00:10 -07:00
Ali Shakiba
0e23b431df v0.3.8 2019-08-10 13:04:20 -07:00
Ali Shakiba
b205570e17 bugfix 2019-08-10 13:04:10 -07:00
Ali Shakiba
271ac53625 v0.3.7 2019-08-10 12:59:20 -07:00
Ali Shakiba
4512543341 fix syntax 2019-08-10 12:57:58 -07:00
Ali Shakiba
a3389a9d58 don't use flatted to serialize 2019-08-10 12:54:22 -07:00
Ali Shakiba
e5c485cf9c add scaleY to testbed 2019-08-10 12:16:49 -07:00
Ali Shakiba
ee5fb21894
Update README.md 2019-08-06 21:35:48 -07:00
Ali Shakiba
3c48b63784
Update README.md 2019-08-01 19:54:08 -07:00
Ali Shakiba
dbb0850f3d
Update README.md 2019-08-01 16:53:12 -07:00
Ali Shakiba
f99fe30095
Update README.md 2019-08-01 08:53:15 -07:00
Ali Shakiba
d992bafef9
Update README.md 2019-07-31 23:57:05 -07:00
Ali Shakiba
6b6fd4642c
Update README.md 2019-07-31 21:55:29 -07:00
Ali Shakiba
feab827ca8 use flatted to serialize 2019-07-30 21:42:06 -07:00
Ali Shakiba
645907bde3
Update README.md 2019-07-28 13:57:58 -07:00
Ali Shakiba
255fc6238a
Update README.md 2019-07-28 13:26:24 -07:00
Ali Shakiba
1df41ade60
Update README.md 2019-07-28 12:13:15 -07:00
Ali Shakiba
581bee9b54
Update README.md 2019-07-28 00:51:24 -07:00
Ali Shakiba
50636b1f5e
Update README.md 2019-07-28 00:50:14 -07:00
Ali Shakiba
0975654fe9 fix spacing 2019-07-24 23:37:28 -07:00
Ali Shakiba
b226669b97 fix spacing 2019-07-24 23:37:28 -07:00
Ali Shakiba
832df9be48 ts bugfix 2019-07-24 23:37:28 -07:00
Ali Shakiba
fdc2ea8b4e add DynamicTree to ts def 2019-07-24 23:37:28 -07:00
Ali Shakiba
d93023cd87 add Sweep to ts def 2019-07-24 23:37:28 -07:00
Ali Shakiba
2481dbc14f ts fix 2019-07-24 23:37:28 -07:00
Ali Shakiba
64dde294b0 add internal.Settings to ts definitions 2019-07-24 23:37:28 -07:00
Ali Shakiba
36d74be4a9 fix tslint 2019-07-24 23:37:28 -07:00
Ali Shakiba
243e53b68f minor update 2019-07-24 23:37:28 -07:00
Ali Shakiba
475e5dd18c
Update README.md 2019-07-12 16:56:45 -07:00
Ali Shakiba
24652286f8
Update README.md 2019-07-12 16:38:05 -07:00
Ali Shakiba
101996a342
Update README.md 2019-07-12 16:29:10 -07:00
Ali Shakiba
04fd4c2dc9
Update README.md 2019-07-12 00:44:24 -07:00
Ali Shakiba
7a8f602d92
Update README.md 2019-07-12 00:43:32 -07:00
Ali Shakiba
979cfb1d4c
Update README.md 2019-07-12 00:42:56 -07:00
Ali Shakiba
d85bf0b93f v0.3.6 2019-07-11 22:06:27 -07:00
Ali Shakiba
1ffa8a8706
Merge pull request #93 from FlorentMasson/master
Fix circle/circle collision response
2019-07-11 21:59:03 -07:00
FlorentMasson
db20ec464f
Fix circle/circle collision response
https://github.com/shakiba/planck.js/issues/92
2019-07-11 17:41:56 +02:00
Oliver Zell
5a983837b5
Merge pull request #89 from zOadT/master
Conditionally use module definition for typescript types
2019-07-05 07:44:41 +02:00
Oliver Zell
76da6d47a2 add missing type import 2019-07-03 13:04:16 +02:00
Oliver Zell
dd67f091a7 remove class declaration of Body 2019-07-03 13:03:23 +02:00
Oliver Zell
126ab64434 explicitly import types in TS definitions 2019-07-02 21:37:41 +02:00
Stéphane Magnenat
097f930dfe Added missing types. 2019-06-30 20:57:30 -07:00
Oliver Zell
5ed174bcb3 add missing export 2019-06-15 15:58:11 +02:00
Ali Shakiba
d9c9fbb94a
Merge pull request #90 from RobLoach/patch-1
Remove World import from Body
2019-06-12 21:54:01 -07:00
Rob Loach
74e250f1e5
Remove World import from Body
It's not used, and ends up with a circular dependency when it is in there. Removing it fixes the circular dependency.
2019-06-13 00:26:20 -04:00
Oliver Zell
2c261c80a0 put planck in front of types imported from other definition files 2019-06-12 20:54:04 +02:00
Oliver Zell
3516420ed6 conditionally use module definition for typescript types 2019-06-11 15:11:30 +02:00
Ali Shakiba
b8b500d8c4
Merge pull request #88 from Prozi/master
update dependencies + build for commonjs too
2019-06-10 10:39:19 -07:00
Jacek Pietal
a2b1e96f7b revert add dist folder with new files 2019-06-10 09:38:06 +02:00
Jacek Pietal
ada179aa2d update dependencies + build for commonjs too 2019-06-07 15:45:31 +02:00
Ali Shakiba
59c32eb882
Update README.md 2019-04-06 23:19:48 -07:00
Ali Shakiba
d83ea74014 v0.3.5 2019-02-24 19:28:50 -08:00
Ali Shakiba
47ebd7dcbc reset fixture/shape 2019-02-24 19:24:51 -08:00
Ali Shakiba
5c5ad82094 v0.3.4 2019-02-24 17:15:31 -08:00
Ali Shakiba
48319046e1 remove console.log 2019-02-24 16:58:32 -08:00
Ali Shakiba
e39b12871e v0.3.3 2019-02-03 00:24:44 -08:00
Ali Shakiba
8faafc8a63 change npm scripts 2019-02-03 00:24:30 -08:00
Ali Shakiba
678cf2fdb3 bugfix 2019-02-03 00:23:12 -08:00
Ali Shakiba
2efd03ff7a v0.3.2 2019-02-02 15:20:39 -08:00
Ali Shakiba
acbebcc669 bugfix 2019-02-02 15:00:27 -08:00
Ali Shakiba
fdda494e22 v0.3.1 2019-02-02 11:37:05 -08:00
Ali Shakiba
0a63c15a3d improve testbed 2019-02-02 11:35:25 -08:00
Ali Shakiba
49015d14ad
Merge pull request #81 from shakiba/serialize
add serialize
2019-02-02 11:34:51 -08:00
Ali Shakiba
6e2a780e92 bugfix 2019-02-02 11:10:23 -08:00
Ali Shakiba
ffe5a98898 deserialize 2019-02-02 10:58:01 -08:00
Ali Shakiba
bf46753cc1 rename serialize functions 2019-02-02 09:50:24 -08:00
Ali Shakiba
6d3d2fd503 serializer progress 2019-02-02 01:06:23 -08:00
Ali Shakiba
cdc898fa0e init serializer 2019-02-01 16:56:19 -08:00
Ali Shakiba
cd1dd396b3
Merge pull request #80 from shakiba/v0.3
Webpack build
2019-02-01 16:14:36 -08:00
Ali Shakiba
157be4f284 revert object reuse 2019-02-01 16:12:27 -08:00
Ali Shakiba
4778d39209 v3.0 2019-01-30 23:29:22 -08:00
Ali Shakiba
ac3c0a1269 fix webpack server 2019-01-30 23:22:37 -08:00
Ali Shakiba
7e9635dfb3 webpack build 2019-01-30 23:08:45 -08:00
Oliver Zell
3d0b0ab5e1 Fix #76
Make the second argument of AABB.prototype.combine optional
2019-01-07 19:19:27 +01:00
Ali Shakiba
44aee932e5
Merge pull request #75 from Quantum64/patch-1
Fix spelling
2018-12-18 21:52:17 -08:00
Dylan
e48fe1b0df
Fix spelling 2018-12-18 22:45:53 -05:00
Ali Shakiba
d02de0d93e v0.3.0-rc.2 2018-11-10 11:30:49 -08:00
Ali Shakiba
81dd4dffab code format 2018-11-10 11:29:59 -08:00
Ali Shakiba
67c31012ce inline solveVelocityConstraint computation 2018-11-10 11:29:36 -08:00
Ali Shakiba
0bcf9faa53 reuse objects 2018-11-09 22:54:38 -08:00
Ali Shakiba
77ebfbc701 v0.3.0-rc.1 2018-11-09 18:06:37 -08:00
Ali Shakiba
4d18c9d314 reuse objects 2018-11-09 18:06:37 -08:00
Ali Shakiba
2b7baff8de
Update README.md 2018-10-29 23:10:26 -07:00
Ali Shakiba
75e9680bd8
Update README.md 2018-10-29 23:08:57 -07:00
Ali Shakiba
9faa4726e2
Update README.md 2018-10-29 22:53:32 -07:00
Ali Shakiba
30fcca3e35
Update README.md 2018-10-29 22:16:36 -07:00
Ali Shakiba
0740bba1a9 v0.2.7 2018-10-27 20:02:45 -07:00
Ali Shakiba
59dd4b64a7 fix tslint 2018-10-21 18:19:38 -07:00
Ali Shakiba
728899fd02 add Transform.mulFn and deprecate Transform.mulAll 2018-10-20 23:36:44 -07:00
Ali Shakiba
f8bb7ed6cb improve examples code 2018-10-20 23:36:27 -07:00
Ali Shakiba
3977b48a7d v0.2.6 2018-10-07 12:46:40 -07:00
Ali Shakiba
2e6f95c46a fix Mat33.add 2018-10-07 12:42:45 -07:00
Ali Shakiba
8c4424971f do not set ContactID.key directly 2018-10-07 12:36:36 -07:00
Ali Shakiba
ad38526c8d
Merge pull request #72 from wemyss/master
Add Mat22 and Mat33 to exports and typescript definitions
2018-10-02 21:08:57 -07:00
Sam Wemyss
f5333d6ec0 📝 add Mat22 and Mat33 to exports and typescript definitions 2018-10-03 11:54:01 +10:00
Oliver Zell
a2211922c4
Merge pull request #71 from CaiBinQing/ts
Fix types of Body.m_jointList and Body.m_contactList
2018-10-02 18:14:18 +02:00
Binqing Cai
c1b35846ab Update definitions 2018-10-02 21:53:58 +08:00
Ali Shakiba
4e408f80fe v0.2.5 2018-09-30 21:57:41 -07:00
Oliver Zell
67c5d6487c
Merge pull request #70 from CaiBinQing/fix 2018-09-27 21:37:59 +02:00
Binqing Cai
5d5140d32d Fix a bug at DynamicTree.shiftOrigin 2018-09-27 21:48:42 +08:00
Binqing Cai
d4bc061c34 Remove unused parameters. 2018-09-27 20:20:33 +08:00
Oliver Zell
1d3b5bd3fd
Merge pull request #66 from shakiba/smaller-ts-files
Break down index.d.ts to smaller files
2018-09-20 10:19:07 +02:00
Oliver Zell
226b455b1a update mul definitions 2018-09-19 20:08:55 -07:00
Oliver Zell
54cff02667 remove note concerning 'remove-body'
Fixed in v0.2.2
2018-09-19 20:08:55 -07:00
Oliver Zell
da188239f3 update definitions to v0.2.3 2018-09-19 20:08:55 -07:00
Oliver Zell
34eb285783 link testbed definitions 2018-09-19 20:08:55 -07:00
Oliver Zell
79669d1cd0 remove headers from sub def files 2018-09-19 20:08:55 -07:00
Oliver Zell
566c9d87ce remove util link 2018-09-19 20:08:55 -07:00
Oliver Zell
368884dce4 link def files 2018-09-19 20:08:55 -07:00
Ali Shakiba
d580cd070e break down index.d.ts to smaller files 2018-09-19 20:08:53 -07:00
Ali Shakiba
0ae2e4d75c add tslint 2018-09-19 20:08:47 -07:00
Ali Shakiba
04a9db3750 v0.2.4 2018-09-16 22:25:45 -07:00
Ali Shakiba
7e3a4a7720 Typed mul mulT functions 2018-09-16 22:23:27 -07:00
Ali Shakiba
81461f9c9c v0.2.3 2018-09-12 23:55:31 -07:00
Ali Shakiba
9e517719a4 undo merge AABB.combine and combinePoints 2018-09-12 23:50:16 -07:00
Ali Shakiba
500cfbf776 v0.2.2 2018-09-09 17:18:28 -07:00
Ali Shakiba
e5059c8fea publish remove-body event 2018-09-09 16:37:21 -07:00
Ali Shakiba
0b8b0b33cc minor ts update @zOadT 2018-09-08 15:31:52 -07:00
Ali Shakiba
7288ac74a5 update 2018-09-08 11:27:41 -07:00
Ali Shakiba
0874fe4988 v0.2.1 2018-09-08 11:24:16 -07:00
Ali Shakiba
8666047975
Merge pull request #64 from shakiba/cleanup-joints-constructor
Cleanup joints constructor and definition classes
2018-09-08 11:19:45 -07:00
Ali Shakiba
92d5811f9e rm depricated pram from clone 2018-09-08 11:17:54 -07:00
Ali Shakiba
3fd1656066 neo for internal use 2018-09-08 11:13:23 -07:00
Ali Shakiba
86b9bf8b24 update examples 2018-09-08 10:52:40 -07:00
Ali Shakiba
f3ea4a1827 bug fix 2018-09-08 10:43:56 -07:00
Ali Shakiba
6506a95bff default vec2 values for joints 2018-09-08 10:31:44 -07:00
Ali Shakiba
cf3f262b59 ts fix 2018-09-07 21:41:36 -07:00
Ali Shakiba
4fed5120b0 more joints cleanup 2018-09-05 00:47:43 -07:00
Ali Shakiba
4d67a4d34c fix typo 2018-09-03 22:54:01 -07:00
Ali Shakiba
84c231b545 polyfill for old argument order 2018-09-03 17:28:14 -07:00
Ali Shakiba
3d55044565 opt classes 2018-09-03 17:15:45 -07:00
Ali Shakiba
6d1921acaa cleanup joints constructor an definition objects 2018-09-03 16:27:07 -07:00
Ali Shakiba
217b1b8ace v0.2.0 2018-09-02 19:10:59 -07:00
Ali Shakiba
e8a54ddc22 wSet/wAdd/wSub to combine and mul 2018-09-02 19:08:50 -07:00
Ali Shakiba
18ee93b26a
Merge pull request #63 from shakiba/post-typescript
Post TypeScript
2018-09-02 15:28:29 -07:00
Ali Shakiba
fb5dbb63a3 fix typo 2018-09-02 14:54:23 -07:00
Ali Shakiba
a2e49ff7f2 doc 2018-09-02 14:39:00 -07:00
Ali Shakiba
0b53ba70e5 add Vec3 to index 2018-09-02 14:34:17 -07:00
Ali Shakiba
07e2974c1a update docs 2018-08-21 00:01:38 -07:00
Ali Shakiba
117c3ebc9c undo some def changes 2018-08-20 23:55:34 -07:00
Ali Shakiba
e24610f26d add ShapeType and BodyType 2018-08-19 23:19:11 -07:00
Ali Shakiba
de2a957630 fix typo 2018-08-19 20:37:38 -07:00
Ali Shakiba
1eb2292e1a typescript cleanup 2018-08-19 20:25:54 -07:00
Ali Shakiba
6fe59ab0af merge AABB.combinePoints with AABB.combine 2018-08-19 19:00:11 -07:00
Ali Shakiba
85576fc587
Update README.md 2018-08-15 20:53:57 -07:00
Ali Shakiba
006aea3143
Update README.md 2018-08-15 20:53:11 -07:00
Ali Shakiba
516e0105b8
Merge pull request #61 from zOadT/master
Add typescript types file
2018-08-15 20:49:51 -07:00
Oliver Zell
4359c19817 Use FixtureDefWithShape 2018-08-15 13:11:02 +02:00
Oliver Zell
da2c791073 Add typescript types file 2018-08-15 12:40:40 +02:00
Ali Shakiba
b1b228fd20
Merge pull request #60 from zOadT/master
Awesome! :)
2018-08-14 22:46:36 -07:00
Oliver Zell
a2a0869fd4 Fix Bugs
Mainly remove operation overloads
2018-08-14 15:40:01 +02:00
Ali Shakiba
51bbbd5457 bug fix 2018-08-09 21:40:40 -07:00
Ali Shakiba
28c37e66a0 fix getReactionForce 2018-07-22 18:18:42 -07:00
Ali Shakiba
63b16af02a ignore package-lock.json 2018-07-22 18:18:27 -07:00
Ali Shakiba
439619bca6 v0.1.44 2018-04-08 13:34:15 -07:00
Ali Shakiba
2e1e46ad8c bug fix 2018-04-08 13:32:58 -07:00
Ali Shakiba
d788983cf3 multiply physics by -y instead of using stage -y scale 2018-02-07 23:16:10 -08:00
Ali Shakiba
fe2f470f99 minor fix 2018-02-04 21:13:14 -08:00
Ali Shakiba
51ccf1acd3 v0.1.43 2018-02-04 21:05:42 -08:00
Ali Shakiba
e52533f182 bug fix 2018-02-04 21:01:04 -08:00
Ali Shakiba
a15a318472 v0.1.42 2018-02-01 08:36:47 -08:00
Ali Shakiba
d8b7c2f8ad fix typo 2018-02-01 08:36:00 -08:00
Ali Shakiba
1657183837 v0.1.41 2018-01-31 19:55:12 -08:00
Ali Shakiba
7ce8044bf8 bug fix 2018-01-31 19:53:55 -08:00
Ali Shakiba
204f1c9f8d v0.1.40 2018-01-31 19:43:10 -08:00
Ali Shakiba
143ccb15cb bug fix 2018-01-31 19:40:02 -08:00
Ali Shakiba
cc56db8f0d remove old debug lines 2018-01-28 04:31:35 -08:00
Ali Shakiba
cf5e228ba8 v0.1.39 2018-01-28 03:56:16 -08:00
Ali Shakiba
07b15bf8e6 bug fix 2018-01-28 03:56:16 -08:00
Ali Shakiba
44001b870c remove solver profiler 2018-01-28 03:56:16 -08:00
Ali Shakiba
746b35cf5d fix debug/assert condition 2018-01-28 03:56:16 -08:00
Ali Shakiba
913501e08e
Update README.md 2018-01-18 20:02:21 -08:00
Ali Shakiba
0c3b130fac v0.1.38 2018-01-15 00:49:35 -08:00
Ali Shakiba
7d6cd62b60 remove destroy fixture from linked list 2018-01-15 00:41:04 -08:00
Ali Shakiba
f5cafb4e19 bug fix testbed 2018-01-15 00:03:10 -08:00
Ali Shakiba
eb0ec99d1c add private setAsBox to polygon 2018-01-14 21:59:42 -08:00
Ali Shakiba
b8d8b2982d v0.1.37 2017-12-24 22:17:06 -08:00
Ali Shakiba
e9d361278c update license year 2017-12-24 21:35:02 -08:00
Ali Shakiba
50381499b1 define DEBUG and ASSERT if undefined 2017-12-24 21:33:33 -08:00
Ali Shakiba
4141ae3932 add build files to npm 2017-12-16 16:11:18 -08:00
Ali Shakiba
2d004e341b
Merge pull request #30 from LukasDrgon/master
Update jsDelivr link
2017-12-16 15:51:29 -08:00
Ali Shakiba
d2519fbf8a v0.1.35 2017-12-16 15:45:24 -08:00
Ali Shakiba
210e63198f Merge pull request #32 from vacuum-c/master
Fix a typo in AABB.diff
2017-09-19 21:04:20 -07:00
Kaleidoscope
a88e91e3df Fix a typo in AABB.diff 2017-09-20 11:19:12 +08:00
Drgy
482ac94c32 Update jsDelivr link 2017-09-12 14:56:37 +02:00
Ali Shakiba
bb164a4b8e Merge pull request #26 from thomasyonug/bugFix
bugFix: lib/common/Rot.js     fix static method clone

@thomasyonug thanks! :)
2017-08-09 15:29:52 -07:00
thomasyonug
6cf0d1aa19 bugFix: lib/common/Rot.js fix static method clone 2017-08-09 22:06:50 +08:00
Ali Shakiba
6828bf1529 update testbed template 2017-04-19 20:52:20 -04:00
Ali Shakiba
0ce755d04c Merge pull request #17 from caseywebdev/master
Fix contact event names in README
2017-04-12 09:10:13 -04:00
Casey Foster
120bbc1d4b
Fix contact event names in README 2017-04-12 07:51:44 -05:00
Ali Shakiba
c79a338588 remove bower dependency 2017-04-09 14:33:21 -04:00
Ali Shakiba
2af71cefe2 fix type 2017-04-08 21:05:48 -04:00
Ali Shakiba
3a51841745 build 2017-04-08 21:04:07 -04:00
Ali Shakiba
456a472288 use box2d world#step signature 2017-04-08 21:03:21 -04:00
Ali Shakiba
bc08f99e0f Update README.md 2017-04-07 16:43:38 -04:00
Ali Shakiba
15ee2c8870 Merge pull request #14 from haujason/master
@haujason Thanks for your time!
2017-04-07 15:52:00 -04:00
Ali Shakiba
e383900bcd update few examples 2017-04-07 10:23:40 -04:00
Ali Shakiba
f55e95ca80 update few examples 2017-04-07 10:14:09 -04:00
haujason
67e98e8b2b Fix writing README.md 2017-04-06 22:19:24 -07:00
Ali Shakiba
e43a06c509 fix readme 2017-04-06 21:15:42 -04:00
Ali Shakiba
248753a246 build 2017-04-06 21:11:56 -04:00
Ali Shakiba
9fa76a6a3f testbed bug fix 2017-04-06 21:10:59 -04:00
Ali Shakiba
220a8ad024 hz to 1/hz 2017-04-06 20:57:19 -04:00
Ali Shakiba
a1c5aa1038 fix raycast example 2017-04-06 11:57:32 -04:00
Ali Shakiba
0feb336526 update examples 2017-04-06 11:47:38 -04:00
Ali Shakiba
94cde42f2d improve testbed 2017-04-06 11:47:15 -04:00
Ali Shakiba
8d48f841e5 use stage pause/resume events 2017-04-01 11:11:51 -04:00
Ali Shakiba
3be4738d27 render fill color and mouse impulse line 2017-04-01 11:09:48 -04:00
Ali Shakiba
98d7a7376a fix/improve testbed drawing cache 2017-03-31 20:20:08 -04:00
Ali Shakiba
e6df4f3281 build 2017-03-31 15:49:40 -04:00
Ali Shakiba
07b4fe80df testbed draw on main canvas context 2017-03-31 15:47:24 -04:00
Ali Shakiba
b6d9bd4719 rm console.log 2017-03-31 15:46:21 -04:00
Ali Shakiba
2ef586fc01 update examples 2017-03-30 20:47:31 -04:00
Ali Shakiba
b4129e2c9e update ignored files 2017-03-30 20:46:22 -04:00
Ali Shakiba
89bf16b887 build 2017-03-30 15:03:34 -04:00
Ali Shakiba
e7c3acf352 bug fix 2017-03-30 15:03:34 -04:00
Ali Shakiba
a25a2c4595 Update README.md 2017-03-30 02:05:13 -04:00
Ali Shakiba
50660b423b update readme 2017-03-26 15:19:12 -04:00
Ali Shakiba
677f3f3745 update examples 2017-03-26 14:00:55 -04:00
Ali Shakiba
d846d0f5fd new build 2017-03-26 13:59:35 -04:00
Ali Shakiba
b113320e81 fix aabb raycast 2017-03-26 13:51:21 -04:00
Ali Shakiba
dfb882d8b1 add setNest/setPrev to EdgeShape 2017-03-26 13:47:59 -04:00
Ali Shakiba
290c8e7ce4 fix testbed 2017-03-26 00:07:20 -04:00
Ali Shakiba
f351db4e29 add dyn4j to resources 2017-03-22 22:20:46 -04:00
384 changed files with 116571 additions and 56442 deletions

8
.changeset/README.md Normal file
View File

@ -0,0 +1,8 @@
# Changesets
Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works
with multi-package repos, or single-package repos to help you version and publish your code. You can
find the full documentation for it [in our repository](https://github.com/changesets/changesets)
We have a quick list of common questions to get you started engaging with this project in
[our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md)

11
.changeset/config.json Normal file
View File

@ -0,0 +1,11 @@
{
"$schema": "https://unpkg.com/@changesets/config@3.0.5/schema.json",
"changelog": "@changesets/cli/changelog",
"commit": false,
"fixed": [],
"linked": [],
"access": "public",
"baseBranch": "master",
"updateInternalDependencies": "patch",
"ignore": []
}

50
.github/workflows/deploy-docs.yml vendored Normal file
View File

@ -0,0 +1,50 @@
name: Deploy docs to github pages
on:
# Runs on pushes targeting the default branch
push:
branches: ["master", "main"]
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
# Sets the GITHUB_TOKEN permissions to allow deployment to GitHub Pages
permissions:
contents: read
pages: write
id-token: write
# Allow one concurrent deployment
concurrency:
group: "pages"
cancel-in-progress: true
jobs:
# Single deploy job since we're just deploying
deploy:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v5
- name: Set up Node
uses: actions/setup-node@v6
with:
node-version: lts/*
cache: "npm"
- name: Install dependencies
run: npm install
- name: Build
run: npm run typedoc && npm run docs:build
- name: Setup Pages
uses: actions/configure-pages@v5
- name: Upload artifact
uses: actions/upload-pages-artifact@v4
with:
# Upload dist folder
path: "./dist"
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4

38
.github/workflows/main.yml vendored Normal file
View File

@ -0,0 +1,38 @@
name: Build
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
workflow_dispatch:
jobs:
build:
runs-on: ubuntu-latest
steps:
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: '18'
- name: npm-install
run: npm install
- name: npm-test
run: npm run test
- name: npm-lint
run: npm run lint
- name: npm-build
run: npm run build
- name: npm-test-types
run: npm run test:types
- name: npm-typedoc
run: npm run typedoc

56
.gitignore vendored
View File

@ -1,5 +1,51 @@
.settings
.project
node_modules/
bower_components/
.idea
dist/docs/
# typedoc
docs/pages/api/
# vitepress
docs/.vitepress/cache/
docs/.vitepress/dist/
docs/.vitepress/.temp/
# misc
.DS_Store
*.pem
# dependencies
node_modules
.pnp
.pnp.js
# debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*
# local env files
.env*.local
.env
# testing
/coverage
/.nyc_output
# production
build
/docs/dist
# next.js
.next/
# out/
# vercel
.vercel
# ide
.idea/
.vscode*/
# typescript
*.tsbuildinfo
next-env.d.ts

2
.prettierignore Normal file
View File

@ -0,0 +1,2 @@
/dist/
/docs/api/

4
.prettierrc.json Normal file
View File

@ -0,0 +1,4 @@
{
"printWidth": 120,
"quoteProps": "preserve"
}

77
CHANGELOG.md Normal file
View File

@ -0,0 +1,77 @@
# planck
## 1.5.0
### Minor Changes
- 6ede4f3: Publish add-body, add-fixture, add-joint events
### Patch Changes
- 9415379: Add fixedRotation to body serialize
- 7791ea1: Remove temp fields from distance-joint serialization
- 86c9079: Remove hasVertex0 and hasVertex3 from serialize Edge
- 4fc10a7: In polygon and chain \_deserialize use Vec2Value
## 1.4.3
### Patch Changes
- 0bba3b2: Bug fix addVec2
## 1.4.2
### Patch Changes
- 9343ffc: Fix testbed drawing
## 1.4.1
### Patch Changes
- d12d0cc: Fix shape name alias export
## 1.4.0
### Minor Changes
- 0dcc98b: Split TestbedInterface and Testbed class
### Patch Changes
- e1a2717: Mark serialize and deserialize functions as @hidden instead of @internal
- 3446820: Fix AABB.rayCast
## 1.3.0
### Minor Changes
- bb9bb87: Testbed rendering rewrite
- 56193e7: Add DataDriver (experimental for demo use-case)
### Patch Changes
- ce1c486: No pointer interaction when mouseForce===0
## 1.2.0
### Minor Changes
- f0127f4: Add world.queueUpdate() to queue and defer updates after current simulation step
### Patch Changes
- 97bb79e: Improve world.queueUpdate
## 1.1.6
### Patch Changes
- f31114b: Add static Vec2.normalize
- bee0e16: Change clampVec2 arg to Vec2Value
## 1.1.5
### Patch Changes
- fbd0021: Un-hidden style field type

View File

@ -1,8 +1,20 @@
## 1.1.0
* Vite build migration
## 1.0.0
* Typescript migration
* Performance improvements
## 0.2
* TypeScript definitions added
* wSet/wAdd/wSub(a, v, b, w) replaced with combine/setCombine/addCombine/subCombine(a, v, b, w)
* wSet/wAdd/wSub(a, v) replaced with mul/setMul/addMul/subMul(a, v)
* Joints constructors cleanup
## 0.1
* source code directory layout changed, classes moved around!
* b2Class renamed to Class
* Dumping is removed, Drawing is moved to Stage viewer
* Dumping is removed, Drawing is moved to tesbed
* GrowableStack replaced with native array, Timer is changed
* Math is changed and split
* Contact and Collide classes merged, Contact registration/creation is changes

86
HelloWorld.ts Normal file
View File

@ -0,0 +1,86 @@
/*
* Copyright (c) Erin Catto
* Licensed under the MIT license
*/
/*
* This is a simple example of building and running a simulation
* using Planck.js. Here we create a large ground box and a small dynamic
* box.
* There are no graphics for this example. Planck.js is meant to be used
* with your rendering engine in your game engine.
*
* To run this example simply run `node HelloWorld.js` from command line.
*/
import { Box, World } from "./src";
// Define the gravity vector.
var gravity = { x: 0.0, y: -10.0 };
// Construct a world object, which will hold and simulate the rigid bodies.
var world = new World({
gravity: gravity,
});
// Define the ground body.
var groundBodyDef = {
position: { x: 0.0, y: -10.0 },
};
// Call the body factory which allocates memory for the ground body
// from a pool and creates the ground box shape (also from a pool).
// The body is also added to the world.
var groundBody = world.createBody(groundBodyDef);
// Define the ground box shape.
// The extents are the half-widths of the box.
var groundBox = new Box(50.0, 10.0);
// Add the ground fixture to the ground body.
groundBody.createFixture(groundBox, 0.0);
// Define the dynamic body. We set its position and call the body factory.
var body = world.createBody({
type: "dynamic",
position: { x: 0.0, y: 4.0 },
});
// Define another box shape for our dynamic body.
var dynamicBox = new Box(1.0, 1.0);
// Define the dynamic body fixture.
var fixtureDef = {
shape: dynamicBox,
// Set the box density to be non-zero, so it will be dynamic.
density: 1.0,
// Override the default friction.
friction: 0.3,
};
// Add the shape to the body.
body.createFixture(fixtureDef);
// Prepare for simulation. Typically we use a time step of 1/60 of a
// second (60Hz) and 10 iterations. This provides a high quality simulation
// in most game scenarios.
var timeStep = 1.0 / 60.0;
var velocityIterations = 6;
var positionIterations = 2;
// This is our little game loop.
for (var i = 0; i < 60; ++i) {
// Instruct the world to perform a single step of simulation.
// It is generally best to keep the time step and iterations fixed.
world.step(timeStep, velocityIterations, positionIterations);
// Now print the position and angle of the body.
var position = body.getPosition();
var angle = body.getAngle();
console.log(position.x.toFixed(2), position.y.toFixed(2), angle.toFixed(2));
}
console.log(Math.abs(position.x) < 0.01);
console.log(Math.abs(position.y - 1.01) < 0.01);
console.log(Math.abs(angle) < 0.01);

View File

@ -1,18 +1,20 @@
Copyright (c) 2016-2017 Ali Shakiba http://shakiba.me/planck.js
Copyright (c) 2006-2013 Erin Catto http://www.gphysics.com
The MIT License
Copyright (c) Erin Catto, Ali Shakiba
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any damages
arising from the use of this software.
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:
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
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.

190
README.md
View File

@ -1,149 +1,65 @@
*This project is under active development and is not stable yet.*
# planck-deterministic
# Planck.js<sup>&alpha;</sup>
A fork of [planck.js](https://github.com/piqnt/planck.js) (MIT, Erin Catto / Ali Shakiba)
with a **cross-platform deterministic math kernel**.
Planck.js is JavaScript rewrite of Box2D physics engine for cross-platform HTML5 game development. **[Check out demos!](http://piqnt.com/planck.js/)**
## Why
[![Car](./doc/img/screenshot.png "Play")](http://piqnt.com/planck.js/Car)
Upstream planck calls the host `Math.sin`, `Math.cos`, `Math.atan2` and `Math.random`.
IEEE-754 guarantees `+ - * /` and `sqrt` are correctly rounded, so those are identical
everywhere — but ECMAScript explicitly permits an *implementation-dependent approximation*
for the transcendental functions, and every engine forwards them to the host libm. Those
results differ between ARM64/JavaScriptCore (iOS) and x86-64/V8 (desktop).
## Motivations
`Rot.setAngle` and `Sweep.getTransform` call sin/cos for **every rotating body on every
step**. So a simulation shared between a mobile build and a desktop build diverges as soon
as anything rotates. That breaks replay portability, server-side replay verification, and
any leaderboard built on re-simulating a replay.
## What changed
- Added `src/common/DeterministicMath.ts` — `sin`, `cos`, `exp`, `atan`, `atan2`, `sqrt` and
a seeded PRNG, built from `+ - * /` and comparisons only. Coefficients and the Cody-Waite
range reduction follow fdlibm (Sun, freely distributable), the reference implementation
most libms derive from. Accuracy is within a few ulp of the host libm.
- Rewired the nine hoisted aliases in `Math.ts`, `Matrix.ts`, `Rot.ts`, `Sweep.ts` and
`dynamics/Position.ts` to use it. **No host libm call remains anywhere in `src/`.**
- Exported the kernel (`DeterministicMath`, `seedRandom`) so consumers can share the exact
same functions the solver uses and seed the PRNG for reproducible replays.
Every upstream test still passes, plus new determinism tests including a check that a
simulated free fall matches the closed-form analytic solution.
```js
import { World, seedRandom, DeterministicMath } from "planck-deterministic";
seedRandom(12345); // before a run, and before replaying it
```
## Upstream
This tracks planck.js v1.5.0. Upstream docs and API below.
---
# Planck.js
Planck.js is JavaScript/TypeScript rewrite of Box2D physics engine for cross-platform HTML5 game development.
#### Motivations
Key motivations in development of this project are:
- Taking advantage of Box2D's efforts and achievements
- Developing readable and maintainable JavaScript code
- Developing readable and editable code in JavaScript/TypeScript
- Providing idiomatic JavaScript/TypeScript API
- Optimizing the library for web and mobile platforms
- Providing a JavaScript-friendly API
## Try it
#### [Documentation](https://piqnt.com/planck.js/docs/)
To try Planck.js, simply add `planck-with-testbed.js` script to your HTML code and call `planck.testbed(callback)` with your code in callback. For example:
#### [Examples](https://piqnt.com/planck.js/)
```html
<html><body>
<script src="https://cdn.jsdelivr.net/planck/0.1/planck-with-testbed.js"></script>
<script>
planck.testbed(function(testbed) {
var world = planck.World();
// rest of your code
return world; // make sure you return the world
});
</script>
</body></html>
```
#### [Discord](https://discord.com/invite/znjh6J7)
Check out [Car example on CodePen](https://codepen.io/ashakiba/pen/yMpvrX?editors=001) to see it in practice.
Also see [`example`](./example/) directory for more testbed usage examples.
#### [Made with Planck.js](https://github.com/piqnt/planck.js/wiki/)
## Install
#### Download
Latest builds are available on [releases page](https://github.com/shakiba/planck.js/releases).
#### CDN
Planck.js is [available on jsDelivr](https://www.jsdelivr.com/projects/planck).
#### NPM
npm install planck-js --save
#### Bower
bower install planck-js --save
## Usage
Planck.js does not use any renderer by default. To use or integrate it with a rendering library all you need to do
is calling `world.step(hz)` in each frame, and then iterating over world entities to draw or update them.
You may also want to listen to world events to remove objects which are removed from the world. For example:
```html
<script src="./path/to/planck.min.js"></script>
<script>
var world = planck.World();
window.requestAnimationFrame(function() {
// in each frame call word.step(hz) with fixed frequency
world.step(1 / 60);
// iterate over bodies and fixtures
for (var body = world.getBodyList(); body; body = body.getNext()) {
for (var fixture = body.getFixtureList(); fixture; fixture = fixture.getNext()) {
// draw or update fixture
}
}
});
world.on('remove-fixture', function(fixture) {
// remove fixture from ui
});
</script>
```
## API
Planck.js public API closely follows Box2D API (see [Resources](#Resources)), with following differences:
- `b2` prefix is dropped from class names, for example `b2World` is now available as `planck.World`.
- Method names are converted from UpperCamelCase to lowerCamelCase.
- Definition classes/objects (BodyDef, FixtureDef, etc.) are replaced by inline JavaScript objects (`{}`).
- Shapes are made immutable and are not cloned when used to create fixtures.
- `World#on(eventName, listenerFn)` and `World#off(eventName, listenerFn)` are added to add and remove event listeners. Currently supported events are:
- `'contact-begin'`
- `'contact-end'`
- `'pre-solve'`
- `'post-solve'`
- `'joint-removed'`
- `'fixture-removed'`
- `'body-removed'`
## Resources
- <a href="http://box2d.org/documentation/" target="_blank">Box2D Manual</a> and <a href="https://github.com/erincatto/Box2D/wiki/FAQ" target="_blank">FAQ</a> are highly recommended to get started.
- [iforce2d](https://www.iforce2d.net/b2dtut/) website includes a collection of helpful tutorials and resources to learn Box2D.
Following technical documents are recommend if you are interested in learning about Box2D/Planck.js's internal details.
- [Continuous Collision](http://twvideo01.ubm-us.net/o1/vault/gdc2013/slides/824737Catto_Erin_PhysicsForGame.pdf) by Erin Catto
- [Solving Rigid Body Contacts](http://www.richardtonge.com/presentations/Tonge-2012-GDC-solvingRigidBodyContacts.pdf) by Richard Tonge
*If you know any other useful resource, please add it or submit an issue about it.*
## Testbed
Another way to use testbed and try included examples (in [`example`](./example/) directory) is running testbed with live build locally:
1. Install `git`, `npm` and `bower`
1. Clone or download this repository
1. Install npm and bower dependencies:
npm install
bower install
1. Run testbed and open it in your web browser (see command-line output for URL to open):
npm run testbed
## Architecture
Planck.js includes Box2D algorithms without modification and its internal architecture and public API are very similar to Box2D.
However some [changes](./CHANGES.md) and refactoring are made during rewrite to address differences between C++ and JavaScript.
## Credits
[Box2D](http://box2d.org/) is a popular C++ 2D rigid-body physics engine created by [Erin Catto](https://twitter.com/erin_catto). Box2D is used in several popular games, such as Angry Birds, Limbo and Crayon Physics, as well as game development tools and libraries such as Apple's SpriteKit.
[Planck.js](https://github.com/shakiba/planck.js) is developed and maintained by Ali Shakiba.
## License
Planck.js is [available under the zlib license](./LICENSE.txt).
#### [Report Issues](https://github.com/piqnt/planck.js/issues)
To speed up resolving issues, please provide [testbed](https://piqnt.com/planck.js/docs/testbed) code to reproduce the issue.

225
benchmark/benchmark.ts Normal file
View File

@ -0,0 +1,225 @@
export interface TestInterface {
name: string;
createBoxShape: (hx: number, hy: number) => any;
createBoxBody: (shape: any, x: number, y: number, density: number) => any;
step: (timeStep: number, velocityIterations: number, positionIterations: number) => void;
setup: () => void;
teardown: () => void;
}
export interface XY {
x: number;
y: number;
}
export type TestFactory = (gravity: XY, edgeV1: XY, edgeV2: XY, edgeDensity: number) => TestInterface;
const PYRAMID_SIZE = 40;
const GRAVITY = { x: 0, y: -10 };
const DELTA_X = { x: 0.5625, y: 1 };
const DELTA_Y = { x: 1.125, y: 0 };
const BOX_DENSITY = 5;
const GROUND_DENSITY = 0;
const TIME_STEP = 1 / 60;
const VELOCITY_ITERATIONS = 3;
const POSITION_ITERATIONS = 3;
const EDGE_V1 = { x: -40, y: 0 };
const EDGE_V2 = { x: 40, y: 0 };
const START_X = { x: -7, y: 0.75 };
const BOX_SIZE = { x: 0.5, y: 0.5 };
const WARMUP_ITERATIONS = 64;
const BENCH_ITERATIONS = 256;
function setupWorld(test: TestInterface) {
// Setup world
const shape = test.createBoxShape(BOX_SIZE.x, BOX_SIZE.y);
const x = { ...START_X };
for (let i = 0; i < PYRAMID_SIZE; ++i) {
const y = { ...x };
for (let j = i; j < PYRAMID_SIZE; ++j) {
test.createBoxBody(shape, y.x, y.y, BOX_DENSITY);
y.x += DELTA_Y.x;
y.y += DELTA_Y.y;
}
x.x += DELTA_X.x;
x.y += DELTA_X.y;
}
}
export type ProgressFunc = (value: number, max: number) => void;
async function warmupAsync(test: TestInterface, progress: ProgressFunc): Promise<void> {
return new Promise<void>((resolve: (value: void) => void) => {
let step = 0;
progress(0, WARMUP_ITERATIONS + BENCH_ITERATIONS);
const runNext = () => {
if (step < WARMUP_ITERATIONS) {
test.step(TIME_STEP, VELOCITY_ITERATIONS, POSITION_ITERATIONS);
progress(step, WARMUP_ITERATIONS + BENCH_ITERATIONS);
step++;
window.requestAnimationFrame(runNext);
} else {
resolve();
}
};
window.requestAnimationFrame(runNext);
});
}
async function benchAsync(test: TestInterface, progress: ProgressFunc): Promise<number[]> {
return new Promise((resolve: (value: number[]) => void) => {
let step = 0;
progress(0, WARMUP_ITERATIONS + BENCH_ITERATIONS);
const times: number[] = [];
const runNext = () => {
if (step < BENCH_ITERATIONS) {
const begin = performance.now();
test.step(TIME_STEP, VELOCITY_ITERATIONS, POSITION_ITERATIONS);
times.push(performance.now() - begin);
progress(WARMUP_ITERATIONS + step, WARMUP_ITERATIONS + BENCH_ITERATIONS);
step++;
window.requestAnimationFrame(runNext);
} else {
resolve(times);
}
};
window.requestAnimationFrame(runNext);
});
}
function warmup(test: TestInterface) {
for (let i = 0; i < WARMUP_ITERATIONS; i++) {
test.step(TIME_STEP, VELOCITY_ITERATIONS, POSITION_ITERATIONS);
}
}
function bench(test: TestInterface) {
const times: number[] = [];
for (let i = 0; i < BENCH_ITERATIONS; i++) {
const begin = performance.now();
test.step(TIME_STEP, VELOCITY_ITERATIONS, POSITION_ITERATIONS);
times.push(performance.now() - begin);
}
return times.sort();
}
function mean(values: number[]) {
let total = 0;
for (const value of values) total += value;
return total / BENCH_ITERATIONS;
}
// Simple nearest-rank %ile (on sorted array). We should have enough samples to make this reasonable.
function percentile(values: number[], pc: number) {
const rank = Math.floor((pc * values.length) / 100);
return values[rank];
}
export function prepareTests(factories: TestFactory[]) {
return factories.map((factory: TestFactory) => factory(GRAVITY, EDGE_V1, EDGE_V2, GROUND_DENSITY));
}
export function runTest(test: TestInterface) {
setupWorld(test);
warmup(test);
const times = bench(test);
return {
name: test.name,
avg: mean(times),
p5: percentile(times, 5),
p95: percentile(times, 95),
};
}
export async function runTestAsync(test: TestInterface, progress: ProgressFunc) {
setupWorld(test);
await warmupAsync(test, progress);
const times = await benchAsync(test, progress);
return {
name: test.name,
avg: mean(times),
p5: percentile(times, 5),
p95: percentile(times, 95),
};
}
export type TestResult = ReturnType<typeof runTest>;
export function runAllTests(factories: TestFactory[]) {
const tests = prepareTests(factories);
const results: TestResult[] = [];
console.log("Running Benchmarks:");
for (const test of tests) {
const result = runTest(test);
results.push(result);
console.log(` ✓ ${result.name}`);
}
return results.sort((a: TestResult, b: TestResult) => a.avg - b.avg);
}
const noop = () => undefined;
export async function runAllTestsAsync(factories: TestFactory[]) {
const tests = prepareTests(factories);
console.log("Running Benchmarks:");
const results: TestResult[] = [];
for (const test of tests) {
// eslint-disable-next-line no-await-in-loop
const result = await runTestAsync(test, noop);
console.log(` ✓ ${result.name}`);
results.push(result);
}
return results.sort((a: TestResult, b: TestResult) => a.avg - b.avg);
}
export function resultsToMarkdown(results: TestResult[]) {
const header = ["Name", "avg ms/frame", "5th %ile", "95th %ile", "Ratio"];
const rows = results.map((r: TestResult) => [
r.name,
r.avg.toFixed(2),
r.p5.toString(),
r.p95.toString(),
(r.avg / results[0].avg).toFixed(2),
]);
const lengths = header.map((label: string, index: number) =>
Math.max(label.length, ...rows.map((columns: string[]) => columns[index].length)),
);
function getDashes(length: number) {
return "-".repeat(length);
}
const dashes = `| ${lengths.map(getDashes).join(" | ")} |`;
const lines: string[] = [];
lines.push(`| ${header.map(pad).join(" | ")} |`);
lines.push(dashes);
function pad(value: string, index: number) {
const length = lengths[index];
if (value.length < length) {
if (index > 0) return " ".repeat(length - value.length) + value;
return value + " ".repeat(length - value.length);
}
return value;
}
for (const row of rows) {
lines.push(`| ${row.map(pad).join(" | ")} |`);
}
return lines.join("\n");
}
export function logResults(results: TestResult[]) {
console.log("\nResults:");
console.log(resultsToMarkdown(results));
}

106
benchmark/browser.ts Normal file
View File

@ -0,0 +1,106 @@
import { prepareTests, resultsToMarkdown, runTestAsync, TestResult, TestInterface, TestFactory } from "./benchmark";
import { box2dJsFactory } from "./tests/box2d-js";
import { planckFactory } from "./tests/planck";
export const tests: TestFactory[] = [
box2dJsFactory,
planckFactory,
];
export function getBrowserInfo() {
const ua = navigator.userAgent;
let M = ua.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) ?? [];
if (/trident/i.test(M[1])) {
const tem = /\brv[ :]+(\d+)/g.exec(ua) ?? [];
const version = tem[1] || "";
return `IE ${version}`;
}
if (M[1] === "Chrome") {
const tem = ua.match(/\bOPR|Edge\/(\d+)/);
if (tem !== null) return `Opera ${tem[1]}`;
}
M = M[2] ? [M[1], M[2]] : [navigator.appName, navigator.appVersion, "-?"];
const tem = ua.match(/version\/(\d+)/i);
if (tem !== null) M.splice(1, 1, tem[1]);
return `${M[0]} ${M[1]}`;
}
const startButton = document.getElementById("start") as HTMLButtonElement;
const tbody = document.querySelector("tbody") as HTMLElement;
const ratioHead = document.getElementById("ratio") as HTMLElement;
const branchName = document.getElementById("branch-name") as HTMLElement;
branchName.innerHTML = [
import.meta.env.VITE_GIT_BRANCH_NAME,
import.meta.env.VITE_GIT_COMMIT_HASH.slice(0, 7),
import.meta.env.VITE_GIT_COMMIT_DATE.slice(0, 19).replace("T", " "),
'\"' + import.meta.env.VITE_GIT_LAST_COMMIT_MESSAGE + '\"',
].join("<br />");
const testRows = prepareTests(tests).map((test: TestInterface) => {
const row = document.createElement("tr");
tbody.appendChild(row);
const name = document.createElement("td");
const avg = document.createElement("td");
const p5 = document.createElement("td");
const p95 = document.createElement("td");
const ratio = document.createElement("td");
name.textContent = test.name;
row.appendChild(name);
row.appendChild(avg);
row.appendChild(p5);
row.appendChild(p95);
row.appendChild(ratio);
const progress = document.createElement("progress");
return {
row,
test,
begin() {
test.setup();
ratio.appendChild(progress);
progress.value = 0;
},
progress(value: number, max: number) {
progress.value = value;
progress.max = max;
},
end(result: TestResult) {
test.teardown();
avg.textContent = result.avg.toFixed(2);
p5.textContent = result.p5.toString();
p95.textContent = result.p95.toString();
ratio.textContent = "✓";
},
final(ratioValue: number) {
ratio.textContent = ratioValue.toFixed(2);
tbody.appendChild(row);
},
};
});
type TestResultAndRow = TestResult & { testRow: typeof testRows[0] };
export async function runAllTestsAsync() {
ratioHead.textContent = "";
const results: TestResultAndRow[] = [];
for (const testRow of testRows) {
testRow.begin();
// eslint-disable-next-line no-await-in-loop
const result = await runTestAsync(testRow.test, testRow.progress);
testRow.end(result);
results.push({ ...result, testRow });
}
results.sort((a: TestResultAndRow, b: TestResultAndRow) => a.avg - b.avg).forEach((result: TestResultAndRow) => result.testRow.final(result.avg / results[0].avg));
startButton.removeAttribute("disabled");
ratioHead.textContent = "Ratio";
console.log(`Browser: ${getBrowserInfo()}\n${resultsToMarkdown(results)}`);
}
startButton.addEventListener("click", () => {
startButton.disabled = true;
runAllTestsAsync();
});

49
benchmark/index.html Normal file
View File

@ -0,0 +1,49 @@
<html>
<head>
<meta charset="utf-8" />
<title>Planck.js/Box2D Benchmark</title>
<style>
th, td {
padding: 2px 5px;
}
table {
border-collapse: collapse;
margin-top: 5px;
}
td {
border: 1px solid gray;
}
th:first-child {
text-align: left;
}
progress {
width: 200px;
}
textarea {
width: 500px;
height: 300px;
}
</style>
</head>
<body>
<h3>Planck.js/Box2D Benchmark</h3>
<button id="start">Start</button>
<table>
<thead>
<tr>
<th>Name</th>
<th>avg ms/frame</th>
<th>5th %ile</th>
<th>95th %ile</th>
<th id="ratio">Ratio</th>
</tr>
</thead>
<tbody></tbody>
</table>
<script src="https://kripken.github.io/box2d.js/build/Box2D_v2.3.1_min.js"></script>
<script type="module" src="./browser.ts"></script>
<br />
<br />
<span id="branch-name"></span>
</body>
</html>

13
benchmark/node.ts Normal file
View File

@ -0,0 +1,13 @@
import { performance } from "perf_hooks";
global.performance = performance as any;
import { logResults, runAllTests } from "./benchmark";
import type { TestFactory } from "./benchmark";
import { planckFactory } from "./tests/planck";
export const tests: TestFactory[] = [
planckFactory,
];
const results = runAllTests(tests);
logResults(results);

View File

@ -0,0 +1,42 @@
import "./fixprocess";
const { b2Body, b2World, b2Vec2, b2EdgeShape, b2PolygonShape, b2_dynamicBody, b2BodyDef } = Box2D;
import type { TestFactory } from "../benchmark";
export const box2dJsFactory: TestFactory = (gravity, edgeV1, edgeV2, edgeDensity) => {
let world: typeof b2World;
let ground: typeof b2Body;
let edgeShape: typeof b2EdgeShape;
return {
name: "box2d.js",
setup() {
world = new b2World(new b2Vec2(gravity.x, gravity.y));
ground = world.CreateBody(new b2BodyDef());
edgeShape = new b2EdgeShape();
edgeShape.Set(new b2Vec2(edgeV1.x, edgeV1.y), new b2Vec2(edgeV2.x, edgeV2.y));
ground.CreateFixture(edgeShape as any, edgeDensity);
},
teardown() {
world = null;
ground = null;
edgeShape = null;
},
createBoxShape(hx: number, hy: number) {
const box = new b2PolygonShape();
box.SetAsBox(hx, hy);
return box;
},
createBoxBody(shape: any, x: number, y: number, density: number) {
const bd = new b2BodyDef();
bd.set_type(b2_dynamicBody);
bd.set_position(new b2Vec2(x, y));
const body = world.CreateBody(bd);
body.CreateFixture(shape, density);
},
step(timeStep: number, velocityIterations: number, positionIterations: number) {
world.Step(timeStep, velocityIterations, positionIterations);
},
};
};

View File

@ -0,0 +1,19 @@
// box2d.js tries to access process.stdout/err, need to emulate it
if ("requestAnimationFrame" in globalThis) {
// // @ts-ignore
// window.process.stdout = {
// write(x: string) {
// console.log(x);
// return true;
// },
// };
// // @ts-ignore
// globalThis.process.stderr = {
// write(x: string) {
// console.error(x);
// return true;
// },
// };
}

39
benchmark/tests/planck.ts Normal file
View File

@ -0,0 +1,39 @@
import { World, Vec2, EdgeShape, BoxShape, Body } from "../../src/index";
import { TestFactory } from "../benchmark";
export const planckFactory: TestFactory = (gravity, edgeV1, edgeV2, edgeDensity) => {
let world: World | null = null;
let ground: Body | null = null;
let edgeShape: EdgeShape | null = null;
return {
name: "planck.js (current)",
setup() {
world = new World({
gravity: new Vec2(gravity.x, gravity.y),
});
ground = world.createBody({});
edgeShape = new EdgeShape(new Vec2(edgeV1.x, edgeV1.y), new Vec2(edgeV2.x, edgeV2.y));
ground.createFixture(edgeShape as any, edgeDensity);
},
createBoxShape(hx: number, hy: number) {
return new BoxShape(hx, hy);
},
createBoxBody(shape: any, x: number, y: number, density: number) {
const body = world?.createBody({
type: "dynamic",
position: new Vec2(x, y),
});
body?.createFixture(shape, density);
},
step(timeStep: number, velocityIterations: number, positionIterations: number) {
world?.step(timeStep, velocityIterations, positionIterations);
},
teardown() {
world = null;
ground = null;
edgeShape = null;
},
};
};

View File

@ -1,26 +0,0 @@
{
"name": "planck-js",
"description": "2D JavaScript physics engine for cross-platform HTML5 game development",
"keywords": [
"html5",
"javascript",
"game",
"physics",
"engine",
"2d",
"mobile"
],
"license": "zlib",
"repository": {
"type": "git",
"url": "git://github.com/shakiba/planck.js.git"
},
"ignore": [
"example/",
"test/"
],
"devDependencies": {
"stage-js": "^0.8.4",
"font-awesome": "font-awsome#~4.5.0"
}
}

4346
dist/planck-with-testbed.d.ts vendored Normal file

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

1
dist/planck-with-testbed.js.map vendored Normal file

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

1
dist/planck-with-testbed.min.js.map vendored Normal file

File diff suppressed because one or more lines are too long

16987
dist/planck-with-testbed.mjs vendored Normal file

File diff suppressed because it is too large Load Diff

1
dist/planck-with-testbed.mjs.map vendored Normal file

File diff suppressed because one or more lines are too long

4346
dist/planck.d.ts vendored Normal file

File diff suppressed because it is too large Load Diff

26644
dist/planck.js vendored

File diff suppressed because it is too large Load Diff

1
dist/planck.js.map vendored Normal file

File diff suppressed because one or more lines are too long

52
dist/planck.min.js vendored

File diff suppressed because one or more lines are too long

1
dist/planck.min.js.map vendored Normal file

File diff suppressed because one or more lines are too long

12144
dist/planck.mjs vendored Normal file

File diff suppressed because it is too large Load Diff

1
dist/planck.mjs.map vendored Normal file

File diff suppressed because one or more lines are too long

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.1 KiB

96
docs/.vitepress/config.ts Normal file
View File

@ -0,0 +1,96 @@
import { defineConfig } from "vitepress";
// https://vitepress.dev/reference/site-config
export default defineConfig({
title: "Planck.js Docs",
description: "2D Physics Engine for JavaScript",
srcDir: "./pages",
base: "/planck.js/docs/",
outDir: "../dist/docs",
themeConfig: {
// https://vitepress.dev/reference/default-theme-config
search: {
provider: "local",
},
nav: [
{ text: "API Reference", link: "/api/" },
{ text: "Playground", link: "https://piqnt.com/" },
{ text: "GitHub", link: "https://github.com/piqnt/planck.js/" },
{ text: "Discord", link: "https://discord.gg/znjh6J7" },
],
sidebar: [
{ link: "/", text: "Introduction" },
{
text: "Get Started",
collapsed: true,
items: [
{ link: "/run-your-code", text: "Run Your Code" },
{ link: "/hello-world", text: "Hello World" },
{ link: "/core-concepts", text: "Core Concepts" },
{ link: "/install", text: "Install" },
],
},
{
text: "API Conventions",
collapsed: true,
items: [
{ link: "/api-conventions/units", text: "Units" },
{ link: "/api-conventions/factories-and-definitions", text: "Factories and Definitions" },
{ link: "/api-conventions/implicit-destruction", text: "Implicit Destruction" },
{ link: "/api-conventions/user-data", text: "User Data" },
],
},
{ link: "/world", text: "World" },
{ link: "/body", text: "Body" },
{ link: "/fixture", text: "Fixture" },
{
text: "Shape",
collapsed: true,
link: "/shape",
items: [
{ link: "/shape", text: "Shape" },
{ link: "/shape/circle", text: "Circle" },
{ link: "/shape/polygon", text: "Polygon" },
{ link: "/shape/edge", text: "Edge" },
{ link: "/shape/chain", text: "Chain" },
],
},
{
text: "Joint",
collapsed: true,
link: "/joint",
items: [
{ link: "/joint", text: "Joint" },
{ link: "/joint/distance-joint", text: "Distance Joint" },
{ link: "/joint/friction-joint", text: "Friction Joint" },
{ link: "/joint/gear-joint", text: "Gear Joint" },
{ link: "/joint/motor-joint", text: "Motor Joint" },
{ link: "/joint/prismatic-joint", text: "Prismatic Joint" },
{ link: "/joint/pulley", text: "Pulley" },
{ link: "/joint/revolute-joint", text: "Revolute Joint" },
{ link: "/joint/rope-joint", text: "Rope Joint" },
{ link: "/joint/weld-joint", text: "Weld Joint" },
{ link: "/joint/wheel-joint", text: "Wheel Joint" },
{ link: "/joint/mouse-joint", text: "Mouse Joint" },
],
},
{ link: "/contacts", text: "Contacts" },
{ link: "/collision", text: "Collision" },
{ link: "/world/simulation", text: "Simulation" },
{ link: "/rendering", text: "Rendering" },
{ link: "/testbed", text: "Testbed" },
{ link: "/limitations", text: "Limitations" },
{ link: "/api/", text: "API Reference" },
{ link: "/references-resources", text: "References & Resources" },
{ link: "/credits", text: "Credits & License" },
],
},
});

View File

@ -0,0 +1,37 @@
## Factories and Definitions
To create a `Body` or a `Joint`, you need to call the factory functions on World:
```js
body = world.createBody(bodyDef);
joint = world.createJoint(jointDef);
```
And there are corresponding destruction functions:
```js
world.destroyBody(body)
world.destroyJoint(joint)
```
When you create a body or joint, you need to provide a definition. These
definitions contain all the information needed to build the body or
joint. By using this approach we can prevent construction errors, keep
the number of function parameters small, provide sensible defaults, and
reduce the number of accessors.
Since fixtures must be parented to a body, they are created and
destroyed using a factory method on `Body`:
```js
let fixture = body.createFixture(fixtureDef);
body.destroyFixture(fixture);
```
There is also a shortcut to create a fixture directly from the shape and
density.
```js
let fixture = body.createFixture(shape, density);
```

View File

@ -0,0 +1,36 @@
## Implicit Destruction
Often when using Planck.js you will create and destroy many bodies, shapes,
and joints. Managing these entities is somewhat automated by Planck.js. If
you destroy a body then all associated shapes and joints are
automatically destroyed. This is called implicit destruction.
When you destroy a body, all its attached shapes, joints, and contacts
are destroyed.
Any body connected to one of those joints and/or contacts is woken. This process is usually
convenient. However, you must be aware of one crucial issue:
> **Caution**:
> When a body is destroyed, all fixtures and joints attached to the body
> are automatically destroyed. You must nullify any references you have to
> those shapes and joints. Otherwise, your program will die horribly if
> you try to use those fixtures or joints later.
To help you nullify your references, Planck.js world publishes events
(`remove-joint`, `remove-fixture`, `remove-body`) that you can listen
to. Then the world object will notify you when an object is
going to be implicitly destroyed.
```js
world.on('remove-joint', function(joint) {
// remove all references to joint.
});
world.on('remove-fixture', function(fixture) {
// remove all references to fixture.
});
world.on('remove-body', function(body) {
// bodies are not removed implicitly,
// but the world publishes this event if a body is removed
})
```

View File

@ -0,0 +1,25 @@
## Units
Planck.js works with floating point numbers and tolerances have to be used to make Planck.js perform well.
These tolerances have been tuned to work well with meters-kilogram-second (MKS) units.
In particular, Planck.js has been tuned to work well with moving shapes between 0.1 and 10 units (meters).
So this means objects between soup cans and buses in size should work well. Static shapes may be up to 50 meters long without trouble.
You should try to get your moving objects in the range 0.1 - 10 meters, with 1 meter being the sweet spot.
Being a 2D physics engine, it is tempting to use pixels as your units.
This could lead to a poor simulation and possibly weird behavior.
An object of length 200 pixels would be seen by Planck.js as the size of a 45 story building.
If you need to use different length units, you have two options:
- Use some scaling system when you render your environment and actors. It is highly recommended to use this approach to keep your physics code portable. The Planck.js testbed does this by using stage.js viewbox transform.
- Set Settings.lengthUnitsPerMeter accordingly. For example if a car height which is around 1.6 meter is 80 units (pixels) in in your game, value of lengthUnitsPerMeter should be set to 50 (80 / 1.6).
Planck.js uses radians for angles.
The body rotation is stored in radians and may grow unbounded.
Consider normalizing the angle of your bodies if the magnitude of the angle becomes too large (use body.setAngle).
> **Caution**:
> Planck.js uses radians, not degrees.

View File

@ -0,0 +1,36 @@
## User Data
The `Fixture`, `Body`, and `Joint` classes allow you to attach user data.
This is handy to implement game-logic and rendering.
For example, it is typical to attach an actor reference to the rigid body
on that actor. This sets up a circular reference. If you have the actor,
you can get the body. If you have the body, you can get the actor.
```js
let actor = gameCreateActor();
actor.body = myWorld.createBody({
userData: actor
});
```
For fixtures you might consider defining a user data structure that lets
you store game specific information, such as material type, effects
hooks, sound hooks, etc.
```js
let fixture = body.createFixture({
shape: someShape,
userData: { materialIndex: 2 },
});
```
Keep in mind that user data is optional and you can put anything in it.
However, you should be consistent. For example, if you want to store an
actor reference on one body, you should keep an actor reference on all
bodies. Don't store an actor reference on one body, and a foo reference on
another body. Casting an actor reference to a foo reference may lead to a
crash.
User data references are null by default.

414
docs/pages/body.md Normal file
View File

@ -0,0 +1,414 @@
## Body
Bodies have position, angle, and velocity. You can apply forces, torques, and
impulses to bodies. Bodies can be `static`, `kinematic`, or `dynamic`. Here
are the body type definitions:
- `static` -
A static body does not move under simulation and behaves as if it has
infinite mass. Internally, Planck.js stores zero for the mass and the
inverse mass. Static bodies can be moved manually by the user. A static
body always has zero velocity. Static bodies do not collide with other static
or kinematic bodies.
- `kinematic` -
A kinematic body is like a static body, but can have velocity.
You can set kinematic body velocity or move it manually.
However, their velocity is not changed in collision or when you apply force.
Kinematic bodies do not collide with other kinematic or static bodies.
When a kinematic body collides with a dynamic body it behaves as if it has infinite mass.
- `dynamic` -
A dynamic body is fully simulated. They can be moved manually by the
user, but normally they move according to forces. A dynamic body can
collide with all body types. A dynamic body always has finite, non-zero
mass. If you try to set the mass of a dynamic body to zero, it will
automatically acquire a mass of one kilogram and it won't rotate.
Bodies are the backbone for fixtures (shapes). Bodies carry fixtures and
move them around in the world. Bodies are always rigid bodies in Planck.js.
That means that two fixtures attached to the same rigid body never move
relative to each other and fixtures attached to the same body don't
collide.
Fixtures have collision geometry and density. Normally, bodies acquire
their mass properties from the fixtures. However, you can override the
mass properties after a body is constructed.
You usually keep references to all the bodies you create. This way you can
query the body positions to update the positions of your graphical
entities. You should also keep body references so you can destroy them
when you are done with them.
## Body Factory
Bodies are created and destroyed using a body factory provided by the
`World` class. This lets the world create the body and add the body to the
world data structure.
```js
let dynamicBody = myWorld.createBody(bodyDef);
// ... do stuff ...
myWorld.destroyBody(dynamicBody);
```
> **Caution**:
> You should never create a body directly using new. The world won't
> know about the body and the body won't be properly initialized.
Planck.js does not keep a reference to the body definition or any of the
data it holds (except user data references). So you can create temporary
body definitions and reuse the same body definitions.
When you destroy a body, the attached fixtures and joints are
automatically destroyed. This has important implications for how you
manage shape and joint references.
## Body Definition
Let's go over some of the key members of the body definition.
### Body Type
As discussed at the beginning of this chapter, there are three different
body types: static, kinematic, and dynamic. You should specify the
body type at creation because changing the body type later is expensive.
```js
world.createBody({
type: 'dynamic'
});
```
Default body type is static, static bodies don't move in simulations.
### Position and Angle
The body definition gives you the chance to initialize the position of
the body on creation. This has far better performance than creating the
body at the world origin and then moving the body.
> **Caution**:
> Do not create a body at the origin and then move it. If you create
> several bodies at the origin, then performance will suffer.
A body has two main points of interest. The first point is the body's
origin. Fixtures and joints are attached relative to the body's origin.
The second point of interest is the center of mass. The center of mass
is determined from mass distribution of the attached shapes or is
explicitly set with `MassData`. Much of Planck.js's internal computations
use the center of mass position. For example `Body` stores the linear
velocity for the center of mass.
When you are building the body definition, you may not know where the
center of mass is located. Therefore you specify the position of the
body's origin. You may also specify the body's angle in radians, which
is not affected by the position of the center of mass. If you later
change the mass properties of the body, then the center of mass may move
on the body, but the origin position does not change and the attached
shapes and joints do not move.
```js
world.createBody({
position: {x: 0, y: 2}, // the body's origin position.
angle: 0.25 * Math.PI // the body's angle in radians.
})
```
A rigid body is also a frame of reference. You can define fixtures and
joints in that frame. Those fixtures and joint anchors never move in the
local frame of the body.
### Damping
Damping is used to reduce the world velocity of bodies. Damping is
different than friction because friction only occurs with contact.
Damping is not a replacement for friction and the two effects should be
used together.
Damping parameters should be between 0 and infinity, with 0 meaning no
damping, and infinity meaning full damping. Normally you will use a
damping value between 0 and 0.1. I generally do not use linear damping
because it makes bodies look like they are floating.
```js
world.createBody({
linearDamping: 0,
angularDamping: 0.01
});
```
Damping is approximated for stability and performance. At small damping
values the damping effect is mostly independent of the time step. At
larger damping values, the damping effect will vary with the time step.
This is not an issue if you use a fixed time step (recommended).
### Gravity Scale
You can use the gravity scale to adjust the gravity on a single body. Be
careful though, increased gravity can decrease stability.
```js
// Set the gravity scale to zero so this body will float
world.createBody({
gravityScale: 0
});
```
### Sleep Parameters
It is expensive to simulate bodies, so the less we have to simulate the better.
When a body comes to rest we would like to stop simulating it.
When Planck.js determines that a body (or group of bodies) has come to rest,
the body enters a sleep state which has very little CPU overhead. If a
body is awake and collides with a sleeping body, then the sleeping body
wakes up. Bodies will also wake up if a joint or contact attached to
them is destroyed. You can also wake a body manually.
The body definition lets you specify whether a body can sleep and
whether a body is created sleeping.
```js
world.createBody({
allowSleep: true,
awake: true,
});
```
### Fixed Rotation
You may want a body, such as a character, to have a fixed
rotation. Such a body should not rotate, even under load. You can use
the fixed rotation setting to achieve this:
```js
world.createBody({
fixedRotation: true
});
```
The fixed rotation flag causes the rotational inertia and its inverse to
be set to zero.
### Bullets
Game simulation usually generates a sequence of images that are played
at some frame rate. This is called discrete simulation. In discrete
simulation, rigid bodies can move by a large amount in one time step. If
a physics engine doesn't account for the large motion, you may see some
objects incorrectly pass through each other. This effect is called
tunneling.
By default, Planck.js uses continuous collision detection (CCD) to prevent
dynamic bodies from tunneling through static bodies. This is done by
sweeping shapes from their old position to their new positions. The
engine looks for new collisions during the sweep and computes the time
of impact (TOI) for these collisions. Bodies are moved to their first
TOI and then the solver performs a sub-step to complete the full time
step. There may be additional TOI events within a sub-step.
Normally CCD is not used between dynamic bodies. This is done to keep
performance reasonable. In some game scenarios you need dynamic bodies
to use CCD. For example, you may want to shoot a high speed bullet at a
stack of dynamic bricks. Without CCD, the bullet might tunnel through
the bricks.
Fast moving objects in Planck.js can be labeled as bullets. Bullets will
perform CCD with both static and dynamic bodies. You should decide what
bodies should be bullets based on your game design. If you decide a body
should be treated as a bullet, use the following setting.
```js
world.createBody({
bullet: true,
});
```
The bullet flag only affects dynamic bodies.
### Activation
You may wish a body to be created but not participate in collision or
dynamics. This state is similar to sleeping except the body will not be
woken by other bodies and the body's fixtures will not be placed in the
broad-phase. This means the body will not participate in collisions, ray
casts, etc.
You can create a body in an inactive state and later re-activate it.
```js
world.createBody({
active: false,
});
```
Joints may be connected to inactive bodies. These joints will not be
simulated. You should be careful when you activate a body that its
joints are not distorted.
Note that activating a body is almost as expensive as creating the body
from scratch. So you should not use activation for streaming worlds. Use
creation/destruction for streaming worlds to save memory.
### User Data
User data is an untyped reference. This gives you a hook to link your
application objects to bodies.
```js
world.createBody({
userData: myActor,
});
```
## Using a Body
After creating a body, there are many operations you can perform on the
body. These include setting mass properties, accessing position and
velocity, applying forces, and transforming points and vectors.
### Mass Data
A body has mass (scalar), center of mass (2-vector), and rotational
inertia (scalar). For static bodies, the mass and rotational inertia are
set to zero. When a body has fixed rotation, its rotational inertia is
zero.
Normally the mass properties of a body are established automatically
when fixtures are added to the body. You can also adjust the mass of a
body at run-time. This is usually done when you have special game
scenarios that require altering the mass.
```js
body.setMassData(massData);
```
After setting a body's mass directly, you may wish to revert to the
natural mass dictated by the fixtures. You can do this with:
```js
body.resetMassData();
```
The body's mass data is available through the following functions:
```js
body.getMass(); // number
body.getInertia(); // number
body.getLocalCenter(); // Vec2
body.getMassData(massData);
```
### State Information
There are many aspects to the body's state. You can access this state
data efficiently through the following functions:
```js
body.setType(bodyType);
body.getType(); // string
body.setBullet(flag);
body.isBullet(); // boolean
body.setSleepingAllowed(flag);
body.isSleepingAllowed(); // boolean
body.setAwake(flag);
body.isAwake(); // boolean
body.setEnabled(flag);
body.isEnabled(); // boolean
body.setFixedRotation(flag);
body.isFixedRotation(); // boolean
```
### Position and Velocity
You can access the position and rotation of a body. This is common when
rendering your associated game actor. You can also set the position and rotation,
although this is less common since you will normally use Planck.js to
simulate movement.
```js
body.setTransform(position, angle);
body.getTransform(); // Transform
body.setPosition(position);
body.getPosition(); // Vec2
body.setAngle(angle);
body.getAngle(); // number
```
You can access the center of mass position in local and world
coordinates. Much of the internal simulation in Planck.js uses the center of
mass. However, you should normally not need to access it. Instead you
will usually work with the body transform. For example, you may have a
body that is square. The body origin might be a corner of the square,
while the center of mass is located at the center of the square.
```js
body.getWorldCenter(); // Vec2
body.getLocalCenter(); // Vec2
```
You can access the linear and angular velocity. The linear velocity is
for the center of mass. Therefore, the linear velocity may change if the
mass properties change.
### Forces and Impulses
You can apply forces, torques (rotational force), and impulses to a body.
When you apply a force or an impulse, you provide a world point where the load is applied.
This often results in a torque about the center of mass.
```js
body.applyForce(force, point); // force: Vec2, point: Vec2
body.applyTorque(torque);
body.applyLinearImpulse(impulse, point); // force: Vec2, point: Vec2
body.applyAngularImpulse(impulse);
```
Applying a force, torque, or impulse wakes the body. Sometimes this is
undesirable. For example, you may be applying a steady force and want to
allow the body to sleep to improve performance. In this case you can use
the following code.
```js
if (myBody.isAwake()) {
myBody.applyForce(myForce, myPoint);
}
```
### Coordinate Transformations
The body class has some utility functions to help you transform points
and vectors between local and world space.
A `localPoint` is a coordinate relative to the body's origin.
A `worldPoint` is a coordinate relative to the world's origin.
A `localVector` is a vector between two points relative to the body's origin.
A `worldVector` is a vector between two points relative to the world's origin.
Here "point" means a point's 2D coordinate, "vector" means the vector between two points.
In point conversion both position and angle of body are considered, in vector conversion only angle.
```js
body.getWorldPoint(localPoint); // Vec2
body.getLocalPoint(worldPoint); // Vec2
body.getWorldVector(localVector); // Vec2
body.getLocalVector(worldVector); // Vec2
```
### Accessing Fixtures, Joints, and Contacts
You can iterate over a body's fixtures.
```js
for (let fixture = body.getFixtureList(); fixture; fixture = fixture.getNext()) {
// do something with fixture
}
```
You can similarly iterate over the body's joint list.
```js
for (var joint = this.getJointList(); joint; joint = joint.getNext()) {
// do something with joint
}
```
The body also provides a list of associated contacts. You can use this
to get information about the current contacts. Be careful, because the
contact list may not contain all the contacts that existed during the
previous time step.

153
docs/pages/collision.md Normal file
View File

@ -0,0 +1,153 @@
## Collision
The Collision classes include shapes and functions that operate on them.
The module also contains a dynamic tree and broad-phase to acceleration
collision processing of large systems.
The collision classes are designed to be usable outside of the dynamic
system. For example, you can use the dynamic tree for other aspects of
your game besides physics.
However, the main purpose of Planck.js is to provide a rigid body physics
engine, so the using the collision module by itself may feel limited for
some applications. Likewise, I will not make a strong effort to document
it or polish the APIs.
### Contact Manifolds
Planck.js has functions to compute contact points for overlapping shapes. If
we consider circle-circle or circle-polygon, we can only get one contact
point and normal. In the case of polygon-polygon we can get two points.
These points share the same normal vector so Planck.js groups them into a
manifold structure. The contact solver takes advantage of this to
improve stacking stability.
![Contact Manifold](./images/manifolds.svg)
Normally you don't need to compute contact manifolds directly, however
you will likely use the results produced in the simulation.
The `Manifold` structure holds a normal vector and up to two contact
points. The normal and points are held in local coordinates. As a
convenience for the contact solver, each point stores the normal and
tangential (friction) impulses.
The data stored in `Manifold` is optimized for internal use. If you need
this data, it is usually best to use the `WorldManifold` structure to
generate the world coordinates of the contact normal and points. You
need to provide a `Manifold` and the shape transforms and radii.
```js
let worldManifold = manifold.getWorldManifold(null, transformA, shapeA.m_radius, transformB, shapeB.m_radius)
for (let i = 0; i < manifold.pointCount; ++i) {
let point = worldManifold.points[i]; // Vec2
// ...
}
```
Notice that the world manifold uses the point count from the original
manifold.
During simulation shapes may move and the manifolds may change. Points
may be added or removed. You can detect this using `GetPointStates()`.
```js
let state1 = []; // [PointState]
let state2 = []; // [PointState]
getPointStates(state1, state2, manifold1, manifold2);
if (state1[0] == PointState.removeState) {
// process event
}
```
### Distance
The `Distance` function can be used to compute the distance between two
shapes. The distance function needs both shapes to be converted into a
`DistanceProxy`. There is also some caching used to warm start the
distance function for repeated calls.
![Distance Function](./images/distance.svg)
### Time of Impact
If two shapes are moving fast, they may *tunnel* through each other in a
single time step.
![Tunneling](./images/tunneling2.svg)
The `TimeOfImpact` function is used to determine the time when two
moving shapes collide. This is called the *time of impact* (TOI). The
main purpose of `TimeOfImpact` is for tunnel prevention. In particular,
it is designed to prevent moving objects from tunneling outside of
static level geometry.
This function accounts for rotation and translation of both shapes,
however if the rotations are large enough, then the function may miss a
collision. However the function will still report a non-overlapped time
and will capture all translational collisions.
The time of impact function identities an initial separating axis and
ensures the shapes do not cross on that axis. This might miss collisions
that are clear at the final positions. While this approach may miss some
collisions, it is very fast and adequate for tunnel prevention.
![Captured Collision](./images/captured_toi.svg)
![Missed Collision](./images/missed_toi.svg)
It is difficult to put a restriction on the rotation magnitude. There
may be cases where collisions are missed for small rotations. Normally,
these missed rotational collisions should not harm game play. They tend
to be glancing collisions.
The function requires two shapes (converted to `DistanceProxy`) and two
`Sweep` structures. The sweep structure defines the initial and final
transforms of the shapes.
You can use fixed rotations to perform a *shape cast*. In this case, the
time of impact function will not miss any collisions.
## Dynamic Tree
The `DynamicTree` class is used by Planck.js to organize large numbers of
shapes efficiently. The class does not know about shapes. Instead it
operates on axis-aligned bounding boxes (AABBs) with user data pointers.
The dynamic tree is a hierarchical AABB tree. Each internal node in the
tree has two children. A leaf node is a single user AABB. The tree uses
rotations to keep the tree balanced, even in the case of degenerate
input.
The tree structure allows for efficient ray casts and region queries.
For example, you may have hundreds of shapes in your scene. You could
perform a ray cast against the scene in a brute force manner by ray
casting each shape. This would be inefficient because it does not take
advantage of shapes being spread out. Instead, you can maintain a
dynamic tree and perform ray casts against the tree. This traverses the
ray through the tree skipping large numbers of shapes.
A region query uses the tree to find all leaf AABBs that overlap a query
AABB. This is faster than a brute force approach because many shapes can
be skipped.
![Raycast](./images/raycast.svg)
![Overlap Test](./images/overlap_test.svg)
Normally you will not use the dynamic tree directly. Rather you will go
through the `World` class for ray casts and region queries. If you plan
to instantiate your own dynamic tree, you can learn how to use it by
looking at how Planck.js uses it.
## Broad-phase
Collision processing in a physics step can be divided into narrow-phase
and broad-phase. In the narrow-phase we compute contact points between
pairs of shapes. Imagine we have N shapes. Using brute force, we would
need to perform the narrow-phase for N*N/2 pairs.
The `BroadPhase` class reduces this load by using a dynamic tree for
pair management. This greatly reduces the number of narrow-phase calls.
Normally you do not interact with the broad-phase directly. Instead,
Planck.js creates and manages a broad-phase internally. Also, BroadPhase
is designed with Planck.js's simulation loop in mind, so it is likely not
suited for other use cases.

311
docs/pages/contacts.md Normal file
View File

@ -0,0 +1,311 @@
## Contacts
Contacts are objects created by Planck.js to manage collision between two
fixtures. If the fixture has children, such as a chain shape, then a
contact exists for each relevant child. There are different kinds of
contacts, derived from Contact, for managing contact between different
kinds of fixtures. For example there is a contact class for managing
polygon-polygon collision and another contact class for managing
circle-circle collision.
Here is some terminology associated with contacts.
#### Contact Point
A contact point is a point where two shapes touch. Planck.js approximates
contact with a small number of points.
#### Contact Normal
A contact normal is a unit vector that points from one shape to another.
By convention, the normal points from fixtureA to fixtureB.
#### Contact Separation
Separation is the opposite of penetration. Separation is negative when
shapes overlap. It is possible that future versions of Planck.js will create
contact points with positive separation, so you may want to check the
sign when contact points are reported.
#### Contact Manifold
Contact between two convex polygons may generate up to 2 contact points.
Both of these points use the same normal, so they are grouped into a
contact manifold, which is an approximation of a continuous region of
contact.
#### Normal Impulse
The normal force is the force applied at a contact point to prevent the
shapes from penetrating. For convenience, Planck.js works with impulses. The
normal impulse is just the normal force multiplied by the time step.
#### Tangent Impulse
The tangent force is generated at a contact point to simulate friction.
For convenience, this is stored as an impulse.
#### Contact Ids
Planck.js tries to re-use the contact force results from a time step as the
initial guess for the next time step. Planck.js uses contact ids to match
contact points across time steps. The ids contain geometric features
indices that help to distinguish one contact point from another.
Contacts are created when two fixture's AABBs overlap. Sometimes
collision filtering will prevent the creation of contacts. Contacts are
destroyed with the AABBs cease to overlap.
So you might gather that there may be contacts created for fixtures that
are not touching (just their AABBs). Well, this is correct. It's a
"chicken or egg" problem. We don't know if we need a contact object
until one is created to analyze the collision. We could delete the
contact right away if the shapes are not touching, or we can just wait
until the AABBs stop overlapping. Planck.js takes the latter approach
because it lets the system cache information to improve performance.
## Contact Class
As mentioned before, the contact class is created and destroyed by
Planck.js. Contact objects are not created by the user. However, you are
able to access the contact class and interact with it.
You can access the raw contact manifold:
```js
let manifold = contact.getManifold();
```
You can potentially modify the manifold, but this is generally not
supported and is for advanced usage.
There is a helper function to get the `WorldManifold`:
```js
contact.getWorldManifold(worldManifold);
```
This uses the current positions of the bodies to compute world positions
of the contact points.
Sensors do not create manifolds, so for them use:
```js
let touching = sensorContact.isTouching();
```
This function also works for non-sensors.
You can get the fixtures from a contact. From those you can get the
bodies.
```js
let fixtureA = myContact.getFixtureA();
let bodyA = fixtureA.getBody();
let actorA = bodyA.getUserData();
```
You can disable a contact. This only works inside the
`pre-solve` event, discussed below.
## Accessing Contacts
You can get access to contacts in several ways. You can access the
contacts directly on the world and body structures. You can also
implement a contact listener.
You can iterate over all contacts in the world:
```js
for (let c = myWorld.getContactList(); c; c = c.getNext()) {
// process c
}
```
You can also iterate over all the contacts on a body. These are stored
in a graph using a contact edge structure.
```js
for (let ce = myBody.getContactList(); ce; ce = ce.next) {
let c = ce.contact;
// process c
}
```
You can also access contacts using the contact listener that is
described below.
> **Caution**:
> Accessing contacts off World and Body may miss some transient
> contacts that occur in the middle of the time step. Use
> ContactListener to get the most accurate results.
## Contact Events
You can receive contact data by adding event listeners to world. The
World supports several events: begin-contact, end-contact, pre-solve,
and post-solve.
```js
world.on('begin-contact', function(contact) {
/* handle begin event */
});
world.on('end-contact', function(contact) {
/* handle end event */
});
world.on('pre-solve', function(contact, oldManifold) {
/* handle pre-solve event */
});
world.on('post-solve', function(contact, contactImpulse) {
/* handle post-solve event */
});
```
> **Caution**:
> Do not keep a reference to the pointers sent to ContactListener.
> Instead make a deep copy of the contact point data into your own buffer.
> The example below shows one way of doing this.
At run-time you can create an instance of the listener and register it
with world.on(). You can remove listener using world.off() function.
### Begin Contact Event
This is called when two fixtures begin to overlap. This is called for
sensors and non-sensors. This event can only occur inside the time step.
### End Contact Event
This is called when two fixtures cease to overlap. This is called for
sensors and non-sensors. This may be called when a body is destroyed, so
this event can occur outside the time step.
### Pre-Solve Event
This is called after collision detection, but before collision
resolution. This gives you a chance to disable the contact based on the
current configuration. For example, you can implement a one-sided
platform using this callback and calling Contact.setEnabled(false).
The contact will be re-enabled each time through collision processing,
so you will need to disable the contact every time-step. The pre-solve
event may be fired multiple times per time-step per contact due to
continuous collision detection.
```ts
world.on('pre-solve', function(contact: Contact, oldManifold: Manifold) {
WorldManifold worldManifold;
contact.getWorldManifold(&worldManifold);
if (worldManifold.normal.y < -0.5)
{
contact.setEnabled(false);
}
});
```
The pre-solve event is also a good place to determine the point state
and the approach velocity of collisions.
```js
world.on('pre-solve', function(contact, oldManifold) {
let worldManifold = contact.getWorldManifold();
let state1 = []; // [PointState]
let state2 = []; // [PointState]
getPointStates(state1, state2, oldManifold, contact.getManifold());
if (state2[0] === PointState.addState) {
let bodyA = contact.getFixtureA().getBody();
let bodyB = contact.getFixtureB().getBody();
let point = worldManifold.points[0];
let vA = bodyA.getLinearVelocityFromWorldPoint(point);
let vB = bodyB.getLinearVelocityFromWorldPoint(point);
let approachVelocity = Vec2.dot(vB -- vA, worldManifold.normal); //[todo]
if (approachVelocity > 1) {
myPlayCollisionSound();
}
}
});
```
### Post-Solve Event
The post solve event is where you can gather collision impulse results.
If you don't care about the impulses, you should probably just implement
the pre-solve event.
It is tempting to implement game logic that alters the physics world
inside a contact callback. For example, you may have a collision that
applies damage and try to destroy the associated actor and its rigid
body. However, Planck.js does not allow you to alter the physics world
inside a callback because you might destroy objects that Planck.js is
currently processing, leading to orphaned pointers.
The recommended practice for processing contact points is to buffer all
contact data that you care about and process it after the time step. You
should always process the contact points immediately after the time
step; otherwise some other client code might alter the physics world,
invalidating the contact buffer. When you process the contact buffer you
can alter the physics world, but you still need to be careful that you
don't orphan pointers stored in the contact point buffer. The testbed
has example contact point processing that is safe from orphaned
pointers.
This code from the CollisionProcessing test shows how to handle orphaned
bodies when processing the contact buffer. Here is an excerpt. Be sure
to read the comments in the listing. This code assumes that all contact
points have been buffered in the ContactPoint array m_points.
```js
// We are going to destroy some bodies according to contact
// points. We must buffer the bodies that should be destroyed
// because they may belong to multiple contact points.
let nuke = [];
// Traverse the contact results. Destroy bodies that
// are touching heavier bodies.
for (let i = 0; i < points.length && nuke.length < MAX_NUKE; ++i) {
let point = points[i];
let body1 = point.fixtureA.getBody();
let body2 = point.fixtureB.getBody();
let mass1 = body1.getMass();
let mass2 = body2.getMass();
if (mass1 > 0.0 && mass2 > 0.0) {
if (mass2 > mass1) {
nuke.push(body1);
} else {
nuke.push(body2);
}
}
}
for (let i = 0; i < nuke.length; i++) {
let b = nuke[i];
world.destroyBody(b);
}
```
## Contact Filtering
Often in a game you don't want all objects to collide. For example, you
may want to create a door that only certain characters can pass through.
This is called contact filtering, because some interactions are filtered
out.
Planck.js allows you to achieve custom contact filtering by implementing a
ContactFilter class. This class requires you to implement a
ShouldCollide function that receives two Shape pointers. Your function
returns true if the shapes should collide.
The default implementation of ShouldCollide uses the filter-data
defined in fixtures.
```js
Fixture.prototype.shouldCollide = function(that) {
if (that.m_filterGroupIndex === this.m_filterGroupIndex && that.m_filterGroupIndex !== 0) {
return that.m_filterGroupIndex > 0;
}
var collideA = (that.m_filterMaskBits & this.m_filterCategoryBits) !== 0;
var collideB = (that.m_filterCategoryBits & this.m_filterMaskBits) !== 0;
var collide = collideA && collideB;
return collide;
}
```
You can override it with your contact filter.
```js
Fixture.prototype.shouldCollide = function(that) {
// should this and that collide?
}
```

View File

@ -0,0 +1,51 @@
## Core Concepts
Planck.js works with several fundamental concepts and objects. We briefly
define these objects here and more details are given later in this
document.
### World
A physics world is a collection of bodies, fixtures, and constraints that interact together.
`World` also manages running simulation.
### Shape
A shape is a 2D geometrical object, such as a circle or polygon.
### Rigid Body
A chunk of matter that is so strong that the distance between any two bits of matter on the chunk is constant.
In the following discussion we use body interchangeably with rigid body.
### Fixture
A fixture binds a shape to a body and adds physical properties such as density, friction, and restitution.
A fixture puts a shape into the collision system (broad-phase) so that it can collide with other shapes.
### Constraint
A constraint is a physical connection that removes degrees of freedom from bodies.
A 2D body has 3 degrees of freedom (two position coordinates and one rotation coordinate).
If we take a body and pin it to the wall (like a pendulum) we have constrained the body to the wall.
At this point the body can only rotate about the pin, so the constraint has removed 2 degrees of freedom.
### Contact Constraint
A special constraint designed to prevent penetration of rigid bodies and to simulate friction and restitution.
You do not create contact constraints; they are created automatically when two objects might collide.
### Joint
This is a constraint used to hold two or more bodies together. There are several joint types implemented in the library: revolute, prismatic, distance, and more.
Some joints may have limits and motors.
A joint limit restricts the range of motion of a joint. For example, the human elbow only allows a certain range of angles.
A joint motor drives the motion of the connected bodies according to the joint's degrees of freedom. For example, you can use a motor to drive the rotation of an elbow.
### Solver
The physics world has a solver that is used to advance time and to resolve contact and joint constraints.
The Planck.js solver is a high-performance iterative solver that operates in order N time, where N is the number of constraints.
### Continuous Collision
The solver advances bodies in time using discrete time steps. Without intervention this can lead to tunneling.
![Tunneling Effect](./images/tunneling1.svg)
Planck.js contains specialized algorithms to deal with tunneling. First, the collision algorithms can interpolate the motion of two bodies to find the first time of impact (TOI).
Second, there is a sub-stepping solver that moves bodies to their first time of impact and then resolves the collision.

12
docs/pages/credits.md Normal file
View File

@ -0,0 +1,12 @@
#### Credits
Box2D is a popular C++ 2D rigid-body physics engine created by Erin Catto. Box2D is used in several popular games, such as Angry Birds, Limbo and Crayon Physics, as well as game development tools and libraries such as Apple's SpriteKit.
Planck.js is developed and maintained by Ali Shakiba.
TypeScript definitions for planck.js are developed by Oliver Zell.
#### License
Box2D and Planck.js are released under the MIT license. You can use them for all purposes, including commercial applications for no fee.

191
docs/pages/fixture.md Normal file
View File

@ -0,0 +1,191 @@
## Fixture
Shapes only have geometrical coordinates, they don't have physical properties and don't know about the body's transformation, so may be used independently of the physics simulation.
The `Fixture` class is used to attach shapes to bodies. A body may have zero or more fixtures. A
body with multiple fixtures is sometimes called a *compound body.*
Fixtures hold the following:
- a single shape
- broad-phase proxies
- density, friction, and restitution
- collision filtering flags
- back pointer to the parent body
- user data
- sensor flag
These are described in the following sections.
### Fixture Creation
Fixtures are created by initializing a fixture definition and then
passing the definition to the parent body.
```js
let myFixture = myBody.createFixture({
shape: myShape,
density: 1,
});
```
This creates the fixture and attaches it to the body. You do not need to
store the fixture pointer since the fixture will automatically be
destroyed when the parent body is destroyed. You can create multiple
fixtures on a single body.
You can destroy a fixture on the parent body. You may do this to model a
breakable object. Otherwise you can just leave the fixture alone and let
the body destruction take care of destroying the attached fixtures.
```js
myBody.destroyFixture(myFixture);
```
### Density
The fixture density is used to compute the mass properties of the parent
body. The density can be zero or positive. You should generally use
similar densities for all your fixtures. This will improve stacking
stability.
The mass of a body is not adjusted when you set the density. You must
call resetMassData for this to occur.
```js
fixture.setDensity(5);
body.resetMassData();
```
### Friction
Friction is used to make objects slide along each other realistically.
Planck.js supports static and dynamic friction, but uses the same parameter
for both. Friction is simulated accurately in Planck.js and the friction
strength is proportional to the normal force (this is called Coulomb
friction). The friction parameter is usually set between 0 and 1, but
can be any non-negative value. A friction value of 0 turns off friction
and a value of 1 makes the friction strong. When the friction force is
computed between two shapes, Planck.js must combine the friction parameters
of the two parent fixtures. This is done with the geometric mean:
```js
function mixFriction(friction1, friction2) {
return Math.sqrt(friction1 * friction2);
}
```
So if one fixture has zero friction then the contact will have zero
friction.
You can override the default mixed friction using
`contact.setFriction`. This is usually done in the contact listener
callback.
### Restitution
Restitution is used to make objects bounce. The restitution value is
usually set to be between 0 and 1. Consider dropping a ball on a table.
A value of zero means the ball won't bounce. This is called an
inelastic collision. A value of one means the ball's velocity will be
exactly reflected. This is called a perfectly elastic collision.
Restitution is combined using the following formula.
```js
function mixRestitution(restitution1, restitution2) {
return Math.max(restitution1, restitution2);
}
```
Restitution is combined this way so that you can have a bouncy super
ball without having a bouncy floor.
You can override the default mixed restitution using
`contact.setRestitution`. This is usually done in the contact listener
callback.
When a shape develops multiple contacts, restitution is simulated
approximately. This is because Planck.js uses an iterative solver. Planck.js
also uses inelastic collisions when the collision velocity is small.
This is done to prevent jitter. See `Settings.velocityThreshold`.
### Filtering
Collision filtering allows you to prevent collision between fixtures.
For example, say you make a character that rides a bicycle. You want the
bicycle to collide with the terrain and the character to collide with
the terrain, but you don't want the character to collide with the
bicycle (because they must overlap). Planck.js supports such collision
filtering using categories and groups.
Planck.js supports 64 [todo?] collision categories. For each fixture you can specify
which category it belongs to. You also specify what other categories
this fixture can collide with. For example, you could specify in a
multiplayer game that all players don't collide with each other and
monsters don't collide with each other, but players and monsters should
collide. This is done with masking bits. For example:
```js
let playerFixtureDef = {
filterCategoryBits: parseInt('010', 2),
filterMaskBits: parseInt('100', 2),
};
let monsterFixtureDef = {
filterCategoryBits: parseInt('100', 2),
filterMaskBits: parseInt('010', 2),
};
```
Here is the rule for a collision to occur:
```js
let catA = fixtureA.filterCategoryBits;
let maskA = fixtureA.filterMaskBits;
let catB = fixtureB.filterCategoryBits;
let maskB = fixtureB.filterMaskBits;
if ((catA & maskB) !== 0 && (catB & maskA) !== 0) {
// fixtures can collide
}
```
Collision groups let you specify an integral group index. You can have
all fixtures with the same group index always collide (positive index)
or never collide (negative index). Group indices are usually used for
things that are somehow related, like the parts of a bicycle. In the
following example, `fixture1` and `fixture2` always collide, but `fixture3`
and `fixture4` never collide.
```js
fixture1Def.filterGroupIndex = 2;
fixture2Def.filterGroupIndex = 2;
fixture3Def.filterGroupIndex = -8;
fixture4Def.filterGroupIndex = -8;
```
Collisions between fixtures of different group indices are filtered
according to the category and mask bits. In other words, group filtering
has higher precedence than category filtering.
Note that additional collision filtering occurs in Planck.js. Here is a
list:
- A fixture on a static body can only collide with a dynamic body.
- A fixture on a kinematic body can only collide with a dynamic body.
- Fixtures on the same body never collide with each other.
- You can optionally enable/disable collision between fixtures on bodies connected by a joint.
Sometimes you might need to change collision filtering after a fixture
has already been created. You can get and set the Filter structure on
an existing fixture using fixture.getFilterData and
fixture.setFilterData. Note that changing the filter data will not
add or remove contacts until the next time step (see the World class).
### Sensors
Sometimes game logic needs to know when two fixtures overlap yet there
should be no collision response. This is done by using sensors. A sensor
is a fixture that detects collision but does not produce a response.
You can flag any fixture as being a sensor. Sensors may be static,
kinematic, or dynamic. Remember that you may have multiple fixtures per
body and you can have any mix of sensors and solid fixtures. Also,
sensors only form contacts when at least one body is dynamic, so you
will not get a contact for kinematic versus kinematic, kinematic versus
static, or static versus static.
Sensors do not generate contact points. There are two ways to get the
state of a sensor:
1. `contact.isTouching()`
2. `begin-contact` and `end-contact` events

104
docs/pages/hello-world.md Normal file
View File

@ -0,0 +1,104 @@
## Hello World
In this section we will walk through a simple example to set up the physics world, and create a platform and a small box.
### Creating a World
Every Planck.js program begins with the creation of a World object.
World is the physics hub that manages objects, their physical interactions, and runs simulation.
To create a world we simply create an object from the `World` class, and optionally pass gravity.
```js
let world = new World({
gravity: {x: 0, y: -10},
});
```
Now that we have our physics world set up, let's start adding some stuff to it.
### Creating a platform
We will create a platform using the following steps:
1. Use the world object to create the body with position.
1. Create a fixture on the body with a shape.
For step 1, we pass body properties to the world object to create the platform body.
With the body properties we specify the type and initial position of the platform:
```js
let platform = world.createBody({
type: "static",
position: {x: 0, y: -10},
angle: Math.PI * 0.1
});
```
Bodies are "static" by default. Static bodies don't collide with other static bodies and are immovable.
For step 2, we need to create a `Shape` and add it to body as `Fixture`.
```js
platform.createFixture({
shape: new Edge({x: -50, y: 0}, {x: +50, y: 0}),
});
```
Shapes only have geometrical properties (such as vertices or radius), and do not have physical properties.
A fixture is used to add a shape to a body, and adds physical properties (such as density, friction, etc.) to a body.
A body can have any number of shapes fixed together.
`Shape`'s geometrical coordinates are local to the body. A fixture does not have location and angle. So when a body moves, all fixtures/shapes in the body move with the body. However we don't move a shape around on the body.
Planck.js is a rigid body engine and many of the assumptions made in Planck.js are based on the rigid body model.
A body with morphing shapes is not a rigid body, and if this is violated many things will break.
So moving or modifying a shape that is on a body is not supported.
Every fixture must have a parent body, even fixtures that are static.
However, you can attach all static fixtures to a single static body.
A static body has zero mass by definition, so we don't need to specify density in this case.
Later we will see how to use a fixture's properties to customize its physical behavior.
### Creating a dynamic box
Creating a dynamic box is similar to the platform. The main difference, besides dimensions, is that for a dynamic body we need to specify mass properties.
First we create the body using `createBody`. By default bodies are static, so we should set the body's `type` at construction time to make the body dynamic.
```js
let body = world.createBody({
type: "dynamic",
position: {x: 0, y: 4}
});
```
> **Caution**:
> You must set the body `type` to `dynamic` if you want the body to move in response to forces.
Next we create and attach a box shape using a fixture definition.
```js
body.createFixture({
shape: new Box(1.0, 1.0),
density: 1.0,
friction: 0.3,
});
```
Notice that we set density to 1. The default density is zero. Setting fixture's density automatically updates the mass of the body. Also, the friction on the shape is set to 0.3.
> **Caution**:
> A dynamic body should have at least one fixture with a non-zero density. Otherwise you will get strange behavior.
You can add as many fixtures as you like to a body. Each one contributes to the total mass.
Box dimensions are specified as the **half-width** and **half-height** (like a circler radius).
So in this case the ground box is 2 units wide (x-axis) and 2 units tall (y-axis).
### Units
Planck.js by default is tuned for meters, kilograms, and seconds. So you can consider the dimensions to be in meters.
Planck.js generally works best when objects are the size of typical real world objects. For example, a barrel is about 1 meter tall.
Due to the limitations of floating point arithmetic, using Planck.js to model the movement of glaciers or dust particles is not a good idea.
If you use a different units for your objects, you can change the value of `Settings.lengthUnitsPerMeter`.
For example if you use pixels and a barrel height is 80 pixels set the `lengthUnitsPerMeter` to 80.

Binary file not shown.

After

Width:  |  Height:  |  Size: 912 B

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="296.5" height="142.844"><path fill="none" stroke="#000" d="M.5 125.343H296v17H.5zM131.673.704l6.16 5.104-85.506 103.175-6.16-5.105z"/><path fill="none" stroke="#000" d="M145.05 3.9l7.847-1.555 26.053 131.443-7.847 1.555z"/><text style="line-height:0%;-inkscape-font-specification:Calibri;text-align:start" x="328" y="465.362" font-weight="400" font-family="Calibri" transform="translate(-245 -431.019)"><tspan x="328" y="465.362" style="line-height:1.25" font-size="12">t=0</tspan></text><text style="line-height:0%;-inkscape-font-specification:Calibri;text-align:start" x="419.5" y="465.339" font-weight="400" font-family="Calibri" transform="translate(-245 -431.019)"><tspan x="419.5" y="465.339" style="line-height:1.25" font-size="12">t=1</tspan></text><path fill="none" stroke="#000" stroke-dasharray="1,2" d="M133.627 4.619l6.888 4.068-68.14 115.381L65.486 120z"/></svg>

After

Width:  |  Height:  |  Size: 923 B

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="401.76" height="216.621"><g transform="translate(-184.534 -272.828)"><path d="M187.768 435.596l66.003 30.73 70.027-17.56s66.002 36.583 70.027 38.046c4.024 1.463 84.417-38.312 84.417-38.312l104.736-34.122-76.466-98.041 58.758-35.852" fill="none" stroke="#767676" stroke-width=".76"/><circle transform="translate(-54.372 -177.182)" cx="241.932" cy="611.936" r="2.525" fill="#b0ddb3" stroke="#7d7d7d" stroke-linecap="round" stroke-linejoin="round"/><circle transform="translate(11.817 -145.14)" cx="241.932" cy="611.936" r="2.525" fill="#b0ddb3" stroke="#7d7d7d" stroke-linecap="round" stroke-linejoin="round"/><circle transform="translate(81.492 -163.513)" cx="241.932" cy="611.936" r="2.525" fill="#b0ddb3" stroke="#7d7d7d" stroke-linecap="round" stroke-linejoin="round"/><circle transform="translate(235.876 -162.86)" cx="241.932" cy="611.936" r="2.525" fill="#b0ddb3" stroke="#7d7d7d" stroke-linecap="round" stroke-linejoin="round"/><circle transform="translate(152.385 -125.513)" cx="241.932" cy="611.936" r="2.525" fill="#b0ddb3" stroke="#7d7d7d" stroke-linecap="round" stroke-linejoin="round"/><circle transform="translate(341.337 -197.586)" cx="241.932" cy="611.936" r="2.525" fill="#b0ddb3" stroke="#7d7d7d" stroke-linecap="round" stroke-linejoin="round"/><circle transform="translate(265.173 -295.863)" cx="241.932" cy="611.936" r="2.525" fill="#b0ddb3" stroke="#7d7d7d" stroke-linecap="round" stroke-linejoin="round"/><circle transform="translate(323.653 -332.435)" cx="241.932" cy="611.936" r="2.525" fill="#b0ddb3" stroke="#7d7d7d" stroke-linecap="round" stroke-linejoin="round"/><text style="line-height:0%;-inkscape-font-specification:Calibri;text-align:start" x="196.41" y="429.327" font-weight="400" font-family="Calibri" letter-spacing="0" word-spacing="0"><tspan x="196.41" y="429.327" style="line-height:1.25" font-size="14">isolated</tspan></text><text y="282.35" x="502.991" style="line-height:0%;-inkscape-font-specification:Calibri;text-align:start" font-weight="400" font-family="Calibri" letter-spacing="0" word-spacing="0"><tspan y="282.35" x="502.991" style="line-height:1.25" font-size="14">isolated</tspan></text></g></svg>

After

Width:  |  Height:  |  Size: 2.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="271.283" height="111.33"><path d="M178.699 69.312l-62 .473" fill="none" stroke="#000" stroke-width="1.214" stroke-dasharray="1.21355975,2.4271195"/><path d="M177.699 12.549l79-1 14 56-91 43zM36.897.81l80.641 69.26L.811 78.545z" fill="none" stroke="#000"/><path fill="#0f0" d="M176.199 65.048h7v7h-7zM113.699 65.548h7v7h-7z"/></svg>

After

Width:  |  Height:  |  Size: 378 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="262.63" height="103.721"><defs><marker orient="auto" refY="0" refX="0" id="a" overflow="visible"><path d="M-1.2 0l-1 1 3.5-1-3.5-1z" fill-rule="evenodd" stroke="#000" stroke-width=".2666"/></marker><marker orient="auto" refY="0" refX="0" id="b" overflow="visible"><path d="M-4 0l-2 2 7-2-7-2z" fill-rule="evenodd" stroke="#000" stroke-width=".5332"/></marker></defs><g transform="translate(-286.888 -532.208)"><path d="M289.914 613.45l255.558 1.516" fill="none" stroke="#7d7d7d" stroke-linecap="round"/><circle transform="translate(47.982 1.515)" cx="241.932" cy="611.936" r="2.525" fill="#b0ddb3" stroke="#7d7d7d" stroke-linecap="round" stroke-linejoin="round"/><circle transform="translate(181.322 2.525)" cx="241.932" cy="611.936" r="2.525" fill="#b0ddb3" stroke="#7d7d7d" stroke-linecap="round" stroke-linejoin="round"/><circle transform="translate(304.561 3.536)" cx="241.932" cy="611.936" r="2.525" fill="#b0ddb3" stroke="#7d7d7d" stroke-linecap="round" stroke-linejoin="round"/><path fill="#d7e3f4" stroke="#7d7d7d" stroke-linecap="round" stroke-linejoin="round" d="M375.231 569.509h47.982v41.921h-47.982z"/><path d="M373.756 552.337h51.013" fill="none" stroke="#000" stroke-width="4" marker-end="url(#a)"/><path d="M454.548 609.915h-28.284" fill="none" stroke="#000" marker-end="url(#b)"/><text style="line-height:0%;-inkscape-font-specification:Calibri;text-align:start" x="370.221" y="541.73" font-weight="400" font-family="Calibri" letter-spacing="0" word-spacing="0"><tspan x="370.221" y="541.73" style="line-height:1.25" font-size="14">box motion</tspan></text><text style="line-height:0%;-inkscape-font-specification:Calibri;text-align:start" x="439.286" y="606.291" font-weight="400" font-family="Calibri" letter-spacing="0" word-spacing="0"><tspan x="439.286" y="606.291" style="line-height:1.25" font-size="14">internal normal</tspan></text><text style="line-height:0%;-inkscape-font-specification:Calibri;text-align:start" x="328.929" y="633.434" font-weight="400" font-family="Calibri" letter-spacing="0" word-spacing="0"><tspan x="328.929" y="633.434" style="line-height:1.25" font-size="14">edge1</tspan></text><text style="line-height:0%;-inkscape-font-specification:Calibri;text-align:start" x="460.783" y="633.362" font-weight="400" font-family="Calibri" letter-spacing="0" word-spacing="0"><tspan x="460.783" y="633.362" style="line-height:1.25" font-size="14">edge2</tspan></text></g></svg>

After

Width:  |  Height:  |  Size: 2.4 KiB

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="248.004" height="94.101"><g transform="translate(-270.195 -531.497)"><path d="M291.786 534.505l66.428 52.5" fill="none" stroke="#7d7d7d" stroke-dasharray="1,3"/><path d="M358.214 586.648l80.715-26.072" fill="none" stroke="#7d7d7d"/><path d="M438.571 560.576l56.786 32.143" fill="none" stroke="#7d7d7d" stroke-dasharray="1,3"/><circle transform="translate(49.054 -77.413)" cx="241.932" cy="611.936" r="2.525" fill="#b0ddb3" stroke="#7d7d7d" stroke-linecap="round" stroke-linejoin="round"/><circle transform="translate(116.322 -24.975)" cx="241.932" cy="611.936" r="2.525" fill="#b0ddb3" stroke="#7d7d7d" stroke-linecap="round" stroke-linejoin="round"/><circle transform="translate(254.918 -18.607)" cx="241.932" cy="611.936" r="2.525" fill="#b0ddb3" stroke="#7d7d7d" stroke-linecap="round" stroke-linejoin="round"/><circle transform="translate(197.061 -51.107)" cx="241.932" cy="611.936" r="2.525" fill="#b0ddb3" stroke="#7d7d7d" stroke-linecap="round" stroke-linejoin="round"/><text style="line-height:0%;-inkscape-font-specification:Calibri;text-align:start" x="492.143" y="610.576" font-weight="400" font-family="Calibri" letter-spacing="0" word-spacing="0"><tspan x="492.143" y="610.576" style="line-height:1.25" font-size="14">v0</tspan></text><text y="577.362" x="432.5" style="line-height:0%;-inkscape-font-specification:Calibri;text-align:start" font-weight="400" font-family="Calibri" letter-spacing="0" word-spacing="0"><tspan y="577.362" x="432.5" style="line-height:1.25" font-size="14">v1</tspan></text><text style="line-height:0%;-inkscape-font-specification:Calibri;text-align:start" x="349.643" y="602.719" font-weight="400" font-family="Calibri" letter-spacing="0" word-spacing="0"><tspan x="349.643" y="602.719" style="line-height:1.25" font-size="14">v2</tspan></text><text y="552.005" x="283.929" style="line-height:0%;-inkscape-font-specification:Calibri;text-align:start" font-weight="400" font-family="Calibri" letter-spacing="0" word-spacing="0"><tspan y="552.005" x="283.929" style="line-height:1.25" font-size="14">v3</tspan></text><text style="line-height:0%;-inkscape-font-specification:Calibri;text-align:start" x="269.286" y="565.934" font-weight="400" font-family="Calibri" letter-spacing="0" word-spacing="0"><tspan x="269.286" y="565.934" style="line-height:1.25" font-size="14">(ghost)</tspan></text><text style="line-height:0%;-inkscape-font-specification:Calibri;text-align:start" x="479.214" y="623.103" font-weight="400" font-family="Calibri" letter-spacing="0" word-spacing="0"><tspan x="479.214" y="623.103" style="line-height:1.25" font-size="14">(ghost)</tspan></text></g></svg>

After

Width:  |  Height:  |  Size: 2.6 KiB

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="278.649" height="199.681"><defs><marker orient="auto" refY="0" refX="0" id="a" overflow="visible"><path d="M8.719 4.034L-2.207.016 8.719-4.002c-1.746 2.372-1.736 5.618 0 8.036z" transform="scale(-.6)" font-size="12" fill-rule="evenodd" stroke-width=".625" stroke-linejoin="round"/></marker></defs><g transform="translate(-208.193 -534.314)"><path d="M227 602.362l79-1 14 56-91 43z" fill="none" stroke="#000"/><path d="M246.198 535.123l80.642 69.26-116.727 8.476z" fill="none" stroke="#000"/><path fill="#0f0" d="M224 608.362h7v7h-7zM303.5 602.362h7v7h-7z"/><path d="M386 601.862l79-1 14 56-91 43z" fill="none" stroke="#000"/><circle transform="translate(-2 14)" cx="428.75" cy="556.612" r="34.75" fill="none" stroke="#000"/><path fill="#0f0" d="M424.5 602.862h7v7h-7z"/><path d="M264 601.362v-26.5M427.51 601.024v-26.5" fill="none" stroke="#000" marker-end="url(#a)"/><text style="line-height:0%;-inkscape-font-specification:Calibri;text-align:start" x="208" y="731.862" font-weight="400" font-family="Calibri"><tspan x="208" y="731.862" style="line-height:1.25" font-size="12">two points, one normal</tspan></text><text style="line-height:0%;-inkscape-font-specification:Calibri;text-align:start" x="378.831" y="731.862" font-weight="400" font-family="Calibri"><tspan x="378.831" y="731.862" style="line-height:1.25" font-size="12">one point, one normal</tspan></text></g></svg>

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="296.5" height="148.657"><defs><marker orient="auto" refY="0" refX="0" id="a" overflow="visible"><path d="M8.719 4.034L-2.207.016 8.719-4.002c-1.746 2.372-1.736 5.618 0 8.036z" transform="scale(-.6)" font-size="12" fill-rule="evenodd" stroke-width=".625" stroke-linejoin="round"/></marker></defs><path fill="none" stroke="#000" d="M.5 131.157H296v17H.5zM134.187.645l7.473 2.857-47.847 125.166-7.473-2.856zM154.67 3.854l7.488-2.816L209.33 126.46l-7.487 2.816z"/><path fill="none" stroke="#000" stroke-dasharray="2,4" d="M144 4.157h8v134h-8z"/><text style="line-height:0%;-inkscape-font-specification:Calibri;text-align:start" x="340.5" y="466.362" font-weight="400" font-family="Calibri" transform="translate(-245 -425.205)"><tspan x="340.5" y="466.362" style="line-height:1.25" font-size="12">t=0</tspan></text><text style="line-height:0%;-inkscape-font-specification:Calibri;text-align:start" x="432.5" y="466.339" font-weight="400" font-family="Calibri" transform="translate(-245 -425.205)"><tspan x="432.5" y="466.339" style="line-height:1.25" font-size="12">t=1</tspan></text><path d="M500.5 556.362v-40.5" fill="none" stroke="#000" marker-end="url(#a)" transform="translate(-245 -425.205)"/><text style="line-height:0%;-inkscape-font-specification:Calibri;text-align:start" x="462.5" y="507.862" font-weight="400" font-family="Calibri" transform="translate(-245 -425.205)"><tspan x="462.5" y="507.862" style="line-height:1.25" font-size="12">separating axis</tspan></text></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="216.625" height="229"><defs><marker orient="auto" refY="0" refX="0" id="a" overflow="visible"><path d="M8.719 4.034L-2.207.016 8.719-4.002c-1.746 2.372-1.736 5.618 0 8.036z" transform="matrix(-1.1 0 0 -1.1 -1.1 0)" font-size="12" fill-rule="evenodd" stroke-width=".625" stroke-linejoin="round"/></marker></defs><path fill="#d7e3f4" d="M0 92h120v46H0zM96.625 0h120v46h-120z"/><text style="line-height:0%;-inkscape-font-specification:Calibri;text-align:start" x="310.137" y="351.927" font-weight="400" font-family="Calibri" transform="translate(-183 -324.362)"><tspan x="310.137" y="351.927" style="line-height:1.25" font-size="16">Common</tspan></text><text style="line-height:0%;-inkscape-font-specification:Calibri;text-align:start" x="215.793" y="442.927" font-weight="400" font-family="Calibri" transform="translate(-183 -324.362)"><tspan x="215.793" y="442.927" style="line-height:1.25" font-size="16">Collision</tspan></text><path fill="#d7e3f4" d="M96.625 183h120v46h-120z"/><text style="line-height:0%;-inkscape-font-specification:Calibri;text-align:start" x="307.945" y="535.927" font-weight="400" font-family="Calibri" transform="translate(-183 -324.362)"><tspan x="307.945" y="535.927" style="line-height:1.25" font-size="16">Dynamics</tspan></text><path d="M315.469 370.362l-48.313 46M267.422 462.362l47.781 45M339.625 370.362v137" fill="none" stroke="#000" marker-end="url(#a)" transform="translate(-183 -324.362)"/></svg>

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="231.149" height="184.63"><g fill="none"><path stroke="#00d200" d="M22.472 67.472h19.816v16.816H22.472zM168.463 22.963h54.335v36.335h-54.335zM12.153 142.653h35.454v21.954H12.153z"/><path stroke="#000" d="M198.61 102.11h32.039v20.539H198.61z"/><path stroke="#00d200" d="M96.597 118.097h43.567v61.067H96.597zM83.016 23.516h33.728v66.228H83.016zM164.735 141.235h33.79v30.79h-33.79z"/><path stroke="#000" d="M.5.5h49.26v43.76H.5z"/><path stroke="#000" stroke-dasharray="2,4" d="M38.13 56.13h149.5v128H38.13z"/></g></svg>

After

Width:  |  Height:  |  Size: 562 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.4 KiB

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="248.014" height="218.692"><defs><marker orient="auto" refY="0" refX="0" id="a" overflow="visible"><path d="M8.719 4.034L-2.207.016 8.719-4.002c-1.746 2.372-1.736 5.618 0 8.036z" transform="scale(-.6)" font-size="12" fill-rule="evenodd" stroke-width=".625" stroke-linejoin="round"/></marker></defs><g fill="none" stroke="#000"><path d="M39.337 106.5h19.816v16.816H39.337zM185.328 61.991h54.335v36.335h-54.335zM29.018 181.681h35.454v21.954H29.018zM215.476 141.14h32.038v20.537h-32.038zM113.462 157.125h43.567v61.067h-43.567zM99.88 62.544h33.729v66.228H99.88zM181.6 180.263h33.79v30.791H181.6zM17.365 39.528h49.26v43.76h-49.26z"/><path d="M413.965 367.897l-219.93 175.43" stroke-dasharray="1,2" marker-end="url(#a)" transform="translate(-193.005 -367.204)"/><path d="M414.268 367.594l-86.856 69.282" marker-end="url(#a)" transform="translate(-193.005 -367.204)"/></g></svg>

After

Width:  |  Height:  |  Size: 917 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.9 KiB

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="335.57" height="156.773"><g transform="translate(-250.723 -313.047)"><path d="M253.77 466.326l70.028-17.56s71.558-119.486 75.583-118.023c4.024 1.464 78.861 117.757 78.861 117.757l104.736-34.122-76.466-98.041-191.107 74.534z" fill="none" stroke="#767676" stroke-width=".76"/><circle transform="translate(11.817 -145.14)" cx="241.932" cy="611.936" r="2.525" fill="#b0ddb3" stroke="#7d7d7d" stroke-linecap="round" stroke-linejoin="round"/><circle transform="translate(81.492 -163.513)" cx="241.932" cy="611.936" r="2.525" fill="#b0ddb3" stroke="#7d7d7d" stroke-linecap="round" stroke-linejoin="round"/><circle transform="translate(235.876 -162.86)" cx="241.932" cy="611.936" r="2.525" fill="#b0ddb3" stroke="#7d7d7d" stroke-linecap="round" stroke-linejoin="round"/><circle transform="translate(72.583 -220.467)" cx="241.932" cy="611.936" r="2.525" fill="#b0ddb3" stroke="#7d7d7d" stroke-linecap="round" stroke-linejoin="round"/><circle transform="translate(341.337 -197.586)" cx="241.932" cy="611.936" r="2.525" fill="#b0ddb3" stroke="#7d7d7d" stroke-linecap="round" stroke-linejoin="round"/><circle transform="translate(265.173 -295.863)" cx="241.932" cy="611.936" r="2.525" fill="#b0ddb3" stroke="#7d7d7d" stroke-linecap="round" stroke-linejoin="round"/><circle transform="translate(157.483 -281.422)" cx="241.932" cy="611.936" r="2.525" fill="#b0ddb3" stroke="#7d7d7d" stroke-linecap="round" stroke-linejoin="round"/></g></svg>

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="322.269" height="108.76"><g transform="translate(-178.071 -467.673)"><path fill="#d7e3f4" stroke="#000" stroke-linecap="round" stroke-linejoin="round" d="M314.034 471.861h56.569v42.426h-56.569z"/><path d="M313.957 468.173a3.215 3.215 0 00-3.215 3.215v42.438a3.215 3.215 0 003.215 3.215h56.562a3.215 3.215 0 003.215-3.215v-42.438a3.215 3.215 0 00-3.215-3.215z" fill="none" stroke="#7d7d7d" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="1,3"/><path fill="#d7e3f4" stroke="#000" stroke-linecap="round" stroke-linejoin="round" d="M319.461 520.264h53.538v47.477h-53.538z"/><path d="M319.159 517.972a3.293 3.293 0 00-3.293 3.293v47.469a3.293 3.293 0 003.293 3.293h53.531a3.293 3.293 0 003.293-3.293v-47.469a3.293 3.293 0 00-3.293-3.293z" fill="none" stroke="#7d7d7d" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="1,3"/><path d="M181.827 572.54h313.148" fill="none" stroke="#000"/><rect width="321.269" height="6.071" x="178.571" y="569.862" ry="3.036" fill="none" stroke="#7d7d7d" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="1,3"/><text style="line-height:0%;-inkscape-font-specification:Calibri;text-align:start" x="393.959" y="501.071" font-weight="400" font-family="Calibri" letter-spacing="0" word-spacing="0"><tspan x="393.959" y="501.071" style="line-height:1.25" font-size="14">Polygons collide</tspan><tspan x="393.959" y="518.571" style="line-height:1.25" font-size="14">with their skin</tspan></text></g></svg>

After

Width:  |  Height:  |  Size: 1.5 KiB

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="174.87" height="149.37"><g stroke="#000"><path d="M6.367 51.331l26 47.5 57.5 43.5 77.5-70-17-61.5-70.5-4z" fill="#d7e3f4"/><path d="M80.155.506a6.436 6.436 0 00-3.055.924L3.6 45.93a6.436 6.436 0 00-2.31 8.596l26 47.5a6.436 6.436 0 001.761 2.043l57.5 43.5a6.436 6.436 0 008.198-.358l77.5-70a6.436 6.436 0 001.888-6.49l-17-61.5a6.436 6.436 0 00-5.838-4.71l-70.5-4a6.436 6.436 0 00-.644-.005z" fill="none" stroke-linecap="round" stroke-linejoin="round" stroke-dasharray="1,4"/></g></svg>

After

Width:  |  Height:  |  Size: 531 B

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="274.69" height="244.503"><defs><marker orient="auto" refY="0" refX="0" id="a" overflow="visible"><path d="M-10 0l-4 4L0 0l-14-4z" fill-rule="evenodd" stroke="#000" stroke-width="1.0664"/></marker></defs><path d="M106.582.108l54.286 244.286" fill="none" stroke="#000"/><path d="M55.154 200.108l-43.71-2.695L.5 155.009l36.946-23.511 33.778 27.873zM243.756 139.675l-39.353-19.215 6.113-43.364 43.13-7.586 20.544 38.675z" fill="none" stroke="#000" stroke-linecap="round" stroke-linejoin="round"/><path d="M290 413.79c27.143-48.57 84.286-68.57 144.286-51.428" fill="none" stroke="#000" stroke-width="1.8" stroke-dasharray="7.19999981,7.19999981" marker-end="url(#a)" transform="translate(-241.99 -300.825)"/><text style="line-height:0%;-inkscape-font-specification:Calibri;text-align:start" x="260" y="533.791" font-weight="400" font-family="Calibri" letter-spacing="0" word-spacing="0" transform="translate(-241.99 -300.825)"><tspan x="260" y="533.791" style="line-height:1.25" font-size="14">time0</tspan></text><text style="line-height:0%;-inkscape-font-specification:Calibri;text-align:start" x="466.857" y="472.076" font-weight="400" font-family="Calibri" letter-spacing="0" word-spacing="0" transform="translate(-241.99 -300.825)"><tspan x="466.857" y="472.076" style="line-height:1.25" font-size="14">time1</tspan></text></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="234" height="101.75"><defs><marker orient="auto" refY="0" refX="0" id="a" overflow="visible"><path d="M8.719 4.034L-2.207.016 8.719-4.002c-1.746 2.372-1.736 5.618 0 8.036z" transform="scale(-.6)" font-size="12" fill-rule="evenodd" stroke-width=".625" stroke-linejoin="round"/></marker></defs><g transform="translate(-210 -490.362)"><path fill="none" stroke="#000" d="M210.5 541.862h233v13.5h-233z"/><circle transform="translate(7.5 3)" cx="295.25" cy="494.112" r="6.25" fill="none" stroke="#000"/><circle transform="translate(7.5 91.25)" cx="295.25" cy="494.112" r="6.25" fill="none" stroke="#000"/><path d="M303 505.33v71.676" fill="none" stroke="#000" stroke-width=".937" stroke-dasharray=".93691866,1.87383732" marker-end="url(#a)"/><text style="line-height:0%;-inkscape-font-specification:Calibri;text-align:start" x="319" y="499.862" font-weight="400" font-family="Calibri"><tspan x="319" y="499.862" style="line-height:1.25" font-size="12">t=0</tspan></text><text y="587.862" x="319" style="line-height:0%;-inkscape-font-specification:Calibri;text-align:start" font-weight="400" font-family="Calibri"><tspan x="319" y="587.862" style="line-height:1.25" font-size="12">t=1</tspan></text></g></svg>

After

Width:  |  Height:  |  Size: 1.2 KiB

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="69.632" height="119.937"><defs><marker orient="auto" refY="0" refX="0" id="b" overflow="visible"><path d="M8.719 4.034L-2.207.016 8.719-4.002c-1.746 2.372-1.736 5.618 0 8.036z" transform="matrix(-1.1 0 0 -1.1 -1.1 0)" font-size="12" fill-rule="evenodd" stroke-width=".625" stroke-linejoin="round"/></marker><marker orient="auto" refY="0" refX="0" id="a" overflow="visible"><path d="M8.719 4.034L-2.207.016 8.719-4.002c-1.746 2.372-1.736 5.618 0 8.036z" transform="translate(1.1) scale(1.1)" font-size="12" fill-rule="evenodd" stroke-width=".625" stroke-linejoin="round"/></marker></defs><g transform="translate(-313.07 -471.36)"><path fill="#d7e3f4" stroke="#767676" stroke-linecap="round" stroke-linejoin="round" d="M314.034 471.861h56.569v42.426h-56.569z"/><circle transform="translate(-8.571 -2.857)" cx="351.25" cy="560.755" r="16.964" fill="#d7e3f4" stroke="#767676" stroke-linecap="round" stroke-linejoin="round"/><path d="M341.786 492.362l1.428 98.929" fill="none" stroke="#000"/><circle transform="translate(134.224 67.175)" cx="208.571" cy="490.934" r="2.143"/><path d="M377.857 506.47l.536 45" fill="none" stroke="#000" marker-start="url(#a)" marker-end="url(#b)"/><path d="M308.311 578.192A23.393 23.393 0 01290.458 559a23.393 23.393 0 0111.166-23.714" transform="translate(23.393 2.5)" fill="none" stroke="#767676" marker-start="url(#a)" marker-end="url(#b)"/></g></svg>

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" width="236.532" height="176.419"><defs><marker orient="auto" refY="0" refX="0" id="b" overflow="visible"><path d="M8.719 4.034L-2.207.016 8.719-4.002c-1.746 2.372-1.736 5.618 0 8.036z" transform="scale(.6)" font-size="12" fill-rule="evenodd" stroke-width=".625" stroke-linejoin="round"/></marker><marker orient="auto" refY="0" refX="0" id="a" overflow="visible"><path d="M8.719 4.034L-2.207.016 8.719-4.002c-1.746 2.372-1.736 5.618 0 8.036z" transform="scale(-.6)" font-size="12" fill-rule="evenodd" stroke-width=".625" stroke-linejoin="round"/></marker></defs><text x="476.473" y="507.864" style="line-height:0%;-inkscape-font-specification:Calibri;text-align:start" font-weight="400" font-size="12" font-family="Calibri" transform="translate(-245.942 -381.592)">x</text><text x="482.473" y="507.864" style="line-height:0%;text-align:start" font-weight="400" font-size="13.8" font-family="Calibri" transform="translate(-245.942 -381.592)"></text><text x="387.673" y="387.193" style="line-height:0%;-inkscape-font-specification:Calibri;text-align:start" font-weight="400" font-size="12" font-family="Calibri" transform="translate(-245.942 -381.592)">y</text><text x="396.323" y="383.193" style="line-height:0%;text-align:start" font-weight="400" font-size="13.8" font-family="Calibri" transform="translate(-245.942 -381.592)"></text><text x="245.373" y="420.096" style="line-height:0%;-inkscape-font-specification:Calibri;text-align:start" font-weight="400" font-size="12" font-family="Calibri" transform="translate(-245.942 -381.592)">CCW winding</text><text x="294.623" y="397.596" style="line-height:0%;text-align:start" font-weight="400" font-size="13.8" font-family="Calibri" transform="translate(-245.942 -381.592)"></text><path d="M345.5 414.362l-56.5 34" fill="none" stroke="#000" stroke-width="1.5" marker-end="url(#a)" transform="translate(-245.942 -381.592)"/><path d="M43.558 84.77l26 47.5 57.5 43.5 77.5-70-17-61.5-70.5-4z" fill="#d7e3f4" stroke="#000"/><path d="M384 392.862v101h95.5" fill="none" stroke="#000" stroke-width="1.5" marker-start="url(#b)" marker-end="url(#a)" transform="translate(-245.942 -381.592)"/></svg>

After

Width:  |  Height:  |  Size: 2.1 KiB

17
docs/pages/index.md Normal file
View File

@ -0,0 +1,17 @@
### Planck.js
Planck.js is JavaScript/TypeScript rewrite of the [Box2D](https://box2d.org/) C++ physics engine for cross-platform game development.
### Box2D
Box2D is a 2D rigid-body physics simulation library for games. You can use it in your games to make objects move in realistic ways and make the game world more interactive.
From the game engine's point of view, a physics engine is just a system for procedural animation.
Planck.js documentation is based on the Box2D manual with adjustments and additions for JavaScript. Both projects' names are used interchangeably in the documentation.
### Before You Start
Planck.js is a physics engine, so to use the library you need to be familiar with basic physics concepts, such as mass, force, torque, and impulses. If not, you can ask ChatGPT to explain them.
Since Planck.js is written in JavaScript, you need to be familiar with JavaScript programming.

70
docs/pages/install.md Normal file
View File

@ -0,0 +1,70 @@
## Install
Planck can be installed or downloaded from NPM or a CDN.
#### NPM
First install the package.
```sh
npm install planck
```
Then import the library in your code:
```js
import { World } from 'planck';
const world = new World();
```
You can alternatively import planck namespace to access all classes:
```js
import planck from 'planck';
const world = new planck.World();
```
To use testbed you need to import `planck/with-testbed` instead:
```js
import { World, Testbed } from 'planck/with-testbed';
const world = new World();
const testbed = Testbed.mount();
testbed.start(world);
```
#### Script tag
Planck.js is available on [jsDelivr](https://www.jsdelivr.com/package/npm/planck), [cdnjs](https://cdnjs.com/libraries/planck), and [unpkg](https://unpkg.com/planck/).
```html
<script src="https://cdn.jsdelivr.net/npm/planck/dist/planck.min.js"></script>
<script>
const { World } = planck;
const world = new World();
</script>
```
To use testbed you need to use `planck-with-testbed.min.js` instead:
```html
<html><body>
<span id="testbed-info"></span>
<span id="testbed-status"></span>
<button id="testbed-play">Play</button>
<script src="https://cdn.jsdelivr.net/npm/planck/dist/planck-with-testbed.min.js"></script>
<script>
const { World, Testbed } = planck;
const world = new World();
const testbed = Testbed.mount();
testbed.start(world);
</script>
</body></html>
```

108
docs/pages/joint.md Normal file
View File

@ -0,0 +1,108 @@
## Joint
Joints are used to constrain bodies to the world or to each other.
Typical examples in games include ragdolls, teeters, and pulleys. Joints
can be combined in many different ways to create interesting motions.
Some joints provide limits so you can control the range of motion. Some
joints provide motors which can be used to drive the joint at a
prescribed speed until a prescribed force/torque is exceeded.
Joint motors can be used in many ways. You can use motors to control
position by specifying a joint velocity that is proportional to the
difference between the actual and desired position. You can also use
motors to simulate joint friction: set the joint velocity to zero and
provide a small, but significant maximum motor force/torque. Then the
motor will attempt to keep the joint from moving until the load becomes
too strong.
### Joint Definition
Each joint type has a definition that derives from JointDef. All
joints are connected between two different bodies. One body may be static.
Joints between static and/or kinematic bodies are allowed, but have no
effect and use some processing time.
You can specify user data for any joint type and you can provide a flag
to prevent the attached bodies from colliding with each other. This is
actually the default behavior and you must set `collideConnected`
to `true` to allow collision between two connected bodies.
Many joint definitions require that you provide some geometric data.
Often a joint will be defined by anchor points. These are points fixed
in the attached bodies. Planck.js requires these points to be specified in
local coordinates. This way the joint can be specified even when the
current body transforms violate the joint constraint—a common
occurrence when a game is saved and reloaded. Additionally, some joint
definitions need to know the default relative angle between the bodies.
This is necessary to constrain rotation correctly.
Initializing the geometric data can be tedious, so many joints have a
constructor that uses the current body transforms to remove
much of the work. However, these initialization functions should usually
only be used for prototyping. Production code should define the geometry
directly. This will make joint behavior more robust.
The rest of the joint definition data depends on the joint type. We
cover these now.
### Joint Factory
Joints are created and destroyed using the world factory methods.
> **Caution**:
> You must create and destroy bodies and joints using the create
> and destroy methods of the World class.
Here's an example of the lifetime of a revolute joint:
```js
let joint = myWorld.createJoint(new RevoluteJoint({
bodyA: myBodyA,
bodyB: myBodyB,
anchorPoint: myBodyA.getCenterPosition(),
}));
// ... do stuff ...
myWorld.destroyJoint(joint);
joint = null;
```
It is always good to nullify your variables after they are destroyed. This
will make the program crash in a controlled manner if you try to reuse
the variable.
The lifetime of a joint is not simple. Heed this warning well:
> **Caution**:
> Joints are destroyed when an attached body is destroyed.
This precaution is not always necessary. You may organize your game
engine so that joints are always destroyed before the attached bodies.
In this case you don't need to implement the listener class. See the
section on Implicit Destruction for details.
### Using Joints
Many simulations create the joints and don't access them again until
they are destroyed. However, there is a lot of useful data contained in
joints that you can use to create a rich simulation.
First of all, you can get the bodies, anchor points, and user data from
a joint.
```js
joint.getBodyA();
joint.getBodyB();
joint.getAnchorA();
joint.getAnchorB();
joint.getUserData();
```
All joints have a reaction force and torque. This the reaction force
applied to body 2 at the anchor point. You can use reaction forces to
break joints or trigger other game events. These functions may do some
computations, so don't call them if you don't need the result.
```js
joint.getReactionForce(inv_dt); // Vec2
joint.getReactionTorque(inv_dt); // number
```

View File

@ -0,0 +1,42 @@
## Distance Joint
One of the simplest joints is a distance joint which says that the
distance between two points on two bodies must be constant. When you
specify a distance joint the two bodies should already be in place. Then
you specify the two anchor points in world coordinates. The first anchor
point is connected to body 1, and the second anchor point is connected
to body 2. These points imply the length of the distance constraint.
![Distance Joint](../images/distance_joint.gif)
Here is an example of a distance joint definition. In this case we
decide to allow the bodies to collide.
```js
new DistanceJoint({
collideConnected: true,
}, myBodyA, myBodyB, worldAnchorOnBodyA, worldAnchorOnBodyB);
```
The distance joint can also be made soft, like a spring-damper
connection. See the Web example in the testbed to see how this behaves.
Softness is achieved by tuning two constants in the definition:
frequency and damping ratio. Think of the frequency as the frequency of
a harmonic oscillator (like a guitar string). The frequency is specified
in Hertz. Typically the frequency should be less than a half the
frequency of the time step. So if you are using a 60Hz time step, the
frequency of the distance joint should be less than 30Hz. The reason is
related to the Nyquist frequency.
The damping ratio is non-dimensional and is typically between 0 and 1,
but can be larger. At 1, the damping is critical (all oscillations
should vanish).
```js
new DistanceJoint({
frequencyHz: 4,
dampingRatio: 0.5,
collideConnected: true,
}, myBodyA, myBodyB, worldAnchorOnBodyA, worldAnchorOnBodyB);
```

View File

@ -0,0 +1,5 @@
## Friction Joint
The friction joint is used for top-down friction. The joint provides 2D
translational friction and angular friction. See FrictionJoint.js and
ApplyForce.js for details.

View File

@ -0,0 +1,44 @@
## Gear Joint
If you want to create a sophisticated mechanical contraption you might
want to use gears. In principle you can create gears in Planck.js by using
compound shapes to model gear teeth. This is not very efficient and
might be tedious to author. You also have to be careful to line up the
gears so the teeth mesh smoothly. Planck.js has a simpler method of creating
gears: the gear joint.
![Gear Joint](../images/gear_joint.gif)
The gear joint can only connect revolute and/or prismatic joints.
Like the pulley ratio, you can specify a gear ratio. However, in this
case the gear ratio can be negative. Also keep in mind that when one
joint is a revolute joint (angular) and the other joint is prismatic
(translation), and then the gear ratio will have units of length or one
over length.
```
coordinate1 + ratio * coordinate2 == constant
```
Here is an example gear joint. The bodies myBodyA and myBodyB are any
bodies from the two joints, as long as they are not the same bodies.
```js
new GearJoint({
bodyA: myBodyA,
bodyB: myBodyB,
joint1: myRevoluteJoint,
joint2: myPrismaticJoint,
ratio: 2 * Math.PI / myLength,
})
```
Note that the gear joint depends on two other joints. This creates a
fragile situation. What happens if those joints are deleted?
> **Caution**:
> Always delete gear joints before the revolute/prismatic joints on the
> gears. Otherwise your code will crash in a bad way due to the orphaned
> joint references in the gear joint. You should also delete the gear joint
> before you delete any of the bodies involved.

View File

@ -0,0 +1,8 @@
## Motor Joint
A motor joint lets you control the motion of a body by specifying target
position and rotation offsets. You can set the maximum motor force and
torque that will be applied to reach the target position and rotation.
If the body is blocked, it will stop and the contact forces will be
proportional the maximum motor force and torque. See MotorJoint and
MotorJoint.h for details.

View File

@ -0,0 +1,18 @@
## Mouse Joint
The mouse joint is used in the testbed to manipulate bodies with the
mouse. It attempts to drive a point on a body towards the current
position of the cursor. There is no restriction on rotation.
The mouse joint definition has a target point, maximum force, frequency,
and damping ratio. The target point initially coincides with the body's
anchor point. The maximum force is used to prevent violent reactions
when multiple dynamic bodies interact. You can make this as large as you
like. The frequency and damping ratio are used to create a spring/damper
effect similar to the distance joint.
Many users have tried to adapt the mouse joint for game play. Users
often want to achieve precise positioning and instantaneous response.
The mouse joint doesn't work very well in that context. You may wish to
consider using kinematic bodies instead.

View File

@ -0,0 +1,43 @@
## Prismatic Joint
A prismatic joint allows for relative translation of two bodies along a
specified axis. A prismatic joint prevents relative rotation. Therefore,
a prismatic joint has a single degree of freedom.
![Prismatic Joint](../images/prismatic_joint.gif)
The prismatic joint definition is similar to the revolute joint
description; just substitute translation for angle, and force for torque.
Using this analogy provides an example prismatic joint definition with a
joint limit and a friction motor:
```js
let worldAxis = new Vec2(1, 0);
new PrismaticJoint({
lowerTranslation: -5,
upperTranslation: 2.5,
enableLimit: true,
maxMotorForce: 1,
motorSpeed: 0,
enableMotor: true,
}, myBodyA, myBodyB, myBodyA.getWorldCenter(), worldAxis);
```
The revolute joint has an implicit axis coming out of the screen. The
prismatic joint needs an explicit axis parallel to the screen. This axis
is fixed in the two bodies and follows their motion.
Like the revolute joint, the prismatic joint translation is zero when
it is not defined. So be sure zero is between your
lower and upper translation limits.
Using a prismatic joint is similar to using a revolute joint. Here are
the relevant member functions:
```js
prismaticJoint.getJointTranslation(); // number
prismaticJoint.getJointSpeed(); // number
prismaticJoint.getMotorForce(); // number
prismaticJoint.setMotorSpeed(speed /*number*/);
prismaticJoint.setMotorForce(force /*number*/);
```

View File

@ -0,0 +1,51 @@
## Pulley Joint
A pulley is used to create an idealized pulley. The pulley connects two
bodies to ground and to each other. As one body goes up, the other goes
down. The total length of the pulley rope is conserved according to the
initial configuration.
```
length1 + length2 == constant
```
You can supply a ratio that simulates a block and tackle. This causes
one side of the pulley to extend faster than the other. At the same time
the constraint force is smaller on one side than the other. You can use
this to create mechanical leverage.
```
length1 + ratio * length2 == constant
```
For example, if the ratio is 2, then `length1` will vary at twice the rate
of `length2`. Also the force in the rope attached to `body1` will have half
the constraint force as the rope attached to `body2`.
![Pulley Joint](../images/pulley_joint.gif)
Pulleys can be troublesome when one side is fully extended. The rope on
the other side will have zero length. At this point the constraint
equations become singular (bad). You should configure collision shapes
to prevent this.
Here is an example pulley definition:
```js
let anchor1 = myBody1.getWorldCenter();
let anchor2 = myBody2.getWorldCenter();
let groundAnchor1 = Vec2(p1.x, p1.y + 10);
let groundAnchor2 = Vec2(p2.x, p2.y + 12);
let ratio = 1;
new PulleyJoint({}, myBody1, myBody2, groundAnchor1, groundAnchor2, anchor1, anchor2, ratio);
```
Pulley joints provide the current lengths.
```js
pulleyJoint.getLengthA(); // number
pulleyJoint.getLengthB(); // number
```

View File

@ -0,0 +1,106 @@
## Revolute Joint
A revolute joint forces two bodies to share a common anchor point, often
called a hinge point. The revolute joint has a single degree of freedom:
the relative rotation of the two bodies. This is called the joint angle.
![Revolute Joint](../images/revolute_joint.gif)
To specify a revolute you need to provide two bodies and a single anchor
point in world space. The initialization function assumes that the
bodies are already in the correct position.
In this example, two bodies are connected by a revolute joint at the
first body's center of mass.
```js
new RevoluteJoint({}, myBodyA, myBodyB, myBodyA.getWorldCenter());
```
The revolute joint angle is positive when bodyB rotates CCW about the
angle point. Like all angles in Planck.js, the revolute angle is measured in
radians. By convention the revolute joint angle is zero if it not specified,
regardless of the current rotation of the two bodies.
In some cases you might wish to control the joint angle. For this, the
revolute joint can optionally simulate a joint limit and/or a motor.
A joint limit forces the joint angle to remain between a lower and upper
bound. The limit will apply as much torque as needed to make this
happen. The limit range should include zero, otherwise the joint will
lurch when the simulation begins.
A joint motor allows you to specify the joint speed (the time derivative
of the angle). The speed can be negative or positive. A motor can have
infinite force, but this is usually not desirable. Recall the eternal
question:
> *What happens when an irresistible force meets an immovable object?*
I can tell you it's not pretty. So you can provide a maximum torque for
the joint motor. The joint motor will maintain the specified speed
unless the required torque exceeds the specified maximum. When the
maximum torque is exceeded, the joint will slow down and can even
reverse.
You can use a joint motor to simulate joint friction. Just set the joint
speed to zero, and set the maximum torque to some small, but significant
value. The motor will try to prevent the joint from rotating, but will
yield to a significant load.
Here's a revision of the revolute joint definition above; this time the
joint has a limit and a motor enabled. The motor is setup to simulate
joint friction.
```js
new RevoluteJoint({
lowerAngle: -0.5 * Math.PI, // -90 degrees
upperAngle: 0.25 * Math.PI, // 45 degrees
enableLimit: true,
maxMotorTorque: 10,
motorSpeed: 0,
enableMotor: true,
}, myBodyA, myBodyB, myBodyA.getWorldCenter());
```
You can access a revolute joint's angle, speed, and motor torque.
```js
revoluteJoint.getJointAngle(); // number
revoluteJoint.getJointSpeed(); // number
revoluteJoint.getMotorTorque(); // number
```
You also update the motor parameters each step.
```js
revoluteJoint.setMotorSpeed(speed /*number*/);
revoluteJoint.setMaxMotorTorque(torque /*number*/);
```
Joint motors have some interesting abilities. You can update the joint
speed every time step so you can make the joint move back-and-forth like
a sine-wave or according to whatever function you want.
```js
// ... Game Loop Begin ...
myJoint.setMotorSpeed(Math.cos(0.5 * time));
// ... Game Loop End ...
```
You can also use joint motors to track a desired joint angle. For example:
```js
// ... Game Loop Begin ...
let angleError = myJoint.getJointAngle() - angleTarget;
let gain = 0.1;
myJoint.setMotorSpeed(-gain * angleError);
// ... Game Loop End ...
```
Generally your gain parameter should not be too large. Otherwise your
joint may become unstable.

View File

@ -0,0 +1,5 @@
## Rope Joint
The rope joint restricts the maximum distance between two points. This
can be useful to prevent chains of bodies from stretching, even under
high load. See RopeJoint.js and RopeJoint.js for details.

View File

@ -0,0 +1,14 @@
## Weld Joint
The weld joint attempts to constrain all relative motion between two
bodies. See the Cantilever.js in the testbed to see how the weld joint
behaves.
It is tempting to use the weld joint to define breakable structures.
However, the Planck.js solver is iterative so the joints are a bit soft. So
chains of bodies connected by weld joints will flex.
Instead it is better to create breakable bodies starting with a single
body with multiple fixtures. When the body breaks, you can destroy a
fixture and recreate it on a new body. See the Breakable example in the
testbed.

View File

@ -0,0 +1,6 @@
## Wheel Joint
The wheel joint restricts a point on bodyB to a line on bodyA. The wheel
joint also provides a suspension spring. See WheelJoint class, and Car example for details.
![Wheel Joint](../images/wheel_joint.svg)

64
docs/pages/limitations.md Normal file
View File

@ -0,0 +1,64 @@
## Limitations
Planck.js uses several approximations to simulate rigid body physics
efficiently. This brings some limitations.
Here are the current limitations:
1. Stacking heavy bodies on top of much lighter bodies is not stable. Stability degrades as the mass ratio passes 10:1.
2. Chains of bodies connected by joints may stretch if a lighter body is supporting a heavier body. For example, a wrecking ball connect to a chain of light weight bodies may not be stable. Stability degrades as the mass ratio passes 10:1.
3. There is typically around 0.5cm of slop in shape versus shape collision.
4. Continuous collision does not handle joints. So you may see joint stretching on fast moving objects.
5. Planck.js uses the symplectic Euler integration scheme. It does not reproduce parabolic motion of projectiles and has only first-order accuracy. However it is fast and has good stability.
6. Planck.js uses an iterative solver to provide real-time performance. You will not get precisely rigid collisions or pixel perfect accuracy. Increasing the iterations will improve accuracy.
## Accuracy
Box2D/Planck.js uses approximate methods for a few reasons.
* Performance
* Some differential equations don't have known solutions
* Some constraints cannot be determined uniquely
What this means is that constraints are not perfectly rigid and sometimes you will see some bounce even when the restitution is zero.
Box2D/Planck.js uses Gauss-Seidel to approximately solve constraints.
Box2D/Planck.js also uses Semi-implicit Euler to approximately solve the differential equations.
Box2D/Planck.js also does not have exact collision. Polygons are covered with a thin skin (around 0.5cm thick) to avoid numerical problems. This can sometimes lead to unexpected contact normals. Also, some shapes may begin to overlap and then be pushed apart by the solver.
## Restitution/Friction mixing accuracy
A physically correct restitution value must be measured in experiments.
But as soon as you change the geometry from the experiment then the value is wrong.
Next, adding simultaneous collision makes the answer worse.
## Determinism
For the same input, and same javascript runtime, Box2D/Planck.js will reproduce any simulation.
Box2D/Planck.js does not use any random numbers nor base any computation on random events (such as timers, etc).
However, people often want more stringent determinism.
People often want to know if Box2D/Planck.js can produce identical results on different binaries and on different platforms. The answer is no. The reason for this answer has to do with how floating point math is implemented in many compilers and processors. I recommend reading this article if you are curious: http://www.yosefk.com/blog/consistency-how-to-defeat-the-purpose-of-ieee-floating-point.html
This naturally leads to the question of fixed-point math.
Box2D/Planck.js does not support fixed-point math.
In the past Box2D was ported to the NDS in fixed-point and apparently it worked okay.
Fixed-point math is slower and more tedious to develop, so fixed-point is used for the development of Box2D.
## Making Games
### Worms Clones
Making a worms clone requires arbitrarily destructible terrain.
This is beyond the scope of Box2D/Planck.js, so you will have to figure out how to do this on your own.
### Tile Based Environment
Using many boxes for your terrain may not work well because box-like characters can get snagged on internal corners.
A future update to Box2D/Planck.js should allow for smooth motion over edge chains.
In general you should avoid using a rectangular character because collision tolerances will still lead to undesirable snagging.
### Asteroid Type Coordinate Systems
Box2D/Planck.js does not have any support for coordinate frame wrapping.
You would likely need to customize Box2D/Planck.js for this purpose.
You may need to use a different broad-phase for this to work.

View File

@ -0,0 +1,22 @@
### References
- [Erin Catto's Publications](https://box2d.org/publications/)
- Collision Detection in Interactive 3D Environments, Gino van den Bergen, 2004
- Real-Time Collision Detection, Christer Ericson, 2005
Box2D was created as part of a physics tutorial at the Game Developer
Conference. You can get these tutorials from the download section of
box2d.org.
### More Resources
After learning Planck.js basics and how to run your code, there are plenty of Box2D resources available online to learn advanced topics. Here are few great examples:
- [iforce2d](https://www.iforce2d.net/b2dtut/) - A collection of helpful Box2D tutorials
- Box2D [tutorials](https://www.emanueleferonato.com/category/box2d/) by Emanuele Feronato
If are interested in learning about algorithms used in Box2D/Planck.js following resources are helpful.
- [dyn4j Blog Posts](http://www.dyn4j.org/category/gamedev/) by William Bittle

126
docs/pages/rendering.md Normal file
View File

@ -0,0 +1,126 @@
## Rendering
Planck.js is a physics engine and it can be used with any graphics library or ui framework for rendering.
For development and debugging you can use the [Testbed](./testbed) that is provided with the library. For production you can use an existing integration or create a new one.
To run simulation and renderer physics objects you need to do the following:
- Advance physics simulation by calling `world.step(timeStep)` in each frame
- Iterate over world entities to draw or update them
- Optionally listen to world events for objects which are removed from simulation and remove them from rendering
```js
class Renderer {
world = null;
started = false;
start(world) {
this.world = world;
// Add listeners
world.on('remove-body', this.removeBody);
world.on('remove-joint', this.removeJoint);
world.on('remove-fixture', this.removeFixture);
// Start frame loop
this.started = true;
this.loop(0);
}
stop() {
// Remove listeners
world.off('remove-body', this.removeBody);
world.off('remove-joint', this.removeJoint);
world.off('remove-fixture', this.removeFixture);
// Stop next frame
this.started = false;
}
// Game loop
loop = (timeStamp) => {
if (!this.started) {
return;
}
// In each frame call world.step with fixed timeStep
// This is a simplified implementation, in a more advanced implementation
// you need to use elapsed time since last frame and call step more than once if needed.
// When called by requestAnimationFrame() you'll get a timestamp as argument,
// https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame
this.world.step(1 / 60);
// Iterate over bodies
for (let body = this.world.getBodyList(); body; body = body.getNext()) {
this.renderBody(body);
// ... and fixtures
for (let fixture = body.getFixtureList(); fixture; fixture = fixture.getNext()) {
this.renderFixture(fixture);
}
}
// Iterate over joints
for (let joint = this.world.getJointList(); joint; joint = joint.getNext()) {
this.renderJoint(joint);
}
// Request a new frame
window.requestAnimationFrame(this.loop);
}
renderBody(body) {
// Render or update body rendering
}
renderFixture(fixture) {
// Render or update fixture rendering
}
renderJoint(joint) {
// Render or update joint rendering
}
removeBody(body) {
// Remove body rendering
}
removeFixture(fixture) {
// Remove fixture rendering
}
removeJoint(joint) {
// Remove joint from rendering
}
}
const renderer = new Renderer();
renderer.start(world);
```
### Pixels and Coordinate Systems
Planck.js uses MKS (meters, kilograms, and seconds) units and
radians for angles, however rendering is done in pixels.
So you need to transformation world geometry into screen and vice versa.
You should consider using MKS units in your game code and find a scale to convert
to pixels when you render. This will simplify your game logic and reduce
the chance for errors since the rendering conversion can be isolated to
a small amount of code.
If you use a conversion factor, you should try tweaking it globally to
make sure nothing breaks. You can also try adjusting it to improve
stability.
### Existing Integration Projects
- [notchris/phaser3-planck](https://github.com/notchris/phaser3-planck) Phaser 3 Planck.js Plugin by Chris McGrane
- [Phaser 3 with Planck.js](https://www.emanueleferonato.com/2019/10/12/use-box2d-physics-in-your-phaser-3-projects-with-planck-js-javascript-physics-engine/) by Emanuele Feronato
- [P5Play](https://p5play.org/) - A game engine based on P5.js and Planck.js, by Quinton Ashley and Paolo Pedercini
- [P5.js integration](https://sites.google.com/site/professorcookga/planck-box2d-physics-for-javascript-p5) by Professor Robert Cook
- [Modd.io](https://www.modd.io/) - Online io game platform
- [KaPlanck](https://github.com/KeSuave/KaPlanck) - Physics extension for KaPlay
- [RealPeha/planck-renderer](https://github.com/RealPeha/planck-renderer)

View File

@ -0,0 +1,11 @@
## Run Your Code
Planck.js is a physics simulation library, and it doesn't draw anything.
[Piqnt](https://piqnt.com/) is an online playground for Planck.js. You can explore [examples](https://piqnt.com/planck.js/), inspect and edit them, or create new ones.
[Testbed](./testbed) is a simple tool (included in the project repository) to visualize and interact with physics simulation. Testbed is compatible with Piqnt playground.
You can use Planck.js with any game engines or frameworks, or use an existing integrations. See [Simulation](./world/simulation) and [Rendering](./rendering) page for more information.

91
docs/pages/shape.md Normal file
View File

@ -0,0 +1,91 @@
## Shape
Shapes describe collision geometry and may be used independently of
physics simulation. At a minimum, you should understand how to create
shapes that can be later attached to rigid bodies.
Planck.js shapes implement the Shape base class. The base class defines
functions to:
- Test a point for overlap with the shape.
- Perform a ray cast against the shape.
- Compute the shape's AABB.
- Compute the mass properties of the shape.
In addition, each shape has a type member and a radius. The radius even
applies to polygons, as discussed below.
Keep in mind that a shape does not know about bodies and stand apart
from the dynamics system. In Planck.js shapes are considered immutable.
When a shape is attached to a body using a fixture, the
shapes move rigidly with the host body. In summary:
- When a shape is **not** attached to a body, you can view its vertices as being expressed in world-space.
- When a shape is attached to a body, you can view its vertices as being expressed in local coordinates.
### Geometric Queries
You can perform a couple geometric queries on a single shape.
#### Shape Point Test
You can test a point for overlap with a shape. You provide a transform
for the shape and a world point.
```js
let transform = Transform.identity();
let point = Vec2(5, 2);
let hit = shape.testPoint(transform, point);
```
Edge and chain shapes always return false, even if the chain is a loop.
#### Shape Ray Cast
You can cast a ray at a shape to get the point of first intersection and normal
vector. A child index is included for chain shapes because the ray cast will
only check a single edge at a time.
> **Caution**:
> No hit will register if the ray starts inside a convex shape like a circle or
> polygon. This is consistent with Planck.js treating convex shapes as solid.
>
```js
let transform = Transform.identity();
let input = {}; // RayCastInput
input.p1 = Vec2(0, 0);
input.p2 = Vec2(1, 0);
input.maxFraction = 1;
let childIndex = 0;
let output = {}; // RayCastOutput
let hit = shape.RayCast(output, input, transform, childIndex);
if (hit) {
let hitPoint = Vec2.add(
Vec2.mul(1 - output.fraction, input.p1),
Vec2.mul(output.fraction, input.p2)
);
}
```
#### Pairwise Functions
The Collision module contains functions that take a pair of shapes and compute some results. These include:
- Overlap
- Contact manifolds
- Distance
- Time of impact
#### Overlap
You can test two shapes for overlap using this function:
```js
Transform xfA = ..., xfB = ...;
bool overlap = TestOverlap(shapeA, indexA, shapeB, indexB, xfA, xfB);
```
Again you must provide child indices for the case of chain shapes.

56
docs/pages/shape/chain.md Normal file
View File

@ -0,0 +1,56 @@
## Chain Shapes
The chain shape provides an efficient way to connect many edges together
to construct your static game worlds. Chain shapes automatically
eliminate ghost collisions and provide two-sided collision.
![Chain Shape](../images/chain_shape.svg)
```js
// This is a chain shape with isolated vertices
let vs = [
Vec2(1.7, 0),
Vec2(1, 0.25),
Vec2(0, 0),
Vec2(-1.7, 0.4)
];
let chain = new Chain(vs);
```
You may have a scrolling game world and would like to connect several
chains together. You can connect chains together using ghost vertices,
like we did with EdgeShape.
```js
// Install ghost vertices
chain.setPrevVertex(Vec2(3, 1));
chain.setNextVertex(Vec2(-2, 0));
```
You may also create loops automatically.
```js
// Create a loop. The first and last vertices are connected.
let chain = new Chain(vs, true);
```
Self-intersection of chain shapes is not supported. It might work, it
might not. The code that prevents ghost collisions assumes there are no
self-intersections of the chain. Also, very close vertices can cause
problems. Make sure all your edges are longer than Settings.linearSlop (5mm).
![Self Intersection](../images/self_intersect.svg)
Each edge in the chain is treated as a child shape and can be accessed
by index. When a chain shape is connected to a body, each edge gets its
own bounding box in the broad-phase collision tree.
```js
// Visit each child edge.
for (let i = 0; i < chain.getChildCount(); ++i) {
let edge = new Edge();
chain.getChildEdge(edge, i);
}
```

View File

@ -0,0 +1,8 @@
## Circle Shapes
Circle shapes have a position and radius. Circles are solid. You cannot
make a hollow circle using the circle shape.
```js
let circle = new Circle(new Vec2(2, 3), 0.5);
```

45
docs/pages/shape/edge.md Normal file
View File

@ -0,0 +1,45 @@
## Edge Shapes
Edge shapes are line segments. These are provided to assist in making a
free-form static environment for your game. A major limitation of edge
shapes is that they can collide with circles and polygons but not with
themselves. The collision algorithms used by Planck.js require that at least
one of two colliding shapes have volume. Edge shapes have no volume, so
edge-edge collision is not possible.
```js
// This is an edge shape.
let edge = new Edge(new Vec2(0, 0), new Vec2(1, 0));
```
In many cases a game environment is constructed by connecting several
edge shapes end-to-end. This can give rise to an unexpected artifact
when a polygon slides along the chain of edges. In the figure below we
see a box colliding with an internal vertex. These *ghost* collisions
are caused when the polygon collides with an internal vertex generating
an internal collision normal.
![Ghost Collision](../images/ghost_collision.svg)
If edge1 did not exist this collision would seem fine. With edge1
present, the internal collision seems like a bug. But normally when
Planck.js collides two shapes, it views them in isolation.
Fortunately, the edge shape provides a mechanism for eliminating ghost
collisions by storing the adjacent *ghost* vertices. Planck.js uses these
ghost vertices to prevent internal collisions.
![Ghost Vertices](../images/ghost_vertices.svg)
```js
// This is an edge shape with ghost vertices.
let v0 = Vec2(1.7, 0);
let v1 = Vec2(1, 0.25);
let v2 = Vec2(0, 0);
let v3 = Vec2(-1.7, 0.4);
let edge = new Edge(v1, v2).setPrevVertex(v0).setNextVertex(v3);
```
In general stitching edges together this way is a bit wasteful and
tedious. This brings us to chain shapes.

View File

@ -0,0 +1,63 @@
## Polygon Shapes
Polygon shapes are solid convex polygons. A polygon is convex when all
line segments connecting two points in the interior do not cross any
edge of the polygon. Polygons are solid and never hollow. A polygon must
have 3 or more vertices.
![Convex and Concave Polygons](../images/convex_concave.gif)
Polygon vertices are stored with a counter-clockwise winding (CCW). We
must be careful because the notion of CCW is with respect to a
right-handed coordinate system with the z-axis pointing out of the
plane. This might turn out to be clockwise on your screen, depending on
your coordinate system conventions.
![Polygon Winding Order](../images/winding.svg)
The initialization functions create normal vectors and perform validation.
So you should use initialization functions to create a polygon.
You can create a polygon shape by passing in a vertex array. The maximal
size of the array is controlled by `Setting.MaxPolygonVertices` which has a
default value of 8. This is sufficient to describe most convex polygons.
The `PolygonShape.set` function automatically computes the convex hull
and establishes the proper winding order. This function is fast when the
number of vertices is low. If you increase `MaxPolygonVertices`, then
the convex hull computation might become slow. Also note that the convex
hull function may eliminate and/or re-order the points you provide.
Vertices that are closer than `Settings.linearSlop` may be merged.
```js
// This defines a triangle in CCW order.
let vertices = [
Vec2(0, 0),
Vec2(1, 0),
Vec2(0, 1)
];
let polygon = new Polygon(vertices);
```
The polygon shape has some convenience functions to create boxes.
```js
new Box(halfWidth, halfHeight);
new Box(halfWidth, halfHeight, center, angle);
```
`center` is the local position of the center of the box shape, and `angle` is its rotation. When not provided, center and angle of the box are `{x: 0, y: 0}` and `0` (relative to the body's origin and angle).
Polygons inherit a radius from Shape. The radius creates a skin around
the polygon. The skin is used in stacking scenarios to keep polygons
slightly separated. This allows continuous collision to work against the
core polygon.
![Polygon Skin](../images/skinned_polygon.svg)
The polygon skin helps prevent tunneling by keeping the polygons
separated. This results in small gaps between the shapes. Your visual
representation can be larger than the polygon to hide any gaps.
![Skin Collision](../images/skin_collision.svg)

127
docs/pages/testbed.md Normal file
View File

@ -0,0 +1,127 @@
## Testbed
Testbed is a debugging tool that is provided with the library. It is useful to get started with Planck.js, and develop and debug physics code, and run examples.
Testbed is not required to use Planck.js physics. You can run simulation and render physics world directly, with any rendering library or framework (see [Simulation](./world/simulation) and [Rendering](./rendering) sections for more details).
There are multiple way to use testbed:
- Use Piqnt online playground
- Install from NPM, or from CDN
- Run locally from source
### Piqnt onlin playground
[Piqnt](https://piqnt.com/) is an online playground to run testbed code. It is useful to quickly try out physics examples, and share them with others.
### Install from NPM
To install testbed from NPM, run `npm install planck`. Then import testbed in your code.
```bash
npm install planck
```
```js
import { World, Testbed } from 'planck/with-testbed';
```
### Script tag and CDN
To use testbed from CDN, add the following script tag to your HTML file.
```html
<html><body>
<span id="testbed-info"></span>
<span id="testbed-status"></span>
<button id="testbed-play">Play</button>
<script src="https://cdn.jsdelivr.net/npm/planck/dist/planck-with-testbed.min.js"></script>
<script>
const { World, Testbed } = planck;
const world = new World();
const testbed = Testbed.mount();
testbed.start(world);
</script>
</body></html>
```
### Run locally from source
Running testbed locally is useful if you want to debug or edit the library or testbed code, or if you want to run testbed examples locally.
To run testbed from source, clone the repository and run `npm install` and `npm run dev` in the root directory. This will start a local server and open testbed in your browser.
```bash
git clone
cd planck.js
npm install
npm run dev
```
## Testbed Usage and API
To use testbed first create a world, then start simulation.
```js
// Create a world
const world = new World();
// Start simulation
const testbed = Testbed.start(world);
```
If you need to access the testbed instance before starting simulation you can mount the testbed first, and later start simulation.
```js
// Mount testbed
const testbed = Testbed.mount();
// Create a world
const world = new World();
// Start simulation
testbed.start(world);
```
#### Viewbox
You can adjust testbed viewbox, by setting the viewbox center and dimensions. Viewbox center and dimension are in defined in physical units. Testbed will calculate and set rendering scale and offset to match provided dimensions and center.
```js
// Viewbox center
testbed.x = 0;
testbed.y = 0;
// Viewbox size
testbed.width = 30;
testbed.height = 20;
```
#### Game-loop callback
You can add a game loop callback to testbed, it will be called in each frame.
```js
testbed.step = function() {
// Code to run in each game loop
};
```
#### Display text information
Testbed has two methods to display information on screen, `info` and `status`.
```js
// Use info() to print some text on screen
testbed.info('Use arrow keys to move player');
testbed.step = function() {
// Use status() to print key-values
// Testbed will retain value of keys until they are changed
testbed.status('score', score);
testbed.status('time', time);
};
```

86
docs/pages/world.md Normal file
View File

@ -0,0 +1,86 @@
## World
The `World` class contains the bodies and joints. It manages all aspects
of the simulation and allows for asynchronous queries (like AABB queries
and ray-casts). Much of your interactions with Planck.js will be with a
World object.
Creating a world is fairly simple. You just need to provide a gravity
vector and a boolean indicating if bodies can sleep.
```js
let myWorld = new World({
gravity: {x: 0, y: -10},
allowSleep: true,
});
```
The world class contains factories for creating and destroying bodies
and joints. These factories are discussed later in the sections on
bodies and joints. There are some other interactions with World that I
will cover now.
### Exploring the World
The world is a container for bodies, contacts, and joints. You can grab
the body, contact, and joint lists off the world and iterate over them.
For example, this code wakes up all the bodies in the world:
```js
for (let b = myWorld.getBodyList(); b; b = b.getNext()) {
b.setAwake(true);
}
```
Unfortunately real programs can be more complicated. For example, the
following code is broken:
```js
for (let b = myWorld.getBodyList(); b; b = b.getNext()) {
let myActor = b.getUserData();
if (myActor.isDead()) {
myWorld.destroyBody(b); // ERROR: now GetNext returns garbage.
}
}
```
Everything goes ok until a body is destroyed. Once a body is destroyed,
its next pointer becomes invalid. So the call to `body.getNext()` will
return garbage. The solution to this is to copy the next pointer before
destroying the body.
```js
let node = myWorld.getBodyList();
while (node) {
let b = node;
node = node.getNext();
let myActor = b.getUserData();
if (myActor.isDead()) {
myWorld.destroyBody(b);
}
}
```
This safely destroys the current body. However, you may want to call a
game function that may destroy multiple bodies. In this case you need to
be very careful. The solution is application specific, but for
convenience I'll show one method of solving the problem.
```js
let node = myWorld.getBodyList();
while (node) {
let b = node;
node = node.getNext();
let myActor = b.getUserData();
if (myActor.IsDead()) {
let otherBodiesDestroyed = gameCrazyBodyDestroyer(b);
if (otherBodiesDestroyed) {
node = myWorld.getBodyList();
}
}
}
```
Obviously to make this work, `gameCrazyBodyDestroyer()` must be honest about
what it has destroyed.

View File

@ -0,0 +1,25 @@
## AABB Queries
Sometimes you want to determine all the shapes in a region. The World
class has a fast O(log N) method for this using the broad-phase data
structure. You provide an AABB in world coordinates and an
implementation of `QueryCallback`. The world calls your class with each
fixture whose AABB overlaps the query AABB. Return `true` to continue the
query, otherwise return `false`. For example, the following code finds all
the fixtures that potentially intersect a specified AABB and wakes up
all of the associated bodies.
```js
const query = new AABB(
new Vec2(-1, -1),
new Vec2(1, 1),
);
myWorld.queryAABB(query, function(fixture) {
let body = fixture.getBody();
body.setAwake(true);
// Return true to continue the query.
return true;
});
```
You cannot make any assumptions about the order of the callbacks.

View File

@ -0,0 +1,46 @@
## Ray Casts
You can use ray casts to do line-of-sight checks, fire guns, etc. You
perform a ray cast by implementing a callback class and providing the
start and end points. The world class calls your class with each fixture
hit by the ray. Your callback is provided with the fixture, the point of
intersection, the unit normal vector, and the fractional distance along
the ray. You cannot make any assumptions about the order of the
callbacks.
You control the continuation of the ray cast by returning a fraction.
Returning a fraction of zero indicates the ray cast should be
terminated. A fraction of one indicates the ray cast should continue as
if no hit occurred. If you return the fraction from the argument list,
the ray will be clipped to the current intersection point. So you can
ray cast any shape, ray cast all shapes, or ray cast the closest shape
by returning the appropriate fraction.
You may also return of fraction of -1 to filter the fixture. Then the
ray cast will proceed as if the fixture does not exist.
Here is an example:
```js
// This class captures the closest hit shape.
let closest = null;
myWorld.rayCast(Vec2(-1, 0), Vec2(3, 1), function(fixture, point, normal, fraction) {
closest = {
fixture: fixture,
point: point, // Vec2
normal: normal, // Vec2
fraction: fraction, // number
}
// By returning the current fraction, we instruct the calling code to clip the ray and
// continue the ray-cast to the next fixture. WARNING: do not assume that fixtures
// are reported in order. However, by clipping, we can always get the closest fixture.
return fraction;
});
```
> **Caution**:
> Due to round-off errors, ray casts can sneak through small cracks
> between polygons in your static environment. If this is not acceptable
> in your application, try slightly overlapping your polygons.

View File

@ -0,0 +1,125 @@
## Simulation
The world class is used to drive the simulation. You specify a time step
and a velocity and position iteration count. For example:
```js
let timeStep = 1 / 60;
let velocityIterations = 10;
let positionIterations = 8;
myWorld.step(timeStep, velocityIterations, positionIterations);
```
After the time step you can examine your bodies and joints for
information. Most likely you will grab the position off the bodies so
that you can update your actors and render them. You can perform the
time step anywhere in your game loop, but you should be aware of the
order of things. For example, you must create bodies before the time
step if you want to get collision results for the new bodies in that
frame.
As I discussed above in the HelloWorld tutorial[todo], you should use a fixed
time step. By using a larger time step you can improve performance in
low frame rate scenarios. But generally you should use a time step no
larger than 1/30 seconds. A time step of 1/60 seconds will usually
deliver a high quality simulation.
The iteration count controls how many times the constraint solver sweeps
over all the contacts and joints in the world. More iteration always
yields a better simulation. But don't trade a small time step for a
large iteration count. 60Hz and 10 iterations is far better than 30Hz
and 20 iterations.
After stepping, you should clear any forces you have applied to your
bodies. This is done with the command `world.clearForces()`. This lets
you take multiple sub-steps with the same force field.
```js
myWorld.clearForces();
```
[todo: clean up next section, it is duplicate]
### Simulating the World
Planck.js uses a computational algorithm called an integrator. Integrators
simulate the physics equations at discrete points of time. This goes
along with the traditional game loop where we essentially have a flip
book of movement on the screen. So we need to pick a time step for
Planck.js. Generally physics engines for games like a time step at least as
fast as 60Hz or 1/60 seconds. You can get away with larger time steps,
but you will have to be more careful about setting up the definitions
for your world. We also don't like the time step to change much. A
variable time step produces variable results, which makes it difficult
to debug. So don't tie the time step to your frame rate (unless you
really, really have to). Without further ado, here is the time step.
```js
let timeStep = 1 / 60;
```
In addition to the integrator, Planck.js also uses a larger bit of code
called a constraint solver. The constraint solver solves all the
constraints in the simulation, one at a time. A single constraint can be
solved perfectly. However, when we solve one constraint, we slightly
disrupt other constraints. To get a good solution, we need to iterate
over all constraints a number of times.
There are two phases in the constraint solver: a velocity phase and a
position phase. In the velocity phase the solver computes the impulses
necessary for the bodies to move correctly. In the position phase the
solver adjusts the positions of the bodies to reduce overlap and joint
detachment. Each phase has its own iteration count. In addition, the
position phase may exit iterations early if the errors are small.
The suggested iteration count for Planck.js is 8 for velocity and 3 for
position. You can tune this number to your liking, just keep in mind
that this has a trade-off between performance and accuracy. Using fewer
iterations increases performance but accuracy suffers. Likewise, using
more iterations decreases performance but improves the quality of your
simulation. For this simple example, we don't need much iteration. Here
are our chosen iteration counts.
```js
let velocityIterations = 6;
let positionIterations = 2;
```
Note that the time step and the iteration count are completely
unrelated. An iteration is not a sub-step. One solver iteration is a
single pass over all the constraints within a time step. You can have
multiple passes over the constraints within a single time step.
We are now ready to begin the simulation loop. In your game the
simulation loop can be merged with your game loop. In each pass through
your game loop you call world.step(). Just one call is usually enough,
depending on your frame rate and your physics time step.
The Hello World program was designed to be simple, so it has no
graphical output. The code prints out the position and rotation of the
dynamic body. Here is the simulation loop that simulates 60 time steps
for a total of 1 second of simulated time.
```js
for (let i = 0; i < 60; ++i) {
world.step(timeStep, velocityIterations, positionIterations);
let position = body.getPosition();
let angle = body.getAngle();
console.log(position.x, position.y, angle);
}
```
The output shows the box falling and landing on the ground box. Your
output should look like this:
```
0.00 4.00 0.00
0.00 3.99 0.00
0.00 3.98 0.00
...
0.00 1.25 0.00
0.00 1.13 0.00
0.00 1.01 0.00
```

50
eslint.config.mjs Normal file
View File

@ -0,0 +1,50 @@
import js from "@eslint/js";
import tseslint from "typescript-eslint";
import { defineConfig } from "eslint/config";
import prettierConfig from "eslint-config-prettier";
export default defineConfig([
js.configs.recommended,
...tseslint.configs.recommended,
// ...tseslint.configs.recommendedTypeChecked,
// ...tseslint.configs.stylisticTypeChecked,
{
files: ["**/*.ts"],
languageOptions: {
parser: tseslint.parser,
parserOptions: {
project: true,
tsconfigRootDir: import.meta.dirname,
},
},
rules: {
"no-var": "off",
"prefer-rest-params": "off",
"prefer-spread": "off",
"quotes": ["warn", "double"],
"semi": ["warn", "always"],
"one-var-declaration-per-line": "warn",
"no-constant-condition": "warn",
"no-empty": "warn",
"no-prototype-builtins": "warn",
"@typescript-eslint/ban-ts-comment": "off",
"@typescript-eslint/ban-types": "off",
"@typescript-eslint/no-empty-function": "off",
"@typescript-eslint/no-empty-interface": "off",
"@typescript-eslint/no-explicit-any": "off",
"@typescript-eslint/no-inferrable-types": "off",
"@typescript-eslint/no-non-null-assertion": "off",
"@typescript-eslint/no-unused-vars": "off",
"@typescript-eslint/no-var-requires": "off",
"@typescript-eslint/typedef": [
"error",
{
propertyDeclaration: true,
},
],
},
},
prettierConfig,
]);

Some files were not shown because too many files have changed in this diff Show More