Rename skysprites to flutter_sprites

This commit is contained in:
Adam Barth
2015-10-13 16:34:01 -07:00
parent 090c37077b
commit a88a85e695
36 changed files with 82 additions and 82 deletions

View File

@@ -0,0 +1,555 @@
part of flutter_sprites;
typedef void ActionCallback();
/// Actions are used to animate properties of nodes or any other type of
/// objects. The actions are powered by an [ActionController], typically
/// associated with a [Node]. The most commonly used action is the
/// [ActionTween] which interpolates a property between two values over time.
///
/// Actions can be nested in different ways; played in sequence using the
/// [ActionSequence], or looped using the [ActionRepeat].
///
/// You should typically not override this class directly, instead override
/// [ActionInterval] or [ActionInstant] if you need to create a new action
/// class.
abstract class Action {
Object _tag;
bool _finished = false;
bool _added = false;
/// Moves to the next time step in an action, [dt] is the delta time since
/// the last time step in seconds. Typically this method is called from the
/// [ActionController].
void step(double dt);
/// Sets the action to a specific point in time. The [t] value that is passed
/// in is a normalized value 0.0 to 1.0 of the duration of the action. Every
/// action will always recieve a callback with the end time point (1.0),
/// unless it is cancelled.
void update(double t) {
}
void _reset() {
_finished = false;
}
double get duration => 0.0;
}
/// The abstract class for an action that changes properties over a time
/// interval, optionally using an easing curve.
abstract class ActionInterval extends Action {
double _duration;
bool _firstTick = true;
double _elapsed = 0.0;
/// The duration, in seconds, of the action.
///
/// double myTime = myAction.duration;
double get duration => _duration;
/// The animation curve used to ease the animation.
///
/// myAction.curve = bounceOut;
Curve curve;
ActionInterval([this._duration = 0.0, this.curve]);
void step(double dt) {
if (_firstTick) {
_firstTick = false;
} else {
_elapsed += dt;
}
double t;
if (this._duration == 0.0) {
t = 1.0;
} else {
t = (_elapsed / _duration).clamp(0.0, 1.0);
}
if (curve == null) {
update(t);
} else {
update(curve.transform(t));
}
if (t >= 1.0) _finished = true;
}
}
/// An action that repeats an action a fixed number of times.
class ActionRepeat extends ActionInterval {
final int numRepeats;
final ActionInterval action;
int _lastFinishedRepeat = -1;
/// Creates a new action that is repeats the passed in action a fixed number
/// of times.
///
/// var myLoop = new ActionRepeat(myAction);
ActionRepeat(this.action, this.numRepeats) {
_duration = action.duration * numRepeats;
}
void update(double t) {
int currentRepeat = math.min((t * numRepeats.toDouble()).toInt(), numRepeats - 1);
for (int i = math.max(_lastFinishedRepeat, 0); i < currentRepeat; i++) {
if (!action._finished) action.update(1.0);
action._reset();
}
_lastFinishedRepeat = currentRepeat;
double ta = (t * numRepeats.toDouble()) % 1.0;
action.update(ta);
if (t >= 1.0) {
action.update(1.0);
action._finished = true;
}
}
}
/// An action that repeats an action an indefinite number of times.
class ActionRepeatForever extends Action {
final ActionInterval action;
double _elapsedInAction = 0.0;
/// Creates a new action with the action that is passed in.
///
/// var myInifiniteLoop = new ActionRepeatForever(myAction);
ActionRepeatForever(this.action);
step(double dt) {
_elapsedInAction += dt;
while (_elapsedInAction > action.duration) {
_elapsedInAction -= action.duration;
if (!action._finished) action.update(1.0);
action._reset();
}
_elapsedInAction = math.max(_elapsedInAction, 0.0);
double t;
if (action._duration == 0.0) {
t = 1.0;
} else {
t = (_elapsedInAction / action._duration).clamp(0.0, 1.0);
}
action.update(t);
}
}
/// An action that plays a number of supplied actions in sequence. The duration
/// of the [ActionSequence] with be the sum of the durations of the actions
/// passed in to the constructor.
class ActionSequence extends ActionInterval {
Action _a;
Action _b;
double _split;
/// Creates a new action with the list of actions passed in.
///
/// var mySequence = new ActionSequence([myAction0, myAction1, myAction2]);
ActionSequence(List<Action> actions) {
assert(actions.length >= 2);
if (actions.length == 2) {
// Base case
_a = actions[0];
_b = actions[1];
} else {
_a = actions[0];
_b = new ActionSequence(actions.sublist(1));
}
// Calculate split and duration
_duration = _a.duration + _b.duration;
if (_duration > 0) {
_split = _a.duration / _duration;
} else {
_split = 1.0;
}
}
void update(double t) {
if (t < _split) {
// Play first action
double ta;
if (_split > 0.0) {
ta = (t / _split).clamp(0.0, 1.0);
} else {
ta = 1.0;
}
_updateWithCurve(_a, ta);
} else if (t >= 1.0) {
// Make sure everything is finished
if (!_a._finished) _finish(_a);
if (!_b._finished) _finish(_b);
} else {
// Play second action, but first make sure the first has finished
if (!_a._finished) _finish(_a);
double tb;
if (_split < 1.0) {
tb = (1.0 - (1.0 - t) / (1.0 - _split)).clamp(0.0, 1.0);
} else {
tb = 1.0;
}
_updateWithCurve(_b, tb);
}
}
void _updateWithCurve(Action action, double t) {
if (action is ActionInterval) {
ActionInterval actionInterval = action;
if (actionInterval.curve == null) {
action.update(t);
} else {
action.update(actionInterval.curve.transform(t));
}
} else {
action.update(t);
}
if (t >= 1.0) {
action._finished = true;
}
}
void _finish(Action action) {
action.update(1.0);
action._finished = true;
}
void _reset() {
super._reset();
_a._reset();
_b._reset();
}
}
/// An action that plays the supplied actions in parallell. The duration of the
/// [ActionGroup] will be the maximum of the durations of the actions used to
/// compose this action.
class ActionGroup extends ActionInterval {
List<Action> _actions;
/// Creates a new action with the list of actions passed in.
///
/// var myGroup = new ActionGroup([myAction0, myAction1, myAction2]);
ActionGroup(this._actions) {
for (Action action in _actions) {
if (action.duration > _duration) {
_duration = action.duration;
}
}
}
void update(double t) {
if (t >= 1.0) {
// Finish all unfinished actions
for (Action action in _actions) {
if (!action._finished) {
action.update(1.0);
action._finished = true;
}
}
} else {
for (Action action in _actions) {
if (action.duration == 0.0) {
// Fire all instant actions immediately
if (!action._finished) {
action.update(1.0);
action._finished = true;
}
} else {
// Update child actions
double ta = (t / (action.duration / duration)).clamp(0.0, 1.0);
if (ta < 1.0) {
if (action is ActionInterval) {
ActionInterval actionInterval = action;
if (actionInterval.curve == null) {
action.update(ta);
} else {
action.update(actionInterval.curve.transform(ta));
}
} else {
action.update(ta);
}
} else if (!action._finished){
action.update(1.0);
action._finished = true;
}
}
}
}
}
void _reset() {
for (Action action in _actions) {
action._reset();
}
}
}
/// An action that doesn't perform any other task than taking time. This action
/// is typically used in a sequence to space out other events.
class ActionDelay extends ActionInterval {
/// Creates a new action with the specified [delay]
ActionDelay(double delay) : super(delay);
}
/// An action that doesn't have a duration. If this class is overridden to
/// create custom instant actions, only the [fire] method should be overriden.
abstract class ActionInstant extends Action {
void step(double dt) {
}
void update(double t) {
fire();
_finished = true;
}
void fire();
}
/// An action that calls a custom function when it is fired.
class ActionCallFunction extends ActionInstant {
ActionCallback _function;
/// Creates a new callback action with the supplied callback.
///
/// var myAction = new ActionCallFunction(() { print("Hello!";) });
ActionCallFunction(this._function);
void fire() {
_function();
}
}
/// An action that removes the supplied node from its parent when it's fired.
class ActionRemoveNode extends ActionInstant {
Node _node;
/// Creates a new action with the node to remove as its argument.
///
/// var myAction = new ActionRemoveNode(myNode);
ActionRemoveNode(this._node);
void fire() {
_node.removeFromParent();
}
}
/// An action that tweens a property between two values, optionally using an
/// animation curve. This is one of the most common building blocks when
/// creating actions. The tween class can be used to animate properties of the
/// type [Point], [Size], [Rect], [double], or [Color].
class ActionTween extends ActionInterval {
/// The setter method used to set the property being animated.
final Function setter;
/// The start value of the animation.
final startVal;
/// The end value of the animation.
final endVal;
var _delta;
/// Creates a new tween action. The [setter] will be called to update the
/// animated property from [startVal] to [endVal] over the [duration] time in
/// seconds. Optionally an animation [curve] can be passed in for easing the
/// animation.
///
/// // Animate myNode from its current position to 100.0, 100.0 during
/// // 1.0 second and a bounceOut easing
/// var myTween = new ActionTween(
/// (a) => myNode.position = a,
/// myNode.position,
/// new Point(100.0, 100.0,
/// 1.0,
/// bounceOut
/// );
/// myNode.actions.run(myTween);
ActionTween(this.setter, this.startVal, this.endVal, double duration, [Curve curve]) : super(duration, curve) {
_computeDelta();
}
void _computeDelta() {
if (startVal is Point) {
// Point
double xStart = startVal.x;
double yStart = startVal.y;
double xEnd = endVal.x;
double yEnd = endVal.y;
_delta = new Point(xEnd - xStart, yEnd - yStart);
} else if (startVal is Size) {
// Size
double wStart = startVal.width;
double hStart = startVal.height;
double wEnd = endVal.width;
double hEnd = endVal.height;
_delta = new Size(wEnd - wStart, hEnd - hStart);
} else if (startVal is Rect) {
// Rect
double lStart = startVal.left;
double tStart = startVal.top;
double rStart = startVal.right;
double bStart = startVal.bottom;
double lEnd = endVal.left;
double tEnd = endVal.top;
double rEnd = endVal.right;
double bEnd = endVal.bottom;
_delta = new Rect.fromLTRB(lEnd - lStart, tEnd - tStart, rEnd - rStart, bEnd - bStart);
} else if (startVal is double) {
// Double
_delta = endVal - startVal;
} else if (startVal is Color) {
// Color
int aDelta = endVal.alpha - startVal.alpha;
int rDelta = endVal.red - startVal.red;
int gDelta = endVal.green - startVal.green;
int bDelta = endVal.blue - startVal.blue;
_delta = new _ColorDiff(aDelta, rDelta, gDelta, bDelta);
} else {
assert(false);
}
}
void update(double t) {
var newVal;
if (startVal is Point) {
// Point
double xStart = startVal.x;
double yStart = startVal.y;
double xDelta = _delta.x;
double yDelta = _delta.y;
newVal = new Point(xStart + xDelta * t, yStart + yDelta * t);
} else if (startVal is Size) {
// Size
double wStart = startVal.width;
double hStart = startVal.height;
double wDelta = _delta.width;
double hDelta = _delta.height;
newVal = new Size(wStart + wDelta * t, hStart + hDelta * t);
} else if (startVal is Rect) {
// Rect
double lStart = startVal.left;
double tStart = startVal.top;
double rStart = startVal.right;
double bStart = startVal.bottom;
double lDelta = _delta.left;
double tDelta = _delta.top;
double rDelta = _delta.right;
double bDelta = _delta.bottom;
newVal = new Rect.fromLTRB(lStart + lDelta * t, tStart + tDelta * t, rStart + rDelta * t, bStart + bDelta * t);
} else if (startVal is double) {
// Doubles
newVal = startVal + _delta * t;
} else if (startVal is Color) {
// Colors
int aNew = (startVal.alpha + (_delta.alpha * t).toInt()).clamp(0, 255);
int rNew = (startVal.red + (_delta.red * t).toInt()).clamp(0, 255);
int gNew = (startVal.green + (_delta.green * t).toInt()).clamp(0, 255);
int bNew = (startVal.blue + (_delta.blue * t).toInt()).clamp(0, 255);
newVal = new Color.fromARGB(aNew, rNew, gNew, bNew);
} else {
// Oopses
assert(false);
}
setter(newVal);
}
}
/// A class the controls the playback of actions. To play back an action it is
/// passed to the [ActionController]'s [run] method. The [ActionController]
/// itself is typically a property of a [Node] and powered by the [SpriteBox].
class ActionController {
List<Action> _actions = [];
/// Creates a new [ActionController]. However, for most uses a reference to
/// an [ActionController] is acquired through the [Node.actions] property.
ActionController();
/// Runs an [action], can optionally be passed a [tag]. The [tag] can be used
/// to reference the action or a set of actions with the same tag.
///
/// myNode.actions.run(myAction, "myActionGroup");
void run(Action action, [Object tag]) {
assert(!action._added);
action._tag = tag;
action._added = true;
action.update(0.0);
_actions.add(action);
}
/// Stops an [action] and removes it from the controller.
///
/// myNode.actions.stop(myAction);
void stop(Action action) {
if (_actions.remove(action)) {
action._added = false;
action._reset();
}
}
void _stopAtIndex(int i) {
Action action = _actions[i];
action._added = false;
action._reset();
_actions.removeAt(i);
}
/// Stops all actions with the specified tag and removes them from the
/// controller.
///
/// myNode.actions.stopWithTag("myActionGroup");
void stopWithTag(Object tag) {
for (int i = _actions.length - 1; i >= 0; i--) {
Action action = _actions[i];
if (action._tag == tag) {
_stopAtIndex(i);
}
}
}
/// Stops all actions currently being run by the controller and removes them.
///
/// myNode.actions.stopAll();
void stopAll() {
for (int i = _actions.length - 1; i >= 0; i--) {
_stopAtIndex(i);
}
}
void step(double dt) {
for (int i = _actions.length - 1; i >= 0; i--) {
Action action = _actions[i];
action.step(dt);
if (action._finished) {
action._added = false;
_actions.removeAt(i);
}
}
}
}
class _ColorDiff {
final int alpha;
final int red;
final int green;
final int blue;
_ColorDiff(this.alpha, this.red, this.green, this.blue);
}

View File

@@ -0,0 +1,67 @@
part of flutter_sprites;
Point _cardinalSplineAt(Point p0, Point p1, Point p2, Point p3, double tension, double t) {
double t2 = t * t;
double t3 = t2 * t;
double s = (1.0 - tension) / 2.0;
double b1 = s * ((-t3 + (2.0 * t2)) - t);
double b2 = s * (-t3 + t2) + (2.0 * t3 - 3.0 * t2 + 1.0);
double b3 = s * (t3 - 2.0 * t2 + t) + (-2.0 * t3 + 3.0 * t2);
double b4 = s * (t3 - t2);
double x = p0.x * b1 + p1.x * b2 + p2.x * b3 + p3.x * b4;
double y = p0.y * b1 + p1.y * b2 + p2.y * b3 + p3.y * b4;
return new Point(x, y);
}
/// The spline action is used to animate a point along a spline definied by
/// a set of points.
class ActionSpline extends ActionInterval {
/// Creates a new spline action with a set of points. The [setter] is a
/// callback for setting the positions, [points] define the spline, and
/// [duration] is the time for the action to complete. Optionally a [curve]
/// can be used for easing.
ActionSpline(this.setter, this.points, double duration, [Curve curve]) : super(duration, curve) {
_dt = 1.0 / (points.length - 1.0);
}
/// The callback used to update a point when the action is run.
final Function setter;
/// A list of points that define the spline.
final List<Point> points;
/// The tension of the spline, defines the roundness of the curve.
double tension = 0.5;
double _dt;
void update(double t) {
int p;
double lt;
if (t < 0.0) t = 0.0;
if (t >= 1.0) {
p = points.length - 1;
lt = 1.0;
} else {
p = (t / _dt).floor();
lt = (t - _dt * p) / _dt;
}
Point p0 = points[(p - 1).clamp(0, points.length - 1)];
Point p1 = points[(p + 0).clamp(0, points.length - 1)];
Point p2 = points[(p + 1).clamp(0, points.length - 1)];
Point p3 = points[(p + 2).clamp(0, points.length - 1)];
Point newPos = _cardinalSplineAt(p0, p1, p2, p3, tension, lt);
setter(newPos);
}
}

View File

@@ -0,0 +1,77 @@
part of flutter_sprites;
/// A sequence of colors representing a gradient or a color transition over
/// time. The sequence is represented by a list of [colors] and a list of
/// [colorStops], the stops are normalized values (0.0 to 1.0) and ordered in
/// the list. Both lists have the same number of elements.
class ColorSequence {
/// List of colors.
List<Color> colors;
/// List of color stops, normalized values (0.0 to 1.0) and ordered.
List<double> colorStops;
/// Creates a new color sequence from a list of [colors] and a list of
/// [colorStops].
ColorSequence(this.colors, this.colorStops) {
assert(colors != null);
assert(colorStops != null);
assert(colors.length == colorStops.length);
}
/// Creates a new color sequence from a start and an end color.
ColorSequence.fromStartAndEndColor(Color start, Color end) {
colors = [start, end];
colorStops = [0.0, 1.0];
}
/// Creates a new color sequence by copying an existing sequence.
ColorSequence.copy(ColorSequence sequence) {
colors = new List<Color>.from(sequence.colors);
colorStops = new List<double>.from(sequence.colorStops);
}
/// Returns the color at a normalized (0.0 to 1.0) position in the color
/// sequence. If a color stop isn't hit, the returned color will be an
/// interpolation of a color between two color stops.
Color colorAtPosition(double pos) {
assert(pos >= 0.0 && pos <= 1.0);
if (pos == 0.0) return colors[0];
double lastStop = colorStops[0];
Color lastColor = colors[0];
for (int i = 0; i < colors.length; i++) {
double currentStop = colorStops[i];
Color currentColor = colors[i];
if (pos <= currentStop) {
double blend = (pos - lastStop) / (currentStop - lastStop);
return _interpolateColor(lastColor, currentColor, blend);
}
lastStop = currentStop;
lastColor = currentColor;
}
return colors[colors.length-1];
}
}
Color _interpolateColor(Color a, Color b, double blend) {
double aa = a.alpha.toDouble();
double ar = a.red.toDouble();
double ag = a.green.toDouble();
double ab = a.blue.toDouble();
double ba = b.alpha.toDouble();
double br = b.red.toDouble();
double bg = b.green.toDouble();
double bb = b.blue.toDouble();
int na = (aa * (1.0 - blend) + ba * blend).toInt();
int nr = (ar * (1.0 - blend) + br * blend).toInt();
int ng = (ag * (1.0 - blend) + bg * blend).toInt();
int nb = (ab * (1.0 - blend) + bb * blend).toInt();
return new Color.fromARGB(na, nr, ng, nb);
}

View File

