Merge pull request #5623 from cocos-creator/3d-v1.0.1

Merge 3d v1.0.1
This commit is contained in:
pandamicro
2019-10-25 17:08:52 +08:00
committed by GitHub
90 changed files with 1819 additions and 3240 deletions
+2 -2
View File
@@ -92,7 +92,7 @@
}],
"@typescript-eslint/no-misused-new": "error",
"@typescript-eslint/no-misused-promises": "error",
"@typescript-eslint/no-namespace": "error",
"@typescript-eslint/no-namespace": "off",
"@typescript-eslint/no-non-null-assertion": "warn",
"@typescript-eslint/no-parameter-properties": "off",
"@typescript-eslint/no-require-imports": "error",
@@ -108,7 +108,7 @@
"@typescript-eslint/prefer-function-type": "off",
"@typescript-eslint/prefer-includes": "warn",
"@typescript-eslint/prefer-namespace-keyword": "off",
"@typescript-eslint/prefer-readonly": "warn",
"@typescript-eslint/prefer-readonly": "off",
"@typescript-eslint/prefer-regexp-exec": "warn",
"@typescript-eslint/prefer-string-starts-ends-with": "warn",
"@typescript-eslint/promise-function-async": "off",
+2 -2
View File
@@ -1,4 +1,4 @@
Re: cocos-creator/fireball#
Re: cocos-creator/3d-tasks#
Changelog:
*
@@ -13,4 +13,4 @@ Changelog:
- [ ] Document new code with comments in source code based on [API Docs](https://github.com/cocos-creator/fireball#api-docs)
- [ ] Make sure any runtime log information in `cc.log` , `cc.error` or `new Error('')` has been moved into `DebugInfos.js` with an ID, and use `cc.logID(id)` or `new Error(cc._getErrorID(id))` instead.
-->
-->
+1 -3
View File
@@ -13,8 +13,6 @@
"javascript.implicitProjectConfig.experimentalDecorators": true,
"eslint.validate": [
"javascript",
"javascriptreact",
"typescript",
"typescriptreact"
{ "language": "typescript", "autoFix": true },
]
}
+1 -1
View File
@@ -109,7 +109,7 @@ declare type Getter = () => any;
declare type Setter = (value: any) => void;
declare namespace Editor {
function require (str: String): any;
function require (str: string): any;
const isMainProcess: boolean | undefined;
const Utils: any;
const serialize: any;
+23
View File
@@ -0,0 +1,23 @@
interface EXT_color_buffer_float {
}
interface EXT_disjoint_timer_query_webgl2 {
readonly QUERY_COUNTER_BITS_EXT: GLenum;
readonly TIME_ELAPSED_EXT: GLenum;
readonly TIMESTAMP_EXT: GLenum;
readonly GPU_DISJOINT_EXT: GLenum;
queryCounterEXT(query: WebGLQuery, target: GLenum): void;
}
interface WEBGL_texture_storage_multisample {
readonly TEXTURE_2D_MULTISAMPLE: number;
texStorage2DMultisample(
target: GLenum,
samples: GLsizei,
internalformat: GLenum,
width: GLsizei,
height: GLsizei,
fixedsamplelocations: GLboolean): void;
}
+6 -780
View File
@@ -8,133 +8,6 @@
You should specify a valid DOM canvas element.
### 1000
<!-- DEPRECATED -->
cc.ActionManager.addAction(): action must be non-null
### 1001
cocos2d: removeAction: Target not found
### 1002
cc.ActionManager.removeActionByTag(): an invalid tag
### 1003
cc.ActionManager.removeActionByTag(): target must be non-null
### 1004
cc.ActionManager.getActionByTag(): an invalid tag
### 1005
cocos2d : getActionByTag(tag = %s): Action not found
### 1006
[Action step]. override me
### 1007
[Action update]. override me
### 1008
cocos2d: FiniteTimeAction#reverse: Implement me
### 1009
cc.EaseElastic.reverse(): it should be overridden in subclass.
### 1010
cc.IntervalAction: reverse not implemented.
### 1011
cc.ActionInterval.setAmplitudeRate(): it should be overridden in subclass.
### 1012
cc.ActionInterval.getAmplitudeRate(): it should be overridden in subclass.
### 1013
The speed parameter error
### 1014
The repeat parameter error
### 1015
parameters should not be ending with null in Javascript
### 1016
cc.RotateTo.reverse(): it should be overridden in subclass.
### 1017
<!-- DEPRECATED -->
cc.GridAction.getGrid(): it should be overridden in subclass.
### 1018
<!-- DEPRECATED -->
Grid size must be (1,1)
### 1019
Failed to construct, Sequence construction needs two or more actions.
### 1020
Failed to construct, Spawn construction needs two or more actions.
### 1021
cc.Speed.initWithAction(): action must be non nil
### 1022
cc.Follow.initWithAction(): followedNode must be non nil
### 1023
cc.ActionEase.initWithAction(): action must be non nil
### 1024
Invalid configuration. It must at least have one control point
### 1025
cc.Sequence.initWithTwoActions(): arguments must all be non nil
### 1026
cc.RepeatForever.initWithAction(): action must be non null
### 1027
cc.Spawn.initWithTwoActions(): arguments must all be non null
### 1028
cc.ReverseTime.initWithAction(): action must be non null
### 1029
cc.ReverseTime.initWithAction(): the action was already passed in.
### 1030
cc.Animate.initWithAnimation(): animation must be non-NULL
### 1100
Expected 'data' dict, but not found. Config file: %s
@@ -147,19 +20,6 @@ Please load the resource first : %s
cocos2d: Director: Error in gettimeofday
### 1201
cocos2d: Director: unrecognized projection
### 1202
<!-- DEPRECATED -->
cocos2d: Director: unrecognized projection
### 1203
cocos2d: Director: Error in gettimeofday
### 1204
running scene should not null
@@ -248,16 +108,6 @@ The '%s' will be removed in v2.0, please use '%s' instead.
cc.pool is being removed from v2.0, you are getting cc.js.Pool instead
### 1500
<!-- DEPRECATED -->
CCSheduler#scheduleCallback. Callback already scheduled. Updating interval from:%s to %s
### 1501
<!-- DEPRECATED -->
cc.scheduler.scheduleCallbackForTarget(): callback_fn should be non-null.
### 1502
cc.scheduler.scheduleCallbackForTarget(): target should be non-null.
@@ -306,27 +156,6 @@ cc.Scheduler: updateFunc parameter is deprecated in scheduleUpdate function, and
cc.Scheduler: scheduler stopped using `__instanceId` as id since v2.0, you should do Scheduler.enableForTarget(target) before all scheduler API usage on target
### 1600
getZOrder is deprecated. Please use getLocalZOrder instead.
### 1601
setZOrder is deprecated. Please use setLocalZOrder instead.
### 1602
RotationX != RotationY. Don't know which one to return
### 1603
ScaleX != ScaleY. Don't know which one to return
### 1604
<!-- DEPRECATED -->
An Node can't be added as a child of itself.
### 1605
child already added. It can't be added again
@@ -347,44 +176,6 @@ boundingBox is deprecated. Use getBoundingBox instead
argument tag is an invalid tag
### 1610
cocos2d: removeChildByTag(tag = %s): child not found!
### 1611
<!-- DEPRECATED -->
removeAllChildrenWithCleanup is deprecated. Use removeAllChildren instead
### 1612
cc.Node.stopActionBy(): argument tag an invalid tag
### 1613
cc.Node.getActionByTag(): argument tag is an invalid tag
### 1614
resumeSchedulerAndActions is deprecated, please use resume instead.
### 1615
pauseSchedulerAndActions is deprecated, please use pause instead.
### 1616
<!-- DEPRECATED -->
Unknown callback function
### 1617
child must be non-null
### 1618
cc.Node.runAction(): action must be non-null
### 1619
callback function must be non-null
@@ -393,16 +184,6 @@ callback function must be non-null
interval must be positive
### 1621
<!-- DEPRECATED -->
cocos2d: Could not initialize cc.AtlasNode. Invalid Texture.
### 1622
<!-- DEPRECATED -->
_ccsg.Node._requestDirtyFlag: failed to satisfy the request, key (%s) for flag have already been taken
### 1623
Set '%s' to normal node (not persist root node).
@@ -471,25 +252,6 @@ Node's zIndex value can't be smaller than cc.macro.MIN_ZINDEX, setting to the mi
Private node's zIndex can't be set, it will keep cc.macro.MIN_ZINDEX as its value
### 1700
<!-- DEPRECATED -->
cc.AtlasNode.updateAtlasValues(): Shall be overridden in subclasses
### 1701
<!-- DEPRECATED -->
### 1702
<!-- DEPRECATED -->
cocos2d: Could not initialize cc.AtlasNode. Invalid Texture.
### 1703
<!-- DEPRECATED -->
The new text must be String
### 1800
cc._EventListenerKeyboard.checkAvailable(): Invalid EventListenerKeyboard!
@@ -510,30 +272,6 @@ cc._EventListenerAcceleration.checkAvailable(): _onAccelerationEvent must be non
Invalid parameter.
### 2000
Don't call this method if the event is for touch.
### 2100
<!-- DEPRECATED -->
parameters should not be ending with null in Javascript
### 2101
<!-- DEPRECATED -->
Invalid index in MultiplexLayer switchTo message
### 2102
<!-- DEPRECATED -->
Invalid index in MultiplexLayer switchTo message
### 2103
<!-- DEPRECATED -->
cc.Layer.addLayer(): layer should be non-null
### 2200
Resolution not valid
@@ -546,535 +284,19 @@ should set resolutionPolicy
The touches is more than MAX_TOUCHES, nUnusedIndex = %s
### 2400
WebGL error %s
### 2401
<!-- DEPRECATED -->
Too many graphics vertices generated, only 65536 vertices support.
### 2500
<!-- DEPRECATED -->
cocos2d: cc.SpriteFrameAnimationCache: No animations were found in provided dictionary.
### 2501
<!-- DEPRECATED -->
cc.SpriteFrameAnimationCache. Invalid animation format
### 2502
<!-- DEPRECATED -->
cc.SpriteFrameAnimationCache.addAnimations(): File could not be found
### 2503
<!-- DEPRECATED -->
cocos2d: cc.SpriteFrameAnimationCache: Animation '%s' found in dictionary without any frames - cannot add to animation cache.
### 2504
<!-- DEPRECATED -->
cocos2d: cc.SpriteFrameAnimationCache: Animation '%s' refers to frame '%s' which is not currently in the cc.SpriteFrameCache. This frame will not be added to the animation.
### 2505
<!-- DEPRECATED -->
cocos2d: cc.SpriteFrameAnimationCache: None of the frames for animation '%s' were found in the cc.SpriteFrameCache. Animation is not being added to the Animation Cache.
### 2506
<!-- DEPRECATED -->
cocos2d: cc.SpriteFrameAnimationCache: An animation in your dictionary refers to a frame which is not in the cc.SpriteFrameCache. Some or all of the frames for the animation '%s' may be missing.
### 2507
<!-- DEPRECATED -->
cocos2d: CCAnimationCache: Animation '%s' found in dictionary without any frames - cannot add to animation cache.
### 2508
<!-- DEPRECATED -->
cocos2d: cc.SpriteFrameAnimationCache: Animation '%s' refers to frame '%s' which is not currently in the cc.SpriteFrameCache. This frame will not be added to the animation.
### 2509
<!-- DEPRECATED -->
cc.SpriteFrameAnimationCache.addAnimations(): Invalid texture file name
### 2600
<!-- DEPRECATED -->
cc.Sprite.reorderChild(): this child is not in children list
### 2601
<!-- DEPRECATED -->
cc.Sprite.setIgnoreAnchorPointForPosition(): it is invalid in cc.Sprite when using SpriteBatchNode
### 2602
cc.Sprite.setDisplayFrameWithAnimationName(): Frame not found
### 2603
cc.Sprite.setDisplayFrameWithAnimationName(): Invalid frame index
### 2604
setDisplayFrame is deprecated, please use setSpriteFrame instead.
### 2605
<!-- DEPRECATED -->
cc.Sprite._updateBlendFunc(): _updateBlendFunc doesn't work when the sprite is rendered using a cc.CCSpriteBatchNode
### 2606
cc.Sprite.initWithSpriteFrame(): spriteFrame should be non-null
### 2607
cc.Sprite.initWithSpriteFrameName(): spriteFrameName should be non-null
### 2608
%s is null, please check.
### 2609
cc.Sprite.initWithFile(): filename should be non-null
### 2610
cc.Sprite.setDisplayFrameWithAnimationName(): animationName must be non-null
### 2611
<!-- DEPRECATED -->
cc.Sprite.reorderChild(): child should be non-null
### 2612
<!-- DEPRECATED -->
cc.Sprite.addChild(): cc.Sprite only supports cc.Sprites as children when using cc.SpriteBatchNode
### 2613
<!-- DEPRECATED -->
cc.Sprite.addChild(): cc.Sprite only supports a sprite using same texture as children when using cc.SpriteBatchNode
### 2614
cc.Sprite.addChild(): child should be non-null
### 2615
<!-- DEPRECATED -->
cc.Sprite.texture setter: Batched sprites should use the same texture as the batchnode
### 2616
cc.SpriteBatchNode.updateQuadFromSprite(): cc.SpriteBatchNode only supports cc.Sprites as children
### 2617
cc.SpriteBatchNode.insertQuadFromSprite(): cc.SpriteBatchNode only supports cc.Sprites as children
### 2618
cc.SpriteBatchNode.addChild(): cc.SpriteBatchNode only supports cc.Sprites as children
### 2619
cc.SpriteBatchNode.addChild(): cc.Sprite is not using the same texture
### 2620
<!-- DEPRECATED -->
Sprite.initWithTexture(): Argument must be non-nil
### 2621
<!-- DEPRECATED -->
Invalid spriteFrameName
### 2622
<!-- DEPRECATED -->
Invalid argument: cc.Sprite.texture setter expects a cc.Texture2D.
### 2623
cc.SpriteBatchNode.updateQuadFromSprite(): sprite should be non-null
### 2624
<!-- DEPRECATED -->
cc.SpriteBatchNode.insertQuadFromSprite(): sprite should be non-null
### 2625
too many tiles, only 16384 tiles will be show
### 2626
Unrecognized fill type in bar fill
### 2627
Can not generate quad
### 2628
%s does not exist
### 2700
<!-- DEPRECATED -->
cc.SpriteBatchNode.addQuadFromSprite(): SpriteBatchNode only supports cc.Sprites as children
### 2701
<!-- DEPRECATED -->
cocos2d: CCSpriteBatchNode: resizing TextureAtlas capacity from %s to %s.
### 2702
<!-- DEPRECATED -->
cocos2d: WARNING: Not enough memory to resize the atlas
### 2703
<!-- DEPRECATED -->
cc.SpriteBatchNode.addChild(): Child doesn't belong to Sprite
### 2704
<!-- DEPRECATED -->
cc.SpriteBatchNode.addChild(): sprite batch node should contain the child
### 2705
<!-- DEPRECATED -->
cc.SpriteBatchNode.addQuadFromSprite(): child should be non-null
### 2706
<!-- DEPRECATED -->
cc.SpriteBatchNode.addChild(): child should be non-null
### 2707
<!-- DEPRECATED -->
cc.SpriteBatchNode.updateQuadFromSprite(): cc.SpriteBatchNode only supports cc.Sprites as children
### 2708
<!-- DEPRECATED -->
cc.SpriteBatchNode.insertQuadFromSprite(): cc.SpriteBatchNode only supports cc.Sprites as children
### 2709
<!-- DEPRECATED -->
cc.SpriteBatchNode.addChild(): cc.SpriteBatchNode only supports cc.Sprites as children
### 2710
Sprite.initWithTexture(): Argument must be non-nil
### 2711
<!-- DEPRECATED -->
cc.Sprite.addChild(): child should be non-null
### 2712
Invalid spriteFrameName
### 2713
<!-- DEPRECATED -->
Invalid argument: cc.Sprite texture setter expects a cc.Texture2D.
### 2714
<!-- DEPRECATED -->
cc.SpriteBatchNode.updateQuadFromSprite(): sprite should be non-null
### 2715
<!-- DEPRECATED -->
cc.SpriteBatchNode.insertQuadFromSprite(): sprite should be non-null
### 2716
<!-- DEPRECATED -->
cc.SpriteBatchNode.addChild(): child should be non-null
### 2728
<!-- DEPRECATED -->
%s does not exist
### 2800
<!-- DEPRECATED -->
cocos2d: WARNING: originalWidth/Height not found on the cc.SpriteFrame. AnchorPoint won't work as expected. Regenrate the .plist
### 2801
<!-- DEPRECATED -->
cocos2d: WARNING: an alias with name %s already exists
### 2802
<!-- DEPRECATED -->
cocos2d: WARNING: Sprite frame: %s has already been added by another source, please fix name conflit
### 2803
<!-- DEPRECATED -->
cocos2d: cc.SpriteFrameCahce: Frame %s not found
### 2804
<!-- DEPRECATED -->
Please load the resource first : %s
### 2805
<!-- DEPRECATED -->
cc.SpriteFrameCache.addSpriteFrames(): plist should be non-null
### 2806
<!-- DEPRECATED -->
Argument must be non-nil
### 2900
<!-- DEPRECATED -->
cocos2d: Could not open file: %s
### 2901
<!-- DEPRECATED -->
cc.TextureAtlas.insertQuad(): invalid totalQuads
### 2902
<!-- DEPRECATED -->
cc.TextureAtlas.initWithTexture():texture should be non-null
### 2903
<!-- DEPRECATED -->
cc.TextureAtlas.updateQuad(): quad should be non-null
### 2904
<!-- DEPRECATED -->
cc.TextureAtlas.updateQuad(): Invalid index
### 2905
<!-- DEPRECATED -->
cc.TextureAtlas.insertQuad(): Invalid index
### 2906
<!-- DEPRECATED -->
cc.TextureAtlas.insertQuad(): Invalid index + amount
### 2907
<!-- DEPRECATED -->
cc.TextureAtlas.insertQuadFromIndex(): Invalid newIndex
### 2908
<!-- DEPRECATED -->
cc.TextureAtlas.insertQuadFromIndex(): Invalid fromIndex
### 2909
<!-- DEPRECATED -->
cc.TextureAtlas.removeQuadAtIndex(): Invalid index
### 2910
<!-- DEPRECATED -->
cc.TextureAtlas.removeQuadsAtIndex(): index + amount out of bounds
### 2911
<!-- DEPRECATED -->
cc.TextureAtlas.moveQuadsFromIndex(): move is out of bounds
### 2912
<!-- DEPRECATED -->
cc.TextureAtlas.moveQuadsFromIndex(): Invalid newIndex
### 2913
<!-- DEPRECATED -->
cc.TextureAtlas.moveQuadsFromIndex(): Invalid oldIndex
### 3000
<!-- DEPRECATED -->
TextureCache:addPVRTCImage does not support on HTML5
### 3001
<!-- DEPRECATED -->
TextureCache:addPVRTCImage does not support on HTML5
### 3002
textureForKey is deprecated. Please use getTextureForKey instead.
### 3003
<!-- DEPRECATED -->
addPVRImage does not support on HTML5
### 3004
<!-- DEPRECATED -->
cocos2d: Couldn't add UIImage in TextureCache
### 3005
cocos2d: '%s' id=%s %s x %s
### 3006
cocos2d: '%s' id= HTMLCanvasElement %s x %s
### 3007
cocos2d: TextureCache dumpDebugInfo: %s textures, HTMLCanvasElement for %s KB (%s MB)
### 3008
<!-- DEPRECATED -->
cc.Texture.addUIImage(): image should be non-null
### 3009
<!-- DEPRECATED -->
TextureCache: url should be non-null
### 3100
<!-- DEPRECATED -->
initWithETCFile does not support on HTML5
### 3101
<!-- DEPRECATED -->
initWithPVRFile does not support on HTML5
### 3102
<!-- DEPRECATED -->
initWithPVRTCData does not support on HTML5
### 3103
cc.Texture.addImage(): path should be non-null
### 3104
<!-- DEPRECATED -->
cocos2d: cc.Texture2D. Can't create Texture. UIImage is nil
### 3105
<!-- DEPRECATED -->
cocos2d: WARNING: Image (%s x %s) is bigger than the supported %s x %s
### 3106
<!-- DEPRECATED -->
initWithString isn't supported on cocos2d-html5
### 3107
<!-- DEPRECATED -->
initWithETCFile does not support on HTML5
### 3108
<!-- DEPRECATED -->
initWithPVRFile does not support on HTML5
### 3109
<!-- DEPRECATED -->
initWithPVRTCData does not support on HTML5
### 3110
<!-- DEPRECATED -->
bitsPerPixelForFormat: %s, cannot give useful result, it's a illegal pixel format
### 3111
<!-- DEPRECATED -->
cocos2d: cc.Texture2D: Using RGB565 texture since image has no alpha
### 3112
cc.Texture.addImage(): path should be non-null
### 3113
NSInternalInconsistencyException
### 3114
<!-- DEPRECATED -->
SpriteFrame: Failed to load sprite texture '%s'
### 3115
<!-- DEPRECATED -->
Frame Grabber: could not attach texture to framebuffer
### 3116
WebGLRenderingContext.CLAMP_TO_EDGE should be used in NPOT textures
### 3117
Mimpap texture only works in POT textures
### 3118
<!-- DEPRECATED -->
contentSize parameter is deprecated and ignored for cc.Texture2D initWithData function.
textureUtil.addImage(): path should be non-null
### 3119
Lazy init texture with image element failed due to image loading failure: %s
### 3200
<!-- DEPRECATED -->
Missing file: %s
### 3300
Rect width exceeds maximum margin: %s
### 3400
### 3301
Rect height exceeds maximum margin: %s
@@ -1410,6 +632,10 @@ you can declare a texture object directly in properties by using:
browser does not support getters
### 3659
Violation error: extending enumerations shall have non-overlaped member names or member values
### 3700
internal error: _prefab is undefined
File diff suppressed because one or more lines are too long
@@ -28,7 +28,7 @@
import { Filter, PixelFormat } from '../../assets/asset-enum';
import { Material } from '../../assets/material';
import { IMeshStruct, Mesh } from '../../assets/mesh';
import { Mesh } from '../../assets/mesh';
import { Skeleton } from '../../assets/skeleton';
import { Texture2D } from '../../assets/texture-2d';
import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../data/class-decorator';
@@ -256,7 +256,7 @@ export class BatchedSkinningModelComponent extends SkinningModelComponent {
// add batch ID to this temp mesh
// first, update bookkeepping
const newMeshStruct: IMeshStruct = JSON.parse(JSON.stringify(unit.mesh.struct));
const newMeshStruct: Mesh.Struct = JSON.parse(JSON.stringify(unit.mesh.struct));
let newOffset = 0;
for (const vb of newMeshStruct.vertexBundles) {
vb.attributes.push(batch_id);
@@ -346,6 +346,12 @@ export class CameraComponent extends Component {
}
}
set flows (val) {
if (this._camera) {
this._camera.flows = val;
}
}
public onLoad () {
cc.director.on(cc.Director.EVENT_AFTER_SCENE_LAUNCH, this.onSceneChanged, this);
}
@@ -27,11 +27,10 @@
* @category model
*/
import { SkeletalAnimationClip } from '../../animation/skeletal-animation-clip';
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 { director } from '../../director';
import { GFXDevice } from '../../gfx/device';
import { selectJointsMediumType } from '../../renderer/models/joints-texture-utils';
import { SkinningModel } from '../../renderer/models/skinning-model';
@@ -87,7 +86,7 @@ export class SkinningModelComponent extends ModelComponent {
return (this._model as SkinningModel);
}
public uploadAnimation (clip: SkeletalAnimationClip | null) {
public uploadAnimation (clip: AnimationClip | null) {
if (this._model) { (this._model as SkinningModel).uploadAnimation(clip); }
}
@@ -98,7 +97,7 @@ export class SkinningModelComponent extends ModelComponent {
}
protected _onMaterialModified (index: number, material: Material | null) {
const device: GFXDevice = director.root!.device;
const device: GFXDevice = cc.director.root!.device;
const type = selectJointsMediumType(device);
const mat = this.getMaterial(index) || this._getBuiltinMaterial();
mat.recompileShaders({ CC_USE_SKINNING: type });
+6 -5
View File
@@ -1,7 +1,8 @@
import { GFXAttributeName, GFXFormat, GFXFormatInfos, GFXFormatType, GFXPrimitiveMode, IGFXFormatInfo } from '../../gfx/define';
export { find } from '../../scene-graph/find';
import { IMeshStruct, IPrimitive, IVertexBundle, Mesh } from '../../assets/mesh';
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';
@@ -156,7 +157,7 @@ export function createMesh (geometry: IGeometry, out?: Mesh, options?: ICreateMe
writeBuffer(vertexBufferView, channel.data, channel.attribute.format, channel.offset, stride);
}
bufferBlob.setNextAlignment(0);
const vertexBundle: IVertexBundle = {
const vertexBundle: Mesh.VertexBundle = {
attributes,
view: {
offset: bufferBlob.getLength(),
@@ -180,7 +181,7 @@ export function createMesh (geometry: IGeometry, out?: Mesh, options?: ICreateMe
}
// Create primitive.
const primitive: IPrimitive = {
const primitive: Mesh.Submesh = {
primitiveMode: geometry.primitiveMode || GFXPrimitiveMode.TRIANGLE_LIST,
vertexBundelIndices: [0],
};
@@ -229,7 +230,7 @@ export function createMesh (geometry: IGeometry, out?: Mesh, options?: ICreateMe
}
// Create mesh struct.
const meshStruct: IMeshStruct = {
const meshStruct: Mesh.Struct = {
vertexBundles: [vertexBundle],
primitives: [primitive],
};
@@ -471,7 +472,7 @@ export function calculateSkinnedBounds (out: aabb, comp: SkinningModelComponent)
root.getWorldMatrix(m4_1);
const boundList = boneSpaceBoundsManager.use(comp.mesh, skeleton);
const len = skeleton.joints.length;
const data = clip.convertedData;
const data = SkelAnimDataHub.getOrExtract(clip);
const fid = animInfo.data[1];
for (let i = 0; i < len; ++i) {
const bounds = boundList[i];
+94 -98
View File
@@ -3,27 +3,16 @@
* @category animation
*/
import { Asset, SpriteFrame } from '../assets';
import { Asset } from '../assets/asset';
import { SpriteFrame } from '../assets/sprite-frame';
import { ccclass, property } from '../data/class-decorator';
import { errorID } from '../platform/debug';
import binarySearchEpsilon from '../utils/binary-search';
import { AnimCurve, IPropertyCurveData, RatioSampler, CurveValueAdapter } from './animation-curve';
import { WrapMode as AnimationWrapMode } from './types';
import { INode } from '../utils/interfaces';
import { murmurhash2_32_gc } from '../utils/murmurhash2_gc';
import { TargetModifier, HierachyModifier, ComponentModifier, isCustomTargetModifier, PropertyModifier, isPropertyModifier } from './target-modifier';
export interface ITargetCurveData {
modifiers: TargetModifier[];
valueAdapter?: CurveValueAdapter;
data: IPropertyCurveData;
}
interface IAnimationEventData {
frame: number;
func: string;
params: string[];
}
import { AnimCurve, CurveValueAdapter, IPropertyCurveData, RatioSampler } from './animation-curve';
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;
@@ -38,10 +27,6 @@ export interface INodeCurveData {
comps?: IComponentsCurveData;
}
export interface ICurveData {
[path: string]: INodeCurveData;
}
export interface IRuntimeCurve {
/**
* 属性曲线。
@@ -56,7 +41,7 @@ export interface IRuntimeCurve {
/**
* 曲线值适配器。
*/
valueAdapter?: CurveValueAdapter;
valueAdapter?: CurveValueAdapter;
/**
* 曲线采样器。
@@ -73,11 +58,43 @@ export interface IAnimationEventGroup {
events: IAnimationEvent[];
}
export declare namespace AnimationClip {
export interface ICurveData {
[path: string]: INodeCurveData;
}
export type PropertyCurveData = IPropertyCurveData;
export interface ICurve {
modifiers: TargetModifier[];
valueAdapter?: CurveValueAdapter;
data: PropertyCurveData;
}
export interface IEvent {
frame: number;
func: string;
params: string[];
}
export namespace _impl {
type MaybeCompactCurve = Omit<AnimationClip.ICurve, 'data'> & {
data: Omit<AnimationClip.PropertyCurveData, 'values'> & {
values: any[] | CompactValueTypeArray;
};
};
type MaybeCompactKeys = Array<number[] | CompactValueTypeArray>;
}
}
/**
* 动画剪辑。
*/
@ccclass('cc.AnimationClip')
export class AnimationClip extends Asset {
public static preventDeferredLoadDependents = true;
public static WrapMode = AnimationWrapMode;
/**
@@ -109,12 +126,12 @@ export class AnimationClip extends Asset {
clip.curves = [{
modifiers: [
new ComponentModifier('cc.SpriteComponent'),
'spriteFrame'
'spriteFrame',
],
data: {
keys: 0,
values,
}
},
}];
return clip;
@@ -138,43 +155,41 @@ export class AnimationClip extends Asset {
@property
public wrapMode = AnimationWrapMode.Normal;
/**
* @zh 动画包含的事件数据。
*/
@property({visible: false})
public events: AnimationClip.IEvent[] = [];
@property
private _duration = 0;
@property
private _keys: number[][] = [];
@property
private _stepness = 0;
/**
* @zh 动画的曲线数据。
* @deprecated 请转用 `this.curves`
*/
@property
private curveDatas?: ICurveData = {};
private curveDatas?: AnimationClip.ICurveData = {};
@property
private _curves: ITargetCurveData[] = [];
private _curves: AnimationClip.ICurve[] = [];
/**
* @zh 动画包含的事件数据。
*/
@property({visible: false})
public events: IAnimationEventData[] = [];
@property
protected _duration = 0;
@property
protected _keys: number[][] = [];
protected _ratioSamplers: RatioSampler[] = [];
protected _runtimeCurves?: IRuntimeCurve[];
protected _runtimeEvents?: {
private _hash = 0;
private frameRate = 0;
private _ratioSamplers: RatioSampler[] = [];
private _runtimeCurves?: IRuntimeCurve[];
private _runtimeEvents?: {
ratios: number[];
eventGroups: IAnimationEventGroup[];
};
protected frameRate = 0;
@property
protected _stepness = 0;
protected _hash = 0;
private _data: Uint8Array | null = null;
/**
* @zh 动画的周期。
@@ -224,7 +239,7 @@ export class AnimationClip extends Asset {
}
get hash () {
if (!this._hash) { this._hash = murmurhash2_32_gc(JSON.stringify(this._getDeprecatedCurveDatas()), 666); }
if (!this._hash) { this._hash = murmurhash2_32_gc(JSON.stringify(this._curves), 666); }
return this._hash;
}
@@ -237,12 +252,20 @@ export class AnimationClip extends Asset {
delete this._runtimeCurves;
}
/**
* 此动画的数据。
*/
get data () {
return this._data;
}
public onLoaded () {
this.frameRate = this.sample;
this._migrateCurveDatas();
this._decodeCVTAs();
}
public getPropertyCurves (root: INode): ReadonlyArray<IRuntimeCurve> {
public getPropertyCurves (): ReadonlyArray<IRuntimeCurve> {
if (!this._runtimeCurves) {
this._createPropertyCurves();
}
@@ -305,7 +328,7 @@ export class AnimationClip extends Asset {
sampler: this._ratioSamplers[targetCurve.data.keys],
};
});
this._applyStepness();
}
@@ -383,53 +406,26 @@ export class AnimationClip extends Asset {
delete this.curveDatas;
}
private _getDeprecatedCurveDatas () {
const result: ICurveData = {};
for (const curve of this._curves) {
if (curve.modifiers.length === 0 ||
!isCustomTargetModifier(curve.modifiers[0], HierachyModifier)) {
continue;
}
let componentName: string | null = null;
let propertyName: string | undefined;
if (curve.modifiers.length === 2 &&
isPropertyModifier(curve.modifiers[1])) {
propertyName = curve.modifiers[1] as PropertyModifier;
} else if (curve.modifiers.length === 3 &&
isCustomTargetModifier(curve.modifiers[1], ComponentModifier) &&
isPropertyModifier(curve.modifiers[2])) {
componentName = (curve.modifiers[1] as ComponentModifier).component;
propertyName = curve.modifiers[2] as PropertyModifier;
} else {
continue;
}
const path = (curve.modifiers[0] as HierachyModifier).path;
if (!(path in result)) {
result[path] = {};
}
const nodeCurveData = result[path];
let objectCurveData: IObjectCurveData | undefined;
if (componentName) {
if (!('comps' in nodeCurveData)) {
nodeCurveData.comps = {};
}
const componentCurveData = nodeCurveData.comps!;
if (!(componentName in componentCurveData)) {
componentCurveData[componentName] = {};
}
objectCurveData = componentCurveData[componentName];
} else {
if (!('props' in nodeCurveData)) {
nodeCurveData.props = {};
}
objectCurveData = nodeCurveData.props!;
}
objectCurveData[propertyName] = curve.data;
private _decodeCVTAs () {
const binaryBuffer: ArrayBuffer = this._nativeAsset;
if (!binaryBuffer) {
return;
}
const maybeCompressedKeys = this._keys as AnimationClip._impl.MaybeCompactKeys;
for (let iKey = 0; iKey < maybeCompressedKeys.length; ++iKey) {
const keys = maybeCompressedKeys[iKey];
if (keys instanceof CompactValueTypeArray) {
maybeCompressedKeys[iKey] = keys.decompress(binaryBuffer);
}
}
for (let iCurve = 0; iCurve < this._curves.length; ++iCurve) {
const curve = this._curves[iCurve] as AnimationClip._impl.MaybeCompactCurve;
if (curve.data.values instanceof CompactValueTypeArray) {
curve.data.values = curve.data.values.decompress(binaryBuffer);
}
}
return result;
}
}
+12 -13
View File
@@ -29,15 +29,14 @@
import { EventArgumentsOf, EventCallbackOf } from '../event/defines';
import { Node } from '../scene-graph/node';
import { INode } from '../utils/interfaces';
import { AnimationBlendState, PropertyBlendState } from './animation-blend-state';
import { AnimationClip, IRuntimeCurve } from './animation-clip';
import { AnimCurve, RatioSampler, ICurveValueProxy } from './animation-curve';
import { AnimCurve, ICurveValueProxy, RatioSampler } from './animation-curve';
import { additive3D, additiveQuat, BlendFunction } from './blending';
import { Playable } from './playable';
import { WrapMode, WrapModeMask, WrappedInfo } from './types';
import { INode } from '../utils/interfaces';
import { BlendFunction, additive3D, additiveQuat } from './blending';
import { BoundTarget } from './target-modifier';
import { director } from '../director';
import { WrapMode, WrapModeMask, WrappedInfo } from './types';
enum PropertySpecialization {
NodePosition,
@@ -145,7 +144,7 @@ export class ICurveInstance {
get propertyName () { return this._rootTargetProperty || ''; }
get curveDetail() {
get curveDetail () {
return this._curveDetail;
}
}
@@ -384,7 +383,7 @@ export class AnimationState extends Playable {
this.repeatCount = 1;
}
const propertyCurves = clip.getPropertyCurves(root);
const propertyCurves = clip.getPropertyCurves();
for (let iPropertyCurve = 0; iPropertyCurve < propertyCurves.length; ++iPropertyCurve) {
const propertyCurve = propertyCurves[iPropertyCurve];
let samplerSharedGroup = this._samplerSharedGroups.find((value) => value.sampler === propertyCurve.sampler);
@@ -414,7 +413,7 @@ export class AnimationState extends Playable {
for (let i = 0, l = args.length; i < l; i++) {
args[i] = restargs[i];
}
director.getAnimationManager().pushDelayEvent(this, '_emit', args);
cc.director.getAnimationManager().pushDelayEvent(this, '_emit', args);
}
public on<K extends string> (type: K, callback: EventCallbackOf<K, IAnimationEventDefinitionMap>, target?: any): void;
@@ -678,26 +677,26 @@ export class AnimationState extends Playable {
this.setTime(0);
this._delayTime = this._delay;
director.getAnimationManager().addAnimation(this);
cc.director.getAnimationManager().addAnimation(this);
this.emit('play', this);
}
protected onStop () {
if (!this.isPaused) {
director.getAnimationManager().removeAnimation(this);
cc.director.getAnimationManager().removeAnimation(this);
}
this.emit('stop', this);
}
protected onResume () {
director.getAnimationManager().addAnimation(this);
cc.director.getAnimationManager().addAnimation(this);
this.emit('resume', this);
}
protected onPause () {
director.getAnimationManager().removeAnimation(this);
cc.director.getAnimationManager().removeAnimation(this);
this.emit('pause', this);
}
@@ -804,7 +803,7 @@ export class AnimationState extends Playable {
lastIndex += direction;
director.getAnimationManager().pushDelayEvent(this, '_fireEvent', [lastIndex]);
cc.director.getAnimationManager().pushDelayEvent(this, '_fireEvent', [lastIndex]);
} while (lastIndex !== eventIndex && lastIndex > -1 && lastIndex < length);
}
+17 -18
View File
@@ -3,10 +3,9 @@
*/
import { clamp01 } from '../math/utils';
import { remove } from '../utils/array';
import { AnimationState } from './animation-state';
import { Playable } from './playable';
import { remove } from '../utils/array';
import { director } from '../director';
interface IManagedState {
state: AnimationState | null;
@@ -85,7 +84,7 @@ export class CrossFade extends Playable {
}
let target = this._managedStates.find((weightedState) => weightedState.state === state);
if (!target) {
target = { state, reference: 0, };
target = { state, reference: 0 };
if (state) {
state.play();
}
@@ -99,9 +98,20 @@ export class CrossFade extends Playable {
});
}
public clear () {
for (let iManagedState = 0; iManagedState < this._managedStates.length; ++iManagedState) {
const state = this._managedStates[iManagedState].state;
if (state) {
state.stop();
}
}
this._managedStates.length = 0;
this._fadings.length = 0;
}
protected onPlay () {
super.onPlay();
director.getAnimationManager().addCrossFade(this);
cc.director.getAnimationManager().addCrossFade(this);
}
/**
@@ -109,7 +119,7 @@ export class CrossFade extends Playable {
*/
protected onPause () {
super.onPause();
director.getAnimationManager().removeCrossFade(this);
cc.director.getAnimationManager().removeCrossFade(this);
for (let iManagedState = 0; iManagedState < this._managedStates.length; ++iManagedState) {
const state = this._managedStates[iManagedState].state;
if (state) {
@@ -123,7 +133,7 @@ export class CrossFade extends Playable {
*/
protected onResume () {
super.onResume();
director.getAnimationManager().addCrossFade(this);
cc.director.getAnimationManager().addCrossFade(this);
for (let iManagedState = 0; iManagedState < this._managedStates.length; ++iManagedState) {
const state = this._managedStates[iManagedState].state;
if (state) {
@@ -137,18 +147,7 @@ export class CrossFade extends Playable {
*/
protected onStop () {
super.onStop();
director.getAnimationManager().removeCrossFade(this);
cc.director.getAnimationManager().removeCrossFade(this);
this.clear();
}
public clear () {
for (let iManagedState = 0; iManagedState < this._managedStates.length; ++iManagedState) {
const state = this._managedStates[iManagedState].state;
if (state) {
state.stop();
}
}
this._managedStates.length = 0;
this._fadings.length = 0;
}
}
+12 -2
View File
@@ -50,8 +50,8 @@ function makeCubicSplineValueConstructor<T> (
const p0 = this.dataPoint;
const p1 = to.dataPoint;
// dt => t_k+1 - t_k
m0 = scaleFx(m0, this.outTangent, dt);
m1 = scaleFx(m1, to.inTangent, dt);
m0 = scaleFx(m0, this.inTangent, dt);
m1 = scaleFx(m1, to.outTangent, dt);
const t_3 = t * t * t;
const t_2 = t * t;
const f_0 = 2 * t_3 - 3 * t_2 + 1;
@@ -70,6 +70,16 @@ function makeCubicSplineValueConstructor<T> (
}
}
// @ts-ignore TS2367
if (constructorX === Quat) {
const lerp = CubicSplineValueClass.prototype.lerp;
CubicSplineValueClass.prototype.lerp = function (this: CubicSplineValueClass, to: CubicSplineValueClass, t: number, dt: number) {
const result = lerp.call(this, to, t, dt) as Quat;
Quat.normalize(result, result);
return result;
};
}
return CubicSplineValueClass;
}
+2 -2
View File
@@ -14,7 +14,7 @@ export {
} from './animation-state';
export * from './cubic-spline-value';
export * from './animation-component';
export * from './skeletal-animation-clip';
export * from './skeletal-animation-data-hub';
export * from './skeletal-animation-state';
export * from './skeletal-animation-component';
export * from './transform-utils';
@@ -27,4 +27,4 @@ export {
} from './target-modifier';
export * from './curve-value-adapters';
import './deprecated';
import './deprecated';
@@ -31,7 +31,7 @@ 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, ITargetCurveData } from './animation-clip';
import { AnimationClip, IObjectCurveData, IRuntimeCurve } from './animation-clip';
import { IPropertyCurveData } from './animation-curve';
import { ComponentModifier, HierachyModifier, isCustomTargetModifier, isPropertyModifier } from './target-modifier';
@@ -98,7 +98,7 @@ export class SkeletalAnimationClip extends AnimationClip {
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: ITargetCurveData[] = [{
const curves: AnimationClip.Curve[] = [{
modifiers: [
new HierachyModifier(''),
new ComponentModifier('cc.SkeletalAnimationComponent'),
@@ -34,7 +34,7 @@ import { Node } from '../scene-graph/node';
import { INode } from '../utils/interfaces';
import { AnimationClip } from './animation-clip';
import { AnimationComponent } from './animation-component';
import { SkeletalAnimationClip } from './skeletal-animation-clip';
import { SkelAnimDataHub } from './skeletal-animation-data-hub';
import { SkeletalAnimationState } from './skeletal-animation-state';
import { getWorldTransformUntilRoot } from './transform-utils';
@@ -51,6 +51,7 @@ export class Socket {
}
const m4_1 = new Mat4();
const m4_2 = new Mat4();
function collectRecursively (node: INode, prefix = '', out: string[] = []) {
for (let i = 0; i < node.children.length; i++) {
@@ -116,7 +117,7 @@ export class SkeletalAnimationComponent extends AnimationComponent {
}
public querySockets () {
const animPaths = this._defaultClip && Object.keys((this._defaultClip as SkeletalAnimationClip).convertedData).sort().reduce((acc, cur) =>
const animPaths = this._defaultClip && Object.keys(SkelAnimDataHub.getOrExtract(this._defaultClip)).sort().reduce((acc, cur) =>
cur.startsWith(acc[acc.length - 1]) ? acc : (acc.push(cur), acc), [] as string[]) || [];
if (!animPaths.length) { return ['default animation clip missing/invalid']; }
const out: string[] = [];
@@ -138,7 +139,8 @@ export class SkeletalAnimationComponent extends AnimationComponent {
target.name = `${socket.path.substring(socket.path.lastIndexOf('/') + 1)} Socket`;
target.parent = this.node;
getWorldTransformUntilRoot(joint, this.node, m4_1);
target.matrix = m4_1;
Mat4.fromRTS(m4_2, target.rotation, target.position, target.scale);
if (!Mat4.equals(m4_2, m4_1)) { target.matrix = m4_1; }
}
}
for (const stateName of Object.keys(this._nameToState)) {
@@ -164,7 +166,6 @@ export class SkeletalAnimationComponent extends AnimationComponent {
}
protected _doCreateState (clip: AnimationClip, name: string) {
if (!(clip instanceof SkeletalAnimationClip)) { console.warn('non-skeletal clip in skeletal component'); }
const state = super._doCreateState(clip, name) as SkeletalAnimationState;
state.rebuildSocketCurves(this._sockets);
return state;
@@ -0,0 +1,151 @@
/*
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 { Mat4 } from '../math';
import { getClassName } from '../utils/js';
import { AnimationClip, IObjectCurveData } from './animation-clip';
import { IPropertyCurveData } from './animation-curve';
import { ComponentModifier, HierachyModifier, isCustomTargetModifier, isPropertyModifier } from './target-modifier';
type ConvertedData = Record<string, {
props: Record<string, IPropertyCurveData>;
}>;
/**
* 骨骼动画数据转换中心。
*/
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;
}
}
function convertToSkeletalCurves (clip: AnimationClip) {
// tslint:disable-next-line: no-unused-expression
clip.hash; // calculate hash before conversion
const originalKeys = clip.keys;
const convertedData: ConvertedData = {};
clip.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;
}
});
// 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
convertToUniformSample(clip, originalKeys, position);
convertToUniformSample(clip, originalKeys, rotation);
convertToUniformSample(clip, originalKeys, scale);
// transform to world space
convertToWorldSpace(convertedData, path, props);
}
return props._worldMatrix;
},
});
}
const values: number[] = new Array(Math.ceil(clip.sample * clip.duration / clip.speed) + 1);
for (let i = 0; i < values.length; i++) { values[i] = i; }
clip.curves = [{ // leave only frameID animation
modifiers: [
new HierachyModifier(''),
new ComponentModifier(getClassName(cc.SkeletalAnimationComponent)),
'frameID',
],
data: { keys: 0, values, interpolate: false },
}];
clip.keys = [values.map((_, i) => i * clip.speed / clip.sample)];
clip.duration = clip.keys[0][values.length - 1];
return convertedData;
}
function convertToUniformSample (clip: AnimationClip, originalKeys: number[][], curve: IPropertyCurveData) {
const keys = originalKeys[curve.keys]; curve.keys = 0;
const len = clip.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 * clip.speed / clip.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;
}
function convertToWorldSpace (convertedData: ConvertedData, 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 = 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 };
}
@@ -29,11 +29,12 @@
import { SkinningModelComponent } from '../3d/framework/skinning-model-component';
import { Mat4 } from '../math';
import { INode } from '../utils/interfaces';
import { IObjectCurveData } from './animation-clip';
import { AnimCurve } from './animation-curve';
import { AnimationState, ICurveInstance } from './animation-state';
import { SkeletalAnimationClip } from './skeletal-animation-clip';
import { Socket } from './skeletal-animation-component';
import { SkelAnimDataHub } from './skeletal-animation-data-hub';
import { ComponentModifier, HierachyModifier, TargetModifier } from './target-modifier';
import { getPathFromRoot, getWorldTransformUntilRoot } from './transform-utils';
@@ -48,13 +49,18 @@ function isFrameIDCurve (modifiers: TargetModifier[]) {
export class SkeletalAnimationState extends AnimationState {
public initialize (root: INode) {
SkelAnimDataHub.getOrExtract(this.clip);
super.initialize(root);
}
public onPlay () {
super.onPlay();
const comps = this._targetNode!.getComponentsInChildren(SkinningModelComponent);
for (let i = 0; i < comps.length; ++i) {
const comp = comps[i] as SkinningModelComponent;
if (comp.skinningRoot === this._targetNode) {
comp.uploadAnimation(this.clip as SkeletalAnimationClip);
comp.uploadAnimation(this.clip);
}
}
}
@@ -85,7 +91,7 @@ export class SkeletalAnimationState extends AnimationState {
const targetNode = root.getChildByPath(socket.path);
if (!targetNode || !socket.target) { return null; }
const targetPath = socket.path;
const sourceData = (this.clip as SkeletalAnimationClip).convertedData;
const sourceData = SkelAnimDataHub.getOrExtract(this.clip);
// find lowest joint animation
let animPath = targetPath;
let source = sourceData[animPath];
+3 -3
View File
@@ -106,8 +106,8 @@ export class Asset extends RawAsset implements IEventTarget {
* 用于本机资产的可序列化URL。供内部使用。
* @default ""
*/
@property
public _native: string | undefined = '';
@property(cc.String)
public _native: string = '';
private _file: any = null;
@@ -247,7 +247,7 @@ export class Asset extends RawAsset implements IEventTarget {
*/
public _setRawAsset (filename: string, inLibrary: boolean = true) {
if (inLibrary !== false) {
this._native = filename || undefined;
this._native = filename || '';
}
else {
this._native = '/' + filename; // simply use '/' to tag location where is not in the library
+1 -1
View File
@@ -30,7 +30,7 @@
import { ccclass, property } from '../../core/data/class-decorator';
import { murmurhash2_32_gc } from '../../core/utils/murmurhash2_gc';
import { builtinResMgr } from '../3d/builtin';
import { builtinResMgr } from '../3d/builtin/init';
import { RenderableComponent } from '../3d/framework/renderable-component';
import { GFXBindingType } from '../gfx/define';
import { GFXTextureView } from '../gfx/texture-view';
+93 -85
View File
@@ -45,7 +45,6 @@ import { GFXDevice } from '../gfx/device';
import { IGFXAttribute } from '../gfx/input-assembler';
import { Root } from '../root';
import { Asset } from './asset';
import { IBufferView } from './utils/buffer-view';
import { postLoadMesh } from './utils/mesh-utils';
function getIndexStrideCtor (stride: number) {
@@ -57,76 +56,6 @@ function getIndexStrideCtor (stride: number) {
return Uint8Array;
}
/**
* @zh
* 顶点块。顶点块描述了一组**交错排列**(interleaved)的顶点属性并存储了顶点属性的实际数据。<br>
* 交错排列是指在实际数据的缓冲区中,每个顶点的所有属性总是依次排列,并总是出现在下一个顶点的所有属性之前。
*/
export interface IVertexBundle {
/**
* 所有顶点属性的实际数据块。
*/
view: IBufferView;
/**
* 包含的所有顶点属性。
*/
attributes: IGFXAttribute[];
}
/**
* 子网格。子网格由一系列相同类型的图元组成(例如点、线、面等)。
*/
export interface IPrimitive {
/**
* 此子网格引用的顶点块,索引至网格的顶点块数组。
*/
vertexBundelIndices: number[];
/**
* 此子网格的图元类型。
*/
primitiveMode: GFXPrimitiveMode;
/**
* 此子网格使用的索引数据。
*/
indexView?: IBufferView;
/**
* (用于射线检测的)几何信息。
*/
geometricInfo?: {
doubleSided?: boolean;
view: IBufferView;
};
}
/**
* 描述了网格的结构。
*/
export interface IMeshStruct {
/**
* 此网格所有的顶点块。
*/
vertexBundles: IVertexBundle[];
/**
* 此网格的所有子网格。
*/
primitives: IPrimitive[];
/**
* (各分量都)小于等于此网格任何顶点位置的最大位置。
*/
minPosition?: Vec3;
/**
* (各分量都)大于等于此网格任何顶点位置的最小位置。
*/
maxPosition?: Vec3;
}
/**
* 允许存储索引的数组视图。
*/
@@ -253,16 +182,95 @@ export class RenderingMesh {
}
}
export interface IMeshCreateInfo {
/**
* 网格结构。
*/
struct: IMeshStruct;
export declare namespace Mesh {
export interface BufferView {
offset: number;
length: number;
count: number;
stride: number;
}
/**
* 网格二进制数据。
* @zh
* 顶点块。顶点块描述了一组**交错排列**(interleaved)的顶点属性并存储了顶点属性的实际数据。<br>
* 交错排列是指在实际数据的缓冲区中,每个顶点的所有属性总是依次排列,并总是出现在下一个顶点的所有属性之前。
*/
data: Uint8Array;
export interface VertexBundle {
/**
* 所有顶点属性的实际数据块。
*/
view: BufferView;
/**
* 包含的所有顶点属性。
*/
attributes: IGFXAttribute[];
}
/**
* 子网格。子网格由一系列相同类型的图元组成(例如点、线、面等)。
*/
export interface Submesh {
/**
* 此子网格引用的顶点块,索引至网格的顶点块数组。
*/
vertexBundelIndices: number[];
/**
* 此子网格的图元类型。
*/
primitiveMode: GFXPrimitiveMode;
/**
* 此子网格使用的索引数据。
*/
indexView?: BufferView;
/**
* (用于射线检测的)几何信息。
*/
geometricInfo?: {
doubleSided?: boolean;
view: BufferView;
};
}
/**
* 描述了网格的结构。
*/
export interface Struct {
/**
* 此网格所有的顶点块。
*/
vertexBundles: VertexBundle[];
/**
* 此网格的所有子网格。
*/
primitives: Submesh[];
/**
* (各分量都)小于等于此网格任何顶点位置的最大位置。
*/
minPosition?: Vec3;
/**
* (各分量都)大于等于此网格任何顶点位置的最小位置。
*/
maxPosition?: Vec3;
}
export interface CreateInfo {
/**
* 网格结构。
*/
struct: Mesh.Struct;
/**
* 网格二进制数据。
*/
data: Uint8Array;
}
}
/**
@@ -336,7 +344,7 @@ export class Mesh extends Asset {
}
@property
private _struct: IMeshStruct = {
private _struct: Mesh.Struct = {
vertexBundles: [],
primitives: [],
};
@@ -458,7 +466,7 @@ export class Mesh extends Asset {
* @param data 新的数据。
* @deprecated 将在 V1.0.0 移除,请转用 `this.reset()`。
*/
public assign (struct: IMeshStruct, data: Uint8Array) {
public assign (struct: Mesh.Struct, data: Uint8Array) {
this.reset({
struct,
data,
@@ -469,7 +477,7 @@ export class Mesh extends Asset {
* 重置此网格。
* @param info 网格重置选项。
*/
public reset (info: IMeshCreateInfo) {
public reset (info: Mesh.CreateInfo) {
this.destroyRenderingMesh();
this._struct = info.struct;
this._data = info.data;
@@ -535,7 +543,7 @@ export class Mesh extends Asset {
let dstAttrView: Uint8Array;
let hasAttr = false;
const vertexBundles = new Array<IVertexBundle>(this._struct.vertexBundles.length);
const vertexBundles = new Array<Mesh.VertexBundle>(this._struct.vertexBundles.length);
for (let i = 0; i < this._struct.vertexBundles.length; ++i) {
const bundle = this._struct.vertexBundles[i];
const dstBundle = mesh._struct.vertexBundles[i];
@@ -600,7 +608,7 @@ export class Mesh extends Asset {
let srcIBView: Uint8Array | Uint16Array | Uint32Array;
let dstIBView: Uint8Array | Uint16Array | Uint32Array;
const primitives: IPrimitive[] = new Array<IPrimitive>(this._struct.primitives.length);
const primitives: Mesh.Submesh[] = new Array<Mesh.Submesh>(this._struct.primitives.length);
for (let i = 0; i < this._struct.primitives.length; ++i) {
const prim = this._struct.primitives[i];
const dstPrim = mesh._struct.primitives[i];
@@ -704,7 +712,7 @@ export class Mesh extends Asset {
}
// Create mesh struct.
const meshStruct: IMeshStruct = {
const meshStruct: Mesh.Struct = {
vertexBundles,
primitives,
minPosition: this._struct.minPosition,
@@ -1024,7 +1032,7 @@ export class Mesh extends Asset {
private _accessAttribute (
primitiveIndex: number,
attributeName: GFXAttributeName,
accessor: (vertexBundle: IVertexBundle, iAttribute: number) => void) {
accessor: (vertexBundle: Mesh.VertexBundle, iAttribute: number) => void) {
if (!this._data ||
primitiveIndex >= this._struct.primitives.length) {
return;
+1 -1
View File
@@ -603,7 +603,7 @@ export class SpriteFrame extends Asset {
}
if (maxY > texture.height) {
cc.errorID(3400, this.name + '/' + texture.name, maxY, texture.height);
cc.errorID(3301, this.name + '/' + texture.name, maxY, texture.height);
return false;
}
-31
View File
@@ -1,31 +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.
*/
export interface IBufferView {
offset: number;
length: number;
count: number;
stride: number;
}
@@ -139,8 +139,14 @@ export class UIComponent extends Component {
const bComp = b._uiComp;
const ca = aComp ? aComp.priority : 0;
const cb = bComp ? bComp.priority : 0;
return ca - cb;
const diff = ca - cb;
if(diff === 0){
return a.getSiblingIndex() - b.getSiblingIndex();
}
return diff;
});
this.node.parent!._updateSiblingIndex();
}
}
@@ -42,7 +42,7 @@ const _vec2b = new Vec2();
const _mat4_temp = new Mat4();
const _matrix = new Mat4();
const _worldMatrix = new Mat4();
const _rect = new Rect();
/**
* @zh
* UI 变换组件。
@@ -351,7 +351,7 @@ export class UITransformComponent extends Component {
/**
* @zh
* 将一个 UI 节点世界坐标系下点转换到另一个 UI 节点 (局部) 空间坐标系,这个坐标系以锚点为原点。
* 非 UI 节点转换到 UI 节点(局部) 空间坐标系,请走 `cc.pipelineUtils.ConvertWorldToUISpaceAR`。
* 非 UI 节点转换到 UI 节点(局部) 空间坐标系,请走 `cc.pipelineUtils.WorldNode3DToLocalNodeUI`。
*
* @param worldPoint - 世界坐标点。
* @param out - 转换后坐标。
@@ -477,16 +477,26 @@ export class UITransformComponent extends Component {
}
/**
* @en
* compute the corresponding aabb in world space for raycast
* @zh
* 计算出此 UI_2D 节点在世界空间下的 aabb 包围盒
*/
public getComputeAABB (out?: aabb) {
const rectWorld = this.getBoundingBoxToWorld();
const px = rectWorld.center.x;
const py = rectWorld.center.y;
const width = this._contentSize.width;
const height = this._contentSize.height;
_rect.set(
-this._anchorPoint.x * width,
-this._anchorPoint.y * height,
width,
height);
_rect.transformMat4(this.node.worldMatrix);
const px = _rect.x + _rect.width * 0.5;
const py = _rect.y + _rect.height * 0.5;;
const pz = this.node.worldPosition.z;
const w = rectWorld.width / 2;
const h = rectWorld.height / 2;
const l = 0.01;
const w = _rect.width / 2;
const h = _rect.height / 2;
const l = 0.001;
if (out != null) {
aabb.set(out, px, py, pz, w, h, l);
} else {
+2 -1
View File
@@ -31,7 +31,8 @@ import * as _decorator from './class-decorator';
cc._decorator = _decorator;
export { _decorator };
export { default as CCClass } from './class';
export { CCObject } from './object';
export { CCObject, isValid } from './object';
export { default as deserialize } from './deserialize';
export { default as instantiate } from './instantiate';
export { CCInteger, CCFloat, CCBoolean, CCString} from './utils/attribute';
export { CompactValueTypeArray } from './utils/compact-value-type-array';
+7 -5
View File
@@ -534,11 +534,12 @@ js.value(CCObject, 'Flags', {
* 如果希望判断当前帧是否调用过 `destroy`,请使用 `cc.isValid(obj, true)`,不过这往往是特殊的业务需求引起的,通常情况下不需要这样。
*
* @method isValid
* @param {any} value
* @param {Boolean} [strictMode=false] - If true, Object called destroy() in this frame will also treated as invalid.
* @return {Boolean} whether is valid
* @param value
* @param [strictMode=false] - If true, Object called destroy() in this frame will also treated as invalid.
* @return whether is valid
* @example
* ```
* import * as cc from 'cc';
* var node = new cc.Node();
* cc.log(cc.isValid(node)); // true
* node.destroy();
@@ -547,14 +548,15 @@ js.value(CCObject, 'Flags', {
* cc.log(cc.isValid(node)); // false, destroyed in the end of last frame
* ```
*/
cc.isValid = (value, strictMode) => {
export function isValid (value: any, strictMode?: boolean) {
if (typeof value === 'object') {
return !!value && !(value._objFlags & (strictMode ? (Destroyed | ToDestroy) : Destroyed));
}
else {
return typeof value !== 'undefined';
}
};
}
cc.isValid = isValid;
if (CC_EDITOR || CC_TEST) {
js.value(CCObject, '_willDestroy', (obj) => {
@@ -0,0 +1,209 @@
import { ccclass, property } from '../class-decorator';
import { Vec3, Quat, Vec4, Vec2 } from '../../math';
export enum StorageUnit {
Uint8, Uint16, Uint32,
Int8, Int16, Int32,
Float32, Float64,
}
export enum ElementType {
Scalar,
Vec2,
Vec3,
Vec4,
Quat,
}
const elementTypeBits = 3;
export type StorageUnitElementType = number;
export function combineStorageUnitElementType (unit: StorageUnit, elementType: ElementType) {
return (elementType << elementTypeBits) + unit;
}
export function extractStorageUnitElementType (combined: StorageUnitElementType) {
return {
storageUnit: ~(-1 << elementTypeBits) & combined,
elementType: combined >> elementTypeBits,
};
}
@ccclass('cc.CompactValueTypeArray')
export class CompactValueTypeArray {
public static StorageUnit = StorageUnit;
public static ElementType = ElementType;
/**
* Offset into buffer, in bytes.
*/
@property
private _byteOffset = 0;
/**
* Unit count this CVTA occupies.
*/
@property
private _unitCount = 0;
/**
* Element type this CVTA holds.
*/
@property
private _unitElement = combineStorageUnitElementType(StorageUnit.Uint8, ElementType.Scalar);
/**
* Element count this CVTA holds.
*/
@property
private _length = 0;
/**
* Returns the length in bytes that a buffer needs to encode the specified value array in form of CVTA.
* @param values The value array.
* @param unit Target element type.
*/
public static lengthFor (values: any[], elementType: ElementType, unit: StorageUnit): number {
const elementTraits = getElementTraits(elementType);
return elementTraits.requiredUnits * values.length * getStorageConstructor(unit).BYTES_PER_ELEMENT;
}
/**
* Compresses the specified value array in form of CVTA into target buffer.
* @param values The value array.
* @param unit Target element type.
* @param arrayBuffer Target buffer.
* @param byteOffset Offset into target buffer.
*/
public static compress (values: any[], elementType: ElementType, unit: StorageUnit, arrayBuffer: ArrayBuffer, byteOffset: number, presumedByteOffset: number): CompactValueTypeArray {
const elementTraits = getElementTraits(elementType);
const storageConstructor = getStorageConstructor(unit);
const unitCount = elementTraits.requiredUnits * values.length;
const storage = new storageConstructor(arrayBuffer, byteOffset, unitCount);
for (let i = 0; i < values.length; ++i) {
elementTraits.compress(storage, i, values[i]);
}
const result = new CompactValueTypeArray();
result._unitElement = combineStorageUnitElementType(unit, elementType);
result._byteOffset = presumedByteOffset;
result._unitCount = unitCount;
result._length = values.length;
return result;
}
/**
* Decompresses this CVTA.
* @param arrayBuffer The buffer this CVTA stored in.
*/
public decompress<T> (arrayBuffer: ArrayBuffer): T[] {
const { storageUnit, elementType } = extractStorageUnitElementType(this._unitElement);
const elementTraits = getElementTraits(elementType);
const storageConstructor = getStorageConstructor(storageUnit);
const storage = new storageConstructor(arrayBuffer, this._byteOffset, this._unitCount);
const result = new Array<T>(this._length);
for (let i = 0; i < this._length; ++i) {
result[i] = elementTraits.decompress(storage, i);
}
return result;
}
}
function getElementTraits (elementType: ElementType) {
return BuiltinElementTypeTraits[elementType];
}
function getStorageConstructor (unit: StorageUnit) {
switch (unit) {
case StorageUnit.Uint8:
return Uint8Array;
case StorageUnit.Uint16:
return Uint16Array;
case StorageUnit.Uint32:
return Uint32Array;
case StorageUnit.Int8:
return Int8Array;
case StorageUnit.Int16:
return Int16Array;
case StorageUnit.Int32:
return Int32Array;
case StorageUnit.Float32:
return Float32Array;
case StorageUnit.Float64:
return Float64Array;
}
}
interface CompactTraits {
requiredUnits: number;
compress (storage: CompactValueTypeArrayStorage, index: number, value: any): void;
decompress (storage: CompactValueTypeArrayStorage, index: number): any;
}
const BuiltinElementTypeTraits: Record<ElementType, CompactTraits> = {
[ElementType.Scalar]: {
requiredUnits: 1,
compress (storage: CompactValueTypeArrayStorage, index: number, value: number) {
storage[index] = value;
},
decompress (storage: CompactValueTypeArrayStorage, index: number) {
return storage[index];
}
},
[ElementType.Vec2]: {
requiredUnits: 2,
compress (storage: CompactValueTypeArrayStorage, index: number, value: Vec2) {
storage[index * 2] = value.x;
storage[index * 2 + 1] = value.y;
},
decompress (storage: CompactValueTypeArrayStorage, index: number) {
return new Vec3(storage[index * 2], storage[index * 2 + 1]);
}
},
[ElementType.Vec3]: {
requiredUnits: 3,
compress (storage: CompactValueTypeArrayStorage, index: number, value: Vec3) {
storage[index * 3] = value.x;
storage[index * 3 + 1] = value.y;
storage[index * 3 + 2] = value.z;
},
decompress (storage: CompactValueTypeArrayStorage, index: number) {
return new Vec3(storage[index * 3], storage[index * 3 + 1], storage[index * 3 + 2]);
}
},
[ElementType.Vec4]: {
requiredUnits: 4,
compress (storage: CompactValueTypeArrayStorage, index: number, value: Vec4) {
storage[index * 4] = value.x;
storage[index * 4 + 1] = value.y;
storage[index * 4 + 2] = value.z;
storage[index * 4 + 3] = value.w;
},
decompress (storage: CompactValueTypeArrayStorage, index: number) {
return new Vec4(storage[index * 4], storage[index * 4 + 1], storage[index * 4 + 2], storage[index * 4 + 3]);
}
},
[ElementType.Quat]: {
requiredUnits: 4,
compress (storage: CompactValueTypeArrayStorage, index: number, value: Quat) {
storage[index * 4] = value.x;
storage[index * 4 + 1] = value.y;
storage[index * 4 + 2] = value.z;
storage[index * 4 + 3] = value.w;
},
decompress (storage: CompactValueTypeArrayStorage, index: number) {
return new Quat(storage[index * 4], storage[index * 4 + 1], storage[index * 4 + 2], storage[index * 4 + 3]);
}
},
};
interface CompactValueTypeArrayStorage {
readonly length: number;
[n: number]: number;
}
export function isCompactValueTypeArray (value: any): value is CompactValueTypeArray {
return value instanceof CompactValueTypeArray;
}
+48
View File
@@ -0,0 +1,48 @@
import { errorID } from '../../platform/debug';
/**
* @zh
* 组合任意多个枚举。
* 此函数的行为等价于返回了一个新的枚举,其成员囊括了所有源枚举的成员。
* 这些枚举的成员必须各不相同(包括成员名和值),否则行为是未定义的。
* @en
* Combine arbitray number of enumerations.
* It behaves like an enumeration having members that is a combination of members of the source enumerations
* is returned.
* These enumerations shall have non-overlaped member names or member values.
* If not, the behavior is undefined.
* @example
* ```ts
* enum Apple { apple = 'apple', }
* enum Pen { pen = 'pen' }
* // As if `enum ApplePen { apple = 'apple'; pen = 'pen'; }`
* const ApplePen = extendsEnum(Apple, Pen);
* ```
*/
export function extendsEnum (): {};
export function extendsEnum<E0> (e0: E0): E0;
export function extendsEnum<E0, E1> (e0: E0, e1: E1): E0 & E1;
export function extendsEnum<E0, E1, E2> (e0: E0, e1: E1, e2: E2): E0 & E1 & E2;
export function extendsEnum<E0, E1, E2, E3> (e0: E0, e1: E1, e2: E2, e3: E3): E0 & E1 & E2 & E3;
export function extendsEnum (...enums: any[]): any {
if (CC_DEV) {
const kvs: PropertyKey[] = [];
for (const e of enums) {
for (const kv of Object.keys(e)) {
if (kvs.indexOf(kv) >= 0) {
errorID(3659);
} else {
kvs.push(kv);
}
}
}
}
return Object.assign({}, ...enums);
}
+7 -1
View File
@@ -4,6 +4,7 @@
import { Vec3 } from '../math';
import enums from './enums';
import { IVec3Like } from '../math/type-define';
/**
* @zh
@@ -125,9 +126,14 @@ export default class ray {
* @param {number} dz 方向的 z 部分。
*/
constructor (ox: number = 0, oy: number = 0, oz: number = 0,
dx: number = 0, dy: number = 0, dz: number = -1) {
dx: number = 0, dy: number = 0, dz: number = -1) {
this._type = enums.SHAPE_RAY;
this.o = new Vec3(ox, oy, oz);
this.d = new Vec3(dx, dy, dz);
}
public computeHit (out: IVec3Like, distance: number) {
Vec3.normalize(out, this.d)
Vec3.scaleAndAdd(out, this.o, out, distance);
}
}
-1554
View File
File diff suppressed because it is too large Load Diff
+2 -1
View File
@@ -1314,7 +1314,8 @@ export class Mat4 extends ValueType {
* @zh 排除浮点数误差的矩阵近似等价判断
*/
public static equals <Out extends IMat4Like> (a: Out, b: Out, epsilon = EPSILON) {
// TAOCP vol.2, 3rd ed., s.4.2.4, p.213-225
// defines a 'close enough' relationship between u and v that scales for magnitude
return (
Math.abs(a.m00 - b.m00) <= epsilon * Math.max(1.0, Math.abs(a.m00), Math.abs(b.m00)) &&
Math.abs(a.m01 - b.m01) <= epsilon * Math.max(1.0, Math.abs(a.m01), Math.abs(b.m01)) &&
@@ -228,7 +228,6 @@ export class ForwardPipeline extends RenderPipeline {
_vec4Array[1] *= tempRGB.y;
_vec4Array[2] *= tempRGB.z;
}
_vec4Array[3] = sphereLit.luminance * this._lightMeterScale;
if (this._isHDR) {
_vec4Array[3] = sphereLit.luminance * this._fpScale * this._lightMeterScale;
} else {
+4 -1
View File
@@ -11,6 +11,7 @@ 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 bufs: GFXCommandBuffer[] = [];
@@ -211,7 +212,9 @@ export class ForwardStage extends RenderStage {
this._opaqueBatchedQueue.recordCommandBuffer(cmdBuff);
cmdBuff.execute(planarShadow.cmdBuffs.array, planarShadow.cmdBuffCount);
if (camera.visibility & Layers.BitMask.DEFAULT) {
cmdBuff.execute(planarShadow.cmdBuffs.array, planarShadow.cmdBuffCount);
}
cmdBuff.execute(this._transparentQueue.cmdBuffs.array, this._transparentQueue.cmdBuffCount);
cmdBuff.endRenderPass();
+4 -15
View File
@@ -4,18 +4,8 @@
import { intersect } from '../geom-utils';
import { GFXBuffer } from '../gfx/buffer';
import {
GFXBindingType,
GFXBufferUsageBit,
GFXFormat,
GFXFormatInfos,
GFXLoadOp,
GFXMemoryUsageBit,
GFXStoreOp,
GFXTextureLayout,
GFXTextureType,
GFXTextureUsageBit,
GFXTextureViewType} from '../gfx/define';
import { GFXBindingType, GFXBufferUsageBit, GFXFormat, GFXFormatInfos, GFXLoadOp, GFXMemoryUsageBit,
GFXStoreOp, GFXTextureLayout, GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } from '../gfx/define';
import { GFXDevice, GFXFeature } from '../gfx/device';
import { GFXFramebuffer } from '../gfx/framebuffer';
import { GFXInputAssembler, IGFXAttribute } from '../gfx/input-assembler';
@@ -35,7 +25,6 @@ import { IRenderFlowInfo, RenderFlow } from './render-flow';
import { RenderView } from './render-view';
const _vec4Array = new Float32Array(4);
const _outMat = new Mat4();
const _v3tmp = new Vec3();
const _v4Zero = new Vec4(0.0, 0.0, 0.0, 0.0);
@@ -1244,8 +1233,8 @@ export abstract class RenderPipeline {
model.updateUBOs();
this.addVisibleModel(model, camera);
}
}else{
if ((model.node && (view.visibility & model.node.layer)) ||
} else {
if (model.node && ((view.visibility & model.node.layer) === model.node.layer) ||
(view.visibility & model.visFlags)) {
model.updateTransform();
+12 -6
View File
@@ -7,6 +7,7 @@ import { GFXWindow } from '../gfx/window';
import { Camera } from '../renderer/scene/camera';
import { RenderFlow } from './render-flow';
import { CameraDefaultMask } from './define';
import { indexOf } from '../utils/array';
/**
* @zh
@@ -183,12 +184,7 @@ export class RenderView {
if (!info.flows) {
info.flows = ['ForwardFlow', 'ToneMapFlow', 'SMAAFlow'];
}
const pipelineFlows = cc.director.root.pipeline.flows;
for (const f of pipelineFlows) {
if (info.flows.indexOf(f.name) !== -1) {
this.flows.push(f);
}
}
this.setExecuteFlows(info.flows);
return true;
}
@@ -209,4 +205,14 @@ export class RenderView {
public enable (isEnable: boolean) {
this._isEnable = isEnable;
}
public setExecuteFlows (flows: string[]) {
this.flows.length = 0;
const pipelineFlows = cc.director.root.pipeline.flows;
for (const f of pipelineFlows) {
if (flows.indexOf(f.name) !== -1) {
this.flows.push(f);
}
}
}
}
+5 -2
View File
@@ -82,8 +82,11 @@ export class UIStage extends RenderStage {
const camera = view.camera!;
this._renderArea.width = this.flow.pipeline.root.device.width;
this._renderArea.height = this.flow.pipeline.root.device.height;
const vp = camera.viewport;
this._renderArea.x = vp.x * camera.width;
this._renderArea.y = vp.y * camera.height;
this._renderArea.width = vp.width * camera.width;
this._renderArea.height = vp.height * camera.height;
cmdBuff.begin();
cmdBuff.beginRenderPass(framebuffer, this._renderArea,
+224
View File
@@ -0,0 +1,224 @@
import { Component } from '../components/component';
import { property, ccclass, menu, executionOrder } from '../data/class-decorator';
import { view } from './view';
import { SpriteComponent } from '../../ui/components/sprite-component';
import { Node } from '../scene-graph';
import { UITransformComponent } from '../components/ui-base/ui-transfrom-component';
import { SpriteFrame, ImageAsset } from '../assets';
import { Rect } from '../math';
/**
* @en SubContextView is a view component which controls open data context viewport in WeChat game platform.<br/>
* The component's node size decide the viewport of the sub context content in main context,
* the entire sub context texture will be scaled to the node's bounding box area.<br/>
* This component provides multiple important features:<br/>
* 1. Sub context could use its own resolution size and policy.<br/>
* 2. Sub context could be minized to smallest size it needed.<br/>
* 3. Resolution of sub context content could be increased.<br/>
* 4. User touch input is transformed to the correct viewport.<br/>
* 5. Texture update is handled by this component. User don't need to worry.<br/>
* One important thing to be noted, whenever the node's bounding box change,
* you need to manually reset the viewport of sub context using updateSubContextViewport.
* @zh SubContextView 可以用来控制微信小游戏平台开放数据域在主域中的视窗的位置。<br/>
* 这个组件的节点尺寸决定了开放数据域内容在主域中的尺寸,整个开放数据域会被缩放到节点的包围盒范围内。<br/>
* 在这个组件的控制下,用户可以更自由得控制开放数据域:<br/>
* 1. 子域中可以使用独立的设计分辨率和适配模式<br/>
* 2. 子域区域尺寸可以缩小到只容纳内容即可<br/>
* 3. 子域的分辨率也可以被放大,以便获得更清晰的显示效果<br/>
* 4. 用户输入坐标会被自动转换到正确的子域视窗中<br/>
* 5. 子域内容贴图的更新由组件负责,用户不需要处理<br/>
* 唯一需要注意的是,当子域节点的包围盒发生改变时,开发者需要使用 `updateSubContextViewport` 来手动更新子域视窗。
*/
@ccclass('cc.SubContextView')
@executionOrder(110)
@menu('Components/SubContextView')
export class SubContextView extends Component {
@property
get fps (){
return this._fps;
}
set fps (value) {
if (this._fps === value) {
return;
}
this._fps = value;
this._updateInterval = 1 / value;
this._updateSubContextFrameRate();
}
@property({ type: Number })
private _fps = 60;
private _sprite: SpriteComponent | null;
private _imageAsset: ImageAsset;
private _context: any;;
private _updatedTime = 0;
private _updateInterval = 0;
constructor () {
super();
this._sprite = null;
this._imageAsset = new ImageAsset();
this._context = null;
this._updatedTime = performance.now();
}
public onLoad () {
// Setup subcontext canvas size
if (wx.getOpenDataContext) {
this._updateInterval = 1000 / this._fps;
this._context = wx.getOpenDataContext();
// reset sharedCanvas width and height
this.reset();
const image = this._imageAsset;
const sharedCanvas = this._context.canvas;
image.reset(sharedCanvas);
image._texture.create(sharedCanvas.width, sharedCanvas.height);
this._sprite = this.node.getComponent(SpriteComponent);
if (!this._sprite) {
this._sprite = this.node.addComponent(SpriteComponent);
}
if (this._sprite!.spriteFrame) {
this._sprite!.spriteFrame.texture = this._imageAsset._texture;
} else {
const sp = new SpriteFrame();
sp.texture = this._imageAsset._texture;
this._sprite!.spriteFrame = sp;
}
} else {
this.enabled = false;
}
}
public onEnable () {
this._runSubContextMainLoop();
this._registerNodeEvent();
this._updateSubContextFrameRate();
this.updateSubContextViewport();
}
public onDisable () {
this._unregisterNodeEvent();
this._stopSubContextMainLoop();
}
public update (dt: number) {
let calledUpdateMannually = (dt === undefined);
if (calledUpdateMannually) {
this._context && this._context.postMessage({
fromEngine: true,
event: 'step',
});
this._updateSubContextTexture();
return;
}
let now = performance.now();
let deltaTime = (now - this._updatedTime);
if (deltaTime >= this._updateInterval) {
this._updatedTime += this._updateInterval;
this._updateSubContextTexture();
}
}
/**
* @en Reset open data context size and viewport
* @zh 重置开放数据域的尺寸和视窗
* @method reset
*/
public reset () {
if (this._context) {
this.updateSubContextViewport();
let sharedCanvas = this._context.canvas;
if (sharedCanvas) {
sharedCanvas.width = this.node.getComponent(UITransformComponent).width;
sharedCanvas.height = this.node.getComponent(UITransformComponent).height;
}
}
}
/**
* @en Update the sub context viewport manually, it should be called whenever the node's bounding box changes.
* @zh 更新开放数据域相对于主域的 viewport,这个函数应该在节点包围盒改变时手动调用。
*/
public updateSubContextViewport () {
if (this._context) {
let box = this.node.getComponent(UITransformComponent).getBoundingBoxToWorld() as Rect;
let sx = view.getScaleX();
let sy = view.getScaleY();
const rect = view.getViewportRect();
this._context.postMessage({
fromEngine: true,
event: 'viewport',
x: box.x * sx + rect.x,
y: box.y * sy + rect.y,
width: box.width * sx,
height: box.height * sy
});
}
}
private _updateSubContextTexture () {
const img = this._imageAsset;
if (!img || !this._context) {
return;
}
if (img.width <= 0 || img.height <= 0) {
return;
}
const canvas = this._context.canvas;
img.reset(canvas);
if (canvas.width > img.width || canvas.height > img.height ){
this._imageAsset._texture.create(canvas.width, canvas.height);
}
this._imageAsset._texture.uploadData(canvas);
}
private _registerNodeEvent () {
this.node.on(Node.EventType.TRANSFORM_CHANGED, this.updateSubContextViewport, this);
this.node.on(Node.EventType.SCALE_PART, this.updateSubContextViewport, this);
this.node.on(Node.EventType.SIZE_CHANGED, this.updateSubContextViewport, this);
}
private _unregisterNodeEvent () {
this.node.off(Node.EventType.TRANSFORM_CHANGED, this.updateSubContextViewport, this);
this.node.off(Node.EventType.SCALE_PART, this.updateSubContextViewport, this);
this.node.off(Node.EventType.SIZE_CHANGED, this.updateSubContextViewport, this);
}
private _runSubContextMainLoop () {
if (this._context) {
this._context.postMessage({
fromEngine: true,
event: 'mainLoop',
value: true,
});
}
}
private _stopSubContextMainLoop () {
if (this._context) {
this._context.postMessage({
fromEngine: true,
event: 'mainLoop',
value: false,
});
}
}
private _updateSubContextFrameRate () {
if (this._context) {
this._context.postMessage({
fromEngine: true,
event: 'frameRate',
value: this._fps,
});
}
}
}
cc.SubContextView = SubContextView;
@@ -28,14 +28,14 @@
* @hidden
*/
import { game, Game } from '../../game';
import { Vec2 } from '../../math/index';
import { rect } from '../../math/rect';
import { macro } from '../macro';
import sys from '../sys';
import eventManager from './event-manager';
import { EventAcceleration, EventKeyboard, EventMouse, EventTouch } from './events';
import { Touch } from './touch';
import eventManager from './event-manager';
import { game, Game } from '../../game';
const TOUCH_TIMEOUT = macro.TOUCH_TIMEOUT;
@@ -682,6 +682,7 @@ class InputManager {
MSPointerUp : this.handleTouchesEnd,
MSPointerCancel : this.handleTouchesCancel,
};
// tslint:disable-next-line: forin
for (const eventName in _pointerEventsMap) {
const touchEvent = _pointerEventsMap[eventName];
// @ts-ignore
@@ -818,7 +819,7 @@ class InputManager {
const inputManager = new InputManager();
game.on(Game.EVENT_ENGINE_INITED, function () {
game.on(Game.EVENT_ENGINE_INITED, () => {
// register system events
if (!CC_EDITOR && game.config.registerSystemEvent) {
inputManager.registerSystemEvent(game.canvas);
+1
View File
@@ -43,3 +43,4 @@ export {
} from './debug';
export { screen } from './screen';
export { SubContextView } from './SubContextView';
+22 -20
View File
@@ -46,9 +46,9 @@ interface IProgramInfo extends IShaderInfo {
globalsInited: boolean;
localsInited: boolean;
}
export interface IDefineValue {
export interface IMacroInfo {
name: string;
result: string | boolean;
value: string;
}
const getBitCount = (cnt: number) => Math.ceil(Math.log2(Math.max(cnt, 2)));
@@ -64,17 +64,17 @@ const mapDefine = (info: IDefineInfo, def: number | string | boolean) => {
};
const prepareDefines = (defs: IDefineMap, tDefs: IDefineInfo[]) => {
const defines: IDefineValue[] = [];
const macros: IMacroInfo[] = [];
for (const tmpl of tDefs) {
const name = tmpl.name;
const result = mapDefine(tmpl, defs[name]);
defines.push({ name, result });
const value = mapDefine(tmpl, defs[name]);
macros.push({ name, value });
}
return defines;
return macros;
};
const getShaderInstanceName = (name: string, defs: IDefineValue[]) => {
return name + defs.reduce((acc, cur) => cur.result !== '0' ? `${acc}|${cur.name}${cur.result}` : acc, '');
const getShaderInstanceName = (name: string, macros: IMacroInfo[]) => {
return name + macros.reduce((acc, cur) => cur.value !== '0' ? `${acc}|${cur.name}${cur.value}` : acc, '');
};
const insertBuiltinBindings = (tmpl: IProgramInfo, source: Map<string, IInternalBindingDesc>, type: string) => {
@@ -143,12 +143,12 @@ class ProgramLib {
if (def.type === 'number') {
const range = def.range!;
cnt = getBitCount(range[1] - range[0] + 1); // inclusive on both ends
def._map = (value: number) => (value - range[0]) << def._offset;
def._map = (value: number) => value - range[0];
} else if (def.type === 'string') {
cnt = getBitCount(def.options!.length);
def._map = (value: any) => Math.max(0, def.options!.findIndex((s) => s === value)) << def._offset;
def._map = (value: any) => Math.max(0, def.options!.findIndex((s) => s === value));
} else if (def.type === 'boolean') {
def._map = (value: any) => value ? (1 << def._offset) : 0;
def._map = (value: any) => value ? 1 : 0;
}
def._offset = offset;
offset += cnt;
@@ -186,9 +186,11 @@ class ProgramLib {
if (value === undefined || !tmplDef._map) {
continue;
}
key |= tmplDef._map(value);
const mapped = tmplDef._map(value);
const offset = tmplDef._offset;
key |= mapped << offset;
}
return key << 8 | (tmpl.id & 0xff);
return `${key.toString(16)}|${tmpl.id}`;
}
/**
@@ -197,9 +199,9 @@ class ProgramLib {
* @param defines 用于筛选的预处理宏列表
*/
public destroyShaderByDefines (defines: IDefineMap) {
const defs = Object.keys(defines); if (!defs.length) { return; }
const regexes = defs.map((cur) => {
let val = defs[cur];
const names = Object.keys(defines); if (!names.length) { return; }
const regexes = names.map((cur) => {
let val = defines[cur];
if (typeof val === 'boolean') { val = val ? '1' : '0'; }
return new RegExp(cur + val);
});
@@ -231,9 +233,9 @@ class ProgramLib {
const tmpl = this._templates[name];
if (!tmpl.globalsInited) { insertBuiltinBindings(tmpl, pipeline.globalBindings, 'globals'); tmpl.globalsInited = true; }
const defs = prepareDefines(defines, tmpl.defines);
const customDef = defs.reduce((acc, cur) => {
return `${acc}#define ${cur.name} ${cur.result}\n`;
const macroArray = prepareDefines(defines, tmpl.defines);
const customDef = macroArray.reduce((acc, cur) => {
return `${acc}#define ${cur.name} ${cur.value}\n`;
}, '');
let vert: string = '';
@@ -247,7 +249,7 @@ class ProgramLib {
}
program = device.createShader({
name: getShaderInstanceName(name, defs),
name: getShaderInstanceName(name, macroArray),
blocks: tmpl.blocks,
samplers: tmpl.samplers,
stages: [
@@ -27,7 +27,8 @@
* @hidden
*/
import { SkeletalAnimationClip } from '../../animation/skeletal-animation-clip';
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';
@@ -59,20 +60,24 @@ 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] = mat.m00;
out[base + 1] = mat.m01;
out[base + 2] = mat.m02;
out[base + 3] = mat.m12;
out[base + 4] = mat.m04;
out[base + 5] = mat.m05;
out[base + 6] = mat.m06;
out[base + 7] = mat.m13;
out[base + 8] = mat.m08;
out[base + 9] = mat.m09;
out[base + 10] = mat.m10;
out[base + 11] = mat.m14;
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
@@ -85,17 +90,17 @@ function uploadJointDataDQS (out: Float32Array, base: number, mat: Mat4, firstBo
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] = qt_1.x;
out[base + 1] = qt_1.y;
out[base + 2] = qt_1.z;
out[base + 3] = qt_1.w;
out[base + 4] = dq_1.x;
out[base + 5] = dq_1.y;
out[base + 6] = dq_1.z;
out[base + 7] = dq_1.w;
out[base + 8] = v3_2.x;
out[base + 9] = v3_2.y;
out[base + 10] = v3_2.z;
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) {
@@ -165,7 +170,7 @@ export class JointsTexturePool {
/**
* 获取指定动画片段的骨骼贴图
*/
public getJointsTextureWithAnimation (skeleton: Skeleton, clip: SkeletalAnimationClip) {
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; }
@@ -175,7 +180,7 @@ export class JointsTexturePool {
if (!handle) { return null; }
texture = { pixelOffset: handle.start / this._formatSize, refCount: 1, hash, handle };
const textureBuffer = new Float32Array(bufSize);
const data = clip.convertedData;
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; }
+4 -4
View File
@@ -27,7 +27,7 @@
* @hidden
*/
import { SkeletalAnimationClip } from '../../animation/skeletal-animation-clip';
import { AnimationClip } from '../../animation/animation-clip';
import { Skeleton } from '../../assets/skeleton';
import { GFXBuffer } from '../../gfx/buffer';
import { GFXAddress, GFXBufferUsageBit, GFXFilter, GFXMemoryUsageBit } from '../../gfx/define';
@@ -68,7 +68,7 @@ export class JointsAnimationInfo {
JointsAnimationInfo.pool.delete(nodeID);
}
public static switchClip (nodeID: string, clip: SkeletalAnimationClip | null) {
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;
@@ -100,7 +100,7 @@ interface IJointsInfo {
export class SkinningModel extends Model {
public uploadedAnim: SkeletalAnimationClip | null = null;
public uploadedAnim: AnimationClip | null = null;
private _jointsMedium: IJointsInfo;
private _skeleton: Skeleton | null = null;
@@ -140,7 +140,7 @@ export class SkinningModel extends Model {
this.uploadAnimation(this.uploadedAnim);
}
public uploadAnimation (anim: SkeletalAnimationClip | null) {
public uploadAnimation (anim: AnimationClip | null) {
if (!this._skeleton) { return; }
this.uploadedAnim = anim;
const texture = this.uploadedAnim ?
+10 -4
View File
@@ -2,10 +2,10 @@ import { frustum, ray } from '../../geom-utils';
import { GFXClearFlag, IGFXColor } from '../../gfx/define';
import { GFXWindow } from '../../gfx/window';
import { lerp, Mat4, Rect, toRadian, Vec3 } from '../../math';
import { CameraDefaultMask } from '../../pipeline/define';
import { RenderView } from '../../pipeline/render-view';
import { INode } from '../../utils/interfaces';
import { RenderScene } from './render-scene';
import { CameraDefaultMask } from '../../pipeline/define';
export enum CameraProjection {
ORTHO,
@@ -62,7 +62,7 @@ export enum CameraShutter {
}
const FSTOPS: number[] = [1.8, 2.0, 2.2, 2.5, 2.8, 3.2, 3.5, 4.0, 4.5, 5.0, 5.6, 6.3, 7.1, 8.0, 9.0, 10.0, 11.0, 13.0, 14.0, 16.0, 18.0, 20.0, 22.0];
const SHUTERS: number[] = [1.0, 1.0 / 2.0, 1.0 / 4.0, 1.0 / 8.0, 1.0 / 15.0, 1.0 / 30.0, 1.0 / 60.0, 1.0 / 125.0,
const SHUTTERS: number[] = [1.0, 1.0 / 2.0, 1.0 / 4.0, 1.0 / 8.0, 1.0 / 15.0, 1.0 / 30.0, 1.0 / 60.0, 1.0 / 125.0,
1.0 / 250.0, 1.0 / 500.0, 1.0 / 1000.0, 1.0 / 2000.0, 1.0 / 4000.0];
const ISOS: number[] = [100.0, 200.0, 400.0, 800.0];
@@ -134,7 +134,7 @@ export class Camera {
this._priority = info.priority || 0;
this._apertureValue = FSTOPS[this._aperture];
this._shutterValue = SHUTERS[this._shutter];
this._shutterValue = SHUTTERS[this._shutter];
this._isoValue = ISOS[this._iso];
this.updateExposure();
@@ -441,7 +441,7 @@ export class Camera {
set shutter (val: CameraShutter) {
this._shutter = val;
this._shutterValue = SHUTERS[this._shutter];
this._shutterValue = SHUTTERS[this._shutter];
this.updateExposure();
}
@@ -479,6 +479,12 @@ export class Camera {
return this._exposure;
}
set flows (val: string[]) {
if (this._view) {
this._view.setExecuteFlows(val);
}
}
public changeTargetWindow (window: GFXWindow | null = null) {
const scene = this._scene;
const win = window || scene.root.mainWindow;
+21 -4
View File
@@ -5,15 +5,32 @@ import { Layers } from "../../scene-graph";
replaceProperty(RenderScene.prototype, 'RenderScene.prototype', [
{
'name': 'raycastUI',
'newName': 'raycastUI2D'
'newName': 'raycastAllCanvas'
},
{
'name': 'raycastUINode',
'newName': 'raycastUI2DNode'
'name': 'raycastUI2D',
'newName': 'raycastAllCanvas'
},
{
'name': 'raycast',
'newName': 'raycastModels'
'newName': 'raycastAllModels'
},
{
'name': 'raycastModels',
'newName': 'raycastAllModels'
},
{
'name': 'raycastModel',
'newName': 'raycastSingleModel'
},
]);
removeProperty(RenderScene.prototype, 'RenderScene.prototype', [
{
'name': 'raycastUI2DNode'
},
{
'name': 'raycastUINode',
}
]);
+32 -10
View File
@@ -1,7 +1,7 @@
import { EffectAsset } from '../../assets/effect-asset';
import { GFXCommandBuffer } from '../../gfx/command-buffer';
import { GFXCommandBufferType } from '../../gfx/define';
import { GFXCommandBufferType, GFXStatus } from '../../gfx/define';
import { GFXInputAssembler } from '../../gfx/input-assembler';
import { GFXPipelineState } from '../../gfx/pipeline-state';
import { Color, Mat4, Quat, Vec3 } from '../../math';
@@ -155,15 +155,15 @@ export class PlanarShadows {
if (!this._scene.mainLight.enabled) { return; }
for (const model of this._scene.models) {
if (!model.enabled || !model.node || !model.castShadow) { continue; }
let pso = this._psoRecord.get(model);
if (!pso) { pso = this._createPSO(model); this._psoRecord.set(model, pso); }
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
for (let i = 0; i < model.subModelNum; i++) {
const ia = model.getSubModel(i).inputAssembler;
if (!ia) { continue; }
let cb = this._cbRecord.get(ia);
if (!cb) {
cb = this._createCommandBuffer();
if (newOne || !cb) {
cb = this._createOrReuseCommandBuffer(cb);
cb.begin();
cb.bindPipelineState(pso);
cb.bindBindingLayout(pso.pipelineLayout.layouts[0]);
@@ -177,6 +177,17 @@ export class PlanarShadows {
}
}
public destroyShadowModel (model: Model) {
const pso = this._psoRecord.get(model);
if (pso) { this._destroyPSO(model, pso); this._psoRecord.delete(model); }
for (let i = 0; i < model.subModelNum; i++) {
const ia = model.getSubModel(i).inputAssembler;
const cb = this._cbRecord.get(ia!);
if (!ia || !cb) { continue; }
cb.destroy(); this._cbRecord.delete(ia);
}
}
public onPipelineChange () {
const cbs = this._cbRecord.values();
let cbRes = cbs.next();
@@ -188,8 +199,7 @@ export class PlanarShadows {
const models = this._psoRecord.keys();
let modelRes = models.next();
while (!modelRes.done) {
const pass = modelRes.value instanceof SkinningModel ? this._passSkinning : this._passNormal;
pass.destroyPipelineState(this._psoRecord.get(modelRes.value)!);
this._destroyPSO(modelRes.value, this._psoRecord.get(modelRes.value)!);
modelRes = models.next();
}
this._psoRecord.clear();
@@ -209,11 +219,23 @@ export class PlanarShadows {
return pso;
}
protected _createCommandBuffer () {
protected _destroyPSO (model: Model, pso: GFXPipelineState) {
const pass = model instanceof SkinningModel ? this._passSkinning : this._passNormal;
return pass.destroyPipelineState(pso);
}
protected _createOrReuseCommandBuffer (cb?: GFXCommandBuffer) {
const device = this._scene.root.device;
return device.createCommandBuffer({
const info = {
allocator: device.commandAllocator,
type: GFXCommandBufferType.SECONDARY,
});
};
if (cb) {
if (cb.status === GFXStatus.SUCCESS) { cb.destroy(); }
cb.initialize(info);
} else {
cb = device.createCommandBuffer(info);
}
return cb;
}
}
+103 -63
View File
@@ -82,6 +82,38 @@ export class RenderScene {
return this._texturePool;
}
/**
* @zh
* 获取 raycastAllCanvas 后的检测结果
*/
get rayResultCanvas () {
return resultCanvas;
}
/**
* @zh
* 获取 raycastAllModels 后的检测结果
*/
get rayResultModels () {
return resultModels;
}
/**
* @zh
* 获取 raycastAll 后的检测结果
*/
get rayResultAll () {
return resultAll;
}
/**
* @zh
* 获取 raycastSingleModel 后的检测结果
*/
get rayResultSingleModel () {
return this.rayResultSingleModel;
}
public static registerCreateFunc (root: Root) {
root._createSceneFun = (_root: Root): RenderScene => new RenderScene(_root);
}
@@ -124,6 +156,7 @@ export class RenderScene {
this.destroyPointLights();
this.destroySpotLights();
this.destroyModels();
this._skybox.destroy();
this._planarShadows.destroy();
this._texturePool.destroy();
}
@@ -198,6 +231,7 @@ export class RenderScene {
public destroyModel (model: Model) {
for (let i = 0; i < this._models.length; ++i) {
if (this._models[i] === model) {
this._planarShadows.destroyShadowModel(model);
this._models.splice(i, 1)[0].destroy();
return;
}
@@ -206,6 +240,7 @@ export class RenderScene {
public destroyModels () {
for (const m of this._models) {
this._planarShadows.destroyShadowModel(m);
m.destroy();
}
this._models = [];
@@ -225,18 +260,49 @@ export class RenderScene {
/**
* @en
* Cast a ray into the scene, record all the intersected models in the result array
* Cast a ray into the scene, record all the intersected models and ui2d nodes in the result array
* @param worldRay the testing ray
* @param mask the layer mask to filter the models
* @param distance the max distance , Infinity by default
* @returns boolean , ray is hit or not
* @note getter of this.rayResultAll can get recently result
* @zh
* 传入一条射线检测场景中所有的 3D 模型和 UI2D Node
* @param worldRay 世界射线
* @param mask mask 用于标记所有要检测的层,默认为 Default | UI2D
* @param distance 射线检测的最大距离, 默认为 Infinity
* @returns boolean , 射线是否有击中
* @nete 通过 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);
const r_ui2d = this.raycastAllCanvas(worldRay, mask, distance);
const isHit = r_3d || r_ui2d;
resultAll.length = 0;
if (isHit) {
Array.prototype.push.apply(resultAll, resultModels);
Array.prototype.push.apply(resultAll, resultCanvas);
}
return isHit;
}
/**
* @en
* Cast a ray into the scene, record all the intersected models in the result array
* @param worldRay the testing ray
* @param mask the layer mask to filter the models
* @param distance the max distance , Infinity by default
* @returns boolean , ray is hit or not
* @note getter of this.rayResultModels can get recently result
* @zh
* 传入一条射线检测场景中所有的 3D 模型。
* @param worldRay 世界射线
* @param mask 用于标记所有要检测的层,默认为 Default
* @param distance 射线检测的最大距离, 默认为 Infinity
* @returns IRaycastResult[]
* @returns boolean , 射线是否有击中
* @nete 通过 this.rayResultModels 可以获取到最近的结果
*/
public raycastModels (worldRay: ray, mask = Layers.Enum.DEFAULT, distance = Infinity): IRaycastResult[] {
public raycastAllModels (worldRay: ray, mask = Layers.Enum.DEFAULT, distance = Infinity): boolean {
pool.reset();
for (const m of this._models) {
const transform = m.transform;
@@ -258,43 +324,45 @@ export class RenderScene {
const r = pool.add();
r.node = m.node;
r.distance = narrowDis * Vec3.multiply(v3, modelRay.d, transform.worldScale).length();
results[pool.length - 1] = r;
resultModels[pool.length - 1] = r;
}
}
}
results.length = pool.length;
return results;
resultModels.length = pool.length;
return resultModels.length > 0;
}
/**
* @en
* Before you raycast the model, make sure the model is not null
* @param worldRay the testing ray
* @param model the testing model
* @param mask the layer mask to filter the models
* @param distance the max distance , Infinity by default
* @returns boolean , ray is hit or not
* @zh
* 传入一条射线和一个 3D 模型进行射线检测。
* @param worldRay 世界射线
* @param model 进行检测的模型
* @param mask 用于标记所有要检测的层,默认为 Default
* @param distance 射线检测的最大距离, 默认为 Infinity
* @returns IRaycastResult[]
* @returns boolean , 射线是否有击中
*/
public raycastModel (worldRay: ray, model: Model, mask = Layers.Enum.DEFAULT, distance = Infinity): IRaycastResult[] {
public raycastSingleModel (worldRay: ray, model: Model, mask = Layers.Enum.DEFAULT, distance = Infinity): boolean {
if (CC_PREVIEW) {
if (model == null) console.error(" 检测前请保证 model 不为 null ");
if (model == null) { console.error(' 检测前请保证 model 不为 null '); }
}
pool.reset();
results.length = 0;
const m = model;
const transform = m.transform;
if (!transform || !m.enabled || m.node.layer & Layers.Enum.IGNORE_RAYCAST || !(m.node.layer & mask) || !m.modelBounds) { return results; }
if (!transform || !m.enabled || m.node.layer & Layers.Enum.IGNORE_RAYCAST || !(m.node.layer & mask) || !m.modelBounds) { return false; }
// transform ray back to model space
Mat4.invert(m4, transform.getWorldMatrix(m4));
Vec3.transformMat4(modelRay.o, worldRay.o, m4);
Vec3.normalize(modelRay.d, Vec3.transformMat4Normal(modelRay.d, worldRay.d, m4));
// broadphase
const d = intersect.ray_aabb(modelRay, m.modelBounds);
if (d <= 0 || d > distance) { return results; }
if (d <= 0 || d > distance) { return false; }
for (let i = 0; i < m.subModelNum; ++i) {
const subModel = m.getSubModel(i).subMeshData;
if (subModel && subModel.geometricInfo) {
@@ -305,27 +373,30 @@ export class RenderScene {
const r = pool.add();
r.node = m.node;
r.distance = narrowDis * Vec3.multiply(v3, modelRay.d, transform.worldScale).length();
results[pool.length - 1] = r;
resultSingleModel[pool.length - 1] = r;
}
}
return results;
resultSingleModel.length = pool.length;
return resultSingleModel.length > 0;
}
/**
* @en
* Cast a ray into the scene, record all the intersected ui aabb in the result array
* Cast a ray into the scene, detect all canvas and its children
* @param worldRay the testing ray
* @param mask the layer mask to filter all ui2d aabb
* @param distance the max distance , Infinity by default
* @returns IRaycastResult[]
* @returns boolean , ray is hit or not
* @note getter of this.rayResultCanvas can get recently result
* @zh
* 传入一条射线检测场景中所有的 UI2D Node,mask 标记了要检测的所有的层,默认为 UI2D*
* 传入一条射线检测场景中所有的 Canvas 以及 Canvas 下的 Node
* @param worldRay 世界射线
* @param mask 用于标记所有要检测的层,默认为 UI2D
* @param distance 射线检测的最大距离, 默认为 Infinity
* @returns IRaycastResult[]
* @returns boolean , 射线是否有击中
* @nete 通过 this.rayResultCanvas 可以获取到最近的结果
*/
public raycastUI2D (worldRay: ray, mask = Layers.Enum.UI_2D, distance = Infinity): IRaycastResult[] {
public raycastAllCanvas (worldRay: ray, mask = Layers.Enum.UI_2D, distance = Infinity): boolean {
poolUI.reset();
const canvasComs = cc.director.getScene().getComponentsInChildren(cc.CanvasComponent);
if (canvasComs != null && canvasComs.length > 0) {
@@ -336,28 +407,13 @@ export class RenderScene {
}
}
}
resultUIs.length = poolUI.length;
return resultUIs;
resultCanvas.length = poolUI.length;
return resultCanvas.length > 0;
}
/**
* @en
* Before you raycast the ui node, make sure the node is not null
* @param worldRay the testing ray
* @param ui2dNode the ui2d node
* @param mask the layer mask to filter the ui2d node aabb
* @param distance the max distance , Infinity by default
* @returns IRaycastResult | undefined
* @zh
* 传入一条射线和一个 UI2D Node 进行射线检测。
* @param worldRay 世界射线
* @param ui2dNode UI2D 的节点
* @param mask 用于标记所有要检测的层,默认为 UI2D
* @param distance 射线检测的最大距离, 默认为 Infinity
*/
public raycastUI2DNode (worldRay: ray, ui2dNode: INode, mask = Layers.Enum.UI_2D, distance = Infinity) {
private _raycastUI2DNode (worldRay: ray, ui2dNode: INode, mask = Layers.Enum.UI_2D, distance = Infinity) {
if (CC_PREVIEW) {
if (ui2dNode == null) console.error(" 检测前请保证 uiNode 不为 null ");
if (ui2dNode == null) { console.error('make sure UINode is not null'); }
}
const uiTransfrom = ui2dNode.uiTransfromComp;
if (uiTransfrom == null || ui2dNode.layer & Layers.Enum.IGNORE_RAYCAST || !(ui2dNode.layer & mask)) { return; }
@@ -374,30 +430,10 @@ export class RenderScene {
}
}
// /**
// * @en
// * Cast a ray into the scene, record all the intersected models and ui2d nodes in the result array
// * @param worldRay the testing ray
// * @param mask the layer mask to filter the models
// * @param distance the max distance , Infinity by default
// * @returns IRaycastResult[]
// * @zh
// * 传入一条射线检测场景中所有的 3D 模型和 UI2D Node
// * @param worldRay 世界射线
// * @param mask mask 用于标记所有要检测的层,默认为 Default | UI2D
// * @param distance 射线检测的最大距离, 默认为 Infinity
// * @returns IRaycastResult[]
// */
// public raycastAll (worldRay: ray, mask = Layers.Default | Layers.UI2D, distance = Infinity): IRaycastResult[] {
// const r_3d = this.raycastModels(worldRay, mask, distance);
// const r_ui2d = this.raycastUI2D(worldRay, mask, distance);
// return r_3d.concat(r_ui2d);
// }
private _raycastUI2DNodeRecursiveChildren (worldRay: ray, parent: INode, mask = Layers.Enum.UI_2D, distance = Infinity) {
const result = this.raycastUI2DNode(worldRay, parent, mask, distance);
const result = this._raycastUI2DNode(worldRay, parent, mask, distance);
if (result != null) {
resultUIs[poolUI.length - 1] = result;
resultCanvas[poolUI.length - 1] = result;
}
for (const node of parent.children) {
if (node != null && node.active) {
@@ -415,13 +451,17 @@ const tri = triangle.create();
const pool = new RecyclePool<IRaycastResult>(() => {
return { node: null!, distance: Infinity };
}, 8);
const results: IRaycastResult[] = [];
/** UI raycast result pool */
const resultModels: IRaycastResult[] = [];
/** Canavas raycast result pool */
const aabbUI = new aabb();
const poolUI = new RecyclePool<IRaycastResult>(() => {
return { node: null!, distance: Infinity };
}, 8);
const resultUIs: IRaycastResult[] = [];
const resultCanvas: IRaycastResult[] = [];
/** raycast all */
const resultAll: IRaycastResult[] = [];
/** raycast single model */
const resultSingleModel: IRaycastResult[] = [];
const narrowphase = (vb: Float32Array, ib: IBArray, pm: GFXPrimitiveMode, sides: boolean, distance = Infinity) => {
narrowDis = distance;
+5 -4
View File
@@ -1,6 +1,7 @@
import { builtinResMgr } from '../../3d/builtin';
import { createMesh } from '../../3d/misc/utils';
import { Material } from '../../assets/material';
import { Mesh } from '../../assets/mesh';
import { TextureCube } from '../../assets/texture-cube';
import { IInternalBindingInst, UNIFORM_ENVIRONMENT } from '../../pipeline/define';
import { box } from '../../primitive';
@@ -8,6 +9,8 @@ import { samplerLib } from '../core/sampler-lib';
import { Model } from './model';
import { RenderScene } from './render-scene';
let skybox_mesh: Mesh | null = null;
export class Skybox extends Model {
set useIBL (val) {
@@ -52,10 +55,8 @@ export class Skybox extends Model {
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)!;
const mesh = createMesh(box({ width: 2, height: 2, length: 2 }));
const subMeshData = mesh.renderingMesh.getSubmesh(0)!;
this.initSubModel(0, subMeshData, this._material);
if (!skybox_mesh) { skybox_mesh = createMesh(box({ width: 2, height: 2, length: 2 })); }
this.initSubModel(0, skybox_mesh.renderingMesh.getSubmesh(0), this._material);
}
protected _updatePipeline () {
+24 -18
View File
@@ -37,6 +37,7 @@ import { IBaseNode } from '../utils/interfaces';
import * as js from '../utils/js';
import { baseNodePolyfill } from './base-node-dev';
import { Scene } from './scene';
import { errorID, warnID } from '../platform/debug';
/**
*
@@ -49,6 +50,9 @@ const Destroying = CCObject.Flags.Destroying;
const DontDestroy = CCObject.Flags.DontDestroy;
// @ts-ignore
const Deactivating = CCObject.Flags.Deactivating;
// @ts-ignore
const Activating = CCObject.Flags.Activating;
const ChangingState = Activating | Deactivating;
// const CHILD_ADDED = 'child-added';
// const CHILD_REMOVED = 'child-removed';
@@ -59,7 +63,7 @@ const NullScene = null as unknown as Scene;
function getConstructor (typeOrClassName: string | Function): Function | null {
if (!typeOrClassName) {
cc.errorID(3804);
errorID(3804);
return null;
}
if (typeof typeOrClassName === 'string') {
@@ -135,7 +139,7 @@ export class BaseNode extends CCObject implements IBaseNode, ISchedulable {
}
set name (value) {
if (CC_DEV && value.indexOf('/') !== -1) {
cc.errorID(1632);
errorID(1632);
return;
}
this._name = value;
@@ -415,8 +419,10 @@ export class BaseNode extends CCObject implements IBaseNode, ISchedulable {
return;
}
const oldParent = this._parent;
if (CC_DEBUG && oldParent && (oldParent._objFlags & Deactivating)) {
cc.errorID(3821);
if (CC_DEBUG && oldParent &&
// Change parent when old parent desactivating or activating
(oldParent._objFlags & ChangingState)) {
errorID(3821);
}
this._parent = value;
@@ -431,7 +437,7 @@ export class BaseNode extends CCObject implements IBaseNode, ISchedulable {
if (value) {
if (CC_DEBUG && (value._objFlags & Deactivating)) {
cc.errorID(3821);
errorID(3821);
}
value._children.push(this);
this._siblingIndex = value._children.length - 1;
@@ -443,7 +449,7 @@ export class BaseNode extends CCObject implements IBaseNode, ISchedulable {
if (!(oldParent._objFlags & Destroying)) {
const removeAt = oldParent._children.indexOf(this);
if (CC_DEV && removeAt < 0) {
return cc.errorID(1633);
return errorID(1633);
}
oldParent._children.splice(removeAt, 1);
oldParent._updateSiblingIndex();
@@ -560,7 +566,7 @@ export class BaseNode extends CCObject implements IBaseNode, ISchedulable {
public addChild (child: this): void {
if (CC_DEV && !(child instanceof cc._BaseNode)) {
return cc.errorID(1634, cc.js.getClassName(child));
return errorID(1634, cc.js.getClassName(child));
}
cc.assertID(child, 1606);
cc.assertID(child._parent === null, 1605);
@@ -616,7 +622,7 @@ export class BaseNode extends CCObject implements IBaseNode, ISchedulable {
return;
}
if (this._parent._objFlags & Deactivating) {
cc.errorID(3821);
errorID(3821);
return;
}
const siblings = this._parent._children;
@@ -982,15 +988,15 @@ export class BaseNode extends CCObject implements IBaseNode, ISchedulable {
if (typeof typeOrClassName === 'string') {
constructor = js.getClassByName(typeOrClassName);
if (!constructor) {
cc.errorID(3807, typeOrClassName);
errorID(3807, typeOrClassName);
if (cc._RF.peek()) {
cc.errorID(3808, typeOrClassName);
errorID(3808, typeOrClassName);
}
return null;
}
} else {
if (!typeOrClassName) {
cc.errorID(3804);
errorID(3804);
return null;
}
constructor = typeOrClassName;
@@ -999,11 +1005,11 @@ export class BaseNode extends CCObject implements IBaseNode, ISchedulable {
// check component
if (typeof constructor !== 'function') {
cc.errorID(3809);
errorID(3809);
return null;
}
if (!js.isChildClassOf(constructor, cc.Component)) {
cc.errorID(3810);
errorID(3810);
return null;
}
@@ -1082,7 +1088,7 @@ export class BaseNode extends CCObject implements IBaseNode, ISchedulable {
public removeComponent (component: any) {
if (!component) {
cc.errorID(3813);
errorID(3813);
return;
}
let componentInstance: Component | null = null;
@@ -1133,7 +1139,7 @@ export class BaseNode extends CCObject implements IBaseNode, ISchedulable {
// Do remove component, only used internally.
public _removeComponent (component: Component) {
if (!component) {
cc.errorID(3814);
errorID(3814);
return;
}
@@ -1147,12 +1153,12 @@ export class BaseNode extends CCObject implements IBaseNode, ISchedulable {
}
// @ts-ignore
else if (component.node !== this) {
cc.errorID(3815);
errorID(3815);
}
}
}
protected _updateSiblingIndex () {
public _updateSiblingIndex () {
for (let i = 0; i < this._children.length; ++i) {
this._children[i]._siblingIndex = i;
}
@@ -1221,7 +1227,7 @@ export class BaseNode extends CCObject implements IBaseNode, ISchedulable {
if (this._persistNode && !(newParent instanceof cc.Scene)) {
cc.game.removePersistRootNode(this);
if (CC_EDITOR) {
cc.warnID(1623);
warnID(1623);
}
}
+9 -10
View File
@@ -27,18 +27,17 @@
* @category scene-graph
*/
import { INode } from '../utils/interfaces';
import { ITargetImpl, EventTarget } from '../event/event-target';
import { eventManager, EventMouse, EventTouch, Touch } from '../platform/event-manager';
import Event from '../event/event';
import { EventTarget } from '../event/event-target';
import { Vec2 } from '../math/vec2';
import { SystemEventType } from '../platform/event-manager/event-enum';
import { EventListener } from '../platform/event-manager/event-listener';
import { array } from '../utils/js';
import Event from '../event/event';
import { Vec2 } from '../math/vec2';
import { eventManager } from '../platform/event-manager/event-manager';
import { EventMouse, EventTouch } from '../platform/event-manager/events';
import { Touch } from '../platform/event-manager/touch';
import { INode } from '../utils/interfaces';
const fastRemove = array.fastRemove;
let _cachedArray = new Array<INode>(16);
const _cachedArray = new Array<INode>(16);
let _currentHovered: INode | null = null;
let pos = new Vec2();
@@ -349,7 +348,7 @@ export class NodeEventProcessor {
public reattach (): void {
if (this.touchListener) {
var mask = this.touchListener.mask = _searchMaskInParent(this._node);
const mask = this.touchListener.mask = _searchMaskInParent(this._node);
if (this.mouseListener) {
this.mouseListener.mask = mask;
}
+4 -2
View File
@@ -31,8 +31,8 @@ import { UIComponent, UITransformComponent } from '../components/ui-base';
import { ccclass, property } from '../data/class-decorator';
import Event from '../event/event';
import { Mat3, Mat4, Quat, Size, Vec2, Vec3 } from '../math';
import { eventManager } from '../platform/event-manager';
import { SystemEventType } from '../platform/event-manager/event-enum';
import { eventManager } from '../platform/event-manager/event-manager';
import { INode } from '../utils/interfaces';
import { BaseNode } from './base-node';
import { Layers } from './layers';
@@ -853,7 +853,9 @@ export class Node extends BaseNode implements INode {
parent.updateWorldTransform();
Mat3.fromQuat(m3_1, Quat.conjugate(qt_1, parent._rot));
Mat3.multiplyMat4(m3_1, m3_1, parent._mat);
m3_scaling.m00 = this._scale.x; m3_scaling.m04 = this._scale.x; m3_scaling.m08 = this._scale.z;
m3_scaling.m00 = this._scale.x;
m3_scaling.m04 = this._scale.y;
m3_scaling.m08 = this._scale.z;
Mat3.multiply(m3_1, m3_scaling, Mat3.invert(m3_1, m3_1));
this._lscale.x = m3_1.m00;
this._lscale.y = m3_1.m04;
File diff suppressed because one or more lines are too long
+1
View File
@@ -736,4 +736,5 @@ export interface INode extends IBaseNode {
targetOff (target: string | Object): void;
pauseSystemEvents (recursive: boolean): void;
resumeSystemEvents (recursive: boolean): void;
_updateSiblingIndex(): void;
}
+2 -2
View File
@@ -225,8 +225,8 @@ export class Profiler {
camera.far = 0;
camera.orthoHeight = this._device!.height;
camera.visibility = Layers.BitMask.PROFILER;
camera.clearFlags = GFXClearFlag.DEPTH | GFXClearFlag.STENCIL;
camera.priority = 1073741928;
camera.clearFlags = GFXClearFlag.NONE;
camera.priority = 0xffffffff; // after everything else
const managerNode = new Node('Profiler_Root');
managerNode.parent = this._rootNode;
+9 -12
View File
@@ -4,15 +4,18 @@
import { Mat4, Quat, Vec3 } from '../core/math';
import { ERigidBodyType } from './physic-enum';
import { RaycastResult } from './raycast-result';
import { PhysicsRayResult } from './physics-ray-result';
import { ray } from '../core/geom-utils';
import { RecyclePool } from '../core';
// tslint:disable:interface-name
// tslint:disable:no-empty-interface
export interface IRaycastOptions {
collisionFilterMask?: number;
collisionFilterGroup?: number;
queryTriggerInteraction?: boolean;
mask: number;
group: number;
queryTrigger: boolean;
maxDistance: number;
}
export interface ICreateBodyOptions {
@@ -64,19 +67,13 @@ export interface BuiltInWorldBase {
* Ray cast, and return information of the closest hit.
* @return True if any body was hit.
*/
raycastClosest (from: Vec3, to: Vec3, options: IRaycastOptions, result: RaycastResult): boolean;
/**
* Ray cast, and stop at the first result. Note that the order is random - but the method is fast.
* @return True if any body was hit.
*/
raycastAny (from: Vec3, to: Vec3, options: IRaycastOptions, result: RaycastResult): boolean;
raycastClosest (worldRay: ray, options: IRaycastOptions, out: PhysicsRayResult): boolean;
/**
* Ray cast against all bodies. The provided callback will be executed for each hit with a RaycastResult as single argument.
* @return True if any body was hit.
*/
raycastAll (from: Vec3, to: Vec3, options: IRaycastOptions, callback: (result: RaycastResult) => void): boolean;
raycast (worldRay: ray, options: IRaycastOptions, pool: RecyclePool<PhysicsRayResult>, resultes: PhysicsRayResult[]): boolean
}
export interface PhysicsWorldBase extends BuiltInWorldBase {
+4 -2
View File
@@ -17,16 +17,17 @@ export class PhysicMaterial extends Asset {
private static _idCounter: number = 0;
@property
private _friction = -1;
private _friction = 0.1;
@property
private _restitution = -1;
private _restitution = 0.1;
/**
* Friction for this material.
* If non-negative, it will be used instead of the friction given by ContactMaterials.
* If there's no matching ContactMaterial, the value from .defaultContactMaterial in the World will be used.
*/
@property
get friction () {
return this._friction;
}
@@ -43,6 +44,7 @@ export class PhysicMaterial extends Asset {
* If non-negative, it will be used instead of the restitution given by ContactMaterials.
* If there's no matching ContactMaterial, the value from .defaultContactMaterial in the World will be used
*/
@property
get restitution () {
return this._restitution;
}
+1 -1
View File
@@ -1,4 +1,4 @@
import CANNON from 'cannon';
import CANNON from '@cocos/cannon';
import { Mat4, Quat, Vec3 } from '../../core/math';
import { ICollisionCallback, ICollisionEventType, ICreateBodyOptions, PhysicsWorldBase, RigidBodyBase, ShapeBase } from '../api';
import { ERigidBodyType } from '../physic-enum';
+12 -33
View File
@@ -1,42 +1,21 @@
import CANNON from 'cannon';
import { IRaycastOptions, RigidBodyBase, ShapeBase } from '../api';
import { RaycastResult } from '../raycast-result';
import CANNON from '@cocos/cannon';
import { IRaycastOptions, ShapeBase } from '../api';
import { PhysicsRayResult } from '../physics-ray-result';
import { getWrap } from '../util';
import { Vec3 } from '../../core';
interface ICANNONRaycastOptions {
collisionFilterMask?: number;
collisionFilterGroup?: number;
checkCollisionResponse?: boolean;
skipBackfaces?: boolean;
export function toCannonRaycastOptions (out: CANNON.IRaycastOptions, options: IRaycastOptions) {
out.checkCollisionResponse = !options.queryTrigger;
// out.collisionFilterGroup = options.group;
// out.collisionFilterMask = options.mask;
out.skipBackFaces = false;
}
export function toCannonRaycastOptions (options: IRaycastOptions): ICANNONRaycastOptions {
return toCannonOptions(options, {
queryTriggerInteraction: 'checkCollisionResponse',
});
}
export function toCannonOptions<T> (options: any, optionsRename?: { [x: string]: string }) {
const result = {};
for (const key of Object.keys(options)) {
let destKey = key;
if (optionsRename) {
const rename = optionsRename[key];
if (rename) {
destKey = rename;
}
}
result[destKey] = options[key];
}
return result as T;
}
export function fillRaycastResult (result: RaycastResult, cannonResult: CANNON.RaycastResult) {
export function fillRaycastResult (result: PhysicsRayResult, cannonResult: CANNON.RaycastResult) {
result._assign(
cannonResult.hitPointWorld,
Vec3.copy(new Vec3(), cannonResult.hitPointWorld),
cannonResult.distance,
getWrap<ShapeBase>(cannonResult.shape),
getWrap<RigidBodyBase>(cannonResult.body),
getWrap<ShapeBase>(cannonResult.shape)
);
}
+35 -17
View File
@@ -1,12 +1,14 @@
import CANNON from 'cannon';
import CANNON from '@cocos/cannon';
import { Vec3 } from '../../core/math';
import { RaycastResult } from '../raycast-result';
import { PhysicsRayResult } from '../physics-ray-result';
import { setWrap } from '../util';
import { AfterStepCallback, BeforeStepCallback, IRaycastOptions, PhysicsWorldBase } from './../api';
import { fillRaycastResult, toCannonRaycastOptions } from './cannon-util';
import { CannonConstraint } from './constraint/cannon-constraint';
import { CannonShape } from './shapes/cannon-shape';
import { PhysicMaterial } from '../assets/physic-material';
import { ray } from '../../core/geom-utils';
import { RecyclePool } from '../../core';
export class CannonWorld implements PhysicsWorldBase {
@@ -62,6 +64,11 @@ export class CannonWorld implements PhysicsWorldBase {
this._callCustomBeforeSteps();
this._world.step(deltaTime, time, maxSubStep);
this._callCustomAfterSteps();
this._world.emitTriggeredEvents();
this._world.emitCollisionEvents();
// hack, node transform may be dirty
this._callCustomBeforeSteps();
}
public addBeforeStep (cb: BeforeStepCallback) {
@@ -88,28 +95,25 @@ export class CannonWorld implements PhysicsWorldBase {
this._customAfterStepListener.splice(i, 1);
}
public raycastClosest (from: Vec3, to: Vec3, options: IRaycastOptions, result: RaycastResult): boolean {
const hit = (this._world as any).raycastClosest(from, to, toCannonRaycastOptions(options), this._raycastResult);
public raycastClosest (worldRay: ray, options: IRaycastOptions, result: PhysicsRayResult): boolean {
setupFromAndTo(worldRay, options.maxDistance);
toCannonRaycastOptions(raycastOpt, options);
const hit = this._world.raycastClosest(from, to, raycastOpt, this._raycastResult);
if (hit) {
fillRaycastResult(result, this._raycastResult);
}
return hit;
}
public raycastAny (from: Vec3, to: Vec3, options: IRaycastOptions, result: RaycastResult): boolean {
const hit = (this._world as any).raycastAny(from, to, toCannonRaycastOptions(options), this._raycastResult);
if (hit) {
fillRaycastResult(result, this._raycastResult);
}
return hit;
}
public raycastAll (from: Vec3, to: Vec3, options: IRaycastOptions, callback: (result: RaycastResult) => void): boolean {
return (this._world as any).raycastAll(from, to, toCannonRaycastOptions(options), (cannonResult: CANNON.RaycastResult) => {
const result = new RaycastResult();
fillRaycastResult(result, cannonResult);
callback(result);
public raycast (worldRay: ray, options: IRaycastOptions, pool: RecyclePool<PhysicsRayResult>, results: PhysicsRayResult[]): boolean {
setupFromAndTo(worldRay, options.maxDistance);
toCannonRaycastOptions(raycastOpt, options);
const hit = this._world.raycastAll(from, to, raycastOpt, (result: CANNON.RaycastResult): any => {
const r = pool.add();
fillRaycastResult(r, result);
results.push(r);
});
return hit
}
// public addContactMaterial (contactMaterial: ContactMaterial) {
@@ -132,3 +136,17 @@ export class CannonWorld implements PhysicsWorldBase {
this._customAfterStepListener.forEach((fx) => fx());
}
}
const from = new CANNON.Vec3();
const to = new CANNON.Vec3();
function setupFromAndTo (worldRay: ray, distance: number) {
Vec3.copy(from, worldRay.o);
worldRay.computeHit(to, distance);
}
const raycastOpt: CANNON.IRaycastOptions = {
'checkCollisionResponse': false,
'collisionFilterGroup': -1,
'collisionFilterMask': -1,
'skipBackFaces': false
}
@@ -1,4 +1,4 @@
import CANNON from 'cannon';
import CANNON from '@cocos/cannon';
import { ConstraintBase } from '../../api';
import { getWrap, setWrap } from '../../util';
import { CannonRigidBody } from '../cannon-body';
@@ -1,4 +1,4 @@
import CANNON from 'cannon';
import CANNON from '@cocos/cannon';
import { DistanceConstraintBase, IDistanceConstraintOptions } from '../../api';
import { CannonRigidBody } from '../cannon-body';
import { CannonConstraint } from './cannon-constraint';
@@ -1,4 +1,4 @@
import CANNON from 'cannon';
import CANNON from '@cocos/cannon';
import { DistanceConstraintBase, IDistanceConstraintOptions } from '../../api';
import { CannonRigidBody } from '../cannon-body';
import { CannonConstraint } from './cannon-constraint';
@@ -1,4 +1,4 @@
import CANNON from 'cannon';
import CANNON from '@cocos/cannon';
import { Vec3 } from '../../../core/math';
import { IPointToPointConstraintOptions, PointToPointConstraintBase } from '../../api';
import { CannonRigidBody } from '../cannon-body';
@@ -1,4 +1,4 @@
import CANNON from 'cannon';
import CANNON from '@cocos/cannon';
import { Vec3 } from '../../../core/math';
import { BoxShapeBase, ShapeBase } from '../../api';
import { getWrap, setWrap, stringfyVec3 } from '../../util';
+1 -1
View File
@@ -1,4 +1,4 @@
import CANNON from 'cannon';
import CANNON from '@cocos/cannon';
import { Quat, Vec3 } from '../../../core/math';
import { ITriggerCallback, ITriggerEventType, ShapeBase } from '../../api';
import { getWrap, stringfyVec3 } from '../../util';
@@ -1,4 +1,4 @@
import CANNON from 'cannon';
import CANNON from '@cocos/cannon';
import { Vec3 } from '../../../core/math';
import { ShapeBase, SphereShapeBase } from '../../api';
import { maxComponent, setWrap } from '../../util';
+15 -15
View File
@@ -28,7 +28,7 @@ export class BuiltInBody extends BuiltinObject implements BuiltInRigidBodyBase {
private _world!: BuiltInWorld;
private _shapes: BuiltinShape[] = [];
public readonly shapes: BuiltinShape[] = [];
private userData: any;
@@ -38,11 +38,11 @@ export class BuiltInBody extends BuiltinObject implements BuiltInRigidBodyBase {
}
public intersects (body: BuiltInBody) {
for (let i = 0; i < this._shapes.length; i++) {
const shapeA = this._shapes[i];
for (let i = 0; i < this.shapes.length; i++) {
const shapeA = this.shapes[i];
for (let j = 0; j < body._shapes.length; j++) {
const shapeB = body._shapes[j];
for (let j = 0; j < body.shapes.length; j++) {
const shapeB = body.shapes[j];
// first, Check collision filter masks
if ((shapeA.collisionFilterGroup & shapeB.collisionFilterMask) === 0 ||
@@ -59,14 +59,14 @@ export class BuiltInBody extends BuiltinObject implements BuiltInRigidBodyBase {
}
public addShape (shape: BuiltinShape): void {
this._shapes.push(shape);
this.shapes.push(shape);
shape.body = this;
}
public removeShape (shape: BuiltinShape): void {
const i = this._shapes.indexOf(shape);
const i = this.shapes.indexOf(shape);
if (i >= 0) {
this._shapes.splice(i, 1);
this.shapes.splice(i, 1);
}
}
@@ -90,7 +90,7 @@ export class BuiltInBody extends BuiltinObject implements BuiltInRigidBodyBase {
public setPosition (pos: Vec3): void {
/** 更新所有形状的位置 */
for (const shape of this._shapes) {
for (const shape of this.shapes) {
shape.setPosition(pos);
}
}
@@ -101,13 +101,13 @@ export class BuiltInBody extends BuiltinObject implements BuiltInRigidBodyBase {
public setRotation (rot: Quat): void {
/** 更新所有形状的方向 */
for (const shape of this._shapes) {
for (const shape of this.shapes) {
shape.setRotation(rot);
}
}
public scaleAllShapes (scale: Vec3): void {
for (const shape of this._shapes) {
for (const shape of this.shapes) {
shape.setScale(scale);
}
}
@@ -121,14 +121,14 @@ export class BuiltInBody extends BuiltinObject implements BuiltInRigidBodyBase {
}
public transform (m: Mat4, pos: Vec3, rot: Quat, scale: Vec3) {
for (let i = this._shapes.length; i--;) {
this._shapes[i].transform(m, pos, rot, scale);
for (let i = this.shapes.length; i--;) {
this.shapes[i].transform(m, pos, rot, scale);
}
}
public translateAndRotate (m: Mat4, rot: Quat): void {
for (let i = this._shapes.length; i--;) {
this._shapes[i].translateAndRotate(m, rot);
for (let i = this.shapes.length; i--;) {
this.shapes[i].translateAndRotate(m, rot);
}
}
}
+62 -17
View File
@@ -3,13 +3,16 @@
*/
import { Vec3 } from '../../core/math';
import { AfterStepCallback, BeforeStepCallback, BuiltInRigidBodyBase, BuiltInWorldBase,
IRaycastOptions, ITriggerEventType, ShapeBase } from '../api';
import { RaycastResult } from '../raycast-result';
import { getWrap } from '../util';
import {
AfterStepCallback, BeforeStepCallback, BuiltInRigidBodyBase, BuiltInWorldBase,
IRaycastOptions, ITriggerEventType
} from '../api';
import { PhysicsRayResult } from '../physics-ray-result';
import { BuiltInBody } from './builtin-body';
import { BuiltinShape } from './shapes/builtin-shape';
import { ArrayCollisionMatrix } from './utils/array-collision-matrix';
import { ray, intersect } from '../../core/geom-utils';
import { RecyclePool } from '../../core';
/**
* Built-in collision system, intended for use as a
@@ -83,10 +86,10 @@ export class BuiltInWorld implements BuiltInWorldBase {
if (this._collisionMatrixPrev.get(shapeA.id, shapeB.id)) {
// emit stay
TriggerEventObject.type = 'onTriggerStay';
TriggerEventObject.type = 'onTriggerStay';
} else {
// first trigger, emit enter
TriggerEventObject.type = 'onTriggerEnter';
TriggerEventObject.type = 'onTriggerEnter';
}
shapeA.onTrigger(TriggerEventObject);
@@ -167,24 +170,66 @@ export class BuiltInWorld implements BuiltInWorldBase {
this._customAfterStepListener.splice(i, 1);
}
public raycastClosest (from: Vec3, to: Vec3, options: IRaycastOptions, result: RaycastResult): boolean {
return false;
public raycastClosest (worldRay: ray, options: IRaycastOptions, out: PhysicsRayResult): boolean {
let tmp_d = Infinity;
const max_d = options.maxDistance!;
const mask = options.mask!;
for (let i = 0; i < this._bodies.length; i++) {
const body = this._bodies[i] as BuiltInBody;
for (let i = 0; i < body.shapes.length; i++) {
const shape = body.shapes[i];
// const collider = shape.getUserData();
// if (!(collider!.node.layer & mask)) {
// continue;
// }
const distance = intersect.resolve(worldRay, shape.worldShape);
if (distance == 0 || distance > max_d) {
continue;
}
if (tmp_d > distance) {
tmp_d = distance;
Vec3.normalize(hitPoint, worldRay.d)
Vec3.scaleAndAdd(hitPoint, worldRay.o, hitPoint, distance);
out._assign(hitPoint, distance, shape);
}
}
}
return !(tmp_d == Infinity);
}
public raycastAny (from: Vec3, to: Vec3, options: IRaycastOptions, result: RaycastResult): boolean {
return false;
public raycast (worldRay: ray, options: IRaycastOptions, pool: RecyclePool<PhysicsRayResult>, results: PhysicsRayResult[]): boolean {
const max_d = options.maxDistance!;
const mask = options.mask!;
for (let i = 0; i < this._bodies.length; i++) {
const body = this._bodies[i] as BuiltInBody;
for (let i = 0; i < body.shapes.length; i++) {
const shape = body.shapes[i];
// const collider = shape.getUserData();
// if (!(collider!.node.layer & mask)) {
// continue;
// }
const distance = intersect.resolve(worldRay, shape.worldShape);
if (distance == 0 || distance > max_d) {
continue;
} else {
const r = pool.add();
worldRay.computeHit(hitPoint, distance);
r._assign(hitPoint, distance, shape);
results.push(r);
}
}
}
return results.length > 0;
}
public raycastAll (from: Vec3, to: Vec3, options: IRaycastOptions, callback: (result: RaycastResult) => void): boolean {
return false;
}
}
const TriggerEventObject = {
type: '' as unknown as ITriggerEventType,
selfCollider: null,
otherCollider: null,
selfCollider: null as any,
otherCollider: null as any,
// selfRigidBody: null,
// otherRigidBody: null,
};
const hitPoint = new Vec3();
+6 -5
View File
@@ -3,6 +3,7 @@ import { ITriggerCallback, ITriggerEvent, ShapeBase } from '../../api';
import { BuiltInBody } from '../builtin-body';
import { IBuiltinShape } from '../builtin-interface';
import { BuiltinObject } from '../object/builtin-object';
import { ColliderComponent } from '../../../../exports/physics-framework';
export class BuiltinShape extends BuiltinObject implements ShapeBase {
@@ -28,7 +29,7 @@ export class BuiltinShape extends BuiltinObject implements ShapeBase {
private readonly _id: number;
private userData: any;
private userData!: ColliderComponent | null;
private _triggeredCB: ITriggerCallback[] = [];
@@ -58,8 +59,8 @@ export class BuiltinShape extends BuiltinObject implements ShapeBase {
Vec3.copy(this._localShape.center, center);
}
public getUserData () {
return this.userData;
public getUserData (): ColliderComponent {
return this.userData!;
}
public setUserData (data: any): void {
@@ -74,7 +75,7 @@ export class BuiltinShape extends BuiltinObject implements ShapeBase {
}
public setPosition (position: Vec3){
public setPosition (position: Vec3) {
}
@@ -86,7 +87,7 @@ export class BuiltinShape extends BuiltinObject implements ShapeBase {
this._localShape.transform(m, pos, rot, scale, this._worldShape);
}
public translateAndRotate (m: Mat4, rot: Quat){
public translateAndRotate (m: Mat4, rot: Quat) {
this._localShape.translateAndRotate(m, rot, this._worldShape);
}
@@ -207,21 +207,11 @@ export class PhysicsBasedComponent extends Component {
}
class SharedRigidBody {
public get isShapeOnly (): boolean { return this._isShapeOnly; }
public get body () {
return this._body;
}
/** the source to manage body transfrom */
public set transfromSource (v: ETransformSource) {
if (v === ETransformSource.SCENE) {
this._isShapeOnly = true;
} else {
this._isShapeOnly = false;
}
}
public get rigidBody () {
return this._rigidBody;
}
@@ -250,9 +240,15 @@ class SharedRigidBody {
private _afterStepCallback!: AfterStepCallback;
/** 是否只有Collider组件 */
private _isShapeOnly: boolean = true;
public get isShapeOnly (): boolean {
return this._isShapeOnly;
}
public set isShapeOnly (v: boolean) {
this._isShapeOnly = v;
}
constructor (node: INode, rigidBody: object | null, world: PhysicsWorldBase) {
this._body = createRigidBody({
@@ -394,11 +390,11 @@ class SharedRigidBody {
private _afterStep () {
if (!CC_PHYSICS_BUILTIN) {
// 物理计算之后,除了只有形状组件的节点,其它有刚体组件的节点,并且刚体类型为DYNAMIC的,需要将计算结果同步到Scene中
if (!this._isShapeOnly && this._body.getType() === ERigidBodyType.DYNAMIC) {
// sync, if body is not static
if (this._body.getType() !== ERigidBodyType.STATIC) {
this._syncSceneWithPhys();
} else {
// 对于只有形状组件的节点,需要将Scene中节点的Transform同步到Phyisc。
// 对于只有形状组件的节点,需要将Scene中节点的Transform同步到Physics。
// 这是因为物理计算后可能会改变一些节点,这会导致这些子节点的Transform也发生改变。
if (this._node.hasChangedFlags) {
this._syncPhysWithScene(this._node);
+60 -7
View File
@@ -3,11 +3,14 @@
*/
import { Vec3 } from '../../core/math';
import { PhysicsWorldBase } from '../api';
import { PhysicsWorldBase, IRaycastOptions } from '../api';
import { createPhysicsWorld } from '../instance';
import { director, Director } from '../../core/director';
import { System } from '../../core/components';
import { PhysicMaterial } from '../assets/physic-material';
import { Layers, RecyclePool } from '../../core';
import { ray } from '../../core/geom-utils';
import { PhysicsRayResult } from '../physics-ray-result';
/**
* @zh
@@ -125,8 +128,8 @@ export class PhysicsSystem extends System {
// this._deltaTime = 1 / this._frameRate;
// }
public static instance: PhysicsSystem;
public static ID: 'physics';
public static readonly instance: PhysicsSystem;
public static readonly ID: 'physics';
public _world: PhysicsWorldBase;
@@ -139,7 +142,21 @@ export class PhysicsSystem extends System {
private readonly _gravity = new Vec3(0, -10, 0);
private readonly _material: PhysicMaterial | null = null;
constructor () {
public readonly raycastClosestResult = new PhysicsRayResult();
public readonly raycastResults: PhysicsRayResult[] = [];
private readonly raycastOptions: IRaycastOptions = {
'group': -1,
'mask': -1,
'queryTrigger': true,
'maxDistance': Infinity
}
private readonly raycastResultPool = new RecyclePool<PhysicsRayResult>(() => {
return new PhysicsRayResult();
}, 1);
private constructor () {
super();
this._world = createPhysicsWorld();
if (!CC_PHYSICS_BUILTIN) {
@@ -176,6 +193,42 @@ export class PhysicsSystem extends System {
director.emit(Director.EVENT_AFTER_PHYSICS);
}
/**
* @zh
* 检测所有的碰撞盒,并记录所有被检测到的结果,通过 PhysicsSystem.instance.raycastResults 访问结果
* @param worldRay 世界空间下的一条射线
* @param mask 掩码
* @param maxDistance 最大检测距离
* @param queryTrigger 是否检测触发器
* @return boolean 表示是否有检测到碰撞盒
* @note 由于目前 Layer 还未完善,mask 暂时失效,请留意更新公告
*/
public raycast (worldRay: ray, mask: number = Layers.Enum.DEFAULT, maxDistance = Infinity, queryTrigger = true): boolean {
this.raycastResultPool.reset();
this.raycastResults.length = 0;
this.raycastOptions.mask = mask;
this.raycastOptions.maxDistance = maxDistance;
this.raycastOptions.queryTrigger = queryTrigger;
return this._world.raycast(worldRay, this.raycastOptions, this.raycastResultPool, this.raycastResults);
}
/**
* @zh
* 检测所有的碰撞盒,并记录与射线距离最短的检测结果,通过 PhysicsSystem.instance.raycastClosestResult 访问结果
* @param worldRay 世界空间下的一条射线
* @param mask 掩码
* @param maxDistance 最大检测距离
* @param queryTrigger 是否检测触发器
* @return boolean 表示是否有检测到碰撞盒
* @note 由于目前 Layer 还未完善,mask 暂时失效,请留意更新公告
*/
public raycastClosest (worldRay: ray, mask: number = Layers.Enum.DEFAULT, maxDistance = Infinity, queryTrigger = true): boolean {
this.raycastOptions.mask = mask;
this.raycastOptions.maxDistance = maxDistance;
this.raycastOptions.queryTrigger = queryTrigger;
return this._world.raycastClosest(worldRay, this.raycastOptions, this.raycastClosestResult);
}
private _updateMaterial () {
if (!CC_PHYSICS_BUILTIN) {
this._world.defaultMaterial = this._material;
@@ -185,7 +238,7 @@ export class PhysicsSystem extends System {
cc.PhysicsSystem = PhysicsSystem;
director.on(Director.EVENT_INIT, function () {
let sys = new PhysicsSystem();
PhysicsSystem.instance = sys;
const sys = new cc.PhysicsSystem();
cc.PhysicsSystem.instance = sys;
director.registerSystem(PhysicsSystem.ID, sys, 0);
});
});
@@ -396,7 +396,8 @@ export class RigidBodyComponent extends PhysicsBasedComponent {
/// COMPONENT LIFECYCLE ///
protected onLoad () {
protected onEnable () {
super.onEnable();
if (!CC_PHYSICS_BUILTIN) {
/**
* 此处设置刚体属性是因为__preload不受executionOrder的顺序影响,
@@ -412,6 +413,7 @@ export class RigidBodyComponent extends PhysicsBasedComponent {
this.fixedRotation = this._fixedRotation;
this.linearFactor = this._linearFactor;
this.angularFactor = this._angularFactor;
this.sharedBody.isShapeOnly = false;
}
}
}
+3 -3
View File
@@ -5,7 +5,7 @@
import { Vec3 } from '../core/math';
import { BoxShapeBase, ICreateBodyOptions, PhysicsWorldBase, RigidBodyBase, SphereShapeBase } from './api';
import { BoxShape, PhysicsWorld, RigidBody, SphereShape } from './impl-selector';
import { RaycastResult } from './raycast-result';
import { PhysicsRayResult } from './physics-ray-result';
export function createPhysicsWorld (): PhysicsWorldBase {
return new PhysicsWorld() as PhysicsWorldBase;
@@ -23,8 +23,8 @@ export function createSphereShape (radius: number): SphereShapeBase {
return new SphereShape(radius);
}
export function createRaycastResult (): RaycastResult {
return new RaycastResult();
export function createRaycastResult (): PhysicsRayResult {
return new PhysicsRayResult();
}
cc.createRaycastResult = createRaycastResult;
+64
View File
@@ -0,0 +1,64 @@
/**
* @category physics
*/
import { Vec3 } from '../core/math';
import { ShapeBase } from './api';
import { ColliderComponent } from '../../exports/physics-framework';
/**
* @zh
* 用于保存物理射线检测结果
*/
export class PhysicsRayResult {
/**
* @zh
* 击中点
*/
get hitPoint (): Vec3 {
return this._hitPoint;
}
/**
* @zh
* 距离
*/
get distance (): number {
return this._distance;
}
/**
* @zh
* 击中的碰撞盒
*/
get collider (): ColliderComponent {
return this._collidier!;
}
private _hitPoint: Vec3 = new Vec3();
private _distance: number = 0;
private _collidier: ColliderComponent | null = null;
/**
* @zh
* 设置射线,此方法由引擎内部使用,请勿在外部脚本调用
*/
public _assign (hitPoint: Vec3, distance: number, shape: ShapeBase) {
Vec3.copy(this._hitPoint, hitPoint);
this._distance = distance;
this._collidier = shape.getUserData() as ColliderComponent;
}
/**
* @zh
* 克隆
*/
public clone () {
const c = new PhysicsRayResult();
Vec3.copy(c._hitPoint, this._hitPoint);
c._distance = this._distance;
c._collidier = this._collidier;
return c;
}
}
-38
View File
@@ -1,38 +0,0 @@
/**
* @hidden
*/
import { Component } from '../core/components/component';
import { Vec3 } from '../core/math';
import { RigidBodyBase, ShapeBase } from './api';
import { INode } from '../core/utils/interfaces';
export class RaycastResult {
get hitPoint (): Vec3 {
return this._hitPoint;
}
get distance (): number {
return this._distance;
}
get collider (): Component {
return this._collidier!;
}
get node (): INode {
return this._node!;
}
private _hitPoint: Vec3 = new Vec3();
private _distance: number = 0;
private _collidier: Component | null = null;
private _node: INode | null = null;
public _assign (hitPoint: any, distance: number, shape: ShapeBase, body: RigidBodyBase) {
Vec3.copy(this._hitPoint, hitPoint);
this._distance = distance;
this._node = body.getUserData();
this._collidier = shape.getUserData() as Component;
}
}
+1
View File
@@ -250,6 +250,7 @@ export class TerrainBlock {
attributes: gfxAttributes,
vertexBuffers: [vertexBuffer],
indexBuffer : this._terrain.getSharedIndexBuffer(),
flatBuffers : [],
primitiveMode: GFXPrimitiveMode.TRIANGLE_LIST,
};
+54 -73
View File
@@ -31,7 +31,7 @@
import { EventHandler as ComponentEventHandler } from '../../core/components';
import { ccclass, executionOrder, menu, property } from '../../core/data/class-decorator';
import { Event } from '../../core/event';
import { EventMouse, EventTouch, SystemEventType, Touch } from '../../core/platform';
import { EventMouse, EventTouch, Touch } from '../../core/platform';
import { Size, Vec2, Vec3 } from '../../core/math';
import { ccenum } from '../../core/value-types/enum';
import { LayoutComponent } from './layout-component';
@@ -41,16 +41,16 @@ import { INode } from '../../core/utils/interfaces';
import { Node } from '../../core/scene-graph/node';
import { director, Director } from '../../core/director';
const NodeEvent = SystemEventType;
const NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED = 5;
const OUT_OF_BOUNDARY_BREAKING_FACTOR = 0.05;
const EPSILON = 1e-4;
const MOVEMENT_FACTOR = 0.7;
const ZERO = new Vec3();
const _tempPos = new Vec3();
const _tempVec2 = new Vec2();
const _tempVec2_1 = new Vec2();
const quintEaseOut = (time) => {
const quintEaseOut = (time: number) => {
time -= 1;
return (time * time * time * time * time + 1);
};
@@ -304,7 +304,7 @@ export class ScrollViewComponent extends ViewGroupComponent {
protected _autoScrolling = false;
protected _scrolling = false;
@property
private _content: INode | null = null;
protected _content: INode | null = null;
@property
protected _horizontalScrollBar: ScrollBarComponent | null = null;
@property
@@ -770,12 +770,12 @@ export class ScrollViewComponent extends ViewGroupComponent {
if (!CC_EDITOR) {
this._registerEvent();
if (this.content) {
this.content.on(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this);
this.content.on(NodeEvent.SCALE_PART, this._calculateBoundary, this);
this.content.on(Node.EventType.SIZE_CHANGED, this._calculateBoundary, this);
this.content.on(Node.EventType.SCALE_PART, this._calculateBoundary, this);
if (this.view!) {
this.view!.on(NodeEvent.POSITION_PART, this._calculateBoundary, this);
this.view!.on(NodeEvent.SCALE_PART, this._calculateBoundary, this);
this.view!.on(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this);
this.view!.on(Node.EventType.POSITION_PART, this._calculateBoundary, this);
this.view!.on(Node.EventType.SCALE_PART, this._calculateBoundary, this);
this.view!.on(Node.EventType.SIZE_CHANGED, this._calculateBoundary, this);
}
}
}
@@ -792,12 +792,12 @@ export class ScrollViewComponent extends ViewGroupComponent {
if (!CC_EDITOR) {
this._unregisterEvent();
if (this.content) {
this.content.off(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this);
this.content.off(NodeEvent.SCALE_PART, this._calculateBoundary, this);
this.content.off(Node.EventType.SIZE_CHANGED, this._calculateBoundary, this);
this.content.off(Node.EventType.SCALE_PART, this._calculateBoundary, this);
if (this.view!) {
this.view!.off(NodeEvent.POSITION_PART, this._calculateBoundary, this);
this.view!.off(NodeEvent.SCALE_PART, this._calculateBoundary, this);
this.view!.off(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this);
this.view!.off(Node.EventType.POSITION_PART, this._calculateBoundary, this);
this.view!.off(Node.EventType.SCALE_PART, this._calculateBoundary, this);
this.view!.off(Node.EventType.SIZE_CHANGED, this._calculateBoundary, this);
}
}
}
@@ -807,29 +807,22 @@ export class ScrollViewComponent extends ViewGroupComponent {
// private methods
protected _registerEvent () {
this.node.on(NodeEvent.TOUCH_START, this._onTouchBegan, this, true);
this.node.on(NodeEvent.TOUCH_MOVE, this._onTouchMoved, this, true);
this.node.on(NodeEvent.TOUCH_END, this._onTouchEnded, this, true);
this.node.on(NodeEvent.TOUCH_CANCEL, this._onTouchCancelled, this, true);
this.node.on(NodeEvent.MOUSE_WHEEL, this._onMouseWheel, this, true);
this.node.on(Node.EventType.TOUCH_START, this._onTouchBegan, this, true);
this.node.on(Node.EventType.TOUCH_MOVE, this._onTouchMoved, this, true);
this.node.on(Node.EventType.TOUCH_END, this._onTouchEnded, this, true);
this.node.on(Node.EventType.TOUCH_CANCEL, this._onTouchCancelled, this, true);
this.node.on(Node.EventType.MOUSE_WHEEL, this._onMouseWheel, this, true);
}
protected _unregisterEvent () {
this.node.off(NodeEvent.TOUCH_START, this._onTouchBegan, this, true);
this.node.off(NodeEvent.TOUCH_MOVE, this._onTouchMoved, this, true);
this.node.off(NodeEvent.TOUCH_END, this._onTouchEnded, this, true);
this.node.off(NodeEvent.TOUCH_CANCEL, this._onTouchCancelled, this, true);
this.node.off(NodeEvent.MOUSE_WHEEL, this._onMouseWheel, this, true);
this.node.off(Node.EventType.TOUCH_START, this._onTouchBegan, this, true);
this.node.off(Node.EventType.TOUCH_MOVE, this._onTouchMoved, this, true);
this.node.off(Node.EventType.TOUCH_END, this._onTouchEnded, this, true);
this.node.off(Node.EventType.TOUCH_CANCEL, this._onTouchCancelled, this, true);
this.node.off(Node.EventType.MOUSE_WHEEL, this._onMouseWheel, this, true);
}
/**
* @zh
* 鼠标滚轮事件。
*
* @param event - 鼠标事件信息。
* @param captureListeners
*/
protected _onMouseWheel (event: EventMouse, captureListeners?: any) {
protected _onMouseWheel (event: EventMouse, captureListeners?: INode[]) {
if (!this.enabledInHierarchy) {
return;
}
@@ -859,8 +852,7 @@ export class ScrollViewComponent extends ViewGroupComponent {
this._stopPropagationIfTargetIsMe(event);
}
// touch event handler
protected _onTouchBegan (event: EventTouch, captureListeners?: any) {
protected _onTouchBegan (event: EventTouch, captureListeners?: INode[]) {
if (!this.enabledInHierarchy || !this._content) { return; }
if (this._hasNestedViewGroup(event, captureListeners)) { return; }
@@ -872,15 +864,11 @@ export class ScrollViewComponent extends ViewGroupComponent {
this._stopPropagationIfTargetIsMe(event);
}
protected _onTouchMoved (event: EventTouch, captureListeners?: any) {
protected _onTouchMoved (event: EventTouch, captureListeners?: INode[]) {
if (!this.enabledInHierarchy || !this._content) { return; }
if (this._hasNestedViewGroup(event, captureListeners)) { return; }
if (!event || !event.touch) {
return;
}
const touch = event.touch;
const touch = event.touch!;
if (this._content) {
this._handleMoveLogic(touch);
}
@@ -889,14 +877,14 @@ export class ScrollViewComponent extends ViewGroupComponent {
return;
}
const deltaMove = new Vec2(touch.getUILocation());
deltaMove.subtract(touch.getUIStartLocation());
const deltaMove = touch.getUILocation(_tempVec2);
deltaMove.subtract(touch.getUIStartLocation(_tempVec2_1));
// FIXME: touch move delta should be calculated by DPI.
if (deltaMove.length() > 7) {
if (!this._touchMoved && event.target !== this.node) {
// Simulate touch cancel for target node
const cancelEvent = new EventTouch(event.getTouches(), event.bubbles);
cancelEvent.type = NodeEvent.TOUCH_CANCEL;
cancelEvent.type = Node.EventType.TOUCH_CANCEL;
cancelEvent.touch = event.touch;
cancelEvent.simulate = true;
(event.target as INode)!.dispatchEvent(cancelEvent);
@@ -906,13 +894,13 @@ export class ScrollViewComponent extends ViewGroupComponent {
this._stopPropagationIfTargetIsMe(event);
}
protected _onTouchEnded (event: EventTouch, captureListeners?: any) {
protected _onTouchEnded (event: EventTouch, captureListeners?: INode[]) {
if (!this.enabledInHierarchy || !this._content || !event) { return; }
if (this._hasNestedViewGroup(event, captureListeners)) { return; }
this._dispatchEvent('touch-up');
const touch = event.touch;
const touch = event.touch!;
if (this._content) {
this._handleReleaseLogic(touch);
}
@@ -923,13 +911,13 @@ export class ScrollViewComponent extends ViewGroupComponent {
}
}
protected _onTouchCancelled (event: EventTouch, captureListeners?: any) {
protected _onTouchCancelled (event: EventTouch, captureListeners?: INode[]) {
if (!this.enabledInHierarchy || !this._content) { return; }
if (this._hasNestedViewGroup(event, captureListeners)) { return; }
// Filte touch cancel event send from self
if (event && !event.simulate) {
const touch = event.touch;
const touch = event.touch!;
if (this._content) {
this._handleReleaseLogic(touch);
}
@@ -937,14 +925,10 @@ export class ScrollViewComponent extends ViewGroupComponent {
this._stopPropagationIfTargetIsMe(event);
}
/**
* @zh
* 重新计算内容活动边界(view)
*/
protected _calculateBoundary () {
if (this.content) {
// refresh content size
const layout:LayoutComponent = this.content.getComponent(LayoutComponent);
const layout: LayoutComponent = this.content.getComponent(LayoutComponent);
if (layout && layout.enabledInHierarchy) {
layout.updateLayout();
}
@@ -964,8 +948,7 @@ export class ScrollViewComponent extends ViewGroupComponent {
}
// this is for nested scrollview
protected _hasNestedViewGroup (event?: Event, captureListeners?: any) {
protected _hasNestedViewGroup (event: Event, captureListeners?: INode[]) {
if (!event || event.eventPhase !== Event.CAPTURING_PHASE) {
return;
}
@@ -973,7 +956,7 @@ export class ScrollViewComponent extends ViewGroupComponent {
if (captureListeners) {
// captureListeners are arranged from child to parent
for (const listerner of captureListeners) {
const item = listerner as INode;
const item = listerner;
if (this.node === item) {
if (event.target && (event.target as INode).getComponent(ViewGroupComponent)) {
@@ -990,7 +973,7 @@ export class ScrollViewComponent extends ViewGroupComponent {
return false;
}
protected _handleReleaseLogic (touch) {
protected _handleReleaseLogic (touch: Touch) {
const delta = touch.getUIDelta();
Vec3.set(this._deltaPos, delta.x, delta.y, 0);
this._gatherTouchMove(this._deltaPos);
@@ -1061,7 +1044,7 @@ export class ScrollViewComponent extends ViewGroupComponent {
this._startAutoScroll(targetDelta, time, true);
}
protected _calculateAutoScrollTimeByInitalSpeed (initalSpeed) {
protected _calculateAutoScrollTimeByInitalSpeed (initalSpeed: number) {
return Math.sqrt(Math.sqrt(initalSpeed / 5));
}
@@ -1204,7 +1187,7 @@ export class ScrollViewComponent extends ViewGroupComponent {
}
}
protected _dispatchEvent (event) {
protected _dispatchEvent (event: string) {
if (event === 'scroll-ended') {
this._scrollEventEmitMask = 0;
@@ -1232,11 +1215,11 @@ export class ScrollViewComponent extends ViewGroupComponent {
this._outOfBoundaryAmountDirty = true;
if (this._isOutOfBoundary()) {
const outOfBoundary = this._getHowMuchOutOfBoundary(new Vec3());
const newPosition = new Vec3(this.getContentPosition());
newPosition.add(outOfBoundary);
const outOfBoundary = this._getHowMuchOutOfBoundary();
_tempPos.set(this.getContentPosition());
_tempPos.add(outOfBoundary);
if (this._content) {
this._content.setPosition(newPosition);
this._content.setPosition(_tempPos);
// this._updateScrollBar(0);
this._updateScrollBar(ZERO);
}
@@ -1264,8 +1247,8 @@ export class ScrollViewComponent extends ViewGroupComponent {
}
// This is for Scrollview as children of a Button
protected _stopPropagationIfTargetIsMe (event?: Event) {
if (event && event.eventPhase === Event.AT_TARGET && event.target === this.node) {
protected _stopPropagationIfTargetIsMe (event: Event) {
if (event.eventPhase === Event.AT_TARGET && event.target === this.node) {
event.propagationStopped = true;
}
}
@@ -1348,6 +1331,7 @@ export class ScrollViewComponent extends ViewGroupComponent {
if (this._autoScrolling) {
this._dispatchEvent('scroll-ended');
}
this._autoScrolling = false;
this._isBouncing = false;
@@ -1372,14 +1356,15 @@ export class ScrollViewComponent extends ViewGroupComponent {
}
protected _gatherTouchMove (delta: Vec3) {
delta = this._clampDelta(delta);
const clampDt = delta.clone();
this._clampDelta(clampDt);
while (this._touchMoveDisplacements.length >= NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED) {
this._touchMoveDisplacements.shift();
this._touchMoveTimeDeltas.shift();
}
this._touchMoveDisplacements.push(delta);
this._touchMoveDisplacements.push(clampDt);
const timeStamp = getTimeInMilliseconds();
this._touchMoveTimeDeltas.push((timeStamp - this._touchMovePreviousTimestamp) / 1000);
@@ -1557,12 +1542,6 @@ export class ScrollViewComponent extends ViewGroupComponent {
return moveDelta;
}
/**
* @zh
*
*
* @param scrollViewSize - 可视区域尺寸。
*/
protected _moveContentToTopLeft (scrollViewSize: Size) {
const contentSize = this._content!.getContentSize();
@@ -1574,6 +1553,7 @@ export class ScrollViewComponent extends ViewGroupComponent {
let leftDeta = this._getContentLeftBoundary() - this._leftBoundary;
leftDeta = -leftDeta;
// 是否限制在上视区上边
if (contentSize.height < scrollViewSize.height) {
totalScrollDelta = contentSize.height - scrollViewSize.height;
moveDelta.y = bottomDeta - totalScrollDelta;
@@ -1587,6 +1567,7 @@ export class ScrollViewComponent extends ViewGroupComponent {
}
}
// 是否限制在上视区左边
if (contentSize.width < scrollViewSize.width) {
totalScrollDelta = contentSize.width - scrollViewSize.width;
moveDelta.x = leftDeta;
+7 -7
View File
@@ -28,13 +28,13 @@
* @category ui
*/
import { RenderableComponent } from '../../core/3d/framework/renderable-component';
import { Material } from '../../core/assets';
import { UIComponent } from '../../core/components/ui-base/ui-component';
import { ccclass, executionOrder, menu } from '../../core/data/class-decorator';
import { director } from '../../core/director';
import { RenderPriority } from '../../core/pipeline/define';
import { UI } from '../../core/renderer/ui/ui';
import { Material } from '../../core/assets';
import { RenderableComponent } from '../../core/3d/framework/renderable-component';
import { UIComponent } from '../../core/components/ui-base/ui-component';
import { director } from '../../core/director';
/**
* @zh
@@ -54,8 +54,8 @@ export class UIModelComponent extends UIComponent {
public onLoad () {
this._modelComponent = this.getComponent('cc.RenderableComponent') as RenderableComponent;
if (!this._modelComponent){
console.warn(`Use this component on a node(${this.node && this.node.name}) that has a model component`);
if (!this._modelComponent) {
console.warn(`node '${this.node && this.node.name}' doesn't have any renderable component`);
return;
}
@@ -65,7 +65,7 @@ export class UIModelComponent extends UIComponent {
public onDestroy () {
this._modelComponent = this.getComponent('cc.RenderableComponent') as RenderableComponent;
if (!this._modelComponent){
if (!this._modelComponent) {
return;
}
+5 -2
View File
@@ -3,6 +3,7 @@
*/
import { PhysicMaterial } from '../cocos/physics/assets/physic-material';
import { PhysicsRayResult } from '../cocos/physics/physics-ray-result';
import { BoxColliderComponent } from '../cocos/physics/components/collider/box-collider-component';
import { ColliderComponent } from '../cocos/physics/components/collider/collider-component';
import { SphereColliderComponent } from '../cocos/physics/components/collider/sphere-collider-component';
@@ -14,11 +15,13 @@ export {
BoxColliderComponent,
SphereColliderComponent,
RigidBodyComponent,
PhysicMaterial
PhysicMaterial,
PhysicsRayResult
};
cc.ColliderComponent = ColliderComponent;
cc.BoxColliderComponent = BoxColliderComponent;
cc.SphereColliderComponent = SphereColliderComponent;
cc.RigidBodyComponent = RigidBodyComponent;
cc.PhysicMaterial = PhysicMaterial;
cc.PhysicMaterial = PhysicMaterial;
cc.PhysicsRayResult = PhysicsRayResult;
+10 -10
View File
@@ -877,6 +877,11 @@
"minimist": "^1.2.0"
}
},
"@cocos/cannon": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/@cocos/cannon/-/cannon-1.0.2.tgz",
"integrity": "sha512-BMr1vEB+eKC1ZGxX0642uj3C4v6tul/T15ZfBAN9gH4Hp/JcNtFooQjcPcxACKoDcErw4zPnX777cZFec4lZbA=="
},
"@jest/console": {
"version": "24.9.0",
"resolved": "https://registry.npm.taobao.org/@jest/console/download/@jest/console-24.9.0.tgz",
@@ -3116,11 +3121,6 @@
"integrity": "sha1-uRk+KTzPfkQmxSRRNLjypWwKxLk=",
"dev": true
},
"cannon": {
"version": "github:cocos-creator/cannon.js#b4461faffe280150a9990f66a0a592c2b06adff4",
"from": "github:cocos-creator/cannon.js#cc1.0.1",
"dev": true
},
"capture-exit": {
"version": "2.0.0",
"resolved": "https://registry.npm.taobao.org/capture-exit/download/capture-exit-2.0.0.tgz",
@@ -12350,9 +12350,9 @@
"dev": true
},
"tfig": {
"version": "1.0.25",
"resolved": "https://registry.npm.taobao.org/tfig/download/tfig-1.0.25.tgz",
"integrity": "sha1-ySivNQRq8QFyceyzhk/+3O4i+78=",
"version": "1.1.0",
"resolved": "https://registry.npm.taobao.org/tfig/download/tfig-1.1.0.tgz",
"integrity": "sha1-fxOXsBiTYfDv3MgmTOyEO/Gp0Ug=",
"dev": true,
"requires": {
"fs-extra": "^7.0.1",
@@ -12362,7 +12362,7 @@
"dependencies": {
"ansi-regex": {
"version": "4.1.0",
"resolved": "https://registry.npm.taobao.org/ansi-regex/download/ansi-regex-4.1.0.tgz",
"resolved": "https://registry.npm.taobao.org/ansi-regex/download/ansi-regex-4.1.0.tgz?cache=0&sync_timestamp=1570188663907&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fansi-regex%2Fdownload%2Fansi-regex-4.1.0.tgz",
"integrity": "sha1-i5+PCM8ay4Q3Vqg5yox+MWjFGZc=",
"dev": true
},
@@ -12449,7 +12449,7 @@
},
"yargs": {
"version": "13.3.0",
"resolved": "https://registry.npm.taobao.org/yargs/download/yargs-13.3.0.tgz?cache=0&sync_timestamp=1567812307271&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fyargs%2Fdownload%2Fyargs-13.3.0.tgz",
"resolved": "https://registry.npm.taobao.org/yargs/download/yargs-13.3.0.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fyargs%2Fdownload%2Fyargs-13.3.0.tgz",
"integrity": "sha1-TGV6VeB+Xyz5R/ijZlZ8BKDe3IM=",
"dev": true,
"requires": {
+4 -2
View File
@@ -43,7 +43,6 @@
"babel-preset-env": "^1.2.2",
"babelify": "7.3.0",
"browserify": "^16.2.3",
"cannon": "github:cocos-creator/cannon.js#cc1.0.1",
"chalk": "1.1.0",
"commander": "^2.20.0",
"dat.gui": "^0.7.5",
@@ -84,7 +83,7 @@
"rollup-plugin-terser": "^5.1.1",
"rollup-plugin-uglify": "^6.0.2",
"rollup-watch": "^4.3.1",
"tfig": "^1.0.25",
"tfig": "^1.1.0",
"ts-jest": "^24.0.2",
"tween.js": "github:cocos-creator/tween.js#cocos-master",
"typedoc": "^0.14.2",
@@ -98,5 +97,8 @@
"vinyl-source-stream": "1.0.0",
"watchify": "^3.7.0",
"yargs": "^12.0.5"
},
"dependencies": {
"@cocos/cannon": "^1.0.2"
}
}
+2 -2
View File
@@ -174,7 +174,7 @@ async function _internalBuild (options: IAdvancedOptions) {
extensions: ['.js', '.ts'],
highlightCode: true,
ignore: [
'node_modules/cannon/**',
'node_modules/@cocos/cannon/**',
'node_modules/tween.js/**',
],
plugins: [
@@ -196,7 +196,7 @@ async function _internalBuild (options: IAdvancedOptions) {
commonjs({
namedExports: {
'cannon': ['CANNON', 'Shape'],
'@cocos/cannon': ['CANNON'],
'tween.js': ['TWEEN'],
},
}),
@@ -1,11 +1,11 @@
const { generate } = require('./generate-declarations');
generate({
outDir: './bin/.declarations',
}).then((successed) => {
if (successed) {
console.log(`Successed.`);
} else {
console.error(`Failed to generate declaration files.`);
}
});
/* eslint-disable @typescript-eslint/no-require-imports */
/* eslint-disable @typescript-eslint/no-var-requires */
const { generate } = require('./generate-declarations');
const fs = require('fs-extra');
const outDir = './bin/.declarations';
(async () => {
await fs.emptyDir(outDir);
await generate({ outDir });
})();
@@ -1,30 +1,39 @@
const { spawn, execSync } = require('child_process');
/* eslint-disable no-console */
/* eslint-disable @typescript-eslint/no-require-imports */
/* eslint-disable @typescript-eslint/no-var-requires */
const { join, extname, basename, dirname, isAbsolute } = require('path');
const { copyFileSync, existsSync, readFileSync, unlinkSync, writeFileSync, ensureDirSync } = require('fs-extra');
const ts = require('typescript');
const gift = require('tfig');
const tscExecutableName = process.platform === 'win32' ? 'tsc.cmd' : 'tsc';
const tscExecutablePath = join(__dirname, '..', '..', 'node_modules', '.bin', tscExecutableName);
const tsConfigDir = join(__dirname, '..', '..');
const tsConfigPath = join(tsConfigDir, 'tsconfig.json');
const tempTsConfigPath = join(tsConfigDir, '__tsconfig-gendecls.json');
async function generate (options) {
const tsConfig = ts.readConfigFile(tsConfigPath, (path) => readFileSync(path).toString());
if (tsConfig.error) {
console.error(`Bad tsconfig.json: ${tsConfig.error.messageText}`);
return undefined;
}
console.log(`Typescript version: ${ts.version}`);
const { outDir } = options;
ensureDirSync(outDir);
tsConfig.config.compilerOptions.declaration = true;
tsConfig.config.compilerOptions.emitDeclarationOnly = true;
tsConfig.config.compilerOptions.outFile = join(outDir, `index.js`);
const unbundledOutFile = join(outDir, `cc-before-rollup.js`);
const parsedCommandLine = ts.getParsedCommandLineOfConfigFile(
tsConfigPath, {
declaration: true,
emitDeclarationOnly: true,
outFile: unbundledOutFile,
outDir: undefined,
}, {
onUnRecoverableConfigFileDiagnostic: () => {},
useCaseSensitiveFileNames: ts.sys.useCaseSensitiveFileNames,
readDirectory: ts.sys.readDirectory,
getCurrentDirectory: ts.sys.getCurrentDirectory,
fileExists: ts.sys.fileExists,
readFile: ts.sys.readFile,
}
);
const outputJSPath = join(tsConfigDir, tsConfig.config.compilerOptions.outFile);
const outputJSPath = join(tsConfigDir, unbundledOutFile);
// console.log(outputJSPath);
const extName = extname(outputJSPath);
@@ -46,52 +55,43 @@ async function generate (options) {
}
}
console.log(`Make temp config file ${tempTsConfigPath}.`);
writeFileSync(tempTsConfigPath, JSON.stringify(tsConfig.config, undefined, 4));
console.log(`Generating...`);
await new Promise((resolve) => {
const tscProcess = spawn(tscExecutablePath, [
'--version',
]);
tscProcess.on('exit', (code) => {
resolve(code);
});
tscProcess.stdout.on('data', (data) => {
console.log(`Typescript version: ${data.toString()}`);
});
tscProcess.stderr.on('data', (data) => {
console.error(data.toString());
});
});
const tscExitCode = await new Promise((resolve) => {
const tscProcess = spawn(tscExecutablePath, [
'-p',
tempTsConfigPath,
], {
cwd: process.cwd(),
env: process.env,
});
tscProcess.on('exit', (code) => {
resolve(code);
});
tscProcess.stdout.on('data', (data) => {
console.log(data.toString());
});
tscProcess.stderr.on('data', (data) => {
console.error(data.toString());
});
});
console.log(`Delete temp config file ${tempTsConfigPath}.`);
unlinkSync(tempTsConfigPath);
if (tscExitCode !== 0) {
console.warn(`tsc exited with non-zero status code ${tscExitCode}.`);
const program = ts.createProgram(parsedCommandLine.fileNames, parsedCommandLine.options);
const emitResult = program.emit(
undefined, // targetSourceFile
undefined, // writeFile
undefined, // cancellationToken,
true, // emitOnlyDtsFiles
undefined, // customTransformers
);
let allDiagnostics = ts.getPreEmitDiagnostics(program).concat(emitResult.diagnostics);
for (const diagnostic of allDiagnostics) {
let printer;
switch (diagnostic.category) {
case ts.DiagnosticCategory.Error:
printer = console.error;
break;
case ts.DiagnosticCategory.Warning:
printer = console.warn;
break;
case ts.DiagnosticCategory.Message:
case ts.DiagnosticCategory.Suggestion:
default:
printer = console.log;
break;
}
if (!printer) {
continue;
}
if (diagnostic.file) {
let { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
let message = ts.flattenDiagnosticMessageText(diagnostic.messageText);
printer(`${diagnostic.file.fileName} (${line + 1},${character + 1}): ${message}`);
} else {
printer(`${ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n")}`);
}
}
const tscOutputDtsFile = join(dirName, baseName + '.d.ts');
@@ -100,7 +100,7 @@ async function generate (options) {
return false;
}
const types = tsConfig.config.compilerOptions.types.map((typeFile) => `${typeFile}.d.ts`);
const types = parsedCommandLine.options.types.map((typeFile) => `${typeFile}.d.ts`);
types.forEach((file) => {
const destPath = join(outDir, isAbsolute(file) ? basename(file) : file);
ensureDirSync(dirname(destPath));
@@ -0,0 +1,13 @@
import { StorageUnit, ElementType, combineStorageUnitElementType, extractStorageUnitElementType } from '../../cocos/core/data/utils/compact-value-type-array';
test('Combine storage unit & element type', () => {
const storageUnits = Object.values(StorageUnit).filter((e) => typeof e === 'number') as StorageUnit[];
const elementTypes = Object.values(ElementType).filter((e) => typeof e === 'number') as ElementType[];
for (const storageUnit of storageUnits) {
for (const elementType of elementTypes) {
const combined = combineStorageUnitElementType(storageUnit, elementType);
const extracted = extractStorageUnitElementType(combined);
expect(extracted.storageUnit === storageUnit && extracted.elementType === elementType).toBe(true);
}
}
});
+3 -2
View File
@@ -16,9 +16,10 @@
"./@types/editor-extends",
"./@types/ammo.js",
"./@types/wx",
"./cocos/core/gfx/webgl/WebGL",
"./cocos/core/gfx/webgl2/WebGL2",
"./@types/webGL.extras",
"./@types/webGL2.extras",
"./node_modules/tween.js/TWEEN",
"./node_modules/@cocos/cannon/CANNON",
"./node_modules/@types/jest/index"
]
},
+2
View File
@@ -13,6 +13,7 @@
true,
"check-open-brace"
],
"no-namespace": false,
"no-console": false,
"space-before-function-paren": true,
"max-classes-per-file": false,
@@ -23,6 +24,7 @@
"no-empty": false,
"radix": false,
"prefer-for-of": false,
"forin":false,
"max-line-length": [
true,