node.dart 24.6 KB
Newer Older
1
part of flutter_sprites;
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17

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 {

Ian Hickson's avatar
Ian Hickson committed
18 19 20 21 22 23 24 25
  // Constructors

  /// Creates a new [Node] without any transformation.
  ///
  ///     Node myNode = new Node();
  Node();


26 27 28 29 30 31 32 33 34
  // Member variables

  SpriteBox _spriteBox;
  Node _parent;

  Point _position = Point.origin;
  double _rotation = 0.0;

  Matrix4 _transformMatrix = new Matrix4.identity();
35
  Matrix4 _transformMatrixInverse;
36 37 38 39 40 41
  Matrix4 _transformMatrixNodeToBox;
  Matrix4 _transformMatrixBoxToNode;

  double _scaleX = 1.0;
  double _scaleY = 1.0;

42 43 44
  double _skewX = 0.0;
  double _skewY = 0.0;

45 46 47 48 49 50 51
  /// The visibility of this node and its children.
  bool visible = true;

  double _zPosition = 0.0;
  int _addedOrder;
  int _childrenLastAddedOrder = 0;
  bool _childrenNeedSorting = false;
52
  Matrix4 _savedTotalMatrix;
53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72

  /// 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;

Hixie's avatar
Hixie committed
73
  List<Node> _children = <Node>[];
74 75 76

  ActionController _actions;

77 78 79
  /// The [ActionController] associated with this node.
  ///
  ///     myNode.actions.run(myAction);
80 81 82
  ActionController get actions {
    if (_actions == null) {
      _actions = new ActionController();
83
      if (_spriteBox != null) _spriteBox._actionControllers = null;
84 85 86 87
    }
    return _actions;
  }

88 89
  List<Constraint> _constraints;

90 91
  /// A [List] of [Constraint]s that will be applied to the node.
  /// The constraints are applied after the [update] method has been called.
92 93 94 95
  List<Constraint> get constraints {
    return _constraints;
  }

96
  void set constraints(List<Constraint> constraints) {
97 98 99 100
    _constraints = constraints;
    if (_spriteBox != null) _spriteBox._constrainedNodes = null;
  }

101 102 103
  /// Called to apply the [constraints] to the node. Normally, this method is
  /// called automatically by the [SpriteBox], but it can be called manually
  /// if the constraints need to be applied immediately.
104 105 106 107 108 109 110 111
  void applyConstraints(double dt) {
    if (_constraints == null) return;

    for (Constraint constraint in _constraints) {
      constraint.constrain(this, dt);
    }
  }

112 113 114 115 116 117 118 119

  // 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
Hixie's avatar
Hixie committed
120
  ///     SpriteBoxTransformMode transformMode = myNode.spriteBox.transformMode;
121 122 123 124 125 126 127 128 129 130 131 132
  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;
133

134 135
  void set rotation(double rotation) {
    assert(rotation != null);
136

137 138
    if (_physicsBody != null && (parent is PhysicsWorld || parent is PhysicsGroup)) {
      _updatePhysicsRotation(physicsBody, rotation, parent);
139 140 141 142 143 144 145
      return;
    }

    _rotation = rotation;
    invalidateTransformMatrix();
  }

146
  void _updatePhysicsRotation(PhysicsBody body, double rotation, Node physicsParent) {
147 148 149 150 151 152 153 154 155 156 157 158 159
    PhysicsWorld world = _physicsWorld(physicsParent);
    if (world == null) return;
    world._updateRotation(body, _rotationToPhysics(rotation, physicsParent));
  }

  PhysicsWorld _physicsWorld(Node parent) {
    if (parent is PhysicsWorld) {
      return parent;
    }
    else if (parent is PhysicsGroup) {
      return _physicsWorld(parent.parent);
    }
    else {
160
      assert(false);
161 162 163 164 165 166 167 168 169 170 171 172 173 174
      return null;
    }
  }

  double _rotationToPhysics(double rotation, Node physicsParent) {
    if (physicsParent is PhysicsWorld) {
      return rotation;
    } else if (physicsParent is PhysicsGroup) {
      return _rotationToPhysics(rotation + physicsParent.rotation, physicsParent.parent);
    } else {
      assert(false);
      return null;
    }
  }
175

176
  double _rotationFromPhysics(double rotation, Node physicsParent) {
177
    if (physicsParent is PhysicsWorld) {
178
      return rotation;
179
    } else if (physicsParent is PhysicsGroup) {
180
      return _rotationToPhysics(rotation - physicsParent.rotation, physicsParent.parent);
181 182
    } else {
      assert(false);
183
      return null;
184 185 186
    }
  }

187
  void _setRotationFromPhysics(double rotation, Node physicsParent) {
188
    assert(rotation != null);
189
    _rotation = _rotationFromPhysics(rotation, physicsParent);
190
    invalidateTransformMatrix();
191 192
  }

193 194
  void teleportRotation(double rotation) {
    assert(rotation != null);
195 196
    if (_physicsBody != null && (parent is PhysicsWorld || parent is PhysicsGroup)) {
      rotation = _rotationToPhysics(rotation, parent);
197 198 199 200
      _physicsBody._body.setTransform(_physicsBody._body.position, radians(rotation));
      _physicsBody._body.angularVelocity = 0.0;
      _physicsBody._body.setType(box2d.BodyType.STATIC);
    }
201
    _setRotationFromPhysics(rotation, parent);
202 203
  }

204 205 206 207
  /// The position of this node relative to its parent.
  ///
  ///     myNode.position = new Point(42.0, 42.0);
  Point get position => _position;
208

209 210
  void set position(Point position) {
    assert(position != null);
211

212 213
    if (_physicsBody != null && (parent is PhysicsWorld || parent is PhysicsGroup)) {
      _updatePhysicsPosition(this.physicsBody, position, parent);
214 215 216 217 218 219 220
      return;
    }

    _position = position;
    invalidateTransformMatrix();
  }

221
  void _updatePhysicsPosition(PhysicsBody body, Point position, Node physicsParent) {
222 223 224 225
    PhysicsWorld world = _physicsWorld(physicsParent);
    if (world == null) return;
    world._updatePosition(body, _positionToPhysics(position, physicsParent));
  }
226

227
  Point _positionToPhysics(Point position, Node physicsParent) {
228
    if (physicsParent is PhysicsWorld) {
229
      return position;
230
    } else if (physicsParent is PhysicsGroup) {
231
      // Transform the position
232
      Vector4 parentPos = physicsParent.transformMatrix.transform(new Vector4(position.x, position.y, 0.0, 1.0));
233 234
      Point newPos = new Point(parentPos.x, parentPos.y);
      return _positionToPhysics(newPos, physicsParent.parent);
235 236
    } else {
      assert(false);
237
      return null;
238 239 240
    }
  }

241
  void _setPositionFromPhysics(Point position, Node physicsParent) {
242
    assert(position != null);
243
    _position = _positionFromPhysics(position, physicsParent);
244
    invalidateTransformMatrix();
245 246
  }

247 248 249 250 251
  Point _positionFromPhysics(Point position, Node physicsParent) {
    if (physicsParent is PhysicsWorld) {
      return position;
    } else if (physicsParent is PhysicsGroup) {
      // Transform the position
252
      Vector4 parentPos = physicsParent._inverseMatrix().transform(new Vector4(position.x, position.y, 0.0, 1.0));
253 254 255 256 257 258 259 260
      Point newPos = new Point(parentPos.x, parentPos.y);
      return _positionToPhysics(newPos, physicsParent.parent);
    } else {
      assert(false);
      return null;
    }
  }

261 262
  void teleportPosition(Point position) {
    assert(position != null);
263 264
    PhysicsWorld world = _physicsWorld(parent);

265 266
    if (_physicsBody != null && (parent is PhysicsWorld || parent is PhysicsGroup)) {
      position = _positionToPhysics(position, parent);
267 268
      _physicsBody._body.setTransform(
        new Vector2(
269 270
          position.x / world.b2WorldToNodeConversionFactor,
          position.y / world.b2WorldToNodeConversionFactor
271 272 273 274 275 276
        ),
        _physicsBody._body.getAngle()
      );
      _physicsBody._body.linearVelocity = new Vector2.zero();
      _physicsBody._body.setType(box2d.BodyType.STATIC);
    }
277
    _setPositionFromPhysics(position, parent);
278 279
  }

280 281 282
  /// The skew along the x-axis of this node in degrees.
  ///
  ///     myNode.skewX = 45.0;
283 284 285 286 287 288 289 290
  double get skewX => _skewX;

  void set skewX (double skewX) {
    assert(skewX != null);
    _skewX = skewX;
    invalidateTransformMatrix();
  }

291 292 293
  /// The skew along the y-axis of this node in degrees.
  ///
  ///     myNode.skewY = 45.0;
294 295 296 297 298 299 300 301
  double get skewY => _skewY;

  void set skewY (double skewY) {
    assert(skewY != null);
    _skewY = skewY;
    invalidateTransformMatrix();
  }

302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331
  /// 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);
332

333 334
    if (_physicsBody != null && (parent is PhysicsWorld || parent is PhysicsGroup)) {
      _updatePhysicsScale(physicsBody, scale, parent);
335 336
    }

337
    _scaleX = _scaleY = scale;
338
    invalidateTransformMatrix();
339 340
  }