@@ -0,0 +1,142 @@
part of flutter_sprites;
/// A constraint limits or otherwise controls a [Node]'s properties, such as
/// position or rotation. Add a list of constraints by setting the [Node]'s
/// constraints property.
///
/// Constrains are applied after the update calls are
/// completed. They can also be applied at any time by calling a [Node]'s
/// [applyConstraints] method. It's possible to create custom constraints by
/// overriding this class and implementing the [constrain] method.
abstract class Constraint {
/// Called before the node's update method is called. This method can be
/// overridden to create setup work that needs to happen before the the
/// node is updated, e.g. to calculate the node's speed.
void preUpdate(Node node, double dt) {
}
/// Called after update is complete, if the constraint has been added to a
/// [Node]. Override this method to modify the node's property according to
/// the constraint.
void constrain(Node node, double dt);
}
double _dampenRotation(double src, double dst, double dampening) {
if (dampening == null)
return dst;
double delta = dst - src;
while (delta > 180.0) delta -= 360;
while (delta < -180) delta += 360;
delta *= dampening;
return src + delta;
}
/// A [Constraint] that aligns a nodes rotation to its movement.
class ConstraintRotationToMovement extends Constraint {
/// Creates a new constraint the aligns a nodes rotation to its movement
/// vector. A [baseRotation] and [dampening] can optionally be set.
ConstraintRotationToMovement({this.baseRotation: 0.0, this.dampening});
/// The filter factor used when constraining the rotation of the node. Valid
/// values are in the range 0.0 to 1.0
final double dampening;
/// The base rotation will be added to a the movement vectors rotation.
final double baseRotation;
Point _lastPosition;
void preUpdate(Node node, double dt) {
_lastPosition = node.position;
}
void constrain(Node node, double dt) {
if (_lastPosition == null) return;
if (_lastPosition == node.position) return;
// Get the target angle
Offset offset = node.position - _lastPosition;
double target = degrees(GameMath.atan2(offset.dy, offset.dx)) + baseRotation;
node.rotation = _dampenRotation(node.rotation, target, dampening);
}
}
/// A [Constraint] that rotates a node to point towards another node. The target
/// node is allowed to have a different parent, but they must be in the same
/// [SpriteBox].
class ConstraintRotationToNode extends Constraint {
/// Creates a new [Constraint] that rotates the node towards the [targetNode].
/// The [baseRotation] will be added to the nodes rotation, and [dampening]
/// can be used to ease the rotation.
ConstraintRotationToNode(this.targetNode, {this.baseRotation: 0.0, this.dampening});
/// The node to rotate towards.
final Node targetNode;
/// The base rotation will be added after the target rotation is calculated.
final double baseRotation;
/// The filter factor used when constraining the rotation of the node. Valid
/// values are in the range 0.0 to 1.0
final double dampening;
void constrain(Node node, double dt) {
Offset offset;
if (targetNode.spriteBox != node.spriteBox) {
// The target node is in another sprite box or has been removed
return;
}
if (targetNode.parent == node.parent) {
offset = targetNode.position - node.position;
} else {
offset = node.convertPointToBoxSpace(Point.origin)
- targetNode.convertPointToBoxSpace(Point.origin);
}
double target = degrees(GameMath.atan2(offset.dy, offset.dx)) + baseRotation;
node.rotation = _dampenRotation(node.rotation, target, dampening);
}
}
/// A [Constraint] that constrains the position of a node to equal the position
/// of another node, optionally with dampening.
class ConstraintPositionToNode extends Constraint {
/// Creates a new [Constraint] that constrains the poistion of a node to be
/// equal to the position of the [targetNode]. Optionally an [offset] can
/// be used and also [dampening]. The targetNode doesn't need to have the
/// same parent, but they need to be added to the same [SpriteBox].
ConstraintPositionToNode(this.targetNode, {this.dampening, this.offset: Offset.zero});
final Node targetNode;
final Offset offset;
final double dampening;
void constrain(Node node, double dt) {
Point targetPosition;
if (targetNode.spriteBox != node.spriteBox || node.parent == null) {
// The target node is in another sprite box or has been removed
return;
}
if (targetNode.parent == node.parent) {
targetPosition = targetNode.position;
} else {
targetPosition = node.parent.convertPointFromNode(Point.origin, targetNode);
}
if (offset != null)
targetPosition += offset;
if (dampening == null)
node.position = targetPosition;
else
node.position = GameMath.filterPoint(node.position, targetPosition, dampening);
}
}

View File

@@ -0,0 +1,204 @@
part of flutter_sprites;
enum EffectLineWidthMode {
linear,
barrel,
}
enum EffectLineAnimationMode {
none,
scroll,
random,
}
class EffectLine extends Node {
EffectLine({
this.texture: null,
this.transferMode: ui.TransferMode.dstOver,
List<Point> points,
this.widthMode : EffectLineWidthMode.linear,
this.minWidth: 10.0,
this.maxWidth: 10.0,
this.widthGrowthSpeed: 0.0,
this.animationMode: EffectLineAnimationMode.none,
this.scrollSpeed: 0.1,
double scrollStart: 0.0,
this.fadeDuration: null,
this.fadeAfterDelay: null,
this.textureLoopLength: null,
this.simplify: true,
ColorSequence colorSequence
}) {
if (points == null) this.points = [];
else this.points = points;
_colorSequence = colorSequence;
if (_colorSequence == null)
_colorSequence = new ColorSequence.fromStartAndEndColor(
new Color(0xffffffff),
new Color(0xffffffff));
_offset = scrollStart;
_painter = new TexturedLinePainter(points, _colors, _widths, texture);
_painter.textureLoopLength = textureLoopLength;
}
final Texture texture;
final ui.TransferMode transferMode;
final EffectLineWidthMode widthMode;
final double minWidth;
final double maxWidth;
final double widthGrowthSpeed;
final EffectLineAnimationMode animationMode;
final double scrollSpeed;
ColorSequence _colorSequence;
ColorSequence get colorSequence => _colorSequence;
List<Point> _points;
List<Point> get points => _points;
set points(List<Point> points) {
_points = points;
_pointAges = [];
for (int i = 0; i < _points.length; i++) {
_pointAges.add(0.0);
}
}
List<double> _pointAges;
List<Color> _colors;
List<double> _widths;
final double fadeDuration;
final double fadeAfterDelay;
final double textureLoopLength;
final bool simplify;
TexturedLinePainter _painter;
double _offset = 0.0;
void update(double dt) {
// Update scrolling position
if (animationMode == EffectLineAnimationMode.scroll) {
_offset += dt * scrollSpeed;
_offset %= 1.0;
} else if (animationMode == EffectLineAnimationMode.random) {
_offset = randomDouble();
}
// Update age of line points and remove if neccesasry
if (fadeDuration != null && fadeAfterDelay != null) {
// Increase age of points
for (int i = _points.length - 1; i >= 0; i--) {
_pointAges[i] += dt;
}
// Check if the first/oldest point should be removed
while(_points.length > 0 && _pointAges[0] > (fadeDuration + fadeAfterDelay)) {
// Update scroll if it isn't the last and only point that is about to removed
if (_points.length > 1 && textureLoopLength != null) {
double dist = GameMath.distanceBetweenPoints(_points[0], _points[1]);
_offset = (_offset - (dist / textureLoopLength)) % 1.0;
if (_offset < 0.0) _offset += 1;
}
// Remove the point
_pointAges.removeAt(0);
_points.removeAt(0);
}
}
}
void paint(PaintingCanvas canvas) {
if (points.length < 2) return;
_painter.points = points;
// Calculate colors
List<double> stops = _painter.calculatedTextureStops;
List<Color> colors = [];
for (int i = 0; i < stops.length; i++) {
double stop = stops[i];
Color color = _colorSequence.colorAtPosition(stop);
if (fadeDuration != null && fadeAfterDelay != null) {
double age = _pointAges[i];
if (age > fadeAfterDelay) {
double fade = 1.0 - (age - fadeAfterDelay) / fadeDuration;
int alpha = (color.alpha * fade).toInt().clamp(0, 255);
color = new Color.fromARGB(alpha, color.red, color.green, color.blue);
}
}
colors.add(color);
}
_painter.colors = colors;
// Calculate widths
List<double> widths = [];
for (int i = 0; i < stops.length; i++) {
double stop = stops[i];
double growth = math.max(widthGrowthSpeed * _pointAges[i], 0.0);
if (widthMode == EffectLineWidthMode.linear) {
double width = minWidth + (maxWidth - minWidth) * stop + growth;
widths.add(width);
} else if (widthMode == EffectLineWidthMode.barrel) {
double width = minWidth + math.sin(stop * math.PI) * (maxWidth - minWidth) + growth;
widths.add(width);
}
}
_painter.widths = widths;
_painter.textureStopOffset = _offset;
_painter.paint(canvas);
}
void addPoint(Point point) {
// Skip duplicate points
if (points.length > 0 && point.x == points[points.length - 1].x && point.y == points[points.length - 1].y)
return;
if (simplify && points.length >= 2 && GameMath.distanceBetweenPoints(point, points[points.length - 2]) < 10.0) {
// Check if we should remove last point before adding the new one
// Calculate the square distance from the middle point to the line of the
// new point and the second to last point
double dist2 = _distToSeqment2(
points[points.length - 1],
point,
points[points.length - 2]
);
// If the point is on the line, remove it
if (dist2 < 1.0) {
_points.removeAt(_points.length - 1);
}
}
// Add point and point's age
_points.add(point);
_pointAges.add(0.0);
}
double _sqr(double x) => x * x;
double _dist2(Point v, Point w) => _sqr(v.x - w.x) + _sqr(v.y - w.y);
double _distToSeqment2(Point p, Point v, Point w) {
double l2 = _dist2(v, w);
if (l2 == 0.0) return _dist2(p, v);
double t = ((p.x - v.x) * (w.x - v.x) + (p.y - v.y) * (w.y - v.y)) / l2;
if (t < 0) return _dist2(p, v);
if (t > 1) return _dist2(p, w);
return _dist2(p, new Point(v.x + t * (w.x - v.x), v.y + t * (w.y - v.y)));
}
}

View File

@@ -0,0 +1,25 @@
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
part of flutter_sprites;
class ImageMap {
ImageMap(AssetBundle bundle) : _bundle = bundle;
final AssetBundle _bundle;
final Map<String, ui.Image> _images = new Map<String, ui.Image>();
Future<List<ui.Image>> load(List<String> urls) {
return Future.wait(urls.map(_loadImage));
}
Future<ui.Image> _loadImage(String url) async {
ui.Image image = await _bundle.loadImage(url).first;
_images[url] = image;
return image;
}
ui.Image getImage(String url) => _images[url];
ui.Image operator [](String url) => _images[url];
}

View File

@@ -0,0 +1,62 @@
part of flutter_sprites;
/// Labels are used to display a string of text in a the node tree. To align
/// the label, the textAlign property of the [TextStyle] can be set.
class Label extends Node {
/// Creates a new Label with the provided [_text] and [_textStyle].
Label(this._text, [this._textStyle]) {
if (_textStyle == null) {
_textStyle = new TextStyle();
}
}
String _text;
/// The text being drawn by the label.
String get text => _text;
set text(String text) {
_text = text;
_painter = null;
}
TextStyle _textStyle;
/// The style to draw the text in.
TextStyle get textStyle => _textStyle;
set textStyle(TextStyle textStyle) {
_textStyle = textStyle;
_painter = null;
}
TextPainter _painter;
double _width;
void paint(PaintingCanvas canvas) {
if (_painter == null) {
PlainTextSpan textSpan = new PlainTextSpan(_text);
StyledTextSpan styledTextSpan = new StyledTextSpan(_textStyle, [textSpan]);
_painter = new TextPainter(styledTextSpan);
_painter.maxWidth = double.INFINITY;
_painter.minWidth = 0.0;
_painter.layout();
_width = _painter.maxContentWidth.ceil().toDouble();
_painter.maxWidth = _width;
_painter.minWidth = _width;
_painter.layout();
}
Offset offset = Offset.zero;
if (_textStyle.textAlign == TextAlign.center) {
offset = new Offset(-_width / 2.0, 0.0);
} else if (_textStyle.textAlign == TextAlign.right) {
offset = new Offset(-_width, 0.0);
}
_painter.paint(canvas, offset);
}
}

View File

@@ -0,0 +1,39 @@
part of flutter_sprites;
/// A [Node] that provides an intermediate rendering surface in the sprite
/// rendering tree. A [Layer] can be used to change the opacity, color, or to
/// apply an effect to a set of nodes. All nodes that are children to the
/// [Layer] will be rendered into the surface. If the area that is needed for
/// the children to be drawn is know, the [layerRect] property should be set as
/// this can enhance performance.
class Layer extends Node with SpritePaint {
/// The area that the children of the [Layer] will occupy. This value is
/// treated as a hint to the rendering system and may in some cases be
/// ignored. If the area isn't known, the layerRect can be set to [null].
///
/// myLayer.layerRect = new Rect.fromLTRB(0.0, 0.0, 200.0, 100.0);
Rect layerRect;
/// Creates a new layer. The layerRect can optionally be passed as an argument
/// if it is known.
///
/// var myLayer = new Layer();
Layer([Rect this.layerRect = null]);
Paint _cachedPaint = new Paint()
..filterQuality = ui.FilterQuality.low
..isAntiAlias = false;
void _prePaint(PaintingCanvas canvas, Matrix4 matrix) {
super._prePaint(canvas, matrix);
_updatePaint(_cachedPaint);
canvas.saveLayer(layerRect, _cachedPaint);
}
void _postPaint(PaintingCanvas canvas, Matrix4 totalMatrix) {
canvas.restore();
super._postPaint(canvas, totalMatrix);
}
}

View File

