Moves sky sprites to its own package

This commit is contained in:
Viktor Lidholt
2015-08-25 16:08:46 -07:00
parent 59817111f0
commit ebeb8e2d42
28 changed files with 48 additions and 26 deletions

View File

@@ -1,555 +0,0 @@
part of 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

@@ -1,55 +0,0 @@
part of 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);
}
class ActionSpline extends ActionInterval {
ActionSpline(this.setter, this.points, double duration, [Curve curve]) : super(duration, curve) {
_dt = 1.0 / (points.length - 1.0);
}
final Function setter;
final List<Point> points;
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

@@ -1,75 +0,0 @@
part of 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);
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

@@ -1,67 +0,0 @@
part of sprites;
abstract class Constraint {
void preUpdate(Node node, double dt) {
}
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;
}
class ConstraintRotationToMovement {
ConstraintRotationToMovement([this.baseRotation = 0.0, this.dampening]);
final double dampening;
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);
}
}
class ConstraintRotationToNode {
ConstraintRotationToNode(this.targetNode, [this.baseRotation, this.dampening]);
final Node targetNode;
final double baseRotation;
final double dampening;
void constrain(Node node, double dt) {
Offset offset;
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);
}
}

View File

@@ -3,9 +3,9 @@ library game;
import 'dart:async';
import 'dart:math' as math;
import 'dart:sky' as sky;
import 'sprites.dart';
import 'package:sky/rendering/object.dart';
import 'package:sky/widgets/framework.dart';
import 'package:skysprites/skysprites.dart';
part 'game_demo_node.dart';

View File

@@ -1,25 +0,0 @@
// 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 sprites;
class ImageMap {
ImageMap(AssetBundle bundle) : _bundle = bundle;
final AssetBundle _bundle;
final Map<String, Image> _images = new Map<String, Image>();
Future<List<Image>> load(List<String> urls) {
return Future.wait(urls.map(_loadImage));
}
Future<Image> _loadImage(String url) async {
Image image = await _bundle.loadImage(url).first;
_images[url] = image;
return image;
}
Image getImage(String url) => _images[url];
Image operator [](String url) => _images[url];
}

View File

@@ -1,39 +0,0 @@
part of 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()
..setFilterQuality(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

@@ -14,9 +14,9 @@ import 'package:sky/widgets/navigator.dart';
import 'package:sky/widgets/framework.dart';
import 'package:sky/widgets/title.dart';
import 'package:sky/widgets/theme.dart';
import 'package:skysprites/skysprites.dart';
import 'game_demo.dart';
import 'sprites.dart';
AssetBundle _initBundle() {
if (rootBundle != null)

View File

@@ -1,607 +0,0 @@
part of 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;
List<Constraint> get constraints {
return _constraints;
}
set constraints(List<Constraint> constraints) {
_constraints = constraints;
if (_spriteBox != null) _spriteBox._constrainedNodes = null;
}
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);
_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);
_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;
}
}

View File

@@ -1,58 +0,0 @@
part of 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

@@ -1,60 +0,0 @@
part of 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

@@ -1,446 +0,0 @@
part of 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].
TransferMode transferMode;
List<_Particle> _particles;
double _emitCounter;
int _numEmittedParticles = 0;
static Paint _paint = new Paint()
..setFilterQuality(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: 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<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;
RSTransform transform = new 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,
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

@@ -1,209 +0,0 @@
part of 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

@@ -1,236 +0,0 @@
part of 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

@@ -1,123 +0,0 @@
part of 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()
..setFilterQuality(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(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;
TransferMode transferMode;
void _updatePaint(Paint paint) {
paint.color = new Color.fromARGB((255.0*_opacity).toInt(), 255, 255, 255);
if (colorOverlay != null) {
paint.setColorFilter(new ColorFilter.mode(colorOverlay, TransferMode.srcATop));
}
if (transferMode != null) {
paint.setTransferMode(transferMode);
}
}
}

View File

@@ -1,516 +0,0 @@
part of 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
double _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;
Rect _visibleArea;
Rect get visibleArea {
if (_visibleArea == null)
_calcTransformMatrix();
return _visibleArea;
}
// 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);
}
// Adding and removing nodes
_registerNode(Node node) {
_actionControllers = null;
_eventTargets = null;
if (node == null || node.constraints != null) _constrainedNodes = null;
}
_deregisterNode(Node node) {
_actionControllers = null;
_eventTargets = 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++;
}
}
EventDisposition handleEvent(Event event, _SpriteBoxHitTestEntry entry) {
if (!attached)
return EventDisposition.ignored;
if (event is 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;
}
}
}
return EventDisposition.ignored;
}
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.fromFloat32List(canvas.getTotalMatrix());
_rootNode._visit(canvas, totalMatrix);
canvas.restore();
}
// Updates
void _scheduleTick() {
scheduler.requestAnimationFrame(_tick);
}
void _tick(double timeStamp) {
if (!attached)
return;
// Calculate delta and frame rate
if (_lastTimeStamp == null) _lastTimeStamp = timeStamp;
double delta = (timeStamp - _lastTimeStamp) / 1000;
_lastTimeStamp = timeStamp;
_frameRate = 1.0/delta;
_callConstraintsPreUpdate(delta);
_runActions(delta);
_callUpdate(_rootNode, delta);
_callConstraintsConstrain(delta);
// Schedule next update
_scheduleTick();
// Make sure the node graph is redrawn
markNeedsPaint();
}
void _runActions(double dt) {
if (_actionControllers == null) {
_actionControllers = [];
_addActionControllers(_rootNode, _actionControllers);
}
for (ActionController actions in _actionControllers) {
actions.step(dt);
}
}
void _addActionControllers(Node node, List<ActionController> controllers) {
if (node._actions != null) controllers.add(node._actions);
for (int i = node.children.length - 1; i >= 0; i--) {
Node child = node.children[i];
_addActionControllers(child, controllers);
}
}
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 _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