341 342
  void _updatePhysicsScale(PhysicsBody body, double scale, Node physicsParent) {
    if (physicsParent == null) return;
343 344
    _physicsWorld(physicsParent)._updateScale(body, _scaleToPhysics(scale, physicsParent));
  }
345

346
  double _scaleToPhysics(double scale, Node physicsParent) {
347
    if (physicsParent is PhysicsWorld) {
348
      return scale;
349
    } else if (physicsParent is PhysicsGroup) {
350
      return _scaleToPhysics(scale * physicsParent.scale, physicsParent.parent);
351 352
    } else {
      assert(false);
353
      return null;
354 355 356
    }
  }

357 358 359 360 361 362 363
  /// 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);
364 365
    assert(physicsBody == null);

366
    _scaleX = scaleX;
367
    invalidateTransformMatrix();
368 369 370 371 372 373 374 375 376
  }

  /// 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);
377 378
    assert(physicsBody == null);

379
    _scaleY = scaleY;
380
    invalidateTransformMatrix();
381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405
  }

  /// 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);
406
    assert(!(child is PhysicsGroup) || this is PhysicsGroup || this is PhysicsWorld);
407

408 409 410 411 412 413 414 415
    assert(() {
      Node node = this;
      while (node.parent != null)
        node = node.parent;
      assert(node != child); // indicates we are about to create a cycle
      return true;
    });