@@ -0,0 +1,658 @@
part of flutter_sprites;
double convertDegrees2Radians(double degrees) => degrees * math.PI/180.8;
double convertRadians2Degrees(double radians) => radians * 180.0/math.PI;
/// A base class for all objects that can be added to the sprite node tree and rendered to screen using [SpriteBox] and
/// [SpriteWidget].
///
/// The [Node] class itself doesn't render any content, but provides the basic functions of any type of node, such as
/// handling transformations and user input. To render the node tree, a root node must be added to a [SpriteBox] or a
/// [SpriteWidget]. Commonly used sub-classes of [Node] are [Sprite], [NodeWithSize], and many more upcoming subclasses.
///
/// Nodes form a hierarchical tree. Each node can have a number of children, and the transformation (positioning,
/// rotation, and scaling) of a node also affects its children.
class Node {
// Member variables
SpriteBox _spriteBox;
Node _parent;
Point _position = Point.origin;
double _rotation = 0.0;
Matrix4 _transformMatrix = new Matrix4.identity();
Matrix4 _transformMatrixNodeToBox;
Matrix4 _transformMatrixBoxToNode;
double _scaleX = 1.0;
double _scaleY = 1.0;
double _skewX = 0.0;
double _skewY = 0.0;
/// The visibility of this node and its children.
bool visible = true;
double _zPosition = 0.0;
int _addedOrder;
int _childrenLastAddedOrder = 0;
bool _childrenNeedSorting = false;
Matrix4 _savedTotalMatrix;
/// Decides if the node and its children is currently paused.
///
/// A paused node will not receive any input events, update calls, or run any animations.
///
/// myNodeTree.paused = true;
bool paused = false;
bool _userInteractionEnabled = false;
/// If set to true the node will receive multiple pointers, otherwise it will only receive events the first pointer.
///
/// This property is only meaningful if [userInteractionEnabled] is set to true. Default value is false.
///
/// class MyCustomNode extends Node {
/// handleMultiplePointers = true;
/// }
bool handleMultiplePointers = false;
int _handlingPointer;
List<Node>_children = [];
ActionController _actions;
/// The [ActionController] associated with this node.
///
/// myNode.actions.run(myAction);
ActionController get actions {
if (_actions == null) {
_actions = new ActionController();
if (_spriteBox != null) _spriteBox._actionControllers = null;
}
return _actions;
}
List<Constraint> _constraints;
/// A [List] of [Constraint]s that will be applied to the node.
/// The constraints are applied after the [update] method has been called.
List<Constraint> get constraints {
return _constraints;
}
set constraints(List<Constraint> constraints) {
_constraints = constraints;
if (_spriteBox != null) _spriteBox._constrainedNodes = null;
}
/// Called to apply the [constraints] to the node. Normally, this method is
/// called automatically by the [SpriteBox], but it can be called manually
/// if the constraints need to be applied immediately.
void applyConstraints(double dt) {
if (_constraints == null) return;
for (Constraint constraint in _constraints) {
constraint.constrain(this, dt);
}
}
// Constructors
/// Creates a new [Node] without any transformation.
///
/// var myNode = new Node();
Node() {
}
// Property setters and getters
/// The [SpriteBox] this node is added to, or null if it's not currently added to a [SpriteBox].
///
/// For most applications it's not necessary to access the [SpriteBox] directly.
///
/// // Get the transformMode of the sprite box
/// var transformMode = myNode.spriteBox.transformMode;
SpriteBox get spriteBox => _spriteBox;
/// The parent of this node, or null if it doesn't have a parent.
///
/// // Hide the parent
/// myNode.parent.visible = false;
Node get parent => _parent;
/// The rotation of this node in degrees.
///
/// myNode.rotation = 45.0;
double get rotation => _rotation;
void set rotation(double rotation) {
assert(rotation != null);
if (_physicsBody != null && parent is PhysicsNode) {
PhysicsNode physicsNode = parent;
physicsNode._updateRotation(this.physicsBody, rotation);
return;
}
_rotation = rotation;
invalidateTransformMatrix();
}
void _setRotationFromPhysics(double rotation) {
assert(rotation != null);
_rotation = rotation;
invalidateTransformMatrix();
}
/// The position of this node relative to its parent.
///
/// myNode.position = new Point(42.0, 42.0);
Point get position => _position;
void set position(Point position) {
assert(position != null);
if (_physicsBody != null && parent is PhysicsNode) {
PhysicsNode physicsNode = parent;
physicsNode._updatePosition(this.physicsBody, position);
return;
}
_position = position;
invalidateTransformMatrix();
}
void _setPositionFromPhysics(Point position) {
assert(position != null);
_position = position;
invalidateTransformMatrix();
}
/// The skew along the x-axis of this node in degrees.
///
/// myNode.skewX = 45.0;
double get skewX => _skewX;
void set skewX (double skewX) {
assert(skewX != null);
_skewX = skewX;
invalidateTransformMatrix();
}
/// The skew along the y-axis of this node in degrees.
///
/// myNode.skewY = 45.0;
double get skewY => _skewY;
void set skewY (double skewY) {
assert(skewY != null);
_skewY = skewY;
invalidateTransformMatrix();
}
/// The draw order of this node compared to its parent and its siblings.
///
/// By default nodes are drawn in the order that they have been added to a parent. To override this behavior the
/// [zPosition] property can be used. A higher value of this property will force the node to be drawn in front of
/// siblings that have a lower value. If a negative value is used the node will be drawn behind its parent.
///
/// nodeInFront.zPosition = 1.0;
/// nodeBehind.zPosition = -1.0;
double get zPosition => _zPosition;
void set zPosition(double zPosition) {
assert(zPosition != null);
_zPosition = zPosition;
if (_parent != null) {
_parent._childrenNeedSorting = true;
}
}
/// The scale of this node relative its parent.
///
/// The [scale] property is only valid if [scaleX] and [scaleY] are equal values.
///
/// myNode.scale = 5.0;
double get scale {
assert(_scaleX == _scaleY);
return _scaleX;
}
void set scale(double scale) {
assert(scale != null);
_scaleX = _scaleY = scale;
invalidateTransformMatrix();
}
/// The horizontal scale of this node relative its parent.
///
/// myNode.scaleX = 5.0;
double get scaleX => _scaleX;
void set scaleX(double scaleX) {
assert(scaleX != null);
_scaleX = scaleX;
invalidateTransformMatrix();
}
/// The vertical scale of this node relative its parent.
///
/// myNode.scaleY = 5.0;
double get scaleY => _scaleY;
void set scaleY(double scaleY) {
assert(scaleY != null);
_scaleY = scaleY;
invalidateTransformMatrix();
}
/// A list of the children of this node.
///
/// This list should only be modified by using the [addChild] and [removeChild] methods.
///
/// // Iterate over a nodes children
/// for (Node child in myNode.children) {
/// // Do something with the child
/// }
List<Node> get children {
_sortChildren();
return _children;
}
// Adding and removing children
/// Adds a child to this node.
///
/// The same node cannot be added to multiple nodes.
///
/// addChild(new Sprite(myImage));
void addChild(Node child) {
assert(child != null);
assert(child._parent == null);
_childrenNeedSorting = true;
_children.add(child);
child._parent = this;
child._spriteBox = this._spriteBox;
_childrenLastAddedOrder += 1;
child._addedOrder = _childrenLastAddedOrder;
if (_spriteBox != null) _spriteBox._registerNode(child);
}
/// Removes a child from this node.
///
/// removeChild(myChildNode);
void removeChild(Node child) {
assert(child != null);
if (_children.remove(child)) {
child._parent = null;
child._spriteBox = null;
if (_spriteBox != null) _spriteBox._deregisterNode(child);
}
}
/// Removes this node from its parent node.
///
/// removeFromParent();
void removeFromParent() {
assert(_parent != null);
_parent.removeChild(this);
}
/// Removes all children of this node.
///
/// removeAllChildren();
void removeAllChildren() {
for (Node child in _children) {
child._parent = null;
child._spriteBox = null;
}
_children = [];
_childrenNeedSorting = false;
if (_spriteBox != null) _spriteBox._deregisterNode(null);
}
void _sortChildren() {
// Sort children primarily by zPosition, secondarily by added order
if (_childrenNeedSorting) {
_children.sort((Node a, Node b) {
if (a._zPosition == b._zPosition) {
return a._addedOrder - b._addedOrder;
}
else if (a._zPosition > b._zPosition) {
return 1;
}
else {
return -1;
}
});
_childrenNeedSorting = false;
}
}
// Calculating the transformation matrix
/// The transformMatrix describes the transformation from the node's parent.
///
/// You cannot set the transformMatrix directly, instead use the position, rotation and scale properties.
///
/// Matrix4 matrix = myNode.transformMatrix;
Matrix4 get transformMatrix {
if (_transformMatrix == null) {
_transformMatrix = computeTransformMatrix();
}
return _transformMatrix;
}
/// Computes the transformation matrix of this node. This method can be
/// overriden if a custom matrix is required. There is usually no reason to
/// call this method directly.
Matrix4 computeTransformMatrix() {
double cx, sx, cy, sy;
if (_rotation == 0.0) {
cx = 1.0;
sx = 0.0;
cy = 1.0;
sy = 0.0;
}
else {
double radiansX = convertDegrees2Radians(_rotation);
double radiansY = convertDegrees2Radians(_rotation);
cx = math.cos(radiansX);
sx = math.sin(radiansX);
cy = math.cos(radiansY);
sy = math.sin(radiansY);
}
// Create transformation matrix for scale, position and rotation
Matrix4 matrix = new Matrix4(cy * _scaleX, sy * _scaleX, 0.0, 0.0,
-sx * _scaleY, cx * _scaleY, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
_position.x, _position.y, 0.0, 1.0);
if (_skewX != 0.0 || _skewY != 0.0) {
// Needs skew transform
Matrix4 skew = new Matrix4(1.0, math.tan(radians(_skewX)), 0.0, 0.0,
math.tan(radians(_skewY)), 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0);
matrix.multiply(skew);
}
return matrix;
}
/// Invalidates the current transform matrix. If the [computeTransformMatrix]
/// method is overidden, this method should be called whenever a property
/// changes that affects the matrix.
void invalidateTransformMatrix() {
_transformMatrix = null;
_invalidateToBoxTransformMatrix();
}
void _invalidateToBoxTransformMatrix () {
_transformMatrixNodeToBox = null;
_transformMatrixBoxToNode = null;
for (Node child in children) {
child._invalidateToBoxTransformMatrix();
}
}
// Transforms to other nodes
Matrix4 _nodeToBoxMatrix() {
assert(_spriteBox != null);
if (_transformMatrixNodeToBox != null) {
return _transformMatrixNodeToBox;
}
if (_parent == null) {
// Base case, we are at the top
assert(this == _spriteBox.rootNode);
_transformMatrixNodeToBox = new Matrix4.copy(_spriteBox.transformMatrix).multiply(transformMatrix);
}
else {
_transformMatrixNodeToBox = new Matrix4.copy(_parent._nodeToBoxMatrix()).multiply(transformMatrix);
}
return _transformMatrixNodeToBox;
}
Matrix4 _boxToNodeMatrix() {
assert(_spriteBox != null);
if (_transformMatrixBoxToNode != null) {
return _transformMatrixBoxToNode;
}
_transformMatrixBoxToNode = new Matrix4.copy(_nodeToBoxMatrix());
_transformMatrixBoxToNode.invert();
return _transformMatrixBoxToNode;
}
/// Converts a point from the coordinate system of the [SpriteBox] to the local coordinate system of the node.
///
/// This method is particularly useful when handling pointer events and need the pointers position in a local
/// coordinate space.
///
/// Point localPoint = myNode.convertPointToNodeSpace(pointInBoxCoordinates);
Point convertPointToNodeSpace(Point boxPoint) {
assert(boxPoint != null);
assert(_spriteBox != null);
Vector4 v =_boxToNodeMatrix().transform(new Vector4(boxPoint.x, boxPoint.y, 0.0, 1.0));
return new Point(v[0], v[1]);
}
/// Converts a point from the local coordinate system of the node to the coordinate system of the [SpriteBox].
///
/// Point pointInBoxCoordinates = myNode.convertPointToBoxSpace(localPoint);
Point convertPointToBoxSpace(Point nodePoint) {
assert(nodePoint != null);
assert(_spriteBox != null);
Vector4 v =_nodeToBoxMatrix().transform(new Vector4(nodePoint.x, nodePoint.y, 0.0, 1.0));
return new Point(v[0], v[1]);
}
/// Converts a [point] from another [node]s coordinate system into the local coordinate system of this node.
///
/// Point pointInNodeASpace = nodeA.convertPointFromNode(pointInNodeBSpace, nodeB);
Point convertPointFromNode(Point point, Node node) {
assert(node != null);
assert(point != null);
assert(_spriteBox != null);
assert(_spriteBox == node._spriteBox);
Point boxPoint = node.convertPointToBoxSpace(point);
Point localPoint = convertPointToNodeSpace(boxPoint);
return localPoint;
}
// Hit test
/// Returns true if the [point] is inside the node, the [point] is in the local coordinate system of the node.
///
/// myNode.isPointInside(localPoint);
///
/// [NodeWithSize] provides a basic bounding box check for this method, if you require a more detailed check this
/// method can be overridden.
///
/// bool isPointInside (Point nodePoint) {
/// double minX = -size.width * pivot.x;
/// double minY = -size.height * pivot.y;
/// double maxX = minX + size.width;
/// double maxY = minY + size.height;
/// return (nodePoint.x >= minX && nodePoint.x < maxX &&
/// nodePoint.y >= minY && nodePoint.y < maxY);
/// }
bool isPointInside(Point point) {
assert(point != null);
return false;
}
// Rendering
void _visit(PaintingCanvas canvas, Matrix4 totalMatrix) {
assert(canvas != null);
if (!visible) return;
_prePaint(canvas, totalMatrix);
_visitChildren(canvas, totalMatrix);
_postPaint(canvas, totalMatrix);
}
void _prePaint(PaintingCanvas canvas, Matrix4 matrix) {
_savedTotalMatrix = new Matrix4.copy(matrix);
// Get the transformation matrix and apply transform
matrix.multiply(transformMatrix);
}
/// Paints this node to the canvas.
///
/// Subclasses, such as [Sprite], override this method to do the actual painting of the node. To do custom
/// drawing override this method and make calls to the [canvas] object. All drawing is done in the node's local
/// coordinate system, relative to the node's position. If you want to make the drawing relative to the node's
/// bounding box's origin, override [NodeWithSize] and call the applyTransformForPivot method before making calls for
/// drawing.
///
/// void paint(PaintingCanvas canvas) {
/// canvas.save();
/// applyTransformForPivot(canvas);
///
/// // Do painting here
///
/// canvas.restore();
/// }
void paint(PaintingCanvas canvas) {
}
void _visitChildren(PaintingCanvas canvas, Matrix4 totalMatrix) {
// Sort children if needed
_sortChildren();
int i = 0;
// Visit children behind this node
while (i < _children.length) {
Node child = _children[i];
if (child.zPosition >= 0.0) break;
child._visit(canvas, totalMatrix);
i++;
}
// Paint this node
canvas.setMatrix(totalMatrix.storage);
paint(canvas);
// Visit children in front of this node
while (i < _children.length) {
Node child = _children[i];
child._visit(canvas, totalMatrix);
i++;
}
}
void _postPaint(PaintingCanvas canvas, Matrix4 totalMatrix) {
totalMatrix.setFrom(_savedTotalMatrix);
}
// Receiving update calls
/// Called before a frame is drawn.
///
/// Override this method to do any updates to the node or node tree before it's drawn to screen.
///
/// // Make the node rotate at a fixed speed
/// void update(double dt) {
/// rotation = rotation * 10.0 * dt;
/// }
void update(double dt) {
}
/// Called whenever the [SpriteBox] is modified or resized, or if the device is rotated.
///
/// Override this method to do any updates that may be necessary to correctly display the node or node tree with the
/// new layout of the [SpriteBox].
///
/// void spriteBoxPerformedLayout() {
/// // Move some stuff around here
/// }
void spriteBoxPerformedLayout() {
}
// Handling user interaction
/// The node will receive user interactions, such as pointer (touch or mouse) events.
///
/// class MyCustomNode extends NodeWithSize {
/// userInteractionEnabled = true;
/// }
bool get userInteractionEnabled => _userInteractionEnabled;
void set userInteractionEnabled(bool userInteractionEnabled) {
_userInteractionEnabled = userInteractionEnabled;
if (_spriteBox != null) _spriteBox._eventTargets = null;
}
/// Handles an event, such as a pointer (touch or mouse) event.
///
/// Override this method to handle events. The node will only receive events if the [userInteractionEnabled] property
/// is set to true and the [isPointInside] method returns true for the position of the pointer down event (default
/// behavior provided by [NodeWithSize]). Unless [handleMultiplePointers] is set to true, the node will only receive
/// events for the first pointer that is down.
///
/// Return true if the node has consumed the event, if an event is consumed it will not be passed on to nodes behind
/// the current node.
///
/// // MyTouchySprite gets transparent when we touch it
/// class MyTouchySprite extends Sprite {
///
/// MyTouchySprite(Image img) : super (img) {
/// userInteractionEnabled = true;
/// }
///
/// bool handleEvent(SpriteBoxEvent event) {
/// if (event.type == 'pointerdown) {
/// opacity = 0.5;
/// }
/// else if (event.type == 'pointerup') {
/// opacity = 1.0;
/// }
/// return true;
/// }
/// }
bool handleEvent(SpriteBoxEvent event) {
return false;
}
// Physics
PhysicsBody _physicsBody;
PhysicsBody get physicsBody => _physicsBody;
set physicsBody(PhysicsBody physicsBody) {
if (parent != null) {
assert(parent is PhysicsNode);
if (physicsBody == null) {
physicsBody._detach();
} else {
physicsBody._attach(parent, this);
}
}
_physicsBody = physicsBody;
}
}

View File

@@ -0,0 +1,58 @@
part of flutter_sprites;
/// An node that transforms its children using a 3D perspective projection. This
/// node type can be used to create 3D flips and other similar effects.
///
/// var myNode3D = new Node3D();
/// myNode3D.rotationY = 45.0;
/// myNode3D.addChild(new Sprite(myTexture));
class Node3D extends Node {
double _rotationX = 0.0;
/// The node's rotation around the x axis in degrees.
double get rotationX => _rotationX;
set rotationX(double rotationX) {
_rotationX = rotationX;
invalidateTransformMatrix();
}
double _rotationY = 0.0;
/// The node's rotation around the y axis in degrees.
double get rotationY => _rotationY;
set rotationY(double rotationY) {
_rotationY = rotationY;
invalidateTransformMatrix();
}
double _projectionDepth = 500.0;
/// The projection depth. Default value is 500.0.
double get projectionDepth => _projectionDepth;
set projectionDepth(double projectionDepth) {
_projectionDepth = projectionDepth;
invalidateTransformMatrix();
}
Matrix4 computeTransformMatrix() {
// Apply normal 2d transforms
Matrix4 matrix = super.computeTransformMatrix();
// Apply perspective projection
Matrix4 projection = new Matrix4(1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, -1.0/_projectionDepth,
0.0, 0.0, 0.0, 1.0);
matrix = matrix.multiply(projection);
// Rotate around x and y axis
matrix.rotateY(radians(_rotationY));
matrix.rotateX(radians(_rotationX));
return matrix;
}
}

View File

@@ -0,0 +1,60 @@
part of flutter_sprites;
/// The super class of any [Node] that has a size.
///
/// NodeWithSize adds the ability for a node to have a size and a pivot point.
class NodeWithSize extends Node {
/// Changing the size will affect the size of the rendering of the node.
///
/// myNode.size = new Size(1024.0, 1024.0);
Size size;
/// The normalized point which the node is transformed around.
///
/// // Position myNode from is middle top
/// myNode.pivot = new Point(0.5, 0.0);
Point pivot;
/// Creates a new NodeWithSize.
///
/// The default [size] is zero and the default [pivot] point is the origin. Subclasses may change the default values.
///
/// var myNodeWithSize = new NodeWithSize(new Size(1024.0, 1024.0));
NodeWithSize(Size this.size) {
if (size == null) size = Size.zero;
pivot = Point.origin;
}
/// Call this method in your [paint] method if you want the origin of your drawing to be the top left corner of the
/// node's bounding box.
///
/// If you use this method you will need to save and restore your canvas at the beginning and
/// end of your [paint] method.
///
/// void paint(PaintingCanvas canvas) {
/// canvas.save();
/// applyTransformForPivot(canvas);
///
/// // Do painting here
///
/// canvas.restore();
/// }
void applyTransformForPivot(PaintingCanvas canvas) {
if (pivot.x != 0 || pivot.y != 0) {
double pivotInPointsX = size.width * pivot.x;
double pivotInPointsY = size.height * pivot.y;
canvas.translate(-pivotInPointsX, -pivotInPointsY);
}
}
bool isPointInside (Point nodePoint) {
double minX = -size.width * pivot.x;
double minY = -size.height * pivot.y;
double maxX = minX + size.width;
double maxY = minY + size.height;
return (nodePoint.x >= minX && nodePoint.x < maxX &&
nodePoint.y >= minY && nodePoint.y < maxY);
}
}

View File

