Merge branch '3d-v1.0.2' into 3d

# Conflicts:
#	cocos/core/components/ui-base/ui-render-component.ts
#	cocos/core/components/ui-base/ui-transform-component.ts
#	cocos/core/scene-graph/base-node.ts
#	cocos/terrain/terrain.ts
This commit is contained in:
pandamicro
2019-11-19 18:28:54 +08:00
162 changed files with 3561 additions and 2302 deletions
+7 -7
View File
@@ -574,15 +574,11 @@ Please do not specifiy "default" attribute in decorator of "%s" property in "%s"
Default value must be initialized at their declaration:
```
// Before:
@property({
type: cc.Integer
default: 0 // <--
})
@property({ default: 0 }) // <--
@integer
value;
// After:
@property({
type: cc.Integer
})
@integer
value = 0; // <--
```
@@ -732,6 +728,10 @@ The renderer doesn't support the renderMode %s
Cannot change hierarchy while activating or deactivating the parent.
### 3822
addComponent: Cannot add any component to the scene.
### 3900
Invalid clip to add
+4 -4
View File
@@ -46,8 +46,8 @@ This is all you have to do to setup engine development environment.
## Links
- [Official site](http://www.cocos.com/en)
- [Forum](https://forum.cocos.com/c/3D)
- [Documentation](https://github.com/cocos-creator/docs-3d)
- API Referencess: Not yet published
- Download: To be announced
- [Forum](https://forum.cocos.org/c/3D)
- [Documentation](https://docs.cocos.com/creator3d/manual/zh)
- [API Referencess](https://docs.cocos.com/creator3d/api/zh)
- [Download](https://www.cocos.com/creator3d)
- Road Map: To be announced
+26 -9
View File
@@ -35,32 +35,46 @@ export class AudioPlayerDOM extends AudioPlayer {
protected _loop = false;
protected _oneShoting = false;
protected _audio: HTMLAudioElement;
protected _cbRegistered = false;
private _remove_cb: () => void;
private _post_play: () => void;
private _on_gesture: () => void;
private _post_gesture: () => void;
constructor (info: IAudioInfo) {
super(info);
this._audio = info.clip;
this._remove_cb = () => {
if (!this._cbRegistered) { return; }
cc.game.canvas.removeEventListener('touchend', this._on_gesture);
cc.game.canvas.removeEventListener('mouseup', this._on_gesture);
this._cbRegistered = false;
};
this._post_play = () => {
this._state = PlayingState.PLAYING;
this._eventTarget.emit('started');
this._remove_cb(); // should remove callbacks after any success play
};
this._post_gesture = () => {
if (this._interrupted) { this._post_play(); this._interrupted = false; }
else { this._audio!.pause(); this._audio!.currentTime = 0; }
};
this._on_gesture = () => {
if (!this._audio) { return; }
const promise = this._audio.play();
if (!promise) {
console.warn('no promise returned from HTMLMediaElement.play()');
if (!promise) { // Chrome50/Firefox53 below
// delay eval here to yield uniform behavior with other platforms
this._state = PlayingState.PLAYING;
cc.director.once(cc.Director.EVENT_AFTER_UPDATE, this._post_gesture);
return;
}
promise.then(() => {
if (this._interrupted) { this._post_play(); this._interrupted = false; }
else { this._audio!.pause(); this._audio!.currentTime = 0; }
cc.game.canvas.removeEventListener('touchend', this._on_gesture);
cc.game.canvas.removeEventListener('mouseup', this._on_gesture);
});
promise.then(this._post_gesture);
this._remove_cb();
};
this._audio.volume = this._volume;
@@ -76,6 +90,7 @@ export class AudioPlayerDOM extends AudioPlayer {
we can freely invoke play() outside event listeners later */
cc.game.canvas.addEventListener('touchend', this._on_gesture);
cc.game.canvas.addEventListener('mouseup', this._on_gesture);
this._cbRegistered = true;
}
public play () {
@@ -83,7 +98,9 @@ export class AudioPlayerDOM extends AudioPlayer {
if (this._blocking) { this._interrupted = true; return; }
const promise = this._audio.play();
if (!promise) {
console.warn('no promise returned from HTMLMediaElement.play()');
// delay eval here to yield uniform behavior with other platforms
this._state = PlayingState.PLAYING;
cc.director.once(cc.Director.EVENT_AFTER_UPDATE, this._post_play);
return;
}
promise.then(this._post_play).catch(() => { this._interrupted = true; });
+7 -5
View File
@@ -27,7 +27,6 @@
* @category component/audio
*/
import { director, Director } from '../../core/director';
import { clamp } from '../../core/math/utils';
import sys from '../../core/platform/sys';
import { AudioPlayer, IAudioInfo, PlayingState } from './player';
@@ -71,11 +70,13 @@ export class AudioPlayerWeb extends AudioPlayer {
this._sourceNode.buffer = this._audio;
this._sourceNode.loop = this._loop;
this._sourceNode.connect(this._gainNode);
this._sourceNode.start(0, this._offset);
this._state = PlayingState.PLAYING;
this._startTime = this._context.currentTime;
// delay eval here to yield uniform behavior with other platforms
director.once(Director.EVENT_AFTER_UPDATE, () => { this._eventTarget.emit('started'); });
cc.director.once(cc.Director.EVENT_AFTER_UPDATE, () => {
this._sourceNode.start(0, this._offset);
this._eventTarget.emit('started');
this._state = PlayingState.PLAYING;
});
/* still not supported by all platforms *
this._sourceNode.onended = this._on_ended;
/* doing it manually for now */
@@ -96,7 +97,8 @@ export class AudioPlayerWeb extends AudioPlayer {
cc.game.canvas.removeEventListener('mouseup', this._on_gesture);
});
};
if (this._context.state !== 'running') {
// Chrome41/Firefox40 below don't have resume
if (this._context.state !== 'running' && this._context.resume) {
cc.game.canvas.addEventListener('touchend', this._on_gesture);
cc.game.canvas.addEventListener('mouseup', this._on_gesture);
}
+7 -7
View File
@@ -48,6 +48,10 @@ export class AudioPlayerWX extends AudioPlayer {
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;
@@ -81,9 +85,6 @@ export class AudioPlayerWX extends AudioPlayer {
}
});
this._audio.onError((res: any) => console.error(res.errMsg));
/* handle hide & show */
wx.onAudioInterruptionBegin(this._onHide);
wx.onAudioInterruptionEnd(this._onShow);
}
public play () {
@@ -107,11 +108,10 @@ export class AudioPlayerWX extends AudioPlayer {
same time so here we fall back to re-start style approach */
if (!this._audio) { return; }
this._offset = 0;
this._audio.seek(0);
this._audio.volume = volume;
if (this._oneShoting) { return; }
this._audio.loop = false;
this._oneShoting = true;
this._audio.stop();
this._audio.loop = false;
this._audio.volume = volume;
this._audio.play();
}
+22 -4
View File
@@ -60,7 +60,10 @@ export class AudioSourceComponent extends Component {
* @zh
* 设定要播放的音频。
*/
@property({ type: AudioClip })
@property({
type: AudioClip,
tooltip:'设定要播放的音频',
})
set clip (val) {
this._clip = val;
this._syncStates();
@@ -75,7 +78,9 @@ export class AudioSourceComponent extends Component {
* @zh
* 是否循环播放音频?
*/
@property
@property({
tooltip:'是否循环播放音频',
})
set loop (val) {
this._loop = val;
if (this._clip) { this._clip.setLoop(val); }
@@ -95,7 +100,9 @@ export class AudioSourceComponent extends Component {
* 请注意,根据最新的自动播放策略,现在大部分时候,自动播放只会在第一次收到用户输入后生效。 <br>
* 参考:https://www.chromium.org/audio-video/autoplay
*/
@property
@property({
tooltip:'是否启用自动播放',
})
set playOnAwake (val) {
this._playOnAwake = val;
}
@@ -111,7 +118,10 @@ export class AudioSourceComponent extends Component {
*
* 请注意,在某些平台上,音量控制可能不起效。<br>
*/
@property
@property({
range:[0.0,1.0],
tooltip:'音频的音量(大小范围为 0.0 到 1.0 )\n请注意,在某些平台上,音量控制可能不起效'
})
set volume (val) {
if (isNaN(val)) { console.warn('illegal audio volume!'); return; }
val = clamp(val, 0, 1);
@@ -132,6 +142,14 @@ export class AudioSourceComponent extends Component {
if (this._playOnAwake) { this.play(); }
}
public onDisable () {
this.pause();
}
public onDestroy () {
this.stop();
}
/**
* @en
* Plays the clip
File diff suppressed because one or more lines are too long
+8 -2
View File
@@ -4,7 +4,7 @@ import { SpriteFrame } from '../../assets/sprite-frame';
import { Texture2D } from '../../assets/texture-2d';
import { TextureCube } from '../../assets/texture-cube';
import { GFXDevice } from '../../gfx/device';
import { selectJointsMediumType } from '../../renderer/models/joints-texture-utils';
import { selectJointsMediumType } from '../../renderer/models/skeletal-animation-utils';
import effects from './effects';
class BuiltinResMgr {
@@ -171,9 +171,15 @@ class BuiltinResMgr {
// sprite material
const spriteColorMtl = new cc.Material();
spriteColorMtl._uuid = 'ui-sprite-material';
spriteColorMtl.initialize({ defines: { USE_TEXTURE: true }, effectName: 'builtin-sprite' });
spriteColorMtl.initialize({ defines: { USE_TEXTURE: true, IS_GRAY: false }, effectName: 'builtin-sprite' });
resources[spriteColorMtl._uuid] = spriteColorMtl;
// sprite gray material
const spriteGrayMtl = new cc.Material();
spriteGrayMtl._uuid = 'ui-sprite-gray-material';
spriteGrayMtl.initialize({ defines: { USE_TEXTURE: true, IS_GRAY: true }, effectName: 'builtin-sprite' });
resources[spriteGrayMtl._uuid] = spriteGrayMtl;
// default particle material
const defaultParticleMtl = new cc.Material();
defaultParticleMtl._uuid = 'default-particle-material';
@@ -98,11 +98,19 @@ export class SkinningModelUnit {
@menu('Components/BatchedSkinningModel')
export class BatchedSkinningModelComponent extends SkinningModelComponent {
@property
@property({
tooltip: '合图生成的最终图集的边长',
})
public atlasSize: number = 1024;
@property({ type: [CCString] })
@property({
type: [CCString],
tooltip: '材质中真正参与合图的贴图属性,不参与的属性统一使用第一个 unit 的贴图',
})
public batchableTextureNames: string[] = [];
@property({ type: [SkinningModelUnit] })
@property({
type: [SkinningModelUnit],
tooltip: '合批前的子蒙皮模型数组,最主要的数据来源',
})
public units: SkinningModelUnit[] = [];
private _textures: Record<string, Texture2D> = {};
@@ -143,6 +151,11 @@ export class BatchedSkinningModelComponent extends SkinningModelComponent {
super.onDestroy();
}
public _onMaterialModified (idx: number, material: Material | null) {
this.cookMaterials();
super._onMaterialModified(idx, this.getMaterial(idx));
}
public cook () {
this.cookMaterials();
this.cookSkeletons();
+31 -9
View File
@@ -117,6 +117,7 @@ export class CameraComponent extends Component {
*/
@property({
type: ProjectionType,
tooltip:'相机的投影类型',
})
get projection () {
return this._projection;
@@ -131,7 +132,9 @@ export class CameraComponent extends Component {
* @en The priority of the camera, it cannot be modified at runtime, instead, it should be set in editor.
* @zh 相机的优先级顺序,只能在编辑器中设置,动态设置无效。
*/
@property
@property({
tooltip:'相机的优先级顺序,只能在编辑器中设置,动态设置无效',
})
get priority () {
return this._priority;
}
@@ -147,7 +150,9 @@ export class CameraComponent extends Component {
* @en The camera field of view
* @zh 相机的视角大小。
*/
@property
@property({
tooltip:'相机的视角大小',
})
get fov () {
return this._fov;
}
@@ -161,7 +166,9 @@ export class CameraComponent extends Component {
* @en The camera height when in orthogonal mode
* @zh 正交模式下的相机视角大小。
*/
@property
@property({
tooltip:'正交模式下的相机视角大小',
})
get orthoHeight () {
return this._orthoHeight;
}
@@ -175,7 +182,9 @@ export class CameraComponent extends Component {
* @en The near clipping distance of the camera
* @zh 相机的近平面。
*/
@property
@property({
tooltip:'相机的近平面',
})
get near () {
return this._near;
}
@@ -189,7 +198,9 @@ export class CameraComponent extends Component {
* @en The far clipping distance of the camera
* @zh 相机的远平面。
*/
@property
@property({
tooltip:'相机的远平面',
})
get far () {
return this._far;
}
@@ -203,7 +214,9 @@ export class CameraComponent extends Component {
* @en The color clearing value of the camera
* @zh 相机的颜色缓冲默认值。
*/
@property
@property({
tooltip:'相机的颜色缓冲默认值',
})
// @constget
get color (): Readonly<Color> {
return this._color;
@@ -223,7 +236,9 @@ export class CameraComponent extends Component {
* @en The depth clearing value of the camera
* @zh 相机的深度缓冲默认值。
*/
@property
@property({
tooltip:'相机的深度缓冲默认值',
})
get depth () {
return this._depth;
}
@@ -237,7 +252,9 @@ export class CameraComponent extends Component {
* @en The stencil clearing value of the camera
* @zh 相机的模板缓冲默认值。
*/
@property
@property({
tooltip:'相机的模板缓冲默认值',
})
get stencil () {
return this._stencil;
}
@@ -253,6 +270,7 @@ export class CameraComponent extends Component {
*/
@property({
type: CameraClearFlag,
tooltip:'相机的缓冲清除标志位',
})
get clearFlags () {
return this._clearFlags;
@@ -267,7 +285,9 @@ export class CameraComponent extends Component {
* @en The screen viewport of the camera wrt. sceen size
* @zh 相机相对屏幕的 viewport。
*/
@property
@property({
tooltip:'相机相对屏幕的 viewport',
})
get rect () {
return this._rect;
}
@@ -297,6 +317,7 @@ export class CameraComponent extends Component {
*/
@property({
type: Layers.BitMask,
tooltip:'设置摄像机可见掩码,与 Component 中的 visibility 同时使用,用于过滤摄像机不需要渲染的物体',
})
get visibility () {
return this._visibility;
@@ -314,6 +335,7 @@ export class CameraComponent extends Component {
*/
@property({
type: RenderTexture,
tooltip:'设置摄像机 RenderTexture',
})
get targetTexture () {
return this._targetTexture;
@@ -34,7 +34,7 @@ import { RenderScene } from '../../renderer/scene/render-scene';
import { LightComponent } from './light-component';
@ccclass('cc.DirectionalLightComponent')
@menu('Components/DirectionalLight')
@menu('Light/DirectionalLight')
@executeInEditMode
export class DirectionalLightComponent extends LightComponent {
@@ -50,7 +50,10 @@ export class DirectionalLightComponent extends LightComponent {
* @zh
* 光源强度。
*/
@property({ unit: 'lx' })
@property({
unit: 'lx',
tooltip:'光源强度'
})
get illuminance () {
return this._illuminance;
}
+7 -2
View File
@@ -61,7 +61,9 @@ export class LightComponent extends Component {
* @zh
* 光源颜色。
*/
@property
@property({
tooltip:'光源颜色',
})
// @constget
get color (): Readonly<Color> {
return this._color;
@@ -81,7 +83,9 @@ export class LightComponent extends Component {
* @zh
* 是否启用光源色温。
*/
@property
@property({
tooltip:'是否启用光源色温'
})
get useColorTemperature () {
return this._useColorTemperature;
}
@@ -99,6 +103,7 @@ export class LightComponent extends Component {
@property({
slide: true,
range: [1000, 15000, 1],
tooltip:'光源色温'
})
get colorTemperature () {
return this._colorTemperature;
+24 -39
View File
@@ -66,6 +66,7 @@ export class ModelComponent extends RenderableComponent {
*/
@property({
type: Mesh,
tooltip: '模型网格',
})
get mesh () {
return this._mesh;
@@ -84,6 +85,7 @@ export class ModelComponent extends RenderableComponent {
*/
@property({
type: ModelShadowCastingMode,
tooltip: '投射阴影方式',
})
get shadowCastingMode () {
return this._shadowCastingMode;
@@ -115,37 +117,25 @@ export class ModelComponent extends RenderableComponent {
/**
* @zh 是否启用动态合批?
*/
@property
@property({
tooltip: '是否启用动态合批',
})
set enableDynamicBatching (enable: boolean) {
if (this._enableDynamicBatching === enable) { return; }
this._enableDynamicBatching = enable;
if (this._mesh) {
if (enable) {
this._mesh.createFlatBuffers();
} else {
this._mesh.destroyFlatBuffers();
}
if (enable) { this._mesh.createFlatBuffers(); }
else { this._mesh.destroyFlatBuffers(); }
}
if (this._model) {
this._model.isDynamicBatching = enable;
if (this._model.isDynamicBatching) {
for (let i = 0; i < this._model.subModels.length; ++i) {
const subModel = this._model.subModels[i];
for (let p = 0; p < subModel.passes.length; ++p) {
const pass = subModel.passes[p];
if (!pass.batchedBuffer) {
pass.createBatchedBuffer();
}
}
}
} else {
for (let i = 0; i < this._model.subModels.length; ++i) {
const subModel = this._model.subModels[i];
for (let p = 0; p < subModel.passes.length; ++p) {
const pass = subModel.passes[p];
if (pass.batchedBuffer) {
pass.clearBatchedBuffer();
}
}
this._model.onPipelineChange(); // update material
for (let i = 0; i < this._model.subModels.length; ++i) {
const subModel = this._model.subModels[i];
for (let p = 0; p < subModel.passes.length; ++p) {
const pass = subModel.passes[p];
if (enable) { pass.createBatchedBuffer(); }
else { pass.clearBatchedBuffer(); }
}
}
}
@@ -196,14 +186,11 @@ export class ModelComponent extends RenderableComponent {
if (this._model) {
this._model.scene.destroyModel(this._model);
this._model = null;
this._models.length = 0;
}
}
public _getModel (): Model | null {
return this._model;
}
public recreateModel () {
public _changeSceneInModel () {
if (this.isValid) {
if (this._model) {
this._model.destroy();
@@ -219,19 +206,14 @@ export class ModelComponent extends RenderableComponent {
return;
}
if (this._model && this._model.inited) {
this._model.destroy();
} else {
this._createModel();
}
this._model!.createBoundingShape(this._mesh.minPosition, this._mesh.maxPosition);
this._createModel();
this._updateModelParams();
if (this._model) {
this._model.createBoundingShape(this._mesh.minPosition, this._mesh.maxPosition);
this._model.enabled = true;
this._model.isDynamicBatching = this._enableDynamicBatching;
if (this._enableDynamicBatching) {
if (!this._mesh.hasFlatBuffers) {
this._mesh.createFlatBuffers();
@@ -246,15 +228,17 @@ 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.visFlags = this.visibility;
this._models.length = 0;
this._models.push(this._model);
}
protected _getModelConstructor () {
@@ -266,6 +250,7 @@ export class ModelComponent extends RenderableComponent {
return;
}
this.node.hasChangedFlags = this._model.transform.hasChangedFlags = TransformDirtyBit.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) {
const material = this.getSharedMaterial(i);
@@ -12,12 +12,17 @@ const { ccclass, property } = _decorator;
@ccclass('cc.RenderableComponent')
export class RenderableComponent extends Component {
@property({ type: [Material] })
@property({
type: [Material],
tooltip: '材质',
})
protected _materials: Array<Material | null> = [];
@property
protected _visFlags = Layers.Enum.NONE;
protected _models: Model[] = [];
constructor () {
super();
}
@@ -25,6 +30,7 @@ export class RenderableComponent extends Component {
@property({
type: Material,
displayName: 'Materials',
tooltip: '源材质',
})
get sharedMaterials () {
// if we don't create an array copy, the editor will modify the original array directly.
@@ -123,11 +129,11 @@ export class RenderableComponent extends Component {
}
}
public _getModel (): Model | null {
return null;
public _collectModels (): Model[] {
return this._models;
}
public recreateModel () {
public _changeSceneInModel () {
}
@@ -31,8 +31,6 @@ import { AnimationClip } from '../../animation';
import { Material } from '../../assets/material';
import { Skeleton } from '../../assets/skeleton';
import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../data/class-decorator';
import { GFXDevice } from '../../gfx/device';
import { selectJointsMediumType } from '../../renderer/models/joints-texture-utils';
import { SkinningModel } from '../../renderer/models/skinning-model';
import { Node } from '../../scene-graph/node';
import { INode } from '../../utils/interfaces';
@@ -55,11 +53,15 @@ export class SkinningModelComponent extends ModelComponent {
@property(Node)
protected _skinningRoot: INode | null = null;
protected _clip: AnimationClip | null = null;
/**
* @en The bone nodes
* @zh 骨骼节点。
* @en The skeleton resource
* @zh 骨骼资源。
*/
@property({ type: Skeleton })
@property({
type: Skeleton,
})
get skeleton () {
return this._skeleton;
}
@@ -72,7 +74,9 @@ export class SkinningModelComponent extends ModelComponent {
/**
* 骨骼根节点的引用。
*/
@property({ type: Node })
@property({
type: Node,
})
get skinningRoot (): INode | null {
return this._skinningRoot;
}
@@ -87,6 +91,7 @@ export class SkinningModelComponent extends ModelComponent {
}
public uploadAnimation (clip: AnimationClip | null) {
this._clip = clip;
if (this._model) { (this._model as SkinningModel).uploadAnimation(clip); }
}
@@ -96,14 +101,6 @@ export class SkinningModelComponent extends ModelComponent {
super._updateModelParams();
}
protected _onMaterialModified (index: number, material: Material | null) {
const device: GFXDevice = cc.director.root!.device;
const type = selectJointsMediumType(device);
const mat = this.getMaterial(index) || this._getBuiltinMaterial();
mat.recompileShaders({ CC_USE_SKINNING: type });
super._onMaterialModified(index, mat);
}
protected _getModelConstructor () {
return SkinningModel;
}
@@ -114,7 +111,10 @@ export class SkinningModelComponent extends ModelComponent {
}
private _update () {
if (this._model) { (this._model as SkinningModel).bindSkeleton(this._skeleton, this._skinningRoot); }
this._materials.forEach((material, index) => material && this._onMaterialModified(index, material));
if (this._model) {
const model = (this._model as SkinningModel);
model.bindSkeleton(this._skeleton, this._skinningRoot, this._mesh);
model.uploadAnimation(this._clip);
}
}
}
@@ -33,7 +33,7 @@ import { SphereLight } from '../../renderer/scene/sphere-light';
import { LightComponent, PhotometricTerm } from './light-component';
@ccclass('cc.SphereLightComponent')
@menu('Components/SphereLight')
@menu('Light/SphereLight')
@executeInEditMode
export class SphereLightComponent extends LightComponent {
@@ -52,7 +52,10 @@ export class SphereLightComponent extends LightComponent {
/**
* 光通量。
*/
@property({ unit: 'lm' })
@property({
unit: 'lm',
tooltip:'光通量',
})
get luminousPower () {
return this._luminance * nt2lm(this._size);
}
@@ -64,7 +67,10 @@ export class SphereLightComponent extends LightComponent {
/**
* 亮度。
*/
@property({ unit: 'cd/m²' })
@property({
unit: 'cd/m²',
tooltip:'亮度',
})
get luminance () {
return this._luminance;
}
@@ -76,7 +82,10 @@ export class SphereLightComponent extends LightComponent {
/**
* 指定光通量或亮度。
*/
@property({ type: PhotometricTerm })
@property({
type: PhotometricTerm,
tooltip:'指定光通量或亮度',
})
get term () {
return this._term;
}
@@ -90,7 +99,9 @@ export class SphereLightComponent extends LightComponent {
* @zh
* 针对聚光灯和点光源设置光源大小。
*/
@property
@property({
tooltip:'针对聚光灯和点光源设置光源大小'
})
get size () {
return this._size;
}
@@ -105,7 +116,9 @@ export class SphereLightComponent extends LightComponent {
* @zh
* 针对聚光灯和点光源设置光源范围。
*/
@property
@property({
tooltip:'针对聚光灯和点光源设置光源范围',
})
get range () {
return this._range;
}
@@ -35,7 +35,7 @@ import { SpotLight } from '../../renderer/scene/spot-light';
import { LightComponent, PhotometricTerm } from './light-component';
@ccclass('cc.SpotLightComponent')
@menu('Components/SpotLight')
@menu('Light/SpotLight')
@executeInEditMode
export class SpotLightComponent extends LightComponent {
@@ -56,7 +56,10 @@ export class SpotLightComponent extends LightComponent {
/**
* 光通量。
*/
@property({ unit: 'lm' })
@property({
unit: 'lm',
tooltip:'光通量',
})
get luminousPower () {
return this._luminance * nt2lm(this._size);
}
@@ -68,7 +71,10 @@ export class SpotLightComponent extends LightComponent {
/**
* 亮度。
*/
@property({ unit: 'cd/m²' })
@property({
unit: 'cd/m²',
tooltip:'亮度',
})
get luminance () {
return this._luminance;
}
@@ -80,7 +86,10 @@ export class SpotLightComponent extends LightComponent {
/**
* 指定光通量或亮度。
*/
@property({ type: PhotometricTerm })
@property({
type: PhotometricTerm,
tooltip:'指定光通量或亮度',
})
get term () {
return this._term;
}
@@ -94,7 +103,9 @@ export class SpotLightComponent extends LightComponent {
* @zh
* 针对聚光灯和点光源设置光源大小。
*/
@property
@property({
tooltip:'针对聚光灯和点光源设置光源大小',
})
get size () {
return this._size;
}
@@ -109,7 +120,9 @@ export class SpotLightComponent extends LightComponent {
* @zh
* 针对聚光灯和点光源设置光源范围。
*/
@property
@property({
tooltip:'针对聚光灯和点光源设置光源范围',
})
get range () {
return this._range;
}
@@ -127,6 +140,7 @@ export class SpotLightComponent extends LightComponent {
@property({
slide: true,
range: [2, 180, 1],
tooltip:'聚光灯锥角',
})
get spotAngle () {
return this._spotAngle;
+1 -152
View File
@@ -1,16 +1,10 @@
import { GFXAttributeName, GFXFormat, GFXFormatInfos, GFXFormatType, GFXPrimitiveMode, IGFXFormatInfo } from '../../gfx/define';
export { find } from '../../scene-graph/find';
import { SkelAnimDataHub } from '../../animation/skeletal-animation-data-hub';
import { Mesh } from '../../assets/mesh';
import { Skeleton } from '../../assets/skeleton';
import { aabb } from '../../geom-utils';
import { IGFXAttribute } from '../../gfx/input-assembler';
import { Mat4, Vec3 } from '../../math';
import { Vec3 } from '../../math';
import { IGeometry } from '../../primitive/define';
import { JointsAnimationInfo } from '../../renderer/models/skinning-model';
import { INode } from '../../utils/interfaces';
import { SkinningModelComponent } from '../framework';
import { BufferBlob } from './buffer-blob';
/**
@@ -343,148 +337,3 @@ export function mapBuffer (
}
return out;
}
// get the lowest common ancestor
const _path: INode[] = [];
export const LCA = (a: INode, b: INode) => {
if (a === b) { return a; }
let cur: INode | null = b;
_path.length = 0;
while (cur) { _path.push(cur); cur = cur.parent; }
cur = a;
while (cur) {
if (_path.find((n) => n === cur)) { return cur; }
cur = cur.parent;
}
return null;
};
const v3_2 = new Vec3();
function calculateBoneSpaceBounds (mesh: Mesh, skeleton: Skeleton) {
const result = new Array< { max: Vec3, min: Vec3, hasValue: boolean } >(skeleton.joints.length);
for (let i = 0; i < result.length; ++i) {
result[i] = {
hasValue: false,
min: new Vec3(Infinity, Infinity, Infinity),
max: new Vec3(-Infinity, -Infinity, -Infinity),
};
}
for (let iPrimitive = 0; iPrimitive < mesh.struct.primitives.length; ++iPrimitive) {
const joints = mesh.readAttribute(iPrimitive, GFXAttributeName.ATTR_JOINTS);
if (!joints) {
continue;
}
const weights = mesh.readAttribute(iPrimitive, GFXAttributeName.ATTR_WEIGHTS);
if (!weights) {
continue;
}
const positions = mesh.readAttribute(iPrimitive, GFXAttributeName.ATTR_POSITION);
if (!positions) {
continue;
}
const vertexCount = Math.min(joints.length / 4, weights.length / 4, positions.length / 3);
for (let iVertex = 0; iVertex < vertexCount; ++iVertex) {
Vec3.set(v3_1, positions[3 * iVertex + 0], positions[3 * iVertex + 1], positions[3 * iVertex + 2]);
for (let i = 0; i < 4; ++i) {
const weight = weights[4 * iVertex + i];
if (weight === 0) {
continue;
}
const refJointIndex = joints[4 * iVertex + i];
if (refJointIndex >= skeleton.joints.length) {
continue;
}
if (skeleton.bindposes) { Vec3.transformMat4(v3_2, v3_1, skeleton.bindposes[refJointIndex]); }
else { Vec3.copy(v3_2, v3_1); }
const jointBounds = result[refJointIndex];
jointBounds.hasValue = true;
Vec3.min(jointBounds.min, jointBounds.min, v3_2);
Vec3.max(jointBounds.max, jointBounds.max, v3_2);
}
}
}
return result.map((bounds) => bounds.hasValue ? aabb.fromPoints(new aabb(), bounds.min, bounds.max) : null);
}
interface ICachedBoneSpaceBounds {
bounds: Array<aabb | null>;
referenceCount: number;
}
class BoneSpaceBoundsManager {
private _cached = new Map<Mesh, Map<Skeleton, ICachedBoneSpaceBounds>>();
public use (mesh: Mesh, skeleton: Skeleton) {
let bucket = this._cached.get(mesh);
if (!bucket) {
bucket = new Map();
this._cached.set(mesh, bucket);
}
let cached = bucket.get(skeleton);
if (!cached) {
cached = {
bounds: calculateBoneSpaceBounds(mesh, skeleton),
referenceCount: 0,
};
bucket.set(skeleton, cached);
}
++cached.referenceCount;
return cached.bounds;
}
public unuse (mesh: Mesh, skeleton: Skeleton) {
const bucket = this._cached.get(mesh);
if (bucket) {
const cached = bucket.get(skeleton);
if (cached) {
--cached.referenceCount;
if (cached.referenceCount === 0) {
bucket.delete(skeleton);
}
}
if (bucket.size === 0) {
this._cached.delete(mesh);
}
}
}
}
const boneSpaceBoundsManager = new BoneSpaceBoundsManager();
const m4_1 = new Mat4();
const m4_2 = new Mat4();
const ab_1 = new aabb();
const v3_3 = new Vec3();
const v3_4 = new Vec3();
export function calculateSkinnedBounds (out: aabb, comp: SkinningModelComponent) {
if (!comp.model || !comp.mesh) { return; }
const skeleton = comp.skeleton;
const root = comp.skinningRoot;
const clip = comp.model.uploadedAnim;
const animInfo = root && JointsAnimationInfo.get(root.uuid);
if (!skeleton || !root || !clip || !animInfo) {
if (!comp.model.worldBounds) { return; }
aabb.copy(out, comp.model.worldBounds);
return true;
}
Vec3.set(v3_3, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY, Number.POSITIVE_INFINITY);
Vec3.set(v3_4, Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY, Number.NEGATIVE_INFINITY);
root.getWorldMatrix(m4_1);
const boundList = boneSpaceBoundsManager.use(comp.mesh, skeleton);
const len = skeleton.joints.length;
const data = SkelAnimDataHub.getOrExtract(clip);
const fid = animInfo.data[1];
for (let i = 0; i < len; ++i) {
const bounds = boundList[i];
const nodeData = data[skeleton.joints[i]];
if (!bounds || !nodeData || !nodeData.props) { continue; }
const matrix = nodeData.props.worldMatrix.values[fid];
Mat4.multiply(m4_2, m4_1, matrix);
aabb.transform(ab_1, bounds, m4_2);
ab_1.getBoundary(v3_1, v3_2);
Vec3.min(v3_3, v3_3, v3_1);
Vec3.max(v3_4, v3_4, v3_2);
}
aabb.fromPoints(out, v3_3, v3_4);
return true;
}
+9 -1
View File
@@ -6,13 +6,15 @@
import { Asset } from '../assets/asset';
import { SpriteFrame } from '../assets/sprite-frame';
import { ccclass, property } from '../data/class-decorator';
import { CompactValueTypeArray } from '../data/utils/compact-value-type-array';
import { errorID } from '../platform/debug';
import { DataPoolManager } from '../renderer/data-pool-manager';
import binarySearchEpsilon from '../utils/binary-search';
import { murmurhash2_32_gc } from '../utils/murmurhash2_gc';
import { AnimCurve, CurveValueAdapter, IPropertyCurveData, RatioSampler } from './animation-curve';
import { SkelAnimDataHub } from './skeletal-animation-data-hub';
import { ComponentModifier, HierachyModifier, TargetModifier } from './target-modifier';
import { WrapMode as AnimationWrapMode } from './types';
import { CompactValueTypeArray } from '../data/utils/compact-value-type-array';
export interface IObjectCurveData {
[propertyName: string]: IPropertyCurveData;
@@ -314,6 +316,12 @@ export class AnimationClip extends Asset {
return this.events.length !== 0;
}
public destroy () {
(cc.director.root.dataPoolManager as DataPoolManager).releaseAnimationClip(this);
SkelAnimDataHub.destroy(this);
return super.destroy();
}
protected _createPropertyCurves () {
this._ratioSamplers = this._keys.map(
(keys) => new RatioSampler(
+11 -3
View File
@@ -97,7 +97,10 @@ export class AnimationComponent extends Component implements IEventTarget {
* 获取此动画组件的自有动画剪辑。
* 动画组件开始运行时会为每个自有动画剪辑创建动画状态。
*/
@property({ type: [AnimationClip] })
@property({
type: [AnimationClip],
tooltip:'此动画组件的自有动画剪辑',
})
get clips () {
return this._clips;
}
@@ -137,7 +140,10 @@ export class AnimationComponent extends Component implements IEventTarget {
* 获取默认动画剪辑。
* @see [[playOnLoad]]
*/
@property({ type: AnimationClip })
@property({
type: AnimationClip,
tooltip:'默认动画剪辑',
})
get defaultClip () {
return this._defaultClip;
}
@@ -162,7 +168,9 @@ export class AnimationComponent extends Component implements IEventTarget {
/**
* 是否在动画组件开始运行时自动播放默认动画剪辑。
*/
@property
@property({
tooltip:'是否在动画组件开始运行时自动播放默认动画剪辑',
})
public playOnLoad = false;
public _callbackTable: ICallbackTable = createMap(true);
@@ -8,7 +8,8 @@ import { SpriteFrame } from '../../assets/sprite-frame';
import { TextureBase } from '../../assets/texture-base';
import { ccclass, property } from '../../data/class-decorator';
import { GFXBindingType } from '../../gfx/define';
import { _type2default, Pass } from '../../renderer/core/pass';
import { Pass } from '../../renderer/core/pass';
import { type2default } from '../../renderer/core/pass-utils';
import { samplerLib } from '../../renderer/core/sampler-lib';
import { CurveValueAdapter } from '../animation-curve';
@@ -44,7 +45,7 @@ export class UniformCurveValueAdapter extends CurveValueAdapter {
} else if (bindingType === GFXBindingType.SAMPLER) {
const binding = Pass.getBindingFromHandle(handle);
const prop = pass.properties[this.uniformName];
const texName = prop && prop.value ? prop.value + '-texture' : _type2default[prop.type];
const texName = prop && prop.value ? prop.value + '-texture' : type2default[prop.type];
let dftTex = builtinResMgr.get<TextureBase>(texName);
if (!dftTex) {
console.warn('illegal texture default value: ' + texName);
@@ -1,178 +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 animation
*/
import { SkinningModelComponent } from '../3d/framework/skinning-model-component';
import { ccclass } from '../data/class-decorator';
import { Mat4 } from '../math';
import { INode } from '../utils/interfaces';
import { AnimationClip, IObjectCurveData, IRuntimeCurve } from './animation-clip';
import { IPropertyCurveData } from './animation-curve';
import { ComponentModifier, HierachyModifier, isCustomTargetModifier, isPropertyModifier } from './target-modifier';
type ConvertedData = Record<string, {
props: Record<string, IPropertyCurveData>;
}>;
/**
* 骨骼动画剪辑。
*/
@ccclass('cc.SkeletalAnimationClip')
export class SkeletalAnimationClip extends AnimationClip {
public originalKeys: number[][] = [];
public convertedData: ConvertedData = {};
protected _converted = false;
public getPropertyCurves (root: INode): ReadonlyArray<IRuntimeCurve> {
// tslint:disable-next-line: no-unused-expression
this.hash; // calculate hash before conversion
if (root.getComponent(cc.SkeletalAnimationComponent)) {
this._convertToSkeletalCurves(root);
} else {
console.warn('skeletal clip in non-skeletal component');
}
return super.getPropertyCurves(root);
}
private _convertToSkeletalCurves (root: INode) {
if (this._converted) { return; }
const convertedData: ConvertedData = {};
this.curves.forEach((curve) => {
if (!curve.valueAdapter &&
isCustomTargetModifier(curve.modifiers[0], HierachyModifier) &&
isPropertyModifier(curve.modifiers[1])) {
const path = (curve.modifiers[0] as HierachyModifier).path;
let cs = convertedData[path];
if (!cs) { cs = convertedData[path] = { props: {} }; }
const property = curve.modifiers[1] as string;
cs.props[property] = curve.data;
}
});
this.convertedData = convertedData; this.curves = [];
// lazy eval the conversion due to memory-heavy ops
// many animation paths may not be actually in-use
for (const path of Object.keys(convertedData)) {
const props = convertedData[path] && convertedData[path].props;
if (!props) { continue; }
Object.defineProperty(props, 'worldMatrix', {
get: () => {
if (!props._worldMatrix) {
const { position, rotation, scale } = props;
// fixed step pre-sample
this._convertToUniformSample(position);
this._convertToUniformSample(rotation);
this._convertToUniformSample(scale);
// transform to world space
this._convertToWorldSpace(path, props);
}
return props._worldMatrix;
},
});
}
const values: number[] = new Array(Math.ceil(this.sample * this._duration / this.speed) + 1);
for (let i = 0; i < values.length; i++) { values[i] = i; }
// create frameID animation
const curves: AnimationClip.Curve[] = [{
modifiers: [
new HierachyModifier(''),
new ComponentModifier('cc.SkeletalAnimationComponent'),
'frameID',
],
data: { keys: 0, values, interpolate: false },
}];
this.curves = curves;
this.originalKeys = this._keys;
this._keys = [values.map((_, i) => i * this.speed / this.sample)];
this._duration = this._keys[0][values.length - 1];
this._converted = true;
if (!root) { return; }
// try eval for the existing skinning models
const comps = root.getComponentsInChildren(SkinningModelComponent);
for (let i = 0; i < comps.length; ++i) {
const comp = comps[i] as SkinningModelComponent;
if (comp.skinningRoot === root && comp.skeleton) {
for (const path of comp.skeleton.joints) {
const data = convertedData[path];
// tslint:disable-next-line: no-unused-expression
data && data.props && data.props.worldMatrix;
}
}
}
}
private _convertToUniformSample (curve: IPropertyCurveData) {
const keys = this.originalKeys[curve.keys]; curve.keys = 0;
const len = this._keys[0].length;
const values: any[] = [];
if (!keys || keys.length === 1) {
for (let i = 0; i < len; i++) {
values[i] = curve.values[0].clone(); // never forget to clone
}
} else {
for (let i = 0, idx = 0; i < len; i++) {
let time = i * this.speed / this.sample;
while (keys[idx] <= time) { idx++; }
if (idx > keys.length - 1) { idx = keys.length - 1; time = keys[idx]; }
else if (idx === 0) { idx = 1; }
const from = curve.values[idx - 1].clone();
from.lerp(curve.values[idx], (time - keys[idx - 1]) / (keys[idx] - keys[idx - 1]));
values[i] = from;
}
}
curve.values = values;
}
private _convertToWorldSpace (path: string, props: IObjectCurveData) {
const oPos = props.position.values;
const oRot = props.rotation.values;
const oScale = props.scale.values;
const matrix = oPos.map(() => new Mat4());
const idx = path.lastIndexOf('/');
let pMatrix: Mat4[] | null = null;
if (idx > 0) {
const name = path.substring(0, idx);
const data = this.convertedData[name];
if (!data || !data.props) { console.warn('no data for parent bone?'); return; }
pMatrix = data.props.worldMatrix.values;
}
// all props should have the same length now
for (let i = 0; i < oPos.length; i++) {
const oT = oPos[i];
const oR = oRot[i];
const oS = oScale[i];
const m = matrix[i];
Mat4.fromRTS(m, oR, oT, oS);
if (pMatrix) { Mat4.multiply(m, pMatrix[i], m); }
}
Object.keys(props).forEach((k) => delete props[k]);
props._worldMatrix = { keys: 0, interpolate: false, values: matrix };
}
}
cc.SkeletalAnimationClip = SkeletalAnimationClip;
@@ -29,7 +29,7 @@
import { ccclass, executeInEditMode, executionOrder, menu, property } from '../data/class-decorator';
import { Mat4 } from '../math';
import { IJointsAnimInfo, JointsAnimationInfo } from '../renderer/models/skinning-model';
import { IAnimInfo, JointsAnimationInfo } from '../renderer/models/skeletal-animation-utils';
import { Node } from '../scene-graph/node';
import { INode } from '../utils/interfaces';
import { AnimationClip } from './animation-clip';
@@ -77,8 +77,12 @@ export class SkeletalAnimationComponent extends AnimationComponent {
@property({ type: [Socket] })
public _sockets: Socket[] = [];
protected _animMgr: JointsAnimationInfo = null!;
@property({ type: [Socket] })
@property({
type: [Socket],
tooltip: 'Joint Sockets',
})
get sockets () {
return this._sockets;
}
@@ -87,25 +91,28 @@ export class SkeletalAnimationComponent extends AnimationComponent {
this.rebuildSocketAnimations();
}
protected _animInfo: IJointsAnimInfo | null = null;
protected _animInfo: IAnimInfo | null = null;
set frameID (fid: number) {
if (!this._animInfo) { return; }
const { data, buffer } = this._animInfo;
data[1] = fid; buffer.update(data);
const info = this._animInfo;
if (!info) { return; }
info.data[1] = fid;
info.dirty = true;
}
get frameID () {
return this._animInfo && this._animInfo.data[1] || 0;
const info = this._animInfo;
return info && info.data[1] || 0;
}
public onLoad () {
super.onLoad();
this._animInfo = JointsAnimationInfo.create(this.node.uuid);
this._animMgr = cc.director.root.dataPoolManager.jointsAnimationInfo;
this._animInfo = this._animMgr.create(this.node.uuid);
}
public onDestroy () {
if (this._animInfo) {
JointsAnimationInfo.destroy(this.node.uuid);
this._animMgr.destroy(this.node.uuid);
this._animInfo = null;
}
super.onDestroy();
@@ -42,13 +42,17 @@ type ConvertedData = Record<string, {
*/
export class SkelAnimDataHub {
public static pool = new Map<AnimationClip, ConvertedData>();
public static getOrExtract (clip: AnimationClip) {
let data = SkelAnimDataHub.pool.get(clip);
if (!data) { data = convertToSkeletalCurves(clip); SkelAnimDataHub.pool.set(clip, data); }
return data;
}
public static destroy (clip: AnimationClip) {
SkelAnimDataHub.pool.delete(clip);
}
protected static pool = new Map<AnimationClip, ConvertedData>();
}
function convertToSkeletalCurves (clip: AnimationClip) {
@@ -58,7 +58,7 @@ export class SkeletalAnimationState extends AnimationState {
super.onPlay();
const comps = this._targetNode!.getComponentsInChildren(SkinningModelComponent);
for (let i = 0; i < comps.length; ++i) {
const comp = comps[i] as SkinningModelComponent;
const comp = comps[i];
if (comp.skinningRoot === this._targetNode) {
comp.uploadAnimation(this.clip);
}
+2 -2
View File
@@ -28,7 +28,7 @@
* @category asset
*/
import { ccclass, property } from '../data/class-decorator';
import { ccclass, property, string } from '../data/class-decorator';
import { Event } from '../event';
import { CallbacksInvoker } from '../event/callbacks-invoker';
import { EventTarget } from '../event/event-target';
@@ -106,7 +106,7 @@ export class Asset extends RawAsset implements IEventTarget {
* 用于本机资产的可序列化URL。供内部使用。
* @default ""
*/
@property(cc.String)
@property
public _native: string = '';
private _file: any = null;
+4 -3
View File
@@ -43,6 +43,7 @@ export interface IPropertyInfo {
samplerHash?: number; // auto-generated from 'sampler'
value?: number[] | string;
}
// Pass instance itself are compliant to IPassStates too
export interface IPassStates {
priority?: number;
primitive?: GFXPrimitiveMode;
@@ -50,9 +51,9 @@ export interface IPassStates {
rasterizerState?: GFXRasterizerState;
depthStencilState?: GFXDepthStencilState;
blendState?: GFXBlendState;
dynamics?: GFXDynamicState[];
dynamicStates?: GFXDynamicState[];
customizations?: string[];
phase?: string;
phase?: string | number;
}
export interface IPassInfo extends IPassStates {
program: string; // auto-generated from 'vert' and 'frag'
@@ -176,7 +177,7 @@ export class EffectAsset extends Asset {
*/
public onLoaded () {
this.shaders.forEach((s) => programLib.define(s));
cc.game.once(cc.Game.EVENT_ENGINE_INITED, this._precompile, this);
if (!CC_EDITOR) { cc.game.once(cc.Game.EVENT_ENGINE_INITED, this._precompile, this); }
EffectAsset.register(this);
}
+4 -6
View File
@@ -314,14 +314,14 @@ export class Material extends Asset {
const len = propsArray.length;
for (let i = 0; i < len; i++) {
const props = propsArray[i];
for (const p of Object.keys(props)) {
for (const p in props) {
if (p === name) { return props[p]; }
}
}
} else {
if (passIdx >= this._props.length) { console.warn(`illegal pass index: ${passIdx}.`); return null; }
const props = this._props[passIdx];
for (const p of Object.keys(props)) {
for (const p in props) {
if (p === name) { return props[p]; }
}
}
@@ -380,9 +380,7 @@ export class Material extends Asset {
this._passes.forEach((pass, i) => {
let props = this._props[pass.idxInTech];
if (!props) { props = this._props[i] = {}; }
for (const p of Object.keys(props)) {
const val = props[p];
if (!val) { continue; }
for (const p in props) {
this._uploadProperty(pass, p, props[p]);
}
});
@@ -428,7 +426,7 @@ export class Material extends Asset {
protected _onPassesChange () {
let str = '';
for (const pass of this._passes) {
str += pass.serializePipelineStates();
str += Pass.getPSOHash(pass);
}
this._hash = murmurhash2_32_gc(str, 666);
if (this._owner) {
+16 -6
View File
@@ -33,7 +33,6 @@ import { BufferBlob } from '../3d/misc/buffer-blob';
import { GFXBuffer } from '../gfx/buffer';
import {
GFXAttributeName,
GFXBufferFlagBit,
GFXBufferUsageBit,
GFXFormat,
GFXFormatInfos,
@@ -43,7 +42,8 @@ import {
} from '../gfx/define';
import { GFXDevice } from '../gfx/device';
import { IGFXAttribute } from '../gfx/input-assembler';
import { Root } from '../root';
import { DataPoolManager } from '../renderer/data-pool-manager';
import { murmurhash2_32_gc } from '../utils/murmurhash2_gc';
import { Asset } from './asset';
import { postLoadMesh } from './utils/mesh-utils';
@@ -84,7 +84,7 @@ export interface IGeometricInfo {
export interface IFlatBuffer {
stride: number;
count: number;
buffer: ArrayBuffer;
buffer: Uint8Array;
}
/**
@@ -336,6 +336,11 @@ export class Mesh extends Asset {
return this._data;
}
get hash () {
if (!this._hash && this._data) { this._hash = murmurhash2_32_gc(this._data, 666); }
return this._hash;
}
/**
* 是否具有平铺的缓冲。
*/
@@ -350,7 +355,10 @@ export class Mesh extends Asset {
};
@property
private _dataLength: number = 0;
private _dataLength = 0;
@property
private _hash = 0;
private _data: Uint8Array | null = null;
private _initialized = false;
@@ -445,6 +453,7 @@ export class Mesh extends Asset {
*/
public destroy () {
this.destroyRenderingMesh();
(cc.director.root.dataPoolManager as DataPoolManager).releaseMesh(this);
return super.destroy();
}
@@ -481,6 +490,7 @@ export class Mesh extends Asset {
this.destroyRenderingMesh();
this._struct = info.struct;
this._data = info.data;
this._hash = 0;
this.loaded = true;
this.emit('load');
}
@@ -995,13 +1005,13 @@ export class Mesh extends Asset {
subMesh.flatBuffers.push({
stride: vbStride,
count: vbCount,
buffer: vbView.buffer,
buffer: vbView,
});
} else {
subMesh.flatBuffers.push({
stride: vbStride,
count: vbCount,
buffer: view.buffer,
buffer: view,
});
}
}
+34 -19
View File
@@ -31,6 +31,8 @@ import { ccclass, property } from '../../core/data/class-decorator';
import { CCString } from '../../core/data/utils/attribute';
import { Mat4, Quat, Vec3 } from '../../core/math';
import { murmurhash2_32_gc } from '../../core/utils/murmurhash2_gc';
import { aabb } from '../geom-utils';
import { DataPoolManager } from '../renderer/data-pool-manager';
import { Asset } from './asset';
export interface IBindTRS {
@@ -39,6 +41,11 @@ export interface IBindTRS {
scale: Vec3;
}
const m4_1 = new Mat4();
const v3_1 = new Vec3();
const v3_min = new Vec3();
const v3_max = new Vec3();
/**
* 骨骼资源。
* 骨骼资源记录了每个关节(相对于`SkinningModelComponent.skinningRoot`)的路径以及它的绑定姿势矩阵。
@@ -52,9 +59,8 @@ export class Skeleton extends Asset {
@property([Mat4])
private _bindposes: Mat4[] = [];
private _bindTRS: IBindTRS[] = [];
private _hash = 0;
private _bounds = new aabb();
/**
* 所有关节的绑定姿势矩阵。该数组的长度始终与 `this.joints` 的长度相同。
@@ -65,23 +71,23 @@ export class Skeleton extends Asset {
set bindposes (value) {
this._bindposes = value;
this._bindTRS = value.map((m) => {
const position = new Vec3();
const rotation = new Quat();
const scale = new Vec3();
Mat4.toRTS(m, rotation, position, scale);
return { position, rotation, scale };
});
this._hash = murmurhash2_32_gc(this.bindposes.reduce((acc, cur) => acc +
cur.m00.toPrecision(2) + ' ' + cur.m01.toPrecision(2) + ' ' + cur.m02.toPrecision(2) + ' ' + cur.m03.toPrecision(2) + ' ' +
cur.m04.toPrecision(2) + ' ' + cur.m05.toPrecision(2) + ' ' + cur.m06.toPrecision(2) + ' ' + cur.m07.toPrecision(2) + ' ' +
cur.m08.toPrecision(2) + ' ' + cur.m09.toPrecision(2) + ' ' + cur.m10.toPrecision(2) + ' ' + cur.m11.toPrecision(2) + ' ' +
cur.m12.toPrecision(2) + ' ' + cur.m13.toPrecision(2) + ' ' + cur.m14.toPrecision(2) + ' ' + cur.m15.toPrecision(2) + '\n'
, ''), 666);
}
get bindTRS () {
return this._bindTRS;
let str = '';
Vec3.set(v3_min, Infinity, Infinity, Infinity);
Vec3.set(v3_max, -Infinity, -Infinity, -Infinity);
for (let i = 0; i < value.length; i++) {
const ibm = value[i];
str +=
ibm.m00.toPrecision(2) + ' ' + ibm.m01.toPrecision(2) + ' ' + ibm.m02.toPrecision(2) + ' ' + ibm.m03.toPrecision(2) + ' ' +
ibm.m04.toPrecision(2) + ' ' + ibm.m05.toPrecision(2) + ' ' + ibm.m06.toPrecision(2) + ' ' + ibm.m07.toPrecision(2) + ' ' +
ibm.m08.toPrecision(2) + ' ' + ibm.m09.toPrecision(2) + ' ' + ibm.m10.toPrecision(2) + ' ' + ibm.m11.toPrecision(2) + ' ' +
ibm.m12.toPrecision(2) + ' ' + ibm.m13.toPrecision(2) + ' ' + ibm.m14.toPrecision(2) + ' ' + ibm.m15.toPrecision(2) + '\n';
Mat4.invert(m4_1, ibm);
Vec3.set(v3_1, m4_1.m12, m4_1.m13, m4_1.m14);
Vec3.min(v3_min, v3_min, v3_1);
Vec3.max(v3_max, v3_max, v3_1);
}
this._hash = murmurhash2_32_gc(str, 666);
aabb.fromPoints(this._bounds, v3_min, v3_max);
}
/**
@@ -99,9 +105,18 @@ export class Skeleton extends Asset {
return this._hash;
}
get bounds () {
return this._bounds;
}
public onLoaded () {
this.bindposes = this._bindposes;
}
public destroy () {
(cc.director.root.dataPoolManager as DataPoolManager).releaseSkeleton(this);
return super.destroy();
}
}
cc.Skeleton = Skeleton;
+2 -2
View File
@@ -643,8 +643,8 @@ export class SpriteFrame extends Asset {
uvSliced.length = 0;
if (this._rotated) {
temp_uvs[0].u = (rect.x + rect.height) / atlasWidth;
temp_uvs[1].u = (rect.x + bottomHeight + centerHeight) / atlasWidth;
temp_uvs[2].u = (rect.x + bottomHeight) / atlasWidth;
temp_uvs[1].u = (rect.x + topHeight + centerHeight) / atlasWidth;
temp_uvs[2].u = (rect.x + topHeight) / atlasWidth;
temp_uvs[3].u = (rect.x) / atlasWidth;
temp_uvs[3].v = (rect.y + rect.width) / atlasHeight;
temp_uvs[2].v = (rect.y + leftWidth + centerWidth) / atlasHeight;
+2 -2
View File
@@ -100,7 +100,7 @@ export class TextureBase extends Asset {
protected _wrapR: number = WrapMode.REPEAT;
@property
protected _anisotropy = 16;
protected _anisotropy = 8;
protected _width: number = 0;
protected _height: number = 0;
@@ -192,7 +192,7 @@ export class TextureBase extends Asset {
public setMipFilter (mipFilter: Filter) {
this._mipFilter = mipFilter;
this._samplerInfo[SamplerInfoIndex.mipFilter] = mipFilter;
this._samplerInfo[SamplerInfoIndex.maxLOD] = mipFilter === Filter.NONE ? 0 : 1000; // WebGL2 on some platform need this
this._samplerInfo[SamplerInfoIndex.maxLOD] = mipFilter === Filter.NONE ? 0 : 15; // WebGL2 on some platform need this
this._samplerHash = genSamplerHash(this._samplerInfo);
}
+2 -2
View File
@@ -28,7 +28,7 @@
* @category asset
*/
import {ccclass, property} from '../data/class-decorator';
import {ccclass, property, string} from '../data/class-decorator';
import { Font } from './font';
/**
@@ -45,9 +45,9 @@ export class TTFFont extends Font {
public _fontFamily: any = null;
@property({
type: cc.String,
override: true,
})
@string
get _nativeAsset () {
return this._fontFamily;
}
@@ -74,6 +74,7 @@ const RenderMode = Enum({
export class CanvasComponent extends Component {
@property({
type: CanvasClearFlag,
tooltip:'清理屏幕缓冲标记',
})
get clearFlag () {
return this._clearFlag;
@@ -86,7 +87,9 @@ export class CanvasComponent extends Component {
}
}
@property
@property({
tooltip:'清理颜色缓冲区后的颜色',
})
get color () {
return this._color;
}
@@ -103,6 +106,7 @@ export class CanvasComponent extends Component {
@property({
type: RenderMode,
tooltip:'Canvas 渲染模式,intersperse 下可以指定 Canvas 与场景中的相机的渲染顺序,overlay 下 Canvas 会在所有场景相机渲染完成后渲染。\n注意:启用 intersperse 模式,如果 3D 场景的相机内容显示上要在 Canvas 前面,相机的 clearFlags 也要为 none',
})
get renderMode () {
return this._renderMode;
@@ -121,7 +125,9 @@ export class CanvasComponent extends Component {
*
* @param value - 渲染优先级。
*/
@property()
@property({
tooltip:'相机排序优先级。当 RenderMode 为 intersperse 时,指定与其它相机的渲染顺序,当 RenderMode 为 overlay 时,指定跟其余 Canvas 做排序使用',
})
get priority () {
return this._priority;
}
@@ -138,6 +144,7 @@ export class CanvasComponent extends Component {
*/
@property({
type: RenderTexture,
tooltip:'目标渲染纹理',
})
get targetTexture (){
return this._targetTexture;
@@ -27,11 +27,11 @@
* @category ui
*/
import { Component } from '../component';
import { ccclass, disallowMultiple, executeInEditMode, executionOrder, property } from '../../../core/data/class-decorator';
import { SystemEventType } from '../../../core/platform/event-manager/event-enum';
import { INode } from '../../../core/utils/interfaces';
import { UI } from '../../renderer/ui/ui';
import { Component } from '../component';
import { CanvasComponent } from './canvas-component';
/**
@@ -48,7 +48,9 @@ export class UIComponent extends Component {
* @zh
* 渲染先后顺序,按照广度渲染排列,按同级节点下进行一次排列。
*/
@property
@property({
tooltip:'渲染排序优先级'
})
get priority () {
return this._priority;
}
@@ -67,7 +69,7 @@ export class UIComponent extends Component {
* 查找被渲染相机。
*/
get visibility () {
if(!this._screen){
if (!this._screen){
return -1;
}
@@ -109,13 +111,13 @@ export class UIComponent extends Component {
}
}
public updateAssembler(render: UI) {
public updateAssembler (render: UI) {
}
public postUpdateAssembler(render: UI) {
public postUpdateAssembler (render: UI) {
}
public _setScreen(value: CanvasComponent){
public _setScreen (value: CanvasComponent){
this._followScreen = value;
}
@@ -45,7 +45,6 @@ import { RenderableComponent } from '../../../core/3d/framework/renderable-compo
import { IAssembler, IAssemblerManager } from '../../renderer/ui/base';
import { UIComponent } from './ui-component';
import { UITransformComponent } from './ui-transform-component';
import { director } from '../../director';
// hack
ccenum(GFXBlendFactor);
@@ -66,6 +65,12 @@ export enum InstanceMaterialType {
* 着色器带颜色和贴图属性。
*/
ADDCOLORANDTEXTURE = 1,
/**
* @zh
* 着色器带颜色和贴图属性,并使用灰度模式。
*/
GRAYSCALE = 2,
}
/**
@@ -92,6 +97,7 @@ export class UIRenderComponent extends UIComponent {
@property({
type: GFXBlendFactor,
displayOrder: 0,
tooltip:'原图混合模式',
})
get srcBlendFactor () {
return this._srcBlendFactor;
@@ -119,6 +125,7 @@ export class UIRenderComponent extends UIComponent {
@property({
type: GFXBlendFactor,
displayOrder: 1,
tooltip:'目标混合模式',
})
get dstBlendFactor () {
return this._dstBlendFactor;
@@ -141,6 +148,7 @@ export class UIRenderComponent extends UIComponent {
*/
@property({
displayOrder: 2,
tooltip:'渲染颜色',
})
// @constget
get color (): Readonly<Color> {
@@ -166,6 +174,7 @@ export class UIRenderComponent extends UIComponent {
@property({
type: Material,
displayOrder: 3,
tooltip:'源材质',
})
get sharedMaterial () {
return this._sharedMaterial;
@@ -323,7 +332,7 @@ export class UIRenderComponent extends UIComponent {
}
}
public postUpdateAssembler(render: UI) {
public postUpdateAssembler (render: UI) {
super.postUpdateAssembler(render);
if (this._renderFlag) {
this._postRender(render);
@@ -331,10 +340,10 @@ export class UIRenderComponent extends UIComponent {
}
// 开始提交渲染数据给中转站
protected _render(render: UI) { }
protected _render (render: UI) { }
// 开始提交渲染数据给中转站
protected _postRender(render: UI) { }
protected _postRender (render: UI) { }
// 像组装器更新渲染数据
protected _checkAndUpdateRenderData (){
@@ -403,6 +412,9 @@ export class UIRenderComponent extends UIComponent {
case InstanceMaterialType.ADDCOLORANDTEXTURE:
mat = Material.getInstantiatedMaterial(cc.builtinResMgr.get('ui-sprite-material'), new RenderableComponent(), CC_EDITOR ? true : false);
break;
case InstanceMaterialType.GRAYSCALE:
mat = Material.getInstantiatedMaterial(cc.builtinResMgr.get('ui-sprite-gray-material'), new RenderableComponent(), CC_EDITOR ? true : false);
break;
}
}
@@ -60,6 +60,7 @@ export class UITransformComponent extends Component {
*/
@property({
displayOrder: 0,
tooltip:'内容尺寸',
})
// @constget
get contentSize (): Readonly<Size> {
@@ -138,6 +139,7 @@ export class UITransformComponent extends Component {
*/
@property({
displayOrder: 1,
tooltip:'锚点位置',
})
// @constget
get anchorPoint (): Readonly<Vec2> {
@@ -328,7 +330,7 @@ export class UITransformComponent extends Component {
if (testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h) {
if (listener && listener.mask) {
const mask = listener.mask as ILinstenerMask;
const mask = listener.mask as IListenerMask;
let parent: any = this.node;
// find mask parent, should hit test it
for (let i = 0; parent && i < mask.index; ++i, parent = parent.parent) {
+35 -1
View File
@@ -52,7 +52,7 @@ import * as js from '../utils/js';
import './class';
import { IExposedAttributes } from './utils/attribute-defines';
import { doValidateMethodWithProps_DEV, getFullFormOfProperty } from './utils/preprocess-class';
import { CCString, CCInteger, CCFloat, CCBoolean } from './utils/attribute';
import { CCString, CCInteger, CCFloat, CCBoolean, PrimitiveType } from './utils/attribute';
// caches for class construction
const CACHE_KEY = '__ccclassCache__';
@@ -605,3 +605,37 @@ export function mixins (...constructors: Function[]) {
}
};
}
/**
* 将该属性标记为 cc 整数。
*/
export const integer = type(CCInteger);
/**
* 将该属性标记为 cc 浮点数。
*/
export const float = type(CCFloat);
/**
* 将该属性标记为 cc 布尔值。
*/
export const boolean = type(CCBoolean);
/**
* 将该属性标记为 cc 字符串。
*/
export const string = type(CCString);
/**
* 标记该属性的类型。
* @param type 指定类型。
*/
export function type (type: Function): PropertyDecorator;
export function type<T> (type: PrimitiveType<T>): PropertyDecorator;
export function type<T> (type: PrimitiveType<T> | Function): PropertyDecorator {
return property({
type,
});
}
+5 -3
View File
@@ -1,5 +1,5 @@
/**
* @category gemotry-utils
* @category geometry
*/
import { Mat3, Mat4, Quat, Vec3 } from '../../core/math';
@@ -91,8 +91,10 @@ export default class aabb {
* @returns {aabb} out 接受操作的 aabb。
*/
public static fromPoints (out: aabb, minPos: Vec3, maxPos: Vec3): aabb {
Vec3.multiplyScalar(out.center, Vec3.add(_v3_tmp, minPos, maxPos), 0.5);
Vec3.multiplyScalar(out.halfExtents, Vec3.subtract(_v3_tmp2, maxPos, minPos), 0.5);
Vec3.add(_v3_tmp, maxPos, minPos);
Vec3.subtract(_v3_tmp2, maxPos, minPos);
Vec3.multiplyScalar(out.center, _v3_tmp, 0.5);
Vec3.multiplyScalar(out.halfExtents, _v3_tmp2, 0.5);
return out;
}
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* @category gemotry-utils
* @category geometry
*/
import CCClass from '../../core/data/class';
+8 -1
View File
@@ -2,8 +2,9 @@
* @hidden
*/
import { replaceProperty } from '../utils/deprecated';
import { replaceProperty, removeProperty } from '../utils/deprecated';
import line from './line';
import intersect from './intersect';
replaceProperty(line.prototype, 'line', [
{
@@ -15,3 +16,9 @@ replaceProperty(line.prototype, 'line', [
newName: 'len',
},
]);
removeProperty(intersect, 'intersect', [
{
name: 'line_quad'
}
])
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* @category gemotry-utils
* @category geometry
*/
import { Vec3 } from '../math';
+1 -1
View File
@@ -1,6 +1,6 @@
/**
* 几何工具模块
* @category gemotry-utils
* @category geometry
*/
/**
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* @category gemotry-utils
* @category geometry
*/
import { Mat4, Vec3 } from '../math';
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* @category gemotry-utils
* @category geometry
*/
export { default as enums } from './enums';
+151 -174
View File
@@ -1,6 +1,6 @@
/**
* 几何工具模块
* @category gemotry-utils
* @category geometry
*/
import { Mat3, Vec3 } from '../math';
@@ -40,24 +40,6 @@ const ray_plane = (function () {
};
})();
/**
* line-plane intersect<br/>
* 线段与平面的相交性检测。
* @param {line} line 线段
* @param {plane} plane 平面
* @return {number} 0 或 非 0
*/
const line_plane = (function () {
const ab = new Vec3(0, 0, 0);
return function (line: line, plane: plane): number {
Vec3.subtract(ab, line.e, line.s);
const t = (plane.d - Vec3.dot(line.s, plane.n)) / Vec3.dot(ab, plane.n);
if (t < 0 || t > 1) { return 0; }
return t;
};
})();
// based on http://fileadmin.cs.lth.se/cs/Personal/Tomas_Akenine-Moller/raytri/
/**
* ray-triangle intersect<br/>
@@ -97,160 +79,6 @@ const ray_triangle = (function () {
};
})();
/**
* line-triangle intersect<br/>
* 线段与三角形的相交性检测。
* @param {line} line 线段
* @param {triangle} triangle 三角形
* @param {Vec3} outPt 可选,相交点
* @return {number} 0 或 非 0
*/
const line_triangle = (function () {
const ab = new Vec3(0, 0, 0);
const ac = new Vec3(0, 0, 0);
const qp = new Vec3(0, 0, 0);
const ap = new Vec3(0, 0, 0);
const n = new Vec3(0, 0, 0);
const e = new Vec3(0, 0, 0);
return function (line: line, triangle: triangle, outPt: Vec3): number {
Vec3.subtract(ab, triangle.b, triangle.a);
Vec3.subtract(ac, triangle.c, triangle.a);
Vec3.subtract(qp, line.s, line.e);
Vec3.cross(n, ab, ac);
const det = Vec3.dot(qp, n);
if (det <= 0.0) {
return 0;
}
Vec3.subtract(ap, line.s, triangle.a);
const t = Vec3.dot(ap, n);
if (t < 0 || t > det) {
return 0;
}
Vec3.cross(e, qp, ap);
let v = Vec3.dot(ac, e);
if (v < 0 || v > det) {
return 0;
}
let w = -Vec3.dot(ab, e);
if (w < 0.0 || v + w > det) {
return 0;
}
if (outPt) {
const invDet = 1.0 / det;
v *= invDet;
w *= invDet;
const u = 1.0 - v - w;
// outPt = u*a + v*d + w*c;
Vec3.set(outPt,
triangle.a.x * u + triangle.b.x * v + triangle.c.x * w,
triangle.a.y * u + triangle.b.y * v + triangle.c.y * w,
triangle.a.z * u + triangle.b.z * v + triangle.c.z * w,
);
}
return 1;
};
})();
/**
* line-quad intersect<br/>
* 线段与四边形的相交性检测。
* @param {Vec3} p 线段的一点
* @param {Vec3} q 线段的另一点
* @param {Vec3} a 四边形的 a 点
* @param {Vec3} b 四边形的 b 点
* @param {Vec3} c 四边形的 c 点
* @param {Vec3} d 四边形的 d 点
* @param {Vec3} outPt 可选,相交点
* @return {number} 0 或 非 0
*/
const line_quad = (function () {
const pq = new Vec3(0, 0, 0);
const pa = new Vec3(0, 0, 0);
const pb = new Vec3(0, 0, 0);
const pc = new Vec3(0, 0, 0);
const pd = new Vec3(0, 0, 0);
const m = new Vec3(0, 0, 0);
const tmp = new Vec3(0, 0, 0);
return function (p: Vec3, q: Vec3, a: Vec3, b: Vec3, c: Vec3, d: Vec3, outPt: Vec3): number {
Vec3.subtract(pq, q, p);
Vec3.subtract(pa, a, p);
Vec3.subtract(pb, b, p);
Vec3.subtract(pc, c, p);
// Determine which triangle to test against by testing against diagonal first
Vec3.cross(m, pc, pq);
let v = Vec3.dot(pa, m);
if (v >= 0) {
// Test intersection against triangle abc
let u = -Vec3.dot(pb, m);
if (u < 0) {
return 0;
}
let w = Vec3.dot(Vec3.cross(tmp, pq, pb), pa);
if (w < 0) {
return 0;
}
// outPt = u*a + v*b + w*c;
if (outPt) {
const denom = 1.0 / (u + v + w);
u *= denom;
v *= denom;
w *= denom;
Vec3.set(outPt,
a.x * u + b.x * v + c.x * w,
a.y * u + b.y * v + c.y * w,
a.z * u + b.z * v + c.z * w,
);
}
} else {
// Test intersection against triangle dac
Vec3.subtract(pd, d, p);
let u = Vec3.dot(pd, m);
if (u < 0) {
return 0;
}
let w = Vec3.dot(Vec3.cross(tmp, pq, pa), pd);
if (w < 0) {
return 0;
}
// outPt = u*a + v*d + w*c;
if (outPt) {
v = -v;
const denom = 1.0 / (u + v + w);
u *= denom;
v *= denom;
w *= denom;
Vec3.set(outPt,
a.x * u + d.x * v + c.x * w,
a.y * u + d.y * v + c.y * w,
a.z * u + d.z * v + c.z * w,
);
}
}
return 1;
};
})();
/**
* ray-sphere intersect<br/>
* 射线和球的相交性检测。
@@ -384,6 +212,148 @@ const ray_obb = (function () {
};
})();
/**
* line-plane intersect<br/>
* 线段与平面的相交性检测。
* @param {line} line 线段
* @param {plane} plane 平面
* @return {number} 0 或 非 0
*/
const line_plane = (function () {
const ab = new Vec3(0, 0, 0);
return function (line: line, plane: plane): number {
Vec3.subtract(ab, line.e, line.s);
const t = (plane.d - Vec3.dot(line.s, plane.n)) / Vec3.dot(ab, plane.n);
if (t < 0 || t > 1) { return 0; }
return t;
};
})();
/**
* line-triangle intersect<br/>
* 线段与三角形的相交性检测。
* @param {line} line 线段
* @param {triangle} triangle 三角形
* @param {Vec3} outPt 可选,相交点
* @return {number} 0 或 非 0
*/
const line_triangle = (function () {
const ab = new Vec3(0, 0, 0);
const ac = new Vec3(0, 0, 0);
const qp = new Vec3(0, 0, 0);
const ap = new Vec3(0, 0, 0);
const n = new Vec3(0, 0, 0);
const e = new Vec3(0, 0, 0);
return function (line: line, triangle: triangle, outPt?: Vec3): number {
Vec3.subtract(ab, triangle.b, triangle.a);
Vec3.subtract(ac, triangle.c, triangle.a);
Vec3.subtract(qp, line.s, line.e);
Vec3.cross(n, ab, ac);
const det = Vec3.dot(qp, n);
if (det <= 0.0) {
return 0;
}
Vec3.subtract(ap, line.s, triangle.a);
const t = Vec3.dot(ap, n);
if (t < 0 || t > det) {
return 0;
}
Vec3.cross(e, qp, ap);
let v = Vec3.dot(ac, e);
if (v < 0 || v > det) {
return 0;
}
let w = -Vec3.dot(ab, e);
if (w < 0.0 || v + w > det) {
return 0;
}
if (outPt) {
const invDet = 1.0 / det;
v *= invDet;
w *= invDet;
const u = 1.0 - v - w;
// outPt = u*a + v*d + w*c;
Vec3.set(outPt,
triangle.a.x * u + triangle.b.x * v + triangle.c.x * w,
triangle.a.y * u + triangle.b.y * v + triangle.c.y * w,
triangle.a.z * u + triangle.b.z * v + triangle.c.z * w,
);
}
return 1;
};
})();
const r_t = new ray();
/**
* @zh
* 线段与轴对齐包围盒的相交性检测
* @param line 线段
* @param aabb 轴对齐包围盒
* @return {number} 0 或 非 0
*/
function line_aabb (line: line, aabb: aabb): number {
r_t.o.set(line.s);
Vec3.subtract(r_t.d, line.e, line.s);
r_t.d.normalize();
const min = ray_aabb(r_t, aabb);
const len = line.length();
if (min <= len) {
return min;
} else {
return 0;
}
}
/**
* @zh
* 线段与方向包围盒的相交性检测
* @param line 线段
* @param obb 方向包围盒
* @return {number} 0 或 非 0
*/
function line_obb (line: line, obb: obb): number {
r_t.o.set(line.s);
Vec3.subtract(r_t.d, line.e, line.s);
r_t.d.normalize();
const min = ray_obb(r_t, obb);
const len = line.length();
if (min <= len) {
return min;
} else {
return 0;
}
}
/**
* @zh
* 线段与球的相交性检测
* @param line 线段
* @param sphere 球
* @return {number} 0 或 非 0
*/
function line_sphere (line: line, sphere: sphere): number {
r_t.o.set(line.s);
Vec3.subtract(r_t.d, line.e, line.s);
r_t.d.normalize();
const min = ray_sphere(r_t, sphere);
const len = line.length();
if (min <= len) {
return min;
} else {
return 0;
}
}
/**
* aabb-aabb intersect<br/>
* 轴对齐包围盒和轴对齐包围盒的相交性检测。
@@ -885,9 +855,12 @@ const intersect = {
ray_obb,
ray_plane,
ray_triangle,
line_sphere,
line_aabb,
line_obb,
line_plane,
line_triangle,
line_quad,
sphere_sphere,
sphere_aabb,
@@ -928,6 +901,10 @@ intersect[enums.SHAPE_RAY | enums.SHAPE_AABB] = ray_aabb;
intersect[enums.SHAPE_RAY | enums.SHAPE_OBB] = ray_obb;
intersect[enums.SHAPE_RAY | enums.SHAPE_PLANE] = ray_plane;
intersect[enums.SHAPE_RAY | enums.SHAPE_TRIANGLE] = ray_triangle;
intersect[enums.SHAPE_LINE | enums.SHAPE_SPHERE] = line_sphere;
intersect[enums.SHAPE_LINE | enums.SHAPE_AABB] = line_aabb;
intersect[enums.SHAPE_LINE | enums.SHAPE_OBB] = line_obb;
intersect[enums.SHAPE_LINE | enums.SHAPE_PLANE] = line_plane;
intersect[enums.SHAPE_LINE | enums.SHAPE_TRIANGLE] = line_triangle;
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* @category gemotry-utils
* @category geometry
*/
import { Vec3 } from '../math';
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* @category gemotry-utils
* @category geometry
*/
import { Mat3, Mat4, Quat, Vec3 } from '../math';
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* @category gemotry-utils
* @category geometry
*/
import { Vec3 } from '../math';
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* @category gemotry-utils
* @category geometry
*/
import { Mat4, Vec3, Vec4 } from '../math';
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* @category gemotry-utils
* @category geometry
*/
import { Vec3 } from '../math';
+2 -2
View File
@@ -1,5 +1,5 @@
/**
* @category gemotry-utils
* @category geometry
*/
import { Mat4, Quat, Vec3 } from '../math';
@@ -77,7 +77,7 @@ export default class sphere {
/**
* @en Set the components of a sphere to the given values
* @zh 将球体的属性设置为给定的值。
*
*
* @param {sphere} out 接受操作的 sphere。
* @param cx 形状的相对于原点的 X 坐标。
* @param cy 形状的相对于原点的 Y 坐标。
+1 -1
View File
@@ -1,5 +1,5 @@
/**
* @category gemotry-utils
* @category geometry
*/
import { Vec3 } from '../math';
+1 -1
View File
@@ -14,7 +14,7 @@ import { GFXTextureView } from './texture-view';
*/
export interface IGFXBinding {
binding: number;
type: GFXBindingType;
bindingType: GFXBindingType;
name: string;
}
+27 -4
View File
@@ -169,13 +169,14 @@ export class GFXInputState {
export interface IGFXPipelineStateInfo {
primitive: GFXPrimitiveMode;
shader: GFXShader;
is: GFXInputState;
rs: GFXRasterizerState;
dss: GFXDepthStencilState;
bs: GFXBlendState;
inputState: GFXInputState;
rasterizerState: GFXRasterizerState;
depthStencilState: GFXDepthStencilState;
blendState: GFXBlendState;
dynamicStates?: GFXDynamicState[];
layout: GFXPipelineLayout;
renderPass: GFXRenderPass;
hash: number;
}
/**
@@ -224,6 +225,14 @@ export abstract class GFXPipelineState extends GFXObject {
return this._bs as GFXBlendState;
}
/**
* @zh
* GFX输入状态。
*/
public get inputState (): GFXInputState {
return this._is as GFXInputState;
}
/**
* @zh
* GFX动态状态数组。
@@ -248,6 +257,14 @@ export abstract class GFXPipelineState extends GFXObject {
return this._renderPass as GFXRenderPass;
}
/**
* @zh
* 此管线状态的 hash。
*/
public get hash (): number {
return this._hash;
}
/**
* @zh
* GFX设备。
@@ -308,6 +325,12 @@ export abstract class GFXPipelineState extends GFXObject {
*/
protected _renderPass: GFXRenderPass | null = null;
/**
* @zh
* 此管线状态的 hash。
*/
protected _hash: number = 0;
/**
* 构造函数。
* @param device GFX设备。
+2 -2
View File
@@ -25,7 +25,7 @@ export class WebGLGFXBindingLayout extends GFXBindingLayout {
const binding = info.bindings[i];
this._bindingUnits[i] = {
binding: binding.binding,
type: binding.type,
type: binding.bindingType,
name: binding.name,
buffer: null,
texView: null,
@@ -41,7 +41,7 @@ export class WebGLGFXBindingLayout extends GFXBindingLayout {
const binding = info.bindings[i];
this._gpuBindingLayout.gpuBindings[i] = {
binding: binding.binding,
type: binding.type,
type: binding.bindingType,
name: binding.name,
gpuBuffer: null,
gpuTexView: null,
+1 -1
View File
@@ -128,7 +128,7 @@ export class WebGLGFXBuffer extends GFXBuffer {
} else {
buffSize = (buffer as ArrayBuffer).byteLength;
}
if (this._bufferView) {
if (this._bufferView && buffer !== this._bufferView.buffer) {
const view = new Uint8Array(buffer as ArrayBuffer, 0, size);
this._bufferView.set(view, offset);
}
+3 -2
View File
@@ -349,16 +349,17 @@ export class WebGLGFXCommandBuffer extends GFXCommandBuffer {
this.cmdPackage.cmds.push(WebGLCmd.DRAW);
++this._numDrawCalls;
const indexCount = inputAssembler.indexCount || inputAssembler.vertexCount;
if (this._curGPUPipelineState) {
const glPrimitive = this._curGPUPipelineState.glPrimitive;
switch (glPrimitive) {
case 0x0004: { // WebGLRenderingContext.TRIANGLES
this._numTris += inputAssembler.indexCount / 3 * Math.max(inputAssembler.instanceCount, 1);
this._numTris += indexCount / 3 * Math.max(inputAssembler.instanceCount, 1);
break;
}
case 0x0005: // WebGLRenderingContext.TRIANGLE_STRIP
case 0x0006: { // WebGLRenderingContext.TRIANGLE_FAN
this._numTris += (inputAssembler.indexCount - 2) * Math.max(inputAssembler.instanceCount, 1);
this._numTris += (indexCount - 2) * Math.max(inputAssembler.instanceCount, 1);
break;
}
}
+2 -1
View File
@@ -2207,6 +2207,7 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web
if (device.useVAO) {
const vao = device.OES_vertex_array_object!;
const ia = device.ANGLE_instanced_arrays;
// check vao
let glVAO = gpuInputAssembler.glVAOs.get(gpuShader.glProgram!);
@@ -2244,7 +2245,7 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web
cache.glCurrentAttribLocs[glLoc] = true;
gl.vertexAttribPointer(glLoc, glAttrib.count, glAttrib.glType, glAttrib.isNormalized, glAttrib.stride, attribOffset);
// gl.vertexAttribDivisor(glLoc, glAttrib.isInstanced ? 1 : 0);
if (ia) { ia.vertexAttribDivisorANGLE(glLoc, glAttrib.isInstanced ? 1 : 0); }
}
}
}
+2 -2
View File
@@ -1,3 +1,4 @@
import sys from '../../platform/sys';
import { GFXBindingLayout, IGFXBindingLayoutInfo } from '../binding-layout';
import { GFXBuffer, IGFXBufferInfo } from '../buffer';
import { GFXCommandAllocator, IGFXCommandAllocatorInfo } from '../command-allocator';
@@ -314,7 +315,6 @@ export class WebGLGFXDevice extends GFXDevice {
this._features.fill(false);
// if (cc.sys.platform !== cc.sys.WECHAT_GAME) {
if (this._WEBGL_color_buffer_float) {
this._features[GFXFeature.COLOR_FLOAT] = true;
}
@@ -373,7 +373,7 @@ export class WebGLGFXDevice extends GFXDevice {
this._features[GFXFeature.MSAA] = false;
if (this._OES_vertex_array_object) {
this._useVAO = true;
if (sys.platform !== sys.WECHAT_GAME || sys.os !== sys.OS_IOS) { this._useVAO = true; }
}
console.info('RENDERER: ' + this._renderer);
+8 -7
View File
@@ -39,11 +39,12 @@ export class WebGLGFXPipelineState extends GFXPipelineState {
this._primitive = info.primitive;
this._shader = info.shader;
this._is = info.is;
this._rs = info.rs;
this._dss = info.dss;
this._bs = info.bs;
this._is = info.inputState;
this._rs = info.rasterizerState;
this._dss = info.depthStencilState;
this._bs = info.blendState;
this._dynamicStates = info.dynamicStates || [];
this._hash = info.hash;
this._layout = info.layout;
this._renderPass = info.renderPass;
@@ -51,9 +52,9 @@ export class WebGLGFXPipelineState extends GFXPipelineState {
this._gpuPipelineState = {
glPrimitive: WebGLPrimitives[info.primitive],
gpuShader: (info.shader as WebGLGFXShader).gpuShader,
rs: info.rs,
dss: info.dss,
bs: info.bs,
rs: info.rasterizerState,
dss: info.depthStencilState,
bs: info.blendState,
dynamicStates: (info.dynamicStates !== undefined ? info.dynamicStates : []),
gpuLayout: (info.layout as WebGLGFXPipelineLayout).gpuPipelineLayout,
gpuRenderPass: (info.renderPass as WebGLGFXRenderPass).gpuRenderPass,
@@ -25,7 +25,7 @@ export class WebGL2GFXBindingLayout extends GFXBindingLayout {
const binding = info.bindings[i];
this._bindingUnits[i] = {
binding: binding.binding,
type: binding.type,
type: binding.bindingType,
name: binding.name,
buffer: null,
texView: null,
@@ -41,7 +41,7 @@ export class WebGL2GFXBindingLayout extends GFXBindingLayout {
const binding = info.bindings[i];
this._gpuBindingLayout.gpuBindings[i] = {
binding: binding.binding,
type: binding.type,
type: binding.bindingType,
name: binding.name,
gpuBuffer: null,
gpuTexView: null,
+1 -1
View File
@@ -113,7 +113,7 @@ export class WebGL2GFXBuffer extends GFXBuffer {
} else {
buffSize = (buffer as ArrayBuffer).byteLength;
}
if (this._bufferView) {
if (this._bufferView && buffer !== this._bufferView.buffer) {
const view = new Uint8Array(buffer as ArrayBuffer, 0, size);
this._bufferView.set(view, offset);
}
@@ -348,16 +348,17 @@ export class WebGL2GFXCommandBuffer extends GFXCommandBuffer {
this.cmdPackage.cmds.push(WebGL2Cmd.DRAW);
++this._numDrawCalls;
const indexCount = inputAssembler.indexCount || inputAssembler.vertexCount;
if (this._curGPUPipelineState) {
const glPrimitive = this._curGPUPipelineState.glPrimitive;
switch (glPrimitive) {
case WebGL2RenderingContext.TRIANGLES: {
this._numTris += inputAssembler.indexCount / 3 * Math.max(inputAssembler.instanceCount, 1);
case 0x0004: { // WebGLRenderingContext.TRIANGLES
this._numTris += indexCount / 3 * Math.max(inputAssembler.instanceCount, 1);
break;
}
case WebGL2RenderingContext.TRIANGLE_STRIP:
case WebGL2RenderingContext.TRIANGLE_FAN: {
this._numTris += (inputAssembler.indexCount - 2) * Math.max(inputAssembler.instanceCount, 1);
case 0x0005: // WebGLRenderingContext.TRIANGLE_STRIP
case 0x0006: { // WebGLRenderingContext.TRIANGLE_FAN
this._numTris += (indexCount - 2) * Math.max(inputAssembler.instanceCount, 1);
break;
}
}
+6 -6
View File
@@ -54,10 +54,10 @@ import {
} from './webgl2-gpu-objects';
const WebGLWraps: GLenum[] = [
WebGLRenderingContext.REPEAT,
WebGLRenderingContext.MIRRORED_REPEAT,
WebGLRenderingContext.CLAMP_TO_EDGE,
WebGLRenderingContext.CLAMP_TO_EDGE,
0x2901, // WebGLRenderingContext.REPEAT
0x8370, // WebGLRenderingContext.MIRRORED_REPEAT
0x812F, // WebGLRenderingContext.CLAMP_TO_EDGE
0x812F, // WebGLRenderingContext.CLAMP_TO_EDGE
];
const SAMPLES: number[] = [
@@ -1262,9 +1262,9 @@ export function WebGL2CmdFuncCreateSampler (device: WebGL2GFXDevice, gpuSampler:
}
if (gpuSampler.magFilter === GFXFilter.LINEAR || gpuSampler.magFilter === GFXFilter.ANISOTROPIC) {
gpuSampler.glMagFilter = WebGLRenderingContext.LINEAR;
gpuSampler.glMagFilter = gl.LINEAR;
} else {
gpuSampler.glMagFilter = WebGLRenderingContext.NEAREST;
gpuSampler.glMagFilter = gl.NEAREST;
}
gpuSampler.glWrapS = WebGLWraps[gpuSampler.addressU];
+6 -6
View File
@@ -118,11 +118,11 @@ export class WebGL2GPUSampler {
public minLOD: number = 0;
public maxLOD: number = 1000;
public glMinFilter: GLenum = WebGL2RenderingContext.NONE;
public glMagFilter: GLenum = WebGL2RenderingContext.NONE;
public glWrapS: GLenum = WebGL2RenderingContext.NONE;
public glWrapT: GLenum = WebGL2RenderingContext.NONE;
public glWrapR: GLenum = WebGL2RenderingContext.NONE;
public glMinFilter: GLenum = 0;
public glMagFilter: GLenum = 0;
public glWrapS: GLenum = 0;
public glWrapT: GLenum = 0;
public glWrapR: GLenum = 0;
}
export class WebGL2GPUInput {
@@ -199,7 +199,7 @@ export class WebGL2GPUPipelineLayout {
export class WebGL2GPUPipelineState {
public glPrimitive: GLenum = WebGL2RenderingContext.TRIANGLES;
public glPrimitive: GLenum = 0x0004; // WebGLRenderingContext.TRIANGLES
public gpuShader: WebGL2GPUShader | null = null;
public rs: GFXRasterizerState = new GFXRasterizerState();
public dss: GFXDepthStencilState = new GFXDepthStencilState();
@@ -39,11 +39,12 @@ export class WebGL2GFXPipelineState extends GFXPipelineState {
this._primitive = info.primitive;
this._shader = info.shader;
this._is = info.is;
this._rs = info.rs;
this._dss = info.dss;
this._bs = info.bs;
this._is = info.inputState;
this._rs = info.rasterizerState;
this._dss = info.depthStencilState;
this._bs = info.blendState;
this._dynamicStates = info.dynamicStates || [];
this._hash = info.hash;
this._layout = info.layout;
this._renderPass = info.renderPass;
@@ -51,9 +52,9 @@ export class WebGL2GFXPipelineState extends GFXPipelineState {
this._gpuPipelineState = {
glPrimitive: WebGLPrimitives[info.primitive],
gpuShader: (info.shader as WebGL2GFXShader).gpuShader,
rs: info.rs,
dss: info.dss,
bs: info.bs,
rs: info.rasterizerState,
dss: info.depthStencilState,
bs: info.blendState,
dynamicStates: (info.dynamicStates !== undefined ? info.dynamicStates : []),
gpuLayout: (info.layout as WebGL2GFXPipelineLayout).gpuPipelineLayout,
gpuRenderPass: (info.renderPass as WebGL2GFXRenderPass).gpuRenderPass,
+5 -5
View File
@@ -84,11 +84,11 @@ export class WebGL2GFXSampler extends GFXSampler {
minLOD: this._state.minLOD,
maxLOD: this._state.maxLOD,
glMinFilter: WebGL2RenderingContext.NONE,
glMagFilter: WebGL2RenderingContext.NONE,
glWrapS: WebGL2RenderingContext.NONE,
glWrapT: WebGL2RenderingContext.NONE,
glWrapR: WebGL2RenderingContext.NONE,
glMinFilter: 0,
glMagFilter: 0,
glWrapS: 0,
glWrapT: 0,
glWrapR: 0,
};
WebGL2CmdFuncCreateSampler(this._device as WebGL2GFXDevice, this._gpuSampler);
+63 -46
View File
@@ -9,31 +9,29 @@ import { GFXPipelineState } from '../gfx/pipeline-state';
import { Mat4 } from '../math';
import { Pass } from '../renderer';
import { SubModel } from '../renderer/scene/submodel';
import { IRenderObject, UBOLocal, UniformBinding } from './define';
import { IRenderObject, UBOLocalBatched } from './define';
export interface IBatchedItem {
vbs: GFXBuffer[];
vbDatas: Uint8Array[];
vbIdx: GFXBuffer;
vbIdxData: Float32Array;
vbCount: number;
mergeCount: number;
ia: GFXInputAssembler;
uboLocal: UBOLocal;
ubo: GFXBuffer;
uboData: UBOLocalBatched;
pso: GFXPipelineState;
}
const _localBatched = new UBOLocalBatched();
export class BatchedBuffer {
public batches: IBatchedItem[] = [];
public pso: GFXPipelineState | null = null;
public ubo: GFXBuffer;
public pass: Pass;
private _limitCount = 10;
constructor (pass: Pass) {
this.pass = pass;
this.ubo = pass.device.createBuffer({
usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST,
memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE,
size: UBOLocal.SIZE,
});
}
public destroy () {
@@ -44,24 +42,22 @@ export class BatchedBuffer {
}
batch.vbIdx.destroy();
batch.ia.destroy();
batch.ubo.destroy();
}
this.batches.splice(0);
this.pso = null;
this.ubo.destroy();
}
public merge (subModel: SubModel, ro: IRenderObject) {
public merge (subModel: SubModel, ro: IRenderObject, pso: GFXPipelineState) {
const flatBuffers = subModel.subMeshData.flatBuffers;
if (flatBuffers.length === 0) {
return ;
}
if (flatBuffers.length === 0) { return; }
let vbSize = 0;
let vbIdxSize = 0;
const vbCount = flatBuffers[0].count;
const bindingLayout = pso.pipelineLayout.layouts[0];
let isBatchExist = false;
for (let i = 0; i < this.batches.length; ++i) {
const batch = this.batches[i];
if (batch.vbs.length === flatBuffers.length && batch.mergeCount <= this._limitCount) {
if (batch.vbs.length === flatBuffers.length && batch.mergeCount < UBOLocalBatched.BATCHING_COUNT) {
isBatchExist = true;
for (let j = 0; j < batch.vbs.length; ++j) {
const vb = batch.vbs[j];
@@ -75,27 +71,43 @@ export class BatchedBuffer {
for (let j = 0; j < batch.vbs.length; ++j) {
const flatBuff = flatBuffers[j];
const batchVB = batch.vbs[j];
let vbBuf = batch.vbDatas[j];
vbSize = (vbCount + batch.vbCount) * flatBuff.stride;
if (vbSize > batchVB.size) {
batchVB.resize(vbSize);
vbBuf = batch.vbDatas[j] = new Uint8Array(batchVB.bufferView!.buffer);
}
batchVB.update(flatBuff.buffer, batch.vbCount * flatBuff.stride);
vbBuf.set(flatBuff.buffer, batch.vbCount * flatBuff.stride);
}
vbIdxSize = (vbCount + batch.vbCount) * 4;
if (vbIdxSize > batch.vbIdx.size) {
batch.vbIdx.resize(vbIdxSize);
batch.vbIdxData = new Float32Array(batch.vbIdx.bufferView!.buffer);
}
const start = batch.vbCount;
const end = start + vbCount;
const vbIdxBuf = batch.vbIdxData;
const mergeCount = batch.mergeCount;
if (vbIdxBuf[start] !== mergeCount || vbIdxBuf[end - 1] !== mergeCount) {
for (let j = start; j < end; j++) {
vbIdxBuf[j] = mergeCount;
}
}
const vbIdxView = new Float32Array(flatBuffers[0].count);
vbIdxView.fill(batch.mergeCount);
batch.vbIdx.update(vbIdxView.buffer, batch.vbCount * 4);
// update world matrix
Mat4.toArray(batch.uboLocal.view, ro.model.transform.worldMatrix, UBOLocal.MAT_WORLDS_OFFSET + batch.mergeCount * 16);
Mat4.toArray(batch.uboData.view, ro.model.transform.worldMatrix, UBOLocalBatched.MAT_WORLDS_OFFSET + batch.mergeCount * 16);
if (!batch.mergeCount && batch.pso !== pso) {
bindingLayout.bindBuffer(UBOLocalBatched.BLOCK.binding, batch.ubo);
bindingLayout.update();
batch.pso = pso;
}
++batch.mergeCount;
batch.vbCount += vbCount;
batch.ia.vertexCount += vbCount;
return;
}
}
@@ -104,7 +116,8 @@ export class BatchedBuffer {
const device = this.pass.device;
// Create a new batch
const newVBs: GFXBuffer[] = [];
const vbs: GFXBuffer[] = [];
const vbDatas: Uint8Array[] = [];
const totalVBS: GFXBuffer[] = [];
for (let i = 0; i < flatBuffers.length; ++i) {
const flatBuff = flatBuffers[i];
@@ -115,8 +128,9 @@ export class BatchedBuffer {
stride: flatBuff.stride,
flags: GFXBufferFlagBit.BAKUP_BUFFER,
});
newVB.update(flatBuff.buffer);
newVBs.push(newVB);
newVB.update(flatBuff.buffer.buffer);
vbs.push(newVB);
vbDatas.push(new Uint8Array(newVB.bufferView!.buffer));
totalVBS.push(newVB);
}
@@ -131,6 +145,7 @@ export class BatchedBuffer {
vbIndices.fill(0);
vbIdx.update(vbIndices);
totalVBS.push(vbIdx);
const vbIdxData = new Float32Array(vbIdx.bufferView!.buffer);
const attributes = subModel.inputAssembler!.attributes;
const attrs = new Array<IGFXAttribute>(attributes.length + 1);
@@ -138,7 +153,7 @@ export class BatchedBuffer {
attrs[a] = attributes[a];
}
attrs[attributes.length] = {
name: 'a_index',
name: 'a_dyn_batch_id',
format: GFXFormat.R32F,
stream: flatBuffers.length,
};
@@ -148,27 +163,22 @@ export class BatchedBuffer {
vertexBuffers: totalVBS,
});
const newBatch: IBatchedItem = {
vbs: newVBs,
vbIdx,
vbCount,
const ubo = this.pass.device.createBuffer({
usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST,
memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE,
size: UBOLocalBatched.SIZE,
});
bindingLayout.bindBuffer(UBOLocalBatched.BLOCK.binding, ubo);
bindingLayout.update();
const uboData = new UBOLocalBatched();
Mat4.toArray(uboData.view, ro.model.transform.worldMatrix, UBOLocalBatched.MAT_WORLDS_OFFSET);
this.batches.push({
mergeCount: 1,
ia,
uboLocal: new UBOLocal(),
};
// newBatch.subModels.push(subModel);
Mat4.toArray(newBatch.uboLocal.view, ro.model.transform.worldMatrix, UBOLocal.MAT_WORLDS_OFFSET);
this.batches.push(newBatch);
this.pass.bindBuffer(UniformBinding.UBO_LOCAL, this.ubo);
this.pass.update();
if (!this.pso) {
this.pso = subModel.psos![this.pass.idxInTech];
const bindingLayout = this.pso.pipelineLayout.layouts[0];
bindingLayout.update();
}
vbs, vbDatas, vbIdx, vbIdxData, vbCount, ia, ubo, uboData, pso,
});
}
public clear () {
@@ -179,4 +189,11 @@ export class BatchedBuffer {
batch.ia.vertexCount = 0;
}
}
public clearUBO () {
for (let i = 0; i < this.batches.length; ++i) {
const batch = this.batches[i];
batch.ubo.update(_localBatched.view.buffer);
}
}
}
+24 -9
View File
@@ -85,11 +85,10 @@ export enum UniformBinding {
UBO_SHADOW = MAX_BINDING_SUPPORTED - 2,
UBO_LOCAL = MAX_BINDING_SUPPORTED - 3,
UBO_LOCAL_BATCHED = MAX_BINDING_SUPPORTED - 4,
UBO_FORWARD_LIGHTS = MAX_BINDING_SUPPORTED - 5,
UBO_SKINNING_ANIMATION = MAX_BINDING_SUPPORTED - 6,
UBO_SKINNING_TEXTURE = MAX_BINDING_SUPPORTED - 7,
UBO_UI = MAX_BINDING_SUPPORTED - 8,
UBO_FORWARD_LIGHTS = MAX_BINDING_SUPPORTED - 4,
UBO_SKINNING_ANIMATION = MAX_BINDING_SUPPORTED - 5,
UBO_SKINNING_TEXTURE = MAX_BINDING_SUPPORTED - 6,
UBO_UI = MAX_BINDING_SUPPORTED - 7,
// samplers
SAMPLER_JOINTS = MAX_BINDING_SUPPORTED + 1,
@@ -184,18 +183,15 @@ export const localBindingsDesc: Map<string, IInternalBindingDesc> = new Map<stri
* 本地 UBO。
*/
export class UBOLocal {
public static BATCHING_COUNT: number = 10;
public static MAT_WORLD_OFFSET: number = 0;
public static MAT_WORLD_IT_OFFSET: number = UBOLocal.MAT_WORLD_OFFSET + 16;
public static MAT_WORLDS_OFFSET: number = UBOLocal.MAT_WORLD_IT_OFFSET + 16;
public static COUNT: number = UBOLocal.MAT_WORLDS_OFFSET + 16 * UBOLocal.BATCHING_COUNT;
public static COUNT: number = UBOLocal.MAT_WORLD_IT_OFFSET + 16;
public static SIZE: number = UBOLocal.COUNT * 4;
public static BLOCK: GFXUniformBlock = {
binding: UniformBinding.UBO_LOCAL, name: 'CCLocal', members: [
{ name: 'cc_matWorld', type: GFXType.MAT4, count: 1 },
{ name: 'cc_matWorldIT', type: GFXType.MAT4, count: 1 },
{ name: 'cc_matWorlds', type: GFXType.MAT4, count: UBOLocal.BATCHING_COUNT },
],
};
@@ -206,6 +202,25 @@ localBindingsDesc.set(UBOLocal.BLOCK.name, {
blockInfo: UBOLocal.BLOCK,
});
export class UBOLocalBatched {
public static BATCHING_COUNT: number = 10;
public static MAT_WORLDS_OFFSET: number = 0;
public static COUNT: number = 16 * UBOLocalBatched.BATCHING_COUNT;
public static SIZE: number = UBOLocalBatched.COUNT * 4;
public static BLOCK: GFXUniformBlock = {
binding: UniformBinding.UBO_LOCAL, name: 'CCLocalBatched', members: [
{ name: 'cc_matWorlds', type: GFXType.MAT4, count: UBOLocalBatched.BATCHING_COUNT },
],
};
public view: Float32Array = new Float32Array(UBOLocalBatched.COUNT);
}
localBindingsDesc.set(UBOLocalBatched.BLOCK.name, {
type: GFXBindingType.UNIFORM_BUFFER,
blockInfo: UBOLocalBatched.BLOCK,
});
/**
* @zh
* 前向灯光 UBO。
+8 -6
View File
@@ -4,6 +4,7 @@
import { GFXCommandBuffer } from '../../gfx/command-buffer';
import { GFXClearFlag, GFXCommandBufferType, GFXFilter, IGFXColor } from '../../gfx/define';
import { Layers } from '../../scene-graph';
import { getPhaseID } from '../pass-phase';
import { SRGBToLinear } from '../pipeline-funcs';
import { RenderBatchedQueue } from '../render-batched-queue';
@@ -11,9 +12,8 @@ import { RenderFlow } from '../render-flow';
import { opaqueCompareFn, RenderQueue, transparentCompareFn } from '../render-queue';
import { IRenderStageInfo, RenderStage } from '../render-stage';
import { RenderView } from '../render-view';
import { Layers } from '../../scene-graph';
const colors: IGFXColor[] = [];
const colors: IGFXColor[] = [ { r: 0, g: 0, b: 0, a: 1 } ];
const bufs: GFXCommandBuffer[] = [];
/**
@@ -118,7 +118,7 @@ export class ForwardStage extends RenderStage {
const pso = subModel.psos![p];
const isTransparent = pso.blendState.targets[0].blend;
if (!isTransparent) {
pass.batchedBuffer.merge(subModel, ro);
pass.batchedBuffer.merge(subModel, ro, pso);
this._opaqueBatchedQueue.queue.add(pass.batchedBuffer);
} else {
const hash = (0 << 30) | pass.priority << 16 | subModel.priority << 8 | p;
@@ -181,15 +181,17 @@ export class ForwardStage extends RenderStage {
this._renderArea.height = vp.height * camera.height * this.pipeline.shadingScale;
if (camera.clearFlag & GFXClearFlag.COLOR) {
colors[0] = camera.clearColor;
if (this._pipeline.isHDR) {
colors[0] = SRGBToLinear(colors[0]);
SRGBToLinear(colors[0], camera.clearColor);
const scale = this._pipeline.fpScale / camera.exposure;
colors[0].r *= scale;
colors[0].g *= scale;
colors[0].b *= scale;
} else {
colors[0].r = camera.clearColor.r;
colors[0].g = camera.clearColor.g;
colors[0].b = camera.clearColor.b;
}
colors.length = 1;
}
if (this._pipeline.usePostProcess) {
+2 -1
View File
@@ -6,7 +6,8 @@
export const getPhaseID = (() => {
const phases: Map<string, number> = new Map<string, number>();
let phaseNum = 0;
return (phaseName: string) => {
return (phaseName: string | number) => {
if (typeof phaseName === 'number') { return phaseName; }
if (!phases.has(phaseName)) {
phases.set(phaseName, 1 << phaseNum);
phaseNum++;
+14 -10
View File
@@ -9,11 +9,13 @@ import { IGFXColor } from '../gfx/define';
* SRGB颜色空间转换为线性空间。
* @param gamma SRGB颜色空间下的GAMMA值。
*/
export function SRGBToLinear (gamma: IGFXColor): IGFXColor {
const r = Math.pow(gamma.r, 2.2);
const g = Math.pow(gamma.g, 2.2);
const b = Math.pow(gamma.b, 2.2);
return { r, g, b, a: 1.0 };
export function SRGBToLinear (out: IGFXColor, gamma: IGFXColor) {
// out.r = Math.pow(gamma.r, 2.2);
// out.g = Math.pow(gamma.g, 2.2);
// out.b = Math.pow(gamma.b, 2.2);
out.r = gamma.r * gamma.r;
out.g = gamma.g * gamma.g;
out.b = gamma.b * gamma.b;
}
/**
@@ -21,9 +23,11 @@ export function SRGBToLinear (gamma: IGFXColor): IGFXColor {
* 线性空间转换为SRGB颜色空间。
* @param linear 线性空间下的颜色值。
*/
export function LinearToSRGB (linear: IGFXColor): IGFXColor {
const r = Math.pow(linear.r, 0.454545);
const g = Math.pow(linear.g, 0.454545);
const b = Math.pow(linear.b, 0.454545);
return { r, g, b, a: 1.0 };
export function LinearToSRGB (out: IGFXColor, linear: IGFXColor) {
// out.r = Math.pow(linear.r, 0.454545);
// out.g = Math.pow(linear.g, 0.454545);
// out.b = Math.pow(linear.b, 0.454545);
out.r = Math.sqrt(linear.r);
out.g = Math.sqrt(linear.g);
out.b = Math.sqrt(linear.b);
}
+8 -3
View File
@@ -3,12 +3,16 @@
*/
import { GFXBindingLayout } from '../../gfx/binding-layout';
import { GFXClearFlag, GFXCommandBufferType } from '../../gfx/define';
import { GFXCommandBuffer } from '../../gfx/command-buffer';
import { GFXClearFlag, GFXCommandBufferType, IGFXColor } from '../../gfx/define';
import { UBOGlobal } from '../define';
import { RenderFlow } from '../render-flow';
import { IRenderStageInfo, RenderStage } from '../render-stage';
import { RenderView } from '../render-view';
const colors: IGFXColor[] = [ { r: 0, g: 0, b: 0, a: 1 } ];
const bufs: GFXCommandBuffer[] = [];
/**
* @zh
* 色调映射渲染阶段。
@@ -89,7 +93,7 @@ export class ToneMapStage extends RenderStage {
this._cmdBuff.begin();
this._cmdBuff.beginRenderPass(framebuffer, this._renderArea,
GFXClearFlag.ALL, [{ r: 0.0, g: 0.0, b: 0.0, a: 1.0 }], 1.0, 0);
GFXClearFlag.ALL, colors, 1.0, 0);
this._cmdBuff.bindPipelineState(this._pso!);
this._cmdBuff.bindBindingLayout(this._pso!.pipelineLayout.layouts[0]);
this._cmdBuff.bindInputAssembler(this._pipeline.quadIA);
@@ -98,7 +102,8 @@ export class ToneMapStage extends RenderStage {
this._cmdBuff.end();
}
this._device.queue.submit([this._cmdBuff!]);
bufs[0] = this._cmdBuff!;
this._device.queue.submit(bufs);
// this._pipeline.swapFBOs();
}
+11 -8
View File
@@ -29,7 +29,7 @@ export class RenderBatchedQueue {
* 清空渲染队列。
*/
public clear () {
for (const batchedBuff of this.queue.values()){
for (const batchedBuff of this.queue.values()) {
batchedBuff.clear();
}
this.queue.clear();
@@ -40,15 +40,18 @@ export class RenderBatchedQueue {
* 记录命令缓冲。
*/
public recordCommandBuffer (cmdBuff: GFXCommandBuffer) {
for (const batchedBuffer of this.queue.values()){
if (batchedBuffer.pso) {
cmdBuff.bindPipelineState(batchedBuffer.pso);
cmdBuff.bindBindingLayout(batchedBuffer.pso.pipelineLayout.layouts[0]);
}
for (const batchedBuffer of this.queue.values()) {
let boundPSO = false;
for (let b = 0; b < batchedBuffer.batches.length; ++b) {
const batch = batchedBuffer.batches[b];
batchedBuffer.ubo.update(batch.uboLocal.view);
if (!batch.mergeCount) { continue; }
for (let v = 0; v < batch.vbs.length; ++v) {
batch.vbs[v].update(batch.vbDatas[v]);
}
batch.vbIdx.update(batch.vbIdxData.buffer);
batch.ubo.update(batch.uboData.view);
if (!boundPSO) { cmdBuff.bindPipelineState(batch.pso); boundPSO = true; }
cmdBuff.bindBindingLayout(batch.pso.pipelineLayout.layouts[0]);
cmdBuff.bindInputAssembler(batch.ia);
cmdBuff.draw(batch.ia);
}
+3 -1
View File
@@ -1128,6 +1128,8 @@ export abstract class RenderPipeline {
// update UBOGlobal
fv[UBOGlobal.TIME_OFFSET] = this._root.cumulativeTime;
fv[UBOGlobal.TIME_OFFSET + 1] = this._root.frameTime;
fv[UBOGlobal.TIME_OFFSET + 2] = cc.director.getTotalFrames();
fv[UBOGlobal.SCREEN_SIZE_OFFSET] = device.width;
fv[UBOGlobal.SCREEN_SIZE_OFFSET + 1] = device.height;
@@ -1251,7 +1253,7 @@ export abstract class RenderPipeline {
}
if (planarShadows.enabled) {
planarShadows.updateCommandBuffers();
planarShadows.updateCommandBuffers(camera.frustum);
}
}
+1
View File
@@ -5,6 +5,7 @@
import { GFXCommandBuffer } from '../gfx/command-buffer';
import { CachedArray } from '../memop/cached-array';
import { IRenderObject, IRenderPass, IRenderQueueDesc } from './define';
import { getPhaseID } from './pass-phase';
/**
* @en
+5 -2
View File
@@ -3,7 +3,7 @@
*/
import { GFXCommandBuffer } from '../../gfx/command-buffer';
import { GFXClearFlag, GFXCommandBufferType } from '../../gfx/define';
import { GFXCommandBufferType, IGFXColor } from '../../gfx/define';
import { getPhaseID } from '../pass-phase';
import { RenderFlow } from '../render-flow';
import { RenderQueue, transparentCompareFn } from '../render-queue';
@@ -11,6 +11,7 @@ import { IRenderStageInfo, RenderStage } from '../render-stage';
import { RenderView } from '../render-view';
const bufs: GFXCommandBuffer[] = [];
const colors: IGFXColor[] = [];
/**
* @zh
@@ -88,9 +89,11 @@ export class UIStage extends RenderStage {
this._renderArea.width = vp.width * camera.width;
this._renderArea.height = vp.height * camera.height;
colors[0] = camera.clearColor;
cmdBuff.begin();
cmdBuff.beginRenderPass(framebuffer, this._renderArea,
camera.clearFlag, [camera.clearColor], camera.clearDepth, camera.clearStencil);
camera.clearFlag, colors, camera.clearDepth, camera.clearStencil);
cmdBuff.execute(this._uiQueue.cmdBuffs.array, this._uiQueue.cmdBuffCount);
+28 -2
View File
@@ -1,3 +1,27 @@
/*
Copyright (c) 2017-2019 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 '../components/component';
import { property, ccclass, menu, executionOrder } from '../data/class-decorator';
@@ -34,7 +58,9 @@ import { Rect } from '../math';
@executionOrder(110)
@menu('Components/SubContextView')
export class SubContextView extends Component {
@property
@property({
tooltip:'帧数',
})
get fps (){
return this._fps;
}
@@ -47,7 +73,7 @@ export class SubContextView extends Component {
this._updateSubContextFrameRate();
}
@property({ type: Number })
@property
private _fps = 60;
private _sprite: SpriteComponent | null;
private _imageAsset: ImageAsset;
@@ -38,7 +38,7 @@ export interface IEventListenerCreateInfo {
[x: string]: any;
}
export interface ILinstenerMask {
export interface IListenerMask {
index: number;
node: INode;
}
@@ -148,7 +148,7 @@ export class EventListener {
// hack: How to solve the problem of uncertain attribute
// callback's this object
public owner: Object | null = null;
public mask: ILinstenerMask | null = null;
public mask: IListenerMask | null = null;
public _previousIn?: boolean = false;
public _target: any = null;
+7 -2
View File
@@ -762,7 +762,13 @@ else {
osVersion = uaResult[2] || '';
osMainVersion = parseInt(osVersion) || 0;
}
else if (/(iPhone|iPad|iPod)/.exec(nav.platform)) {
// refer to https://github.com/cocos-creator/engine/pull/5542 , thanks for contribition from @krapnikkk
// ipad OS 13 safari identifies itself as "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15) AppleWebKit/605.1.15 (KHTML, like Gecko)"
// so use maxTouchPoints to check whether it's desktop safari or not.
// reference: https://stackoverflow.com/questions/58019463/how-to-detect-device-name-in-safari-on-ios-13-while-it-doesnt-show-the-correct
// FIXME: should remove it when touch-enabled mac are available
// TODO: due to compatibility issues, it is still determined to be ios, and a new operating system type ipados may be added later?
else if (/(iPhone|iPad|iPod)/.exec(nav.platform) || (nav.platform === 'MacIntel' && nav.maxTouchPoints && nav.maxTouchPoints > 1)) {
iOS = true;
osVersion = '';
osMainVersion = 0;
@@ -920,7 +926,6 @@ else {
else if (sys.browserType === sys.BROWSER_TYPE_WECHAT_GAME) {
_supportWebGL = true;
}
// @ts-ignore
else if (win.WebGLRenderingContext) {
// @ts-ignore
if (create3DContext(document.createElement('CANVAS'))) {
+4 -4
View File
@@ -76,7 +76,7 @@ export function toWavefrontOBJ (primitive: IGeometry, scale = 1) {
/**
* @deprecated
*/
export function normals (positions: number[], normals: number[], length = 1) {
export function normals (positions: number[], nms: number[], length = 1) {
const verts = new Array(2 * positions.length);
for (let i = 0; i < positions.length / 3; ++i) {
@@ -89,9 +89,9 @@ export function normals (positions: number[], normals: number[], length = 1) {
verts[i6 + 2] = positions[i3 + 2];
// line end
verts[i6 + 3] = positions[i3 + 0] + normals[i3 + 0] * length;
verts[i6 + 4] = positions[i3 + 1] + normals[i3 + 1] * length;
verts[i6 + 5] = positions[i3 + 2] + normals[i3 + 2] * length;
verts[i6 + 3] = positions[i3 + 0] + nms[i3 + 0] * length;
verts[i6 + 4] = positions[i3 + 1] + nms[i3 + 1] * length;
verts[i6 + 5] = positions[i3 + 2] + nms[i3 + 2] * length;
}
return verts;
+87
View File
@@ -0,0 +1,87 @@
/*
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 material
*/
import { GFXBindingType, GFXType } from '../../gfx/define';
import { Mat3, Mat4, Vec2, Vec3, Vec4 } from '../../math';
const btMask = 0xf0000000; // 4 bits => 16 binding types
const typeMask = 0x0fc00000; // 6 bits => 64 types
const bindingMask = 0x003fc000; // 8 bits => 256 bindings
const offsetMask = 0x00003fff; // 14 bits => 4096 vectors
export const genHandle = (bt: GFXBindingType, binding: number, type: GFXType, offset: number = 0) =>
((bt << 28) & btMask) | ((type << 22) & typeMask) | ((binding << 14) & bindingMask) | (offset & offsetMask);
export const getBindingTypeFromHandle = (handle: number) => (handle & btMask) >>> 28;
export const getTypeFromHandle = (handle: number) => (handle & typeMask) >>> 22;
export const getBindingFromHandle = (handle: number) => (handle & bindingMask) >>> 14;
export const getOffsetFromHandle = (handle: number) => (handle & offsetMask);
export const customizeType = (handle: number, type: GFXType) => (handle & ~typeMask) | ((type << 22) & typeMask);
export const type2reader = {
[GFXType.UNKNOWN]: (a: Float32Array, v: any, idx: number = 0) => console.warn('illegal uniform handle'),
[GFXType.INT]: (a: Float32Array, v: any, idx: number = 0) => a[idx],
[GFXType.INT2]: (a: Float32Array, v: any, idx: number = 0) => Vec2.fromArray(v, a, idx),
[GFXType.INT3]: (a: Float32Array, v: any, idx: number = 0) => Vec3.fromArray(v, a, idx),
[GFXType.INT4]: (a: Float32Array, v: any, idx: number = 0) => Vec4.fromArray(v, a, idx),
[GFXType.FLOAT]: (a: Float32Array, v: any, idx: number = 0) => a[idx],
[GFXType.FLOAT2]: (a: Float32Array, v: any, idx: number = 0) => Vec2.fromArray(v, a, idx),
[GFXType.FLOAT3]: (a: Float32Array, v: any, idx: number = 0) => Vec3.fromArray(v, a, idx),
[GFXType.FLOAT4]: (a: Float32Array, v: any, idx: number = 0) => Vec4.fromArray(v, a, idx),
[GFXType.MAT3]: (a: Float32Array, v: any, idx: number = 0) => Mat3.fromArray(v, a, idx),
[GFXType.MAT4]: (a: Float32Array, v: any, idx: number = 0) => Mat4.fromArray(v, a, idx),
};
export const type2writer = {
[GFXType.UNKNOWN]: (a: Float32Array, v: any, idx: number = 0) => console.warn('illegal uniform handle'),
[GFXType.INT]: (a: Float32Array, v: any, idx: number = 0) => a[idx] = v,
[GFXType.INT2]: (a: Float32Array, v: any, idx: number = 0) => Vec2.toArray(a, v, idx),
[GFXType.INT3]: (a: Float32Array, v: any, idx: number = 0) => Vec3.toArray(a, v, idx),
[GFXType.INT4]: (a: Float32Array, v: any, idx: number = 0) => Vec4.toArray(a, v, idx),
[GFXType.FLOAT]: (a: Float32Array, v: any, idx: number = 0) => a[idx] = v,
[GFXType.FLOAT2]: (a: Float32Array, v: any, idx: number = 0) => Vec2.toArray(a, v, idx),
[GFXType.FLOAT3]: (a: Float32Array, v: any, idx: number = 0) => Vec3.toArray(a, v, idx),
[GFXType.FLOAT4]: (a: Float32Array, v: any, idx: number = 0) => Vec4.toArray(a, v, idx),
[GFXType.MAT3]: (a: Float32Array, v: any, idx: number = 0) => Mat3.toArray(a, v, idx),
[GFXType.MAT4]: (a: Float32Array, v: any, idx: number = 0) => Mat4.toArray(a, v, idx),
};
export const type2default = {
[GFXType.INT]: [0],
[GFXType.INT2]: [0, 0],
[GFXType.INT3]: [0, 0, 0],
[GFXType.INT4]: [0, 0, 0, 0],
[GFXType.FLOAT]: [0],
[GFXType.FLOAT2]: [0, 0],
[GFXType.FLOAT3]: [0, 0, 0],
[GFXType.FLOAT4]: [0, 0, 0, 0],
[GFXType.MAT3]: [1, 0, 0, 0, 1, 0, 0, 0, 1],
[GFXType.MAT4]: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
[GFXType.SAMPLER2D]: 'default-texture',
[GFXType.SAMPLER_CUBE]: 'default-cube-texture',
};
+197 -204
View File
@@ -28,26 +28,28 @@
*/
import { builtinResMgr } from '../../3d/builtin/init';
import { EffectAsset, IPassInfo, IPassStates, IPropertyInfo, IShaderInfo } from '../../assets/effect-asset';
import { EffectAsset, IPassInfo, IPassStates, IPropertyInfo } from '../../assets/effect-asset';
import { TextureBase } from '../../assets/texture-base';
import { GFXBindingLayout, IGFXBinding } from '../../gfx/binding-layout';
import { GFXBuffer } from '../../gfx/buffer';
import { GFXBindingLayout, IGFXBinding, IGFXBindingLayoutInfo } from '../../gfx/binding-layout';
import { GFXBuffer, IGFXBufferInfo } from '../../gfx/buffer';
import { GFXBindingType, GFXBufferUsageBit, GFXDynamicState,
GFXGetTypeSize, GFXMemoryUsageBit, GFXPrimitiveMode, GFXType } from '../../gfx/define';
import { GFXDevice } from '../../gfx/device';
import { GFXPipelineLayout } from '../../gfx/pipeline-layout';
import { GFXPipelineLayout, IGFXPipelineLayoutInfo } from '../../gfx/pipeline-layout';
import { GFXBlendState, GFXBlendTarget, GFXDepthStencilState,
GFXInputState, GFXPipelineState, GFXRasterizerState } from '../../gfx/pipeline-state';
GFXInputState, GFXPipelineState, GFXRasterizerState, IGFXPipelineStateInfo } from '../../gfx/pipeline-state';
import { GFXRenderPass } from '../../gfx/render-pass';
import { GFXSampler } from '../../gfx/sampler';
import { GFXShader } from '../../gfx/shader';
import { GFXTextureView } from '../../gfx/texture-view';
import { Mat3, Mat4, Vec2, Vec3, Vec4 } from '../../math';
import { BatchedBuffer } from '../../pipeline/batched-buffer';
import { isBuiltinBinding, RenderPassStage, RenderPriority, UBOLocal } from '../../pipeline/define';
import { isBuiltinBinding, RenderPassStage, RenderPriority } from '../../pipeline/define';
import { getPhaseID } from '../../pipeline/pass-phase';
import { Root } from '../../root';
import { programLib } from './program-lib';
import { murmurhash2_32_gc } from '../../utils/murmurhash2_gc';
import { customizeType, getBindingFromHandle, getBindingTypeFromHandle,
getOffsetFromHandle, getTypeFromHandle, type2default, type2reader, type2writer } from './pass-utils';
import { IProgramInfo, programLib } from './program-lib';
import { samplerLib } from './sampler-lib';
export interface IDefineMap { [name: string]: number | boolean | string; }
@@ -59,62 +61,7 @@ export interface IPassInfoFull extends IPassInfo {
}
export type PassOverrides = RecursivePartial<IPassStates>;
const _type2writer = {
[GFXType.UNKNOWN]: (a: Float32Array, v: any, idx: number = 0) => console.warn('illegal uniform handle'),
[GFXType.INT]: (a: Float32Array, v: any, idx: number = 0) => a[idx] = v,
[GFXType.INT2]: (a: Float32Array, v: any, idx: number = 0) => Vec2.toArray(a, v, idx),
[GFXType.INT3]: (a: Float32Array, v: any, idx: number = 0) => Vec3.toArray(a, v, idx),
[GFXType.INT4]: (a: Float32Array, v: any, idx: number = 0) => Vec4.toArray(a, v, idx),
[GFXType.FLOAT]: (a: Float32Array, v: any, idx: number = 0) => a[idx] = v,
[GFXType.FLOAT2]: (a: Float32Array, v: any, idx: number = 0) => Vec2.toArray(a, v, idx),
[GFXType.FLOAT3]: (a: Float32Array, v: any, idx: number = 0) => Vec3.toArray(a, v, idx),
[GFXType.FLOAT4]: (a: Float32Array, v: any, idx: number = 0) => Vec4.toArray(a, v, idx),
[GFXType.MAT3]: (a: Float32Array, v: any, idx: number = 0) => Mat3.toArray(a, v, idx),
[GFXType.MAT4]: (a: Float32Array, v: any, idx: number = 0) => Mat4.toArray(a, v, idx),
};
const _type2reader = {
[GFXType.UNKNOWN]: (a: Float32Array, v: any, idx: number = 0) => console.warn('illegal uniform handle'),
[GFXType.INT]: (a: Float32Array, v: any, idx: number = 0) => a[idx],
[GFXType.INT2]: (a: Float32Array, v: any, idx: number = 0) => Vec2.fromArray(v, a, idx),
[GFXType.INT3]: (a: Float32Array, v: any, idx: number = 0) => Vec3.fromArray(v, a, idx),
[GFXType.INT4]: (a: Float32Array, v: any, idx: number = 0) => Vec4.fromArray(v, a, idx),
[GFXType.FLOAT]: (a: Float32Array, v: any, idx: number = 0) => a[idx],
[GFXType.FLOAT2]: (a: Float32Array, v: any, idx: number = 0) => Vec2.fromArray(v, a, idx),
[GFXType.FLOAT3]: (a: Float32Array, v: any, idx: number = 0) => Vec3.fromArray(v, a, idx),
[GFXType.FLOAT4]: (a: Float32Array, v: any, idx: number = 0) => Vec4.fromArray(v, a, idx),
[GFXType.MAT3]: (a: Float32Array, v: any, idx: number = 0) => Mat3.fromArray(v, a, idx),
[GFXType.MAT4]: (a: Float32Array, v: any, idx: number = 0) => Mat4.fromArray(v, a, idx),
};
export const _type2default = {
[GFXType.INT]: [0],
[GFXType.INT2]: [0, 0],
[GFXType.INT3]: [0, 0, 0],
[GFXType.INT4]: [0, 0, 0, 0],
[GFXType.FLOAT]: [0],
[GFXType.FLOAT2]: [0, 0],
[GFXType.FLOAT3]: [0, 0, 0],
[GFXType.FLOAT4]: [0, 0, 0, 0],
[GFXType.MAT3]: [1, 0, 0, 0, 1, 0, 0, 0, 1],
[GFXType.MAT4]: [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
[GFXType.SAMPLER2D]: 'default-texture',
[GFXType.SAMPLER_CUBE]: 'default-cube-texture',
};
const btMask = 0xf0000000; // 4 bits => 16 binding types
const typeMask = 0x0fc00000; // 6 bits => 64 types
const bindingMask = 0x003fc000; // 8 bits => 256 bindings
const offsetMask = 0x00003fff; // 14 bits => 4096 vectors
const genHandle = (bt: GFXBindingType, binding: number, type: GFXType, index: number = 0) =>
((bt << 28) & btMask) | ((type << 22) & typeMask) | ((binding << 14) & bindingMask) | (index & offsetMask);
const getBindingTypeFromHandle = (handle: number) => (handle & btMask) >>> 28;
const getTypeFromHandle = (handle: number) => (handle & typeMask) >>> 22;
const getBindingFromHandle = (handle: number) => (handle & bindingMask) >>> 14;
const getOffsetFromHandle = (handle: number) => (handle & offsetMask);
const customizeType = (handle: number, type: GFXType) => (handle & ~typeMask) | ((type << 22) & typeMask);
interface IBlock {
export interface IBlock {
buffer: ArrayBuffer;
view: Float32Array;
dirty: boolean;
@@ -127,7 +74,7 @@ interface IPassResources {
}
interface IPassDynamics {
[type: string]: {
[type: number]: {
dirty: boolean,
value: number[],
};
@@ -139,6 +86,48 @@ interface IEffectInfo {
states: PassOverrides[];
}
interface IPSOHashInfo {
program: string;
defines: IDefineMap;
stage: RenderPassStage;
primitive: GFXPrimitiveMode;
rasterizerState: GFXRasterizerState;
depthStencilState: GFXDepthStencilState;
blendState: GFXBlendState;
dynamicStates: GFXDynamicState[];
}
const _bfInfo: IGFXBufferInfo = {
memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE,
size: 0,
usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST,
};
const _blInfo: IGFXBindingLayoutInfo = {
bindings: null!,
};
const _plInfo: IGFXPipelineLayoutInfo = {
layouts: null!,
};
const _psoInfo: IGFXPipelineStateInfo & IPSOHashInfo = {
primitive: 0,
shader: null!,
inputState: new GFXInputState(),
rasterizerState: null!,
depthStencilState: null!,
blendState: null!,
dynamicStates: null!,
layout: null!,
renderPass: null!,
hash: 0,
program: '',
defines: null!,
stage: 0,
};
/**
* @zh
* 渲染 pass,储存实际描述绘制过程的各项资源。
@@ -179,6 +168,42 @@ export class Pass {
return passes;
}
public static fillinPipelineInfo (target: Pass, info: PassOverrides) {
if (info.priority !== undefined) { target._priority = info.priority; }
if (info.primitive !== undefined) { target._primitive = info.primitive; }
if (info.stage !== undefined) { target._stage = info.stage; }
if (info.dynamicStates !== undefined) { target._dynamicStates = info.dynamicStates as GFXDynamicState[]; }
if (info.customizations) { target._customizations = info.customizations as string[]; }
if (info.phase) { target._phase = getPhaseID(info.phase); }
const bs = target._bs;
if (info.blendState) {
const bsInfo = Object.assign({}, info.blendState);
if (bsInfo.targets) {
bsInfo.targets.forEach((t, i) => Object.assign(
bs.targets[i] || (bs.targets[i] = new GFXBlendTarget()), t));
}
delete bsInfo.targets;
Object.assign(bs, bsInfo);
}
Object.assign(target._rs, info.rasterizerState);
Object.assign(target._dss, info.depthStencilState);
}
/**
* @zh
* 根据指定 PSO 信息计算 hash
* @param psoInfo 用于计算 PSO hash 的最小必要信息
*/
public static getPSOHash (psoInfo: IPSOHashInfo) {
const shaderKey = programLib.getKey(psoInfo.program, psoInfo.defines);
let res = `${shaderKey},${psoInfo.stage},${psoInfo.primitive}`;
res += serializeBlendState(psoInfo.blendState);
res += serializeDepthStencilState(psoInfo.depthStencilState);
res += serializeRasterizerState(psoInfo.rasterizerState);
return murmurhash2_32_gc(res, 666);
}
protected static getOffsetFromHandle = getOffsetFromHandle;
// internal resources
protected _buffers: Record<number, GFXBuffer> = {};
@@ -186,7 +211,7 @@ export class Pass {
protected _textureViews: Record<number, GFXTextureView> = {};
protected _resources: IPassResources[] = [];
// internal data
protected _phase: number = 0;
protected _phase = getPhaseID('default');
protected _idxInTech = 0;
protected _programName = '';
protected _priority: RenderPriority = RenderPriority.DEFAULT;
@@ -201,7 +226,7 @@ export class Pass {
protected _customizations: string[] = [];
protected _handleMap: Record<string, number> = {};
protected _blocks: IBlock[] = [];
protected _shaderInfo: IShaderInfo = null!;
protected _shaderInfo: IProgramInfo = null!;
protected _defines: IDefineMap = {};
protected _properties: Record<string, IPropertyInfo> = {};
// external references
@@ -227,41 +252,30 @@ export class Pass {
this._properties = info.properties || this._properties;
// pipeline state
const device = this._device;
this._fillinPipelineInfo(info);
this._fillinPipelineInfo(info.states);
for (const u of this._shaderInfo.blocks) {
if (isBuiltinBinding(u.binding)) { continue; }
const blockSize = u.members.reduce((s, m) => s + GFXGetTypeSize(m.type) * m.count, 0);
Pass.fillinPipelineInfo(this, info);
Pass.fillinPipelineInfo(this, info.states);
const blocks = this._shaderInfo.blocks;
for (let i = 0; i < blocks.length; i++) {
const { size, binding } = blocks[i];
if (isBuiltinBinding(binding)) { continue; }
// create gfx buffer resource
this._buffers[u.binding] = device.createBuffer({
memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE,
size: Math.ceil(blockSize / 16) * 16, // https://bugs.chromium.org/p/chromium/issues/detail?id=988988
usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST,
});
_bfInfo.size = Math.ceil(size / 16) * 16; // https://bugs.chromium.org/p/chromium/issues/detail?id=988988
this._buffers[binding] = device.createBuffer(_bfInfo);
// non-builtin UBO data pools, note that the effect compiler
// guarantees these bindings to be consecutive, starting from 0
const buffer = new ArrayBuffer(blockSize);
this._blocks[u.binding] = { buffer, dirty: false, view: new Float32Array(buffer) };
u.members.reduce((acc, cur) => {
// store handle map
this._handleMap[cur.name] = genHandle(GFXBindingType.UNIFORM_BUFFER, u.binding, cur.type, acc);
// proceed the counter
return acc + (GFXGetTypeSize(cur.type) >> 2) * cur.count;
}, 0);
const buffer = new ArrayBuffer(size);
this._blocks[binding] = { buffer, dirty: false, view: new Float32Array(buffer) };
}
// store indirect property handles
for (const name of Object.keys(this._properties)) {
// store handles
const directHandleMap = this._handleMap = this._shaderInfo.handleMap;
const indirectHandleMap: Record<string, number> = {};
for (const name in this._properties) {
const prop = this._properties[name];
if (!prop.handleInfo) { continue; }
this._handleMap[name] = this.getHandle.apply(this, prop.handleInfo)!;
}
// store sampler handles
for (const u of this._shaderInfo.samplers) {
this._handleMap[u.name] = genHandle(GFXBindingType.SAMPLER, u.binding, u.type);
indirectHandleMap[name] = this.getHandle.apply(this, prop.handleInfo)!;
}
Object.assign(directHandleMap, indirectHandleMap);
this.resetUBOs();
this.resetTextures();
@@ -286,8 +300,7 @@ export class Pass {
* ```
*/
public getHandle (name: string, offset = 0, targetType = GFXType.UNKNOWN): number | undefined {
let handle = this._handleMap[name];
if (!handle) { return; }
let handle = this._handleMap[name]; if (!handle) { return; }
if (targetType) { handle = customizeType(handle, targetType); }
else if (offset) { handle = customizeType(handle, getTypeFromHandle(handle) - offset); }
return handle + offset;
@@ -315,7 +328,7 @@ export class Pass {
const type = Pass.getTypeFromHandle(handle);
const ofs = Pass.getOffsetFromHandle(handle);
const block = this._blocks[binding];
_type2writer[type](block.view, value, ofs);
type2writer[type](block.view, value, ofs);
block.dirty = true;
}
@@ -330,7 +343,7 @@ export class Pass {
const type = Pass.getTypeFromHandle(handle);
const ofs = Pass.getOffsetFromHandle(handle);
const block = this._blocks[binding];
return _type2reader[type](block.view, out, ofs);
return type2reader[type](block.view, out, ofs);
}
/**
@@ -347,7 +360,7 @@ export class Pass {
let ofs = Pass.getOffsetFromHandle(handle);
for (let i = 0; i < value.length; i++, ofs += stride) {
if (value[i] === null) { continue; }
_type2writer[type](block.view, value[i], ofs);
type2writer[type](block.view, value[i], ofs);
}
block.dirty = true;
}
@@ -422,8 +435,8 @@ export class Pass {
this._bs = new GFXBlendState();
this._dss = new GFXDepthStencilState();
this._rs = new GFXRasterizerState();
this._fillinPipelineInfo(original);
this._fillinPipelineInfo(overrides);
Pass.fillinPipelineInfo(this, original);
Pass.fillinPipelineInfo(this, overrides);
}
/**
@@ -482,7 +495,7 @@ export class Pass {
const cur = u.members[i];
const inf = this._properties[cur.name];
const givenDefault = inf && inf.value;
const value = givenDefault ? givenDefault : _type2default[cur.type];
const value = givenDefault ? givenDefault : type2default[cur.type];
const stride = GFXGetTypeSize(cur.type) >> 2;
for (let j = 0; j < cur.count; j++) { block.view.set(value, ofs + j * stride); }
ofs += stride * cur.count;
@@ -499,7 +512,7 @@ export class Pass {
for (const u of this._shaderInfo.samplers) {
if (isBuiltinBinding(u.binding)) { continue; }
const inf = this._properties[u.name];
const texName = inf && inf.value ? inf.value + '-texture' : _type2default[u.type];
const texName = inf && inf.value ? inf.value + '-texture' : type2default[u.type];
const texture = builtinResMgr.get<TextureBase>(texName);
const textureView = texture && texture.getGFXTextureView();
if (!textureView) { console.warn('illegal texture default value: ' + texName); continue; }
@@ -519,46 +532,67 @@ export class Pass {
* 尝试编译 shader 并获取相关资源引用。
* @param defineOverrides shader 预处理宏定义重载
*/
public tryCompile (defineOverrides?: IDefineMap) {
if (defineOverrides) { Object.assign(this._defines, defineOverrides); }
public tryCompile (defineOverrides?: IDefineMap, saveOverrides = true) {
const pipeline = (cc.director.root as Root).pipeline;
if (!pipeline) { return false; }
if (!pipeline) { return null; }
this._renderPass = pipeline.getRenderPass(this._stage);
if (!this._renderPass) { console.warn(`illegal pass stage.`); return false; }
this._shader = programLib.getGFXShader(this._device, this._programName, this._defines, pipeline);
if (!this._shader) { console.warn(`create shader ${this._programName} failed`); return false; }
this._bindings = this._shaderInfo.blocks.reduce((acc, cur) => {
if (cur.defines.every((d) => this._defines[d])) {
acc.push({ name: cur.name, binding: cur.binding, type: GFXBindingType.UNIFORM_BUFFER });
if (!this._renderPass) { console.warn(`illegal pass stage.`); return null; }
let defines = this._defines;
if (defineOverrides) {
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; }
}
return acc;
}, [] as IGFXBinding[]).concat(this._shaderInfo.samplers.reduce((acc, cur) => {
if (cur.defines.every((d) => this._defines[d])) {
acc.push({ name: cur.name, binding: cur.binding, type: GFXBindingType.SAMPLER });
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; }
}
return acc;
}, [] as IGFXBinding[]));
return true;
lastBinding = sampler.binding;
this._bindings.push(sampler);
}
return shader;
}
/**
* @zh
* 根据当前 pass 持有的信息创建 [[GFXPipelineState]]。
*/
public createPipelineState (): GFXPipelineState | null {
public createPipelineState (defineOverrides?: IDefineMap, stateOverrides?: IPassStates): GFXPipelineState | null {
if ((!this._renderPass || !this._shader || !this._bindings.length) && !this.tryCompile()) {
console.warn(`pass resources not complete, create PSO failed`);
return null;
}
let shader = this._shader!;
if (defineOverrides) { shader = this.tryCompile(defineOverrides, false)!; }
// bind resources
const bindingLayout = this._device.createBindingLayout({ bindings: this._bindings });
for (const b of Object.keys(this._buffers)) {
_blInfo.bindings = this._bindings;
const bindingLayout = this._device.createBindingLayout(_blInfo);
for (const b in this._buffers) {
bindingLayout.bindBuffer(parseInt(b), this._buffers[b]);
}
for (const s of Object.keys(this._samplers)) {
for (const s in this._samplers) {
bindingLayout.bindSampler(parseInt(s), this._samplers[s]);
}
for (const t of Object.keys(this._textureViews)) {
for (const t in this._textureViews) {
bindingLayout.bindTextureView(parseInt(t), this._textureViews[t]);
}
// bind pipeline builtins
@@ -575,20 +609,22 @@ export class Pass {
if (info.sampler) { bindingLayout.bindSampler(info.samplerInfo!.binding, info.sampler); }
bindingLayout.bindTextureView(info.samplerInfo!.binding, info.textureView!);
}
_plInfo.layouts = [bindingLayout];
const pipelineLayout = this._device.createPipelineLayout(_plInfo);
// create pipeline state
const pipelineLayout = this._device.createPipelineLayout({ layouts: [bindingLayout] });
const pipelineState = this._device.createPipelineState({
bs: this._bs,
dss: this._dss,
dynamicStates: this._dynamicStates,
is: new GFXInputState(),
layout: pipelineLayout,
primitive: this._primitive,
renderPass: this._renderPass!,
rs: this._rs,
shader: this._shader!,
});
_psoInfo.primitive = stateOverrides && stateOverrides.primitive || this._primitive;
_psoInfo.shader = shader;
_psoInfo.rasterizerState = stateOverrides && stateOverrides.rasterizerState || this._rs;
_psoInfo.depthStencilState = stateOverrides && stateOverrides.depthStencilState || this._dss;
_psoInfo.blendState = stateOverrides && stateOverrides.blendState || this._bs;
_psoInfo.dynamicStates = stateOverrides && stateOverrides.dynamicStates || this._dynamicStates;
_psoInfo.layout = pipelineLayout;
_psoInfo.renderPass = this._renderPass!;
_psoInfo.program = this._programName;
_psoInfo.defines = defineOverrides || this._defines;
_psoInfo.stage = this._stage;
_psoInfo.hash = Pass.getPSOHash(_psoInfo);
const pipelineState = this._device.createPipelineState(_psoInfo);
this._resources.push({ bindingLayout, pipelineLayout, pipelineState });
return pipelineState;
}
@@ -606,19 +642,6 @@ export class Pass {
}
}
/**
* @zh
* 返回这个 pass 的序列化信息,用于计算 hash。
*/
public serializePipelineStates () {
const shaderKey = programLib.getKey(this._programName, this._defines);
let res = `${shaderKey},${this._stage},${this._primitive}`;
res += serializeBlendState(this._bs);
res += serializeDepthStencilState(this._dss);
res += serializeRasterizerState(this._rs);
return res;
}
/**
* @zh
* 创建合批缓冲。
@@ -629,91 +652,61 @@ export class Pass {
}
}
/**
* @zh
* 销毁合批缓冲。
*/
public destroyBatchedBuffer () {
if (this._batchedBuffer) {
this._batchedBuffer.destroy();
this._batchedBuffer = null;
}
}
/**
* @zh
* 清空合批缓冲。
*/
public clearBatchedBuffer () {
if (this._batchedBuffer) {
const uboLocal = new UBOLocal();
this._batchedBuffer.ubo.update(uboLocal.view.buffer);
this._batchedBuffer.clearUBO();
}
}
protected _fillinPipelineInfo (info: PassOverrides) {
if (info.priority !== undefined) { this._priority = info.priority; }
if (info.primitive !== undefined) { this._primitive = info.primitive; }
if (info.stage !== undefined) { this._stage = info.stage; }
if (info.dynamics !== undefined) { this._dynamicStates = info.dynamics as GFXDynamicState[]; }
if (info.customizations) { this._customizations = info.customizations as string[]; }
if (this._phase === 0) {
const phaseName = info.phase || 'default';
this._phase = getPhaseID(phaseName);
}
const bs = this._bs;
if (info.blendState) {
const bsInfo = Object.assign({}, info.blendState);
if (bsInfo.targets) {
bsInfo.targets.forEach((t, i) => Object.assign(
bs.targets[i] || (bs.targets[i] = new GFXBlendTarget()), t));
}
delete bsInfo.targets;
Object.assign(bs, bsInfo);
}
Object.assign(this._rs, info.rasterizerState);
Object.assign(this._dss, info.depthStencilState);
}
get device () { return this._device; }
get idxInTech () { return this._idxInTech; }
get programName () { return this._programName; }
// states
get priority () { return this._priority; }
get primitive () { return this._primitive; }
get stage () { return this._stage; }
get phase () { return this._phase; }
get bindings () { return this._bindings; }
get blendState () { return this._bs; }
get depthStencilState () { return this._dss; }
get rasterizerState () { return this._rs; }
get dynamics () { return this._dynamics; }
get depthStencilState () { return this._dss; }
get blendState () { return this._bs; }
get dynamicStates () { return this._dynamicStates; }
get customizations () { return this._customizations; }
get shader (): GFXShader { return this._shader!; }
get batchedBuffer (): BatchedBuffer | null { return this._batchedBuffer; }
get phase () { return this._phase; }
// infos
get shaderInfo () { return this._shaderInfo; }
get program () { return this._programName; }
get properties () { return this._properties; }
get defines () { return this._defines; }
get idxInTech () { return this._idxInTech; }
// resources
get device () { return this._device; }
get bindings () { return this._bindings; }
get shader () { return this._shader!; }
get renderPass () { return this._renderPass!; }
get dynamics () { return this._dynamics; }
get batchedBuffer () { return this._batchedBuffer; }
get blocks () { return this._blocks; }
}
const serializeBlendState = (bs: GFXBlendState) => {
function serializeBlendState (bs: GFXBlendState) {
let res = `,bs,${bs.isA2C},${bs.blendColor}`;
for (const t of bs.targets) {
res += `,bt,${t.blend},${t.blendEq},${t.blendAlphaEq},${t.blendColorMask}`;
res += `,${t.blendSrc},${t.blendDst},${t.blendSrcAlpha},${t.blendDstAlpha}`;
}
return res;
};
}
const serializeRasterizerState = (rs: GFXRasterizerState) => {
function serializeRasterizerState (rs: GFXRasterizerState) {
const res = `,rs,${rs.cullMode},${rs.depthBias},${rs.isFrontFaceCCW}`;
return res;
};
}
const serializeDepthStencilState = (dss: GFXDepthStencilState) => {
function serializeDepthStencilState (dss: GFXDepthStencilState) {
let res = `,dss,${dss.depthTest},${dss.depthWrite},${dss.depthFunc}`;
res += `,${dss.stencilTestFront},${dss.stencilFuncFront},${dss.stencilRefFront},${dss.stencilReadMaskFront}`;
res += `,${dss.stencilFailOpFront},${dss.stencilZFailOpFront},${dss.stencilPassOpFront},${dss.stencilWriteMaskFront}`;
res += `,${dss.stencilTestBack},${dss.stencilFuncBack},${dss.stencilRefBack},${dss.stencilReadMaskBack}`;
res += `,${dss.stencilFailOpBack},${dss.stencilZFailOpBack},${dss.stencilPassOpBack},${dss.stencilWriteMaskBack}`;
return res;
};
}
+71 -44
View File
@@ -27,33 +27,45 @@
* @category material
*/
import { IBuiltinInfo, IDefineInfo, IShaderInfo } from '../../assets/effect-asset';
import { GFXBindingType, GFXShaderType } from '../../gfx/define';
import { IBlockInfo, IBuiltinInfo, IDefineInfo, ISamplerInfo, IShaderInfo } from '../../assets/effect-asset';
import { IGFXBinding } from '../../gfx/binding-layout';
import { GFXBindingType, GFXGetTypeSize, GFXShaderType } from '../../gfx/define';
import { GFXAPI, GFXDevice } from '../../gfx/device';
import { GFXShader } from '../../gfx/shader';
import { GFXShader, GFXUniformBlock } from '../../gfx/shader';
import { IInternalBindingDesc, localBindingsDesc } from '../../pipeline/define';
import { RenderPipeline } from '../../pipeline/render-pipeline';
import { IDefineMap } from './pass';
import { genHandle } from './pass-utils';
let _shdID = 0;
interface IDefineRecord extends IDefineInfo {
_map: (value: any) => number;
_offset: number;
}
interface IProgramInfo extends IShaderInfo {
id: number;
interface IBlockInfoRT extends IBlockInfo, IGFXBinding {
size: number;
}
interface ISamplerInfoRT extends ISamplerInfo, IGFXBinding {
}
export interface IProgramInfo extends IShaderInfo {
blocks: IBlockInfoRT[];
samplers: ISamplerInfoRT[];
defines: IDefineRecord[];
handleMap: Record<string, number>;
offsets: number[][];
globalsInited: boolean;
localsInited: boolean;
}
export interface IMacroInfo {
name: string;
value: string;
isDefault: boolean;
}
const getBitCount = (cnt: number) => Math.ceil(Math.log2(Math.max(cnt, 2)));
function getBitCount (cnt: number) {
return Math.ceil(Math.log2(Math.max(cnt, 2)));
}
const mapDefine = (info: IDefineInfo, def: number | string | boolean) => {
function mapDefine (info: IDefineInfo, def: number | string | boolean) {
switch (info.type) {
case 'boolean': return def as boolean ? '1' : '0';
case 'string': return def !== undefined ? def as string : info.options![0];
@@ -61,39 +73,70 @@ const mapDefine = (info: IDefineInfo, def: number | string | boolean) => {
}
console.warn(`unknown define type '${info.type}'`);
return '-1'; // should neven happen
};
}
const prepareDefines = (defs: IDefineMap, tDefs: IDefineInfo[]) => {
function prepareDefines (defs: IDefineMap, tDefs: IDefineInfo[]) {
const macros: IMacroInfo[] = [];
for (const tmpl of tDefs) {
const name = tmpl.name;
const value = mapDefine(tmpl, defs[name]);
macros.push({ name, value });
const v = defs[name];
const value = mapDefine(tmpl, v);
const isDefault = !v || v === '0';
macros.push({ name, value, isDefault });
}
return macros;
};
}
const getShaderInstanceName = (name: string, macros: IMacroInfo[]) => {
return name + macros.reduce((acc, cur) => cur.value !== '0' ? `${acc}|${cur.name}${cur.value}` : acc, '');
};
function getShaderInstanceName (name: string, macros: IMacroInfo[]) {
return name + macros.reduce((acc, cur) => cur.isDefault ? acc : `${acc}|${cur.name}${cur.value}`, '');
}
const insertBuiltinBindings = (tmpl: IProgramInfo, source: Map<string, IInternalBindingDesc>, type: string) => {
function insertBuiltinBindings (tmpl: IProgramInfo, source: Map<string, IInternalBindingDesc>, type: string) {
const target = tmpl.builtins[type] as IBuiltinInfo;
const blocks = tmpl.blocks;
for (const b of target.blocks) {
const info = source.get(b.name);
if (!info || info.type !== GFXBindingType.UNIFORM_BUFFER) { console.warn(`builtin UBO '${b.name}' not available!`); continue; }
const builtin = Object.assign({ defines: b.defines }, info.blockInfo);
const builtin: IBlockInfoRT = Object.assign({
defines: b.defines,
size: getSize(info.blockInfo!),
bindingType: GFXBindingType.UNIFORM_BUFFER,
}, info.blockInfo!);
blocks.push(builtin);
}
const samplers = tmpl.samplers;
for (const s of target.samplers) {
const info = source.get(s.name);
if (!info || info.type !== GFXBindingType.SAMPLER) { console.warn(`builtin sampler '${s.name}' not available!`); continue; }
const builtin = Object.assign({ defines: s.defines }, info.samplerInfo);
const builtin = Object.assign({ defines: s.defines, bindingType: GFXBindingType.SAMPLER }, info.samplerInfo);
samplers.push(builtin);
}
};
}
function getSize (block: GFXUniformBlock) {
return block.members.reduce((s, m) => s + GFXGetTypeSize(m.type) * m.count, 0);
}
function genHandles (tmpl: IProgramInfo) {
const handleMap: Record<string, number> = {};
// block member handles
for (let i = 0; i < tmpl.blocks.length; i++) {
const block = tmpl.blocks[i];
const members = block.members;
let offset = 0;
for (let j = 0; j < members.length; j++) {
const uniform = members[j];
handleMap[uniform.name] = genHandle(GFXBindingType.UNIFORM_BUFFER, block.binding, uniform.type, offset);
offset += (GFXGetTypeSize(uniform.type) >> 2) * uniform.count;
}
}
// sampler handles
for (let i = 0; i < tmpl.samplers.length; i++) {
const sampler = tmpl.samplers[i];
handleMap[sampler.name] = genHandle(GFXBindingType.SAMPLER, sampler.binding, sampler.type);
}
return handleMap;
}
/**
* @zh
@@ -111,31 +154,11 @@ class ProgramLib {
/**
* @zh
* 根据 effect 信息注册 shader 模板。
* @example
* ```typescript
* // this object is auto-generated from your actual shaders
* let program = {
* name: 'foobar',
* glsl1: { vert: '...', frag: '...' },
* glsl3: { vert: '...', frag: '...' },
* defines: [
* { name: 'shadow', type: 'boolean', defines: [] },
* { name: 'lightCount', type: 'number', range: [1, 4], defines: [] }
* ],
* blocks: [{ name: 'Constants', binding: 0, members: [
* { name: 'color', type: 'vec4', count: 1, size: 16 }], defines: [], size: 16 }
* ],
* samplers: [],
* };
* programLib.define(program);
* ```
*/
public define (prog: IShaderInfo) {
const cur = this._templates[prog.name];
if (cur && cur.hash === prog.hash) { return; }
const tmpl = Object.assign({ id: ++_shdID }, prog) as IProgramInfo;
if (!tmpl.localsInited) { insertBuiltinBindings(tmpl, localBindingsDesc, 'locals'); tmpl.localsInited = true; }
const curTmpl = this._templates[prog.name];
if (curTmpl && curTmpl.hash === prog.hash) { return; }
const tmpl = prog as IProgramInfo;
// calculate option mask offset
let offset = 0;
for (const def of tmpl.defines) {
@@ -153,6 +176,10 @@ class ProgramLib {
def._offset = offset;
offset += cnt;
}
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);
if (!tmpl.localsInited) { insertBuiltinBindings(tmpl, localBindingsDesc, 'locals'); tmpl.localsInited = true; }
// store it
this._templates[prog.name] = tmpl;
}
@@ -190,7 +217,7 @@ class ProgramLib {
const offset = tmplDef._offset;
key |= mapped << offset;
}
return `${key.toString(16)}|${tmpl.id}`;
return `${key.toString(16)}|${tmpl.hash}`;
}
/**
+4 -6
View File
@@ -54,11 +54,12 @@ const defaultInfo = [
GFXAddress.WRAP,
GFXAddress.WRAP,
GFXAddress.WRAP,
16,
8,
GFXComparisonFunc.NEVER,
0, 0, 0,
0, 0, 0, 0,
];
const defaultHash = genSamplerHash(defaultInfo);
const gfxInfo: IGFXSamplerInfo = {};
@@ -99,13 +100,10 @@ class SamplerLib {
* @param info 目标 sampler 属性
*/
public getSampler (device: GFXDevice, hash: number) {
if (hash === 0) { hash = defaultHash; }
const cache = this._cache[hash];
if (cache) { return cache; }
if (hash === 0) {
hash = genSamplerHash(defaultInfo);
}
gfxInfo.minFilter = (hash & 3);
gfxInfo.magFilter = ((hash >> 2) & 3);
gfxInfo.mipFilter = ((hash >> 4) & 3);
@@ -117,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 = { r: 0, g: 0, b: 0, a: 0 };
const sampler = this._cache[hash] = device.createSampler(gfxInfo);
return sampler;
@@ -2,8 +2,7 @@
* @hidden
*/
import { GFXFormat } from '../../gfx';
import { GFXBufferTextureCopy, GFXFormatInfos, GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } from '../../gfx/define';
import { GFXBufferTextureCopy, GFXFormat, GFXFormatInfos, GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } from '../../gfx/define';
import { GFXDevice } from '../../gfx/device';
import { GFXTexture } from '../../gfx/texture';
import { GFXTextureView } from '../../gfx/texture-view';
+37
View File
@@ -0,0 +1,37 @@
// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
import { AnimationClip } from '../animation/animation-clip';
import { Mesh, Skeleton } from '../assets';
import { GFXDevice } from '../gfx/device';
import { AnimatedBoundsInfo, JointsAnimationInfo, JointsTexturePool } from './models/skeletal-animation-utils';
export class DataPoolManager {
public jointsTexturePool: JointsTexturePool;
public jointsAnimationInfo: JointsAnimationInfo;
public animatedBoundsInfo: AnimatedBoundsInfo;
constructor (device: GFXDevice) {
this.jointsTexturePool = new JointsTexturePool(device);
this.jointsAnimationInfo = new JointsAnimationInfo(device);
this.animatedBoundsInfo = new AnimatedBoundsInfo();
}
public releaseMesh (mesh: Mesh) {
this.animatedBoundsInfo.releaseMesh(mesh);
}
public releaseSkeleton (skeleton: Skeleton) {
this.jointsTexturePool.releaseSkeleton(skeleton);
this.animatedBoundsInfo.releaseSkeleton(skeleton);
}
public releaseAnimationClip (clip: AnimationClip) {
this.jointsTexturePool.releaseAnimationClip(clip);
this.animatedBoundsInfo.releaseAnimationClip(clip);
}
public clear () {
this.jointsTexturePool.clear();
this.jointsAnimationInfo.clear();
this.animatedBoundsInfo.clear();
}
}
+3 -2
View File
@@ -17,6 +17,7 @@ export { Camera } from './scene/camera';
export { Model } from './scene/model';
export { SkinningModel } from './models/skinning-model';
export * from './models/joints-texture-utils';
export * from './models/skeletal-animation-utils';
import './scene/deprecated';
import './scene/deprecated';
import './ui/render-data';
@@ -1,206 +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.
*/
/**
* @hidden
*/
import { AnimationClip } from '../../animation/animation-clip';
import { SkelAnimDataHub } from '../../animation/skeletal-animation-data-hub';
import { Skeleton } from '../../assets/skeleton';
import { GFXFormat, GFXFormatInfos } from '../../gfx/define';
import { GFXDevice, GFXFeature } from '../../gfx/device';
import { Mat4, Quat, Vec3 } from '../../math';
import { ITextureBufferHandle, TextureBufferPool } from '../core/texture-buffer-pool';
// change here and cc-skinning.inc to use other skinning algorithms
const uploadJointData = uploadJointDataDQS;
export enum JointsMediumType {
NONE, // for non-skinning models only
RGBA8,
RGBA32F,
}
export function selectJointsMediumType (device: GFXDevice) {
if (device.hasFeature(GFXFeature.TEXTURE_FLOAT)) {
return JointsMediumType.RGBA32F;
} else {
return JointsMediumType.RGBA8;
}
}
const id_m4 = Object.freeze(new Mat4());
const m4_1 = new Mat4();
const dq_0 = new Quat();
const dq_1 = new Quat();
const v3_1 = new Vec3();
const qt_1 = new Quat();
const v3_2 = new Vec3();
// negative zeros cannot be decoded correctly at GLSL 100 minimum highp float precision, 1/1024
// and it has a significant effect on the final transformation
function makeStable (n: number) { return n ? n : 0; }
// Linear Blending Skinning
function uploadJointDataLBS (out: Float32Array, base: number, mat: Mat4, firstBone: boolean) {
out[base + 0] = makeStable(mat.m00);
out[base + 1] = makeStable(mat.m01);
out[base + 2] = makeStable(mat.m02);
out[base + 3] = makeStable(mat.m12);
out[base + 4] = makeStable(mat.m04);
out[base + 5] = makeStable(mat.m05);
out[base + 6] = makeStable(mat.m06);
out[base + 7] = makeStable(mat.m13);
out[base + 8] = makeStable(mat.m08);
out[base + 9] = makeStable(mat.m09);
out[base + 10] = makeStable(mat.m10);
out[base + 11] = makeStable(mat.m14);
}
// Dual Quaternion Skinning
function uploadJointDataDQS (out: Float32Array, base: number, mat: Mat4, firstBone: boolean) {
Mat4.toRTS(mat, qt_1, v3_1, v3_2);
// sign consistency
if (firstBone) { Quat.copy(dq_0, qt_1); }
else if (Quat.dot(dq_0, qt_1) < 0) { Quat.multiplyScalar(qt_1, qt_1, -1); }
// conversion
Quat.set(dq_1, v3_1.x, v3_1.y, v3_1.z, 0);
Quat.multiplyScalar(dq_1, Quat.multiply(dq_1, dq_1, qt_1), 0.5);
// upload
out[base + 0] = makeStable(qt_1.x);
out[base + 1] = makeStable(qt_1.y);
out[base + 2] = makeStable(qt_1.z);
out[base + 3] = makeStable(qt_1.w);
out[base + 4] = makeStable(dq_1.x);
out[base + 5] = makeStable(dq_1.y);
out[base + 6] = makeStable(dq_1.z);
out[base + 7] = makeStable(dq_1.w);
out[base + 8] = makeStable(v3_2.x);
out[base + 9] = makeStable(v3_2.y);
out[base + 10] = makeStable(v3_2.z);
}
function roundUpTextureSize (targetLength: number, formatSize: number) {
const minSize = 204;
const formatScale = 4 / Math.sqrt(formatSize);
return Math.ceil(Math.max(minSize * formatScale, targetLength) / 12) * 12;
}
const _jointsFormat = {
[JointsMediumType.RGBA8]: GFXFormat.RGBA8,
[JointsMediumType.RGBA32F]: GFXFormat.RGBA32F,
};
export interface IJointsTextureHandle {
pixelOffset: number;
refCount: number;
hash: number;
handle: ITextureBufferHandle;
}
export class JointsTexturePool {
private _device: GFXDevice;
private _pool: TextureBufferPool;
private _textureBuffers: Map<number, IJointsTextureHandle> = new Map();
private _formatSize = 0;
constructor (device: GFXDevice) {
this._device = device;
this._pool = new TextureBufferPool(device);
}
public initialize (maxChunks: number = 8) {
const format = _jointsFormat[selectJointsMediumType(this._device)];
this._formatSize = GFXFormatInfos[format].size;
const scale = 16 / this._formatSize;
this._pool.initialize({
format,
maxChunks: maxChunks * scale,
roundUpFn: roundUpTextureSize,
});
}
public destroy () {
this._pool.destroy();
}
/**
* 获取默认骨骼贴图
*/
public getDefaultJointsTexture (skeleton?: Skeleton) {
const len = skeleton && skeleton.joints.length || 1;
let texture: IJointsTextureHandle | null = this._textureBuffers.get(len) || null;
if (texture) { texture.refCount++; return texture; }
const handle = this._pool.alloc(len * 12 * Float32Array.BYTES_PER_ELEMENT);
if (!handle) { return null; }
texture = { pixelOffset: handle.start / this._formatSize, refCount: 1, hash: len, handle };
const textureBuffer = new Float32Array(len * 12);
for (let i = 0; i < len; i++) {
uploadJointData(textureBuffer, 12 * i, id_m4, i === 0);
}
this._pool.update(handle, textureBuffer.buffer);
this._textureBuffers.set(len, texture);
return texture;
}
/**
* 获取指定动画片段的骨骼贴图
*/
public getJointsTextureWithAnimation (skeleton: Skeleton, clip: AnimationClip) {
const hash = skeleton.hash ^ clip.hash;
let texture: IJointsTextureHandle | null = this._textureBuffers.get(hash) || null;
if (texture) { texture.refCount++; return texture; }
const frames = clip.keys[0].length;
const bufSize = skeleton.joints.length * 12 * frames;
const handle = this._pool.alloc(bufSize * Float32Array.BYTES_PER_ELEMENT);
if (!handle) { return null; }
texture = { pixelOffset: handle.start / this._formatSize, refCount: 1, hash, handle };
const textureBuffer = new Float32Array(bufSize);
const data = SkelAnimDataHub.getOrExtract(clip);
for (let i = 0; i < skeleton.joints.length; i++) {
const nodeData = data[skeleton.joints[i]];
if (!nodeData || !nodeData.props) { continue; }
const bindpose = skeleton.bindposes[i];
const matrix = nodeData.props.worldMatrix.values;
for (let frame = 0; frame < frames; frame++) {
const m = matrix[frame];
Mat4.multiply(m4_1, m, bindpose);
uploadJointData(textureBuffer, 12 * (frames * i + frame), m4_1, i === 0);
}
}
this._pool.update(handle, textureBuffer.buffer);
this._textureBuffers.set(hash, texture);
return texture;
}
public releaseTexture (texture: IJointsTextureHandle) {
if (--texture.refCount === 0) {
this._pool.free(texture.handle);
this._textureBuffers.delete(texture.hash);
}
}
}
@@ -0,0 +1,449 @@
/*
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.
*/
/**
* @hidden
*/
import { AnimationClip } from '../../animation/animation-clip';
import { SkelAnimDataHub } from '../../animation/skeletal-animation-data-hub';
import { Mesh } from '../../assets/mesh';
import { Skeleton } from '../../assets/skeleton';
import { aabb } from '../../geom-utils';
import { GFXBuffer } from '../../gfx/buffer';
import { GFXAddress, GFXAttributeName, GFXBufferUsageBit, GFXFilter, GFXFormat, GFXFormatInfos, GFXMemoryUsageBit } from '../../gfx/define';
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';
// change here and cc-skinning.chunk to use other skinning algorithms
const uploadJointData = uploadJointDataLBS;
export enum JointsMediumType {
NONE, // for non-skinning models only
RGBA8,
RGBA32F,
}
export function selectJointsMediumType (device: GFXDevice) {
if (device.hasFeature(GFXFeature.TEXTURE_FLOAT)) {
return JointsMediumType.RGBA32F;
} else {
return JointsMediumType.RGBA8;
}
}
const m4_1 = new Mat4();
const dq_0 = new Quat();
const dq_1 = new Quat();
const v3_1 = new Vec3();
const qt_1 = new Quat();
const v3_2 = new Vec3();
// negative zeros cannot be decoded correctly at GLSL 100 minimum highp float precision, 1/1024
// and it has a significant effect on the final transformation
function makeStable (n: number) { return n ? n : 0; }
// Linear Blending Skinning
function uploadJointDataLBS (out: Float32Array, base: number, mat: Mat4, firstBone: boolean) {
out[base + 0] = makeStable(mat.m00);
out[base + 1] = makeStable(mat.m01);
out[base + 2] = makeStable(mat.m02);
out[base + 3] = makeStable(mat.m12);
out[base + 4] = makeStable(mat.m04);
out[base + 5] = makeStable(mat.m05);
out[base + 6] = makeStable(mat.m06);
out[base + 7] = makeStable(mat.m13);
out[base + 8] = makeStable(mat.m08);
out[base + 9] = makeStable(mat.m09);
out[base + 10] = makeStable(mat.m10);
out[base + 11] = makeStable(mat.m14);
}
// Dual Quaternion Skinning
function uploadJointDataDQS (out: Float32Array, base: number, mat: Mat4, firstBone: boolean) {
Mat4.toRTS(mat, qt_1, v3_1, v3_2);
// sign consistency
if (firstBone) { Quat.copy(dq_0, qt_1); }
else if (Quat.dot(dq_0, qt_1) < 0) { Quat.multiplyScalar(qt_1, qt_1, -1); }
// conversion
Quat.set(dq_1, v3_1.x, v3_1.y, v3_1.z, 0);
Quat.multiplyScalar(dq_1, Quat.multiply(dq_1, dq_1, qt_1), 0.5);
// upload
out[base + 0] = makeStable(qt_1.x);
out[base + 1] = makeStable(qt_1.y);
out[base + 2] = makeStable(qt_1.z);
out[base + 3] = makeStable(qt_1.w);
out[base + 4] = makeStable(dq_1.x);
out[base + 5] = makeStable(dq_1.y);
out[base + 6] = makeStable(dq_1.z);
out[base + 7] = makeStable(dq_1.w);
out[base + 8] = makeStable(v3_2.x);
out[base + 9] = makeStable(v3_2.y);
out[base + 10] = makeStable(v3_2.z);
}
function roundUpTextureSize (targetLength: number, formatSize: number) {
const minSize = 204;
const formatScale = 4 / Math.sqrt(formatSize);
return Math.ceil(Math.max(minSize * formatScale, targetLength) / 12) * 12;
}
const _jointsFormat = {
[JointsMediumType.RGBA8]: GFXFormat.RGBA8,
[JointsMediumType.RGBA32F]: GFXFormat.RGBA32F,
};
export const jointsTextureSamplerHash = genSamplerHash([
GFXFilter.POINT,
GFXFilter.POINT,
GFXFilter.NONE,
GFXAddress.CLAMP,
GFXAddress.CLAMP,
GFXAddress.CLAMP,
]);
export interface IJointsTextureHandle {
pixelOffset: number;
refCount: number;
clipHash: number;
skeletonHash: number;
readyToBeDeleted: boolean;
handle: ITextureBufferHandle;
}
export class JointsTexturePool {
private _device: GFXDevice;
private _pool: TextureBufferPool;
private _textureBuffers: Map<number, IJointsTextureHandle> = new Map(); // per skeleton per clip
private _identityBuffer: IJointsTextureHandle | null;
private _maxIdentityJoints = 64;
private _formatSize = 0;
constructor (device: GFXDevice, maxChunks = 8) {
this._device = device;
this._pool = new TextureBufferPool(device);
const format = _jointsFormat[selectJointsMediumType(this._device)];
this._formatSize = GFXFormatInfos[format].size;
const scale = 16 / this._formatSize;
this._pool.initialize({
format,
maxChunks: maxChunks * scale,
roundUpFn: roundUpTextureSize,
});
this._identityBuffer = this._allocIdentityBuffer();
}
public clear () {
this._pool.destroy();
this._textureBuffers.clear();
this._identityBuffer = null;
}
/**
* 获取默认骨骼贴图
*/
public getDefaultJointsTexture (skeleton?: Skeleton) {
const len = skeleton && skeleton.joints.length || 1;
if (len > this._maxIdentityJoints) {
if (this._identityBuffer) {
this._identityBuffer.readyToBeDeleted = true;
this.releaseHandle(this._identityBuffer, false);
}
this._maxIdentityJoints *= 2;
this._identityBuffer = this._allocIdentityBuffer();
}
if (!this._identityBuffer) { return null; }
this._identityBuffer.refCount++;
return this._identityBuffer;
}
/**
* 获取指定动画片段的骨骼贴图
*/
public getJointsTextureWithAnimation (skeleton: Skeleton, clip: AnimationClip) {
const hash = skeleton.hash ^ clip.hash;
let texture: IJointsTextureHandle | null = this._textureBuffers.get(hash) || null;
if (texture) { texture.refCount++; return texture; }
const frames = clip.keys[0].length;
const bufSize = skeleton.joints.length * 12 * frames;
const handle = this._pool.alloc(bufSize * Float32Array.BYTES_PER_ELEMENT);
if (!handle) { return null; }
texture = { pixelOffset: handle.start / this._formatSize, refCount: 1,
skeletonHash: skeleton.hash, clipHash: clip.hash, readyToBeDeleted: false, handle };
const textureBuffer = new Float32Array(bufSize);
const data = SkelAnimDataHub.getOrExtract(clip);
for (let i = 0; i < skeleton.joints.length; i++) {
const nodeData = data[skeleton.joints[i]];
if (!nodeData || !nodeData.props) { continue; }
const bindpose = skeleton.bindposes[i];
const matrix = nodeData.props.worldMatrix.values;
for (let frame = 0; frame < frames; frame++) {
const m = matrix[frame];
Mat4.multiply(m4_1, m, bindpose);
uploadJointData(textureBuffer, 12 * (frames * i + frame), m4_1, i === 0);
}
}
this._pool.update(handle, textureBuffer.buffer);
this._textureBuffers.set(hash, texture);
return texture;
}
public releaseHandle (handle: IJointsTextureHandle, decr = true) {
if (decr && handle.refCount > 0) { handle.refCount--; }
if (!handle.refCount && handle.readyToBeDeleted) {
this._pool.free(handle.handle);
this._textureBuffers.delete(handle.skeletonHash ^ handle.clipHash);
}
}
public releaseSkeleton (skeleton: Skeleton) {
const it = this._textureBuffers.values();
let res = it.next();
while (!res.done) {
if (res.value.skeletonHash === skeleton.hash) {
res.value.readyToBeDeleted = true;
this.releaseHandle(res.value, false);
}
res = it.next();
}
}
public releaseAnimationClip (clip: AnimationClip) {
const it = this._textureBuffers.values();
let res = it.next();
while (!res.done) {
if (res.value.clipHash === clip.hash) {
res.value.readyToBeDeleted = true;
this.releaseHandle(res.value, false);
}
res = it.next();
}
}
private _allocIdentityBuffer (len = this._maxIdentityJoints) {
const handle = this._pool.alloc(len * 12 * Float32Array.BYTES_PER_ELEMENT);
if (!handle) { return null; }
const textureBuffer = new Float32Array(len * 12);
for (let i = 0; i < len; i++) {
uploadJointData(textureBuffer, 12 * i, Mat4.IDENTITY, i === 0);
}
this._pool.update(handle, textureBuffer.buffer);
return { pixelOffset: handle.start / this._formatSize, refCount: 0,
skeletonHash: len, clipHash: 0, readyToBeDeleted: false, handle };
}
}
export interface IAnimInfo {
buffer: GFXBuffer;
data: Float32Array;
dirty: boolean;
}
export class JointsAnimationInfo {
private _pool = new Map<string, IAnimInfo>(); // per node
private _device: GFXDevice;
constructor (device: GFXDevice) {
this._device = device;
}
public create (nodeID: string) {
const res = this._pool.get(nodeID);
if (res) { return res; }
const buffer = this._device.createBuffer({
usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST,
memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE,
size: UBOSkinningAnimation.SIZE,
stride: UBOSkinningAnimation.SIZE,
});
const data = new Float32Array([1, 0, 0, 0]);
buffer.update(data);
const info = { buffer, data, dirty: false };
this._pool.set(nodeID, info);
return info;
}
public destroy (nodeID: string) {
const info = this._pool.get(nodeID);
if (!info) { return; }
info.buffer.destroy();
this._pool.delete(nodeID);
}
public get (nodeID: string) {
return this._pool.get(nodeID) || this.create(-1 as any);
}
public switchClip (info: IAnimInfo, clip: AnimationClip | null) {
info.data[0] = clip ? clip.keys[0].length : 1;
info.data[1] = 0;
info.buffer.update(info.data);
info.dirty = false;
return info;
}
public clear () {
for (const info of this._pool.values()) {
info.buffer.destroy();
}
this._pool.clear();
}
}
const v3_3 = new Vec3();
const v3_4 = new Vec3();
const ab_1 = new aabb();
export class AnimatedBoundsInfo {
private _perJointBoundsPool = new Map<number, Map<number, Array<aabb | null>>>(); // per Mesh per Skeleton
private _fullClipBoundsPool = new Map<number, Map<number, aabb[]>>(); // per Skeleton per AnimationClip
public get (mesh: Mesh, skeleton: Skeleton, clip: AnimationClip) {
const list: aabb[] = this._getFullClipBounds(skeleton, clip) || [];
if (list.length) { return list; }
let perJointBounds = this._getPerJointBounds(mesh, skeleton);
if (!perJointBounds) {
perJointBounds = this.getBoneSpacePerJointBounds(mesh, skeleton);
this._setPerJointBounds(mesh, skeleton, perJointBounds);
}
const frames = clip.keys[0].length;
for (let fid = 0; fid < frames; fid++) {
list.push(new aabb(Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity));
}
const data = SkelAnimDataHub.getOrExtract(clip);
const joints = skeleton.joints;
// per frame bounding box
for (let i = 0; i < joints.length; i++) {
const nodeData = data[joints[i]];
const bound = perJointBounds[i];
if (!bound || !nodeData || !nodeData.props) { continue; }
const matrix = nodeData.props.worldMatrix.values;
for (let fid = 0; fid < frames; fid++) {
const m = matrix[fid];
const info = list[fid];
aabb.transform(ab_1, bound, m);
ab_1.getBoundary(v3_3, v3_4);
Vec3.min(info.center, info.center, v3_3);
Vec3.max(info.halfExtents, info.halfExtents, v3_4);
}
}
for (let fid = 0; fid < frames; fid++) {
const { center, halfExtents } = list[fid];
aabb.fromPoints(list[fid], center, halfExtents);
}
this._setFullClipBounds(skeleton, clip, list);
return list;
}
public getBoneSpacePerJointBounds (mesh: Mesh, skeleton: Skeleton) {
const bounds: Array<aabb | null> = [];
const valid: boolean[] = [];
const bindposes = skeleton.bindposes;
for (let i = 0; i < bindposes.length; i++) {
bounds.push(new aabb(Infinity, Infinity, Infinity, -Infinity, -Infinity, -Infinity));
valid.push(false);
}
for (let p = 0; p < mesh.struct.primitives.length; p++) {
const joints = mesh.readAttribute(p, GFXAttributeName.ATTR_JOINTS);
const weights = mesh.readAttribute(p, GFXAttributeName.ATTR_WEIGHTS);
const positions = mesh.readAttribute(p, GFXAttributeName.ATTR_POSITION);
if (!joints || !weights || !positions) { continue; }
const vertCount = Math.min(joints.length / 4, weights.length / 4, positions.length / 3);
for (let i = 0; i < vertCount; i++) {
Vec3.set(v3_3, positions[3 * i + 0], positions[3 * i + 1], positions[3 * i + 2]);
for (let j = 0; j < 4; ++j) {
const idx = 4 * i + j;
const joint = joints[idx];
if (weights[idx] === 0 || joint >= bindposes.length) { continue; }
Vec3.transformMat4(v3_4, v3_3, bindposes[joint]);
valid[joint] = true;
const b = bounds[joint]!;
Vec3.min(b.center, b.center, v3_4);
Vec3.max(b.halfExtents, b.halfExtents, v3_4);
}
}
}
for (let i = 0; i < bindposes.length; i++) {
const b = bounds[i]!;
if (!valid[i]) { bounds[i] = null; }
else { aabb.fromPoints(b, b.center, b.halfExtents); }
}
return bounds;
}
public clear () {
this._perJointBoundsPool.clear();
this._fullClipBoundsPool.clear();
}
public releaseMesh (mesh: Mesh) {
this._perJointBoundsPool.delete(mesh.hash);
}
public releaseSkeleton (skeleton: Skeleton) {
const it = this._perJointBoundsPool.values();
let res = it.next();
while (!res.done) {
res.value.delete(skeleton.hash);
res = it.next();
}
this._fullClipBoundsPool.delete(skeleton.hash);
}
public releaseAnimationClip (clip: AnimationClip) {
const it = this._fullClipBoundsPool.values();
let res = it.next();
while (!res.done) {
res.value.delete(clip.hash);
res = it.next();
}
}
private _getPerJointBounds (mesh: Mesh, skeleton: Skeleton) {
const m = this._perJointBoundsPool.get(mesh.hash);
return m && m.get(skeleton.hash);
}
private _getFullClipBounds (skeleton: Skeleton, clip: AnimationClip) {
const m = this._fullClipBoundsPool.get(skeleton.hash);
return m && m.get(clip.hash);
}
private _setPerJointBounds (mesh: Mesh, skeleton: Skeleton, bounds: Array<aabb | null>) {
let m = this._perJointBoundsPool.get(mesh.hash);
if (!m) { m = new Map<number, Array<aabb | null>>(); }
m.set(skeleton.hash, bounds);
}
private _setFullClipBounds (skeleton: Skeleton, clip: AnimationClip, bounds: aabb[]) {
let m = this._fullClipBoundsPool.get(skeleton.hash);
if (!m) { m = new Map<number, aabb[]>(); }
m.set(clip.hash, bounds);
}
}
+66 -83
View File
@@ -28,74 +28,26 @@
*/
import { AnimationClip } from '../../animation/animation-clip';
import { Mesh } from '../../assets/mesh';
import { Skeleton } from '../../assets/skeleton';
import { aabb } from '../../geom-utils';
import { GFXBuffer } from '../../gfx/buffer';
import { GFXAddress, GFXBufferUsageBit, GFXFilter, GFXMemoryUsageBit } from '../../gfx/define';
import { GFXBufferUsageBit, GFXMemoryUsageBit } from '../../gfx/define';
import { Vec3 } from '../../math';
import { UBOSkinningAnimation, UBOSkinningTexture, UniformJointsTexture } from '../../pipeline/define';
import { INode } from '../../utils/interfaces';
import { Pass } from '../core/pass';
import { genSamplerHash, samplerLib } from '../core/sampler-lib';
import { samplerLib } from '../core/sampler-lib';
import { Model } from '../scene/model';
import { RenderScene } from '../scene/render-scene';
import { IJointsTextureHandle } from './joints-texture-utils';
export interface IJointsAnimInfo {
buffer: GFXBuffer;
data: Float32Array;
}
export class JointsAnimationInfo {
public static create (nodeID: string) {
const res = JointsAnimationInfo.pool.get(nodeID);
if (res) { return res; }
const buffer = cc.director.root.device.createBuffer({
usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST,
memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE,
size: UBOSkinningAnimation.SIZE,
stride: UBOSkinningAnimation.SIZE,
});
const data = new Float32Array([1, 0, 0, 0]);
buffer.update(data);
const info = { buffer, data };
JointsAnimationInfo.pool.set(nodeID, info);
return info;
}
public static destroy (nodeID: string) {
const info = JointsAnimationInfo.pool.get(nodeID);
if (!info) { return; }
info.buffer.destroy();
JointsAnimationInfo.pool.delete(nodeID);
}
public static switchClip (nodeID: string, clip: AnimationClip | null) {
const info = JointsAnimationInfo.pool.get(nodeID);
if (!info) { return; }
info.data[0] = clip ? clip.keys[0].length : 1;
info.data[1] = 0;
info.buffer.update(info.data);
}
public static get (nodeID: string) {
return JointsAnimationInfo.pool.get(nodeID) || JointsAnimationInfo.create(-1 as any);
}
protected static pool = new Map<string, IJointsAnimInfo>();
}
const jointsTextureSamplerHash = genSamplerHash([
GFXFilter.POINT,
GFXFilter.POINT,
GFXFilter.NONE,
GFXAddress.CLAMP,
GFXAddress.CLAMP,
GFXAddress.CLAMP,
]);
import { IAnimInfo, IJointsTextureHandle, jointsTextureSamplerHash, selectJointsMediumType } from './skeletal-animation-utils';
interface IJointsInfo {
buffer: GFXBuffer | null;
jointsTextureInfo: Float32Array;
texture: IJointsTextureHandle | null;
animInfo: IAnimInfo | null;
boundsInfo: aabb[] | null;
}
export class SkinningModel extends Model {
@@ -104,17 +56,15 @@ export class SkinningModel extends Model {
private _jointsMedium: IJointsInfo;
private _skeleton: Skeleton | null = null;
get worldBounds () {
return this.uploadedAnim ? null : this._worldBounds;
}
private _staticModelBounds: aabb | null = null;
private _mesh: Mesh | null = null;
constructor (scene: RenderScene, node: INode) {
super(scene, node);
this._type = 'skinning';
const jointsTextureInfo = new Float32Array(4);
const texture = this._scene.texturePool.getDefaultJointsTexture();
this._jointsMedium = { buffer: null, jointsTextureInfo, texture };
const texture = this._scene.root.dataPoolManager.jointsTexturePool.getDefaultJointsTexture();
this._jointsMedium = { buffer: null, jointsTextureInfo, texture, animInfo: null, boundsInfo: null };
}
public destroy () {
@@ -125,10 +75,12 @@ export class SkinningModel extends Model {
}
}
public bindSkeleton (skeleton: Skeleton | null, skinningRoot: INode | null) {
public bindSkeleton (skeleton: Skeleton | null, skinningRoot: INode | null, mesh: Mesh | null) {
this._skeleton = skeleton;
if (!skeleton || !skinningRoot) { return; }
this._mesh = mesh;
if (!skeleton || !skinningRoot || !mesh) { return; }
this._transform = skinningRoot;
this._jointsMedium.animInfo = this._scene.root.dataPoolManager.jointsAnimationInfo.get(skinningRoot.uuid);
if (!this._jointsMedium.buffer) {
this._jointsMedium.buffer = this._device.createBuffer({
usage: GFXBufferUsageBit.UNIFORM | GFXBufferUsageBit.TRANSFER_DST,
@@ -137,25 +89,49 @@ export class SkinningModel extends Model {
stride: UBOSkinningTexture.SIZE,
});
}
this.uploadAnimation(this.uploadedAnim);
}
public updateTransform () {
super.updateTransform();
if (!this.uploadedAnim) { return; }
const { animInfo, boundsInfo } = this._jointsMedium;
const skelBound = boundsInfo![animInfo!.data[1]];
const node = this._transform;
if (this._worldBounds) {
// @ts-ignore TS2339
skelBound.transform(node._mat, node._pos, node._rot, node._scale, this._worldBounds);
}
}
// update fid buffer only when visible
public updateUBOs () {
if (!super.updateUBOs()) { return false; }
const info = this._jointsMedium.animInfo!;
if (info.dirty) { info.buffer.update(info.data); info.dirty = false; }
return true;
}
public createBoundingShape (minPos?: Vec3, maxPos?: Vec3) {
super.createBoundingShape(minPos, maxPos);
this._staticModelBounds = this._modelBounds && aabb.clone(this._modelBounds);
}
public uploadAnimation (anim: AnimationClip | null) {
if (!this._skeleton) { return; }
if (!this._skeleton || !this._mesh) { return; }
this.uploadedAnim = anim;
const texture = this.uploadedAnim ?
this._scene.texturePool.getJointsTextureWithAnimation(this._skeleton, this.uploadedAnim) :
this._scene.texturePool.getDefaultJointsTexture(this._skeleton);
JointsAnimationInfo.switchClip(this._transform.uuid, anim);
const resMgr = this._scene.root.dataPoolManager;
const texture = anim ? resMgr.jointsTexturePool.getJointsTextureWithAnimation(this._skeleton, anim) :
resMgr.jointsTexturePool.getDefaultJointsTexture(this._skeleton);
resMgr.jointsAnimationInfo.switchClip(this._jointsMedium.animInfo!, anim);
this._applyJointsTexture(texture);
this._jointsMedium.boundsInfo = anim ? resMgr.animatedBoundsInfo.get(this._mesh, this._skeleton, anim) : null;
this._modelBounds = anim ? this._staticModelBounds : null; // don't calc bounds again in Model
}
protected _applyJointsTexture (texture: IJointsTextureHandle | null) {
if (!texture) { return; }
// we skip freeing the joints texture by default as an aggressive caching strategy
// toggle the following when memory usage becomes more important than stable performance
// const oldTex = this._jointsMedium.texture;
// if (oldTex && oldTex !== texture) { this._scene.texturePool.releaseTexture(oldTex); }
const oldTex = this._jointsMedium.texture;
if (oldTex && oldTex !== texture) { this._scene.root.dataPoolManager.jointsTexturePool.releaseHandle(oldTex); }
this._jointsMedium.texture = texture;
const { buffer, jointsTextureInfo } = this._jointsMedium;
jointsTextureInfo[0] = texture.handle.texture.width;
@@ -166,22 +142,29 @@ export class SkinningModel extends Model {
for (const submodel of this._subModels) {
if (!submodel.psos) { continue; }
for (const pso of submodel.psos) {
pso.pipelineLayout.layouts[0].bindTextureView(UniformJointsTexture.binding, texture.handle.texView);
pso.pipelineLayout.layouts[0].bindSampler(UniformJointsTexture.binding, sampler);
const bindingLayout = pso.pipelineLayout.layouts[0];
bindingLayout.bindTextureView(UniformJointsTexture.binding, texture.handle.texView);
bindingLayout.bindSampler(UniformJointsTexture.binding, sampler);
}
}
for (const pso of this._implantPSOs) {
const bindingLayout = pso.pipelineLayout.layouts[0];
bindingLayout.bindTextureView(UniformJointsTexture.binding, texture.handle.texView);
bindingLayout.bindSampler(UniformJointsTexture.binding, sampler);
bindingLayout.update();
}
}
protected _doCreatePSO (pass: Pass) {
const pso = super._doCreatePSO(pass);
const { buffer, texture } = this._jointsMedium;
const animInfo = JointsAnimationInfo.get(this._transform.uuid);
pso.pipelineLayout.layouts[0].bindBuffer(UBOSkinningTexture.BLOCK.binding, buffer!);
pso.pipelineLayout.layouts[0].bindBuffer(UBOSkinningAnimation.BLOCK.binding, animInfo.buffer);
const pso = super._doCreatePSO(pass, { CC_USE_SKINNING: selectJointsMediumType(this._device) });
const { buffer, texture, animInfo } = this._jointsMedium;
const bindingLayout = pso.pipelineLayout.layouts[0];
bindingLayout.bindBuffer(UBOSkinningTexture.BLOCK.binding, buffer!);
bindingLayout.bindBuffer(UBOSkinningAnimation.BLOCK.binding, animInfo!.buffer);
const sampler = samplerLib.getSampler(this._device, jointsTextureSamplerHash);
if (texture) {
pso.pipelineLayout.layouts[0].bindTextureView(UniformJointsTexture.binding, texture.handle.texView);
pso.pipelineLayout.layouts[0].bindSampler(UniformJointsTexture.binding, sampler);
bindingLayout.bindTextureView(UniformJointsTexture.binding, texture.handle.texView);
bindingLayout.bindSampler(UniformJointsTexture.binding, sampler);
}
return pso;
}
+30 -29
View File
@@ -1,4 +1,5 @@
// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
import { IPassStates } from '../../assets/effect-asset';
import { Material } from '../../assets/material';
import { IRenderingSubmesh } from '../../assets/mesh';
import { aabb } from '../../geom-utils';
@@ -12,7 +13,7 @@ import Pool from '../../memop/pool';
import { IInternalBindingInst, UBOForwardLight, UBOLocal } from '../../pipeline/define';
import { Layers } from '../../scene-graph/layers';
import { INode } from '../../utils/interfaces';
import { Pass } from '../core/pass';
import { IDefineMap, Pass } from '../core/pass';
import { customizationManager } from './customization-manager';
import { RenderScene } from './render-scene';
import { SubModel } from './submodel';
@@ -69,18 +70,10 @@ export class Model {
return this._enabled;
}
/**
* Get the hosting node of this camera
* @returns the hosting node
*/
get node () {
return this._node;
}
/**
* Set the hosting node of this model
* @param {Node} node the hosting node
*/
set node (node: INode) {
this._node = node;
}
@@ -154,23 +147,24 @@ export class Model {
protected _node: INode;
protected _transform: INode;
protected _id: number;
protected _enabled: boolean = false;
protected _enabled = false;
protected _visFlags = Layers.Enum.NONE;
protected _cameraID: number = -1;
protected _userKey: number = -1;
protected _cameraID = -1;
protected _userKey = -1;
protected _worldBounds: aabb | null = null;
protected _modelBounds: aabb | null = null;
protected _subModels: SubModel[] = [];
protected _matPSORecord: Map<Material, GFXPipelineState[]>;
protected _matRefCount: Map<Material, number>;
protected _uboLocal: UBOLocal;
protected _implantPSOs: GFXPipelineState[] = [];
protected _matPSORecord = new Map<Material, GFXPipelineState[]>();
protected _matRefCount = new Map<Material, number>();
protected _uboLocal = new UBOLocal();
protected _localUBO: GFXBuffer | null = null;
protected _localBindings: Map<string, IInternalBindingInst> = new Map<string, IInternalBindingInst>();
protected _inited: boolean = false;
protected _uboUpdated: boolean = false;
protected _castShadow: boolean = false;
protected _isDynamicBatching: boolean = false;
private _transformUpdated: boolean = true;
protected _localBindings = new Map<string, IInternalBindingInst>();
protected _inited = false;
protected _uboUpdated = false;
protected _castShadow = false;
protected _isDynamicBatching = false;
protected _transformUpdated = true;
/**
* Setup a default empty model
@@ -178,12 +172,8 @@ export class Model {
constructor (scene: RenderScene, node: INode) {
this._device = cc.director.root!.device;
this._scene = scene;
this._node = this._transform = node;
this._id = this._scene.generateModelId();
this._transform = this._node = node;
this._matPSORecord = new Map<Material, GFXPipelineState[]>();
this._matRefCount = new Map<Material, number>();
this._uboLocal = new UBOLocal();
}
public destroy () {
@@ -223,7 +213,7 @@ export class Model {
node.updateWorldTransform();
this._transformUpdated = true;
if (this._modelBounds && this._worldBounds) {
// @ts-ignore
// @ts-ignore TS2339
this._modelBounds.transform(node._mat, node._pos, node._rot, node._scale, this._worldBounds);
}
}
@@ -329,6 +319,15 @@ export class Model {
}
}
public insertImplantPSO (pso: GFXPipelineState) {
this._implantPSOs.push(pso);
}
public removeImplantPSO (pso: GFXPipelineState) {
const idx = this._implantPSOs.indexOf(pso);
if (idx >= 0) { this._implantPSOs.splice(idx, 1); }
}
protected createPipelineState (mat: Material): GFXPipelineState[] {
const ret = new Array<GFXPipelineState>(mat.passes.length);
for (let i = 0; i < ret.length; i++) {
@@ -347,8 +346,10 @@ export class Model {
}
}
protected _doCreatePSO (pass: Pass) {
const pso = pass.createPipelineState()!;
protected _doCreatePSO (pass: Pass, defineOverrides?: IDefineMap, stateOverrides?: IPassStates) {
defineOverrides = defineOverrides || {};
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!);
if (this._localBindings.has(UBOForwardLight.BLOCK.name)) {
pso.pipelineLayout.layouts[0].bindBuffer(UBOForwardLight.BLOCK.binding, this._localBindings.get(UBOForwardLight.BLOCK.name)!.buffer!);
+19 -11
View File
@@ -1,6 +1,7 @@
import { EffectAsset } from '../../assets/effect-asset';
import { GFXCommandBuffer } from '../../gfx/command-buffer';
import { aabb, frustum, intersect } from '../../geom-utils';
import { GFXCommandBuffer, IGFXCommandBufferInfo } from '../../gfx/command-buffer';
import { GFXCommandBufferType, GFXStatus } from '../../gfx/define';
import { GFXInputAssembler } from '../../gfx/input-assembler';
import { GFXPipelineState } from '../../gfx/pipeline-state';
@@ -8,7 +9,7 @@ import { Color, Mat4, Quat, Vec3 } from '../../math';
import { CachedArray } from '../../memop/cached-array';
import { IInternalBindingInst, UBOShadow } from '../../pipeline/define';
import { Pass } from '../core/pass';
import { selectJointsMediumType } from '../models/joints-texture-utils';
import { selectJointsMediumType } from '../models/skeletal-animation-utils';
import { SkinningModel } from '../models/skinning-model';
import { DirectionalLight } from './directional-light';
import { Model } from './model';
@@ -17,7 +18,12 @@ import { SphereLight } from './sphere-light';
const _forward = new Vec3(0, 0, -1);
const _v3 = new Vec3();
const _ab = new aabb();
const _qt = new Quat();
const _info: IGFXCommandBufferInfo = {
allocator: null!,
type: GFXCommandBufferType.SECONDARY,
};
export class PlanarShadows {
@@ -150,11 +156,15 @@ export class PlanarShadows {
this._globalBindings.buffer!.update(this.data);
}
public updateCommandBuffers () {
public updateCommandBuffers (frstm: frustum) {
this._cmdBuffs.clear();
if (!this._scene.mainLight.enabled) { return; }
for (const model of this._scene.models) {
if (!model.enabled || !model.node || !model.castShadow) { continue; }
if (model.worldBounds) {
aabb.transform(_ab, model.worldBounds, this._matLight);
if (!intersect.aabb_frustum(_ab, frstm)) { continue; }
}
let pso = this._psoRecord.get(model); let newOne = false;
if (!pso) { pso = this._createPSO(model); this._psoRecord.set(model, pso); newOne = true; }
if (!model.UBOUpdated) { model.updateUBOs(); } // for those outside the frustum
@@ -213,28 +223,26 @@ export class PlanarShadows {
protected _createPSO (model: Model) {
const pass = model instanceof SkinningModel ? this._passSkinning : this._passNormal;
// @ts-ignore
// @ts-ignore TS2445
const pso = model._doCreatePSO(pass);
model.insertImplantPSO(pso); // add back to model to sync binding layouts
pso.pipelineLayout.layouts[0].update();
return pso;
}
protected _destroyPSO (model: Model, pso: GFXPipelineState) {
const pass = model instanceof SkinningModel ? this._passSkinning : this._passNormal;
return pass.destroyPipelineState(pso);
model.removeImplantPSO(pso); pass.destroyPipelineState(pso);
}
protected _createOrReuseCommandBuffer (cb?: GFXCommandBuffer) {
const device = this._scene.root.device;
const info = {
allocator: device.commandAllocator,
type: GFXCommandBufferType.SECONDARY,
};
_info.allocator = device.commandAllocator;
if (cb) {
if (cb.status === GFXStatus.SUCCESS) { cb.destroy(); }
cb.initialize(info);
cb.initialize(_info);
} else {
cb = device.createCommandBuffer(info);
cb = device.createCommandBuffer(_info);
}
return cb;
}
+5 -14
View File
@@ -7,7 +7,6 @@ import { Root } from '../../root';
import { Layers } from '../../scene-graph/layers';
import { Node } from '../../scene-graph/node';
import { INode } from '../../utils/interfaces';
import { JointsTexturePool } from '../models/joints-texture-utils';
import { Ambient } from './ambient';
import { Camera, ICameraInfo } from './camera';
import { DirectionalLight } from './directional-light';
@@ -78,10 +77,6 @@ export class RenderScene {
return this._models;
}
get texturePool () {
return this._texturePool;
}
/**
* @zh
* 获取 raycastAllCanvas 后的检测结果
@@ -111,7 +106,7 @@ export class RenderScene {
* 获取 raycastSingleModel 后的检测结果
*/
get rayResultSingleModel () {
return this.rayResultSingleModel;
return resultSingleModel;
}
public static registerCreateFunc (root: Root) {
@@ -130,7 +125,6 @@ export class RenderScene {
private _spotLights: SpotLight[] = [];
private _models: Model[] = [];
private _modelId: number = 0;
private _texturePool: JointsTexturePool;
constructor (root: Root) {
this._root = root;
@@ -142,12 +136,10 @@ export class RenderScene {
this._ambient = new Ambient(this);
this._skybox = new Skybox(this);
this._planarShadows = new PlanarShadows(this);
this._texturePool = new JointsTexturePool(root.device);
}
public initialize (info: IRenderSceneInfo): boolean {
this._name = info.name;
this._texturePool.initialize();
return true;
}
@@ -158,7 +150,6 @@ export class RenderScene {
this.destroyModels();
this._skybox.destroy();
this._planarShadows.destroy();
this._texturePool.destroy();
}
public createCamera (info: ICameraInfo): Camera {
@@ -272,7 +263,7 @@ export class RenderScene {
* @param mask mask 用于标记所有要检测的层,默认为 Default | UI2D
* @param distance 射线检测的最大距离, 默认为 Infinity
* @returns boolean , 射线是否有击中
* @nete 通过 this.rayResultAll 可以获取到最近的结果
* @note 通过 this.rayResultAll 可以获取到最近的结果
*/
public raycastAll (worldRay: ray, mask = Layers.Enum.DEFAULT | Layers.Enum.UI_2D, distance = Infinity): boolean {
const r_3d = this.raycastAllModels(worldRay, mask, distance);
@@ -300,7 +291,7 @@ export class RenderScene {
* @param mask 用于标记所有要检测的层,默认为 Default
* @param distance 射线检测的最大距离, 默认为 Infinity
* @returns boolean , 射线是否有击中
* @nete 通过 this.rayResultModels 可以获取到最近的结果
* @note 通过 this.rayResultModels 可以获取到最近的结果
*/
public raycastAllModels (worldRay: ray, mask = Layers.Enum.DEFAULT, distance = Infinity): boolean {
pool.reset();
@@ -391,10 +382,10 @@ export class RenderScene {
* @zh
* 传入一条射线检测场景中所有的 Canvas 以及 Canvas 下的 Node
* @param worldRay 世界射线
* @param mask 用于标记所有要检测的层,默认为 UI2D
* @param mask 用于标记所有要检测的层,默认为 UI_2D
* @param distance 射线检测的最大距离, 默认为 Infinity
* @returns boolean , 射线是否有击中
* @nete 通过 this.rayResultCanvas 可以获取到最近的结果
* @note 通过 this.rayResultCanvas 可以获取到最近的结果
*/
public raycastAllCanvas (worldRay: ray, mask = Layers.Enum.UI_2D, distance = Infinity): boolean {
poolUI.reset();
+9 -6
View File
@@ -10,6 +10,7 @@ import { Model } from './model';
import { RenderScene } from './render-scene';
let skybox_mesh: Mesh | null = null;
let skybox_material: Material | null = null;
export class Skybox extends Model {
@@ -23,8 +24,8 @@ export class Skybox extends Model {
set isRGBE (val) {
this._isRGBE = val;
this._material.recompileShaders({ USE_RGBE_CUBEMAP: this._isRGBE });
this.setSubModelMaterial(0, this._material);
skybox_material!.recompileShaders({ USE_RGBE_CUBEMAP: this._isRGBE });
this.setSubModelMaterial(0, skybox_material);
this._updateGlobalBinding();
this._updatePipeline();
}
@@ -47,16 +48,18 @@ export class Skybox extends Model {
protected _isRGBE = false;
protected _useIBL = false;
protected _material = new Material();
protected _globalBinding: IInternalBindingInst;
constructor (scene: RenderScene) {
super(scene, null!);
this._scene = scene;
this._material.initialize({ effectName: 'pipeline/skybox', defines: { USE_RGBE_CUBEMAP: this._isRGBE } });
this._globalBinding = this._scene.root.pipeline.globalBindings.get(UNIFORM_ENVIRONMENT.name)!;
if (!skybox_material) {
skybox_material = new Material();
skybox_material.initialize({ effectName: 'pipeline/skybox', defines: { USE_RGBE_CUBEMAP: this._isRGBE } });
}
if (!skybox_mesh) { skybox_mesh = createMesh(box({ width: 2, height: 2, length: 2 })); }
this.initSubModel(0, skybox_mesh.renderingMesh.getSubmesh(0), this._material);
this.initSubModel(0, skybox_mesh.renderingMesh.getSubmesh(0), skybox_material);
}
protected _updatePipeline () {
@@ -74,7 +77,7 @@ export class Skybox extends Model {
this._globalBinding.textureView = textureView;
// update skybox material, need to do this every time pso is created
// because skybox.updateUBOs is not called in pipeline per frame
const mat = this._material;
const mat = skybox_material!;
mat.passes[0].bindSampler(UNIFORM_ENVIRONMENT.binding, sampler);
mat.passes[0].bindTextureView(UNIFORM_ENVIRONMENT.binding, textureView);
for (const pso of this._matPSORecord.get(mat)!) {
+2 -30
View File
@@ -40,10 +40,6 @@ export class MeshBuffer {
public vb: GFXBuffer | null = null;
public ib: GFXBuffer | null = null;
public ia: GFXInputAssembler | null = null;
// public vbCount: number = 0;
// public vbSize: number = 0;
// public ibCount: number = 0;
// public ibSize: number = 0;
public byteStart: number = 0;
public byteOffset: number = 0;
@@ -93,15 +89,6 @@ export class MeshBuffer {
});
this._reallocBuffer();
// const batch = this._bufferBatchPool.add();
// batch.vb = vb;
// batch.ib = ib;
// batch.ia = ia;
// batch.vf32 = null;
// batch.vui16 = null;
// batch.vbSize = vb.size;
// batch.ibSize = ib.size;
}
public request (vertexCount = 4, indiceCount = 6) {
@@ -140,10 +127,6 @@ export class MeshBuffer {
}
public reset () {
// this._arrOffset = 0;
// this._vb = this._vbArr[0];
// this._ib = this._ibArr[0];
this.byteStart = 0;
this.byteOffset = 0;
this.indiceStart = 0;
@@ -155,17 +138,6 @@ export class MeshBuffer {
}
public destroy () {
// for (const key in this._vbArr) {
// const vb = this._vbArr[key];
// vb.destroy();
// }
// this._vbArr = undefined;
// for (const key in this._ibArr) {
// const ib = this._ibArr[key];
// ib.destroy();
// }
// this._ibArr = undefined;
this.ib!.destroy();
this.vb!.destroy();
this.ia!.destroy();
@@ -198,7 +170,7 @@ export class MeshBuffer {
this._reallocIData(true);
}
private _reallocVData (copyOldData) {
private _reallocVData (copyOldData: boolean) {
let oldVData;
if (this.vData) {
oldVData = new Uint8Array(this.vData.buffer);
@@ -214,7 +186,7 @@ export class MeshBuffer {
}
}
private _reallocIData (copyOldData) {
private _reallocIData (copyOldData: boolean) {
const oldIData = this.iData;
this.iData = new Uint16Array(this._initIDataCount);
+4 -2
View File
@@ -30,6 +30,8 @@
import { Pool, RecyclePool } from '../../memop';
import { Material } from '../../assets';
import { Color } from '../../math';
import { GFXTextureView } from '../../gfx';
import { MeshBuffer } from '../../../ui';
export interface IRenderData {
x: number;
@@ -126,7 +128,7 @@ export class RenderData extends BaseRenderData {
}
}
export class IARenderData extends BaseRenderData {
export class MeshRenderData extends BaseRenderData {
public vData: Float32Array = new Float32Array(256 * 9 * Float32Array.BYTES_PER_ELEMENT);
public iData: Uint16Array = new Uint16Array(256 * 6);
public vertexStart = 0;
@@ -189,7 +191,7 @@ const _dataPool = new Pool(() => {
u: 0,
v: 0,
color: Color.WHITE.clone(),
} as IRenderData;
};
}, 128);
const _pool = new RecyclePool(() => {
+1 -1
View File
@@ -32,7 +32,7 @@ import { GFXPipelineState } from '../../gfx/pipeline-state';
import { Model } from '../scene/model';
import { RenderScene } from '../scene/render-scene';
import { SubModel } from '../scene/submodel';
import { UIDrawBatch } from './ui';
import { UIDrawBatch } from './ui-draw-batch';
export class UIBatchModel extends Model {
+48
View File
@@ -0,0 +1,48 @@
import { UI } from "./ui";
import { Camera } from "../scene/camera";
import { MeshBuffer } from "../../../ui";
import { Model } from "../scene/model";
import { Material } from "../../assets";
import { GFXTextureView, GFXPipelineState } from "../../gfx";
import { INode } from "../../utils/interfaces";
import { GFXBindingLayout } from "../../gfx/binding-layout";
export class UIDrawBatch {
public camera: Camera | null = null;
public bufferBatch: MeshBuffer | null = null;
public model: Model | null = null;
public material: Material | null = null;
public texView: GFXTextureView | null = null;
public firstIdx: number = 0;
public idxCount: number = 0;
public pipelineState: GFXPipelineState | null = null;
public bindingLayout: GFXBindingLayout | null = null;
public useLocalData: INode | null = null;
public isStatic = false;
public destroy (ui: UI) {
if (this.pipelineState) {
ui._getUIMaterial(this.material!).revertPipelineState(this.pipelineState);
this.pipelineState = null;
}
if (this.bindingLayout) {
this.bindingLayout = null;
}
}
public clear (ui: UI) {
if (this.pipelineState) {
ui._getUIMaterial(this.material!).revertPipelineState(this.pipelineState);
this.pipelineState = null;
}
this.camera = null;
this.bufferBatch = null;
this.material = null;
this.texView = null;
this.firstIdx = 0;
this.idxCount = 0;
this.model = null;
this.isStatic = false;
}
}

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