416 417 418 419 420 421
    _childrenNeedSorting = true;
    _children.add(child);
    child._parent = this;
    child._spriteBox = this._spriteBox;
    _childrenLastAddedOrder += 1;
    child._addedOrder = _childrenLastAddedOrder;
422
    if (_spriteBox != null) _spriteBox._registerNode(child);
423 424 425 426

    if (child is PhysicsGroup) {
      child._attachGroup(child, child._world);
    }
427 428 429 430 431 432 433 434 435 436
  }

  /// 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;
437
      if (_spriteBox != null) _spriteBox._deregisterNode(child);
438 439 440 441
    }

    if (child is PhysicsGroup) {
      child._detachGroup(child);
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460
    }
  }

  /// 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;
    }
Hixie's avatar
Hixie committed
461
    _children = <Node>[];
462
    _childrenNeedSorting = false;
463
    if (_spriteBox != null) _spriteBox._deregisterNode(null);
464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491
  }

  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 {
492 493
    if (_transformMatrix == null) {
      _transformMatrix = computeTransformMatrix();
494
    }
495 496
    return _transformMatrix;
  }
497

498 499 500
  /// 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.
501
  Matrix4 computeTransformMatrix() {
502
    double cx, sx, cy, sy;
503

504 505 506 507 508 509 510 511 512
    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);
513

514 515 516 517 518 519 520
      cx = math.cos(radiansX);
      sx = math.sin(radiansX);
      cy = math.cos(radiansY);
      sy = math.sin(radiansY);
    }

    // Create transformation matrix for scale, position and rotation
521
    Matrix4 matrix = new Matrix4(cy * _scaleX, sy * _scaleX, 0.0, 0.0,
522 523 524
               -sx * _scaleY, cx * _scaleY, 0.0, 0.0,
               0.0, 0.0, 1.0, 0.0,
              _position.x, _position.y, 0.0, 1.0);