@@ -0,0 +1,446 @@
part of flutter_sprites;
class _Particle {
Vector2 pos;
Vector2 startPos;
double colorPos = 0.0;
double deltaColorPos = 0.0;
double size = 0.0;
double deltaSize = 0.0;
double rotation = 0.0;
double deltaRotation = 0.0;
double timeToLive = 0.0;
Vector2 dir;
_ParticleAccelerations accelerations;
Float64List simpleColorSequence;
ColorSequence colorSequence;
}
class _ParticleAccelerations {
double radialAccel = 0.0;
double tangentialAccel = 0.0;
}
/// A particle system uses a large number of sprites to draw complex effects
/// such as explosions, smoke, rain, or fire. There are a number of properties
/// that can be set to control the look of the particle system. Most of the
/// properties have a base value and a variance, these values are used when
/// creating each individual particle. For instance, by setting the [life] to
/// 1.0 and the [lifeVar] to 0.5, each particle will get a life time in the
/// range of 0.5 to 1.5.
///
/// Particles are created and added to the system at [emissionRate], but the
/// number of particles can never exceed the [maxParticles] limit.
class ParticleSystem extends Node {
/// The texture used to draw each individual sprite.
Texture texture;
/// The time in seconds each particle will be alive.
double life;
/// Variance of the [life] property.
double lifeVar;
/// The variance of a particles initial position.
Point posVar;
/// The start scale of each individual particle.
double startSize;
/// Variance of the [startSize] property.
double startSizeVar;
/// The end scale of each individual particle.
double endSize;
/// Variance of the [endSize] property.
double endSizeVar;
/// The start rotation of each individual particle.
double startRotation;
/// Variance of the [startRotation] property.
double startRotationVar;
/// The end rotation of each individual particle.
double endRotation;
/// Variance of the [endRotation] property.
double endRotationVar;
/// If true, each particle will be rotated to the direction of the movement
/// of the particle. The calculated rotation will be added to the current
/// rotation as calculated by the [startRotation] and [endRotation]
/// properties.
bool rotateToMovement;
/// The direction in which each particle will be emitted in degrees.
double direction;
/// Variance of the [direction] property.
double directionVar;
/// The speed at which each particle will be emitted.
double speed;
/// Variance of the [direction] property.
double speedVar;
/// The radial acceleration of each induvidual particle.
double radialAcceleration;
/// Variance of the [radialAcceleration] property.
double radialAccelerationVar;
/// The tangential acceleration of each individual particle.
double tangentialAcceleration;
/// Variance of the [tangentialAcceleration] property.
double tangentialAccelerationVar;
/// The gravity vector of the particle system.
Vector2 gravity;
/// The maximum number of particles the system can display at a single time.
int maxParticles;
/// Total number of particles to emit, if the value is set to 0 the system
/// will continue to emit particles for an indifinte period of time.
int numParticlesToEmit;
/// The rate at which particles are emitted, defined in particles per second.
double emissionRate;
/// If set to true, the particle system will be automatically removed as soon
/// as there are no more particles left to draw.
bool autoRemoveOnFinish;
/// The [ColorSequence] used to animate the color of each individual particle
/// over the duration of its [life]. When applied to a particle the sequence's
/// color stops modified in accordance with the [alphaVar], [redVar],
/// [greenVar], and [blueVar] properties.
ColorSequence colorSequence;
/// Alpha varience of the [colorSequence] property.
int alphaVar;
/// Red varience of the [colorSequence] property.
int redVar;
/// Green varience of the [colorSequence] property.
int greenVar;
/// Blue varience of the [colorSequence] property.
int blueVar;
/// The transfer mode used to draw the particle system. Default is
/// [TransferMode.plus].
ui.TransferMode transferMode;
List<_Particle> _particles;
double _emitCounter;
int _numEmittedParticles = 0;
static Paint _paint = new Paint()
..filterQuality = ui.FilterQuality.low
..isAntiAlias = false;
ParticleSystem(this.texture,
{this.life: 1.5,
this.lifeVar: 1.0,
this.posVar: Point.origin,
this.startSize: 2.5,
this.startSizeVar: 0.5,
this.endSize: 0.0,
this.endSizeVar: 0.0,
this.startRotation: 0.0,
this.startRotationVar: 0.0,
this.endRotation: 0.0,
this.endRotationVar: 0.0,
this.rotateToMovement : false,
this.direction: 0.0,
this.directionVar: 360.0,
this.speed: 100.0,
this.speedVar: 50.0,
this.radialAcceleration: 0.0,
this.radialAccelerationVar: 0.0,
this.tangentialAcceleration: 0.0,
this.tangentialAccelerationVar: 0.0,
this.gravity,
this.maxParticles: 100,
this.emissionRate: 50.0,
this.colorSequence,
this.alphaVar: 0,
this.redVar: 0,
this.greenVar: 0,
this.blueVar: 0,
this.transferMode: ui.TransferMode.plus,
this.numParticlesToEmit: 0,
this.autoRemoveOnFinish: true}) {
_particles = new List<_Particle>();
_emitCounter = 0.0;
// _elapsedTime = 0.0;
if (gravity == null) gravity = new Vector2.zero();
if (colorSequence == null) colorSequence = new ColorSequence.fromStartAndEndColor(new Color(0xffffffff), new Color(0x00ffffff));
}
void update(double dt) {
// TODO: Fix this (it's a temp fix for low framerates)
if (dt > 0.1) dt = 0.1;
// Create new particles
double rate = 1.0 / emissionRate;
if (_particles.length < maxParticles) {
_emitCounter += dt;
}
while(_particles.length < maxParticles
&& _emitCounter > rate
&& (numParticlesToEmit == 0 || _numEmittedParticles < numParticlesToEmit)) {
// Add a new particle
_addParticle();
_emitCounter -= rate;
}
// _elapsedTime += dt;
// Iterate over all particles
for (int i = _particles.length -1; i >= 0; i--) {
_Particle particle = _particles[i];
// Manage life time
particle.timeToLive -= dt;
if (particle.timeToLive <= 0) {
_particles.removeAt(i);
continue;
}
// Update the particle
if (particle.accelerations != null) {
// Radial acceleration
Vector2 radial;
if (particle.pos[0] != 0 || particle.pos[1] != 0) {
radial = new Vector2.copy(particle.pos).normalize();
} else {
radial = new Vector2.zero();
}
Vector2 tangential = new Vector2.copy(radial);
radial.scale(particle.accelerations.radialAccel);
// Tangential acceleration
double newY = tangential.x;
tangential.x = -tangential.y;
tangential.y = newY;
tangential.scale(particle.accelerations.tangentialAccel);
// (gravity + radial + tangential) * dt
Vector2 accel = (gravity + radial + tangential).scale(dt);
particle.dir += accel;
} else if (gravity[0] != 0.0 || gravity[1] != 0) {
// gravity
Vector2 accel = gravity.scale(dt);
particle.dir += accel;
}
// Update particle position
particle.pos[0] += particle.dir[0] * dt;
particle.pos[1] += particle.dir[1] * dt;
// Size
particle.size = math.max(particle.size + particle.deltaSize * dt, 0.0);
// Angle
particle.rotation += particle.deltaRotation * dt;
// Color
if (particle.simpleColorSequence != null) {
for (int i = 0; i < 4; i++) {
particle.simpleColorSequence[i] += particle.simpleColorSequence[i + 4] * dt;
}
} else {
particle.colorPos = math.min(particle.colorPos + particle.deltaColorPos * dt, 1.0);
}
}
if (autoRemoveOnFinish && _particles.length == 0 && _numEmittedParticles > 0) {
if (parent != null) removeFromParent();
}
}
void _addParticle() {
_Particle particle = new _Particle();
// Time to live
particle.timeToLive = math.max(life + lifeVar * randomSignedDouble(), 0.0);
// Position
Point srcPos = Point.origin;
particle.pos = new Vector2(srcPos.x + posVar.x * randomSignedDouble(),
srcPos.y + posVar.y * randomSignedDouble());
// Size
particle.size = math.max(startSize + startSizeVar * randomSignedDouble(), 0.0);
double endSizeFinal = math.max(endSize + endSizeVar * randomSignedDouble(), 0.0);
particle.deltaSize = (endSizeFinal - particle.size) / particle.timeToLive;
// Rotation
particle.rotation = startRotation + startRotationVar * randomSignedDouble();
double endRotationFinal = endRotation + endRotationVar * randomSignedDouble();
particle.deltaRotation = (endRotationFinal - particle.rotation) / particle.timeToLive;
// Direction
double dirRadians = convertDegrees2Radians(direction + directionVar * randomSignedDouble());
Vector2 dirVector = new Vector2(math.cos(dirRadians), math.sin(dirRadians));
double speedFinal = speed + speedVar * randomSignedDouble();
particle.dir = dirVector.scale(speedFinal);
// Accelerations
if (radialAcceleration != 0.0 || radialAccelerationVar != 0.0 ||
tangentialAcceleration != 0.0 || tangentialAccelerationVar != 0.0) {
particle.accelerations = new _ParticleAccelerations();
// Radial acceleration
particle.accelerations.radialAccel = radialAcceleration + radialAccelerationVar * randomSignedDouble();
// Tangential acceleration
particle.accelerations.tangentialAccel = tangentialAcceleration + tangentialAccelerationVar * randomSignedDouble();
}
// Color
particle.colorPos = 0.0;
particle.deltaColorPos = 1.0 / particle.timeToLive;
if (alphaVar != 0 || redVar != 0 || greenVar != 0 || blueVar != 0) {
particle.colorSequence = _ColorSequenceUtil.copyWithVariance(colorSequence, alphaVar, redVar, greenVar, blueVar);
}
// Optimizes the case where there are only two colors in the sequence
if (colorSequence.colors.length == 2) {
Color startColor;
Color endColor;
if (particle.colorSequence != null) {
startColor = particle.colorSequence.colors[0];
endColor = particle.colorSequence.colors[1];
} else {
startColor = colorSequence.colors[0];
endColor = colorSequence.colors[1];
}
// First 4 elements are start ARGB, last 4 are delta ARGB
particle.simpleColorSequence = new Float64List(8);
particle.simpleColorSequence[0] = startColor.alpha.toDouble();
particle.simpleColorSequence[1] = startColor.red.toDouble();
particle.simpleColorSequence[2] = startColor.green.toDouble();
particle.simpleColorSequence[3] = startColor.blue.toDouble();
particle.simpleColorSequence[4] = (endColor.alpha.toDouble() - startColor.alpha.toDouble()) / particle.timeToLive;
particle.simpleColorSequence[5] = (endColor.red.toDouble() - startColor.red.toDouble()) / particle.timeToLive;
particle.simpleColorSequence[6] = (endColor.green.toDouble() - startColor.green.toDouble()) / particle.timeToLive;
particle.simpleColorSequence[7] = (endColor.blue.toDouble() - startColor.blue.toDouble()) / particle.timeToLive;
}
_particles.add(particle);
_numEmittedParticles++;
}
void paint(PaintingCanvas canvas) {
List<ui.RSTransform> transforms = [];
List<Rect> rects = [];
List<Color> colors = [];
_paint.setTransferMode(transferMode);
for (_Particle particle in _particles) {
// Rect
Rect rect = texture.frame;
rects.add(rect);
// Transform
double scos;
double ssin;
if (rotateToMovement) {
double extraRotation = GameMath.atan2(particle.dir[1], particle.dir[0]);
scos = math.cos(convertDegrees2Radians(particle.rotation) + extraRotation) * particle.size;
ssin = math.sin(convertDegrees2Radians(particle.rotation) + extraRotation) * particle.size;
} else if (particle.rotation != 0.0) {
scos = math.cos(convertDegrees2Radians(particle.rotation)) * particle.size;
ssin = math.sin(convertDegrees2Radians(particle.rotation)) * particle.size;
} else {
scos = particle.size;
ssin = 0.0;
}
double ax = rect.width / 2;
double ay = rect.height / 2;
double tx = particle.pos[0] + -scos * ax + ssin * ay;
double ty = particle.pos[1] + -ssin * ax - scos * ay;
ui.RSTransform transform = new ui.RSTransform(scos, ssin, tx, ty);
transforms.add(transform);
// Color
if (particle.simpleColorSequence != null) {
Color particleColor = new Color.fromARGB(
particle.simpleColorSequence[0].toInt().clamp(0, 255),
particle.simpleColorSequence[1].toInt().clamp(0, 255),
particle.simpleColorSequence[2].toInt().clamp(0, 255),
particle.simpleColorSequence[3].toInt().clamp(0, 255));
colors.add(particleColor);
} else {
Color particleColor;
if (particle.colorSequence != null) {
particleColor = particle.colorSequence.colorAtPosition(particle.colorPos);
} else {
particleColor = colorSequence.colorAtPosition(particle.colorPos);
}
colors.add(particleColor);
}
}
canvas.drawAtlas(texture.image, transforms, rects, colors,
ui.TransferMode.modulate, null, _paint);
}
}
class _ColorSequenceUtil {
static ColorSequence copyWithVariance(
ColorSequence sequence,
int alphaVar,
int redVar,
int greenVar,
int blueVar
) {
ColorSequence copy = new ColorSequence.copy(sequence);
int i = 0;
for (Color color in sequence.colors) {
int aDelta = ((randomDouble() * 2.0 - 1.0) * alphaVar).toInt();
int rDelta = ((randomDouble() * 2.0 - 1.0) * redVar).toInt();
int gDelta = ((randomDouble() * 2.0 - 1.0) * greenVar).toInt();
int bDelta = ((randomDouble() * 2.0 - 1.0) * blueVar).toInt();
int aNew = (color.alpha + aDelta).clamp(0, 255);
int rNew = (color.red + rDelta).clamp(0, 255);
int gNew = (color.green + gDelta).clamp(0, 255);
int bNew = (color.blue + bDelta).clamp(0, 255);
copy.colors[i] = new Color.fromARGB(aNew, rNew, gNew, bNew);
i++;
}
return copy;
}
}

View File

@@ -0,0 +1,369 @@
part of flutter_sprites;
enum PhysicsBodyType {
static,
dynamic
}
class PhysicsBody {
PhysicsBody(this.shape, {
this.tag: null,
this.type: PhysicsBodyType.dynamic,
double density: 1.0,
double friction: 0.0,
double restitution: 0.0,
bool isSensor: false,
Offset linearVelocity: Offset.zero,
double angularVelocity: 0.0,
this.linearDampening: 0.0,
double angularDampening: 0.0,
bool allowSleep: true,
bool awake: true,
bool fixedRotation: false,
bool bullet: false,
bool active: true,
this.gravityScale: 1.0
}) {
this.density = density;
this.friction = friction;
this.restitution = restitution;
this.isSensor = isSensor;
this.linearVelocity = linearVelocity;
this.angularVelocity = angularVelocity;
this.angularDampening = angularDampening;
this.allowSleep = allowSleep;
this.awake = awake;
this.fixedRotation = fixedRotation;
this.bullet = bullet;
this.active = active;
}
Object tag;
final PhysicsShape shape;
PhysicsBodyType type;
double _density;
double get density => _density;
set density(double density) {
_density = density;
if (_body == null)
return;
for (box2d.Fixture f = _body.getFixtureList(); f != null; f = f.getNext()) {
f.setDensity(density);
}
}
double _friction;
double get friction => _friction;
set friction(double friction) {
_friction = friction;
if (_body == null)
return;
for (box2d.Fixture f = _body.getFixtureList(); f != null; f = f.getNext()) {
f.setFriction(friction);
}
}
double _restitution;
double get restitution => _restitution;
set restitution(double restitution) {
_restitution = restitution;
if (_body == null)
return;
for (box2d.Fixture f = _body.getFixtureList(); f != null; f = f.getNext()) {
f.setRestitution(restitution);
}
}
bool _isSensor;
bool get isSensor => _isSensor;
set isSensor(bool isSensor) {
_isSensor = isSensor;
if (_body == null)
return;
for (box2d.Fixture f = _body.getFixtureList(); f != null; f = f.getNext()) {
f.setSensor(isSensor);
}
}
Offset _linearVelocity;
Offset get linearVelocity {
if (_body == null)
return _linearVelocity;
else {
double dx = _body.linearVelocity.x * _physicsNode.b2WorldToNodeConversionFactor;
double dy = _body.linearVelocity.y * _physicsNode.b2WorldToNodeConversionFactor;
return new Offset(dx, dy);
}
}
set linearVelocity(Offset linearVelocity) {
_linearVelocity = linearVelocity;
if (_body != null) {
Vector2 vec = new Vector2(
linearVelocity.dx / _physicsNode.b2WorldToNodeConversionFactor,
linearVelocity.dy / _physicsNode.b2WorldToNodeConversionFactor
);
_body.linearVelocity = vec;
}
}
double _angularVelocity;
double get angularVelocity {
if (_body == null)
return _angularVelocity;
else
return _body.angularVelocity;
}
set angularVelocity(double angularVelocity) {
_angularVelocity = angularVelocity;
if (_body != null) {
_body.angularVelocity = angularVelocity;
}
}
// TODO: Should this be editable in box2d.Body ?
final double linearDampening;
double _angularDampening;
double get angularDampening => _angularDampening;
set angularDampening(double angularDampening) {
_angularDampening = angularDampening;
if (_body != null)
_body.angularDamping = angularDampening;
}
bool _allowSleep;
bool get allowSleep => _allowSleep;
set allowSleep(bool allowSleep) {
_allowSleep = allowSleep;
if (_body != null)
_body.setSleepingAllowed(allowSleep);
}
bool _awake;
bool get awake {
if (_body != null)
return _body.isAwake();
else
return _awake;
}
set awake(bool awake) {
_awake = awake;
if (_body != null)
_body.setAwake(awake);
}
bool _fixedRotation;
bool get fixedRotation => _fixedRotation;
set fixedRotation(bool fixedRotation) {
_fixedRotation = fixedRotation;
if (_body != null)
_body.setFixedRotation(fixedRotation);
}
bool _bullet;
bool get bullet => _bullet;
set bullet(bool bullet) {
_bullet = bullet;
if (_body != null) {
_body.setBullet(bullet);
}
}
bool _active;
bool get active {
if (_body != null)
return _body.isActive();
else
return _active;
}
set active(bool active) {
_active = active;
if (_body != null)
_body.setActive(active);
}
double gravityScale;
PhysicsNode _physicsNode;
Node _node;
box2d.Body _body;
List<PhysicsJoint> _joints = [];
bool _attached = false;
void applyForce(Offset force, Point worldPoint) {
assert(_body != null);
Vector2 b2Force = new Vector2(
force.dx / _physicsNode.b2WorldToNodeConversionFactor,
force.dy / _physicsNode.b2WorldToNodeConversionFactor);
Vector2 b2Point = new Vector2(
worldPoint.x / _physicsNode.b2WorldToNodeConversionFactor,
worldPoint.y / _physicsNode.b2WorldToNodeConversionFactor
);
_body.applyForce(b2Force, b2Point);
}
void applyForceToCenter(Offset force) {
assert(_body != null);
Vector2 b2Force = new Vector2(
force.dx / _physicsNode.b2WorldToNodeConversionFactor,
force.dy / _physicsNode.b2WorldToNodeConversionFactor);
_body.applyForceToCenter(b2Force);
}
void applyTorque(double torque) {
assert(_body != null);
_body.applyTorque(torque / _physicsNode.b2WorldToNodeConversionFactor);
}
void applyLinearImpulse(Offset impulse, Point worldPoint, [bool wake = true]) {
assert(_body != null);
Vector2 b2Impulse = new Vector2(
impulse.dx / _physicsNode.b2WorldToNodeConversionFactor,
impulse.dy / _physicsNode.b2WorldToNodeConversionFactor);
Vector2 b2Point = new Vector2(
worldPoint.x / _physicsNode.b2WorldToNodeConversionFactor,
worldPoint.y / _physicsNode.b2WorldToNodeConversionFactor
);
_body.applyLinearImpulse(b2Impulse, b2Point, wake);
}
void applyAngularImpulse(double impulse) {
assert(_body != null);
_body.applyAngularImpulse(impulse / _physicsNode.b2WorldToNodeConversionFactor);
}
void _attach(PhysicsNode physicsNode, Node node) {
assert(_attached == false);
// Create BodyDef
box2d.BodyDef bodyDef = new box2d.BodyDef();
bodyDef.linearVelocity = new Vector2(linearVelocity.dx, linearVelocity.dy);
bodyDef.angularVelocity = angularVelocity;
bodyDef.linearDamping = linearDampening;
bodyDef.angularDamping = angularDampening;
bodyDef.allowSleep = allowSleep;
bodyDef.awake = awake;
bodyDef.fixedRotation = fixedRotation;
bodyDef.bullet = bullet;
bodyDef.active = active;
bodyDef.gravityScale = gravityScale;
if (type == PhysicsBodyType.dynamic)
bodyDef.type = box2d.BodyType.DYNAMIC;
else
bodyDef.type = box2d.BodyType.STATIC;
double conv = physicsNode.b2WorldToNodeConversionFactor;
bodyDef.position = new Vector2(node.position.x / conv, node.position.y / conv);
bodyDef.angle = radians(node.rotation);
// Create Body
_body = physicsNode.b2World.createBody(bodyDef);
// Create FixtureDef
box2d.FixtureDef fixtureDef = new box2d.FixtureDef();
fixtureDef.friction = friction;
fixtureDef.restitution = restitution;
fixtureDef.density = density;
fixtureDef.isSensor = isSensor;
// Get shapes
List<box2d.Shape> b2Shapes = [];
List<PhysicsShape> physicsShapes = [];
_addB2Shapes(physicsNode, shape, b2Shapes, physicsShapes);
// Create fixtures
for (int i = 0; i < b2Shapes.length; i++) {
box2d.Shape b2Shape = b2Shapes[i];
PhysicsShape physicsShape = physicsShapes[i];
fixtureDef.shape = b2Shape;
box2d.Fixture fixture = _body.createFixtureFromFixtureDef(fixtureDef);
fixture.userData = physicsShape;
}
_body.userData = this;
_physicsNode = physicsNode;
_node = node;
_attached = true;
// Attach any joints
for (PhysicsJoint joint in _joints) {
if (joint.bodyA._attached && joint.bodyB._attached) {
joint._attach(physicsNode);
}
}
}
void _detach() {
if (_attached) {
_physicsNode._bodiesScheduledForDestruction.add(_body);
_attached = false;
}
}
void _addB2Shapes(PhysicsNode physicsNode, PhysicsShape shape, List<box2d.Shape> b2Shapes, List<PhysicsShape> physicsShapes) {
if (shape is PhysicsShapeGroup) {
for (PhysicsShape child in shape.shapes) {
_addB2Shapes(physicsNode, child, b2Shapes, physicsShapes);
}
} else {
b2Shapes.add(shape.getB2Shape(physicsNode));
physicsShapes.add(shape);
}
}
}

View File

