diff --git a/@types/globals.d.ts b/@types/globals.d.ts index ec88be1fea..84564b8f1e 100644 --- a/@types/globals.d.ts +++ b/@types/globals.d.ts @@ -64,13 +64,6 @@ interface HTMLElement{ type ActiveXObject = new (s: string) => any; declare var ActiveXObject: ActiveXObject; -declare const cc: { - // polyfills: { - // destroyObject? (object: any): void; - // }; - [x: string]: any; -}; - declare type CompareFunction = (a: T, b: T) => number; declare type RecursivePartial = { diff --git a/cocos/audio/assets/clip.ts b/cocos/audio/assets/clip.ts index bb21d52e9c..cfc5b94f05 100644 --- a/cocos/audio/assets/clip.ts +++ b/cocos/audio/assets/clip.ts @@ -33,6 +33,7 @@ import { Enum } from '../../core/value-types'; import { AudioPlayer, PlayingState } from './player'; import { AudioPlayerDOM } from './player-dom'; import { AudioPlayerWeb } from './player-web'; +import { legacyCC } from '../../core/global-exports'; export const AudioType = Enum({ WEB_AUDIO: 0, @@ -131,4 +132,4 @@ export class AudioClip extends Asset { } } -cc.AudioClip = AudioClip; +legacyCC.AudioClip = AudioClip; diff --git a/cocos/audio/assets/player-dom.ts b/cocos/audio/assets/player-dom.ts index a8dc1007ef..1af89b8b54 100644 --- a/cocos/audio/assets/player-dom.ts +++ b/cocos/audio/assets/player-dom.ts @@ -29,6 +29,7 @@ import { clamp } from '../../core/math/utils'; import { AudioPlayer, IAudioInfo, PlayingState } from './player'; +import { legacyCC } from '../../core/global-exports'; export class AudioPlayerDOM extends AudioPlayer { protected _volume = 1; @@ -48,8 +49,8 @@ export class AudioPlayerDOM extends AudioPlayer { this._remove_cb = () => { if (!this._cbRegistered) { return; } - cc.game.canvas.removeEventListener('touchend', this._on_gesture); - cc.game.canvas.removeEventListener('mouseup', this._on_gesture); + legacyCC.game.canvas.removeEventListener('touchend', this._on_gesture); + legacyCC.game.canvas.removeEventListener('mouseup', this._on_gesture); this._cbRegistered = false; }; @@ -70,7 +71,7 @@ export class AudioPlayerDOM extends AudioPlayer { if (!promise) { // Chrome50/Firefox53 below // delay eval here to yield uniform behavior with other platforms this._state = PlayingState.PLAYING; - cc.director.once(cc.Director.EVENT_AFTER_UPDATE, this._post_gesture); + legacyCC.director.once(legacyCC.Director.EVENT_AFTER_UPDATE, this._post_gesture); return; } promise.then(this._post_gesture); @@ -88,8 +89,8 @@ export class AudioPlayerDOM extends AudioPlayer { }); /* play & stop immediately after receiving a gesture so that we can freely invoke play() outside event listeners later */ - cc.game.canvas.addEventListener('touchend', this._on_gesture); - cc.game.canvas.addEventListener('mouseup', this._on_gesture); + legacyCC.game.canvas.addEventListener('touchend', this._on_gesture); + legacyCC.game.canvas.addEventListener('mouseup', this._on_gesture); this._cbRegistered = true; } @@ -100,7 +101,7 @@ export class AudioPlayerDOM extends AudioPlayer { if (!promise) { // delay eval here to yield uniform behavior with other platforms this._state = PlayingState.PLAYING; - cc.director.once(cc.Director.EVENT_AFTER_UPDATE, this._post_play); + legacyCC.director.once(legacyCC.Director.EVENT_AFTER_UPDATE, this._post_play); return; } promise.then(this._post_play).catch(() => { this._interrupted = true; }); diff --git a/cocos/audio/assets/player-web.ts b/cocos/audio/assets/player-web.ts index e8b543ffa9..95bee1905a 100644 --- a/cocos/audio/assets/player-web.ts +++ b/cocos/audio/assets/player-web.ts @@ -30,6 +30,7 @@ import { clamp } from '../../core/math/utils'; import { sys } from '../../core/platform/sys'; import { AudioPlayer, IAudioInfo, PlayingState } from './player'; +import { legacyCC } from '../../core/global-exports'; const audioSupport = sys.__audioSupport; @@ -65,8 +66,8 @@ export class AudioPlayerWeb extends AudioPlayer { // Chrome41/Firefox40 below don't have resume if (this._context.state !== 'running' && this._context.resume) { - cc.game.canvas.addEventListener('touchend', this._onGestureCB); - cc.game.canvas.addEventListener('mouseup', this._onGestureCB); + legacyCC.game.canvas.addEventListener('touchend', this._onGestureCB); + legacyCC.game.canvas.addEventListener('mouseup', this._onGestureCB); } } @@ -150,7 +151,7 @@ export class AudioPlayerWeb extends AudioPlayer { this._startTime = this._context.currentTime; this._startInvoked = false; // delay eval here to yield uniform behavior with other platforms - cc.director.once(cc.Director.EVENT_AFTER_UPDATE, this._playAndEmit, this); + legacyCC.director.once(legacyCC.Director.EVENT_AFTER_UPDATE, this._playAndEmit, this); /* still not supported by all platforms * this._sourceNode.onended = this._onEnded; /* doing it manually for now */ @@ -167,7 +168,7 @@ export class AudioPlayerWeb extends AudioPlayer { private _doStop () { // stop can only be called after play if (this._startInvoked) { this._sourceNode.stop(); } - else { cc.director.off(cc.Director.EVENT_AFTER_UPDATE, this._playAndEmit, this); } + else { legacyCC.director.off(legacyCC.Director.EVENT_AFTER_UPDATE, this._playAndEmit, this); } } private _playAndEmit () { @@ -186,8 +187,8 @@ export class AudioPlayerWeb extends AudioPlayer { private _onGestureProceed () { if (this._interrupted) { this._doPlay(); this._interrupted = false; } - cc.game.canvas.removeEventListener('touchend', this._onGestureCB); - cc.game.canvas.removeEventListener('mouseup', this._onGestureCB); + legacyCC.game.canvas.removeEventListener('touchend', this._onGestureCB); + legacyCC.game.canvas.removeEventListener('mouseup', this._onGestureCB); } private _onGesture () { diff --git a/cocos/audio/assets/player.ts b/cocos/audio/assets/player.ts index 28d343e50f..dc3d51aab5 100644 --- a/cocos/audio/assets/player.ts +++ b/cocos/audio/assets/player.ts @@ -23,6 +23,8 @@ THE SOFTWARE. */ +import { legacyCC } from '../../core/global-exports'; + /** * @category component/audio */ @@ -63,8 +65,8 @@ export abstract class AudioPlayer { this.play(); this._interrupted = false; }; /* handle hide & show */ - cc.game.on(cc.Game.EVENT_HIDE, this._onHide); - cc.game.on(cc.Game.EVENT_SHOW, this._onShow); + legacyCC.game.on(legacyCC.Game.EVENT_HIDE, this._onHide); + legacyCC.game.on(legacyCC.Game.EVENT_SHOW, this._onShow); } public abstract play (): void; @@ -80,9 +82,9 @@ export abstract class AudioPlayer { public getState () { return this._state; } public getDuration () { return this._duration; } public destroy () { - cc.game.off(cc.Game.EVENT_HIDE, this._onHide); - cc.game.off(cc.Game.EVENT_SHOW, this._onShow); + legacyCC.game.off(legacyCC.Game.EVENT_HIDE, this._onHide); + legacyCC.game.off(legacyCC.Game.EVENT_SHOW, this._onShow); } } -cc.internal.AudioPlayer = AudioPlayer; +legacyCC.internal.AudioPlayer = AudioPlayer; diff --git a/cocos/audio/audio-downloader.ts b/cocos/audio/audio-downloader.ts index 024ba9c011..f3e9be7f5f 100644 --- a/cocos/audio/audio-downloader.ts +++ b/cocos/audio/audio-downloader.ts @@ -30,6 +30,7 @@ import { getError, log } from '../core/platform/debug'; import { sys } from '../core/platform/sys'; import { AudioClip, AudioType } from './assets/clip'; +import { legacyCC } from '../core/global-exports'; const __audioSupport = sys.__audioSupport; const formatSupport = __audioSupport.format; @@ -76,7 +77,7 @@ function loadWebAudio (item, callback) { callback(new Error(getError(4926))); } - const request = cc.loader.getXMLHttpRequest(); + const request = legacyCC.loader.getXMLHttpRequest(); request.open('GET', item.url, true); request.responseType = 'arraybuffer'; diff --git a/cocos/core/3d/builtin/init.ts b/cocos/core/3d/builtin/init.ts index d5c59b932b..b2de073e05 100644 --- a/cocos/core/3d/builtin/init.ts +++ b/cocos/core/3d/builtin/init.ts @@ -5,6 +5,7 @@ import { Texture2D } from '../../assets/texture-2d'; import { TextureCube } from '../../assets/texture-cube'; import { GFXDevice } from '../../gfx/device'; import effects from './effects'; +import { legacyCC } from '../../global-exports'; class BuiltinResMgr { protected _device: GFXDevice | null = null; @@ -118,12 +119,12 @@ class BuiltinResMgr { // builtin effects effects.forEach((e) => { - const effect = Object.assign(new cc.EffectAsset(), e); + const effect = Object.assign(new legacyCC.EffectAsset(), e); effect.onLoaded(); }); // standard material - const standardMtl = new cc.Material(); + const standardMtl = new legacyCC.Material(); standardMtl._uuid = 'standard-material'; standardMtl.initialize({ effectName: 'builtin-standard', @@ -131,63 +132,63 @@ class BuiltinResMgr { resources[standardMtl._uuid] = standardMtl; // material indicating missing effect (yellow) - const missingEfxMtl = new cc.Material(); + const missingEfxMtl = new legacyCC.Material(); missingEfxMtl._uuid = 'missing-effect-material'; missingEfxMtl.initialize({ effectName: 'builtin-unlit', defines: { USE_COLOR: true }, }); - missingEfxMtl.setProperty('mainColor', cc.color('#ffff00')); + missingEfxMtl.setProperty('mainColor', legacyCC.color('#ffff00')); resources[missingEfxMtl._uuid] = missingEfxMtl; // material indicating missing material (purple) - const missingMtl = new cc.Material(); + const missingMtl = new legacyCC.Material(); missingMtl._uuid = 'missing-material'; missingMtl.initialize({ effectName: 'builtin-unlit', defines: { USE_COLOR: true }, }); - missingMtl.setProperty('mainColor', cc.color('#ff00ff')); + missingMtl.setProperty('mainColor', legacyCC.color('#ff00ff')); resources[missingMtl._uuid] = missingMtl; // sprite material - const spriteMtl = new cc.Material(); + const spriteMtl = new legacyCC.Material(); spriteMtl._uuid = 'ui-base-material'; spriteMtl.initialize({ defines: { USE_TEXTURE: false }, effectName: 'builtin-sprite' }); resources[spriteMtl._uuid] = spriteMtl; // sprite material - const spriteColorMtl = new cc.Material(); + const spriteColorMtl = new legacyCC.Material(); spriteColorMtl._uuid = 'ui-sprite-material'; spriteColorMtl.initialize({ defines: { USE_TEXTURE: true, IS_GRAY: false }, effectName: 'builtin-sprite' }); resources[spriteColorMtl._uuid] = spriteColorMtl; // sprite gray material - const spriteGrayMtl = new cc.Material(); + const spriteGrayMtl = new legacyCC.Material(); spriteGrayMtl._uuid = 'ui-sprite-gray-material'; spriteGrayMtl.initialize({ defines: { USE_TEXTURE: true, IS_GRAY: true }, effectName: 'builtin-sprite' }); resources[spriteGrayMtl._uuid] = spriteGrayMtl; // default particle material - const defaultParticleMtl = new cc.Material(); + const defaultParticleMtl = new legacyCC.Material(); defaultParticleMtl._uuid = 'default-particle-material'; defaultParticleMtl.initialize({ effectName: 'builtin-particle' }); resources[defaultParticleMtl._uuid] = defaultParticleMtl; // default particle gpu material - const defaultParticleGPUMtl = new cc.Material(); + const defaultParticleGPUMtl = new legacyCC.Material(); defaultParticleGPUMtl._uuid = 'default-particle-gpu-material'; defaultParticleGPUMtl.initialize({ effectName: 'builtin-particle-gpu' }); resources[defaultParticleGPUMtl._uuid] = defaultParticleGPUMtl; // default particle material - const defaultTrailMtl = new cc.Material(); + const defaultTrailMtl = new legacyCC.Material(); defaultTrailMtl._uuid = 'default-trail-material'; defaultTrailMtl.initialize({ effectName: 'builtin-particle-trail' }); resources[defaultTrailMtl._uuid] = defaultTrailMtl; // default particle material - const defaultBillboardMtl = new cc.Material(); + const defaultBillboardMtl = new legacyCC.Material(); defaultBillboardMtl._uuid = 'default-billboard-material'; defaultBillboardMtl.initialize({ effectName: 'builtin-billboard' }); resources[defaultBillboardMtl._uuid] = defaultBillboardMtl; @@ -198,5 +199,5 @@ class BuiltinResMgr { } } -const builtinResMgr = cc.builtinResMgr = new BuiltinResMgr(); +const builtinResMgr = legacyCC.builtinResMgr = new BuiltinResMgr(); export { builtinResMgr }; diff --git a/cocos/core/3d/framework/batched-skinning-model-component.ts b/cocos/core/3d/framework/batched-skinning-model-component.ts index 526a582108..29bed90e0f 100644 --- a/cocos/core/3d/framework/batched-skinning-model-component.ts +++ b/cocos/core/3d/framework/batched-skinning-model-component.ts @@ -42,6 +42,7 @@ import { IGFXAttribute } from '../../gfx/input-assembler'; import { Mat4, Vec2, Vec3 } from '../../math'; import { mapBuffer, readBuffer, writeBuffer } from '../misc/buffer'; import { SkinningModelComponent } from './skinning-model-component'; +import { legacyCC } from '../../global-exports'; const repeat = (n: number) => n - Math.floor(n); const batch_id: IGFXAttribute = { name: GFXAttributeName.ATTR_BATCH_ID, format: GFXFormat.R32F, isNormalized: false }; @@ -472,7 +473,7 @@ export class BatchedSkinningModelComponent extends SkinningModelComponent { } } const gfxTex = target.getGFXTexture()!; - const device: GFXDevice = cc.director.root!.device; + const device: GFXDevice = legacyCC.director.root!.device; if (texBuffers.length > 0) { device.copyBuffersToTexture(texBuffers, gfxTex, texBufferRegions); } if (texImages.length > 0) { device.copyTexImagesToTexture(texImages, gfxTex, texImageRegions); } } @@ -554,10 +555,10 @@ export class BatchedSkinningModelComponent extends SkinningModelComponent { const srcVertex = src.subarray(oldOffset, oldOffset + oldStride); newMeshData.set(srcVertex, newOffset); // insert batch ID - dataView.setFloat32(newOffset + oldStride, unitIdx, cc.sys.isLittleEndian); + dataView.setFloat32(newOffset + oldStride, unitIdx, legacyCC.sys.isLittleEndian); // insert batch UV - dataView.setFloat32(newOffset + oldStride + 4, uvs[j * 2], cc.sys.isLittleEndian); - dataView.setFloat32(newOffset + oldStride + 8, uvs[j * 2 + 1], cc.sys.isLittleEndian); + dataView.setFloat32(newOffset + oldStride + 4, uvs[j * 2], legacyCC.sys.isLittleEndian); + dataView.setFloat32(newOffset + oldStride + 8, uvs[j * 2 + 1], legacyCC.sys.isLittleEndian); newOffset += newStride; oldOffset += oldStride; } for (let k = 0; k < newMeshStruct.primitives.length; k++) { diff --git a/cocos/core/3d/framework/camera-component.ts b/cocos/core/3d/framework/camera-component.ts index d8ed97c7a1..f2eb9da5e8 100644 --- a/cocos/core/3d/framework/camera-component.ts +++ b/cocos/core/3d/framework/camera-component.ts @@ -44,6 +44,7 @@ import { Root } from '../../root'; import { Layers, Node, Scene } from '../../scene-graph'; import { Enum } from '../../value-types'; import { TransformBit } from '../../scene-graph/node-enum'; +import { legacyCC } from '../../global-exports'; const _temp_vec3_1 = new Vec3(); @@ -443,7 +444,7 @@ export class CameraComponent extends Component { this._updateTargetTexture(); if (!value && this._camera) { - this._camera.changeTargetWindow(EDITOR ? cc.director.root.tempWindow : null); + this._camera.changeTargetWindow(EDITOR ? legacyCC.director.root.tempWindow : null); this._camera.isWindowSize = true; } } @@ -469,7 +470,7 @@ export class CameraComponent extends Component { set inEditorMode (value) { this._inEditorMode = value; if (this._camera) { - this._camera.changeTargetWindow(value ? cc.director.root && cc.director.root.mainWindow : cc.director.root && cc.director.root.tempWindow); + this._camera.changeTargetWindow(value ? legacyCC.director.root && legacyCC.director.root.mainWindow : legacyCC.director.root && legacyCC.director.root.tempWindow); } } @@ -481,7 +482,7 @@ export class CameraComponent extends Component { } public onLoad () { - cc.director.on(cc.Director.EVENT_AFTER_SCENE_LAUNCH, this.onSceneChanged, this); + legacyCC.director.on(legacyCC.Director.EVENT_AFTER_SCENE_LAUNCH, this.onSceneChanged, this); this._createCamera(); } @@ -501,7 +502,7 @@ export class CameraComponent extends Component { public onDestroy () { if (this._camera) { - cc.director.root.destroyCamera(this._camera); + legacyCC.director.root.destroyCamera(this._camera); this._camera = null; } @@ -552,8 +553,8 @@ export class CameraComponent extends Component { const designSize = view.getVisibleSize(); const xoffset = _temp_vec3_1.x - this._camera!.width * 0.5; const yoffset = _temp_vec3_1.y - this._camera!.height * 0.5; - _temp_vec3_1.x = xoffset / cc.view.getScaleX() + designSize.width * 0.5; - _temp_vec3_1.y = yoffset / cc.view.getScaleY() + designSize.height * 0.5; + _temp_vec3_1.x = xoffset / legacyCC.view.getScaleX() + designSize.width * 0.5; + _temp_vec3_1.y = yoffset / legacyCC.view.getScaleY() + designSize.height * 0.5; if (cmp) { cmp.convertToNodeSpaceAR(_temp_vec3_1, out); @@ -563,12 +564,12 @@ export class CameraComponent extends Component { } protected _createCamera () { - this._camera = (cc.director.root as Root).createCamera(); + this._camera = (legacyCC.director.root as Root).createCamera(); this._camera.initialize({ name: this.node.name, node: this.node, projection: this._projection, - window: this._inEditorMode ? cc.director.root && cc.director.root.mainWindow : cc.director.root && cc.director.root.tempWindow, + window: this._inEditorMode ? legacyCC.director.root && legacyCC.director.root.mainWindow : legacyCC.director.root && legacyCC.director.root.tempWindow, priority: this._priority, flows: this._flows, }); diff --git a/cocos/core/3d/framework/editor-camera-component.ts b/cocos/core/3d/framework/editor-camera-component.ts index c1c509924e..7f7c8ee65b 100644 --- a/cocos/core/3d/framework/editor-camera-component.ts +++ b/cocos/core/3d/framework/editor-camera-component.ts @@ -8,6 +8,7 @@ import { toRadian } from '../../math'; import { Camera } from '../../renderer'; import { CameraComponent } from './camera-component'; import { CAMERA_EDITOR_MASK } from '../../pipeline/define'; +import { legacyCC } from '../../global-exports'; @ccclass('cc.EditorCameraComponent') export class EditorCameraComponent extends CameraComponent { @@ -111,7 +112,7 @@ export class EditorCameraComponent extends CameraComponent { public onEnable () { super.onEnable(); if (this._uiEditorCamera) { - cc.director.root!.ui.renderScene.addCamera(this._uiEditorCamera); + legacyCC.director.root!.ui.renderScene.addCamera(this._uiEditorCamera); this._uiEditorCamera.enabled = true; } } @@ -119,14 +120,14 @@ export class EditorCameraComponent extends CameraComponent { public onDisable () { super.onDisable(); if (this._uiEditorCamera) { - cc.director.root!.ui.renderScene.removeCamera(this._uiEditorCamera); + legacyCC.director.root!.ui.renderScene.removeCamera(this._uiEditorCamera); } } public onDestroy () { super.onDestroy(); if (this._uiEditorCamera) { - cc.director.root!.destroyCamera(this._uiEditorCamera); + legacyCC.director.root!.destroyCamera(this._uiEditorCamera); this._uiEditorCamera = null; } } @@ -137,15 +138,15 @@ export class EditorCameraComponent extends CameraComponent { if (this._camera !== priorCamera && this._camera) { if (this._uiEditorCamera) { - cc.director.root!.destroyCamera(this._uiEditorCamera); + legacyCC.director.root!.destroyCamera(this._uiEditorCamera); this._uiEditorCamera = null; } - this._uiEditorCamera = cc.director.root!.createCamera(); + this._uiEditorCamera = legacyCC.director.root!.createCamera(); this._uiEditorCamera!.initialize({ name: 'Editor UICamera', node: this._camera.node, projection: this._projection, - window: cc.director.root!.mainWindow, + window: legacyCC.director.root!.mainWindow, priority: this._priority + 1, flows: ['UIFlow'], }); diff --git a/cocos/core/3d/framework/index.ts b/cocos/core/3d/framework/index.ts index 8fcfda568a..812d8764b2 100644 --- a/cocos/core/3d/framework/index.ts +++ b/cocos/core/3d/framework/index.ts @@ -27,7 +27,7 @@ /** * @hidden */ - +import { legacyCC } from '../../global-exports'; import { BatchedSkinningModelComponent, SkinningModelUnit } from './batched-skinning-model-component'; import { CameraComponent } from './camera-component'; import { DirectionalLightComponent } from './directional-light-component'; @@ -55,19 +55,19 @@ export { }; // cc.AnimationComponent = AnimationComponent; -cc.CameraComponent = CameraComponent; -cc.EditorComponent = EditorCameraComponent; -cc.RenderableComponent = RenderableComponent; -cc.ModelComponent = ModelComponent; -cc.SkinningModelComponent = SkinningModelComponent; +legacyCC.CameraComponent = CameraComponent; +legacyCC.EditorComponent = EditorCameraComponent; +legacyCC.RenderableComponent = RenderableComponent; +legacyCC.ModelComponent = ModelComponent; +legacyCC.SkinningModelComponent = SkinningModelComponent; -cc.BatchedSkinningModelComponent = BatchedSkinningModelComponent; -cc.SkinningModelUnit = SkinningModelUnit; +legacyCC.BatchedSkinningModelComponent = BatchedSkinningModelComponent; +legacyCC.SkinningModelUnit = SkinningModelUnit; -cc.LightComponent = LightComponent; -cc.DirectionalLightComponent = DirectionalLightComponent; -cc.SphereLightComponent = SphereLightComponent; -cc.SpotLightComponent = SpotLightComponent; +legacyCC.LightComponent = LightComponent; +legacyCC.DirectionalLightComponent = DirectionalLightComponent; +legacyCC.SphereLightComponent = SphereLightComponent; +legacyCC.SpotLightComponent = SpotLightComponent; /** deprecated */ import './deprecated'; diff --git a/cocos/core/3d/framework/light-component.ts b/cocos/core/3d/framework/light-component.ts index f6704f0eaf..e207dd4df1 100644 --- a/cocos/core/3d/framework/light-component.ts +++ b/cocos/core/3d/framework/light-component.ts @@ -37,6 +37,7 @@ import { Light, LightType } from '../../renderer/scene/light'; import { SphereLight } from '../../renderer/scene/sphere-light'; import { SpotLight } from '../../renderer/scene/spot-light'; import { Root } from '../../root'; +import { legacyCC } from '../../global-exports'; export const PhotometricTerm = Enum({ LUMINOUS_POWER: 0, @@ -177,7 +178,7 @@ export class LightComponent extends Component { protected _createLight () { if (!this._light) { - this._light = (cc.director.root as Root).createLight(this._lightType); + this._light = (legacyCC.director.root as Root).createLight(this._lightType); } this.color = this._color; this.useColorTemperature = this._useColorTemperature; @@ -187,7 +188,7 @@ export class LightComponent extends Component { protected _destroyLight () { if (this._light) { - cc.director.root.destroyLight(this); + legacyCC.director.root.destroyLight(this); this._light = null; } } diff --git a/cocos/core/3d/framework/model-component.ts b/cocos/core/3d/framework/model-component.ts index d18f18d9b4..a629ebfa7a 100644 --- a/cocos/core/3d/framework/model-component.ts +++ b/cocos/core/3d/framework/model-component.ts @@ -40,6 +40,7 @@ import { Enum } from '../../value-types'; import { builtinResMgr } from '../builtin'; import { RenderableComponent } from './renderable-component'; import { MorphRenderingInstance } from '../../assets/morph'; +import { legacyCC } from '../../global-exports'; /** * @en Shadow projection mode. @@ -244,7 +245,7 @@ export class ModelComponent extends RenderableComponent { public onDestroy () { if (this._model) { - cc.director.root.destroyModel(this._model); + legacyCC.director.root.destroyModel(this._model); this._model = null; this._models.length = 0; } @@ -294,7 +295,7 @@ export class ModelComponent extends RenderableComponent { } protected _createModel () { - this._model = (cc.director.root as Root).createModel(this._modelType); + this._model = (legacyCC.director.root as Root).createModel(this._modelType); this._model.visFlags = this.visibility; this._model.initialize(this.node); this._models.length = 0; diff --git a/cocos/core/3d/framework/skinning-model-component.ts b/cocos/core/3d/framework/skinning-model-component.ts index b7ff523757..6bb3e7af0f 100644 --- a/cocos/core/3d/framework/skinning-model-component.ts +++ b/cocos/core/3d/framework/skinning-model-component.ts @@ -36,6 +36,7 @@ import { SkinningModel } from '../../renderer/models/skinning-model'; import { Node } from '../../scene-graph/node'; import { ModelComponent } from './model-component'; import { SkeletalAnimationComponent } from '../../animation/skeletal-animation-component'; +import { legacyCC } from '../../global-exports'; /** * @en The Skinning Model Component. @@ -118,7 +119,7 @@ export class SkinningModelComponent extends ModelComponent { this._modelType = modelType; const modelCreated = !!this._model; if (modelCreated) { - cc.director.root.destroyModel(this._model); + legacyCC.director.root.destroyModel(this._model); this._model = null; this._models.length = 0; } diff --git a/cocos/core/3d/index.ts b/cocos/core/3d/index.ts index b559449a01..ebf8c6700c 100644 --- a/cocos/core/3d/index.ts +++ b/cocos/core/3d/index.ts @@ -30,8 +30,9 @@ export * from './builtin'; export * from './framework'; import * as utils from './misc/utils'; +import { legacyCC } from '../global-exports'; export { utils, }; -cc.utils = utils; +legacyCC.utils = utils; diff --git a/cocos/core/animation/animation-clip.ts b/cocos/core/animation/animation-clip.ts index 7deab6b873..54820ec44e 100644 --- a/cocos/core/animation/animation-clip.ts +++ b/cocos/core/animation/animation-clip.ts @@ -17,6 +17,7 @@ import { SkelAnimDataHub } from './skeletal-animation-data-hub'; import { ComponentPath, HierarchyPath, TargetPath } from './target-path'; import { WrapMode as AnimationWrapMode } from './types'; import { IValueProxyFactory } from './value-proxy'; +import { legacyCC } from '../global-exports'; export interface IObjectCurveData { [propertyName: string]: IPropertyCurveData; @@ -308,7 +309,7 @@ export class AnimationClip extends Asset { } public destroy () { - (cc.director.root.dataPoolManager as DataPoolManager).releaseAnimationClip(this); + (legacyCC.director.root.dataPoolManager as DataPoolManager).releaseAnimationClip(this); SkelAnimDataHub.destroy(this); return super.destroy(); } @@ -394,4 +395,4 @@ export class AnimationClip extends Asset { } } -cc.AnimationClip = AnimationClip; +legacyCC.AnimationClip = AnimationClip; diff --git a/cocos/core/animation/animation-component.ts b/cocos/core/animation/animation-component.ts index eb71dc4599..008f35f98f 100644 --- a/cocos/core/animation/animation-component.ts +++ b/cocos/core/animation/animation-component.ts @@ -40,6 +40,7 @@ import { AnimationClip } from './animation-clip'; import { AnimationState } from './animation-state'; import { CrossFade } from './cross-fade'; import { EDITOR, TEST } from 'internal:constants'; +import { legacyCC } from '../global-exports'; /** * @en The event type supported by Animation @@ -510,7 +511,7 @@ applyMixins(AnimationComponent, [CallbacksInvoker, EventTarget]); AnimationComponent.prototype.on = on; AnimationComponent.prototype.off = off; -cc.AnimationComponent = AnimationComponent; +legacyCC.AnimationComponent = AnimationComponent; function equalClips (clip1: AnimationClip | null, clip2: AnimationClip | null) { if (clip1 === clip2) { diff --git a/cocos/core/animation/animation-curve.ts b/cocos/core/animation/animation-curve.ts index 135642374a..17f49c7f7a 100644 --- a/cocos/core/animation/animation-curve.ts +++ b/cocos/core/animation/animation-curve.ts @@ -9,6 +9,7 @@ import { ValueType } from '../value-types'; import { bezierByTime, BezierControlPoints } from './bezier'; import * as easing from './easing'; import { ILerpable, isLerpable } from './types'; +import { legacyCC } from '../global-exports'; /** * 表示曲线值,曲线值可以是任意类型,但必须符合插值方式的要求。 @@ -100,7 +101,7 @@ export class RatioSampler { return this._findRatio(this.ratios, ratio); } } -cc.RatioSampler = RatioSampler; +legacyCC.RatioSampler = RatioSampler; /** * 动画曲线。 @@ -243,7 +244,7 @@ export class AnimCurve { return this._values.length === 1; } } -cc.AnimCurve = AnimCurve; +legacyCC.AnimCurve = AnimCurve; export class EventInfo { public events: any[] = []; @@ -281,7 +282,7 @@ export function sampleAnimationCurve (curve: AnimCurve, sampler: RatioSampler, r } return curve.valueAt(index); } -cc.sampleAnimationCurve = sampleAnimationCurve; +legacyCC.sampleAnimationCurve = sampleAnimationCurve; /** * Compute a new ratio by curve type. diff --git a/cocos/core/animation/animation-manager.ts b/cocos/core/animation/animation-manager.ts index 0f5fe9a151..ee6e9b29e1 100644 --- a/cocos/core/animation/animation-manager.ts +++ b/cocos/core/animation/animation-manager.ts @@ -12,6 +12,7 @@ import { MutableForwardIterator, remove } from '../utils/array'; import { BlendStateBuffer } from './skeletal-animation-blending'; import { AnimationState } from './animation-state'; import { CrossFade } from './cross-fade'; +import { legacyCC } from '../global-exports'; @ccclass export class AnimationManager extends System { @@ -90,4 +91,4 @@ director.on(Director.EVENT_INIT, () => { director.registerSystem(AnimationManager.ID, animationManager, Scheduler.PRIORITY_SYSTEM); }); -cc.AnimationManager = AnimationManager; +legacyCC.AnimationManager = AnimationManager; diff --git a/cocos/core/animation/animation-state.ts b/cocos/core/animation/animation-state.ts index 90547208b6..16ec44b025 100644 --- a/cocos/core/animation/animation-state.ts +++ b/cocos/core/animation/animation-state.ts @@ -39,6 +39,7 @@ import { error } from '../platform/debug'; import { EDITOR } from 'internal:constants'; import { HierarchyPath, TargetPath, evaluatePath } from './target-path'; import { BlendStateBuffer, createBlendStateWriter, IBlendStateWriter } from './skeletal-animation-blending'; +import { legacyCC } from '../global-exports'; enum PropertySpecialization { NodePosition, @@ -329,7 +330,7 @@ export class AnimationState extends Playable { this._curveLoaded = true; this._destroyBlendStateWriters(); this._samplerSharedGroups.length = 0; - this._blendStateBuffer = cc.director.getAnimationManager()?.blendState ?? null; + this._blendStateBuffer = legacyCC.director.getAnimationManager()?.blendState ?? null; this._targetNode = root; const clip = this._clip; @@ -428,7 +429,7 @@ export class AnimationState extends Playable { for (let i = 0, l = args.length; i < l; i++) { args[i] = restargs[i]; } - cc.director.getAnimationManager().pushDelayEvent(this, '_emit', args); + legacyCC.director.getAnimationManager().pushDelayEvent(this, '_emit', args); } public on (type: K, callback: EventCallbackOf, target?: any): void; @@ -817,7 +818,7 @@ export class AnimationState extends Playable { lastIndex += direction; - cc.director.getAnimationManager().pushDelayEvent(this, '_fireEvent', [lastIndex]); + legacyCC.director.getAnimationManager().pushDelayEvent(this, '_fireEvent', [lastIndex]); } while (lastIndex !== eventIndex && lastIndex > -1 && lastIndex < length); } @@ -854,11 +855,11 @@ export class AnimationState extends Playable { } this._isBlendStateWriterInitialized = true; } - cc.director.getAnimationManager().addAnimation(this); + legacyCC.director.getAnimationManager().addAnimation(this); } private _onPauseOrStop () { - cc.director.getAnimationManager().removeAnimation(this); + legacyCC.director.getAnimationManager().removeAnimation(this); } private _destroyBlendStateWriters () { @@ -899,4 +900,4 @@ function wrapIterations (iterations: number) { return iterations | 0; } -cc.AnimationState = AnimationState; +legacyCC.AnimationState = AnimationState; diff --git a/cocos/core/animation/bezier.ts b/cocos/core/animation/bezier.ts index 45a78afcaa..f3abf1de8f 100644 --- a/cocos/core/animation/bezier.ts +++ b/cocos/core/animation/bezier.ts @@ -3,6 +3,8 @@ * @category animation */ +import { legacyCC } from '../global-exports'; + export type BezierControlPoints = [ number, number, number, number ]; export function bezier (C1: number, C2: number, C3: number, C4: number, t: number) { @@ -12,7 +14,7 @@ export function bezier (C1: number, C2: number, C3: number, C4: number, t: numbe C3 * 3 * t1 * t * t + C4 * t * t * t; } -cc.bezier = bezier; +legacyCC.bezier = bezier; // var sin = Math.sin; const cos = Math.cos; @@ -161,4 +163,4 @@ export function bezierByTime (controlPoints: BezierControlPoints, x: number) { p2y * 3 * percent * percent * t1 + p3y * percent * percent * percent; } -cc.bezierByTime = bezierByTime; +legacyCC.bezierByTime = bezierByTime; diff --git a/cocos/core/animation/cross-fade.ts b/cocos/core/animation/cross-fade.ts index 59ddb133da..b1dd9307a6 100644 --- a/cocos/core/animation/cross-fade.ts +++ b/cocos/core/animation/cross-fade.ts @@ -6,6 +6,7 @@ import { clamp01 } from '../math/utils'; import { remove } from '../utils/array'; import { AnimationState } from './animation-state'; import { Playable } from './playable'; +import { legacyCC } from '../global-exports'; interface IManagedState { state: AnimationState | null; @@ -127,7 +128,7 @@ export class CrossFade extends Playable { protected onPlay () { super.onPlay(); - cc.director.getAnimationManager().addCrossFade(this); + legacyCC.director.getAnimationManager().addCrossFade(this); } /** @@ -135,7 +136,7 @@ export class CrossFade extends Playable { */ protected onPause () { super.onPause(); - cc.director.getAnimationManager().removeCrossFade(this); + legacyCC.director.getAnimationManager().removeCrossFade(this); for (let iManagedState = 0; iManagedState < this._managedStates.length; ++iManagedState) { const state = this._managedStates[iManagedState].state; if (state) { @@ -149,7 +150,7 @@ export class CrossFade extends Playable { */ protected onResume () { super.onResume(); - cc.director.getAnimationManager().addCrossFade(this); + legacyCC.director.getAnimationManager().addCrossFade(this); for (let iManagedState = 0; iManagedState < this._managedStates.length; ++iManagedState) { const state = this._managedStates[iManagedState].state; if (state) { @@ -163,7 +164,7 @@ export class CrossFade extends Playable { */ protected onStop () { super.onStop(); - cc.director.getAnimationManager().removeCrossFade(this); + legacyCC.director.getAnimationManager().removeCrossFade(this); this.clear(); } } diff --git a/cocos/core/animation/cubic-spline-value.ts b/cocos/core/animation/cubic-spline-value.ts index 9a07e0df6a..53374ea17a 100644 --- a/cocos/core/animation/cubic-spline-value.ts +++ b/cocos/core/animation/cubic-spline-value.ts @@ -6,6 +6,7 @@ import { ccclass, property } from '../data/class-decorator'; import { Quat, Vec2, Vec3, Vec4 } from '../math'; import { ILerpable } from './types'; +import { legacyCC } from '../global-exports'; interface ICubicSplineValue extends ILerpable { dataPoint: T; @@ -85,19 +86,19 @@ function makeCubicSplineValueConstructor ( export const CubicSplineVec2Value = makeCubicSplineValueConstructor( 'cc.CubicSplineVec2Value', Vec2, Vec2.multiplyScalar, Vec2.scaleAndAdd); -cc.CubicSplineVec2Value = CubicSplineVec2Value; +legacyCC.CubicSplineVec2Value = CubicSplineVec2Value; export const CubicSplineVec3Value = makeCubicSplineValueConstructor( 'cc.CubicSplineVec3Value', Vec3, Vec3.multiplyScalar, Vec3.scaleAndAdd); -cc.CubicSplineVec3Value = CubicSplineVec3Value; +legacyCC.CubicSplineVec3Value = CubicSplineVec3Value; export const CubicSplineVec4Value = makeCubicSplineValueConstructor( 'cc.CubicSplineVec4Value', Vec4, Vec4.multiplyScalar, Vec4.scaleAndAdd); -cc.CubicSplineVec4Value = CubicSplineVec4Value; +legacyCC.CubicSplineVec4Value = CubicSplineVec4Value; export const CubicSplineQuatValue = makeCubicSplineValueConstructor( 'cc.CubicSplineQuatValue', Quat, Quat.multiplyScalar, Quat.scaleAndAdd); -cc.CubicSplineQuatValue = CubicSplineQuatValue; +legacyCC.CubicSplineQuatValue = CubicSplineQuatValue; @ccclass('cc.CubicSplineNumberValue') export class CubicSplineNumberValue implements ICubicSplineValue { @@ -135,4 +136,4 @@ export class CubicSplineNumberValue implements ICubicSplineValue { return this.dataPoint; } } -cc.CubicSplineNumberValue = CubicSplineNumberValue; +legacyCC.CubicSplineNumberValue = CubicSplineNumberValue; diff --git a/cocos/core/animation/index.ts b/cocos/core/animation/index.ts index e7ffd84ef2..c0eeda54c7 100644 --- a/cocos/core/animation/index.ts +++ b/cocos/core/animation/index.ts @@ -8,8 +8,9 @@ import * as easing from './easing'; import { ComponentPath, HierarchyPath, ICustomTargetPath, TargetPath } from './target-path'; import { IValueProxyFactory } from './value-proxy'; import { UniformProxyFactory } from './value-proxy-factories/uniform'; +import { legacyCC } from '../global-exports'; -cc.easing = easing; +legacyCC.easing = easing; export * from './bezier'; export { easing }; export * from './animation-curve'; @@ -37,7 +38,7 @@ export * from './cubic-spline-value'; */ @ccclass('cc.HierachyModifier') export class HierachyModifier extends HierarchyPath {} -cc.HierachyModifier = HierachyModifier; +legacyCC.HierachyModifier = HierachyModifier; /** * Alias of `ComponentPath`. @@ -45,7 +46,7 @@ cc.HierachyModifier = HierachyModifier; */ @ccclass('cc.ComponentModifier') export class ComponentModifier extends ComponentPath {} -cc.ComponentModifier = ComponentModifier; +legacyCC.ComponentModifier = ComponentModifier; /** * Implements `IValueProxyFactory` but do nothing. @@ -61,7 +62,7 @@ export class CurveValueAdapter implements IValueProxyFactory { }; } } -cc.CurveValueAdapter = CurveValueAdapter; +legacyCC.CurveValueAdapter = CurveValueAdapter; /** * Alias of `UniformProxyFactory`. @@ -69,7 +70,7 @@ cc.CurveValueAdapter = CurveValueAdapter; */ @ccclass('cc.UniformCurveValueAdapter') export class UniformCurveValueAdapter extends UniformProxyFactory {} -cc.UniformCurveValueAdapter = UniformCurveValueAdapter; +legacyCC.UniformCurveValueAdapter = UniformCurveValueAdapter; /** * Alias of `isPropertyPath(path) && typeof path === 'string'`. @@ -78,7 +79,7 @@ cc.UniformCurveValueAdapter = UniformCurveValueAdapter; export function isPropertyModifier (path: TargetPath): path is string { return typeof path === 'string'; } -cc.isPropertyModifier = isPropertyModifier; +legacyCC.isPropertyModifier = isPropertyModifier; /** * Alias of `isPropertyPath(path) && typeof path === 'number'`. @@ -87,7 +88,7 @@ cc.isPropertyModifier = isPropertyModifier; export function isElementModifier (path: TargetPath): path is number { return typeof path === 'number'; } -cc.isElementModifier = isElementModifier; +legacyCC.isElementModifier = isElementModifier; /** * Alias of `isCustomPath()`. @@ -96,4 +97,4 @@ cc.isElementModifier = isElementModifier; export function isCustomTargetModifier (path: TargetPath, constructor: Constructor): path is T { return path instanceof constructor; } -cc.isCustomTargetModifier = isCustomTargetModifier; +legacyCC.isCustomTargetModifier = isCustomTargetModifier; diff --git a/cocos/core/animation/skeletal-animation-component.ts b/cocos/core/animation/skeletal-animation-component.ts index cfd9ef6a05..b8c8efc516 100644 --- a/cocos/core/animation/skeletal-animation-component.ts +++ b/cocos/core/animation/skeletal-animation-component.ts @@ -37,6 +37,7 @@ import { AnimationComponent } from './animation-component'; import { SkelAnimDataHub } from './skeletal-animation-data-hub'; import { SkeletalAnimationState } from './skeletal-animation-state'; import { getWorldTransformUntilRoot } from './transform-utils'; +import { legacyCC } from '../global-exports'; @ccclass('cc.SkeletalAnimationComponent.Socket') export class Socket { @@ -148,7 +149,7 @@ export class SkeletalAnimationComponent extends AnimationComponent { public onDestroy () { super.onDestroy(); - (cc.director.root.dataPoolManager as DataPoolManager).jointAnimationInfo.destroy(this.node.uuid); + (legacyCC.director.root.dataPoolManager as DataPoolManager).jointAnimationInfo.destroy(this.node.uuid); } public start () { @@ -213,4 +214,4 @@ export class SkeletalAnimationComponent extends AnimationComponent { } } -cc.SkeletalAnimationComponent = SkeletalAnimationComponent; +legacyCC.SkeletalAnimationComponent = SkeletalAnimationComponent; diff --git a/cocos/core/animation/skeletal-animation-data-hub.ts b/cocos/core/animation/skeletal-animation-data-hub.ts index d4319b06aa..37168f23e1 100644 --- a/cocos/core/animation/skeletal-animation-data-hub.ts +++ b/cocos/core/animation/skeletal-animation-data-hub.ts @@ -31,6 +31,7 @@ import { clamp01, Mat4, Quat, Vec3 } from '../math'; import { DataPoolManager } from '../renderer/data-pool-manager'; import { AnimationClip, IObjectCurveData } from './animation-clip'; import { HierarchyPath, isCustomPath, isPropertyPath } from './target-path'; +import { legacyCC } from '../global-exports'; type CurveData = Vec3 | Quat | Mat4; type ConvertedProps = Record; @@ -57,7 +58,7 @@ export class SkelAnimDataHub { let data = SkelAnimDataHub.pool.get(clip); if (!data || data.info.sample !== clip.sample) { // release outdated render data - if (data) { (cc.director.root.dataPoolManager as DataPoolManager).releaseAnimationClip(clip); } + if (data) { (legacyCC.director.root.dataPoolManager as DataPoolManager).releaseAnimationClip(clip); } data = convertToSkeletalCurves(clip); SkelAnimDataHub.pool.set(clip, data); } diff --git a/cocos/core/animation/skeletal-animation-state.ts b/cocos/core/animation/skeletal-animation-state.ts index 273a354b41..c057d2f5cd 100644 --- a/cocos/core/animation/skeletal-animation-state.ts +++ b/cocos/core/animation/skeletal-animation-state.ts @@ -37,6 +37,7 @@ import { AnimationState } from './animation-state'; import { SkeletalAnimationComponent, Socket } from './skeletal-animation-component'; import { SkelAnimDataHub } from './skeletal-animation-data-hub'; import { getWorldTransformUntilRoot } from './transform-utils'; +import { legacyCC } from '../global-exports'; const m4_1 = new Mat4(); const m4_2 = new Mat4(); @@ -68,7 +69,7 @@ export class SkeletalAnimationState extends AnimationState { constructor (clip: AnimationClip, name = '') { super(clip, name); - this._animInfoMgr = cc.director.root.dataPoolManager.jointAnimationInfo; + this._animInfoMgr = legacyCC.director.root.dataPoolManager.jointAnimationInfo; } public initialize (root: Node) { @@ -169,7 +170,7 @@ export class SkeletalAnimationState extends AnimationState { private _sampleCurvesRealTime (ratio: number) { super._sampleCurves(ratio); - const stamp = cc.director.getTotalFrames(); + const stamp = legacyCC.director.getTotalFrames(); for (let i = 0; i < this._sockets.length; ++i) { const { target, transform } = this._sockets[i]; target.matrix = getWorldMatrix(transform, stamp); diff --git a/cocos/core/animation/value-proxy-factories/uniform.ts b/cocos/core/animation/value-proxy-factories/uniform.ts index e8ae467267..e96b34365f 100644 --- a/cocos/core/animation/value-proxy-factories/uniform.ts +++ b/cocos/core/animation/value-proxy-factories/uniform.ts @@ -13,6 +13,7 @@ import { getDefaultFromType } from '../../renderer/core/pass-utils'; import { samplerLib } from '../../renderer/core/sampler-lib'; import { IValueProxy, IValueProxyFactory } from '../value-proxy'; import { warn } from '../../platform/debug'; +import { legacyCC } from '../../global-exports'; @ccclass('cc.animation.UniformProxyFactory') export class UniformProxyFactory implements IValueProxyFactory { @@ -74,7 +75,7 @@ export class UniformProxyFactory implements IValueProxyFactory { if (!tv || !tv.texture.width || !tv.texture.height) { return; } pass.bindTextureView(binding, tv); if (value instanceof TextureBase) { - pass.bindSampler(binding, samplerLib.getSampler(cc.game._gfxDevice, value.getSamplerHash())); + pass.bindSampler(binding, samplerLib.getSampler(legacyCC.game._gfxDevice, value.getSamplerHash())); } }, }; diff --git a/cocos/core/assets/asset-library.ts b/cocos/core/assets/asset-library.ts index acfd8733ba..1f16233ade 100644 --- a/cocos/core/assets/asset-library.ts +++ b/cocos/core/assets/asset-library.ts @@ -39,6 +39,7 @@ import { SubPackPipe } from '../load-pipeline/subpackage-pipe'; import { Asset } from './asset'; import * as debug from '../platform/debug'; import { EDITOR, TEST, BUILD } from 'internal:constants'; +import { legacyCC } from '../global-exports'; // tslint:disable: max-line-length @@ -49,7 +50,7 @@ let _rawAssetsBase = ''; // The base dir for raw assets in runtime const _uuidToRawAsset = createMap(true); function isScene (asset) { - return asset && (asset.constructor === cc.SceneAsset || asset instanceof cc.Scene); + return asset && (asset.constructor === legacyCC.SceneAsset || asset instanceof legacyCC.Scene); } // types @@ -112,17 +113,17 @@ const AssetLibrary = { if (options && options.existingAsset) { item.existingAsset = options.existingAsset; } - cc.loader.load(item, (error, asset) => { + legacyCC.loader.load(item, (error, asset) => { if (error || !asset) { error = new Error('[AssetLibrary] loading JSON or dependencies failed: ' + (error ? error.message : 'Unknown error')); } else { - if (asset.constructor === cc.SceneAsset) { + if (asset.constructor === legacyCC.SceneAsset) { if (EDITOR && !asset.scene) { debug.error('Sorry, the scene data of "%s" is corrupted!', uuid); } else { - const key = cc.loader._getReferenceKey(uuid); + const key = legacyCC.loader._getReferenceKey(uuid); asset.scene.dependAssets = getDependsRecursively(key); } } @@ -165,7 +166,7 @@ const AssetLibrary = { return callback(loadError); } - const ctor = cc.js.getClassByName(info.type); + const ctor = legacyCC.js.getClassByName(info.type); if (ctor) { const isRawAsset = !isChildClassOf(ctor, Asset); const url = `import://${info.uuid.substr(0, 2)}/${info.uuid}.json`; @@ -186,7 +187,7 @@ const AssetLibrary = { _getAssetInfoInRuntime (uuid, result?: any) { result = result || {url: null, raw: false}; const info = _uuidToRawAsset[uuid]; - if (info && !isChildClassOf(info.type, cc.Asset)) { + if (info && !isChildClassOf(info.type, legacyCC.Asset)) { // backward compatibility since 1.10 result.url = _rawAssetsBase + info.url; result.raw = true; @@ -238,12 +239,12 @@ const AssetLibrary = { let uuid = ''; const isImported = url.startsWith(_libraryBase); if (isImported) { - const dir = cc.path.dirname(url); - const dirBasename = cc.path.basename(dir); + const dir = legacyCC.path.dirname(url); + const dirBasename = legacyCC.path.basename(dir); const isAssetUrl = dirBasename.length === 2; if (isAssetUrl) { - uuid = cc.path.basename(url); + uuid = legacyCC.path.basename(url); const index = uuid.indexOf('.'); if (index !== -1) { uuid = uuid.slice(0, index); @@ -273,20 +274,20 @@ const AssetLibrary = { uuid: randomUuid, type: 'uuid', content: json, - skips: [ cc.loader.assetLoader.id, cc.loader.downloader.id ], + skips: [ legacyCC.loader.assetLoader.id, legacyCC.loader.downloader.id ], }; - cc.loader.load(item, (error, asset) => { + legacyCC.loader.load(item, (error, asset) => { if (error) { error = new Error('[AssetLibrary] loading JSON or dependencies failed: ' + error.message); } else { - if (asset.constructor === cc.SceneAsset) { - const key = cc.loader._getReferenceKey(randomUuid); + if (asset.constructor === legacyCC.SceneAsset) { + const key = legacyCC.loader._getReferenceKey(randomUuid); asset.scene.dependAssets = getDependsRecursively(key); } if (EDITOR || isScene(asset)) { - const id = cc.loader._getReferenceKey(randomUuid); - cc.loader.removeItem(id); + const id = legacyCC.loader._getReferenceKey(randomUuid); + legacyCC.loader.removeItem(id); } } asset._uuid = ''; @@ -325,7 +326,7 @@ const AssetLibrary = { */ init (options) { if (EDITOR && _libraryBase) { - cc.errorID(6402); + legacyCC.errorID(6402); return; } @@ -333,7 +334,7 @@ const AssetLibrary = { // 不使用 url.format 的原因是 windows 不支持 file:// 和 /// 开头的协议,所以只能用 replace 操作直接把路径转成 URL。 let libraryPath = options.libraryPath; libraryPath = libraryPath.replace(/\\/g, '/'); - _libraryBase = cc.path.stripSep(libraryPath) + '/'; + _libraryBase = legacyCC.path.stripSep(libraryPath) + '/'; _rawAssetsBase = options.rawAssetsBase; @@ -365,21 +366,21 @@ const AssetLibrary = { } const md5Pipe = new MD5Pipe(md5ImportMap, md5RawAssetsMap, _libraryBase); - cc.loader.insertPipeAfter(cc.loader.assetLoader, md5Pipe); - cc.loader.md5Pipe = md5Pipe; + legacyCC.loader.insertPipeAfter(legacyCC.loader.assetLoader, md5Pipe); + legacyCC.loader.md5Pipe = md5Pipe; } const subPackages = options.subPackages; if (subPackages) { - cc.loader.downloader.setSubPackages(subPackages); + legacyCC.loader.downloader.setSubPackages(subPackages); const subPackPipe = new SubPackPipe(subPackages); - cc.loader.insertPipeAfter(cc.loader.assetLoader, subPackPipe); - cc.loader.subPackPipe = subPackPipe; + legacyCC.loader.insertPipeAfter(legacyCC.loader.assetLoader, subPackPipe); + legacyCC.loader.subPackPipe = subPackPipe; } // init raw assets - const assetTables = cc.loader._assetTables; + const assetTables = legacyCC.loader._assetTables; // tslint:disable: forin for (const mount in assetTables) { assetTables[mount].reset(); @@ -395,7 +396,7 @@ const AssetLibrary = { const typeId = info[1]; const type = _getClassById(typeId); if (!type) { - cc.error('Cannot get', typeId); + legacyCC.error('Cannot get', typeId); continue; } // backward compatibility since 1.10 @@ -417,7 +418,7 @@ const AssetLibrary = { } // init cc.url - cc.url._init((options.mountPaths && options.mountPaths.assets) || _rawAssetsBase + 'assets'); + legacyCC.url._init((options.mountPaths && options.mountPaths.assets) || _rawAssetsBase + 'assets'); }, }; @@ -431,5 +432,5 @@ const AssetLibrary = { // } // }; -cc.AssetLibrary = AssetLibrary; +legacyCC.AssetLibrary = AssetLibrary; export default AssetLibrary; diff --git a/cocos/core/assets/asset.ts b/cocos/core/assets/asset.ts index 0f0cc992e6..ceecc10e2c 100644 --- a/cocos/core/assets/asset.ts +++ b/cocos/core/assets/asset.ts @@ -36,6 +36,7 @@ import { applyMixins, IEventTarget } from '../event/event-target-factory'; import { createMap } from '../utils/js-typed'; import { RawAsset } from './raw-asset'; import { Node } from '../scene-graph'; +import { legacyCC } from '../global-exports'; /** * @en @@ -88,7 +89,7 @@ export class Asset extends RawAsset implements IEventTarget { * @return {Asset} */ public static deserialize (data) { - return cc.deserialize(data); + return legacyCC.deserialize(data); } /** @@ -158,8 +159,8 @@ export class Asset extends RawAsset implements IEventTarget { // not imported in library, just created on-the-fly return name.slice(1); } - if (cc.AssetLibrary) { - const base = cc.AssetLibrary.getLibUrlNoExt(this._uuid, true); + if (legacyCC.AssetLibrary) { + const base = legacyCC.AssetLibrary.getLibUrlNoExt(this._uuid, true); if (name.charCodeAt(0) === 46) { // '.' // imported in dir where json exist return base + name; @@ -170,7 +171,7 @@ export class Asset extends RawAsset implements IEventTarget { } } else { - cc.errorID(6400); + legacyCC.errorID(6400); } } return ''; @@ -275,4 +276,4 @@ type CreateNodeCallback = (error: Error | null, node: Node) => void; // @ts-ignore Asset.prototype.createNode = null; -cc.Asset = Asset; +legacyCC.Asset = Asset; diff --git a/cocos/core/assets/bitmap-font.ts b/cocos/core/assets/bitmap-font.ts index 9e37455c1e..6c41020b33 100644 --- a/cocos/core/assets/bitmap-font.ts +++ b/cocos/core/assets/bitmap-font.ts @@ -31,6 +31,7 @@ import { ccclass, property } from '../data/class-decorator'; import { Font } from './font'; import { SpriteFrame } from './sprite-frame'; +import { legacyCC } from '../global-exports'; export interface IConfig { [key: string]: any; @@ -73,4 +74,4 @@ export class BitmapFont extends Font { public fntConfig: IConfig | null = null; } -cc.BitmapFont = BitmapFont; +legacyCC.BitmapFont = BitmapFont; diff --git a/cocos/core/assets/effect-asset.ts b/cocos/core/assets/effect-asset.ts index 355e6f642e..a6ac058991 100644 --- a/cocos/core/assets/effect-asset.ts +++ b/cocos/core/assets/effect-asset.ts @@ -38,6 +38,7 @@ import { IDefineMap } from '../renderer/core/pass-utils'; import { programLib } from '../renderer/core/program-lib'; import { Asset } from './asset'; import { EDITOR } from 'internal:constants'; +import { legacyCC } from '../global-exports'; export interface IPropertyInfo { type: number; // auto-extracted from shader @@ -183,12 +184,12 @@ export class EffectAsset extends Asset { */ public onLoaded () { this.shaders.forEach((s) => programLib.define(s)); - if (!EDITOR) { cc.game.once(cc.Game.EVENT_ENGINE_INITED, this._precompile, this); } + if (!EDITOR) { legacyCC.game.once(legacyCC.Game.EVENT_ENGINE_INITED, this._precompile, this); } EffectAsset.register(this); } protected _precompile () { - const root = cc.director.root as Root; + const root = legacyCC.director.root as Root; for (let i = 0; i < this.shaders.length; i++) { const shader = this.shaders[i]; const combination = this.combinations[i]; @@ -204,4 +205,4 @@ export class EffectAsset extends Asset { } } -cc.EffectAsset = EffectAsset; +legacyCC.EffectAsset = EffectAsset; diff --git a/cocos/core/assets/font.ts b/cocos/core/assets/font.ts index 3f7c322006..640f96f2fa 100644 --- a/cocos/core/assets/font.ts +++ b/cocos/core/assets/font.ts @@ -30,6 +30,7 @@ import {ccclass} from '../data/class-decorator'; import { Asset } from './asset'; +import { legacyCC } from '../global-exports'; /** * @en @@ -43,4 +44,4 @@ import { Asset } from './asset'; export class Font extends Asset { } -cc.Font = Font; +legacyCC.Font = Font; diff --git a/cocos/core/assets/image-asset.ts b/cocos/core/assets/image-asset.ts index b597415a06..84e2d57b46 100644 --- a/cocos/core/assets/image-asset.ts +++ b/cocos/core/assets/image-asset.ts @@ -33,6 +33,7 @@ import { GFXDevice, GFXFeature } from '../gfx/device'; import { Asset } from './asset'; import { PixelFormat } from './asset-enum'; import { EDITOR, MINIGAME } from 'internal:constants'; +import { legacyCC } from '../global-exports'; /** * 内存图像源。 @@ -123,7 +124,7 @@ export class ImageAsset extends Asset { get _texture () { if (!this._tex) { - const tex = new cc.Texture2D(); + const tex = new legacyCC.Texture2D(); tex.name = this._url; tex.image = this; this._tex = tex; @@ -193,7 +194,7 @@ export class ImageAsset extends Asset { this._onDataComplete(); }); data.addEventListener('error', (err) => { - cc.warnID(3119, err.message); + legacyCC.warnID(3119, err.message); }); } } @@ -249,7 +250,7 @@ export class ImageAsset extends Asset { let preferedExtensionIndex = Number.MAX_VALUE; let format = this._format; let ext = ''; - const SupportTextureFormats = cc.macro.SUPPORT_TEXTURE_FORMATS as string[]; + const SupportTextureFormats = legacyCC.macro.SUPPORT_TEXTURE_FORMATS as string[]; for (const extensionID of extensionIDs) { const extFormat = extensionID.split('@'); @@ -267,7 +268,7 @@ export class ImageAsset extends Asset { } else if ((fmt === PixelFormat.RGB_ETC2 || fmt === PixelFormat.RGBA_ETC2) && (!device || !device.hasFeature(GFXFeature.FORMAT_ETC2))) { continue; - } else if (tmpExt === '.webp' && !cc.sys.capabilities.webp) { + } else if (tmpExt === '.webp' && !legacyCC.sys.capabilities.webp) { continue; } preferedExtensionIndex = index; @@ -297,8 +298,8 @@ export class ImageAsset extends Asset { } function _getGlobalDevice (): GFXDevice | null { - if (cc.director.root) { - return cc.director.root.device; + if (legacyCC.director.root) { + return legacyCC.director.root.device; } else { return null; } @@ -313,4 +314,4 @@ function _getGlobalDevice (): GFXDevice | null { * @event loads */ -cc.ImageAsset = ImageAsset; +legacyCC.ImageAsset = ImageAsset; diff --git a/cocos/core/assets/index.ts b/cocos/core/assets/index.ts index 7247b1ce8d..1346cfbfab 100644 --- a/cocos/core/assets/index.ts +++ b/cocos/core/assets/index.ts @@ -27,7 +27,7 @@ /** * @hidden */ - +import { legacyCC } from '../global-exports'; export { RawAsset } from './raw-asset'; export { Asset } from './asset'; export {default as Prefab} from './prefab'; @@ -46,7 +46,7 @@ export { LabelAtlas } from './label-atlas'; export { BitmapFont } from './bitmap-font'; export { Font } from './font'; import * as textureUtil from './texture-util'; -cc.textureUtil = textureUtil; +legacyCC.textureUtil = textureUtil; export { textureUtil }; export { EffectAsset } from './effect-asset'; export { Material } from './material'; diff --git a/cocos/core/assets/json-asset.ts b/cocos/core/assets/json-asset.ts index 0ac53c6851..2c6b49e683 100644 --- a/cocos/core/assets/json-asset.ts +++ b/cocos/core/assets/json-asset.ts @@ -29,6 +29,7 @@ import {ccclass, property} from '../data/class-decorator'; import { Asset } from './asset'; +import { legacyCC } from '../global-exports'; /** * @zh @@ -44,4 +45,4 @@ export default class JsonAsset extends Asset { public json: object | null = null; } -cc.JsonAsset = JsonAsset; +legacyCC.JsonAsset = JsonAsset; diff --git a/cocos/core/assets/label-atlas.ts b/cocos/core/assets/label-atlas.ts index 6b47596a9c..b5b6288dcc 100644 --- a/cocos/core/assets/label-atlas.ts +++ b/cocos/core/assets/label-atlas.ts @@ -30,6 +30,7 @@ import { ccclass } from '../data/class-decorator'; import { BitmapFont } from './bitmap-font'; +import { legacyCC } from '../global-exports'; /** * @en * Class for LabelAtlas handling. @@ -43,4 +44,4 @@ import { BitmapFont } from './bitmap-font'; export class LabelAtlas extends BitmapFont{ } -cc.LabelAtlas = LabelAtlas; +legacyCC.LabelAtlas = LabelAtlas; diff --git a/cocos/core/assets/material.ts b/cocos/core/assets/material.ts index 9bae6024c4..2b2bd104c5 100644 --- a/cocos/core/assets/material.ts +++ b/cocos/core/assets/material.ts @@ -41,6 +41,7 @@ import { Asset } from './asset'; import { EffectAsset } from './effect-asset'; import { SpriteFrame } from './sprite-frame'; import { TextureBase } from './texture-base'; +import { legacyCC } from '../global-exports'; /** * @en @@ -365,7 +366,7 @@ export class Material extends Asset { if (passInfo.switch && !defs[passInfo.switch]) { continue; } passInfo.stateOverrides = this._states.length > k ? this._states[k] : {}; passInfo.idxInTech = k; - const pass = new Pass(cc.director.root.device); + const pass = new Pass(legacyCC.director.root.device); pass.initialize(passInfo); passes.push(pass); } @@ -425,7 +426,7 @@ export class Material extends Asset { } pass.bindTextureView(binding, textureView); if (val instanceof TextureBase) { - pass.bindSampler(binding, samplerLib.getSampler(cc.director.root.device, val.getSamplerHash())); + pass.bindSampler(binding, samplerLib.getSampler(legacyCC.director.root.device, val.getSamplerHash())); } } else if (!val) { pass.resetTexture(name); @@ -448,4 +449,4 @@ export class Material extends Asset { } } -cc.Material = Material; +legacyCC.Material = Material; diff --git a/cocos/core/assets/mesh.ts b/cocos/core/assets/mesh.ts index cc962b3689..ea2936bda9 100644 --- a/cocos/core/assets/mesh.ts +++ b/cocos/core/assets/mesh.ts @@ -52,6 +52,7 @@ import { Asset } from './asset'; import { Skeleton } from './skeleton'; import { postLoadMesh } from './utils/mesh-utils'; import { Morph, createMorphRendering, MorphRendering } from './morph'; +import { legacyCC } from '../global-exports'; function getIndexStrideCtor (stride: number) { switch (stride) { @@ -139,7 +140,7 @@ export class RenderingSubMesh { const indices = mesh.readIndices(index) as Uint16Array; const max = new Vec3(); const min = new Vec3(); - const pAttri = this.attributes.find(element => element.name == cc.GFXAttributeName.ATTR_POSITION); + const pAttri = this.attributes.find(element => element.name == legacyCC.GFXAttributeName.ATTR_POSITION); if (pAttri) { const conut = GFXFormatInfos[pAttri.format].count; if (conut == 2) { @@ -221,7 +222,7 @@ export class RenderingSubMesh { } let jointFormat: GFXFormat; let jointOffset: number; - const device: GFXDevice = cc.director.root.device; + const device: GFXDevice = legacyCC.director.root.device; for (let i = 0; i < prim.vertexBundelIndices.length; i++) { const bundle = struct.vertexBundles[prim.vertexBundelIndices[i]]; jointOffset = 0; @@ -465,8 +466,8 @@ export class Mesh extends Asset { set _nativeAsset (value: ArrayBuffer) { if (this._data && this._data.byteLength === value.byteLength) { this._data.set(new Uint8Array(value)); - if (cc.loader._cache[this.nativeUrl]) { - cc.loader._cache[this.nativeUrl].content = this._data.buffer; + if (legacyCC.loader._cache[this.nativeUrl]) { + legacyCC.loader._cache[this.nativeUrl].content = this._data.buffer; } } else { @@ -564,7 +565,7 @@ export class Mesh extends Asset { postLoadMesh(this); } const buffer = this._data.buffer; - const gfxDevice: GFXDevice = cc.director.root.device; + const gfxDevice: GFXDevice = legacyCC.director.root.device; const vertexBuffers = this._createVertexBuffers(gfxDevice, buffer); const indexBuffers: GFXBuffer[] = []; const subMeshes: RenderingSubMesh[] = []; @@ -1275,7 +1276,7 @@ export class Mesh extends Asset { public morphRendering: MorphRendering | null = null; } -cc.Mesh = Mesh; +legacyCC.Mesh = Mesh; function getOffset (attributes: IGFXAttribute[], attributeIndex: number) { let result = 0; diff --git a/cocos/core/assets/morph-rendering.ts b/cocos/core/assets/morph-rendering.ts index 5d739193ce..d3d8d28a69 100644 --- a/cocos/core/assets/morph-rendering.ts +++ b/cocos/core/assets/morph-rendering.ts @@ -9,6 +9,7 @@ import { MorphRendering, SubMeshMorph, Morph, MorphRenderingInstance } from './m import { assertIsNonNullable, assertIsTrue } from '../data/utils/asserts'; import { nextPow2 } from '../math/bits'; import { IMacroPatch } from '../renderer'; +import { legacyCC } from '../global-exports'; /** * True if force to use cpu computing based sub-mesh rendering. @@ -415,7 +416,7 @@ class CpuComputingRenderingInstance implements SubMeshMorphRenderingInstance { if (false) { for (let i = 0; i texture.width) { - cc.errorID(3300, this.name + '/' + texture.name, maxX, texture.width); + legacyCC.errorID(3300, this.name + '/' + texture.name, maxX, texture.width); return false; } if (maxY > texture.height) { - cc.errorID(3301, this.name + '/' + texture.name, maxY, texture.height); + legacyCC.errorID(3301, this.name + '/' + texture.name, maxY, texture.height); return false; } @@ -952,4 +953,4 @@ export class SpriteFrame extends Asset { } } -cc.SpriteFrame = SpriteFrame; +legacyCC.SpriteFrame = SpriteFrame; diff --git a/cocos/core/assets/text-asset.ts b/cocos/core/assets/text-asset.ts index f342612a57..e0698f22c1 100644 --- a/cocos/core/assets/text-asset.ts +++ b/cocos/core/assets/text-asset.ts @@ -30,6 +30,7 @@ import {ccclass, property} from '../data/class-decorator'; import { Asset } from './asset'; +import { legacyCC } from '../global-exports'; /** * @en Class for text file. @@ -52,4 +53,4 @@ export default class TextAsset extends Asset { } } -cc.TextAsset = TextAsset; +legacyCC.TextAsset = TextAsset; diff --git a/cocos/core/assets/texture-2d.ts b/cocos/core/assets/texture-2d.ts index aa3853e3a4..428593c4b0 100644 --- a/cocos/core/assets/texture-2d.ts +++ b/cocos/core/assets/texture-2d.ts @@ -33,6 +33,7 @@ import { GFXTextureType, GFXTextureViewType } from '../gfx/define'; import { PixelFormat } from './asset-enum'; import { ImageAsset } from './image-asset'; import { PresumedGFXTextureInfo, PresumedGFXTextureViewInfo, SimpleTexture } from './simple-texture'; +import { legacyCC } from '../global-exports'; /** * 贴图创建选项。 @@ -275,7 +276,7 @@ export class Texture2D extends SimpleTexture { } } -cc.Texture2D = Texture2D; +legacyCC.Texture2D = Texture2D; export interface ITexture2DSerializeData { base: string; diff --git a/cocos/core/assets/texture-base.ts b/cocos/core/assets/texture-base.ts index 3770fcbfbb..27a91bbab8 100644 --- a/cocos/core/assets/texture-base.ts +++ b/cocos/core/assets/texture-base.ts @@ -37,6 +37,7 @@ import IDGenerator from '../utils/id-generator'; import { Asset } from './asset'; import { Filter, PixelFormat, WrapMode } from './asset-enum'; import { GFXSampler } from '../gfx'; +import { legacyCC } from '../global-exports'; const CHAR_CODE_1 = 49; // '1' @@ -269,7 +270,7 @@ export class TextureBase extends Asset { if (this._gfxDevice) { this._gfxSampler = samplerLib.getSampler(this._gfxDevice, this._samplerHash); } else { - cc.errorID(9302); + legacyCC.errorID(9302); } } return this._gfxSampler; @@ -314,7 +315,7 @@ export class TextureBase extends Asset { } protected _getGFXDevice (): GFXDevice | null { - return cc.director.root && cc.director.root.device; + return legacyCC.director.root && legacyCC.director.root.device; } protected _getGFXFormat () { @@ -326,4 +327,4 @@ export class TextureBase extends Asset { } } -cc.TextureBase = TextureBase; +legacyCC.TextureBase = TextureBase; diff --git a/cocos/core/assets/texture-cube.ts b/cocos/core/assets/texture-cube.ts index 9565946677..bb142921c5 100644 --- a/cocos/core/assets/texture-cube.ts +++ b/cocos/core/assets/texture-cube.ts @@ -32,6 +32,7 @@ import { GFXTextureFlagBit, GFXTextureType, GFXTextureViewType } from '../gfx/de import { ImageAsset } from './image-asset'; import { PresumedGFXTextureInfo, PresumedGFXTextureViewInfo, SimpleTexture } from './simple-texture'; import { ITexture2DCreateInfo, Texture2D } from './texture-2d'; +import { legacyCC } from '../global-exports'; export type ITextureCubeCreateInfo = ITexture2DCreateInfo; @@ -275,7 +276,7 @@ export class TextureCube extends SimpleTexture { } -cc.TextureCube = TextureCube; +legacyCC.TextureCube = TextureCube; interface ITextureCubeSerializeData { base: string; diff --git a/cocos/core/assets/ttf-font.ts b/cocos/core/assets/ttf-font.ts index 81b07c74b9..f4fc2a41b4 100644 --- a/cocos/core/assets/ttf-font.ts +++ b/cocos/core/assets/ttf-font.ts @@ -30,6 +30,7 @@ import {ccclass, property, string} from '../data/class-decorator'; import { Font } from './font'; +import { legacyCC } from '../global-exports'; /** * @en @@ -56,4 +57,4 @@ export class TTFFont extends Font { } } -cc.TTFFont = TTFFont; +legacyCC.TTFFont = TTFFont; diff --git a/cocos/core/assets/utils/mesh-utils.ts b/cocos/core/assets/utils/mesh-utils.ts index de0882ac7b..8cd2891cf3 100644 --- a/cocos/core/assets/utils/mesh-utils.ts +++ b/cocos/core/assets/utils/mesh-utils.ts @@ -23,6 +23,7 @@ THE SOFTWARE. */ import { Mesh } from '../mesh'; +import { legacyCC } from '../../global-exports'; export function postLoadMesh (mesh: Mesh, callback?: Function) { if (mesh.loaded) { if (callback) { @@ -37,7 +38,7 @@ export function postLoadMesh (mesh: Mesh, callback?: Function) { return; } // load image - cc.loader.load({ + legacyCC.loader.load({ url: mesh.nativeUrl, }, (err, arrayBuffer) => { if (arrayBuffer) { diff --git a/cocos/core/components/block-input-events-component.ts b/cocos/core/components/block-input-events-component.ts index 865c06d678..30da01a20d 100644 --- a/cocos/core/components/block-input-events-component.ts +++ b/cocos/core/components/block-input-events-component.ts @@ -43,6 +43,7 @@ import { ccclass, help, menu } from '../data/class-decorator'; import { Component } from './component'; import { Event } from '../event'; import { SystemEventType } from '../platform/event-manager/event-enum'; +import { legacyCC } from '../global-exports'; const BlockEvents = [SystemEventType.TOUCH_START, SystemEventType.TOUCH_END, SystemEventType.TOUCH_MOVE, SystemEventType.MOUSE_DOWN, SystemEventType.MOUSE_MOVE, SystemEventType.MOUSE_UP, @@ -71,4 +72,4 @@ export class BlockInputEventsComponent extends Component { } } -cc.BlockInputEventsComponent = BlockInputEventsComponent; +legacyCC.BlockInputEventsComponent = BlockInputEventsComponent; diff --git a/cocos/core/components/component-event-handler.ts b/cocos/core/components/component-event-handler.ts index f0c2e1d92f..4f38bb7816 100644 --- a/cocos/core/components/component-event-handler.ts +++ b/cocos/core/components/component-event-handler.ts @@ -30,6 +30,7 @@ import {ccclass, property} from '../data/class-decorator'; import { Node } from '../scene-graph'; +import { legacyCC } from '../global-exports'; /** * @zh @@ -80,7 +81,7 @@ export class EventHandler { * @zh * 目标节点。 */ - @property(cc.Node) + @property(legacyCC.Node) public target: Node | null = null; /** * @zh @@ -123,13 +124,13 @@ export class EventHandler { */ public emit (params: any[]) { const target = this.target; - if (!cc.isValid(target)) { return; } + if (!legacyCC.isValid(target)) { return; } this._genCompIdIfNeeded(); - const compType = cc.js._getClassById(this._componentId); + const compType = legacyCC.js._getClassById(this._componentId); const comp = target!.getComponent(compType); - if (!cc.isValid(comp)) { return; } + if (!legacyCC.isValid(comp)) { return; } const handler = comp![this.handler]; if (typeof(handler) !== 'function') { return; } @@ -143,13 +144,13 @@ export class EventHandler { } private _compName2Id (compName) { - const comp = cc.js.getClassByName(compName); - return cc.js._getClassId(comp); + const comp = legacyCC.js.getClassByName(compName); + return legacyCC.js._getClassId(comp); } private _compId2Name (compId) { - const comp = cc.js._getClassById(compId); - return cc.js.getClassName(comp); + const comp = legacyCC.js._getClassById(compId); + return legacyCC.js.getClassName(comp); } // to be deprecated in the future @@ -161,4 +162,4 @@ export class EventHandler { } } -cc.Component.EventHandler = EventHandler; +legacyCC.Component.EventHandler = EventHandler; diff --git a/cocos/core/components/component.ts b/cocos/core/components/component.ts index 77e177195a..82d00f1398 100644 --- a/cocos/core/components/component.ts +++ b/cocos/core/components/component.ts @@ -40,6 +40,7 @@ import { Rect } from '../math'; import * as RF from '../data/utils/requiring-frame'; import { Node } from '../scene-graph'; import { EDITOR, TEST, DEV } from 'internal:constants'; +import { legacyCC } from '../global-exports'; const idGenerator = new IDGenerator('Comp'); // @ts-ignore @@ -131,7 +132,7 @@ class Component extends CCObject { if (this._enabled !== value) { this._enabled = value; if (this.node.activeInHierarchy) { - const compScheduler = cc.director._compScheduler; + const compScheduler = legacyCC.director._compScheduler; if (value) { compScheduler.enableComp(this); } @@ -361,13 +362,13 @@ class Component extends CCObject { // @ts-ignore const depend = this.node._getDependComponent(this); if (depend) { - return cc.errorID(3626, + return legacyCC.errorID(3626, getClassName(this), getClassName(depend)); } } if (super.destroy()) { if (this._enabled && this.node.activeInHierarchy) { - cc.director._compScheduler.disableComp(this); + legacyCC.director._compScheduler.disableComp(this); } } } @@ -391,7 +392,7 @@ class Component extends CCObject { } // onDestroy - cc.director._nodeActivator.destroyComp(this); + legacyCC.director._nodeActivator.destroyComp(this); // do remove component this.node._removeComponent(this); @@ -399,7 +400,7 @@ class Component extends CCObject { public _instantiate (cloned) { if (!cloned) { - cloned = cc.instantiate._clone(this, this); + cloned = legacyCC.instantiate._clone(this, this); } cloned.node = null; return cloned; @@ -427,15 +428,15 @@ class Component extends CCObject { * this.schedule(timeCallback, 1); * ``` */ - public schedule (callback, interval: number = 0, repeat: number = cc.macro.REPEAT_FOREVER, delay: number = 0) { - cc.assertID(callback, 1619); - cc.assertID(interval >= 0, 1620); + public schedule (callback, interval: number = 0, repeat: number = legacyCC.macro.REPEAT_FOREVER, delay: number = 0) { + legacyCC.assertID(callback, 1619); + legacyCC.assertID(interval >= 0, 1620); interval = interval || 0; - repeat = isNaN(repeat) ? cc.macro.REPEAT_FOREVER : repeat; + repeat = isNaN(repeat) ? legacyCC.macro.REPEAT_FOREVER : repeat; delay = delay || 0; - const scheduler = cc.director.getScheduler(); + const scheduler = legacyCC.director.getScheduler(); // should not use enabledInHierarchy to judge whether paused, // because enabledInHierarchy is assigned after onEnable. @@ -479,7 +480,7 @@ class Component extends CCObject { return; } - cc.director.getScheduler().unschedule(callback_fn, this); + legacyCC.director.getScheduler().unschedule(callback_fn, this); } /** @@ -494,7 +495,7 @@ class Component extends CCObject { * ``` */ public unscheduleAllCallbacks () { - cc.director.getScheduler().unscheduleAllForTarget(this); + legacyCC.director.getScheduler().unscheduleAllForTarget(this); } // LIFECYCLE METHODS @@ -706,7 +707,7 @@ if (EDITOR || TEST) { // COMPONENT HELPERS // TODO Keep temporarily, compatible with old version - cc._componentMenuItems = []; + legacyCC._componentMenuItems = []; } // we make this non-enumerable, to prevent inherited by sub classes. @@ -735,7 +736,7 @@ value(Component, '_registerEditorProps', function (cls, props) { cls._playOnFocus = true; } else { - cc.warnID(3601, name); + legacyCC.warnID(3601, name); } } break; @@ -772,12 +773,12 @@ value(Component, '_registerEditorProps', function (cls, props) { break; default: - cc.warnID(3602, key, name); + legacyCC.warnID(3602, key, name); break; } } } }); -cc.Component = Component; +legacyCC.Component = Component; export { Component }; diff --git a/cocos/core/components/missing-script.ts b/cocos/core/components/missing-script.ts index ee2bc00493..62f5e0332e 100644 --- a/cocos/core/components/missing-script.ts +++ b/cocos/core/components/missing-script.ts @@ -33,6 +33,7 @@ import {_getClassById} from '../utils/js'; import {BUILTIN_CLASSID_RE} from '../utils/misc'; import { Component } from './component'; import { EDITOR } from 'internal:constants'; +import { legacyCC } from '../global-exports'; /** * @en @@ -80,7 +81,7 @@ export default class MissingScript extends Component { return cls; } if (id) { - cc.deserialize.reportMissingClass(id); + legacyCC.deserialize.reportMissingClass(id); return MissingScript.getMissingWrapper(id, data); } return null; @@ -116,8 +117,8 @@ export default class MissingScript extends Component { } public onLoad () { - cc.warnID(4600, this.node.name); + legacyCC.warnID(4600, this.node.name); } } -cc._MissingScript = MissingScript; +legacyCC._MissingScript = MissingScript; diff --git a/cocos/core/components/ui-base/canvas-component.ts b/cocos/core/components/ui-base/canvas-component.ts index 037db36f26..f679d9f891 100644 --- a/cocos/core/components/ui-base/canvas-component.ts +++ b/cocos/core/components/ui-base/canvas-component.ts @@ -44,6 +44,7 @@ import { Enum } from '../../value-types'; import { Component } from '../component'; import { UITransformComponent } from './ui-transform-component'; import { EDITOR } from 'internal:constants'; +import { legacyCC } from '../../global-exports'; const _worldPos = new Vec3(); @@ -343,7 +344,7 @@ export class CanvasComponent extends Component { designSize = view.getDesignResolutionSize(); const policy = view.getResolutionPolicy(); // const clipTopRight = !this.fitHeight && !this.fitWidth; - const clipTopRight = policy === cc.view._rpNoBorder; + const clipTopRight = policy === legacyCC.view._rpNoBorder; let offsetX = 0; let offsetY = 0; if (clipTopRight) { @@ -423,4 +424,4 @@ export class CanvasComponent extends Component { } } -cc.CanvasComponent = CanvasComponent; +legacyCC.CanvasComponent = CanvasComponent; diff --git a/cocos/core/components/ui-base/ui-render-component.ts b/cocos/core/components/ui-base/ui-render-component.ts index 1fd97b293b..4a8e446597 100644 --- a/cocos/core/components/ui-base/ui-render-component.ts +++ b/cocos/core/components/ui-base/ui-render-component.ts @@ -43,6 +43,7 @@ import { UI } from '../../renderer/ui/ui'; import { Node } from '../../scene-graph'; import { TransformBit } from '../../scene-graph/node-enum'; import { UIComponent } from './ui-component'; +import { legacyCC } from '../../global-exports'; // hack ccenum(GFXBlendFactor); @@ -461,4 +462,4 @@ export class UIRenderComponent extends UIComponent { protected _flushAssembler? (): void; } -cc.UIRenderComponent = UIRenderComponent; +legacyCC.UIRenderComponent = UIRenderComponent; diff --git a/cocos/core/components/ui-base/ui-transform-component.ts b/cocos/core/components/ui-base/ui-transform-component.ts index 9eba2f7c31..7fbd12db42 100644 --- a/cocos/core/components/ui-base/ui-transform-component.ts +++ b/cocos/core/components/ui-base/ui-transform-component.ts @@ -36,6 +36,7 @@ import { aabb } from '../../geometry'; import { CanvasComponent } from './canvas-component'; import { Node } from '../../scene-graph'; import { EDITOR } from 'internal:constants'; +import { legacyCC } from '../../global-exports'; const _vec2a = new Vec2(); const _vec2b = new Vec2(); @@ -211,7 +212,7 @@ export class UITransformComponent extends Component { } if (this._canvas && this._canvas.node === this.node) { - cc.warn(9200); + legacyCC.warn(9200); return; } @@ -388,7 +389,7 @@ export class UITransformComponent extends Component { canvas.node.getWorldRT(_mat4_temp); const m12 = _mat4_temp.m12; const m13 = _mat4_temp.m13; - const center = cc.visibleRect.center; + const center = legacyCC.visibleRect.center; _mat4_temp.m12 = center.x - (_mat4_temp.m00 * m12 + _mat4_temp.m04 * m13); _mat4_temp.m13 = center.y - (_mat4_temp.m01 * m12 + _mat4_temp.m05 * m13); Mat4.invert(_mat4_temp, _mat4_temp); @@ -408,7 +409,7 @@ export class UITransformComponent extends Component { for (let i = 0; parent && i < mask.index; ++i, parent = parent.parent) { } if (parent === mask.node) { - const comp = parent.getComponent(cc.MaskComponent); + const comp = parent.getComponent(legacyCC.MaskComponent); return (comp && comp.enabledInHierarchy) ? comp.isHit(cameraPt) : true; } else { listener.mask = null; @@ -641,4 +642,4 @@ export class UITransformComponent extends Component { } } -cc.UITransformComponent = UITransformComponent; +legacyCC.UITransformComponent = UITransformComponent; diff --git a/cocos/core/data/class-decorator.ts b/cocos/core/data/class-decorator.ts index a7a10fa0f1..8dfe15166f 100644 --- a/cocos/core/data/class-decorator.ts +++ b/cocos/core/data/class-decorator.ts @@ -55,6 +55,7 @@ import { doValidateMethodWithProps_DEV, getFullFormOfProperty } from './utils/pr import { CCString, CCInteger, CCFloat, CCBoolean, PrimitiveType } from './utils/attribute'; import { error, errorID, warnID } from '../platform/debug'; import { DEV } from 'internal:constants'; +import { legacyCC } from '../global-exports'; // caches for class construction const CACHE_KEY = '__ccclassCache__'; @@ -93,7 +94,7 @@ function _checkNormalArgument (validator_DEV, decorate, decoratorName) { } const checkCompArgument = _checkNormalArgument.bind(null, DEV && function (arg, decoratorName) { - if (!cc.Class._isCCClass(arg)) { + if (!legacyCC.Class._isCCClass(arg)) { error('The parameter for %s is missing.', decoratorName); return false; } @@ -101,7 +102,7 @@ const checkCompArgument = _checkNormalArgument.bind(null, DEV && function (arg, function _argumentChecker (type) { return _checkNormalArgument.bind(null, DEV && function (arg, decoratorName) { - if (arg instanceof cc.Component || arg === undefined) { + if (arg instanceof legacyCC.Component || arg === undefined) { error('The parameter for %s is missing.', decoratorName); return false; } @@ -116,7 +117,7 @@ const checkNumberArgument = _argumentChecker('number'); // var checkBooleanArgument = _argumentChecker('boolean'); function getClassCache (ctor, decoratorName?) { - if (DEV && cc.Class._isCCClass(ctor)) { + if (DEV && legacyCC.Class._isCCClass(ctor)) { error('`@%s` should be used after @ccclass for class "%s"', decoratorName, js.getClassName(ctor)); return null; } @@ -289,7 +290,7 @@ export const ccclass = checkCtorArgument(function (ctor, name) { ctor[CACHE_KEY] = undefined; } - const res = cc.Class(proto); + const res = legacyCC.Class(proto); // validate methods if (DEV) { diff --git a/cocos/core/data/class.ts b/cocos/core/data/class.ts index b38995b213..d1aed3d3cd 100644 --- a/cocos/core/data/class.ts +++ b/cocos/core/data/class.ts @@ -47,6 +47,7 @@ import { preprocessAttrs, validateMethodWithProps } from './utils/preprocess-cla import * as RF from './utils/requiring-frame'; import { error } from '../platform/debug'; import { DEV, EDITOR, SUPPORT_JIT, TEST } from 'internal:constants'; +import { legacyCC } from '../global-exports'; const DELIMETER = attributeUtils.DELIMETER; @@ -235,7 +236,7 @@ function getDefault (defaultVal) { return defaultVal(); } catch (e) { - cc._throw(e); + legacyCC._throw(e); return undefined; } } @@ -354,7 +355,7 @@ function doDefine (className, baseClass, mixins, options) { } function define (className, baseClass, mixins, options) { - const Component = cc.Component; + const Component = legacyCC.Component; const frame = RF.peek(); if (frame && js.isChildClassOf(baseClass, Component)) { @@ -377,9 +378,9 @@ function define (className, baseClass, mixins, options) { const cls = doDefine(className, baseClass, mixins, options); // for RenderPipeline, RenderFlow, RenderStage - const isRenderPipeline = js.isChildClassOf(baseClass, cc.RenderPipeline); - const isRenderFlow = js.isChildClassOf(baseClass, cc.RenderFlow); - const isRenderStage = js.isChildClassOf(baseClass, cc.RenderStage); + const isRenderPipeline = js.isChildClassOf(baseClass, legacyCC.RenderPipeline); + const isRenderFlow = js.isChildClassOf(baseClass, legacyCC.RenderFlow); + const isRenderStage = js.isChildClassOf(baseClass, legacyCC.RenderStage); const isRender = isRenderPipeline || isRenderFlow || isRenderStage || false; @@ -499,7 +500,7 @@ function getInitPropsJit (attrs, propList) { let expression; const def = attrs[attrKey]; if (typeof def === 'object' && def) { - if (def instanceof cc.ValueType) { + if (def instanceof legacyCC.ValueType) { expression = getNewValueTypeCodeJit(def); } else if (Array.isArray(def)) { @@ -577,7 +578,7 @@ function getInitProps (attrs, propList) { let expression; const def = advancedValues[i]; if (typeof def === 'object') { - if (def instanceof cc.ValueType) { + if (def instanceof legacyCC.ValueType) { expression = def.clone(); } else if (Array.isArray(def)) { @@ -594,7 +595,7 @@ function getInitProps (attrs, propList) { expression = def(); } catch (err) { - cc._throw(err); + legacyCC._throw(err); continue; } } @@ -993,7 +994,7 @@ function CCClass (options) { // create constructor const cls = define(name, base, mixins, options); if (!name) { - name = cc.js.getClassName(cls); + name = legacyCC.js.getClassName(cls); } cls._sealed = true; @@ -1053,8 +1054,8 @@ function CCClass (options) { const editor = options.editor; if (editor) { - if (js.isChildClassOf(base, cc.Component)) { - cc.Component._registerEditorProps(cls, editor); + if (js.isChildClassOf(base, legacyCC.Component)) { + legacyCC.Component._registerEditorProps(cls, editor); } else if (DEV) { warnID(3623, name); @@ -1321,4 +1322,4 @@ CCClass.getNewValueTypeCode = (SUPPORT_JIT && getNewValueTypeCodeJit) as ((value export default CCClass; -cc.Class = CCClass; +legacyCC.Class = CCClass; diff --git a/cocos/core/data/deserialize.ts b/cocos/core/data/deserialize.ts index 33599c57ec..e1ab04325a 100644 --- a/cocos/core/data/deserialize.ts +++ b/cocos/core/data/deserialize.ts @@ -35,6 +35,7 @@ import CCClass from './class'; import * as Attr from './utils/attribute'; import MissingScript from '../components/missing-script'; import { EDITOR, TEST, DEV, JSB, PREVIEW, SUPPORT_JIT } from 'internal:constants'; +import { legacyCC } from '../global-exports'; // HELPERS @@ -169,7 +170,7 @@ function _dereference (self) { } function compileObjectTypeJit (sources, defaultValue, accessorToSet, propNameLiteralToSet, assumeHavePropIfIsValue, stillUseUrl) { - if (defaultValue instanceof cc.ValueType) { + if (defaultValue instanceof legacyCC.ValueType) { // fast case if (!assumeHavePropIfIsValue) { sources.push('if(prop){'); @@ -245,10 +246,10 @@ const compileDeserialize = SUPPORT_JIT ? (self, klass) => { let isPrimitiveType; const userType = attrs[propName + TYPE]; if (defaultValue === undefined && userType) { - isPrimitiveType = userType === cc.String || - userType === cc.Integer || - userType === cc.Float || - userType === cc.Boolean; + isPrimitiveType = userType === legacyCC.String || + userType === legacyCC.Integer || + userType === legacyCC.Float || + userType === legacyCC.Boolean; } else { const defaultType = typeof defaultValue; @@ -273,9 +274,9 @@ const compileDeserialize = SUPPORT_JIT ? (self, klass) => { } sources.push('}'); } - if (cc.js.isChildClassOf(klass, cc._BaseNode) || cc.js.isChildClassOf(klass, cc.Component)) { + if (legacyCC.js.isChildClassOf(klass, legacyCC._BaseNode) || legacyCC.js.isChildClassOf(klass, legacyCC.Component)) { if (PREVIEW || (EDITOR && self._ignoreEditorOnly)) { - const mayUsedInPersistRoot = js.isChildClassOf(klass, cc.Node); + const mayUsedInPersistRoot = js.isChildClassOf(klass, legacyCC.Node); if (mayUsedInPersistRoot) { sources.push('d._id&&(o._id=d._id);'); } @@ -293,7 +294,7 @@ const compileDeserialize = SUPPORT_JIT ? (self, klass) => { return Function('s', 'o', 'd', 'k', 't', sources.join('')); } : (self, klass) => { const fastMode = misc.BUILTIN_CLASSID_RE.test(js._getClassId(klass)); - const shouldCopyId = cc.js.isChildClassOf(klass, cc._BaseNode) || cc.js.isChildClassOf(klass, cc.Component); + const shouldCopyId = legacyCC.js.isChildClassOf(klass, legacyCC._BaseNode) || legacyCC.js.isChildClassOf(klass, legacyCC.Component); let shouldCopyRawData; const simpleProps: any = []; @@ -327,10 +328,10 @@ const compileDeserialize = SUPPORT_JIT ? (self, klass) => { if (fastMode) { const userType = attrs[propName + TYPE]; if (defaultValue === undefined && userType) { - isPrimitiveType = userType === cc.String || - userType === cc.Integer || - userType === cc.Float || - userType === cc.Boolean; + isPrimitiveType = userType === legacyCC.String || + userType === legacyCC.Integer || + userType === legacyCC.Float || + userType === legacyCC.Boolean; } else { const defaultType = typeof defaultValue; @@ -357,7 +358,7 @@ const compileDeserialize = SUPPORT_JIT ? (self, klass) => { advancedPropsToRead.push(propNameToRead); } advancedPropsUseUrl.push(stillUseUrl); - advancedPropsValueType.push((defaultValue instanceof cc.ValueType) && defaultValue.constructor); + advancedPropsValueType.push((defaultValue instanceof legacyCC.ValueType) && defaultValue.constructor); } } })(); @@ -448,7 +449,7 @@ function _deserializeFireClass (self, obj, serialized, klass, target) { deserialize(self, obj, serialized, klass, target); // if preview or build worker if (PREVIEW || (EDITOR && self._ignoreEditorOnly)) { - if (klass === cc._PrefabInfo && !obj.sync) { + if (klass === legacyCC._PrefabInfo && !obj.sync) { unlinkUnusedPrefab(self, serialized, obj); } } @@ -590,7 +591,7 @@ class _Deserializer { if (!klass) { const notReported = this._classFinder === js._getClassById; if (notReported) { - cc.deserialize.reportMissingClass(type); + legacyCC.deserialize.reportMissingClass(type); } return null; } @@ -613,7 +614,7 @@ class _Deserializer { obj._deserialize(serialized.content, self); return; } - if (cc.Class._isCCClass(klass)) { + if (legacyCC.Class._isCCClass(klass)) { _deserializeFireClass(self, obj, serialized, klass, target); } else { @@ -629,12 +630,12 @@ class _Deserializer { catch (e) { console.error('deserialize ' + klass.name + ' failed, ' + e.stack); klass = MissingScript.getMissingWrapper(type, serialized); - cc.deserialize.reportMissingClass(type); + legacyCC.deserialize.reportMissingClass(type); deserializeByType(); } } - if (EDITOR && cc.js.isChildClassOf(klass, cc.Component)) { + if (EDITOR && legacyCC.js.isChildClassOf(klass, legacyCC.Component)) { checkDeserializeByType(); } else { @@ -746,23 +747,23 @@ class _Deserializer { } private _deserializeTypedObject (instance, serialized, klass) { - if (klass === cc.Vec2) { + if (klass === legacyCC.Vec2) { instance.x = serialized.x || 0; instance.y = serialized.y || 0; return; - } else if (klass === cc.Vec3) { + } else if (klass === legacyCC.Vec3) { instance.x = serialized.x || 0; instance.y = serialized.y || 0; instance.z = serialized.z || 0; return; - } else if (klass === cc.Color) { + } else if (klass === legacyCC.Color) { instance.r = serialized.r || 0; instance.g = serialized.g || 0; instance.b = serialized.b || 0; const a = serialized.a; instance.a = (a === undefined ? 255 : a); return; - } else if (klass === cc.Size) { + } else if (klass === legacyCC.Size) { instance.width = serialized.width || 0; instance.height = serialized.height || 0; return; @@ -849,7 +850,7 @@ function deserialize (data, details, options) { options = options || {}; const classFinder = options.classFinder || js._getClassById; // 启用 createAssetRefs 后,如果有 url 属性则会被统一强制设置为 { uuid: 'xxx' },必须后面再特殊处理 - const createAssetRefs = options.createAssetRefs || cc.sys.platform === cc.sys.EDITOR_CORE; + const createAssetRefs = options.createAssetRefs || legacyCC.sys.platform === legacyCC.sys.EDITOR_CORE; const target = (EDITOR || TEST) && options.target; const customEnv = options.customEnv; const ignoreEditorOnly = options.ignoreEditorOnly; @@ -865,9 +866,9 @@ function deserialize (data, details, options) { // @ts-ignore const deserializer: any = _Deserializer.pool.get(details, target, classFinder, customEnv, ignoreEditorOnly); - cc.game._isCloning = true; + legacyCC.game._isCloning = true; const res = deserializer.deserialize(data); - cc.game._isCloning = false; + legacyCC.game._isCloning = false; _Deserializer.pool.put(deserializer); if (createAssetRefs) { @@ -894,6 +895,6 @@ deserialize.reportMissingClass = (id) => { warnID(5302, id); } }; -cc.deserialize = deserialize; +legacyCC.deserialize = deserialize; export default deserialize; diff --git a/cocos/core/data/index.ts b/cocos/core/data/index.ts index b4e405a3b7..4d57e9b5d6 100644 --- a/cocos/core/data/index.ts +++ b/cocos/core/data/index.ts @@ -28,7 +28,8 @@ */ import * as _decorator from './class-decorator'; -cc._decorator = _decorator; +import { legacyCC } from '../global-exports'; +legacyCC._decorator = _decorator; export { _decorator }; export { default as CCClass } from './class'; export { CCObject, isValid } from './object'; diff --git a/cocos/core/data/instantiate-jit.ts b/cocos/core/data/instantiate-jit.ts index ccfc743293..159c7b9160 100644 --- a/cocos/core/data/instantiate-jit.ts +++ b/cocos/core/data/instantiate-jit.ts @@ -36,6 +36,7 @@ import { CCObject } from './object'; import * as Attr from './utils/attribute'; import {flattenCodeArray} from './utils/compiler'; import { TEST } from 'internal:constants'; +import { legacyCC } from '../global-exports'; // @ts-ignore const Destroyed = CCObject.Flags.Destroyed; @@ -329,7 +330,7 @@ class Parser { if (equalsToDefault(defaultValue, val)) { continue; } - if (typeof val === 'object' && val instanceof cc.ValueType) { + if (typeof val === 'object' && val instanceof legacyCC.ValueType) { defaultValue = CCClass.getDefault(defaultValue); if (defaultValue && defaultValue.constructor === val.constructor) { // fast case @@ -417,7 +418,7 @@ class Parser { // codeArray - the source code array for this object public enumerateObject (codeArray, obj) { const klass = obj.constructor; - if (cc.Class._isCCClass(klass)) { + if (legacyCC.Class._isCCClass(klass)) { this.enumerateCCClass(codeArray, obj, klass); } else { @@ -439,10 +440,10 @@ class Parser { } public instantiateObj (obj) { - if (obj instanceof cc.ValueType) { + if (obj instanceof legacyCC.ValueType) { return CCClass.getNewValueTypeCode(obj); } - if (obj instanceof cc.Asset) { + if (obj instanceof legacyCC.Asset) { // register to asset list and just return the reference. return this.getObjRef(obj); } @@ -453,21 +454,21 @@ class Parser { let createCode; const ctor = obj.constructor; - if (cc.Class._isCCClass(ctor)) { + if (legacyCC.Class._isCCClass(ctor)) { if (this.parent) { - if (this.parent instanceof cc.Component) { - if (obj instanceof cc._BaseNode || obj instanceof cc.Component) { + if (this.parent instanceof legacyCC.Component) { + if (obj instanceof legacyCC._BaseNode || obj instanceof legacyCC.Component) { return this.getObjRef(obj); } } - else if (this.parent instanceof cc._BaseNode) { - if (obj instanceof cc._BaseNode) { + else if (this.parent instanceof legacyCC._BaseNode) { + if (obj instanceof legacyCC._BaseNode) { if (!obj.isChildOf(this.parent)) { // should not clone other nodes if not descendant return this.getObjRef(obj); } } - else if (obj instanceof cc.Component) { + else if (obj instanceof legacyCC.Component) { if (!obj.node.isChildOf(this.parent)) { // should not clone other component if not descendant return this.getObjRef(obj); @@ -519,7 +520,7 @@ export function equalsToDefault (def, value) { return true; } if (def && value) { - if (def instanceof cc.ValueType && def.equals(value)) { + if (def instanceof legacyCC.ValueType && def.equals(value)) { return true; } if ((Array.isArray(def) && Array.isArray(value)) || @@ -536,13 +537,13 @@ export function equalsToDefault (def, value) { } export function compile (node) { - const root = (node instanceof cc._BaseNode) && node; + const root = (node instanceof legacyCC._BaseNode) && node; const parser = new Parser(node, root); return parser.result; } if (TEST) { - cc._Test.IntantiateJit = { + legacyCC._Test.IntantiateJit = { equalsToDefault, compile, }; diff --git a/cocos/core/data/instantiate.ts b/cocos/core/data/instantiate.ts index c3baee2f2c..7f8447522a 100644 --- a/cocos/core/data/instantiate.ts +++ b/cocos/core/data/instantiate.ts @@ -34,6 +34,7 @@ import { CCObject } from './object'; import { js } from '../utils'; import { errorID, warn } from '../platform/debug'; import { DEV } from 'internal:constants'; +import { legacyCC } from '../global-exports'; // @ts-ignore const Destroyed = CCObject.Flags.Destroyed; @@ -77,13 +78,13 @@ function instantiate (original, internal_force?) { } return null; } - if (!cc.isValid(original)) { + if (!legacyCC.isValid(original)) { if (DEV) { errorID(6902); } return null; } - if (DEV && original instanceof cc.Component) { + if (DEV && original instanceof legacyCC.Component) { warn('Should not instantiate a single cc.Component directly, you must instantiate the entire node.'); } } @@ -98,12 +99,12 @@ function instantiate (original, internal_force?) { // no need to create new object by itself. // @returns {Object} - the instantiated object if (original._instantiate) { - cc.game._isCloning = true; + legacyCC.game._isCloning = true; clone = original._instantiate(); - cc.game._isCloning = false; + legacyCC.game._isCloning = false; return clone; } - else if (original instanceof cc.Asset) { + else if (original instanceof legacyCC.Asset) { // 不允许用通用方案实例化资源 if (DEV) { errorID(6903); @@ -112,9 +113,9 @@ function instantiate (original, internal_force?) { } } - cc.game._isCloning = true; + legacyCC.game._isCloning = true; clone = doInstantiate(original); - cc.game._isCloning = false; + legacyCC.game._isCloning = false; return clone; } @@ -199,7 +200,7 @@ function enumerateObject (obj, clone, parent) { js.value(obj, '_iN$t', clone, true); objsToClearTmpVar.push(obj); const klass = obj.constructor; - if (cc.Class._isCCClass(klass)) { + if (legacyCC.Class._isCCClass(klass)) { enumerateCCClass(klass, obj, clone, parent); } else { @@ -236,7 +237,7 @@ function instantiateObj (obj, parent) { if (obj instanceof ValueType) { return obj.clone(); } - if (obj instanceof cc.Asset) { + if (obj instanceof legacyCC.Asset) { // 所有资源直接引用,不需要拷贝 return obj; } @@ -264,21 +265,21 @@ function instantiateObj (obj, parent) { } const ctor = obj.constructor; - if (cc.Class._isCCClass(ctor)) { + if (legacyCC.Class._isCCClass(ctor)) { if (parent) { - if (parent instanceof cc.Component) { - if (obj instanceof cc._BaseNode || obj instanceof cc.Component) { + if (parent instanceof legacyCC.Component) { + if (obj instanceof legacyCC._BaseNode || obj instanceof legacyCC.Component) { return obj; } } - else if (parent instanceof cc._BaseNode) { - if (obj instanceof cc._BaseNode) { + else if (parent instanceof legacyCC._BaseNode) { + if (obj instanceof legacyCC._BaseNode) { if (!obj.isChildOf(parent)) { // should not clone other nodes if not descendant return obj; } } - else if (obj instanceof cc.Component) { + else if (obj instanceof legacyCC.Component) { if (!obj.node.isChildOf(parent)) { // should not clone other component if not descendant return obj; @@ -303,5 +304,5 @@ function instantiateObj (obj, parent) { } instantiate._clone = doInstantiate; -cc.instantiate = instantiate; +legacyCC.instantiate = instantiate; export default instantiate; diff --git a/cocos/core/data/object.ts b/cocos/core/data/object.ts index 4fb055f3fc..1d739a9cb1 100644 --- a/cocos/core/data/object.ts +++ b/cocos/core/data/object.ts @@ -31,6 +31,7 @@ import * as js from '../utils/js'; import CCClass from './class'; import { errorID, warnID } from '../platform/debug'; import { SUPPORT_JIT, EDITOR, TEST } from 'internal:constants'; +import { legacyCC } from '../global-exports'; // definitions for CCObject.Flags @@ -72,7 +73,7 @@ const objectsToDestroy: any = []; let deferredDestroyTimer = null; function compileDestruct (obj, ctor) { - const shouldSkipId = obj instanceof cc._BaseNode || obj instanceof cc.Component; + const shouldSkipId = obj instanceof legacyCC._BaseNode || obj instanceof legacyCC.Component; const idToSkip = shouldSkipId ? '_id' : null; let key; @@ -95,12 +96,12 @@ function compileDestruct (obj, ctor) { } // Overwrite propsToReset according to Class if (CCClass._isCCClass(ctor)) { - const attrs = cc.Class.Attr.getClassAttrs(ctor); + const attrs = legacyCC.Class.Attr.getClassAttrs(ctor); const propList = ctor.__props__; // tslint:disable-next-line: prefer-for-of for (let i = 0; i < propList.length; i++) { key = propList[i]; - const attrKey = key + cc.Class.Attr.DELIMETER + 'default'; + const attrKey = key + legacyCC.Class.Attr.DELIMETER + 'default'; if (attrKey in attrs) { if (shouldSkipId && key === '_id') { continue; @@ -281,7 +282,7 @@ class CCObject { this._objFlags |= ToDestroy; objectsToDestroy.push(this); - if (EDITOR && deferredDestroyTimer === null && cc.engine && ! cc.engine._isUpdating) { + if (EDITOR && deferredDestroyTimer === null && legacyCC.engine && ! legacyCC.engine._isUpdating) { // auto destroy immediate in edit mode // @ts-ignore deferredDestroyTimer = setImmediate(CCObject._deferredDestroy); @@ -332,7 +333,7 @@ class CCObject { this._onPreDestroy(); } - if ((TEST ? (/* make EDITOR mockable*/ Function('return !EDITOR'))() : !EDITOR) || cc.engine._isPlaying) { + if ((TEST ? (/* make EDITOR mockable*/ Function('return !EDITOR'))() : !EDITOR) || legacyCC.engine._isPlaying) { this._destruct(); } @@ -559,7 +560,7 @@ export function isValid (value: any, strictMode?: boolean) { return typeof value !== 'undefined'; } } -cc.isValid = isValid; +legacyCC.isValid = isValid; if (EDITOR || TEST) { js.value(CCObject, '_willDestroy', (obj) => { @@ -571,5 +572,5 @@ if (EDITOR || TEST) { }); } -cc.Object = CCObject; +legacyCC.Object = CCObject; export { CCObject }; diff --git a/cocos/core/data/utils/attribute.ts b/cocos/core/data/utils/attribute.ts index fcc15f2091..26389ccee2 100644 --- a/cocos/core/data/utils/attribute.ts +++ b/cocos/core/data/utils/attribute.ts @@ -31,6 +31,7 @@ import { errorID, log, warnID } from '../../platform/debug'; import { extend, formatStr, get, getClassName, isChildClassOf, value } from '../../utils/js'; import { isPlainEmptyObj_DEV } from '../../utils/misc'; import { EDITOR, DEV, SUPPORT_JIT } from 'internal:constants'; +import { legacyCC } from '../../global-exports'; export const DELIMETER = '$_$'; @@ -62,7 +63,7 @@ export function createAttrsSingle (owner: Object, ownerConstructor: Function, su */ export function createAttrs (subclass: any) { let superClass: any; - const chains: any[] = cc.Class.getInheritanceChain(subclass); + const chains: any[] = legacyCC.Class.getInheritanceChain(subclass); for (let i = chains.length - 1; i >= 0; i--) { const cls = chains[i]; const attrs = cls.hasOwnProperty('__attrs__') && cls.__attrs__; @@ -185,8 +186,8 @@ export class PrimitiveType { * ``` */ export const CCInteger = new PrimitiveType('Integer', 0); -cc.Integer = CCInteger; -cc.CCInteger = CCInteger; +legacyCC.Integer = CCInteger; +legacyCC.CCInteger = CCInteger; /** * 指定编辑器以浮点数形式对待该属性或数组元素。 @@ -204,11 +205,11 @@ cc.CCInteger = CCInteger; * ``` */ export const CCFloat = new PrimitiveType('Float', 0.0); -cc.Float = CCFloat; -cc.CCFloat = CCFloat; +legacyCC.Float = CCFloat; +legacyCC.CCFloat = CCFloat; if (EDITOR) { - get(cc, 'Number', function () { + get(legacyCC, 'Number', function () { warnID(3603); return CCFloat; }); @@ -230,8 +231,8 @@ if (EDITOR) { * ``` */ export const CCBoolean = new PrimitiveType('Boolean', false); -cc.Boolean = CCBoolean; -cc.CCBoolean = CCBoolean; +legacyCC.Boolean = CCBoolean; +legacyCC.CCBoolean = CCBoolean; /** * 指定编辑器以字符串形式对待该属性或数组元素。 @@ -249,8 +250,8 @@ cc.CCBoolean = CCBoolean; * ``` */ export const CCString = new PrimitiveType('String', ''); -cc.String = CCString; -cc.CCString = CCString; +legacyCC.String = CCString; +legacyCC.CCString = CCString; /* BuiltinAttributes: { @@ -311,7 +312,7 @@ export function getTypeChecker (type: string, attributeName: string) { } } else if (defaultType !== 'function') { if (type === CCString.default && defaultVal == null) { - if (!isChildClassOf(mainPropAttrs.ctor, cc.RawAsset)) { + if (!isChildClassOf(mainPropAttrs.ctor, legacyCC.RawAsset)) { warnID(3607, propInfo); } } else { @@ -330,8 +331,8 @@ export function getObjTypeChecker (typeCtor) { getTypeChecker('Object', 'type')(classCtor, mainPropName); // check ValueType const defaultDef = getClassAttrs(classCtor)[mainPropName + DELIMETER + 'default']; - const defaultVal = cc.Class.getDefault(defaultDef); - if (!Array.isArray(defaultVal) && isChildClassOf(typeCtor, cc.ValueType)) { + const defaultVal = legacyCC.Class.getDefault(defaultDef); + if (!Array.isArray(defaultVal) && isChildClassOf(typeCtor, legacyCC.ValueType)) { const typename = getClassName(typeCtor); const info = formatStr('No need to specify the "type" of "%s.%s" because %s is a child class of ValueType.', getClassName(classCtor), mainPropName, typename); diff --git a/cocos/core/data/utils/preprocess-class.ts b/cocos/core/data/utils/preprocess-class.ts index 2dd54db243..8cf353d992 100644 --- a/cocos/core/data/utils/preprocess-class.ts +++ b/cocos/core/data/utils/preprocess-class.ts @@ -28,6 +28,7 @@ import { error, errorID, warn, warnID } from '../../platform/debug'; import * as js from '../../utils/js'; import { PrimitiveType } from './attribute'; import { DEV, EDITOR, TEST } from 'internal:constants'; +import { legacyCC } from '../../global-exports'; // 增加预处理属性这个步骤的目的是降低 CCClass 的实现难度,将比较稳定的通用逻辑和一些需求比较灵活的属性需求分隔开。 @@ -107,10 +108,10 @@ function checkUrl (val, className, propName, url) { if (url == null) { return warnID(5503, className, propName); } - if (typeof url !== 'function' || !js.isChildClassOf(url, cc.RawAsset)) { + if (typeof url !== 'function' || !js.isChildClassOf(url, legacyCC.RawAsset)) { return errorID(5504, className, propName); } - if (url === cc.RawAsset) { + if (url === legacyCC.RawAsset) { warn('Please change the definition of property \'%s\' in class \'%s\'. Starting from v1.10,\n' + 'the use of declaring a property in CCClass as a URL has been deprecated.\n' + 'For example, if property is cc.RawAsset, the previous definition is:\n' + @@ -133,8 +134,8 @@ function checkUrl (val, className, propName, url) { 'sorry for the inconvenience. \uD83D\uDE30 )', propName, className, propName, propName, propName, propName, propName); } - else if (js.isChildClassOf(url, cc.Asset)) { - return errorID(5505, className, propName, cc.js.getClassName(url)); + else if (js.isChildClassOf(url, legacyCC.Asset)) { + return errorID(5505, className, propName, legacyCC.js.getClassName(url)); } if (val.type) { return warnID(5506, className, propName); @@ -149,12 +150,12 @@ function checkUrl (val, className, propName, url) { function parseType (val, type, className, propName) { if (Array.isArray(type)) { if ((EDITOR || TEST) && 'default' in val) { - if (!cc.Class.isArray(val.default)) { + if (!legacyCC.Class.isArray(val.default)) { warnID(5507, className, propName); } } if (type.length > 0) { - if (cc.RawAsset.isRawAssetType(type[0])) { + if (legacyCC.RawAsset.isRawAssetType(type[0])) { val.url = type[0]; delete val.type; return; @@ -167,16 +168,16 @@ function parseType (val, type, className, propName) { } if (EDITOR || TEST) { if (typeof type === 'function') { - if (cc.RawAsset.isRawAssetType(type)) { + if (legacyCC.RawAsset.isRawAssetType(type)) { warnID(5509, className, propName, js.getClassName(type)); } else if (type === String) { - val.type = cc.String; + val.type = legacyCC.String; warnID(3608, `"${className}.${propName}"`); } else if (type === Boolean) { - val.type = cc.Boolean; + val.type = legacyCC.Boolean; warnID(3609, `"${className}.${propName}"`); } else if (type === Number) { - val.type = cc.Float; + val.type = legacyCC.Float; warnID(3610, `"${className}.${propName}"`); } } else { @@ -206,7 +207,7 @@ function parseType (val, type, className, propName) { function postCheckType (val, type, className, propName) { if (EDITOR && typeof type === 'function') { - if (cc.Class._isCCClass(type) && val.serializable !== false && !js._getClassId(type, false)) { + if (legacyCC.Class._isCCClass(type) && val.serializable !== false && !js._getClassId(type, false)) { warnID(5512, className, propName, className, propName); } } @@ -240,9 +241,9 @@ export function getFullFormOfProperty (options, propname_dev?, classname_dev?) { }; } else if (typeof options === 'function') { const type = options; - if (!cc.RawAsset.isRawAssetType(type)) { + if (!legacyCC.RawAsset.isRawAssetType(type)) { return { - default: js.isChildClassOf(type, cc.ValueType) ? new type() : null, + default: js.isChildClassOf(type, legacyCC.ValueType) ? new type() : null, type, _short: true, }; @@ -283,7 +284,7 @@ export function preprocessAttrs (properties, className, cls, es6) { else if (val.set) { errorID(5514, className, propName); } - else if (cc.Class._isCCClass(val.default)) { + else if (legacyCC.Class._isCCClass(val.default)) { val.default = null; errorID(5515, className, propName); } @@ -334,7 +335,7 @@ export function doValidateMethodWithProps_DEV (func, funcName, className, cls, b return false; } if (funcName === 'destroy' && - js.isChildClassOf(base, cc.Component) && + js.isChildClassOf(base, legacyCC.Component) && !CALL_SUPER_DESTROY_REG_DEV.test(func) ) { // tslint:disable-next-line: max-line-length diff --git a/cocos/core/data/utils/requiring-frame.ts b/cocos/core/data/utils/requiring-frame.ts index 0c6b126741..c9937f150d 100644 --- a/cocos/core/data/utils/requiring-frame.ts +++ b/cocos/core/data/utils/requiring-frame.ts @@ -25,6 +25,7 @@ */ import { EDITOR } from 'internal:constants'; +import { legacyCC } from '../../global-exports'; /** * @@ -66,14 +67,14 @@ export function peek () { return requiringFrames[requiringFrames.length - 1]; } -cc._RF = { +legacyCC._RF = { push, pop, peek, }; if (EDITOR) { - cc._RF.reset = () => { + legacyCC._RF.reset = () => { requiringFrames = []; }; } diff --git a/cocos/core/deprecated.ts b/cocos/core/deprecated.ts index 280f67f706..528a7f7ae4 100644 --- a/cocos/core/deprecated.ts +++ b/cocos/core/deprecated.ts @@ -7,6 +7,7 @@ import * as math from './math'; import { Scheduler } from './scheduler'; import { CameraComponent } from './3d'; import { EventTouch } from './platform'; +import { legacyCC } from './global-exports'; // VMATH @@ -163,7 +164,7 @@ replaceProperty(vmath,'vmath',[ }, ]); -cc.vmath = vmath; +legacyCC.vmath = vmath; export { vmath }; diff --git a/cocos/core/director.ts b/cocos/core/director.ts index b789977ae8..0ccdb95c47 100644 --- a/cocos/core/director.ts +++ b/cocos/core/director.ts @@ -46,6 +46,7 @@ import NodeActivator from './scene-graph/node-activator'; import { Scheduler } from './scheduler'; import { js } from './utils'; import { DEBUG, EDITOR, BUILD } from 'internal:constants'; +import { legacyCC } from './global-exports'; // ---------------------------------------------------------------------------------------------------------------------- @@ -301,11 +302,11 @@ export class Director extends EventTarget { this._systems = []; - cc.game.on(Game.EVENT_SHOW, () => { + legacyCC.game.on(Game.EVENT_SHOW, () => { this._lastUpdate = performance.now(); }); - cc.game.once(Game.EVENT_RENDERER_INITED, this._initOnRendererInitialized, this); + legacyCC.game.once(Game.EVENT_RENDERER_INITED, this._initOnRendererInitialized, this); } /** @@ -331,8 +332,8 @@ export class Director extends EventTarget { * @deprecated since v2.0 */ public convertToGL (uiPoint: Vec2) { - const container = cc.game.container; - const view = cc.view; + const container = legacyCC.game.container; + const view = legacyCC.view; const box = container.getBoundingClientRect(); const left = box.left + window.pageXOffset - container.clientLeft; const top = box.top + window.pageYOffset - container.clientTop; @@ -350,8 +351,8 @@ export class Director extends EventTarget { * @deprecated since v2.0 */ public convertToUI (glPoint: Vec2) { - const container = cc.game.container; - const view = cc.view; + const container = legacyCC.game.container; + const view = legacyCC.view; const box = container.getBoundingClientRect(); const left = box.left + window.pageXOffset - container.clientLeft; const top = box.top + window.pageYOffset - container.clientTop; @@ -382,7 +383,7 @@ export class Director extends EventTarget { * @deprecated since v2.0 */ public getWinSize () { - return size(cc.winSize); + return size(legacyCC.winSize); } /** @@ -397,7 +398,7 @@ export class Director extends EventTarget { * @deprecated since v2.0 */ public getWinSizeInPixels () { - return size(cc.winSize); + return size(legacyCC.winSize); } /** @@ -421,7 +422,7 @@ export class Director extends EventTarget { * @deprecated since v2.0 */ public purgeCachedData () { - cc.loader.releaseAll(); + legacyCC.loader.releaseAll(); } /** @@ -445,7 +446,7 @@ export class Director extends EventTarget { // cc.renderer.clear(); if (!EDITOR) { - if (cc.isValid(this._scene)) { + if (legacyCC.isValid(this._scene)) { this._scene!.destroy(); } this._scene = null; @@ -459,7 +460,7 @@ export class Director extends EventTarget { this._root = null; // Clear all caches - cc.loader.releaseAll(); + legacyCC.loader.releaseAll(); } /** @@ -488,11 +489,11 @@ export class Director extends EventTarget { * @param onLaunched - The function invoked at the scene after launch. */ public runSceneImmediate (scene: Scene, onBeforeLoadScene?: Director.OnBeforeLoadScene, onLaunched?: Director.OnSceneLaunched) { - cc.assertID(scene instanceof cc.Scene, 1216); + legacyCC.assertID(scene instanceof legacyCC.Scene, 1216); - const uuid = cc.loader._getReferenceKey(scene.uuid); + const uuid = legacyCC.loader._getReferenceKey(scene.uuid); // Scene cannot be cached in loader, because it will be destroyed after switching. - cc.loader.removeItem(uuid); + legacyCC.loader.removeItem(uuid); if (BUILD && DEBUG) { console.time('InitScene'); @@ -506,13 +507,13 @@ export class Director extends EventTarget { if (BUILD && DEBUG) { console.time('AttachPersist'); } - const persistNodeList = Object.keys(cc.game._persistRootNodes).map((x) => { - return cc.game._persistRootNodes[x]; + const persistNodeList = Object.keys(legacyCC.game._persistRootNodes).map((x) => { + return legacyCC.game._persistRootNodes[x]; }); // tslint:disable-next-line: prefer-for-of for (let i = 0; i < persistNodeList.length; i++) { const node = persistNodeList[i]; - node.emit(cc.Node.SCENE_CHANGED_FOR_PERSISTS, scene.renderScene); + node.emit(legacyCC.Node.SCENE_CHANGED_FOR_PERSISTS, scene.renderScene); const existNode = scene.getChildByUuid(node.uuid); if (existNode) { // scene also contains the persist node, select the old one @@ -544,7 +545,7 @@ export class Director extends EventTarget { if (BUILD && DEBUG) { console.time('Destroy'); } - if (cc.isValid(oldScene)) { + if (legacyCC.isValid(oldScene)) { oldScene!.destroy(); } @@ -557,7 +558,7 @@ export class Director extends EventTarget { if (onBeforeLoadScene) { onBeforeLoadScene(); } - this.emit(cc.Director.EVENT_BEFORE_SCENE_LAUNCH, scene); + this.emit(legacyCC.Director.EVENT_BEFORE_SCENE_LAUNCH, scene); // Run an Entity Scene this._scene = scene; @@ -579,7 +580,7 @@ export class Director extends EventTarget { if (onLaunched) { onLaunched(null, scene); } - this.emit(cc.Director.EVENT_AFTER_SCENE_LAUNCH, scene); + this.emit(legacyCC.Director.EVENT_AFTER_SCENE_LAUNCH, scene); } /** @@ -593,15 +594,15 @@ export class Director extends EventTarget { * @private */ public runScene (scene: Scene, onBeforeLoadScene?: Director.OnBeforeLoadScene, onLaunched?: Director.OnSceneLaunched) { - cc.assertID(scene, 1205); - cc.assertID(scene instanceof cc.Scene, 1216); + legacyCC.assertID(scene, 1205); + legacyCC.assertID(scene instanceof legacyCC.Scene, 1216); // ensure scene initialized // @ts-ignore scene._load(); // Delay run / replace scene to the end of the frame - this.once(cc.Director.EVENT_AFTER_UPDATE, () => { + this.once(legacyCC.Director.EVENT_AFTER_UPDATE, () => { this.runSceneImmediate(scene, onBeforeLoadScene, onLaunched); }); } @@ -609,7 +610,7 @@ export class Director extends EventTarget { // @Scene loading section public _getSceneUuid (key: string | number) { - const scenes = cc.game._sceneInfos; + const scenes = legacyCC.game._sceneInfos; if (typeof key === 'string') { if (!key.endsWith('.scene')) { key += '.scene'; @@ -631,11 +632,11 @@ export class Director extends EventTarget { return scenes[key]; } else { - cc.errorID(1206, key); + legacyCC.errorID(1206, key); } } else { - cc.errorID(1207, key); + legacyCC.errorID(1207, key); } return null; } @@ -650,19 +651,19 @@ export class Director extends EventTarget { */ public loadScene (sceneName: string, onLaunched?: Director.OnSceneLaunched, onUnloaded?: Director.OnUnload) { if (this._loadingScene) { - cc.errorID(1208, sceneName, this._loadingScene); + legacyCC.errorID(1208, sceneName, this._loadingScene); return false; } const info = this._getSceneUuid(sceneName); if (info) { const uuid = info.uuid; - this.emit(cc.Director.EVENT_BEFORE_SCENE_LOADING, sceneName); + this.emit(legacyCC.Director.EVENT_BEFORE_SCENE_LOADING, sceneName); this._loadingScene = sceneName; this._loadSceneByUuid(uuid, onLaunched, onUnloaded); return true; } else { - cc.errorID(1209, sceneName); + legacyCC.errorID(1209, sceneName); return false; } } @@ -714,12 +715,12 @@ export class Director extends EventTarget { const info = this._getSceneUuid(sceneName); if (info) { - this.emit(cc.Director.EVENT_BEFORE_SCENE_LOADING, sceneName); - cc.loader.load({ uuid: info.uuid, type: 'uuid' }, + this.emit(legacyCC.Director.EVENT_BEFORE_SCENE_LOADING, sceneName); + legacyCC.loader.load({ uuid: info.uuid, type: 'uuid' }, onProgress, (error: null | Error, asset: SceneAsset) => { if (error) { - cc.errorID(1210, sceneName, error.message); + legacyCC.errorID(1210, sceneName, error.message); } if (onLoaded) { onLoaded(error, asset); @@ -731,7 +732,7 @@ export class Director extends EventTarget { if (onLoaded) { onLoaded(new Error(error)); } - cc.error('preloadScene: ' + error); + legacyCC.error('preloadScene: ' + error); } } @@ -770,16 +771,16 @@ export class Director extends EventTarget { // cc.AssetLibrary.unloadAsset(uuid); // force reload console.time('LoadScene ' + uuid); - cc.AssetLibrary.loadAsset(uuid, (error, sceneAsset) => { + legacyCC.AssetLibrary.loadAsset(uuid, (error, sceneAsset) => { console.timeEnd('LoadScene ' + uuid); const self = director; self._loadingScene = ''; if (error) { error = 'Failed to load scene: ' + error; - cc.error(error); + legacyCC.error(error); } else { - if (sceneAsset instanceof cc.SceneAsset) { + if (sceneAsset instanceof legacyCC.SceneAsset) { const scene = sceneAsset.scene; scene._id = sceneAsset._uuid; scene._name = sceneAsset._name; @@ -801,7 +802,7 @@ export class Director extends EventTarget { } else { error = 'The asset ' + uuid + ' is not a scene'; - cc.error(error); + legacyCC.error(error); } } if (onLaunched) { @@ -821,7 +822,7 @@ export class Director extends EventTarget { this._lastUpdate = performance.now(); if (!this._lastUpdate) { - cc.logID(1200); + legacyCC.logID(1200); } this._paused = false; @@ -836,10 +837,10 @@ export class Director extends EventTarget { * @deprecated since v2.0 */ public setDepthTest (value: boolean) { - if (!cc.Camera.main) { + if (!legacyCC.Camera.main) { return; } - cc.Camera.main.depth = !!value; + legacyCC.Camera.main.depth = !!value; } /** @@ -852,10 +853,10 @@ export class Director extends EventTarget { * @deprecated since v2.0 */ public setClearColor (clearColor: Color) { - if (!cc.Camera.main) { + if (!legacyCC.Camera.main) { return; } - cc.Camera.main.backgroundColor = clearColor; + legacyCC.Camera.main.backgroundColor = clearColor; } get root () { @@ -891,7 +892,7 @@ export class Director extends EventTarget { * @deprecated since v2.0. */ public getAnimationInterval () { - return 1000 / cc.game.getFrameRate(); + return 1000 / legacyCC.game.getFrameRate(); } /** @@ -903,7 +904,7 @@ export class Director extends EventTarget { * @param value - The animation interval desired. */ public setAnimationInterval (value: number) { - cc.game.setFrameRate(Math.round(1000 / value)); + legacyCC.game.setFrameRate(Math.round(1000 / value)); } /** @@ -991,7 +992,7 @@ export class Director extends EventTarget { * @deprecated */ public getAnimationManager (): any { - return this.getSystem(cc.AnimationManager.ID); + return this.getSystem(legacyCC.AnimationManager.ID); } // Loop management @@ -1081,8 +1082,8 @@ export class Director extends EventTarget { } private _init () { - cc.loader.init(this); - this._root = new Root(cc.game._gfxDevice); + legacyCC.loader.init(this); + this._root = new Root(legacyCC.game._gfxDevice); const rootInfo = {}; if (!this._root.initialize(rootInfo)) { return false; @@ -1109,10 +1110,10 @@ export declare namespace Director { export type OnLoadSceneProgress = (completedCount: number, totalCount: number, item: any) => void; } -cc.Director = Director; +legacyCC.Director = Director; /** * 导演类。 * @property director */ -export const director: Director = Director.instance = cc.director = new Director(); +export const director: Director = Director.instance = legacyCC.director = new Director(); diff --git a/cocos/core/event/callbacks-invoker.ts b/cocos/core/event/callbacks-invoker.ts index d8bab4b836..cd26cef5c4 100644 --- a/cocos/core/event/callbacks-invoker.ts +++ b/cocos/core/event/callbacks-invoker.ts @@ -31,6 +31,7 @@ import { Pool } from '../memop'; import { array, createMap } from '../utils/js'; import { TEST } from 'internal:constants'; +import { legacyCC } from '../global-exports'; const fastRemoveAt = array.fastRemoveAt; function empty (){} @@ -335,5 +336,5 @@ export class CallbacksInvoker { } if (TEST) { - cc._Test.CallbacksInvoker = CallbacksInvoker; + legacyCC._Test.CallbacksInvoker = CallbacksInvoker; } diff --git a/cocos/core/event/event-target.ts b/cocos/core/event/event-target.ts index 2294d63bf5..b125036545 100644 --- a/cocos/core/event/event-target.ts +++ b/cocos/core/event/event-target.ts @@ -30,6 +30,7 @@ import * as js from '../utils/js'; import { CallbacksInvoker } from './callbacks-invoker'; +import { legacyCC } from '../global-exports'; const fastRemove = js.array.fastRemove; @@ -85,7 +86,7 @@ export class EventTarget extends CallbacksInvoker { */ public on (type: string, callback: Function, target?: Object) { if (!callback) { - cc.errorID(6800); + legacyCC.errorID(6800); return; } @@ -174,7 +175,7 @@ export class EventTarget extends CallbacksInvoker { */ public once (type: string, callback: Function, target?: Object) { if (!callback) { - cc.errorID(6800); + legacyCC.errorID(6800); return; } @@ -194,4 +195,4 @@ export class EventTarget extends CallbacksInvoker { } } -cc.EventTarget = EventTarget; +legacyCC.EventTarget = EventTarget; diff --git a/cocos/core/event/event.ts b/cocos/core/event/event.ts index 448d7cfea7..3e4495f5d8 100644 --- a/cocos/core/event/event.ts +++ b/cocos/core/event/event.ts @@ -24,6 +24,8 @@ THE SOFTWARE. */ +import { legacyCC } from '../global-exports'; + /** * 事件相关 * @category event @@ -284,4 +286,4 @@ export default class Event { } /* tslint:disable:no-string-literal */ -cc.Event = Event; +legacyCC.Event = Event; diff --git a/cocos/core/game.ts b/cocos/core/game.ts index a96eba919c..5a4c64a676 100644 --- a/cocos/core/game.ts +++ b/cocos/core/game.ts @@ -38,6 +38,7 @@ import inputManager from './platform/event-manager/input-manager'; import { sys } from './platform/sys'; import { macro } from './platform/macro'; import { ICustomJointTextureLayout } from './renderer'; +import { legacyCC } from './global-exports'; /** * @zh @@ -418,7 +419,7 @@ export class Game extends EventTarget { * @zh 执行一帧游戏循环。 */ public step () { - cc.director.mainLoop(); + legacyCC.director.mainLoop(); } /** @@ -443,7 +444,7 @@ export class Game extends EventTarget { if (--swapbuffers > 1) { window.requestAnimationFrame(cb); } - const root = cc.director.root; + const root = legacyCC.director.root; root.frameMove(0); root.device.present(); }; window.requestAnimationFrame(cb); @@ -476,20 +477,20 @@ export class Game extends EventTarget { * @zh 重新开始游戏 */ public restart () { - cc.director.once(cc.Director.EVENT_AFTER_DRAW, () => { + legacyCC.director.once(legacyCC.Director.EVENT_AFTER_DRAW, () => { // tslint:disable-next-line: forin - for (const id in cc.game._persistRootNodes) { - cc.game.removePersistRootNode(cc.game._persistRootNodes[id]); + for (const id in legacyCC.game._persistRootNodes) { + legacyCC.game.removePersistRootNode(legacyCC.game._persistRootNodes[id]); } // Clear scene - cc.director.getScene().destroy(); - cc.Object._deferredDestroy(); + legacyCC.director.getScene().destroy(); + legacyCC.Object._deferredDestroy(); - cc.director.purgeDirector(); + legacyCC.director.purgeDirector(); - cc.director.reset(); - cc.game.onStart(); + legacyCC.director.reset(); + legacyCC.game.onStart(); }); } @@ -580,11 +581,11 @@ export class Game extends EventTarget { this._initEvents(); } - if (!EDITOR && !PREVIEW && cc.internal.SplashScreenWebgl && this.canvas) { - cc.internal.SplashScreenWebgl.instance.main(this.canvas); + if (!EDITOR && !PREVIEW && legacyCC.internal.SplashScreenWebgl && this.canvas) { + legacyCC.internal.SplashScreenWebgl.instance.main(this.canvas); } - cc.director.root.dataPoolManager.jointTexturePool.registerCustomTextureLayouts(config.customJointTextureLayouts); + legacyCC.director.root.dataPoolManager.jointTexturePool.registerCustomTextureLayouts(config.customJointTextureLayouts); return this._inited; } @@ -612,7 +613,7 @@ export class Game extends EventTarget { inputManager.registerSystemEvent(game.canvas); } - const splashScreen = cc.internal.SplashScreenWebgl && cc.internal.SplashScreenWebgl.instance; + const splashScreen = legacyCC.internal.SplashScreenWebgl && legacyCC.internal.SplashScreenWebgl.instance; const useSplash = (!EDITOR && !PREVIEW && splashScreen); if (useSplash) { splashScreen.setOnFinish(() => { @@ -622,7 +623,7 @@ export class Game extends EventTarget { // Load render pipeline if needed const renderPipeline = this.config.renderPipeline; if (renderPipeline) { - cc.loader.load({ uuid: renderPipeline }, (err, asset) => { + legacyCC.loader.load({ uuid: renderPipeline }, (err, asset) => { // failed load renderPipeline if (err || !(asset instanceof RenderPipeline)) { console.warn(`Failed load renderpipeline: ${renderPipeline}, engine failed to initialize, all process stopped`); @@ -662,18 +663,18 @@ export class Game extends EventTarget { * @param {Node} node - The node to be made persistent */ public addPersistRootNode (node: { uuid: any; parent: any; _persistNode: boolean; }) { - if (!cc.Node.isNode(node) || !node.uuid) { + if (!legacyCC.Node.isNode(node) || !node.uuid) { debug.warnID(3800); return; } const id = node.uuid; if (!this._persistRootNodes[id]) { - const scene = cc.director._scene; - if (cc.isValid(scene)) { + const scene = legacyCC.director._scene; + if (legacyCC.isValid(scene)) { if (!node.parent) { node.parent = scene; } - else if (!(node.parent instanceof cc.Scene)) { + else if (!(node.parent instanceof legacyCC.Scene)) { debug.warnID(3801); return; } @@ -714,11 +715,11 @@ export class Game extends EventTarget { private _initEngine () { this._initDevice(); - cc.director._init(); + legacyCC.director._init(); this.setRenderPipeline(); // Log engine version - console.log('Cocos Creator 3D v' + cc.ENGINE_VERSION); + console.log('Cocos Creator 3D v' + legacyCC.ENGINE_VERSION); this.emit(Game.EVENT_ENGINE_INITED); this._inited = true; } @@ -728,7 +729,7 @@ export class Game extends EventTarget { // @Time ticker section private _setAnimFrame () { this._lastTime = new Date(); - const frameRate = cc.game.config.frameRate; + const frameRate = legacyCC.game.config.frameRate; this._frameTime = 1000 / frameRate; if (JSB) { @@ -762,9 +763,9 @@ export class Game extends EventTarget { } private _stTime (callback) { const currTime = new Date().getTime(); - const timeToCall = Math.max(0, cc.game._frameTime - (currTime - cc.game._lastTime)); + const timeToCall = Math.max(0, legacyCC.game._frameTime - (currTime - legacyCC.game._lastTime)); const id = window.setTimeout(callback, timeToCall); - cc.game._lastTime = currTime + timeToCall; + legacyCC.game._lastTime = currTime + timeToCall; return id; } private _ctTime (id: number | undefined) { @@ -774,7 +775,7 @@ export class Game extends EventTarget { private _runMainLoop () { let callback: FrameRequestCallback; const config = this.config; - const director = cc.director; + const director = legacyCC.director; let skip: boolean = true; const frameRate = config.frameRate; @@ -842,20 +843,20 @@ export class Game extends EventTarget { let supportRender = false; if (userRenderMode === 0) { - if (cc.sys.capabilities.opengl) { + if (legacyCC.sys.capabilities.opengl) { this.renderType = Game.RENDER_TYPE_WEBGL; supportRender = true; } - else if (cc.sys.capabilities.canvas) { + else if (legacyCC.sys.capabilities.canvas) { this.renderType = Game.RENDER_TYPE_CANVAS; supportRender = true; } } - else if (userRenderMode === 1 && cc.sys.capabilities.canvas) { + else if (userRenderMode === 1 && legacyCC.sys.capabilities.canvas) { this.renderType = Game.RENDER_TYPE_CANVAS; supportRender = true; } - else if (userRenderMode === 2 && cc.sys.capabilities.opengl) { + else if (userRenderMode === 2 && legacyCC.sys.capabilities.opengl) { this.renderType = Game.RENDER_TYPE_WEBGL; supportRender = true; } @@ -887,10 +888,10 @@ export class Game extends EventTarget { } // useWebGL2 = false; - if (useWebGL2 && cc.WebGL2GFXDevice) { - this._gfxDevice = new cc.WebGL2GFXDevice(); - } else if (cc.WebGLGFXDevice) { - this._gfxDevice = new cc.WebGLGFXDevice(); + if (useWebGL2 && legacyCC.WebGL2GFXDevice) { + this._gfxDevice = new legacyCC.WebGL2GFXDevice(); + } else if (legacyCC.WebGLGFXDevice) { + this._gfxDevice = new legacyCC.WebGLGFXDevice(); } const opts = { @@ -903,7 +904,7 @@ export class Game extends EventTarget { }; // fallback if WebGL2 is actually unavailable (usually due to driver issues) if (!this._gfxDevice!.initialize(opts) && useWebGL2) { - this._gfxDevice = new cc.WebGLGFXDevice(); + this._gfxDevice = new legacyCC.WebGLGFXDevice(); this._gfxDevice!.initialize(opts); } } @@ -916,7 +917,7 @@ export class Game extends EventTarget { } this.canvas!.oncontextmenu = () => { - if (!cc._isContextMenuEnable) { return false; } + if (!legacyCC._isContextMenuEnable) { return false; } }; } @@ -939,13 +940,13 @@ export class Game extends EventTarget { function onHidden () { if (!hidden) { hidden = true; - cc.game.emit(Game.EVENT_HIDE); + legacyCC.game.emit(Game.EVENT_HIDE); } } function onShown () { if (hidden) { hidden = false; - cc.game.emit(Game.EVENT_SHOW); + legacyCC.game.emit(Game.EVENT_SHOW); } } @@ -990,10 +991,10 @@ export class Game extends EventTarget { } this.on(Game.EVENT_HIDE, () => { - cc.game.pause(); + legacyCC.game.pause(); }); this.on(Game.EVENT_SHOW, () => { - cc.game.resume(); + legacyCC.game.resume(); }); } @@ -1002,7 +1003,7 @@ export class Game extends EventTarget { rppl = new ForwardPipeline(); rppl.initialize(ForwardPipeline.initInfo); } - if (!cc.director.root.setRenderPipeline(rppl)) { + if (!legacyCC.director.root.setRenderPipeline(rppl)) { this.setRenderPipeline(); } @@ -1011,5 +1012,5 @@ export class Game extends EventTarget { } } -cc.Game = Game; -export const game = cc.game = new Game(); +legacyCC.Game = Game; +export const game = legacyCC.game = new Game(); diff --git a/cocos/core/geometry/plane.ts b/cocos/core/geometry/plane.ts index 025d90f99a..4032e098b9 100644 --- a/cocos/core/geometry/plane.ts +++ b/cocos/core/geometry/plane.ts @@ -4,11 +4,12 @@ import { Mat4, Vec3, Vec4 } from '../math'; import enums from './enums'; +import { legacyCC } from '../global-exports'; const v1 = new Vec3(0, 0, 0); const v2 = new Vec3(0, 0, 0); -const temp_mat = cc.mat4(); -const temp_vec4 = cc.v4(); +const temp_mat = legacyCC.mat4(); +const temp_vec4 = legacyCC.v4(); /** * @en diff --git a/cocos/core/gfx/index.ts b/cocos/core/gfx/index.ts index 964c2085d2..8f911261cc 100644 --- a/cocos/core/gfx/index.ts +++ b/cocos/core/gfx/index.ts @@ -16,6 +16,7 @@ import { GFXSampler } from './sampler'; import { GFXShader } from './shader'; import { GFXTexture } from './texture'; import { GFXTextureView } from './texture-view'; +import { legacyCC } from '../global-exports'; export * from './binding-layout'; export * from './buffer'; @@ -35,18 +36,18 @@ export * from './texture-view'; export * from './texture'; export * from './window'; -cc.GFXDevice = GFXDevice; -cc.GFXBuffer = GFXBuffer; -cc.GFXTexture = GFXTexture; -cc.GFXTextureView = GFXTextureView; -cc.GFXSampler = GFXSampler; -cc.GFXShader = GFXShader; -cc.GFXInputAssembler = GFXInputAssembler; -cc.GFXRenderPass = GFXRenderPass; -cc.GFXFramebuffer = GFXFramebuffer; -cc.GFXPipelineLayout = GFXPipelineLayout; -cc.GFXPipelineState = GFXPipelineState; -cc.GFXCommandBuffer = GFXCommandBuffer; -cc.GFXQueue = GFXQueue; +legacyCC.GFXDevice = GFXDevice; +legacyCC.GFXBuffer = GFXBuffer; +legacyCC.GFXTexture = GFXTexture; +legacyCC.GFXTextureView = GFXTextureView; +legacyCC.GFXSampler = GFXSampler; +legacyCC.GFXShader = GFXShader; +legacyCC.GFXInputAssembler = GFXInputAssembler; +legacyCC.GFXRenderPass = GFXRenderPass; +legacyCC.GFXFramebuffer = GFXFramebuffer; +legacyCC.GFXPipelineLayout = GFXPipelineLayout; +legacyCC.GFXPipelineState = GFXPipelineState; +legacyCC.GFXCommandBuffer = GFXCommandBuffer; +legacyCC.GFXQueue = GFXQueue; -Object.assign(cc, GFXDefines); +Object.assign(legacyCC, GFXDefines); diff --git a/cocos/core/global-exports.ts b/cocos/core/global-exports.ts new file mode 100644 index 0000000000..0e1ac1adcd --- /dev/null +++ b/cocos/core/global-exports.ts @@ -0,0 +1,116 @@ +/* + Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + */ + +import { + ALIPAY, + BAIDU, + BUILD, + COCOSPLAY, + DEBUG, + DEV, + EDITOR, + JSB, + MINIGAME, + PHYSICS_AMMO, + PHYSICS_BUILTIN, + PHYSICS_CANNON, + PREVIEW, + RUNTIME_BASED, + SUPPORT_JIT, + TEST, + WECHAT, + XIAOMI, +} from 'internal:constants'; + +/** + * !#en + * The main namespace of Cocos2d-JS, all engine core classes, functions, properties and constants are defined in this namespace. + * !#zh + * Cocos 引擎的主要命名空间,引擎代码中所有的类,函数,属性和常量都在这个命名空间中定义。 + * @deprecated + */ +export const legacyCC: Record = {}; + +// For internal usage +legacyCC.internal = {}; + +// @ts-ignore +const _global = typeof window === 'undefined' ? global : window; + +legacyCC._global = _global; + +if (BUILD) { + // Supports dynamically access from external scripts such as adapters and debugger. + // So macros should still defined in global even if inlined in engine. + _global.CC_BUILD = BUILD; + _global.CC_TEST = TEST; + _global.CC_EDITOR = EDITOR; + _global.CC_PREVIEW = PREVIEW; + _global.CC_DEV = DEV; + _global.CC_DEBUG = DEBUG; + _global.CC_JSB = JSB; + _global.CC_WECHAT = WECHAT; + _global.CC_ALIPAY = ALIPAY; + _global.CC_XIAOMI = XIAOMI; + _global.CC_BAIDU = BAIDU; + _global.CC_COCOSPLAY = COCOSPLAY; + _global.CC_MINIGAME = MINIGAME; + _global.CC_RUNTIME_BASED = RUNTIME_BASED; + _global.CC_SUPPORT_JIT = SUPPORT_JIT; + _global.CC_PHYSICS_BUILTIN = PHYSICS_BUILTIN; + _global.CC_PHYSICS_CANNON = PHYSICS_CANNON; + _global.CC_PHYSICS_AMMO = PHYSICS_AMMO; +} + +if (DEV) { + /** + * contains internal apis for unit tests + * @expose + */ + legacyCC._Test = {}; +} + +/** + * deprecated + */ +// TODO: ALIPAY and runtime will redefine +if (!(RUNTIME_BASED || ALIPAY)) { + Object.defineProperty(_global, 'CC_PHYSICS_BUILT_IN', { + get: () => { + console.warn('CC_PHYSICS_BUILT_IN is deprecated, please using CC_PHYSICS_BUILTIN instead.'); + return _global.CC_PHYSICS_BUILTIN; + }, + }); +} + +/** + * The current version of Cocos2d being used.
+ * Please DO NOT remove this String, it is an important flag for bug tracking.
+ * If you post a bug to forum, please attach this flag. + */ +const engineVersion = '1.1.0'; +_global.CocosEngine = legacyCC.ENGINE_VERSION = engineVersion; + +_global.cc = legacyCC; diff --git a/cocos/core/index.ts b/cocos/core/index.ts index 8762f6b566..a5a3c3b00e 100644 --- a/cocos/core/index.ts +++ b/cocos/core/index.ts @@ -26,12 +26,14 @@ /** * @category core */ +import { legacyCC } from './global-exports'; import * as geometry from './geometry'; import * as math from './math'; import * as memop from './memop'; -cc.math = math; -cc.geometry = geometry; + +legacyCC.math = math; +legacyCC.geometry = geometry; export { math, memop, geometry }; @@ -61,3 +63,5 @@ export * from './utils/profiler/profiler'; import './deprecated'; // import './splash-image'; import './splash-screen-webgl'; + + diff --git a/cocos/core/legacy.ts b/cocos/core/legacy.ts index 57f67da6de..a0472d8868 100644 --- a/cocos/core/legacy.ts +++ b/cocos/core/legacy.ts @@ -4,6 +4,7 @@ import * as debug from './platform/debug'; import { _normalize, basename, changeBasename, changeExtname, dirname, extname, getSeperator, join, mainFileName, stripSep } from './utils/path'; +import { legacyCC } from './global-exports'; // import Pipeline from './load-pipeline/pipeline'; // import Url from './load-pipeline/url'; @@ -12,19 +13,19 @@ import { _normalize, basename, changeBasename, changeExtname, dirname, extname, // cc.AssetLibrary = AssetLibrary; // CCDebug.js -cc.log = debug.log; -cc.warn = debug.warn; -cc.error = debug.error; -cc.assert = debug.assert; -cc._throw = debug._throw; -cc.logID = debug.logID; -cc.warnID = debug.warnID; -cc.errorID = debug.errorID; -cc.assertID = debug.assertID; -cc.debug = debug; +legacyCC.log = debug.log; +legacyCC.warn = debug.warn; +legacyCC.error = debug.error; +legacyCC.assert = debug.assert; +legacyCC._throw = debug._throw; +legacyCC.logID = debug.logID; +legacyCC.warnID = debug.warnID; +legacyCC.errorID = debug.errorID; +legacyCC.assertID = debug.assertID; +legacyCC.debug = debug; // path.js -cc.path = { +legacyCC.path = { join, extname, mainFileName, diff --git a/cocos/core/load-pipeline/CCLoader.ts b/cocos/core/load-pipeline/CCLoader.ts index ac47462b43..0924d2564f 100644 --- a/cocos/core/load-pipeline/CCLoader.ts +++ b/cocos/core/load-pipeline/CCLoader.ts @@ -44,6 +44,7 @@ import { LoadingItems } from './loading-items'; import { Pipeline } from './pipeline'; import ReleasedAssetChecker from './released-asset-checker'; import { DEBUG, EDITOR, DEV } from 'internal:constants'; +import { legacyCC } from '../global-exports'; const assetTables = Object.create(null); assetTables.assets = new AssetTable(); @@ -81,8 +82,8 @@ function getResWithUrl (res) { result = {}; id = res; } - isUuid = result.type ? result.type === 'uuid' : cc.AssetLibrary._uuidInSettings(id); - cc.AssetLibrary._getAssetInfoInRuntime(id, _info); + isUuid = result.type ? result.type === 'uuid' : legacyCC.AssetLibrary._uuidInSettings(id); + legacyCC.AssetLibrary._getAssetInfoInRuntime(id, _info); result.url = !isUuid ? id : _info.url; if (_info.url && result.type === 'uuid' && _info.raw) { result.type = null; @@ -199,7 +200,7 @@ export class CCLoader extends Pipeline { public init (director) { if (DEBUG) { const self = this; - director.on(cc.Director.EVENT_AFTER_UPDATE, () => { + director.on(legacyCC.Director.EVENT_AFTER_UPDATE, () => { self._releasedAssetChecker_DEBUG.checkCouldRelease(self._cache); }); } @@ -291,7 +292,7 @@ export class CCLoader extends Pipeline { */ public load (resources, progressCallback, completeCallback?) { if (DEV && !resources) { - return cc.error('[cc.loader.load] resources must be non-nil.'); + return legacyCC.error('[cc.loader.load] resources must be non-nil.'); } if (completeCallback === undefined) { @@ -317,7 +318,7 @@ export class CCLoader extends Pipeline { const resource = resources[i]; // Backward compatibility if (resource && resource.id) { - cc.warnID(4920, resource.id); + legacyCC.warnID(4920, resource.id); if (!resource.uuid && !resource.url) { resource.url = resource.id; } @@ -582,7 +583,7 @@ export class CCLoader extends Pipeline { // To show users the exact structure in asset panel, we need to return the spriteFrame assets in spriteAtlas const assetResLength = assetRes.length; for (let i = 0; i < assetResLength; ++i) { - if (assetRes[i] instanceof cc.SpriteAtlas) { + if (assetRes[i] instanceof legacyCC.SpriteAtlas) { const spriteFrames = assetRes[i].getSpriteFrames(); // tslint:disable: forin for (const k in spriteFrames) { @@ -808,7 +809,7 @@ export class CCLoader extends Pipeline { if (item) { const removed = this.removeItem(id); asset = item.content; - if (asset instanceof cc.Asset) { + if (asset instanceof legacyCC.Asset) { const nativeUrl = asset.nativeUrl; if (nativeUrl) { this.release(nativeUrl); // uncache loading item of native asset @@ -852,7 +853,7 @@ export class CCLoader extends Pipeline { this.release(uuid); } else { - cc.errorID(4914, url); + legacyCC.errorID(4914, url); } } @@ -935,7 +936,7 @@ export class CCLoader extends Pipeline { this._autoReleaseSetting[key] = !!autoRelease; } else if (DEV) { - cc.warnID(4902); + legacyCC.warnID(4902); } } @@ -983,7 +984,7 @@ export class CCLoader extends Pipeline { } } else if (DEV) { - cc.warnID(4902); + legacyCC.warnID(4902); } } @@ -1030,13 +1031,13 @@ export class CCLoader extends Pipeline { } uuid = assetTable.getUuid(url, type); if (!uuid) { - const extname = cc.path.extname(url); + const extname = legacyCC.path.extname(url); if (extname) { // strip extname url = url.slice(0, - extname.length); uuid = assetTable.getUuid(url, type); if (uuid && !quiet) { - cc.warnID(4901, url, extname); + legacyCC.warnID(4901, url, extname); } } } @@ -1044,7 +1045,7 @@ export class CCLoader extends Pipeline { } if (!uuid && type) { if (isChildClassOf(type, SpriteFrame) || isChildClassOf(type, Texture2D) || isChildClassOf(type, TextureCube)) { - cc.warnID(4934); + legacyCC.warnID(4934); } } return uuid; @@ -1065,10 +1066,10 @@ export class CCLoader extends Pipeline { key = this._getResUuid(assetOrUrlOrUuid, null, null, true) || assetOrUrlOrUuid; } if (!key) { - cc.warnID(4800, assetOrUrlOrUuid); + legacyCC.warnID(4800, assetOrUrlOrUuid); return key; } - cc.AssetLibrary._getAssetInfoInRuntime(key, _info); + legacyCC.AssetLibrary._getAssetInfoInRuntime(key, _info); return this._cache[_info.url!] ? _info.url : key; } @@ -1078,7 +1079,7 @@ export class CCLoader extends Pipeline { */ private _urlNotFound (url, type, completeCallback) { callInNextTick(() => { - url = cc.url.normalize(url); + url = legacyCC.url.normalize(url); const info = `${type ? getClassName(type) : 'Asset'} in "resources/${url}" does not exist.`; if (completeCallback) { completeCallback(new Error(info), []); @@ -1097,7 +1098,7 @@ export class CCLoader extends Pipeline { */ private _parseLoadResArgs (type, onProgress, onComplete) { if (onComplete === undefined) { - const isValidType = isChildClassOf(type, cc.RawAsset); + const isValidType = isChildClassOf(type, legacyCC.RawAsset); if (onProgress) { onComplete = onProgress; if (isValidType) { @@ -1175,10 +1176,10 @@ export class CCLoader extends Pipeline { } } -export const loader = cc.loader = new CCLoader(); +export const loader = legacyCC.loader = new CCLoader(); if (EDITOR) { - cc.loader.refreshUrl = function (uuid, oldUrl, newUrl) { + legacyCC.loader.refreshUrl = function (uuid, oldUrl, newUrl) { let item = this._cache[uuid]; if (item) { item.url = newUrl; diff --git a/cocos/core/load-pipeline/asset-loader.ts b/cocos/core/load-pipeline/asset-loader.ts index 9c96957a65..bdea7e0104 100644 --- a/cocos/core/load-pipeline/asset-loader.ts +++ b/cocos/core/load-pipeline/asset-loader.ts @@ -32,6 +32,7 @@ import * as debug from '../platform/debug'; import { Pipeline, IPipe } from './pipeline'; import { LoadingItems } from './loading-items'; import { EDITOR } from 'internal:constants'; +import { legacyCC } from '../global-exports'; const ID = 'AssetLoader'; let reusedArray:Array = []; @@ -48,7 +49,7 @@ export default class AssetLoader implements IPipe { return item.content || null; } - cc.AssetLibrary.queryAssetInfo(uuid, (error, url, isRawAsset) => { + legacyCC.AssetLibrary.queryAssetInfo(uuid, (error, url, isRawAsset) => { if (error) { callback(error); } diff --git a/cocos/core/load-pipeline/auto-release-utils.ts b/cocos/core/load-pipeline/auto-release-utils.ts index c2e55241be..f87fe927ef 100644 --- a/cocos/core/load-pipeline/auto-release-utils.ts +++ b/cocos/core/load-pipeline/auto-release-utils.ts @@ -29,9 +29,10 @@ import {createMap} from '../utils/js'; import { RawAsset } from '../assets/raw-asset'; +import { legacyCC } from '../global-exports'; function parseDepends (key, parsed) { - let item = cc.loader.getItem(key); + let item = legacyCC.loader.getItem(key); if (item) { let depends = item.dependKeys; if (depends) { @@ -51,7 +52,7 @@ function visitAsset (asset, excludeMap) { if (!asset._uuid) { return; } - let key = cc.loader._getReferenceKey(asset); + let key = legacyCC.loader._getReferenceKey(asset); if ( !excludeMap[key] ) { excludeMap[key] = true; parseDepends(key, excludeMap); @@ -98,7 +99,7 @@ function visitNode (node, excludeMap) { // do auto release export function autoRelease (oldSceneAssets, nextSceneAssets, persistNodes) { - let releaseSettings = cc.loader._autoReleaseSetting; + let releaseSettings = legacyCC.loader._autoReleaseSetting; let excludeMap = createMap(); // collect next scene assets @@ -118,7 +119,7 @@ export function autoRelease (oldSceneAssets, nextSceneAssets, persistNodes) { for (let i = 0; i < oldSceneAssets.length; i++) { let key = oldSceneAssets[i]; if (releaseSettings[key] !== false && !excludeMap[key]) { - cc.loader.release(key); + legacyCC.loader.release(key); } } } @@ -129,7 +130,7 @@ export function autoRelease (oldSceneAssets, nextSceneAssets, persistNodes) { for (let i = 0; i < keys.length; i++) { let key = keys[i]; if (releaseSettings[key] === true && !excludeMap[key]) { - cc.loader.release(key); + legacyCC.loader.release(key); } } } diff --git a/cocos/core/load-pipeline/binary-downloader.ts b/cocos/core/load-pipeline/binary-downloader.ts index a04bcf3260..18f5fa1b01 100644 --- a/cocos/core/load-pipeline/binary-downloader.ts +++ b/cocos/core/load-pipeline/binary-downloader.ts @@ -27,9 +27,11 @@ * @category loader */ +import { legacyCC } from '../global-exports'; + export default function downloadBinary (item, callback) { var url = item.url; - var xhr = cc.loader.getXMLHttpRequest(), + var xhr = legacyCC.loader.getXMLHttpRequest(), errInfo = 'Load binary data failed: ' + url + ''; xhr.open('GET', url, true); xhr.responseType = "arraybuffer"; diff --git a/cocos/core/load-pipeline/downloader.ts b/cocos/core/load-pipeline/downloader.ts index 9d636fd58f..00de864965 100644 --- a/cocos/core/load-pipeline/downloader.ts +++ b/cocos/core/load-pipeline/downloader.ts @@ -35,6 +35,7 @@ import downloadBinary from './binary-downloader'; import downloadText from './text-downloader'; import {urlAppendTimestamp} from './utils'; import { downloadAudio } from '../../audio/audio-downloader'; +import { legacyCC } from '../global-exports'; function skip () { return null; @@ -239,7 +240,7 @@ export default class Downloader implements IPipe { } _handleLoadQueue () { - while (this._curConcurrent < cc.macro.DOWNLOAD_MAX_CONCURRENT) { + while (this._curConcurrent < legacyCC.macro.DOWNLOAD_MAX_CONCURRENT) { let nextOne = this._loadQueue.shift(); if (!nextOne) { break; @@ -260,7 +261,7 @@ export default class Downloader implements IPipe { let self = this; let downloadFunc = this.extMap[item.type] || this.extMap['default']; let syncRet = undefined; - if (this._curConcurrent < cc.macro.DOWNLOAD_MAX_CONCURRENT) { + if (this._curConcurrent < legacyCC.macro.DOWNLOAD_MAX_CONCURRENT) { this._curConcurrent++; syncRet = downloadFunc.call(this, item, function (err, result) { self._curConcurrent = Math.max(0, self._curConcurrent - 1); diff --git a/cocos/core/load-pipeline/font-loader.ts b/cocos/core/load-pipeline/font-loader.ts index 188ae69023..426c22859d 100644 --- a/cocos/core/load-pipeline/font-loader.ts +++ b/cocos/core/load-pipeline/font-loader.ts @@ -28,6 +28,7 @@ */ import {safeMeasureText} from '../utils/text-utils'; +import { legacyCC } from '../global-exports'; interface IFontLoadHandle { fontFamilyName; @@ -109,7 +110,7 @@ function nativeCheckFontLoaded (start, font, callback) { } callback(null, font); }, function () { - cc.warnID(4933, font); + legacyCC.warnID(4933, font); callback(null, font); }); } @@ -123,7 +124,7 @@ function _checkFontLoaded () { let fontFamily = fontLoadHandle.fontFamilyName; // load timeout if (now - fontLoadHandle.startTime > _timeout) { - cc.warnID(4933, fontFamily); + legacyCC.warnID(4933, fontFamily); fontLoadHandle.callback(null, fontFamily); _loadingFonts.splice(i, 1); continue; diff --git a/cocos/core/load-pipeline/loader.ts b/cocos/core/load-pipeline/loader.ts index fc1aafc30b..6c4aee5de5 100644 --- a/cocos/core/load-pipeline/loader.ts +++ b/cocos/core/load-pipeline/loader.ts @@ -34,6 +34,7 @@ import plistParser from './plist-parser'; import { Pipeline, IPipe } from './pipeline'; import {loadUuid} from './uuid-loader'; import {loadFont} from './font-loader'; +import { legacyCC } from '../global-exports'; function loadNothing () { return null; @@ -54,14 +55,14 @@ function loadJSON (item) { } function loadImage (item) { - let loadByDeserializedAsset = (item._owner instanceof cc.Asset); + let loadByDeserializedAsset = (item._owner instanceof legacyCC.Asset); if (loadByDeserializedAsset) { // already has cc.Asset return null; } let image = item.content; - if (cc.sys.platform !== cc.sys.FB_PLAYABLE_ADS && !(image instanceof Image)) { + if (legacyCC.sys.platform !== legacyCC.sys.FB_PLAYABLE_ADS && !(image instanceof Image)) { return new Error('Image Loader: Input item doesn\'t contain Image content'); } @@ -78,13 +79,13 @@ function loadImage (item) { // If audio is loaded by url directly, than this loader will wrap it into a new cc.AudioClip object. // If audio is loaded by deserialized AudioClip, than this loader will be skipped. function loadAudioAsAsset (item, callback) { - let loadByDeserializedAsset = (item._owner instanceof cc.Asset); + let loadByDeserializedAsset = (item._owner instanceof legacyCC.Asset); if (loadByDeserializedAsset) { // already has cc.Asset return null; } - let audioClip = new cc.AudioClip(); + let audioClip = new legacyCC.AudioClip(); audioClip._setRawAsset(item.rawUrl, false); audioClip._nativeAsset = item.content; return audioClip; diff --git a/cocos/core/load-pipeline/loading-items.ts b/cocos/core/load-pipeline/loading-items.ts index 1c44453502..4d0698463b 100644 --- a/cocos/core/load-pipeline/loading-items.ts +++ b/cocos/core/load-pipeline/loading-items.ts @@ -31,6 +31,7 @@ import {CallbacksInvoker} from '../event/callbacks-invoker'; import {extname} from '../utils/path'; import {createMap, mixin} from '../utils/js'; +import { legacyCC } from '../global-exports'; let _qid = (0|(Math.random()*998)); let _queues = createMap(true); @@ -93,7 +94,7 @@ function createItem (id, queueId) { complete: false, states: {}, deps: null, - isScene: id.uuid && cc.game._sceneInfos.find((info) => info.uuid === id.uuid), + isScene: id.uuid && legacyCC.game._sceneInfos.find((info) => info.uuid === id.uuid), }; if (typeof id === 'object') { @@ -196,7 +197,7 @@ export class LoadingItems extends CallbacksInvoker { /** * @property {Number} ERROR */ - static ItemState = new cc.Enum(ItemState); + static ItemState = new legacyCC.Enum(ItemState); /** * @en This is a callback which will be invoked while an item flow out the pipeline. @@ -781,4 +782,4 @@ export class LoadingItems extends CallbacksInvoker { } } -cc.LoadingItems = LoadingItems; +legacyCC.LoadingItems = LoadingItems; diff --git a/cocos/core/load-pipeline/md5-pipe.ts b/cocos/core/load-pipeline/md5-pipe.ts index 380b509445..dfd2b4f3d4 100644 --- a/cocos/core/load-pipeline/md5-pipe.ts +++ b/cocos/core/load-pipeline/md5-pipe.ts @@ -29,6 +29,7 @@ */ import { Pipeline, IPipe } from './pipeline'; +import { legacyCC } from '../global-exports'; const ID = 'MD5Pipe'; const ExtnameRegex = /(\.[^.\n\\/]*)$/; @@ -79,8 +80,8 @@ export default class MD5Pipe implements IPipe { let hashValue = map[uuid]; if (hashValue) { if (hashPatchInFolder) { - let dirname = cc.path.dirname(url); - let basename = cc.path.basename(url); + let dirname = legacyCC.path.dirname(url); + let basename = legacyCC.path.basename(url); url = `${dirname}.${hashValue}/${basename}`; } else { let matched = false; diff --git a/cocos/core/load-pipeline/pack-downloader.ts b/cocos/core/load-pipeline/pack-downloader.ts index 86f67bed0b..df1d39b58e 100644 --- a/cocos/core/load-pipeline/pack-downloader.ts +++ b/cocos/core/load-pipeline/pack-downloader.ts @@ -35,6 +35,7 @@ import { errorID } from '../platform/debug'; import { js } from '../utils'; import { Texture2D } from '../assets/texture-2d'; import { DEBUG, TEST } from 'internal:constants'; +import { legacyCC } from '../global-exports'; // when more than one package contains the required asset, // choose to load from the package with the largest state value. @@ -85,8 +86,8 @@ export function initPacks (packs) { } export function _loadNewPack (uuid, packUuid, callback) { - var packUrl = cc.AssetLibrary.getLibUrlNoExt(packUuid) + '.json'; - cc.loader.load({ url: packUrl, ignoreMaxConcurrency: true }, function (err, packJson) { + var packUrl = legacyCC.AssetLibrary.getLibUrlNoExt(packUuid) + '.json'; + legacyCC.loader.load({ url: packUrl, ignoreMaxConcurrency: true }, function (err, packJson) { if (err) { errorID(4916, uuid); return callback(err); @@ -205,7 +206,7 @@ export function load (item, callback) { } if (TEST) { - cc._Test.PackDownloader = { + legacyCC._Test.PackDownloader = { initPacks, _loadNewPack, _doPreload, diff --git a/cocos/core/load-pipeline/pipeline.ts b/cocos/core/load-pipeline/pipeline.ts index 0e6a118465..8c65ef662d 100644 --- a/cocos/core/load-pipeline/pipeline.ts +++ b/cocos/core/load-pipeline/pipeline.ts @@ -31,6 +31,7 @@ import {createMap} from '../utils/js'; import { LoadingItems, IItem } from './loading-items'; import { EDITOR } from 'internal:constants'; +import { legacyCC } from '../global-exports'; const ItemState = LoadingItems.ItemState; export interface IPipe { @@ -171,12 +172,12 @@ export class Pipeline { insertPipe (pipe, index) { // Must have handle and id, handle for flow, id for state flag if (!pipe.handle || !pipe.id || index > this._pipes.length) { - cc.warnID(4921); + legacyCC.warnID(4921); return; } if (this._pipes.indexOf(pipe) > 0) { - cc.warnID(4922); + legacyCC.warnID(4922); return; } @@ -394,7 +395,7 @@ export class Pipeline { if (EDITOR) { let references = removed.references; if (references) { - let dependListener = cc.AssetLibrary.dependListener; + let dependListener = legacyCC.AssetLibrary.dependListener; if (dependListener) { for (let uuid in references) { dependListener.off(uuid, references[uuid]); @@ -423,4 +424,4 @@ export class Pipeline { } } -cc.Pipeline = Pipeline; +legacyCC.Pipeline = Pipeline; diff --git a/cocos/core/load-pipeline/plist-parser.ts b/cocos/core/load-pipeline/plist-parser.ts index 90e9f36fea..feb1454a6a 100644 --- a/cocos/core/load-pipeline/plist-parser.ts +++ b/cocos/core/load-pipeline/plist-parser.ts @@ -26,6 +26,7 @@ */ import { EDITOR } from 'internal:constants'; +import { legacyCC } from '../global-exports'; /** * @category loader @@ -89,7 +90,7 @@ class PlistParser extends SAXParser { let xmlDoc = this._parseXML(xmlTxt); let plist = xmlDoc.documentElement; if (plist.tagName !== 'plist') { - cc.warnID(5100); + legacyCC.warnID(5100); return {}; } diff --git a/cocos/core/load-pipeline/released-asset-checker.ts b/cocos/core/load-pipeline/released-asset-checker.ts index 87a66a546a..87ddb35fcc 100644 --- a/cocos/core/load-pipeline/released-asset-checker.ts +++ b/cocos/core/load-pipeline/released-asset-checker.ts @@ -29,6 +29,7 @@ */ import {createMap, getClassName, clear} from '../utils/js'; +import { legacyCC } from '../global-exports'; let _tmpInfo:any = null; @@ -37,7 +38,7 @@ function getItemDesc (item) { if (!_tmpInfo) { _tmpInfo = { path: "", type: null }; } - if (cc.loader._assetTables.assets._getInfo_DEBUG(item.uuid, _tmpInfo)) { + if (legacyCC.loader._assetTables.assets._getInfo_DEBUG(item.uuid, _tmpInfo)) { _tmpInfo.path = 'resources/' + _tmpInfo.path; return `"${_tmpInfo.path}" (type: ${getClassName(_tmpInfo.type)}, uuid: ${item.uuid})`; } @@ -53,7 +54,7 @@ function getItemDesc (item) { function doCheckCouldRelease (releasedKey, refOwnerItem, caches) { var loadedAgain = caches[releasedKey]; if (!loadedAgain) { - cc.log(`"${releasedKey}" was released but maybe still referenced by ${getItemDesc(refOwnerItem)}`); + legacyCC.log(`"${releasedKey}" was released but maybe still referenced by ${getItemDesc(refOwnerItem)}`); } } diff --git a/cocos/core/load-pipeline/text-downloader.ts b/cocos/core/load-pipeline/text-downloader.ts index f251b776ba..95d6c554b3 100644 --- a/cocos/core/load-pipeline/text-downloader.ts +++ b/cocos/core/load-pipeline/text-downloader.ts @@ -28,12 +28,13 @@ */ import {urlAppendTimestamp} from './utils'; +import { legacyCC } from '../global-exports'; export default function (item, callback) { let url = item.url; url = urlAppendTimestamp(url); - let xhr = cc.loader.getXMLHttpRequest(), + let xhr = legacyCC.loader.getXMLHttpRequest(), errInfo = 'Load text file failed: ' + url; xhr.open('GET', url, true); if (xhr.overrideMimeType) xhr.overrideMimeType('text/plain; charset=utf-8'); diff --git a/cocos/core/load-pipeline/unpackers.ts b/cocos/core/load-pipeline/unpackers.ts index 9b898953d8..76d56a707c 100644 --- a/cocos/core/load-pipeline/unpackers.ts +++ b/cocos/core/load-pipeline/unpackers.ts @@ -24,6 +24,8 @@ THE SOFTWARE. */ +import { legacyCC } from '../global-exports'; + /** * @category loader */ @@ -37,7 +39,7 @@ export class JsonUnpacker { */ load (indices, packedJson) { if (packedJson.length !== indices.length) { - cc.errorID(4915); + legacyCC.errorID(4915); } for (let i = 0; i < indices.length; i++) { let key = indices[i]; @@ -62,7 +64,7 @@ export class TextureUnpacker { load (indices, packedJson) { let datas = packedJson.data; if (datas.length !== indices.length) { - cc.errorID(4915); + legacyCC.errorID(4915); } for (let i = 0; i < indices.length; i++) { this.contents[indices[i]] = {base: datas[i][0], mipmaps: datas[i][1]}; @@ -73,7 +75,7 @@ export class TextureUnpacker { let content = this.contents[key]; if (content) { return { - __type__: cc.js._getClassId(cc.Texture2D), + __type__: legacyCC.js._getClassId(legacyCC.Texture2D), content: content }; } diff --git a/cocos/core/load-pipeline/url.ts b/cocos/core/load-pipeline/url.ts index 1c4aacab20..aa1402f6fd 100644 --- a/cocos/core/load-pipeline/url.ts +++ b/cocos/core/load-pipeline/url.ts @@ -25,6 +25,7 @@ */ import { EDITOR } from 'internal:constants'; +import { legacyCC } from '../global-exports'; /** * 加载相关模块 @@ -70,20 +71,20 @@ let url = { */ raw: function (url) { if (EDITOR && !this._rawAssets) { - cc.errorID(7000); + legacyCC.errorID(7000); return ''; } url = this.normalize(url); if ( !url.startsWith('resources/') ) { - cc.errorID(EDITOR ? 7001 : 7002, url); + legacyCC.errorID(EDITOR ? 7001 : 7002, url); } else { // Compatible with versions lower than 1.10 - var uuid = cc.loader._getResUuid(url.slice(10), cc.Asset, null, true); + var uuid = legacyCC.loader._getResUuid(url.slice(10), legacyCC.Asset, null, true); if (uuid) { - return cc.AssetLibrary.getLibUrlNoExt(uuid, true) + cc.path.extname(url); + return legacyCC.AssetLibrary.getLibUrlNoExt(uuid, true) + legacyCC.path.extname(url); } } @@ -91,10 +92,10 @@ let url = { }, _init: function (assets) { - this._rawAssets = cc.path.stripSep(assets) + '/'; + this._rawAssets = legacyCC.path.stripSep(assets) + '/'; } } -cc.url = url; +legacyCC.url = url; export default url; diff --git a/cocos/core/load-pipeline/utils.ts b/cocos/core/load-pipeline/utils.ts index 9957fa5370..8d4b2e507c 100644 --- a/cocos/core/load-pipeline/utils.ts +++ b/cocos/core/load-pipeline/utils.ts @@ -23,6 +23,8 @@ THE SOFTWARE. */ +import { legacyCC } from '../global-exports'; + /** * @category loader */ @@ -30,7 +32,7 @@ let _noCacheRex = /\?/; export function urlAppendTimestamp (url) { - if (cc.game.config['noCache'] && typeof url === 'string') { + if (legacyCC.game.config['noCache'] && typeof url === 'string') { if (_noCacheRex.test(url)) //@ts-ignore url += '&_t=' + (new Date() - 0); diff --git a/cocos/core/load-pipeline/uuid-loader.ts b/cocos/core/load-pipeline/uuid-loader.ts index 3d445e644f..ac31a9eeec 100644 --- a/cocos/core/load-pipeline/uuid-loader.ts +++ b/cocos/core/load-pipeline/uuid-loader.ts @@ -34,6 +34,7 @@ import { getError } from '../platform/debug'; import { LoadingItems } from './loading-items'; import { decompressJson } from './utils'; import { EDITOR, DEBUG, JSB } from 'internal:constants'; +import { legacyCC } from '../global-exports'; export function isSceneObj (json) { let SCENE_ID = 'cc.Scene'; @@ -62,7 +63,7 @@ function parseDepends (item, asset, tdInfo, deferredLoadRawAssetsInRuntime) { dependUuid = uuidList[i]; let obj = objList[i]; let prop = propList[i]; - let info = cc.AssetLibrary._getAssetInfoInRuntime(dependUuid); + let info = legacyCC.AssetLibrary._getAssetInfoInRuntime(dependUuid); if (info.raw) { // skip preloading raw assets let url = info.url; @@ -158,7 +159,7 @@ function loadDepends (pipeline, item, asset, depends, callback) { missingAssetReporter.stashByOwner(dependObj, dependProp, EditorExtends.serialize.asAsset(dependSrc)); } else { - cc._throw(item.error); + legacyCC._throw(item.error); } } else { @@ -198,12 +199,12 @@ function canDeferredLoad (asset, item, isScene) { let res = item.deferredLoadRaw; if (res) { // check if asset support deferred - if ((asset instanceof cc.Asset) && asset.constructor.preventDeferredLoadDependents) { + if ((asset instanceof legacyCC.Asset) && asset.constructor.preventDeferredLoadDependents) { res = false; } } else if (isScene) { - if (asset instanceof cc.SceneAsset || asset instanceof cc.Prefab) { + if (asset instanceof legacyCC.SceneAsset || asset instanceof legacyCC.Prefab) { res = asset.asyncLoadAssets; //if (res) { // cc.log('deferred load raw assets for ' + item.id); @@ -255,12 +256,12 @@ export function loadUuid (item, callback) { if (res) { return res; } - return cc._MissingScript.getMissingWrapper(type, data); + return legacyCC._MissingScript.getMissingWrapper(type, data); }; classFinder.onDereferenced = MissingClass.classFinder.onDereferenced; } else { - classFinder = cc._MissingScript.safeFindClass; + classFinder = legacyCC._MissingScript.safeFindClass; } } else { @@ -269,23 +270,23 @@ export function loadUuid (item, callback) { if (cls) { return cls; } - cc.warnID(4903, id); + legacyCC.warnID(4903, id); return Object; }; } - let tdInfo = cc.deserialize.Details.pool.get(); + let tdInfo = legacyCC.deserialize.Details.pool.get(); let asset; try { - asset = cc.deserialize(json, tdInfo, { + asset = legacyCC.deserialize(json, tdInfo, { classFinder: classFinder, target: item.existingAsset, customEnv: item }); } catch (e) { - cc.deserialize.Details.pool.put(tdInfo); + legacyCC.deserialize.Details.pool.put(tdInfo); console.error(e); return new Error(`Failed to load asset ${item.id}, exception occurs during deserialization: ${JSB ? (e + '\n' + e.stack) : e.stack}.`); // return new Error(debug.getError(4925, item.id, err)); @@ -300,7 +301,7 @@ export function loadUuid (item, callback) { let deferredLoad = canDeferredLoad(asset, item, isScene); let depends = parseDepends(item, asset, tdInfo, deferredLoad); - cc.deserialize.Details.pool.put(tdInfo); + legacyCC.deserialize.Details.pool.put(tdInfo); let wrappedCallback = function(err, asset) { if (!err && asset.onLoaded) { @@ -311,15 +312,15 @@ export function loadUuid (item, callback) { } } if (EDITOR && !isScene) { - let dependListener = cc.AssetLibrary.dependListener; - let assetListener = cc.AssetLibrary.assetListener; + let dependListener = legacyCC.AssetLibrary.dependListener; + let assetListener = legacyCC.AssetLibrary.assetListener; // @ts-ignore function propSetter (asset, obj, propName, oldAsset, newAsset) { if (oldAsset === newAsset || obj[propName] === newAsset) { return; } - if (asset instanceof cc.Material && newAsset instanceof cc.Texture2D) { + if (asset instanceof legacyCC.Material && newAsset instanceof legacyCC.Texture2D) { for (let i = 0, l = asset.passes.length; i < l; i++) { if (asset.getProperty(propName, i) === oldAsset) { asset.setProperty(propName, newAsset, i); diff --git a/cocos/core/math/affine-transform.ts b/cocos/core/math/affine-transform.ts index c99bc02d44..21bf75c6d2 100644 --- a/cocos/core/math/affine-transform.ts +++ b/cocos/core/math/affine-transform.ts @@ -33,6 +33,7 @@ import { Mat4 } from './mat4'; import { Rect } from './rect'; import { Size } from './size'; import { Vec2 } from './vec2'; +import { legacyCC } from '../global-exports'; /** * 二维仿射变换矩阵,描述了平移、缩放和缩放。 @@ -228,4 +229,4 @@ export class AffineTransform { } } -cc.AffineTransform = AffineTransform; +legacyCC.AffineTransform = AffineTransform; diff --git a/cocos/core/math/color.ts b/cocos/core/math/color.ts index f339f2e1fc..479e9bf48e 100644 --- a/cocos/core/math/color.ts +++ b/cocos/core/math/color.ts @@ -32,6 +32,7 @@ import CCClass from '../data/class'; import { ValueType } from '../value-types/value-type'; import { IColorLike } from './type-define'; import { clamp, EPSILON } from './utils'; +import { legacyCC } from '../global-exports'; const toFloat = 1 / 255; @@ -629,7 +630,7 @@ export class Color extends ValueType { } CCClass.fastDefine('cc.Color', Color, { r: 0, g: 0, b: 0, a: 255 }); -cc.Color = Color; +legacyCC.Color = Color; export function color (other: Color | string): Color; export function color (r?: number, g?: number, b?: number, a?: number): Color; @@ -638,4 +639,4 @@ export function color (r?: number | Color | string, g?: number, b?: number, a?: return new Color(r as any, g, b, a); } -cc.color = color; +legacyCC.color = color; diff --git a/cocos/core/math/deprecated.ts b/cocos/core/math/deprecated.ts index b1db27e6d9..4192c19bc0 100644 --- a/cocos/core/math/deprecated.ts +++ b/cocos/core/math/deprecated.ts @@ -10,6 +10,7 @@ import { Quat } from './quat'; import { Vec2 } from './vec2'; import { Vec3 } from './vec3'; import { Vec4 } from './vec4'; +import { legacyCC } from '../global-exports'; replaceProperty(Vec2, 'Vec2', [ { @@ -362,7 +363,7 @@ replaceProperty(Color, 'Color', [ newName: 'fromHEX', customFunction: function (...args: any) { let arg1 = args[1].toString(16); - return cc.Color.fromHEX(args[0], arg1); + return legacyCC.Color.fromHEX(args[0], arg1); }, }, ]); diff --git a/cocos/core/math/mat3.ts b/cocos/core/math/mat3.ts index 543df41498..4c201c268a 100644 --- a/cocos/core/math/mat3.ts +++ b/cocos/core/math/mat3.ts @@ -33,6 +33,7 @@ import { Quat } from './quat'; import { IMat3Like, IMat4Like, IQuatLike, IVec2Like, IVec3Like } from './type-define'; import { EPSILON } from './utils'; import { Vec3 } from './vec3'; +import { legacyCC } from '../global-exports'; /** * 表示三维(3x3)矩阵。 @@ -1007,4 +1008,4 @@ CCClass.fastDefine('cc.Mat3', Mat3, { m03: 0, m04: 1, m05: 0, m06: 0, m07: 0, m08: 1, }); -cc.Mat3 = Mat3; +legacyCC.Mat3 = Mat3; diff --git a/cocos/core/math/mat4.ts b/cocos/core/math/mat4.ts index e77dd73d28..8e4a3d2714 100644 --- a/cocos/core/math/mat4.ts +++ b/cocos/core/math/mat4.ts @@ -34,6 +34,7 @@ import { Quat } from './quat'; import { IMat4Like, IVec3Like } from './type-define'; import { EPSILON } from './utils'; import { Vec3 } from './vec3'; +import { legacyCC } from '../global-exports'; /** * 表示四维(4x4)矩阵。 @@ -2032,7 +2033,7 @@ CCClass.fastDefine('cc.Mat4', Mat4, { m08: 0, m09: 0, m10: 1, m11: 0, m12: 0, m13: 0, m14: 0, m15: 1, }); -cc.Mat4 = Mat4; +legacyCC.Mat4 = Mat4; export function mat4 (other: Mat4): Mat4; export function mat4 ( @@ -2049,4 +2050,4 @@ export function mat4 ( return new Mat4(m00 as any, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33); } -cc.mat4 = mat4; +legacyCC.mat4 = mat4; diff --git a/cocos/core/math/quat.ts b/cocos/core/math/quat.ts index e24e2693e9..96e0340f74 100644 --- a/cocos/core/math/quat.ts +++ b/cocos/core/math/quat.ts @@ -33,6 +33,7 @@ import { Mat3 } from './mat3'; import { IQuatLike, IVec3Like } from './type-define'; import { EPSILON, toDegree } from './utils'; import { Vec3 } from './vec3'; +import { legacyCC } from '../global-exports'; /** * 四元数。 @@ -782,7 +783,7 @@ const m3_1 = new Mat3(); const halfToRad = 0.5 * Math.PI / 180.0; CCClass.fastDefine('cc.Quat', Quat, { x: 0, y: 0, z: 0, w: 1 }); -cc.Quat = Quat; +legacyCC.Quat = Quat; export function quat (other: Quat): Quat; export function quat (x?: number, y?: number, z?: number, w?: number): Quat; @@ -791,4 +792,4 @@ export function quat (x: number | Quat = 0, y: number = 0, z: number = 0, w: num return new Quat(x as any, y, z, w); } -cc.quat = quat; +legacyCC.quat = quat; diff --git a/cocos/core/math/rect.ts b/cocos/core/math/rect.ts index 32889386b3..9e99eedb6d 100644 --- a/cocos/core/math/rect.ts +++ b/cocos/core/math/rect.ts @@ -34,6 +34,7 @@ import { Mat4 } from './mat4'; import { Size } from './size'; import { IRectLike, IVec2Like } from './type-define'; import { Vec2 } from './vec2'; +import { legacyCC } from '../global-exports'; /** * 轴对齐矩形。 @@ -189,7 +190,7 @@ export class Rect extends ValueType { * 获取或设置矩形最小点的坐标。 */ get origin () { - return new cc.Vec2(this.x, this.y); + return new legacyCC.Vec2(this.x, this.y); } set origin (value) { @@ -416,7 +417,7 @@ export class Rect extends ValueType { CCClass.fastDefine('cc.Rect', Rect, { x: 0, y: 0, width: 0, height: 0 }); -cc.Rect = Rect; +legacyCC.Rect = Rect; /** * 构造与指定矩形相等的矩形。等价于 `new Rect(rect)`。 @@ -439,4 +440,4 @@ export function rect (x: Rect | number = 0, y: number = 0, width: number = 0, he return new Rect(x as any, y, width, height); } -cc.rect = rect; +legacyCC.rect = rect; diff --git a/cocos/core/math/size.ts b/cocos/core/math/size.ts index c3311c30b9..b018429c45 100644 --- a/cocos/core/math/size.ts +++ b/cocos/core/math/size.ts @@ -31,6 +31,7 @@ import CCClass from '../data/class'; import { ValueType } from '../value-types/value-type'; import { ISizeLike } from './type-define'; +import { legacyCC } from '../global-exports'; /** * 二维尺寸。 @@ -178,6 +179,6 @@ export function size (width: Size | number = 0, height: number = 0) { return new Size(width as any, height); } -cc.size = size; +legacyCC.size = size; -cc.Size = Size; +legacyCC.Size = Size; diff --git a/cocos/core/math/vec2.ts b/cocos/core/math/vec2.ts index a974765fb3..81c97f923e 100644 --- a/cocos/core/math/vec2.ts +++ b/cocos/core/math/vec2.ts @@ -35,6 +35,7 @@ import { IMat3Like, IMat4Like, IVec2Like } from './type-define'; import { clamp } from './utils'; import { EPSILON, random } from './utils'; import { Vec3 } from './vec3'; +import { legacyCC } from '../global-exports'; /** * 二维向量。 @@ -755,7 +756,7 @@ const v2_1 = new Vec2(); const v2_2 = new Vec2(); CCClass.fastDefine('cc.Vec2', Vec2, { x: 0, y: 0 }); -cc.Vec2 = Vec2; +legacyCC.Vec2 = Vec2; export function v2 (other: Vec2): Vec2; export function v2 (x?: number, y?: number): Vec2; @@ -764,4 +765,4 @@ export function v2 (x?: number | Vec2, y?: number) { return new Vec2(x as any, y); } -cc.v2 = v2; +legacyCC.v2 = v2; diff --git a/cocos/core/math/vec3.ts b/cocos/core/math/vec3.ts index b8fce62da7..d02407ac7d 100644 --- a/cocos/core/math/vec3.ts +++ b/cocos/core/math/vec3.ts @@ -33,6 +33,7 @@ import { ValueType } from '../value-types/value-type'; import { Mat4 } from './mat4'; import { IMat3Like, IMat4Like, IQuatLike, IVec3Like } from './type-define'; import { clamp, EPSILON, random } from './utils'; +import { legacyCC } from '../global-exports'; /** * 三维向量。 @@ -978,7 +979,7 @@ const v3_1 = new Vec3(); const v3_2 = new Vec3(); CCClass.fastDefine('cc.Vec3', Vec3, { x: 0, y: 0, z: 0 }); -cc.Vec3 = Vec3; +legacyCC.Vec3 = Vec3; export function v3 (other: Vec3): Vec3; export function v3 (x?: number, y?: number, z?: number): Vec3; @@ -987,4 +988,4 @@ export function v3 (x?: number | Vec3, y?: number, z?: number) { return new Vec3(x as any, y, z); } -cc.v3 = v3; +legacyCC.v3 = v3; diff --git a/cocos/core/math/vec4.ts b/cocos/core/math/vec4.ts index a2480c7658..0ff56bf328 100644 --- a/cocos/core/math/vec4.ts +++ b/cocos/core/math/vec4.ts @@ -33,6 +33,7 @@ import { ValueType } from '../value-types/value-type'; import { Mat4 } from './mat4'; import { IMat4Like, IQuatLike, IVec4Like } from './type-define'; import { clamp, EPSILON, random } from './utils'; +import { legacyCC } from '../global-exports'; /** * 四维向量。 @@ -831,7 +832,7 @@ export class Vec4 extends ValueType { } CCClass.fastDefine('cc.Vec4', Vec4, { x: 0, y: 0, z: 0, w: 0 }); -cc.Vec4 = Vec4; +legacyCC.Vec4 = Vec4; export function v4 (other: Vec4): Vec4; export function v4 (x?: number, y?: number, z?: number, w?: number): Vec4; @@ -840,4 +841,4 @@ export function v4 (x?: number | Vec4, y?: number, z?: number, w?: number) { return new Vec4(x as any, y, z, w); } -cc.v4 = v4; +legacyCC.v4 = v4; diff --git a/cocos/core/pipeline/define.ts b/cocos/core/pipeline/define.ts index 914d75c919..8a99f48b67 100644 --- a/cocos/core/pipeline/define.ts +++ b/cocos/core/pipeline/define.ts @@ -12,6 +12,7 @@ import { Pass } from '../renderer/core/pass'; import { Model } from '../renderer/scene/model'; import { SubModel } from '../renderer/scene/submodel'; import { Layers } from '../scene-graph/layers'; +import { legacyCC } from '../global-exports'; export const PIPELINE_FLOW_FORWARD: string = 'ForwardFlow'; export const PIPELINE_FLOW_SMAA: string = 'SMAAFlow'; @@ -24,7 +25,7 @@ export const PIPELINE_FLOW_TONEMAP: string = 'ToneMapFlow'; export enum RenderPassStage { DEFAULT = 100, } -cc.RenderPassStage = RenderPassStage; +legacyCC.RenderPassStage = RenderPassStage; /** * @zh diff --git a/cocos/core/pipeline/render-flow.ts b/cocos/core/pipeline/render-flow.ts index 443371614f..7003973f16 100644 --- a/cocos/core/pipeline/render-flow.ts +++ b/cocos/core/pipeline/render-flow.ts @@ -9,6 +9,7 @@ import { RenderFlowType } from './pipeline-serialization'; import { RenderPipeline } from './render-pipeline'; import { RenderStage } from './render-stage'; import { RenderView } from './render-view'; +import { legacyCC } from '../global-exports'; /** * @zh @@ -93,7 +94,7 @@ export abstract class RenderFlow { * 材质。 */ @property({ - type: cc.Material, + type: legacyCC.Material, displayOrder: 2, visible: true, }) @@ -210,4 +211,4 @@ export abstract class RenderFlow { } } -cc.RenderFlow = RenderFlow; +legacyCC.RenderFlow = RenderFlow; diff --git a/cocos/core/pipeline/render-pipeline.ts b/cocos/core/pipeline/render-pipeline.ts index 9ba1d77b1f..0bf0793471 100644 --- a/cocos/core/pipeline/render-pipeline.ts +++ b/cocos/core/pipeline/render-pipeline.ts @@ -31,6 +31,7 @@ import { IRenderObject, RenderPassStage, UBOGlobal, UBOShadow, UNIFORM_ENVIRONME import { FrameBufferDesc, RenderFlowType, RenderPassDesc, RenderTextureDesc } from './pipeline-serialization'; import { RenderFlow } from './render-flow'; import { RenderView } from './render-view'; +import { legacyCC } from '../global-exports'; const v3_1 = new Vec3(); @@ -516,7 +517,7 @@ export abstract class RenderPipeline { // update UBOGlobal fv[UBOGlobal.TIME_OFFSET] = this._root.cumulativeTime; fv[UBOGlobal.TIME_OFFSET + 1] = this._root.frameTime; - fv[UBOGlobal.TIME_OFFSET + 2] = cc.director.getTotalFrames(); + fv[UBOGlobal.TIME_OFFSET + 2] = legacyCC.director.getTotalFrames(); fv[UBOGlobal.SCREEN_SIZE_OFFSET] = device.width; fv[UBOGlobal.SCREEN_SIZE_OFFSET + 1] = device.height; @@ -618,7 +619,7 @@ export abstract class RenderPipeline { } const models = scene.models; - const stamp = cc.director.getTotalFrames(); + const stamp = legacyCC.director.getTotalFrames(); for (let i = 0; i < models.length; i++) { const model = models[i]; @@ -1073,4 +1074,4 @@ export abstract class RenderPipeline { } } } -cc.RenderPipeline = RenderPipeline; +legacyCC.RenderPipeline = RenderPipeline; diff --git a/cocos/core/pipeline/render-stage.ts b/cocos/core/pipeline/render-stage.ts index dc163f26f3..c7858ab553 100644 --- a/cocos/core/pipeline/render-stage.ts +++ b/cocos/core/pipeline/render-stage.ts @@ -17,6 +17,7 @@ import { RenderFlow } from './render-flow'; import { RenderPipeline } from './render-pipeline'; import { opaqueCompareFn, RenderQueue, transparentCompareFn } from './render-queue'; import { RenderView } from './render-view'; +import { legacyCC } from '../global-exports'; const _colors: IGFXColor[] = [ { r: 0, g: 0, b: 0, a: 1 } ]; const bufs: GFXCommandBuffer[] = []; @@ -406,4 +407,4 @@ export abstract class RenderStage { } } -cc.RenderStage = RenderStage; +legacyCC.RenderStage = RenderStage; diff --git a/cocos/core/pipeline/render-view.ts b/cocos/core/pipeline/render-view.ts index 7bf9f6cab8..865952c929 100644 --- a/cocos/core/pipeline/render-view.ts +++ b/cocos/core/pipeline/render-view.ts @@ -8,6 +8,7 @@ import { Root } from '../root'; import { CAMERA_DEFAULT_MASK } from './define'; import { RenderFlowType } from './pipeline-serialization'; import { RenderFlow } from './render-flow'; +import { legacyCC } from '../global-exports'; /** * @zh @@ -73,8 +74,8 @@ export class RenderView { public set priority (val: number) { this._priority = val; - if (cc.director.root) { - cc.director.root.sortViews(); + if (legacyCC.director.root) { + legacyCC.director.root.sortViews(); } } @@ -209,10 +210,10 @@ export class RenderView { public setExecuteFlows (flows: string[] | undefined) { this.flows.length = 0; if (flows && flows.length === 1 && flows[0] === 'UIFlow') { - this._flows.push(cc.director.root.pipeline.getFlow('UIFlow')); + this._flows.push(legacyCC.director.root.pipeline.getFlow('UIFlow')); return; } - const pipelineFlows = cc.director.root.pipeline.activeFlows; + const pipelineFlows = legacyCC.director.root.pipeline.activeFlows; for (const f of pipelineFlows) { if (f.type === RenderFlowType.SCENE || (flows && flows.indexOf(f.name) !== -1)) { this.flows.push(f); diff --git a/cocos/core/platform/SubContextView.ts b/cocos/core/platform/SubContextView.ts index 5d2b795b1b..b0fba9b473 100644 --- a/cocos/core/platform/SubContextView.ts +++ b/cocos/core/platform/SubContextView.ts @@ -35,6 +35,7 @@ import { Node } from '../scene-graph'; import { UITransformComponent } from '../components/ui-base/ui-transform-component'; import { SpriteFrame, ImageAsset } from '../assets'; import { Rect } from '../math'; +import { legacyCC } from '../global-exports'; /** * @en SubContextView is a view component which controls open data context viewport in WeChat game platform.
@@ -251,4 +252,4 @@ export class SubContextView extends Component { } } } -cc.SubContextView = SubContextView; +legacyCC.SubContextView = SubContextView; diff --git a/cocos/core/platform/debug.ts b/cocos/core/platform/debug.ts index 17fad0e58a..6396e4edc4 100644 --- a/cocos/core/platform/debug.ts +++ b/cocos/core/platform/debug.ts @@ -30,6 +30,7 @@ import debugInfos from '../../../DebugInfos'; import { EDITOR, JSB, DEV, DEBUG } from 'internal:constants'; +import { legacyCC } from '../global-exports'; const ERROR_MAP_URL = 'https://github.com/cocos-creator/engine/blob/3d/EngineErrorMap.md'; // The html element displays log in web page (DebugMode.INFO_FOR_WEB_PAGE) @@ -48,7 +49,7 @@ let ccAssert = (condition: any, message?: any, ...optionalParams: any[]) => { }; function formatString (message?: any, ...optionalParams: any[]) { - return cc.js.formatStr.apply(null, [message].concat(optionalParams)); + return legacyCC.js.formatStr.apply(null, [message].concat(optionalParams)); } /** @@ -122,7 +123,7 @@ export function _resetDebugSetting (mode: DebugMode) { if (mode > DebugMode.ERROR) { // Log to web page. const logToWebPage = (msg: string) => { - if (!cc.game.canvas) { + if (!legacyCC.game.canvas) { return; } @@ -130,7 +131,7 @@ export function _resetDebugSetting (mode: DebugMode) { const logDiv = document.createElement('Div'); logDiv.setAttribute('id', 'logInfoDiv'); logDiv.setAttribute('width', '200'); - logDiv.setAttribute('height', cc.game.canvas.height); + logDiv.setAttribute('height', legacyCC.game.canvas.height); const logDivStyle = logDiv.style; logDivStyle.zIndex = '99999'; logDivStyle.position = 'absolute'; @@ -149,7 +150,7 @@ export function _resetDebugSetting (mode: DebugMode) { logListStyle.margin = '0px'; logDiv.appendChild(logList); - cc.game.canvas.parentNode.appendChild(logDiv); + legacyCC.game.canvas.parentNode.appendChild(logDiv); } logList.value = logList.value + msg + '\r\n'; @@ -359,7 +360,7 @@ export function getError (errorId: any, ...param: any[]): string { * @zh 是否显示 FPS 信息和部分调试信息。 */ export function isDisplayStats (): boolean { - return cc.profiler ? cc.profiler.isShowingStats() : false; + return legacyCC.profiler ? legacyCC.profiler.isShowingStats() : false; } /** @@ -367,8 +368,8 @@ export function isDisplayStats (): boolean { * @zh 设置是否在左下角显示 FPS 和部分调试。 */ export function setDisplayStats (displayStats: boolean) { - if (cc.profiler) { - displayStats ? cc.profiler.showStats() : cc.profiler.hideStats(); - cc.game.config.showFPS = !!displayStats; + if (legacyCC.profiler) { + displayStats ? legacyCC.profiler.showStats() : legacyCC.profiler.hideStats(); + legacyCC.game.config.showFPS = !!displayStats; } } diff --git a/cocos/core/platform/event-manager/event-enum.ts b/cocos/core/platform/event-manager/event-enum.ts index 5c476d22ef..1add796264 100644 --- a/cocos/core/platform/event-manager/event-enum.ts +++ b/cocos/core/platform/event-manager/event-enum.ts @@ -2,6 +2,7 @@ * @category event */ import { ccenum } from '../../value-types/enum'; +import { legacyCC } from '../../global-exports'; /** * @en The event type supported by SystemEvent and Node events @@ -199,4 +200,4 @@ export enum SystemEventType { ccenum(SystemEventType); -cc.SystemEventType = SystemEventType; +legacyCC.SystemEventType = SystemEventType; diff --git a/cocos/core/platform/event-manager/event-listener.ts b/cocos/core/platform/event-manager/event-listener.ts index fb4c5ec240..ef02b68e82 100644 --- a/cocos/core/platform/event-manager/event-listener.ts +++ b/cocos/core/platform/event-manager/event-listener.ts @@ -30,6 +30,7 @@ import { EventKeyboard, EventAcceleration, EventMouse } from './events'; import { Node } from '../../scene-graph'; +import { legacyCC } from '../../global-exports'; export interface IEventListenerCreateInfo { event?: number; @@ -110,21 +111,21 @@ export class EventListener { * @param argObj a json object */ public static create (argObj: IEventListenerCreateInfo): EventListener { - cc.assertID(argObj && argObj.event, 1900); + legacyCC.assertID(argObj && argObj.event, 1900); const listenerType = argObj.event; delete argObj.event; let listener: EventListener | null = null; - if (listenerType === cc.EventListener.TOUCH_ONE_BY_ONE) { + if (listenerType === legacyCC.EventListener.TOUCH_ONE_BY_ONE) { listener = new TouchOneByOne(); - } else if (listenerType === cc.EventListener.TOUCH_ALL_AT_ONCE) { + } else if (listenerType === legacyCC.EventListener.TOUCH_ALL_AT_ONCE) { listener = new TouchAllAtOnce(); - } else if (listenerType === cc.EventListener.MOUSE) { + } else if (listenerType === legacyCC.EventListener.MOUSE) { listener = new Mouse(); - } else if (listenerType === cc.EventListener.KEYBOARD) { + } else if (listenerType === legacyCC.EventListener.KEYBOARD) { listener = new Keyboard(); - } else if (listenerType === cc.EventListener.ACCELERATION) { + } else if (listenerType === legacyCC.EventListener.ACCELERATION) { listener = new Acceleration(argObj.callback); delete argObj.callback; } @@ -350,7 +351,7 @@ export class Mouse extends EventListener { } public _callback (event: EventMouse) { - const eventType = cc.Event.EventMouse; + const eventType = legacyCC.Event.EventMouse; switch (event.eventType) { case eventType.DOWN: if (this.onMouseDown) { @@ -424,7 +425,7 @@ export class TouchOneByOne extends EventListener { public checkAvailable () { if (!this.onTouchBegan) { - cc.logID(1801); + legacyCC.logID(1801); return false; } return true; @@ -453,7 +454,7 @@ export class TouchAllAtOnce extends EventListener { public checkAvailable () { if (this.onTouchesBegan === null && this.onTouchesMoved === null && this.onTouchesEnded === null && this.onTouchesCancelled === null) { - cc.logID(1802); + legacyCC.logID(1802); return false; } return true; @@ -477,7 +478,7 @@ export class Acceleration extends EventListener { } public checkAvailable () { - cc.assertID(this._onAccelerationEvent, 1803); + legacyCC.assertID(this._onAccelerationEvent, 1803); return true; } @@ -517,11 +518,11 @@ export class Keyboard extends EventListener { public checkAvailable () { if (this.onKeyPressed === null && this.onKeyReleased === null) { - cc.logID(1800); + legacyCC.logID(1800); return false; } return true; } } -cc.EventListener = EventListener; +legacyCC.EventListener = EventListener; diff --git a/cocos/core/platform/event-manager/event-manager.ts b/cocos/core/platform/event-manager/event-manager.ts index 78c2943346..c9a3e947d0 100644 --- a/cocos/core/platform/event-manager/event-manager.ts +++ b/cocos/core/platform/event-manager/event-manager.ts @@ -35,6 +35,7 @@ import { EventTouch } from './events'; import { EventListener, TouchOneByOne } from './event-listener'; import { Node } from '../../scene-graph'; import { macro } from '../macro'; +import { legacyCC } from '../../global-exports'; const ListenerID = EventListener.ListenerID; function checkUINode (node) { @@ -104,7 +105,7 @@ function __getListenerID (event: Event) { // Touch listener is very special, it contains two kinds of listeners: // EventListenerTouchOneByOne and EventListenerTouchAllAtOnce. // return UNKNOWN instead. - cc.logID(2000); + legacyCC.logID(2000); } return ''; } @@ -147,8 +148,8 @@ class EventManager { * @param recursive - 是否往子节点递归暂停。默认为 false。 */ public pauseTarget (node: Node, recursive = false) { - if (!(node instanceof cc._BaseNode)) { - cc.warnID(3506); + if (!(node instanceof legacyCC._BaseNode)) { + legacyCC.warnID(3506); return; } const listeners = this._nodeListenersMap[node.uuid]; @@ -180,8 +181,8 @@ class EventManager { * @param recursive - 是否往子节点递归。默认为 false。 */ public resumeTarget (node: Node, recursive = false) { - if (!(node instanceof cc._BaseNode)) { - cc.warnID(3506); + if (!(node instanceof legacyCC._BaseNode)) { + legacyCC.warnID(3506); return; } const listeners = this._nodeListenersMap[node.uuid]; @@ -259,17 +260,17 @@ class EventManager { * @returns */ public addListener (listener: EventListener, nodeOrPriority: any | number): any { - cc.assertID(listener && nodeOrPriority, 3503); - if (!(cc.js.isNumber(nodeOrPriority) || nodeOrPriority instanceof cc._BaseNode)) { - cc.warnID(3506); + legacyCC.assertID(listener && nodeOrPriority, 3503); + if (!(legacyCC.js.isNumber(nodeOrPriority) || nodeOrPriority instanceof legacyCC._BaseNode)) { + legacyCC.warnID(3506); return; } - if (!(listener instanceof cc.EventListener)) { - cc.assertID(!cc.js.isNumber(nodeOrPriority), 3504); - listener = cc.EventListener.create(listener); + if (!(listener instanceof legacyCC.EventListener)) { + legacyCC.assertID(!legacyCC.js.isNumber(nodeOrPriority), 3504); + listener = legacyCC.EventListener.create(listener); } else { if (listener._isRegistered()) { - cc.logID(3505); + legacyCC.logID(3505); return; } } @@ -278,9 +279,9 @@ class EventManager { return; } - if (cc.js.isNumber(nodeOrPriority)) { + if (legacyCC.js.isNumber(nodeOrPriority)) { if (nodeOrPriority === 0) { - cc.logID(3500); + legacyCC.logID(3500); return; } @@ -291,7 +292,7 @@ class EventManager { this._addListener(listener); } else { if (!checkUINode(nodeOrPriority)) { - cc.logID(3512); + legacyCC.logID(3512); return; } listener._setSceneGraphPriority(nodeOrPriority); @@ -316,7 +317,7 @@ class EventManager { */ public addCustomListener (eventName: string, callback: Function) { const listener = EventListener.create({ - event: cc.EventListener.CUSTOM, + event: legacyCC.EventListener.CUSTOM, eventName, callback, }); @@ -371,7 +372,7 @@ class EventManager { for (let i = locToAddedListeners.length - 1; i >= 0; i--) { const selListener = locToAddedListeners[i]; if (selListener === listener) { - cc.js.array.removeAt(locToAddedListeners, i); + legacyCC.js.array.removeAt(locToAddedListeners, i); selListener._setRegistered(false); break; } @@ -399,8 +400,8 @@ class EventManager { * @param recursive - 递归子节点的同类型监听器一并移除。默认为 false。 */ public removeListeners (listenerType: number | any, recursive = false) { - if (!(cc.js.isNumber(listenerType) || listenerType instanceof cc._BaseNode)) { - cc.warnID(3506); + if (!(legacyCC.js.isNumber(listenerType) || listenerType instanceof legacyCC._BaseNode)) { + legacyCC.warnID(3506); return; } if (listenerType._id !== undefined) { @@ -408,7 +409,7 @@ class EventManager { // Don't want any dangling pointers or the possibility of dealing with deleted objects.. const listeners = this._nodeListenersMap[listenerType._id]; if (listeners) { - const listenersCopy = cc.js.array.copy(listeners); + const listenersCopy = legacyCC.js.array.copy(listeners); for (let i = 0; i < listenersCopy.length; ++i) { const listenerCopy = listenersCopy[i]; this.removeListener(listenerCopy); @@ -442,18 +443,18 @@ class EventManager { } } } else { - if (listenerType === cc.EventListener.TOUCH_ONE_BY_ONE) { + if (listenerType === legacyCC.EventListener.TOUCH_ONE_BY_ONE) { this._removeListenersForListenerID(ListenerID.TOUCH_ONE_BY_ONE); - } else if (listenerType === cc.EventListener.TOUCH_ALL_AT_ONCE) { + } else if (listenerType === legacyCC.EventListener.TOUCH_ALL_AT_ONCE) { this._removeListenersForListenerID(ListenerID.TOUCH_ALL_AT_ONCE); - } else if (listenerType === cc.EventListener.MOUSE) { + } else if (listenerType === legacyCC.EventListener.MOUSE) { this._removeListenersForListenerID(ListenerID.MOUSE); - } else if (listenerType === cc.EventListener.ACCELERATION) { + } else if (listenerType === legacyCC.EventListener.ACCELERATION) { this._removeListenersForListenerID(ListenerID.ACCELERATION); - } else if (listenerType === cc.EventListener.KEYBOARD) { + } else if (listenerType === legacyCC.EventListener.KEYBOARD) { this._removeListenersForListenerID(ListenerID.KEYBOARD); } else { - cc.logID(3501); + legacyCC.logID(3501); } } } @@ -511,7 +512,7 @@ class EventManager { const found = fixedPriorityListeners.indexOf(listener); if (found !== -1) { if (listener._getSceneGraphPriority() != null) { - cc.logID(3502); + legacyCC.logID(3502); } if (listener._getFixedPriority() !== fixedPriority) { listener._setFixedPriority(fixedPriority); @@ -565,10 +566,10 @@ class EventManager { this._updateDirtyFlagForSceneGraph(); this._inDispatch++; if (!event || !event.getType) { - cc.errorID(3511); + legacyCC.errorID(3511); return; } - if (event.getType().startsWith(cc.Event.TOUCH)) { + if (event.getType().startsWith(legacyCC.Event.TOUCH)) { this._dispatchTouchEvent(event as EventTouch); this._inDispatch--; return; @@ -605,7 +606,7 @@ class EventManager { * @param optionalUserData */ public dispatchCustomEvent (eventName, optionalUserData) { - const ev = new cc.Event.EventCustom(eventName); + const ev = new legacyCC.Event.EventCustom(eventName); ev.setUserData(optionalUserData); this.dispatchEvent(ev); } @@ -653,7 +654,7 @@ class EventManager { const node = listener._getSceneGraphPriority(); if (node === null) { - cc.logID(3507); + legacyCC.logID(3507); } this._associateNodeAndEventListener(node, listener); @@ -692,7 +693,7 @@ class EventManager { } if (this._inDispatch === 0) { - cc.js.array.removeAt(listenerVector, i); + legacyCC.js.array.removeAt(listenerVector, i); } } } @@ -720,7 +721,7 @@ class EventManager { for (let i = locToAddedListeners.length - 1; i >= 0; i--) { const listener = locToAddedListeners[i]; if (listener && listener._getListenerID() === listenerID) { - cc.js.array.removeAt(locToAddedListeners, i); + legacyCC.js.array.removeAt(locToAddedListeners, i); } } } @@ -741,7 +742,7 @@ class EventManager { } if (dirtyFlag & DIRTY_SCENE_GRAPH_PRIORITY) { - const rootEntity = cc.director.getScene(); + const rootEntity = legacyCC.director.getScene(); if (rootEntity) { this._sortListenersOfSceneGraphPriority(listenerID); } @@ -837,7 +838,7 @@ class EventManager { for (let i = sceneGraphPriorityListeners.length - 1; i >= 0; i--) { const selListener = sceneGraphPriorityListeners[i]; if (!selListener._isRegistered()) { - cc.js.array.removeAt(sceneGraphPriorityListeners, i); + legacyCC.js.array.removeAt(sceneGraphPriorityListeners, i); // if item in toRemove list, remove it from the list const idx = toRemovedListeners.indexOf(selListener); if (idx !== -1) { @@ -851,7 +852,7 @@ class EventManager { for (let i = fixedPriorityListeners.length - 1; i >= 0; i--) { const selListener = fixedPriorityListeners[i]; if (!selListener._isRegistered()) { - cc.js.array.removeAt(fixedPriorityListeners, i); + legacyCC.js.array.removeAt(fixedPriorityListeners, i); // if item in toRemove list, remove it from the list const idx = toRemovedListeners.indexOf(selListener); if (idx !== -1) { @@ -872,7 +873,7 @@ class EventManager { private _updateTouchListeners (event) { const locInDispatch = this._inDispatch; - cc.assertID(locInDispatch > 0, 3508); + legacyCC.assertID(locInDispatch > 0, 3508); if (locInDispatch > 1) { return; @@ -888,7 +889,7 @@ class EventManager { this._onUpdateListeners(listeners); } - cc.assertID(locInDispatch === 1, 3509); + legacyCC.assertID(locInDispatch === 1, 3509); const locToAddedListeners = this._toAddedListeners; if (locToAddedListeners.length !== 0) { @@ -1020,7 +1021,7 @@ class EventManager { } const originalTouches = event.getTouches(); - const mutableTouches = cc.js.array.copy(originalTouches); + const mutableTouches = legacyCC.js.array.copy(originalTouches); const oneByOneArgsObj = { event, needsMutableSet: (oneByOneListeners && allAtOnceListeners), touches: mutableTouches, selTouch: null }; // @@ -1088,7 +1089,7 @@ class EventManager { private _dissociateNodeAndEventListener (node: Node, listener: EventListener) { const listeners = this._nodeListenersMap[node.uuid]; if (listeners) { - cc.js.array.remove(listeners, listener); + legacyCC.js.array.remove(listeners, listener); if (listeners.length === 0) { delete this._nodeListenersMap[node.uuid]; } @@ -1164,7 +1165,7 @@ class EventManager { } if (this._inDispatch === 0) { - cc.js.array.removeAt(listeners, i); + legacyCC.js.array.removeAt(listeners, i); } else { this._toRemovedListeners.push(selListener); } @@ -1190,7 +1191,7 @@ class EventManager { } if (this._inDispatch === 0) { - cc.js.array.removeAt(listeners, i); + legacyCC.js.array.removeAt(listeners, i); } else { this._toRemovedListeners.push(selListener); } @@ -1222,6 +1223,6 @@ class EventManager { */ export const eventManager = new EventManager(); -cc.eventManager = eventManager; +legacyCC.eventManager = eventManager; export default eventManager; diff --git a/cocos/core/platform/event-manager/events.ts b/cocos/core/platform/event-manager/events.ts index 9b3e1f9284..0254f9e1d3 100644 --- a/cocos/core/platform/event-manager/events.ts +++ b/cocos/core/platform/event-manager/events.ts @@ -31,6 +31,7 @@ import Event from '../../event/event'; import { Vec2 } from '../../math/vec2'; import { Touch } from './touch'; +import { legacyCC } from '../../global-exports'; let _vec2 = new Vec2(); @@ -232,7 +233,7 @@ export class EventMouse extends Event { out = new Vec2(); } - Vec2.set(out, this._x, cc.view._designResolutionSize.height - this._y); + Vec2.set(out, this._x, legacyCC.view._designResolutionSize.height - this._y); return out; } @@ -247,7 +248,7 @@ export class EventMouse extends Event { } Vec2.set(out, this._x, this._y); - cc.view._convertPointWithScale(out); + legacyCC.view._convertPointWithScale(out); return out; } @@ -276,7 +277,7 @@ export class EventMouse extends Event { } Vec2.set(out, this._prevX, this._prevY); - cc.view._convertPointWithScale(out); + legacyCC.view._convertPointWithScale(out); return out; } @@ -320,7 +321,7 @@ export class EventMouse extends Event { out = new Vec2(); } - Vec2.set(out, (this._x - this._prevX) / cc.view.getScaleX(), (this._y - this._prevY) / cc.view.getScaleY()); + Vec2.set(out, (this._x - this._prevX) / legacyCC.view.getScaleX(), (this._y - this._prevY) / legacyCC.view.getScaleY()); return out; } @@ -329,7 +330,7 @@ export class EventMouse extends Event { * @zh 获取鼠标距离上一次事件移动在 UI 坐标系下的 X 轴距离。 */ public getUIDeltaX () { - return (this._x - this._prevX) / cc.view.getScaleX(); + return (this._x - this._prevX) / legacyCC.view.getScaleX(); } /** @@ -337,7 +338,7 @@ export class EventMouse extends Event { * @zh 获取鼠标距离上一次事件移动在 UI 坐标系下的 Y 轴距离。 */ public getUIDeltaY () { - return (this._y - this._prevY) / cc.view.getScaleY(); + return (this._y - this._prevY) / legacyCC.view.getScaleY(); } /** @@ -378,8 +379,8 @@ export class EventMouse extends Event { * @zh 获取鼠标当前 X 轴位置。 */ public getUILocationX () { - const viewport = cc.view.getViewportRect(); - return (this._x - viewport.x) / cc.view.getScaleX(); + const viewport = legacyCC.view.getViewportRect(); + return (this._x - viewport.x) / legacyCC.view.getScaleX(); } /** @@ -387,8 +388,8 @@ export class EventMouse extends Event { * @zh 获取鼠标当前 Y 轴位置。 */ public getUILocationY () { - const viewport = cc.view.getViewportRect(); - return (this._y - viewport.y) / cc.view.getScaleY(); + const viewport = legacyCC.view.getViewportRect(); + return (this._y - viewport.y) / legacyCC.view.getScaleY(); } } diff --git a/cocos/core/platform/event-manager/input-manager.ts b/cocos/core/platform/event-manager/input-manager.ts index 451e9150d0..c835e0d1e5 100644 --- a/cocos/core/platform/event-manager/input-manager.ts +++ b/cocos/core/platform/event-manager/input-manager.ts @@ -36,6 +36,7 @@ import eventManager from './event-manager'; import { EventAcceleration, EventKeyboard, EventMouse, EventTouch } from './events'; import { Touch } from './touch'; import { JSB, RUNTIME_BASED } from 'internal:constants'; +import { legacyCC } from '../../global-exports'; const TOUCH_TIMEOUT = macro.TOUCH_TIMEOUT; @@ -81,7 +82,7 @@ class Acceleration { this.timestamp = timestamp; } } -cc.internal.Acceleration = Acceleration; +legacyCC.internal.Acceleration = Acceleration; /** * This class manages all events of input. include: touch, mouse, accelerometer, keyboard @@ -127,7 +128,7 @@ class InputManager { if (index === undefined) { const unusedIndex = this._getUnUsedIndex(); if (unusedIndex === -1) { - cc.logID(2300, unusedIndex); + legacyCC.logID(2300, unusedIndex); continue; } // curTouch = this._touches[unusedIndex] = touch; @@ -388,7 +389,7 @@ class InputManager { return; } - this._glView = cc.view; + this._glView = legacyCC.view; let prohibition = sys.isMobile; let supportMouse = ('mouse' in sys.capabilities); @@ -415,7 +416,7 @@ class InputManager { } // Register keyboard events. - if (cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB) { + if (legacyCC.sys.browserType !== legacyCC.sys.BROWSER_TYPE_WECHAT_GAME_SUB) { this._registerKeyboardEvent(); } @@ -431,7 +432,7 @@ class InputManager { } this._accelEnabled = isEnable; - const scheduler = cc.director.getScheduler(); + const scheduler = legacyCC.director.getScheduler(); scheduler.enableForTarget(this); if (this._accelEnabled) { this._registerAccelerometerEvent(); @@ -477,7 +478,7 @@ class InputManager { z = ((deviceOrientationEvent.alpha || 0) / 90) * 0.981; } - if (cc.view._isRotated) { + if (legacyCC.view._isRotated) { const tmp = x; x = -y; y = tmp; @@ -500,8 +501,8 @@ class InputManager { mAcceleration.y = -mAcceleration.y; } // fix android acc values are opposite - if (cc.sys.os === cc.sys.OS_ANDROID && - cc.sys.browserType !== cc.sys.BROWSER_TYPE_MOBILE_QQ) { + if (legacyCC.sys.os === legacyCC.sys.OS_ANDROID && + legacyCC.sys.browserType !== legacyCC.sys.BROWSER_TYPE_MOBILE_QQ) { mAcceleration.x = -mAcceleration.x; mAcceleration.y = -mAcceleration.y; } @@ -535,7 +536,7 @@ class InputManager { private _getUnUsedIndex () { let temp = this._indexBitsUsed; - const now = cc.director.getCurrentTime(); + const now = legacyCC.director.getCurrentTime(); for (let i = 0; i < this._maxTouches; i++) { if (!(temp & 0x00000001)) { @@ -586,7 +587,7 @@ class InputManager { private _registerPointerLockEvent () { const lockChangeAlert = () => { - const canvas = cc.game.canvas; + const canvas = legacyCC.game.canvas; // @ts-ignore if (document.pointerLockElement === canvas || document.mozPointerLockElement === canvas){ this._pointLocked = true; @@ -708,7 +709,7 @@ class InputManager { } private _registerTouchEvents (element: HTMLElement) { - if (cc.sys.browserType === cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB) { + if (legacyCC.sys.browserType === legacyCC.sys.BROWSER_TYPE_WECHAT_GAME_SUB) { this._registerWXGameTouchEvents(element); } else { this._registerHTMLTouchEvents(element); @@ -777,7 +778,7 @@ class InputManager { } private _registerKeyboardEvent () { - const canvas = cc.game.canvas as HTMLCanvasElement; + const canvas = legacyCC.game.canvas as HTMLCanvasElement; canvas.addEventListener('keydown', (event: KeyboardEvent) => { eventManager.dispatchEvent(new EventKeyboard(event, true)); event.stopPropagation(); @@ -797,7 +798,7 @@ class InputManager { this._accelDeviceEvent = window.DeviceMotionEvent || window.DeviceOrientationEvent; // TODO fix DeviceMotionEvent bug on QQ Browser version 4.1 and below. - if (cc.sys.browserType === cc.sys.BROWSER_TYPE_MOBILE_QQ) { + if (legacyCC.sys.browserType === legacyCC.sys.BROWSER_TYPE_MOBILE_QQ) { // TODO // @ts-ignore this._accelDeviceEvent = window.DeviceOrientationEvent; @@ -828,4 +829,4 @@ const inputManager = new InputManager(); export default inputManager; -cc.internal.inputManager = inputManager; +legacyCC.internal.inputManager = inputManager; diff --git a/cocos/core/platform/event-manager/system-event.ts b/cocos/core/platform/event-manager/system-event.ts index c36e6a0442..7ac5ecf4bd 100644 --- a/cocos/core/platform/event-manager/system-event.ts +++ b/cocos/core/platform/event-manager/system-event.ts @@ -36,6 +36,7 @@ import eventManager from './event-manager'; import inputManager from './input-manager'; import { Touch } from './touch'; import { EDITOR } from 'internal:constants'; +import { legacyCC } from '../../global-exports'; let keyboardListener: EventListener | null = null; let accelerationListener: EventListener | null = null; @@ -146,7 +147,7 @@ export class SystemEvent extends EventTarget { event: EventListener.ACCELERATION, callback (acc: Object, event: EventAcceleration) { event.type = SystemEventType.DEVICEMOTION; - cc.systemEvent.emit(event.type, event); + legacyCC.systemEvent.emit(event.type, event); }, }); eventManager.addListener(accelerationListener!, 256); @@ -164,20 +165,20 @@ export class SystemEvent extends EventTarget { event: EventListener.TOUCH_ONE_BY_ONE, onTouchBegan (touch: Touch, event: EventTouch) { event.type = SystemEventType.TOUCH_START; - cc.systemEvent.emit(event.type, touch, event); + legacyCC.systemEvent.emit(event.type, touch, event); return true; }, onTouchMoved (touch: Touch, event: EventTouch) { event.type = SystemEventType.TOUCH_MOVE; - cc.systemEvent.emit(event.type, touch, event); + legacyCC.systemEvent.emit(event.type, touch, event); }, onTouchEnded (touch: Touch, event: EventTouch) { event.type = SystemEventType.TOUCH_END; - cc.systemEvent.emit(event.type, touch, event); + legacyCC.systemEvent.emit(event.type, touch, event); }, onTouchCancelled (touch: Touch, event: EventTouch) { event.type = SystemEventType.TOUCH_CANCEL; - cc.systemEvent.emit(event.type, touch, event); + legacyCC.systemEvent.emit(event.type, touch, event); }, }); eventManager.addListener(touchListener, 256); @@ -195,19 +196,19 @@ export class SystemEvent extends EventTarget { event: EventListener.MOUSE, onMouseDown (event: EventMouse) { event.type = SystemEventType.MOUSE_DOWN; - cc.systemEvent.emit(event.type, event); + legacyCC.systemEvent.emit(event.type, event); }, onMouseMove (event:EventMouse) { event.type = SystemEventType.MOUSE_MOVE; - cc.systemEvent.emit(event.type, event); + legacyCC.systemEvent.emit(event.type, event); }, onMouseUp (event: EventMouse) { event.type = SystemEventType.MOUSE_UP; - cc.systemEvent.emit(event.type, event); + legacyCC.systemEvent.emit(event.type, event); }, onMouseScroll (event: EventMouse) { event.type = SystemEventType.MOUSE_WHEEL; - cc.systemEvent.emit(event.type, event); + legacyCC.systemEvent.emit(event.type, event); }, }); eventManager.addListener(mouseListener, 256); @@ -278,7 +279,7 @@ export class SystemEvent extends EventTarget { } } -cc.SystemEvent = SystemEvent; +legacyCC.SystemEvent = SystemEvent; /** * @module cc */ @@ -288,4 +289,4 @@ cc.SystemEvent = SystemEvent; * @zh 系统事件单例,方便全局使用。 */ export const systemEvent = new SystemEvent(); -cc.systemEvent = systemEvent; +legacyCC.systemEvent = systemEvent; diff --git a/cocos/core/platform/event-manager/touch.ts b/cocos/core/platform/event-manager/touch.ts index 32a1cc4d43..756d77db8d 100644 --- a/cocos/core/platform/event-manager/touch.ts +++ b/cocos/core/platform/event-manager/touch.ts @@ -29,6 +29,7 @@ */ import { Vec2 } from '../../math'; +import { legacyCC } from '../../global-exports'; const _vec2 = new Vec2(); /** @@ -97,7 +98,7 @@ export class Touch { } out.set(this._point.x, this._point.y); - cc.view._convertPointWithScale(out); + legacyCC.view._convertPointWithScale(out); return out; } @@ -106,8 +107,8 @@ export class Touch { * @zh 获取当前触点在 UI 坐标系中 X 轴位置。 */ public getUILocationX () { - const viewport = cc.view.getViewportRect(); - return (this._point.x - viewport.x) / cc.view.getScaleX(); + const viewport = legacyCC.view.getViewportRect(); + return (this._point.x - viewport.x) / legacyCC.view.getScaleX(); } /** @@ -115,8 +116,8 @@ export class Touch { * @zh 获取当前触点在 UI 坐标系中 Y 轴位置。 */ public getUILocationY () { - const viewport = cc.view.getViewportRect(); - return (this._point.y - viewport.y) / cc.view.getScaleY(); + const viewport = legacyCC.view.getViewportRect(); + return (this._point.y - viewport.y) / legacyCC.view.getScaleY(); } /** @@ -144,7 +145,7 @@ export class Touch { } out.set(this._prevPoint.x, this._prevPoint.y); - cc.view._convertPointWithScale(out); + legacyCC.view._convertPointWithScale(out); return out; } @@ -173,7 +174,7 @@ export class Touch { } out.set(this._startPoint.x, this._startPoint.y); - cc.view._convertPointWithScale(out); + legacyCC.view._convertPointWithScale(out); return out; } @@ -204,7 +205,7 @@ export class Touch { _vec2.set(this._point); _vec2.subtract(this._prevPoint); - out.set(cc.view.getScaleX(), cc.view.getScaleY()); + out.set(legacyCC.view.getScaleX(), legacyCC.view.getScaleY()); Vec2.divide(out, _vec2, out); return out; } @@ -219,7 +220,7 @@ export class Touch { out = new Vec2(); } - out.set(this._point.x, cc.view._designResolutionSize.height - this._point.y); + out.set(this._point.x, legacyCC.view._designResolutionSize.height - this._point.y); return out; } @@ -233,7 +234,7 @@ export class Touch { out = new Vec2(); } - out.set(this._prevPoint.x, cc.view._designResolutionSize.height - this._prevPoint.y); + out.set(this._prevPoint.x, legacyCC.view._designResolutionSize.height - this._prevPoint.y); return out; } @@ -247,7 +248,7 @@ export class Touch { out = new Vec2(); } - out.set(this._startPoint.x, cc.view._designResolutionSize.height - this._startPoint.y); + out.set(this._startPoint.x, legacyCC.view._designResolutionSize.height - this._startPoint.y); return out; } @@ -300,7 +301,7 @@ export class Touch { this._point.x = x || 0; this._point.y = y || 0; } - this._lastModified = cc.director.getCurrentTime(); + this._lastModified = legacyCC.director.getCurrentTime(); } /** @@ -324,8 +325,8 @@ export class Touch { } else { this._prevPoint = new Vec2(x || 0, y || 0); } - this._lastModified = cc.director.getCurrentTime(); + this._lastModified = legacyCC.director.getCurrentTime(); } } -cc.Touch = Touch; +legacyCC.Touch = Touch; diff --git a/cocos/core/platform/macro.ts b/cocos/core/platform/macro.ts index 52e1de8521..d370799740 100644 --- a/cocos/core/platform/macro.ts +++ b/cocos/core/platform/macro.ts @@ -30,6 +30,7 @@ */ import { Vec2 } from '../math'; +import { legacyCC } from '../global-exports'; const SUPPORT_TEXTURE_FORMATS = ['.pkm', '.pvr', '.webp', '.jpg', '.jpeg', '.bmp', '.png']; @@ -1014,6 +1015,6 @@ const macro = { ENABLE_MULTI_TOUCH: true, }; -cc.macro = macro; +legacyCC.macro = macro; export { macro }; diff --git a/cocos/core/platform/screen.ts b/cocos/core/platform/screen.ts index 0d2462c273..0ef2a31611 100644 --- a/cocos/core/platform/screen.ts +++ b/cocos/core/platform/screen.ts @@ -28,6 +28,8 @@ * @category core */ +import { legacyCC } from '../global-exports'; + /** * @en The screen API provides an easy way for web content to be presented using the user's entire screen. * It's designed for web platforms and some mobile browsers don't provide such behavior, e.g. Safari @@ -159,7 +161,7 @@ const screen = { */ autoFullScreen (element: HTMLElement, onFullScreenChange: (this: Document, ev: any) => any) { element = element || document.body; - const touchTarget = cc.game.canvas || element; + const touchTarget = legacyCC.game.canvas || element; const theScreen = this; // Function bind will be too complicated here because we need the callback function's reference to remove the listener function callback () { @@ -172,6 +174,6 @@ const screen = { }; screen.init(); -cc.screen = screen; +legacyCC.screen = screen; export { screen }; diff --git a/cocos/core/platform/sys.ts b/cocos/core/platform/sys.ts index ad81c45272..8fe486bce1 100644 --- a/cocos/core/platform/sys.ts +++ b/cocos/core/platform/sys.ts @@ -29,6 +29,7 @@ */ import { EDITOR, TEST, WECHAT, ALIPAY, XIAOMI, BAIDU, COCOSPLAY, JSB, MINIGAME } from 'internal:constants'; +import { legacyCC } from '../global-exports'; // tslint:disable @@ -656,8 +657,8 @@ export const sys: { [x: string]: any; } = { str += 'os : ' + this.os + '\r\n'; str += 'osVersion : ' + this.osVersion + '\r\n'; str += 'platform : ' + this.platform + '\r\n'; - str += 'Using ' + (cc.game.renderType === cc.game.RENDER_TYPE_WEBGL ? 'WEBGL' : 'CANVAS') + ' renderer.' + '\r\n'; - cc.log(str); + str += 'Using ' + (legacyCC.game.renderType === legacyCC.game.RENDER_TYPE_WEBGL ? 'WEBGL' : 'CANVAS') + ' renderer.' + '\r\n'; + legacyCC.log(str); }, /** @@ -945,7 +946,7 @@ else { localStorage = null; } catch (e) { const warn = function () { - cc.warnID(5200); + legacyCC.warnID(5200); }; sys.localStorage = { getItem: warn, @@ -1063,11 +1064,11 @@ else { if (DEBUG) { setTimeout(function () { - cc.log('browse type: ' + sys.browserType); - cc.log('browse version: ' + version); - cc.log('MULTI_CHANNEL: ' + __audioSupport.MULTI_CHANNEL); - cc.log('WEB_AUDIO: ' + __audioSupport.WEB_AUDIO); - cc.log('AUTOPLAY: ' + __audioSupport.AUTOPLAY); + legacyCC.log('browse type: ' + sys.browserType); + legacyCC.log('browse version: ' + version); + legacyCC.log('MULTI_CHANNEL: ' + __audioSupport.MULTI_CHANNEL); + legacyCC.log('WEB_AUDIO: ' + __audioSupport.WEB_AUDIO); + legacyCC.log('AUTOPLAY: ' + __audioSupport.AUTOPLAY); }, 0); } })(); @@ -1085,7 +1086,7 @@ else { } } catch (error) { __audioSupport.WEB_AUDIO = false; - cc.logID(5201); + legacyCC.logID(5201); } const formatSupport: string[] = []; @@ -1109,4 +1110,4 @@ else { sys.__audioSupport = __audioSupport; } -cc.sys = sys; +legacyCC.sys = sys; diff --git a/cocos/core/platform/view.ts b/cocos/core/platform/view.ts index 7ee0a5c8f8..77371f091d 100644 --- a/cocos/core/platform/view.ts +++ b/cocos/core/platform/view.ts @@ -35,6 +35,7 @@ import '../game'; import { Rect, Size, Vec2 } from '../math'; import visibleRect from './visible-rect'; import { EDITOR, MINIGAME, WECHAT, JSB } from 'internal:constants'; +import { legacyCC } from '../global-exports'; class BrowserGetter { @@ -44,7 +45,7 @@ class BrowserGetter { width: 'device-width', }; - public adaptationType: any = cc.sys.browserType; + public adaptationType: any = legacyCC.sys.browserType; public init () { if (!MINIGAME) { @@ -53,7 +54,7 @@ class BrowserGetter { } public availWidth (frame) { - if (cc.sys.isMobile || !frame || frame === this.html) { + if (legacyCC.sys.isMobile || !frame || frame === this.html) { return window.innerWidth; } else { @@ -62,7 +63,7 @@ class BrowserGetter { } public availHeight (frame) { - if (cc.sys.isMobile || !frame || frame === this.html) { + if (legacyCC.sys.isMobile || !frame || frame === this.html) { return window.innerHeight; } else { @@ -73,19 +74,19 @@ class BrowserGetter { const __BrowserGetter = new BrowserGetter(); -if (cc.sys.os === cc.sys.OS_IOS) { // All browsers are WebView - __BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_SAFARI; +if (legacyCC.sys.os === legacyCC.sys.OS_IOS) { // All browsers are WebView + __BrowserGetter.adaptationType = legacyCC.sys.BROWSER_TYPE_SAFARI; } if (WECHAT) { - __BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_WECHAT_GAME; + __BrowserGetter.adaptationType = legacyCC.sys.BROWSER_TYPE_WECHAT_GAME; } switch (__BrowserGetter.adaptationType) { - case cc.sys.BROWSER_TYPE_SAFARI: + case legacyCC.sys.BROWSER_TYPE_SAFARI: __BrowserGetter.meta['minimal-ui'] = 'true'; - case cc.sys.BROWSER_TYPE_SOUGOU: - case cc.sys.BROWSER_TYPE_UC: + case legacyCC.sys.BROWSER_TYPE_SOUGOU: + case legacyCC.sys.BROWSER_TYPE_UC: __BrowserGetter.availWidth = (frame) => { return frame.clientWidth; }; @@ -93,7 +94,7 @@ switch (__BrowserGetter.adaptationType) { return frame.clientHeight; }; break; - case cc.sys.BROWSER_TYPE_WECHAT_GAME: + case legacyCC.sys.BROWSER_TYPE_WECHAT_GAME: __BrowserGetter.availWidth = () => { return window.innerWidth; }; @@ -101,7 +102,7 @@ switch (__BrowserGetter.adaptationType) { return window.innerHeight; }; break; - case cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB: + case legacyCC.sys.BROWSER_TYPE_WECHAT_GAME_SUB: const sharedCanvas = window.sharedCanvas || wx.getSharedCanvas(); __BrowserGetter.availWidth = () => { return sharedCanvas.width; @@ -194,7 +195,7 @@ export class View extends EventTarget { this._resizeWithBrowserSize = false; this._orientationChanging = true; this._isRotated = false; - this._orientation = cc.macro.ORIENTATION_AUTO; + this._orientation = legacyCC.macro.ORIENTATION_AUTO; this._isAdjustViewport = true; this._antiAliasEnabled = false; @@ -206,7 +207,7 @@ export class View extends EventTarget { this._rpFixedWidth = new ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.FIXED_WIDTH); this._resolutionPolicy = this._rpShowAll; - cc.game.once(cc.Game.EVENT_ENGINE_INITED, this.init, this); + legacyCC.game.once(legacyCC.Game.EVENT_ENGINE_INITED, this.init, this); } public init () { @@ -215,8 +216,8 @@ export class View extends EventTarget { this._initFrameSize(); this.enableAntiAlias(true); - const w = cc.game.canvas.width; - const h = cc.game.canvas.height; + const w = legacyCC.game.canvas.width; + const h = legacyCC.game.canvas.height; this._designResolutionSize.width = w; this._designResolutionSize.height = h; this._originalDesignResolutionSize.width = w; @@ -226,10 +227,10 @@ export class View extends EventTarget { this._visibleRect.width = w; this._visibleRect.height = h; - cc.winSize.width = this._visibleRect.width; - cc.winSize.height = this._visibleRect.height; - if (cc.visibleRect) { - cc.visibleRect.init(this._visibleRect); + legacyCC.winSize.width = this._visibleRect.width; + legacyCC.winSize.height = this._visibleRect.height; + if (legacyCC.visibleRect) { + legacyCC.visibleRect.init(this._visibleRect); } } @@ -291,7 +292,7 @@ export class View extends EventTarget { * @param orientation - Possible values: macro.ORIENTATION_LANDSCAPE | macro.ORIENTATION_PORTRAIT | macro.ORIENTATION_AUTO */ public setOrientation (orientation: number) { - orientation = orientation & cc.macro.ORIENTATION_AUTO; + orientation = orientation & legacyCC.macro.ORIENTATION_AUTO; if (orientation && this._orientation !== orientation) { this._orientation = orientation; } @@ -348,14 +349,14 @@ export class View extends EventTarget { return; } this._antiAliasEnabled = enabled; - if (cc.game.renderType === cc.Game.RENDER_TYPE_WEBGL) { - const cache = cc.loader._cache; + if (legacyCC.game.renderType === legacyCC.Game.RENDER_TYPE_WEBGL) { + const cache = legacyCC.loader._cache; // tslint:disable-next-line: forin for (const key in cache) { const item = cache[key]; - const tex = item && item.content instanceof cc.Texture2D ? item.content : null; + const tex = item && item.content instanceof legacyCC.Texture2D ? item.content : null; if (tex) { - const Filter = cc.Texture2D.Filter; + const Filter = legacyCC.Texture2D.Filter; if (enabled) { tex.setFilters(Filter.LINEAR, Filter.LINEAR); } @@ -365,8 +366,8 @@ export class View extends EventTarget { } } } - else if (cc.game.renderType === cc.Game.RENDER_TYPE_CANVAS) { - const ctx = cc.game.canvas.getContext('2d'); + else if (legacyCC.game.renderType === legacyCC.Game.RENDER_TYPE_CANVAS) { + const ctx = legacyCC.game.canvas.getContext('2d'); ctx.imageSmoothingEnabled = enabled; ctx.mozImageSmoothingEnabled = enabled; } @@ -391,11 +392,11 @@ export class View extends EventTarget { public enableAutoFullScreen (enabled: boolean) { if (enabled && enabled !== this._autoFullScreen && - cc.sys.isMobile && - cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT) { + legacyCC.sys.isMobile && + legacyCC.sys.browserType !== legacyCC.sys.BROWSER_TYPE_WECHAT) { // Automatically full screen when user touches on mobile version this._autoFullScreen = true; - cc.screen.autoFullScreen(cc.game.frame); + legacyCC.screen.autoFullScreen(legacyCC.game.frame); } else { this._autoFullScreen = false; @@ -423,8 +424,8 @@ export class View extends EventTarget { * @param {Number} height */ public setCanvasSize (width: number, height: number) { - const canvas = cc.game.canvas; - const container = cc.game.container; + const canvas = legacyCC.game.canvas; + const container = legacyCC.game.container; this._devicePixelRatio = window.devicePixelRatio; canvas.width = width * this._devicePixelRatio; @@ -452,7 +453,7 @@ export class View extends EventTarget { * 在 Web 平台下,它返回 canvas 元素尺寸。 */ public getCanvasSize (): Size { - return new Size(cc.game.canvas.width, cc.game.canvas.height); + return new Size(legacyCC.game.canvas.width, legacyCC.game.canvas.height); } /** @@ -479,8 +480,8 @@ export class View extends EventTarget { public setFrameSize (width: number, height: number) { this._frameSize.width = width; this._frameSize.height = height; - cc.frame.style.width = width + 'px'; - cc.frame.style.height = height + 'px'; + legacyCC.frame.style.width = width + 'px'; + legacyCC.frame.style.height = height + 'px'; this._resizeEvent(); } @@ -576,7 +577,7 @@ export class View extends EventTarget { public setDesignResolutionSize (width: number, height: number, resolutionPolicy: ResolutionPolicy|number) { // Defensive code if ( !(width > 0 || height > 0) ){ - cc.logID(2200); + legacyCC.logID(2200); return; } @@ -587,7 +588,7 @@ export class View extends EventTarget { } // Reinit frame size - if (cc.sys.isMobile) { + if (legacyCC.sys.isMobile) { this._adjustViewportMeta(); } @@ -599,7 +600,7 @@ export class View extends EventTarget { } if (!policy) { - cc.logID(2201); + legacyCC.logID(2201); return; } @@ -630,8 +631,8 @@ export class View extends EventTarget { } policy.postApply(this); - cc.winSize.width = this._visibleRect.width; - cc.winSize.height = this._visibleRect.height; + legacyCC.winSize.width = this._visibleRect.width; + legacyCC.winSize.height = this._visibleRect.height; if (visibleRect) { visibleRect.init(this._visibleRect); @@ -726,7 +727,7 @@ export class View extends EventTarget { const x = this._devicePixelRatio * (tx - relatedPos.left); const y = this._devicePixelRatio * (relatedPos.top + relatedPos.height - ty); if (this._isRotated) { - result.x = cc.game.canvas.width - y; + result.x = legacyCC.game.canvas.width - y; result.y = x; } else { @@ -750,14 +751,14 @@ export class View extends EventTarget { // Resize helper functions private _resizeEvent () { - const _view = cc.view; + const _view = legacyCC.view; // Check frame size changed or not const prevFrameW = _view._frameSize.width; const prevFrameH = _view._frameSize.height; const prevRotated = _view._isRotated; - if (cc.sys.isMobile) { - const containerStyle = cc.game.container.style; + if (legacyCC.sys.isMobile) { + const containerStyle = legacyCC.game.container.style; const margin = containerStyle.margin; containerStyle.margin = '0'; containerStyle.display = 'none'; @@ -789,32 +790,32 @@ export class View extends EventTarget { } private _orientationChange () { - cc.view._orientationChanging = true; - cc.view._resizeEvent(); + legacyCC.view._orientationChanging = true; + legacyCC.view._resizeEvent(); } private _initFrameSize () { const locFrameSize = this._frameSize; - const w = __BrowserGetter.availWidth(cc.game.frame); - const h = __BrowserGetter.availHeight(cc.game.frame); + const w = __BrowserGetter.availWidth(legacyCC.game.frame); + const h = __BrowserGetter.availHeight(legacyCC.game.frame); const isLandscape: Boolean = w >= h; - if (EDITOR || !cc.sys.isMobile || - (isLandscape && this._orientation & cc.macro.ORIENTATION_LANDSCAPE) || - (!isLandscape && this._orientation & cc.macro.ORIENTATION_PORTRAIT)) { + if (EDITOR || !legacyCC.sys.isMobile || + (isLandscape && this._orientation & legacyCC.macro.ORIENTATION_LANDSCAPE) || + (!isLandscape && this._orientation & legacyCC.macro.ORIENTATION_PORTRAIT)) { locFrameSize.width = w; locFrameSize.height = h; - cc.game.container.style['-webkit-transform'] = 'rotate(0deg)'; - cc.game.container.style.transform = 'rotate(0deg)'; + legacyCC.game.container.style['-webkit-transform'] = 'rotate(0deg)'; + legacyCC.game.container.style.transform = 'rotate(0deg)'; this._isRotated = false; } else { locFrameSize.width = h; locFrameSize.height = w; - cc.game.container.style['-webkit-transform'] = 'rotate(90deg)'; - cc.game.container.style.transform = 'rotate(90deg)'; - cc.game.container.style['-webkit-transform-origin'] = '0px 0px 0px'; - cc.game.container.style.transformOrigin = '0px 0px 0px'; + legacyCC.game.container.style['-webkit-transform'] = 'rotate(90deg)'; + legacyCC.game.container.style.transform = 'rotate(90deg)'; + legacyCC.game.container.style['-webkit-transform-origin'] = '0px 0px 0px'; + legacyCC.game.container.style.transformOrigin = '0px 0px 0px'; this._isRotated = true; // Fix for issue: https://github.com/cocos-creator/fireball/issues/8365 @@ -823,12 +824,12 @@ export class View extends EventTarget { // Because 'transform' style adds canvas (the top-element of container) to a new stack context. // That causes the DOM Input was hidden under canvas. // This should be done after container rotated, instead of in style-mobile.css. - cc.game.canvas.style['-webkit-transform'] = 'translateZ(0px)'; - cc.game.canvas.style.transform = 'translateZ(0px)'; + legacyCC.game.canvas.style['-webkit-transform'] = 'translateZ(0px)'; + legacyCC.game.canvas.style.transform = 'translateZ(0px)'; } if (this._orientationChanging) { setTimeout(() => { - cc.view._orientationChanging = false; + legacyCC.view._orientationChanging = false; }, 1000); } } @@ -976,11 +977,11 @@ class ContainerStrategy { } protected _setupContainer (_view, w, h) { - const locCanvas = cc.game.canvas; - const locContainer = cc.game.container; + const locCanvas = legacyCC.game.canvas; + const locContainer = legacyCC.game.container; - if (cc.sys.platform !== cc.sys.WECHAT_GAME) { - if (cc.sys.os === cc.sys.OS_ANDROID) { + if (legacyCC.sys.platform !== legacyCC.sys.WECHAT_GAME) { + if (legacyCC.sys.os === legacyCC.sys.OS_ANDROID) { document.body.style.width = (_view._isRotated ? h : w) + 'px'; document.body.style.height = (_view._isRotated ? w : h) + 'px'; } @@ -1000,14 +1001,14 @@ class ContainerStrategy { protected _fixContainer () { // Add container to document body - document.body.insertBefore(cc.game.container, document.body.firstChild); + document.body.insertBefore(legacyCC.game.container, document.body.firstChild); // Set body's width height to window's size, and forbid overflow, so that game will be centered const bs = document.body.style; bs.width = window.innerWidth + 'px'; bs.height = window.innerHeight + 'px'; bs.overflow = 'hidden'; // Body size solution doesn't work on all mobile browser so this is the aleternative: fixed container - const contStyle = cc.game.container.style; + const contStyle = legacyCC.game.container.style; contStyle.position = 'fixed'; contStyle.left = contStyle.top = '0px'; // Reposition body @@ -1093,7 +1094,7 @@ class ContentStrategy { public name = 'EqualToFrame'; public apply (_view) { const frameH = _view._frameSize.height; - const containerStyle = cc.game.container.style; + const containerStyle = legacyCC.game.container.style; this._setupContainer(_view, _view._frameSize.width, _view._frameSize.height); // Setup container's margin and padding if (_view._isRotated) { @@ -1115,7 +1116,7 @@ class ContentStrategy { public apply (_view, designedResolution) { const frameW = _view._frameSize.width; const frameH = _view._frameSize.height; - const containerStyle = cc.game.container.style; + const containerStyle = legacyCC.game.container.style; const designW = designedResolution.width; const designH = designedResolution.height; const scaleX = frameW / designW; @@ -1170,8 +1171,8 @@ class ContentStrategy { class ExactFit extends ContentStrategy { public name = 'ExactFit'; public apply (_view: View, designedResolution: Size) { - const containerW = cc.game.canvas.width; - const containerH = cc.game.canvas.height; + const containerW = legacyCC.game.canvas.width; + const containerH = legacyCC.game.canvas.height; const scaleX = containerW / designedResolution.width; const scaleY = containerH / designedResolution.height; @@ -1182,8 +1183,8 @@ class ContentStrategy { class ShowAll extends ContentStrategy { public name = 'ShowAll'; public apply (_view, designedResolution) { - const containerW = cc.game.canvas.width; - const containerH = cc.game.canvas.height; + const containerW = legacyCC.game.canvas.width; + const containerH = legacyCC.game.canvas.height; const designW = designedResolution.width; const designH = designedResolution.height; const scaleX = containerW / designW; @@ -1202,8 +1203,8 @@ class ContentStrategy { class NoBorder extends ContentStrategy { public name = 'NoBorder'; public apply (_view, designedResolution) { - const containerW = cc.game.canvas.width; - const containerH = cc.game.canvas.height; + const containerW = legacyCC.game.canvas.width; + const containerH = legacyCC.game.canvas.height; const designW = designedResolution.width; const designH = designedResolution.height; const scaleX = containerW / designW; @@ -1222,8 +1223,8 @@ class ContentStrategy { class FixedHeight extends ContentStrategy { public name = 'FixedHeight'; public apply (_view, designedResolution) { - const containerW = cc.game.canvas.width; - const containerH = cc.game.canvas.height; + const containerW = legacyCC.game.canvas.width; + const containerH = legacyCC.game.canvas.height; const designH = designedResolution.height; const scale = containerH / designH; const contentW = containerW; @@ -1236,8 +1237,8 @@ class ContentStrategy { class FixedWidth extends ContentStrategy { public name = 'FixedWidth'; public apply (_view, designedResolution) { - const containerW = cc.game.canvas.width; - const containerH = cc.game.canvas.height; + const containerW = legacyCC.game.canvas.width; + const containerH = legacyCC.game.canvas.height; const designW = designedResolution.width; const scale = containerW / designW; const contentW = containerW; @@ -1319,7 +1320,7 @@ export class ResolutionPolicy { } get canvasSize () { - return cc.v2(cc.game.canvas.width, cc.game.canvas.height); + return legacyCC.v2(legacyCC.game.canvas.width, legacyCC.game.canvas.height); } /** @@ -1378,16 +1379,16 @@ export class ResolutionPolicy { } } } -cc.ResolutionPolicy = ResolutionPolicy; +legacyCC.ResolutionPolicy = ResolutionPolicy; /** * @en view is the singleton view object. * @zh view 是全局的视图单例对象。 */ -export const view = View.instance = cc.view = new View(); +export const view = View.instance = legacyCC.view = new View(); /** * @en winSize is the alias object for the size of the current game window. * @zh winSize 为当前的游戏窗口的大小。 */ -cc.winSize = new Vec2(); +legacyCC.winSize = new Vec2(); diff --git a/cocos/core/platform/visible-rect.ts b/cocos/core/platform/visible-rect.ts index 2314ec881d..e1bed633ea 100644 --- a/cocos/core/platform/visible-rect.ts +++ b/cocos/core/platform/visible-rect.ts @@ -29,6 +29,7 @@ */ import { Rect } from '../math'; +import { legacyCC } from '../global-exports'; /** * cc.visibleRect is a singleton object which defines the actual visible rect of the current view, @@ -38,47 +39,47 @@ const visibleRect = { /** * Top left coordinate of the screen related to the game scene. */ - topLeft: cc.v2(0, 0), + topLeft: legacyCC.v2(0, 0), /** * Top right coordinate of the screen related to the game scene. */ - topRight: cc.v2(0, 0), + topRight: legacyCC.v2(0, 0), /** * Top center coordinate of the screen related to the game scene. */ - top: cc.v2(0, 0), + top: legacyCC.v2(0, 0), /** * Bottom left coordinate of the screen related to the game scene. */ - bottomLeft: cc.v2(0, 0), + bottomLeft: legacyCC.v2(0, 0), /** * Bottom right coordinate of the screen related to the game scene. */ - bottomRight: cc.v2(0, 0), + bottomRight: legacyCC.v2(0, 0), /** * Bottom center coordinate of the screen related to the game scene. */ - bottom: cc.v2(0, 0), + bottom: legacyCC.v2(0, 0), /** * Center coordinate of the screen related to the game scene. */ - center: cc.v2(0, 0), + center: legacyCC.v2(0, 0), /** * Left center coordinate of the screen related to the game scene. */ - left: cc.v2(0, 0), + left: legacyCC.v2(0, 0), /** * Right center coordinate of the screen related to the game scene. */ - right: cc.v2(0, 0), + right: legacyCC.v2(0, 0), /** * Width of the screen. @@ -132,5 +133,5 @@ const visibleRect = { }, }; -cc.visibleRect = visibleRect; +legacyCC.visibleRect = visibleRect; export default visibleRect; diff --git a/cocos/core/primitive/primitive.ts b/cocos/core/primitive/primitive.ts index 235f2eb3ce..65f1f49912 100644 --- a/cocos/core/primitive/primitive.ts +++ b/cocos/core/primitive/primitive.ts @@ -7,6 +7,7 @@ import { Mesh } from '../assets/mesh'; import { ccclass, property } from '../data/class-decorator'; import * as primitives from '../primitive'; import { ccenum } from '../value-types/enum'; +import { legacyCC } from '../global-exports'; enum PrimitiveType { BOX = 0, @@ -62,4 +63,4 @@ export class Primitive extends Mesh { } } -cc.Primitive = Primitive; +legacyCC.Primitive = Primitive; diff --git a/cocos/core/renderer/core/pass.ts b/cocos/core/renderer/core/pass.ts index 3c07752cba..03e26d9271 100644 --- a/cocos/core/renderer/core/pass.ts +++ b/cocos/core/renderer/core/pass.ts @@ -53,6 +53,7 @@ import { customizeType, getBindingFromHandle, getBindingTypeFromHandle, getDefaultFromType, getOffsetFromHandle, getTypeFromHandle, IDefineMap, MaterialProperty, type2reader, type2writer } from './pass-utils'; import { IProgramInfo, programLib } from './program-lib'; import { samplerLib } from './sampler-lib'; +import { legacyCC } from '../../global-exports'; export interface IPassInfoFull extends IPassInfo { // generated part @@ -401,7 +402,7 @@ export class Pass { block.dirty = false; } } - const source = (cc.director.root as Root).pipeline.globalBindings; + const source = (legacyCC.director.root as Root).pipeline.globalBindings; const target = this._shaderInfo.builtins.globals; const samplerLen = target.samplers.length; for (let i = 0; i < samplerLen; i++) { @@ -515,7 +516,7 @@ export class Pass { * @param defineOverrides shader 预处理宏定义重载 */ public tryCompile () { - const pipeline = (cc.director.root as Root).pipeline; + const pipeline = (legacyCC.director.root as Root).pipeline; if (!pipeline) { return null; } this._dynamicBatchingSync(); this._renderPass = pipeline.getRenderPass(this._stage); @@ -550,7 +551,7 @@ export class Pass { bindingLayout.bindTextureView(parseInt(t), this._textureViews[t]); } // bind pipeline builtins - const source = (cc.director.root as Root).pipeline.globalBindings; + const source = (legacyCC.director.root as Root).pipeline.globalBindings; const target = this._shaderInfo.builtins.globals; for (const b of target.blocks) { const info = source.get(b.name); @@ -668,7 +669,7 @@ export class Pass { } } } - const pipeline = (cc.director.root as Root).pipeline; + const pipeline = (legacyCC.director.root as Root).pipeline; if (!pipeline) { return null; } for (let i = 0; i < patches.length; i++) { const patch = patches[i]; diff --git a/cocos/core/renderer/core/program-lib.ts b/cocos/core/renderer/core/program-lib.ts index 41bccfa45d..e9d40f6555 100644 --- a/cocos/core/renderer/core/program-lib.ts +++ b/cocos/core/renderer/core/program-lib.ts @@ -37,6 +37,7 @@ import { GFXShader, GFXUniformBlock } from '../../gfx/shader'; import { IInternalBindingDesc, localBindingsDesc } from '../../pipeline/define'; import { RenderPipeline } from '../../pipeline/render-pipeline'; import { genHandle, IDefineMap } from './pass-utils'; +import { legacyCC } from '../../global-exports'; interface IDefineRecord extends IDefineInfo { _map: (value: any) => number; @@ -347,4 +348,4 @@ class ProgramLib { } export const programLib = new ProgramLib(); -cc.programLib = programLib; +legacyCC.programLib = programLib; diff --git a/cocos/core/renderer/core/sampler-lib.ts b/cocos/core/renderer/core/sampler-lib.ts index 39f0795a51..acd93e17db 100644 --- a/cocos/core/renderer/core/sampler-lib.ts +++ b/cocos/core/renderer/core/sampler-lib.ts @@ -30,6 +30,7 @@ import { GFXAddress, GFXComparisonFunc, GFXFilter } from '../../gfx/define'; import { GFXDevice } from '../../gfx/device'; import { GFXSampler, IGFXSamplerInfo } from '../../gfx/sampler'; +import { legacyCC } from '../../global-exports'; export enum SamplerInfoIndex { minFilter, @@ -123,4 +124,4 @@ class SamplerLib { } export const samplerLib = new SamplerLib(); -cc.samplerLib = samplerLib; +legacyCC.samplerLib = samplerLib; diff --git a/cocos/core/renderer/models/baked-skinning-model.ts b/cocos/core/renderer/models/baked-skinning-model.ts index 1470204b3f..b0c0dcea84 100644 --- a/cocos/core/renderer/models/baked-skinning-model.ts +++ b/cocos/core/renderer/models/baked-skinning-model.ts @@ -43,6 +43,7 @@ import { DataPoolManager } from '../data-pool-manager'; import { Model, ModelType } from '../scene/model'; import { IAnimInfo, IJointTextureHandle, jointTextureSamplerHash } from './skeletal-animation-utils'; import { MorphModel } from './morph-model'; +import { legacyCC } from '../../global-exports'; interface IJointsInfo { buffer: GFXBuffer | null; @@ -77,7 +78,7 @@ export class BakedSkinningModel extends MorphModel { constructor () { super(); this.type = ModelType.BAKED_SKINNING; - this._dataPoolManager = cc.director.root.dataPoolManager; + this._dataPoolManager = legacyCC.director.root.dataPoolManager; const jointTextureInfo = new Float32Array(4); const animInfo = this._dataPoolManager.jointAnimationInfo.getData(); this._jointsMedium = { buffer: null, jointTextureInfo, animInfo, texture: null, boundsInfo: null }; diff --git a/cocos/core/renderer/scene/camera.ts b/cocos/core/renderer/scene/camera.ts index 5b97287179..1d59b94b4d 100644 --- a/cocos/core/renderer/scene/camera.ts +++ b/cocos/core/renderer/scene/camera.ts @@ -6,6 +6,7 @@ import { CAMERA_DEFAULT_MASK } from '../../pipeline/define'; import { RenderView } from '../../pipeline/render-view'; import { Node } from '../../scene-graph'; import { RenderScene } from './render-scene'; +import { legacyCC } from '../../global-exports'; export enum CameraFOVAxis { VERTICAL, @@ -149,7 +150,7 @@ export class Camera { this._proj = info.projection; this._priority = info.priority || 0; - this._view = cc.director.root.createView({ + this._view = legacyCC.director.root.createView({ camera: this, name: this._name, priority: this._priority, @@ -161,7 +162,7 @@ export class Camera { } public destroy () { - cc.director.root.destroyView(this._view); + legacyCC.director.root.destroyView(this._view); this._view = null; this._name = null; } @@ -517,7 +518,7 @@ export class Camera { } public changeTargetWindow (window: GFXWindow | null = null) { - const win = window || cc.director.root.mainWindow; + const win = window || legacyCC.director.root.mainWindow; if (win && this._view) { this._view.window = win; this.resize(win.width, win.height); diff --git a/cocos/core/renderer/scene/deprecated.ts b/cocos/core/renderer/scene/deprecated.ts index 1fbb823d0b..d2f7d93917 100644 --- a/cocos/core/renderer/scene/deprecated.ts +++ b/cocos/core/renderer/scene/deprecated.ts @@ -1,6 +1,7 @@ import { replaceProperty, removeProperty, markAsWarning } from "../../utils"; import { RenderScene } from "./render-scene"; import { Layers } from "../../scene-graph"; +import { legacyCC } from '../../global-exports'; replaceProperty(RenderScene.prototype, 'RenderScene.prototype', [ { @@ -86,7 +87,7 @@ replaceProperty(CameraVisFlags, 'CameraVisFlags', [ }, ]); -cc.CameraVisFlags = CameraVisFlags; +legacyCC.CameraVisFlags = CameraVisFlags; export { CameraVisFlags }; @@ -137,6 +138,6 @@ replaceProperty(VisibilityFlags, 'VisibilityFlags', [ }, ]); -cc.VisibilityFlags = VisibilityFlags; +legacyCC.VisibilityFlags = VisibilityFlags; export { VisibilityFlags }; diff --git a/cocos/core/renderer/scene/model.ts b/cocos/core/renderer/scene/model.ts index 1dcfad1c58..ed10ee9c07 100644 --- a/cocos/core/renderer/scene/model.ts +++ b/cocos/core/renderer/scene/model.ts @@ -14,6 +14,7 @@ import { Layers } from '../../scene-graph/layers'; import { IMacroPatch, Pass } from '../core/pass'; import { RenderScene } from './render-scene'; import { SubModel } from './submodel'; +import { legacyCC } from '../../global-exports'; const m4_1 = new Mat4(); @@ -114,7 +115,7 @@ export class Model { * Setup a default empty model */ constructor () { - this._device = cc.director.root!.device; + this._device = legacyCC.director.root!.device; } public initialize (node: Node) { diff --git a/cocos/core/renderer/scene/render-scene.ts b/cocos/core/renderer/scene/render-scene.ts index 7717f4ae79..4de93042a1 100644 --- a/cocos/core/renderer/scene/render-scene.ts +++ b/cocos/core/renderer/scene/render-scene.ts @@ -16,6 +16,7 @@ import { SphereLight } from './sphere-light'; import { SpotLight } from './spot-light'; import { PREVIEW } from 'internal:constants'; import { Fog } from './fog'; +import { legacyCC } from '../../global-exports'; export interface IRenderSceneInfo { name: string; @@ -409,7 +410,7 @@ export class RenderScene { */ public raycastAllCanvas (worldRay: ray, mask = Layers.Enum.UI_2D, distance = Infinity): boolean { poolUI.reset(); - const canvasComs = cc.director.getScene().getComponentsInChildren(cc.CanvasComponent); + const canvasComs = legacyCC.director.getScene().getComponentsInChildren(legacyCC.CanvasComponent); if (canvasComs != null && canvasComs.length > 0) { for (let i = 0; i < canvasComs.length; i++) { const canvasNode = canvasComs[i].node; diff --git a/cocos/core/renderer/scene/submodel.ts b/cocos/core/renderer/scene/submodel.ts index bf04b01442..b8b7e57beb 100644 --- a/cocos/core/renderer/scene/submodel.ts +++ b/cocos/core/renderer/scene/submodel.ts @@ -7,6 +7,7 @@ import { GFXDevice } from '../../gfx/device'; import { GFXInputAssembler } from '../../gfx/input-assembler'; import { GFXPipelineState } from '../../gfx/pipeline-state'; import { RenderPriority } from '../../pipeline/define'; +import { legacyCC } from '../../global-exports'; export class SubModel { @@ -33,7 +34,7 @@ export class SubModel { if (this._inputAssembler) { this._inputAssembler.initialize(sm); } else { - this._inputAssembler = (cc.director.root.device as GFXDevice).createInputAssembler(sm); + this._inputAssembler = (legacyCC.director.root.device as GFXDevice).createInputAssembler(sm); } } @@ -103,7 +104,7 @@ export class SubModel { } protected recordCommandBuffer (index: number) { - const device = cc.director.root.device as GFXDevice; + const device = legacyCC.director.root.device as GFXDevice; const pso = this._psos![index]; if (this._cmdBuffers[index] == null) { const cmdBufferInfo = { diff --git a/cocos/core/renderer/ui/ui.ts b/cocos/core/renderer/ui/ui.ts index 431c403fe1..bc52c21526 100644 --- a/cocos/core/renderer/ui/ui.ts +++ b/cocos/core/renderer/ui/ui.ts @@ -49,6 +49,7 @@ import { UIBatchModel } from './ui-batch-model'; import { UIDrawBatch } from './ui-draw-batch'; import { UIMaterial } from './ui-material'; import * as UIVertexFormat from './ui-vertex-format'; +import { legacyCC } from '../../global-exports'; /** * @zh @@ -110,7 +111,7 @@ export class UI { name: 'GUIScene', }); this._uiModelPool = new Pool(() => { - const model = cc.director.root.createModel(UIBatchModel); + const model = legacyCC.director.root.createModel(UIBatchModel); model.enabled = true; model.visFlags |= Layers.Enum.UI_3D; return model; @@ -118,7 +119,7 @@ export class UI { this._modelInUse = new CachedArray(10); this._batches = new CachedArray(64); - cc.director.on(cc.Director.EVENT_BEFORE_DRAW, this.update, this); + legacyCC.director.on(legacyCC.Director.EVENT_BEFORE_DRAW, this.update, this); } public initialize () { diff --git a/cocos/core/root.ts b/cocos/core/root.ts index 0d3c6bd80c..e4687eb9b1 100644 --- a/cocos/core/root.ts +++ b/cocos/core/root.ts @@ -16,6 +16,7 @@ import { IRenderSceneInfo, RenderScene } from './renderer/scene/render-scene'; import { SphereLight } from './renderer/scene/sphere-light'; import { SpotLight } from './renderer/scene/spot-light'; import { UI } from './renderer/ui/ui'; +import { legacyCC } from './global-exports'; export let _createSceneFun; export let _createViewFun; @@ -232,9 +233,9 @@ export class Root { builtinResMgr.initBuiltinRes(this._device); - cc.view.on('design-resolution-changed', () => { - const width = cc.game.canvas.width; - const height = cc.game.canvas.height; + legacyCC.view.on('design-resolution-changed', () => { + const width = legacyCC.game.canvas.width; + const height = legacyCC.game.canvas.height; this.resize(width, height); }, this); diff --git a/cocos/core/scene-graph/base-node-dev.ts b/cocos/core/scene-graph/base-node-dev.ts index 49d23ecb5d..0240bd6f4b 100644 --- a/cocos/core/scene-graph/base-node-dev.ts +++ b/cocos/core/scene-graph/base-node-dev.ts @@ -30,6 +30,7 @@ import { CCObject } from '../data/object'; import * as js from '../utils/js'; import { EDITOR, DEV, TEST } from 'internal:constants'; +import { legacyCC } from '../global-exports'; // @ts-ignore const Destroying = CCObject.Flags.Destroying; @@ -40,9 +41,9 @@ export function baseNodePolyfill (BaseNode) { const existing = this.getComponent(ctor._disallowMultiple); if (existing) { if (existing.constructor === ctor) { - cc.errorID(3805, js.getClassName(ctor), this._name); + legacyCC.errorID(3805, js.getClassName(ctor), this._name); } else { - cc.errorID(3806, js.getClassName(ctor), this._name, js.getClassName(existing)); + legacyCC.errorID(3806, js.getClassName(ctor), this._name, js.getClassName(existing)); } return false; } @@ -57,13 +58,13 @@ export function baseNodePolyfill (BaseNode) { */ BaseNode.prototype._addComponentAt = function (comp, index) { if (this._objFlags & Destroying) { - return cc.error('isDestroying'); + return legacyCC.error('isDestroying'); } - if (!(comp instanceof cc.Component)) { - return cc.errorID(3811); + if (!(comp instanceof legacyCC.Component)) { + return legacyCC.errorID(3811); } if (index > this._components.length) { - return cc.errorID(3812); + return legacyCC.errorID(3812); } // recheck attributes because script may changed @@ -90,11 +91,11 @@ export function baseNodePolyfill (BaseNode) { comp.node = this; this._components.splice(index, 0, comp); - if ((EDITOR || TEST) && cc.engine && (this._id in cc.engine.attachedObjsForEditor)) { - cc.engine.attachedObjsForEditor[comp._id] = comp; + if ((EDITOR || TEST) && legacyCC.engine && (this._id in legacyCC.engine.attachedObjsForEditor)) { + legacyCC.engine.attachedObjsForEditor[comp._id] = comp; } if (this._activeInHierarchy) { - cc.director._nodeActivator.activateComp(comp); + legacyCC.director._nodeActivator.activateComp(comp); } }; @@ -107,7 +108,7 @@ export function baseNodePolyfill (BaseNode) { // tslint:disable-next-line: prefer-for-of for (let i = 0; i < this._components.length; i++) { const comp = this._components[i]; - if (comp !== depended && comp.isValid && !cc.Object._willDestroy(comp)) { + if (comp !== depended && comp.isValid && !legacyCC.Object._willDestroy(comp)) { const depend = comp.constructor._requireComponent; if (depend && depended instanceof depend) { return comp; @@ -121,7 +122,7 @@ export function baseNodePolyfill (BaseNode) { // check activity state const shouldActiveNow = this._active && !!(this._parent && this._parent._activeInHierarchy); if (this._activeInHierarchy !== shouldActiveNow) { - cc.director._nodeActivator.activateNode(this, shouldActiveNow); + legacyCC.director._nodeActivator.activateNode(this, shouldActiveNow); } }; @@ -140,7 +141,7 @@ export function baseNodePolyfill (BaseNode) { if (EDITOR || TEST) { BaseNode.prototype._registerIfAttached = function (register) { - const attachedObjsForEditor = cc.engine.attachedObjsForEditor; + const attachedObjsForEditor = legacyCC.engine.attachedObjsForEditor; if (register) { attachedObjsForEditor[this._id] = this; for (let i = this._components.length - 1; i >= 0; i--) { @@ -152,9 +153,9 @@ export function baseNodePolyfill (BaseNode) { } attachedObjsForEditor[comp._id] = comp; } - cc.engine.emit('node-attach-to-scene', this); + legacyCC.engine.emit('node-attach-to-scene', this); } else { - cc.engine.emit('node-detach-from-scene', this); + legacyCC.engine.emit('node-detach-from-scene', this); delete attachedObjsForEditor[this._id]; for (const comp of this._components) { delete attachedObjsForEditor[comp._id]; @@ -174,7 +175,7 @@ export function baseNodePolyfill (BaseNode) { let path = ''; // @ts-ignore let node = this; - while (node && !(node instanceof cc.Scene)) { + while (node && !(node instanceof legacyCC.Scene)) { if (path) { path = node.name + '/' + path; } else { diff --git a/cocos/core/scene-graph/base-node.ts b/cocos/core/scene-graph/base-node.ts index a2408a0e8c..c35f012328 100644 --- a/cocos/core/scene-graph/base-node.ts +++ b/cocos/core/scene-graph/base-node.ts @@ -39,6 +39,7 @@ import * as js from '../utils/js'; import { baseNodePolyfill } from './base-node-dev'; import { NodeEventProcessor } from './node-event-processor'; import { DEV, DEBUG, EDITOR } from 'internal:constants'; +import { legacyCC } from '../global-exports'; /** * @@ -212,7 +213,7 @@ export class BaseNode extends CCObject implements ISchedulable { if (parent) { const couldActiveInScene = parent._activeInHierarchy; if (couldActiveInScene) { - cc.director._nodeActivator.activateNode(this, isActive); + legacyCC.director._nodeActivator.activateNode(this, isActive); } } } @@ -255,11 +256,11 @@ export class BaseNode extends CCObject implements ISchedulable { } public static _setScene (node: BaseNode) { - if (node instanceof cc.Scene) { + if (node instanceof legacyCC.Scene) { node._scene = node; } else { if (node._parent == null) { - cc.error('Node %s(%s) has not attached to a scene.', node.name, node.uuid); + legacyCC.error('Node %s(%s) has not attached to a scene.', node.name, node.uuid); } else { node._scene = node._parent._scene; } @@ -524,7 +525,7 @@ export class BaseNode extends CCObject implements ISchedulable { */ public getChildByUuid (uuid: string) { if (!uuid) { - cc.log('Invalid uuid'); + legacyCC.log('Invalid uuid'); return null; } @@ -549,7 +550,7 @@ export class BaseNode extends CCObject implements ISchedulable { */ public getChildByName (name: string) { if (!name) { - cc.log('Invalid name'); + legacyCC.log('Invalid name'); return null; } @@ -591,11 +592,11 @@ export class BaseNode extends CCObject implements ISchedulable { public addChild (child: this): void { - if (DEV && !(child instanceof cc._BaseNode)) { - return errorID(1634, cc.js.getClassName(child)); + if (DEV && !(child instanceof legacyCC._BaseNode)) { + return errorID(1634, legacyCC.js.getClassName(child)); } - cc.assertID(child, 1606); - cc.assertID(child._parent === null, 1605); + legacyCC.assertID(child, 1606); + legacyCC.assertID(child._parent === null, 1605); // invokes the parent setter child.setParent(this); @@ -1002,7 +1003,7 @@ export class BaseNode extends CCObject implements ISchedulable { public addComponent (typeOrClassName: string | Function) { if (EDITOR && (this._objFlags & Destroying)) { - cc.error('isDestroying'); + legacyCC.error('isDestroying'); return null; } @@ -1013,7 +1014,7 @@ export class BaseNode extends CCObject implements ISchedulable { constructor = js.getClassByName(typeOrClassName); if (!constructor) { errorID(3807, typeOrClassName); - if (cc._RF.peek()) { + if (legacyCC._RF.peek()) { errorID(3808, typeOrClassName); } return null; @@ -1032,7 +1033,7 @@ export class BaseNode extends CCObject implements ISchedulable { errorID(3809); return null; } - if (!js.isChildClassOf(constructor, cc.Component)) { + if (!js.isChildClassOf(constructor, legacyCC.Component)) { errorID(3810); return null; } @@ -1072,7 +1073,7 @@ export class BaseNode extends CCObject implements ISchedulable { } } if (this._activeInHierarchy) { - cc.director._nodeActivator.activateComp(component); + legacyCC.director._nodeActivator.activateComp(component); } return component; @@ -1275,7 +1276,7 @@ export class BaseNode extends CCObject implements ISchedulable { protected _instantiate (cloned) { if (!cloned) { - cloned = cc.instantiate._clone(this, this); + cloned = legacyCC.instantiate._clone(this, this); } const thisPrefabInfo = this._prefab; @@ -1287,7 +1288,7 @@ export class BaseNode extends CCObject implements ISchedulable { // if (thisPrefabInfo._synced) { // return clone; // } - } else if (EDITOR && cc.engine._isPlaying) { + } else if (EDITOR && legacyCC.engine._isPlaying) { cloned._name += ' (Clone)'; } @@ -1300,15 +1301,15 @@ export class BaseNode extends CCObject implements ISchedulable { protected _onHierarchyChangedBase (oldParent: this | null) { const newParent = this._parent; - if (this._persistNode && !(newParent instanceof cc.Scene)) { - cc.game.removePersistRootNode(this); + if (this._persistNode && !(newParent instanceof legacyCC.Scene)) { + legacyCC.game.removePersistRootNode(this); if (EDITOR) { warnID(1623); } } if (EDITOR) { - const scene = cc.director.getScene() as this | null; + const scene = legacyCC.director.getScene() as this | null; const inCurrentSceneBefore = oldParent && oldParent.isChildOf(scene); const inCurrentSceneNow = newParent && newParent.isChildOf(scene); if (!inCurrentSceneBefore && inCurrentSceneNow) { @@ -1325,7 +1326,7 @@ export class BaseNode extends CCObject implements ISchedulable { const shouldActiveNow = this._active && !!(newParent && newParent._activeInHierarchy); if (this._activeInHierarchy !== shouldActiveNow) { - cc.director._nodeActivator.activateNode(this, shouldActiveNow); + legacyCC.director._nodeActivator.activateNode(this, shouldActiveNow); } } @@ -1366,7 +1367,7 @@ export class BaseNode extends CCObject implements ISchedulable { // remove from persist if (this._persistNode) { - cc.game.removePersistRootNode(this); + legacyCC.game.removePersistRootNode(this); } if (!destroyByParent) { @@ -1393,7 +1394,7 @@ export class BaseNode extends CCObject implements ISchedulable { for (let i = 0; i < comps.length; ++i) { const component = comps[i]; if (component._enabled) { - cc.director._compScheduler.disableComp(component); + legacyCC.director._compScheduler.disableComp(component); } } // deactivate recursively @@ -1423,4 +1424,4 @@ baseNodePolyfill(BaseNode); * @param {Event.EventCustom} event */ -cc._BaseNode = BaseNode; +legacyCC._BaseNode = BaseNode; diff --git a/cocos/core/scene-graph/component-scheduler.ts b/cocos/core/scene-graph/component-scheduler.ts index d5541441dc..ea7e88f356 100644 --- a/cocos/core/scene-graph/component-scheduler.ts +++ b/cocos/core/scene-graph/component-scheduler.ts @@ -32,6 +32,7 @@ import { MutableForwardIterator } from '../utils/array'; import { array } from '../utils/js'; import { tryCatchFunctor_EDITOR } from '../utils/misc'; import { EDITOR, SUPPORT_JIT, DEV, TEST } from 'internal:constants'; +import { legacyCC } from '../global-exports'; const fastRemoveAt = array.fastRemoveAt; // @ts-ignore @@ -113,7 +114,7 @@ export class LifeCycleInvoker { this._pos = new Iterator([]); if (TEST) { - cc.assert(typeof invokeFunc === 'function', 'invokeFunc must be type function'); + legacyCC.assert(typeof invokeFunc === 'function', 'invokeFunc must be type function'); } this._invoke = invokeFunc; } @@ -175,7 +176,7 @@ class ReusableInvoker extends LifeCycleInvoker { array.splice(~i, 0, comp); } else if (DEV) { - cc.error('component already added'); + legacyCC.error('component already added'); } } } @@ -209,7 +210,7 @@ class ReusableInvoker extends LifeCycleInvoker { function enableInEditor (comp) { if (!(comp._objFlags & IsEditorOnEnableCalled)) { - cc.engine.emit('component-enabled', comp.uuid); + legacyCC.engine.emit('component-enabled', comp.uuid); comp._objFlags |= IsEditorOnEnableCalled; } } @@ -239,7 +240,7 @@ export function createInvokeImpl (singleInvoke, fastPath, ensureFlag?) { } catch (e) { // slow path - cc._throw(e); + legacyCC._throw(e); var array = iterator.array; if (ensureFlag) { array[iterator.i]._objFlags |= ensureFlag; @@ -250,7 +251,7 @@ export function createInvokeImpl (singleInvoke, fastPath, ensureFlag?) { singleInvoke(array[iterator.i], dt); } catch (e) { - cc._throw(e); + legacyCC._throw(e); if (ensureFlag) { array[iterator.i]._objFlags |= ensureFlag; } @@ -304,7 +305,7 @@ const invokeLateUpdate = SUPPORT_JIT ? createInvokeImplJit('c.lateUpdate(dt)', t ); export const invokeOnEnable = EDITOR ? (iterator) => { - const compScheduler = cc.director._compScheduler; + const compScheduler = legacyCC.director._compScheduler; const array = iterator.array; for (iterator.i = 0; iterator.i < array.length; ++iterator.i) { const comp = array[iterator.i]; @@ -317,7 +318,7 @@ export const invokeOnEnable = EDITOR ? (iterator) => { } } } : (iterator) => { - const compScheduler = cc.director._compScheduler; + const compScheduler = legacyCC.director._compScheduler; const array = iterator.array; for (iterator.i = 0; iterator.i < array.length; ++iterator.i) { const comp = array[iterator.i]; @@ -357,7 +358,7 @@ export class ComponentScheduler { } public _onEnabled (comp) { - cc.director.getScheduler().resumeTarget(comp); + legacyCC.director.getScheduler().resumeTarget(comp); comp._objFlags |= IsOnEnableCalled; // schedule @@ -370,7 +371,7 @@ export class ComponentScheduler { } public _onDisabled (comp) { - cc.director.getScheduler().pauseTarget(comp); + legacyCC.director.getScheduler().pauseTarget(comp); comp._objFlags &= ~IsOnEnableCalled; // cancel schedule task @@ -493,7 +494,7 @@ export class ComponentScheduler { if (EDITOR) { ComponentScheduler.prototype.enableComp = function (comp, invoker) { - if (cc.engine.isPlaying || comp.constructor._executeInEditMode) { + if (legacyCC.engine.isPlaying || comp.constructor._executeInEditMode) { if (!(comp._objFlags & IsOnEnableCalled)) { if (comp.onEnable) { if (invoker) { @@ -517,7 +518,7 @@ if (EDITOR) { }; ComponentScheduler.prototype.disableComp = function (comp) { - if (cc.engine.isPlaying || comp.constructor._executeInEditMode) { + if (legacyCC.engine.isPlaying || comp.constructor._executeInEditMode) { if (comp._objFlags & IsOnEnableCalled) { if (comp.onDisable) { callOnDisableInTryCatch(comp); @@ -526,7 +527,7 @@ if (EDITOR) { } } if (comp._objFlags & IsEditorOnEnableCalled) { - cc.engine.emit('component-disabled', comp.uuid); + legacyCC.engine.emit('component-disabled', comp.uuid); comp._objFlags &= ~IsEditorOnEnableCalled; } }; diff --git a/cocos/core/scene-graph/find.ts b/cocos/core/scene-graph/find.ts index e98c677ebb..df7c9f2c3e 100644 --- a/cocos/core/scene-graph/find.ts +++ b/cocos/core/scene-graph/find.ts @@ -30,6 +30,7 @@ import { warnID } from '../platform/debug'; import { Node } from './node'; import { DEV } from 'internal:constants'; +import { legacyCC } from '../global-exports'; /** * Finds a node by hierarchy path, the path is case-sensitive. @@ -39,7 +40,7 @@ import { DEV } from 'internal:constants'; */ export function find (path: string, referenceNode?: Node): Node | null { if (!referenceNode) { - const scene = cc.director.getScene(); + const scene = legacyCC.director.getScene(); if (!scene) { if (DEV) { warnID(5601); @@ -57,4 +58,4 @@ export function find (path: string, referenceNode?: Node): Node | null { return referenceNode!.getChildByPath(path); } -cc.find = find; +legacyCC.find = find; diff --git a/cocos/core/scene-graph/layers.ts b/cocos/core/scene-graph/layers.ts index d6740d0e9d..3172716379 100644 --- a/cocos/core/scene-graph/layers.ts +++ b/cocos/core/scene-graph/layers.ts @@ -28,6 +28,7 @@ */ import { BitMask, Enum } from '../value-types'; +import { legacyCC } from '../global-exports'; // built-in layers, users can use 0~19 bits, 20~31 are system preserve bits. const layerList = { @@ -118,4 +119,4 @@ export class Layers { } } -cc.Layers = Layers; +legacyCC.Layers = Layers; diff --git a/cocos/core/scene-graph/node-activator.ts b/cocos/core/scene-graph/node-activator.ts index 86c41ab564..ffbc7ab56a 100644 --- a/cocos/core/scene-graph/node-activator.ts +++ b/cocos/core/scene-graph/node-activator.ts @@ -32,6 +32,7 @@ import { array, Pool } from '../utils/js'; import { tryCatchFunctor_EDITOR } from '../utils/misc'; import { invokeOnEnable, createInvokeImpl, createInvokeImplJit, OneOffInvoker, LifeCycleInvoker } from './component-scheduler'; import { EDITOR, DEV, TEST, SUPPORT_JIT } from 'internal:constants'; +import { legacyCC } from '../global-exports'; const MAX_POOL_SIZE = 4; @@ -50,7 +51,7 @@ const callOnLoadInTryCatch = EDITOR && function (c) { c.onLoad(); } catch (e) { - cc._throw(e); + legacyCC._throw(e); } c._objFlags |= IsOnLoadCalled; _onLoadInEditor(c); @@ -128,7 +129,7 @@ activateTasksPool.get = function getActivateTask () { function _componentCorrupted (node, comp, index) { if (DEV) { - cc.errorID(3817, node.name, index); + legacyCC.errorID(3817, node.name, index); console.log('Corrupted component value:', comp); } if (comp) { @@ -140,7 +141,7 @@ function _componentCorrupted (node, comp, index) { } function _onLoadInEditor (comp) { - if (comp.onLoad && !cc.engine._isPlaying) { + if (comp.onLoad && !legacyCC.engine._isPlaying) { // @ts-ignore const focused = Editor.Selection.curActivate('node') === comp.node.uuid; if (focused) { @@ -237,13 +238,13 @@ export default class NodeActivator { if (deactivatedOnLoading) { return; } - cc.director._compScheduler.enableComp(comp, onEnableInvoker); + legacyCC.director._compScheduler.enableComp(comp, onEnableInvoker); } } public destroyComp (comp) { // ensure onDisable called - cc.director._compScheduler.disableComp(comp); + legacyCC.director._compScheduler.disableComp(comp); if (comp.onDestroy && (comp._objFlags & IsOnLoadCalled)) { comp.onDestroy(); @@ -258,7 +259,7 @@ export default class NodeActivator { // zh: // 对相同节点而言,无法撤销反激活,防止反激活 - 激活 - 反激活的死循环发生。 // 这样设计简化了一些引擎的实现,而且对调用者来说能保证反激活操作都能成功。 - cc.errorID(3816, node.name); + legacyCC.errorID(3816, node.name); return; } @@ -270,7 +271,7 @@ export default class NodeActivator { // activate components for (let i = 0; i < originCount; ++i) { const component = node._components[i]; - if (component instanceof cc.Component) { + if (component instanceof legacyCC.Component) { this.activateComp(component, preloadInvoker, onLoadInvoker, onEnableInvoker); } else { @@ -292,9 +293,9 @@ export default class NodeActivator { protected _deactivateNodeRecursively (node) { if (DEV) { - cc.assert(!(node._objFlags & Deactivating), 'node should not deactivating'); + legacyCC.assert(!(node._objFlags & Deactivating), 'node should not deactivating'); // ensures _activeInHierarchy is always changing when Deactivating flagged - cc.assert(node._activeInHierarchy, 'node should not deactivated'); + legacyCC.assert(node._activeInHierarchy, 'node should not deactivated'); } node._objFlags |= Deactivating; node._activeInHierarchy = false; @@ -305,7 +306,7 @@ export default class NodeActivator { for (let c = 0; c < originCount; ++c) { const component = node._components[c]; if (component._enabled) { - cc.director._compScheduler.disableComp(component); + legacyCC.director._compScheduler.disableComp(component); if (node._activeInHierarchy) { // reactivated from root @@ -334,7 +335,7 @@ export default class NodeActivator { if (EDITOR) { NodeActivator.prototype.activateComp = (comp, preloadInvoker, onLoadInvoker, onEnableInvoker) => { - if (cc.engine._isPlaying || comp.constructor._executeInEditMode) { + if (legacyCC.engine._isPlaying || comp.constructor._executeInEditMode) { if (!(comp._objFlags & IsPreloadStarted)) { comp._objFlags |= IsPreloadStarted; if (comp.__preload) { @@ -367,16 +368,16 @@ if (EDITOR) { if (deactivatedOnLoading) { return; } - cc.director._compScheduler.enableComp(comp, onEnableInvoker); + legacyCC.director._compScheduler.enableComp(comp, onEnableInvoker); } }; NodeActivator.prototype.destroyComp = (comp) => { // ensure onDisable called - cc.director._compScheduler.disableComp(comp); + legacyCC.director._compScheduler.disableComp(comp); if (comp.onDestroy && (comp._objFlags & IsOnLoadCalled)) { - if (cc.engine._isPlaying || comp.constructor._executeInEditMode) { + if (legacyCC.engine._isPlaying || comp.constructor._executeInEditMode) { callOnDestroyInTryCatch && callOnDestroyInTryCatch(comp); } } diff --git a/cocos/core/scene-graph/node-event-processor.ts b/cocos/core/scene-graph/node-event-processor.ts index fed183a1b2..a8d623b93a 100644 --- a/cocos/core/scene-graph/node-event-processor.ts +++ b/cocos/core/scene-graph/node-event-processor.ts @@ -37,6 +37,7 @@ import { EventMouse, EventTouch } from '../platform/event-manager/events'; import { Touch } from '../platform/event-manager/touch'; import { BaseNode } from './base-node'; import { Node } from './node'; +import { legacyCC } from '../global-exports'; const _cachedArray = new Array(16); let _currentHovered: BaseNode | null = null; @@ -270,10 +271,10 @@ function _doDispatchEvent (owner: BaseNode, event: Event) { } function _searchMaskInParent (node: Node | null) { - const Mask = cc.MaskComponent; + const Mask = legacyCC.MaskComponent; if (Mask) { let index = 0; - for (let curr = node; curr && cc.Node.isNode(curr); curr = curr.parent, ++index) { + for (let curr = node; curr && legacyCC.Node.isNode(curr); curr = curr.parent, ++index) { if (curr.getComponent(Mask)) { return { index, @@ -650,8 +651,8 @@ export class NodeEventProcessor { // just for ui if (_touchEvents.indexOf(type) !== -1) { if (!this.touchListener) { - this.touchListener = cc.EventListener.create({ - event: cc.EventListener.TOUCH_ONE_BY_ONE, + this.touchListener = legacyCC.EventListener.create({ + event: legacyCC.EventListener.TOUCH_ONE_BY_ONE, swallowTouches: true, owner: this._node, mask: _searchMaskInParent(this._node as Node), @@ -666,8 +667,8 @@ export class NodeEventProcessor { forDispatch = true; } else if (_mouseEvents.indexOf(type) !== -1) { if (!this.mouseListener) { - this.mouseListener = cc.EventListener.create({ - event: cc.EventListener.MOUSE, + this.mouseListener = legacyCC.EventListener.create({ + event: legacyCC.EventListener.MOUSE, _previousIn: false, owner: this._node, mask: _searchMaskInParent(this._node as Node), @@ -682,7 +683,7 @@ export class NodeEventProcessor { forDispatch = true; } if (newAdded && !this._node.activeInHierarchy) { - cc.director.getScheduler().schedule(() => { + legacyCC.director.getScheduler().schedule(() => { if (!this._node.activeInHierarchy) { eventManager.pauseTarget(this._node as Node); } @@ -698,7 +699,7 @@ export class NodeEventProcessor { target = undefined; } else { useCapture = !!useCapture; } if (!callback) { - cc.errorID(6800); + legacyCC.errorID(6800); return; } @@ -740,4 +741,4 @@ export class NodeEventProcessor { } } -cc.NodeEventProcessor = NodeEventProcessor; +legacyCC.NodeEventProcessor = NodeEventProcessor; diff --git a/cocos/core/scene-graph/node.ts b/cocos/core/scene-graph/node.ts index fed25379a2..23198e50bb 100644 --- a/cocos/core/scene-graph/node.ts +++ b/cocos/core/scene-graph/node.ts @@ -36,6 +36,7 @@ import { BaseNode, TRANSFORM_ON } from './base-node'; import { Layers } from './layers'; import { NodeSpace, TransformBit } from './node-enum'; import { NodeUIProperties } from './node-ui-properties'; +import { legacyCC } from '../global-exports'; const v3_a = new Vec3(); const q_a = new Quat(); @@ -86,7 +87,7 @@ export class Node extends BaseNode { * @param obj 待测试的节点 */ public static isNode (obj: object | null): obj is Node { - return obj instanceof Node && (obj.constructor === Node || !(obj instanceof cc.Scene)); + return obj instanceof Node && (obj.constructor === Node || !(obj instanceof legacyCC.Scene)); } // UI 部分的脏数据 @@ -972,4 +973,4 @@ export class Node extends BaseNode { } } -cc.Node = Node; +legacyCC.Node = Node; diff --git a/cocos/core/scene-graph/private-node.ts b/cocos/core/scene-graph/private-node.ts index d246187b93..268c9ea971 100644 --- a/cocos/core/scene-graph/private-node.ts +++ b/cocos/core/scene-graph/private-node.ts @@ -30,6 +30,7 @@ import { ccclass } from '../data/class-decorator'; import { CCObject } from '../data/object'; import { Node } from './node'; +import { legacyCC } from '../global-exports'; // const LocalDirtyFlag = Node._LocalDirtyFlag; // const POSITION_ON = 1 << 0; @@ -168,4 +169,4 @@ export class PrivateNode extends Node { // cc.js.getset(PrivateNode.prototype, 'parent', PrivateNode.prototype.getParent, PrivateNode.prototype.setParent); // cc.js.getset(PrivateNode.prototype, 'position', PrivateNode.prototype.getPosition, PrivateNode.prototype.setPosition); -cc.PrivateNode = PrivateNode; +legacyCC.PrivateNode = PrivateNode; diff --git a/cocos/core/scene-graph/scene-globals.ts b/cocos/core/scene-graph/scene-globals.ts index 0830e68e04..26bf793c4c 100644 --- a/cocos/core/scene-graph/scene-globals.ts +++ b/cocos/core/scene-graph/scene-globals.ts @@ -37,6 +37,7 @@ import { RenderScene } from '../renderer/scene/render-scene'; import { Skybox } from '../renderer/scene/skybox'; import { Fog, FogType } from '../renderer/scene/fog'; import { Node } from './node'; +import { legacyCC } from '../global-exports'; const _up = new Vec3(0, 1, 0); const _v3 = new Vec3(); @@ -100,7 +101,7 @@ export class AmbientInfo { this.groundAlbedo = this._groundAlbedo; } } -cc.AmbientInfo = AmbientInfo; +legacyCC.AmbientInfo = AmbientInfo; /** * @zh 天空盒相关信息 @@ -174,7 +175,7 @@ export class SkyboxInfo { this.useIBL = this._useIBL; } } -cc.SkyboxInfo = SkyboxInfo; +legacyCC.SkyboxInfo = SkyboxInfo; /** * @zh 全局雾相关信息 @@ -465,7 +466,7 @@ export class PlanarShadowInfo { this.enabled = this._enabled; } } -cc.PlanarShadowInfo = PlanarShadowInfo; +legacyCC.PlanarShadowInfo = PlanarShadowInfo; /** * @zh 各类场景级别的渲染参数,将影响全场景的所有物体 @@ -497,4 +498,4 @@ export class SceneGlobals { this.fog.renderScene = rs; } } -cc.SceneGlobals = SceneGlobals; +legacyCC.SceneGlobals = SceneGlobals; diff --git a/cocos/core/scene-graph/scene.ts b/cocos/core/scene-graph/scene.ts index 8efe1da88e..319db78a2e 100644 --- a/cocos/core/scene-graph/scene.ts +++ b/cocos/core/scene-graph/scene.ts @@ -34,6 +34,7 @@ import { RenderScene } from '../renderer/scene/render-scene'; import { BaseNode } from './base-node'; import { SceneGlobals } from './scene-globals'; import { EDITOR, TEST } from 'internal:constants'; +import { legacyCC } from '../global-exports'; /** * @en @@ -84,15 +85,15 @@ export class Scene extends BaseNode { constructor (name: string) { super(name); this._activeInHierarchy = false; - if (cc.director && cc.director.root) { - this._renderScene = cc.director.root.createScene({}); + if (legacyCC.director && legacyCC.director.root) { + this._renderScene = legacyCC.director.root.createScene({}); } - this._inited = cc.game ? !cc.game._isCloning : true; + this._inited = legacyCC.game ? !legacyCC.game._isCloning : true; } public destroy () { const success = super.destroy(); - cc.director.root.destroyScene(this._renderScene); + legacyCC.director.root.destroyScene(this._renderScene); this._activeInHierarchy = false; return success; } @@ -144,7 +145,7 @@ export class Scene extends BaseNode { protected _load () { if (!this._inited) { if (TEST) { - cc.assert(!this._activeInHierarchy, 'Should deactivate ActionManager and EventManager by default'); + legacyCC.assert(!this._activeInHierarchy, 'Should deactivate ActionManager and EventManager by default'); } this._onBatchCreated(); this._inited = true; @@ -159,9 +160,9 @@ export class Scene extends BaseNode { // register all nodes to editor this._registerIfAttached!(active); } - cc.director._nodeActivator.activateNode(this, active); + legacyCC.director._nodeActivator.activateNode(this, active); this._globals.renderScene = this._renderScene!; } } -cc.Scene = Scene; +legacyCC.Scene = Scene; diff --git a/cocos/core/scheduler.ts b/cocos/core/scheduler.ts index 7b59e7e883..511103d1bb 100644 --- a/cocos/core/scheduler.ts +++ b/cocos/core/scheduler.ts @@ -30,6 +30,7 @@ import IdGenerator from './utils/id-generator'; import {createMap} from './utils/js'; import System from './components/system'; +import { legacyCC } from './global-exports'; const MAX_POOL_SIZE = 20; @@ -244,7 +245,7 @@ class CallbackTimer { this._delay = delay; this._useDelay = (this._delay > 0); this._repeat = repeat; - this._runForever = (this._repeat === cc.macro.REPEAT_FOREVER); + this._runForever = (this._repeat === legacyCC.macro.REPEAT_FOREVER); return true; } /** @@ -385,7 +386,7 @@ export class Scheduler extends System { if (!found) { // @ts-ignore if (target.__instanceId) { - cc.warnID(1513); + legacyCC.warnID(1513); } else { target.id = idGenerator.getNewId(); @@ -577,15 +578,15 @@ export class Scheduler extends System { // selector, target, interval, paused if (arguments.length === 3 || arguments.length === 4 || arguments.length === 5) { paused = !!repeat; - repeat = cc.macro.REPEAT_FOREVER; + repeat = legacyCC.macro.REPEAT_FOREVER; delay = 0; } - cc.assertID(target, 1502); + legacyCC.assertID(target, 1502); let targetId = target.uuid || target.id; if (!targetId) { - cc.errorID(1510); + legacyCC.errorID(1510); return; } let element = this._hashForTimers[targetId]; @@ -595,7 +596,7 @@ export class Scheduler extends System { this._arrayForTimers.push(element); this._hashForTimers[targetId] = element; } else if (element.paused !== paused) { - cc.warnID(1511); + legacyCC.warnID(1511); } let timer; @@ -607,7 +608,7 @@ export class Scheduler extends System { for (i = 0; i < element.timers.length; ++i) { timer = element.timers[i]; if (timer && callback === timer._callback) { - cc.logID(1507, timer.getInterval(), interval); + legacyCC.logID(1507, timer.getInterval(), interval); timer._interval = interval; return; } @@ -638,7 +639,7 @@ export class Scheduler extends System { public scheduleUpdate (target: ISchedulable, priority: Number, paused: Boolean) { let targetId = target.uuid || target.id; if (!targetId) { - cc.errorID(1510); + legacyCC.errorID(1510); return; } const hashElement = this._hashForUpdates[targetId]; @@ -646,7 +647,7 @@ export class Scheduler extends System { // check if priority has changed if (hashElement.entry.priority !== priority){ if (this._updateHashLocked){ - cc.logID(1506); + legacyCC.logID(1506); hashElement.entry.markedForDeletion = false; hashElement.entry.paused = paused; return; @@ -698,7 +699,7 @@ export class Scheduler extends System { } let targetId = target.uuid || target.id; if (!targetId) { - cc.errorID(1510); + legacyCC.errorID(1510); return; } @@ -743,7 +744,7 @@ export class Scheduler extends System { } let targetId = target.uuid || target.id; if (!targetId) { - cc.errorID(1510); + legacyCC.errorID(1510); return; } @@ -771,7 +772,7 @@ export class Scheduler extends System { } let targetId = target.uuid || target.id; if (!targetId) { - cc.errorID(1510); + legacyCC.errorID(1510); return; } @@ -808,7 +809,7 @@ export class Scheduler extends System { * 不用调用此函数,除非你确定你在做什么。 */ public unscheduleAll (){ - this.unscheduleAllWithMinPriority(cc.Scheduler.PRIORITY_SYSTEM); + this.unscheduleAllWithMinPriority(legacyCC.Scheduler.PRIORITY_SYSTEM); } /** @@ -882,11 +883,11 @@ export class Scheduler extends System { public isScheduled (callback, target:ISchedulable){ // key, target // selector, target - cc.assertID(callback, 1508); - cc.assertID(target, 1509); + legacyCC.assertID(callback, 1508); + legacyCC.assertID(target, 1509); let targetId = target.uuid || target.id; if (!targetId) { - cc.errorID(1510); + legacyCC.errorID(1510); return; } @@ -921,7 +922,7 @@ export class Scheduler extends System { * 不要调用这个方法,除非你知道你正在做什么。 */ public pauseAllTargets () { - return this.pauseAllTargetsWithMinPriority(cc.Scheduler.PRIORITY_SYSTEM); + return this.pauseAllTargetsWithMinPriority(legacyCC.Scheduler.PRIORITY_SYSTEM); } /** @@ -1017,10 +1018,10 @@ export class Scheduler extends System { * @param {Object} target */ public pauseTarget (target:ISchedulable) { - cc.assertID(target, 1503); + legacyCC.assertID(target, 1503); let targetId = target.uuid || target.id; if (!targetId) { - cc.errorID(1510); + legacyCC.errorID(1510); return; } @@ -1050,10 +1051,10 @@ export class Scheduler extends System { * @param {Object} target */ public resumeTarget (target:ISchedulable) { - cc.assertID(target, 1504); + legacyCC.assertID(target, 1504); let targetId = target.uuid || target.id; if (!targetId) { - cc.errorID(1510); + legacyCC.errorID(1510); return; } @@ -1078,10 +1079,10 @@ export class Scheduler extends System { * @return {Boolean} */ public isTargetPaused (target:ISchedulable) { - cc.assertID(target, 1505); + legacyCC.assertID(target, 1505); let targetId = target.uuid || target.id; if (!targetId) { - cc.errorID(1510); + legacyCC.errorID(1510); return false; } @@ -1148,4 +1149,4 @@ export class Scheduler extends System { } -cc.Scheduler = Scheduler; +legacyCC.Scheduler = Scheduler; diff --git a/cocos/core/splash-screen-webgl.ts b/cocos/core/splash-screen-webgl.ts index 78d766dd40..7d4a053397 100644 --- a/cocos/core/splash-screen-webgl.ts +++ b/cocos/core/splash-screen-webgl.ts @@ -8,6 +8,7 @@ import { easing } from "./animation"; import { macro } from "./platform"; import { sys } from "./platform/sys"; import { COCOSPLAY, XIAOMI, JSB, ALIPAY } from 'internal:constants'; +import { legacyCC } from './global-exports'; type SplashEffectType = 'none' | 'Fade-InOut'; @@ -151,12 +152,12 @@ export class SplashScreenWebgl { this._directCall = true; return; } else { - cc.view.enableRetina(true); + legacyCC.view.enableRetina(true); const designRes = window._CCSettings.designResolution; if (designRes) { - cc.view.setDesignResolutionSize(designRes.width, designRes.height, designRes.policy); + legacyCC.view.setDesignResolutionSize(designRes.width, designRes.height, designRes.policy); } else { - cc.view.setDesignResolutionSize(960, 640, 4); + legacyCC.view.setDesignResolutionSize(960, 640, 4); } let useWebGL2 = (!!window.WebGL2RenderingContext); @@ -180,7 +181,7 @@ export class SplashScreenWebgl { let gl: WebGLRenderingContext | null = null; let gl2: WebGL2RenderingContext | null = null; - if (useWebGL2 && cc.WebGL2GFXDevice) { + if (useWebGL2 && legacyCC.WebGL2GFXDevice) { gl2 = canvas.getContext('webgl2', webGLCtxAttribs) as WebGL2RenderingContext; if (gl2 == null) { gl = canvas.getContext('webgl', webGLCtxAttribs) as WebGLRenderingContext; @@ -221,7 +222,7 @@ export class SplashScreenWebgl { private init () { // adapt for native mac & ios if (JSB) { - if (sys.os == cc.sys.OS_OSX || sys.os == cc.sys.OS_IOS) { + if (sys.os == legacyCC.sys.OS_OSX || sys.os == legacyCC.sys.OS_IOS) { this.gl.canvas.width = screen.width * devicePixelRatio; this.gl.canvas.height = screen.height * devicePixelRatio; } @@ -448,4 +449,4 @@ export class SplashScreenWebgl { private constructor () { }; } -cc.internal.SplashScreenWebgl = SplashScreenWebgl; +legacyCC.internal.SplashScreenWebgl = SplashScreenWebgl; diff --git a/cocos/core/utils/array.ts b/cocos/core/utils/array.ts index 4277ee56ae..ff7f6d32c3 100644 --- a/cocos/core/utils/array.ts +++ b/cocos/core/utils/array.ts @@ -23,6 +23,8 @@ THE SOFTWARE. */ +import { legacyCC } from '../global-exports'; + export {default as MutableForwardIterator} from './mutable-forward-iterator'; /** @@ -86,7 +88,7 @@ export function verifyType (array: T[], type: Function) { if (array && array.length > 0) { for (const item of array) { if (!(item instanceof type)) { - cc.logID(1300); + legacyCC.logID(1300); return false; } } diff --git a/cocos/core/utils/coordinates-converts-utils.ts b/cocos/core/utils/coordinates-converts-utils.ts index f4da0793ba..2227719976 100644 --- a/cocos/core/utils/coordinates-converts-utils.ts +++ b/cocos/core/utils/coordinates-converts-utils.ts @@ -6,6 +6,7 @@ import { CameraComponent } from '../3d/framework/camera-component'; import { Vec3 } from '../math'; import { Node } from '../scene-graph'; import { replaceProperty } from './deprecated'; +import { legacyCC } from '../global-exports'; const _vec3 = new Vec3(); @@ -47,8 +48,8 @@ export function WorldNode3DToWorldNodeUI (mainCamera: CameraComponent, wpos: Vec } mainCamera.worldToScreen(wpos, out); - out.x = out.x / cc.view.getScaleX(); - out.y = out.y / cc.view.getScaleY(); + out.x = out.x / legacyCC.view.getScaleX(); + out.y = out.y / legacyCC.view.getScaleY(); return out; } @@ -61,9 +62,9 @@ const convertUtils = { }; export { convertUtils }; -cc.pipelineUtils = convertUtils; +legacyCC.pipelineUtils = convertUtils; -replaceProperty(cc.pipelineUtils, 'cc.pipelineUtils', [ +replaceProperty(legacyCC.pipelineUtils, 'cc.pipelineUtils', [ { 'name': 'WorldNode3DToLocalNodeUI', 'newName': 'convertToUINode', diff --git a/cocos/core/utils/decode-uuid.ts b/cocos/core/utils/decode-uuid.ts index 3cfb6cb6bd..5ad369723a 100644 --- a/cocos/core/utils/decode-uuid.ts +++ b/cocos/core/utils/decode-uuid.ts @@ -26,6 +26,7 @@ import { BASE64_VALUES } from './misc'; import { TEST } from 'internal:constants'; +import { legacyCC } from '../global-exports'; const HexChars = '0123456789abcdef'.split(''); @@ -69,5 +70,5 @@ export default function decodeUuid (base64: string) { } if (TEST) { - cc._Test.decodeUuid = decodeUuid; + legacyCC._Test.decodeUuid = decodeUuid; } diff --git a/cocos/core/utils/html-text-parser.ts b/cocos/core/utils/html-text-parser.ts index 34d201689a..dc32df2643 100644 --- a/cocos/core/utils/html-text-parser.ts +++ b/cocos/core/utils/html-text-parser.ts @@ -25,6 +25,7 @@ */ import { TEST } from 'internal:constants'; +import { legacyCC } from '../global-exports'; /** * @@ -367,5 +368,5 @@ export class HtmlTextParser { } if (TEST) { - cc._Test.HtmlTextParser = HtmlTextParser; + legacyCC._Test.HtmlTextParser = HtmlTextParser; } diff --git a/cocos/core/utils/index.ts b/cocos/core/utils/index.ts index 2aa14fae94..e4db530a7d 100644 --- a/cocos/core/utils/index.ts +++ b/cocos/core/utils/index.ts @@ -35,6 +35,7 @@ import * as misc from './misc'; * 用于处理文件与目录的路径的模块 */ import * as path from './path'; +import { legacyCC } from '../global-exports'; export * from './deprecated'; export * from './text-utils'; diff --git a/cocos/core/utils/js-typed.ts b/cocos/core/utils/js-typed.ts index fccfc302d1..1cb8bb7f15 100644 --- a/cocos/core/utils/js-typed.ts +++ b/cocos/core/utils/js-typed.ts @@ -2,6 +2,7 @@ import { warnID } from '../platform/debug'; import IDGenerator from './id-generator'; import { EDITOR, DEV, TEST } from 'internal:constants'; +import { legacyCC } from '../global-exports'; const tempCIDGenerator = new IDGenerator('TmpCId.'); /** @@ -307,7 +308,7 @@ export function addon (object?: any, ...sources: any[]) { for (const source of sources) { if (source) { if (typeof source !== 'object') { - cc.errorID(5402, source); + legacyCC.errorID(5402, source); continue; } for (const name in source) { @@ -329,7 +330,7 @@ export function mixin (object?: any, ...sources: any[]) { for (const source of sources) { if (source) { if (typeof source !== 'object') { - cc.errorID(5403, source); + legacyCC.errorID(5403, source); continue; } for (const name in source) { @@ -350,15 +351,15 @@ export function mixin (object?: any, ...sources: any[]) { export function extend (cls: Function, base: Function) { if (DEV) { if (!base) { - cc.errorID(5404); + legacyCC.errorID(5404); return; } if (!cls) { - cc.errorID(5405); + legacyCC.errorID(5405); return; } if (Object.keys(cls.prototype).length > 0) { - cc.errorID(5406); + legacyCC.errorID(5406); } } for (const p in base) { if (base.hasOwnProperty(p)) { cls[p] = base[p]; } } @@ -454,7 +455,7 @@ export function _setClassId (id, constructor) { If you dont need serialization, you can set class id to "". You can also call \ cc.js.unregisterClass to remove the id of unused class'; } - cc.error(error); + legacyCC.error(error); } else { table[id] = constructor; @@ -483,7 +484,7 @@ function doSetClassName (id, constructor) { If you dont need serialization, you can set class id to "". You can also call \ cc.js.unregisterClass to remove the id of unused class'; } - cc.error(error); + legacyCC.error(error); } else { table[id] = constructor; diff --git a/cocos/core/utils/js.ts b/cocos/core/utils/js.ts index a95453025b..112b00e8dc 100644 --- a/cocos/core/utils/js.ts +++ b/cocos/core/utils/js.ts @@ -61,6 +61,7 @@ import { _nameToClass, } from './js-typed'; import { EDITOR } from 'internal:constants'; +import { legacyCC } from '../global-exports'; export * from './js-typed'; export {default as IDGenerator} from './id-generator'; @@ -102,10 +103,10 @@ export const js = { * This module provides some JavaScript utilities. * All members can be accessed with "cc.js". */ -cc.js = js; +legacyCC.js = js; if (EDITOR) { - cc.js.getset(cc.js, '_registeredClassIds', () => { + legacyCC.js.getset(legacyCC.js, '_registeredClassIds', () => { const dump = {}; for (const id in _idToClass) { if (!(id in _idToClass)) { @@ -125,7 +126,7 @@ if (EDITOR) { } }, ); - cc.js.getset(cc.js, '_registeredClassNames', + legacyCC.js.getset(legacyCC.js, '_registeredClassNames', () => { const dump = {}; for (const id in _nameToClass) { diff --git a/cocos/core/utils/misc.ts b/cocos/core/utils/misc.ts index 727fe66072..515ee015b5 100644 --- a/cocos/core/utils/misc.ts +++ b/cocos/core/utils/misc.ts @@ -28,6 +28,7 @@ import { getClassName, getset } from './js'; import { EDITOR, DEV } from 'internal:constants'; +import { legacyCC } from '../global-exports'; export const BUILTIN_CLASSID_RE = /^(?:cc|dragonBones|sp|ccsg)\..+/; @@ -61,10 +62,10 @@ export function propertyDefine (ctor, sameNameGetSets, diffNameGetSets) { else { const getterFunc = np[getter]; if (DEV && !getterFunc) { - const clsName = (cc.Class._isCCClass(ctor) && getClassName(ctor)) || + const clsName = (legacyCC.Class._isCCClass(ctor) && getClassName(ctor)) || ctor.name || '(anonymous class)'; - cc.warnID(5700, propName, getter, clsName); + legacyCC.warnID(5700, propName, getter, clsName); } else { getset(np, propName, getterFunc, np[setter]); @@ -215,7 +216,7 @@ export function cloneable_DEV (obj) { // } // } -cc.misc = { +legacyCC.misc = { BUILTIN_CLASSID_RE, BASE64_VALUES, propertyDefine, diff --git a/cocos/core/utils/path.ts b/cocos/core/utils/path.ts index a6a17b8bdb..c335798669 100644 --- a/cocos/core/utils/path.ts +++ b/cocos/core/utils/path.ts @@ -24,6 +24,8 @@ THE SOFTWARE. */ +import { legacyCC } from '../global-exports'; + const EXTNAME_RE = /(\.[^\.\/\?\\]*)(\?.*)?$/; const DIRNAME_RE = /((.*)(\/|\\|\\\\))?(.*?\..*$)?/; const NORMALIZE_RE = /[^\.\/]+\/\.\.\//; @@ -156,5 +158,5 @@ export function stripSep (path: string) { } export function getSeperator () { - return cc.sys.os === cc.sys.OS_WINDOWS ? '\\' : '/'; + return legacyCC.sys.os === legacyCC.sys.OS_WINDOWS ? '\\' : '/'; } diff --git a/cocos/core/utils/prefab-helper.ts b/cocos/core/utils/prefab-helper.ts index 397849a92c..ecb6cd79c9 100644 --- a/cocos/core/utils/prefab-helper.ts +++ b/cocos/core/utils/prefab-helper.ts @@ -27,6 +27,7 @@ import { ccclass, property } from '../data/class-decorator'; import { Quat } from '../math'; import { EDITOR, SUPPORT_JIT } from 'internal:constants'; +import { legacyCC } from '../global-exports'; @ccclass('cc.PrefabInfo') export class PrefabInfo { @@ -67,7 +68,7 @@ export class PrefabInfo { // } } -cc._PrefabInfo = PrefabInfo; +legacyCC._PrefabInfo = PrefabInfo; // update node to make it sync with prefab export default function syncWithPrefab (node) { @@ -87,7 +88,7 @@ export default function syncWithPrefab (node) { // node.name += PrefabUtils.MISSING_PREFAB_SUFFIX; } else { - cc.errorID(3701, node.name); + legacyCC.errorID(3701, node.name); } node._prefab = null; return; @@ -106,7 +107,7 @@ export default function syncWithPrefab (node) { const _globalZOrder = node._globalZOrder; // instantiate prefab - cc.game._isCloning = true; + legacyCC.game._isCloning = true; if (SUPPORT_JIT) { _prefab.asset._doInstantiate(node); } @@ -119,9 +120,9 @@ export default function syncWithPrefab (node) { prefabRoot._iN$t = node; // instantiate prefab and apply to node - cc.instantiate._clone(prefabRoot, prefabRoot); + legacyCC.instantiate._clone(prefabRoot, prefabRoot); } - cc.game._isCloning = false; + legacyCC.game._isCloning = false; // restore preserved props node._objFlags = _objFlags; diff --git a/cocos/core/utils/profiler/profiler.ts b/cocos/core/utils/profiler/profiler.ts index c0b0fd959f..12cd8dbc43 100644 --- a/cocos/core/utils/profiler/profiler.ts +++ b/cocos/core/utils/profiler/profiler.ts @@ -38,6 +38,7 @@ import { Node } from '../../scene-graph/node'; import { ICounterOption } from './counter'; import { PerfCounter } from './perf-counter'; import { TEST } from 'internal:constants'; +import { legacyCC } from '../../global-exports'; const _characters = '0123456789. '; @@ -139,33 +140,33 @@ export class Profiler { this._rootNode.active = false; } - cc.director.off(cc.Director.EVENT_BEFORE_UPDATE, this.beforeUpdate, this); - cc.director.off(cc.Director.EVENT_AFTER_UPDATE, this.afterUpdate, this); - cc.director.off(cc.Director.EVENT_BEFORE_PHYSICS, this.beforePhysics, this); - cc.director.off(cc.Director.EVENT_AFTER_PHYSICS, this.afterPhysics, this); - cc.director.off(cc.Director.EVENT_BEFORE_DRAW, this.beforeDraw, this); - cc.director.off(cc.Director.EVENT_AFTER_DRAW, this.afterDraw, this); + legacyCC.director.off(legacyCC.Director.EVENT_BEFORE_UPDATE, this.beforeUpdate, this); + legacyCC.director.off(legacyCC.Director.EVENT_AFTER_UPDATE, this.afterUpdate, this); + legacyCC.director.off(legacyCC.Director.EVENT_BEFORE_PHYSICS, this.beforePhysics, this); + legacyCC.director.off(legacyCC.Director.EVENT_AFTER_PHYSICS, this.afterPhysics, this); + legacyCC.director.off(legacyCC.Director.EVENT_BEFORE_DRAW, this.beforeDraw, this); + legacyCC.director.off(legacyCC.Director.EVENT_AFTER_DRAW, this.afterDraw, this); this._showFPS = false; } } public showStats () { if (!this._showFPS) { - if (!this._device) { this._device = cc.director.root.device; } + if (!this._device) { this._device = legacyCC.director.root.device; } this.generateCanvas(); this.generateStats(); - cc.game.once(cc.Game.EVENT_ENGINE_INITED, this.generateNode, this); + legacyCC.game.once(legacyCC.Game.EVENT_ENGINE_INITED, this.generateNode, this); if (this._rootNode) { this._rootNode.active = true; } - cc.director.on(cc.Director.EVENT_BEFORE_UPDATE, this.beforeUpdate, this); - cc.director.on(cc.Director.EVENT_AFTER_UPDATE, this.afterUpdate, this); - cc.director.on(cc.Director.EVENT_BEFORE_PHYSICS, this.beforePhysics, this); - cc.director.on(cc.Director.EVENT_AFTER_PHYSICS, this.afterPhysics, this); - cc.director.on(cc.Director.EVENT_BEFORE_DRAW, this.beforeDraw, this); - cc.director.on(cc.Director.EVENT_AFTER_DRAW, this.afterDraw, this); + legacyCC.director.on(legacyCC.Director.EVENT_BEFORE_UPDATE, this.beforeUpdate, this); + legacyCC.director.on(legacyCC.Director.EVENT_AFTER_UPDATE, this.afterUpdate, this); + legacyCC.director.on(legacyCC.Director.EVENT_BEFORE_PHYSICS, this.beforePhysics, this); + legacyCC.director.on(legacyCC.Director.EVENT_AFTER_PHYSICS, this.afterPhysics, this); + legacyCC.director.on(legacyCC.Director.EVENT_BEFORE_DRAW, this.beforeDraw, this); + legacyCC.director.on(legacyCC.Director.EVENT_AFTER_DRAW, this.afterDraw, this); this._showFPS = true; this._canvasDone = true; @@ -260,7 +261,7 @@ export class Profiler { } this._rootNode = new Node('PROFILER_NODE'); - cc.game.addPersistRootNode(this._rootNode); + legacyCC.game.addPersistRootNode(this._rootNode); const cameraNode = new Node('Profiler_Camera'); cameraNode.setPosition(0, 0, 1); @@ -355,7 +356,7 @@ export class Profiler { } const now = performance.now(); - if (cc.director.isPaused()) { + if (legacyCC.director.isPaused()) { (this._stats.frame.counter as PerfCounter).start(now); } else { (this._stats.logic.counter as PerfCounter).end(now); @@ -431,4 +432,4 @@ export class Profiler { } export const profiler = new Profiler(); -cc.profiler = profiler; +legacyCC.profiler = profiler; diff --git a/cocos/core/value-types/bitmask.ts b/cocos/core/value-types/bitmask.ts index 1bc1d0edda..63d586eac8 100644 --- a/cocos/core/value-types/bitmask.ts +++ b/cocos/core/value-types/bitmask.ts @@ -29,6 +29,7 @@ import { value } from '../utils/js'; import { EDITOR, TEST } from 'internal:constants'; +import { legacyCC } from '../global-exports'; export function BitMask (obj: T): T { if ('__bitmask__' in obj) { @@ -57,7 +58,7 @@ export function BitMask (obj: T): T { const reverseKey: string = '' + val; if (key !== reverseKey) { if ((EDITOR || TEST) && reverseKey in obj && obj[reverseKey] !== key) { - cc.errorID(7100, reverseKey); + legacyCC.errorID(7100, reverseKey); continue; } value(obj, reverseKey, key); @@ -94,4 +95,4 @@ export function ccbitmask (bitmaskx) { value(bitmaskx, '__bitmask__', null, true); } -cc.BitMask = BitMask; +legacyCC.BitMask = BitMask; diff --git a/cocos/core/value-types/enum.ts b/cocos/core/value-types/enum.ts index bd24b9ef9d..663c6002ea 100644 --- a/cocos/core/value-types/enum.ts +++ b/cocos/core/value-types/enum.ts @@ -30,6 +30,7 @@ import { value } from '../utils/js'; import { EDITOR, TEST, DEV } from 'internal:constants'; +import { legacyCC } from '../global-exports'; /** * @en @@ -72,7 +73,7 @@ export function Enum (obj: T): T { const reverseKey: string = '' + val; if (key !== reverseKey) { if ((EDITOR || TEST) && reverseKey in obj && obj[reverseKey] !== key) { - cc.errorID(7100, reverseKey); + legacyCC.errorID(7100, reverseKey); continue; } value(obj, reverseKey, key); @@ -115,7 +116,7 @@ if (DEV) { THREE: -1, }); if (_TestEnum.ZERO !== 0 || _TestEnum.ONE !== 1 || _TestEnum.THREE !== 3) { - cc.errorID(7101); + legacyCC.errorID(7101); } } @@ -126,4 +127,4 @@ export function ccenum (enumx) { value(enumx, '__enums__', null, true); } -cc.Enum = Enum; +legacyCC.Enum = Enum; diff --git a/cocos/core/value-types/value-type.ts b/cocos/core/value-types/value-type.ts index a969e57057..9da1ae1e86 100644 --- a/cocos/core/value-types/value-type.ts +++ b/cocos/core/value-types/value-type.ts @@ -30,6 +30,7 @@ import { errorID } from '../platform/debug'; import * as js from '../utils/js'; +import { legacyCC } from '../global-exports'; /** * 所有值类型的基类。 @@ -78,4 +79,4 @@ export class ValueType { } js.setClassName('cc.ValueType', ValueType); -cc.ValueType = ValueType; +legacyCC.ValueType = ValueType; diff --git a/cocos/particle/billboard-component.ts b/cocos/particle/billboard-component.ts index 89fa1a89ec..82cbcd9b13 100644 --- a/cocos/particle/billboard-component.ts +++ b/cocos/particle/billboard-component.ts @@ -11,6 +11,7 @@ import { ccclass, help, executeInEditMode, menu, property } from '../core/data/c import { GFXAttributeName, GFXFormat, GFXPrimitiveMode } from '../core/gfx'; import { Color, toDegree, toRadian, Vec4 } from '../core/math'; import { Model } from '../core/renderer/scene/model'; +import { legacyCC } from '../core/global-exports'; @ccclass('cc.BillboardComponent') @help('i18n:cc.BillboardComponent') @@ -171,7 +172,7 @@ export class BillboardComponent extends Component { ], indices: [0, 1, 2, 1, 2, 3], }, undefined, { calculateBounds: false }); - this._model = cc.director.root.createModel(Model, this.node); + this._model = legacyCC.director.root.createModel(Model, this.node); this._model!.initialize(this.node); if (this._material == null) { this._material = new Material(); diff --git a/cocos/particle/index.ts b/cocos/particle/index.ts index 9e8bd92bb9..db9787ee95 100644 --- a/cocos/particle/index.ts +++ b/cocos/particle/index.ts @@ -7,6 +7,7 @@ import { LineComponent } from './line-component'; import { ParticleSystemComponent } from './particle-system-component'; import { ParticleUtils } from './particle-utils'; import './deprecated'; +import { legacyCC } from '../core/global-exports'; export { BillboardComponent, @@ -15,8 +16,8 @@ export { ParticleUtils }; -cc.ParticleSystemComponent = ParticleSystemComponent; -cc.BillboardComponent = BillboardComponent; -cc.LineComponent = LineComponent; +legacyCC.ParticleSystemComponent = ParticleSystemComponent; +legacyCC.BillboardComponent = BillboardComponent; +legacyCC.LineComponent = LineComponent; -cc.ParticleUtils = ParticleUtils; \ No newline at end of file +legacyCC.ParticleUtils = ParticleUtils; \ No newline at end of file diff --git a/cocos/particle/line-component.ts b/cocos/particle/line-component.ts index 2e456656ee..f68dcd1f0e 100644 --- a/cocos/particle/line-component.ts +++ b/cocos/particle/line-component.ts @@ -13,6 +13,7 @@ import { LineModel } from './models/line-model'; import { builtinResMgr } from '../core/3d/builtin'; import CurveRange from './animator/curve-range'; import GradientRange from './animator/gradient-range'; +import { legacyCC } from '../core/global-exports'; const CC_USE_WORLD_SPACE = 'CC_USE_WORLD_SPACE'; const define = { CC_USE_WORLD_SPACE: false }; @@ -201,7 +202,7 @@ export class LineComponent extends Component { } public onLoad () { - this._model = cc.director.root.createModel(LineModel); + this._model = legacyCC.director.root.createModel(LineModel); this._model!.initialize(this.node); this._model!.setCapacity(100); if (this._material == null) { diff --git a/cocos/particle/renderer/particle-system-renderer-base.ts b/cocos/particle/renderer/particle-system-renderer-base.ts index b8bd989487..1e2f021dea 100644 --- a/cocos/particle/renderer/particle-system-renderer-base.ts +++ b/cocos/particle/renderer/particle-system-renderer-base.ts @@ -4,6 +4,7 @@ import ParticleSystemRenderer from './particle-system-renderer-data'; import { Material } from '../../core/assets'; import { Particle, IParticleModule } from '../particle'; import { RenderMode } from '../enum'; +import { legacyCC } from '../../core/global-exports'; export interface IParticleSystemRenderer { onInit (ps: Component): void; @@ -57,7 +58,7 @@ export abstract class ParticleSystemRendererBase implements IParticleSystemRende public onDestroy () { if (this._model) { - cc.director.root.destroyModel(this._model); + legacyCC.director.root.destroyModel(this._model); this._model = null; } } @@ -85,7 +86,7 @@ export abstract class ParticleSystemRendererBase implements IParticleSystemRende protected _updateModel () { if (!this._model) { - this._model = cc.director.root.createModel(ParticleBatchModel); + this._model = legacyCC.director.root.createModel(ParticleBatchModel); this._model!.setCapacity(this._particleSystem.capacity); this._model!.visFlags = this._particleSystem.visibility; } diff --git a/cocos/particle/renderer/trail.ts b/cocos/particle/renderer/trail.ts index 2643e08ee6..6be2ef8f2c 100644 --- a/cocos/particle/renderer/trail.ts +++ b/cocos/particle/renderer/trail.ts @@ -18,6 +18,7 @@ import CurveRange from '../animator/curve-range'; import GradientRange from '../animator/gradient-range'; import { Space, TextureMode, TrailMode } from '../enum'; import { Particle } from '../particle'; +import { legacyCC } from '../../core/global-exports'; // tslint:disable: max-line-length const PRE_TRIANGLE_INDEX = 1; @@ -389,7 +390,7 @@ export default class TrailModule { public destroy () { this.destroySubMeshData(); if (this._trailModel) { - cc.director.root.destroyModel(this._trailModel); + legacyCC.director.root.destroyModel(this._trailModel); this._trailModel = null; } if (this._trailSegments) { @@ -620,7 +621,7 @@ export default class TrailModule { this._subMeshData.indexBuffer = indexBuffer; this._subMeshData.indirectBuffer = this._iaInfoBuffer; - this._trailModel = cc.director.root.createModel(Model); + this._trailModel = legacyCC.director.root.createModel(Model); this._trailModel!.initialize(this._particleSystem.node); this._trailModel!.visFlags = this._particleSystem.visibility; this._trailModel!.setSubModelMesh(0, this._subMeshData); diff --git a/cocos/physics/framework/index.ts b/cocos/physics/framework/index.ts index 52d224d7a9..5db0ee2df8 100644 --- a/cocos/physics/framework/index.ts +++ b/cocos/physics/framework/index.ts @@ -13,6 +13,7 @@ import { CylinderColliderComponent } from './components/collider/cylinder-collid import { MeshColliderComponent } from './components/collider/mesh-collider-component'; import { RigidBodyComponent } from './components/rigid-body-component'; import { ConstantForce } from './components/constant-force'; +import { legacyCC } from '../../core/global-exports'; export { PhysicsSystem, @@ -32,20 +33,19 @@ export { ConstantForce }; -cc.PhysicsSystem = PhysicsSystem; +legacyCC.PhysicsSystem = PhysicsSystem; -cc.ColliderComponent = ColliderComponent; -cc.BoxColliderComponent = BoxColliderComponent; -cc.SphereColliderComponent = SphereColliderComponent; +legacyCC.ColliderComponent = ColliderComponent; +legacyCC.BoxColliderComponent = BoxColliderComponent; +legacyCC.SphereColliderComponent = SphereColliderComponent; -cc.RigidBodyComponent = RigidBodyComponent; +legacyCC.RigidBodyComponent = RigidBodyComponent; -cc.PhysicMaterial = PhysicMaterial; -cc.PhysicsRayResult = PhysicsRayResult; -cc.ConstantForce = ConstantForce; +legacyCC.PhysicMaterial = PhysicMaterial; +legacyCC.PhysicsRayResult = PhysicsRayResult; +legacyCC.ConstantForce = ConstantForce; export * from './physics-interface'; export * from './physics-enum'; import './deprecated'; - diff --git a/cocos/physics/framework/physics-system.ts b/cocos/physics/framework/physics-system.ts index 5c11e27b1f..1ceda5dda7 100644 --- a/cocos/physics/framework/physics-system.ts +++ b/cocos/physics/framework/physics-system.ts @@ -12,6 +12,7 @@ import { Layers, RecyclePool } from '../../core'; import { ray } from '../../core/geometry'; import { PhysicsRayResult } from './physics-ray-result'; import { EDITOR, PHYSICS_BUILTIN, DEBUG, PHYSICS_CANNON, PHYSICS_AMMO } from 'internal:constants'; +import { legacyCC } from '../../core/global-exports'; /** * @en @@ -273,8 +274,8 @@ export class PhysicsSystem extends System { if (PHYSICS_BUILTIN || PHYSICS_CANNON || PHYSICS_AMMO) { director.on(Director.EVENT_INIT, function () { - const sys = new cc.PhysicsSystem(); - cc.PhysicsSystem._instance = sys; + const sys = new legacyCC.PhysicsSystem(); + legacyCC.PhysicsSystem._instance = sys; director.registerSystem(PhysicsSystem.ID, sys, 0); }); } diff --git a/cocos/terrain/terrain-asset.ts b/cocos/terrain/terrain-asset.ts index 4e9231f206..d6c24ab483 100644 --- a/cocos/terrain/terrain-asset.ts +++ b/cocos/terrain/terrain-asset.ts @@ -3,6 +3,7 @@ */ import { Asset } from '../core/assets'; import { ccclass } from '../core/data/class-decorator'; +import { legacyCC } from '../core/global-exports'; export const TERRAIN_DATA_VERSION = 0x01010001; export const TERRAIN_DATA_VERSION2 = 0x01010002; @@ -179,8 +180,8 @@ export class TerrainAsset extends Asset{ set _nativeAsset (value: ArrayBuffer) { if (this._data && this._data.byteLength === value.byteLength) { this._data.set(new Uint8Array(value)); - if (cc.loader._cache[this.nativeUrl]) { - cc.loader._cache[this.nativeUrl].content = this._data.buffer; + if (legacyCC.loader._cache[this.nativeUrl]) { + legacyCC.loader._cache[this.nativeUrl].content = this._data.buffer; } } else { diff --git a/cocos/terrain/terrain.ts b/cocos/terrain/terrain.ts index 6418a88eee..a9de00eb2f 100644 --- a/cocos/terrain/terrain.ts +++ b/cocos/terrain/terrain.ts @@ -22,6 +22,7 @@ import { Root } from '../core/root'; import { PrivateNode } from '../core/scene-graph/private-node'; import { HeightField } from './height-field'; import { TerrainAsset, TerrainLayerInfo } from './terrain-asset'; +import { legacyCC } from '../core/global-exports'; export const TERRAIN_MAX_LEVELS = 4; export const TERRAIN_MAX_BLEND_LAYERS = 4; @@ -106,7 +107,7 @@ export class TerrainRenderable extends RenderableComponent { public destroy () { this._invalidMaterial(); if (this._model != null) { - cc.director.root.destroyModel(this._model); + legacyCC.director.root.destroyModel(this._model); this._model = null; } @@ -136,7 +137,7 @@ export class TerrainRenderable extends RenderableComponent { this._currentMaterial = new Material(); this._currentMaterial.initialize({ - effectAsset: cc.EffectAsset.get('builtin-terrain'), + effectAsset: legacyCC.EffectAsset.get('builtin-terrain'), defines: block._getMaterialDefines(nlayers), }); @@ -223,7 +224,7 @@ export class TerrainBlock { // @ts-ignore this._node.setParent(this._terrain.node); // @ts-ignore - this._node._objFlags |= cc.Object.Flags.DontSave; + this._node._objFlags |= legacyCC.Object.Flags.DontSave; this._renderable = this._node.addComponent(TerrainRenderable) as TerrainRenderable; } @@ -270,7 +271,7 @@ export class TerrainBlock { const subMesh = this._renderable._meshData = new RenderingSubMesh([vertexBuffer], gfxAttributes, GFXPrimitiveMode.TRIANGLE_LIST); subMesh.indexBuffer = this._terrain.getSharedIndexBuffer() || undefined; - this._renderable._model = (cc.director.root as Root).createModel(Model); + this._renderable._model = (legacyCC.director.root as Root).createModel(Model); this._renderable._model.initialize(this._node); this._renderable._getRenderScene().addModel(this._renderable._model); @@ -320,7 +321,7 @@ export class TerrainBlock { mtl.setProperty('detailMap0', l0 != null ? l0.detailMap : null); } else { - mtl.setProperty('detailMap0', cc.builtinResMgr.get('default-texture')); + mtl.setProperty('detailMap0', legacyCC.builtinResMgr.get('default-texture')); } } else if (nlayers === 1) { @@ -848,7 +849,7 @@ export class Terrain extends Component { } public onLoad () { - const gfxDevice = cc.director.root.device as GFXDevice; + const gfxDevice = legacyCC.director.root.device as GFXDevice; // initialize shared index buffer const indexData = new Uint16Array(TERRAIN_BLOCK_TILE_COMPLEXITY * TERRAIN_BLOCK_TILE_COMPLEXITY * 6); @@ -1315,7 +1316,7 @@ export class Terrain extends Component { for (const i of this._asset.layerInfos) { const layer = new TerrainLayer(); layer.tileSize = i.tileSize; - cc.loader.loadRes(i.detailMap, Texture2D, (err, asset) => { + legacyCC.loader.loadRes(i.detailMap, Texture2D, (err, asset) => { layer.detailMap = asset; }); diff --git a/cocos/tween/actions/action-manager.ts b/cocos/tween/actions/action-manager.ts index 5b16b47e9c..f08c429587 100644 --- a/cocos/tween/actions/action-manager.ts +++ b/cocos/tween/actions/action-manager.ts @@ -33,6 +33,7 @@ import * as js from '../../core/utils/js'; import { errorID } from '../../core/platform/debug'; import { Action } from './action'; import { Node } from '../../core'; +import { legacyCC } from '../../core/global-exports'; let ID_COUNTER = 0; @@ -216,10 +217,10 @@ export class ActionManager { * @param {Node} target */ removeActionByTag (tag: number, target: Node) { - if (tag === cc.Action.TAG_INVALID) - cc.logID(1002); + if (tag === legacyCC.Action.TAG_INVALID) + legacyCC.logID(1002); - cc.assertID(target, 1003); + legacyCC.assertID(target, 1003); var element = this._hashTargets[target.uuid]; @@ -244,8 +245,8 @@ export class ActionManager { * @return {Action|null} return the Action with the given tag on success */ getActionByTag (tag: number, target: Node): Action | null { - if (tag === cc.Action.TAG_INVALID) - cc.logID(1004); + if (tag === legacyCC.Action.TAG_INVALID) + legacyCC.logID(1004); var element = this._hashTargets[target.uuid]; if (element) { @@ -256,7 +257,7 @@ export class ActionManager { return action; } } - cc.logID(1005, tag); + legacyCC.logID(1005, tag); } return null; } @@ -371,7 +372,7 @@ export class ActionManager { * @method purgeSharedManager */ purgeSharedManager () { - cc.director.getScheduler().unscheduleUpdate(this); + legacyCC.director.getScheduler().unscheduleUpdate(this); } //protected diff --git a/cocos/tween/tween-action.ts b/cocos/tween/tween-action.ts index 450498ab3a..7a5486b64f 100644 --- a/cocos/tween/tween-action.ts +++ b/cocos/tween/tween-action.ts @@ -5,6 +5,7 @@ import { warnID, warn, easing } from '../core'; import { ActionInterval } from './actions/action-interval'; import { ITweenOption } from './export-api'; +import { legacyCC } from '../core/global-exports'; /** adapter */ function TweenEasinAdapter (easingName: string) { @@ -50,7 +51,7 @@ function TweenEasinAdapter (easingName: string) { /** checker */ function TweenOptionChecker (opts: ITweenOption) { const header = ' [Tween:] '; - const message = ' option is not support in v' + cc.ENGINE_VERSION; + const message = ' option is not support in v' + legacyCC.ENGINE_VERSION; if (opts['delay']) { warn(header + 'delay' + message); } diff --git a/cocos/tween/tween.ts b/cocos/tween/tween.ts index 2456af4d0d..a531fa8374 100644 --- a/cocos/tween/tween.ts +++ b/cocos/tween/tween.ts @@ -10,6 +10,7 @@ import { Action } from './actions/action'; import { ITweenOption } from './export-api'; import { TweenAction } from './tween-action'; import { SetAction } from './set-action'; +import { legacyCC } from '../core/global-exports'; /** * @en @@ -428,7 +429,7 @@ export class Tween { return spawn.apply(spawn, tmp_args as any); } } -cc.Tween = Tween; +legacyCC.Tween = Tween; /** @@ -448,7 +449,7 @@ cc.Tween = Tween; export function tween (target?: object) { return new Tween(target); } -cc.tween = tween; +legacyCC.tween = tween; /** * @en @@ -461,4 +462,4 @@ export function tweenUtil (target?: object) { warn("tweenUtil' is deprecated, please use 'tween' instead "); return new Tween(target); } -cc.tweenUtil = tweenUtil; \ No newline at end of file +legacyCC.tweenUtil = tweenUtil; \ No newline at end of file diff --git a/cocos/ui/assembler/label/bmfontUtils.ts b/cocos/ui/assembler/label/bmfontUtils.ts index bf9678727a..bca193282d 100644 --- a/cocos/ui/assembler/label/bmfontUtils.ts +++ b/cocos/ui/assembler/label/bmfontUtils.ts @@ -34,6 +34,7 @@ import { Rect, Size, Vec2 } from '../../../core/math'; import { HorizontalTextAlignment, VerticalTextAlignment } from '../../components/label-component'; import { LabelComponent, Overflow } from '../../components/label-component'; import { js } from '../../../core/utils'; +import { legacyCC } from '../../../core/global-exports'; class FontLetterDefinition { public u = 0; @@ -96,7 +97,7 @@ export class FontAtlas { } } -cc.FontAtlas = FontAtlas; +legacyCC.FontAtlas = FontAtlas; class LetterInfo { public char = ''; diff --git a/cocos/ui/components/button-component.ts b/cocos/ui/components/button-component.ts index 52d3f9f07b..5cdbba558e 100644 --- a/cocos/ui/components/button-component.ts +++ b/cocos/ui/components/button-component.ts @@ -40,6 +40,7 @@ import { Node } from '../../core/scene-graph/node'; import { SpriteComponent } from './sprite-component'; import { UIRenderComponent } from '../../core/components/ui-base/ui-render-component'; import { EDITOR } from 'internal:constants'; +import { legacyCC } from '../../core/global-exports'; const _tempColor = new Color(); @@ -866,7 +867,7 @@ export class ButtonComponent extends Component { } -cc.ButtonComponent = ButtonComponent; +legacyCC.ButtonComponent = ButtonComponent; /** * @zh diff --git a/cocos/ui/components/editbox/edit-box-component.ts b/cocos/ui/components/editbox/edit-box-component.ts index 138583292d..3076e1677e 100644 --- a/cocos/ui/components/editbox/edit-box-component.ts +++ b/cocos/ui/components/editbox/edit-box-component.ts @@ -44,6 +44,7 @@ import { EditBoxImplBase } from './edit-box-impl-base'; import { InputFlag, InputMode, KeyboardReturnType } from './types'; import { sys } from '../../../core/platform/sys'; import { EDITOR } from 'internal:constants'; +import { legacyCC } from '../../../core/global-exports'; const LEFT_PADDING = 2; @@ -864,7 +865,7 @@ if (sys.isBrowser){ EditBoxComponent._EditBoxImpl = EditBoxImpl; } -cc.EditBoxComponent = EditBoxComponent; +legacyCC.EditBoxComponent = EditBoxComponent; /** * @en diff --git a/cocos/ui/components/graphics-component.ts b/cocos/ui/components/graphics-component.ts index 909786a8fc..5421d3a825 100644 --- a/cocos/ui/components/graphics-component.ts +++ b/cocos/ui/components/graphics-component.ts @@ -39,6 +39,7 @@ import { IAssembler } from '../../core/renderer/ui/base'; import { UI } from '../../core/renderer/ui/ui'; import { LineCap, LineJoin } from '../assembler/graphics/types'; import { Impl } from '../assembler/graphics/webgl/impl'; +import { legacyCC } from '../../core/global-exports'; const _matInsInfo: IMaterialInstanceInfo = { parent: null!, @@ -617,4 +618,4 @@ export class GraphicsComponent extends UIRenderComponent { } } -cc.GraphicsComponent = GraphicsComponent; +legacyCC.GraphicsComponent = GraphicsComponent; diff --git a/cocos/ui/components/label-component.ts b/cocos/ui/components/label-component.ts index a1f449c91d..82122efd80 100644 --- a/cocos/ui/components/label-component.ts +++ b/cocos/ui/components/label-component.ts @@ -39,6 +39,7 @@ import { UIRenderComponent } from '../../core/components/ui-base/ui-render-compo import { warnID } from '../../core/platform/debug'; import { sys } from '../../core/platform/sys'; import { EDITOR } from 'internal:constants'; +import { legacyCC } from '../../core/global-exports'; /** * @en Enum for horizontal text alignment. @@ -846,4 +847,4 @@ export class LabelComponent extends UIRenderComponent { } } -cc.LabelComponent = LabelComponent; +legacyCC.LabelComponent = LabelComponent; diff --git a/cocos/ui/components/label-outline-component.ts b/cocos/ui/components/label-outline-component.ts index 2862ee88e4..13f4f81c68 100644 --- a/cocos/ui/components/label-outline-component.ts +++ b/cocos/ui/components/label-outline-component.ts @@ -32,6 +32,7 @@ import { Component } from '../../core/components/component'; import { ccclass, help, executionOrder, menu, property } from '../../core/data/class-decorator'; import { Color } from '../../core/math'; import { LabelComponent } from './label-component'; +import { legacyCC } from '../../core/global-exports'; /** * @en @@ -125,4 +126,4 @@ export class LabelOutlineComponent extends Component { } } -cc.LabelOutlineComponent = LabelOutlineComponent; +legacyCC.LabelOutlineComponent = LabelOutlineComponent; diff --git a/cocos/ui/components/layout-component.ts b/cocos/ui/components/layout-component.ts index dffde3ec93..01466f00f6 100644 --- a/cocos/ui/components/layout-component.ts +++ b/cocos/ui/components/layout-component.ts @@ -38,6 +38,7 @@ import { director, Director } from '../../core/director'; import { TransformBit } from '../../core/scene-graph/node-enum'; import { Node } from '../../core'; import { EDITOR } from 'internal:constants'; +import { legacyCC } from '../../core/global-exports'; const NodeEvent = SystemEventType; /** * @en Enum for layout. @@ -292,7 +293,7 @@ export class LayoutComponent extends Component { return; } - if (EDITOR && this._resizeMode === ResizeMode.CONTAINER && !cc.engine.isPlaying) { + if (EDITOR && this._resizeMode === ResizeMode.CONTAINER && !legacyCC.engine.isPlaying) { // const reLayouted = _Scene.DetectConflict.checkConflict_Layout(this); // if (reLayouted) { // return; @@ -996,7 +997,7 @@ export class LayoutComponent extends Component { parentTransform.convertToNodeSpaceAR(_tempPos, rightTopInParentSpace); Vec3.set(rightTopInParentSpace, rightTopInParentSpace.x + this._paddingRight, rightTopInParentSpace.y + this._paddingTop, rightTopInParentSpace.z); - const newSize = cc.size(parseFloat((rightTopInParentSpace.x - leftBottomInParentSpace.x).toFixed(2)), + const newSize = legacyCC.size(parseFloat((rightTopInParentSpace.x - leftBottomInParentSpace.x).toFixed(2)), parseFloat((rightTopInParentSpace.y - leftBottomInParentSpace.y).toFixed(2))); this.node.getPosition(_tempPos); @@ -1203,4 +1204,4 @@ export class LayoutComponent extends Component { } -cc.LayoutComponent = LayoutComponent; +legacyCC.LayoutComponent = LayoutComponent; diff --git a/cocos/ui/components/mask-component.ts b/cocos/ui/components/mask-component.ts index b12815404c..812e38b085 100644 --- a/cocos/ui/components/mask-component.ts +++ b/cocos/ui/components/mask-component.ts @@ -40,6 +40,7 @@ import { GraphicsComponent } from './graphics-component'; import { TransformBit } from '../../core/scene-graph/node-enum'; import { Material } from '@cocos/cannon'; import { Game } from '../../core'; +import { legacyCC } from '../../core/global-exports'; const _worldMatrix = new Mat4(); const _vec2_temp = new Vec2(); @@ -148,8 +149,8 @@ export class MaskComponent extends UIRenderComponent { } set inverted (value) { - if (cc.game.renderType === Game.RENDER_TYPE_CANVAS) { - cc.warnID(4202); + if (legacyCC.game.renderType === Game.RENDER_TYPE_CANVAS) { + legacyCC.warnID(4202); return; } @@ -491,4 +492,4 @@ export class MaskComponent extends UIRenderComponent { } // tslint:disable-next-line -cc.MaskComponent = MaskComponent; +legacyCC.MaskComponent = MaskComponent; diff --git a/cocos/ui/components/page-view-component.ts b/cocos/ui/components/page-view-component.ts index e4a8c6b318..44f96e24cc 100644 --- a/cocos/ui/components/page-view-component.ts +++ b/cocos/ui/components/page-view-component.ts @@ -41,6 +41,7 @@ import { extendsEnum } from '../../core/data/utils/extends-enum'; import { EventType as ScrollEventType } from './scroll-view-component'; import { Node } from '../../core'; import { EDITOR } from 'internal:constants'; +import { legacyCC } from '../../core/global-exports'; const _temp_vec2 = new Vec2(); @@ -791,7 +792,7 @@ export class PageViewComponent extends ScrollViewComponent { } -cc.PageViewComponent = PageViewComponent; +legacyCC.PageViewComponent = PageViewComponent; /** * @en diff --git a/cocos/ui/components/page-view-indicator-component.ts b/cocos/ui/components/page-view-indicator-component.ts index 0df1a6ef3c..93fd026df9 100644 --- a/cocos/ui/components/page-view-indicator-component.ts +++ b/cocos/ui/components/page-view-indicator-component.ts @@ -38,6 +38,7 @@ import { LayoutComponent } from './layout-component'; import { PageViewComponent } from './page-view-component'; import { SpriteComponent } from './sprite-component'; import { UIRenderComponent } from '../../core/components/ui-base/ui-render-component'; +import { legacyCC } from '../../core/global-exports'; const _color = new Color(); @@ -273,4 +274,4 @@ export class PageViewIndicatorComponent extends Component { } } -cc.PageViewIndicatorComponent = PageViewIndicatorComponent; +legacyCC.PageViewIndicatorComponent = PageViewIndicatorComponent; diff --git a/cocos/ui/components/progress-bar-component.ts b/cocos/ui/components/progress-bar-component.ts index 298cd1b4d0..1ee6ee0ace 100644 --- a/cocos/ui/components/progress-bar-component.ts +++ b/cocos/ui/components/progress-bar-component.ts @@ -35,6 +35,7 @@ import { Enum } from '../../core/value-types'; import { clamp01 } from '../../core/math/utils'; import { SpriteComponent } from './sprite-component'; import { warn } from '../../core/platform/debug'; +import { legacyCC } from '../../core/global-exports'; /** * @en @@ -349,4 +350,4 @@ export class ProgressBarComponent extends Component { } } -cc.ProgressBarComponent = ProgressBarComponent; +legacyCC.ProgressBarComponent = ProgressBarComponent; diff --git a/cocos/ui/components/rich-text-component.ts b/cocos/ui/components/rich-text-component.ts index 2055899d4d..4c9c141627 100644 --- a/cocos/ui/components/rich-text-component.ts +++ b/cocos/ui/components/rich-text-component.ts @@ -44,6 +44,7 @@ import { UITransformComponent } from '../../core/components/ui-base/ui-transform import { assert, warnID } from '../../core/platform/debug'; import { loader } from '../../core/load-pipeline'; import { EDITOR, DEV } from 'internal:constants'; +import { legacyCC } from '../../core/global-exports'; const _htmlTextParser = new HtmlTextParser(); const RichTextChildName = 'RICHTEXT_CHILD'; @@ -82,7 +83,7 @@ const pool = new Pool((labelSeg: ILabelSegment) => { if (DEV) { assert(!labelSeg.node.parent, 'Recycling node\'s parent should be null!'); } - if (!cc.isValid(labelSeg.node)) { + if (!legacyCC.isValid(labelSeg.node)) { return false; } else if (labelSeg.node.getComponent(LabelOutlineComponent)) { @@ -1030,4 +1031,4 @@ export class RichTextComponent extends UIComponent { } } -cc.RichTextComponent = RichTextComponent; +legacyCC.RichTextComponent = RichTextComponent; diff --git a/cocos/ui/components/scroll-bar-component.ts b/cocos/ui/components/scroll-bar-component.ts index 4fa713b924..5ccf6dfb17 100644 --- a/cocos/ui/components/scroll-bar-component.ts +++ b/cocos/ui/components/scroll-bar-component.ts @@ -36,6 +36,7 @@ import { clamp01 } from '../../core/math/utils'; import { ScrollViewComponent } from './scroll-view-component'; import { SpriteComponent } from './sprite-component'; import { Node } from '../../core'; +import { legacyCC } from '../../core/global-exports'; const GETTINGSHORTERFACTOR = 20; const ZERO = new Vec3(); @@ -495,4 +496,4 @@ export class ScrollBarComponent extends Component { } } -cc.ScrollBarComponent = ScrollBarComponent; +legacyCC.ScrollBarComponent = ScrollBarComponent; diff --git a/cocos/ui/components/scroll-view-component.ts b/cocos/ui/components/scroll-view-component.ts index b84a872834..e91d68395f 100644 --- a/cocos/ui/components/scroll-view-component.ts +++ b/cocos/ui/components/scroll-view-component.ts @@ -40,6 +40,7 @@ import { Node } from '../../core/scene-graph/node'; import { director, Director } from '../../core/director'; import { TransformBit } from '../../core/scene-graph/node-enum'; import { EDITOR } from 'internal:constants'; +import { legacyCC } from '../../core/global-exports'; const NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED = 5; const OUT_OF_BOUNDARY_BREAKING_FACTOR = 0.05; @@ -1753,7 +1754,7 @@ export class ScrollViewComponent extends ViewGroupComponent { } } -cc.ScrollViewComponent = ScrollViewComponent; +legacyCC.ScrollViewComponent = ScrollViewComponent; /** * @en diff --git a/cocos/ui/components/slider-component.ts b/cocos/ui/components/slider-component.ts index aa4f3bb1cc..66b6ac987c 100644 --- a/cocos/ui/components/slider-component.ts +++ b/cocos/ui/components/slider-component.ts @@ -36,6 +36,7 @@ import { ccenum } from '../../core/value-types/enum'; import { clamp01 } from '../../core/math/utils'; import { SpriteComponent } from './sprite-component'; import { EDITOR } from 'internal:constants'; +import { legacyCC } from '../../core/global-exports'; const _tempPos = new Vec3(); /** @@ -321,7 +322,7 @@ export class SliderComponent extends Component { } } -cc.SliderComponent = SliderComponent; +legacyCC.SliderComponent = SliderComponent; /** * @zh diff --git a/cocos/ui/components/sprite-component.ts b/cocos/ui/components/sprite-component.ts index 34571acc0f..f18bc08b03 100644 --- a/cocos/ui/components/sprite-component.ts +++ b/cocos/ui/components/sprite-component.ts @@ -37,6 +37,7 @@ import { clamp } from '../../core/math/utils'; import { UI } from '../../core/renderer/ui/ui'; import { UIRenderComponent, InstanceMaterialType } from '../../core/components/ui-base/ui-render-component'; import { EDITOR } from 'internal:constants'; +import { legacyCC } from '../../core/global-exports'; /** * @en @@ -654,7 +655,7 @@ export class SpriteComponent extends UIRenderComponent { const spriteFrame = this._spriteFrame; const material = this._material; // WebGL - if (cc.game.renderType !== cc.game.RENDER_TYPE_CANVAS) { + if (legacyCC.game.renderType !== legacyCC.game.RENDER_TYPE_CANVAS) { // if (!material) { // this._material = cc.builtinResMgr.get('sprite-material'); // material = this._material; @@ -773,4 +774,4 @@ export class SpriteComponent extends UIRenderComponent { } } -cc.SpriteComponent = SpriteComponent; +legacyCC.SpriteComponent = SpriteComponent; diff --git a/cocos/ui/components/toggle-component.ts b/cocos/ui/components/toggle-component.ts index f51ce4041c..05b8dbc05d 100644 --- a/cocos/ui/components/toggle-component.ts +++ b/cocos/ui/components/toggle-component.ts @@ -36,6 +36,7 @@ import { ToggleContainerComponent } from './toggle-container-component'; import { extendsEnum } from '../../core/data/utils/extends-enum'; import { EventType as ButtonEventType } from './button-component'; import { EDITOR } from 'internal:constants'; +import { legacyCC } from '../../core/global-exports'; enum EventType { TOGGLE = 'toggle', @@ -282,7 +283,7 @@ export class ToggleComponent extends ButtonComponent { } } -cc.ToggleComponent = ToggleComponent; +legacyCC.ToggleComponent = ToggleComponent; /** * @zh diff --git a/cocos/ui/components/toggle-container-component.ts b/cocos/ui/components/toggle-container-component.ts index 96197060af..b706252bb3 100644 --- a/cocos/ui/components/toggle-container-component.ts +++ b/cocos/ui/components/toggle-container-component.ts @@ -31,6 +31,7 @@ import { Component, EventHandler as ComponentEventHandler } from '../../core/components'; import { ccclass, help, executeInEditMode, executionOrder, menu, property } from '../../core/data/class-decorator'; import { ToggleComponent} from './toggle-component'; +import { legacyCC } from '../../core/global-exports'; /** * @en @@ -182,4 +183,4 @@ export class ToggleContainerComponent extends Component { } } -cc.ToggleContainerComponent = ToggleContainerComponent; +legacyCC.ToggleContainerComponent = ToggleContainerComponent; diff --git a/cocos/ui/components/ui-model-component.ts b/cocos/ui/components/ui-model-component.ts index eab21f5a2c..4f6deb75c4 100644 --- a/cocos/ui/components/ui-model-component.ts +++ b/cocos/ui/components/ui-model-component.ts @@ -36,6 +36,7 @@ import { director } from '../../core/director'; import { RenderPriority } from '../../core/pipeline/define'; import { UI } from '../../core/renderer/ui/ui'; import { Model } from '../../core/renderer'; +import { legacyCC } from '../../core/global-exports'; /** * @en @@ -98,7 +99,7 @@ export class UIModelComponent extends UIComponent { } this._modelComponent._sceneGetter = null; - if (cc.isValid(this._modelComponent, true)) { + if (legacyCC.isValid(this._modelComponent, true)) { (this._modelComponent as any)._attachToScene(); } this._models = null; @@ -166,4 +167,4 @@ export class UIModelComponent extends UIComponent { } } -cc.UIModelComponent = UIModelComponent; +legacyCC.UIModelComponent = UIModelComponent; diff --git a/cocos/ui/components/ui-reorder-component.ts b/cocos/ui/components/ui-reorder-component.ts index 2135b98631..54b25957da 100644 --- a/cocos/ui/components/ui-reorder-component.ts +++ b/cocos/ui/components/ui-reorder-component.ts @@ -29,6 +29,7 @@ import { ccclass, help, disallowMultiple, executeInEditMode, executionOrder, menu } from '../../core/data/class-decorator'; import { UIComponent } from '../../core/components/ui-base/ui-component'; +import { legacyCC } from '../../core/global-exports'; /** * @zh @@ -44,4 +45,4 @@ import { UIComponent } from '../../core/components/ui-base/ui-component'; export class UIReorderComponent extends UIComponent { } -cc.UIReorderComponent = UIReorderComponent; +legacyCC.UIReorderComponent = UIReorderComponent; diff --git a/cocos/ui/components/view-group-component.ts b/cocos/ui/components/view-group-component.ts index 246e05c59b..3f642d685e 100644 --- a/cocos/ui/components/view-group-component.ts +++ b/cocos/ui/components/view-group-component.ts @@ -44,6 +44,7 @@ import { Component } from '../../core/components'; import { ccclass, executionOrder } from '../../core/data/class-decorator'; +import { legacyCC } from '../../core/global-exports'; @ccclass('cc.ViewGroupComponent') @executionOrder(110) @@ -51,4 +52,4 @@ export class ViewGroupComponent extends Component { } -cc.ViewGroupComponent = ViewGroupComponent; +legacyCC.ViewGroupComponent = ViewGroupComponent; diff --git a/cocos/ui/components/webview/webView-component.ts b/cocos/ui/components/webview/webView-component.ts index e2627be38e..0e55dd14fc 100644 --- a/cocos/ui/components/webview/webView-component.ts +++ b/cocos/ui/components/webview/webView-component.ts @@ -33,6 +33,7 @@ import { ccclass, help, executionOrder, menu, property } from '../../../core/dat import { UIComponent } from '../../../core/components/ui-base/ui-component'; import { WebViewEventType, WebViewImpl } from './webview-impl'; import { EDITOR } from 'internal:constants'; +import { legacyCC } from '../../../core/global-exports'; /** * @en WebView event type @@ -250,7 +251,7 @@ export class WebviewComponent extends UIComponent { } } -cc.WebviewComponent = WebviewComponent; +legacyCC.WebviewComponent = WebviewComponent; /** * @en if you don't need the WebView and it isn't in any running Scene, you should diff --git a/cocos/ui/components/webview/webview-impl.ts b/cocos/ui/components/webview/webview-impl.ts index 19344b1074..e2375a7106 100644 --- a/cocos/ui/components/webview/webview-impl.ts +++ b/cocos/ui/components/webview/webview-impl.ts @@ -36,6 +36,7 @@ import { logID, log } from '../../../core/platform/debug'; import { view } from '../../../core/platform/view'; import { Node } from '../../../core'; import { EDITOR } from 'internal:constants'; +import { legacyCC } from '../../../core/global-exports'; const _mat4_temp = new Mat4(); @@ -125,9 +126,9 @@ export class WebViewImpl { public removeDom () { const div = this._div; if (div) { - const hasChild = misc.contains(cc.game.container, div); + const hasChild = misc.contains(legacyCC.game.container, div); if (hasChild) { - cc.game.container.removeChild(div); + legacyCC.game.container.removeChild(div); } this._div = null; @@ -341,7 +342,7 @@ export class WebViewImpl { scaleX /= dpr; scaleY /= dpr; - const container = cc.game.container; + const container = legacyCC.game.container; const a = _mat4_temp.m00 * scaleX; const b = _mat4_temp.m01; const c = _mat4_temp.m04; @@ -454,7 +455,7 @@ export class WebViewImpl { this._div.style.overflow = 'scroll'; this._iframe.style.border = 'none'; - cc.game.container.appendChild(this._div); + legacyCC.game.container.appendChild(this._div); this._updateVisibility(); } diff --git a/cocos/ui/components/widget-component.ts b/cocos/ui/components/widget-component.ts index 2de090fa05..5d86a21987 100644 --- a/cocos/ui/components/widget-component.ts +++ b/cocos/ui/components/widget-component.ts @@ -41,6 +41,7 @@ import { Node } from '../../core/scene-graph/node'; import { ccenum } from '../../core/value-types/enum'; import { TransformBit } from '../../core/scene-graph/node-enum'; import { EDITOR, DEV } from 'internal:constants'; +import { legacyCC } from '../../core/global-exports'; const _zeroVec3 = new Vec3(); @@ -232,7 +233,7 @@ export class WidgetComponent extends Component { this._registerTargetEvents(); if (EDITOR /*&& !cc.engine._isPlaying*/ && this.node.parent) { // adjust the offsets to keep the size and position unchanged after target changed - cc._widgetManager.updateOffsetsToStayPut(this); + legacyCC._widgetManager.updateOffsetsToStayPut(this); } this._validateTargetInDEV(); @@ -785,7 +786,7 @@ export class WidgetComponent extends Component { * ``` */ public updateAlignment () { - cc._widgetManager.updateAlignment(this.node as Node); + legacyCC._widgetManager.updateAlignment(this.node as Node); } public _validateTargetInDEV () { @@ -811,13 +812,13 @@ export class WidgetComponent extends Component { public onEnable () { this.node.getPosition(this._lastPos); this.node.getContentSize(this._lastSize); - cc._widgetManager.add(this); + legacyCC._widgetManager.add(this); this._registerEvent(); this._registerTargetEvents(); } public onDisable () { - cc._widgetManager.remove(this); + legacyCC._widgetManager.remove(this); this._unregisterEvent(); this._unregisterTargetEvents(); } @@ -831,7 +832,7 @@ export class WidgetComponent extends Component { return; } - if (cc._widgetManager.isAligning) { + if (legacyCC._widgetManager.isAligning) { return; } @@ -884,7 +885,7 @@ export class WidgetComponent extends Component { // return; // } - if (cc._widgetManager.isAligning) { + if (legacyCC._widgetManager.isAligning) { return; } @@ -989,7 +990,7 @@ export class WidgetComponent extends Component { target.on(SystemEventType.TRANSFORM_CHANGED, this._targetChangedOperation, this); target.on(SystemEventType.SIZE_CHANGED, this._targetChangedOperation, this); } else { - cc.warnID(6501, this.node.name); + legacyCC.warnID(6501, this.node.name); } } } @@ -1049,7 +1050,7 @@ export class WidgetComponent extends Component { if (EDITOR && this.node.parent) { // adjust the offsets to keep the size and position unchanged after alignment changed - cc._widgetManager.updateOffsetsToStayPut(this, flag); + legacyCC._widgetManager.updateOffsetsToStayPut(this, flag); } } else { if (isHorizontal) { @@ -1078,6 +1079,6 @@ export class WidgetComponent extends Component { } // @ts-ignore -cc.WidgetComponent = WidgetComponent; +legacyCC.WidgetComponent = WidgetComponent; // cc.Widget = module.exports = Widget; diff --git a/cocos/ui/components/widget-manager.ts b/cocos/ui/components/widget-manager.ts index e29fc5eb86..702b721ccb 100644 --- a/cocos/ui/components/widget-manager.ts +++ b/cocos/ui/components/widget-manager.ts @@ -40,6 +40,7 @@ import { array } from '../../core/utils/js'; import { AlignFlags, AlignMode, computeInverseTransForTarget, getReadonlyNodeSize, WidgetComponent } from './widget-component'; import { UITransformComponent } from '../../core/components'; import { EDITOR, DEV } from 'internal:constants'; +import { legacyCC } from '../../core/global-exports'; const _tempPos = new Vec3(); const _defaultAnchor = new Vec2(); @@ -211,7 +212,7 @@ function visitNode (node: any) { if ((!EDITOR || widgetManager.animationState!.animatedSinceLastFrame) && widget.alignMode !== AlignMode.ALWAYS) { widget.enabled = false; } else { - if (cc.isValid(node, true)) { + if (legacyCC.isValid(node, true)) { activeWidgets.push(widget); } else { return; @@ -341,7 +342,7 @@ function updateAlignment (node: Node) { const canvasList: CanvasComponent[] = []; -export const widgetManager = cc._widgetManager = { +export const widgetManager = legacyCC._widgetManager = { isAligning: false, _nodesOrderDirty: false, _activeWidgetsIterator: new array.MutableForwardIterator(activeWidgets), @@ -416,7 +417,7 @@ export const widgetManager = cc._widgetManager = { } if (!widgetParent.getComponent(UITransformComponent)) { - cc.warnID(6501, widget.node.name); + legacyCC.warnID(6501, widget.node.name); return; } diff --git a/cocos/ui/index.ts b/cocos/ui/index.ts index e2a16875c1..f6f81c01c9 100644 --- a/cocos/ui/index.ts +++ b/cocos/ui/index.ts @@ -21,6 +21,7 @@ import { import { MeshBuffer } from '../core/renderer/ui/mesh-buffer'; import * as UIVertexFormat from '../core/renderer/ui/ui-vertex-format'; import { StencilManager } from '../core/renderer/ui/stencil-manager'; +import { legacyCC } from '../core/global-exports'; export * from './components'; @@ -45,7 +46,7 @@ export { }; -cc.UI = { +legacyCC.UI = { MeshBuffer, UIVertexFormat, barFilled, diff --git a/exports/audio.ts b/exports/audio.ts index 18a5592fb9..6522834e77 100644 --- a/exports/audio.ts +++ b/exports/audio.ts @@ -6,6 +6,7 @@ export { AudioClip } from '../cocos/audio/assets/clip'; import '../cocos/audio/audio-downloader'; import { AudioSourceComponent } from '../cocos/audio/audio-source-component'; +import { legacyCC } from '../cocos/core/global-exports'; export { AudioSourceComponent }; -cc.AudioSourceComponent = AudioSourceComponent; \ No newline at end of file +legacyCC.AudioSourceComponent = AudioSourceComponent; \ No newline at end of file diff --git a/exports/base.ts b/exports/base.ts index 37d4fba00d..d76efb52f9 100644 --- a/exports/base.ts +++ b/exports/base.ts @@ -2,6 +2,7 @@ * @hidden */ +import { legacyCC } from '../cocos/core/global-exports'; // has to import predefines first import '../predefine'; @@ -12,16 +13,15 @@ import '../cocos/core/legacy'; export * from '../cocos/core'; import * as renderer from '../cocos/core/renderer'; export { renderer }; -cc.renderer = renderer; +legacyCC.renderer = renderer; export * from '../extensions/ccpool/node-pool'; -const cclegacy = cc; -export { cclegacy }; +export { legacyCC as cclegacy }; import * as primitives from '../cocos/core/primitive'; export { primitives, }; -cc.primitives = primitives; +legacyCC.primitives = primitives; export * from '../cocos/core/primitive/primitive'; diff --git a/exports/gfx-webgl.ts b/exports/gfx-webgl.ts index 3644eb2053..62783bdb98 100644 --- a/exports/gfx-webgl.ts +++ b/exports/gfx-webgl.ts @@ -3,4 +3,6 @@ */ import { WebGLGFXDevice } from '../cocos/core/gfx/webgl/webgl-device'; -cc.WebGLGFXDevice = WebGLGFXDevice; +import { legacyCC } from '../cocos/core/global-exports'; +export { WebGLGFXDevice }; +legacyCC.WebGLGFXDevice = WebGLGFXDevice; diff --git a/exports/gfx-webgl2.ts b/exports/gfx-webgl2.ts index c259146ab2..3545c120b3 100644 --- a/exports/gfx-webgl2.ts +++ b/exports/gfx-webgl2.ts @@ -3,4 +3,6 @@ */ import { WebGL2GFXDevice } from '../cocos/core/gfx/webgl2/webgl2-device'; -cc.WebGL2GFXDevice = WebGL2GFXDevice; +import { legacyCC } from '../cocos/core/global-exports'; +export { WebGL2GFXDevice }; +legacyCC.WebGL2GFXDevice = WebGL2GFXDevice; diff --git a/extensions/ccpool/node-pool.ts b/extensions/ccpool/node-pool.ts index 1d8622b5e2..0366429fd9 100644 --- a/extensions/ccpool/node-pool.ts +++ b/extensions/ccpool/node-pool.ts @@ -4,6 +4,7 @@ import { Component } from '../../cocos/core/components/component'; import { Node } from '../../cocos/core/scene-graph'; +import { legacyCC } from '../../cocos/core/global-exports'; /**************************************************************************** Copyright (c) 2016 Chukong Technologies Inc. @@ -172,4 +173,4 @@ export class NodePool { } } -cc.NodePool = NodePool; +legacyCC.NodePool = NodePool; diff --git a/predefine.ts b/predefine.ts index e62a31e0f2..09f7bf88d8 100644 --- a/predefine.ts +++ b/predefine.ts @@ -23,162 +23,6 @@ THE SOFTWARE. */ -import { - ALIPAY, - BAIDU, - BUILD, - COCOSPLAY, - DEBUG, - DEV, - EDITOR, - JSB, - MINIGAME, - PHYSICS_AMMO, - PHYSICS_BUILTIN, - PHYSICS_CANNON, - PREVIEW, - RUNTIME_BASED, - SUPPORT_JIT, - TEST, - WECHAT, - XIAOMI, -} from 'internal:constants'; +import { legacyCC } from './cocos/core/global-exports'; -/** - * @hidden - */ - -/** - * !#zh - * 这里是一些用来判断执行环境的宏,这些宏都是全局变量,直接访问即可。
- * 在项目构建时,这些宏将会被预处理并根据构建的平台剔除不需要的代码,例如 - * - * if (CC_DEBUG) { - * cc.log('debug'); - * } - * else { - * cc.log('release'); - * } - * - * 在构建后会只剩下 - * - * cc.log('release'); - * - *
- * 如需判断脚本是否运行于指定平台,可以用如下表达式: - * - * { - * "编辑器": CC_EDITOR, - * "编辑器 或 预览": CC_DEV, - * "编辑器 或 预览 或 构建调试": CC_DEBUG, - * "网页预览": CC_PREVIEW && !CC_JSB, - * "模拟器预览": CC_PREVIEW && CC_JSB, - * "构建调试": CC_BUILD && CC_DEBUG, - * "构建发行": CC_BUILD && !CC_DEBUG, - * } - * - * !#en - * Here are some of the macro used to determine the execution environment, these macros are global variables, can be accessed directly.
- * When the project is built, these macros will be preprocessed and discard unreachable code based on the built platform, for example: - * - * if (CC_DEBUG) { - * cc.log('debug'); - * } - * else { - * cc.log('release'); - * } - * - * After build will become: - * - * cc.log('release'); - * - *
- * To determine whether the script is running on the specified platform, you can use the following expression: - * - * { - * "editor": CC_EDITOR, - * "editor or preview": CC_DEV, - * "editor or preview or build in debug mode": CC_DEBUG, - * "web preview": CC_PREVIEW && !CC_JSB, - * "simulator preview": CC_PREVIEW && CC_JSB, - * "build in debug mode": CC_BUILD && CC_DEBUG, - * "build in release mode": CC_BUILD && !CC_DEBUG, - * } - * - * @module GLOBAL-MACROS - */ - -// PREDEFINE - -// window may be undefined when first load engine from editor -// @ts-ignore -const _global = typeof window === 'undefined' ? global : window; - -/** - * !#en - * The main namespace of Cocos2d-JS, all engine core classes, functions, properties and constants are defined in this namespace. - * !#zh - * Cocos 引擎的主要命名空间,引擎代码中所有的类,函数,属性和常量都在这个命名空间中定义。 - * @module cc - * @main cc - */ -const cc = _global.cc = _global.cc || {}; - -// For internal usage -cc.internal = cc.internal || {}; - -cc._global = _global; - -if (BUILD) { - // Supports dynamically access from external scripts such as adapters and debugger. - // So macros should still defined in global even if inlined in engine. - _global.CC_BUILD = BUILD; - _global.CC_TEST = TEST; - _global.CC_EDITOR = EDITOR; - _global.CC_PREVIEW = PREVIEW; - _global.CC_DEV = DEV; - _global.CC_DEBUG = DEBUG; - _global.CC_JSB = JSB; - _global.CC_WECHAT = WECHAT; - _global.CC_ALIPAY = ALIPAY; - _global.CC_XIAOMI = XIAOMI; - _global.CC_BAIDU = BAIDU; - _global.CC_COCOSPLAY = COCOSPLAY; - _global.CC_MINIGAME = MINIGAME; - _global.CC_RUNTIME_BASED = RUNTIME_BASED; - _global.CC_SUPPORT_JIT = SUPPORT_JIT; - _global.CC_PHYSICS_BUILTIN = PHYSICS_BUILTIN; - _global.CC_PHYSICS_CANNON = PHYSICS_CANNON; - _global.CC_PHYSICS_AMMO = PHYSICS_AMMO; -} - -if (DEV) { - /** - * contains internal apis for unit tests - * @expose - */ - cc._Test = {}; -} - -/** - * The current version of Cocos2d being used.
- * Please DO NOT remove this String, it is an important flag for bug tracking.
- * If you post a bug to forum, please attach this flag. - */ -const engineVersion = '1.1.0'; -_global.CocosEngine = cc.ENGINE_VERSION = engineVersion; - -export default cc; - -/** - * deprecated - */ -// TODO: ALIPAY and runtime will redefine -if (!(RUNTIME_BASED || ALIPAY)) { - Object.defineProperty(_global, 'CC_PHYSICS_BUILT_IN', { - get: () => { - console.warn('CC_PHYSICS_BUILT_IN is deprecated, please using CC_PHYSICS_BUILTIN instead.'); - return _global.CC_PHYSICS_BUILTIN; - }, - }); -} +export default legacyCC;