├── .github └── workflows │ └── test.yaml ├── .gitignore ├── .rustfmt.toml ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── benches ├── benchmark.rs └── dyn_vs_not.rs ├── examples ├── cubic_bezier.rs ├── delayed_tween.rs └── erased.rs └── src ├── lib.rs ├── macros.rs ├── math.rs ├── math ├── glam.rs └── na.rs ├── tweener.rs ├── tweener ├── extrapolator.rs ├── looper.rs └── oscillator.rs ├── tweens.rs └── tweens ├── back.rs ├── bounce.rs ├── circ.rs ├── cubic.rs ├── elastic.rs ├── expo.rs ├── linear.rs ├── quad.rs ├── quart.rs ├── quint.rs └── sine.rs /.github/workflows/test.yaml: -------------------------------------------------------------------------------- 1 | on: [push, pull_request] 2 | 3 | name: ci 4 | 5 | jobs: 6 | clippy: 7 | name: Clippy 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v2 11 | - uses: actions-rs/toolchain@v1 12 | with: 13 | profile: minimal 14 | toolchain: stable 15 | override: true 16 | - run: rustup component add clippy 17 | - uses: actions-rs/cargo@v1 18 | with: 19 | command: clippy 20 | args: --features glam,nalgebra -- -D warnings 21 | 22 | clippy_no_std: 23 | name: Clippy no-std 24 | runs-on: ubuntu-latest 25 | steps: 26 | - uses: actions/checkout@v2 27 | - uses: actions-rs/toolchain@v1 28 | with: 29 | profile: minimal 30 | toolchain: stable 31 | override: true 32 | - run: rustup component add clippy 33 | - uses: actions-rs/cargo@v1 34 | with: 35 | command: clippy 36 | args: --features libm --no-default-features -- -D warnings 37 | test: 38 | name: Test Suite 39 | runs-on: ubuntu-latest 40 | steps: 41 | - uses: actions/checkout@v2 42 | - uses: actions-rs/toolchain@v1 43 | with: 44 | profile: minimal 45 | toolchain: stable 46 | override: true 47 | - uses: actions-rs/cargo@v1 48 | with: 49 | command: test 50 | 51 | test-no-std: 52 | name: Test Suite No Std 53 | runs-on: ubuntu-latest 54 | steps: 55 | - uses: actions/checkout@v2 56 | - uses: actions-rs/toolchain@v1 57 | with: 58 | profile: minimal 59 | toolchain: stable 60 | override: true 61 | - uses: actions-rs/cargo@v1 62 | with: 63 | command: test 64 | args: --features libm --no-default-features 65 | 66 | fmt: 67 | name: Rustfmt 68 | runs-on: ubuntu-latest 69 | steps: 70 | - uses: actions/checkout@v2 71 | - uses: actions-rs/toolchain@v1 72 | with: 73 | profile: minimal 74 | toolchain: nightly 75 | override: true 76 | - run: rustup component add rustfmt 77 | - uses: actions-rs/cargo@v1 78 | with: 79 | command: fmt 80 | args: --all -- --check 81 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | .vscode/** -------------------------------------------------------------------------------- /.rustfmt.toml: -------------------------------------------------------------------------------- 1 | max_width = 120 2 | tab_spaces = 4 3 | newline_style = "Auto" 4 | wrap_comments = true 5 | comment_width = 100 6 | format_code_in_doc_comments = true 7 | normalize_comments = true 8 | normalize_doc_attributes = true 9 | format_macro_bodies = true 10 | imports_granularity = "Crate" 11 | reorder_impl_items = false 12 | type_punctuation_density = "Wide" 13 | space_before_colon = false 14 | space_after_colon = true 15 | spaces_around_ranges = false 16 | binop_separator = "Front" 17 | remove_nested_parens = true 18 | combine_control_expr = true 19 | overflow_delimited_expr = false 20 | struct_field_align_threshold = 0 21 | enum_discrim_align_threshold = 0 22 | match_arm_blocks = true 23 | match_arm_leading_pipes = "Never" 24 | force_multiline_blocks = false 25 | fn_args_layout = "Tall" 26 | brace_style = "SameLineWhere" 27 | control_brace_style = "AlwaysSameLine" 28 | trailing_semicolon = true 29 | trailing_comma = "Vertical" 30 | match_block_trailing_comma = false 31 | blank_lines_upper_bound = 1 32 | blank_lines_lower_bound = 0 33 | version = "Two" 34 | inline_attribute_width = 0 35 | merge_derives = true 36 | use_try_shorthand = false 37 | use_field_init_shorthand = false 38 | force_explicit_abi = true 39 | condense_wildcard_suffixes = false 40 | color = "Auto" 41 | unstable_features = false 42 | disable_all_formatting = false 43 | ignore = [] 44 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | ## [unreleased] 4 | 5 | ## [2.1.0] - 2025-05-12 6 | - **BREAKING**: Removed support for `vek`, `ultraviolet`, and `cgmath`, as they provided a maintenance 7 | burden without apparent need. 8 | - Bumped math versions again again again. 9 | - Bumped MSRV to current Rust, and move version to `rust_version = 2024`. 10 | 11 | ## [2.0.4] - 2024-01-02 12 | 13 | - Bumped math versions again again. 14 | 15 | ## [2.0.3] - 2023-04-02 16 | 17 | - Bumped math versions again. 18 | 19 | ## [2.0.2] - 2023-12-10 20 | 21 | - Bumped math versions. 22 | 23 | ## [2.0.1] - 2023-02-19 24 | 25 | - Added better support for delayed tweens, including an example in `examples/delayed_tween.rs` 26 | - Added `new_at` which situations a tween in time. Added similar methods for shortcut constructors, such as 27 | support for `sine_in_at`. 28 | - Fixed the `new` method for most Tweens and added support for `Copy`, `Ord`, and `Eq`. 29 | - Added support for `Copy`, `Ord`, and `Eq` to all Tweener adapters. 30 | - Upgraded all math libraries 31 | 32 | ## [2.0.0] - 2023-01-01 33 | 34 | - Rewrote the library: 35 | - `Tween` is generic about only `Value`, 36 | - All `Tween`s have become ZSTs, and all state has moved to `Tweener`s. 37 | - The library no longer uses Ranges. 38 | - Added `Looper`, `Oscillator`, and `Extrapolator` 39 | 40 | ## [1.0.1] - 2022-04-08 41 | 42 | - Updated typings on the Tweener to be less difficult. 43 | - Added getters to the Tweener. 44 | 45 | ## [1.0.0] - 2022-04-03 46 | 47 | - Initial implementation of the library. 48 | 49 | [unreleased]: https://github.com/sanbox-irl/tween/compare/v2.0.1...HEAD 50 | [2.0.1]: https://github.com/sanbox-irl/tween/releases/tag/v2.0.1 51 | [2.0.0]: https://github.com/sanbox-irl/tween/releases/tag/v2.0.0 52 | [1.0.1]: https://github.com/sanbox-irl/tween/releases/tag/v1.0.1 53 | [1.0.0]: https://github.com/sanbox-irl/tween/releases/tag/v1.0.0 54 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "tween" 3 | version = "2.1.0" 4 | edition = "2024" 5 | authors = ["Jonathan Spira "] 6 | license = "MIT OR Apache-2.0" 7 | repository = "https://github.com/sanbox-irl/tween" 8 | description = "A tweening library for games" 9 | categories = ["rendering::data-formats", "game-development"] 10 | 11 | [features] 12 | default = ["std"] 13 | std = [] 14 | 15 | [dependencies] 16 | libm = { version = "0.2", optional = true } 17 | glam = { version = "0.30", optional = true } 18 | nalgebra = { version = "0.33", optional = true } 19 | 20 | [dev-dependencies] 21 | criterion = "0.5" 22 | rand = "0.8.5" 23 | paste = "1.0.11" 24 | approx = "0.5" 25 | easer = "0.3" 26 | static_assertions = "1.1" 27 | 28 | [[example]] 29 | name = "erased" 30 | required-features = ["std"] 31 | 32 | [[bench]] 33 | name = "benchmark" 34 | harness = false 35 | 36 | [[bench]] 37 | name = "dyn_vs_not" 38 | harness = false 39 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright 2022 Jonathan Spira 2 | 3 | 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: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | 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. 8 | 9 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # tween 2 | 3 | ![docs.rs](https://img.shields.io/docsrs/tween) 4 | ![Crates.io](https://img.shields.io/crates/v/tween) 5 | ![Crates.io](https://img.shields.io/crates/l/tween) 6 | 7 | `tween` is an std-optional tweening library, designed for use in games and animations. 8 | 9 | ## Quick Start 10 | 11 | To install, add the following to your Cargo.toml: 12 | 13 | ```toml 14 | tween = "2.1.0" 15 | ``` 16 | 17 | You can make a Tweener, like this: 18 | 19 | ```rust 20 | use tween::Tweener; 21 | 22 | let (start, end) = (0, 100); 23 | let duration = 15.0; 24 | 25 | let mut tweener = Tweener::sine_in_out(start, end, duration); 26 | let mut position = 0; 27 | 28 | const DT: f32 = 1.0 / 60.0; 29 | 30 | // and then in your main loop... 31 | loop { 32 | position = tweener.move_by(DT); 33 | if tweener.is_finished() { 34 | break; 35 | } 36 | } 37 | 38 | assert_eq!(position, 100, "we've moved to the end of the tween"); 39 | ``` 40 | 41 | ## Overview 42 | 43 | A `Tween` is a function which returns values from one specified number to another specified number over a specified amount of time. The simplest `Tween` which everyone is familiar with is `lerp`, or "linear interpolation". In this library, it is called `Linear` -- a Linear Tween moves from its start to its end by the formula `start * (1.0 - p) + end * p`, where `p` is the percent over time you are into the tween. So at time `0`, or `0%`, you end up with the `start` value, and at time `1`, or `100%`, you end up with the end value. 44 | 45 | There are many kinds of Tweens beyond Linear, of course; all of which can produce feel and animations! We often use tweens to move positions of objects in games, but you can use Tweens for animating a sprite, selecting behavior, audio manipulation, or even drawing fonts with Cubic Bezier Tweens. 46 | 47 | This library gives you access to all the tweens initially made by Robert Penner -- you can see them in action [here](https://easings.net/). 48 | 49 | This library exposes three kinds of structs: 50 | 51 | - Zero-Sized Tweens which implement the `Tween` trait. They also expose the method `tween` inherently, so you can tween easily with them, like `tween::Linear.tween`. 52 | - Wrapper Tweens which implement the `Tween` trait. These are `Looper`, `Oscillator` and `Extrapolator`. These all wrap *around* other Tweens. See their documentation for more information. 53 | - `Tweener` and `FixedTweener`, both of which "drive" a `Tween`. You should use `FixedTweener` in a fixed timestep application; otherwise, use `Tweener`. Although you can use a `Tween` directly, a `Tweener` manages all the Tween state for you. 54 | 55 | For 99% of users, you'll want to construct `Tweener`s or `FixedTweener`s with a Tween for this library, occasionally looping or oscillating them. 56 | 57 | ## Making Tweens Yourself 58 | 59 | If you'd like to make your own tween, you absolutely can! For that, you'll need to see the main trait of this library: `Tween`. You can prototype your own `Tween` implementations with a simple closure, since `FnMut(value_delta: Value, percent: f32) -> Value` implements `Tween`, or just use that yourself. Closures are very nice because you can add, or even composite, tweens in interesting ways. 60 | 61 | For example, here's a `Linear` tween averaged with a `SineIn` tween: 62 | 63 | ```rust 64 | use tween::{Tweener, SineIn, Linear}; 65 | 66 | Tweener::new(0.0, 10.0, 10, |value_delta, percent| { 67 | (Linear.tween(value_delta, percent) + SineIn.tween(value_delta, percent)) / 2.0 68 | }); 69 | ``` 70 | 71 | To see a documented example of a Cubic Bezier Tween, see `examples/cubic_bezier.rs`. 72 | 73 | ## Storing Tweens 74 | 75 | Very often in a game or animation engine, you'll want to store Tweens by what they act *on*, without caring about what kind of Tween example it is. To do that, you'll want to box the Tween within the Tweener. Since all the Tweens in this library are ZSTs, the Box won't actually allocate, though you will have to use dynamic access (which will be more than fast enough). 76 | 77 | ```rust no_run 78 | use tween::{Tweener, Looper, Linear, SineIn, Tween}; 79 | 80 | // very often game engines need sync/sync 81 | type SendSyncTween = Tweener + Send + Sync>>; 82 | 83 | let mut my_tweener: SendSyncTween = Tweener::new(0, 100, 100, Box::new(Linear)); 84 | let mut going_up = true; 85 | 86 | // we lerp from 0 to 100 over 100 frames, and then we flip our tween back 87 | // into a SineIn tween over 10 frames, so this looks like a slowwwwwww buildup 88 | // and then a SHARP drop down. 89 | // 90 | // we put this in a thread here to demonstrate `Send + Sync` 91 | std::thread::spawn(move || { 92 | loop { 93 | let _output_assigned_somewhere = my_tweener.move_by(1); 94 | if my_tweener.is_finished() { 95 | my_tweener = if going_up { 96 | Tweener::new(100, 0, 10, Box::new(SineIn)) 97 | } else { 98 | Tweener::new(0, 100, 100, Box::new(Linear)) 99 | }; 100 | going_up = !going_up; 101 | } 102 | } 103 | }); 104 | ``` 105 | 106 | To see a documented example of erased Tweeners, see `examples/erased.rs`. 107 | 108 | ## Implementing `TweenValue` 109 | 110 | This library uses two traits: `TweenTime` and `TweenValue`. You can implement these yourself, but implementing `TweenTime` would only have fairly obscure uses. 111 | 112 | On the other hand, `TweenValue` needs to be implemented for any tweenable value. By default, all numerical types are already implemented in this library. Additionally, several math libs have a feature flag (see below) which gates an implementation for their structs as appropriate. 113 | 114 | ## Going Fast ⚡️ 115 | 116 | This library is, ultimately, a math library, and benefits enormously from being in release mode. 117 | 118 | ## Features 119 | 120 | `tween` has the following features: 121 | 122 | - `std`: **enabled by default**, gives access to faster floating point math and helper methods with `Box` 123 | - `libm`: enable this, without default features, for no-std tweening 124 | - `glam`: enable this for `glam` types to implement `TweenValue` 125 | - `nalgebra`: enable this for `nalgebra` types to implement `TweenValue` 126 | 127 | ## Std Optional 128 | 129 | This library uses `std` with the default feature `std`. Disable default features, and enable `libm`, for a no-std experience. (We need to use `libm` for the floating point math), like so: 130 | 131 | ```toml 132 | tween = { verison = "2.1.0", default_features = false, features = ["libm"] } 133 | ``` 134 | 135 | ## MSRV and Safety 136 | 137 | This crate has no MSRV yet. If it sees good adoption, an MSRV policy will be decided. 138 | 139 | Additionally, this crate is `#![deny(unsafe_code)]`, since no unsafe code was needed. Changing this policy would constitute a minor breaking change. 140 | 141 | ## Breaking Changes 142 | 143 | This crate follows normal rules for breaking changes **except for math libraries besides `glam`.** We make no promises that we'll update perfectly with math libraries -- you are encouraged to make forks of this repo instead if you have version handling requirements. 144 | 145 | ## Roadmap 146 | 147 | Next up for this library is handling Splines of Tweeners. 148 | 149 | ## License 150 | 151 | Dual-licensed under MIT or APACHE 2.0. 152 | -------------------------------------------------------------------------------- /benches/benchmark.rs: -------------------------------------------------------------------------------- 1 | use criterion::{Criterion, black_box, criterion_group, criterion_main}; 2 | use tween::{Linear, Tweener}; 3 | 4 | #[inline(never)] 5 | #[unsafe(no_mangle)] 6 | fn bencher_function(i: &mut [Tweener]) { 7 | let mut output = 0.0; 8 | for tweener in i.iter_mut() { 9 | output += tweener.move_to(5.5); 10 | } 11 | 12 | black_box(output); 13 | } 14 | 15 | fn criterion_benchmark(c: &mut Criterion) { 16 | let mut input: Vec<_> = (0..100_048_576).map(|_| Tweener::linear(0.0, 10.0, 10.0)).collect(); 17 | 18 | c.bench_function("simd come thru", |b| { 19 | b.iter(|| { 20 | bencher_function(&mut input); 21 | }); 22 | 23 | black_box(&input); 24 | }); 25 | } 26 | 27 | criterion_group!(benches, criterion_benchmark); 28 | criterion_main!(benches); 29 | -------------------------------------------------------------------------------- /benches/dyn_vs_not.rs: -------------------------------------------------------------------------------- 1 | use criterion::{Criterion, black_box, criterion_group, criterion_main}; 2 | use tween::{Linear, Tween, Tweener}; 3 | 4 | fn static_access(tweeners: &mut [Tweener]) { 5 | let mut output = 0; 6 | for tweener in tweeners.iter_mut() { 7 | for _ in 0..10 { 8 | output = tweener.move_to(5); 9 | } 10 | } 11 | 12 | black_box(output); 13 | } 14 | 15 | fn dynamic_access(tweeners: &mut [Tweener>>]) { 16 | let mut output = 0; 17 | for tweener in tweeners.iter_mut() { 18 | for _ in 0..10 { 19 | output = tweener.move_to(5); 20 | } 21 | } 22 | 23 | black_box(output); 24 | } 25 | 26 | fn bench_static_vs_dyn(c: &mut Criterion) { 27 | let mut static_tweener: Vec> = 28 | (0..100_000).map(|_| Tweener::new(0, 10, 10, Linear)).collect(); 29 | 30 | let mut dyn_tweeners: Vec>>> = (0..100_000) 31 | .map(|_| Tweener::new(0, 10, 10, Box::new(Linear) as Box>)) 32 | .collect(); 33 | 34 | let mut group = c.benchmark_group("Linear Tween"); 35 | group.bench_function("Static", |b| b.iter(|| static_access(&mut static_tweener))); 36 | group.bench_function("Dynamic", |b| b.iter(|| dynamic_access(&mut dyn_tweeners))); 37 | group.finish(); 38 | } 39 | 40 | criterion_group!(static_vs_dyn, bench_static_vs_dyn); 41 | criterion_main!(static_vs_dyn); 42 | -------------------------------------------------------------------------------- /examples/cubic_bezier.rs: -------------------------------------------------------------------------------- 1 | //! In this example, we implement a Cubic Bezier function as a tween. 2 | //! 3 | //! We do it two ways -- first as a closure, which we pass around unnamed (which means, 4 | //! of course, we can't store it in a struct), and then as a struct with an implementation. 5 | //! For fun, that second implementation also overrides `is_finite`, producing a Bezier Tween 6 | //! which goes...on and on...and on! You probably would never want to do that directly on a Tween 7 | //! which isn't about "looping" (for that use `Looper` or `Oscillator`). Instead, if you actually 8 | //! wanted that, leave the default implementation and then wrap our `CubicBezier` in `Extrapolator` 9 | //! when you want to extrapolate. 10 | 11 | use std::ops::{Add, Sub}; 12 | 13 | use tween::{Tween, TweenValue, Tweener}; 14 | 15 | fn main() { 16 | let start = Point(0.0, 0.0); 17 | let destination = Point(10.0, 0.0); 18 | let duration = 10.0; 19 | 20 | let quarter_pt = Point(start.0 + destination.0 * 0.25, 10.0); 21 | let three_quarter_pt = Point(start.0 + destination.0 * 0.75, 10.0); 22 | 23 | // there are a couple ways to do this: 24 | // 25 | // first, let's implement it as just as closure: 26 | 27 | let mut tweener = cubic_bezier_closure(start, destination, duration, quarter_pt, three_quarter_pt); 28 | assert_eq!(tweener.move_to(5.0), Point(5.0, 7.5)); 29 | assert_eq!(tweener.move_to(10.0), Point(10.0, 0.0)); 30 | 31 | // secondly, let's implement it using a for real struct 32 | // notice how we override `is_finite` so you can do some terrible, weird cubic beziers that are way 33 | // too smooth. 34 | let mut tweener = cubic_bezier_for_real(start, destination, duration, quarter_pt, three_quarter_pt); 35 | assert_eq!(tweener.move_to(5.0), Point(5.0, 7.5)); 36 | assert_eq!(tweener.move_to(10.0), Point(10.0, 0.0)); 37 | 38 | // normal stuff... 39 | assert_eq!(tweener.move_to(20.0), Point(5.0, -60.0)); 40 | } 41 | 42 | // notice the `impl` type here 43 | fn cubic_bezier_closure( 44 | start: Point, 45 | destination: Point, 46 | duration: f32, 47 | quarter_pt: Point, 48 | three_quarter_pt: Point, 49 | ) -> Tweener> { 50 | // this closure takes a `value_delta` and a `t`: 51 | // 52 | // `value_delta` is just `destination - start`. 53 | // `t` is an f32 in the range (0.0..=1.0). 54 | // 55 | // Notice that we *don't* use `start` and `destination` in the closure. 56 | // That's because a `Tweener` automatically adds the result of this closure 57 | // back to the `start` value, so we don't want to use `start` ourselves. If we did, 58 | // we would end up "double adding" `start`. In this example, `start` is `(0.0, 0.0)`, 59 | // so it wouldn't matter, but if we weren't tweening off the origin, it would be 60 | // very important! 61 | // 62 | // finally, we've written our own lerp for simplicity, but we actually could use `Linear` 63 | // within the tween ourself, but it'd have to be `Linear.tween(b - a) + a`, which is not exactly 64 | // clear. 65 | Tweener::new(start, destination, duration, move |delta, t| { 66 | let a = Point(0.0, 0.0).lerp(quarter_pt, t); 67 | let b = quarter_pt.lerp(three_quarter_pt, t); 68 | let c = three_quarter_pt.lerp(delta, t); 69 | 70 | let d = a.lerp(b, t); 71 | let e = b.lerp(c, t); 72 | 73 | d.lerp(e, t) 74 | }) 75 | } 76 | 77 | /// These are our two control points 78 | pub struct CubicBezier(T, T); 79 | 80 | /// This is going to be a strictly speaking **better* implementation: 81 | /// we're going to implement our Tween generically here. That means, although we'll 82 | /// only use Points in this example, you could use this to cubic bezier tween anything. 83 | fn cubic_bezier_for_real( 84 | start: Point, 85 | destination: Point, 86 | duration: f32, 87 | quarter_pt: Point, 88 | three_quarter_pt: Point, 89 | ) -> Tweener> { 90 | Tweener::new(start, destination, duration, CubicBezier(quarter_pt, three_quarter_pt)) 91 | } 92 | 93 | impl Tween for CubicBezier { 94 | fn tween(&mut self, delta: T, t: f32) -> T { 95 | // we need to write our own lerp with the generic functions available to us 96 | fn lerp(a: T, b: T, t: f32) -> T { 97 | (b - a).scale(t) + a 98 | } 99 | 100 | // cheeky way to get a zero 101 | let zero = delta.scale(0.0); 102 | 103 | let a = lerp(zero, self.0, t); 104 | let b = lerp(self.0, self.1, t); 105 | let c = lerp(self.1, delta, t); 106 | 107 | let d = lerp(a, b, t); 108 | let e = lerp(b, c, t); 109 | 110 | lerp(d, e, t) 111 | } 112 | 113 | // oh yeah, we're wild 114 | fn is_finite(&self) -> bool { 115 | false 116 | } 117 | } 118 | 119 | // <-- Below is math stuff that any math lib would have --> 120 | 121 | #[derive(Debug, Clone, Copy, PartialEq)] 122 | struct Point(f32, f32); 123 | 124 | impl Point { 125 | /// Moves us towards the other Point by a factor of `t` 126 | fn lerp(self, other: Self, t: f32) -> Self { 127 | self.scale(1.0 - t) + other.scale(t) 128 | } 129 | } 130 | 131 | impl Add for Point { 132 | type Output = Self; 133 | 134 | fn add(self, rhs: Self) -> Self::Output { 135 | Self(self.0 + rhs.0, self.1 + rhs.1) 136 | } 137 | } 138 | impl Sub for Point { 139 | type Output = Self; 140 | 141 | fn sub(self, rhs: Self) -> Self::Output { 142 | Self(self.0 - rhs.0, self.1 - rhs.1) 143 | } 144 | } 145 | impl TweenValue for Point { 146 | fn scale(self, scale: f32) -> Self { 147 | Self(self.0 * scale, self.1 * scale) 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /examples/delayed_tween.rs: -------------------------------------------------------------------------------- 1 | //! In this example, we explore working with Delayed Tweens using a negative time interval. 2 | //! This is relatively simple, but an extension of the API which users can trivially wrap. 3 | 4 | use tween::{CurrentTimeState, SineInOut, Tweener}; 5 | 6 | pub fn main() { 7 | let (start, end) = (0, 100); 8 | let duration = 15.0; 9 | // notice that this is NEGATIVE 10 | let current_time = -15.0; 11 | 12 | let mut tweener = Tweener::new_at(start, end, duration, SineInOut, current_time); 13 | let mut position = 0; 14 | 15 | const DT: f32 = 1.0 / 60.0; 16 | 17 | // and then in your main loop... 18 | loop { 19 | let new_position = tweener.move_by(DT); 20 | match tweener.current_time_state() { 21 | CurrentTimeState::Waiting => { 22 | // do nothing -- this is how we wait around! 23 | } 24 | CurrentTimeState::Valid => { 25 | // assign the poistion out 26 | position = new_position; 27 | } 28 | CurrentTimeState::Finished => { 29 | break; 30 | } 31 | } 32 | } 33 | 34 | assert!(tweener.is_finished()); 35 | assert_eq!(tweener.current_time_state(), CurrentTimeState::Finished); 36 | 37 | assert_eq!(position, 100, "we've moved to the end of the tween"); 38 | } 39 | -------------------------------------------------------------------------------- /examples/erased.rs: -------------------------------------------------------------------------------- 1 | //! In this example, we explore working with Erased Tweeners. 2 | //! An "Erased" tweener will be extremely useful for most game engines, 3 | //! where you'll want one component or field to store all your tweens of 4 | //! a certain value and kind. For example, a Ui struct might want to have a 5 | //! "transform" tween which tweens Vec2s over some frames. But sometimes you might 6 | //! want that Tween to be `SineIn`, other times `CircOut`, etc etc. 7 | //! 8 | //! Because all the tweens in this library are ZSTs, you won't actually pay for an allocation, 9 | //! but you will be using dynamic access. This is totally fine -- in practice, this reduces 10 | //! performance by a small amount, but it takes ~10million tween operations to last 1ms, so any 11 | //! dynamic access will not impact performance. 12 | 13 | use tween::{FixedTweener, Linear, Tween, Tweener}; 14 | 15 | pub fn main() { 16 | // this is how we erase a tween 17 | let _tweener_of_erased: Tweener>> = Tweener::new(0, 0, 0, Box::new(Linear)); 18 | 19 | // here's another way to erase a tween... 20 | let tweener_of_erased = Tweener::new(0, 0, 0, Box::new(Linear) as Box>); 21 | 22 | access_tweener(&tweener_of_erased); 23 | 24 | // crucially, you can write `Send + Sync` or any other trait here to implement it 25 | let tweener_of_erased: Tweener + Send + Sync>> = 26 | Tweener::new(0, 0, 0, Box::new(Linear)); 27 | std::thread::spawn(move || { 28 | access_tweener(&tweener_of_erased); 29 | }); 30 | 31 | // here's a fixed version of it 32 | let fixed_tweener: FixedTweener>> = FixedTweener::new(0, 0, 0, Box::new(Linear), 0); 33 | 34 | // remember, `fixed_tweener` implements `Deref` to tweener, so you can generically use `Tweener` if 35 | // needed! 36 | access_tweener(&fixed_tweener); 37 | } 38 | 39 | /// This is how you write a generic function which needs to access a variety of tweeners! 40 | fn access_tweener(tweener: &Tweener) 41 | where 42 | Value: tween::TweenValue, 43 | Time: tween::TweenTime, 44 | T: Tween, 45 | { 46 | tweener.final_value(); 47 | } 48 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![cfg_attr(feature = "std", doc = include_str!("../README.md"))] 2 | #![cfg_attr(not(feature = "std"), doc = "no-std stand in")] 3 | #![deny(unsafe_code)] 4 | #![deny(rust_2018_idioms)] 5 | #![deny(missing_docs)] 6 | #![deny(rustdoc::broken_intra_doc_links)] 7 | #![no_std] 8 | 9 | #[cfg(feature = "std")] 10 | #[macro_use] 11 | extern crate std; 12 | 13 | #[cfg(all(feature = "std", feature = "libm"))] 14 | compile_error!("Please disable feature `libm` or disable default features -- both cannot be active at once."); 15 | 16 | #[macro_use] 17 | mod macros; 18 | 19 | mod math; 20 | mod tweener; 21 | mod tweens; 22 | 23 | pub use tweener::*; 24 | pub use tweens::*; 25 | 26 | /// This is the core trait of the Library, which all tweens implement. 27 | pub trait Tween { 28 | /// Returns a new value based on the value_delta and the percent. 29 | /// 30 | /// [Linear], for example, is implemented simply as: 31 | /// ```no_test 32 | /// value_delta.scale(percent) 33 | /// ``` 34 | /// which is just `value_delta * percent`. 35 | fn tween(&mut self, value_delta: Value, percent: f32) -> Value; 36 | 37 | /// All Tweens in this library use this default method, except [Looper] and [Oscillator], which 38 | /// which are both unbounded (because they never stop returning values), and [Extrapolator], 39 | /// which simply unbounds tweens. 40 | /// 41 | /// This is used by [Tweener] and [FixedTweener] to determine when to clamp and when a tween 42 | /// will return true for [Tweener::is_finished]. 43 | /// 44 | /// If you have a [Tween] which returns valid values at all percentage ranges at all times, you 45 | /// should return [false]. 46 | /// 47 | /// If you would like to extrapolate a tween *beyond* its bounds, you can wrap it in 48 | /// [Extrapolator]. 49 | #[inline(always)] 50 | fn is_finite(&self) -> bool { 51 | true 52 | } 53 | } 54 | 55 | #[cfg(test)] 56 | static_assertions::assert_obj_safe!(Tween); 57 | 58 | #[cfg(feature = "std")] 59 | impl Tween for &'_ mut dyn Tween 60 | where 61 | Value: TweenValue, 62 | { 63 | #[inline(always)] 64 | fn tween(&mut self, value_delta: Value, percent: f32) -> Value { 65 | (**self).tween(value_delta, percent) 66 | } 67 | 68 | fn is_finite(&self) -> bool { 69 | true 70 | } 71 | } 72 | 73 | impl_tween_for_box!(); 74 | impl_tween_for_box!(Send); 75 | impl_tween_for_box!(Sync); 76 | impl_tween_for_box!(Send, Sync); 77 | impl_tween_for_box!(Unpin); 78 | impl_tween_for_box!(Send, Unpin); 79 | impl_tween_for_box!(Send, Sync, Unpin); 80 | 81 | impl Tween for F 82 | where 83 | F: FnMut(Value, f32) -> Value, 84 | Value: TweenValue, 85 | { 86 | #[inline(always)] 87 | fn tween(&mut self, value_delta: Value, percent: f32) -> Value { 88 | self(value_delta, percent) 89 | } 90 | } 91 | 92 | /// A `TweenValue` is a value which *can* be Tweened. The library fundamentally outputs 93 | /// `TweenValue` eventually. 94 | /// 95 | /// If you want to implement your own values to be tweened (for example, your favorite color lib), 96 | /// then you'll need to implement this trait. 97 | /// 98 | /// For now, we require `Copy`, but can reduce this to a `Clone` implementation. Please file an 99 | /// issue if that is needed for your workflow. 100 | pub trait TweenValue: Copy + core::fmt::Debug + core::ops::Add + core::ops::Sub { 101 | /// This should be implemented as a simple multiplication. For f64, for example, 102 | /// it's implemented as `(self as f32 * scale) as f64`. 103 | fn scale(self, scale: f32) -> Self; 104 | } 105 | 106 | /// A `TweenTime` is a representation of Time. The two most common will be `f32`/`f64` for 107 | /// seconds and `u32`/`u64`/`usize` for frames. 108 | /// 109 | /// If you want to implement your own time for duration, then you'll need to implement this 110 | /// trait. 111 | pub trait TweenTime: 112 | Copy 113 | + PartialEq 114 | + PartialOrd 115 | + core::fmt::Debug 116 | + core::ops::Add 117 | + core::ops::AddAssign 118 | + core::ops::Rem 119 | + core::ops::Sub 120 | { 121 | /// The ZERO value. This is 0 or 0.0. 122 | const ZERO: Self; 123 | 124 | /// Converts the given number to an `f32`. 125 | fn to_f32(self) -> f32; 126 | } 127 | 128 | declare_time!(u8, i8, i16, u16, i32, i64, u32, u64, i128, u128, usize, isize); 129 | 130 | impl TweenTime for f32 { 131 | const ZERO: Self = 0.0; 132 | 133 | #[inline(always)] 134 | fn to_f32(self) -> f32 { 135 | self 136 | } 137 | } 138 | impl TweenTime for f64 { 139 | const ZERO: Self = 0.0; 140 | 141 | #[inline(always)] 142 | fn to_f32(self) -> f32 { 143 | self as f32 144 | } 145 | } 146 | 147 | declare_value!(u8, i8, i16, u16, i32, i64, u32, u64, i128, u128, usize, isize); 148 | 149 | impl TweenValue for f32 { 150 | #[inline(always)] 151 | fn scale(self, scale: f32) -> Self { 152 | self * scale 153 | } 154 | } 155 | 156 | impl TweenValue for f64 { 157 | #[inline(always)] 158 | fn scale(self, scale: f32) -> Self { 159 | (self as f32 * scale) as Self 160 | } 161 | } 162 | 163 | #[cfg(test)] 164 | mod tests { 165 | use super::*; 166 | 167 | #[test] 168 | fn lambda_test() { 169 | // this tweener will always return `100` for `4` frames! 170 | let (start, end) = (0, 1); // this is basically ignored by the Lambda Tween 171 | let length = 4; 172 | let mut pct_50_or_over = false; 173 | let mut tweener = Tweener::new(start, end, length, |_vd, pct| { 174 | if pct >= 0.5 { 175 | pct_50_or_over = true; 176 | } 177 | 100 178 | }); 179 | assert_eq!(tweener.move_by(1), 100); 180 | assert_eq!(tweener.move_by(1), 100); 181 | assert_eq!(tweener.move_by(1), 100); 182 | assert_eq!(tweener.move_by(1), 100); 183 | // because we're clamped to the tween's original bounds! 184 | assert_eq!(tweener.move_by(1), 1); 185 | assert!(tweener.is_finished()); 186 | assert!(pct_50_or_over); 187 | } 188 | 189 | #[test] 190 | fn cubic_bezier() { 191 | use core::ops::{Add, Sub}; 192 | #[derive(Debug, Clone, Copy, PartialEq)] 193 | struct Point(f32, f32); 194 | impl Add for Point { 195 | type Output = Self; 196 | 197 | fn add(self, rhs: Self) -> Self::Output { 198 | Self(self.0 + rhs.0, self.1 + rhs.1) 199 | } 200 | } 201 | impl Sub for Point { 202 | type Output = Self; 203 | 204 | fn sub(self, rhs: Self) -> Self::Output { 205 | Self(self.0 - rhs.0, self.1 - rhs.1) 206 | } 207 | } 208 | impl TweenValue for Point { 209 | fn scale(self, scale: f32) -> Self { 210 | Self(self.0 * scale, self.1 * scale) 211 | } 212 | } 213 | 214 | let start = Point(0.0, 0.0); 215 | let destination = Point(10.0, 0.0); 216 | 217 | let ctrl_one = Point(2.5, 10.0); 218 | let ctrl_two = Point(7.5, 10.0); 219 | 220 | // decasteljau for simplicity 221 | let mut tweener = Tweener::new(start, destination, 10.0, |delta, t| { 222 | fn lerp(a: Point, b: Point, t: f32) -> Point { 223 | a.scale(1.0 - t) + b.scale(t) 224 | } 225 | 226 | let a = lerp(Point(0.0, 0.0), ctrl_one, t); 227 | let b = lerp(ctrl_two, ctrl_one, t); 228 | let c = lerp(ctrl_two, delta, t); 229 | 230 | let d = lerp(a, b, t); 231 | let e = lerp(b, c, t); 232 | 233 | lerp(d, e, t) 234 | }); 235 | 236 | assert_eq!(tweener.move_to(5.0), Point(5.0, 7.5)); 237 | assert_eq!(tweener.move_to(10.0), Point(10.0, 0.0)); 238 | } 239 | } 240 | -------------------------------------------------------------------------------- /src/macros.rs: -------------------------------------------------------------------------------- 1 | /// This is internal to the library, but allows for simple numeric 2 | /// types to be made into a time value. 3 | macro_rules! declare_time { 4 | ($($t:ty),*) => { 5 | $( 6 | impl TweenTime for $t { 7 | const ZERO: Self = 0; 8 | 9 | #[inline(always)] 10 | fn to_f32(self) -> f32 { 11 | self as f32 12 | } 13 | } 14 | )* 15 | }; 16 | } 17 | 18 | /// This is internal to the library, but allows for simple numeric 19 | /// types to be made into a tween_value. 20 | macro_rules! declare_value { 21 | ($($t:ident),*) => { 22 | $( 23 | impl TweenValue for $t { 24 | #[inline(always)] 25 | fn scale(self, scale: f32) -> Self { 26 | (self as f32 * scale) as $t 27 | } 28 | })* 29 | }; 30 | } 31 | 32 | /// This is internal to the library, but allows for creating simple ease-style 33 | /// tweens. 34 | macro_rules! declare_tween { 35 | ( 36 | $(#[$struct_meta:meta])* 37 | pub struct $name:ident; 38 | 39 | $(#[$method_meta:meta])* 40 | pub fn $tweener_method_name:ident; 41 | 42 | $(#[$at_method_meta:meta])* 43 | pub fn $tweener_at_method_name:ident; 44 | 45 | $tween:item 46 | ) => { 47 | $(#[$struct_meta])* 48 | #[derive(Debug, PartialEq, Eq, Clone, Copy, Default, PartialOrd, Ord)] 49 | pub struct $name; 50 | 51 | impl $name { 52 | /// Creates a new tween out of a range with a duration. 53 | pub fn new() -> Self{ 54 | Self 55 | } 56 | 57 | /// Run the given Tween with a new time. 58 | #[inline(always)] 59 | $tween 60 | } 61 | 62 | impl $crate::Tween for $name 63 | where 64 | Value: $crate::TweenValue, 65 | { 66 | #[inline(always)] 67 | fn tween(&mut self, value_delta: Value, percent_time: f32) -> Value { 68 | self.tween(value_delta, percent_time) 69 | } 70 | } 71 | 72 | impl $crate::Tweener 73 | where 74 | Time: $crate::TweenTime, 75 | Value: $crate::TweenValue, 76 | { 77 | $(#[$method_meta])* 78 | pub fn $tweener_method_name(start: Value, end: Value, duration: Time) -> $crate::Tweener { 79 | $crate::Tweener::new(start, end, duration, $crate::$name) 80 | } 81 | 82 | $(#[$at_method_meta])* 83 | pub fn $tweener_at_method_name(start: Value, end: Value, duration: Time, current_time: Time) -> $crate::Tweener { 84 | $crate::Tweener::new_at(start, end, duration, $crate::$name, current_time) 85 | } 86 | } 87 | 88 | impl $crate::FixedTweener 89 | where 90 | Time: $crate::TweenTime, 91 | Value: $crate::TweenValue, 92 | { 93 | $(#[$method_meta])* 94 | pub fn $tweener_method_name(start: Value, end: Value, duration: Time, delta: Time) -> $crate::FixedTweener { 95 | $crate::FixedTweener::new(start, end, duration, $crate::$name, delta) 96 | } 97 | 98 | $(#[$at_method_meta])* 99 | pub fn $tweener_at_method_name(start: Value, end: Value, duration: Time, current_time: Time) -> $crate::Tweener { 100 | $crate::Tweener::new_at(start, end, duration, $crate::$name, current_time) 101 | } 102 | } 103 | }; 104 | } 105 | 106 | macro_rules! impl_tween_for_box { 107 | ($($trait_bounds:ident),*) => { 108 | #[cfg(feature = "std")] 109 | impl Tween for std::boxed::Box $(+ $trait_bounds)*> { 110 | #[inline(always)] 111 | fn tween(&mut self, value_delta: Value, percent: f32) -> Value { 112 | (**self).tween(value_delta, percent) 113 | } 114 | 115 | fn is_finite(&self) -> bool { 116 | (**self).is_finite() 117 | } 118 | } 119 | }; 120 | } 121 | 122 | macro_rules! test_tween { 123 | ($name:ident) => { 124 | #[cfg(test)] 125 | mod test { 126 | paste::paste! { 127 | use super::*; 128 | use approx::assert_relative_eq; 129 | use easer::functions::{$name as [], Easing}; 130 | 131 | #[test] 132 | fn t_in() { 133 | let mut tweener = $crate::Tweener::new(0.0, 100.0, 10.0, [<$name In>]); 134 | 135 | for time in 0..=10 { 136 | let time = time as f32; 137 | 138 | let v = tweener.move_to(time); 139 | let o = []::ease_in(time, 0.0, 100.0, 10.0); 140 | 141 | assert_relative_eq!(v, o, max_relative = 0.000001, epsilon = 0.0001); 142 | } 143 | } 144 | 145 | #[test] 146 | fn t_in_f() { 147 | assert_relative_eq!([<$name In>].tween(5.0, 0.0), []::ease_in(0.0, 0.0, 5.0, 5.0), epsilon = 0.00001); 148 | assert_relative_eq!([<$name In>].tween(5.0, 0.1), []::ease_in(0.5, 0.0, 5.0, 5.0), epsilon = 0.00001); 149 | assert_relative_eq!([<$name In>].tween(5.0, 0.2), []::ease_in(1.0, 0.0, 5.0, 5.0), epsilon = 0.00001); 150 | assert_relative_eq!([<$name In>].tween(5.0, 0.3), []::ease_in(1.5, 0.0, 5.0, 5.0), epsilon = 0.00001); 151 | assert_relative_eq!([<$name In>].tween(5.0, 0.4), []::ease_in(2.0, 0.0, 5.0, 5.0), epsilon = 0.00001); 152 | assert_relative_eq!([<$name In>].tween(5.0, 0.5), []::ease_in(2.5, 0.0, 5.0, 5.0), epsilon = 0.00001); 153 | assert_relative_eq!([<$name In>].tween(5.0, 0.6), []::ease_in(3.0, 0.0, 5.0, 5.0), epsilon = 0.00001); 154 | assert_relative_eq!([<$name In>].tween(5.0, 0.7), []::ease_in(3.5, 0.0, 5.0, 5.0), epsilon = 0.00001); 155 | assert_relative_eq!([<$name In>].tween(5.0, 0.8), []::ease_in(4.0, 0.0, 5.0, 5.0), epsilon = 0.00001); 156 | assert_relative_eq!([<$name In>].tween(5.0, 0.9), []::ease_in(4.5, 0.0, 5.0, 5.0), epsilon = 0.00001); 157 | assert_relative_eq!([<$name In>].tween(5.0, 1.0), []::ease_in(5.0, 0.0, 5.0, 5.0), epsilon = 0.00001); 158 | } 159 | 160 | #[test] 161 | fn t_in_rev() { 162 | let mut tweener = $crate::Tweener::new(100.0, 0.0, 10.0, [<$name In>]); 163 | 164 | for time in 0..=10 { 165 | let time = time as f32; 166 | 167 | let v = tweener.move_to(time); 168 | let o = []::ease_in(time, 100.0, -100.0, 10.0); 169 | 170 | assert_relative_eq!(v, o, max_relative = 0.000001); 171 | } 172 | } 173 | 174 | #[test] 175 | fn t_out() { 176 | let mut tweener = $crate::Tweener::new(0.0, 100.0, 10.0, [<$name Out>]); 177 | 178 | for time in 0..=10 { 179 | let time = time as f32; 180 | 181 | let v = tweener.move_to(time); 182 | let o = []::ease_out(time, 0.0, 100.0, 10.0); 183 | 184 | assert_relative_eq!(v, o, max_relative = 0.000001); 185 | } 186 | } 187 | 188 | #[test] 189 | fn t_out_f() { 190 | assert_relative_eq!([<$name Out>].tween(5.0, 0.0), []::ease_out(0.0, 0.0, 5.0, 5.0), epsilon = 0.00001); 191 | assert_relative_eq!([<$name Out>].tween(5.0, 0.1), []::ease_out(0.5, 0.0, 5.0, 5.0), epsilon = 0.00001); 192 | assert_relative_eq!([<$name Out>].tween(5.0, 0.2), []::ease_out(1.0, 0.0, 5.0, 5.0), epsilon = 0.00001); 193 | assert_relative_eq!([<$name Out>].tween(5.0, 0.3), []::ease_out(1.5, 0.0, 5.0, 5.0), epsilon = 0.00001); 194 | assert_relative_eq!([<$name Out>].tween(5.0, 0.4), []::ease_out(2.0, 0.0, 5.0, 5.0), epsilon = 0.00001); 195 | assert_relative_eq!([<$name Out>].tween(5.0, 0.5), []::ease_out(2.5, 0.0, 5.0, 5.0), epsilon = 0.00001); 196 | assert_relative_eq!([<$name Out>].tween(5.0, 0.6), []::ease_out(3.0, 0.0, 5.0, 5.0), epsilon = 0.00001); 197 | assert_relative_eq!([<$name Out>].tween(5.0, 0.7), []::ease_out(3.5, 0.0, 5.0, 5.0), epsilon = 0.00001); 198 | assert_relative_eq!([<$name Out>].tween(5.0, 0.8), []::ease_out(4.0, 0.0, 5.0, 5.0), epsilon = 0.00001); 199 | assert_relative_eq!([<$name Out>].tween(5.0, 0.9), []::ease_out(4.5, 0.0, 5.0, 5.0), epsilon = 0.00001); 200 | assert_relative_eq!([<$name Out>].tween(5.0, 1.0), []::ease_out(5.0, 0.0, 5.0, 5.0), epsilon = 0.00001); 201 | } 202 | 203 | #[test] 204 | fn t_out_rev() { 205 | let mut tweener = $crate::Tweener::new(100.0, 0.0, 10.0, [<$name Out>]); 206 | 207 | for time in 0..=10 { 208 | let time = time as f32; 209 | 210 | let v = tweener.move_to(time); 211 | let o = []::ease_out(time, 100.0, -100.0, 10.0); 212 | 213 | assert_relative_eq!(v, o, max_relative = 0.000001); 214 | } 215 | } 216 | 217 | #[test] 218 | fn t_in_out() { 219 | let mut tweener = $crate::Tweener::new(0.0, 100.0, 10.0, [<$name InOut>]); 220 | 221 | for time in 0..=10 { 222 | let time = time as f32; 223 | 224 | let our_value = tweener.move_to(time); 225 | let easer = []::ease_in_out(time, 0.0, 100.0, 10.0); 226 | 227 | assert_relative_eq!(our_value, easer, max_relative = 0.000001); 228 | } 229 | } 230 | 231 | #[test] 232 | fn t_in_out_f() { 233 | assert_relative_eq!([<$name InOut>].tween(5.0, 0.0), []::ease_in_out(0.0, 0.0, 5.0, 5.0), epsilon = 0.00001); 234 | assert_relative_eq!([<$name InOut>].tween(5.0, 0.1), []::ease_in_out(0.5, 0.0, 5.0, 5.0), epsilon = 0.00001); 235 | assert_relative_eq!([<$name InOut>].tween(5.0, 0.2), []::ease_in_out(1.0, 0.0, 5.0, 5.0), epsilon = 0.00001); 236 | assert_relative_eq!([<$name InOut>].tween(5.0, 0.3), []::ease_in_out(1.5, 0.0, 5.0, 5.0), epsilon = 0.00001); 237 | assert_relative_eq!([<$name InOut>].tween(5.0, 0.4), []::ease_in_out(2.0, 0.0, 5.0, 5.0), epsilon = 0.00001); 238 | assert_relative_eq!([<$name InOut>].tween(5.0, 0.5), []::ease_in_out(2.5, 0.0, 5.0, 5.0), epsilon = 0.00001); 239 | assert_relative_eq!([<$name InOut>].tween(5.0, 0.6), []::ease_in_out(3.0, 0.0, 5.0, 5.0), epsilon = 0.00001); 240 | assert_relative_eq!([<$name InOut>].tween(5.0, 0.7), []::ease_in_out(3.5, 0.0, 5.0, 5.0), epsilon = 0.00001); 241 | assert_relative_eq!([<$name InOut>].tween(5.0, 0.8), []::ease_in_out(4.0, 0.0, 5.0, 5.0), epsilon = 0.00001); 242 | assert_relative_eq!([<$name InOut>].tween(5.0, 0.9), []::ease_in_out(4.5, 0.0, 5.0, 5.0), epsilon = 0.00001); 243 | assert_relative_eq!([<$name InOut>].tween(5.0, 1.0), []::ease_in_out(5.0, 0.0, 5.0, 5.0), epsilon = 0.00001); 244 | } 245 | 246 | #[test] 247 | fn t_in_out_rev() { 248 | let mut tweener = $crate::Tweener::new(100.0, 0.0, 10.0, [<$name InOut>]); 249 | 250 | for time in 0..=10 { 251 | let time = time as f32; 252 | 253 | let v = tweener.move_to(time); 254 | let o = []::ease_in_out(time, 100.0, -100.0, 10.0); 255 | 256 | assert_relative_eq!(v, o, max_relative = 0.000001); 257 | } 258 | } 259 | } 260 | } 261 | }; 262 | } 263 | -------------------------------------------------------------------------------- /src/math.rs: -------------------------------------------------------------------------------- 1 | #[cfg(feature = "glam")] 2 | mod glam; 3 | 4 | #[cfg(feature = "nalgebra")] 5 | mod na; 6 | -------------------------------------------------------------------------------- /src/math/glam.rs: -------------------------------------------------------------------------------- 1 | impl crate::TweenValue for glam::Vec2 { 2 | fn scale(self, scale: f32) -> Self { 3 | self * scale 4 | } 5 | } 6 | 7 | impl crate::TweenValue for glam::UVec2 { 8 | fn scale(self, scale: f32) -> Self { 9 | (self.as_vec2() * scale).as_uvec2() 10 | } 11 | } 12 | 13 | impl crate::TweenValue for glam::IVec2 { 14 | fn scale(self, scale: f32) -> Self { 15 | (self.as_vec2() * scale).as_ivec2() 16 | } 17 | } 18 | 19 | impl crate::TweenValue for glam::DVec2 { 20 | fn scale(self, scale: f32) -> Self { 21 | (self.as_vec2() * scale).as_dvec2() 22 | } 23 | } 24 | 25 | impl crate::TweenValue for glam::Vec3 { 26 | fn scale(self, scale: f32) -> Self { 27 | self * scale 28 | } 29 | } 30 | 31 | impl crate::TweenValue for glam::UVec3 { 32 | fn scale(self, scale: f32) -> Self { 33 | (self.as_vec3() * scale).as_uvec3() 34 | } 35 | } 36 | 37 | impl crate::TweenValue for glam::IVec3 { 38 | fn scale(self, scale: f32) -> Self { 39 | (self.as_vec3() * scale).as_ivec3() 40 | } 41 | } 42 | 43 | impl crate::TweenValue for glam::DVec3 { 44 | fn scale(self, scale: f32) -> Self { 45 | (self.as_vec3() * scale).as_dvec3() 46 | } 47 | } 48 | 49 | impl crate::TweenValue for glam::Vec4 { 50 | fn scale(self, scale: f32) -> Self { 51 | self * scale 52 | } 53 | } 54 | 55 | impl crate::TweenValue for glam::UVec4 { 56 | fn scale(self, scale: f32) -> Self { 57 | (self.as_vec4() * scale).as_uvec4() 58 | } 59 | } 60 | 61 | impl crate::TweenValue for glam::IVec4 { 62 | fn scale(self, scale: f32) -> Self { 63 | (self.as_vec4() * scale).as_ivec4() 64 | } 65 | } 66 | 67 | impl crate::TweenValue for glam::DVec4 { 68 | fn scale(self, scale: f32) -> Self { 69 | (self.as_vec4() * scale).as_dvec4() 70 | } 71 | } 72 | 73 | impl crate::TweenValue for glam::Mat2 { 74 | fn scale(self, scale: f32) -> Self { 75 | self * scale 76 | } 77 | } 78 | 79 | impl crate::TweenValue for glam::Mat3 { 80 | fn scale(self, scale: f32) -> Self { 81 | self * scale 82 | } 83 | } 84 | 85 | impl crate::TweenValue for glam::Mat3A { 86 | fn scale(self, scale: f32) -> Self { 87 | self * scale 88 | } 89 | } 90 | 91 | impl crate::TweenValue for glam::Mat4 { 92 | fn scale(self, scale: f32) -> Self { 93 | self * scale 94 | } 95 | } 96 | 97 | impl crate::TweenValue for glam::DMat2 { 98 | fn scale(self, scale: f32) -> Self { 99 | self * scale as f64 100 | } 101 | } 102 | 103 | impl crate::TweenValue for glam::DMat3 { 104 | fn scale(self, scale: f32) -> Self { 105 | self * scale as f64 106 | } 107 | } 108 | 109 | impl crate::TweenValue for glam::DMat4 { 110 | fn scale(self, scale: f32) -> Self { 111 | self * scale as f64 112 | } 113 | } 114 | -------------------------------------------------------------------------------- /src/math/na.rs: -------------------------------------------------------------------------------- 1 | impl crate::TweenValue for nalgebra::Vector2 2 | where 3 | T: crate::TweenValue + nalgebra::ClosedAddAssign + nalgebra::ClosedSubAssign + nalgebra::Scalar, 4 | { 5 | fn scale(self, scale: f32) -> Self { 6 | nalgebra::Vector2::new(self[0].scale(scale), self[1].scale(scale)) 7 | } 8 | } 9 | 10 | impl crate::TweenValue for nalgebra::Vector3 11 | where 12 | T: crate::TweenValue + nalgebra::ClosedAddAssign + nalgebra::ClosedSubAssign + nalgebra::Scalar, 13 | { 14 | fn scale(self, scale: f32) -> Self { 15 | nalgebra::Vector3::new(self[0].scale(scale), self[1].scale(scale), self[2].scale(scale)) 16 | } 17 | } 18 | 19 | impl crate::TweenValue for nalgebra::Vector4 20 | where 21 | T: crate::TweenValue + nalgebra::ClosedAddAssign + nalgebra::ClosedSubAssign + nalgebra::Scalar, 22 | { 23 | fn scale(self, scale: f32) -> Self { 24 | nalgebra::Vector4::new( 25 | self[0].scale(scale), 26 | self[1].scale(scale), 27 | self[2].scale(scale), 28 | self[3].scale(scale), 29 | ) 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/tweener.rs: -------------------------------------------------------------------------------- 1 | use crate::{Tween, TweenTime, TweenValue}; 2 | 3 | mod extrapolator; 4 | mod looper; 5 | mod oscillator; 6 | 7 | pub use extrapolator::Extrapolator; 8 | pub use looper::Looper; 9 | pub use oscillator::Oscillator; 10 | 11 | /// A Tweener is a wrapper around a Tween. Although you can tween dynamically using just a raw 12 | /// Tween, this struct will manage state and allow for more naturalistic handling. 13 | /// 14 | /// When you create a Tweener, you'll provide the `start`, `end,` and `duration` of the Tween (along 15 | /// with the actual tween itself). All of these are in absolute values. Internally, the Tweener, as 16 | /// with this library, works in "parametric" space, which is a fancy way of describing `0.0..=1.0`, 17 | /// or a percentage of the Tween. 18 | /// 19 | /// This struct has two important methods: `move_to` and `move_by`. `move_to` effectively just moves 20 | /// your time into parametric space (ie, takes a tween of length 4, and time 2, and gets the percent 21 | /// 0.5) and clamps the output to the `start` and `end` value in case you tried to `move_to` a time 22 | /// beyond the tween's duration (a negative time, or a `time > duration`). `move_by` does the same, 23 | /// but given a relative value. 24 | /// 25 | /// ## Clamping 26 | /// 27 | /// A Tweener clamps its output value to within the range of `start..=end` given in [new]. 28 | /// This can easily happen moving a Tweener with [move_by]. To check if that's occured, use 29 | /// [is_finished], or, if negative movement is possible, invert [is_valid]. 30 | /// 31 | /// For most users of this library, a common pattern will be: 32 | /// 33 | /// ``` 34 | /// # use tween::Tweener; 35 | /// 36 | /// let (start, end) = (0, 100); 37 | /// let duration = 1; 38 | /// let mut tweener = Tweener::linear(start, end, duration); 39 | /// 40 | /// // and then in your main loop... 41 | /// let dt = 1; 42 | /// let mut last_value = None; 43 | /// loop { 44 | /// last_value = Some(tweener.move_by(dt)); 45 | /// // we'd want to run `!is_valid()` if negative movement was possible, but we know its not. 46 | /// if tweener.is_finished() { 47 | /// break; 48 | /// } 49 | /// } 50 | /// assert_eq!(last_value, Some(100)); 51 | /// ``` 52 | /// 53 | /// What is `finished` and what is `started` exactly, though? In this library **`is_finished` 54 | /// returns `true` when the Time is at or beyond the duration of the Tweener.** This is a fancy way 55 | /// of saying if the Tweener has ran 5 frames, and its duration was 5, it will return `true` on 56 | /// `is_finished`. 57 | /// 58 | /// We can demonstrate that here: 59 | /// 60 | /// ``` 61 | /// # use tween::Tweener; 62 | /// let (start, end) = (0, 2); 63 | /// let duration = 2; 64 | /// let mut tweener = Tweener::linear(start, end, duration); 65 | /// 66 | /// let mut accum = 0; 67 | /// 68 | /// loop { 69 | /// accum += dbg!(tweener.move_by(1)); 70 | /// if tweener.is_finished() { 71 | /// break; 72 | /// } 73 | /// } 74 | /// 75 | /// assert_eq!(accum, 3); 76 | /// ``` 77 | /// 78 | /// NB: this is probably your assumption as to how this library works, but does mean that in a loop 79 | /// constructed like so, you will never actually see a clamp occur within `move_by`. 80 | /// 81 | /// Finally, if you'd like this library to actually *not* clamp your tween, take a look at 82 | /// [Extrapolator]. 83 | /// 84 | /// ## Iterator 85 | /// 86 | /// In situations where the same delta time is alwayas used for `move_by`, you can 87 | /// instead convert a [Tweener] into a [FixedTweener] by `into_fixed`. See [FixedTweener] 88 | /// for more information. 89 | /// 90 | /// [new]: Tweener::new 91 | /// [move_by]: Tweener::move_by 92 | /// [is_finished]: Tweener::is_finished 93 | /// [is_valid]: Tweener::is_valid 94 | #[derive(Debug, PartialEq, Clone, PartialOrd, Eq, Ord, Copy)] 95 | pub struct Tweener { 96 | /// The current time of the Tweener. You can change this value at will without running the 97 | /// Tween, or change it with `move_by`. 98 | pub current_time: Time, 99 | 100 | /// The Tweener's total duration. 101 | pub duration: Time, 102 | 103 | values: (Value, Value), 104 | value_delta: Value, 105 | 106 | /// The actual underlying Tween. 107 | pub tween: T, 108 | } 109 | 110 | impl Tweener 111 | where 112 | Time: TweenTime, 113 | Value: TweenValue, 114 | T: Tween, 115 | { 116 | /// Creates a new [Tweener] out of a [Tween], start and end [TweenValue], and [TweenTime] 117 | /// duration. 118 | pub fn new(start: Value, end: Value, duration: Time, tween: T) -> Self { 119 | Self { 120 | values: (start, end), 121 | value_delta: end - start, 122 | duration, 123 | tween, 124 | current_time: Time::ZERO, 125 | } 126 | } 127 | 128 | /// Creates a new [Tweener] out of a [Tween], start and end [TweenValue], [TweenTime] 129 | /// duration, and [TweenTime] current time. 130 | /// 131 | /// Use this to have "negative" times in Tweeners. This can be useful for starting tweens "with 132 | /// a delay". See the example in `examples/delayed_tween.rs` 133 | pub fn new_at(start: Value, end: Value, duration: Time, tween: T, current_time: Time) -> Self { 134 | Self { 135 | values: (start, end), 136 | value_delta: end - start, 137 | duration, 138 | tween, 139 | current_time, 140 | } 141 | } 142 | 143 | /// Maps a `Tweener` to a `Tweener`. This can be useful for 144 | /// boxing inner tweens. 145 | pub fn map>(self, mut f: impl FnMut(T) -> R) -> Tweener { 146 | Tweener { 147 | current_time: self.current_time, 148 | duration: self.duration, 149 | values: self.values, 150 | value_delta: self.value_delta, 151 | tween: f(self.tween), 152 | } 153 | } 154 | 155 | /// Moves the tween to a given Time. If this Tween previously was outside 156 | /// `0..=1` in parametric (percentage) space, ie. outside the duration of the tween or in 157 | /// negative time, this can move it back into bounds. 158 | /// 159 | /// Giving [TweenTime::ZERO] to this function effectively resets a tweener. 160 | /// 161 | /// Giving a negative time or a time beyond `duration` will move the tween there, but **we will 162 | /// always clamp the output time**. 163 | #[inline(always)] 164 | pub fn move_to(&mut self, position: Time) -> Value { 165 | self.current_time = position; 166 | 167 | let pct = position.to_f32() / self.duration.to_f32(); 168 | if self.tween.is_finite() { 169 | if pct < 0.0 { 170 | return self.values.0; 171 | } else if pct > 1.0 { 172 | return self.values.1; 173 | } 174 | } 175 | 176 | self.tween.tween(self.value_delta, pct) + self.values.0 177 | } 178 | 179 | /// Drives the [Tweener] forward X steps in time. 180 | /// 181 | /// If an input higher than the tween's `duration` is given, you will 182 | /// receive the max value of the tween. 183 | #[inline] 184 | pub fn move_by(&mut self, delta: Time) -> Value { 185 | self.current_time += delta; 186 | 187 | self.move_to(self.current_time) 188 | } 189 | 190 | /// The initial value a tween was set to start at. 191 | #[inline] 192 | pub fn initial_value(&self) -> Value { 193 | self.values.0 194 | } 195 | 196 | /// The final value the tween should end at. 197 | #[inline] 198 | pub fn final_value(&self) -> Value { 199 | self.values.1 200 | } 201 | 202 | /// Returns `true` is the Tweener's [current_time] is greater than or equal to `0`. Only 203 | /// negative times will return `false`. 204 | /// 205 | /// Note that for tweens without bounds (infinite tweens like [Looper]), this method will always 206 | /// return `true`. Moreover, this method does not check if a tweener is *finished*. For 207 | /// that, use [is_finished]. 208 | /// 209 | /// [current_time]: Self::current_time 210 | /// [is_finished]: Self::is_finished 211 | pub fn is_started(&self) -> bool { 212 | self.current_time_state() != CurrentTimeState::Waiting 213 | } 214 | 215 | /// Returns `true` is the Tweener's [current_time] is greater than or equal to `duration`. 216 | /// 217 | /// Note that for tweens without bounds (infinite tweens like [Looper]), this method will always 218 | /// return `false`. Moreover, this method does not check if a tweener is *started*. For 219 | /// that, use [is_started]. 220 | /// 221 | /// [current_time]: Self::current_time 222 | /// [is_started]: Self::is_started 223 | pub fn is_finished(&self) -> bool { 224 | self.current_time_state() == CurrentTimeState::Finished 225 | } 226 | 227 | /// Returns `true` is the Tweener's [current_time] is greater than or equal to `0` but less than 228 | /// `duration`. 229 | /// 230 | /// Note that for tweens without bounds (infinite tweens like [Looper]), this method will always 231 | /// return `true`. 232 | /// 233 | /// This method is **rarely needed** -- only use it if you are doing some second-order tweening. 234 | /// 235 | /// [current_time]: Self::current_time 236 | pub fn is_valid(&self) -> bool { 237 | self.current_time_state() == CurrentTimeState::Valid 238 | } 239 | 240 | /// Returns `CurrentTimeState` based on the Tweener's [current_time]. 241 | /// 242 | /// Note that for tweens without bounds (in this library, [Looper], [Oscillator], and 243 | /// [Extrapolator]), this method will always return `CurrentTimeState::Valid`. 244 | /// 245 | /// [current_time]: Self::current_time 246 | pub fn current_time_state(&self) -> CurrentTimeState { 247 | if self.tween.is_finite() { 248 | let pct = self.current_time.to_f32() / self.duration.to_f32(); 249 | 250 | if pct < 0.0 { 251 | CurrentTimeState::Waiting 252 | } else if pct >= 1.0 { 253 | CurrentTimeState::Finished 254 | } else { 255 | CurrentTimeState::Valid 256 | } 257 | } else { 258 | CurrentTimeState::Valid 259 | } 260 | } 261 | 262 | /// Converts this [Tweener] to a [FixedTweener]. See its documentation for more information. 263 | pub fn into_fixed(self, delta: Time) -> FixedTweener { 264 | FixedTweener::from_tweener(self, delta) 265 | } 266 | } 267 | 268 | /// A FixedTweener is a [Tweener] wrapper which implements [Iterator]. To do this, 269 | /// it takes a "fixed" delta on its constructor. 270 | /// 271 | /// ## Basic Example 272 | /// 273 | /// ``` 274 | /// # use tween::{FixedTweener, Tweener, Linear}; 275 | /// 276 | /// // we provide a tweener which goes from 0 up to 4, in 4 ticks, 277 | /// // and we progress it by 1 each time we call it. 278 | /// let (start, end) = (0, 4); 279 | /// let duration = 4; 280 | /// let delta = 1; 281 | /// let mut fixed_tweener = FixedTweener::linear(start, end, duration, delta); 282 | /// assert_eq!(fixed_tweener.next().unwrap(), 1); 283 | /// assert_eq!(fixed_tweener.next().unwrap(), 2); 284 | /// assert_eq!(fixed_tweener.next().unwrap(), 3); 285 | /// assert_eq!(fixed_tweener.next().unwrap(), 4); 286 | /// assert_eq!(fixed_tweener.next(), None); 287 | /// ``` 288 | /// 289 | /// ## Clamping 290 | /// 291 | /// `FixedTweener`, just [Tweener], clamps its output, but **in its [Iterator] implementation, 292 | /// it returns `None` when it would otherwise clamp!** 293 | /// 294 | /// Therefore, in all cases where a `fixed_tweener.is_finished()` is `true`, 295 | /// `fixed_tweener.next().is_none` as well. 296 | /// 297 | /// If you *don't* want this behavior, you can instead use `move_next()`, which clamps. 298 | /// 299 | /// ``` 300 | /// # use tween::{FixedTweener, Tweener, Linear}; 301 | /// // a single iteration length tween 302 | /// let mut fixed_tweener = FixedTweener::linear(0, 1, 1, 1); 303 | /// 304 | /// // move it to its end... 305 | /// assert_eq!(fixed_tweener.next().unwrap(), 1); 306 | /// 307 | /// // and now `.next` returns `None`! 308 | /// assert!(fixed_tweener.next().is_none()); 309 | /// assert!(fixed_tweener.is_finished()); 310 | /// 311 | /// // but you can still use `move_next`. Note how it returns `Value`, not `Option` 312 | /// assert_eq!(fixed_tweener.move_next(), 1); 313 | /// ``` 314 | #[derive(Debug, PartialEq, Clone, PartialOrd, Eq, Ord, Copy)] 315 | pub struct FixedTweener { 316 | /// The delta upon which we move. 317 | pub delta: Time, 318 | 319 | /// The internal tweener that we've fixed a Delta to. 320 | pub tweener: Tweener, 321 | } 322 | 323 | impl FixedTweener 324 | where 325 | Value: TweenValue, 326 | Time: TweenTime, 327 | T: Tween, 328 | { 329 | /// Creates a new [FixedTweener] out of a [Tween], start and end [TweenValue], [TweenTime] 330 | /// duration, and [TweenTime] delta. 331 | pub fn new(start: Value, end: Value, duration: Time, tween: T, delta: Time) -> Self { 332 | Self::from_tweener(Tweener::new(start, end, duration, tween), delta) 333 | } 334 | 335 | /// Creates a new [FixedTweener] out of a [Tween], start and end [TweenValue], [TweenTime] 336 | /// duration, and [TweenTime] current time. 337 | /// 338 | /// Use this to have "negative" times in Tweeners. This can be useful for starting tweens "with 339 | /// a delay". See the example in `examples/delayed_tween.rs` 340 | pub fn new_at(start: Value, end: Value, duration: Time, tween: T, current_time: Time, delta: Time) -> Self { 341 | Self::from_tweener(Tweener::new_at(start, end, duration, tween, current_time), delta) 342 | } 343 | 344 | /// Creates a new [FixedTweener], and takes in the delta time 345 | /// it will use per tick. 346 | pub fn from_tweener(tweener: Tweener, delta: Time) -> Self { 347 | Self { tweener, delta } 348 | } 349 | 350 | /// This is the exact same as called `next` via [Iterator] except that it doesn't require a 351 | /// useless `.unwrap()` because it *clamps* instead. 352 | #[inline] 353 | pub fn move_next(&mut self) -> Value { 354 | self.tweener.move_by(self.delta) 355 | } 356 | } 357 | 358 | impl core::ops::Deref for FixedTweener { 359 | type Target = Tweener; 360 | 361 | #[inline] 362 | fn deref(&self) -> &Self::Target { 363 | &self.tweener 364 | } 365 | } 366 | 367 | impl core::ops::DerefMut for FixedTweener { 368 | #[inline] 369 | fn deref_mut(&mut self) -> &mut Self::Target { 370 | &mut self.tweener 371 | } 372 | } 373 | 374 | impl Iterator for FixedTweener 375 | where 376 | Value: TweenValue, 377 | Time: TweenTime, 378 | T: Tween, 379 | { 380 | type Item = Value; 381 | 382 | #[inline] 383 | fn next(&mut self) -> Option { 384 | if self.tweener.is_valid() { 385 | Some(self.move_next()) 386 | } else { 387 | None 388 | } 389 | } 390 | } 391 | 392 | /// This enum indicates a [Tweener] or [FixedTweener]'s current state. 393 | /// It returns `Waiting` is the current time is less than 0, `Finished` if it's at the duration of 394 | /// the [Tweener] or greater, and valid otherwise. 395 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] 396 | pub enum CurrentTimeState { 397 | /// Indicates the Tweener's current time was before `0` 398 | Waiting, 399 | /// Indicates the Tweener's current time in after `0` and before the `duration`. 400 | Valid, 401 | /// Indicates the Tweener's current time is after `duration` 402 | Finished, 403 | } 404 | 405 | #[cfg(feature = "std")] 406 | #[cfg(test)] 407 | mod tests { 408 | use super::*; 409 | use crate::{BounceIn, BounceInOut, BounceOut, ElasticIn, Linear}; 410 | 411 | #[test] 412 | fn tweener() { 413 | let mut tweener = Tweener::new(0, 100, 10, Linear); 414 | let values: std::vec::Vec<_> = (0..10).map(|_| tweener.move_by(1)).collect(); 415 | 416 | assert_eq!(*values, [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]); 417 | } 418 | 419 | #[test] 420 | fn fixed_tweener() { 421 | let mut tweener = Tweener::new(0, 100, 10, Linear).into_fixed(1); 422 | let values: std::vec::Vec<_> = (0..10).map(|_| tweener.next().unwrap()).collect(); 423 | 424 | assert_eq!(*values, [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]); 425 | 426 | let mut fixed_tweener = Tweener::new(0, 4, 4, Linear).into_fixed(1); 427 | assert_eq!(fixed_tweener.next().unwrap(), 1); 428 | assert_eq!(fixed_tweener.next().unwrap(), 2); 429 | assert_eq!(fixed_tweener.next().unwrap(), 3); 430 | assert_eq!(fixed_tweener.next().unwrap(), 4); 431 | assert!(fixed_tweener.is_finished()); 432 | assert_eq!(fixed_tweener.next(), None); 433 | } 434 | 435 | #[test] 436 | fn tweener_weird() { 437 | let mut tweener = Tweener::new(0, 2, 2, Linear); 438 | 439 | assert_eq!(tweener.move_by(0), 0); 440 | assert_eq!(tweener.move_by(1), 1); 441 | assert_eq!(tweener.move_by(1), 2); 442 | assert_eq!(tweener.move_by(0), 2); 443 | assert_eq!(tweener.move_by(0), 2); 444 | assert_eq!(tweener.move_by(0), 2); 445 | } 446 | 447 | #[test] 448 | fn bounds_checker() { 449 | fn checker(mut tweener: Tweener) 450 | where 451 | T: Tween, 452 | { 453 | fn move_and_return( 454 | tweener: &mut Tweener, 455 | f: impl FnOnce(&Tweener) -> bool, 456 | ) -> bool 457 | where 458 | T: Tween, 459 | { 460 | tweener.move_by(1); 461 | f(tweener) 462 | } 463 | 464 | assert!(move_and_return(&mut tweener, |t| !t.is_finished())); 465 | assert!(move_and_return(&mut tweener, |t| t.is_finished())); 466 | 467 | tweener.move_to(-2); 468 | 469 | assert!(move_and_return(&mut tweener, |t| !t.is_started())); 470 | assert!(move_and_return(&mut tweener, |t| t.is_started())); 471 | assert!(move_and_return(&mut tweener, |t| t.is_started())); 472 | assert!(move_and_return(&mut tweener, |t| t.is_started())); 473 | assert!(move_and_return(&mut tweener, |t| t.is_started())); 474 | 475 | tweener.move_to(-2); 476 | 477 | assert!(move_and_return(&mut tweener, |t| !t.is_valid())); 478 | assert!(move_and_return(&mut tweener, |t| t.is_valid())); 479 | assert!(move_and_return(&mut tweener, |t| t.is_valid())); 480 | assert!(move_and_return(&mut tweener, |t| !t.is_valid())); 481 | } 482 | 483 | checker(Tweener::new(0, 2, 2, Linear)); 484 | checker(Tweener::new(0, 2, 2, ElasticIn)); 485 | checker(Tweener::new(0, 2, 2, BounceInOut)); 486 | checker(Tweener::new(0, 2, 2, BounceIn)); 487 | checker(Tweener::new(0, 2, 2, BounceOut)); 488 | } 489 | 490 | #[test] 491 | fn shortcuts() { 492 | Tweener::back_in(0, 0, 0); 493 | Tweener::back_out(0, 0, 0); 494 | Tweener::back_in_out(0, 0, 0); 495 | Tweener::bounce_in(0, 0, 0); 496 | Tweener::bounce_out(0, 0, 0); 497 | Tweener::bounce_in_out(0, 0, 0); 498 | Tweener::circ_in(0, 0, 0); 499 | Tweener::circ_out(0, 0, 0); 500 | Tweener::circ_in_out(0, 0, 0); 501 | Tweener::cubic_in(0, 0, 0); 502 | Tweener::cubic_out(0, 0, 0); 503 | Tweener::cubic_in_out(0, 0, 0); 504 | Tweener::elastic_in(0, 0, 0); 505 | Tweener::elastic_out(0, 0, 0); 506 | Tweener::elastic_in_out(0, 0, 0); 507 | Tweener::expo_in(0, 0, 0); 508 | Tweener::expo_out(0, 0, 0); 509 | Tweener::expo_in_out(0, 0, 0); 510 | Tweener::linear(0, 0, 0); 511 | Tweener::quad_in(0, 0, 0); 512 | Tweener::quad_out(0, 0, 0); 513 | Tweener::quad_in_out(0, 0, 0); 514 | Tweener::quart_in(0, 0, 0); 515 | Tweener::quart_out(0, 0, 0); 516 | Tweener::quart_in_out(0, 0, 0); 517 | Tweener::quint_in(0, 0, 0); 518 | Tweener::quint_out(0, 0, 0); 519 | Tweener::quint_in_out(0, 0, 0); 520 | Tweener::sine_in(0, 0, 0); 521 | Tweener::sine_out(0, 0, 0); 522 | Tweener::sine_in_out(0, 0, 0); 523 | 524 | Tweener::back_in_at(0, 0, 0, 0); 525 | Tweener::back_out_at(0, 0, 0, 0); 526 | Tweener::back_in_out_at(0, 0, 0, 0); 527 | Tweener::bounce_in_at(0, 0, 0, 0); 528 | Tweener::bounce_out_at(0, 0, 0, 0); 529 | Tweener::bounce_in_out_at(0, 0, 0, 0); 530 | Tweener::circ_in_at(0, 0, 0, 0); 531 | Tweener::circ_out_at(0, 0, 0, 0); 532 | Tweener::circ_in_out_at(0, 0, 0, 0); 533 | Tweener::cubic_in_at(0, 0, 0, 0); 534 | Tweener::cubic_out_at(0, 0, 0, 0); 535 | Tweener::cubic_in_out_at(0, 0, 0, 0); 536 | Tweener::elastic_in_at(0, 0, 0, 0); 537 | Tweener::elastic_out_at(0, 0, 0, 0); 538 | Tweener::elastic_in_out_at(0, 0, 0, 0); 539 | Tweener::expo_in_at(0, 0, 0, 0); 540 | Tweener::expo_out_at(0, 0, 0, 0); 541 | Tweener::expo_in_out_at(0, 0, 0, 0); 542 | Tweener::linear_at(0, 0, 0, 0); 543 | Tweener::quad_in_at(0, 0, 0, 0); 544 | Tweener::quad_out_at(0, 0, 0, 0); 545 | Tweener::quad_in_out_at(0, 0, 0, 0); 546 | Tweener::quart_in_at(0, 0, 0, 0); 547 | Tweener::quart_out_at(0, 0, 0, 0); 548 | Tweener::quart_in_out_at(0, 0, 0, 0); 549 | Tweener::quint_in_at(0, 0, 0, 0); 550 | Tweener::quint_out_at(0, 0, 0, 0); 551 | Tweener::quint_in_out_at(0, 0, 0, 0); 552 | Tweener::sine_in_at(0, 0, 0, 0); 553 | Tweener::sine_out_at(0, 0, 0, 0); 554 | Tweener::sine_in_out_at(0, 0, 0, 0); 555 | } 556 | } 557 | -------------------------------------------------------------------------------- /src/tweener/extrapolator.rs: -------------------------------------------------------------------------------- 1 | use crate::{Tween, TweenValue}; 2 | 3 | /// An [Extrapolator] is a wrapper around a [Tween], which allows a tween to go beyond the range of 4 | /// `0.0` to `1.0`. Note that for [Looper], [Oscillator], or any [Tween] whose [Tween::is_finite] 5 | /// returns false, wrapping in an Extrapolator is unnecssary, as they are already infinite tween. 6 | /// 7 | /// As a note of caution, some Tweens, like [Linear] handle extrapolation just fine, 8 | /// but many others, like [SineIn] will give unhelpful results. They are clamped for 9 | /// a reason! 10 | /// 11 | /// [Looper]: crate::Looper 12 | /// [Oscillator]: crate::Oscillator 13 | /// [Linear]: crate::Linear 14 | /// [SineIn]: crate::SineIn 15 | #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] 16 | #[repr(transparent)] 17 | pub struct Extrapolator(pub T); 18 | 19 | impl Extrapolator { 20 | /// Creates a new Extrapolator around a [Tween]. 21 | pub fn new(tween: T) -> Self { 22 | Extrapolator(tween) 23 | } 24 | } 25 | 26 | impl Tween for Extrapolator 27 | where 28 | Value: TweenValue, 29 | T: Tween, 30 | { 31 | #[inline(always)] 32 | fn tween(&mut self, value_delta: Value, percent: f32) -> Value { 33 | // pass through to the underlying tween 34 | self.0.tween(value_delta, percent) 35 | } 36 | 37 | fn is_finite(&self) -> bool { 38 | false 39 | } 40 | } 41 | 42 | #[cfg(test)] 43 | mod tests { 44 | use crate::{FixedTweener, Linear, Tweener}; 45 | 46 | use super::*; 47 | 48 | #[test] 49 | fn tweener_loop() { 50 | let mut looper = Tweener::new(0, 2, 2, Extrapolator(Linear)); 51 | 52 | assert_eq!(looper.move_to(0), 0); 53 | assert_eq!(looper.move_to(1), 1); 54 | assert_eq!(looper.move_to(2), 2); 55 | assert_eq!(looper.move_to(3), 3); 56 | assert_eq!(looper.move_to(4), 4); 57 | assert_eq!(looper.move_to(5), 5); 58 | } 59 | 60 | #[test] 61 | fn delta_tweener_loop() { 62 | let mut looper = Tweener::new(0, 2, 2, Extrapolator::new(Linear)); 63 | 64 | assert_eq!(looper.move_by(1), 1); 65 | assert_eq!(looper.move_by(1), 2); 66 | assert_eq!(looper.move_by(1), 3); 67 | assert_eq!(looper.move_by(1), 4); 68 | assert_eq!(looper.move_by(1), 5); 69 | assert_eq!(looper.move_by(1), 6); 70 | } 71 | 72 | #[test] 73 | fn fixed_delta_tweener_loop() { 74 | let mut looper = FixedTweener::new(0, 2, 2, Extrapolator(Linear), 1); 75 | 76 | assert_eq!(looper.next().unwrap(), 1); 77 | assert_eq!(looper.next().unwrap(), 2); 78 | assert_eq!(looper.next().unwrap(), 3); 79 | assert_eq!(looper.next().unwrap(), 4); 80 | assert_eq!(looper.next().unwrap(), 5); 81 | assert_eq!(looper.next().unwrap(), 6); 82 | } 83 | } 84 | -------------------------------------------------------------------------------- /src/tweener/looper.rs: -------------------------------------------------------------------------------- 1 | use crate::{Tween, TweenValue}; 2 | 3 | /// A [Looper] is a wrapper around a [Tween], which makes it so that 4 | /// every time the tweener *would* fuse (end), it loops from the start. 5 | #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] 6 | #[repr(transparent)] 7 | pub struct Looper(pub T); 8 | 9 | impl Looper { 10 | /// Creates a new Looper around a [Tween]. 11 | pub fn new(tween: T) -> Self { 12 | Self(tween) 13 | } 14 | } 15 | 16 | impl Tween for Looper 17 | where 18 | Value: TweenValue, 19 | T: Tween, 20 | { 21 | #[inline(always)] 22 | fn tween(&mut self, value_delta: Value, mut percent: f32) -> Value { 23 | if percent == 0.0 { 24 | return self.0.tween(value_delta, percent); 25 | } 26 | 27 | percent %= 1.0; 28 | if percent == 0.0 { 29 | percent = 1.0 30 | } 31 | 32 | // pass through to the underlying tween 33 | self.0.tween(value_delta, percent) 34 | } 35 | 36 | fn is_finite(&self) -> bool { 37 | false 38 | } 39 | } 40 | 41 | #[cfg(test)] 42 | mod tests { 43 | use crate::{FixedTweener, Linear, Tweener}; 44 | 45 | use super::*; 46 | 47 | #[test] 48 | fn tweener_loop() { 49 | let mut looper = Tweener::new(0, 2, 2, Looper::new(Linear)); 50 | 51 | assert_eq!(looper.move_to(0), 0); 52 | assert_eq!(looper.move_to(1), 1); 53 | assert_eq!(looper.move_to(2), 2); 54 | assert_eq!(looper.move_to(3), 1); 55 | assert_eq!(looper.move_to(4), 2); 56 | assert_eq!(looper.move_to(5), 1); 57 | assert_eq!(looper.move_to(6), 2); 58 | } 59 | 60 | #[test] 61 | fn delta_tweener_loop() { 62 | let mut looper = Tweener::new(0, 2, 2, Looper::new(Linear)); 63 | 64 | assert_eq!(looper.move_by(1), 1); 65 | assert_eq!(looper.move_by(1), 2); 66 | assert_eq!(looper.move_by(1), 1); 67 | assert_eq!(looper.move_by(1), 2); 68 | assert_eq!(looper.move_by(1), 1); 69 | assert_eq!(looper.move_by(1), 2); 70 | } 71 | 72 | #[test] 73 | fn fixed_delta_tweener_loop() { 74 | let mut looper = FixedTweener::new(0, 2, 2, Looper::new(Linear), 1); 75 | 76 | assert_eq!(looper.next().unwrap(), 1); 77 | assert_eq!(looper.next().unwrap(), 2); 78 | assert_eq!(looper.next().unwrap(), 1); 79 | assert_eq!(looper.next().unwrap(), 2); 80 | assert_eq!(looper.next().unwrap(), 1); 81 | assert_eq!(looper.next().unwrap(), 2); 82 | } 83 | 84 | #[test] 85 | fn tweener_loop_frac() { 86 | let mut looper = Tweener::new(0, 2, 0.5, Looper::new(Linear)); 87 | 88 | assert_eq!(looper.move_by(0.25), 1); 89 | assert_eq!(looper.move_by(0.25), 2); 90 | assert_eq!(looper.move_by(0.25), 1); 91 | assert_eq!(looper.move_by(0.25), 2); 92 | assert_eq!(looper.move_by(0.25), 1); 93 | } 94 | 95 | #[test] 96 | fn tweener_big_loop() { 97 | let mut looper = Tweener::new(0, 2, 2, Looper::new(Linear)); 98 | 99 | assert_eq!(looper.move_by(3), 1); 100 | assert_eq!(looper.move_by(4), 1); 101 | assert_eq!(looper.move_by(4), 1); 102 | assert_eq!(looper.move_by(5), 2); 103 | } 104 | 105 | #[test] 106 | fn type_test() { 107 | let mut _looper: FixedTweener> = FixedTweener::new(0, 2, 2, Looper::new(Linear), 2); 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /src/tweener/oscillator.rs: -------------------------------------------------------------------------------- 1 | use crate::{Tween, TweenValue}; 2 | 3 | /// An [Oscillator] is a wrapper around a [Tween] which places the Tween into an infinite 4 | /// ping pong. 5 | /// 6 | /// This is similar to a [Looper](super::Looper), but instead of restarting the tween at the 7 | /// beginning, it restarts it at the end and travels backwards. For many Tweens in this library, 8 | /// this is the same 9 | #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone, Copy)] 10 | #[repr(transparent)] 11 | pub struct Oscillator(pub T); 12 | 13 | impl Oscillator { 14 | /// Creates a new Oscillator around a [Tween]. 15 | pub fn new(tween: T) -> Self { 16 | Self(tween) 17 | } 18 | } 19 | 20 | impl Tween for Oscillator 21 | where 22 | Value: TweenValue, 23 | T: Tween, 24 | { 25 | #[inline(always)] 26 | fn tween(&mut self, value_delta: Value, percent: f32) -> Value { 27 | let temp = percent % 2.0; 28 | 29 | #[cfg(feature = "std")] 30 | let (which_tween, percent) = { (temp.trunc(), percent.fract()) }; 31 | 32 | #[cfg(feature = "libm")] 33 | let (which_tween, percent) = { (libm::truncf(temp), percent - libm::truncf(percent)) }; 34 | 35 | // note: we don't have to worry about 0/1 difference here, since the tween 36 | // will get us to the same place 37 | let percent = if which_tween == 0.0 { percent } else { 1.0 - percent }; 38 | 39 | self.0.tween(value_delta, percent) 40 | } 41 | 42 | fn is_finite(&self) -> bool { 43 | false 44 | } 45 | } 46 | 47 | #[cfg(test)] 48 | mod tests { 49 | use super::*; 50 | use crate::{FixedTweener, Linear, Tweener}; 51 | 52 | #[test] 53 | fn div_euclid_fun() { 54 | assert_eq!(0.0f32 % 2.0, 0.0); 55 | assert_eq!(0.5f32 % 2.0, 0.5); 56 | assert_eq!(1.0f32 % 2.0, 1.0); 57 | assert_eq!(1.5f32 % 2.0, 1.5); 58 | assert_eq!(2.0f32 % 2.0, 0.0); 59 | 60 | assert_eq!((0.0f32 % 2.0).div_euclid(1.0), 0.0); 61 | assert_eq!((0.5f32 % 2.0).div_euclid(1.0), 0.0); 62 | assert_eq!((1.0f32 % 2.0).div_euclid(1.0), 1.0); 63 | assert_eq!((1.5f32 % 2.0).div_euclid(1.0), 1.0); 64 | assert_eq!((2.0f32 % 2.0).div_euclid(1.0), 0.0); 65 | assert_eq!((3.0f32 % 2.0).div_euclid(1.0), 1.0); 66 | assert_eq!((3.5f32 % 2.0).div_euclid(1.0), 1.0); 67 | assert_eq!((4.0f32 % 2.0).div_euclid(1.0), 0.0); 68 | assert_eq!((-0.5f32 % 2.0).div_euclid(1.0), -1.0); 69 | 70 | assert_eq!((0.0f32 % 2.0).div_euclid(1.0), (0.0f32 % 2.0).trunc()); 71 | assert_eq!((0.5f32 % 2.0).div_euclid(1.0), (0.5f32 % 2.0).trunc()); 72 | assert_eq!((1.0f32 % 2.0).div_euclid(1.0), (1.0f32 % 2.0).trunc()); 73 | assert_eq!((1.5f32 % 2.0).div_euclid(1.0), (1.5f32 % 2.0).trunc()); 74 | assert_eq!((2.0f32 % 2.0).div_euclid(1.0), (2.0f32 % 2.0).trunc()); 75 | assert_eq!((3.0f32 % 2.0).div_euclid(1.0), (3.0f32 % 2.0).trunc()); 76 | assert_eq!((3.5f32 % 2.0).div_euclid(1.0), (3.5f32 % 2.0).trunc()); 77 | assert_eq!((4.0f32 % 2.0).div_euclid(1.0), (4.0f32 % 2.0).trunc()); 78 | } 79 | 80 | #[test] 81 | fn tweener_oscillator() { 82 | let mut oscillator = Tweener::new(0, 2, 2, Oscillator::new(Linear)); 83 | 84 | assert_eq!(oscillator.move_to(0), 0); 85 | assert_eq!(oscillator.move_to(1), 1); 86 | assert_eq!(oscillator.move_to(2), 2); 87 | assert_eq!(oscillator.move_to(3), 1); 88 | assert_eq!(oscillator.move_to(4), 0); 89 | assert_eq!(oscillator.move_to(5), 1); 90 | assert_eq!(oscillator.move_to(6), 2); 91 | } 92 | 93 | #[test] 94 | fn delta_tweener_oscillator() { 95 | let mut oscillator = Tweener::new(0, 2, 2, Oscillator::new(Linear)); 96 | 97 | assert_eq!(oscillator.move_by(0), 0); 98 | assert_eq!(oscillator.move_by(1), 1); 99 | assert_eq!(oscillator.move_by(1), 2); 100 | assert_eq!(oscillator.move_by(1), 1); 101 | assert_eq!(oscillator.move_by(1), 0); 102 | assert_eq!(oscillator.move_by(1), 1); 103 | assert_eq!(oscillator.move_by(1), 2); 104 | } 105 | 106 | #[test] 107 | fn tweener_oscillator_big_loop() { 108 | let mut oscillator = Tweener::new(0, 2, 2, Oscillator::new(Linear)); 109 | 110 | assert_eq!(oscillator.move_by(2), 2); 111 | assert_eq!(oscillator.move_by(1), 1); 112 | assert_eq!(oscillator.move_by(2), 1); 113 | } 114 | 115 | #[test] 116 | fn fixed_tweener_oscillator() { 117 | let mut oscillator = FixedTweener::new(0, 2, 2, Oscillator::new(Linear), 1); 118 | 119 | assert_eq!(oscillator.next().unwrap(), 1); 120 | assert_eq!(oscillator.next().unwrap(), 2); 121 | assert_eq!(oscillator.next().unwrap(), 1); 122 | assert_eq!(oscillator.next().unwrap(), 0); 123 | assert_eq!(oscillator.next().unwrap(), 1); 124 | assert_eq!(oscillator.next().unwrap(), 2); 125 | } 126 | 127 | #[test] 128 | fn type_test() { 129 | let _one_type: Oscillator; 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /src/tweens.rs: -------------------------------------------------------------------------------- 1 | mod linear; 2 | pub use linear::Linear; 3 | 4 | mod cubic; 5 | pub use cubic::{CubicIn, CubicInOut, CubicOut}; 6 | 7 | mod sine; 8 | pub use sine::{SineIn, SineInOut, SineOut}; 9 | 10 | mod quint; 11 | pub use quint::{QuintIn, QuintInOut, QuintOut}; 12 | 13 | mod quad; 14 | pub use quad::{QuadIn, QuadInOut, QuadOut}; 15 | 16 | mod quart; 17 | pub use quart::{QuartIn, QuartInOut, QuartOut}; 18 | 19 | mod expo; 20 | pub use expo::{ExpoIn, ExpoInOut, ExpoOut}; 21 | 22 | mod circ; 23 | pub use circ::{CircIn, CircInOut, CircOut}; 24 | 25 | mod back; 26 | pub use back::{BackIn, BackInOut, BackOut}; 27 | 28 | mod elastic; 29 | pub use elastic::{ElasticIn, ElasticInOut, ElasticOut}; 30 | 31 | mod bounce; 32 | pub use bounce::{BounceIn, BounceInOut, BounceOut}; 33 | -------------------------------------------------------------------------------- /src/tweens/back.rs: -------------------------------------------------------------------------------- 1 | /// This appears to be a magic constant for Back eases. I have no idea 2 | /// where it's from, but we'll use it 3 | const BACK_CONST: f32 = 1.70158; 4 | 5 | /// This is another magic constant for the back in out tween. 6 | /// Where it comes from, I do not know! 7 | const BACK_IN_OUT_CONST: f32 = BACK_CONST * 1.525; 8 | 9 | declare_tween! { 10 | /// A tween that goes out and then back in a bit. Go [here](https://easings.net/#easeInBack) for a visual demonstration. 11 | pub struct BackIn; 12 | 13 | /// Creates a new [BackIn] Tweener. 14 | pub fn back_in; 15 | 16 | /// Creates a new [BackIn] Tweener at the given time. 17 | pub fn back_in_at; 18 | 19 | pub fn tween(&mut self, value_delta: Value, percent: f32) -> Value { 20 | let scalar = percent * percent * ((BACK_CONST + 1.0) * percent - BACK_CONST); 21 | 22 | value_delta.scale(scalar) 23 | } 24 | } 25 | 26 | declare_tween! { 27 | /// A tween that goes in and then back out a bit. Go [here](https://easings.net/#easeOutBack) for a visual demonstration. 28 | pub struct BackOut; 29 | 30 | /// Creates a new [BackOut] Tweener. 31 | pub fn back_out; 32 | 33 | /// Creates a new [BackOut] Tweener at the given time. 34 | pub fn back_out_at; 35 | 36 | pub fn tween(&mut self, value_delta: Value, percent: f32) -> Value { 37 | let t = percent - 1.0; 38 | let scalar = t * t * ((BACK_CONST + 1.0) * t + BACK_CONST) + 1.0; 39 | 40 | value_delta.scale(scalar) 41 | } 42 | } 43 | 44 | declare_tween! { 45 | /// A tween that goes out, in, and then back in and out a bit. Go [here](https://easings.net/#easeInOutBack) for a visual demonstration. 46 | pub struct BackInOut; 47 | 48 | /// Creates a new [BackInOut] Tweener. 49 | pub fn back_in_out; 50 | 51 | /// Creates a new [BackInOut] Tweener at the given time. 52 | pub fn back_in_out_at; 53 | 54 | pub fn tween(&mut self, value_delta: Value, mut percent: f32) -> Value { 55 | percent *= 2.0; 56 | 57 | let scalar = if percent < 1.0 { 58 | percent * percent * ((BACK_IN_OUT_CONST + 1.0) * percent - BACK_IN_OUT_CONST) 59 | } else { 60 | let t = percent - 2.0; 61 | 62 | t * t * ((BACK_IN_OUT_CONST + 1.0) * t + BACK_IN_OUT_CONST) + 2.0 63 | }; 64 | 65 | value_delta.scale(scalar / 2.0) 66 | } 67 | } 68 | 69 | test_tween!(Back); 70 | -------------------------------------------------------------------------------- /src/tweens/bounce.rs: -------------------------------------------------------------------------------- 1 | const MAGIC: f32 = 7.5625; 2 | const STAGE_ZERO: f32 = 1.0 / 2.75; 3 | const STAGE_ONE: f32 = 2.0 / 2.75; 4 | const STAGE_TWO: f32 = 2.5 / 2.75; 5 | 6 | declare_tween!( 7 | /// A bouncy tween, similar to gravity. Go [here](https://easings.net/#easeInBounce) for a visual demonstration. 8 | pub struct BounceIn; 9 | 10 | /// Creates a new [BounceIn] Tweener. 11 | pub fn bounce_in; 12 | 13 | /// Creates a new [BounceIn] Tweener at the given time. 14 | pub fn bounce_in_at; 15 | 16 | pub fn tween(&mut self, value_delta: Value, mut percent: f32) -> Value { 17 | percent = 1.0 - percent; 18 | 19 | let v = { 20 | let multip = if percent < STAGE_ZERO { 21 | MAGIC * percent * percent 22 | } else if percent < STAGE_ONE { 23 | let t = percent - 1.5 / 2.75; 24 | MAGIC * t * t + 0.75 25 | } else if percent < STAGE_TWO { 26 | let t = percent - 2.25 / 2.75; 27 | MAGIC * t * t + 0.9375 28 | } else { 29 | let t = percent - 2.625 / 2.75; 30 | 31 | MAGIC * t * t + 0.984375 32 | }; 33 | 34 | value_delta.scale(multip) 35 | }; 36 | 37 | value_delta - v 38 | } 39 | 40 | ); 41 | 42 | declare_tween!( 43 | /// A bouncy tween, similar to gravity. Go [here](https://easings.net/#easeOutBounce) for a visual demonstration. 44 | pub struct BounceOut; 45 | 46 | /// Creates a new [BounceOut] Tweener. 47 | pub fn bounce_out; 48 | 49 | /// Creates a new [BounceOut] Tweener at the given time. 50 | pub fn bounce_out_at; 51 | 52 | pub fn tween(&mut self, value_delta: Value, percent: f32) -> Value { 53 | let multip = if percent < STAGE_ZERO { 54 | MAGIC * percent * percent 55 | } else if percent < STAGE_ONE { 56 | let t = percent - 1.5 / 2.75; 57 | MAGIC * t * t + 0.75 58 | } else if percent < STAGE_TWO { 59 | let t = percent - 2.25 / 2.75; 60 | MAGIC * t * t + 0.9375 61 | } else { 62 | let t = percent - 2.625 / 2.75; 63 | 64 | MAGIC * t * t + 0.984375 65 | }; 66 | 67 | value_delta.scale(multip) 68 | } 69 | ); 70 | 71 | declare_tween!( 72 | /// A bouncy tween, similar to gravity. Go [here](https://easings.net/#easeInOutBounce) for a visual demonstration. 73 | pub struct BounceInOut; 74 | 75 | /// Creates a new [BounceInOut] Tweener. 76 | pub fn bounce_in_out; 77 | 78 | /// Creates a new [BounceInOut] Tweener at the given time. 79 | pub fn bounce_in_out_at; 80 | 81 | pub fn tween(&mut self, value_delta: Value, mut percent: f32) -> Value { 82 | if percent < 0.5 { 83 | percent = 1.0 - percent * 2.0; 84 | // (duration - current_time * 2.0) / duration 85 | 86 | let multip = if percent < STAGE_ZERO { 87 | MAGIC * percent * percent 88 | } else if percent < STAGE_ONE { 89 | let t = percent - 1.5 / 2.75; 90 | MAGIC * t * t + 0.75 91 | } else if percent < STAGE_TWO { 92 | let t = percent - 2.25 / 2.75; 93 | MAGIC * t * t + 0.9375 94 | } else { 95 | let t = percent - 2.625 / 2.75; 96 | 97 | MAGIC * t * t + 0.984375 98 | }; 99 | 100 | (value_delta - value_delta.scale(multip)).scale(0.5) 101 | } else { 102 | percent = (percent - 0.5) * 2.0; 103 | 104 | let multip = if percent < STAGE_ZERO { 105 | MAGIC * percent * percent 106 | } else if percent < STAGE_ONE { 107 | let t = percent - 1.5 / 2.75; 108 | MAGIC * t * t + 0.75 109 | } else if percent < STAGE_TWO { 110 | let t = percent - 2.25 / 2.75; 111 | MAGIC * t * t + 0.9375 112 | } else { 113 | let t = percent - 2.625 / 2.75; 114 | 115 | MAGIC * t * t + 0.984375 116 | }; 117 | 118 | value_delta.scale(multip).scale(0.5) + value_delta.scale(0.5) 119 | } 120 | } 121 | 122 | ); 123 | 124 | test_tween!(Bounce); 125 | -------------------------------------------------------------------------------- /src/tweens/circ.rs: -------------------------------------------------------------------------------- 1 | declare_tween!( 2 | /// A circular tween in. Go [here](https://easings.net/#easeInCirc) for a visual demonstration. 3 | pub struct CircIn; 4 | 5 | /// Creates a new [CircIn] Tweener. 6 | pub fn circ_in; 7 | 8 | /// Creates a new [CircIn] Tweener at the given time. 9 | pub fn circ_in_at; 10 | 11 | pub fn tween(&mut self, value_delta: Value, percent: f32) -> Value { 12 | #[cfg(feature = "libm")] 13 | let scalar = 1.0 - libm::sqrtf(1.0 - percent * percent); 14 | 15 | #[cfg(feature = "std")] 16 | let scalar = 1.0 - (1.0 - percent * percent).sqrt(); 17 | 18 | value_delta.scale(scalar) 19 | } 20 | ); 21 | 22 | declare_tween!( 23 | /// A circular tween out. Go [here](https://easings.net/#easeOutCirc) for a visual demonstration. 24 | pub struct CircOut; 25 | 26 | /// Creates a new [CircOut] Tweener. 27 | pub fn circ_out; 28 | 29 | /// Creates a new [CircOut] Tweener at the given time. 30 | pub fn circ_out_at; 31 | 32 | pub fn tween(&mut self, value_delta: Value, percent: f32) -> Value { 33 | let t = percent - 1.0; 34 | 35 | #[cfg(feature = "libm")] 36 | let scalar = libm::sqrtf(1.0 - t * t); 37 | 38 | #[cfg(feature = "std")] 39 | let scalar = (1.0 - t * t).sqrt(); 40 | 41 | value_delta.scale(scalar) 42 | } 43 | ); 44 | 45 | declare_tween!( 46 | /// A circular tween in and out. Go [here](https://easings.net/#easeInOutCirc) for a visual demonstration. 47 | pub struct CircInOut; 48 | 49 | /// Creates a new [CircInOut] Tweener. 50 | pub fn circ_in_out; 51 | 52 | /// Creates a new [CircInOut] Tweener at the given time. 53 | pub fn circ_in_out_at; 54 | 55 | pub fn tween(&mut self, value_delta: Value, mut percent: f32) -> Value { 56 | percent *= 2.0; 57 | 58 | let scalar = if percent < 1.0 { 59 | #[cfg(feature = "libm")] 60 | let o = 1.0 - libm::sqrtf(1.0 - percent * percent); 61 | 62 | #[cfg(feature = "std")] 63 | let o = 1.0 - (1.0 - percent * percent).sqrt(); 64 | 65 | o 66 | } else { 67 | let percent = percent - 2.0; 68 | 69 | #[cfg(feature = "libm")] 70 | let o = libm::sqrtf(1.0 - percent * percent) + 1.0; 71 | 72 | #[cfg(feature = "std")] 73 | let o = (1.0 - percent * percent).sqrt() + 1.0; 74 | 75 | o 76 | }; 77 | 78 | value_delta.scale(scalar / 2.0) 79 | } 80 | ); 81 | 82 | test_tween!(Circ); 83 | -------------------------------------------------------------------------------- /src/tweens/cubic.rs: -------------------------------------------------------------------------------- 1 | declare_tween!( 2 | /// A cubic tween in. Go [here](https://easings.net/#easeInCubic) for a visual demonstration. 3 | pub struct CubicIn; 4 | 5 | /// Creates a new [CubicIn] Tweener. 6 | pub fn cubic_in; 7 | 8 | /// Creates a new [CubicIn] Tweener at the given time. 9 | pub fn cubic_in_at; 10 | 11 | pub fn tween(&mut self, value_delta: Value, percent: f32) -> Value { 12 | value_delta.scale(percent * percent * percent) 13 | } 14 | ); 15 | 16 | declare_tween!( 17 | /// A cubic tween out. Go [here](https://easings.net/#easeOutCubic) for a visual demonstration. 18 | pub struct CubicOut; 19 | 20 | /// Creates a new [CubicOut] Tweener. 21 | pub fn cubic_out; 22 | 23 | /// Creates a new [CubicOut] Tweener at the given time. 24 | pub fn cubic_out_at; 25 | 26 | pub fn tween(&mut self, value_delta: Value, mut percent: f32) -> Value { 27 | percent -= 1.0; 28 | 29 | value_delta.scale(percent * percent * percent + 1.0) 30 | } 31 | ); 32 | 33 | declare_tween!( 34 | /// A cubic tween in and out. Go [here](https://easings.net/#easeInOutCubic) for a visual demonstration. 35 | pub struct CubicInOut; 36 | 37 | /// Creates a new [CubicInOut] Tweener. 38 | pub fn cubic_in_out; 39 | 40 | /// Creates a new [CubicInOut] Tweener at the given time. 41 | pub fn cubic_in_out_at; 42 | 43 | pub fn tween(&mut self, value_delta: Value, mut percent: f32) -> Value { 44 | percent *= 2.0; 45 | 46 | let scalar = if percent < 1.0 { 47 | percent * percent * percent 48 | } else { 49 | let p = percent - 2.0; 50 | p * p * p + 2.0 51 | }; 52 | value_delta.scale(scalar / 2.0) 53 | } 54 | ); 55 | 56 | test_tween!(Cubic); 57 | -------------------------------------------------------------------------------- /src/tweens/elastic.rs: -------------------------------------------------------------------------------- 1 | use core::f32::consts::TAU; 2 | 3 | const SIGMA: f32 = 0.075; 4 | const SIGMA_IN_OUT: f32 = 0.1125; 5 | const THREE_DOT_THREE_REPEATING: f32 = 10.0 / 3.0; 6 | const FORTY_FIVE: f32 = 2.222222; 7 | 8 | declare_tween!( 9 | /// An elastic tween in. Go [here](https://easings.net/#easeInElastic) for a visual demonstration. 10 | pub struct ElasticIn; 11 | 12 | /// Creates a new [ElasticIn] Tweener. 13 | pub fn elastic_in; 14 | 15 | /// Creates a new [ElasticIn] Tweener at the given time. 16 | pub fn elastic_in_at; 17 | 18 | pub fn tween(&mut self, value_delta: Value, mut percent: f32) -> Value { 19 | if percent == 0.0 { 20 | return value_delta.scale(0.0); 21 | } 22 | 23 | if percent == 1.0 { 24 | return value_delta; 25 | } 26 | 27 | percent -= 1.0; 28 | 29 | #[cfg(feature = "libm")] 30 | let scalar = libm::powf(2.0, percent * 10.0); 31 | 32 | #[cfg(feature = "std")] 33 | let scalar = 2f32.powf(percent * 10.0); 34 | 35 | let post_fix = value_delta.scale(scalar); 36 | let temp = (percent - SIGMA) * TAU * THREE_DOT_THREE_REPEATING; 37 | 38 | #[cfg(feature = "libm")] 39 | let scalar = -libm::sinf(temp); 40 | 41 | #[cfg(feature = "std")] 42 | let scalar = -temp.sin(); 43 | 44 | post_fix.scale(scalar) 45 | } 46 | ); 47 | 48 | declare_tween!( 49 | /// An elastic tween out. Go [here](https://easings.net/#easeOutElastic) for a visual demonstration. 50 | pub struct ElasticOut; 51 | 52 | /// Creates a new [ElasticOut] Tweener. 53 | pub fn elastic_out; 54 | 55 | /// Creates a new [ElasticOut] Tweener at the given time. 56 | pub fn elastic_out_at; 57 | 58 | pub fn tween(&mut self, value_delta: Value, percent: f32) -> Value { 59 | if percent == 0.0 { 60 | return value_delta.scale(0.0); 61 | } 62 | 63 | if percent == 1.0 { 64 | return value_delta; 65 | } 66 | 67 | let temp = (percent - SIGMA) * TAU * THREE_DOT_THREE_REPEATING; 68 | 69 | #[cfg(feature = "libm")] 70 | let scalar = libm::powf(2.0, -10.0 * percent) * libm::sinf(temp); 71 | 72 | #[cfg(feature = "std")] 73 | let scalar = 2f32.powf(-10.0 * percent) * temp.sin(); 74 | 75 | value_delta.scale(scalar) + value_delta 76 | } 77 | ); 78 | 79 | declare_tween!( 80 | /// An elastic tween in and out. Go [here](https://easings.net/#easeInOutElastic) for a visual demonstration. 81 | pub struct ElasticInOut; 82 | 83 | /// Creates a new [ElasticInOut] Tweener. 84 | pub fn elastic_in_out; 85 | 86 | /// Creates a new [ElasticInOut] Tweener at the given time. 87 | pub fn elastic_in_out_at; 88 | 89 | pub fn tween(&mut self, value_delta: Value, mut percent: f32) -> Value { 90 | if percent == 0.0 { 91 | return value_delta.scale(0.0); 92 | } 93 | 94 | if percent == 1.0 { 95 | return value_delta; 96 | } 97 | 98 | percent = (percent * 2.0) - 1.0; 99 | 100 | if percent < 0.0 { 101 | #[cfg(feature = "libm")] 102 | let scalar = libm::powf(2.0, percent * 10.0); 103 | 104 | #[cfg(feature = "std")] 105 | let scalar = 2f32.powf(percent * 10.0); 106 | 107 | let post_fix = value_delta.scale(scalar); 108 | let temp = (percent - SIGMA_IN_OUT) * TAU * FORTY_FIVE; 109 | 110 | #[cfg(feature = "libm")] 111 | let temp_sin = libm::sinf(temp); 112 | 113 | #[cfg(feature = "std")] 114 | let temp_sin = temp.sin(); 115 | 116 | post_fix.scale(-0.5 * temp_sin) 117 | } else { 118 | #[cfg(feature = "libm")] 119 | let scalar = libm::powf(2.0, percent * -10.0); 120 | 121 | #[cfg(feature = "std")] 122 | let scalar = 2f32.powf(-10.0 * percent); 123 | 124 | let post_fix = value_delta.scale(scalar); 125 | let temp = (percent - SIGMA_IN_OUT) * TAU * FORTY_FIVE; 126 | 127 | #[cfg(feature = "libm")] 128 | let temp_sin = libm::sinf(temp); 129 | 130 | #[cfg(feature = "std")] 131 | let temp_sin = temp.sin(); 132 | 133 | post_fix.scale(temp_sin * 0.5) + value_delta 134 | } 135 | 136 | } 137 | ); 138 | 139 | test_tween!(Elastic); 140 | -------------------------------------------------------------------------------- /src/tweens/expo.rs: -------------------------------------------------------------------------------- 1 | declare_tween!( 2 | /// An exponenential tween in. See [here](https://easings.net/#easeInExpo) 3 | pub struct ExpoIn; 4 | 5 | /// Creates a new [ExpoIn] Tweener. 6 | pub fn expo_in; 7 | 8 | /// Creates a new [ExpoIn] Tweener at the given time. 9 | pub fn expo_in_at; 10 | 11 | pub fn tween(&mut self, value_delta: Value, percent: f32) -> Value { 12 | // weird edge in this tween? 13 | if percent == 0.0 { 14 | return value_delta.scale(0.0); 15 | } 16 | 17 | let percent = 10.0 * (percent - 1.0); 18 | 19 | #[cfg(feature = "libm")] 20 | let scalar = libm::powf(2.0, percent); 21 | 22 | #[cfg(feature = "std")] 23 | let scalar = 2.0f32.powf(percent); 24 | 25 | value_delta.scale(scalar) 26 | } 27 | ); 28 | 29 | declare_tween!( 30 | /// An exponenential tween out. See [here](https://easings.net/#easeOutExpo) 31 | pub struct ExpoOut; 32 | 33 | /// Creates a new [ExpoOut] Tweener. 34 | pub fn expo_out; 35 | 36 | /// Creates a new [ExpoOut] Tweener at the given time. 37 | pub fn expo_out_at; 38 | 39 | pub fn tween(&mut self, value_delta: Value, percent: f32) -> Value { 40 | if percent == 1.0 { 41 | value_delta 42 | } else { 43 | #[cfg(feature = "libm")] 44 | let powf = libm::powf(2.0, -10.0 * percent); 45 | 46 | #[cfg(feature = "std")] 47 | let powf = 2.0f32.powf(-10.0 * percent); 48 | 49 | value_delta.scale(1.0 - powf) 50 | } 51 | } 52 | ); 53 | 54 | declare_tween!( 55 | /// An exponenential tween in and out. See [here](https://easings.net/#easeInOutExpo) 56 | pub struct ExpoInOut; 57 | 58 | /// Creates a new [ExpoInOut] Tweener. 59 | pub fn expo_in_out; 60 | 61 | /// Creates a new [ExpoInOut] Tweener at the given time. 62 | pub fn expo_in_out_at; 63 | 64 | pub fn tween(&mut self, value_delta: Value, mut percent: f32) -> Value { 65 | if percent == 0.0 { 66 | return value_delta.scale(0.0); 67 | } 68 | 69 | if percent == 1.0 { 70 | return value_delta; 71 | } 72 | 73 | percent *= 2.0; 74 | 75 | let powf = if percent < 1.0 { 76 | #[cfg(feature = "libm")] 77 | let scalar = libm::powf(2.0, 10.0 * (percent - 1.0)); 78 | 79 | #[cfg(feature = "std")] 80 | let scalar = 2.0f32.powf(10.0 * (percent - 1.0)); 81 | 82 | scalar / 2.0 83 | } else { 84 | let percent = percent - 1.0; 85 | 86 | #[cfg(feature = "libm")] 87 | let scalar = libm::powf(2.0, -10.0 * percent); 88 | 89 | #[cfg(feature = "std")] 90 | let scalar = 2.0f32.powf(-10.0 * percent); 91 | 92 | (2.0 - scalar) / 2.0 93 | }; 94 | 95 | value_delta.scale(powf) 96 | } 97 | ); 98 | 99 | test_tween!(Expo); 100 | -------------------------------------------------------------------------------- /src/tweens/linear.rs: -------------------------------------------------------------------------------- 1 | declare_tween!( 2 | /// A Linear tween is a simple lerp from one value to another. 3 | pub struct Linear; 4 | 5 | /// Creates a new [Linear] Tweener. 6 | pub fn linear; 7 | 8 | /// Creates a new [Linear] Tweener at the given time. 9 | pub fn linear_at; 10 | 11 | pub fn tween(&mut self, value_delta: Value, percent: f32) -> Value { 12 | value_delta.scale(percent) 13 | } 14 | ); 15 | 16 | #[cfg(test)] 17 | mod tests { 18 | use super::Linear; 19 | use approx::assert_ulps_eq; 20 | 21 | #[test] 22 | fn linear_over_frames() { 23 | let mut value; 24 | let mut tweener = crate::Tweener::new(0.0, 100.0, 10, Linear); 25 | 26 | for val in 1..=10 { 27 | value = tweener.move_to(val); 28 | assert_ulps_eq!(value, val as f32 * 10.0); 29 | } 30 | } 31 | 32 | #[test] 33 | fn linear_over_frames_rev() { 34 | let mut value; 35 | let mut tweener = crate::Tweener::new(100.0, 0.0, 10, Linear); 36 | 37 | for val in 1..=10 { 38 | value = tweener.move_to(val); 39 | assert_ulps_eq!(value, 100.0 - val as f32 * 10.0); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/tweens/quad.rs: -------------------------------------------------------------------------------- 1 | declare_tween!( 2 | /// An quadratic tween in. Go [here](https://easings.net/#easeInQuad) for a visual demonstration. 3 | pub struct QuadIn; 4 | 5 | /// Creates a new [QuadIn] Tweener. 6 | pub fn quad_in; 7 | 8 | /// Creates a new [QuadIn] Tweener at the given time. 9 | pub fn quad_in_at; 10 | 11 | pub fn tween(&mut self, value_delta: Value, percent: f32) -> Value { 12 | value_delta.scale(percent * percent) 13 | } 14 | ); 15 | 16 | declare_tween!( 17 | /// An quadratic tween out. Go [here](https://easings.net/#easeOutQuad) for a visual demonstration. 18 | pub struct QuadOut; 19 | 20 | /// Creates a new [QuadOut] Tweener. 21 | pub fn quad_out; 22 | 23 | /// Creates a new [QuadOut] Tweener at the given time. 24 | pub fn quad_out_at; 25 | 26 | pub fn tween(&mut self, value_delta: Value, percent: f32) -> Value { 27 | value_delta.scale(-percent).scale(percent - 2.0) 28 | } 29 | ); 30 | 31 | declare_tween!( 32 | /// An quadratic tween in and out. Go [here](https://easings.net/#easeInOutQuad) for a visual demonstration. 33 | pub struct QuadInOut; 34 | 35 | /// Creates a new [QuadInOut] Tweener. 36 | pub fn quad_in_out; 37 | 38 | /// Creates a new [QuadInOut] Tweener at the given time. 39 | pub fn quad_in_out_at; 40 | 41 | pub fn tween(&mut self, value_delta: Value, mut percent: f32) -> Value { 42 | percent *= 2.0; 43 | 44 | let scalar = if percent < 1.0 { 45 | percent * percent 46 | } else { 47 | let p = percent - 1.0; 48 | 49 | (p * (p - 2.0) - 1.0) * -1.0 50 | }; 51 | value_delta.scale(scalar / 2.0) 52 | } 53 | ); 54 | 55 | test_tween!(Quad); 56 | -------------------------------------------------------------------------------- /src/tweens/quart.rs: -------------------------------------------------------------------------------- 1 | declare_tween!( 2 | /// An quartic tween in. Go [here](https://easings.net/#easeInQuart) for a visual demonstration. 3 | pub struct QuartIn; 4 | 5 | /// Creates a new [QuartIn] Tweener. 6 | pub fn quart_in; 7 | 8 | /// Creates a new [QuartIn] Tweener at the given time. 9 | pub fn quart_in_at; 10 | 11 | pub fn tween(&mut self, value_delta: Value, percent: f32) -> Value { 12 | value_delta.scale(percent * percent * percent * percent) 13 | } 14 | ); 15 | 16 | declare_tween!( 17 | /// An quartic tween out. Go [here](https://easings.net/#easeOutQuart) for a visual demonstration. 18 | pub struct QuartOut; 19 | 20 | /// Creates a new [QuartOut] Tweener. 21 | pub fn quart_out; 22 | 23 | /// Creates a new [QuartOut] Tweener at the given time. 24 | pub fn quart_out_at; 25 | 26 | pub fn tween(&mut self, value_delta: Value, mut percent: f32) -> Value { 27 | percent -= 1.0; 28 | value_delta.scale(-(percent * percent * percent * percent - 1.0)) 29 | } 30 | ); 31 | 32 | declare_tween!( 33 | /// An quartic tween in and out. Go [here](https://easings.net/#easeInOutQuart) for a visual demonstration. 34 | pub struct QuartInOut; 35 | 36 | /// Creates a new [QuartInOut] Tweener. 37 | pub fn quart_in_out; 38 | 39 | /// Creates a new [QuartInOut] Tweener at the given time. 40 | pub fn quart_in_out_at; 41 | 42 | pub fn tween(&mut self, value_delta: Value, mut percent: f32) -> Value { 43 | percent *= 2.0; 44 | 45 | let scalar = if percent < 1.0 { 46 | percent * percent * percent * percent 47 | } else { 48 | let p = percent - 2.0; 49 | -(p * p * p * p - 2.0) 50 | }; 51 | value_delta.scale(scalar / 2.0) 52 | } 53 | ); 54 | 55 | test_tween!(Quart); 56 | -------------------------------------------------------------------------------- /src/tweens/quint.rs: -------------------------------------------------------------------------------- 1 | declare_tween!( 2 | /// An quintic tween in. Go [here](https://easings.net/#easeInQuint) for a visual demonstration. 3 | pub struct QuintIn; 4 | 5 | /// Creates a new [QuintInOut] Tweener. 6 | pub fn quint_in; 7 | 8 | /// Creates a new [QuintInOut] Tweener at the given time. 9 | pub fn quint_in_at; 10 | 11 | pub fn tween(&mut self, value_delta: Value, percent: f32) -> Value { 12 | value_delta.scale(percent * percent * percent * percent * percent) 13 | } 14 | ); 15 | 16 | declare_tween!( 17 | /// An quintic tween out. Go [here](https://easings.net/#easeOutQuint) for a visual demonstration. 18 | pub struct QuintOut; 19 | 20 | /// Creates a new [QuintOut] Tweener. 21 | pub fn quint_out; 22 | 23 | /// Creates a new [QuintOut] Tweener at the given time. 24 | pub fn quint_out_at; 25 | 26 | pub fn tween(&mut self, value_delta: Value, mut percent: f32) -> Value { 27 | percent -= 1.0; 28 | value_delta.scale(percent * percent * percent * percent * percent + 1.0) 29 | } 30 | ); 31 | 32 | declare_tween!( 33 | /// An quintic tween in out. Go [here](https://easings.net/#easeInOutQuint) for a visual demonstration. 34 | pub struct QuintInOut; 35 | 36 | /// Creates a new [QuintInOut] Tweener. 37 | pub fn quint_in_out; 38 | 39 | /// Creates a new [QuintInOut] Tweener at the given time. 40 | pub fn quint_in_out_at; 41 | 42 | pub fn tween(&mut self, value_delta: Value, mut percent: f32) -> Value { 43 | percent *= 2.0; 44 | 45 | let scalar = if percent < 1.0 { 46 | percent * percent * percent * percent * percent 47 | } else { 48 | let p = percent - 2.0; 49 | p * p * p * p * p + 2.0 50 | }; 51 | value_delta.scale(scalar / 2.0) 52 | } 53 | ); 54 | 55 | test_tween!(Quint); 56 | -------------------------------------------------------------------------------- /src/tweens/sine.rs: -------------------------------------------------------------------------------- 1 | use core::f32::consts::PI; 2 | 3 | declare_tween!( 4 | /// An sine based tween in. Go [here](https://easings.net/#easeInSine) for a visual demonstration. 5 | pub struct SineIn; 6 | 7 | /// Creates a new [SineIn] Tweener. 8 | pub fn sine_in; 9 | 10 | /// Creates a new [SineIn] Tweener at the given time. 11 | pub fn sine_in_at; 12 | 13 | pub fn tween(&mut self, value_delta: Value, percent: f32) -> Value { 14 | #[cfg(feature = "libm")] 15 | let time = libm::cosf(percent * PI / 2.0); 16 | 17 | #[cfg(feature = "std")] 18 | let time = (percent * PI / 2.0).cos(); 19 | 20 | value_delta.scale(-time) + value_delta 21 | } 22 | ); 23 | 24 | declare_tween!( 25 | /// An sine based tween out. Go [here](https://easings.net/#easeOutSine) for a visual demonstration. 26 | pub struct SineOut; 27 | 28 | /// Creates a new [SineOut] Tweener. 29 | pub fn sine_out; 30 | 31 | /// Creates a new [SineOut] Tweener at the given time. 32 | pub fn sine_out_at; 33 | 34 | pub fn tween(&mut self, value_delta: Value, percent: f32) -> Value { 35 | #[cfg(feature = "libm")] 36 | let time = libm::sinf(percent * PI / 2.0); 37 | 38 | #[cfg(feature = "std")] 39 | let time = (percent * PI / 2.0).sin(); 40 | 41 | value_delta.scale(time) 42 | } 43 | ); 44 | 45 | declare_tween!( 46 | /// An sine based tween in out. Go [here](https://easings.net/#easeInOutSine) for a visual demonstration. 47 | pub struct SineInOut; 48 | 49 | /// Creates a new [SineOut] Tweener. 50 | pub fn sine_in_out; 51 | 52 | /// Creates a new [SineOut] Tweener at the given time. 53 | pub fn sine_in_out_at; 54 | 55 | pub fn tween(&mut self, value_delta: Value, percent: f32) -> Value 56 | { 57 | #[cfg(feature = "libm")] 58 | let time = libm::cosf(percent * PI) - 1.0; 59 | 60 | #[cfg(feature = "std")] 61 | let time = (percent * PI).cos() - 1.0; 62 | value_delta.scale(-time / 2.0) 63 | } 64 | ); 65 | 66 | test_tween!(Sine); 67 | --------------------------------------------------------------------------------