@@ -0,0 +1,364 @@
part of flutter_sprites;
typedef void PhysicsJointBreakCallback(PhysicsJoint joint);
abstract class PhysicsJoint {
PhysicsJoint(this._bodyA, this._bodyB, this.breakingForce, this.breakCallback) {
bodyA._joints.add(this);
bodyB._joints.add(this);
}
PhysicsBody _bodyA;
PhysicsBody get bodyA => _bodyA;
PhysicsBody _bodyB;
PhysicsBody get bodyB => _bodyB;
final double breakingForce;
final PhysicsJointBreakCallback breakCallback;
bool _active = true;
box2d.Joint _joint;
PhysicsNode _physicsNode;
void _completeCreation() {
if (bodyA._attached && bodyB._attached) {
_attach(bodyA._physicsNode);
}
}
void _attach(PhysicsNode physicsNode) {
if (_joint == null) {
_physicsNode = physicsNode;
_joint = _createB2Joint(physicsNode);
_physicsNode._joints.add(this);
}
}
void _detach() {
if (_joint != null && _active) {
_physicsNode.b2World.destroyJoint(_joint);
_joint = null;
_physicsNode._joints.remove(this);
}
_active = false;
}
box2d.Joint _createB2Joint(PhysicsNode physicsNode);
void destroy() {
_detach();
}
void _checkBreakingForce(double dt) {
if (breakingForce == null) return;
if (_joint != null && _active) {
Vector2 reactionForce = new Vector2.zero();
_joint.getReactionForce(1.0 / dt, reactionForce);
if (breakingForce * breakingForce < reactionForce.length2) {
// Destroy the joint
destroy();
// Notify any observer
if (breakCallback != null)
breakCallback(this);
}
}
}
}
class PhysicsJointRevolute extends PhysicsJoint {
PhysicsJointRevolute(
PhysicsBody bodyA,
PhysicsBody bodyB,
this._worldAnchor, {
this.lowerAngle: 0.0,
this.upperAngle: 0.0,
this.enableLimit: false,
PhysicsJointBreakCallback breakCallback,
double breakingForce
}) : super(bodyA, bodyB, breakingForce, breakCallback) {
_completeCreation();
}
final Point _worldAnchor;
final double lowerAngle;
final double upperAngle;
final bool enableLimit;
box2d.Joint _createB2Joint(PhysicsNode physicsNode) {
// Create Joint Definition
Vector2 vecAnchor = new Vector2(
_worldAnchor.x / physicsNode.b2WorldToNodeConversionFactor,
_worldAnchor.y / physicsNode.b2WorldToNodeConversionFactor
);
box2d.RevoluteJointDef b2Def = new box2d.RevoluteJointDef();
b2Def.initialize(bodyA._body, bodyB._body, vecAnchor);
b2Def.enableLimit = enableLimit;
b2Def.lowerAngle = lowerAngle;
b2Def.upperAngle = upperAngle;
// Create joint
return physicsNode.b2World.createJoint(b2Def);
}
}
class PhysicsJointPrismatic extends PhysicsJoint {
PhysicsJointPrismatic(
PhysicsBody bodyA,
PhysicsBody bodyB,
this.axis, {
double breakingForce,
PhysicsJointBreakCallback breakCallback
}
) : super(bodyA, bodyB, breakingForce, breakCallback) {
_completeCreation();
}
Offset axis;
box2d.Joint _createB2Joint(PhysicsNode physicsNode) {
box2d.PrismaticJointDef b2Def = new box2d.PrismaticJointDef();
b2Def.initialize(bodyA._body, bodyB._body, bodyA._body.position, new Vector2(axis.dx, axis.dy));
return physicsNode.b2World.createJoint(b2Def);
}
}
class PhysicsJointWeld extends PhysicsJoint {
PhysicsJointWeld(
PhysicsBody bodyA,
PhysicsBody bodyB, {
double breakingForce,
PhysicsJointBreakCallback breakCallback,
this.dampening: 0.0,
this.frequency: 0.0
}
) : super(bodyA, bodyB, breakingForce, breakCallback) {
_completeCreation();
}
final double dampening;
final double frequency;
box2d.Joint _createB2Joint(PhysicsNode physicsNode) {
box2d.WeldJointDef b2Def = new box2d.WeldJointDef();
Vector2 middle = new Vector2(
(bodyA._body.position.x + bodyB._body.position.x) / 2.0,
(bodyA._body.position.y + bodyB._body.position.y) / 2.0
);
b2Def.initialize(bodyA._body, bodyB._body, middle);
b2Def.dampingRatio = dampening;
b2Def.frequencyHz = frequency;
return physicsNode.b2World.createJoint(b2Def);
}
}
class PhysicsJointPulley extends PhysicsJoint {
PhysicsJointPulley(
PhysicsBody bodyA,
PhysicsBody bodyB,
this.groundAnchorA,
this.groundAnchorB,
this.anchorA,
this.anchorB,
this.ratio, {
double breakingForce,
PhysicsJointBreakCallback breakCallback
}
) : super(bodyA, bodyB, breakingForce, breakCallback) {
_completeCreation();
}
final Point groundAnchorA;
final Point groundAnchorB;
final Point anchorA;
final Point anchorB;
final double ratio;
box2d.Joint _createB2Joint(PhysicsNode physicsNode) {
box2d.PulleyJointDef b2Def = new box2d.PulleyJointDef();
b2Def.initialize(
bodyA._body,
bodyB._body,
_convertPosToVec(groundAnchorA, physicsNode),
_convertPosToVec(groundAnchorB, physicsNode),
_convertPosToVec(anchorA, physicsNode),
_convertPosToVec(anchorB, physicsNode),
ratio
);
return physicsNode.b2World.createJoint(b2Def);
}
}
class PhysicsJointGear extends PhysicsJoint {
PhysicsJointGear(
PhysicsBody bodyA,
PhysicsBody bodyB, {
double breakingForce,
PhysicsJointBreakCallback breakCallback,
this.ratio: 0.0
}
) : super(bodyA, bodyB, breakingForce, breakCallback) {
_completeCreation();
}
final double ratio;
box2d.Joint _createB2Joint(PhysicsNode physicsNode) {
box2d.GearJointDef b2Def = new box2d.GearJointDef();
b2Def.bodyA = bodyA._body;
b2Def.bodyB = bodyB._body;
b2Def.ratio = ratio;
return physicsNode.b2World.createJoint(b2Def);
}
}
class PhysicsJointDistance extends PhysicsJoint {
PhysicsJointDistance(
PhysicsBody bodyA,
PhysicsBody bodyB,
this.anchorA,
this.anchorB, {
double breakingForce,
PhysicsJointBreakCallback breakCallback,
this.length,
this.dampening: 0.0,
this.frequency: 0.0
}
) : super(bodyA, bodyB, breakingForce, breakCallback) {
_completeCreation();
}
final Point anchorA;
final Point anchorB;
final double length;
final double dampening;
final double frequency;
box2d.Joint _createB2Joint(PhysicsNode physicsNode) {
box2d.DistanceJointDef b2Def = new box2d.DistanceJointDef();
b2Def.initialize(
bodyA._body,
bodyB._body,
_convertPosToVec(anchorA, physicsNode),
_convertPosToVec(anchorB, physicsNode)
);
b2Def.dampingRatio = dampening;
b2Def.frequencyHz = frequency;
if (length != null)
b2Def.length = length / physicsNode.b2WorldToNodeConversionFactor;
return physicsNode.b2World.createJoint(b2Def);
}
}
class PhysicsJointWheel extends PhysicsJoint {
PhysicsJointWheel(
PhysicsBody bodyA,
PhysicsBody bodyB,
this.anchor,
this.axis, {
double breakingForce,
PhysicsJointBreakCallback breakCallback,
this.dampening: 0.0,
this.frequency: 0.0
}
) : super(bodyA, bodyB, breakingForce, breakCallback) {
_completeCreation();
}
final Point anchor;
final Offset axis;
final double dampening;
final double frequency;
box2d.Joint _createB2Joint(PhysicsNode physicsNode) {
box2d.WheelJointDef b2Def = new box2d.WheelJointDef();
b2Def.initialize(
bodyA._body,
bodyB._body,
_convertPosToVec(anchor, physicsNode),
new Vector2(axis.dx, axis.dy)
);
b2Def.dampingRatio = dampening;
b2Def.frequencyHz = frequency;
return physicsNode.b2World.createJoint(b2Def);
}
}
class PhysicsJointFriction extends PhysicsJoint {
PhysicsJointFriction(
PhysicsBody bodyA,
PhysicsBody bodyB,
this.anchor, {
double breakingForce,
PhysicsJointBreakCallback breakCallback,
this.maxForce: 0.0,
this.maxTorque: 0.0
}
) : super(bodyA, bodyB, breakingForce, breakCallback) {
_completeCreation();
}
final Point anchor;
final double maxForce;
final double maxTorque;
box2d.Joint _createB2Joint(PhysicsNode physicsNode) {
box2d.FrictionJointDef b2Def = new box2d.FrictionJointDef();
b2Def.initialize(
bodyA._body,
bodyB._body,
_convertPosToVec(anchor, physicsNode)
);
b2Def.maxForce = maxForce / physicsNode.b2WorldToNodeConversionFactor;
b2Def.maxTorque = maxTorque / physicsNode.b2WorldToNodeConversionFactor;
return physicsNode.b2World.createJoint(b2Def);
}
}
class PhysicsJointConstantVolume extends PhysicsJoint {
PhysicsJointConstantVolume(
this.bodies, {
double breakingForce,
PhysicsJointBreakCallback breakCallback,
this.dampening,
this.frequency
}
) : super(null, null, breakingForce, breakCallback) {
assert(bodies.length > 2);
_bodyA = bodies[0];
_bodyB = bodies[1];
_completeCreation();
}
final List<PhysicsBody> bodies;
final double dampening;
final double frequency;
box2d.Joint _createB2Joint(PhysicsNode physicsNode) {
box2d.ConstantVolumeJointDef b2Def = new box2d.ConstantVolumeJointDef();
for (PhysicsBody body in bodies) {
b2Def.addBody(body._body);
}
b2Def.dampingRatio = dampening;
b2Def.frequencyHz = frequency;
return physicsNode.b2World.createJoint(b2Def);
}
}
Vector2 _convertPosToVec(Point pt, PhysicsNode physicsNode) {
return new Vector2(
pt.x / physicsNode.b2WorldToNodeConversionFactor,
pt.y / physicsNode.b2WorldToNodeConversionFactor
);
}

View File

@@ -0,0 +1,436 @@
part of flutter_sprites;
enum PhysicsContactType {
preSolve,
postSolve,
begin,
end
}
typedef void PhysicsContactCallback(PhysicsContactType type, PhysicsContact contact);
class PhysicsNode extends Node {
PhysicsNode(Offset gravity) {
b2World = new box2d.World.withGravity(
new Vector2(
gravity.dx / b2WorldToNodeConversionFactor,
gravity.dy / b2WorldToNodeConversionFactor));
_init();
}
PhysicsNode.fromB2World(this.b2World, this.b2WorldToNodeConversionFactor) {
_init();
}
void _init() {
_contactHandler = new _ContactHandler(this);
b2World.setContactListener(_contactHandler);
}
box2d.World b2World;
_ContactHandler _contactHandler;
List<PhysicsJoint> _joints = [];
List<box2d.Body> _bodiesScheduledForDestruction = [];
double b2WorldToNodeConversionFactor = 10.0;
Offset get gravity {
Vector2 g = b2World.getGravity();
return new Offset(g.x, g.y);
}
set gravity(Offset gravity) {
// Convert from points/s^2 to m/s^2
b2World.setGravity(new Vector2(gravity.dx / b2WorldToNodeConversionFactor,
gravity.dy / b2WorldToNodeConversionFactor));
}
bool get allowSleep => b2World.isAllowSleep();
set allowSleep(bool allowSleep) {
b2World.setAllowSleep(allowSleep);
}
bool get subStepping => b2World.isSubStepping();
set subStepping(bool subStepping) {
b2World.setSubStepping(subStepping);
}
void _stepPhysics(double dt) {
// Remove bodies that were marked for destruction during the update phase
_removeBodiesScheduledForDestruction();
// Calculate a step in the simulation
b2World.stepDt(dt, 10, 10);
// Iterate over the bodies
for (box2d.Body b2Body = b2World.bodyList; b2Body != null; b2Body = b2Body.getNext()) {
// Update visual position and rotation
PhysicsBody body = b2Body.userData;
body._node._setPositionFromPhysics(new Point(
b2Body.position.x * b2WorldToNodeConversionFactor,
b2Body.position.y * b2WorldToNodeConversionFactor
));
body._node._setRotationFromPhysics(degrees(b2Body.getAngle()));
}
// Break joints
for (PhysicsJoint joint in _joints) {
joint._checkBreakingForce(dt);
}
// Remove bodies that were marked for destruction during the simulation
_removeBodiesScheduledForDestruction();
}
void _removeBodiesScheduledForDestruction() {
for (box2d.Body b2Body in _bodiesScheduledForDestruction) {
// Destroy any joints before destroying the body
PhysicsBody body = b2Body.userData;
for (PhysicsJoint joint in body._joints) {
joint._detach();
}
// Destroy the body
b2World.destroyBody(b2Body);
}
_bodiesScheduledForDestruction.clear();
}
void _updatePosition(PhysicsBody body, Point position) {
Vector2 newPos = new Vector2(
position.x / b2WorldToNodeConversionFactor,
position.y / b2WorldToNodeConversionFactor
);
double angle = body._body.getAngle();
body._body.setTransform(newPos, angle);
body._body.setAwake(true);
}
void _updateRotation(PhysicsBody body, double rotation) {
Vector2 pos = body._body.position;
double newAngle = radians(rotation);
body._body.setTransform(pos, newAngle);
body._body.setAwake(true);
}
void addChild(Node node) {
super.addChild(node);
if (node.physicsBody != null) {
node.physicsBody._attach(this, node);
}
}
void removeChild(Node node) {
super.removeChild(node);
if (node.physicsBody != null) {
node.physicsBody._detach();
}
}
void addContactCallback(PhysicsContactCallback callback, Object tagA, Object tagB, [PhysicsContactType type]) {
_contactHandler.addContactCallback(callback, tagA, tagB, type);
}
void paint(PaintingCanvas canvas) {
super.paint(canvas);
paintDebug(canvas);
}
void paintDebug(PaintingCanvas canvas) {
Paint shapePaint = new Paint();
shapePaint.setStyle(ui.PaintingStyle.stroke);
shapePaint.strokeWidth = 1.0;
for (box2d.Body body = b2World.bodyList; body != null; body = body.getNext()) {
canvas.save();
Point point = new Point(
body.position.x * b2WorldToNodeConversionFactor,
body.position.y * b2WorldToNodeConversionFactor);
canvas.translate(point.x, point.y);
canvas.rotate(body.getAngle());
if (body.getType() == box2d.BodyType.DYNAMIC) {
if (body.isAwake())
shapePaint.color = new Color(0xff00ff00);
else
shapePaint.color = new Color(0xff666666);
}
else if (body.getType() == box2d.BodyType.STATIC)
shapePaint.color = new Color(0xffff0000);
else if (body.getType() == box2d.BodyType.KINEMATIC)
shapePaint.color = new Color(0xffff9900);
for (box2d.Fixture fixture = body.getFixtureList(); fixture != null; fixture = fixture.getNext()) {
box2d.Shape shape = fixture.getShape();
if (shape.shapeType == box2d.ShapeType.CIRCLE) {
box2d.CircleShape circle = shape;
Point cp = new Point(
circle.p.x * b2WorldToNodeConversionFactor,
circle.p.y * b2WorldToNodeConversionFactor
);
double radius = circle.radius * b2WorldToNodeConversionFactor;
canvas.drawCircle(cp, radius, shapePaint);
} else if (shape.shapeType == box2d.ShapeType.POLYGON) {
box2d.PolygonShape poly = shape;
List<Point> points = [];
for (int i = 0; i < poly.getVertexCount(); i++) {
Vector2 vertex = poly.getVertex(i);
Point pt = new Point(
vertex.x * b2WorldToNodeConversionFactor,
vertex.y * b2WorldToNodeConversionFactor
);
points.add(pt);
}
if (points.length >= 2) {
for (int i = 0; i < points.length; i++) {
canvas.drawLine(points[i], points[(i + 1) % points.length], shapePaint);
}
}
}
}
canvas.restore();
// Draw contacts
for (box2d.ContactEdge edge = body.getContactList(); edge != null; edge = edge.next) {
box2d.Contact contact = edge.contact;
Vector2 cA = new Vector2.zero();
Vector2 cB = new Vector2.zero();
box2d.Fixture fixtureA = contact.fixtureA;
box2d.Fixture fixtureB = contact.fixtureB;
fixtureA.getAABB(contact.getChildIndexA()).getCenterToOut(cA);
fixtureB.getAABB(contact.getChildIndexB()).getCenterToOut(cB);
Point p1 = new Point(
cA.x * b2WorldToNodeConversionFactor,
cA.y * b2WorldToNodeConversionFactor
);
Point p2 = new Point(
cB.x * b2WorldToNodeConversionFactor,
cB.y * b2WorldToNodeConversionFactor
);
shapePaint.color = new Color(0x33ffffff);
canvas.drawLine(p1, p2, shapePaint);
box2d.WorldManifold worldManifold = new box2d.WorldManifold();
contact.getWorldManifold(worldManifold);
shapePaint.color = new Color(0xffffffff);
for (Vector2 pt in worldManifold.points) {
Point pCenter = new Point(
pt.x * b2WorldToNodeConversionFactor,
pt.y * b2WorldToNodeConversionFactor
);
Offset offset = new Offset(
worldManifold.normal.x * 5.0,
worldManifold.normal.y * 5.0
);
Point p2 = pCenter + offset;
Point p1 = new Point(pCenter.x - offset.dx, pCenter.y - offset.dy);
canvas.drawLine(p1, p2, shapePaint);
canvas.drawCircle(pCenter, 5.0, shapePaint);
}
}
// Draw joints
shapePaint.color = new Color(0xff0000ff);
for (box2d.JointEdge edge = body.getJointList(); edge != null; edge = edge.next) {
box2d.Joint joint = edge.joint;
// Make sure we only draw each joint once
if (joint.getBodyB() == body)
continue;
// Get anchor A
Vector2 anchorA = new Vector2.zero();
joint.getAnchorA(anchorA);
Point ptAnchorA = new Point(
anchorA.x * b2WorldToNodeConversionFactor,
anchorA.y * b2WorldToNodeConversionFactor
);
// Get anchor B
Vector2 anchorB = new Vector2.zero();
joint.getAnchorB(anchorB);
Point ptAnchorB = new Point(
anchorB.x * b2WorldToNodeConversionFactor,
anchorB.y * b2WorldToNodeConversionFactor
);
// Get body A position
Point ptBodyA = new Point(
joint.getBodyA().position.x * b2WorldToNodeConversionFactor,
joint.getBodyA().position.y * b2WorldToNodeConversionFactor
);
Point ptBodyB = new Point(
joint.getBodyB().position.x * b2WorldToNodeConversionFactor,
joint.getBodyB().position.y * b2WorldToNodeConversionFactor
);
// Draw the joint depending on type
box2d.JointType type = joint.getType();
if (type == box2d.JointType.WELD || type == box2d.JointType.REVOLUTE) {
// Draw weld joint
canvas.drawCircle(ptAnchorA, 5.0, shapePaint);
canvas.drawLine(ptBodyA, ptAnchorA, shapePaint);
canvas.drawLine(ptAnchorB, ptBodyB, shapePaint);
}
}
}
}
}
class PhysicsContact {
PhysicsContact(
this.nodeA,
this.nodeB,
this.shapeA,
this.shapeB,
this.isTouching,
this.isEnabled,
this.touchingPoints,
this.touchingNormal
);
final Node nodeA;
final Node nodeB;
final PhysicsShape shapeA;
final PhysicsShape shapeB;
final isTouching;
bool isEnabled;
final List<Point> touchingPoints;
final Offset touchingNormal;
}
class _ContactCallbackInfo {
_ContactCallbackInfo(this.callback, this.tagA, this.tagB, this.type);
PhysicsContactCallback callback;
Object tagA;
Object tagB;
PhysicsContactType type;
}
class _ContactHandler extends box2d.ContactListener {
_ContactHandler(this.physicsNode);
PhysicsNode physicsNode;
List<_ContactCallbackInfo> callbackInfos = [];
void addContactCallback(PhysicsContactCallback callback, Object tagA, Object tagB, PhysicsContactType type) {
callbackInfos.add(new _ContactCallbackInfo(callback, tagA, tagB, type));
}
void handleCallback(PhysicsContactType type, box2d.Contact b2Contact, box2d.Manifold oldManifold, box2d.ContactImpulse impulse) {
// Get info about the contact
PhysicsBody bodyA = b2Contact.fixtureA.getBody().userData;
PhysicsBody bodyB = b2Contact.fixtureB.getBody().userData;
box2d.Fixture fixtureA = b2Contact.fixtureA;
box2d.Fixture fixtureB = b2Contact.fixtureB;
// Match callback with added callbacks
for (_ContactCallbackInfo info in callbackInfos) {
// Check that type is matching
if (info.type != null && info.type != type)
continue;
// Check if there is a match
bool matchA = (info.tagA == null) || info.tagA == bodyA.tag;
bool matchB = (info.tagB == null) || info.tagB == bodyB.tag;
bool match = (matchA && matchB);
if (!match) {
// Check if there is a match if we swap a & b
bool matchA = (info.tagA == null) || info.tagA == bodyB.tag;
bool matchB = (info.tagB == null) || info.tagB == bodyA.tag;
match = (matchA && matchB);
if (match) {
// Swap a & b
PhysicsBody tempBody = bodyA;
bodyA = bodyB;
bodyB = tempBody;
box2d.Fixture tempFixture = fixtureA;
fixtureA = fixtureB;
fixtureB = tempFixture;
}
}
if (match) {
// We have contact and a matched callback, setup contact info
List<Point> touchingPoints = null;
Offset touchingNormal = null;
// Fetch touching points, if any
if (b2Contact.isTouching()) {
box2d.WorldManifold manifold = new box2d.WorldManifold();
b2Contact.getWorldManifold(manifold);
touchingNormal = new Offset(manifold.normal.x, manifold.normal.y);
touchingPoints = [];
for (Vector2 vec in manifold.points) {
touchingPoints.add(new Point(
vec.x * physicsNode.b2WorldToNodeConversionFactor,
vec.y * physicsNode.b2WorldToNodeConversionFactor
));
}
}
// Create the contact
PhysicsContact contact = new PhysicsContact(
bodyA._node,
bodyB._node,
fixtureA.userData,
fixtureB.userData,
b2Contact.isTouching(),
b2Contact.isEnabled(),
touchingPoints,
touchingNormal
);
// Make callback
info.callback(type, contact);
// Update Box2D contact
b2Contact.setEnabled(contact.isEnabled);
}
}
}
void beginContact(box2d.Contact contact) {
handleCallback(PhysicsContactType.begin, contact, null, null);
}
void endContact(box2d.Contact contact) {
handleCallback(PhysicsContactType.end, contact, null, null);
}
void preSolve(box2d.Contact contact, box2d.Manifold oldManifold) {
handleCallback(PhysicsContactType.preSolve, contact, oldManifold, null);
}
void postSolve(box2d.Contact contact, box2d.ContactImpulse impulse) {
handleCallback(PhysicsContactType.postSolve, contact, null, impulse);
}
}