525

526 527 528 529 530 531 532 533 534
    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);
    }

535
    return matrix;
536 537
  }

538 539 540
  /// Invalidates the current transform matrix. If the [computeTransformMatrix]
  /// method is overidden, this method should be called whenever a property
  /// changes that affects the matrix.
541
  void invalidateTransformMatrix() {
542
    _transformMatrix = null;
543
    _transformMatrixInverse = null;
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
    _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;
  }

588 589 590 591 592 593 594 595
  Matrix4 _inverseMatrix() {
    if (_transformMatrixInverse == null) {
      _transformMatrixInverse = new Matrix4.copy(transformMatrix);
      _transformMatrixInverse.invert();
    }
    return _transformMatrixInverse;
  }

596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
  /// 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
660

Adam Barth's avatar
Adam Barth committed
661
  void _visit(Canvas canvas, Matrix4 totalMatrix) {
662 663 664
    assert(canvas != null);
    if (!visible) return;

665 666 667
    _prePaint(canvas, totalMatrix);
    _visitChildren(canvas, totalMatrix);
    _postPaint(canvas, totalMatrix);
668
  }
669

Adam Barth's avatar
Adam Barth committed
670
  void _prePaint(Canvas canvas, Matrix4 matrix) {
671
    _savedTotalMatrix = new Matrix4.copy(matrix);
672 673

    // Get the transformation matrix and apply transform
674
    matrix.multiply(transformMatrix);
675 676 677 678 679 680 681 682 683 684
  }

  /// 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.
  ///
Adam Barth's avatar
Adam Barth committed
685
  ///     void paint(Canvas canvas) {
686 687 688 689 690 691 692
  ///       canvas.save();
  ///       applyTransformForPivot(canvas);
  ///
  ///       // Do painting here
  ///
  ///       canvas.restore();
  ///     }
Adam Barth's avatar
Adam Barth committed
693
  void paint(Canvas canvas) {
694
  }
695

Adam Barth's avatar
Adam Barth committed
696
  void _visitChildren(Canvas canvas, Matrix4 totalMatrix) {
697 698 699 700 701 702 703 704 705
    // 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;
706
      child._visit(canvas, totalMatrix);
707 708 709 710
      i++;
    }

    // Paint this node
711
    canvas.setMatrix(totalMatrix.storage);
712 713 714 715 716
    paint(canvas);

    // Visit children in front of this node
    while (i < _children.length) {
      Node child = _children[i];
717
      child._visit(canvas, totalMatrix);
718 719 720
      i++;
    }
  }
721

Adam Barth's avatar
Adam Barth committed
722
  void _postPaint(Canvas canvas, Matrix4 totalMatrix) {
723
    totalMatrix.setFrom(_savedTotalMatrix);
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
  }

  // 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) {
782
  ///         if (event.type == PointerDownEvent) {
783 784
  ///           opacity = 0.5;
  ///         }
785
  ///         else if (event.type == PointerUpEvent) {
786 787 788 789 790 791 792 793
  ///           opacity = 1.0;
  ///         }
  ///         return true;
  ///       }
  ///     }
  bool handleEvent(SpriteBoxEvent event) {
    return false;
  }
794 795 796 797 798

  // Physics

  PhysicsBody _physicsBody;

799 800 801 802 803 804 805
  /// The physics body associated with this node. If a physics body is assigned,
  /// and the node is a child of a [PhysicsWorld] or a [PhysicsGroup] the
  /// node's position and rotation will be controlled by the body.
  ///
  ///     myNode.physicsBody = new PhysicsBody(
  ///       new PhysicsShapeCircle(Point.zero, 20.0)
  ///     );
806 807
  PhysicsBody get physicsBody => _physicsBody;

808
  void set physicsBody(PhysicsBody physicsBody) {
809
    if (parent != null) {
810
      assert(parent is PhysicsWorld);
811 812 813 814 815 816 817 818 819 820

      if (physicsBody == null) {
        physicsBody._detach();
      } else {
        physicsBody._attach(parent, this);
      }
    }

    _physicsBody = physicsBody;
  }
821
}