# rebound **Repository Path**: prashantpatil/rebound ## Basic Information - **Project Name**: rebound - **Description**: No description available - **Primary Language**: Unknown - **License**: Apache-2.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 14 - **Created**: 2022-04-12 - **Last Updated**: 2022-04-20 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ## rebound ## Introduction rebound is a simple library that models Spring dynamics for the purpose of driving physical animations. ## Download & Install ```javascript npm install @ohos/rebound --save ``` Details about OpenHarmony NPM environment configuration, see at (https://gitee.com/openharmony-tpc/docs/blob/master/OpenHarmony_npm_usage.md) ## Usage Instructions ##### 1. Create rebound SpringSystem which maintains Spring objects. Create and register Spring objects by configuring Tension, friction, Animator values. And add listener to receive spring positions. ```javascript spring=springSystem.createSpring(); spring.setSpringConfig(rebound.SpringConfig.DEFAULT_ORIGAMI_SPRING_CONFIG); springConfig = spring.getSpringConfig(); spring.addListener({ onSpringUpdate: function(spring) { var val = spring.getCurrentValue(); //Use Spring val to Process/Animate }, onSpringEndStateChange: function(spring){ } }); ``` ##### 2. Spring animates in the range between 0 to ā€˜n’, ā€˜n’ is the end value, call spring.setEndValue() to set end value. With below snippet spring positions are emitted between 0 to 1. ```javascript spring.setEndValue(1); ``` ##### 3. spring position is utilized in animating view components. Call mapValueInRange() to convert to custom range. in below example, spring positions are converted to image size multiplier to show spring animation. ```javascript spring.addListener({ onSpringUpdate: function(spring) { var val = spring.getCurrentValue(); val = rebound.MathUtil .mapValueInRange(val, 0, 1, 1, 0.5); self.imageSize=val; }, onSpringEndStateChange: function(spring){ } }); ``` ##### 4. call spring.setEndValue(0) to end spring effects. ```javascript spring.setEndValue(0); ``` ### API Introduction #### SpringSystem | Interface name | Parameter | Return Value | Remarks | | ----------------- | ----------------- | ----------------- | ----------------- | | SpringSystem() | Looper | StringSystem | SpringSystem is iterated by a looper. The looper is responsible for executing each frame as the SpringSystem is resolved to idle. There are three types of Loopers described below AnimationLooper, SimulationLooper, and SteppingSimulationLooper. AnimationLooper is default as it is the most useful for common UI animations. | |createSpring() |tension?: number, friction?: number|Spring|Add a new spring to this SpringSystem. This Spring will now be solved for during the physics iteration loop. By default the spring will use the default Origami spring config with 40 tension and 7 friction, but you can also provide your own values here.| |createSpringWithBouncinessAndSpeed()|bounciness?: number, speed?: number|Spring|Add a spring with a specified bounciness and speed. To replicate Origami compositions based on PopAnimation patches, use this factory method to create matching springs.| | createSpringWithConfig(): | kwargs: SpringConfigDict | Spring | Add a spring with the provided SpringConfig | | getIsIdle() | None |boolean|Check if a SpringSystem is idle or active. If all of the Springs in the SpringSystem are at rest, i.e. the physics forces have reached equilibrium, then this method will return true.| |getSpringById() |id: number|Spring|Retrieve a specific Spring from the SpringSystem by id. This can be useful for inspecting the state of a spring before or after an integration loop in the SpringSystem executes.| |getAllSprings() |None|Array|Get a listing of all the springs registered with this SpringSystem.| | registerSpring() | value: Spring | void |Manually add a spring to this system. This is called automatically if a Spring is created with SpringSystem#createSpring. This method sets the spring up in the registry so that it can be solved| |deregisterSpring(value: Spring) |value: Spring|void|Deregister a spring with this SpringSystem. The SpringSystem will no longer consider this Spring during its integration loop once this is called. This is normally done automatically for you when you call Spring#destroy.| |loop() |currentTimeMillis: number|void|This is the main solver loop called to move the simulation forward through time. Before each pass in the solver loop onBeforeIntegrate is called on an any listeners that have registered themeselves with the SpringSystem. This gives you an opportunity to apply any constraints or adjustments to the springs that should be enforced before each iteration loop.| |activateSpring() |springId: number|void|Used to notify the SpringSystem that a Spring has become displaced. The system responds by
starting its solver loop up if it is currently idle.| |addListener |listener: Listener|void|Add a listener to the SpringSystem to receive before/after integration notifications allowing
Springs to be constrained or adjusted.| |removeListener() |listener: Listener|void|Remove a previously added listener on the SpringSystem.| |removeAllListeners |None|void|Remove all previously added listeners on the SpringSystem.| #### Spring | Interface name | Parameter | Return Value | Remarks | | ----------------- | ----------------- | ----------------- | ----------------- | | Spring() | springSystem | String | Provides a model of a classical spring acting to resolve a body to equilibrium. | | destroy() | None | void | Destroy the spring | | getId() | None | number | Get Spring id of Spring | | getSpringConfig() | None | SpringConfigDict | Retrieve the SpringConfig used by this Spring. | | getCurrentValue() | None | number | Retrieve the current value of the Spring | | setCurrentValue() | currentValue: number, skipSetAtRest?: boolean | Spring | Set the current position of this Spring. | | getStartValue() | None | number | Get the position that the most recent animation started at. This can be useful for determining the number off oscillations that have occurred | | getCurrentDisplacementDistance() | None | number | Get the absolute distance of the Spring from its resting endValue position. | | getCurrentDisplacementDistanceForState() | state: PhysicsState | number | Get the absolute distance of the Spring from a given state value | | getEndValue() | None | number | Retrieve the endValue or resting position of this spring. | | setEndValue() | value: number | Spring | Set the endValue or resting position of the spring. If this value is different than the current value, the SpringSystem will be notified and will begin running its solver loop to resolve the Spring to equilibrium. Any listeners that are registered for onSpringEndStateChange will also be notified of this update immediately. | | getVelocity() | None | number | Get the current velocity of the Spring, in pixels per second. | | setVelocity() | value: number | Spring | Set the current velocity of the Spring, in pixels per second. As previously mentioned, this can be useful when you are performing a direct manipulation gesture. When a UI element is released you may call setVelocity on its animation Spring so that the Spring continues with the same velocity as the gesture ended with. The friction, tension, and displacement of the Spring will then govern its motion to return to rest on a natural feeling curve. | | getRestSpeedThreshold() | None | number | Retrieve the rest speed threshold for this Spring. | | setRestSpeedThreshold() | value: number | Spring | Set a threshold value for the movement speed of the Spring below which it will be considered to be not moving or resting. | | getRestDisplacementThreshold() | None | number | Retrieve the rest displacement threshold for this spring. | | isOvershootClampingEnabled() | None | boolean | Check if overshoot clamping is enabled for this spring. | | setOvershootClampingEnabled() | value: boolean | Spring | Enable overshoot clamping. This means that the Spring will stop immediately when it reaches its resting position regardless of any existing momentum it may have. This can be useful for certain types of animations that should not oscillate such as a scale down to 0 or alpha fade. | | isOvershooting() | None | boolean | Check if the Spring has gone past its end point by comparing the direction it was moving in when it started to the current position and end value. | | isAtRest() | None | boolean | Check if the Spring is atRest meaning that it's currentValue and endValue are the same and that it has no velocity. The previously described thresholds for speed and displacement define the bounds of this equivalence check. If the Spring has 0 tension, then it will be considered at rest whenever its absolute velocity drops below the restSpeedThreshold | | setAtRest() | None | Spring | set At Rest | | interpolate() | value: number | void | spring moving from position 0 to 1 could be interpolated to move | | addListener() | value: Listener | Spring | Add a listener to the SpringSystem to receive before/after integration notifications allowing Springs to be constrained or adjusted. | | removeListener() | value: Listener | Spring | Remove a previously added listener on the SpringSystem. | | removeAllListeners() | None | Spring | Remove all previously added listeners on the SpringSystem. | | | | | | #### Listeners | Interface name | Parameter | Return Value | Remarks | | ----------------- | ----------------- | ----------------- | ----------------- | | onSpringEndStateChange() | spring: Spring | void | Listen to Spring end state changes | | onBeforeIntegrate() | spring: Spring | void | onBeforeIntegrate is called on an any listeners that have registered themeselves with the SpringSystem. This gives you an opportunity to apply any constraints or adjustments to the springs that should be enforced before each iteration loop. | | onAfterIntegrate() | spring: Spring | void | integration step runs in advance, onAfterIntegrate is called on any listeners that have registered themselves with the SpringSystem. This gives you an opportunity to run any post integration constraints or adjustments on the Springs in the SpringSystem | | onSpringActivate() | spring: Spring | void | called on Spring get Activated | | onSpringUpdate | spring: Spring | void | on Spring Update | | onSpringAtRest() | spring: Spring | void | on spring at rest | #### SpringConfig | Interface name | Parameter | Return Value | Remarks | | ----------------- | ----------------- | ----------------- | ----------------- | | SpringConfig() | tension: number, friction: number | SpringConfig | Create a SpringConfig with no tension or a coasting spring with some amount of Friction so that it does not coast infininitely. | | fromOrigamiTensionAndFriction() | tension: number, friction: number | SpringConfig | Convert an origami Spring tension and friction to Rebound spring constants. If you are prototyping a design with Origami, this makes it easy to make your springs behave exactly the same in Rebound. | | fromBouncinessAndSpeed | bounciness: number, speed: number | SpringConfig | Convert an origami PopAnimation Spring bounciness and speed to Rebound spring constants. If you are using PopAnimation patches in Origami, this utility will provide springs that match your prototype. | | coastingConfigWithOrigamiFriction | friction: number | SpringConfig | Create a SpringConfig with no tension or a coasting spring with some amount of Friction so that it does not coast infininitely. Spring dynamics are observed when we use with setVelocity. | #### Looper | Interface name | Parameter | Return Value | Remarks | | ----------------- | ----------------- | ----------------- | ----------------- | | AnimationLooper() | None | AnimationLooper | Plays each frame of the SpringSystem on animation timing loop. This is the default type of looper for a new spring system as it is the most common when developing UI. | | SimulationLooper() | None | SimulationLooper | synchronously generating pre-recorded animations that can then be played on a timing loop later. | | SteppingSimulationLooper() | | SteppingSimulationLooper | one step at a time controlled by an outside loop. | #### OrigamiValueConverter | Interface name | Parameter | Return Value | Remarks | | ----------------- | ----------------- | ----------------- | ----------------- | | tensionFromOrigamiValue() | oValue: number | number | Origami value to tension convertor | | origamiValueFromTension() | tension: number | number | tension value to Origami value convertor | | frictionFromOrigamiValue() | oValue: number | number | Origami value to friction convertor | | origamiFromFriction() | friction: number | number | friction value to Origami value convertor | #### MathUtil | Interface name | Parameter | Return Value | Remarks | | ----------------- | ----------------- | ----------------- | ----------------- | | mapValueInRange() | value: number, fromLow: number, fromHigh: number, toLow: number, toHigh: number | number | map values from range to to range | |interpolateColor|val: number, startColorStr: string, endColorStr: string|string|Interpolate two hex colors in a 0 - 1 range| |degreesToRadians|deg: number|number|Degrees to Randian| |radiansToDegrees|rad: number|number|radian to Degree| #### util | Interface name | Parameter | Return Value | Remarks | | ----------------- | ----------------- | ----------------- | ----------------- | | bind() | func, context | void | Bind a function to a context object. | | extend() | target, source | void | Add all the properties in the source to the target. | | removeFirst() | array, item | void | Lop off the first occurrence of the reference in the Array. | | hexToRGB() | colorString | string | Converts a hex-formatted color string to its rgb-formatted equivalent. Handy when performing color tweening animations | | rgbToHex() | rNum, gNum, bNum | string | rgb to hex convertion | #### BouncyConversion | Interface name | Parameter | Return Value | Remarks | | ----------------- | ----------------- | ----------------- | ----------------- | | BouncyConversion() | bounciness: number, speed: number | BouncyConversion | Provides math for converting from Origami PopAnimation config values to regular Origami tension and friction values. | ##Compatibility OpenHarmony API version 8 or later is supported. ## Directory structure ```` |---- Rebound | |---- entry # Sample code folder | |-- rebound # rebound library folder | |-- README.md # Installation and usage method ```` ## Contribution Code Any questions found during the use process can be submitted to us by [Issue](https://gitee.com/openharmony-tpc/rebound/issues). Of course, we welcome you to send us [PR](https://gitee.com/openharmony-tpc/rebound/pulls). ## Open Source Protocol This project is based on [Apache License 2.0](https://gitee.com/openharmony-tpc/rebound/blob/master/LICENSE.txt). Please enjoy and participate freely in open source.