View File

@@ -0,0 +1,65 @@
part of flutter_sprites;
abstract class PhysicsShape {
box2d.Shape _b2Shape;
Object userObject;
box2d.Shape getB2Shape(PhysicsNode node) {
if (_b2Shape == null) {
_b2Shape = _createB2Shape(node);
}
return _b2Shape;
}
box2d.Shape _createB2Shape(PhysicsNode node);
}
class PhysicsShapeCircle extends PhysicsShape {
PhysicsShapeCircle(this.point, this.radius);
final Point point;
final double radius;
box2d.Shape _createB2Shape(PhysicsNode node) {
box2d.CircleShape shape = new box2d.CircleShape();
shape.p.x = point.x / node.b2WorldToNodeConversionFactor;
shape.p.y = point.y / node.b2WorldToNodeConversionFactor;
shape.radius = radius / node.b2WorldToNodeConversionFactor;
return shape;
}
}
class PhysicsShapePolygon extends PhysicsShape {
PhysicsShapePolygon(this.points);
final List<Point> points;
box2d.Shape _createB2Shape(PhysicsNode node) {
List<Vector2> vectors = [];
for (Point point in points) {
Vector2 vec = new Vector2(
point.x / node.b2WorldToNodeConversionFactor,
point.y / node.b2WorldToNodeConversionFactor
);
vectors.add(vec);
}
box2d.PolygonShape shape = new box2d.PolygonShape();
shape.set(vectors, vectors.length);
return shape;
}
}
class PhysicsShapeGroup extends PhysicsShape {
PhysicsShapeGroup(this.shapes);
final List<PhysicsShape> shapes;
box2d.Shape _createB2Shape(PhysicsNode node) {
return null;
}
}

View File

@@ -0,0 +1,209 @@
part of flutter_sprites;
// TODO: The sound effects should probably use Android's SoundPool instead of
// MediaPlayer as it is more efficient and flexible for playing back sound effects
typedef void SoundEffectStreamCallback(SoundEffectStream);
class SoundEffect {
SoundEffect(this._pipeFuture);
// TODO: Remove load method from SoundEffect
Future load() async {
_data = await _pipeFuture;
}
Future<MojoDataPipeConsumer> _pipeFuture;
MojoDataPipeConsumer _data;
}
class SoundEffectStream {
SoundEffectStream(
this.sound,
this.loop,
this.volume,
this.pitch,
this.pan,
this.onSoundComplete
);
// TODO: Make these properties work
SoundEffect sound;
bool playing = false;
bool loop = false;
double volume = 1.0;
double pitch = 1.0;
double pan = 0.0;
// TODO: Implement completion callback. On completion, sounds should
// also be removed from the list of playing sounds.
SoundEffectStreamCallback onSoundComplete;
MediaPlayerProxy _player;
}
SoundEffectPlayer _sharedSoundEffectPlayer;
class SoundEffectPlayer {
static SoundEffectPlayer sharedInstance() {
if (_sharedSoundEffectPlayer == null) {
_sharedSoundEffectPlayer = new SoundEffectPlayer();
}
return _sharedSoundEffectPlayer;
}
SoundEffectPlayer() {
_mediaService = new MediaServiceProxy.unbound();
shell.requestService(null, _mediaService);
}
MediaServiceProxy _mediaService;
List<SoundEffectStream> _soundEffectStreams = [];
// TODO: This should no longer be needed when moving to SoundPool backing
Map<SoundEffect,MediaPlayerProxy> _mediaPlayers = {};
Future _prepare(SoundEffectStream playingSound) async {
await playingSound._player.ptr.prepare(playingSound.sound._data);
}
// TODO: Move sound loading here
// TODO: Support loading sounds from bundles
// Future<SoundEffect> load(url) async {
// ...
// }
// TODO: Add sound unloader
// unload(SoundEffect effect) {
// ...
// }
// TODO: Add paused property (should pause playback of all sounds)
bool paused;
SoundEffectStream play(
SoundEffect sound,
[bool loop = false,
double volume = 1.0,
double pitch = 1.0,
double pan = 0.0,
SoundEffectStreamCallback callback = null]) {
// Create new PlayingSound object
SoundEffectStream playingSound = new SoundEffectStream(
sound,
loop,
volume,
pitch,
pan,
callback
);
// TODO: Replace this with calls to SoundPool
if (_mediaPlayers[sound] == null) {
// Create player
playingSound._player = new MediaPlayerProxy.unbound();
_mediaService.ptr.createPlayer(playingSound._player);
// Prepare sound, then play it
_prepare(playingSound).then((_) {
playingSound._player.ptr.seekTo(0);
playingSound._player.ptr.start();
});
_soundEffectStreams.add(playingSound);
_mediaPlayers[sound] = playingSound._player;
} else {
// Reuse player
playingSound._player = _mediaPlayers[sound];
playingSound._player.ptr.seekTo(0);
playingSound._player.ptr.start();
}
return playingSound;
}
void stop(SoundEffectStream stream) {
stream._player.ptr.pause();
_soundEffectStreams.remove(stream);
}
void stopAll() {
for (SoundEffectStream playingSound in _soundEffectStreams) {
playingSound._player.ptr.pause();
}
_soundEffectStreams = [];
}
}
typedef void SoundTrackCallback(SoundTrack);
typedef void SoundTrackBufferingCallback(SoundTrack, int);
class SoundTrack {
MediaPlayerProxy _player;
SoundTrackCallback onSoundComplete;
SoundTrackCallback onSeekComplete;
SoundTrackBufferingCallback onBufferingUpdate;
bool loop;
double time;
double volume;
}
SoundTrackPlayer _sharedSoundTrackPlayer;
class SoundTrackPlayer {
List<SoundTrack> _soundTracks = [];
static sharedInstance() {
if (_sharedSoundTrackPlayer == null) {
_sharedSoundTrackPlayer = new SoundTrackPlayer();
}
return _sharedSoundTrackPlayer;
}
SoundTrackPlayer() {
_mediaService = new MediaServiceProxy.unbound();
shell.requestService(null, _mediaService);
}
MediaServiceProxy _mediaService;
Future<SoundTrack> load(Future<MojoDataPipeConsumer> pipe) async {
// Create media player
SoundTrack soundTrack = new SoundTrack();
soundTrack._player = new MediaPlayerProxy.unbound();
_mediaService.ptr.createPlayer(soundTrack._player);
await soundTrack._player.ptr.prepare(await pipe);
return soundTrack;
}
void unload(SoundTrack soundTrack) {
stop(soundTrack);
_soundTracks.remove(soundTrack);
}
void play(
SoundTrack soundTrack,
[bool loop = false,
double volume,
double startTime = 0.0]) {
// TODO: Implement looping & volume
// soundTrack._player.ptr.setLooping(loop);
// soundTrack._player.ptr.setVolume(volume);
soundTrack._player.ptr.seekTo((startTime * 1000.0).toInt());
soundTrack._player.ptr.start();
}
void stop(SoundTrack track) {
track._player.ptr.pause();
}
void stopAll() {
for (SoundTrack soundTrack in _soundTracks) {
soundTrack._player.ptr.pause();
}
}
}

View File

@@ -0,0 +1,236 @@
part of flutter_sprites;
enum SoundFadeMode {
crossFade,
fadeOutThenPlay,
fadeOutThenFadeIn,
}
enum SoundEventSimultaneousPolicy {
dontPlay,
stopOldest,
}
enum SoundEventMinimumOverlapPolicy {
dontPlay,
delay,
}
class SoundEvent {
SoundEvent(SoundEffect effect) {
effects = [effect];
}
SoundEvent.withList(this.effects);
List<SoundEffect> effects;
double pitchVariance = 0.0;
double volumeVariance = 0.0;
double panVariance = 0.0;
SoundEventSimultaneousPolicy simultaneousLimitPolicy = SoundEventSimultaneousPolicy.stopOldest;
int simultaneousLimit = 0;
SoundEventMinimumOverlapPolicy minimumOverlapPolicy = SoundEventMinimumOverlapPolicy.dontPlay;
double minimumOverlap = 0.0;
}
class _PlayingSoundEvent {
SoundEvent event;
SoundEffectStream stream;
int startTime;
}
SoundManager _sharedSoundManager;
class SoundManager {
static SoundManager sharedInstance() {
if (_sharedSoundManager == null) {
_sharedSoundManager = new SoundManager();
}
return _sharedSoundManager;
}
static void purgeSharedInstance() {
if (_sharedSoundManager == null) return;
_sharedSoundManager = null;
}
SoundManager() {
new Timer.periodic(new Duration(milliseconds:10), _update);
}
Map<SoundEvent, List<_PlayingSoundEvent>> _playingEvents = {};
SoundTrack _backgroundMusicTrack;
SoundEffectPlayer _effectPlayer = SoundEffectPlayer.sharedInstance();
SoundTrackPlayer _trackPlayer = SoundTrackPlayer.sharedInstance();
ActionController actions = new ActionController();
bool enableBackgroundMusic;
bool enableSoundEffects;
int _lastTimeStamp;
void playEvent(SoundEvent evt, [double volume = 1.0, double pitch = 1.0, double pan = 0.0]) {
List<_PlayingSoundEvent> playingList = _playingEvents[evt];
if (playingList == null) playingList = [];
// Check simultaneousLimit
if (evt.simultaneousLimit != 0 && evt.simultaneousLimit >= playingList.length) {
// We have too many sounds playing
if (evt.simultaneousLimitPolicy == SoundEventSimultaneousPolicy.dontPlay) {
// Skip this sound event
return;
} else {
// Stop the oldest sound
_effectPlayer.stop(playingList[0].stream);
}
}
// Check for overlap
int playTime = new DateTime.now().millisecondsSinceEpoch;
if (evt.minimumOverlap != 0.0 && playingList.length > 0) {
int overlap = playTime - playingList.last.startTime;
if (overlap.toDouble() / 1000.0 < evt.minimumOverlap) {
// Sounds are overlapping
if (evt.minimumOverlapPolicy == SoundEventMinimumOverlapPolicy.dontPlay) {
return;
} else {
// TODO: try to play the sound a little bit later
return;
}
}
}
// Create a new entry for the event
_PlayingSoundEvent newPlaying = new _PlayingSoundEvent();
newPlaying.startTime = playTime;
newPlaying.event = evt;
// Pick a sound effect to play
SoundEffect effect = evt.effects.elementAt(randomInt(evt.effects.length));
// Add the entry
playingList.add(newPlaying);
// Play the event
newPlaying.stream = _effectPlayer.play(
effect,
false,
(volume + evt.volumeVariance * randomSignedDouble()).clamp(0.0, 2.0),
(pitch + evt.pitchVariance * randomSignedDouble()).clamp(0.5, 2.0),
(pan + evt.panVariance * randomSignedDouble()).clamp(-1.0, 1.0),
(SoundEffectStream s) {
// Completion callback - remove the entry
playingList.remove(newPlaying);
}
);
}
void stopAllEvents([double fadeDuration]) {
for (List<_PlayingSoundEvent> playingList in _playingEvents) {
for (_PlayingSoundEvent playing in playingList) {
if (fadeDuration > 0.0) {
// Fade out and stop
ActionTween fadeOut = new ActionTween((a) => playing.stream.volume = a, playing.stream.volume, 0.0, fadeDuration);
ActionCallFunction stop = new ActionCallFunction(() { _effectPlayer.stop(playing.stream); });
ActionSequence seq = new ActionSequence([fadeOut, stop]);
actions.run(seq);
}
else {
// Stop right away
_effectPlayer.stop(playing.stream);
}
}
}
}
void playBackgroundMusic(SoundTrack track, [double fadeDuration = 0.0, SoundFadeMode fadeMode = SoundFadeMode.fadeOutThenPlay]) {
double fadeInDuration = 0.0;
double fadeInDelay = 0.0;
double fadeOutDuration = 0.0;
// Calculate durations
if (fadeDuration > 0.0) {
if (fadeMode == SoundFadeMode.crossFade) {
fadeOutDuration = fadeDuration;
fadeInDuration = fadeDuration;
} else if (fadeMode == SoundFadeMode.fadeOutThenPlay) {
fadeOutDuration = fadeDuration;
fadeInDelay = fadeDuration;
} else if (fadeMode == SoundFadeMode.fadeOutThenFadeIn) {
fadeOutDuration = fadeDuration / 2.0;
fadeInDuration = fadeDuration / 2.0;
fadeInDelay = fadeDuration / 2.0;
}
}
if (_backgroundMusicTrack != null) {
// Stop the current track
if (fadeOutDuration == 0.0) {
_trackPlayer.stop(_backgroundMusicTrack);
} else {
ActionTween fadeOut = new ActionTween((a) => _backgroundMusicTrack.volume = a, _backgroundMusicTrack.volume, 0.0, fadeOutDuration);
ActionCallFunction stop = new ActionCallFunction(() { _trackPlayer.stop(_backgroundMusicTrack); });
ActionSequence seq = new ActionSequence([fadeOut, stop]);
actions.run(seq);
}
} else {
fadeInDelay = 0.0;
}
// Fade in new sound
if (fadeInDelay == 0.0) {
_fadeInTrack(track, fadeInDuration);
} else {
ActionDelay delay = new ActionDelay(fadeInDelay);
ActionCallFunction fadeInCall = new ActionCallFunction(() {
_fadeInTrack(track, fadeInDuration);
});
ActionSequence seq = new ActionSequence([delay, fadeInCall]);
actions.run(seq);
}
}
void _fadeInTrack(SoundTrack track, double duration) {
_backgroundMusicTrack = track;
if (duration == 0.0) {
_trackPlayer.play(track);
} else {
_trackPlayer.play(track, true, 0.0);
actions.run(new ActionTween((a) => track.volume = a, 0.0, 1.0, duration));
}
}
void stopBackgroundMusic([double fadeDuration = 0.0]) {
if (fadeDuration == 0.0) {
_trackPlayer.stop(_backgroundMusicTrack);
} else {
ActionTween fadeOut = new ActionTween(
(a) => _backgroundMusicTrack.volume = a,
_backgroundMusicTrack.volume, 0.0, fadeDuration);
ActionCallFunction stopCall = new ActionCallFunction(() {
_trackPlayer.stop(_backgroundMusicTrack);
});
ActionSequence seq = new ActionSequence([fadeOut, stopCall]);
actions.run(seq);
}
_backgroundMusicTrack = null;
}
void _update(Timer timer) {
int delta = 0;
int timestamp = new DateTime.now().millisecondsSinceEpoch;
if (_lastTimeStamp != null) {
delta = timestamp - _lastTimeStamp;
}
_lastTimeStamp = timestamp;
actions.step(delta / 1000.0);
}
}

View File

@@ -0,0 +1,123 @@
part of flutter_sprites;
/// A Sprite is a [Node] that renders a bitmap image to the screen.
class Sprite extends NodeWithSize with SpritePaint {
/// The texture that the sprite will render to screen.
///
/// If the texture is null, the sprite will be rendered as a red square
/// marking the bounds of the sprite.
///
/// mySprite.texture = myTexture;
Texture texture;
/// If true, constrains the proportions of the image by scaling it down, if its proportions doesn't match the [size].
///
/// mySprite.constrainProportions = true;
bool constrainProportions = false;
Paint _cachedPaint = new Paint()
..filterQuality = ui.FilterQuality.low
..isAntiAlias = false;
/// Creates a new sprite from the provided [texture].
///
/// var mySprite = new Sprite(myTexture)
Sprite([this.texture]) : super(Size.zero) {
if (texture != null) {
size = texture.size;
pivot = texture.pivot;
} else {
pivot = new Point(0.5, 0.5);
}
}
/// Creates a new sprite from the provided [image].
///
/// var mySprite = new Sprite.fromImage(myImage);
Sprite.fromImage(ui.Image image) : super(Size.zero) {
assert(image != null);
texture = new Texture(image);
size = texture.size;
pivot = new Point(0.5, 0.5);
}
void paint(PaintingCanvas canvas) {
// Account for pivot point
applyTransformForPivot(canvas);
if (texture != null) {
double w = texture.size.width;
double h = texture.size.height;
if (w <= 0 || h <= 0) return;
double scaleX = size.width / w;
double scaleY = size.height / h;
if (constrainProportions) {
// Constrain proportions, using the smallest scale and by centering the image
if (scaleX < scaleY) {
canvas.translate(0.0, (size.height - scaleX * h) / 2.0);
scaleY = scaleX;
} else {
canvas.translate((size.width - scaleY * w) / 2.0, 0.0);
scaleX = scaleY;
}
}
canvas.scale(scaleX, scaleY);
// Setup paint object for opacity and transfer mode
_updatePaint(_cachedPaint);
// Do actual drawing of the sprite
texture.drawTexture(canvas, Point.origin, _cachedPaint);
} else {
// Paint a red square for missing texture
canvas.drawRect(new Rect.fromLTRB(0.0, 0.0, size.width, size.height),
new Paint()..color = new Color.fromARGB(255, 255, 0, 0));
}
}
}
abstract class SpritePaint {
double _opacity = 1.0;
/// The opacity of the sprite in the range 0.0 to 1.0.
///
/// mySprite.opacity = 0.5;
double get opacity => _opacity;
void set opacity(double opacity) {
assert(opacity != null);
assert(opacity >= 0.0 && opacity <= 1.0);
_opacity = opacity;
}
/// The color to draw on top of the sprite, null if no color overlay is used.
///
/// // Color the sprite red
/// mySprite.colorOverlay = new Color(0x77ff0000);
Color colorOverlay;
/// The transfer mode used when drawing the sprite to screen.
///
/// // Add the colors of the sprite with the colors of the background
/// mySprite.transferMode = TransferMode.plusMode;
ui.TransferMode transferMode;
void _updatePaint(Paint paint) {
paint.color = new Color.fromARGB((255.0*_opacity).toInt(), 255, 255, 255);
if (colorOverlay != null) {
paint.colorFilter = new ui.ColorFilter.mode(colorOverlay, ui.TransferMode.srcATop);
}
if (transferMode != null) {
paint.transferMode = transferMode;
}
}
}