@@ -1,37 +0,0 @@
part of sprites;
/// A widget that uses a [SpriteBox] to render a sprite node tree to the screen.
class SpriteWidget extends OneChildRenderObjectWrapper {
/// 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 get renderObject => super.renderObject;
SpriteBox createNode() => new SpriteBox(rootNode, transformMode);
void syncRenderObject(SpriteWidget old) {
super.syncRenderObject(old);
renderObject.rootNode = rootNode;
renderObject.transformMode = transformMode;
}
}

View File

@@ -1,42 +0,0 @@
// 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.
library sprites;
import 'dart:async';
import 'dart:convert';
import 'dart:math' as math;
import 'dart:typed_data';
import 'dart:sky';
import 'package:mojo/core.dart';
import 'package:sky/animation/curves.dart';
import 'package:sky/base/scheduler.dart' as scheduler;
import 'package:sky/mojo/asset_bundle.dart';
import 'package:sky/mojo/shell.dart' as shell;
import 'package:sky/rendering/box.dart';
import 'package:sky/rendering/object.dart';
import 'package:sky/widgets/framework.dart';
import 'package:sky_services/media/media.mojom.dart';
import 'package:vector_math/vector_math.dart';
part 'action.dart';
part 'constraint.dart';
part 'action_spline.dart';
part 'color_secuence.dart';
part 'image_map.dart';
part 'layer.dart';
part 'node.dart';
part 'node3d.dart';
part 'node_with_size.dart';
part 'particle_system.dart';
part 'sound.dart';
part 'sound_manager.dart';
part 'sprite.dart';
part 'spritesheet.dart';
part 'sprite_box.dart';
part 'sprite_widget.dart';
part 'texture.dart';
part 'util.dart';
part 'virtual_joystick.dart';

View File

@@ -1,74 +0,0 @@
part of 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 {
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;
Image get image => _image;
/// Returns a texture by its name.
///
/// var myTexture = mySpriteSheet["example.png"];
Texture operator [](String fileName) => _textures[fileName];
}

View File

@@ -1,112 +0,0 @@
part of 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 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(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

@@ -1,104 +0,0 @@
part of sprites;
math.Random _random = new math.Random();
// Random methods
double randomDouble() {
return _random.nextDouble();
}
double randomSignedDouble() {
return _random.nextDouble() * 2.0 - 1.0;
}
int randomInt(int max) {
return _random.nextInt(max);
}
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);
}
class GameMath {
static final _Atan2Constants _atan2 = new _Atan2Constants();
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()];
}
}
}
static double pointQuickDist(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;
}
}
static double filter (double a, double b, double filterFactor) {
return (a * (1-filterFactor)) + b * filterFactor;
}
}

View File

@@ -1,62 +0,0 @@
part of 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(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);
}
}

View File

@@ -2,8 +2,11 @@ name: asteroids
dependencies:
sky: any
sky_tools: any
skysprites: any
dependency_overrides:
material_design_icons:
path: ../../sky/packages/material_design_icons
sky:
path: ../../sky/packages/sky
skysprites:
path: ../../skysprites

View File

@@ -1,5 +1,3 @@
import 'lib/sprites.dart';
import 'dart:sky';
import 'package:sky/mojo/asset_bundle.dart';
@@ -7,6 +5,7 @@ import 'package:sky/rendering/object.dart';
import 'package:sky/theme/colors.dart' as colors;
import 'package:sky/widgets/basic.dart';
import 'package:sky/widgets.dart';
import 'package:skysprites/skysprites.dart';
AssetBundle _initBundle() {
if (rootBundle != null)

View File

@@ -5,8 +5,7 @@ import 'package:sky/mojo/asset_bundle.dart';
import 'package:sky/rendering/object.dart';
import 'package:sky/theme/colors.dart' as colors;
import 'package:sky/widgets.dart';
import 'lib/sprites.dart';
import 'package:skysprites/skysprites.dart';
AssetBundle _initBundle() {
if (rootBundle != null)