forked from robterrell/cocos2d-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNode.js
692 lines (575 loc) · 18.4 KB
/
Node.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
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
588
589
590
591
592
593
594
595
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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
'use strict'
//{{{ Imports
var util = require('util')
, events = require('events')
, geo = require('geometry')
, ccp = geo.ccp
var Scheduler = require('../Scheduler').Scheduler
, ActionManager = require('../ActionManager').ActionManager
//}}}
/**
* @class
* The base class all visual elements extend from
*
* @memberOf cocos.nodes
*/
function Node () {
this.contentSize = new geo.Size(0, 0)
this.anchorPoint = ccp(0.5, 0.5)
this.anchorPointInPixels = ccp(0, 0)
this.position = ccp(0, 0)
this.children = []
events.addPropertyListener(this, 'scaleX scaleY rotation position anchorPoint contentSize isRelativeAnchorPoint'.w, 'change', this._dirtyTransform.bind(this))
events.addPropertyListener(this, 'anchorPoint contentSize'.w, 'change', this._updateAnchorPointInPixels.bind(this))
events.addPropertyListener(this, 'opacity visible'.w, 'change', this._dirtyDraw.bind(this))
}
Node.inherit(Object, /** @lends cocos.nodes.Node# */ {
/**
* Is the node visible
* @type Boolean
*/
visible: true
/**
* Position relative to parent node
* @type geometry.Point
*/
, position: null
/**
* Parent node
* @type cocos.nodes.Node
* @readonly
*/
, parent: null
/**
* Unique tag to identify the node
* @type String
*/
, tag: null
/**
* Size of the node
* @type geometry.Size
*/
, contentSize: null
/**
* Nodes Z index. i.e. draw order
* @type Integer
*/
, zOrder: 0
/**
* Anchor point for scaling and rotation. 0x0 is top left and 1x1 is bottom right
* @type geometry.Point
*/
, anchorPoint: null
/**
* Anchor point for scaling and rotation in pixels from top left
* @type geometry.Point
*/
, anchorPointInPixels: null
/**
* Rotation angle in degrees
* @type Float
*/
, rotation: 0
/**
* X scale factor
* @type Float
*/
, scaleX: 1
/**
* Y scale factor
* @type Float
*/
, scaleY: 1
/**
* Opacity of the Node. 0 is totally transparent, 255 is totally opaque
* @type Float
*/
, opacity: 255
/**
* Is the node active in the scene
* @type Boolean
* @readonly
*/
, isRunning: false
/**
* Is the anchor point relative to the Node
* @type Boolean
*/
, isRelativeAnchorPoint: true
/**
* Has a property changed the requires recaculation of the transform matrix
* @type Boolean
*/
, isTransformDirty: true
, isInverseDirty: true
, inverse: null
/**
* Current transform matrix used to render the Node. Set by cocos.nodes.Node#nodeToParentTransform
* @type Boolean
*/
, transformMatrix: null
/**
* The child Nodes
* @type {cocos.nodes.Node[]}
*/
, children: null
/**
* @private
* Calculates the anchor point in pixels and updates the
* anchorPointInPixels property
*/
, _updateAnchorPointInPixels: function () {
var ap = this.anchorPoint
, cs = this.contentSize
this.anchorPointInPixels = ccp(cs.width * ap.x, cs.height * ap.y)
}
/**
* Add a child Node
*
* @opt {cocos.nodes.Node} child The child node to add
* @opt {Integer} [z] Z Index for the child
* @opt {Integer|String} [tag] A tag to reference the child with
* @returns {cocos.nodes.Node} The node the child was added to. i.e. 'this'
*/
, addChild: function (opts) {
if (opts instanceof Node) {
return this.addChild({child: opts})
}
var child = opts.child
, z = opts.z
, tag = opts.tag
, added = false
if (z === undefined || z === null) {
z = child.zOrder
}
//this.insertChild({child: child, z:z})
var childLen = this.children.length
, i, c
for (i = 0; i < childLen; i++) {
c = this.children[i]
if (c.zOrder > z) {
added = true
this.children.splice(i, 0, child)
break
}
}
if (!added) {
this.children.push(child)
}
child.tag = tag
child.zOrder = z
child.parent = this
if (this.isRunning) {
child.onEnter()
}
return this
}
/**
* Get a child node via its tag. Returns null if no Node is found
*
* @opt {String} tag Tag of the Node to return
*
* @returns cocos.nodes.Node
*/
, getChild: function (opts) {
var tag = opts.tag
for (var i = 0; i < this.children.length; i++) {
if (this.children[i].tag == tag) {
return this.children[i]
}
}
return null
}
/**
* Remove a child node.
*
* If 'cleanup' is true all actions and scheduled methods will be removed
* from the child and its children.
*
* @opt {cocos.nodes.Node} child The Node to remove
* @opt {Boolean} [cleanup=false] Should a cleanup be performed after removing the Node
*/
, removeChild: function (opts) {
if (opts instanceof Node) {
return this.removeChild({child: opts})
}
var child = opts.child
, cleanup = opts.cleanup
if (!child) {
return
}
var children = this.children
, idx = children.indexOf(child)
if (idx > -1) {
this._detachChild({child: child, cleanup: cleanup})
}
}
/**
* Remove all child nodes.
*
* If 'cleanup' is true all actions and scheduled methods will be removed
* from the child and its children.
*
* @opt {Boolean} [cleanup=false] Should a cleanup be performed after removing the Node
*/
, removeChildren: function (opts) {
var children = this.children
, isRunning = this.isRunning
// Perform cleanup on each child but can't call removeChild()
// due to Array.splice's destructive nature during iteration.
for (var i = 0; i < children.length; i++) {
if (opts.cleanup) {
children[i].cleanup()
}
if (isRunning) {
children[i].onExit()
}
children[i].parent = null
}
// Now safe to empty children list
this.children = []
}
/**
* @private
* Detach the child node from this node
*
* @opt {cocos.nodes.Node} child The Node to remove
* @opt {Boolean} [cleanup=false] Should a cleanup be performed after removing the Node
*/
, _detachChild: function (opts) {
var child = opts.child
, cleanup = opts.cleanup
var children = this.children
, isRunning = this.isRunning
, idx = children.indexOf(child)
if (isRunning) {
child.onExit()
}
if (cleanup) {
child.cleanup()
}
child.parent = null
children.splice(idx, 1)
}
/**
* Change the Z index of a child node. Other child nodes will have their Z
* index adjusted to accommodate.
*
* @opt {cocos.nodes.Node} child Child node to reorder
* @opt {Integer} z The new Z index for the child
*/
, reorderChild: function (opts) {
var child = opts.child
, z = opts.z
, pos = this.children.indexOf(child)
if (pos == -1) {
throw "Node isn't a child of this node"
}
child.zOrder = z
// Remove child
this.children.splice(pos, 1)
// Add child back at correct location
var added = false
, childLen = this.children.length
, i, c
for (i = 0; i < childLen; i++) {
c = this.children[i]
if (c.zOrder > z) {
added = true
this.children.splice(i, 0, child)
break
}
}
if (!added) {
this.children.push(child)
}
}
/**
* Draws the node. Override to do custom drawing. If it's less efficient to
* draw only the area inside the rect then don't bother. The result will be
* clipped to that area anyway.
*
* @param {CanvasRenderingContext2D} context Canvas rendering context
* @param {geometry.Rect} rect Rectangular region that needs redrawing. Limit drawing to this area only if it's more efficient to do so.
*/
, draw: function (context, rect) {
// All draw code goes here
}
/**
* The scale factor for the node. Only valid is scaleX and scaleY are identical
*
* @type Float
*/
, get scale () {
if (this.scaleX != this.scaleY) {
throw "scaleX and scaleY aren't identical"
}
return this.scaleX
}
/**
* Sets both scaleX and scaleY to the given value
*
* @type Float
*/
, set scale (val) {
this.scaleX = val
this.scaleY = val
}
/**
* Schedule a timer to call the 'update' method on this node every frame
*
* @opt {Integer} [priority=0] Priority order for when the method should be called
*/
, scheduleUpdate: function (opts) {
opts = opts || {}
var priority = opts.priority || 0
Scheduler.sharedScheduler.scheduleUpdate({target: this, priority: priority, paused: !this.isRunning})
}
/**
* Triggered when the node is added to a scene
*
* @event
*/
, onEnter: function () {
this.children.forEach(function (child) { child.onEnter() })
this.resumeSchedulerAndActions()
this.isRunning = true
}
/**
* Triggered when the node is removed from a scene
*
* @event
*/
, onExit: function () {
this.pauseSchedulerAndActions()
this.isRunning = false
this.children.forEach(function (child) { child.onExit() })
}
, cleanup: function () {
this.stopAllActions()
this.unscheduleAllSelectors()
this.children.forEach(function (child) { child.cleanup() })
}
, resumeSchedulerAndActions: function () {
Scheduler.sharedScheduler.resumeTarget(this)
ActionManager.sharedManager.resumeTarget(this)
}
, pauseSchedulerAndActions: function () {
Scheduler.sharedScheduler.pauseTarget(this)
ActionManager.sharedManager.pauseTarget(this)
}
, unscheduleSelector: function (selector) {
Scheduler.sharedScheduler.unschedule({target: this, method: selector})
}
, unscheduleAllSelectors: function () {
Scheduler.sharedScheduler.unscheduleAllSelectorsForTarget(this)
}
/**
* Stop all running actions on this node
*/
, stopAllActions: function () {
ActionManager.sharedManager.removeAllActionsFromTarget(this)
}
/**
* Called automatically every frame and triggers the call to 'draw' this
* node and its chidlren in the correct order.
*
* For custom drawing override the 'draw' method. Only override this if you
* really need to do something special.
*
* @param {CanvasRenderingContext2D} context Canvas rendering context
* @param {geometry.Rect} [rect] Area that needs redrawing
*/
, visit: function (context, rect) {
if (!this.visible) {
return
}
context.save()
this.transform(context)
// Set alpha value (global only for now)
context.globalAlpha = this.opacity / 255.0
// Adjust redraw region by nodes position
if (rect) {
var pos = this.position
rect = new geo.Rect(rect.origin.x - pos.x, rect.origin.y - pos.y, rect.size.width, rect.size.height)
}
// Draw background nodes
this.children.forEach(function (child, i) {
if (child.zOrder < 0) {
child.visit(context, rect)
}
})
this.draw(context, rect)
// Draw foreground nodes
this.children.forEach(function (child, i) {
if (child.zOrder >= 0) {
child.visit(context, rect)
}
})
context.restore()
}
/**
* Transforms the node by its scale, rotation and position. Called automatically when one of these changes
*
* @param {CanvasRenderingContext2D} context Canvas rendering context
*/
, transform: function (context) {
// Translate
if (this.isRelativeAnchorPoint && (this.anchorPointInPixels.x !== 0 || this.anchorPointInPixels.y !== 0)) {
context.translate(Math.round(-this.anchorPointInPixels.x), Math.round(-this.anchorPointInPixels.y))
}
if (this.anchorPointInPixels.x !== 0 || this.anchorPointInPixels.y !== 0) {
context.translate(Math.round(this.position.x + this.anchorPointInPixels.x), Math.round(this.position.y + this.anchorPointInPixels.y))
} else {
context.translate(Math.round(this.position.x), Math.round(this.position.y))
}
// Rotate
if (FLIP_Y_AXIS) {
context.rotate(-geo.degreesToRadians(this.rotation))
} else {
context.rotate(geo.degreesToRadians(this.rotation))
}
// Scale
context.scale(this.scaleX, this.scaleY)
if (this.anchorPointInPixels.x !== 0 || this.anchorPointInPixels.y !== 0) {
context.translate(Math.round(-this.anchorPointInPixels.x), Math.round(-this.anchorPointInPixels.y))
}
}
/**
* Run an action on the node
*
* @param {cocos.actions.Action} action Action to run
*/
, runAction: function (action) {
ActionManager.sharedManager.addAction({action: action, target: this, paused: this.isRunning})
}
/**
* @opt {String} tag Tag of the action to return
*/
, getAction: function (opts) {
return ActionManager.sharedManager.getActionFromTarget({target: this, tag: opts.tag})
}
, nodeToParentTransform: function () {
if (this.isTransformDirty) {
this.transformMatrix = geo.affineTransformIdentity()
if (!this.isRelativeAnchorPoint && !geo.pointEqualToPoint(this.anchorPointInPixels, ccp(0, 0))) {
this.transformMatrix = geo.affineTransformTranslate(this.transformMatrix, this.anchorPointInPixels.x, this.anchorPointInPixels.y)
}
if (!geo.pointEqualToPoint(this.position, ccp(0, 0))) {
this.transformMatrix = geo.affineTransformTranslate(this.transformMatrix, this.position.x, this.position.y)
}
if (this.rotation !== 0) {
this.transformMatrix = geo.affineTransformRotate(this.transformMatrix, -geo.degreesToRadians(this.rotation))
}
if (!(this.scaleX == 1 && this.scaleY == 1)) {
this.transformMatrix = geo.affineTransformScale(this.transformMatrix, this.scaleX, this.scaleY)
}
if (!geo.pointEqualToPoint(this.anchorPointInPixels, ccp(0, 0))) {
this.transformMatrix = geo.affineTransformTranslate(this.transformMatrix, -this.anchorPointInPixels.x, -this.anchorPointInPixels.y)
}
this.isTransformDirty = false
}
return this.transformMatrix
}
, parentToNodeTransform: function () {
// TODO
}
, nodeToWorldTransform: function () {
var t = this.nodeToParentTransform()
var p
for (p = this.parent; p; p = p.parent) {
t = geo.affineTransformConcat(t, p.nodeToParentTransform())
}
return t
}
, worldToNodeTransform: function () {
return geo.affineTransformInvert(this.nodeToWorldTransform())
}
, convertToNodeSpace: function (worldPoint) {
return geo.pointApplyAffineTransform(worldPoint, this.worldToNodeTransform())
}
/**
* Rectangle bounding box relative to its parent Node
*
* @type geometry.Rect
*/
, get boundingBox () {
if (this.isTransformDirty || !this._boundingBox) {
this._updateBoundingBox()
}
return this._boundingBox
}
, _updateBoundingBox: function () {
var cs = this.contentSize
, rect = new geo.Rect(0, 0, cs.width, cs.height)
this._boundingBox = geo.rectApplyAffineTransform(rect, this.nodeToParentTransform())
}
/**
* Rectangle bounding box relative to the world
*
* @type geometry.Rect
*/
, get worldBoundingBox () {
var cs = this.contentSize
, rect = new geo.Rect(0, 0, cs.width, cs.height)
rect = geo.rectApplyAffineTransform(rect, this.nodeToWorldTransform())
return rect
}
/**
* The area of the node currently visible on screen. Returns an rect even
* if visible is false.
*
* @type geometry.Rect
*/
, get visibleRect () {
var s = require('../Director').Director.sharedDirector.winSize
, rect = new geo.Rect(0, 0, s.width, s.height)
return geo.rectApplyAffineTransform(rect, this.worldToNodeTransform())
}
/**
* @private
*/
, _dirtyTransform: function () {
var oldBB = this.boundingBox
this.isTransformDirty = true
this._dirtyDraw(oldBB)
events.trigger(this, 'transformdirty', oldBB)
}
, _dirtyDraw: function (oldBB) {
events.trigger(this, 'drawdirty', (oldBB instanceof geo.Rect) ? oldBB : void(0))
}
/**
* Schedules a custom method with an interval time in seconds.
* If time is 0, it will be ticked every frame.
* If time is 0, it is recommended to use 'scheduleUpdate' instead.
*
* If the method is already scheduled, then the interval parameter will
* be updated without scheduling it again.
*
* @opt {String|Function} method Function of method name to schedule
* @opt {Float} [interval=0] Interval in seconds
*/
, schedule: function (opts) {
if (typeof opts == 'string') {
return this.schedule({method: opts, interval: 0})
}
opts.interval = opts.interval || 0
Scheduler.sharedScheduler.schedule({target: this, method: opts.method, interval: opts.interval, paused: this.isRunning})
}
/**
* Unschedules a custom method
*
* @param {String|Function} method
*/
, unschedule: function (method) {
if (!method) {
return
}
if (typeof method == 'string') {
method = this[method]
}
Scheduler.sharedScheduler.unschedule({target: this, method: method})
}
})
module.exports.Node = Node
// vim:et:st=4:fdm=marker:fdl=0:fdc=1