View File

@@ -0,0 +1,541 @@
part of flutter_sprites;
/// Options for setting up a [SpriteBox].
///
/// * [nativePoints], use the same points as the parent [Widget].
/// * [letterbox], use the size of the root node for the coordinate system, constrain the aspect ratio and trim off
/// areas that end up outside the screen.
/// * [stretch], use the size of the root node for the coordinate system, scale it to fit the size of the box.
/// * [scaleToFit], similar to the letterbox option, but instead of trimming areas the sprite system will be scaled
/// down to fit the box.
/// * [fixedWidth], uses the width of the root node to set the size of the coordinate system, this option will change
/// the height of the root node to fit the box.
/// * [fixedHeight], uses the height of the root node to set the size of the coordinate system, this option will change
/// the width of the root node to fit the box.
enum SpriteBoxTransformMode {
nativePoints,
letterbox,
stretch,
scaleToFit,
fixedWidth,
fixedHeight,
}
class SpriteBox extends RenderBox {
// Member variables
// Root node for drawing
NodeWithSize _rootNode;
void set rootNode (NodeWithSize value) {
if (value == _rootNode) return;
// Ensure that the root node has a size
assert(value.size.width > 0);
assert(value.size.height > 0);
// Remove sprite box references
if (_rootNode != null) _removeSpriteBoxReference(_rootNode);
// Update the value
_rootNode = value;
// Add new references
_addSpriteBoxReference(_rootNode);
markNeedsLayout();
}
// Tracking of frame rate and updates
Duration _lastTimeStamp;
double _frameRate = 0.0;
double get frameRate => _frameRate;
// Transformation mode
SpriteBoxTransformMode _transformMode;
void set transformMode (SpriteBoxTransformMode value) {
if (value == _transformMode)
return;
_transformMode = value;
// Invalidate stuff
markNeedsLayout();
}
/// The transform mode used by the [SpriteBox].
SpriteBoxTransformMode get transformMode => _transformMode;
// Cached transformation matrix
Matrix4 _transformMatrix;
List<Node> _eventTargets;
List<ActionController> _actionControllers;
List<Node> _constrainedNodes;
List<PhysicsNode> _physicsNodes;
Rect _visibleArea;
Rect get visibleArea {
if (_visibleArea == null)
_calcTransformMatrix();
return _visibleArea;
}
bool _initialized = false;
// Setup
/// Creates a new SpriteBox with a node as its content, by default uses letterboxing.
///
/// The [rootNode] provides the content of the node tree, typically it's a custom subclass of [NodeWithSize]. The
/// [mode] provides different ways to scale the content to best fit it to the screen. In most cases it's preferred to
/// use a [SpriteWidget] that automatically wraps the SpriteBox.
///
/// var spriteBox = new SpriteBox(myNode, SpriteBoxTransformMode.fixedHeight);
SpriteBox(NodeWithSize rootNode, [SpriteBoxTransformMode mode = SpriteBoxTransformMode.letterbox]) {
assert(rootNode != null);
assert(rootNode._spriteBox == null);
// Setup root node
this.rootNode = rootNode;
// Setup transform mode
this.transformMode = mode;
}
void _removeSpriteBoxReference(Node node) {
node._spriteBox = null;
for (Node child in node._children) {
_removeSpriteBoxReference(child);
}
}
void _addSpriteBoxReference(Node node) {
node._spriteBox = this;
for (Node child in node._children) {
_addSpriteBoxReference(child);
}
}
void attach() {
super.attach();
_scheduleTick();
}
// Properties
/// The root node of the node tree that is rendered by this box.
///
/// var rootNode = mySpriteBox.rootNode;
NodeWithSize get rootNode => _rootNode;
void performLayout() {
size = constraints.biggest;
_invalidateTransformMatrix();
_callSpriteBoxPerformedLayout(_rootNode);
_initialized = true;
}
// Adding and removing nodes
void _registerNode(Node node) {
_actionControllers = null;
_eventTargets = null;
_physicsNodes = null;
if (node == null || node.constraints != null) _constrainedNodes = null;
}
void _deregisterNode(Node node) {
_actionControllers = null;
_eventTargets = null;
_physicsNodes = null;
if (node == null || node.constraints != null) _constrainedNodes = null;
}
// Event handling
void _addEventTargets(Node node, List<Node> eventTargets) {
List children = node.children;
int i = 0;
// Add childrens that are behind this node
while (i < children.length) {
Node child = children[i];
if (child.zPosition >= 0.0)
break;
_addEventTargets(child, eventTargets);
i++;
}
// Add this node
if (node.userInteractionEnabled) {
eventTargets.add(node);
}
// Add children in front of this node
while (i < children.length) {
Node child = children[i];
_addEventTargets(child, eventTargets);
i++;
}
}
void handleEvent(ui.Event event, _SpriteBoxHitTestEntry entry) {
if (!attached)
return;
if (event is ui.PointerEvent) {
if (event.type == 'pointerdown') {
// Build list of event targets
if (_eventTargets == null) {
_eventTargets = [];
_addEventTargets(_rootNode, _eventTargets);
}
// Find the once that are hit by the pointer
List<Node> nodeTargets = [];
for (int i = _eventTargets.length - 1; i >= 0; i--) {
Node node = _eventTargets[i];
// Check if the node is ready to handle a pointer
if (node.handleMultiplePointers || node._handlingPointer == null) {
// Do the hit test
Point posInNodeSpace = node.convertPointToNodeSpace(entry.localPosition);
if (node.isPointInside(posInNodeSpace)) {
nodeTargets.add(node);
node._handlingPointer = event.pointer;
}
}
}
entry.nodeTargets = nodeTargets;
}
// Pass the event down to nodes that were hit by the pointerdown
List<Node> targets = entry.nodeTargets;
for (Node node in targets) {
// Check if this event should be dispatched
if (node.handleMultiplePointers || event.pointer == node._handlingPointer) {
// Dispatch event
bool consumedEvent = node.handleEvent(new SpriteBoxEvent(new Point(event.x, event.y), event.type, event.pointer));
if (consumedEvent == null || consumedEvent)
break;
}
}
// De-register pointer for nodes that doesn't handle multiple pointers
for (Node node in targets) {
if (event.type == 'pointerup' || event.type == 'pointercancel') {
node._handlingPointer = null;
}
}
}
}
bool hitTest(HitTestResult result, { Point position }) {
result.add(new _SpriteBoxHitTestEntry(this, position));
return true;
}
// Rendering
/// The transformation matrix used to transform the root node to the space of the box.
///
/// It's uncommon to need access to this property.
///
/// var matrix = mySpriteBox.transformMatrix;
Matrix4 get transformMatrix {
// Get cached matrix if available
if (_transformMatrix == null) {
_calcTransformMatrix();
}
return _transformMatrix;
}
void _calcTransformMatrix() {
_transformMatrix = new Matrix4.identity();
// Calculate matrix
double scaleX = 1.0;
double scaleY = 1.0;
double offsetX = 0.0;
double offsetY = 0.0;
double systemWidth = rootNode.size.width;
double systemHeight = rootNode.size.height;
switch(_transformMode) {
case SpriteBoxTransformMode.stretch:
scaleX = size.width/systemWidth;
scaleY = size.height/systemHeight;
break;
case SpriteBoxTransformMode.letterbox:
scaleX = size.width/systemWidth;
scaleY = size.height/systemHeight;
if (scaleX > scaleY) {
scaleY = scaleX;
offsetY = (size.height - scaleY * systemHeight)/2.0;
} else {
scaleX = scaleY;
offsetX = (size.width - scaleX * systemWidth)/2.0;
}
break;
case SpriteBoxTransformMode.scaleToFit:
scaleX = size.width/systemWidth;
scaleY = size.height/systemHeight;
if (scaleX < scaleY) {
scaleY = scaleX;
offsetY = (size.height - scaleY * systemHeight)/2.0;
} else {
scaleX = scaleY;
offsetX = (size.width - scaleX * systemWidth)/2.0;
}
break;
case SpriteBoxTransformMode.fixedWidth:
scaleX = size.width/systemWidth;
scaleY = scaleX;
systemHeight = size.height/scaleX;
rootNode.size = new Size(systemWidth, systemHeight);
break;
case SpriteBoxTransformMode.fixedHeight:
scaleY = size.height/systemHeight;
scaleX = scaleY;
systemWidth = size.width/scaleY;
rootNode.size = new Size(systemWidth, systemHeight);
break;
case SpriteBoxTransformMode.nativePoints:
break;
default:
assert(false);
break;
}
_visibleArea = new Rect.fromLTRB(-offsetX / scaleX,
-offsetY / scaleY,
systemWidth + offsetX / scaleX,
systemHeight + offsetY / scaleY);
_transformMatrix.translate(offsetX, offsetY);
_transformMatrix.scale(scaleX, scaleY);
}
void _invalidateTransformMatrix() {
_visibleArea = null;
_transformMatrix = null;
_rootNode._invalidateToBoxTransformMatrix();
}
void paint(PaintingContext context, Offset offset) {
final PaintingCanvas canvas = context.canvas;
canvas.save();
// Move to correct coordinate space before drawing
canvas.translate(offset.dx, offset.dy);
canvas.concat(transformMatrix.storage);
// Draw the sprite tree
Matrix4 totalMatrix = new Matrix4.fromFloat64List(canvas.getTotalMatrix());
_rootNode._visit(canvas, totalMatrix);
canvas.restore();
}
// Updates
void _scheduleTick() {
scheduler.requestAnimationFrame(_tick);
}
void _tick(Duration timeStamp) {
if (!attached)
return;
// Calculate delta and frame rate
if (_lastTimeStamp == null)
_lastTimeStamp = timeStamp;
double delta = (timeStamp - _lastTimeStamp).inMicroseconds.toDouble() / Duration.MICROSECONDS_PER_SECOND;
_lastTimeStamp = timeStamp;
_frameRate = 1.0/delta;
if (_initialized) {
_callConstraintsPreUpdate(delta);
_runActions(delta);
_callUpdate(_rootNode, delta);
_callStepPhysics(delta);
_callConstraintsConstrain(delta);
}
// Schedule next update
_scheduleTick();
// Make sure the node graph is redrawn
markNeedsPaint();
}
void _runActions(double dt) {
if (_actionControllers == null) {
_rebuildActionControllersAndPhysicsNodes();
}
for (ActionController actions in _actionControllers) {
actions.step(dt);
}
}
void _rebuildActionControllersAndPhysicsNodes() {
_actionControllers = [];
_physicsNodes = [];
_addActionControllersAndPhysicsNodes(_rootNode);
}
void _addActionControllersAndPhysicsNodes(Node node) {
if (node._actions != null) _actionControllers.add(node._actions);
if (node is PhysicsNode) _physicsNodes.add(node);
for (int i = node.children.length - 1; i >= 0; i--) {
Node child = node.children[i];
_addActionControllersAndPhysicsNodes(child);
}
}
void _callUpdate(Node node, double dt) {
node.update(dt);
for (int i = node.children.length - 1; i >= 0; i--) {
Node child = node.children[i];
if (!child.paused) {
_callUpdate(child, dt);
}
}
}
void _callStepPhysics(double dt) {
if (_physicsNodes == null)
_rebuildActionControllersAndPhysicsNodes();
for (PhysicsNode physicsNode in _physicsNodes) {
physicsNode._stepPhysics(dt);
}
}
void _callConstraintsPreUpdate(double dt) {
if (_constrainedNodes == null) {
_constrainedNodes = [];
_addConstrainedNodes(_rootNode, _constrainedNodes);
}
for (Node node in _constrainedNodes) {
for (Constraint constraint in node.constraints) {
constraint.preUpdate(node, dt);
}
}
}
void _callConstraintsConstrain(double dt) {
if (_constrainedNodes == null) {
_constrainedNodes = [];
_addConstrainedNodes(_rootNode, _constrainedNodes);
}
for (Node node in _constrainedNodes) {
for (Constraint constraint in node.constraints) {
constraint.constrain(node, dt);
}
}
}
void _addConstrainedNodes(Node node, List<Node> nodes) {
if (node._constraints != null && node._constraints.length > 0) {
nodes.add(node);
}
for (Node child in node.children) {
_addConstrainedNodes(child, nodes);
}
}
void _callSpriteBoxPerformedLayout(Node node) {
node.spriteBoxPerformedLayout();
for (Node child in node.children) {
_callSpriteBoxPerformedLayout(child);
}
}
// Hit tests
/// Finds all nodes at a position defined in the box's coordinates.
///
/// Use this method with caution. It searches the complete node tree to locate the nodes, which can be slow if the
/// node tree is large.
///
/// List nodes = mySpriteBox.findNodesAtPosition(new Point(50.0, 50.0));
List<Node> findNodesAtPosition(Point position) {
assert(position != null);
List<Node> nodes = [];
// Traverse the render tree and find objects at the position
_addNodesAtPosition(_rootNode, position, nodes);
return nodes;
}
_addNodesAtPosition(Node node, Point position, List<Node> list) {
// Visit children first
for (Node child in node.children) {
_addNodesAtPosition(child, position, list);
}
// Do the hit test
Point posInNodeSpace = node.convertPointToNodeSpace(position);
if (node.isPointInside(posInNodeSpace)) {
list.add(node);
}
}
}
class _SpriteBoxHitTestEntry extends BoxHitTestEntry {
List<Node> nodeTargets;
_SpriteBoxHitTestEntry(RenderBox target, Point localPosition) : super(target, localPosition);
}
/// An event that is passed down the node tree when pointer events occur. The SpriteBoxEvent is typically handled in
/// the handleEvent method of [Node].
class SpriteBoxEvent {
/// The position of the event in box coordinates.
///
/// You can use the convertPointToNodeSpace of [Node] to convert the position to local coordinates.
///
/// bool handleEvent(SpriteBoxEvent event) {
/// Point localPosition = convertPointToNodeSpace(event.boxPosition);
/// if (event.type == 'pointerdown') {
/// // Do something!
/// }
/// }
final Point boxPosition;
/// The type of event, there are currently four valid types, 'pointerdown', 'pointermoved', 'pointerup', and
/// 'pointercancel'.
///
/// if (event.type == 'pointerdown') {
/// // Do something!
/// }
final String type;
/// The id of the pointer. Each pointer on the screen will have a unique pointer id.
///
/// if (event.pointer == firstPointerId) {
/// // Do something
/// }
final int pointer;
/// Creates a new SpriteBoxEvent, typically this is done internally inside the SpriteBox.
///
/// var event = new SpriteBoxEvent(new Point(50.0, 50.0), 'pointerdown', 0);
SpriteBoxEvent(this.boxPosition, this.type, this.pointer);
}

View File

@@ -0,0 +1,33 @@
part of flutter_sprites;
/// A widget that uses a [SpriteBox] to render a sprite node tree to the screen.
class SpriteWidget extends OneChildRenderObjectWidget {
/// The rootNode of the sprite node tree.
///
/// var node = mySpriteWidget.rootNode;
final NodeWithSize rootNode;
/// The transform mode used to fit the sprite node tree to the size of the widget.
final SpriteBoxTransformMode transformMode;
/// Creates a new sprite widget with [rootNode] as its content.
///
/// The widget will setup the coordinate space for the sprite node tree using the size of the [rootNode] in
/// combination with the supplied [transformMode]. By default the letterbox transform mode is used. See
/// [SpriteBoxTransformMode] for more details on the different modes.
///
/// The most common way to setup the sprite node graph is to subclass [NodeWithSize] and pass it to the sprite widget.
/// In the custom subclass it's possible to build the node graph, do animations and handle user events.
///
/// var mySpriteTree = new MyCustomNodeWithSize();
/// var mySpriteWidget = new SpriteWidget(mySpriteTree, SpriteBoxTransformMode.fixedHeight);
SpriteWidget(this.rootNode, [this.transformMode = SpriteBoxTransformMode.letterbox]);
SpriteBox createRenderObject() => new SpriteBox(rootNode, transformMode);
void updateRenderObject(SpriteBox renderObject, SpriteWidget oldWidget) {
renderObject.rootNode = rootNode;
renderObject.transformMode = transformMode;
}
}

View File

@@ -0,0 +1,74 @@
part of flutter_sprites;
/// A sprite sheet packs a number of smaller images into a single large image.
///
/// The placement of the smaller images are defined by a json file. The larger image and json file is typically created
/// by a tool such as TexturePacker. The [SpriteSheet] class will take a reference to a larger image and a json string.
/// From the image and the string the [SpriteSheet] creates a number of [Texture] objects. The names of the frames in
/// the sprite sheet definition are used to reference the different textures.
class SpriteSheet {
ui.Image _image;
Map<String, Texture> _textures = new Map();
/// Creates a new sprite sheet from an [_image] and a sprite sheet [jsonDefinition].
///
/// var mySpriteSheet = new SpriteSheet(myImage, jsonString);
SpriteSheet(this._image, String jsonDefinition) {
assert(_image != null);
assert(jsonDefinition != null);
JsonDecoder decoder = new JsonDecoder();
Map file = decoder.convert(jsonDefinition);
assert(file != null);
List frames = file["frames"];
for (Map frameInfo in frames) {
String fileName = frameInfo["filename"];
Rect frame = _readJsonRect(frameInfo["frame"]);
bool rotated = frameInfo["rotated"];
bool trimmed = frameInfo["trimmed"];
Rect spriteSourceSize = _readJsonRect(frameInfo["spriteSourceSize"]);
Size sourceSize = _readJsonSize(frameInfo["sourceSize"]);
Point pivot = _readJsonPoint(frameInfo["pivot"]);
var texture = new Texture._fromSpriteFrame(_image, fileName, sourceSize, rotated, trimmed, frame,
spriteSourceSize, pivot);
_textures[fileName] = texture;
}
}
Rect _readJsonRect(Map data) {
num x = data["x"];
num y = data["y"];
num w = data["w"];
num h = data["h"];
return new Rect.fromLTRB(x.toDouble(), y.toDouble(), (x + w).toDouble(), (y + h).toDouble());
}
Size _readJsonSize(Map data) {
num w = data["w"];
num h = data["h"];
return new Size(w.toDouble(), h.toDouble());
}
Point _readJsonPoint(Map data) {
num x = data["x"];
num y = data["y"];
return new Point(x.toDouble(), y.toDouble());
}
/// The image used by the sprite sheet.
///
/// var spriteSheetImage = mySpriteSheet.image;
ui.Image get image => _image;
/// Returns a texture by its name.
///
/// var myTexture = mySpriteSheet["example.png"];
Texture operator [](String fileName) => _textures[fileName];
}

