forked from robterrell/cocos2d-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDirector.js
599 lines (493 loc) · 16 KB
/
Director.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
'use strict'
var util = require('util')
, events = require('events')
, geo = require('geometry')
, ccp = geo.ccp
var EventDispatcher = require('./EventDispatcher').EventDispatcher
, Scheduler = require('./Scheduler').Scheduler
/**
* Create a new instance of Director. This is a singleton so you shouldn't use
* the constructor directly. Instead grab the shared instance using the
* cocos.Director.sharedDirector property.
*
* @class
* Creates and handles the main view and manages how and when to execute the
* Scenes.
*
* This class is a singleton so don't instantiate it yourself, instead use
* cocos.Director.sharedDirector to return the instance.
*
* @memberOf cocos
* @singleton
*/
function Director () {
if (Director._instance) {
throw new Error('Director instance already exists')
}
this.sceneStack = []
this.window = parent.window
this.document = this.window.document
// Prevent writing to some properties
util.makeReadonly(this, 'canvas context sceneStack winSize isReady document window container'.w)
}
Director.inherit(Object, /** @lends cocos.Director# */ {
/**
* Background colour of the canvas. It can be any valid CSS colour.
* @type String
*/
backgroundColor: 'rgb(0, 0, 0)'
/**
* DOM Window of the containing page
*
* The global 'window' property is a sandbox and not the global of the
* containing page. If you need to access the real window, use this
* property.
*
* @type DOMWindow
* @readonly
*/
, window: null
/**
* DOM Document of the containing page
*
* The global 'document' property is a sandbox and not the global of the
* containing page. If you need to access the real document, use this
* property.
*
* @type Document
* @readonly
*/
, document: null
/**
* Container DIV around the canvas
*
* This element is created dynamically. Its parent is the HTML element the
* script was added into.
*
* @type HTMLDivElement
* @readonly
*/
, container: null
/**
* Canvas HTML element
* @type HTMLCanvasElement
* @readonly
*/
, canvas: null
/**
* Canvas rendering context
* @type CanvasRenderingContext2D
* @readonly
*/
, context: null
/**
* Stack of scenes
* @type cocos.nodes.Scene[]
* @readonly
*/
, sceneStack: null
/**
* Size of the canvas
* @type geometry.Size
* @readonly
*/
, winSize: null
/**
* Whether the scene is paused. When true the framerate will drop to conserve CPU
* @type Boolean
*/
, isPaused: false
/**
* Maximum possible framerate
* @type Integer
*/
, maxFrameRate: 30
/**
* Should the framerate be drawn in the corner
* @type Boolean
*/
, displayFPS: false
/**
* Scene that draws the preload progres bar
* @type cocos.nodes.PreloadScene
*/
, preloadScene: null
/**
* Has everything been preloaded and ready to use
* @type Boolean
* @readonly
*/
, isReady: false
/**
* Number of milliseconds since last frame
* @type Float
* @readonly
*/
, dt: 0
/**
* @private
*/
, _nextDeltaTimeZero: false
/**
* @private
* @type Float
*/
, _lastUpdate: 0
/**
* @private
* @type cocos.nodes.Scene
*/
, _nextScene: null
/**
* Append to an HTML element. It will create this canvas tag and attach
* event listeners
*
* @param {HTMLElement} view Any HTML element to add the application to
*/
, attachInView: function (view) {
var document = this.document
view = view || window.container || document.body
while (view.firstChild) {
view.removeChild(view.firstChild)
}
// Wrapper <div> which can be used for adding special HTML elements if required
var container = this._container = document.createElement('div')
container.style.width = view.clientWidth + 'px'
container.style.height = view.clientHeight + 'px'
container.style.position = 'relative'
container.style.overflow = 'hidden'
view.appendChild(container)
view = container
var canvas = document.createElement('canvas')
canvas.style.verticalAlign = 'bottom'
this._canvas = canvas
canvas.setAttribute('width', view.clientWidth)
canvas.setAttribute('height', view.clientHeight)
var context = canvas.getContext('2d')
this._context = context
if (FLIP_Y_AXIS) {
context.translate(0, view.clientHeight)
context.scale(1, -1)
}
view.appendChild(canvas)
this._winSize = {width: view.clientWidth, height: view.clientHeight}
// Setup event handling
// Mouse events
var eventDispatcher = EventDispatcher.sharedDispatcher
, mouseDown = function (evt) {
evt.locationInWindow = ccp(evt.clientX, evt.clientY)
evt.locationInCanvas = this.convertEventToCanvas(evt)
var mouseDragged = function (evt) {
evt.locationInWindow = ccp(evt.clientX, evt.clientY)
evt.locationInCanvas = this.convertEventToCanvas(evt)
eventDispatcher.mouseDragged(evt)
}.bind(this)
, mouseUp = function (evt) {
evt.locationInWindow = ccp(evt.clientX, evt.clientY)
evt.locationInCanvas = this.convertEventToCanvas(evt)
document.body.removeEventListener('mousemove', mouseDragged, false)
document.body.removeEventListener('mouseup', mouseUp, false)
eventDispatcher.mouseUp(evt)
}.bind(this)
document.body.addEventListener('mousemove', mouseDragged, false)
document.body.addEventListener('mouseup', mouseUp, false)
eventDispatcher.mouseDown(evt)
}.bind(this)
, mouseMoved = function (evt) {
evt.locationInWindow = ccp(evt.clientX, evt.clientY)
evt.locationInCanvas = this.convertEventToCanvas(evt)
eventDispatcher.mouseMoved(evt)
}.bind(this)
canvas.addEventListener('mousedown', mouseDown, false)
canvas.addEventListener('mousemove', mouseMoved, false)
// Keyboard events
function keyDown(evt) {
this._keysDown = this._keysDown || {}
eventDispatcher.keyDown(evt)
}
function keyUp(evt) {
eventDispatcher.keyUp(evt)
}
document.documentElement.addEventListener('keydown', keyDown, false)
document.documentElement.addEventListener('keyup', keyUp, false)
}
/**
* Create and push a Preload Scene which will draw a progress bar while
* also preloading all assets.
*
* If you wish to customise the preload scene first inherit from cocos.nodes.PreloadScene
* and then set Director#preloadScene to an instance of your PreloadScene
*/
, runPreloadScene: function () {
if (!this.canvas) {
this.attachInView()
}
var preloader = this.preloadScene
if (!preloader) {
var PreloadScene = require('./nodes/PreloadScene').PreloadScene
preloader = new PreloadScene()
this.preloadScene = preloader
}
events.addListener(preloader, 'complete', function (preloader) {
this._isReady = true
events.trigger(this, 'ready', this)
}.bind(this))
this.pushScene(preloader)
this.startAnimation()
}
/**
* Enters the Director's main loop with the given Scene. Call it to run
* only your FIRST scene. Don't call it if there is already a running
* scene.
*
* @param {cocos.Scene} scene The scene to start
*/
, runWithScene: function (scene) {
var Scene = require('./nodes/Scene').Scene
if (!(scene instanceof Scene)) {
throw new Error("Director.runWithScene must be given an instance of Scene")
}
if (this._runningScene) {
throw new Error("You can't run a Scene if another Scene is already running. Use replaceScene or pushScene instead")
}
this.pushScene(scene)
this.startAnimation()
}
/**
* Replaces the running scene with a new one. The running scene is
* terminated. ONLY call it if there is a running scene.
*
* @param {cocos.Scene} scene The scene to replace with
*/
, replaceScene: function (scene) {
var Scene = require('./nodes/Scene').Scene
if (!(scene instanceof Scene)) {
throw new Error("Director.replaceScene must be given an instance of Scene")
}
var index = this.sceneStack.length
this._sendCleanupToScene = true
this.sceneStack.pop()
this.sceneStack.push(scene)
this._nextScene = scene
}
/**
* Pops out a scene from the queue. This scene will replace the running
* one. The running scene will be deleted. If there are no more scenes in
* the stack the execution is terminated. ONLY call it if there is a
* running scene.
*/
, popScene: function () {
throw new Error("Not implemented yet")
}
/**
* Suspends the execution of the running scene, pushing it on the stack of
* suspended scenes. The new scene will be executed. Try to avoid big
* stacks of pushed scenes to reduce memory allocation. ONLY call it if
* there is a running scene.
*
* @param {cocos.Scene} scene The scene to add to the stack
*/
, pushScene: function (scene) {
var Scene = require('./nodes/Scene').Scene
if (!(scene instanceof Scene)) {
throw new Error("Director.pushScene must be given an instance of Scene")
}
this._nextScene = scene
}
/**
* The main loop is triggered again. Call this function only if
* cocos.Directory#stopAnimation was called earlier.
*/
, startAnimation: function () {
if (!this.canvas) {
this.attachInView()
}
this._animating = true
this.animate()
}
/**
* Draws the scene after waiting for the next animation frame time. This
* controls the framerate.
*/
, animate: function() {
if (this._animating) {
this.drawScene()
this.animate._bound = this.animate._bound || this.animate.bind(this)
window.requestAnimationFrame(this.animate._bound, this.canvas)
}
}
/**
* Stops the animation. Nothing will be drawn. The main loop won't be
* triggered anymore. If you want to pause your animation call
* cocos.Directory#pause instead.
*/
, stopAnimation: function () {
if (this._animationTimer) {
clearInterval(this._animationTimer)
this._animationTimer = null
}
this._animating = false
}
/**
* @private
* Calculate time since last call
*/
, _calculateDeltaTime: function () {
var now = (new Date()).getTime() / 1000
if (this._nextDeltaTimeZero) {
this.dt = 0
this._nextDeltaTimeZero = false
}
this.dt = Math.max(0, now - this._lastUpdate)
this._lastUpdate = now
}
/**
* @private
* The main run loop
*/
, drawScene: function () {
this._calculateDeltaTime()
if (!this.isPaused) {
Scheduler.sharedScheduler.tick(this.dt)
}
var context = this.context
context.fillStyle = this.backgroundColor
context.fillRect(0, 0, this.winSize.width, this.winSize.height)
//this.canvas.width = this.canvas.width
if (this._nextScene) {
this._setNextScene()
}
var rect = new geo.Rect(0, 0, this.winSize.width, this.winSize.height)
if (rect) {
context.beginPath()
context.rect(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)
context.clip()
context.closePath()
}
this._runningScene.visit(context, rect)
if (SHOW_REDRAW_REGIONS) {
if (rect) {
context.beginPath()
context.rect(rect.origin.x, rect.origin.y, rect.size.width, rect.size.height)
context.fillStyle = "rgba(255, 0, 0, 0.5)"
//context.fill()
context.closePath()
}
}
if (this.displayFPS) {
this._showFPS()
}
}
/**
* @private
* Initialises the next scene
*/
, _setNextScene: function () {
// TODO transitions
if (this._runningScene) {
this._runningScene.onExit()
if (this._sendCleanupToScene) {
this._runningScene.cleanup()
}
}
this._runningScene = this._nextScene
this._nextScene = null
this._runningScene.onEnter()
}
/**
* Convert the coordinates in a mouse event so they're relative to the corner of the canvas
*
* @param {MouseEvent} evt
*/
, convertEventToCanvas: function (evt) {
var x = this.canvas.offsetLeft - document.documentElement.scrollLeft
, y = this.canvas.offsetTop - document.documentElement.scrollTop
var o = this.canvas
while ((o = o.offsetParent)) {
x += o.offsetLeft - o.scrollLeft
y += o.offsetTop - o.scrollTop
}
var p = geo.ccpSub(evt.locationInWindow, ccp(x, y))
if (FLIP_Y_AXIS) {
p.y = this.canvas.height - p.y
}
return p
}
/**
* @private
* Draw the FPS counter
*/
, _showFPS: function () {
if (!this._fpsLabel) {
var Label = require('./nodes/Label').Label
this._fpsLabel = new Label({string: '', fontSize: 16})
this._fpsLabel.anchorPoint = ccp(0, 0)
this._fpsLabel.position = ccp(10, 10)
this._frames = 0
this._accumDt = 0
}
this._frames++
this._accumDt += this.dt
if (this._accumDt > 1.0 / 3.0) {
var frameRate = this._frames / this._accumDt
this._frames = 0
this._accumDt = 0
this._fpsLabel.string = 'FPS: ' + (Math.round(frameRate * 100) / 100).toString()
}
this._fpsLabel.visit(this.context)
}
})
Object.defineProperty(Director, 'sharedDirector', {
/**
* A shared singleton instance of cocos.Director
*
* @memberOf cocos.Director
* @getter {cocos.Director} sharedDirector
*/
get: function () {
if (!Director._instance) {
Director._instance = new this()
}
return Director._instance
}
, enumerable: true
})
/**
* @memberOf cocos
* @class Pretends to run at a constant frame rate even if it slows down
* @extends cocos.Director
*/
function DirectorFixedSpeed () {
DirectorFixedSpeed.superclass.constructor.call(this)
}
DirectorFixedSpeed.inherit(Director, /** @lends cocos.DirectorFixedSpeed */ {
/**
* Frames per second to draw.
* @type Integer
*/
frameRate: 60
/**
* Calculate time since last call
* @private
*/
, _calculateDeltaTime: function () {
if (this._nextDeltaTimeZero) {
this.dt = 0
this._nextDeltaTimeZero = false
}
this.dt = 1.0 / this.frameRate
}
/**
* The main loop is triggered again. Call this function only if
* cocos.Directory#stopAnimation was called earlier.
*/
, startAnimation: function () {
this._animationTimer = setInterval(this.drawScene.bind(this), 1000 / this.frameRate)
this.drawScene()
}
}
)
Object.defineProperty(DirectorFixedSpeed, 'sharedDirector', Object.getOwnPropertyDescriptor(Director, 'sharedDirector'))
exports.Director = Director
exports.DirectorFixedSpeed = DirectorFixedSpeed
// vim:et:st=4:fdm=marker:fdl=0:fdc=1