├── .arcconfig ├── .arclint ├── .editorconfig ├── .gitignore ├── .local.dependencies.template ├── .travis.yml ├── AUTHORS ├── CHANGELOG.md ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── build.gradle ├── checkstyle.xml ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── install-local-dependency.sh ├── library ├── build.gradle ├── proguard-rules.pro └── src │ ├── main │ ├── AndroidManifest.xml │ └── java │ │ └── com │ │ └── google │ │ └── android │ │ └── material │ │ └── motion │ │ └── physics │ │ ├── ChoreographerCompat.java │ │ ├── Force.java │ │ ├── Integrator.java │ │ ├── forces │ │ ├── AnchoredForce.java │ │ └── Spring.java │ │ ├── integrators │ │ └── Rk4Integrator.java │ │ └── math │ │ ├── MathUtils.java │ │ ├── Vector.java │ │ └── Vectors.java │ └── test │ └── java │ └── com │ └── google │ └── android │ └── material │ └── motion │ └── physics │ └── UnitTests.java ├── local-dependency-substitution.gradle ├── sample ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── google │ │ └── android │ │ └── material │ │ └── motion │ │ └── physics │ │ └── sample │ │ ├── DragFrameLayout.java │ │ └── MainActivity.java │ └── res │ ├── drawable │ ├── anchor1.xml │ ├── anchor2.xml │ └── circle.xml │ ├── layout │ └── main_activity.xml │ ├── mipmap-hdpi │ └── ic_launcher.png │ ├── mipmap-mdpi │ └── ic_launcher.png │ ├── mipmap-xhdpi │ └── ic_launcher.png │ ├── mipmap-xxhdpi │ └── ic_launcher.png │ ├── mipmap-xxxhdpi │ └── ic_launcher.png │ └── values │ ├── dimens.xml │ ├── strings.xml │ └── styles.xml └── settings.gradle /.arcconfig: -------------------------------------------------------------------------------- 1 | { 2 | "load": [ 3 | "material-arc-tools/third_party/arc-hook-conphig", 4 | "material-arc-tools/third_party/arc-hook-github-issues", 5 | "material-arc-tools/third_party/arc-proselint" 6 | ], 7 | "arcanist_configuration": "HookConphig", 8 | "phabricator.uri": "http://codereview.cc/", 9 | "arc.land.onto.default": "develop", 10 | "arc.feature.start.default": "origin/develop" 11 | } 12 | -------------------------------------------------------------------------------- /.arclint: -------------------------------------------------------------------------------- 1 | { 2 | "linters": { 3 | "chmod": { 4 | "type": "chmod" 5 | }, 6 | "text": { 7 | "type": "text", 8 | "include": "(\\.(java|xml)$)", 9 | "exclude": [], 10 | "severity": { 11 | "3": "disabled", 12 | "5": "disabled" 13 | } 14 | }, 15 | "prose": { 16 | "type": "prose", 17 | "include": "(\\.(md)$)", 18 | "exclude": [ 19 | "(^CHANGELOG.md)" 20 | ], 21 | "severity": { 22 | "consistency.spacing": "disabled", 23 | "typography.symbols.curly_quotes": "disabled", 24 | "typography.symbols.ellipsis": "disabled", 25 | "leonard.exclamation.30ppm": "disabled", 26 | "misc.annotations": "warning" 27 | } 28 | }, 29 | "spelling": { 30 | "type": "spelling", 31 | "include": "(\\.(md)$)" 32 | } 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | 3 | root = true 4 | 5 | [*] 6 | charset = utf-8 7 | indent_style = space 8 | indent_size = 2 9 | end_of_line = lf 10 | insert_final_newline = true 11 | trim_trailing_whitespace = true 12 | 13 | [*.md] 14 | trim_trailing_whitespace = true 15 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | 3 | # Built application files 4 | *.apk 5 | *.ap_ 6 | 7 | # Files for the ART/Dalvik VM 8 | *.dex 9 | 10 | # Java class files 11 | *.class 12 | 13 | # Generated files 14 | bin/ 15 | gen/ 16 | out/ 17 | 18 | # Gradle files 19 | .gradle/ 20 | build/ 21 | 22 | # Local configuration file (sdk path, etc) 23 | local.properties 24 | local.dependencies 25 | 26 | # Proguard folder generated by Eclipse 27 | proguard/ 28 | 29 | # Log Files 30 | *.log 31 | 32 | # Android Studio Navigation editor temp files 33 | .navigation/ 34 | 35 | # Android Studio captures folder 36 | captures/ 37 | 38 | # Intellij 39 | *.iml 40 | .idea/ 41 | 42 | # Keystore files 43 | *.jks 44 | -------------------------------------------------------------------------------- /.local.dependencies.template: -------------------------------------------------------------------------------- 1 | # List local dependencies here to be applied to all projects in this library. 2 | # 3 | # ██████╗ ██╗ ███████╗ █████╗ ███████╗███████╗ ██████╗ ███████╗ █████╗ ██████╗ 4 | # ██╔══██╗██║ ██╔════╝██╔══██╗██╔════╝██╔════╝ ██╔══██╗██╔════╝██╔══██╗██╔══██╗ 5 | # ██████╔╝██║ █████╗ ███████║███████╗█████╗ ██████╔╝█████╗ ███████║██║ ██║ 6 | # ██╔═══╝ ██║ ██╔══╝ ██╔══██║╚════██║██╔══╝ ██╔══██╗██╔══╝ ██╔══██║██║ ██║ 7 | # ██║ ███████╗███████╗██║ ██║███████║███████╗ ██║ ██║███████╗██║ ██║██████╔╝ 8 | # ╚═╝ ╚══════╝╚══════╝╚═╝ ╚═╝╚══════╝╚══════╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ 9 | # 10 | # Format: 11 | # 12 | # [group]:[name] 13 | # 14 | # Example: 15 | # 16 | # com.github.material-motion:physics-android 17 | # 18 | # These are dependencies defined in your build.gradle for which you would like to reflect any local 19 | # changes. This is useful if you would like to develop multiple libraries in tandem. 20 | # 21 | # You must `Sync Project with Gradle Files` every time you add or remove a local dependency. 22 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: android 3 | jdk: oraclejdk8 4 | env: 5 | matrix: 6 | - ANDROID_TARGET=android-25 7 | 8 | android: 9 | components: 10 | - platform-tools 11 | - tools 12 | - android-25 13 | - build-tools-25.0.0 14 | 15 | licenses: 16 | - 'android-sdk-license-.+' 17 | 18 | before_install: 19 | - echo yes | android update sdk --filter extra-android-m2repository --no-ui --force > /dev/null 20 | 21 | script: 22 | - ./gradlew check 23 | 24 | after_success: 25 | - bash <(curl -s https://codecov.io/bash) 26 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | # This is the list of Material Motion Physics for Android authors for copyright purposes. 2 | # 3 | # This does not necessarily list everyone who has contributed code, since in 4 | # some cases, their employer may be the copyright holder. To see the full list 5 | # of contributors, see the revision history with git log. 6 | 7 | Google Inc. 8 | and other contributors 9 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/material-motion/physics-android/85d3101c0d74466efa347dbb42c1b8223609a4c5/CHANGELOG.md -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Want to contribute? Great! First, read this page (including the small print at 2 | the end). 3 | 4 | ### Before you contribute 5 | 6 | Before we can use your code, you must sign the 7 | [Google Individual Contributor License Agreement] 8 | (https://cla.developers.google.com/about/google-individual) 9 | (CLA), which you can do online. The CLA is necessary mainly because you own the 10 | copyright to your changes, even after your contribution becomes part of our 11 | codebase, so we need your permission to use and distribute your code. We also 12 | need to be sure of various other things—for instance that you'll tell us if you 13 | know that your code infringes on other people's patents. You don't have to sign 14 | the CLA until after you've submitted your code for review and a member has 15 | approved it, but you must do it before we can put your code into our codebase. 16 | Before you start working on a larger contribution, you should get in touch with 17 | us first through the issue tracker with your idea so that we can help out and 18 | possibly guide you. Coordinating up front makes it much easier to avoid 19 | frustration later on. 20 | 21 | ### Code reviews 22 | 23 | All submissions, including submissions by project members, require review. 24 | We use GitHub pull requests for this purpose. 25 | 26 | ### The small print 27 | 28 | Contributions made by corporations are covered by a different agreement than 29 | the one above, the 30 | [Software Grant and Corporate Contributor License Agreement] 31 | (https://cla.developers.google.com/about/google-corporate). 32 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Material Motion Physics for Android 2 | 3 | [![Build Status](https://travis-ci.org/material-motion/physics-android.svg?branch=develop)](https://travis-ci.org/material-motion/physics-android) 4 | [![codecov](https://codecov.io/gh/material-motion/physics-android/branch/develop/graph/badge.svg)](https://codecov.io/gh/material-motion/physics-android) 5 | [![Release](https://img.shields.io/github/release/material-motion/physics-android.svg)](https://github.com/material-motion/physics-android/releases/latest) 6 | [![Docs](https://img.shields.io/badge/jitpack-docs-green.svg)](https://jitpack.io/com/github/material-motion/physics-android/stable-SNAPSHOT/javadoc/) 7 | 8 | The Material Motion Physics for Android repo. 9 | 10 | Learn more about the APIs defined in the library by reading our 11 | [technical documentation](https://jitpack.io/com/github/material-motion/physics-android/1.0.0/javadoc/) and our 12 | [Starmap](https://material-motion.github.io/material-motion/starmap/). 13 | 14 | ## Installation 15 | 16 | ### Installation with Jitpack 17 | 18 | Add the Jitpack repository to your project's `build.gradle`: 19 | 20 | ```gradle 21 | allprojects { 22 | repositories { 23 | maven { url "https://jitpack.io" } 24 | } 25 | } 26 | ``` 27 | 28 | Depend on the [latest version](https://github.com/material-motion/physics-android/releases) of the library. 29 | Take care to occasionally [check for updates](https://github.com/ben-manes/gradle-versions-plugin). 30 | 31 | ```gradle 32 | dependencies { 33 | compile 'com.github.material-motion:physics-android:1.0.0' 34 | } 35 | ``` 36 | 37 | For more information regarding versioning, see: 38 | 39 | - [Material Motion Versioning Policies](https://material-motion.github.io/material-motion/team/essentials/core_team_contributors/release_process#versioning) 40 | 41 | ### Using the files from a folder local to the machine 42 | 43 | You can have a copy of this library with local changes and test it in tandem 44 | with its client project. To add a local dependency on this library, add this 45 | library's identifier to your project's `local.dependencies`: 46 | 47 | ``` 48 | com.github.material-motion:physics-android 49 | ``` 50 | 51 | > Because `local.dependencies` is never to be checked into Version Control 52 | Systems, you must also ensure that any local dependencies are also defined in 53 | `build.gradle` as explained in the previous section. 54 | 55 | **Important** 56 | 57 | For each local dependency listed, you *must* run `gradle install` from its 58 | project root every time you make a change to it. That command will publish your 59 | latest changes to the local maven repository. If your local dependencies have 60 | local dependencies of their own, you must `gradle install` them as well. 61 | 62 | You must `gradle clean` your project every time you add or remove a local 63 | dependency. 64 | 65 | ### Usage 66 | 67 | How to use the library in your project. 68 | 69 | #### Editing the library in Android Studio 70 | 71 | Open Android Studio, 72 | choose `File > New > Import`, 73 | choose the root `build.gradle` file. 74 | 75 | ## Example apps/unit tests 76 | 77 | To build the sample application, run the following commands: 78 | 79 | git clone https://github.com/material-motion/physics-android.git 80 | cd physics-android 81 | gradle installDebug 82 | 83 | To run all unit tests, run the following commands: 84 | 85 | git clone https://github.com/material-motion/physics-android.git 86 | cd physics-android 87 | gradle test 88 | 89 | # Guides 90 | 91 | 1. [Architecture](#architecture) 92 | 1. [How to ...](#how-to-...) 93 | 94 | ## Architecture 95 | 96 | ## How to ... 97 | 98 | ## Contributing 99 | 100 | We welcome contributions! 101 | 102 | Check out our [upcoming milestones](https://github.com/material-motion/physics-android/milestones). 103 | 104 | Learn more about [our team](https://material-motion.github.io/material-motion/team/), 105 | [our community](https://material-motion.github.io/material-motion/team/community/), and 106 | our [contributor essentials](https://material-motion.github.io/material-motion/team/essentials/). 107 | 108 | ## License 109 | 110 | Licensed under the Apache 2.0 license. See LICENSE for details. 111 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | apply from: 'local-dependency-substitution.gradle' 2 | apply plugin: "checkstyle" 3 | 4 | buildscript { 5 | repositories { 6 | jcenter() 7 | } 8 | dependencies { 9 | classpath 'com.android.tools.build:gradle:2.2.3' 10 | classpath 'com.github.dcendents:android-maven-gradle-plugin:1.4.1' 11 | classpath 'com.vanniktech:gradle-android-junit-jacoco-plugin:0.5.0' 12 | } 13 | } 14 | 15 | allprojects { 16 | repositories { 17 | jcenter() 18 | maven { url "https://jitpack.io" } 19 | } 20 | } 21 | 22 | subprojects { 23 | apply plugin: 'checkstyle' 24 | apply plugin: 'pmd' 25 | 26 | checkstyle { 27 | configFile = rootProject.file('checkstyle.xml') 28 | toolVersion = '7.1' 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /checkstyle.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 69 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 94 | 95 | 96 | 98 | 99 | 100 | 101 | 103 | 104 | 105 | 106 | 108 | 109 | 110 | 111 | 113 | 114 | 115 | 116 | 117 | 118 | 120 | 121 | 122 | 123 | 125 | 126 | 127 | 128 | 130 | 131 | 132 | 133 | 135 | 136 | 137 | 138 | 140 | 142 | 144 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | 163 | 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | 173 | 174 | 175 | 176 | 177 | 178 | 179 | 180 | 181 | 182 | 183 | 184 | 185 | 186 | 187 | 188 | 189 | 190 | 191 | 192 | 193 | 194 | 195 | 196 | 197 | 198 | 199 | 201 | 202 | 203 | 204 | 205 | 206 | 207 | 208 | 209 | 210 | 211 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | # Default value: -Xmx10248m -XX:MaxPermSize=256m 13 | org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8 14 | 15 | # When configured, Gradle will run in incubating parallel mode. 16 | # This option should only be used with decoupled projects. More details, visit 17 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 18 | # org.gradle.parallel=true 19 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/material-motion/physics-android/85d3101c0d74466efa347dbb42c1b8223609a4c5/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Thu Dec 15 20:21:14 PST 2016 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-3.2.1-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env sh 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Attempt to set APP_HOME 10 | # Resolve links: $0 may be a link 11 | PRG="$0" 12 | # Need this for relative symlinks. 13 | while [ -h "$PRG" ] ; do 14 | ls=`ls -ld "$PRG"` 15 | link=`expr "$ls" : '.*-> \(.*\)$'` 16 | if expr "$link" : '/.*' > /dev/null; then 17 | PRG="$link" 18 | else 19 | PRG=`dirname "$PRG"`"/$link" 20 | fi 21 | done 22 | SAVED="`pwd`" 23 | cd "`dirname \"$PRG\"`/" >/dev/null 24 | APP_HOME="`pwd -P`" 25 | cd "$SAVED" >/dev/null 26 | 27 | APP_NAME="Gradle" 28 | APP_BASE_NAME=`basename "$0"` 29 | 30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 31 | DEFAULT_JVM_OPTS="" 32 | 33 | # Use the maximum available, or set MAX_FD != -1 to use that value. 34 | MAX_FD="maximum" 35 | 36 | warn ( ) { 37 | echo "$*" 38 | } 39 | 40 | die ( ) { 41 | echo 42 | echo "$*" 43 | echo 44 | exit 1 45 | } 46 | 47 | # OS specific support (must be 'true' or 'false'). 48 | cygwin=false 49 | msys=false 50 | darwin=false 51 | nonstop=false 52 | case "`uname`" in 53 | CYGWIN* ) 54 | cygwin=true 55 | ;; 56 | Darwin* ) 57 | darwin=true 58 | ;; 59 | MINGW* ) 60 | msys=true 61 | ;; 62 | NONSTOP* ) 63 | nonstop=true 64 | ;; 65 | esac 66 | 67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 68 | 69 | # Determine the Java command to use to start the JVM. 70 | if [ -n "$JAVA_HOME" ] ; then 71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 72 | # IBM's JDK on AIX uses strange locations for the executables 73 | JAVACMD="$JAVA_HOME/jre/sh/java" 74 | else 75 | JAVACMD="$JAVA_HOME/bin/java" 76 | fi 77 | if [ ! -x "$JAVACMD" ] ; then 78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 79 | 80 | Please set the JAVA_HOME variable in your environment to match the 81 | location of your Java installation." 82 | fi 83 | else 84 | JAVACMD="java" 85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 86 | 87 | Please set the JAVA_HOME variable in your environment to match the 88 | location of your Java installation." 89 | fi 90 | 91 | # Increase the maximum file descriptors if we can. 92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then 93 | MAX_FD_LIMIT=`ulimit -H -n` 94 | if [ $? -eq 0 ] ; then 95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 96 | MAX_FD="$MAX_FD_LIMIT" 97 | fi 98 | ulimit -n $MAX_FD 99 | if [ $? -ne 0 ] ; then 100 | warn "Could not set maximum file descriptor limit: $MAX_FD" 101 | fi 102 | else 103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 104 | fi 105 | fi 106 | 107 | # For Darwin, add options to specify how the application appears in the dock 108 | if $darwin; then 109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 110 | fi 111 | 112 | # For Cygwin, switch paths to Windows format before running java 113 | if $cygwin ; then 114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 116 | JAVACMD=`cygpath --unix "$JAVACMD"` 117 | 118 | # We build the pattern for arguments to be converted via cygpath 119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 120 | SEP="" 121 | for dir in $ROOTDIRSRAW ; do 122 | ROOTDIRS="$ROOTDIRS$SEP$dir" 123 | SEP="|" 124 | done 125 | OURCYGPATTERN="(^($ROOTDIRS))" 126 | # Add a user-defined pattern to the cygpath arguments 127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 129 | fi 130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 131 | i=0 132 | for arg in "$@" ; do 133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 135 | 136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 138 | else 139 | eval `echo args$i`="\"$arg\"" 140 | fi 141 | i=$((i+1)) 142 | done 143 | case $i in 144 | (0) set -- ;; 145 | (1) set -- "$args0" ;; 146 | (2) set -- "$args0" "$args1" ;; 147 | (3) set -- "$args0" "$args1" "$args2" ;; 148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 154 | esac 155 | fi 156 | 157 | # Escape application args 158 | save ( ) { 159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done 160 | echo " " 161 | } 162 | APP_ARGS=$(save "$@") 163 | 164 | # Collect all arguments for the java command, following the shell quoting and substitution rules 165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" 166 | 167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong 168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then 169 | cd "$(dirname "$0")" 170 | fi 171 | 172 | exec "$JAVACMD" "$@" 173 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | set DIRNAME=%~dp0 12 | if "%DIRNAME%" == "" set DIRNAME=. 13 | set APP_BASE_NAME=%~n0 14 | set APP_HOME=%DIRNAME% 15 | 16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 17 | set DEFAULT_JVM_OPTS= 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windows variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | 53 | :win9xME_args 54 | @rem Slurp the command line arguments. 55 | set CMD_LINE_ARGS= 56 | set _SKIP=2 57 | 58 | :win9xME_args_slurp 59 | if "x%~1" == "x" goto execute 60 | 61 | set CMD_LINE_ARGS=%* 62 | 63 | :execute 64 | @rem Setup the command line 65 | 66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 67 | 68 | @rem Execute Gradle 69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 70 | 71 | :end 72 | @rem End local scope for the variables with windows NT shell 73 | if "%ERRORLEVEL%"=="0" goto mainEnd 74 | 75 | :fail 76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 77 | rem the _cmd.exe /c_ return code! 78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 79 | exit /b 1 80 | 81 | :mainEnd 82 | if "%OS%"=="Windows_NT" endlocal 83 | 84 | :omega 85 | -------------------------------------------------------------------------------- /install-local-dependency.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -e 2 | # 3 | # Copyright 2016-present The Material Motion Authors. All Rights Reserved. 4 | # 5 | # Licensed under the Apache License, Version 2.0 (the "License"); 6 | # you may not use this file except in compliance with the License. 7 | # You may obtain a copy of the License at 8 | # 9 | # http://www.apache.org/licenses/LICENSE-2.0 10 | # 11 | # Unless required by applicable law or agreed to in writing, software 12 | # distributed under the License is distributed on an "AS IS" BASIS, 13 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | # See the License for the specific language governing permissions and 15 | # limitations under the License. 16 | # 17 | # Usage: `install-local-dependency.sh ` 18 | # 19 | # Publishes the dependency : to the local maven repository 20 | # using `gradle install`. This builds the local changes in that project 21 | # and propagates them to dependent projects. 22 | # 23 | # Used by local-dependency-substitution.gradle 24 | 25 | group="$1" 26 | name="$2" 27 | 28 | dir="$(mdm dir $name)" || { 29 | cat << EOF 30 | Failed to get the local repo path for dependency $group:$name. 31 | Make sure you read through our Contributor essentials: https://material-motion.github.io/material-motion/team/essentials/ 32 | 33 | Especially make sure that: 34 | 35 | * You have installed our team's mdm tool https://material-motion.github.io/material-motion/team/essentials/frequent_contributors/tools 36 | \$(mdm dir) should output the correct directory 37 | * You have cloned the repo for $group:$name 38 | \$(mdm dir $name) should output the correct directory 39 | EOF 40 | exit 1 41 | } 42 | 43 | cd "$dir" 44 | ./gradlew install || { 45 | echo "Failed to publish dependency $group:$name to the local maven repository." 46 | exit 1 47 | } 48 | -------------------------------------------------------------------------------- /library/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | apply plugin: 'com.github.dcendents.android-maven' 3 | apply plugin: 'com.vanniktech.android.junit.jacoco' 4 | 5 | group = 'com.github.material-motion' 6 | 7 | install { 8 | repositories.mavenInstaller { 9 | pom.version = 'local' 10 | pom.artifactId = 'physics-android' 11 | } 12 | } 13 | 14 | android { 15 | compileSdkVersion 25 16 | buildToolsVersion '25.0.0' 17 | 18 | defaultConfig { 19 | minSdkVersion 15 20 | targetSdkVersion 25 21 | versionCode 1 22 | versionName "1.0" 23 | consumerProguardFiles 'proguard-rules.pro' 24 | } 25 | 26 | lintOptions { 27 | abortOnError false 28 | } 29 | 30 | buildTypes { 31 | debug { 32 | testCoverageEnabled true 33 | } 34 | } 35 | } 36 | 37 | dependencies { 38 | // If you are developing any dependencies locally, also list them in local.dependencies. 39 | compile 'com.android.support:support-core-utils:25.1.0' 40 | 41 | testCompile 'com.google.truth:truth:0.28' 42 | testCompile 'junit:junit:4.12' 43 | testCompile 'org.mockito:mockito-core:1.10.19' 44 | testCompile 'org.robolectric:robolectric:3.1.2' 45 | } 46 | 47 | // build a jar with source files 48 | task sourcesJar(type: Jar) { 49 | from android.sourceSets.main.java.srcDirs 50 | classifier = 'sources' 51 | } 52 | 53 | task javadoc(type: Javadoc) { 54 | failOnError false 55 | source = android.sourceSets.main.java.sourceFiles 56 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) 57 | classpath += configurations.compile 58 | } 59 | 60 | // build a jar with javadoc 61 | task javadocJar(type: Jar, dependsOn: javadoc) { 62 | classifier = 'javadoc' 63 | from javadoc.destinationDir 64 | } 65 | 66 | artifacts { 67 | archives sourcesJar 68 | archives javadocJar 69 | } 70 | -------------------------------------------------------------------------------- /library/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | -keep @android.support.annotation.Keep class * 13 | 14 | -keepclassmembers class * { 15 | @android.support.annotation.Keep *; 16 | } 17 | -------------------------------------------------------------------------------- /library/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /library/src/main/java/com/google/android/material/motion/physics/ChoreographerCompat.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017-present The Material Motion Authors. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.android.material.motion.physics; 17 | 18 | import android.annotation.TargetApi; 19 | import android.os.Build.VERSION; 20 | import android.os.Build.VERSION_CODES; 21 | import android.os.Handler; 22 | import android.os.Looper; 23 | import android.view.Choreographer; 24 | 25 | /** 26 | * A compatibility shim for {@link android.view.Choreographer} calls, since this class was not 27 | * available until API 16. For older versions of Android, a Handler will be used instead. 28 | */ 29 | public abstract class ChoreographerCompat { 30 | private static final ThreadLocal threadInstance = 31 | new ThreadLocal() { 32 | @Override 33 | protected ChoreographerCompat initialValue() { 34 | if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN) { 35 | return new RealChoreographer(); 36 | } else { 37 | Looper looper = Looper.myLooper(); 38 | if (looper == null) { 39 | throw new IllegalStateException("The current thread must have a looper!"); 40 | } 41 | return new LegacyHandlerWrapper(looper); 42 | } 43 | } 44 | }; 45 | 46 | /** 47 | * Return the instance of {@link ChoreographerCompat} for the current thread. The thread must 48 | * have a looper associated with it. 49 | */ 50 | public static ChoreographerCompat getInstance() { 51 | return threadInstance.get(); 52 | } 53 | 54 | /** 55 | * Post a frame callback to run on the next frame. 56 | *

57 | *

The callback runs once then is automatically removed.

58 | */ 59 | public abstract void postFrameCallback(FrameCallback callback); 60 | 61 | /** 62 | * Post a frame callback to run on the next frame after the specified delay. 63 | *

64 | *

The callback runs once then is automatically removed.

65 | */ 66 | public abstract void postFrameCallbackDelayed(FrameCallback callback, long delayMillis); 67 | 68 | /** 69 | * Remove a previously posted frame callback. 70 | */ 71 | public abstract void removeFrameCallback(FrameCallback callback); 72 | 73 | 74 | /** 75 | * A callback that will occur on a future drawing frame. This is a compatible version of {@link 76 | * android.view.Choreographer.FrameCallback}. 77 | */ 78 | public abstract static class FrameCallback { 79 | private Runnable runnable; 80 | private Choreographer.FrameCallback realCallback; 81 | 82 | public abstract void doFrame(long frameTimeNanos); 83 | 84 | @TargetApi(VERSION_CODES.JELLY_BEAN) 85 | Choreographer.FrameCallback getRealCallback() { 86 | if (realCallback == null) { 87 | realCallback = new Choreographer.FrameCallback() { 88 | @Override 89 | public void doFrame(long frameTimeNanos) { 90 | FrameCallback.this.doFrame(frameTimeNanos); 91 | } 92 | }; 93 | } 94 | 95 | return realCallback; 96 | } 97 | 98 | Runnable getRunnable() { 99 | if (runnable == null) { 100 | runnable = new Runnable() { 101 | @Override 102 | public void run() { 103 | doFrame(System.nanoTime()); 104 | } 105 | }; 106 | } 107 | 108 | return runnable; 109 | } 110 | } 111 | 112 | /** 113 | * A {@link ChoreographerCompat} that just wraps a real {@link Choreographer}, for use on API 114 | * versions that support it. 115 | */ 116 | @TargetApi(VERSION_CODES.JELLY_BEAN) 117 | private static class RealChoreographer extends ChoreographerCompat { 118 | private Choreographer choreographer; 119 | 120 | public RealChoreographer() { 121 | choreographer = Choreographer.getInstance(); 122 | } 123 | 124 | @Override 125 | public void postFrameCallback(FrameCallback callback) { 126 | choreographer.postFrameCallback(callback.getRealCallback()); 127 | } 128 | 129 | @Override 130 | public void postFrameCallbackDelayed(FrameCallback callback, long delayMillis) { 131 | choreographer.postFrameCallbackDelayed(callback.getRealCallback(), delayMillis); 132 | } 133 | 134 | @Override 135 | public void removeFrameCallback(FrameCallback callback) { 136 | choreographer.removeFrameCallback(callback.getRealCallback()); 137 | } 138 | } 139 | 140 | /** 141 | * A {@link ChoreographerCompat} that wraps a {@link Handler} and emulates (at a basic level, 142 | * anyway) the behavior of a {@link Choreographer}. 143 | */ 144 | private static class LegacyHandlerWrapper extends ChoreographerCompat { 145 | private static final long FRAME_TIME_MS = 17; 146 | private Handler handler; 147 | 148 | public LegacyHandlerWrapper(Looper looper) { 149 | handler = new Handler(looper); 150 | } 151 | 152 | @Override 153 | public void postFrameCallback(FrameCallback callback) { 154 | handler.postDelayed(callback.getRunnable(), 0); 155 | } 156 | 157 | @Override 158 | public void postFrameCallbackDelayed(FrameCallback callback, long delayMillis) { 159 | handler.postDelayed(callback.getRunnable(), delayMillis + FRAME_TIME_MS); 160 | } 161 | 162 | @Override 163 | public void removeFrameCallback(FrameCallback callback) { 164 | handler.removeCallbacks(callback.getRunnable()); 165 | } 166 | } 167 | } 168 | -------------------------------------------------------------------------------- /library/src/main/java/com/google/android/material/motion/physics/Force.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017-present The Material Motion Authors. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.android.material.motion.physics; 17 | 18 | import com.google.android.material.motion.physics.math.Vector; 19 | 20 | /** 21 | * A dynamic Force that acts on an object. Usually models a force in real life. 22 | */ 23 | public interface Force { 24 | 25 | /** 26 | * Calculates the acceleration this Force applies on an object. 27 | * 28 | * @param x The object's position. 29 | * @param v The object's velocity. 30 | * @param t The time elapsed since this Force was first active. 31 | */ 32 | Vector acceleration(Vector x, Vector v, double t); 33 | 34 | /** 35 | * Calculates the potential energy of this Force on an object. The potential energy of a force 36 | * which is a function of an object's position is the integral of the force function with 37 | * respect to position. 38 | *

39 | * Return {@link Integrator#SOME_ENERGY} if the potential energy of this force is difficult or 40 | * unrealistic to calculate, but is a non-trivial amount. 41 | *

42 | * Return {@link Integrator#NO_ENERGY} if this force does not have potential energy or only a 43 | * trivial amount. For example, if the force is not a function of the object's position. 44 | * 45 | * @param x The object's position. 46 | * @param t The time elapsed since this Force was first active. 47 | */ 48 | float potentialEnergy(Vector x, double t); 49 | } 50 | -------------------------------------------------------------------------------- /library/src/main/java/com/google/android/material/motion/physics/Integrator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017-present The Material Motion Authors. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.android.material.motion.physics; 17 | 18 | import android.content.Context; 19 | import android.os.Build.VERSION; 20 | import android.os.Build.VERSION_CODES; 21 | import android.provider.Settings.Global; 22 | import android.support.annotation.Nullable; 23 | import android.support.annotation.VisibleForTesting; 24 | import android.support.v4.util.SimpleArrayMap; 25 | 26 | import com.google.android.material.motion.physics.ChoreographerCompat.FrameCallback; 27 | import com.google.android.material.motion.physics.math.Vector; 28 | 29 | import java.util.Locale; 30 | import java.util.concurrent.CopyOnWriteArrayList; 31 | 32 | import static com.google.android.material.motion.physics.math.Vectors.dot; 33 | 34 | /** 35 | * An integrator that runs an ongoing physics simulation of an object with multiple forced being 36 | * applied to it. 37 | */ 38 | public abstract class Integrator { 39 | 40 | /** 41 | * A Listener that receives notifications from a physics simulation, including on every 42 | * animation frame. 43 | */ 44 | public interface Listener { 45 | 46 | /** 47 | * Notifies the start of the physics simulation. 48 | */ 49 | void onStart(); 50 | 51 | /** 52 | * Notifies the occurrence of another frame of the physics simulation. This is called after 53 | * the current frame's values have been calculated. 54 | * 55 | * @param x The position of the object. 56 | * @param v The velocity of the object. 57 | */ 58 | void onUpdate(Vector x, Vector v); 59 | 60 | /** 61 | * Notifies the physics simulation coming to a settled state. This is called after the total 62 | * energy of the system is below the energy threshold. 63 | */ 64 | void onSettle(); 65 | 66 | /** 67 | * Notifies the end of the physics simulation. This is called upon reaching a settled state, 68 | * or if {@link #stop()} is called externally. 69 | */ 70 | void onStop(); 71 | } 72 | 73 | /** 74 | * This class provides empty implementations of the methods from {@link Listener}. Any custom 75 | * listener that cares only about a subset of the methods of this listener can simply subclass 76 | * this adapter class instead of implementing the interface directly. 77 | */ 78 | public abstract static class SimpleListener implements Listener { 79 | 80 | @Override 81 | public void onStart() { 82 | } 83 | 84 | @Override 85 | public void onUpdate(Vector x, Vector v) { 86 | } 87 | 88 | @Override 89 | public void onSettle() { 90 | } 91 | 92 | @Override 93 | public void onStop() { 94 | } 95 | } 96 | 97 | public static final float MASS = 1f; 98 | /** 99 | * The minimum amount of energy required to continue the physics simulation. 100 | *

101 | * This value can be returned from {@link Force#potentialEnergy(Vector, double)} to signify that 102 | * the force acting on the given object constitutes some non-trivial amount of potential 103 | * energy. 104 | */ 105 | public static final float SOME_ENERGY = 1f; 106 | /** 107 | * This value can be returned from {@link Force#potentialEnergy(Vector, double)} to signify that 108 | * the force acting on the given object constitutes zero or a trivial amount of potential 109 | * energy. 110 | */ 111 | public static final float NO_ENERGY = 0f; 112 | 113 | private static final float FRAME = 1f / 60f; 114 | private static final float MAX_FRAMES_TO_SIMULATE = 4; 115 | private static final float MAX_DELTA = MAX_FRAMES_TO_SIMULATE * FRAME; 116 | 117 | private final ChoreographerCompat choreographer = ChoreographerCompat.getInstance(); 118 | private final CopyOnWriteArrayList listeners = new CopyOnWriteArrayList<>(); 119 | /** 120 | * A mapping from a Force to the initial time at which that force was first active in this 121 | * system. 122 | */ 123 | private final SimpleArrayMap forces = new SimpleArrayMap<>(); 124 | 125 | private final State current = new State(); 126 | private final State previous = new State(); 127 | private final State interpolated = new State(); 128 | private final float animatorDurationScale; 129 | 130 | private boolean isActive; 131 | private boolean isScheduled; 132 | private double lastTime = -1; 133 | 134 | public Integrator() { 135 | this(null); 136 | } 137 | 138 | public Integrator(@Nullable Context context) { 139 | if (VERSION.SDK_INT >= VERSION_CODES.JELLY_BEAN_MR1 && context != null) { 140 | animatorDurationScale = 141 | Global.getFloat(context.getContentResolver(), Global.ANIMATOR_DURATION_SCALE, 1.0f); 142 | } else { 143 | animatorDurationScale = 1f; 144 | } 145 | } 146 | 147 | public final void start() { 148 | boolean wasActive = isActive; 149 | 150 | isActive = true; 151 | schedule(); 152 | 153 | if (!wasActive) { 154 | lastTime = -1; 155 | for (int i = 0, count = forces.size(); i < count; i++) { 156 | forces.setValueAt(i, lastTime); 157 | } 158 | 159 | for (Listener listener : listeners) { 160 | listener.onStart(); 161 | } 162 | } 163 | } 164 | 165 | public final void stop() { 166 | boolean wasActive = isActive; 167 | 168 | isActive = false; 169 | unschedule(); 170 | 171 | if (wasActive) { 172 | for (Listener listener : listeners) { 173 | listener.onStop(); 174 | } 175 | } 176 | } 177 | 178 | public final Integrator setState(Vector x, Vector v) { 179 | current.x.set(x); 180 | current.v.set(v); 181 | 182 | previous.x.set(x); 183 | previous.v.set(v); 184 | 185 | interpolated.x.set(x); 186 | interpolated.v.set(v); 187 | return this; 188 | } 189 | 190 | public final State getState() { 191 | return new State().set(interpolated); 192 | } 193 | 194 | public final Integrator addListener(Listener listener) { 195 | if (!listeners.contains(listener)) { 196 | listeners.add(listener); 197 | } 198 | return this; 199 | } 200 | 201 | public final Integrator removeListener(Listener listener) { 202 | listeners.remove(listener); 203 | return this; 204 | } 205 | 206 | public final Integrator addForce(Force force) { 207 | if (!hasForce(force)) { 208 | forces.put(force, lastTime); 209 | } 210 | return this; 211 | } 212 | 213 | public final Integrator removeForce(Force force) { 214 | forces.remove(force); 215 | return this; 216 | } 217 | 218 | public final boolean hasForce(Force force) { 219 | return forces.containsKey(force); 220 | } 221 | 222 | public final boolean hasForces() { 223 | return !forces.isEmpty(); 224 | } 225 | 226 | public final Integrator clearForces() { 227 | forces.clear(); 228 | return this; 229 | } 230 | 231 | private void schedule() { 232 | boolean wasScheduled = isScheduled; 233 | 234 | isScheduled = true; 235 | 236 | if (!wasScheduled) { 237 | choreographer.postFrameCallback(frameCallback); 238 | } 239 | } 240 | 241 | private void unschedule() { 242 | boolean wasScheduled = isScheduled; 243 | 244 | isScheduled = false; 245 | 246 | if (wasScheduled) { 247 | choreographer.removeFrameCallback(frameCallback); 248 | } 249 | } 250 | 251 | private void doFrame(double frameTime) { 252 | boolean hasEnergy = 253 | hasKineticEnergyGreaterThan(current, SOME_ENERGY) 254 | || hasPotentialEnergyGreaterThan(current, SOME_ENERGY); 255 | if (!hasEnergy) { 256 | for (Listener listener : listeners) { 257 | listener.onSettle(); 258 | } 259 | 260 | // Ensure listener did not #start. 261 | if (!isScheduled) { 262 | stop(); 263 | } 264 | return; 265 | } 266 | 267 | schedule(); 268 | 269 | if (lastTime == -1) { 270 | lastTime = frameTime; 271 | } 272 | 273 | double deltaTime = frameTime - lastTime; 274 | lastTime = frameTime; 275 | 276 | if (deltaTime > MAX_DELTA) { 277 | deltaTime = MAX_DELTA; 278 | } 279 | 280 | for (int i = 0, count = forces.size(); i < count; i++) { 281 | if (forces.valueAt(i) == -1) { 282 | forces.setValueAt(i, lastTime); 283 | } 284 | } 285 | 286 | State state = onFrame(deltaTime); 287 | 288 | for (Listener listener : listeners) { 289 | listener.onUpdate(state.x, state.v); 290 | } 291 | } 292 | 293 | @VisibleForTesting 294 | final State onFrame(double deltaTime) { 295 | State state = onFrame(deltaTime, current, previous, animatorDurationScale); 296 | interpolated.set(state); 297 | return interpolated; 298 | } 299 | 300 | /** 301 | * Advance the physics simulation by one frame. The implementation should update 302 | * current and previous, then return an interpolated State. 303 | */ 304 | protected abstract State onFrame( 305 | double deltaTime, State current, State previous, float animatorDurationScale); 306 | 307 | protected final Vector acceleration(State state, Vector out) { 308 | out.clear(); 309 | for (int i = 0, count = forces.size(); i < count; i++) { 310 | Force force = forces.keyAt(i); 311 | double initialTime = forces.valueAt(i); 312 | out.add(force.acceleration(state.x, state.v, state.t - initialTime)); 313 | } 314 | return out; 315 | } 316 | 317 | @VisibleForTesting 318 | final boolean hasKineticEnergyGreaterThan(State state, float energy) { 319 | return 0.5f * MASS * dot(state.v, state.v) > energy; 320 | } 321 | 322 | @VisibleForTesting 323 | final boolean hasPotentialEnergyGreaterThan(State state, float energy) { 324 | for (int i = 0, count = forces.size(); i < count; i++) { 325 | Force force = forces.keyAt(i); 326 | double initialTime = forces.valueAt(i); 327 | float potentialEnergy = force.potentialEnergy(state.x, state.t - initialTime); 328 | if (potentialEnergy > energy) { 329 | return true; 330 | } 331 | } 332 | return false; 333 | } 334 | 335 | private final FrameCallback frameCallback = 336 | new FrameCallback() { 337 | private static final double NANOS_PER_SECOND = 1000000000.0; 338 | 339 | @Override 340 | public void doFrame(long frameTimeNanos) { 341 | isScheduled = false; 342 | Integrator.this.doFrame(frameTimeNanos / NANOS_PER_SECOND); 343 | } 344 | }; 345 | 346 | /** 347 | * A data holder for a position and velocity at time t. 348 | */ 349 | public static class State { 350 | public final Vector x = new Vector(); 351 | public final Vector v = new Vector(); 352 | public double t; 353 | 354 | public State set(State other) { 355 | this.x.set(other.x); 356 | this.v.set(other.v); 357 | this.t = other.t; 358 | return this; 359 | } 360 | 361 | @Override 362 | public String toString() { 363 | return String.format(Locale.US, "%s\nx=%s\nv=%s", State.class.getSimpleName(), x, v); 364 | } 365 | } 366 | 367 | /** 368 | * A data holder for rate of change. This is used to calculate intermediary {@link State 369 | * States}. 370 | */ 371 | public static class Derivative { 372 | public final Vector dx = new Vector(); 373 | public final Vector dv = new Vector(); 374 | 375 | @Override 376 | public String toString() { 377 | return String.format(Locale.US, "%s\ndx=%s\ndv=%s", State.class.getSimpleName(), dx, dv); 378 | } 379 | } 380 | } 381 | -------------------------------------------------------------------------------- /library/src/main/java/com/google/android/material/motion/physics/forces/AnchoredForce.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017-present The Material Motion Authors. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.android.material.motion.physics.forces; 17 | 18 | import com.google.android.material.motion.physics.Force; 19 | import com.google.android.material.motion.physics.math.Vector; 20 | 21 | /** 22 | * A force with an intrinsic anchor point. The direction and magnitude that this force acts upon an 23 | * object is usually a function of the displacement between that object and the anchor point. 24 | * 25 | * @param Subclass type. This is used to enable method chaining. 26 | */ 27 | public abstract class AnchoredForce> implements Force { 28 | 29 | private final Vector anchorPoint = new Vector(); 30 | private final T self; 31 | 32 | @SuppressWarnings("unchecked") 33 | protected AnchoredForce() { 34 | self = (T) this; 35 | } 36 | 37 | public Vector getAnchorPoint() { 38 | return new Vector(anchorPoint); 39 | } 40 | 41 | /** 42 | * Sets the anchor point of the force. All displacements are calculated relative to this point. 43 | */ 44 | public T setAnchorPoint(Vector anchorPoint) { 45 | this.anchorPoint.set(anchorPoint); 46 | return self; 47 | } 48 | 49 | protected final Vector displacement(Vector x, Vector out) { 50 | out.sub(x, anchorPoint); 51 | return out; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /library/src/main/java/com/google/android/material/motion/physics/forces/Spring.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017-present The Material Motion Authors. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.android.material.motion.physics.forces; 17 | 18 | import com.google.android.material.motion.physics.Integrator; 19 | import com.google.android.material.motion.physics.math.Vector; 20 | 21 | import static com.google.android.material.motion.physics.math.Vectors.dot; 22 | 23 | /** 24 | * A force that models a damped spring with a spring constant k and damping coefficient 25 | * b. All springs assume zero resting distance from the anchor point. 26 | */ 27 | public class Spring extends AnchoredForce { 28 | 29 | public float k = 342f; 30 | public float b = 30f; 31 | 32 | private final Vector tmp1 = new Vector(); 33 | private final Vector tmp2 = new Vector(); 34 | 35 | /** 36 | * Creates a spring with the given spring constant and damping coefficient. 37 | */ 38 | public static Spring create(float k, float b) { 39 | Spring spring = new Spring(); 40 | spring.k = k; 41 | spring.b = b; 42 | 43 | return spring; 44 | } 45 | 46 | /** 47 | * Creates a critically damped spring with the given spring constant. 48 | *

49 | * The damping coefficient is chosen so that for all initial states:

  • The spring has at 50 | * most one overshoot.
  • The spring comes to rest in the minimum possible duration.
  • 51 | *
52 | */ 53 | public static Spring createCriticallyDamped(float k) { 54 | Spring spring = new Spring(); 55 | spring.k = k; 56 | spring.b = (float) Math.sqrt(4 * Integrator.MASS * k); 57 | 58 | return spring; 59 | } 60 | 61 | /** 62 | * Creates a viscous frictional force that opposes the object's velocity. 63 | */ 64 | public static Spring createFriction(float mu) { 65 | Spring spring = new Spring(); 66 | spring.k = 0f; 67 | spring.b = mu; 68 | 69 | return spring; 70 | } 71 | 72 | @Override 73 | public Vector acceleration(Vector x, Vector v, double t) { 74 | Vector displacement = displacement(x, tmp2); 75 | 76 | // Vector tension = -k * displacement; 77 | Vector tension = tmp1; 78 | tension.scale(displacement, -k); 79 | 80 | // Vector damping = -b * v; 81 | Vector damping = tmp2; 82 | damping.scale(v, -b); 83 | 84 | // Vector force = tension + damping; 85 | Vector force = tension.add(damping); 86 | return force.scale(1f / Integrator.MASS); 87 | } 88 | 89 | @Override 90 | public float potentialEnergy(Vector x, double t) { 91 | Vector displacement = displacement(x, tmp2); 92 | return 0.5f * k * dot(displacement, displacement); 93 | } 94 | 95 | public static float tensionFromOrigamiValue(float value) { 96 | return value == 0f ? 0f : (value - 30f) * 3.62f + 194f; 97 | } 98 | 99 | public static float frictionFromOrigamiValue(float value) { 100 | return value == 0f ? 0f : (value - 8f) * 3f + 25f; 101 | } 102 | } 103 | -------------------------------------------------------------------------------- /library/src/main/java/com/google/android/material/motion/physics/integrators/Rk4Integrator.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017-present The Material Motion Authors. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.android.material.motion.physics.integrators; 17 | 18 | import android.content.Context; 19 | 20 | import com.google.android.material.motion.physics.Integrator; 21 | import com.google.android.material.motion.physics.math.Vector; 22 | 23 | /** 24 | * An integrator based on the Runge-Kutta method. 25 | */ 26 | public class Rk4Integrator extends Integrator { 27 | private static final float FRAME = 1f / 60f; 28 | /** 29 | * Experimentally determined. Lowest value with acceptable accuracy. 30 | */ 31 | private static final float ITERATIONS_PER_FRAME = 2; 32 | private static final float DT = (1 / ITERATIONS_PER_FRAME) * FRAME; 33 | 34 | private final State tmpState = new State(); 35 | private final Derivative tmpDerivative1 = new Derivative(); 36 | private final Derivative tmpDerivative2 = new Derivative(); 37 | private final Derivative tmpDerivative3 = new Derivative(); 38 | private final Derivative tmpDerivative4 = new Derivative(); 39 | private final Vector tmpVector1 = new Vector(); 40 | private final Vector tmpVector2 = new Vector(); 41 | 42 | private double accumulator; 43 | 44 | public Rk4Integrator() { 45 | super(); 46 | } 47 | 48 | public Rk4Integrator(Context context) { 49 | super(context); 50 | } 51 | 52 | @Override 53 | protected State onFrame( 54 | double deltaTime, State current, State previous, float animatorDurationScale) { 55 | deltaTime = deltaTime / animatorDurationScale; 56 | float dt = DT / animatorDurationScale; 57 | 58 | accumulator += deltaTime; 59 | 60 | while (accumulator >= dt) { 61 | accumulator -= dt; 62 | previous.set(current); 63 | integrate(current, dt); 64 | } 65 | 66 | return interpolate(previous, current, (float) (accumulator / dt), tmpState); 67 | } 68 | 69 | private void integrate(State state, float dt) { 70 | Derivative a = evaluate(state, tmpDerivative1); 71 | Derivative b = evaluate(state, dt * 0.5f, a, tmpDerivative2); 72 | Derivative c = evaluate(state, dt * 0.5f, b, tmpDerivative3); 73 | Derivative d = evaluate(state, dt, c, tmpDerivative4); 74 | 75 | // Vector dxdt = 1.0f / 6.0f * (a.dx + 2.0f * (b.dx + c.dx) + d.dx); 76 | Vector dxdt = tmpVector1; 77 | dxdt.add(b.dx, c.dx); 78 | dxdt.scale(2.0f); 79 | dxdt.add(a.dx); 80 | dxdt.add(d.dx); 81 | dxdt.scale(1.0f / 6.0f); 82 | 83 | // Vector dvdt = 1.0f / 6.0f * (a.dv + 2.0f * (b.dv + c.dv) + d.dv); 84 | Vector dvdt = tmpVector2; 85 | dvdt.add(b.dv, c.dv); 86 | dvdt.scale(2.0f); 87 | dvdt.add(a.dv); 88 | dvdt.add(d.dv); 89 | dvdt.scale(1.0f / 6.0f); 90 | 91 | // state.x = state.x + dxdt * dt; 92 | dxdt.scale(dt); 93 | state.x.add(dxdt); 94 | 95 | // state.v = state.v + dvdt * dt; 96 | dvdt.scale(dt); 97 | state.v.add(dvdt); 98 | 99 | // state.t = state.t + dt; 100 | state.t += dt; 101 | } 102 | 103 | private Derivative evaluate(State initial, Derivative out) { 104 | out.dx.set(initial.v); 105 | out.dv.set(acceleration(initial, tmpVector1)); 106 | return out; 107 | } 108 | 109 | private Derivative evaluate(State initial, float dt, Derivative d, Derivative out) { 110 | State state = tmpState; 111 | 112 | // state.x = initial.x + d.dx * dt; 113 | Vector x = state.x; 114 | x.scale(d.dx, dt); 115 | x.add(initial.x); 116 | 117 | // state.v = initial.v + d.dv * dt; 118 | Vector v = state.v; 119 | v.scale(d.dv, dt); 120 | v.add(initial.v); 121 | 122 | state.t = initial.t + dt; 123 | 124 | out.dx.set(state.v); 125 | out.dv.set(acceleration(state, tmpVector1)); 126 | return out; 127 | } 128 | 129 | private State interpolate(State previous, State current, float alpha, State out) { 130 | // out.x = current.x * alpha + previous.x * (1 - alpha); 131 | Vector x = out.x; 132 | x.scale(current.x, alpha); 133 | tmpVector1.scale(previous.x, 1 - alpha); 134 | x.add(tmpVector1); 135 | 136 | // out.v = current.v * alpha + previous.v * (1 - alpha); 137 | Vector v = out.v; 138 | v.scale(current.v, alpha); 139 | tmpVector1.scale(previous.v, 1 - alpha); 140 | v.add(tmpVector1); 141 | 142 | out.t = current.t * alpha + previous.t * (1 - alpha); 143 | 144 | return out; 145 | } 146 | } 147 | -------------------------------------------------------------------------------- /library/src/main/java/com/google/android/material/motion/physics/math/MathUtils.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017-present The Material Motion Authors. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.android.material.motion.physics.math; 17 | 18 | /** 19 | * A class that contains utility methods related to numbers. 20 | */ 21 | public final class MathUtils { 22 | 23 | /** 24 | * Default epsilon value for fuzzy float comparisons. 25 | */ 26 | public static final float DEFAULT_EPSILON = 0.0001f; 27 | 28 | private static final float DEG_TO_RAD = 3.1415926f / 180.0f; 29 | private static final float RAD_TO_DEG = 180.0f / 3.1415926f; 30 | 31 | private MathUtils() { 32 | } 33 | 34 | public static float abs(float v) { 35 | return v > 0 ? v : -v; 36 | } 37 | 38 | public static int constrain(int amount, int low, int high) { 39 | return amount < low ? low : (amount > high ? high : amount); 40 | } 41 | 42 | public static long constrain(long amount, long low, long high) { 43 | return amount < low ? low : (amount > high ? high : amount); 44 | } 45 | 46 | public static float constrain(float amount, float low, float high) { 47 | return amount < low ? low : (amount > high ? high : amount); 48 | } 49 | 50 | public static int nearest(int amount, int low, int high) { 51 | return abs(amount - low) < abs(amount - high) ? low : high; 52 | } 53 | 54 | public static float nearest(float amount, float low, float high) { 55 | return abs(amount - low) < abs(amount - high) ? low : high; 56 | } 57 | 58 | public static float log(float a) { 59 | return (float) Math.log(a); 60 | } 61 | 62 | public static float exp(float a) { 63 | return (float) Math.exp(a); 64 | } 65 | 66 | public static float pow(float a, float b) { 67 | return (float) Math.pow(a, b); 68 | } 69 | 70 | public static float max(float a, float b) { 71 | return a > b ? a : b; 72 | } 73 | 74 | public static float max(int a, int b) { 75 | return a > b ? a : b; 76 | } 77 | 78 | public static float max(float a, float b, float c) { 79 | return a > b ? (a > c ? a : c) : (b > c ? b : c); 80 | } 81 | 82 | public static float max(int a, int b, int c) { 83 | return a > b ? (a > c ? a : c) : (b > c ? b : c); 84 | } 85 | 86 | public static float max(float a, float b, float c, float d) { 87 | return a > b && a > c && a > d ? a : b > c && b > d ? b : c > d ? c : d; 88 | } 89 | 90 | public static float max(int a, int b, int c, int d) { 91 | return a > b && a > c && a > d ? a : b > c && b > d ? b : c > d ? c : d; 92 | } 93 | 94 | public static float min(float a, float b) { 95 | return a < b ? a : b; 96 | } 97 | 98 | public static float min(int a, int b) { 99 | return a < b ? a : b; 100 | } 101 | 102 | public static float min(float a, float b, float c) { 103 | return a < b ? (a < c ? a : c) : (b < c ? b : c); 104 | } 105 | 106 | public static float min(int a, int b, int c) { 107 | return a < b ? (a < c ? a : c) : (b < c ? b : c); 108 | } 109 | 110 | public static float dist(float x1, float y1, float x2, float y2) { 111 | final float x = (x2 - x1); 112 | final float y = (y2 - y1); 113 | return (float) Math.hypot(x, y); 114 | } 115 | 116 | public static float dist(float x1, float y1, float z1, float x2, float y2, float z2) { 117 | final float x = (x2 - x1); 118 | final float y = (y2 - y1); 119 | final float z = (z2 - z1); 120 | return (float) Math.sqrt(x * x + y * y + z * z); 121 | } 122 | 123 | public static float mag(float a, float b) { 124 | return (float) Math.hypot(a, b); 125 | } 126 | 127 | public static float mag(float a, float b, float c) { 128 | return (float) Math.sqrt(a * a + b * b + c * c); 129 | } 130 | 131 | public static float sq(float v) { 132 | return v * v; 133 | } 134 | 135 | public static float sqrt(float value) { 136 | return (float) Math.sqrt(value); 137 | } 138 | 139 | public static float dot(float v1x, float v1y, float v2x, float v2y) { 140 | return v1x * v2x + v1y * v2y; 141 | } 142 | 143 | public static float cross(float v1x, float v1y, float v2x, float v2y) { 144 | return v1x * v2y - v1y * v2x; 145 | } 146 | 147 | public static float radians(float degrees) { 148 | return degrees * DEG_TO_RAD; 149 | } 150 | 151 | public static float degrees(float radians) { 152 | return radians * RAD_TO_DEG; 153 | } 154 | 155 | public static float acos(float value) { 156 | return (float) Math.acos(value); 157 | } 158 | 159 | public static float asin(float value) { 160 | return (float) Math.asin(value); 161 | } 162 | 163 | public static float atan(float value) { 164 | return (float) Math.atan(value); 165 | } 166 | 167 | public static float atan2(float a, float b) { 168 | return (float) Math.atan2(a, b); 169 | } 170 | 171 | public static float tan(float angle) { 172 | return (float) Math.tan(angle); 173 | } 174 | 175 | public static float lerp(float start, float stop, float amount) { 176 | return (1 - amount) * start + amount * stop; 177 | } 178 | 179 | public static float norm(float start, float stop, float value) { 180 | return (value - start) / (stop - start); 181 | } 182 | 183 | public static float map( 184 | float minStart, float minStop, float maxStart, float maxStop, float value) { 185 | return maxStart + (maxStart - maxStop) * ((value - minStart) / (minStop - minStart)); 186 | } 187 | 188 | /** 189 | * Fuzzy less than or equal to for floats. 190 | *

191 | * Returns true if {@code a} is less than or equal to {@code b}, allowing for {@code epsilon} 192 | * error due to limitations in floating point accuracy. 193 | *

194 | * Does not handle overflow, underflow, infinity, or NaN. 195 | */ 196 | public static boolean leq(float a, float b, float epsilon) { 197 | return a <= b + epsilon; 198 | } 199 | 200 | /** 201 | * Fuzzy greater than or equal to for floats. 202 | *

203 | * Returns true if {@code a} is greater than or equal to {@code b}, allowing for {@code epsilon} 204 | * error due to limitations in floating point accuracy. 205 | *

206 | * Does not handle overflow, underflow, infinity, or NaN. 207 | */ 208 | public static boolean geq(float a, float b, float epsilon) { 209 | return a + epsilon >= b; 210 | } 211 | 212 | /** 213 | * Fuzzy equal to for floats. 214 | *

215 | * Returns true if {@code a} is equal to {@code b}, allowing for {@code epsilon} error due to 216 | * limitations in floating point accuracy. 217 | *

218 | * Does not handle overflow, underflow, infinity, or NaN. 219 | */ 220 | public static boolean eq(float a, float b, float epsilon) { 221 | return abs(a - b) <= epsilon; 222 | } 223 | 224 | /** 225 | * Fuzzy not equal to for floats. 226 | *

227 | * Returns false if {@code a} is equal to {@code b}, allowing for {@code epsilon} error due to 228 | * limitations in floating point accuracy. 229 | *

230 | * Does not handle overflow, underflow, infinity, or NaN. 231 | */ 232 | public static boolean neq(float a, float b, float epsilon) { 233 | return abs(a - b) > epsilon; 234 | } 235 | 236 | /** 237 | * Returns the furthest distance from the point defined by pointX and pointY to the four corners 238 | * of the rectangle defined by rectLeft, rectTop, rectRight, and rectBottom. 239 | *

240 | * The caller should ensure that the point and rectangle share the same coordinate space. 241 | */ 242 | public static float distanceToFurthestCorner( 243 | float pointX, 244 | float pointY, 245 | float rectLeft, 246 | float rectTop, 247 | float rectRight, 248 | float rectBottom) { 249 | return max( 250 | dist(pointX, pointY, rectLeft, rectTop), 251 | dist(pointX, pointY, rectRight, rectTop), 252 | dist(pointX, pointY, rectRight, rectBottom), 253 | dist(pointX, pointY, rectLeft, rectBottom)); 254 | } 255 | } 256 | -------------------------------------------------------------------------------- /library/src/main/java/com/google/android/material/motion/physics/math/Vector.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017-present The Material Motion Authors. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.android.material.motion.physics.math; 17 | 18 | import android.support.annotation.NonNull; 19 | import android.support.annotation.Nullable; 20 | 21 | import java.util.Arrays; 22 | 23 | /** 24 | * A general purpose one dimensional vector class. The size of a vector is effectively 25 | * final. All calculations involving multiple vectors will assume that all vectors involved are the 26 | * same size. All calculations that return a Vector will mutate the vector that the method was 27 | * called on. 28 | *

29 | * The only exception is the zero-sized vector. It represents an arbitrarily sized vector with all 30 | * zero values. 31 | */ 32 | public class Vector { 33 | private int size; 34 | @Nullable 35 | private float[] values; 36 | 37 | public Vector() { 38 | this.size = 0; 39 | this.values = null; 40 | } 41 | 42 | public Vector(Vector vector) { 43 | if (vector.size == 0) { 44 | this.size = 0; 45 | this.values = null; 46 | return; 47 | } 48 | this.size = vector.size; 49 | this.values = new float[size]; 50 | System.arraycopy(checkNotNull(vector.values), 0, values, 0, size); 51 | } 52 | 53 | public Vector(float... values) { 54 | this.size = values.length; 55 | this.values = new float[size]; 56 | System.arraycopy(values, 0, this.values, 0, size); 57 | } 58 | 59 | public int getSize() { 60 | return size; 61 | } 62 | 63 | public float[] getValues() { 64 | return checkNotNull(values); 65 | } 66 | 67 | public float getValue(int index) { 68 | if (size == 0) { 69 | return 0f; 70 | } 71 | return checkNotNull(values)[index]; 72 | } 73 | 74 | /** 75 | * Sets this vector to the given vector's values. 76 | */ 77 | public Vector set(Vector other) { 78 | if (other.size == 0) { 79 | size = 0; 80 | values = null; 81 | return this; 82 | } 83 | if (size == 0) { 84 | size = other.size; 85 | values = new float[size]; 86 | } 87 | checkArgument(size == other.size); 88 | System.arraycopy( 89 | checkNotNull(other.values), 0, checkNotNull(values), 0, size); 90 | return this; 91 | } 92 | 93 | /** 94 | * Sets this vector to the given values. 95 | */ 96 | public Vector set(float... values) { 97 | if (size == 0) { 98 | size = values.length; 99 | this.values = new float[size]; 100 | } 101 | checkArgument(size == values.length); 102 | System.arraycopy(values, 0, checkNotNull(this.values), 0, size); 103 | return this; 104 | } 105 | 106 | /** 107 | * Sets this vector to all zero values. 108 | */ 109 | public Vector clear() { 110 | if (size > 0) { 111 | Arrays.fill(checkNotNull(values), 0, size, 0f); 112 | } 113 | return this; 114 | } 115 | 116 | /** 117 | * Returns a + b, the sum of the given vector and this. 118 | */ 119 | public Vector add(Vector b) { 120 | return add(this, b); 121 | } 122 | 123 | /** 124 | * Sets this vector to a + b. 125 | */ 126 | public Vector add(Vector a, Vector b) { 127 | if (a.size == 0) { 128 | set(b); 129 | return this; 130 | } 131 | if (b.size == 0) { 132 | set(a); 133 | return this; 134 | } 135 | 136 | if (size == 0) { 137 | size = a.size; 138 | values = new float[size]; 139 | } 140 | checkArgument(size == a.size); 141 | checkArgument(size == b.size); 142 | float[] aValues = checkNotNull(a.values); 143 | float[] bValues = checkNotNull(b.values); 144 | for (int i = 0; i < a.size; i++) { 145 | values[i] = aValues[i] + bValues[i]; 146 | } 147 | return this; 148 | } 149 | 150 | /** 151 | * Returns a - b, the subtraction of the given vector from this. 152 | */ 153 | public Vector sub(Vector b) { 154 | return sub(this, b); 155 | } 156 | 157 | /** 158 | * Sets this vector to a - b. 159 | */ 160 | public Vector sub(Vector a, Vector b) { 161 | if (a.size == 0) { 162 | scale(b, -1f); 163 | return this; 164 | } 165 | if (b.size == 0) { 166 | set(a); 167 | return this; 168 | } 169 | 170 | if (size == 0) { 171 | size = a.size; 172 | values = new float[size]; 173 | } 174 | checkArgument(size == a.size); 175 | checkArgument(size == b.size); 176 | float[] aValues = checkNotNull(a.values); 177 | float[] bValues = checkNotNull(b.values); 178 | for (int i = 0; i < a.size; i++) { 179 | values[i] = aValues[i] - bValues[i]; 180 | } 181 | return this; 182 | } 183 | 184 | /** 185 | * Returns k * v, the scaling of this vector by the given scalar. 186 | */ 187 | public Vector scale(float k) { 188 | return scale(this, k); 189 | } 190 | 191 | /** 192 | * Sets this vector to k * v. 193 | */ 194 | public Vector scale(Vector v, float k) { 195 | if (k == 1f) { 196 | set(v); 197 | return this; 198 | } 199 | 200 | if (v.size == 0) { 201 | size = 0; 202 | values = null; 203 | return this; 204 | } 205 | 206 | if (size == 0) { 207 | size = v.size; 208 | values = new float[size]; 209 | } 210 | checkArgument(size == v.size); 211 | float[] vValues = checkNotNull(v.values); 212 | for (int i = 0; i < v.size; i++) { 213 | values[i] = vValues[i] * k; 214 | } 215 | return this; 216 | } 217 | 218 | /** 219 | * Returns v / ||v||, the normalization of this vector. 220 | *

221 | *

If this is a zero vector, the normalization results in a zero vector. 222 | */ 223 | public Vector normalize() { 224 | return normalize(this); 225 | } 226 | 227 | /** 228 | * Sets this vector to v/||v||, the normalization of this vector. 229 | *

230 | *

If this is a zero vector, its normalization results in a zero vector. 231 | */ 232 | public Vector normalize(Vector v) { 233 | if (v.size == 0) { 234 | size = 0; 235 | values = null; 236 | return this; 237 | } 238 | 239 | if (size == 0) { 240 | size = v.size; 241 | values = new float[size]; 242 | } 243 | checkArgument(size == v.size); 244 | float magnitude = v.magnitude(); 245 | if (magnitude == 0f) { 246 | clear(); 247 | return this; 248 | } 249 | 250 | float[] vValues = checkNotNull(v.values); 251 | for (int i = 0; i < v.size; i++) { 252 | values[i] = vValues[i] / magnitude; 253 | } 254 | return this; 255 | } 256 | 257 | /** 258 | * Returns whether this vector is normalized within the given epsilon error. 259 | *

260 | *

A zero vector is considered normalized. 261 | */ 262 | public boolean isNormalized(float epsilon) { 263 | float magnitude = magnitude(); 264 | return MathUtils.eq(magnitude, 1f, epsilon) || MathUtils.eq(magnitude, 0f, epsilon); 265 | } 266 | 267 | /** 268 | * Returns whether this vector is a zero vector within the given epsilon error. 269 | */ 270 | public boolean isZero(float epsilon) { 271 | float magnitude = magnitude(); 272 | return MathUtils.eq(magnitude, 0f, epsilon); 273 | } 274 | 275 | /** 276 | * Returns projab, the projection of the given vector onto this. 277 | *

278 | *

279 | * If this is a zero vector, the projection of the given vector onto this results in itself. 280 | */ 281 | public Vector proj(Vector b) { 282 | return proj(this, b); 283 | } 284 | 285 | /** 286 | * Sets this vector to projab, the projection of b onto a. 287 | *

288 | *

289 | * If a is a zero vector, the projection of b onto a results in itself. 290 | */ 291 | public Vector proj(Vector a, Vector b) { 292 | if (a.size == 0) { 293 | set(b); 294 | return this; 295 | } 296 | if (b.size == 0) { 297 | clear(); 298 | return this; 299 | } 300 | 301 | if (size == 0) { 302 | size = a.size; 303 | values = new float[size]; 304 | } 305 | checkArgument(size == a.size); 306 | checkArgument(size == b.size); 307 | float aa = Vectors.dot(a, a); 308 | if (aa == 0f) { 309 | set(b); 310 | return this; 311 | } 312 | 313 | float ab = Vectors.dot(a, b); 314 | float scalar = ab / aa; 315 | scale(a, scalar); 316 | return this; 317 | } 318 | 319 | /** 320 | * Returns v1⋅v2, the dot product of this vector and the given vector. 321 | */ 322 | public float dot(Vector other) { 323 | if (size == 0 || other.size == 0) { 324 | return 0f; 325 | } 326 | 327 | checkArgument(size == other.size); 328 | float[] thisValues = checkNotNull(this.values); 329 | float[] otherValues = checkNotNull(other.values); 330 | float sum = 0f; 331 | for (int i = 0; i < size; i++) { 332 | sum += thisValues[i] * otherValues[i]; 333 | } 334 | return sum; 335 | } 336 | 337 | /** 338 | * Returns θ, the unsigned angle in between this normalized vector and the 339 | * given normalized vector. 340 | *

341 | *

Zero vectors are considered to have 0f angle with any other vector. 342 | */ 343 | public float angle(Vector other) { 344 | checkState(isNormalized(MathUtils.DEFAULT_EPSILON)); 345 | checkState(other.isNormalized(MathUtils.DEFAULT_EPSILON)); 346 | 347 | if (isZero(MathUtils.DEFAULT_EPSILON) || other.isZero(MathUtils.DEFAULT_EPSILON)) { 348 | return 0f; 349 | } 350 | 351 | return MathUtils.acos(dot(other)); 352 | } 353 | 354 | /** 355 | * Returns θ, the unsigned angle in between this vector and the given vector. 356 | * Both vectors will be normalized in place. 357 | *

358 | *

Zero vectors are considered to have 0f angle with any other vector. 359 | */ 360 | public float angleWithNormalization(Vector other) { 361 | normalize(); 362 | other.normalize(); 363 | return angle(other); 364 | } 365 | 366 | /** 367 | * Returns the unsigned distance between this vector and the given vector. 368 | *

369 | *

This is identical to ||v1-v2||, but without the intermediary vector 370 | * allocation or mutation. 371 | */ 372 | public float distance(Vector other) { 373 | if (size == 0) { 374 | return other.magnitude(); 375 | } 376 | if (other.size == 0) { 377 | return magnitude(); 378 | } 379 | 380 | checkArgument(size == other.size); 381 | float[] thisValues = checkNotNull(this.values); 382 | float[] otherValues = checkNotNull(other.values); 383 | float sum = 0f; 384 | for (int i = 0; i < size; i++) { 385 | float diff = thisValues[i] - otherValues[i]; 386 | sum += diff * diff; 387 | } 388 | return MathUtils.sqrt(sum); 389 | } 390 | 391 | /** 392 | * Returns ||v||, the magnitude of this vector. 393 | */ 394 | public float magnitude() { 395 | return MathUtils.sqrt(Vectors.dot(this, this)); 396 | } 397 | 398 | @Override 399 | public String toString() { 400 | return String.format("%s %s", Vector.class.getSimpleName(), Arrays.toString(values)); 401 | } 402 | 403 | @Override 404 | public boolean equals(Object o) { 405 | if (this == o) { 406 | return true; 407 | } 408 | if (o == null || getClass() != o.getClass()) { 409 | return false; 410 | } 411 | 412 | Vector vector = (Vector) o; 413 | 414 | return size == 0 && vector.size == 0 415 | || size == 0 && vector.magnitude() == 0 416 | || vector.size == 0 && magnitude() == 0 417 | || Arrays.equals(values, vector.values); 418 | } 419 | 420 | @Override 421 | public int hashCode() { 422 | if (size == 0 || magnitude() == 0) { 423 | return 0; 424 | } 425 | 426 | return Arrays.hashCode(values); 427 | } 428 | 429 | /** 430 | * Ensures that an object reference passed as a parameter to the calling method is not null. 431 | * 432 | * @param reference an object reference 433 | * @return the non-null reference that was validated 434 | * @throws NullPointerException if {@code reference} is null 435 | */ 436 | @NonNull 437 | private static T checkNotNull(@Nullable T reference) { 438 | if (reference == null) { 439 | throw new NullPointerException(); 440 | } 441 | return reference; 442 | } 443 | 444 | /** 445 | * Ensures the truth of an expression involving one or more parameters to the calling method. 446 | * 447 | * @param expression a boolean expression 448 | * @throws IllegalArgumentException if {@code expression} is false 449 | */ 450 | private static void checkArgument(boolean expression) { 451 | if (!expression) { 452 | throw new IllegalArgumentException(); 453 | } 454 | } 455 | 456 | /** 457 | * Ensures the truth of an expression involving the state of the calling instance, but not 458 | * involving any parameters to the calling method. 459 | * 460 | * @param expression a boolean expression 461 | * @throws IllegalStateException if {@code expression} is false 462 | */ 463 | private static void checkState(boolean expression) { 464 | if (!expression) { 465 | throw new IllegalStateException(); 466 | } 467 | } 468 | } 469 | -------------------------------------------------------------------------------- /library/src/main/java/com/google/android/material/motion/physics/math/Vectors.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017-present The Material Motion Authors. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.android.material.motion.physics.math; 17 | 18 | /** 19 | * A class that contains utility methods related to vectors. 20 | */ 21 | public final class Vectors { 22 | 23 | private Vectors() { 24 | } 25 | 26 | public static float dot(Vector v1, Vector v2) { 27 | return v1.dot(v2); 28 | } 29 | 30 | public static float angle(Vector v1, Vector v2) { 31 | return v1.angle(v2); 32 | } 33 | 34 | public static float distance(Vector v1, Vector v2) { 35 | return v1.distance(v2); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /library/src/test/java/com/google/android/material/motion/physics/UnitTests.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016-present The Material Motion Authors. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.android.material.motion.physics; 17 | 18 | import org.junit.Before; 19 | import org.junit.Test; 20 | import org.junit.runner.RunWith; 21 | import org.robolectric.RobolectricTestRunner; 22 | import org.robolectric.annotation.Config; 23 | 24 | @RunWith(RobolectricTestRunner.class) 25 | @Config(constants = BuildConfig.class, sdk = 21) 26 | public class UnitTests { 27 | 28 | @Before 29 | public void setUp() { 30 | 31 | } 32 | 33 | @Test 34 | public void unitTest() { 35 | 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /local-dependency-substitution.gradle: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016-present The Material Motion Authors. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | /* 18 | * This Gradle script does 4 things that enable local dependencies. 19 | * 20 | * 1. Ensure config file exists. 21 | * 2. Substitute each dependencies declared in the file for local versions. 22 | * 3. Publish each local dependencies on every build. 23 | * 4. Alert the user. 24 | */ 25 | 26 | def config = new File('local.dependencies') 27 | def substitutions = [] as Set 28 | 29 | /* 1. Ensure local.dependencies exists */ 30 | 31 | config.exists() || config << new File('.local.dependencies.template').text 32 | 33 | /* 2. Substitute each dependencies declared in local.dependencies with the ":local" version. */ 34 | 35 | subprojects { 36 | repositories { 37 | mavenLocal() 38 | } 39 | 40 | def trim = { line -> 41 | def comment = line.indexOf('#') 42 | if (comment != -1) { 43 | line = line.substring(0, comment) 44 | } 45 | line.trim() 46 | } 47 | 48 | configurations.all { 49 | List localDependencies = ( 50 | config as String[] 51 | ).collect { 52 | def line = trim it 53 | if (line) { 54 | this.project.dependencies.create("$line:local") 55 | } 56 | }.findAll() 57 | 58 | resolutionStrategy.dependencySubstitution.all { DependencySubstitution dependency -> 59 | if (dependency.requested instanceof ModuleComponentSelector) { 60 | ModuleComponentSelector requested = dependency.requested; 61 | 62 | Dependency local = localDependencies.find { 63 | it.group == requested.group && it.name == requested.module 64 | } 65 | 66 | if (local) { 67 | substitutions << local 68 | dependency.useTarget([ 69 | group : local.group, 70 | name : local.name, 71 | version: local.version, 72 | ]) 73 | logger.info("Substituded local dependency for: $requested.") 74 | } 75 | } 76 | } 77 | } 78 | } 79 | 80 | /* 3. Publish each local dependencies's changes to the local maven repository on every build. */ 81 | 82 | subprojects { 83 | afterEvaluate { 84 | preBuild.dependsOn installLocalDependencies 85 | } 86 | 87 | task installLocalDependencies << { 88 | configurations 89 | .collectMany { it.allDependencies } 90 | .unique() 91 | .each { Dependency dependency -> 92 | if (substitutions.find { it.group == dependency.group && it.name == dependency.name }) { 93 | logger.lifecycle("Installing $dependency.group:$dependency.name") 94 | logger.info( 95 | "Executing \"./install-local-dependency.sh $dependency.group $dependency.name\"") 96 | 97 | def log = new File("${getTemporaryDir()}/${dependency.group}/${dependency.name}.log") 98 | log.parentFile.mkdirs() 99 | def out = new FileOutputStream(log) 100 | logger.info("Streaming output to $log") 101 | 102 | def result = exec { 103 | commandLine './install-local-dependency.sh' 104 | args dependency.group, dependency.name 105 | standardOutput out 106 | errorOutput out 107 | ignoreExitValue true 108 | } 109 | 110 | if (result.exitValue != 0) { 111 | throw new TaskExecutionException(it, 112 | new Exception("Command './install-local-dependency.sh' failed. See $log for output.")) 113 | } 114 | } 115 | } 116 | } 117 | } 118 | 119 | /* 4. Alert the user that local dependencies are being used. */ 120 | 121 | gradle.buildFinished { 122 | if (substitutions) { 123 | logger.lifecycle('Applied {} local dependency substitution(s).', substitutions.size()) 124 | logger.info(substitutions.inject('') { acc, val -> 125 | acc << "\n\t* $val.group:$val.name" 126 | }.substring(1)) 127 | } 128 | } 129 | -------------------------------------------------------------------------------- /sample/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 25 5 | buildToolsVersion '25.0.0' 6 | 7 | defaultConfig { 8 | applicationId "com.google.android.material.motion.physics.sample" 9 | minSdkVersion 15 10 | targetSdkVersion 25 11 | versionCode 1 12 | versionName "1.0" 13 | } 14 | 15 | lintOptions { 16 | abortOnError false 17 | 18 | // Disable gradle dependency check for new versions. 19 | // Many of these have been chosen to work with Google Tools. 20 | disable 'GradleDependency' 21 | } 22 | 23 | buildTypes { 24 | release { 25 | minifyEnabled true 26 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 27 | } 28 | } 29 | } 30 | 31 | dependencies { 32 | // If you are developing any dependencies locally, also list them in local.dependencies. 33 | compile project(':library') 34 | compile 'com.android.support:appcompat-v7:25.1.0' 35 | } 36 | -------------------------------------------------------------------------------- /sample/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | -------------------------------------------------------------------------------- /sample/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 19 | 20 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | -------------------------------------------------------------------------------- /sample/src/main/java/com/google/android/material/motion/physics/sample/DragFrameLayout.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2017-present The Material Motion Authors. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.android.material.motion.physics.sample; 17 | 18 | import android.content.Context; 19 | import android.support.annotation.Nullable; 20 | import android.support.v4.view.MotionEventCompat; 21 | import android.support.v4.widget.ViewDragHelper; 22 | import android.support.v4.widget.ViewDragHelper.Callback; 23 | import android.util.AttributeSet; 24 | import android.view.MotionEvent; 25 | import android.view.View; 26 | import android.widget.FrameLayout; 27 | 28 | /** 29 | * A FrameLayout that uses a ViewDragHelper to allow its children to be interacted with. 30 | *

31 | *

This class helps reduce the amount of boilerplate needed to use a ViewDragHelper. 32 | */ 33 | public class DragFrameLayout extends FrameLayout { 34 | 35 | private final ViewDragHelper helper; 36 | @Nullable 37 | private Callback callback; 38 | 39 | public DragFrameLayout(Context context) { 40 | this(context, null); 41 | } 42 | 43 | public DragFrameLayout(Context context, AttributeSet attrs) { 44 | super(context, attrs); 45 | 46 | helper = 47 | ViewDragHelper.create( 48 | this, 49 | new Callback() { 50 | @Override 51 | public boolean tryCaptureView(View child, int pointerId) { 52 | if (callback != null) { 53 | return callback.tryCaptureView(child, pointerId); 54 | } 55 | return true; 56 | } 57 | 58 | @Override 59 | public void onViewDragStateChanged(int state) { 60 | if (callback != null) { 61 | callback.onViewDragStateChanged(state); 62 | } 63 | } 64 | 65 | @Override 66 | public void onViewPositionChanged( 67 | View changedView, int left, int top, int dx, int dy) { 68 | if (callback != null) { 69 | callback.onViewPositionChanged(changedView, left, top, dx, dy); 70 | } 71 | } 72 | 73 | @Override 74 | public void onViewCaptured(View capturedChild, int activePointerId) { 75 | if (callback != null) { 76 | callback.onViewCaptured(capturedChild, activePointerId); 77 | } 78 | } 79 | 80 | @Override 81 | public void onViewReleased(View releasedChild, float xvel, float yvel) { 82 | if (callback != null) { 83 | callback.onViewReleased(releasedChild, xvel, yvel); 84 | } 85 | } 86 | 87 | @Override 88 | public void onEdgeTouched(int edgeFlags, int pointerId) { 89 | if (callback != null) { 90 | callback.onEdgeTouched(edgeFlags, pointerId); 91 | } 92 | } 93 | 94 | @Override 95 | public boolean onEdgeLock(int edgeFlags) { 96 | if (callback != null) { 97 | return callback.onEdgeLock(edgeFlags); 98 | } 99 | return super.onEdgeLock(edgeFlags); 100 | } 101 | 102 | @Override 103 | public void onEdgeDragStarted(int edgeFlags, int pointerId) { 104 | if (callback != null) { 105 | callback.onEdgeDragStarted(edgeFlags, pointerId); 106 | } 107 | } 108 | 109 | @Override 110 | public int getOrderedChildIndex(int index) { 111 | if (callback != null) { 112 | return callback.getOrderedChildIndex(index); 113 | } 114 | return super.getOrderedChildIndex(index); 115 | } 116 | 117 | @Override 118 | public int getViewHorizontalDragRange(View child) { 119 | if (callback != null) { 120 | return callback.getViewHorizontalDragRange(child); 121 | } 122 | return super.getViewHorizontalDragRange(child); 123 | } 124 | 125 | @Override 126 | public int getViewVerticalDragRange(View child) { 127 | if (callback != null) { 128 | return callback.getViewVerticalDragRange(child); 129 | } 130 | return super.getViewVerticalDragRange(child); 131 | } 132 | 133 | @Override 134 | public int clampViewPositionHorizontal(View child, int left, int dx) { 135 | if (callback != null) { 136 | return callback.clampViewPositionHorizontal(child, left, dx); 137 | } 138 | return super.clampViewPositionHorizontal(child, left, dx); 139 | } 140 | 141 | @Override 142 | public int clampViewPositionVertical(View child, int top, int dy) { 143 | if (callback != null) { 144 | return callback.clampViewPositionVertical(child, top, dy); 145 | } 146 | return super.clampViewPositionVertical(child, top, dy); 147 | } 148 | }); 149 | } 150 | 151 | public void setCallback(@Nullable Callback callback) { 152 | this.callback = callback; 153 | } 154 | 155 | @Override 156 | public boolean onInterceptTouchEvent(MotionEvent ev) { 157 | final int action = MotionEventCompat.getActionMasked(ev); 158 | if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) { 159 | helper.cancel(); 160 | return false; 161 | } 162 | return helper.shouldInterceptTouchEvent(ev); 163 | } 164 | 165 | @Override 166 | public boolean onTouchEvent(MotionEvent ev) { 167 | helper.processTouchEvent(ev); 168 | return true; 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /sample/src/main/java/com/google/android/material/motion/physics/sample/MainActivity.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2016-present The Material Motion Authors. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.android.material.motion.physics.sample; 17 | 18 | import android.os.Bundle; 19 | import android.support.v4.widget.ViewDragHelper.Callback; 20 | import android.support.v7.app.AppCompatActivity; 21 | import android.view.View; 22 | import android.view.View.OnLayoutChangeListener; 23 | 24 | import com.google.android.material.motion.physics.Integrator; 25 | import com.google.android.material.motion.physics.Integrator.SimpleListener; 26 | import com.google.android.material.motion.physics.forces.AnchoredForce; 27 | import com.google.android.material.motion.physics.forces.Spring; 28 | import com.google.android.material.motion.physics.integrators.Rk4Integrator; 29 | import com.google.android.material.motion.physics.math.Vector; 30 | import com.google.android.material.motion.physics.math.Vectors; 31 | 32 | import java.util.ArrayList; 33 | import java.util.List; 34 | 35 | /** 36 | * Activity that displays a basic demo of dynamic motion in Odeon. 37 | */ 38 | public class MainActivity extends AppCompatActivity { 39 | 40 | private final List demos = new ArrayList<>(); 41 | 42 | @Override 43 | protected void onCreate(Bundle savedInstanceState) { 44 | super.onCreate(savedInstanceState); 45 | setContentView(R.layout.main_activity); 46 | 47 | getWindow().getDecorView().addOnLayoutChangeListener(layoutChangeListener); 48 | 49 | final View dynamicEndValueTarget = findViewById(R.id.target); 50 | final DragFrameLayout dynamicEndValueContainer = 51 | (DragFrameLayout) dynamicEndValueTarget.getParent(); 52 | View dynamicEndValue1 = findViewById(R.id.anchor1); 53 | View dynamicEndValue2 = findViewById(R.id.anchor2); 54 | AnchoredForce dynamicEndValueSpring1 = Spring.createCriticallyDamped(75f); 55 | AnchoredForce dynamicEndValueSpring2 = Spring.createCriticallyDamped(75f); 56 | final Integrator dynamicEndValueIntegrator = new Rk4Integrator(this); 57 | final Demo dynamicEndValueDemo = 58 | Demo.of(dynamicEndValueContainer, dynamicEndValueIntegrator, dynamicEndValueTarget) 59 | .with(dynamicEndValue1, dynamicEndValue2) 60 | .with(dynamicEndValueSpring1, dynamicEndValueSpring2); 61 | 62 | dynamicEndValueIntegrator.addListener(new TrackingListener(dynamicEndValueDemo)); 63 | dynamicEndValueContainer.setCallback( 64 | new TrackingCallback(dynamicEndValueDemo) { 65 | @Override 66 | public void onViewReleased(View releasedChild, float xvel, float yvel) { 67 | super.onViewReleased(releasedChild, xvel, yvel); 68 | 69 | if (releasedChild == dynamicEndValueDemo.target) { 70 | activateAnchoredForceForTargetVelocity(xvel, yvel, dynamicEndValueDemo); 71 | } 72 | } 73 | }); 74 | activateNextForce(dynamicEndValueDemo); 75 | demos.add(dynamicEndValueDemo); 76 | } 77 | 78 | private void activateNextForce(Demo demo) { 79 | if (!demo.integrator.hasForces()) { 80 | activateForce(0, demo); 81 | } else if (demo.forces.length > 0) { 82 | int currentIndex = -1; 83 | for (int i = 0; i < demo.forces.length; i++) { 84 | if (demo.integrator.hasForce(demo.forces[i])) { 85 | currentIndex = i; 86 | break; 87 | } 88 | } 89 | activateForce((currentIndex + 1) % demo.forces.length, demo); 90 | } 91 | } 92 | 93 | private void activateForce(int index, Demo demo) { 94 | for (int i = 0; i < demo.forces.length; i++) { 95 | AnchoredForce force = demo.forces[i]; 96 | if (i == index) { 97 | demo.integrator.addForce(force); 98 | } else { 99 | demo.integrator.removeForce(force); 100 | } 101 | } 102 | demo.integrator.start(); 103 | } 104 | 105 | private void activateAnchoredForceForTargetVelocity(float xvel, float yvel, Demo demo) { 106 | Vector targetLocation = new Vector(getCenterX(demo.target), getCenterY(demo.target)); 107 | Vector[] anchorLocations = new Vector[demo.forces.length]; 108 | for (int i = 0; i < demo.forces.length; i++) { 109 | AnchoredForce force = demo.forces[i]; 110 | anchorLocations[i] = force.getAnchorPoint(); 111 | } 112 | 113 | Vector flingDirection = new Vector(xvel, yvel).normalize(); 114 | Vector[] anchorDirections = new Vector[demo.forces.length]; 115 | for (int i = 0; i < demo.forces.length; i++) { 116 | anchorDirections[i] = new Vector().sub(anchorLocations[i], targetLocation).normalize(); 117 | } 118 | 119 | float minAngle = Float.MAX_VALUE; 120 | int minIndex = -1; 121 | for (int i = 0; i < anchorDirections.length; i++) { 122 | float angle = Vectors.angle(flingDirection, anchorDirections[i]); 123 | if (angle < minAngle) { 124 | minAngle = angle; 125 | minIndex = i; 126 | } 127 | } 128 | 129 | activateForce(minIndex, demo); 130 | } 131 | 132 | @Override 133 | public void onResume() { 134 | super.onResume(); 135 | for (Demo demo : demos) { 136 | demo.integrator.start(); 137 | } 138 | } 139 | 140 | @Override 141 | public void onPause() { 142 | super.onPause(); 143 | for (Demo demo : demos) { 144 | demo.integrator.stop(); 145 | } 146 | } 147 | 148 | private void setCenter(View view, float x, float y) { 149 | view.offsetLeftAndRight((int) (x - getCenterX(view))); 150 | view.offsetTopAndBottom((int) (y - getCenterY(view))); 151 | } 152 | 153 | private float getCenterX(View view) { 154 | return view.getLeft() + view.getWidth() / 2f; 155 | } 156 | 157 | private float getCenterY(View view) { 158 | return view.getTop() + view.getHeight() / 2f; 159 | } 160 | 161 | private final OnLayoutChangeListener layoutChangeListener = 162 | new OnLayoutChangeListener() { 163 | @Override 164 | public void onLayoutChange( 165 | View v, 166 | int left, 167 | int top, 168 | int right, 169 | int bottom, 170 | int oldLeft, 171 | int oldTop, 172 | int oldRight, 173 | int oldBottom) { 174 | // Re-initialize the data of any animators that depend on laid out positioning 175 | setPhysicsValues(); 176 | } 177 | }; 178 | 179 | private void setPhysicsValues() { 180 | for (Demo demo : demos) { 181 | for (int i = 0; i < demo.anchors.length; i++) { 182 | View anchor = demo.anchors[i]; 183 | AnchoredForce force = demo.forces[i]; 184 | force.setAnchorPoint(new Vector(getCenterX(anchor), getCenterY(anchor))); 185 | } 186 | demo.integrator.setState( 187 | new Vector(getCenterX(demo.target), getCenterY(demo.target)), new Vector()); 188 | demo.integrator.start(); 189 | } 190 | } 191 | 192 | /** 193 | * An encapsulation of a physics demo. It consists of the container for all UI components, a 194 | * target view, multiple forces and their associated anchor views. 195 | */ 196 | private static class Demo { 197 | public final DragFrameLayout container; 198 | public final Integrator integrator; 199 | public final View target; 200 | public View[] anchors; 201 | public AnchoredForce[] forces; 202 | 203 | public static Demo of( 204 | DragFrameLayout container, Integrator dynamicEndValueIntegrator, View targets) { 205 | return new Demo(container, dynamicEndValueIntegrator, targets); 206 | } 207 | 208 | private Demo(DragFrameLayout container, Integrator integrator, View target) { 209 | this.container = container; 210 | this.integrator = integrator; 211 | this.target = target; 212 | } 213 | 214 | /** 215 | * Sets the anchor views on this demo. Each anchor view in {@link #anchors} at index 216 | * i must correspond to the {@link AnchoredForce} in {@link #forces} at index 217 | * i. 218 | */ 219 | public Demo with(View... anchors) { 220 | this.anchors = anchors; 221 | return this; 222 | } 223 | 224 | /** 225 | * Sets the forces on this demo. Each anchor view in {@link #anchors} at index 226 | * i must correspond to the {@link AnchoredForce} in {@link #forces} at index 227 | * i. 228 | *

229 | *

Forces without an anchor view should just be directly added to the {@link 230 | * Integrator}. 231 | */ 232 | public Demo with(AnchoredForce... forces) { 233 | this.forces = forces; 234 | return this; 235 | } 236 | } 237 | 238 | /** 239 | * An {@link Integrator.Listener} that syncs the integrator's state with the target view's 240 | * position. When the integrator settles, it activates the next force. 241 | */ 242 | private class TrackingListener extends SimpleListener { 243 | 244 | private final Demo demo; 245 | 246 | public TrackingListener(Demo demo) { 247 | this.demo = demo; 248 | } 249 | 250 | @Override 251 | public void onUpdate(Vector x, Vector v) { 252 | setCenter(demo.target, x.getValue(0), x.getValue(1)); 253 | } 254 | 255 | @Override 256 | public void onSettle() { 257 | activateNextForce(demo); 258 | } 259 | } 260 | 261 | /** 262 | * A {@link Callback} that allows both the target and anchor views to be captured. It syncs the 263 | * anchor view's position with the corresponding force's anchor point. When the target view is 264 | * flung, it calculates which force to activate. 265 | */ 266 | private class TrackingCallback extends Callback { 267 | 268 | private final Demo demo; 269 | 270 | public TrackingCallback(Demo demo) { 271 | this.demo = demo; 272 | } 273 | 274 | @Override 275 | public boolean tryCaptureView(View child, int pointerId) { 276 | if (child == demo.target) { 277 | return true; 278 | } 279 | for (View anchor : demo.anchors) { 280 | if (child == anchor) { 281 | return true; 282 | } 283 | } 284 | return false; 285 | } 286 | 287 | @Override 288 | public void onViewCaptured(View capturedChild, int activePointerId) { 289 | demo.container.getParent().requestDisallowInterceptTouchEvent(true); 290 | if (capturedChild == demo.target) { 291 | demo.integrator.stop(); 292 | } 293 | } 294 | 295 | @Override 296 | public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) { 297 | for (int i = 0; i < demo.anchors.length; i++) { 298 | View anchor = demo.anchors[i]; 299 | if (changedView == anchor) { 300 | AnchoredForce force = demo.forces[i]; 301 | force.setAnchorPoint(new Vector(getCenterX(anchor), getCenterY(anchor))); 302 | break; 303 | } 304 | } 305 | } 306 | 307 | @Override 308 | public void onViewReleased(View releasedChild, float xvel, float yvel) { 309 | if (releasedChild == demo.target) { 310 | demo.integrator.setState( 311 | new Vector(getCenterX(releasedChild), getCenterY(releasedChild)), 312 | new Vector(xvel, yvel)); 313 | demo.integrator.start(); 314 | } 315 | } 316 | 317 | @Override 318 | public int clampViewPositionHorizontal(View child, int left, int dx) { 319 | return left; 320 | } 321 | 322 | @Override 323 | public int clampViewPositionVertical(View child, int top, int dy) { 324 | return top; 325 | } 326 | } 327 | } 328 | -------------------------------------------------------------------------------- /sample/src/main/res/drawable/anchor1.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 9 | 10 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /sample/src/main/res/drawable/anchor2.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 9 | 10 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /sample/src/main/res/drawable/circle.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 9 | 10 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/main_activity.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 24 | 25 | 30 | 31 | 37 | 38 | 46 | 47 | 55 | 56 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/material-motion/physics-android/85d3101c0d74466efa347dbb42c1b8223609a4c5/sample/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/material-motion/physics-android/85d3101c0d74466efa347dbb42c1b8223609a4c5/sample/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/material-motion/physics-android/85d3101c0d74466efa347dbb42c1b8223609a4c5/sample/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/material-motion/physics-android/85d3101c0d74466efa347dbb42c1b8223609a4c5/sample/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/material-motion/physics-android/85d3101c0d74466efa347dbb42c1b8223609a4c5/sample/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /sample/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 10dp 4 | 40dp 5 | 10dp 6 | 7 | -------------------------------------------------------------------------------- /sample/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | Material Motion Physics for Android Sample 19 | 20 | Physics based animations allow the user to dynamically affect the end value of the animation. 21 | Drag any of the three dots to see how they affect the animation. 22 | 23 | 24 | -------------------------------------------------------------------------------- /sample/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 17 | 18 | 19 | 20 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':library', ':sample' 2 | --------------------------------------------------------------------------------