View File

@@ -0,0 +1,112 @@
part of flutter_sprites;
/// A texture represents a rectangular area of an image and is typically used to draw a sprite to the screen.
///
/// Normally you get a reference to a texture from a [SpriteSheet], but you can also create one from an [Image].
class Texture {
/// The image that this texture is a part of.
///
/// var textureImage = myTexture.image;
final ui.Image image;
/// The logical size of the texture, before being trimmed by the texture packer.
///
/// var textureSize = myTexture.size;
final Size size;
/// The name of the image acts as a tag when acquiring a reference to it.
///
/// myTexture.name = "new_texture_name";
String name;
/// The texture was rotated 90 degrees when being packed into a sprite sheet.
///
/// if (myTexture.rotated) drawRotated();
final bool rotated;
/// The texture was trimmed when being packed into a sprite sheet.
///
/// bool trimmed = myTexture.trimmed
final bool trimmed;
/// The frame of the trimmed texture inside the image.
///
/// Rect frame = myTexture.frame;
final Rect frame;
/// The offset and size of the trimmed texture inside the image.
///
/// Position represents the offset from the logical [size], the size of the rect represents the size of the trimmed
/// texture.
///
/// Rect spriteSourceSize = myTexture.spriteSourceSize;
final Rect spriteSourceSize;
/// The default pivot point for this texture. When creating a [Sprite] from the texture, this is the pivot point that
/// will be used.
///
/// myTexture.pivot = new Point(0.5, 0.5);
Point pivot;
/// Creates a new texture from an [Image] object.
///
/// var myTexture = new Texture(myImage);
Texture(ui.Image image) :
size = new Size(image.width.toDouble(), image.height.toDouble()),
image = image,
trimmed = false,
rotated = false,
frame = new Rect.fromLTRB(0.0, 0.0, image.width.toDouble(), image.height.toDouble()),
spriteSourceSize = new Rect.fromLTRB(0.0, 0.0, image.width.toDouble(), image.height.toDouble()),
pivot = new Point(0.5, 0.5);
Texture._fromSpriteFrame(this.image, this.name, this.size, this.rotated, this.trimmed, this.frame,
this.spriteSourceSize, this.pivot) {
}
Texture textureFromRect(Rect rect, [String name = null]) {
assert(rect != null);
assert(!rotated);
Rect srcFrame = new Rect.fromLTWH(rect.left + frame.left, rect.top + frame.top, rect.size.width, rect.size.height);
Rect dstFrame = new Rect.fromLTWH(0.0, 0.0, rect.size.width, rect.size.height);
return new Texture._fromSpriteFrame(image, name, rect.size, false, false, srcFrame, dstFrame, new Point(0.5, 0.5));
}
void drawTexture(PaintingCanvas canvas, Point position, Paint paint) {
// Get drawing position
double x = position.x;
double y = position.y;
// Draw the texture
if (rotated) {
// Account for position
bool translate = (x != 0 || y != 0);
if (translate) {
canvas.translate(x, y);
}
// Calculate the rotated frame and spriteSourceSize
Size originalFrameSize = frame.size;
Rect rotatedFrame = frame.topLeft & new Size(originalFrameSize.height, originalFrameSize.width);
Point rotatedSpriteSourcePoint = new Point(
-spriteSourceSize.top - (spriteSourceSize.bottom - spriteSourceSize.top),
spriteSourceSize.left);
Rect rotatedSpriteSourceSize = rotatedSpriteSourcePoint & new Size(originalFrameSize.height, originalFrameSize.width);
// Draw the rotated sprite
canvas.rotate(-math.PI/2.0);
canvas.drawImageRect(image, rotatedFrame, rotatedSpriteSourceSize, paint);
canvas.rotate(math.PI/2.0);
// Translate back
if (translate) {
canvas.translate(-x, -y);
}
} else {
// Draw the sprite
Rect dstRect = new Rect.fromLTWH(x + spriteSourceSize.left, y + spriteSourceSize.top, spriteSourceSize.width, spriteSourceSize.height);
canvas.drawImageRect(image, frame, dstRect, paint);
}
}
}

View File

@@ -0,0 +1,299 @@
part of flutter_sprites;
class TexturedLine extends Node {
TexturedLine(List<Point> points, List<Color> colors, List<double> widths, [Texture texture, List<double> textureStops]) {
painter = new TexturedLinePainter(points, colors, widths, texture, textureStops);
}
TexturedLinePainter painter;
void paint(PaintingCanvas canvas) {
painter.paint(canvas);
}
}
class TexturedLinePainter {
TexturedLinePainter(this._points, this.colors, this.widths, [Texture texture, this.textureStops]) {
this.texture = texture;
}
List<Point> _points;
List<Point> get points => _points;
set points(List<Point> points) {
_points = points;
_calculatedTextureStops = null;
}
List<Color> colors;
List<double> widths;
Texture _texture;
Texture get texture => _texture;
set texture(Texture texture) {
_texture = texture;
if (texture == null) {
_cachedPaint = new Paint();
} else {
Matrix4 matrix = new Matrix4.identity();
ui.ImageShader shader = new ui.ImageShader(texture.image,
ui.TileMode.repeated, ui.TileMode.repeated, matrix.storage);
_cachedPaint = new Paint();
_cachedPaint.setShader(shader);
}
}
List<double> textureStops;
List<double> _calculatedTextureStops;
List<double> get calculatedTextureStops {
if (_calculatedTextureStops == null)
_calculateTextureStops();
return _calculatedTextureStops;
}
double _length;
double get length {
if (_calculatedTextureStops == null)
_calculateTextureStops();
return _length;
}
double textureStopOffset = 0.0;
double _textureLoopLength;
get textureLoopLength => textureLoopLength;
set textureLoopLength(double textureLoopLength) {
_textureLoopLength = textureLoopLength;
_calculatedTextureStops = null;
}
bool removeArtifacts = true;
ui.TransferMode transferMode = ui.TransferMode.srcOver;
Paint _cachedPaint = new Paint();
void paint(PaintingCanvas canvas) {
// Check input values
assert(_points != null);
if (_points.length < 2) return;
assert(_points.length == colors.length);
assert(_points.length == widths.length);
_cachedPaint.transferMode = transferMode;
// Calculate normals
List<Vector2> vectors = [];
for (Point pt in _points) {
vectors.add(new Vector2(pt.x, pt.y));
}
List<Vector2> miters = _computeMiterList(vectors, false);
List<Point> vertices = [];
List<int> indicies = [];
List<Color> verticeColors = [];
List<Point> textureCoordinates;
double textureTop;
double textureBottom;
List<double> stops;
// Add first point
Point lastPoint = _points[0];
Vector2 lastMiter = miters[0];
// Add vertices and colors
_addVerticesForPoint(vertices, lastPoint, lastMiter, widths[0]);
verticeColors.add(colors[0]);
verticeColors.add(colors[0]);
if (texture != null) {
assert(texture.rotated == false);
// Setup for calculating texture coordinates
textureTop = texture.frame.top;
textureBottom = texture.frame.bottom;
textureCoordinates = [];
// Use correct stops
if (textureStops != null) {
assert(_points.length == textureStops.length);
stops = textureStops;
} else {
if (_calculatedTextureStops == null) _calculateTextureStops();
stops = _calculatedTextureStops;
}
// Texture coordinate points
double xPos = _xPosForStop(stops[0]);
textureCoordinates.add(new Point(xPos, textureTop));
textureCoordinates.add(new Point(xPos, textureBottom));
}
// Add the rest of the points
for (int i = 1; i < _points.length; i++) {
// Add vertices
Point currentPoint = _points[i];
Vector2 currentMiter = miters[i];
_addVerticesForPoint(vertices, currentPoint, currentMiter, widths[i]);
// Add references to the triangles
int lastIndex0 = (i - 1) * 2;
int lastIndex1 = (i - 1) * 2 + 1;
int currentIndex0 = i * 2;
int currentIndex1 = i * 2 + 1;
indicies.addAll([lastIndex0, lastIndex1, currentIndex0]);
indicies.addAll([lastIndex1, currentIndex1, currentIndex0]);
// Add colors
verticeColors.add(colors[i]);
verticeColors.add(colors[i]);
if (texture != null) {
// Texture coordinate points
double xPos = _xPosForStop(stops[i]);
textureCoordinates.add(new Point(xPos, textureTop));
textureCoordinates.add(new Point(xPos, textureBottom));
}
// Update last values
lastPoint = currentPoint;
lastMiter = currentMiter;
}
canvas.drawVertices(ui.VertexMode.triangles, vertices, textureCoordinates, verticeColors, ui.TransferMode.modulate, indicies, _cachedPaint);
}
double _xPosForStop(double stop) {
if (_textureLoopLength == null) {
return texture.frame.left + texture.frame.width * (stop - textureStopOffset);
} else {
return texture.frame.left + texture.frame.width * (stop - textureStopOffset * (_textureLoopLength / length)) * (length / _textureLoopLength);
}
}
void _addVerticesForPoint(List<Point> vertices, Point point, Vector2 miter, double width) {
double halfWidth = width / 2.0;
Offset offset0 = new Offset(miter[0] * halfWidth, miter[1] * halfWidth);
Offset offset1 = new Offset(-miter[0] * halfWidth, -miter[1] * halfWidth);
Point vertex0 = point + offset0;
Point vertex1 = point + offset1;
int vertexCount = vertices.length;
if (removeArtifacts && vertexCount >= 2) {
Point oldVertex0 = vertices[vertexCount - 2];
Point oldVertex1 = vertices[vertexCount - 1];
Point intersection = GameMath.lineIntersection(oldVertex0, oldVertex1, vertex0, vertex1);
if (intersection != null) {
if (GameMath.distanceBetweenPoints(vertex0, intersection) < GameMath.distanceBetweenPoints(vertex1, intersection)) {
vertex0 = oldVertex0;
} else {
vertex1 = oldVertex1;
}
}
}
vertices.add(vertex0);
vertices.add(vertex1);
}
void _calculateTextureStops() {
List<double> stops = [];
double length = 0.0;
// Add first stop
stops.add(0.0);
// Calculate distance to each point from the first point along the line
for (int i = 1; i < _points.length; i++) {
Point lastPoint = _points[i - 1];
Point currentPoint = _points[i];
double dist = GameMath.distanceBetweenPoints(lastPoint, currentPoint);
length += dist;
stops.add(length);
}
// Normalize the values in the range [0.0, 1.0]
for (int i = 1; i < points.length; i++) {
stops[i] = stops[i] / length;
new Point(512.0, 512.0);
}
_calculatedTextureStops = stops;
_length = length;
}
}
Vector2 _computeMiter(Vector2 lineA, Vector2 lineB) {
Vector2 miter = new Vector2(- (lineA[1] + lineB[1]), lineA[0] + lineB[0]);
miter.normalize();
double dot = dot2(miter, new Vector2(-lineA[1], lineA[0]));
if (dot.abs() < 0.1) {
miter = _vectorNormal(lineA).normalize();
return miter;
}
double miterLength = 1.0 / dot;
miter = miter.scale(miterLength);
return miter;
}
Vector2 _vectorNormal(Vector2 v) {
return new Vector2(-v[1], v[0]);
}
Vector2 _vectorDirection(Vector2 a, Vector2 b) {
Vector2 result = a - b;
return result.normalize();
}
List<Vector2> _computeMiterList(List<Vector2> points, bool closed) {
List<Vector2> out = [];
Vector2 curNormal = null;
if (closed) {
points = new List<Vector2>.from(points);
points.add(points[0]);
}
int total = points.length;
for (int i = 1; i < total; i++) {
Vector2 last = points[i - 1];
Vector2 cur = points[i];
Vector2 next = (i < total - 1) ? points[i + 1] : null;
Vector2 lineA = _vectorDirection(cur, last);
if (curNormal == null) {
curNormal = _vectorNormal(lineA);
}
if (i == 1) {
out.add(curNormal);
}
if (next == null) {
curNormal = _vectorNormal(lineA);
out.add(curNormal);
} else {
Vector2 lineB = _vectorDirection(next, cur);
Vector2 miter = _computeMiter(lineA, lineB);
out.add(miter);
}
}
return out;
}

View File

@@ -0,0 +1,149 @@
part of flutter_sprites;
math.Random _random = new math.Random();
// Random methods
/// Returns a random [double] in the range of 0.0 to 1.0.
double randomDouble() {
return _random.nextDouble();
}
/// Returns a random [double] in the range of -1.0 to 1.0.
double randomSignedDouble() {
return _random.nextDouble() * 2.0 - 1.0;
}
/// Returns a random [int] from 0 to max - 1.
int randomInt(int max) {
return _random.nextInt(max);
}
/// Returns either [true] or [false] in a most random fashion.
bool randomBool() {
return _random.nextDouble() < 0.5;
}
// atan2
class _Atan2Constants {
_Atan2Constants() {
for (int i = 0; i <= size; i++) {
double f = i.toDouble() / size.toDouble();
ppy[i] = math.atan(f) * stretch / math.PI;
ppx[i] = stretch * 0.5 - ppy[i];
pny[i] = -ppy[i];
pnx[i] = ppy[i] - stretch * 0.5;
npy[i] = stretch - ppy[i];
npx[i] = ppy[i] + stretch * 0.5;
nny[i] = ppy[i] - stretch;
nnx[i] = -stretch * 0.5 - ppy[i];
}
}
static const int size = 1024;
static const double stretch = math.PI;
static const int ezis = -size;
final Float64List ppy = new Float64List(size + 1);
final Float64List ppx = new Float64List(size + 1);
final Float64List pny = new Float64List(size + 1);
final Float64List pnx = new Float64List(size + 1);
final Float64List npy = new Float64List(size + 1);
final Float64List npx = new Float64List(size + 1);
final Float64List nny = new Float64List(size + 1);
final Float64List nnx = new Float64List(size + 1);
}
/// Provides convenience methods for calculations often carried out in graphics.
/// Some of the methods are returning approximations.
class GameMath {
static final _Atan2Constants _atan2 = new _Atan2Constants();
/// Returns the angle of two vector components. The result is less acurate
/// than the standard atan2 function in the math package.
static double atan2(double y, double x) {
if (x >= 0) {
if (y >= 0) {
if (x >= y)
return _atan2.ppy[(_Atan2Constants.size * y / x + 0.5).toInt()];
else
return _atan2.ppx[(_Atan2Constants.size * x / y + 0.5).toInt()];
} else {
if (x >= -y)
return _atan2.pny[(_Atan2Constants.ezis * y / x + 0.5).toInt()];
else
return _atan2.pnx[(_Atan2Constants.ezis * x / y + 0.5).toInt()];
}
} else {
if (y >= 0) {
if (-x >= y)
return _atan2.npy[(_Atan2Constants.ezis * y / x + 0.5).toInt()];
else
return _atan2.npx[(_Atan2Constants.ezis * x / y + 0.5).toInt()];
} else {
if (x <= y)
return _atan2.nny[(_Atan2Constants.size * y / x + 0.5).toInt()];
else
return _atan2.nnx[(_Atan2Constants.size * x / y + 0.5).toInt()];
}
}
}
/// Approximates the distance between two points. The returned value can be
/// up to 6% wrong in the worst case.
static double distanceBetweenPoints(Point a, Point b) {
double dx = a.x - b.x;
double dy = a.y - b.y;
if (dx < 0.0) dx = -dx;
if (dy < 0.0) dy = -dy;
if (dx > dy) {
return dx + dy/2.0;
}
else {
return dy + dx/2.0;
}
}
/// Interpolates a [double] between [a] and [b] according to the
/// [filterFactor], which should be in the range of 0.0 to 1.0.
static double filter (double a, double b, double filterFactor) {
return (a * (1-filterFactor)) + b * filterFactor;
}
/// Interpolates a [Point] between [a] and [b] according to the
/// [filterFactor], which should be in the range of 0.0 to 1.0.
static Point filterPoint(Point a, Point b, double filterFactor) {
return new Point(filter(a.x, b.x, filterFactor), filter(a.y, b.y, filterFactor));
}
/// Returns the intersection between two line segmentss defined by p0, p1 and
/// q0, q1. If the lines are not intersecting null is returned.
static Point lineIntersection(Point p0, Point p1, Point q0, Point q1) {
double epsilon = 1e-10;
Vector2 r = new Vector2(p1.x - p0.x, p1.y - p0.y);
Vector2 s = new Vector2(q1.x - q0.x, q1.y - q0.y);
Vector2 qp = new Vector2(q0.x - p0.x, q0.y - p0.y);
double rxs = cross2(r, s);
if (rxs.abs() < epsilon) {
// The lines are linear or collinear
return null;
}
double t = cross2(qp, s) / rxs;
double u = cross2(qp, r) / rxs;
if ((0.0 <= t && t <= 1.0) && (0.0 <= u && u <= 1.0)) {
return new Point(p0.x + t * r.x, p0.y + t * r.y);
}
// No intersection between the lines
return null;
}
}

View File

@@ -0,0 +1,62 @@
part of flutter_sprites;
class VirtualJoystick extends NodeWithSize {
VirtualJoystick() : super(new Size(160.0, 160.0)) {
userInteractionEnabled = true;
handleMultiplePointers = false;
position = new Point(160.0, -20.0);
pivot = new Point(0.5, 1.0);
_center = new Point(size.width / 2.0, size.height / 2.0);
_handlePos = _center;
_paintHandle = new Paint()
..color=new Color(0xffffffff);
_paintControl = new Paint()
..color=new Color(0xffffffff)
..strokeWidth = 1.0
..setStyle(ui.PaintingStyle.stroke);
}
Point _value = Point.origin;
Point get value => _value;
bool _isDown = false;
bool get isDown => _isDown;
Point _pointerDownAt;
Point _center;
Point _handlePos;
Paint _paintHandle;
Paint _paintControl;
bool handleEvent(SpriteBoxEvent event) {
if (event.type == "pointerdown") {
_pointerDownAt = event.boxPosition;
actions.stopAll();
_isDown = true;
}
else if (event.type == "pointerup" || event.type == "pointercancel") {
_pointerDownAt = null;
_value = Point.origin;
ActionTween moveToCenter = new ActionTween((a) => _handlePos = a, _handlePos, _center, 0.4, elasticOut);
actions.run(moveToCenter);
_isDown = false;
} else if (event.type == "pointermove") {
Offset movedDist = event.boxPosition - _pointerDownAt;
_value = new Point(
(movedDist.dx / 80.0).clamp(-1.0, 1.0),
(movedDist.dy / 80.0).clamp(-1.0, 1.0));
_handlePos = _center + new Offset(_value.x * 40.0, _value.y * 40.0);
}
return true;
}
void paint(PaintingCanvas canvas) {
applyTransformForPivot(canvas);
canvas.drawCircle(_handlePos, 25.0, _paintHandle);
canvas.drawCircle(_center, 40.0, _paintControl);
}
}