Merge pull request #5834 from pandamicro/3d

Merge v1.0.2
This commit is contained in:
pandamicro
2019-12-03 19:34:50 +08:00
committed by GitHub
140 changed files with 2876 additions and 3518 deletions
+35
View File
@@ -0,0 +1,35 @@
{
"version": "0.1",
"words": [
"Chukong",
"Yaji",
"ccclass",
"ccenum",
"forin",
"struct",
"realloc",
"polyfill",
"lerp",
"lerpable",
"slerp",
"renderable",
"grayscale",
"raycast",
"skybox",
"earcut",
"Arial",
"OPENGL",
"IGFX",
"UNORM",
"SNORM",
"WECHAT",
"WECHATGAME"
]
}
+5 -5
View File
@@ -31,10 +31,10 @@ declare const CC_PREVIEW: boolean;
declare const CC_DEV: boolean;
declare const CC_DEBUG: boolean;
declare const CC_JSB: boolean;
declare const CC_WECHATGAME_SUB: boolean;
declare const CC_WECHATGAME: boolean;
declare const CC_QQPLAY: boolean;
declare const CC_RUNTIME: boolean;
declare const CC_WECHAT: boolean;
declare const CC_ALIPAY: boolean;
declare const CC_MINIGAME: boolean;
declare const CC_RUNTIME_BASED: boolean;
declare const CC_SUPPORT_JIT: boolean;
declare const jsb: any;
@@ -45,7 +45,7 @@ declare const CC_PHYSICS_BUILTIN: boolean;
interface Window {
[x: string]: any;
WebGL2RenderingContext: any;
sharedCanvas: any;
+34 -1
View File
@@ -574,7 +574,7 @@ Please do not specifiy "default" attribute in decorator of "%s" property in "%s"
Default value must be initialized at their declaration:
```
// Before:
@property({ default: 0 }) // <--
@property({ default: 0 }) // <--
@integer
value;
// After:
@@ -632,6 +632,27 @@ browser does not support getters
Violation error: extending enumerations shall have non-overlaped member names or member values
### 3660
You are explicitly specifying `undefined` type to cc property "%s" of cc class "%s".
Is this intended? If not, this may indicate a circular reference.
For example:
```
// foo.ts
import { _decorator } from 'cc';
import { Bar } from './bar'; // Given that './bar' also reference 'foo.ts'.
// When importing './bar', execution of './bar' is hung on to wait execution of 'foo.ts',
// the `Bar` imported here is `undefined` until './bar' finish its execution.
// It leads to that
@_decorator.ccclass // ↓
export class Foo { // ↓
@_decorator.type(Bar) // → is equivalent to `@_decorator.type(undefined)`
public bar: Bar; // To eliminate this error, either:
// - Refactor your module structure(recommended), or
// - specify the type as cc class name: `@_decorator.type('Bar'/* or any name you specified for `Bar` */)`
}
```
### 3700
internal error: _prefab is undefined
@@ -1939,3 +1960,15 @@ Stencil manager is already empty, cannot pop any mask
### 9100
texture size exceeds current device limits %d/%d
### 9200
Priority can't be set in Canvas node
### 9300
The current buffer beyond the limit in ui static component, please reduce the amount
### 9301
The UI has not been initialized
+14 -13
View File
@@ -33,12 +33,11 @@ import { Enum } from '../../core/value-types';
import { AudioPlayer, PlayingState } from './player';
import { AudioPlayerDOM } from './player-dom';
import { AudioPlayerWeb } from './player-web';
import { AudioPlayerWX } from './player-wx';
export const AudioType = Enum({
WEB_AUDIO: 0,
DOM_AUDIO: 1,
WX_GAME_AUDIO: 2,
MINI_GAME_AUDIO: 2,
UNKNOWN_AUDIO: 3,
});
@@ -74,20 +73,22 @@ export class AudioClip extends Asset {
return super.destroy();
}
private _getPlayer (clip: any) {
let ctor: any;
if (typeof AudioBuffer !== 'undefined' && clip instanceof AudioBuffer) {
ctor = AudioPlayerWeb;
this._loadMode = AudioType.WEB_AUDIO;
} else {
ctor = AudioPlayerDOM;
this._loadMode = AudioType.DOM_AUDIO;
}
return ctor;
}
set _nativeAsset (clip: any) {
this._audio = clip;
if (clip) {
let ctor: any;
if (CC_WECHATGAME) {
ctor = AudioPlayerWX;
this._loadMode = AudioType.WX_GAME_AUDIO;
} else if (typeof AudioBuffer !== 'undefined' && clip instanceof AudioBuffer) {
ctor = AudioPlayerWeb;
this._loadMode = AudioType.WEB_AUDIO;
} else {
ctor = AudioPlayerDOM;
this._loadMode = AudioType.DOM_AUDIO;
}
const ctor = this._getPlayer(clip);
this._player = new ctor({ clip, duration: this._duration, eventTarget: this });
this.loaded = true;
this.emit('load');
-156
View File
@@ -1,156 +0,0 @@
/*
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.
*/
/**
* @category component/audio
*/
import { clamp } from '../../core/math/utils';
import { AudioPlayer, IAudioInfo, PlayingState } from './player';
/**
* The main lesson learnt during the porting is,
* be very careful with the getter methods on InnerAudioContext,
* serious performance issue have been encountered when accessed frequently.
* For now this includes duration, current time and volume,
* so those are all maintained manually here.
*/
export class AudioPlayerWX extends AudioPlayer {
protected _startTime = 0;
protected _offset = 0;
protected _volume = 1;
protected _loop = false;
protected _oneShoting = false;
protected _audio: InnerAudioContext;
constructor (info: IAudioInfo) {
super(info);
this._audio = info.clip;
// [HACK] volume property doesn't work on some devices during the first playthrough
this._audio.play();
this._audio.stop();
this._audio.onPlay(() => {
if (this._state === PlayingState.PLAYING) { return; }
this._state = PlayingState.PLAYING;
this._startTime = performance.now();
this._eventTarget.emit('started');
});
this._audio.onPause(() => {
if (this._state === PlayingState.STOPPED) { return; }
this._state = PlayingState.STOPPED;
this._offset += performance.now() - this._startTime;
});
this._audio.onStop(() => {
if (this._state === PlayingState.STOPPED) { return; }
this._state = PlayingState.STOPPED;
this._offset = 0;
if (this._oneShoting) {
this._audio.volume = this._volume;
this._audio.loop = this._loop;
this._oneShoting = false;
}
});
this._audio.onEnded(() => {
if (this._state === PlayingState.STOPPED) { return; }
this._state = PlayingState.STOPPED;
this._offset = 0;
this._eventTarget.emit('ended');
if (this._oneShoting) {
this._audio.volume = this._volume;
this._audio.loop = this._loop;
this._oneShoting = false;
}
});
this._audio.onError((res: any) => console.error(res.errMsg));
}
public play () {
if (!this._audio || this._state === PlayingState.PLAYING) { return; }
if (this._blocking) { this._interrupted = true; return; }
this._audio.play();
}
public pause () {
if (!this._audio || this._state !== PlayingState.PLAYING) { return; }
this._audio.pause();
}
public stop () {
if (!this._audio) { return; }
this._audio.stop();
}
public playOneShot (volume = 1) {
/* InnerAudioContext doesn't support multiple playback at the
same time so here we fall back to re-start style approach */
if (!this._audio) { return; }
this._offset = 0;
this._oneShoting = true;
this._audio.stop();
this._audio.loop = false;
this._audio.volume = volume;
this._audio.play();
}
public getCurrentTime () {
if (this._state !== PlayingState.PLAYING) { return this._offset / 1000; }
let current = (performance.now() - this._startTime + this._offset) / 1000;
if (current > this._duration) { current -= this._duration; this._startTime += this._duration * 1000; }
return current;
}
public setCurrentTime (val: number) {
if (!this._audio) { return; }
this._offset = clamp(val, 0, this._duration) * 1000;
this._startTime = performance.now();
this._audio.seek(val);
}
public getVolume () {
return this._volume;
}
public setVolume (val: number, immediate: boolean) {
this._volume = val;
if (this._audio) { this._audio.volume = val; }
}
public getLoop () {
return this._loop;
}
public setLoop (val: boolean) {
this._loop = val;
if (this._audio) { this._audio.loop = val; }
}
public destroy () {
if (this._audio) { this._audio.destroy(); }
wx.offAudioInterruptionBegin(this._onHide);
wx.offAudioInterruptionEnd(this._onShow);
super.destroy();
}
}
+2
View File
@@ -84,3 +84,5 @@ export abstract class AudioPlayer {
cc.game.off(cc.Game.EVENT_SHOW, this._onShow);
}
}
cc.AudioPlayer = AudioPlayer;
+3 -20
View File
@@ -27,7 +27,6 @@
* @category loader
*/
import { loader } from '../core/load-pipeline';
import { getError, log } from '../core/platform/debug';
import sys from '../core/platform/sys';
import { AudioClip, AudioType } from './assets/clip';
@@ -35,12 +34,6 @@ import { AudioClip, AudioType } from './assets/clip';
const __audioSupport = sys.__audioSupport;
const formatSupport = __audioSupport.format;
function loadWXAudio (item, callback) {
const clip = wx.createInnerAudioContext();
clip.src = item.url;
clip.onCanplay(() => callback(null, clip));
}
function loadDomAudio (item, callback) {
const dom = document.createElement('audio');
dom.src = item.url;
@@ -83,7 +76,7 @@ function loadWebAudio (item, callback) {
callback(new Error(getError(4926)));
}
const request = loader.getXMLHttpRequest();
const request = cc.loader.getXMLHttpRequest();
request.open('GET', item.url, true);
request.responseType = 'arraybuffer';
@@ -105,15 +98,13 @@ function loadWebAudio (item, callback) {
request.send();
}
function downloadAudio (item, callback) {
export function downloadAudio (item, callback) {
if (formatSupport.length === 0) {
return new Error(getError(4927));
}
let audioLoader;
if (CC_WECHATGAME) {
audioLoader = loadWXAudio;
} else if (!__audioSupport.WEB_AUDIO) {
if (!__audioSupport.WEB_AUDIO) {
audioLoader = loadDomAudio; // If WebAudio is not supported, load using DOM mode
} else {
const loadByDeserializedAudio = item._owner instanceof AudioClip;
@@ -125,11 +116,3 @@ function downloadAudio (item, callback) {
}
audioLoader(item, callback);
}
loader.downloader.addHandlers({
// Audio
mp3 : downloadAudio,
ogg : downloadAudio,
wav : downloadAudio,
m4a : downloadAudio,
});
File diff suppressed because one or more lines are too long
+48 -29
View File
@@ -34,11 +34,12 @@ import { ray } from '../../geom-utils';
import { GFXClearFlag } from '../../gfx/define';
import { GFXWindow } from '../../gfx/window';
import { Color, Rect, toRadian, Vec3 } from '../../math';
import { CameraDefaultMask } from '../../pipeline/define';
import { Camera } from '../../renderer';
import { SKYBOX_FLAG } from '../../renderer/scene/camera';
import { Root } from '../../root';
import { Layers, Scene } from '../../scene-graph';
import { Enum } from '../../value-types';
import { CameraDefaultMask } from '../../pipeline/define';
/**
* The projection type<br/>
@@ -117,7 +118,7 @@ export class CameraComponent extends Component {
*/
@property({
type: ProjectionType,
tooltip:'相机的投影类型',
tooltip: '相机的投影类型',
})
get projection () {
return this._projection;
@@ -133,7 +134,7 @@ export class CameraComponent extends Component {
* @zh 相机的优先级顺序,只能在编辑器中设置,动态设置无效。
*/
@property({
tooltip:'相机的优先级顺序,只能在编辑器中设置,动态设置无效',
tooltip: '相机的优先级顺序,只能在编辑器中设置,动态设置无效',
})
get priority () {
return this._priority;
@@ -151,7 +152,7 @@ export class CameraComponent extends Component {
* @zh 相机的视角大小。
*/
@property({
tooltip:'相机的视角大小',
tooltip: '相机的视角大小',
})
get fov () {
return this._fov;
@@ -167,7 +168,7 @@ export class CameraComponent extends Component {
* @zh 正交模式下的相机视角大小。
*/
@property({
tooltip:'正交模式下的相机视角大小',
tooltip: '正交模式下的相机视角大小',
})
get orthoHeight () {
return this._orthoHeight;
@@ -183,7 +184,7 @@ export class CameraComponent extends Component {
* @zh 相机的近平面。
*/
@property({
tooltip:'相机的近平面',
tooltip: '相机的近平面',
})
get near () {
return this._near;
@@ -199,7 +200,7 @@ export class CameraComponent extends Component {
* @zh 相机的远平面。
*/
@property({
tooltip:'相机的远平面',
tooltip: '相机的远平面',
})
get far () {
return this._far;
@@ -215,7 +216,7 @@ export class CameraComponent extends Component {
* @zh 相机的颜色缓冲默认值。
*/
@property({
tooltip:'相机的颜色缓冲默认值',
tooltip: '相机的颜色缓冲默认值',
})
// @constget
get color (): Readonly<Color> {
@@ -237,7 +238,7 @@ export class CameraComponent extends Component {
* @zh 相机的深度缓冲默认值。
*/
@property({
tooltip:'相机的深度缓冲默认值',
tooltip: '相机的深度缓冲默认值',
})
get depth () {
return this._depth;
@@ -253,7 +254,7 @@ export class CameraComponent extends Component {
* @zh 相机的模板缓冲默认值。
*/
@property({
tooltip:'相机的模板缓冲默认值',
tooltip: '相机的模板缓冲默认值',
})
get stencil () {
return this._stencil;
@@ -270,7 +271,7 @@ export class CameraComponent extends Component {
*/
@property({
type: CameraClearFlag,
tooltip:'相机的缓冲清除标志位',
tooltip: '相机的缓冲清除标志位',
})
get clearFlags () {
return this._clearFlags;
@@ -286,7 +287,7 @@ export class CameraComponent extends Component {
* @zh 相机相对屏幕的 viewport。
*/
@property({
tooltip:'相机相对屏幕的 viewport',
tooltip: '相机相对屏幕的 viewport',
})
get rect () {
return this._rect;
@@ -317,7 +318,7 @@ export class CameraComponent extends Component {
*/
@property({
type: Layers.BitMask,
tooltip:'设置摄像机可见掩码,与 Component 中的 visibility 同时使用,用于过滤摄像机不需要渲染的物体',
tooltip: '设置摄像机可见掩码,与 Component 中的 visibility 同时使用,用于过滤摄像机不需要渲染的物体',
})
get visibility () {
return this._visibility;
@@ -335,7 +336,7 @@ export class CameraComponent extends Component {
*/
@property({
type: RenderTexture,
tooltip:'设置摄像机 RenderTexture',
tooltip: '设置摄像机 RenderTexture',
})
get targetTexture () {
return this._targetTexture;
@@ -352,16 +353,16 @@ export class CameraComponent extends Component {
this._updateTargetTexture();
if (!value && this._camera){
this._camera.changeTargetWindow(CC_EDITOR? cc.director.root.tempWindow: null);
this._camera.changeTargetWindow(CC_EDITOR ? cc.director.root.tempWindow : null);
this._camera.isWindowSize = true;
}
}
get inEditorMode() {
get inEditorMode () {
return this._inEditorMode;
}
set inEditorMode(value) {
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);
@@ -376,21 +377,25 @@ export class CameraComponent extends Component {
public onLoad () {
cc.director.on(cc.Director.EVENT_AFTER_SCENE_LAUNCH, this.onSceneChanged, this);
this._createCamera();
}
public onEnable () {
if (this._camera) { this._camera.enabled = true; return; }
this._createCamera();
this._camera!.enabled = true;
if (this._camera) {
this._attachToScene();
return;
}
}
public onDisable () {
if (this._camera) { this._camera.enabled = false; }
if (this._camera) {
this._detachFromScene();
}
}
public onDestroy () {
if (this._camera) {
this._getRenderScene().destroyCamera(this._camera);
cc.director.root.destroyCamera(this._camera);
this._camera = null;
}
@@ -418,10 +423,8 @@ export class CameraComponent extends Component {
}
protected _createCamera () {
if (!this.node.scene) { return; }
const scene = this._getRenderScene();
if (this._camera && scene.cameras.find((c) => c === this._camera)) { return; }
this._camera = scene.createCamera({
this._camera = (cc.director.root as Root).createCamera();
this._camera.initialize({
name: this.node.name,
node: this.node,
projection: this._projection,
@@ -449,11 +452,27 @@ export class CameraComponent extends Component {
this._updateTargetTexture();
}
protected _attachToScene () {
if (!this.node.scene || !this._camera) {
return;
}
if (this._camera && this._camera.scene) {
this._camera.scene.removeCamera(this._camera);
}
const scene = this._getRenderScene();
scene.addCamera(this._camera);
}
protected _detachFromScene () {
if (this._camera && this._camera.scene) {
this._camera.scene.removeCamera(this._camera);
}
}
protected onSceneChanged (scene: Scene) {
// to handle scene switch of editor camera
if (this._camera && this._camera.scene !== scene.renderScene) {
this._createCamera();
this._camera.enabled = true;
if (this._camera && this._camera.scene == null) {
this._attachToScene();
}
}
@@ -52,7 +52,7 @@ export class DirectionalLightComponent extends LightComponent {
*/
@property({
unit: 'lx',
tooltip:'光源强度'
tooltip: '光源强度',
})
get illuminance () {
return this._illuminance;
@@ -62,23 +62,14 @@ export class DirectionalLightComponent extends LightComponent {
if (this._light) { this._light.illuminance = this._illuminance; }
}
protected _createLight (scene?: RenderScene) {
if (!this.node.scene) { return; }
scene = scene || this._getRenderScene();
if (scene.mainLight.node.activeInHierarchy) {
console.warn('there can be only one directional(main) light.');
return;
}
this._light = scene.mainLight;
this.illuminance = this._illuminance;
super._createLight(scene);
constructor () {
super();
this._lightType = DirectionalLight;
}
protected _destroyLight (scene?: RenderScene) {
if (!this.node.scene || !this._light) { return; }
this._light.enabled = false;
scene = scene || this._getRenderScene();
this._light.node = scene.defaultMainLightNode;
super._destroyLight(scene);
protected _createLight () {
super._createLight();
if (!this._light) { return; }
this.illuminance = this._illuminance;
}
}
@@ -110,16 +110,22 @@ export class EditorCameraComponent extends CameraComponent {
public onEnable () {
super.onEnable();
if (this._uiEditorCamera) {
cc.director.root!.ui.renderScene.addCamera(this._uiEditorCamera);
}
}
public onDisable () {
public onDisable() {
super.onDisable();
if (this._uiEditorCamera) {
cc.director.root!.ui.renderScene.removeCamera(this._uiEditorCamera);
}
}
public onDestroy () {
super.onDestroy();
if (this._uiEditorCamera) {
cc.director.root!.ui.renderScene.destroyCamera(this._uiEditorCamera);
cc.director.root!.destroyCamera(this._uiEditorCamera);
this._uiEditorCamera = null;
}
}
@@ -130,10 +136,11 @@ export class EditorCameraComponent extends CameraComponent {
if (this._camera !== priorCamera && this._camera) {
if (this._uiEditorCamera) {
cc.director.root!.ui.renderScene.destroyCamera(this._uiEditorCamera);
cc.director.root!.destroyCamera(this._uiEditorCamera);
this._uiEditorCamera = null;
}
this._uiEditorCamera = cc.director.root!.ui.renderScene.createCamera({
this._uiEditorCamera = cc.director.root!.createCamera();
this._uiEditorCamera!.initialize({
name: 'Editor UICamera',
node: this._camera.node,
projection: this._projection,
+61 -12
View File
@@ -32,8 +32,11 @@ import { ccclass, property } from '../../data/class-decorator';
import { Color } from '../../math';
import { Enum } from '../../value-types';
import { DirectionalLight } from '../../renderer/scene/directional-light';
import { Light, LightType } from '../../renderer/scene/light';
import { RenderScene } from '../../renderer/scene/render-scene';
import { SphereLight } from '../../renderer/scene/sphere-light';
import { SpotLight } from '../../renderer/scene/spot-light';
import { Root } from '../../root';
export const PhotometricTerm = Enum({
LUMINOUS_POWER: 0,
@@ -53,6 +56,7 @@ export class LightComponent extends Component {
protected _colorTemperature = 6550;
protected _type = LightType.UNKNOWN;
protected _lightType: typeof Light;
protected _light: Light | null = null;
/**
@@ -62,7 +66,7 @@ export class LightComponent extends Component {
* 光源颜色。
*/
@property({
tooltip:'光源颜色',
tooltip: '光源颜色',
})
// @constget
get color (): Readonly<Color> {
@@ -84,7 +88,7 @@ export class LightComponent extends Component {
* 是否启用光源色温。
*/
@property({
tooltip:'是否启用光源色温'
tooltip: '是否启用光源色温',
})
get useColorTemperature () {
return this._useColorTemperature;
@@ -103,7 +107,7 @@ export class LightComponent extends Component {
@property({
slide: true,
range: [1000, 15000, 1],
tooltip:'光源色温'
tooltip: '光源色温',
})
get colorTemperature () {
return this._colorTemperature;
@@ -124,29 +128,74 @@ export class LightComponent extends Component {
return this._type;
}
public onEnable () {
if (this._light) { this._light.enabled = true; return; }
constructor () {
super();
this._lightType = Light;
}
public onLoad (){
this._createLight();
}
public onEnable () {
this._attachToScene();
}
public onDisable () {
if (this._light) { this._light.enabled = false; }
this._detachFromScene();
}
public onDestroy () {
this._destroyLight();
}
protected _createLight (scene?: RenderScene) {
if (!this._light) { return; }
protected _createLight () {
if (!this._light) {
this._light = (cc.director.root as Root).createLight(this._lightType);
}
this.color = this._color;
this.useColorTemperature = this._useColorTemperature;
this.colorTemperature = this._colorTemperature;
this._light.node = this.node;
this._light.enabled = this.enabledInHierarchy;
}
protected _destroyLight (scene?: RenderScene) {
this._light = null;
protected _destroyLight () {
if (this._light) {
cc.director.root.destroyLight(this);
this._light = null;
}
}
protected _attachToScene () {
this._detachFromScene();
if (this._light && !this._light.scene && this.node.scene) {
switch (this._type) {
case LightType.DIRECTIONAL:
this._getRenderScene().setMainLight(this._light as DirectionalLight);
break;
case LightType.SPHERE:
this._getRenderScene().addSphereLight(this._light as SphereLight);
break;
case LightType.SPOT:
this._getRenderScene().addSpotLight(this._light as SpotLight);
break;
}
}
}
protected _detachFromScene () {
if (this._light && this._light.scene) {
switch (this._type) {
case LightType.DIRECTIONAL:
this._light.scene.unsetMainLight(this._light as DirectionalLight);
break;
case LightType.SPHERE:
this._light.scene.removeSphereLight(this._light as SphereLight);
break;
case LightType.SPOT:
this._light.scene.removeSpotLight(this._light as SpotLight);
break;
}
}
}
}
+38 -26
View File
@@ -30,7 +30,8 @@
import { Material, Mesh } from '../../assets';
import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../data/class-decorator';
import { Model } from '../../renderer/scene/model';
import { TransformDirtyBit } from '../../scene-graph/node-enum';
import { Root } from '../../root';
import { TransformBit } from '../../scene-graph/node-enum';
import { Enum } from '../../value-types';
import { builtinResMgr } from '../builtin';
import { RenderableComponent } from './renderable-component';
@@ -77,6 +78,9 @@ export class ModelComponent extends RenderableComponent {
this._mesh = val;
this._onMeshChanged(old);
this._updateModels();
if (this.node.activeInHierarchy) {
this._attachToScene();
}
}
/**
@@ -147,6 +151,8 @@ export class ModelComponent extends RenderableComponent {
public static ShadowCastingMode = ModelShadowCastingMode;
protected _modelType: typeof Model;
protected _model: Model | null = null;
@property
@@ -161,6 +167,11 @@ export class ModelComponent extends RenderableComponent {
@property
private _receiveShadows = false;
constructor () {
super();
this._modelType = Model;
}
public onLoad () {
this._updateModels();
this._updateCastShadow();
@@ -169,44 +180,34 @@ export class ModelComponent extends RenderableComponent {
public onEnable () {
if (this._model) {
if (!this._model.inited) {
this._updateModels();
}
this._model.enabled = true;
this._attachToScene();
}
}
public onDisable () {
if (this._model) {
this._model.enabled = false;
this._detachFromScene();
}
}
public onDestroy () {
if (this._model) {
this._model.scene.destroyModel(this._model);
cc.director.root.destroyModel(this._model);
this._model = null;
this._models.length = 0;
}
}
public _changeSceneInModel () {
if (this.isValid) {
if (this._model) {
this._model.destroy();
this._model.scene.destroyModel(this._model);
this._model = null;
}
this._updateModels();
}
}
protected _updateModels () {
if (!this.enabledInHierarchy || !this._mesh) {
return;
}
this._createModel();
if (this._model) {
this._model.destroy();
} else {
this._createModel();
}
this._updateModelParams();
@@ -232,24 +233,35 @@ export class ModelComponent extends RenderableComponent {
}
protected _createModel () {
if (!this.node.scene) { return; }
const scene = this._getRenderScene();
if (this._model) { scene.destroyModel(this._model); }
this._model = scene.createModel(this._getModelConstructor(), this.node);
this._model = (cc.director.root as Root).createModel(this._modelType);
this._model.visFlags = this.visibility;
this._model.initialize(this.node);
this._models.length = 0;
this._models.push(this._model);
}
protected _getModelConstructor () {
return Model;
protected _attachToScene () {
if (!this.node.scene && !this._model) {
return;
}
const scene = this._getRenderScene();
if (this._model!.scene != null) {
this._detachFromScene();
}
scene.addModel(this._model!);
}
protected _detachFromScene () {
if (this._model && this._model.scene) {
this._model.scene.removeModel(this._model);
}
}
protected _updateModelParams () {
if (!this._mesh || !this._model) {
return;
}
this.node.hasChangedFlags = this._model.transform.hasChangedFlags = TransformDirtyBit.POSITION;
this.node.hasChangedFlags = this._model.transform.hasChangedFlags = TransformBit.POSITION;
this._model.isDynamicBatching = this._enableDynamicBatching; // should pass this in before create PSO
const meshCount = this._mesh ? this._mesh.subMeshCount : 0;
for (let i = 0; i < meshCount; ++i) {
@@ -139,8 +139,10 @@ export class RenderableComponent extends Component {
return this._models;
}
public _changeSceneInModel () {
protected _attachToScene() {
}
protected _detachFromScene() {
}
protected _onMaterialModified (index: number, material: Material | null) {
@@ -90,6 +90,11 @@ export class SkinningModelComponent extends ModelComponent {
return (this._model as SkinningModel);
}
constructor () {
super();
this._modelType = SkinningModel;
}
public uploadAnimation (clip: AnimationClip | null) {
this._clip = clip;
if (this._model) { (this._model as SkinningModel).uploadAnimation(clip); }
@@ -101,10 +106,6 @@ export class SkinningModelComponent extends ModelComponent {
super._updateModelParams();
}
protected _getModelConstructor () {
return SkinningModel;
}
protected _getBuiltinMaterial () {
// classic ugly pink indicating missing material
return builtinResMgr.get<Material>('missing-skinning-material');
@@ -28,7 +28,6 @@
import { ccclass, executeInEditMode, menu, property } from '../../data/class-decorator';
import { LightType, nt2lm } from '../../renderer/scene/light';
import { RenderScene } from '../../renderer/scene/render-scene';
import { SphereLight } from '../../renderer/scene/sphere-light';
import { LightComponent, PhotometricTerm } from './light-component';
@@ -54,7 +53,7 @@ export class SphereLightComponent extends LightComponent {
*/
@property({
unit: 'lm',
tooltip:'光通量',
tooltip: '光通量',
})
get luminousPower () {
return this._luminance * nt2lm(this._size);
@@ -69,7 +68,7 @@ export class SphereLightComponent extends LightComponent {
*/
@property({
unit: 'cd/m²',
tooltip:'亮度',
tooltip: '亮度',
})
get luminance () {
return this._luminance;
@@ -84,7 +83,7 @@ export class SphereLightComponent extends LightComponent {
*/
@property({
type: PhotometricTerm,
tooltip:'指定光通量或亮度',
tooltip: '指定光通量或亮度',
})
get term () {
return this._term;
@@ -100,7 +99,7 @@ export class SphereLightComponent extends LightComponent {
* 针对聚光灯和点光源设置光源大小。
*/
@property({
tooltip:'针对聚光灯和点光源设置光源大小'
tooltip: '针对聚光灯和点光源设置光源大小',
})
get size () {
return this._size;
@@ -117,7 +116,7 @@ export class SphereLightComponent extends LightComponent {
* 针对聚光灯和点光源设置光源范围。
*/
@property({
tooltip:'针对聚光灯和点光源设置光源范围',
tooltip: '针对聚光灯和点光源设置光源范围',
})
get range () {
return this._range;
@@ -127,25 +126,16 @@ export class SphereLightComponent extends LightComponent {
if (this._light) { this._light.range = val; }
}
protected _createLight (scene?: RenderScene) {
if (!this.node.scene) { return; }
scene = scene || this._getRenderScene();
if (this._light && scene.sphereLights.find((c) => c === this._light)) { return; }
this._light = scene.createSphereLight(this.name, this.node);
if (!this._light) {
console.warn('we don\'t support this many lights in forward pipeline.');
return;
}
this._light.luminance = this._luminance;
this.size = this._size;
this.range = this._range;
super._createLight(scene);
constructor () {
super();
this._lightType = SphereLight;
}
protected _destroyLight (scene?: RenderScene) {
if (!this.node.scene || !this._light) { return; }
if (!scene) { scene = this._getRenderScene(); }
scene.destroySphereLight(this._light);
super._destroyLight(scene);
protected _createLight () {
super._createLight();
if (!this._light) { return; }
this.luminance = this._luminance;
this.size = this._size;
this.range = this._range;
}
}
+15 -25
View File
@@ -30,7 +30,6 @@
import { ccclass, executeInEditMode, menu, property } from '../../data/class-decorator';
import { toRadian } from '../../math';
import { LightType, nt2lm } from '../../renderer/scene/light';
import { RenderScene } from '../../renderer/scene/render-scene';
import { SpotLight } from '../../renderer/scene/spot-light';
import { LightComponent, PhotometricTerm } from './light-component';
@@ -58,7 +57,7 @@ export class SpotLightComponent extends LightComponent {
*/
@property({
unit: 'lm',
tooltip:'光通量',
tooltip: '光通量',
})
get luminousPower () {
return this._luminance * nt2lm(this._size);
@@ -73,7 +72,7 @@ export class SpotLightComponent extends LightComponent {
*/
@property({
unit: 'cd/m²',
tooltip:'亮度',
tooltip: '亮度',
})
get luminance () {
return this._luminance;
@@ -88,7 +87,7 @@ export class SpotLightComponent extends LightComponent {
*/
@property({
type: PhotometricTerm,
tooltip:'指定光通量或亮度',
tooltip: '指定光通量或亮度',
})
get term () {
return this._term;
@@ -104,7 +103,7 @@ export class SpotLightComponent extends LightComponent {
* 针对聚光灯和点光源设置光源大小。
*/
@property({
tooltip:'针对聚光灯和点光源设置光源大小',
tooltip: '针对聚光灯和点光源设置光源大小',
})
get size () {
return this._size;
@@ -121,7 +120,7 @@ export class SpotLightComponent extends LightComponent {
* 针对聚光灯和点光源设置光源范围。
*/
@property({
tooltip:'针对聚光灯和点光源设置光源范围',
tooltip: '针对聚光灯和点光源设置光源范围',
})
get range () {
return this._range;
@@ -140,7 +139,7 @@ export class SpotLightComponent extends LightComponent {
@property({
slide: true,
range: [2, 180, 1],
tooltip:'聚光灯锥角',
tooltip: '聚光灯锥角',
})
get spotAngle () {
return this._spotAngle;
@@ -151,26 +150,17 @@ export class SpotLightComponent extends LightComponent {
if (this._light) { this._light.spotAngle = toRadian(val); }
}
protected _createLight (scene?: RenderScene) {
if (!this.node.scene) { return; }
if (!scene) { scene = this._getRenderScene(); }
if (this._light && scene.spotLights.find((c) => c === this._light)) { return; }
this._light = scene.createSpotLight(this.name, this.node);
if (!this._light) {
console.warn('we don\'t support this many lights in forward pipeline.');
return;
}
this._light.luminance = this._luminance;
constructor () {
super();
this._lightType = SpotLight;
}
protected _createLight () {
super._createLight();
if (!this._light) { return; }
this.luminance = this._luminance;
this.size = this._size;
this.range = this._range;
this.spotAngle = this._spotAngle;
super._createLight(scene);
}
protected _destroyLight (scene?: RenderScene) {
if (!this.node.scene || !this._light) { return; }
if (!scene) { scene = this._getRenderScene(); }
scene.destroySpotLight(this._light);
super._destroyLight(scene);
}
}
@@ -66,10 +66,13 @@ export class AnimationBlendState {
}
public apply () {
for (const targetState of this._blendTargets) {
const targets = this._blendTargets;
for (let i = 0; i < targets.length; i++) {
const targetState = targets[i];
const target = targetState.target;
const propertyStates = targetState.properties;
for (const p of propertyStates) {
for (let j = 0; j < propertyStates.length; j++) {
const p = propertyStates[j];
if (p.weight !== 0) {
if (target instanceof Node) {
if (p.name === 'position') {
@@ -88,7 +91,9 @@ export class AnimationBlendState {
}
public clear () {
for (const targetState of this._blendTargets) {
const targets = this._blendTargets;
for (let i = 0; i < targets.length; i++) {
const targetState = targets[i];
const propertyStates = targetState.properties;
for (const p of propertyStates) {
p.weight = 0;
+1 -1
View File
@@ -181,7 +181,7 @@ export class ImageAsset extends Asset {
this._onDataComplete();
} else {
this._nativeData = data;
if (CC_WECHATGAME || CC_QQPLAY || (data as any).complete || data instanceof HTMLCanvasElement) {
if (CC_MINIGAME || (data as any).complete || data instanceof HTMLCanvasElement) { // todo need adatper
this._onDataComplete();
} else {
this.loaded = false;
+5 -1
View File
@@ -188,4 +188,8 @@ export default class Prefab extends Asset {
}
cc.Prefab = Prefab;
obsolete(cc, 'cc._Prefab', 'Prefab');
if (CC_ALIPAY || CC_RUNTIME_BASED) {
cc._Prefab = Prefab;
} else {
obsolete(cc, 'cc._Prefab', 'Prefab');
}
+7 -2
View File
@@ -4,7 +4,7 @@
import { ccclass } from '../data/class-decorator';
import { GFXBufferTextureCopy, GFXTextureFlagBit, GFXTextureUsageBit } from '../gfx/define';
import { GFXDevice } from '../gfx/device';
import { GFXAPI, GFXDevice } from '../gfx/device';
import { GFXTexture, IGFXTextureInfo } from '../gfx/texture';
import { GFXTextureView, IGFXTextureViewInfo } from '../gfx/texture-view';
import { error } from '../platform/debug';
@@ -46,6 +46,11 @@ function getMipLevel (width: number, height: number) {
}
function isPOT (n: number) { return n && (n & (n - 1)) === 0; }
function canGenerateMipmap (device: GFXDevice, w: number, h: number) {
const needCheckPOT = device.gfxAPI === GFXAPI.WEBGL;
if (needCheckPOT) { return isPOT(w) && isPOT(h); }
return true;
}
/**
* 简单贴图基类。
@@ -213,7 +218,7 @@ export class SimpleTexture extends TextureBase {
protected _createTexture (device: GFXDevice) {
let flags = GFXTextureFlagBit.NONE;
if (this._mipFilter !== Filter.NONE && isPOT(this._width) && isPOT(this._height)) {
if (this._mipFilter !== Filter.NONE && canGenerateMipmap(device, this._width, this._height)) {
this._mipmapLevel = getMipLevel(this._width, this._height);
flags = GFXTextureFlagBit.GEN_MIPMAP;
}
@@ -49,7 +49,7 @@ const BlockEvents = [SystemEventType.TOUCH_START, SystemEventType.TOUCH_END, Sys
SystemEventType.MOUSE_ENTER, SystemEventType.MOUSE_LEAVE, SystemEventType.MOUSE_WHEEL];
function stopPropagation(event: Event) {
event.propagationStopped = true;;
event.propagationStopped = true;
}
@ccclass('cc.BlockInputEventsComponent')
+1
View File
@@ -33,3 +33,4 @@ export { default as MissingScript } from './missing-script';
export { BlockInputEventsComponent } from './block-input-events-component';
export { default as System } from './system';
export * from './ui-base';
export { UICoordinateTrackerComponent } from './ui-coodinate-tracker-component';
@@ -28,22 +28,22 @@
* @category ui
*/
import { Component } from '../component';
import { ccclass, disallowMultiple, executeInEditMode, executionOrder, menu, property, requireComponent } from '../../data/class-decorator';
import { Vec3, Color } from '../../math';
import { GFXClearFlag } from '../../gfx/define';
import { Camera } from '../../renderer';
import { UITransformComponent } from './ui-transform-component';
import { Node } from '../../scene-graph/node';
import { RenderTexture } from '../../assets/render-texture';
import { GFXWindow } from '../../gfx/window';
import { director, Director } from '../../director';
import { view, ResolutionPolicy } from '../../platform/view';
import visibleRect from '../../platform/visible-rect';
import { CameraComponent } from '../../3d/framework/camera-component';
import { RenderTexture } from '../../assets/render-texture';
import { ccclass, disallowMultiple, executeInEditMode, executionOrder, menu, property, requireComponent } from '../../data/class-decorator';
import { director, Director } from '../../director';
import { game } from '../../game';
import { GFXClearFlag } from '../../gfx/define';
import { GFXWindow } from '../../gfx/window';
import { Color, Vec3 } from '../../math';
import { ResolutionPolicy, view } from '../../platform/view';
import visibleRect from '../../platform/visible-rect';
import { Camera } from '../../renderer';
import { Node } from '../../scene-graph/node';
import { INode } from '../../utils/interfaces';
import { Enum } from '../../value-types';
import { game } from '../../game';
import { Component } from '../component';
import { UITransformComponent } from './ui-transform-component';
const _worldPos = new Vec3();
@@ -74,7 +74,7 @@ const RenderMode = Enum({
export class CanvasComponent extends Component {
@property({
type: CanvasClearFlag,
tooltip:'清理屏幕缓冲标记',
tooltip: '清理屏幕缓冲标记',
})
get clearFlag () {
return this._clearFlag;
@@ -88,7 +88,7 @@ export class CanvasComponent extends Component {
}
@property({
tooltip:'清理颜色缓冲区后的颜色',
tooltip: '清理颜色缓冲区后的颜色',
})
get color () {
return this._color;
@@ -106,7 +106,7 @@ export class CanvasComponent extends Component {
@property({
type: RenderMode,
tooltip:'Canvas 渲染模式,intersperse 下可以指定 Canvas 与场景中的相机的渲染顺序,overlay 下 Canvas 会在所有场景相机渲染完成后渲染。\n注意:启用 intersperse 模式,如果 3D 场景的相机内容显示上要在 Canvas 前面,相机的 clearFlags 也要为 none',
tooltip: 'Canvas 渲染模式,intersperse 下可以指定 Canvas 与场景中的相机的渲染顺序,overlay 下 Canvas 会在所有场景相机渲染完成后渲染。\n注意:启用 intersperse 模式,如果 3D 场景的相机内容显示上要在 Canvas 前面,相机的 clearFlags 也要为 none',
})
get renderMode () {
return this._renderMode;
@@ -126,7 +126,7 @@ export class CanvasComponent extends Component {
* @param value - 渲染优先级。
*/
@property({
tooltip:'相机排序优先级。当 RenderMode 为 intersperse 时,指定与其它相机的渲染顺序,当 RenderMode 为 overlay 时,指定跟其余 Canvas 做排序使用',
tooltip: '相机排序优先级。当 RenderMode 为 intersperse 时,指定与其它相机的渲染顺序,当 RenderMode 为 overlay 时,指定跟其余 Canvas 做排序使用',
})
get priority () {
return this._priority;
@@ -137,6 +137,10 @@ export class CanvasComponent extends Component {
if (this._camera) {
this._camera.priority = this._getViewPriority();
}
if (director.root && director.root.ui){
director.root.ui.sortScreens();
}
}
/**
@@ -144,14 +148,14 @@ export class CanvasComponent extends Component {
*/
@property({
type: RenderTexture,
tooltip:'目标渲染纹理',
tooltip: '目标渲染纹理',
})
get targetTexture (){
return this._targetTexture;
}
set targetTexture (value) {
if(this._targetTexture === value){
if (this._targetTexture === value){
return;
}
@@ -212,7 +216,8 @@ export class CanvasComponent extends Component {
const cameraNode = new Node('UICamera_' + this.node.name);
cameraNode.setPosition(0, 0, 1000);
if (!CC_EDITOR) {
this._camera = director.root!.ui.renderScene.createCamera({
this._camera = director.root!.createCamera();
this._camera.initialize({
name: 'ui_' + this.node.name,
node: cameraNode as INode,
projection: CameraComponent.ProjectionType.ORTHO,
@@ -246,17 +251,22 @@ export class CanvasComponent extends Component {
director.root!.ui.addScreen(this);
}
// public onEnable (){
public onEnable () {
if (this._camera) {
director.root!.ui.renderScene.addCamera(this._camera);
}
}
// }
// public onDisable () {
// }
public onDisable () {
if (this._camera) {
director.root!.ui.renderScene.removeCamera(this._camera);
}
}
public onDestroy () {
director.root!.ui.removeScreen(this);
if (this._camera) {
director.root!.ui.renderScene.destroyCamera(this._camera);
director.root!.destroyCamera(this._camera);
}
if (CC_EDITOR) {
@@ -268,7 +278,6 @@ export class CanvasComponent extends Component {
}
view.off('design-resolution-changed', this._thisOnResized);
director.root!.ui.removeScreen(this);
// if (CanvasComponent.instance === this) {
// CanvasComponent.instance = null;
// }
@@ -359,12 +368,12 @@ export class CanvasComponent extends Component {
// }
// }
protected _chechTargetTextureEvent(old: RenderTexture | null) {
protected _chechTargetTextureEvent (old: RenderTexture | null) {
const resizeFunc = (window: GFXWindow) => {
if (this._camera) {
this._camera.setFixedSize(window.width, window.height);
}
}
};
if (old) {
old.off('resize');
@@ -375,7 +384,7 @@ export class CanvasComponent extends Component {
}
}
protected _updateTargetTexture() {
protected _updateTargetTexture () {
if (!this._camera) {
return;
}
+5 -114
View File
@@ -27,82 +27,34 @@
* @category ui
*/
import { ccclass, disallowMultiple, executeInEditMode, executionOrder, property } from '../../../core/data/class-decorator';
import { SystemEventType } from '../../../core/platform/event-manager/event-enum';
import { ccclass, disallowMultiple, executeInEditMode, executionOrder, property, requireComponent } from '../../../core/data/class-decorator';
import { INode } from '../../../core/utils/interfaces';
import { UI } from '../../renderer/ui/ui';
import { Component } from '../component';
import { CanvasComponent } from './canvas-component';
import { UITransformComponent } from './ui-transform-component';
/**
* @zh
* UI 及 UI 模型渲染基类。
*/
@ccclass('cc.UIComponent')
@requireComponent(UITransformComponent)
@executionOrder(110)
@disallowMultiple
@executeInEditMode
export class UIComponent extends Component {
/**
* @zh
* 渲染先后顺序,按照广度渲染排列,按同级节点下进行一次排列。
*/
@property({
tooltip:'渲染排序优先级'
})
get priority () {
return this._priority;
}
set priority (value) {
if (this._priority === value) {
return;
}
this._priority = value;
this._sortSiblings();
}
/**
* @zh
* 查找被渲染相机。
*/
get visibility () {
if (!this._screen){
return -1;
}
return this._screen.visibility;
}
get _screen (){
return this._followScreen;
}
@property
protected _priority = 0;
protected _followScreen: CanvasComponent | null = null;
private _lastParent: INode | null = null;
protected _lastParent: INode | null = null;
public __preload () {
this.node._uiComp = this;
}
public onEnable () {
this._lastParent = this.node.parent;
this._updateVisibility();
if (this._lastParent) {
this.node.on(SystemEventType.CHILD_REMOVED, this._parentChanged, this);
}
this._sortSiblings();
}
public onDisable () {
this._cancelEventFromParent();
}
public onDestroy () {
@@ -116,65 +68,4 @@ export class UIComponent extends Component {
public postUpdateAssembler (render: UI) {
}
public _setScreen (value: CanvasComponent){
this._followScreen = value;
}
protected _parentChanged (node: INode) {
if (node === this.node) {
this._updateVisibility();
this._cancelEventFromParent();
this._lastParent = this.node.parent;
this._sortSiblings();
return true;
}
return false;
}
private _sortSiblings () {
const siblings = this.node.parent && this.node.parent.children as Mutable<INode[]>;
if (siblings) {
siblings.sort((a: INode, b: INode) => {
const aComp = a._uiComp;
const bComp = b._uiComp;
const ca = aComp ? aComp.priority : 0;
const cb = bComp ? bComp.priority : 0;
const diff = ca - cb;
if(diff === 0){
return a.getSiblingIndex() - b.getSiblingIndex();
}
return diff;
});
this.node.parent!._updateSiblingIndex();
}
}
private _updateVisibility () {
let parent = this.node;
// 获取被渲染相机的 visibility
while (parent) {
if (parent) {
const canvasComp = parent.getComponent(CanvasComponent);
if (canvasComp) {
this._followScreen = canvasComp;
break;
}
}
// @ts-ignore
parent = parent.parent;
}
}
private _cancelEventFromParent () {
if (this._lastParent) {
this._lastParent.off(SystemEventType.CHILD_REMOVED, this._parentChanged, this);
this._lastParent = null;
}
this._followScreen = null;
}
}
@@ -29,10 +29,7 @@
import {
ccclass,
executeInEditMode,
executionOrder,
property,
requireComponent,
} from '../../../core/data/class-decorator';
import { SystemEventType } from '../../../core/platform/event-manager/event-enum';
import { Color } from '../../../core/math';
@@ -44,7 +41,8 @@ import { Material } from '../../assets';
import { RenderableComponent } from '../../../core/3d/framework/renderable-component';
import { IAssembler, IAssemblerManager } from '../../renderer/ui/base';
import { UIComponent } from './ui-component';
import { UITransformComponent } from './ui-transform-component';
import { TransformBit } from '../../scene-graph/node-enum';
import { INode } from '../../utils/interfaces';
// hack
ccenum(GFXBlendFactor);
@@ -79,9 +77,6 @@ export enum InstanceMaterialType {
* 可通过 cc.UIRenderComponent 获得该组件。
*/
@ccclass('cc.UIRenderComponent')
@executionOrder(110)
@requireComponent(UITransformComponent)
@executeInEditMode
export class UIRenderComponent extends UIComponent {
/**
@@ -206,8 +201,8 @@ export class UIRenderComponent extends UIComponent {
}
// Render data can be submitted even if it is not on the node tree
set simulate (value) {
this._simulate = value;
set delegateSrc (value: INode) {
this._delegateSrc = value;
}
public static BlendState = GFXBlendFactor;
@@ -228,8 +223,8 @@ export class UIRenderComponent extends UIComponent {
protected _renderData: RenderData | null = null;
protected _renderDataFlag = true;
protected _renderFlag = true;
// 特殊渲染标记,在可渲染情况下,因为自身某个原因不给予渲染
// protected _renderPermit = true;
// 特殊渲染节点,给一些不在节点树上的组件做依赖渲染(例如 mask 组件内置两个 graphics 来渲染)
protected _delegateSrc: INode | null = null;
protected _material: Material | null = null;
protected _instanceMaterialType = InstanceMaterialType.ADDCOLORANDTEXTURE;
protected _blendTemplate = {
@@ -244,7 +239,6 @@ export class UIRenderComponent extends UIComponent {
depthStencilState: {},
rasterizerState: {},
};
protected _simulate = false;
public __preload (){
super.__preload();
@@ -354,7 +348,7 @@ export class UIRenderComponent extends UIComponent {
}
protected _canRender () {
return this.material !== null && this.enabled && (this._simulate? true: this.enabledInHierarchy);
return this.material !== null && this.enabled && (this._delegateSrc ? this._delegateSrc.activeInHierarchy : this.enabledInHierarchy);
}
protected _postCanRender(){}
@@ -387,7 +381,7 @@ export class UIRenderComponent extends UIComponent {
}
// pos, rot, scale changed
protected _nodeStateChange (type: SystemEventType){
protected _nodeStateChange (type: TransformBit){
if (this._renderData) {
this.markForUpdateRenderData();
}
@@ -35,7 +35,7 @@ import { Mat4, Rect, Size, Vec2, Vec3 } from '../../math';
import { aabb } from '../../geom-utils';
import { CanvasComponent } from './canvas-component';
import { director } from '../../director';
import { Layers } from '../../scene-graph/layers';
import { INode } from '../../utils/interfaces';
const _vec2a = new Vec2();
const _vec2b = new Vec2();
@@ -181,16 +181,75 @@ export class UITransformComponent extends Component {
this.node.emit(SystemEventType.ANCHOR_CHANGED, this._anchorPoint);
}
/**
* @zh
* 渲染先后顺序,按照广度渲染排列,按同级节点下进行一次排列。
*/
@property({
tooltip: '渲染排序优先级'
})
get priority() {
return this._priority;
}
set priority(value) {
if (this._priority === value) {
return;
}
if (this._canvas && this._canvas.node === this.node) {
cc.warn(9200);
return;
}
this._priority = value;
this._sortSiblings();
}
@property
protected _priority = 0;
/**
* @zh
* 查找被渲染相机。
*/
get visibility() {
if (!this._screen) {
return -1;
}
return this._screen.visibility;
}
get _screen() {
return this._canvas;
}
public static EventType = SystemEventType;
@property
private _contentSize = new Size(100, 100);
protected _contentSize = new Size(100, 100);
@property
private _anchorPoint = new Vec2(0.5, 0.5);
protected _anchorPoint = new Vec2(0.5, 0.5);
public _canvas: CanvasComponent | null = null;
public __preload () {
this.node.uiTransfromComp = this;
}
public onEnable(){
this._updateVisibility();
this.node.on(SystemEventType.PARENT_CHANGED, this._parentChanged, this);
this._sortSiblings();
}
public onDisable(){
this.node.off(SystemEventType.PARENT_CHANGED, this._parentChanged, this);
this._canvas = null;
}
public onDestroy () {
this.node.uiTransfromComp = null;
}
@@ -292,22 +351,12 @@ export class UITransformComponent extends Component {
* @param listener - 事件监听器。
*/
public isHit (point: Vec2, listener?: EventListener) {
// console.log('click point ' + point.toString());
const w = this._contentSize.width;
const h = this._contentSize.height;
const cameraPt = _vec2a;
const testPt = _vec2b;
// hack: discuss how to distribute 3D event
let visibility = -1;
const renderComp = this.node.getComponent(cc.UIRenderComponent) as any;
if (!renderComp) {
visibility = this._getVisibility();
} else {
visibility = renderComp.visibility;
}
const canvas = director.root!.ui.getScreen(visibility);
const canvas = this._canvas;
if (!canvas) {
return;
}
@@ -360,7 +409,7 @@ export class UITransformComponent extends Component {
* @returns - 返回与目标节点的相对位置。
* @example
* ```typescript
* var newVec3 = uiTransform.convertToNodeSpaceAR(cc.v3(100, 100, 0));
* const newVec3 = uiTransform.convertToNodeSpaceAR(cc.v3(100, 100, 0));
* ```
*/
public convertToNodeSpaceAR (worldPoint: Vec3, out?: Vec3) {
@@ -382,7 +431,7 @@ export class UITransformComponent extends Component {
* @returns - 返回 UI 世界坐标系。
* @example
* ```typescript
* var newVec3 = uiTransform.convertToWorldSpaceAR(3(100, 100, 0));
* const newVec3 = uiTransform.convertToWorldSpaceAR(3(100, 100, 0));
* ```
*/
public convertToWorldSpaceAR (nodePoint: Vec3, out?: Vec3) {
@@ -401,7 +450,7 @@ export class UITransformComponent extends Component {
* @return - 节点大小的包围盒
* @example
* ```typescript
* var boundingBox = uiTransform.getBoundingBox();
* const boundingBox = uiTransform.getBoundingBox();
* ```
*/
public getBoundingBox () {
@@ -425,7 +474,7 @@ export class UITransformComponent extends Component {
* @returns - 返回世界坐标系下包围盒。
* @example
* ```typescript
* var newRect = uiTransform.getBoundingBoxToWorld();
* const newRect = uiTransform.getBoundingBoxToWorld();
* ```
*/
public getBoundingBoxToWorld () {
@@ -506,15 +555,14 @@ export class UITransformComponent extends Component {
}
}
private _getVisibility () {
let visibility = -1;
public _updateVisibility() {
let parent = this.node;
// 获取被渲染相机的 visibility
while (parent) {
if (parent) {
const canvasComp = parent.getComponent('cc.CanvasComponent') as CanvasComponent;
if (canvasComp) {
visibility = canvasComp.visibility;
this._canvas = canvasComp;
break;
}
}
@@ -522,8 +570,33 @@ export class UITransformComponent extends Component {
// @ts-ignore
parent = parent.parent;
}
}
return visibility;
protected _parentChanged(node: INode) {
if (this._canvas && this._canvas.node === this.node) {
return;
}
this._sortSiblings();
}
protected _sortSiblings() {
const siblings = this.node.parent && this.node.parent.children as Mutable<INode[]>;
if (siblings) {
siblings.sort((a: INode, b: INode) => {
const aComp = a.uiTransfromComp;
const bComp = b.uiTransfromComp;
const ca = aComp ? aComp.priority : 0;
const cb = bComp ? bComp.priority : 0;
const diff = ca - cb;
if (diff === 0) {
return a.getSiblingIndex() - b.getSiblingIndex();
}
return diff;
});
this.node.parent!._updateSiblingIndex();
}
}
}
@@ -0,0 +1,178 @@
/*
Copyright (c) 2013-2016 Chukong Technologies Inc.
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 { Component } from './component';
import { EventHandler } from './component-event-handler';
import { ccclass, property, menu, executionOrder } from '../data/class-decorator';
import { Node } from '../scene-graph';
import { convertUtils } from '../utils';
import { CameraComponent } from '../3d';
import { Vec3 } from '../math';
/**
* @zh 3D 节点映射 UI 节点组件
* 主要提供映射后的转换世界坐标以及模拟透视相机远近比。
*/
@ccclass('cc.UICoordinateTrackerComponent')
@menu('Components/UICoordinateTracker')
@executionOrder(110)
export class UICoordinateTrackerComponent extends Component {
/**
* @zh
* 目标对象。
*/
@property({
type: Node,
tooltip: '目标对象',
})
get target () {
return this._target;
}
set target (value) {
if (this._target === value) {
return;
}
this._target = value;
this._checkCanMove();
}
/**
* @zh
* 照射相机。
*/
@property({
type: CameraComponent,
tooltip: '照射相机',
})
get camera () {
return this._camera;
}
set camera (value) {
if (this._camera === value) {
return;
}
this._camera = value;
this._checkCanMove();
}
/**
* @zh
* 是否是缩放映射。
*/
@property({
tooltip: '是否是缩放映射',
})
get useScale () {
return this._useScale;
}
set useScale (value) {
if (this._useScale === value) {
return;
}
this._useScale = value;
}
/**
* @zh
* 距相机多少距离为正常显示计算大小。
*/
@property({
tooltip: '距相机多少距离为正常显示计算大小',
})
get distance () {
return this._distance;
}
set distance (value) {
if (this._distance === value) {
return;
}
this._distance = value;
}
/**
* @zh
* 映射数据事件。回调的第一个参数是映射后的本地坐标,第二个是距相机距离比。
*/
@property({
type: [EventHandler],
tooltip: '映射数据事件。回调的第一个参数是映射后的本地坐标,第二个是距相机距离比',
})
public syncEvents: EventHandler[] = [];
@property
protected _target: Node | null = null;
@property
protected _camera: CameraComponent | null = null;
@property
protected _useScale = true;
@property
protected _distance = 1;
protected _transformPos = new Vec3();
protected _viewPos = new Vec3();
protected _canMove = true;
protected _lastWpos = new Vec3();
public onEnable () {
this._checkCanMove();
}
public update () {
const wpos = this.node.worldPosition;
// @ts-ignore
if (!this._canMove || !this._camera!._camera || this._lastWpos.equals(wpos)) {
return;
}
this._lastWpos.set(wpos);
const camera = this._camera!;
// [HACK]
// @ts-ignore
camera._camera.update();
convertUtils.WorldNode3DToLocalNodeUI(camera, wpos, this._target!, this._transformPos);
if (this._useScale) {
// @ts-ignore
Vec3.transformMat4(this._viewPos, this.node.worldPosition, camera._camera!.matView);
}
if (this.syncEvents.length > 0) {
const data = this._distance / Math.abs(this._viewPos.z);
EventHandler.emitEvents(this.syncEvents, this._transformPos, data);
}
}
protected _checkCanMove () {
this._canMove = !!(this._camera && this._target);
}
}
+6
View File
@@ -346,6 +346,12 @@ export function property (ctorProtoOrOptions?, propName?, desc?) {
genProperty(ctorProto.constructor, properties, propName, options, desc, cache);
}
}
if (ctorProtoOrOptions === undefined) {
// @property(undefined)
return property({
type: undefined,
});
}
if (typeof propName === 'undefined') {
options = ctorProtoOrOptions;
return normalized;
+5 -1
View File
@@ -1,4 +1,4 @@
/*
/*
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
@@ -1147,6 +1147,10 @@ function parseAttributes (constructor: Function, attributes: IAcceptableAttribut
tmpAttrs.length = 0;
const result: IParsedAttribute[] = tmpAttrs;
if ('type' in attributes && typeof attributes.type === 'undefined') {
warnID(3660, propertyName, className);
}
const type = attributes.type;
if (type) {
const primitiveType = PrimitiveTypes[type];
+1 -1
View File
@@ -28,7 +28,7 @@
* @hidden
*/
import Pool from '../memop/pool';
import { Pool } from '../memop';
import { array, createMap } from '../utils/js';
const fastRemoveAt = array.fastRemoveAt;
+2 -24
View File
@@ -498,7 +498,6 @@ export class Game extends EventTarget {
if (err || !(asset instanceof cc.RenderPipeline)) {
console.error(`Failed load renderpipeline: ${config.renderpipeline}`);
console.error(err);
cc.game.setRenderPipeline(null);
} else {
cc.game.setRenderPipeline(asset);
@@ -628,12 +627,7 @@ export class Game extends EventTarget {
if (cb) { cb(); }
};
if (!CC_EDITOR && CC_WECHATGAME) {
SplashScreen.instance.setOnFinish(start);
SplashScreen.instance.loadFinish = true;
} else {
start();
}
start();
}
// @Methods
@@ -797,10 +791,8 @@ export class Game extends EventTarget {
let height: any;
let localCanvas: HTMLCanvasElement;
let localContainer: HTMLElement;
const isWeChatGame = cc.sys.platform === cc.sys.WECHAT_GAME;
const isQQPlay = cc.sys.platform === cc.sys.QQ_PLAY;
if (isWeChatGame || CC_JSB) {
if (CC_JSB) {
this.container = localContainer = document.createElement<'div'>('div');
this.frame = localContainer.parentNode === document.body ? document.documentElement : localContainer.parentNode;
if (cc.sys.browserType === cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB) {
@@ -814,11 +806,6 @@ export class Game extends EventTarget {
}
this.canvas = localCanvas;
}
else if (isQQPlay) {
this.container = cc.container = document.createElement<'div'>('div');
this.frame = document.documentElement;
this.canvas = localCanvas = window.canvas;
}
else {
const element = !el ? null : ((el instanceof HTMLElement) ? el : (document.querySelector(el) || document.querySelector('#' + el)));
if (!element) {
@@ -968,15 +955,6 @@ export class Game extends EventTarget {
win.onfocus = onShown;
}
if (CC_WECHATGAME && cc.sys.browserType !== cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB) {
if (wx.onShow) {
wx.onShow(onShown);
}
if (wx.onHide) {
wx.onHide(onHidden);
}
}
if ('onpageshow' in window && 'onpagehide' in window) {
win.addEventListener('pagehide', onHidden);
win.addEventListener('pageshow', onShown);
-1
View File
@@ -14,7 +14,6 @@ export { default as sphere } from './sphere';
export { default as aabb } from './aabb';
export { default as obb } from './obb';
export { frustum } from './frustum';
export { default as Octree } from './octree';
export { Keyframe, AnimationCurve } from './curve';
import './deprecated';
-259
View File
@@ -1,259 +0,0 @@
/**
* @category geometry
*/
import { Vec3 } from '../math';
import { FixedArray } from '../memop';
import aabb from './aabb';
import intersect from './intersect';
const mul = (out, v, x, y, z) => {
return Vec3.set(out, v.x * x, v.y * y, v.z * z);
};
class OctreeBlock {
public minPos: Vec3;
public maxPos: Vec3;
public boundingBox: aabb;
public capacity: number;
public depth: number;
public maxDepth: number;
public blocks: null | OctreeBlock[];
public entries: FixedArray;
private _getBoundingShape: Function;
constructor (minPos, maxPos, capacity, depth, maxDepth, getBoundingShape) {
this.minPos = minPos;
this.maxPos = maxPos;
this.boundingBox = aabb.fromPoints(aabb.create(), minPos, maxPos);
this.capacity = capacity;
this.depth = depth;
this.maxDepth = maxDepth;
this._getBoundingShape = getBoundingShape;
this.blocks = null;
this.entries = new FixedArray(this.capacity);
}
public addEntry (entry) {
if (this.blocks) {
for (const block of this.blocks) {
block.addEntry(entry);
}
} else {
const shape = this._getBoundingShape(entry);
if (!intersect.resolve(this.boundingBox, shape)) { return; }
this.entries.push(entry);
if (this.entries.length >= this.capacity && this.depth < this.maxDepth) {
this.blocks = Octree.createBlocks(this.minPos, this.maxPos, this.entries,
this.capacity, this.depth, this.maxDepth, this._getBoundingShape);
this.entries.reset();
}
}
}
public removeEntry (entry) {
if (this.blocks) {
for (const block of this.blocks) {
block.removeEntry(entry);
}
} else {
this.entries.fastRemove(this.entries.indexOf(entry));
}
}
public select (out, shape) {
if (!intersect.resolve(this.boundingBox, shape)) { return; }
if (this.blocks) {
for (const block of this.blocks) {
block.select(out, shape);
}
} else {
for (let i = 0; i < this.entries.length; i++) {
out.add(this.entries.data[i]);
}
}
}
public frustumSelect (out, frustum) {
if (!intersect.aabb_frustum(this.boundingBox, frustum)) { return; }
if (this.blocks) {
for (const block of this.blocks) {
block.frustumSelect(out, frustum);
}
} else {
for (let i = 0; i < this.entries.length; i++) {
out.add(this.entries.data[i]);
}
}
}
}
/**
* An octree acceleration data structure
* @example
* ```
* let octree = new Octree();
* octree.build(models, model => {
* return model._boundingShape;
* });
* octree.select(enums.SHAPE_FRUSTUM, view._frustum);
* ```
*/
export default class Octree {
/**
* @en Create sub blocks and populate them with given entries
* @zh 创建子块,并用给定的条目填充它们
* @param {Vec3} worldMin - min position of the parent bounding box
* @param {Vec3} worldMax - max position of the parent bounding box
* @param {Array<Object>} entries - the entries to be inserted
* @param {number} blockCapacity - maximum capacity for each block node
* before it's been subdivided, might be exceeded if `maxDepth` is reached
* @param {number} curDepth - depth before subdivided
* @param {number} maxDepth - maximum depth of this tree
* @param {function(entry: Object): Object} getBoundingShape - a function takes an entry and returns its primitive info
* @return {OctreeBlock[]} the sub blocks
*/
public static createBlocks (worldMin, worldMax, entries, blockCapacity, curDepth, maxDepth, getBoundingShape) {
const blocks: OctreeBlock[] = [];
const blockSize = new Vec3();
Vec3.multiplyScalar(blockSize, Vec3.subtract(blockSize, worldMax, worldMin), 0.5);
for (let x = 0; x < 2; x++) {
for (let y = 0; y < 2; y++) {
for (let z = 0; z < 2; z++) {
const localMin = new Vec3();
const localMax = new Vec3();
Vec3.add(localMin, worldMin, mul(localMin, blockSize, x, y, z));
Vec3.add(localMax, worldMin, mul(localMax, blockSize, x + 1, y + 1, z + 1));
const block = new OctreeBlock(localMin, localMax,
blockCapacity, curDepth + 1, maxDepth, getBoundingShape);
for (let i = 0; i < entries.length; i++) {
const entry = (entries.data || entries)[i];
block.addEntry(entry);
}
blocks.push(block);
}
}
}
return blocks;
}
public blockCapacity: number;
public maxDepth: number;
public blocks: OctreeBlock[];
public dynamics: any[];
private _selection: Set<any>;
private _getBoundingShape: Function;
/**
* Create a octree structure
* @param {number} blockCapacity - maximum capacity for each block node
* before it's been subdivided, might be exceeded if `maxDepth` is reached
* @param {number} maxDepth - maximum depth of this tree
*/
constructor (blockCapacity = 32, maxDepth = 5) {
this.blockCapacity = blockCapacity;
this.maxDepth = maxDepth;
this.blocks = [];
this.dynamics = [];
this._selection = new Set();
this._getBoundingShape = () => this._getBoundingShape;
}
/**
* @en Build this octree from given entries.<br/>
* Root Boundary is the bounding box of all the entries.
* @zh 从给定的项中构建这个八叉树。根边界是所有这些条目的边界框。
* @param {Array<Object>} entries - a collection of entries to be queried later
* @param {function(entry: Object): Object} getBoundingShape
* - a function takes an entry and returns its primitive info
*/
public build (entries, getBoundingShape) {
// calc world min & max
const worldMin = new Vec3(Infinity, Infinity, Infinity);
const worldMax = new Vec3(-Infinity, -Infinity, -Infinity);
const minPos = new Vec3();
const maxPos = new Vec3();
const staticEntries: any[] = []; this.dynamics = [];
for (let i = 0; i < entries.length; i++) {
const entry = (entries.data || entries)[i];
const shape = getBoundingShape(entry);
if (!shape) {
this.dynamics.push(entry);
} else {
shape.getBoundary(minPos, maxPos);
Vec3.min(worldMin, worldMin, minPos);
Vec3.max(worldMax, worldMax, maxPos);
staticEntries.push(entry);
}
}
this.blocks = Octree.createBlocks(worldMin, worldMax, staticEntries,
this.blockCapacity, 0, this.maxDepth, getBoundingShape);
this._getBoundingShape = getBoundingShape;
}
/**
* @en Add an entry to this tree. Should be called after `build`.
* @zh 在这个树中添加一个条目。应该在构建之后调用。
* @param {Object} entry - the new entry
*/
public addEntry (entry) {
if (!this._getBoundingShape(entry).shape) {
this.dynamics.push(entry);
return;
}
for (const block of this.blocks) {
block.addEntry(entry);
}
}
/**
* @en Remove an entry from this tree. Should be called after `build`.
* @zh 从这个树中删除一个条目。应该在构建之后调用。
* @param {Object} entry - the entry to be removed
*/
public removeEntry (entry) {
if (!this._getBoundingShape(entry).shape) {
this.dynamics.splice(this.dynamics.indexOf(entry), 1);
return;
}
for (const block of this.blocks) {
block.removeEntry(entry);
}
}
/**
* @en Select all the entries overlapping the given primitive
* @zh 选择与给定原始项重叠的所有项
* @param {Object} shape - the selecting primitive
* @return {Set<Object>} the resulting set of entries
*/
public select (shape) {
this._selection.clear();
for (const block of this.blocks) {
block.select(this._selection, shape);
}
for (const dynamic of this.dynamics) {
this._selection.add(dynamic);
}
return this._selection;
}
/**
* Specialized selection for frustums
* @param {Object} frustum - the selecting frustum
* @return {Set<Object>} the resulting set of entries
*/
public frustumSelect (frustum) {
this._selection.clear();
for (const block of this.blocks) {
block.frustumSelect(this._selection, frustum);
}
for (const dynamic of this.dynamics) {
this._selection.add(dynamic);
}
return this._selection;
}
}
+1 -1
View File
@@ -465,7 +465,7 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer {
this.cmdPackage.copyBufferToTextureCmds.push(cmd);
}
this.cmdPackage.cmds.concat(webGLCmdBuff.cmdPackage.cmds);
this.cmdPackage.cmds.concat(webGLCmdBuff.cmdPackage.cmds.array);
this._numDrawCalls += webGLCmdBuff._numDrawCalls;
this._numTris += webGLCmdBuff._numTris;
+34 -18
View File
@@ -424,7 +424,7 @@ export class WebGLCmdBeginRenderPass extends WebGLCmdObject {
public clear () {
this.gpuFramebuffer = null;
this.clearColors = [];
this.clearColors.length = 0;
}
}
@@ -529,7 +529,7 @@ export class WebGLCmdCopyBufferToTexture extends WebGLCmdObject {
this.gpuBuffer = null;
this.gpuTexture = null;
this.dstLayout = null;
this.regions = [];
this.regions.length = 0;
}
}
@@ -1138,7 +1138,8 @@ export function WebGLCmdFuncDestroyFramebuffer (device: WebGLGFXDevice, gpuFrame
export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: WebGLGPUShader) {
const gl = device.gl;
for (const gpuStage of gpuShader.gpuStages) {
for (let k = 0; k < gpuShader.gpuStages.length; k++) {
const gpuStage = gpuShader.gpuStages[k];
let glShaderType: GLenum = 0;
let shaderTypeStr = '';
@@ -1187,7 +1188,8 @@ export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: Web
gpuShader.glProgram = glProgram;
// link program
for (const gpuStage of gpuShader.gpuStages) {
for (let k = 0; k < gpuShader.gpuStages.length; k++) {
const gpuStage = gpuShader.gpuStages[k];
gl.attachShader(gpuShader.glProgram, gpuStage.glShader!);
}
@@ -1198,7 +1200,8 @@ export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: Web
console.error('Failed to link shader \'' + gpuShader.name + '\'.');
console.error(gl.getProgramInfoLog(gpuShader.glProgram));
for (const gpuStage of gpuShader.gpuStages) {
for (let k = 0; k < gpuShader.gpuStages.length; k++) {
const gpuStage = gpuShader.gpuStages[k];
if (gpuStage.glShader) {
gl.deleteShader(gpuStage.glShader);
gpuStage.glShader = null;
@@ -1288,7 +1291,8 @@ export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: Web
/*
glBlock.buffer = new ArrayBuffer(glBlock.size);
for (const glUniform of glBlock.glUniforms) {
for (let k = 0; k < glBlock.glUniforms.length; k++) {
const glUniform = glBlock.glUniforms[k];
switch (glUniform.glType) {
case gl.BOOL:
case gl.BOOL_VEC2:
@@ -1339,7 +1343,7 @@ export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: Web
const uniformInfo = gl.getActiveUniform(gpuShader.glProgram, i);
if (uniformInfo) {
const glLoc = gl.getUniformLocation(gpuShader.glProgram, uniformInfo.name);
if (glLoc) {
if (glLoc !== null) {
let varName: string;
const nameOffset = uniformInfo.name.indexOf('[');
if (nameOffset !== -1) {
@@ -1355,9 +1359,11 @@ export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: Web
// let stride = WebGLGetTypeSize(info.type);
// build uniform block mapping
for (const glBlock of gpuShader.glBlocks) {
for (let j = 0; j < gpuShader.glBlocks.length; j++) {
const glBlock = gpuShader.glBlocks[j];
for (const glUniform of glBlock.glUniforms) {
for (let k = 0; k < glBlock.glUniforms.length; k++) {
const glUniform = glBlock.glUniforms[k];
if (glUniform.name === varName) {
// let varSize = stride * info.size;
@@ -1370,7 +1376,8 @@ export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: Web
} // for
} else {
for (const glSampler of gpuShader.glSamplers) {
for (let j = 0; j < gpuShader.glSamplers.length; j++) {
const glSampler = gpuShader.glSamplers[j];
if (glSampler.name === varName) {
// let varSize = stride * uniformInfo.size;
@@ -1397,7 +1404,8 @@ export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: Web
device.stateCache.glProgram = gpuShader.glProgram;
}
for (const glSampler of glActiveSamplers) {
for (let i = 0; i < glActiveSamplers.length; i++) {
const glSampler = glActiveSamplers[i];
gl.uniform1iv(glSampler.glLoc, glSampler.units);
}
}
@@ -1405,7 +1413,8 @@ export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: Web
export function WebGLCmdFuncDestroyShader (device: WebGLGFXDevice, gpuShader: WebGLGPUShader) {
for (const gpuStage of gpuShader.gpuStages) {
for (let i = 0; i < gpuShader.gpuStages.length; i++) {
const gpuStage = gpuShader.gpuStages[i];
if (gpuStage.glShader) {
device.gl.deleteShader(gpuStage.glShader);
gpuStage.glShader = null;
@@ -1454,8 +1463,11 @@ export function WebGLCmdFuncCreateInputAssember (device: WebGLGFXDevice, gpuInpu
}
export function WebGLCmdFuncDestroyInputAssembler (device: WebGLGFXDevice, gpuInputAssembler: IWebGLGPUInputAssembler) {
for (const vao of gpuInputAssembler.glVAOs) {
device.OES_vertex_array_object!.deleteVertexArrayOES(vao[1]);
const it = gpuInputAssembler.glVAOs.values();
let res = it.next();
while (!res.done) {
device.OES_vertex_array_object!.deleteVertexArrayOES(res.value);
res = it.next();
}
gpuInputAssembler.glVAOs.clear();
}
@@ -2558,7 +2570,8 @@ export function WebGLCmdFuncCopyTexImagesToTexture (
switch (gpuTexture.glTarget) {
case gl.TEXTURE_2D: {
for (const region of regions) {
for (let i = 0; i < regions.length; i++) {
const region = regions[i];
// console.debug('Copying image to texture 2D: ' + region.texExtent.width + ' x ' + region.texExtent.height);
for (m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) {
gl.texSubImage2D(gl.TEXTURE_2D, m,
@@ -2569,7 +2582,8 @@ export function WebGLCmdFuncCopyTexImagesToTexture (
break;
}
case gl.TEXTURE_CUBE_MAP: {
for (const region of regions) {
for (let i = 0; i < regions.length; i++) {
const region = regions[i];
// console.debug('Copying image to texture cube: ' + region.texExtent.width + ' x ' + region.texExtent.height);
const fcount = region.texSubres.baseArrayLayer + region.texSubres.layerCount;
for (f = region.texSubres.baseArrayLayer; f < fcount; ++f) {
@@ -2617,7 +2631,8 @@ export function WebGLCmdFuncCopyBuffersToTexture (
const isCompressed = fmtInfo.isCompressed;
switch (gpuTexture.glTarget) {
case gl.TEXTURE_2D: {
for (const region of regions) {
for (let i = 0; i < regions.length; i++) {
const region = regions[i];
w = region.texExtent.width;
h = region.texExtent.height;
// console.debug('Copying buffer to texture 2D: ' + w + ' x ' + h);
@@ -2647,7 +2662,8 @@ export function WebGLCmdFuncCopyBuffersToTexture (
break;
}
case gl.TEXTURE_CUBE_MAP: {
for (const region of regions) {
for (let i = 0; i < regions.length; i++) {
const region = regions[i];
n = 0;
const fcount = region.texSubres.baseArrayLayer + region.texSubres.layerCount;
for (f = region.texSubres.baseArrayLayer; f < fcount; ++f) {
@@ -459,7 +459,7 @@ export class WebGL2GFXCommandBuffer extends GFXCommandBuffer {
this.cmdPackage.copyBufferToTextureCmds.push(cmd);
}
this.cmdPackage.cmds.concat(webGLCmdBuff.cmdPackage.cmds);
this.cmdPackage.cmds.concat(webGLCmdBuff.cmdPackage.cmds.array);
this._numDrawCalls += webGLCmdBuff._numDrawCalls;
this._numTris += webGLCmdBuff._numTris;
+56 -37
View File
@@ -575,7 +575,7 @@ export class WebGL2CmdBeginRenderPass extends WebGL2CmdObject {
public clear () {
this.gpuFramebuffer = null;
this.clearColors = [];
this.clearColors.length = 0;
}
}
@@ -679,7 +679,7 @@ export class WebGL2CmdCopyBufferToTexture extends WebGL2CmdObject {
this.gpuBuffer = null;
this.gpuTexture = null;
this.dstLayout = null;
this.regions = [];
this.regions.length = 0;
}
}
@@ -928,18 +928,11 @@ export function WebGL2CmdFuncUpdateBuffer (device: WebGL2GFXDevice, gpuBuffer: W
cache.glUniformBuffer = gpuBuffer.glBuffer;
}
let buf: Float32Array;
if (buffer instanceof Float32Array) {
buf = buffer;
} else {
buf = new Float32Array(buff, 0, size / 4);
}
if (size === buf.byteLength) {
gl.bufferSubData(gpuBuffer.glTarget, offset, buf);
if (size === buff.byteLength) {
gl.bufferSubData(gpuBuffer.glTarget, offset, buff);
// if (gl.getBufferParameter(gl.UNIFORM_BUFFER, gl.BUFFER_SIZE) !== buff.length * 4) { debugger; }
} else {
gl.bufferSubData(gpuBuffer.glTarget, offset, new Float32Array(buf.buffer, 0, size / 4));
gl.bufferSubData(gpuBuffer.glTarget, offset, new Float32Array(buff, 0, size / 4));
}
break;
}
@@ -1387,7 +1380,8 @@ export function WebGL2CmdFuncDestroyFramebuffer (device: WebGL2GFXDevice, gpuFra
export function WebGL2CmdFuncCreateShader (device: WebGL2GFXDevice, gpuShader: WebGL2GPUShader) {
const gl = device.gl;
for (const gpuStage of gpuShader.gpuStages) {
for (let k = 0; k < gpuShader.gpuStages.length; k++) {
const gpuStage = gpuShader.gpuStages[k];
let glShaderType: GLenum = 0;
let shaderTypeStr = '';
@@ -1436,7 +1430,8 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2GFXDevice, gpuShader: W
gpuShader.glProgram = glProgram;
// link program
for (const gpuStage of gpuShader.gpuStages) {
for (let k = 0; k < gpuShader.gpuStages.length; k++) {
const gpuStage = gpuShader.gpuStages[k];
gl.attachShader(gpuShader.glProgram, gpuStage.glShader!);
}
@@ -1447,7 +1442,8 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2GFXDevice, gpuShader: W
console.error('Failed to link shader \'' + gpuShader.name + '\'.');
console.error(gl.getProgramInfoLog(gpuShader.glProgram));
for (const gpuStage of gpuShader.gpuStages) {
for (let k = 0; k < gpuShader.gpuStages.length; k++) {
const gpuStage = gpuShader.gpuStages[k];
if (gpuStage.glShader) {
gl.deleteShader(gpuStage.glShader);
gpuStage.glShader = null;
@@ -1518,7 +1514,8 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2GFXDevice, gpuShader: W
// blockIdx = gl.getUniformBlockIndex(gpuShader.glProgram, blockName);
blockBinding = -1;
for (const block of gpuShader.blocks) {
for (let k = 0; k < gpuShader.blocks.length; k++) {
const block = gpuShader.blocks[k];
if (block.name === blockName) {
blockBinding = block.binding;
break;
@@ -1612,7 +1609,7 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2GFXDevice, gpuShader: W
const uniformInfo = gl.getActiveUniform(gpuShader.glProgram, i);
if (uniformInfo) {
const glLoc = gl.getUniformLocation(gpuShader.glProgram, uniformInfo.name);
if (glLoc) {
if (glLoc !== null) {
let varName: string;
const nameOffset = uniformInfo.name.indexOf('[');
if (nameOffset !== -1) {
@@ -1625,7 +1622,8 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2GFXDevice, gpuShader: W
(uniformInfo.type === gl.SAMPLER_CUBE);
if (isSampler) {
for (const glSampler of gpuShader.glSamplers) {
for (let k = 0; k < gpuShader.glSamplers.length; k++) {
const glSampler = gpuShader.glSamplers[k];
if (glSampler.name === varName) {
// let varSize = stride * uniformInfo.size;
@@ -1652,7 +1650,8 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2GFXDevice, gpuShader: W
device.stateCache.glProgram = gpuShader.glProgram;
}
for (const glSampler of glActiveSamplers) {
for (let k = 0; k < glActiveSamplers.length; k++) {
const glSampler = glActiveSamplers[k];
gl.uniform1iv(glSampler.glLoc, glSampler.units);
}
}
@@ -1660,7 +1659,8 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2GFXDevice, gpuShader: W
export function WebGL2CmdFuncDestroyShader (device: WebGL2GFXDevice, gpuShader: WebGL2GPUShader) {
for (const gpuStage of gpuShader.gpuStages) {
for (let k = 0; k < gpuShader.gpuStages.length; k++) {
const gpuStage = gpuShader.gpuStages[k];
if (gpuStage.glShader) {
device.gl.deleteShader(gpuStage.glShader);
gpuStage.glShader = null;
@@ -1710,8 +1710,11 @@ export function WebGL2CmdFuncCreateInputAssember (device: WebGL2GFXDevice, gpuIn
}
export function WebGL2CmdFuncDestroyInputAssembler (device: WebGL2GFXDevice, gpuInputAssembler: IWebGL2GPUInputAssembler) {
for (const vao of gpuInputAssembler.glVAOs) {
device.gl.deleteVertexArray(vao[1]);
const it = gpuInputAssembler.glVAOs.values();
let res = it.next();
while (!res.done) {
device.gl.deleteVertexArray(res.value);
res = it.next();
}
gpuInputAssembler.glVAOs.clear();
}
@@ -1906,7 +1909,7 @@ export function WebGL2CmdFuncExecuteCmds (device: WebGL2GFXDevice, cmdPackage: W
break;
}
case WebGL2Cmd.END_RENDER_PASS: {
// WebGL 1.0 doesn't support store operation of attachments.
// WebGL 2.0 doesn't support store operation of attachments.
// GFXStoreOp.Store is the default GL behaviour.
break;
}
@@ -2160,13 +2163,16 @@ export function WebGL2CmdFuncExecuteCmds (device: WebGL2GFXDevice, cmdPackage: W
} // bind pso
if (cmd2.gpuBindingLayout && gpuShader) {
for (const gpuBinding of cmd2.gpuBindingLayout.gpuBindings) {
const gpuBindings = cmd2.gpuBindingLayout.gpuBindings;
for (let j = 0; j < gpuBindings.length; j++) {
const gpuBinding = gpuBindings[j];
switch (gpuBinding.type) {
case GFXBindingType.UNIFORM_BUFFER: {
if (gpuBinding.gpuBuffer) {
for (const glBlock of gpuShader.glBlocks) {
for (let k = 0; k < gpuShader.glBlocks.length; k++) {
const glBlock = gpuShader.glBlocks[k];
if (glBlock.binding === gpuBinding.binding) {
if (cache.glBindUBOs[glBlock.binding] !== gpuBinding.gpuBuffer.glBuffer) {
gl.bindBufferBase(gl.UNIFORM_BUFFER, glBlock.binding, gpuBinding.gpuBuffer.glBuffer);
@@ -2187,7 +2193,8 @@ export function WebGL2CmdFuncExecuteCmds (device: WebGL2GFXDevice, cmdPackage: W
let glSampler: WebGL2GPUUniformSampler | null = null;
for (const sampler of gpuShader.glSamplers) {
for (let k = 0; k < gpuShader.glSamplers.length; k++) {
const sampler = gpuShader.glSamplers[k];
if (sampler.binding === gpuBinding.binding) {
glSampler = sampler;
break;
@@ -2195,7 +2202,8 @@ export function WebGL2CmdFuncExecuteCmds (device: WebGL2GFXDevice, cmdPackage: W
}
if (glSampler) {
for (const texUnit of glSampler.units) {
for (let k = 0; k < glSampler.units.length; k++) {
const texUnit = glSampler.units[k];
const glTexUnit = cache.glTexUnits[texUnit];
@@ -2250,10 +2258,12 @@ export function WebGL2CmdFuncExecuteCmds (device: WebGL2GFXDevice, cmdPackage: W
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
let glAttrib: WebGL2Attrib | null;
for (const glInput of gpuShader.glInputs) {
for (let j = 0; j < gpuShader.glInputs.length; j++) {
const glInput = gpuShader.glInputs[j];
glAttrib = null;
for (const attrib of gpuInputAssembler.glAttribs) {
for (let k = 0; k < gpuInputAssembler.glAttribs.length; k++) {
const attrib = gpuInputAssembler.glAttribs[k];
if (attrib.name === glInput.name) {
glAttrib = attrib;
break;
@@ -2297,10 +2307,12 @@ export function WebGL2CmdFuncExecuteCmds (device: WebGL2GFXDevice, cmdPackage: W
cache.glCurrentAttribLocs[a] = false;
}
for (const glInput of gpuShader.glInputs) {
for (let j = 0; j < gpuShader.glInputs.length; j++) {
const glInput = gpuShader.glInputs[j];
let glAttrib: WebGL2Attrib | null = null;
for (const attrib of gpuInputAssembler.glAttribs) {
for (let k = 0; k < gpuInputAssembler.glAttribs.length; k++) {
const attrib = gpuInputAssembler.glAttribs[k];
if (attrib.name === glInput.name) {
glAttrib = attrib;
break;
@@ -2346,7 +2358,8 @@ export function WebGL2CmdFuncExecuteCmds (device: WebGL2GFXDevice, cmdPackage: W
}
if (gpuPipelineState) {
for (const dynamicState of gpuPipelineState.dynamicStates) {
for (let k = 0; k < gpuPipelineState.dynamicStates.length; k++) {
const dynamicState = gpuPipelineState.dynamicStates[k];
switch (dynamicState) {
case GFXDynamicState.VIEWPORT: {
if (cmd2.viewport) {
@@ -2517,7 +2530,9 @@ export function WebGL2CmdFuncExecuteCmds (device: WebGL2GFXDevice, cmdPackage: W
}
} else {
if (gpuInputAssembler.gpuIndirectBuffer) {
for (const drawInfo of gpuInputAssembler.gpuIndirectBuffer.indirects) {
const indirects = gpuInputAssembler.gpuIndirectBuffer.indirects;
for (let k = 0; k < indirects.length; k++) {
const drawInfo = indirects[k];
const gpuBuffer = gpuInputAssembler.gpuIndexBuffer;
if (gpuBuffer && drawInfo.indexCount > -1) {
const offset = drawInfo.firstIndex * gpuBuffer.stride;
@@ -2574,7 +2589,8 @@ export function WebGL2CmdFuncCopyTexImagesToTexture (
let f = 0;
switch (gpuTexture.glTarget) {
case gl.TEXTURE_2D: {
for (const region of regions) {
for (let k = 0; k < regions.length; k++) {
const region = regions[k];
for (m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) {
gl.texSubImage2D(gl.TEXTURE_2D, m,
region.texOffset.x, region.texOffset.y,
@@ -2584,7 +2600,8 @@ export function WebGL2CmdFuncCopyTexImagesToTexture (
break;
}
case gl.TEXTURE_CUBE_MAP: {
for (const region of regions) {
for (let k = 0; k < regions.length; k++) {
const region = regions[k];
const fcount = region.texSubres.baseArrayLayer + region.texSubres.layerCount;
for (f = region.texSubres.baseArrayLayer; f < fcount; ++f) {
const mcount = region.texSubres.baseMipLevel + region.texSubres.levelCount;
@@ -2629,7 +2646,8 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
const isCompressed = fmtInfo.isCompressed;
switch (gpuTexture.glTarget) {
case gl.TEXTURE_2D: {
for (const region of regions) {
for (let k = 0; k < regions.length; k++) {
const region = regions[k];
w = region.texExtent.width;
h = region.texExtent.height;
for (m = region.texSubres.baseMipLevel; m < region.texSubres.levelCount; ++m) {
@@ -2655,7 +2673,8 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
break;
}
case gl.TEXTURE_CUBE_MAP: {
for (const region of regions) {
for (let k = 0; k < regions.length; k++) {
const region = regions[k];
n = 0;
const fcount = region.texSubres.baseArrayLayer + region.texSubres.layerCount;
for (f = region.texSubres.baseArrayLayer; f < fcount; ++f) {
+5 -3
View File
@@ -27,12 +27,14 @@
* @category core
*/
import * as math from './math';
import * as geometry from './geom-utils';
import * as math from './math';
import * as memop from './memop';
cc.math = math;
cc.geometry = geometry;
cc.memop = memop;
export { math, geometry };
export { math, memop, geometry };
export * from './math';
export * from './memop';
@@ -58,5 +60,5 @@ import './primitive';
export * from './utils/profiler/profiler';
import './splash-image';
import './deprecated';
import './splash-image';
+7
View File
@@ -34,6 +34,7 @@ import * as PackDownloader from './pack-downloader';
import downloadBinary from './binary-downloader';
import downloadText from './text-downloader';
import {urlAppendTimestamp} from './utils';
import { downloadAudio } from '../../audio/audio-downloader';
function skip () {
return null;
@@ -143,6 +144,12 @@ let defaultMap = {
'pvr': downloadBinary,
'pkm': downloadBinary,
// Audio
'mp3' : downloadAudio,
'ogg' : downloadAudio,
'wav' : downloadAudio,
'm4a' : downloadAudio,
// Txt
'txt' : downloadText,
'xml' : downloadText,
+2 -2
View File
@@ -61,7 +61,7 @@ function loadImage (item) {
}
let image = item.content;
if (!CC_WECHATGAME && !CC_QQPLAY && !(image instanceof Image)) {
if (cc.sys.platform !== cc.sys.FB_PLAYABLE_ADS && !(image instanceof Image)) {
return new Error('Image Loader: Input item doesn\'t contain Image content');
}
@@ -290,7 +290,7 @@ let ID = 'Loader';
*/
export default class Loader implements IPipe {
static ID = ID;
public id = ID;
public async = true;
public pipeline: Pipeline | null = null;
+18 -16
View File
@@ -22,12 +22,6 @@ export class CachedArray<T> {
*/
public length: number = 0;
/**
* @zh
* 指向缓存数组的引用
*/
private cache: Array<T|null>;
/**
* @zh
* 比较函数
@@ -41,7 +35,6 @@ export class CachedArray<T> {
*/
constructor (length: number, compareFn?: (a: T, b: T) => number) {
this.array = new Array(length);
this.cache = this.array;
this.length = 0;
if (compareFn !== undefined) {
@@ -66,7 +59,7 @@ export class CachedArray<T> {
* @param item 数组元素
*/
public pop (): T | undefined {
return this.array[this.length--];
return this.array[--this.length];
}
/**
@@ -83,7 +76,6 @@ export class CachedArray<T> {
* 清空数组所有元素
*/
public clear () {
this.cache.fill(null);
this.length = 0;
}
@@ -100,19 +92,29 @@ export class CachedArray<T> {
* @zh
* 连接一个指定数组中的所有元素到当前数组末尾
*/
public concat (array: CachedArray<T>) {
public concat (array: T[]) {
for (let i = 0; i < array.length; ++i) {
this.array[this.length++] = array.array[i];
this.array[this.length++] = array[i];
}
}
/**
* @zh
* 向数组中追加一组数据
* @zh 删除指定位置的元素并将最后一个元素移动至该位置。
* @param idx 数组索引。
*/
public append (array: T[]) {
for (const item of array) {
this.array[this.length++] = item;
public fastRemove (idx: number) {
if (idx >= this.length || idx < 0) {
return;
}
const last = --this.length;
this.array[idx] = this.array[last];
}
/**
* @zh 返回某个数组元素对应的下标。
* @param val 数组元素。
*/
public indexOf (val: T) {
return this.array.indexOf(val);
}
}
-116
View File
@@ -1,116 +0,0 @@
/**
* @category memop
*/
import sort from './timsort';
/**
* @zh 定长数组。
*/
export default class FixedArray<T = {}> {
private _count: number;
private _data: Array<T | undefined>;
/**
* 构造函数。
* @param size 数组长度。
*/
constructor (size: number) {
this._count = 0;
this._data = new Array(size);
}
public _resize (size: number) {
if (size > this._data.length) {
for (let i = this._data.length; i < size; ++i) {
this._data[i] = undefined;
}
}
}
/**
* @zh 当前有效数据长度。
*/
get length () {
return this._count;
}
/**
* @zh 获取数组元素。
*/
get data () {
return this._data;
}
/**
* @zh 将数组清空。
*/
public reset () {
for (let i = 0; i < this._count; ++i) {
this._data[i] = undefined;
}
this._count = 0;
}
/**
* @zh 把一个对象插入到数组末尾。
* @param val 一个数组元素
*/
public push (val) {
if (this._count >= this._data.length) {
this._resize(this._data.length * 2);
}
this._data[this._count] = val;
++this._count;
}
/**
* @zh 删除数组最后一个元素并返回。
*/
public pop () {
--this._count;
if (this._count < 0) {
this._count = 0;
}
const ret = this._data[this._count];
this._data[this._count] = undefined;
return ret;
}
/**
* @zh 删除指定位置的元素并将最后一个元素移动至该位置。
* @param idx 数组索引。
*/
public fastRemove (idx) {
if (idx >= this._count || idx < 0) {
return;
}
const last = this._count - 1;
this._data[idx] = this._data[last];
this._data[last] = undefined;
this._count -= 1;
}
/**
* @zh 返回某个数组元素对应的下标。
* @param val 数组元素。
*/
public indexOf (val) {
return this._data.indexOf(val);
}
/**
* @zh 对数组进行排序。
* @param cmp 比较函数。
*/
public sort (cmp) {
return sort(this._data, 0, this._count, cmp);
}
}
+3 -6
View File
@@ -2,9 +2,6 @@
* @hidden
*/
export { default as CircularPool } from './circular-pool';
export { default as FixedArray } from './fixed-array';
export { default as LinkedArray } from './linked-array';
export { default as Pool } from './pool';
export { default as RecyclePool } from './recycle-pool';
export { default as TypedArrayPool } from './typed-array-pool';
export * from './pool';
export * from './recycle-pool';
export * from './cached-array';
+1 -1
View File
@@ -3,7 +3,7 @@
* @category memop
*/
import Pool from './pool';
import { Pool } from './pool';
// NOTE: you must have `_prev` and `_next` field in the object returns by `fn`
+1 -2
View File
@@ -4,11 +4,10 @@
* @category memop
*/
/**
* @zh 对象池。
*/
export default class Pool<T> {
export class Pool<T> {
private _fn: () => T;
private _idx: number;
+1 -11
View File
@@ -3,12 +3,10 @@
* @category memop
*/
import sort from './timsort';
/**
* @zh 循环对象池。
*/
export default class RecyclePool<T = any> {
export class RecyclePool<T = any> {
private _fn: () => T;
private _count = 0;
private _data: T[];
@@ -86,12 +84,4 @@ export default class RecyclePool<T = any> {
this._data[last] = tmp;
this._count -= 1;
}
/**
* @zh 对对象池中的元素进行排序。
* @param compare 比较函数。
*/
public sort (compare: (a: T, b: T) => number) {
return sort(this._data, 0, this._count, compare);
}
}
+2 -2
View File
@@ -57,7 +57,7 @@ export const calcDirectionalLightCullFrustum = (() => {
const minBoxCorner = new Vec3();
const maxBoxCorner = new Vec3();
return (out: frustum, sceneCamera: Camera, light: DirectionalLight, near: number, far: number, nearBias: number) => {
Mat4.fromRT(lightViewMat, light.node.getWorldRotation(lightRot), sceneCamera.node.getWorldPosition(lightPos));
Mat4.fromRT(lightViewMat, light.node!.getWorldRotation(lightRot), sceneCamera.node.getWorldPosition(lightPos));
Mat4.invert(lightVeiwMatInv, lightViewMat);
sceneCamera.getSplitFrustum(camFrustum, near, far);
// transform camera frustum to light space
@@ -77,7 +77,7 @@ export const calcDirectionalLightCullFrustum = (() => {
Vec3.set(lightViewCenter, (minBoxCorner.x + maxBoxCorner.x) / 2, (minBoxCorner.y + maxBoxCorner.y) / 2, maxBoxCorner.z);
lightViewCenter.z += nearBias;
Vec3.transformMat4(lightPos, lightViewCenter, lightViewMat);
Mat4.fromRT(lightViewMat, light.node.getWorldRotation(lightRot), lightPos);
Mat4.fromRT(lightViewMat, light.node!.getWorldRotation(lightRot), lightPos);
// calc the light's frustum
frustum.createOrtho(out, maxBoxCorner.x - minBoxCorner.x, maxBoxCorner.y - minBoxCorner.y, 0, minBoxCorner.z - nearBias - maxBoxCorner.z, lightViewMat);
};
+18 -20
View File
@@ -180,7 +180,7 @@ export class ForwardPipeline extends RenderPipeline {
let spotNum = 0;
for (let l = this._lightIndexOffset[i]; l < nextLightIndex; l++) {
const light = this._validLights[this._lightIndices[l]];
if (light && light.enabled) {
if (light) {
switch (light.type) {
case LightType.SPHERE:
if (sphereNum >= UBOForwardLight.MAX_SPHERE_LIGHTS) {
@@ -260,30 +260,28 @@ export class ForwardPipeline extends RenderPipeline {
*/
protected sceneCulling(view: RenderView) {
super.sceneCulling(view);
this._validLights.splice(0);
for (let i = 0; i < view.camera.scene.sphereLights.length; i++) {
const light = view.camera.scene.sphereLights[i];
if (light.enabled) {
light.update();
sphere.set(_sphere, light.position.x, light.position.y, light.position.z, light.range);
if (intersect.sphere_frustum(_sphere, view.camera.frustum)) {
this._validLights.push(light);
}
this._validLights.length = 0;
const sphereLights = view.camera.scene.sphereLights;
for (let i = 0; i < sphereLights.length; i++) {
const light = sphereLights[i];
light.update();
sphere.set(_sphere, light.position.x, light.position.y, light.position.z, light.range);
if (intersect.sphere_frustum(_sphere, view.camera.frustum)) {
this._validLights.push(light);
}
}
for (let i = 0; i < view.camera.scene.spotLights.length; i++) {
const light = view.camera.scene.spotLights[i];
if (light.enabled) {
light.update();
sphere.set(_sphere, light.position.x, light.position.y, light.position.z, light.range);
if (intersect.sphere_frustum(_sphere, view.camera.frustum)) {
this._validLights.push(light);
}
const spotLights = view.camera.scene.spotLights;
for (let i = 0; i < spotLights.length; i++) {
const light = spotLights[i];
light.update();
sphere.set(_sphere, light.position.x, light.position.y, light.position.z, light.range);
if (intersect.sphere_frustum(_sphere, view.camera.frustum)) {
this._validLights.push(light);
}
}
this._lightIndexOffset.splice(0);
this._lightIndices.splice(0);
this._lightIndexOffset.length = 0;
this._lightIndices.length = 0;
for (let i = 0; i < this._renderObjects.length; i++) {
this._lightIndexOffset[i] = this._lightIndices.length;
if (this._renderObjects[i].model.localBindings.get(UBOForwardLight.BLOCK.name)) {
+1 -1
View File
@@ -161,7 +161,7 @@ export class ForwardStage extends RenderStage {
this._framebuffer = view.window!.framebuffer;
}
const planarShadow = camera.scene.planarShadows;
const planarShadow = camera.scene!.planarShadows;
cmdBuff.begin();
cmdBuff.beginRenderPass(this._framebuffer!, this._renderArea!,
+23 -25
View File
@@ -32,9 +32,7 @@ import { IRenderFlowInfo, RenderFlow } from './render-flow';
import { RenderView } from './render-view';
import { Asset } from '../assets';
const _vec4Array = new Float32Array(4);
const _v3tmp = new Vec3();
const _v4Zero = new Vec4(0.0, 0.0, 0.0, 0.0);
const v3_1 = new Vec3();
/**
* @zh
@@ -879,7 +877,7 @@ export abstract class RenderPipeline {
protected updateUBOs (view: RenderView) {
const camera = view.camera;
const scene = camera.scene;
const scene = camera.scene!;
const device = this._root.device;
const mainLight = scene.mainLight;
@@ -921,9 +919,8 @@ export abstract class RenderPipeline {
fv[UBOGlobal.EXPOSURE_OFFSET + 2] = this._isHDR ? 1.0 : 0.0;
fv[UBOGlobal.EXPOSURE_OFFSET + 3] = this._fpScale / exposure;
Vec3.toArray(fv, mainLight.direction, UBOGlobal.MAIN_LIT_DIR_OFFSET);
if (mainLight.enabled) {
if (mainLight) {
Vec3.toArray(fv, mainLight.direction, UBOGlobal.MAIN_LIT_DIR_OFFSET);
Vec3.toArray(fv, mainLight.color, UBOGlobal.MAIN_LIT_COLOR_OFFSET);
if (mainLight.useColorTemperature) {
const colorTempRGB = mainLight.colorTemperatureRGB;
@@ -938,16 +935,17 @@ export abstract class RenderPipeline {
fv[UBOGlobal.MAIN_LIT_COLOR_OFFSET + 3] = mainLight.illuminance * exposure;
}
} else {
Vec4.toArray(fv, _v4Zero, UBOGlobal.MAIN_LIT_COLOR_OFFSET);
Vec3.toArray(fv, Vec3.UNIT_Z, UBOGlobal.MAIN_LIT_DIR_OFFSET);
Vec4.toArray(fv, Vec4.ZERO, UBOGlobal.MAIN_LIT_COLOR_OFFSET);
}
_vec4Array.set(ambient.skyColor);
const skyColor = ambient.skyColor;
if (this._isHDR) {
_vec4Array[3] = ambient.skyIllum * this._fpScale;
skyColor[3] = ambient.skyIllum * this._fpScale;
} else {
_vec4Array[3] = ambient.skyIllum * exposure;
skyColor[3] = ambient.skyIllum * exposure;
}
this._uboGlobal.view.set(_vec4Array, UBOGlobal.AMBIENT_SKY_OFFSET);
this._uboGlobal.view.set(skyColor, UBOGlobal.AMBIENT_SKY_OFFSET);
this._uboGlobal.view.set(ambient.groundAlbedo, UBOGlobal.AMBIENT_GROUND_OFFSET);
@@ -963,26 +961,27 @@ export abstract class RenderPipeline {
protected sceneCulling (view: RenderView) {
const camera = view.camera;
const scene = camera.scene;
const scene = camera.scene!;
this._renderObjects.splice(0);
this._renderObjects.length = 0;
const mainLight = scene.mainLight;
if (mainLight && mainLight.enabled) {
mainLight.update();
}
const planarShadows = scene.planarShadows;
if (planarShadows.enabled && mainLight.node.hasChangedFlags) {
planarShadows.updateDirLight(mainLight);
if (mainLight) {
mainLight.update();
if (planarShadows.enabled && mainLight.node!.hasChangedFlags) {
planarShadows.updateDirLight(mainLight);
}
}
if (scene.skybox.enabled && (camera.clearFlag & SKYBOX_FLAG)) {
this.addVisibleModel(scene.skybox, camera);
}
for (let i = 0; i < scene.models.length; i++) {
const model = scene.models[i];
const models = scene.models;
for (let i = 0; i < models.length; i++) {
const model = models[i];
model._resetUBOUpdateFlag();
// filter model by view visibility
@@ -1026,9 +1025,8 @@ export abstract class RenderPipeline {
protected addVisibleModel (model: Model, camera: Camera) {
let depth = 0;
if (model.node) {
model.node.getWorldPosition(_v3tmp);
Vec3.subtract(_v3tmp, _v3tmp, camera.position);
depth = Vec3.dot(_v3tmp, camera.forward);
Vec3.subtract(v3_1, model.node.worldPosition, camera.position);
depth = Vec3.dot(v3_1, camera.forward);
}
this._renderObjects.push({
model,
+1 -3
View File
@@ -91,7 +91,7 @@ export class SubContextView extends Component {
public onLoad () {
// Setup subcontext canvas size
if (wx.getOpenDataContext) {
if (wx && wx.getOpenDataContext) {
this._updateInterval = 1000 / this._fps;
this._context = wx.getOpenDataContext();
// reset sharedCanvas width and height
@@ -207,13 +207,11 @@ export class SubContextView extends Component {
private _registerNodeEvent () {
this.node.on(Node.EventType.TRANSFORM_CHANGED, this.updateSubContextViewport, this);
this.node.on(Node.EventType.SCALE_PART, this.updateSubContextViewport, this);
this.node.on(Node.EventType.SIZE_CHANGED, this.updateSubContextViewport, this);
}
private _unregisterNodeEvent () {
this.node.off(Node.EventType.TRANSFORM_CHANGED, this.updateSubContextViewport, this);
this.node.off(Node.EventType.SCALE_PART, this.updateSubContextViewport, this);
this.node.off(Node.EventType.SIZE_CHANGED, this.updateSubContextViewport, this);
}
@@ -0,0 +1,17 @@
import { replaceProperty } from '../../utils';
import { SystemEventType } from './event-enum';
replaceProperty(SystemEventType, 'Node.EventType', [
{
name: 'POSITION_PART',
newName: 'TRANSFORM_CHANGED',
},
{
name: 'ROTATION_PART',
newName: 'TRANSFORM_CHANGED',
},
{
name: 'SCALE_PART',
newName: 'TRANSFORM_CHANGED',
},
]);
+10 -26
View File
@@ -120,37 +120,21 @@ export enum SystemEventType {
/**
* @en
* The event type for position, rotation, scale changed.
* The event type for position, rotation, scale changed.Use the type parameter as [[Node.TransformBit]] to check which part is changed
*
* @zh
* 节点改变位置、旋转或缩放事件.
* 节点改变位置、旋转或缩放事件。如果具体需要判断是哪一个事件,可通过判断回调的第一个参数类型是 [[Node.TransformBit]] 中的哪一个来获取
* @example
* ```
* this.node.on(Node.EventType.TRANSFORM_CHANGED, (type)=>{
* if (type & Node.TransformBit.POSITION) {
* //...
* }
* }, this);
* ```
*/
TRANSFORM_CHANGED = 'transform-changed',
/**
* @en
* The event type for position changed.
*
* @zh
* 节点位置改变事件
*/
POSITION_PART = 'position-part',
/**
* @en
* The event type for rotation changed.
*
* @zh
* 节点旋转事件
*/
ROTATION_PART = 'rotation-part',
/**
* @en The event type for scale changed.
* @zh 节点缩放事件
*/
SCALE_PART = 'scale-part',
/**
* @en The event type for press the devicemotion event, you can use its value directly: 'devicemotion'.
* @zh
@@ -768,14 +768,18 @@ class EventManager {
const node1 = l1._getSceneGraphPriority();
const node2 = l2._getSceneGraphPriority();
// Event manager should only care about ui node in the current scene hierarchy
if (!l2 || !node2 || !node2._activeInHierarchy) {
if (!l2 || !node2 || !node2._activeInHierarchy || !(node2 as INode).uiTransfromComp) {
return -1;
}
else if (!l1 || !node1 || !node1._activeInHierarchy) {
else if (!l1 || !node1 || !node1._activeInHierarchy || !(node1 as INode).uiTransfromComp) {
return 1;
}
let p1 = node1; let p2 = node2; let ex = false;
let p1 = node1; let p2 = node2; let trans1 = (node1 as INode).uiTransfromComp; let trans2 = (node2 as INode).uiTransfromComp; let ex = false;
if (trans1.visibility !== trans2.visibility) {
return trans2.visibility - trans1.visibility;
}
while (p1.parent._id !== p2.parent._id) {
p1 = p1.parent.parent === null ? (ex = true) && node2 : p1.parent;
p2 = p2.parent.parent === null ? (ex = true) && node1 : p2.parent;
+3 -1
View File
@@ -33,4 +33,6 @@ export * from './input-manager';
export * from './system-event';
export * from './events';
export * from './touch';
export * from './event-enum';
export * from './event-enum';
import './deprecated';
+16 -120
View File
@@ -34,6 +34,8 @@
*/
const sys: { [x: string]: any; } = {};
const _global = typeof window === 'undefined' ? global : window;
/**
* English language code
* @property {String} LANGUAGE_ENGLISH
@@ -362,19 +364,12 @@ sys.BROWSER_TYPE_WECHAT = 'wechat';
*/
sys.BROWSER_TYPE_WECHAT_GAME = 'wechatgame';
/**
* BROWSER_TYPE_WECHAT_GAME_SUB
* @property {String} BROWSER_TYPE_WECHAT_GAME_SUB
* BROWSER_TYPE_ALIPAY_GAME
* @property {String} BROWSER_TYPE_ALIPAY_GAME
* @readOnly
* @default "wechatgamesub"
* @default "alipaygame"
*/
sys.BROWSER_TYPE_WECHAT_GAME_SUB = 'wechatgamesub';
/**
* BROWSER_TYPE_QQ_PLAY
* @property {String} BROWSER_TYPE_QQ_PLAY
* @readOnly
* @default "qqplay"
*/
sys.BROWSER_TYPE_QQ_PLAY = 'qqplay';
sys.BROWSER_TYPE_ALIPAY_GAME = 'alipaygame';
/**
*
* @property {String} BROWSER_TYPE_ANDROID
@@ -526,7 +521,7 @@ sys.isNative = CC_JSB;
* Is web browser ?
* @property {Boolean} isBrowser
*/
sys.isBrowser = typeof window === 'object' && typeof document === 'object' && !CC_WECHATGAME && !CC_QQPLAY && !CC_JSB;
sys.isBrowser = typeof window === 'object' && typeof document === 'object' && !CC_MINIGAME && !CC_JSB;
/**
* Endianess of current platform
@@ -539,7 +534,11 @@ sys.isLittleEndian = (() => {
return new Int16Array(buffer)[0] === 256;
})();
if (CC_EDITOR && Editor.isMainProcess) {
if (_global.__globalAdapter && _global.__globalAdapter.adaptSys) {
// init sys info in adapter
_global.__globalAdapter.adaptSys(sys);
}
else if (CC_EDITOR && Editor.isMainProcess) {
sys.isMobile = false;
sys.platform = sys.EDITOR_CORE;
sys.language = sys.LANGUAGE_UNKNOWN;
@@ -611,109 +610,6 @@ else if (CC_JSB) {
format: ['.mp3'],
};
}
else if (CC_WECHATGAME) {
const env = wx.getSystemInfoSync();
sys.isMobile = true;
sys.platform = sys.WECHAT_GAME;
sys.language = env.language.substr(0, 2);
let system = env.system.toLowerCase();
if (env.platform === 'android') {
sys.os = sys.OS_ANDROID;
}
else if (env.platform === 'ios') {
sys.os = sys.OS_IOS;
}
else if (env.platform === 'devtools') {
sys.isMobile = false;
if (system.indexOf('android') > -1) {
sys.os = sys.OS_ANDROID;
}
else if (system.indexOf('ios') > -1) {
sys.os = sys.OS_IOS;
}
}
// Adaptation to Android P
if (system === 'android p') {
system = 'android p 9.0';
}
const version = /[\d\.]+/.exec(system);
sys.osVersion = version ? version[0] : system;
sys.osMainVersion = parseInt(sys.osVersion);
// wechagame subdomain
if (!wx.getFileSystemManager) {
sys.browserType = sys.BROWSER_TYPE_WECHAT_GAME_SUB;
}
else {
sys.browserType = sys.BROWSER_TYPE_WECHAT_GAME;
}
sys.browserVersion = env.version;
const w = env.windowWidth;
const h = env.windowHeight;
const ratio = env.pixelRatio || 1;
sys.windowPixelResolution = {
width: ratio * w,
height: ratio * h,
};
sys.localStorage = window.localStorage;
sys.capabilities = {
canvas: true,
opengl: (sys.browserType !== sys.BROWSER_TYPE_WECHAT_GAME_SUB),
webp: false,
};
sys.__audioSupport = {
ONLY_ONE: false,
WEB_AUDIO: false,
DELAY_CREATE_CTX: false,
format: ['.mp3'],
};
}
else if (CC_QQPLAY) {
// @ts-ignore
const env = window.BK.Director.queryDeviceInfo();
sys.isMobile = true;
sys.platform = sys.QQ_PLAY;
sys.language = sys.LANGUAGE_UNKNOWN;
if (env.platform === 'android') {
sys.os = sys.OS_ANDROID;
}
else if (env.platform === 'ios') {
sys.os = sys.OS_IOS;
}
else {
sys.os = sys.OS_UNKNOWN;
}
sys.osVersion = env.version;
sys.osMainVersion = parseInt(sys.osVersion.split('.')[0]);
sys.browserType = sys.BROWSER_TYPE_QQ_PLAY;
sys.browserVersion = 0;
const w = env.screenWidth;
const h = env.screenHeight;
const ratio = env.pixelRatio || 1;
sys.windowPixelResolution = {
width: ratio * w,
height: ratio * h,
};
sys.localStorage = window.localStorage;
sys.capabilities = {
canvas: false,
opengl: true,
webp: false,
};
sys.__audioSupport = {
ONLY_ONE: false,
WEB_AUDIO: false,
DELAY_CREATE_CTX: false,
format: ['.mp3'],
};
}
else {
// browser or runtime
const win = window, nav = win.navigator, doc = document, docEle = doc.documentElement;
@@ -813,12 +709,12 @@ else {
if (!browserTypes) { browserTypes = typeReg3.exec(ua); }
let browserType = browserTypes ? browserTypes[0].toLowerCase() : sys.BROWSER_TYPE_UNKNOWN;
if (CC_WECHATGAME) {
if (CC_WECHAT) {
browserType = sys.BROWSER_TYPE_WECHAT_GAME;
}
else if (CC_QQPLAY) {
browserType = sys.BROWSER_TYPE_QQ_PLAY;
}
else if(CC_ALIPAY) {
browserType = sys.BROWSER_TYPE_ALIPAY_GAME;
}
else if (browserType === 'micromessenger') {
browserType = sys.BROWSER_TYPE_WECHAT;
}
+17 -14
View File
@@ -41,7 +41,7 @@ class BrowserGetter {
public adaptationType: any = cc.sys.browserType;
public init () {
if (!CC_WECHATGAME) {
if (!CC_MINIGAME) {
this.html = document.getElementsByTagName('html')[0];
}
}
@@ -71,17 +71,8 @@ if (cc.sys.os === cc.sys.OS_IOS) { // All browsers are WebView
__BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_SAFARI;
}
if (CC_WECHATGAME) {
if (cc.sys.browserType === cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB) {
__BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB;
}
else {
__BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_WECHAT_GAME;
}
}
if (CC_QQPLAY) {
__BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_QQ_PLAY;
if (CC_WECHAT) {
__BrowserGetter.adaptationType = cc.sys.BROWSER_TYPE_WECHAT_GAME;
}
switch (__BrowserGetter.adaptationType) {
@@ -729,7 +720,7 @@ export class View extends EventTarget {
* @param {ResolutionPolicy|Number} resolutionPolicy The resolution policy desired
*/
public setRealPixelResolution (width, height, resolutionPolicy) {
if (!CC_JSB && !CC_WECHATGAME && !CC_QQPLAY) {
if (!CC_JSB && !CC_MINIGAME) {
// Set viewport's width
this._setViewportMeta({width}, true);
@@ -1044,7 +1035,7 @@ export class View extends EventTarget {
}
private _adjustViewportMeta () {
if (this._isAdjustViewport && !CC_JSB && !CC_WECHATGAME && !CC_QQPLAY) {
if (this._isAdjustViewport && !CC_JSB && !CC_MINIGAME) {
this._setViewportMeta(__BrowserGetter.meta, false);
this._isAdjustViewport = false;
}
@@ -1328,6 +1319,18 @@ class ContentStrategy {
}
}
// need to adapt prototype before instantiating
let _global = typeof window === 'undefined' ? global : window;
let globalAdapter = _global.__globalAdapter;
if (globalAdapter) {
if (globalAdapter.adaptContainerStrategy) {
globalAdapter.adaptContainerStrategy(ContainerStrategy.prototype);
}
if (globalAdapter.adaptView) {
globalAdapter.adaptView(View.prototype);
}
}
// Alias: Strategy that makes the container's size equals to the frame's size
ContainerStrategy.EQUAL_TO_FRAME = new EqualToFrame();
// Alias: Strategy that scale proportionally the container's size to frame's size
+9 -31
View File
@@ -542,34 +542,10 @@ export class Pass {
if (saveOverrides) { Object.assign(this._defines, defineOverrides); }
else { Object.assign(defineOverrides, this._defines); defines = defineOverrides; }
}
const shader = programLib.getGFXShader(this._device, this._programName, defines, pipeline);
if (!shader) { console.warn(`create shader ${this._programName} failed`); return null; }
if (saveOverrides) { this._shader = shader; }
const { blocks, samplers } = this._shaderInfo;
this._bindings.length = 0;
let lastBinding = -1;
blocks:
for (let i = 0; i < blocks.length; i++) {
const block = blocks[i];
if (block.binding === lastBinding) { continue; }
for (let j = 0; j < block.defines.length; j++) {
if (!defines[block.defines[j]]) { continue blocks; }
}
lastBinding = block.binding;
this._bindings.push(block);
}
samplers:
for (let i = 0; i < samplers.length; i++) {
const sampler = samplers[i];
if (sampler.binding === lastBinding) { continue; }
for (let j = 0; j < sampler.defines.length; j++) {
if (!defines[sampler.defines[j]]) { continue samplers; }
}
lastBinding = sampler.binding;
this._bindings.push(sampler);
}
return shader;
const res = programLib.getGFXShader(this._device, this._programName, defines, pipeline);
if (!res.shader) { console.warn(`create shader ${this._programName} failed`); return null; }
if (saveOverrides) { this._shader = res.shader; this._bindings = res.bindings; }
return res;
}
/**
@@ -581,10 +557,12 @@ export class Pass {
console.warn(`pass resources not complete, create PSO failed`);
return null;
}
let shader = this._shader!;
if (defineOverrides) { shader = this.tryCompile(defineOverrides, false)!; }
let shader = this._shader!; _blInfo.bindings = this._bindings;
if (defineOverrides) {
const res = this.tryCompile(defineOverrides, false);
if (res) { shader = res.shader; _blInfo.bindings = res.bindings; }
}
// bind resources
_blInfo.bindings = this._bindings;
const bindingLayout = this._device.createBindingLayout(_blInfo);
for (const b in this._buffers) {
bindingLayout.bindBuffer(parseInt(b), this._buffers[b]);
+75 -25
View File
@@ -54,6 +54,7 @@ export interface IProgramInfo extends IShaderInfo {
offsets: number[][];
globalsInited: boolean;
localsInited: boolean;
uber: boolean; // macro number exceeds default limits
}
export interface IMacroInfo {
name: string;
@@ -138,13 +139,44 @@ function genHandles (tmpl: IProgramInfo) {
return handleMap;
}
function dependencyCheck (dependencies: string[], defines: IDefineMap) {
for (let i = 0; i < dependencies.length; i++) {
if (!defines[dependencies[i]]) { return false; }
}
return true;
}
function getShaderBindings (
tmpl: IProgramInfo, defines: IDefineMap, outBlocks: IBlockInfoRT[], outSamplers: ISamplerInfoRT[], bindings: IGFXBinding[]) {
const { blocks, samplers } = tmpl;
let lastBinding = -1;
for (let i = 0; i < blocks.length; i++) {
const block = blocks[i];
if (block.binding === lastBinding || !dependencyCheck(block.defines, defines)) { continue; }
lastBinding = block.binding;
outBlocks.push(block);
bindings.push(block);
}
for (let i = 0; i < samplers.length; i++) {
const sampler = samplers[i];
if (sampler.binding === lastBinding || !dependencyCheck(sampler.defines, defines)) { continue; }
lastBinding = sampler.binding;
outSamplers.push(sampler);
bindings.push(sampler);
}
}
interface IShaderResources {
shader: GFXShader;
bindings: IGFXBinding[];
}
/**
* @zh
* 维护 shader 资源实例的全局管理器。
*/
class ProgramLib {
protected _templates: Record<string, IProgramInfo>;
protected _cache: Record<string, GFXShader>;
protected _cache: Record<string, IShaderResources>;
constructor () {
this._templates = {};
@@ -176,6 +208,7 @@ class ProgramLib {
def._offset = offset;
offset += cnt;
}
if (offset > 31) { tmpl.uber = true; }
tmpl.blocks.forEach((b) => (b.size = getSize(b), b.bindingType = GFXBindingType.UNIFORM_BUFFER));
tmpl.samplers.forEach((s) => (s.bindingType = GFXBindingType.SAMPLER));
tmpl.handleMap = genHandles(tmpl);
@@ -207,17 +240,34 @@ class ProgramLib {
*/
public getKey (name: string, defines: IDefineMap) {
const tmpl = this._templates[name];
let key = 0;
for (const tmplDef of tmpl.defines) {
const value = defines[tmplDef.name];
if (value === undefined || !tmplDef._map) {
continue;
const tmplDefs = tmpl.defines;
if (tmpl.uber) {
let key = '';
for (let i = 0; i < tmplDefs.length; i++) {
const tmplDef = tmplDefs[i];
const value = defines[tmplDef.name];
if (value === undefined || !tmplDef._map) {
continue;
}
const mapped = tmplDef._map(value);
const offset = tmplDef._offset;
key += offset + (mapped + '|');
}
const mapped = tmplDef._map(value);
const offset = tmplDef._offset;
key |= mapped << offset;
return key + tmpl.hash;
} else {
let key = 0;
for (let i = 0; i < tmplDefs.length; i++) {
const tmplDef = tmplDefs[i];
const value = defines[tmplDef.name];
if (value === undefined || !tmplDef._map) {
continue;
}
const mapped = tmplDef._map(value);
const offset = tmplDef._offset;
key |= mapped << offset;
}
return `${key.toString(16)}|${tmpl.hash}`;
}
return `${key.toString(16)}|${tmpl.hash}`;
}
/**
@@ -232,10 +282,11 @@ class ProgramLib {
if (typeof val === 'boolean') { val = val ? '1' : '0'; }
return new RegExp(cur + val);
});
const keys = Object.keys(this._cache).filter((k) => regexes.every((re) => re.test(this._cache[k].name)));
const keys = Object.keys(this._cache).filter((k) => regexes.every((re) => re.test(this._cache[k].shader.name)));
for (const k of keys) {
console.log(`destroyed shader ${this._cache[k].name}`);
this._cache[k].destroy();
const prog = this._cache[k].shader;
console.log(`destroyed shader ${prog.name}`);
prog.destroy();
delete this._cache[k];
}
}
@@ -251,19 +302,15 @@ class ProgramLib {
public getGFXShader (device: GFXDevice, name: string, defines: IDefineMap, pipeline: RenderPipeline) {
Object.assign(defines, pipeline.macros);
const key = this.getKey(name, defines);
let program = this._cache[key];
if (program !== undefined) {
return program;
}
const res = this._cache[key];
if (res) { return res; }
// get template
const tmpl = this._templates[name];
if (!tmpl.globalsInited) { insertBuiltinBindings(tmpl, pipeline.globalBindings, 'globals'); tmpl.globalsInited = true; }
const macroArray = prepareDefines(defines, tmpl.defines);
const customDef = macroArray.reduce((acc, cur) => {
return `${acc}#define ${cur.name} ${cur.value}\n`;
}, '');
const customDef = macroArray.reduce((acc, cur) => `${acc}#define ${cur.name} ${cur.value}\n`, '');
let vert: string = '';
let frag: string = '';
@@ -275,17 +322,20 @@ class ProgramLib {
frag = `#version 100\n${customDef}\n${tmpl.glsl1.frag}`;
}
program = device.createShader({
const blocks: IBlockInfoRT[] = [];
const samplers: ISamplerInfoRT[] = [];
const bindings: IGFXBinding[] = [];
getShaderBindings(tmpl, defines, blocks, samplers, bindings);
const shader = device.createShader({
name: getShaderInstanceName(name, macroArray),
blocks: tmpl.blocks,
samplers: tmpl.samplers,
blocks, samplers,
stages: [
{ type: GFXShaderType.VERTEX, source: vert },
{ type: GFXShaderType.FRAGMENT, source: frag },
],
});
this._cache[key] = program;
return program;
return this._cache[key] = { shader, bindings };
}
}
+4 -4
View File
@@ -43,8 +43,7 @@ export enum SamplerInfoIndex {
minLOD,
maxLOD,
mipLODBias,
borderColor,
total = borderColor + 4,
total,
}
const defaultInfo = [
@@ -57,10 +56,11 @@ const defaultInfo = [
8,
GFXComparisonFunc.NEVER,
0, 0, 0,
0, 0, 0, 0,
];
const defaultHash = genSamplerHash(defaultInfo);
const borderColor = { r: 0, g: 0, b: 0, a: 0 };
const gfxInfo: IGFXSamplerInfo = {};
export function genSamplerHash (info: Array<number | undefined>): number {
@@ -115,7 +115,7 @@ class SamplerLib {
gfxInfo.minLOD = ((hash >> 20) & 15);
gfxInfo.maxLOD = ((hash >> 24) & 15);
gfxInfo.mipLODBias = ((hash >> 28) & 15);
gfxInfo.borderColor = { r: 0, g: 0, b: 0, a: 0 };
gfxInfo.borderColor = borderColor;
const sampler = this._cache[hash] = device.createSampler(gfxInfo);
return sampler;
@@ -7,7 +7,7 @@ import { GFXDevice } from '../../gfx/device';
import { GFXTexture } from '../../gfx/texture';
import { GFXTextureView } from '../../gfx/texture-view';
function nearestPO2 (num: number): number {
export function nearestPOT (num: number): number {
--num;
num |= num >> 16;
num |= num >> 8;
@@ -145,7 +145,7 @@ export class TextureBufferPool {
// create a new one
const targetSize = Math.sqrt(size / this._formatSize);
const texWidth = this._roundUpFn && this._roundUpFn(targetSize, this._formatSize) || Math.max(1024, nearestPO2(targetSize));
const texWidth = this._roundUpFn && this._roundUpFn(targetSize, this._formatSize) || Math.max(1024, nearestPOT(targetSize));
const texSize = texWidth * texWidth * this._formatSize;
console.info('TextureBufferPool: Allocate chunk ' + this._chunkCount + ', size: ' + texSize);
@@ -38,7 +38,7 @@ import { GFXDevice, GFXFeature } from '../../gfx/device';
import { Mat4, Quat, Vec3 } from '../../math';
import { UBOSkinningAnimation } from '../../pipeline/define';
import { genSamplerHash } from '../core/sampler-lib';
import { ITextureBufferHandle, TextureBufferPool } from '../core/texture-buffer-pool';
import { ITextureBufferHandle, nearestPOT, TextureBufferPool } from '../core/texture-buffer-pool';
// change here and cc-skinning.chunk to use other skinning algorithms
const uploadJointData = uploadJointDataLBS;
@@ -175,7 +175,7 @@ export class JointsTexturePool {
this._identityBuffer.readyToBeDeleted = true;
this.releaseHandle(this._identityBuffer, false);
}
this._maxIdentityJoints *= 2;
this._maxIdentityJoints = nearestPOT(len);
this._identityBuffer = this._allocIdentityBuffer();
}
if (!this._identityBuffer) { return null; }
+12 -7
View File
@@ -59,12 +59,11 @@ export class SkinningModel extends Model {
private _staticModelBounds: aabb | null = null;
private _mesh: Mesh | null = null;
constructor (scene: RenderScene, node: INode) {
super(scene, node);
constructor () {
super();
this._type = 'skinning';
const jointsTextureInfo = new Float32Array(4);
const texture = this._scene.root.dataPoolManager.jointsTexturePool.getDefaultJointsTexture();
this._jointsMedium = { buffer: null, jointsTextureInfo, texture, animInfo: null, boundsInfo: null };
this._jointsMedium = { buffer: null, jointsTextureInfo, texture: null, animInfo: null, boundsInfo: null };
}
public destroy () {
@@ -75,12 +74,18 @@ export class SkinningModel extends Model {
}
}
public attachToScene (scene: RenderScene) {
super.attachToScene(scene);
const texture = scene.root.dataPoolManager.jointsTexturePool.getDefaultJointsTexture();
this._jointsMedium.texture = texture;
}
public bindSkeleton (skeleton: Skeleton | null, skinningRoot: INode | null, mesh: Mesh | null) {
this._skeleton = skeleton;
this._mesh = mesh;
if (!skeleton || !skinningRoot || !mesh) { return; }
this._transform = skinningRoot;
this._jointsMedium.animInfo = this._scene.root.dataPoolManager.jointsAnimationInfo.get(skinningRoot.uuid);
this._jointsMedium.animInfo = cc.director.root.dataPoolManager.jointsAnimationInfo.get(skinningRoot.uuid);
if (!this._jointsMedium.buffer) {
this._jointsMedium.buffer = this._device.createBuffer({
usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST,
@@ -119,7 +124,7 @@ export class SkinningModel extends Model {
public uploadAnimation (anim: AnimationClip | null) {
if (!this._skeleton || !this._mesh) { return; }
this.uploadedAnim = anim;
const resMgr = this._scene.root.dataPoolManager;
const resMgr = cc.director.root.dataPoolManager;
const texture = anim ? resMgr.jointsTexturePool.getJointsTextureWithAnimation(this._skeleton, anim) :
resMgr.jointsTexturePool.getDefaultJointsTexture(this._skeleton);
resMgr.jointsAnimationInfo.switchClip(this._jointsMedium.animInfo!, anim);
@@ -131,7 +136,7 @@ export class SkinningModel extends Model {
protected _applyJointsTexture (texture: IJointsTextureHandle | null) {
if (!texture) { return; }
const oldTex = this._jointsMedium.texture;
if (oldTex && oldTex !== texture) { this._scene.root.dataPoolManager.jointsTexturePool.releaseHandle(oldTex); }
if (oldTex && oldTex !== texture) { cc.director.root.dataPoolManager.jointsTexturePool.releaseHandle(oldTex); }
this._jointsMedium.texture = texture;
const { buffer, jointsTextureInfo } = this._jointsMedium;
jointsTextureInfo[0] = texture.handle.texture.width;
+45 -23
View File
@@ -86,10 +86,10 @@ export const SKYBOX_FLAG = GFXClearFlag.STENCIL << 1;
export class Camera {
private _scene: RenderScene;
private _name: string;
private _scene: RenderScene | null = null;
private _name: string | null = null;
private _enabled: boolean = false;
private _proj: CameraProjection;
private _proj: CameraProjection = -1;
private _isWindowSize: boolean = true;
private _width: number;
private _height: number;
@@ -114,7 +114,7 @@ export class Camera {
private _forward: Vec3 = new Vec3();
private _position: Vec3 = new Vec3();
private _node: INode | null = null;
private _view: RenderView;
private _view: RenderView | null = null;
private _visibility = CameraDefaultMask;
private _priority: number = 0;
private _aperture: CameraAperture = CameraAperture.F16_0;
@@ -126,13 +126,7 @@ export class Camera {
private _ec: number = 0.0;
private _exposure: number = 0.0;
constructor (scene: RenderScene, info: ICameraInfo) {
this._scene = scene;
this._name = info.name;
this._node = info.node;
this._proj = info.projection;
this._priority = info.priority || 0;
constructor () {
this._apertureValue = FSTOPS[this._aperture];
this._shutterValue = SHUTTERS[this._shutter];
this._isoValue = ISOS[this._iso];
@@ -140,20 +134,43 @@ export class Camera {
this._aspect = this._width = this._height = this._screenScale = 1;
this._view = this._scene.root.createView({
}
public initialize (info: ICameraInfo) {
this._name = info.name;
this._node = info.node;
this._proj = info.projection;
this._priority = info.priority || 0;
this._view = cc.director.root.createView({
camera: this,
name: this._name,
priority: this._priority,
flows: info.flows,
});
this.changeTargetWindow(info.window);
console.log('Create Camera: ' + this._name + ' ' + this._width + ' x ' + this._height);
console.log('Created Camera: ' + this._name + ' ' + this._width + 'x' + this._height);
}
public destroy () {
this._scene.root.destroyView(this._view);
cc.director.root.destroyView(this._view);
this._view = null;
this._name = null;
}
public attachToScene (scene: RenderScene) {
this._scene = scene;
if (this._view) {
this._view.enable(true);
}
}
public detachFromScene () {
this._scene = null;
if (this._view) {
this._view.enable(false);
}
}
public resize (width: number, height: number) {
@@ -241,7 +258,9 @@ export class Camera {
set enabled (val) {
this._enabled = val;
this._view.enable(val);
if (this._view) {
this._view.enable(val);
}
}
get enabled () {
@@ -249,7 +268,7 @@ export class Camera {
}
get view (): RenderView {
return this._view;
return this._view!;
}
set node (val: INode) {
@@ -410,19 +429,23 @@ export class Camera {
set visibility (vis) {
this._visibility = vis;
this._view.visibility = vis;
if (this._view) {
this._view.visibility = vis;
}
}
get visibility () {
return this._visibility;
}
get priority (): number {
return this._view.priority;
return this._view ? this._view.priority : -1;
}
set priority (val: number) {
this._priority = val;
this._view.priority = this._priority;
if (this._view) {
this._view.priority = this._priority;
}
}
set aperture (val: CameraAperture) {
@@ -486,9 +509,8 @@ export class Camera {
}
public changeTargetWindow (window: GFXWindow | null = null) {
const scene = this._scene;
const win = window || scene.root.mainWindow;
if (win) {
const win = window || cc.director.root.mainWindow;
if (win && this._view) {
this._view.window = win;
this.resize(win.width, win.height);
}
@@ -1,7 +1,6 @@
import { Quat, Vec3 } from '../../math';
import { INode } from '../../utils/interfaces';
import { Ambient } from './ambient';
import { Light, LightType } from './light';
import { RenderScene } from './render-scene';
const _forward = new Vec3(0, 0, -1);
const _v3 = new Vec3();
@@ -10,7 +9,7 @@ const _qt = new Quat();
export class DirectionalLight extends Light {
protected _dir: Vec3 = new Vec3(1.0, -1.0, -1.0);
protected _illum: number = 65000.0;
protected _illum: number = Ambient.SUN_ILLUM;
set direction (dir: Vec3) {
this._dir = dir;
@@ -30,13 +29,13 @@ export class DirectionalLight extends Light {
return this._illum;
}
constructor (scene: RenderScene, name: string, node: INode) {
super(scene, name, node);
constructor () {
super();
this._type = LightType.DIRECTIONAL;
}
public update () {
if (this._node) {
if (this._node && this._node.hasChangedFlags) {
this._dir = Vec3.transformQuat(_v3, _forward, this._node.getWorldRotation(_qt));
Vec3.normalize(this._dir, this._dir);
}
+30 -13
View File
@@ -1,4 +1,5 @@
import { Vec3 } from '../../math';
import { TransformBit } from '../../scene-graph/node-enum';
import { INode } from '../../utils/interfaces';
import { RenderScene } from './render-scene';
@@ -40,13 +41,6 @@ export const nt2lm = (size: number) => 4 * Math.PI * Math.PI * size * size;
export class Light {
set enabled (val) {
this._enabled = val;
}
get enabled () {
return this._enabled;
}
set color (color: Vec3) {
this._color.set(color);
}
@@ -78,6 +72,9 @@ export class Light {
set node (n) {
this._node = n;
if (this._node) {
this._node.hasChangedFlags = TransformBit.ROTATION;
}
}
get node () {
@@ -92,22 +89,42 @@ export class Light {
return this._name;
}
protected _enabled = true;
get scene () {
return this._scene;
}
protected _color: Vec3 = new Vec3(1, 1, 1);
protected _useColorTemp: boolean = false;
protected _colorTemp: number = 6550.0;
protected _colorTempRGB: Vec3 = new Vec3(1, 1, 1);
protected _scene: RenderScene;
protected _node: INode;
protected _scene: RenderScene | null = null;
protected _node: INode | null = null;
protected _type: LightType;
protected _name: string;
protected _name: string | null = null;
constructor (scene: RenderScene, name: string, node: INode) {
this._scene = scene;
constructor () {
this._type = LightType.UNKNOWN;
}
public initialize (name: string, node: INode) {
this._name = name;
this._type = LightType.UNKNOWN;
this._node = node;
}
public attachToScene (scene: RenderScene) {
this._scene = scene;
}
public detachFromScene () {
this._scene = null;
}
public destroy () {
this._name = null;
this._type = LightType.UNKNOWN;
this._node = null;
}
public update () {}
}
+28 -16
View File
@@ -9,7 +9,7 @@ import { GFXDevice } from '../../gfx/device';
import { GFXPipelineState } from '../../gfx/pipeline-state';
import { GFXUniformBlock } from '../../gfx/shader';
import { Mat4, Vec3 } from '../../math';
import Pool from '../../memop/pool';
import { Pool } from '../../memop';
import { IInternalBindingInst, UBOForwardLight, UBOLocal } from '../../pipeline/define';
import { Layers } from '../../scene-graph/layers';
import { INode } from '../../utils/interfaces';
@@ -39,11 +39,10 @@ export class Model {
set scene (scene: RenderScene) {
this._scene = scene;
this._id = this._scene.generateModelId();
}
get scene () {
return this._scene;
return this._scene!;
}
get id () {
@@ -71,7 +70,7 @@ export class Model {
}
get node () {
return this._node;
return this._node!;
}
set node (node: INode) {
@@ -79,7 +78,7 @@ export class Model {
}
get transform () {
return this._transform;
return this._transform!;
}
set transform (transform: INode) {
@@ -143,11 +142,11 @@ export class Model {
protected _type: string = 'default';
protected _device: GFXDevice;
protected _scene: RenderScene;
protected _node: INode;
protected _transform: INode;
protected _id: number;
protected _enabled = false;
protected _scene: RenderScene | null = null;
protected _node: INode | null = null;
protected _transform: INode | null = null;
protected _id: number = -1;
protected _enabled: boolean = true;
protected _visFlags = Layers.Enum.NONE;
protected _cameraID = -1;
protected _userKey = -1;
@@ -169,11 +168,12 @@ export class Model {
/**
* Setup a default empty model
*/
constructor (scene: RenderScene, node: INode) {
constructor () {
this._device = cc.director.root!.device;
this._scene = scene;
this._node = this._transform = node;
this._id = this._scene.generateModelId();
}
public initialize (node: INode) {
this._transform = this._node = node;
}
public destroy () {
@@ -200,6 +200,17 @@ export class Model {
this._matPSORecord.clear();
this._matRefCount.clear();
this._inited = false;
this._transformUpdated = true;
}
public attachToScene (scene: RenderScene) {
this._scene = scene;
this._id = this._scene.generateModelId();
}
public detachFromScene () {
this._scene = null;
this._id = -1;
}
public getSubModel (idx: number) {
@@ -210,7 +221,7 @@ export class Model {
const node = this._transform;
// @ts-ignore
if (node.hasChangedFlags || node._dirtyFlags) {
node.updateWorldTransform();
node!.updateWorldTransform();
this._transformUpdated = true;
if (this._modelBounds && this._worldBounds) {
// @ts-ignore TS2339
@@ -256,7 +267,7 @@ export class Model {
if (!minPos || !maxPos) { return; }
this._modelBounds = aabb.fromPoints(aabb.create(), minPos, maxPos);
this._worldBounds = aabb.clone(this._modelBounds);
this._transform.updateWorldTransform();
this._transform!.updateWorldTransform();
// @ts-ignore
this._modelBounds.transform(this._transform._mat, this._transform._pos, this._transform._rot, this._transform._scale, this._worldBounds);
}
@@ -348,6 +359,7 @@ export class Model {
protected _doCreatePSO (pass: Pass, defineOverrides?: IDefineMap, stateOverrides?: IPassStates) {
defineOverrides = defineOverrides || {};
if (pass.blendState.targets[0].blend) { this._isDynamicBatching = false; }
defineOverrides.CC_USE_BATCHING = this._isDynamicBatching;
const pso = pass.createPipelineState(defineOverrides, stateOverrides)!;
pso.pipelineLayout.layouts[0].bindBuffer(UBOLocal.BLOCK.binding, this._localBindings.get(UBOLocal.BLOCK.name)!.buffer!);
+7 -7
View File
@@ -29,7 +29,7 @@ export class PlanarShadows {
set enabled (enable: boolean) {
this._enabled = enable;
this.updateDirLight();
if (this._scene.mainLight) { this.updateDirLight(this._scene.mainLight); }
this._cmdBuffs.clear();
}
@@ -39,7 +39,7 @@ export class PlanarShadows {
set normal (val: Vec3) {
Vec3.copy(this._normal, val);
this.updateDirLight();
if (this._scene.mainLight) { this.updateDirLight(this._scene.mainLight); }
}
get normal () {
return this._normal;
@@ -47,7 +47,7 @@ export class PlanarShadows {
set distance (val: number) {
this._distance = val;
this.updateDirLight();
if (this._scene.mainLight) { this.updateDirLight(this._scene.mainLight); }
}
get distance () {
return this._distance;
@@ -102,7 +102,7 @@ export class PlanarShadows {
}
public updateSphereLight (light: SphereLight) {
light.node.getWorldPosition(_v3);
light.node!.getWorldPosition(_v3);
const n = this._normal; const d = this._distance;
const NdL = Vec3.dot(n, _v3);
const lx = _v3.x; const ly = _v3.y; const lz = _v3.z;
@@ -128,8 +128,8 @@ export class PlanarShadows {
this._globalBindings.buffer!.update(this.data);
}
public updateDirLight (light: DirectionalLight = this._scene.mainLight) {
light.node.getWorldRotation(_qt);
public updateDirLight (light: DirectionalLight) {
light.node!.getWorldRotation(_qt);
Vec3.transformQuat(_v3, _forward, _qt);
const n = this._normal; const d = this._distance;
const NdL = Vec3.dot(n, _v3); const scale = 1 / NdL;
@@ -158,7 +158,7 @@ export class PlanarShadows {
public updateCommandBuffers (frstm: frustum) {
this._cmdBuffs.clear();
if (!this._scene.mainLight.enabled) { return; }
if (!this._scene.mainLight) { return; }
for (const model of this._scene.models) {
if (!model.enabled || !model.node || !model.castShadow) { continue; }
if (model.worldBounds) {
+54 -49
View File
@@ -57,11 +57,7 @@ export class RenderScene {
return this._planarShadows;
}
get defaultMainLightNode (): INode {
return this._defaultMainLightNode;
}
get mainLight (): DirectionalLight {
get mainLight (): DirectionalLight | null {
return this._mainLight;
}
@@ -119,21 +115,15 @@ export class RenderScene {
private _ambient: Ambient;
private _skybox: Skybox;
private _planarShadows: PlanarShadows;
private _mainLight: DirectionalLight;
private _defaultMainLightNode: INode;
private _models: Model[] = [];
private _sphereLights: SphereLight[] = [];
private _spotLights: SpotLight[] = [];
private _models: Model[] = [];
private _mainLight: DirectionalLight | null = null;
private _modelId: number = 0;
constructor (root: Root) {
this._root = root;
this._ambient = new Ambient(this);
this._defaultMainLightNode = new Node('Main Light');
this._mainLight = new DirectionalLight(this, 'Main Light', this._defaultMainLightNode);
this._mainLight.illuminance = Ambient.SUN_ILLUM;
this._mainLight.enabled = false; // disabled by default
this._ambient = new Ambient(this);
this._skybox = new Skybox(this);
this._planarShadows = new PlanarShadows(this);
}
@@ -144,97 +134,112 @@ export class RenderScene {
}
public destroy () {
this.destroyCameras();
this.destroyPointLights();
this.destroySpotLights();
this.destroyModels();
this.removeCameras();
this.removeSphereLights();
this.removeSpotLights();
this.removeModels();
this._skybox.destroy();
this._planarShadows.destroy();
}
public createCamera (info: ICameraInfo): Camera {
const camera = new Camera(this, info);
this._cameras.push(camera);
return camera;
public addCamera (cam: Camera) {
cam.attachToScene(this);
this._cameras.push(cam);
}
public destroyCamera (camera: Camera) {
public removeCamera (camera: Camera) {
for (let i = 0; i < this._cameras.length; ++i) {
if (this._cameras[i] === camera) {
camera.destroy();
this._cameras.splice(i, 1);
camera.detachFromScene();
return;
}
}
}
public destroyCameras () {
public removeCameras () {
for (const camera of this._cameras) {
camera.destroy();
camera.detachFromScene();
}
this._cameras.splice(0);
}
public createSphereLight (name: string, node: INode): SphereLight | null {
const light = new SphereLight(this, name, node);
this._sphereLights.push(light);
return light;
public setMainLight (dl: DirectionalLight) {
dl.attachToScene(this);
this._mainLight = dl;
}
public destroySphereLight (light: SphereLight) {
public unsetMainLight (dl: DirectionalLight) {
dl.detachFromScene();
this._mainLight = null;
}
public addSphereLight (pl: SphereLight) {
pl.attachToScene(this);
this._sphereLights.push(pl);
}
public removeSphereLight (pl: SphereLight) {
for (let i = 0; i < this._sphereLights.length; ++i) {
if (this._sphereLights[i] === light) {
if (this._sphereLights[i] === pl) {
pl.detachFromScene();
this._sphereLights.splice(i, 1);
return;
}
}
}
public createSpotLight (name: string, node: INode): SpotLight | null {
const light = new SpotLight(this, name, node);
this._spotLights.push(light);
return light;
public addSpotLight (sl: SpotLight) {
sl.attachToScene(this);
this._spotLights.push(sl);
}
public destroySpotLight (light: SpotLight) {
public removeSpotLight (sl: SpotLight) {
for (let i = 0; i < this._spotLights.length; ++i) {
if (this._spotLights[i] === light) {
if (this._spotLights[i] === sl) {
sl.detachFromScene();
this._spotLights.splice(i, 1);
return;
}
}
}
public destroyPointLights () {
this._sphereLights = [];
public removeSphereLights () {
for (let i = 0; i < this._sphereLights.length; ++i) {
this._sphereLights[i].detachFromScene();
}
this._sphereLights.length = 0;
}
public destroySpotLights () {
public removeSpotLights () {
for (let i = 0; i < this._spotLights.length; ++i) {
this._spotLights[i].detachFromScene();
}
this._spotLights = [];
}
public createModel<T extends Model> (clazz: new (scene: RenderScene, node: INode) => T, node: INode): T {
const model = new clazz(this, node);
this._models.push(model);
return model;
public addModel (m: Model) {
m.attachToScene(this);
this._models.push(m);
}
public destroyModel (model: Model) {
public removeModel (model: Model) {
for (let i = 0; i < this._models.length; ++i) {
if (this._models[i] === model) {
this._planarShadows.destroyShadowModel(model);
this._models.splice(i, 1)[0].destroy();
model.detachFromScene();
this._models.splice(i, 1);
return;
}
}
}
public destroyModels () {
public removeModels () {
for (const m of this._models) {
this._planarShadows.destroyShadowModel(m);
m.destroy();
m.detachFromScene();
}
this._models = [];
this._models.length = 0;
}
public onPipelineChange () {
+4 -4
View File
@@ -36,7 +36,7 @@ export class Skybox extends Model {
set envmap (val: TextureCube | null) {
const newEnvmap = val || this._default;
this._envmap = newEnvmap;
this._scene.ambient.groundAlbedo[3] = this._envmap.mipmapLevel;
this._scene!.ambient.groundAlbedo[3] = this._envmap.mipmapLevel;
this._updateGlobalBinding();
}
get envmap () {
@@ -51,7 +51,7 @@ export class Skybox extends Model {
protected _globalBinding: IInternalBindingInst;
constructor (scene: RenderScene) {
super(scene, null!);
super();
this._scene = scene;
this._globalBinding = this._scene.root.pipeline.globalBindings.get(UNIFORM_ENVIRONMENT.name)!;
if (!skybox_material) {
@@ -64,10 +64,10 @@ export class Skybox extends Model {
protected _updatePipeline () {
const value = this._useIBL ? this._isRGBE ? 2 : 1 : 0;
const pipeline = this._scene.root.pipeline;
const pipeline = this._scene!.root.pipeline;
if (pipeline.macros.CC_USE_IBL === value) { return; }
pipeline.macros.CC_USE_IBL = value;
this._scene.onPipelineChange();
this._scene!.onPipelineChange();
}
protected _updateGlobalBinding () {
+2 -2
View File
@@ -44,8 +44,8 @@ export class SphereLight extends Light {
protected _pos: Vec3;
protected _aabb: aabb;
constructor (scene: RenderScene, name: string, node: INode) {
super(scene, name, node);
constructor () {
super();
this._type = LightType.SPHERE;
this._aabb = aabb.create();
this._pos = new Vec3();
+2 -2
View File
@@ -72,8 +72,8 @@ export class SpotLight extends Light {
return this._frustum;
}
constructor (scene: RenderScene, name: string, node: INode) {
super(scene, name, node);
constructor () {
super();
this._type = LightType.SPOT;
this._aabb = aabb.create();
this._frustum = frustum.create();
+2 -4
View File
@@ -27,11 +27,9 @@
* @hidden
*/
import { Pool, RecyclePool } from '../../memop';
import { Material } from '../../assets';
import { Color } from '../../math';
import { GFXTextureView } from '../../gfx';
import { MeshBuffer } from '../../../ui';
import { Pool, RecyclePool } from '../../memop';
export interface IRenderData {
x: number;
@@ -49,7 +47,6 @@ export class BaseRenderData {
}
export class RenderData extends BaseRenderData {
public vData: Float32Array | null = null;
get dataLength () {
return this._datas.length;
@@ -90,6 +87,7 @@ export class RenderData extends BaseRenderData {
_pool.data[idx].clear();
_pool.removeAt(idx);
}
public vData: Float32Array | null = null;
public uvDirty: boolean = true;
public vertDirty: boolean = true;
+3 -3
View File
@@ -38,8 +38,8 @@ export class UIBatchModel extends Model {
private _subModel: UISubModel;
constructor (scene: RenderScene) {
super(scene, null!);
constructor () {
super();
this._subModel = new UISubModel();
}
@@ -50,7 +50,7 @@ export class UIBatchModel extends Model {
return false;
}
public initialize (ia: GFXInputAssembler, batch: UIDrawBatch) {
public directInitialize (ia: GFXInputAssembler, batch: UIDrawBatch) {
this._subModel.directInitialize(ia, batch.material!, batch.pipelineState!);
this._subModels[0] = this._subModel;
}
+1 -1
View File
@@ -27,8 +27,8 @@
*/
import { Material } from '../../assets/material';
import Pool from '../../memop/pool';
import { GFXPipelineState } from '../../gfx/pipeline-state';
import { Pool } from '../../memop';
import { Pass } from '../../renderer/core/pass';
export interface IUIMaterialInfo {
+35 -20
View File
@@ -98,7 +98,7 @@ export class UI {
private _emptyMaterial = new Material();
private _currMaterial: Material = this._emptyMaterial;
private _currTexView: GFXTextureView | null = null;
private _currCanvas = -1;
private _currCanvas: CanvasComponent | null = null;
private _currMeshBuffer: MeshBuffer | null = null;
private _currStaticRoot: UIStaticBatchComponent | null = null;
@@ -108,7 +108,8 @@ export class UI {
name: 'GUIScene',
});
this._uiModelPool = new Pool(() => {
const model = this._scene.createModel<UIBatchModel>(UIBatchModel, null!);
const model = cc.director.root.createModel(UIBatchModel);
model.enabled = true;
model.visFlags |= Layers.Enum.UI_3D;
return model;
}, 2);
@@ -189,12 +190,17 @@ export class UI {
*/
public addScreen (comp: CanvasComponent) {
this._screens.push(comp);
if (comp.camera) {
comp.camera.view.visibility = Layers.BitMask.UI_2D | this._screens.length;
this._canvasMaterials.set(comp.camera.view.visibility, new Map<number, number>());
}
this._screens.sort(this._screenSort);
const screens = this._screens;
for (let i = 0; i < screens.length; i++) {
const element = screens[i];
if(element.camera){
element.camera.view.visibility = Layers.BitMask.UI_2D | (i + 1);
if (!this._canvasMaterials.has(element.camera.view.visibility)){
this._canvasMaterials.set(element.camera.view.visibility, new Map<number, number>());
}
}
}
}
/**
@@ -267,12 +273,16 @@ export class UI {
this._reset();
}
public sortScreens(){
this._screens.sort(this._screenSort);
}
public render () {
let batchPriority = 0;
for (let i = 0; i < this._modelInUse.length; i++) {
this._modelInUse.get(i).enabled = false;
this._scene.removeModel(this._modelInUse.get(i));
this._uiModelPool!.free(this._modelInUse.get(i));
}
this._modelInUse.clear();
@@ -302,8 +312,8 @@ export class UI {
ia.indexCount = batch.idxCount;
const uiModel = this._uiModelPool!.alloc();
uiModel.initialize(ia, batch);
uiModel.enabled = true;
uiModel.directInitialize(ia, batch);
this._scene.addModel(uiModel);
uiModel.getSubModel(0).priority = batchPriority++;
if (batch.camera) {
uiModel.visFlags = batch.camera.view.visibility;
@@ -331,13 +341,11 @@ export class UI {
const renderComp = comp;
const texView = frame;
if (this._currMaterial.hash !== renderComp.material!.hash ||
this._currTexView !== texView ||
this._currCanvas !== renderComp.visibility
this._currTexView !== texView
) {
this.autoMergeBatches();
this._currMaterial = renderComp.material!;
this._currTexView = texView;
this._currCanvas = renderComp.visibility;
}
if (assembler) {
@@ -368,7 +376,7 @@ export class UI {
}
}
const uiCanvas = this.getScreen(comp.visibility);
const uiCanvas = this._currCanvas;
const curDrawBatch = this._drawBatchPool.alloc();
curDrawBatch.camera = uiCanvas && uiCanvas.camera;
curDrawBatch.model = model;
@@ -384,13 +392,12 @@ export class UI {
// reset current render state to null
this._currMaterial = this._emptyMaterial;
this._currTexView = null;
this._currCanvas = comp.visibility;
this._batches.push(curDrawBatch);
}
public commitStaticBatch (comp: UIStaticBatchComponent) {
this._batches.append(comp.drawBatchList);
this._batches.concat(comp.drawBatchList);
this.finishMergeBatches();
}
@@ -407,7 +414,7 @@ export class UI {
return;
}
const uiCanvas = this.getScreen(this._currCanvas);
const uiCanvas = this._currCanvas;
StencilManager.sharedManager!.handleMaterial(mat);
@@ -490,11 +497,18 @@ export class UI {
continue;
}
this._currCanvas = screen;
this._recursiveScreenNode(screen.node);
}
}
private _preprocess (c: INode) {
if(!c.uiTransfromComp){
return;
}
// parent changed can flush child visibility
c.uiTransfromComp._canvas = this._currCanvas;
const render = c._uiComp;
if (render && render.enabledInHierarchy) {
render.updateAssembler(this);
@@ -527,7 +541,7 @@ export class UI {
this._batches.clear();
this._currMaterial = this._emptyMaterial;
this._currCanvas = -1;
this._currCanvas = null;
this._currTexView = null;
this._meshBufferUseCount = 0;
this._requireBufferBatch();
@@ -554,7 +568,8 @@ export class UI {
}
}
private _screenSort (a: CanvasComponent, b: CanvasComponent){
return a.priority - b.priority;
private _screenSort(a: CanvasComponent, b: CanvasComponent) {
const delta = a.priority - b.priority;
return delta === 0 ? a.node.getSiblingIndex() - b.node.getSiblingIndex() : delta;
}
}
+77 -2
View File
@@ -5,10 +5,16 @@
import { builtinResMgr } from './3d/builtin';
import { GFXDevice } from './gfx/device';
import { GFXWindow, IGFXWindowInfo } from './gfx/window';
import { Pool } from './memop';
import { RenderPipeline } from './pipeline/render-pipeline';
import { IRenderViewInfo, RenderView } from './pipeline/render-view';
import { Camera, Light, Model } from './renderer';
import { DataPoolManager } from './renderer/data-pool-manager';
import { DirectionalLight } from './renderer/scene/directional-light';
import { LightType } from './renderer/scene/light';
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';
export let _createSceneFun;
@@ -182,6 +188,12 @@ export class Root {
private _dataPoolMgr: DataPoolManager;
private _scenes: RenderScene[] = [];
private _views: RenderView[] = [];
private _modelPools: Map<Function, Pool<any>> = new Map<Function, Pool<any>>();
private _cameraPool: Pool<Camera> | null = null;
private _lightPools: Map<Function, Pool<any>> = new Map<Function, Pool<any>>();
private _directLightPool: Pool<DirectionalLight> | null = null;
private _sphereLightPool: Pool<SphereLight> | null = null;
private _spotLightPool: Pool<SpotLight> | null = null;
private _time: number = 0;
private _frameTime: number = 0;
private _fpsTime: number = 0;
@@ -200,6 +212,8 @@ export class Root {
RenderScene.registerCreateFunc(this);
RenderView.registerCreateFunc(this);
this._cameraPool = new Pool(() => new Camera(), 4);
}
/**
@@ -333,11 +347,13 @@ export class Root {
this._fpsTime = 0.0;
}
this._views.sort((a: RenderView, b: RenderView) => {
const views = this._views;
views.sort((a: RenderView, b: RenderView) => {
return a.priority - b.priority;
});
for (const view of this._views) {
for (let i = 0; i < views.length; i++) {
const view = views[i];
if (view.isEnable && (view.window &&
(view.window.isOffscreen ||
(!view.window.isOffscreen && (view.window === this._curWindow)))) && this._pipeline) {
@@ -468,4 +484,63 @@ export class Root {
}
this._views = [];
}
public createModel<T extends Model> (mClass: new () => T): T {
let p = this._modelPools.get(mClass);
if (!p) {
this._modelPools.set(mClass, new Pool(() => new mClass(), 10));
p = this._modelPools.get(mClass)!;
}
return p.alloc();
}
public destroyModel (m: Model) {
const p = this._modelPools.get(m.constructor);
if (p) {
p.free(m);
m.destroy();
if (m.scene) {
m.scene.removeModel(m);
}
}
}
public createCamera (): Camera {
return this._cameraPool!.alloc();
}
public destroyCamera (c: Camera) {
this._cameraPool!.free(c);
c.destroy();
if (c.scene) {
c.scene.removeCamera(c);
}
}
public createLight<T extends Light> (lClass: new () => T): T {
let l = this._lightPools.get(lClass);
if (!l) {
this._lightPools.set(lClass, new Pool(() => new lClass(), 4));
l = this._lightPools.get(lClass)!;
}
return l.alloc();
}
public destroyLight (l: Light) {
const p = this._lightPools.get(l.constructor);
l.destroy();
if (p) {
p.free(l);
if (l.scene) {
switch (l.type) {
case LightType.SPHERE:
l.scene.removeSphereLight(l as SphereLight);
break;
case LightType.SPOT:
l.scene.removeSpotLight(l as SpotLight);
break;
}
}
}
}
}
+1 -1
View File
@@ -1330,7 +1330,7 @@ export class BaseNode extends CCObject implements IBaseNode, ISchedulable {
// detach self and children from editor
const parent = this._parent;
const destroyByParent: boolean = (parent !== null) && ((parent._objFlags & Destroying) !== 0);
const destroyByParent: boolean = (!!parent) && ((parent._objFlags & Destroying) !== 0);
if (!destroyByParent && CC_EDITOR) {
this._registerIfAttached!(false);
}
+1 -1
View File
@@ -36,4 +36,4 @@ export { find } from './find';
export { PrivateNode } from './private-node';
export { default as NodeActivator } from './node-activator';
import './deprecated';
import './deprecated';
+30 -4
View File
@@ -27,17 +27,43 @@
* @category scene-graph
*/
import { ccenum } from '../value-types/enum';
export enum NodeSpace {
LOCAL,
WORLD,
}
export enum TransformDirtyBit {
export enum TransformBit {
/**
* @zh
* 无改变
*/
NONE = 0,
/**
* @zh
* 节点位置改变
*/
POSITION = (1 << 0),
/**
* @zh
* 节点旋转
*/
ROTATION = (1 << 1),
/**
* @zh
* 节点缩放
*/
SCALE = (1 << 2),
RS = TransformDirtyBit.ROTATION | TransformDirtyBit.SCALE,
TRS = TransformDirtyBit.POSITION | TransformDirtyBit.ROTATION | TransformDirtyBit.SCALE,
TRS_MASK = ~TransformDirtyBit.TRS,
/**
* @zh
* 节点旋转及缩放
*/
RS = TransformBit.ROTATION | TransformBit.SCALE,
/**
* @zh
* 节点平移,旋转及缩放
*/
TRS = TransformBit.POSITION | TransformBit.ROTATION | TransformBit.SCALE,
TRS_MASK = ~TransformBit.TRS,
}
+44 -40
View File
@@ -35,7 +35,7 @@ import { eventManager } from '../platform/event-manager/event-manager';
import { INode } from '../utils/interfaces';
import { BaseNode, TRANFORM_ON } from './base-node';
import { Layers } from './layers';
import { NodeSpace, TransformDirtyBit } from './node-enum';
import { NodeSpace, TransformBit } from './node-enum';
const v3_a = new Vec3();
const q_a = new Quat();
@@ -70,9 +70,15 @@ export class Node extends BaseNode implements INode {
public static NodeSpace = NodeSpace;
/**
* @zh
* 节点变换脏更新的具体部分
* 节点变换更新的具体部分
* @deprecated 请使用 [Node.TransformBit]
*/
public static TransformDirtyBit = TransformDirtyBit;
public static TransformDirtyBit = TransformBit;
/**
* @zh
* 节点变换更新的具体部分,可用于判断 TRANSFORM_CHANGED 事件的具体类型
*/
public static TransformBit = TransformBit;
// UI 部分的脏数据
public _uiTransfromComp: UITransformComponent | null = null;
@@ -99,7 +105,7 @@ export class Node extends BaseNode implements INode {
@property
protected _euler = new Vec3();
protected _dirtyFlags = TransformDirtyBit.NONE; // does the world transform need to update?
protected _dirtyFlags = TransformBit.NONE; // does the world transform need to update?
protected _eulerDirty = false;
/**
@@ -208,12 +214,10 @@ export class Node extends BaseNode implements INode {
*/
public set matrix (val: Readonly<Mat4>) {
Mat4.toRTS(val, this._lrot, this._lpos, this._lscale);
this.invalidateChildren(TransformDirtyBit.TRS);
this.invalidateChildren(TransformBit.TRS);
this._eulerDirty = true;
if (this._eventMask & TRANFORM_ON) {
this.emit(SystemEventType.TRANSFORM_CHANGED, SystemEventType.POSITION_PART);
this.emit(SystemEventType.TRANSFORM_CHANGED, SystemEventType.ROTATION_PART);
this.emit(SystemEventType.TRANSFORM_CHANGED, SystemEventType.SCALE_PART);
this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.TRS);
}
}
@@ -339,13 +343,13 @@ export class Node extends BaseNode implements INode {
this._eulerDirty = true;
}
this.invalidateChildren(TransformDirtyBit.TRS);
this.invalidateChildren(TransformBit.TRS);
}
public _onBatchCreated () {
super._onBatchCreated();
bookOfChange.set(this._id, TransformDirtyBit.TRS);
this._dirtyFlags = TransformDirtyBit.TRS;
bookOfChange.set(this._id, TransformBit.TRS);
this._dirtyFlags = TransformBit.TRS;
const len = this._children.length;
for (let i = 0; i < len; ++i) {
this._children[i]._onBatchCreated();
@@ -393,9 +397,9 @@ export class Node extends BaseNode implements INode {
}
}
this.invalidateChildren(TransformDirtyBit.POSITION);
this.invalidateChildren(TransformBit.POSITION);
if (this._eventMask & TRANFORM_ON) {
this.emit(SystemEventType.TRANSFORM_CHANGED, SystemEventType.POSITION_PART);
this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.POSITION);
}
}
@@ -420,9 +424,9 @@ export class Node extends BaseNode implements INode {
}
this._eulerDirty = true;
this.invalidateChildren(TransformDirtyBit.ROTATION);
this.invalidateChildren(TransformBit.ROTATION);
if (this._eventMask & TRANFORM_ON) {
this.emit(SystemEventType.TRANSFORM_CHANGED, SystemEventType.ROTATION_PART);
this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.ROTATION);
}
}
@@ -451,11 +455,11 @@ export class Node extends BaseNode implements INode {
* @zh
* 递归标记节点世界变换为 dirty
*/
public invalidateChildren (dirtyBit: TransformDirtyBit) {
public invalidateChildren (dirtyBit: TransformBit) {
if ((this._dirtyFlags & this.hasChangedFlags & dirtyBit) === dirtyBit) { return; }
this._dirtyFlags |= dirtyBit;
bookOfChange.set(this._id, this.hasChangedFlags | dirtyBit);
dirtyBit |= TransformDirtyBit.POSITION;
dirtyBit |= TransformBit.POSITION;
const len = this._children.length;
for (let i = 0; i < len; ++i) {
this._children[i].invalidateChildren(dirtyBit);
@@ -482,16 +486,16 @@ export class Node extends BaseNode implements INode {
child = array_a[--i];
dirtyBits |= child._dirtyFlags;
if (cur) {
if (dirtyBits & TransformDirtyBit.POSITION) {
if (dirtyBits & TransformBit.POSITION) {
Vec3.transformMat4(child._pos, child._lpos, cur._mat);
child._mat.m12 = child._pos.x;
child._mat.m13 = child._pos.y;
child._mat.m14 = child._pos.z;
}
if (dirtyBits & TransformDirtyBit.RS) {
if (dirtyBits & TransformBit.RS) {
Mat4.fromRTS(child._mat, child._lrot, child._lpos, child._lscale);
Mat4.multiply(child._mat, cur._mat, child._mat);
if (dirtyBits & TransformDirtyBit.ROTATION) {
if (dirtyBits & TransformBit.ROTATION) {
Quat.multiply(child._rot, cur._rot, child._lrot);
}
Mat3.fromQuat(m3_1, Quat.conjugate(qt_1, child._rot));
@@ -501,14 +505,14 @@ export class Node extends BaseNode implements INode {
child._scale.z = m3_1.m08;
}
} else {
if (dirtyBits & TransformDirtyBit.POSITION) {
if (dirtyBits & TransformBit.POSITION) {
Vec3.copy(child._pos, child._lpos);
child._mat.m12 = child._pos.x;
child._mat.m13 = child._pos.y;
child._mat.m14 = child._pos.z;
}
if (dirtyBits & TransformDirtyBit.RS) {
if (dirtyBits & TransformDirtyBit.ROTATION) {
if (dirtyBits & TransformBit.RS) {
if (dirtyBits & TransformBit.ROTATION) {
Quat.copy(child._rot, child._lrot);
} else {
Vec3.copy(child._scale, child._lscale);
@@ -516,7 +520,7 @@ export class Node extends BaseNode implements INode {
Mat4.fromRTS(child._mat, child._rot, child._pos, child._scale);
}
}
child._dirtyFlags = TransformDirtyBit.NONE;
child._dirtyFlags = TransformBit.NONE;
cur = child;
}
}
@@ -549,9 +553,9 @@ export class Node extends BaseNode implements INode {
Vec3.set(this._lpos, val as number, y, z);
}
this.invalidateChildren(TransformDirtyBit.POSITION);
this.invalidateChildren(TransformBit.POSITION);
if (this._eventMask & TRANFORM_ON) {
this.emit(SystemEventType.TRANSFORM_CHANGED, SystemEventType.POSITION_PART);
this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.POSITION);
}
}
@@ -593,9 +597,9 @@ export class Node extends BaseNode implements INode {
}
this._eulerDirty = true;
this.invalidateChildren(TransformDirtyBit.ROTATION);
this.invalidateChildren(TransformBit.ROTATION);
if (this._eventMask & TRANFORM_ON) {
this.emit(SystemEventType.TRANSFORM_CHANGED, SystemEventType.ROTATION_PART);
this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.ROTATION);
}
}
@@ -611,9 +615,9 @@ export class Node extends BaseNode implements INode {
Quat.fromEuler(this._lrot, x, y, z);
this._eulerDirty = false;
this.invalidateChildren(TransformDirtyBit.ROTATION);
this.invalidateChildren(TransformBit.ROTATION);
if (this._eventMask & TRANFORM_ON) {
this.emit(SystemEventType.TRANSFORM_CHANGED, SystemEventType.ROTATION_PART);
this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.ROTATION);
}
}
@@ -653,9 +657,9 @@ export class Node extends BaseNode implements INode {
Vec3.set(this._lscale, val as number, y, z);
}
this.invalidateChildren(TransformDirtyBit.SCALE);
this.invalidateChildren(TransformBit.SCALE);
if (this._eventMask & TRANFORM_ON) {
this.emit(SystemEventType.TRANSFORM_CHANGED, SystemEventType.SCALE_PART);
this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.SCALE);
}
}
@@ -723,9 +727,9 @@ export class Node extends BaseNode implements INode {
Vec3.copy(local, this._pos);
}
this.invalidateChildren(TransformDirtyBit.POSITION);
this.invalidateChildren(TransformBit.POSITION);
if (this._eventMask & TRANFORM_ON) {
this.emit(SystemEventType.TRANSFORM_CHANGED, SystemEventType.POSITION_PART);
this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.POSITION);
}
}
@@ -774,9 +778,9 @@ export class Node extends BaseNode implements INode {
}
this._eulerDirty = true;
this.invalidateChildren(TransformDirtyBit.ROTATION);
this.invalidateChildren(TransformBit.ROTATION);
if (this._eventMask & TRANFORM_ON) {
this.emit(SystemEventType.TRANSFORM_CHANGED, SystemEventType.ROTATION_PART);
this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.ROTATION);
}
}
@@ -797,9 +801,9 @@ export class Node extends BaseNode implements INode {
}
this._eulerDirty = true;
this.invalidateChildren(TransformDirtyBit.ROTATION);
this.invalidateChildren(TransformBit.ROTATION);
if (this._eventMask & TRANFORM_ON) {
this.emit(SystemEventType.TRANSFORM_CHANGED, SystemEventType.ROTATION_PART);
this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.ROTATION);
}
}
@@ -855,9 +859,9 @@ export class Node extends BaseNode implements INode {
Vec3.copy(this._lscale, this._scale);
}
this.invalidateChildren(TransformDirtyBit.SCALE);
this.invalidateChildren(TransformBit.SCALE);
if (this._eventMask & TRANFORM_ON) {
this.emit(SystemEventType.TRANSFORM_CHANGED, SystemEventType.SCALE_PART);
this.emit(SystemEventType.TRANSFORM_CHANGED, TransformBit.SCALE);
}
}
+1 -1
View File
@@ -28,7 +28,7 @@
*/
import { TextureCube } from '../assets/texture-cube';
import { ccclass, property, float } from '../data/class-decorator';
import { ccclass, float, property } from '../data/class-decorator';
import { CCBoolean, CCFloat } from '../data/utils/attribute';
import { Color, Quat, Vec3 } from '../math';
import { Ambient } from '../renderer/scene/ambient';
+10 -1
View File
@@ -62,6 +62,7 @@ export class SplashScreen {
private _splashFinish: boolean = false;
private _loadFinish: boolean = false;
private _directCall: boolean = false;
/** text */
private textImg!: TexImageSource;
@@ -106,7 +107,7 @@ export class SplashScreen {
if (this.callBack) { this.callBack(); }
this.callBack = null;
(this.setting as any) = null;
delete SplashScreen._ins;
this._directCall = true;
return;
} else {
cc.game.once(cc.Game.EVENT_GAME_INITED, () => {
@@ -181,6 +182,12 @@ export class SplashScreen {
}
public setOnFinish (cb: Function) {
if (this._directCall) {
if (cb) {
delete SplashScreen._ins;
return cb();
}
}
this.callBack = cb;
}
@@ -589,3 +596,5 @@ export class SplashScreen {
private constructor () { };
}
cc.SplashScreen = SplashScreen;
+4
View File
@@ -4,6 +4,7 @@
import { error, warn } from '../platform/debug';
// TODO: will redefined in ALIPAY and runtime
let defaultLogTimes = 10;
@@ -78,6 +79,7 @@ replacePropertyLog = function (n: string, dp: string, n2: string, newp: string,
};
replaceProperty = (owner: object, ownerName: string, properties: IReplacement[]) => {
if (CC_ALIPAY) { return; }
if (owner == null) return;
properties.forEach(function (item: IReplacement) {
@@ -164,6 +166,7 @@ removePropertyLog = function (n: string, dp: string, f: Function, id: number) {
};
removeProperty = (owner: object, ownerName: string, properties: IRemoveItem[]) => {
if (CC_ALIPAY) { return; }
if (owner == null) return;
properties.forEach(function (item: IRemoveItem) {
@@ -191,6 +194,7 @@ markAsWarningLog = function (n: string, dp: string, f: Function, id: number) {
};
markAsWarning = (owner: object, ownerName: string, properties: IMarkItem[]) => {
if (CC_ALIPAY) { return; }
if (owner == null) return;
let _defaultGetSet = function (o: {}, p: string, d: PropertyDescriptor, n: string, dp: string, f: Function, id: number) {
+2 -2
View File
@@ -27,7 +27,7 @@ import { Component } from '../components/component';
import { Event } from '../event';
import { Mat4, Quat, Size, Vec2, Vec3 } from '../math';
import { SystemEventType } from '../platform/event-manager/event-enum';
import { NodeSpace, TransformDirtyBit } from '../scene-graph/node-enum';
import { NodeSpace, TransformBit } from '../scene-graph/node-enum';
import { NodeEventProcessor } from '../scene-graph/node-event-processor';
import { Scene } from '../scene-graph/scene';
@@ -446,7 +446,7 @@ export interface INode extends IBaseNode {
* @zh
* 这个节点的空间变换信息在当前帧内是否有变过?
*/
hasChangedFlags: Readonly<TransformDirtyBit>;
hasChangedFlags: Readonly<TransformBit>;
/**
* @zh
+22 -6
View File
@@ -117,10 +117,12 @@ export class BillboardComponent extends Component {
super();
}
public onLoad () {
this.createModel();
}
public onEnable () {
if (!this._model) {
this.createModel();
}
this.attachToScene();
this._model!.enabled = true;
this.width = this._width;
this.height = this._height;
@@ -129,8 +131,21 @@ export class BillboardComponent extends Component {
}
public onDisable () {
if (this._model) {
this._model.enabled = false;
this.detachFromScene();
}
private attachToScene () {
if (this._model && this.node && this.node.scene) {
if (this._model.scene) {
this.detachFromScene();
}
this._getRenderScene().addModel(this._model);
}
}
private detachFromScene () {
if (this._model && this._model.scene) {
this._model.scene.removeModel(this._model);
}
}
@@ -157,7 +172,8 @@ export class BillboardComponent extends Component {
],
indices: [0, 1, 2, 1, 2, 3],
}, undefined, { calculateBounds: false });
this._model = this._getRenderScene().createModel(Model, this.node);
this._model = cc.director.root.createModel(Model, this.node);
this._model.initialize(this.node);
if (this._material == null) {
this._material = new Material();
this._material.copy(builtinResMgr.get<Material>('default-billboard-material'));
+31 -11
View File
@@ -199,19 +199,24 @@ export class LineComponent extends Component {
super();
}
public onLoad () {
this._model = cc.director.root.createModel(LineModel);
this._model.initialize(this.node);
this._model.setCapacity(100);
if (this._material == null) {
this._material = new Material();
this._material.copy(builtinResMgr.get<Material>('default-trail-material'));
define[CC_USE_WORLD_SPACE] = this.worldSpace;
this._material.recompileShaders(define);
}
this._model.setSubModelMaterial(0, this._material!);
}
public onEnable () {
if (!this._model) {
this._model = this._getRenderScene().createModel(LineModel, this.node);
this._model.setCapacity(100);
if (this._material == null) {
this._material = new Material();
this._material.copy(builtinResMgr.get<Material>('default-trail-material'));
define[CC_USE_WORLD_SPACE] = this.worldSpace;
this._material.recompileShaders(define);
}
this._model.setSubModelMaterial(0, this._material!);
return;
}
this._model!.enabled = true;
this.attachToScene();
this.texture = this.texture;
this.tile = this._tile;
this.offset = this._offset;
@@ -220,7 +225,22 @@ export class LineComponent extends Component {
public onDisable () {
if (this._model) {
this._model.enabled = false;
this.detachFromScene();
}
}
private attachToScene () {
if (this._model && this.node && this.node.scene) {
if (this._model.scene) {
this.detachFromScene();
}
this._getRenderScene().addModel(this._model);
}
}
private detachFromScene () {
if (this._model && this._model.scene) {
this._model.scene.removeModel(this._model);
}
}
}
+2 -2
View File
@@ -36,8 +36,8 @@ export class LineModel extends Model {
private _vertCount: number = 0;
private _indexCount: number = 0;
constructor (scene: RenderScene, node: INode) {
super(scene, node);
constructor () {
super();
this._capacity = 100;
this._iaInfo = {
drawInfos: [{
+11 -5
View File
@@ -31,12 +31,10 @@ import { Material } from '../../core/assets/material';
import { IRenderingSubmesh, Mesh } from '../../core/assets/mesh';
import { GFX_DRAW_INFO_SIZE, GFXBuffer, IGFXIndirectBuffer } from '../../core/gfx/buffer';
import { GFXAttributeName, GFXBufferUsageBit, GFXFormatInfos,
GFXMemoryUsageBit, GFXPrimitiveMode } from '../../core/gfx/define';
GFXMemoryUsageBit, GFXPrimitiveMode, GFXStatus } from '../../core/gfx/define';
import { IGFXAttribute } from '../../core/gfx/input-assembler';
import { Color } from '../../core/math/color';
import { Model } from '../../core/renderer/scene/model';
import { RenderScene } from '../../core/renderer/scene/render-scene';
import { Node } from '../../core/scene-graph';
export default class ParticleBatchModel extends Model {
@@ -54,8 +52,8 @@ export default class ParticleBatchModel extends Model {
private _vertCount: number = 0;
private _indexCount: number = 0;
constructor (scene: RenderScene, node: Node) {
super(scene, node);
constructor () {
super();
this._type = 'particle-batch';
this._capacity = 0;
@@ -184,6 +182,14 @@ export default class ParticleBatchModel extends Model {
this._iaInfo.drawInfos[0].vertexCount = this._capacity * this._vertCount;
this._iaInfo.drawInfos[0].indexCount = this._capacity * this._indexCount;
if (this._iaInfoBuffer.status === GFXStatus.UNREADY) {
this._iaInfoBuffer.initialize({
usage: GFXBufferUsageBit.INDIRECT,
memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE,
size: GFX_DRAW_INFO_SIZE,
stride: 1,
});
}
this._iaInfoBuffer.update(this._iaInfo);
this._subMeshData = {
+11 -17
View File
@@ -501,23 +501,17 @@ export class ParticleSystemComponent extends RenderableComponent {
return this._models;
}
public _changeSceneInModel () {
if (this.isValid) {
const r = this.renderer as any;
if (r && r._model) {
r._model.scene.destroyModel(r._model);
r._model = null;
r.onEnable();
r._updateModel();
r._updateMaterialParams();
}
const t = this.trailModule as any;
if (t && t._trailModel) {
t._trailModel.scene.destroyModel(t._trailModel);
t._trailModel = null;
t.enable = t._enable;
r._updateTrailMaterial();
}
protected _attachToScene() {
this.renderer._attachToScene();
if (this.trailModule.enable) {
this.trailModule._attachToScene();
}
}
protected _detachFromScene() {
this.renderer._detachFromScene();
if (this.trailModule.enable) {
this.trailModule._detachFromScene();
}
}
+16 -16
View File
@@ -2,16 +2,14 @@
* @hidden
*/
import { ParticleSystemComponent } from './particle-system-component';
import { CCObject } from '../core/data/object';
import { Node } from '../core/scene-graph';
import { Pool } from '../core/memop';
import { Director, director } from '../core/director';
import { instantiate } from '../core/data';
import { CCObject } from '../core/data/object';
import { Director, director } from '../core/director';
import { Pool } from '../core/memop';
import { Node } from '../core/scene-graph';
import { ParticleSystemComponent } from './particle-system-component';
export class ParticleUtils {
private static particleSystemPool: Map<string, Pool<CCObject>> = new Map<string, Pool<CCObject>>();
private static registeredSceneEvent: boolean = false;
/**
* instantiate
@@ -36,15 +34,6 @@ export class ParticleUtils {
}
}
private static onSceneUnload () {
this.particleSystemPool.forEach((value) => {
value.clear((prefab) => {
prefab.destroy();
});
});
this.particleSystemPool.clear();
}
public static play (rootNode: Node) {
for (const ps of rootNode.getComponentsInChildren(ParticleSystemComponent)) {
(ps as ParticleSystemComponent).play();
@@ -56,4 +45,15 @@ export class ParticleUtils {
(ps as ParticleSystemComponent).stop();
}
}
private static particleSystemPool: Map<string, Pool<CCObject>> = new Map<string, Pool<CCObject>>();
private static registeredSceneEvent: boolean = false;
private static onSceneUnload () {
this.particleSystemPool.forEach((value) => {
value.clear((prefab) => {
prefab.destroy();
});
});
this.particleSystemPool.clear();
}
}
@@ -1,14 +1,14 @@
import { builtinResMgr } from '../../core/3d/builtin';
import { Material, Mesh } from '../../core/assets';
import { Component } from '../../core/components';
import { ccclass, property } from '../../core/data/class-decorator';
import { Mat4, Vec2, Vec3, Vec4 } from '../../core/math';
import { GFXAttributeName, GFXFormat } from '../../core/gfx/define';
import { IGFXAttribute } from '../../core/gfx/input-assembler';
import { Mat4, Vec2, Vec3, Vec4 } from '../../core/math';
import { RecyclePool } from '../../core/memop';
import { IDefineMap } from '../../core/renderer/core/pass';
import ParticleBatchModel from '../models/particle-batch-model';
import { Mesh, Material } from '../../core/assets';
import { builtinResMgr } from '../../core/3d/builtin';
import RecyclePool from '../../core/memop/recycle-pool';
import { RenderMode, Space } from '../enum';
import ParticleBatchModel from '../models/particle-batch-model';
import Particle from '../particle';
const _tempAttribUV = new Vec3();
@@ -23,11 +23,13 @@ const _uvs = [
];
const CC_USE_WORLD_SPACE = 'CC_USE_WORLD_SPACE';
const CC_USE_BILLBOARD = 'CC_USE_BILLBOARD';
const CC_USE_STRETCHED_BILLBOARD = 'CC_USE_STRETCHED_BILLBOARD';
const CC_USE_HORIZONTAL_BILLBOARD = 'CC_USE_HORIZONTAL_BILLBOARD';
const CC_USE_VERTICAL_BILLBOARD = 'CC_USE_VERTICAL_BILLBOARD';
const CC_USE_MESH = 'CC_USE_MESH';
const CC_RENDER_MODE = 'CC_RENDER_MODE';
const RENDER_MODE_BILLBOARD = 0;
const RENDER_MODE_STRETCHED_BILLBOARD = 1;
const RENDER_MODE_HORIZONTAL_BILLBOARD = 2;
const RENDER_MODE_VERTICAL_BILLBOARD = 3;
const RENDER_MODE_MESH = 4;
const _vertex_attrs = [
{ name: GFXAttributeName.ATTR_POSITION, format: GFXFormat.RGB32F }, // position
@@ -66,7 +68,7 @@ export default class ParticleSystemRenderer {
@property({
type: RenderMode,
displayOrder: 0,
tooltip:'设定粒子生成模式',
tooltip: '设定粒子生成模式',
})
public get renderMode () {
return this._renderMode;
@@ -87,7 +89,7 @@ export default class ParticleSystemRenderer {
*/
@property({
displayOrder: 1,
tooltip:'在粒子生成方式为 StrecthedBillboard 时,对粒子在运动方向上按速度大小进行拉伸',
tooltip: '在粒子生成方式为 StrecthedBillboard 时,对粒子在运动方向上按速度大小进行拉伸',
})
public get velocityScale () {
return this._velocityScale;
@@ -104,7 +106,7 @@ export default class ParticleSystemRenderer {
*/
@property({
displayOrder: 2,
tooltip:'在粒子生成方式为 StrecthedBillboard 时,对粒子在运动方向上按粒子大小进行拉伸',
tooltip: '在粒子生成方式为 StrecthedBillboard 时,对粒子在运动方向上按粒子大小进行拉伸',
})
public get lengthScale () {
return this._lengthScale;
@@ -137,10 +139,7 @@ export default class ParticleSystemRenderer {
})
private _mesh: Mesh | null = null;
@property({
type: cc.ParticleSystemComponent,
visible: false,
})
@property
private _particleSystem: any = null;
/**
@@ -149,7 +148,7 @@ export default class ParticleSystemRenderer {
@property({
type: Mesh,
displayOrder: 7,
tooltip:'粒子发射的模型',
tooltip: '粒子发射的模型',
})
public get mesh () {
return this._mesh;
@@ -168,7 +167,7 @@ export default class ParticleSystemRenderer {
@property({
type: Material,
displayOrder: 8,
tooltip:'粒子使用的材质',
tooltip: '粒子使用的材质',
})
public get particleMaterial () {
if (!this._particleSystem) {
@@ -187,7 +186,7 @@ export default class ParticleSystemRenderer {
@property({
type: Material,
displayOrder: 9,
tooltip:'拖尾使用的材质',
tooltip: '拖尾使用的材质',
})
public get trailMaterial () {
if (!this._particleSystem) {
@@ -236,7 +235,6 @@ export default class ParticleSystemRenderer {
return new Particle(this);
}, 16);
this._setVertexAttrib();
this.onEnable();
this._updateModel();
this._updateMaterialParams();
this._updateTrailMaterial();
@@ -246,30 +244,37 @@ export default class ParticleSystemRenderer {
if (!this._particleSystem) {
return;
}
if (this._model == null) {
this._model = this._particleSystem._getRenderScene().createModel(ParticleBatchModel, this._particleSystem.node) as ParticleBatchModel;
this._model.visFlags = this._particleSystem.visibility;
}
if (!this._model.inited) {
this._model.setCapacity(this._particleSystem.capacity);
this._model.node = this._particleSystem.node;
}
this._model.enabled = this._particleSystem.enabledInHierarchy;
this._attachToScene();
this._model!.initialize(this._particleSystem.node);
this._model!.enabled = this._particleSystem.enabledInHierarchy;
}
public onDisable () {
if (this._model) {
this._model.enabled = this._particleSystem.enabledInHierarchy;
}
this._detachFromScene();
}
public onDestroy () {
if (this._model) {
this._model.scene.destroyModel(this._model);
cc.director.root.destroyModel(this._model);
this._model = null;
}
}
public _attachToScene () {
if (this._model) {
if (this._model.scene) {
this._detachFromScene();
}
this._particleSystem._getRenderScene().addModel(this._model);
}
}
public _detachFromScene () {
if (this._model && this._model.scene) {
this._model.scene.removeModel(this._model);
}
}
public clear () {
this._particles!.reset();
this._updateRenderData();
@@ -463,37 +468,17 @@ export default class ParticleSystemRenderer {
}
if (this._renderMode === RenderMode.Billboard) {
this._defines[CC_USE_BILLBOARD] = true;
this._defines[CC_USE_STRETCHED_BILLBOARD] = false;
this._defines[CC_USE_HORIZONTAL_BILLBOARD] = false;
this._defines[CC_USE_VERTICAL_BILLBOARD] = false;
this._defines[CC_USE_MESH] = false;
this._defines[CC_RENDER_MODE] = RENDER_MODE_BILLBOARD;
} else if (this._renderMode === RenderMode.StrecthedBillboard) {
this._defines[CC_USE_BILLBOARD] = false;
this._defines[CC_USE_STRETCHED_BILLBOARD] = true;
this._defines[CC_USE_HORIZONTAL_BILLBOARD] = false;
this._defines[CC_USE_VERTICAL_BILLBOARD] = false;
this._defines[CC_USE_MESH] = false;
this._defines[CC_RENDER_MODE] = RENDER_MODE_STRETCHED_BILLBOARD;
this.frameTile_velLenScale.z = this._velocityScale;
this.frameTile_velLenScale.w = this._lengthScale;
} else if (this._renderMode === RenderMode.HorizontalBillboard) {
this._defines[CC_USE_BILLBOARD] = false;
this._defines[CC_USE_STRETCHED_BILLBOARD] = false;
this._defines[CC_USE_HORIZONTAL_BILLBOARD] = true;
this._defines[CC_USE_VERTICAL_BILLBOARD] = false;
this._defines[CC_USE_MESH] = false;
this._defines[CC_RENDER_MODE] = RENDER_MODE_HORIZONTAL_BILLBOARD;
} else if (this._renderMode === RenderMode.VerticalBillboard) {
this._defines[CC_USE_BILLBOARD] = false;
this._defines[CC_USE_STRETCHED_BILLBOARD] = false;
this._defines[CC_USE_HORIZONTAL_BILLBOARD] = false;
this._defines[CC_USE_VERTICAL_BILLBOARD] = true;
this._defines[CC_USE_MESH] = false;
this._defines[CC_RENDER_MODE] = RENDER_MODE_VERTICAL_BILLBOARD;
} else if (this._renderMode === RenderMode.Mesh) {
this._defines[CC_USE_BILLBOARD] = false;
this._defines[CC_USE_STRETCHED_BILLBOARD] = false;
this._defines[CC_USE_HORIZONTAL_BILLBOARD] = false;
this._defines[CC_USE_VERTICAL_BILLBOARD] = false;
this._defines[CC_USE_MESH] = true;
this._defines[CC_RENDER_MODE] = RENDER_MODE_MESH;
} else {
console.warn(`particle system renderMode ${this._renderMode} not support.`);
}
@@ -531,9 +516,11 @@ export default class ParticleSystemRenderer {
private _updateModel () {
if (!this._model) {
return;
this._model = cc.director.root.createModel(ParticleBatchModel);
this._model!.setCapacity(this._particleSystem.capacity);
this._model!.visFlags = this._particleSystem.visibility;
}
this._model.setVertexAttributes(this._renderMode === RenderMode.Mesh ? this._mesh : null, this._vertAttrs);
this._model!.setVertexAttributes(this._renderMode === RenderMode.Mesh ? this._mesh : null, this._vertAttrs);
// if (Object.getPrototypeOf(this).constructor.name === 'ParticleSystemGpuRenderer') {
// return;
// }
+41 -32
View File
@@ -3,17 +3,17 @@
* @category particle
*/
import { Color, Vec3, Mat4, Quat, toRadian } from '../../core/math';
import { Material } from '../../core/assets/material';
import { IRenderingSubmesh } from '../../core/assets/mesh';
import { ccclass, property } from '../../core/data/class-decorator';
import { director } from '../../core/director';
import { GFX_DRAW_INFO_SIZE, GFXBuffer, IGFXIndirectBuffer } from '../../core/gfx/buffer';
import { GFXAttributeName, GFXBufferUsageBit, GFXFormat, GFXFormatInfos, GFXMemoryUsageBit, GFXPrimitiveMode } from '../../core/gfx/define';
import { GFXDevice } from '../../core/gfx/device';
import { IGFXAttribute } from '../../core/gfx/input-assembler';
import { Model } from '../../core/renderer';
import { Material } from '../../core/assets/material';
import { IRenderingSubmesh } from '../../core/assets/mesh';
import { Color, Mat4, Quat, toRadian, Vec3 } from '../../core/math';
import { Pool } from '../../core/memop';
import { director } from '../../core/director';
import { Model } from '../../core/renderer';
import CurveRange from '../animator/curve-range';
import GradientRange from '../animator/gradient-range';
import { Space, TextureMode, TrailMode } from '../enum';
@@ -31,15 +31,15 @@ const _temp_vec3 = new Vec3();
const _temp_vec3_1 = new Vec3();
const _temp_color = new Color();
const barycentric = [1,0,0, 0,1,0, 0,0,1]; // <wireframe debug>
let _bcIdx = 0;
const barycentric = [1, 0, 0, 0, 1, 0, 0, 0, 1]; // <wireframe debug>
const _bcIdx = 0;
interface ITrailElement {
position: Vec3;
lifetime: number;
width: number;
velocity: Vec3;
direction: number; //if one element's direction differs from the previous one,it means the trail's direction reverse.
direction: number; // if one element's direction differs from the previous one,it means the trail's direction reverse.
color: Color;
}
@@ -178,7 +178,7 @@ export default class TrailModule {
@property({
type: TrailMode,
displayOrder: 1,
tooltip:'Particle在每个粒子的运动轨迹上形成拖尾效果',
tooltip: 'Particle在每个粒子的运动轨迹上形成拖尾效果',
})
public mode = TrailMode.Particles;
@@ -188,7 +188,7 @@ export default class TrailModule {
@property({
type: CurveRange,
displayOrder: 3,
tooltip:'拖尾的生命周期',
tooltip: '拖尾的生命周期',
})
public lifeTime = new CurveRange();
@@ -200,7 +200,7 @@ export default class TrailModule {
*/
@property({
displayOrder: 5,
tooltip:'粒子每生成一个拖尾节点所运行的最短距离',
tooltip: '粒子每生成一个拖尾节点所运行的最短距离',
})
public get minParticleDistance () {
return this._minParticleDistance;
@@ -214,7 +214,7 @@ export default class TrailModule {
@property({
type: Space,
displayOrder: 6,
tooltip:'拖尾所在的坐标系,World在世界坐标系中运行,Local在本地坐标系中运行',
tooltip: '拖尾所在的坐标系,World在世界坐标系中运行,Local在本地坐标系中运行',
})
public get space () {
return this._space;
@@ -232,7 +232,7 @@ export default class TrailModule {
*/
@property({
displayOrder: 7,
tooltip:'拖尾是否跟随粒子一起消失',
tooltip: '拖尾是否跟随粒子一起消失',
})
public existWithParticles = true;
@@ -242,13 +242,13 @@ export default class TrailModule {
@property({
type: TextureMode,
displayOrder: 8,
tooltip:'贴图在拖尾上的展开形式,Stretch贴图覆盖在整条拖尾上,Repeat贴图覆盖在一段拖尾上',
tooltip: '贴图在拖尾上的展开形式,Stretch贴图覆盖在整条拖尾上,Repeat贴图覆盖在一段拖尾上',
})
public textureMode = TextureMode.Stretch;
@property({
displayOrder: 9,
tooltip:'拖尾宽度继承自粒子大小'
tooltip: '拖尾宽度继承自粒子大小',
})
public widthFromParticle = true;
@@ -258,27 +258,27 @@ export default class TrailModule {
@property({
type: CurveRange,
displayOrder: 10,
tooltip:'拖尾宽度,如果继承自粒子则是粒子大小的比例',
tooltip: '拖尾宽度,如果继承自粒子则是粒子大小的比例',
})
public widthRatio = new CurveRange();
@property({
displayOrder: 11,
tooltip:'拖尾颜色是否继承自粒子'
tooltip: '拖尾颜色是否继承自粒子',
})
public colorFromParticle = false;
@property({
type: GradientRange,
displayOrder: 12,
tooltip:'拖尾颜色随拖尾自身长度的颜色渐变'
tooltip: '拖尾颜色随拖尾自身长度的颜色渐变',
})
public colorOverTrail = new GradientRange();
@property({
type: GradientRange,
displayOrder: 13,
tooltip:'拖尾颜色随时间的颜色渐变'
tooltip: '拖尾颜色随时间的颜色渐变',
})
public colorOvertime = new GradientRange();
@@ -290,10 +290,7 @@ export default class TrailModule {
})
private _space = Space.World;
@property({
type: cc.ParticleSystemComponent,
visible: false,
})
@property
private _particleSystem: any = null;
private _minSquaredDistance: number = 0;
@@ -359,20 +356,31 @@ export default class TrailModule {
}
public onEnable () {
if (this._enable && this._trailModel) {
this._trailModel.enabled = true;
}
this._attachToScene();
}
public onDisable () {
if (this._enable && this._trailModel) {
this._trailModel.enabled = false;
this._detachFromScene();
}
public _attachToScene () {
if (this._trailModel) {
if (this._trailModel.scene) {
this._detachFromScene();
}
this._particleSystem._getRenderScene().addModel(this._trailModel);
}
}
public _detachFromScene () {
if (this._trailModel && this._trailModel.scene) {
this._trailModel.scene.removeModel(this._trailModel);
}
}
public destroy () {
if (this._trailModel) {
this._trailModel.scene.destroyModel(this._trailModel);
cc.director.root.destroyModel(this._trailModel);
this._trailModel = null;
}
if (this._trailSegments) {
@@ -521,8 +529,8 @@ export default class TrailModule {
const lastThirdTrail = trailSeg.getElement(trailSeg.end - 2)!;
Vec3.subtract(_temp_vec3, lastThirdTrail.position, lastSecondTrail.position);
Vec3.subtract(_temp_vec3_1, _temp_trailEle.position, lastSecondTrail.position);
Vec3.normalize(_temp_vec3,_temp_vec3);
Vec3.normalize(_temp_vec3_1,_temp_vec3_1);
Vec3.normalize(_temp_vec3, _temp_vec3);
Vec3.normalize(_temp_vec3_1, _temp_vec3_1);
Vec3.subtract(lastSecondTrail.velocity, _temp_vec3_1, _temp_vec3);
Vec3.normalize(lastSecondTrail.velocity, lastSecondTrail.velocity);
this._checkDirectionReverse(lastSecondTrail, lastThirdTrail);
@@ -606,7 +614,8 @@ export default class TrailModule {
flatBuffers: [],
};
this._trailModel = this._particleSystem._getRenderScene().createModel(Model, this._particleSystem.node);
this._trailModel = cc.director.root.createModel(Model);
this._trailModel!.initialize(this._particleSystem.node);
this._trailModel!.visFlags = this._particleSystem.visibility;
this._trailModel!.setSubModelMesh(0, this._subMeshData);
this._trailModel!.enabled = true;
@@ -11,7 +11,7 @@ import { AfterStepCallback, BeforeStepCallback, PhysicsWorldBase, RigidBodyBase
import { createRigidBody } from '../../instance';
import { ERigidBodyType, ETransformSource } from '../../physic-enum';
import { INode } from '../../../core/utils/interfaces';
import { TransformDirtyBit } from '../../../core/scene-graph/node-enum';
import { TransformBit } from '../../../core/scene-graph/node-enum';
import { error } from '../../../core/platform/debug';
import { PhysicsSystem } from '../physics-system';
@@ -376,7 +376,7 @@ class SharedRigidBody {
// 开始物理计算之前,用户脚本或引擎功能有可能改变节点的Transform,所以需要判断并进行更新
if (this._node.hasChangedFlags) {
// scale 进行单独判断,因为目前的物理系统处理后不会改变scale的属性
if (this._node.hasChangedFlags & TransformDirtyBit.SCALE) {
if (this._node.hasChangedFlags & TransformBit.SCALE) {
this._body.scaleAllShapes(this._node.worldScale);
}
this._syncPhysWithScene(this._node);
@@ -30,7 +30,6 @@
import { Color, Vec3 } from '../../../../core/math';
import { GFXPrimitiveMode } from '../../../../core/gfx';
import { Model } from '../../../../core/renderer';
import { RenderScene } from '../../../../core/renderer/scene/render-scene';
import { MeshRenderData } from '../../../../core/renderer/ui/render-data';
import { UI } from '../../../../core/renderer/ui/ui';
import { createMesh } from '../../../../core/3d/misc/utils';
@@ -40,7 +39,8 @@ import { IAssembler } from '../../../../core/renderer/ui/base';
import { LineCap, LineJoin, PointFlags } from '../types';
import { earcut as Earcut } from './earcut';
import { Impl, Point } from './impl';
import { director } from '../../../../core/director';
import { director } from '../../../../core';
import { RenderScene } from '../../../../core/renderer/scene/render-scene';
const MAX_VERTEX = 65535;
const MAX_INDICE = MAX_VERTEX * 2;
@@ -175,14 +175,10 @@ export const graphicsAssembler: IAssembler = {
this.end(graphics);
},
end (graphics: GraphicsComponent){
const scene = director.root!.ui.renderScene as RenderScene;
if (graphics.model){
end(graphics: GraphicsComponent) {
if (graphics.model) {
graphics.model.destroy();
scene.destroyModel(graphics.model);
graphics.model = null;
}
const impl = graphics.impl;
const primitiveMode = GFXPrimitiveMode.TRIANGLE_LIST;
const renderDatas = impl && impl.getRenderDatas();
@@ -226,9 +222,8 @@ export const graphicsAssembler: IAssembler = {
indices,
}, undefined, { calculateBounds: false });
graphics.model = scene.createModel(Model, graphics.node);
graphics.model.initSubModel(0, mesh.getSubMesh(0), graphics.material!);
graphics.model.enabled = true;
graphics.model!.initialize(graphics.node);
graphics.model!.initSubModel(0, mesh.getSubMesh(0), graphics.material!);
graphics.markForUpdateRenderData();
},
+1 -1
View File
@@ -1,7 +1,7 @@
import { Color, Vec2 } from '../../../../core/math';
import { RecyclePool } from '../../../../core/memop';
import { MeshRenderData } from '../../../../core/renderer/ui/render-data';
import RecyclePool from '../../../../core/memop/recycle-pool';
import { arc, ellipse, roundRect, tesselateBezier } from '../helper';
import { LineCap, LineJoin, PointFlags} from '../types';
+4 -3
View File
@@ -34,6 +34,7 @@ import { barFilled } from './bar-filled';
import { radialFilled } from './radial-filled';
import { simple } from './simple';
import { sliced } from './sliced';
import { tilled } from './tiled';
const SpriteType = SpriteComponent.Type;
const FillType = SpriteComponent.FillType;
@@ -49,9 +50,9 @@ const spriteAssembler: IAssemblerManager = {
case SpriteType.SLICED:
util = sliced;
break;
// case SpriteType.TILED:
// util = tilled;
// break;
case SpriteType.TILED:
util = tilled;
break;
case SpriteType.FILLED:
if (comp.fillType === FillType.RADIAL) {
util = radialFilled;
+100 -165
View File
@@ -23,23 +23,19 @@
THE SOFTWARE.
*/
import { Mat4, Vec3 } from '../../../core/math';
import { RenderData } from '../../../core/renderer/ui/render-data';
import { Mat4, Vec3, Color } from '../../../core/math';
import { RenderData, IRenderData } from '../../../core/renderer/ui/render-data';
import { UI } from '../../../core/renderer/ui/ui';
import { SpriteComponent } from '../../components/sprite-component';
import { UIRenderComponent } from '../../../core/components/ui-base/ui-render-component';
import { IAssembler } from '../../../core/renderer/ui/base';
const matrix = new Mat4();
const vec3_temps: Vec3[] = [];
for (let i = 0; i < 4; i++) {
vec3_temps.push(new Vec3());
}
const _tempVertexOffset = 6;
const _tempUvOffset = 3;
const _tempColorOffset = 5;
const _perVertextLength = 9;
export const tilled: IAssembler = {
useModel: false,
@@ -49,33 +45,17 @@ export const tilled: IAssembler = {
},
updateRenderData (sprite: SpriteComponent) {
const frame = sprite.spriteFrame;
// TODO: Material API design and export from editor could affect the material activation process
// need to update the logic here
// if (frame) {
// if (!frame._original && dynamicAtlasManager) {
// dynamicAtlasManager.insertSpriteFrame(frame);
// }
// if (sprite._material._texture !== frame._texture) {
// sprite._activateMaterial();
// }
// }
const renderData = sprite.renderData;
if (!frame || !renderData ||
!(renderData.uvDirty || renderData.vertDirty)) {
const renderData = sprite.renderData!;
const frame = sprite.spriteFrame!;
if (!frame || !renderData || !(renderData.uvDirty || renderData.vertDirty)){
return;
}
const node = sprite.node;
// contentWidth = Math.abs(node.width),
// contentHeight = Math.abs(node.height),
const contentWidth = Math.abs(node.width);
const contentHeight = Math.abs(node.height);
const appx = node.anchorX * contentWidth;
const appy = node.anchorY * contentHeight;
// node._updateWorldMatrix();
const rect = frame.getRect();
const rectWidth = rect.width;
@@ -85,14 +65,14 @@ export const tilled: IAssembler = {
const row = Math.ceil(vRepeat);
const col = Math.ceil(hRepeat);
const data = renderData.datas;
const datas = renderData.datas;
renderData.dataLength = Math.max(8, row + 1, col + 1);
for (let i = 0; i <= col; ++i) {
data[i].x = Math.min(rectWidth * i, contentWidth) - appx;
datas[i].x = Math.min(rectWidth * i, contentWidth) - appx;
}
for (let i = 0; i <= row; ++i) {
data[i].y = Math.min(rectHeight * i, contentHeight) - appy;
datas[i].y = Math.min(rectHeight * i, contentHeight) - appy;
}
// update data property
@@ -103,28 +83,32 @@ export const tilled: IAssembler = {
},
fillBuffers (sprite: SpriteComponent, renderer: UI) {
const buffer = renderer.currBufferBatch!;
const node = sprite.node;
const color = sprite.color;
const renderData = sprite.renderData;
const datas = renderData!.datas;
const renderData = sprite.renderData!;
// buffer
let vertexOffset = buffer.byteOffset >> 2;
let indiceOffset = buffer.indiceOffset;
let vertexId = buffer.vertexOffset;
buffer.request(renderData!.vertexCount, renderData!.indiceCount);
let buffer = renderer.currBufferBatch!;
// buffer data may be realloc, need get reference after request.
const vbuf = buffer.vData;
// uintbuf = buffer._uintVData,
const ibuf = buffer.iData;
let indiceOffset = buffer.indiceOffset;
let vertexOffset = buffer.byteOffset >> 2;
let vertexId = buffer.vertexOffset;
const vertexCount = renderData!.vertexCount;
const indiceCount = renderData.indiceCount;
const vbuf = buffer.vData!;
const ibuf = buffer.iData!;
const rotated = sprite.spriteFrame!.isRotated;
const uv = sprite.spriteFrame!.uv;
const rect = sprite.spriteFrame!.getRect();
const isRecreate = buffer.request(vertexCount, indiceCount);
if (!isRecreate) {
buffer = renderer.currBufferBatch!;
vertexOffset = 0;
indiceOffset = 0;
vertexId = 0;
}
const frame = sprite.spriteFrame!;
const rotated = frame.isRotated();
const uv = frame.uv;
const rect = frame.getRect();
const contentWidth = Math.abs(node.width);
const contentHeight = Math.abs(node.height);
const hRepeat = contentWidth / rect.width;
@@ -132,14 +116,72 @@ export const tilled: IAssembler = {
const row = Math.ceil(vRepeat);
const col = Math.ceil(hRepeat);
// const matrix = node._worldMatrix;
const matrix = node.worldMatrix;
// this.updateVerts(vbuf, vertexOffset, matrix, row, col, datas);
// updataVerts
let x = 0;
let x1 = 0;
let y = 0;
let y1 = 0;
this.fillVertices(vbuf, vertexOffset, matrix, row, col, renderData.datas);
const offset = _perVertextLength;
const offset1 = offset; const offset2 = offset * 2; const offset3 = offset * 3; const offset4 = offset * 4;
let coefu = 0; let coefv = 0;
for (let yindex = 0, ylength = row; yindex < ylength; ++yindex) {
coefv = Math.min(1, vRepeat - yindex);
for (let xindex = 0, xlength = col; xindex < xlength; ++xindex) {
coefu = Math.min(1, hRepeat - xindex);
const vertexOffsetU = vertexOffset + 3;
const vertexOffsetV = vertexOffsetU + 1;
// UV
if (rotated) {
// lb
vbuf[vertexOffsetU] = uv[0];
vbuf[vertexOffsetV] = uv[1];
// rb
vbuf[vertexOffsetU + offset1] = uv[0];
vbuf[vertexOffsetV + offset1] = uv[1] + (uv[7] - uv[1]) * coefu;
// lt
vbuf[vertexOffsetU + offset2] = uv[0] + (uv[6] - uv[0]) * coefv;
vbuf[vertexOffsetV + offset2] = uv[1];
// rt
vbuf[vertexOffsetU + offset3] = vbuf[vertexOffsetU + offset2];
vbuf[vertexOffsetV + offset3] = vbuf[vertexOffsetV + offset1];
}
else {
// lb
vbuf[vertexOffsetU] = uv[0];
vbuf[vertexOffsetV] = uv[1];
// rb
vbuf[vertexOffsetU + offset1] = uv[0] + (uv[6] - uv[0]) * coefu;
vbuf[vertexOffsetV + offset1] = uv[1];
// lt
vbuf[vertexOffsetU + offset2] = uv[0];
vbuf[vertexOffsetV + offset2] = uv[1] + (uv[7] - uv[1]) * coefv;
// rt
vbuf[vertexOffsetU + offset3] = vbuf[vertexOffsetU + offset1];
vbuf[vertexOffsetV + offset3] = vbuf[vertexOffsetV + offset2];
}
// color
Color.toArray(vbuf!, sprite.color, vertexOffsetV + 1);
Color.toArray(vbuf!, sprite.color, vertexOffsetV + offset1 + 1);
Color.toArray(vbuf!, sprite.color, vertexOffsetV + offset2 + 1);
Color.toArray(vbuf!, sprite.color, vertexOffsetV + offset3 + 1);
vertexOffset += offset4;
}
}
// update indices
for (let i = 0; i < indiceCount; i += 6) {
ibuf[indiceOffset++] = vertexId;
ibuf[indiceOffset++] = vertexId + 1;
ibuf[indiceOffset++] = vertexId + 2;
ibuf[indiceOffset++] = vertexId + 1;
ibuf[indiceOffset++] = vertexId + 3;
ibuf[indiceOffset++] = vertexId + 2;
vertexId += 4;
}
},
fillVertices (vbuf: Float32Array, vertexOffset: number, matrix: Mat4, row: number, col: number, datas: IRenderData[]) {
let x = 0; let x1 = 0; let y = 0; let y1 = 0;
for (let yindex = 0, ylength = row; yindex < ylength; ++yindex) {
y = datas[yindex].y;
y1 = datas[yindex + 1].y;
@@ -155,121 +197,14 @@ export const tilled: IAssembler = {
for (let i = 0; i < 4; i++) {
const vec3_temp = vec3_temps[i];
Vec3.transformMat4(vec3_temp, vec3_temp, matrix);
const move = i * 6;
vbuf![vertexOffset + move] = vec3_temp.x;
vbuf![vertexOffset + move + 1] = vec3_temp.y;
vbuf![vertexOffset + move + 2] = vec3_temp.z;
const offset = i * _perVertextLength;
vbuf[vertexOffset + offset] = vec3_temp.x;
vbuf[vertexOffset + offset + 1] = vec3_temp.y;
vbuf[vertexOffset + offset + 2] = vec3_temp.z;
}
vertexOffset += 24;
vertexOffset += 36;
}
}
const offset = _tempVertexOffset;
const uvOffset = _tempUvOffset;
const colorOffset = _tempColorOffset;
const offset1 = offset;
const offset2 = offset * 2;
const offset3 = offset * 3;
const offset4 = offset * 4;
let coefu = 0;
let coefv = 0;
for (let yindex = 0, ylength = row; yindex < ylength; ++yindex) {
coefv = Math.min(1, vRepeat - yindex);
for (let xindex = 0, xlength = col; xindex < xlength; ++xindex) {
coefu = Math.min(1, hRepeat - xindex);
const vertexOffsetU = vertexOffset + uvOffset;
const vertexOffsetV = vertexOffsetU + 1;
// UV
if (rotated) {
// lb
vbuf![vertexOffsetU] = uv[0];
vbuf![vertexOffsetV] = uv[1];
// rb
vbuf![vertexOffsetU + offset1] = uv[0];
vbuf![vertexOffsetV + offset1] = uv[1] + (uv[7] - uv[1]) * coefu;
// lt
vbuf![vertexOffsetU + offset2] = uv[0] + (uv[6] - uv[0]) * coefv;
vbuf![vertexOffsetV + offset2] = uv[1];
// rt
vbuf![vertexOffsetU + offset3] = vbuf![vertexOffsetU + offset2];
vbuf![vertexOffsetV + offset3] = vbuf![vertexOffsetV + offset1];
} else {
// lb
vbuf![vertexOffsetU] = uv[0];
vbuf![vertexOffsetV] = uv[1];
// rb
vbuf![vertexOffsetU + offset1] = uv[0] + (uv[6] - uv[0]) * coefu;
vbuf![vertexOffsetV + offset1] = uv[1];
// lt
vbuf![vertexOffsetU + offset2] = uv[0];
vbuf![vertexOffsetV + offset2] = uv[1] + (uv[7] - uv[1]) * coefv;
// rt
vbuf![vertexOffsetU + offset3] = vbuf![vertexOffsetU + offset1];
vbuf![vertexOffsetV + offset3] = vbuf![vertexOffsetV + offset2];
}
vbuf![vertexOffset + colorOffset] = color.x;
vbuf![vertexOffset + colorOffset + offset1] = color.y;
vbuf![vertexOffset + colorOffset + offset2] = color.z;
vbuf![vertexOffset + colorOffset + offset3] = color.w;
// TODO: addColor
// color
// uintbuf[vertexOffset + colorOffset] = color;
// uintbuf[vertexOffset + colorOffset + offset1] = color;
// uintbuf[vertexOffset + colorOffset + offset2] = color;
// uintbuf[vertexOffset + colorOffset + offset3] = color;
vertexOffset += offset4;
}
}
// update indices
const length = renderData!.indiceCount;
for (let i = 0; i < length; i += 6) {
ibuf![indiceOffset++] = vertexId;
ibuf![indiceOffset++] = vertexId + 1;
ibuf![indiceOffset++] = vertexId + 2;
ibuf![indiceOffset++] = vertexId + 1;
ibuf![indiceOffset++] = vertexId + 3;
ibuf![indiceOffset++] = vertexId + 2;
vertexId += 4;
}
},
updateVerts (sprite: SpriteComponent) {
// const renderData = sprite.renderData;
// const datas = renderData!.datas;
// const vbuf;
// const vertexOffset;
// sprite.node.getWorldMatrix(matrix);
// const row;
// const col;
// const data;
// let x, x1, y, y1;
// for (let yindex = 0, ylength = row; yindex < ylength; ++yindex) {
// y = data[yindex].y;
// y1 = data[yindex + 1].y;
// for (let xindex = 0, xlength = col; xindex < xlength; ++xindex) {
// x = data[xindex].x;
// x1 = data[xindex + 1].x;
// vec3.set(vec3_temps[0], x, y, 0);
// vec3.set(vec3_temps[1], x1, y, 0);
// vec3.set(vec3_temps[2], x, y1, 0);
// vec3.set(vec3_temps[3], x1, y1, 0);
// for (let i = 0; i < 4; i++) {
// let vec3_temp = vec3_temps[i];
// vec3.transformMat4(vec3_temp, vec3_temp, matrix);
// let offset = i * 6;
// vbuf[vertexOffset + offset] = vec3_temp.x;
// vbuf[vertexOffset + offset + 1] = vec3_temp.y;
// vbuf[vertexOffset + offset + 2] = vec3_temp.z;
// }
// vertexOffset += 24;
// }
// }
},
};
+5 -14
View File
@@ -421,13 +421,13 @@ export class EditBoxImpl {
public _updateMatrix () {
if (!this._edTxt) { return; }
const node = this._node;
const node = this._node!;
let scaleX = view.getScaleX();
let scaleY = view.getScaleY();
const viewport = view.getViewportRect();
const dpr = view.getDevicePixelRatio();
node!.getWorldMatrix(_matrix);
node.getWorldMatrix(_matrix);
const transform = node!.uiTransfromComp;
if (transform) {
Vec3.set(_vec3, -transform.anchorX * transform.width, -transform.anchorY * transform.height, _vec3.z);
@@ -435,20 +435,11 @@ export class EditBoxImpl {
Mat4.transform(_matrix, _matrix, _vec3);
// let camera;
// can't find camera in editor
// if (CC_EDITOR) {
// camera = cc.Camera.main;
// }
// else {
// camera = cc.Camera.findCamera(node);
// }
const renderComp:UIRenderComponent = node!.getComponent(UIRenderComponent);
if (!renderComp) {
if (!node.uiTransfromComp) {
return false;
}
// let canvas = cc.CanvasComponent.findView(renderComp);
const canvas = director.root!.ui.getScreen(renderComp.visibility);
const canvas = director.root!.ui.getScreen(node.uiTransfromComp.visibility);
if (!canvas) {
return;
}

Some files were not shown because too many files have changed in this diff Show More