(function(window,document,Laya){ var __un=Laya.un,__uns=Laya.uns,__static=Laya.static,__class=Laya.class,__getset=Laya.getset,__newvec=Laya.__newvec; var AnimationContent=laya.ani.AnimationContent,AnimationPlayer=laya.ani.AnimationPlayer,AnimationState=laya.ani.AnimationState; var AnimationTemplet=laya.ani.AnimationTemplet,Arith=laya.maths.Arith,AtlasResourceManager=laya.webgl.atlas.AtlasResourceManager; var BaseShader=laya.webgl.shader.BaseShader,Browser=laya.utils.Browser,Buffer=laya.webgl.utils.Buffer,Byte=laya.utils.Byte; var CacheAbleSkinMesh=laya.ani.bone.canvasmesh.CacheAbleSkinMesh,ClassUtils=laya.utils.ClassUtils,Config=Laya.Config; var Event=laya.events.Event,EventDispatcher=laya.events.EventDispatcher,Handler=laya.utils.Handler,Loader=laya.net.Loader; var LoaderManager=laya.net.LoaderManager,MathUtil=laya.maths.MathUtil,Node=laya.display.Node,Render=laya.renders.Render; var RenderContext=laya.renders.RenderContext,RenderSprite=laya.renders.RenderSprite,RenderState2D=laya.webgl.utils.RenderState2D; var Resource=laya.resource.Resource,RunDriver=laya.utils.RunDriver,Shader=laya.webgl.shader.Shader,ShaderCompile=laya.webgl.utils.ShaderCompile; var Sprite=laya.display.Sprite,Stat=laya.utils.Stat,StringKey=laya.utils.StringKey,Style=laya.display.css.Style; var Texture=laya.resource.Texture,URL=laya.net.URL,Utils=laya.utils.Utils,WebGL=laya.webgl.WebGL,WebGLContext=laya.webgl.WebGLContext; var WebGLContext2D=laya.webgl.canvas.WebGLContext2D; Laya.interface('laya.d3.core.IClone'); Laya.interface('laya.d3.graphics.IVertex'); Laya.interface('laya.d3.core.render.IUpdate'); Laya.interface('laya.d3.core.scene.ITreeNode'); Laya.interface('laya.d3.core.render.IRenderable'); /** *@private */ //class laya.d3.animation.AnimationClipParser01 var AnimationClipParser01=(function(){ function AnimationClipParser01(){} __class(AnimationClipParser01,'laya.d3.animation.AnimationClipParser01'); AnimationClipParser01.READ_DATA=function(){ AnimationClipParser01._DATA.offset=AnimationClipParser01._reader.getUint32(); AnimationClipParser01._DATA.size=AnimationClipParser01._reader.getUint32(); } AnimationClipParser01.READ_BLOCK=function(){ var count=AnimationClipParser01._BLOCK.count=AnimationClipParser01._reader.getUint16(); var blockStarts=AnimationClipParser01._BLOCK.blockStarts=[]; var blockLengths=AnimationClipParser01._BLOCK.blockLengths=[]; for (var i=0;i < count;i++){ blockStarts.push(AnimationClipParser01._reader.getUint32()); blockLengths.push(AnimationClipParser01._reader.getUint32()); } } AnimationClipParser01.READ_STRINGS=function(){ var offset=AnimationClipParser01._reader.getUint32(); var count=AnimationClipParser01._reader.getUint16(); var prePos=AnimationClipParser01._reader.pos; AnimationClipParser01._reader.pos=offset+AnimationClipParser01._DATA.offset; for (var i=0;i < count;i++) AnimationClipParser01._strings[i]=AnimationClipParser01._reader.readUTFString(); AnimationClipParser01._reader.pos=prePos; } AnimationClipParser01.parse=function(clip,reader){ AnimationClipParser01._animationClip=clip; AnimationClipParser01._reader=reader; var arrayBuffer=reader.__getBuffer(); AnimationClipParser01.READ_DATA(); AnimationClipParser01.READ_BLOCK(); AnimationClipParser01.READ_STRINGS(); for (var i=0,n=AnimationClipParser01._BLOCK.count;i < n;i++){ var index=reader.getUint16(); var blockName=AnimationClipParser01._strings[index]; var fn=AnimationClipParser01["READ_"+blockName]; if (fn==null) throw new Error("model file err,no this function:"+index+" "+blockName); else fn.call(); } } AnimationClipParser01.READ_ANIMATIONS=function(){ var i=0,j=0; var node; var reader=AnimationClipParser01._reader; var buffer=reader.__getBuffer(); var lengthTypes=[]; var lenghthTypeCount=reader.getUint8(); lengthTypes.length=lenghthTypeCount; for (i=0;i < lenghthTypeCount;i++) lengthTypes[i]=reader.getUint16(); var startTimeTypes=[]; var startTimeTypeCount=reader.getUint16(); startTimeTypes.length=startTimeTypeCount; for (i=0;i < startTimeTypeCount;i++) startTimeTypes[i]=reader.getFloat32(); var clip=AnimationClipParser01._animationClip; clip.name=AnimationClipParser01._strings[reader.getUint16()]; var clipDur=clip._duration=reader.getFloat32(); clip.islooping=!!reader.getByte(); clip._frameRate=reader.getInt16(); var nodeCount=reader.getInt16(); var nodes=clip._nodes=new Array; nodes.length=nodeCount; var publicDatas=clip._publicClipDatas=[]; publicDatas.length=nodeCount; var nodesMap=clip._nodesMap={}; var cachePropertyToNodeIndex=0,unCachePropertyToNodeIndex=0; for (i=0;i < nodeCount;i++){ node=nodes[i]=new KeyframeNode(); var pathLength=reader.getUint16(); var path=node.path=[]; path.length=pathLength; for (j=0;j < pathLength;j++) path[j]=AnimationClipParser01._strings[reader.getUint16()]; var nodePath=path.join("/"); var mapArray=nodesMap[nodePath]; (mapArray)|| (nodesMap[nodePath]=mapArray=[]); mapArray.push(node); var componentTypeStrIndex=reader.getInt16(); (componentTypeStrIndex!==-1)&& (node.componentType=AnimationClipParser01._strings[componentTypeStrIndex]); var propertyNameID=AnimationNode._propertyIndexDic[AnimationClipParser01._strings[reader.getUint16()]]; if (propertyNameID !=null){ var isTransformProperty=propertyNameID < 4; var cacheProperty=!isTransformProperty || (isTransformProperty && path[0]===""); node._cacheProperty=cacheProperty; if (cacheProperty) cachePropertyToNodeIndex++; else unCachePropertyToNodeIndex++; node.propertyNameID=propertyNameID; }else { throw new Error("AnimationClipParser01:unknown property name."); }; var dataLength=lengthTypes[reader.getUint8()]; node.keyFrameWidth=dataLength / 4; var keyFrames=node.keyFrames=[]; var keyframeCount=keyFrames.length=reader.getUint16(); var lastKeyFrame=null; var startTime=NaN; for (j=0;j < keyframeCount;j++){ var keyFrame=keyFrames[j]=new Keyframe(); startTime=keyFrame.startTime=startTimeTypes[reader.getUint16()]; var offset=reader.pos; keyFrame.inTangent=new Float32Array(buffer.slice(offset,offset+dataLength)); reader.pos+=dataLength; offset=reader.pos; keyFrame.outTangent=new Float32Array(buffer.slice(offset,offset+dataLength)); reader.pos+=dataLength; offset=reader.pos; keyFrame.data=new Float32Array(buffer.slice(offset,offset+dataLength)); reader.pos+=dataLength; if (lastKeyFrame){ lastKeyFrame.next=keyFrame; lastKeyFrame.duration=startTime-lastKeyFrame.startTime; } lastKeyFrame=keyFrame; } keyFrame.next=null; keyFrame.duration=clipDur-startTime; }; var nodeToCachePropertyMap=clip._nodeToCachePropertyMap=new Int32Array(nodeCount); var cachePropertyToNodeMap=clip._cachePropertyMap=new Int32Array(cachePropertyToNodeIndex); var unCachePropertyToNodeMap=clip._unCachePropertyMap=new Int32Array(unCachePropertyToNodeIndex); cachePropertyToNodeIndex=unCachePropertyToNodeIndex=0; for (i=0;i < nodeCount;i++){ node=nodes[i]; if (node._cacheProperty){ nodeToCachePropertyMap[i]=cachePropertyToNodeIndex; cachePropertyToNodeMap[cachePropertyToNodeIndex++]=i; }else { unCachePropertyToNodeMap[unCachePropertyToNodeIndex++]=i; } } } AnimationClipParser01._animationClip=null; AnimationClipParser01._reader=null; AnimationClipParser01._strings=[]; __static(AnimationClipParser01, ['_BLOCK',function(){return this._BLOCK={count:0};},'_DATA',function(){return this._DATA={offset:0,size:0};} ]); return AnimationClipParser01; })() /** *@private */ //class laya.d3.animation.AnimationClipParser02 var AnimationClipParser02=(function(){ function AnimationClipParser02(){} __class(AnimationClipParser02,'laya.d3.animation.AnimationClipParser02'); AnimationClipParser02.READ_DATA=function(){ AnimationClipParser02._DATA.offset=AnimationClipParser02._reader.getUint32(); AnimationClipParser02._DATA.size=AnimationClipParser02._reader.getUint32(); } AnimationClipParser02.READ_BLOCK=function(){ var count=AnimationClipParser02._BLOCK.count=AnimationClipParser02._reader.getUint16(); var blockStarts=AnimationClipParser02._BLOCK.blockStarts=[]; var blockLengths=AnimationClipParser02._BLOCK.blockLengths=[]; for (var i=0;i < count;i++){ blockStarts.push(AnimationClipParser02._reader.getUint32()); blockLengths.push(AnimationClipParser02._reader.getUint32()); } } AnimationClipParser02.READ_STRINGS=function(){ var offset=AnimationClipParser02._reader.getUint32(); var count=AnimationClipParser02._reader.getUint16(); var prePos=AnimationClipParser02._reader.pos; AnimationClipParser02._reader.pos=offset+AnimationClipParser02._DATA.offset; for (var i=0;i < count;i++) AnimationClipParser02._strings[i]=AnimationClipParser02._reader.readUTFString(); AnimationClipParser02._reader.pos=prePos; } AnimationClipParser02.parse=function(clip,reader){ AnimationClipParser02._animationClip=clip; AnimationClipParser02._reader=reader; var arrayBuffer=reader.__getBuffer(); AnimationClipParser02.READ_DATA(); AnimationClipParser02.READ_BLOCK(); AnimationClipParser02.READ_STRINGS(); for (var i=0,n=AnimationClipParser02._BLOCK.count;i < n;i++){ var index=reader.getUint16(); var blockName=AnimationClipParser02._strings[index]; var fn=AnimationClipParser02["READ_"+blockName]; if (fn==null) throw new Error("model file err,no this function:"+index+" "+blockName); else fn.call(); } } AnimationClipParser02.READ_ANIMATIONS=function(){ var i=0,j=0; var node; var reader=AnimationClipParser02._reader; var buffer=reader.__getBuffer(); var lengthTypes=[]; var lenghthTypeCount=reader.getUint8(); lengthTypes.length=lenghthTypeCount; for (i=0;i < lenghthTypeCount;i++) lengthTypes[i]=reader.getUint16(); var startTimeTypes=[]; var startTimeTypeCount=reader.getUint16(); startTimeTypes.length=startTimeTypeCount; for (i=0;i < startTimeTypeCount;i++) startTimeTypes[i]=reader.getFloat32(); var clip=AnimationClipParser02._animationClip; clip.name=AnimationClipParser02._strings[reader.getUint16()]; var clipDur=clip._duration=reader.getFloat32(); clip.islooping=!!reader.getByte(); clip._frameRate=reader.getInt16(); var nodeCount=reader.getInt16(); var nodes=clip._nodes=new Array; nodes.length=nodeCount; var publicDatas=clip._publicClipDatas=[]; publicDatas.length=nodeCount; var nodesMap=clip._nodesMap={}; var cachePropertyToNodeIndex=0,unCachePropertyToNodeIndex=0; for (i=0;i < nodeCount;i++){ node=nodes[i]=new KeyframeNode(); var pathLength=reader.getUint16(); var path=node.path=[]; path.length=pathLength; for (j=0;j < pathLength;j++) path[j]=AnimationClipParser02._strings[reader.getUint16()]; var nodePath=path.join("/"); var mapArray=nodesMap[nodePath]; (mapArray)|| (nodesMap[nodePath]=mapArray=[]); mapArray.push(node); var componentTypeStrIndex=reader.getInt16(); (componentTypeStrIndex!==-1)&& (node.componentType=AnimationClipParser02._strings[componentTypeStrIndex]); var propertyNameID=AnimationNode._propertyIndexDic[AnimationClipParser02._strings[reader.getUint16()]]; if (propertyNameID !=null){ var isTransformProperty=propertyNameID < 4; var cacheProperty=!isTransformProperty || (isTransformProperty && path[0]===""); node._cacheProperty=cacheProperty; if (cacheProperty) cachePropertyToNodeIndex++; else unCachePropertyToNodeIndex++; node.propertyNameID=propertyNameID; }else { throw new Error("AnimationClipParser02:unknown property name."); }; var dataLength=lengthTypes[reader.getUint8()]; node.keyFrameWidth=dataLength / 4; var keyFrames=node.keyFrames=[]; var keyframeCount=keyFrames.length=reader.getUint16(); var lastKeyFrame=null; var startTime=NaN; for (j=0;j < keyframeCount;j++){ var keyFrame=keyFrames[j]=new Keyframe(); startTime=keyFrame.startTime=startTimeTypes[reader.getUint16()]; var offset=reader.pos; keyFrame.inTangent=new Float32Array(buffer.slice(offset,offset+dataLength)); reader.pos+=dataLength; offset=reader.pos; keyFrame.outTangent=new Float32Array(buffer.slice(offset,offset+dataLength)); reader.pos+=dataLength; offset=reader.pos; keyFrame.data=new Float32Array(buffer.slice(offset,offset+dataLength)); reader.pos+=dataLength; if (lastKeyFrame){ lastKeyFrame.next=keyFrame; lastKeyFrame.duration=startTime-lastKeyFrame.startTime; } lastKeyFrame=keyFrame; } keyFrame.next=null; keyFrame.duration=clipDur-startTime; }; var eventCount=reader.getUint16(); for (i=0;i < eventCount;i++){ var event=new AnimationEvent(); event.time=reader.getFloat32(); event.eventName=AnimationClipParser02._strings[reader.getUint16()]; var params; var paramCount=reader.getUint16(); (paramCount > 0)&& (event.params=params=[]); for (j=0;j < paramCount;j++){ var type=reader.getByte(); switch (type){ case 0: params.push(!!reader.getByte()); break ; case 1: params.push(reader.getInt32()); break ; case 2: params.push(reader.getFloat32()); break ; case 3: params.push(AnimationClipParser02._strings[reader.getUint16()]); break ; default : throw new Error("unknown type."); } } clip.addEvent(event); }; var nodeToCachePropertyMap=clip._nodeToCachePropertyMap=new Int32Array(nodeCount); var cachePropertyToNodeMap=clip._cachePropertyMap=new Int32Array(cachePropertyToNodeIndex); var unCachePropertyToNodeMap=clip._unCachePropertyMap=new Int32Array(unCachePropertyToNodeIndex); cachePropertyToNodeIndex=unCachePropertyToNodeIndex=0; for (i=0;i < nodeCount;i++){ node=nodes[i]; if (node._cacheProperty){ nodeToCachePropertyMap[i]=cachePropertyToNodeIndex; cachePropertyToNodeMap[cachePropertyToNodeIndex++]=i; }else { unCachePropertyToNodeMap[unCachePropertyToNodeIndex++]=i; } } } AnimationClipParser02._animationClip=null; AnimationClipParser02._reader=null; AnimationClipParser02._strings=[]; __static(AnimationClipParser02, ['_BLOCK',function(){return this._BLOCK={count:0};},'_DATA',function(){return this._DATA={offset:0,size:0};} ]); return AnimationClipParser02; })() /** *AnimationEvent 类用于实现动画事件。 */ //class laya.d3.animation.AnimationEvent var AnimationEvent=(function(){ function AnimationEvent(){ /**事件触发时间。*/ this.time=NaN; /**事件触发名称。*/ this.eventName=null; /**事件触发参数。*/ this.params=null; } __class(AnimationEvent,'laya.d3.animation.AnimationEvent'); return AnimationEvent; })() /** *BoneNode 类用于实现骨骼节点。 */ //class laya.d3.animation.AnimationNode var AnimationNode=(function(){ function AnimationNode(){ /**@private */ //this._childs=null; /**@private */ //this._parent=null; /**@private [只读]*/ //this.transform=null; /**节点名称。 */ //this.name=null; this._childs=[]; this.transform=new AnimationTransform3D(this); } __class(AnimationNode,'laya.d3.animation.AnimationNode'); var __proto=AnimationNode.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *添加子节点。 *@param child 子节点。 */ __proto.addChild=function(child){ child._parent=this; child.transform.setParent(this.transform); this._childs.push(child); } /** *移除子节点。 *@param child 子节点。 */ __proto.removeChild=function(child){ var index=this._childs.indexOf(child); (index!==-1)&& (this._childs.splice(index,1)); } /** *根据名字获取子节点。 *@param name 名字。 */ __proto.getChildByName=function(name){ for (var i=0,n=this._childs.length;i < n;i++){ var child=this._childs[i]; if (child.name===name) return child; } return null; } /** *根据索引获取子节点。 *@param index 索引。 */ __proto.getChildByIndex=function(index){ return this._childs[index]; } /** *获取子节点的个数。 */ __proto.getChildCount=function(){ return this._childs.length; } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destNode=destObject; destNode.name=this.name; for (var i=0,n=this._childs.length;i < n;i++){ var child=this._childs[i]; var destChild=child.clone(); destNode.addChild(destChild); var transform=child.transform; var destTransform=destChild.transform; destTransform.setLocalPosition(transform.getLocalPosition()); destTransform.setLocalRotation(transform.getLocalRotation()); destTransform.setLocalScale(transform.getLocalScale()); destTransform._localRotationEuler=transform._localRotationEuler; destTransform._setWorldMatrixIgnoreUpdate(transform.getWorldMatrix()); } } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var dest=/*__JS__ */new this.constructor(); this.cloneTo(dest); return dest; } AnimationNode.__init__=function(){ AnimationNode.registerAnimationNodeProperty("localPosition",AnimationNode._getLocalPosition,AnimationNode._setLocalPosition); AnimationNode.registerAnimationNodeProperty("localRotation",AnimationNode._getLocalRotation,AnimationNode._setLocalRotation); AnimationNode.registerAnimationNodeProperty("localScale",AnimationNode._getLocalScale,AnimationNode._setLocalScale); AnimationNode.registerAnimationNodeProperty("localRotationEuler",AnimationNode._getLocalRotationEuler,AnimationNode._setLocalRotationEuler); AnimationNode.registerAnimationNodeProperty("particleRender.sharedMaterial.tintColor",AnimationNode._getParticleRenderSharedMaterialTintColor,AnimationNode._setParticleRenderSharedMaterialTintColor); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.tilingOffset",AnimationNode._getMeshRenderSharedMaterialTilingOffset,AnimationNode._setMeshRenderSharedMaterialTilingOffset); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.albedoColor",AnimationNode._getMeshRenderSharedMaterialAlbedo,AnimationNode._setMeshRenderSharedMaterialAlbedo); AnimationNode.registerAnimationNodeProperty("skinnedMeshRender.sharedMaterial.tilingOffset",AnimationNode._getSkinnedMeshRenderSharedMaterialTilingOffset,AnimationNode._setSkinnedMeshRenderSharedMaterialTilingOffset); AnimationNode.registerAnimationNodeProperty("skinnedMeshRender.sharedMaterial.albedoColor",AnimationNode._getSkinnedMeshRenderSharedMaterialAlbedo,AnimationNode._setSkinnedMeshRenderSharedMaterialAlbedo); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.albedo",AnimationNode._getMeshRenderSharedMaterialAlbedo,AnimationNode._setMeshRenderSharedMaterialAlbedo); AnimationNode.registerAnimationNodeProperty("skinnedMeshRender.sharedMaterial.albedo",AnimationNode._getSkinnedMeshRenderSharedMaterialAlbedo,AnimationNode._setSkinnedMeshRenderSharedMaterialAlbedo); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.intensity",AnimationNode._getMeshRenderSharedMaterialIntensity,AnimationNode._setMeshRenderSharedMaterialIntensity); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.alpha",AnimationNode._getMeshRenderSharedMaterialAlpha,AnimationNode._setMeshRenderSharedMaterialAlpha); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.alphaColor",AnimationNode._getMeshRenderSharedMaterialAlphaColor,AnimationNode._setMeshRenderSharedMaterialAlphaColor); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.baseColor",AnimationNode._getMeshRenderSharedMaterialBaseColor,AnimationNode._setMeshRenderSharedMaterialBaseColor); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.dissolve",AnimationNode._getMeshRenderSharedMaterialDissolve,AnimationNode._setMeshRenderSharedMaterialDissolve); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.dissolveSpeed",AnimationNode._getMeshRenderSharedMaterialDissolveSpeed,AnimationNode._setMeshRenderSharedMaterialDissolveSpeed); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.mMultiplier",AnimationNode._getMeshRenderSharedMaterialMMultiplier,AnimationNode._setMeshRenderSharedMaterialMMultiplier); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.baseScrollSpeedX",AnimationNode._getMeshRenderSharedMaterialBaseScrollSpeedX,AnimationNode._setMeshRenderSharedMaterialBaseScrollSpeedX); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.baseScrollSpeedY",AnimationNode._getMeshRenderSharedMaterialBaseScrollSpeedY,AnimationNode._setMeshRenderSharedMaterialBaseScrollSpeedY); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.secondScrollSpeedX",AnimationNode._getMeshRenderSharedMaterialSecondScrollSpeedX,AnimationNode._setMeshRenderSharedMaterialSecondScrollSpeedX); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.secondScrollSpeedY",AnimationNode._getMeshRenderSharedMaterialSecondScrollSpeedY,AnimationNode._setMeshRenderSharedMaterialSecondScrollSpeedY); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.detailTilingOffset",AnimationNode._getMeshRenderSharedMaterialDetailTilingOffset,AnimationNode._setMeshRenderSharedMaterialDetailTilingOffset); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.dissolveTilingOffset",AnimationNode._getMeshRenderSharedMaterialDissolveTilingOffset,AnimationNode._setMeshRenderSharedMaterialDissolveTilingOffset); AnimationNode.registerAnimationNodeProperty("meshRender.sharedMaterial.maskTilingOffset",AnimationNode._getMeshRenderSharedMaterialMaskTilingOffset,AnimationNode._setMeshRenderSharedMaterialMaskTilingOffset); } AnimationNode.registerAnimationNodeProperty=function(propertyName,getFunc,setFunc){ if (AnimationNode._propertyIndexDic[propertyName]){ throw new Error("AnimationNode: this propertyName has registered."); }else { AnimationNode._propertyIndexDic[propertyName]=AnimationNode._propertyIDCounter; AnimationNode._propertyGetFuncs[AnimationNode._propertyIDCounter]=getFunc; AnimationNode._propertySetFuncs[AnimationNode._propertyIDCounter]=setFunc; AnimationNode._propertyIDCounter++; } } AnimationNode._getLocalPosition=function(animationNode,sprite3D){ if (animationNode) return animationNode.transform.getLocalPosition(); else return sprite3D._transform.localPosition.elements; } AnimationNode._setLocalPosition=function(animationNode,sprite3D,value){ if (animationNode){ animationNode.transform.setLocalPosition(value); }else { var spriteTransform=sprite3D._transform; var localPosition=spriteTransform.localPosition; localPosition.elements=value; spriteTransform.localPosition=localPosition; } } AnimationNode._getLocalRotation=function(animationNode,sprite3D){ if (animationNode) return animationNode.transform.getLocalRotation(); else return sprite3D._transform.localRotation.elements; } AnimationNode._setLocalRotation=function(animationNode,sprite3D,value){ if (animationNode){ animationNode.transform.setLocalRotation(value); }else { var spriteTransform=sprite3D._transform; var localRotation=spriteTransform.localRotation; localRotation.elements=value; spriteTransform.localRotation=localRotation; } } AnimationNode._getLocalScale=function(animationNode,sprite3D){ if (animationNode) return animationNode.transform.getLocalScale(); else return sprite3D._transform.localScale.elements; } AnimationNode._setLocalScale=function(animationNode,sprite3D,value){ if (animationNode){ animationNode.transform.setLocalScale(value); }else { var spriteTransform=sprite3D._transform; var localScale=spriteTransform.localScale; localScale.elements=value; spriteTransform.localScale=localScale; } } AnimationNode._getLocalRotationEuler=function(animationNode,sprite3D){ if (animationNode) return animationNode.transform.getLocalRotationEuler(); else return sprite3D._transform.localRotationEuler.elements; } AnimationNode._setLocalRotationEuler=function(animationNode,sprite3D,value){ if (animationNode){ animationNode.transform.setLocalRotationEuler(value); }else { var spriteTransform=sprite3D._transform; var localRotationEuler=spriteTransform.localRotationEuler; localRotationEuler.elements=value; spriteTransform.localRotationEuler=localRotationEuler; } } AnimationNode._getMeshRenderSharedMaterialTilingOffset=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.sharedMaterial; return material.tilingOffset.elements; }else return null; }else { material=(sprite3D).meshRender.sharedMaterial; return material.tilingOffset.elements; } } AnimationNode._setMeshRenderSharedMaterialTilingOffset=function(animationNode,sprite3D,value){ var material,tilingOffset; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.material; tilingOffset=material.tilingOffset; tilingOffset.elements=value; material.tilingOffset=tilingOffset; } }else { material=(sprite3D).meshRender.material; tilingOffset=material.tilingOffset; tilingOffset.elements=value; material.tilingOffset=tilingOffset; } } AnimationNode._getMeshRenderSharedMaterialAlbedo=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.sharedMaterial; return material.albedoColor.elements; }else return null; }else { material=(sprite3D).meshRender.sharedMaterial; return material.albedoColor.elements; } } AnimationNode._setMeshRenderSharedMaterialAlbedo=function(animationNode,sprite3D,value){ var material,albedo; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.material; albedo=material.albedoColor; albedo.elements=value; material.albedoColor=albedo; } }else { material=(sprite3D).meshRender.material; albedo=material.albedoColor; albedo.elements=value; material.albedoColor=albedo; } } AnimationNode._getSkinnedMeshRenderSharedMaterialTilingOffset=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).skinnedMeshRender.sharedMaterial; return material.tilingOffset.elements; }else return null; }else { material=(sprite3D).skinnedMeshRender.sharedMaterial; return material.tilingOffset.elements; } } AnimationNode._setSkinnedMeshRenderSharedMaterialTilingOffset=function(animationNode,sprite3D,value){ var material,tilingOffset; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).skinnedMeshRender.material; tilingOffset=material.tilingOffset; tilingOffset.elements=value; material.tilingOffset=tilingOffset; } }else { material=(sprite3D).skinnedMeshRender.material; tilingOffset=material.tilingOffset; tilingOffset.elements=value; material.tilingOffset=tilingOffset; } } AnimationNode._getSkinnedMeshRenderSharedMaterialAlbedo=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).skinnedMeshRender.sharedMaterial; return material.albedoColor.elements; }else { return null; } }else { material=(sprite3D).skinnedMeshRender.sharedMaterial; return material.albedoColor.elements; } } AnimationNode._setSkinnedMeshRenderSharedMaterialAlbedo=function(animationNode,sprite3D,value){ var material,albedo; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).skinnedMeshRender.material; albedo=material.albedoColor; albedo.elements=value; material.albedoColor=albedo; } }else { material=(sprite3D).skinnedMeshRender.material; albedo=material.albedoColor; albedo.elements=value; material.albedoColor=albedo; } } AnimationNode._getParticleRenderSharedMaterialTintColor=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).particleRender.sharedMaterial; return material.tintColor.elements; }else return null; }else { material=(sprite3D).particleRender.sharedMaterial; return material.tintColor.elements; } } AnimationNode._setParticleRenderSharedMaterialTintColor=function(animationNode,sprite3D,value){ var material,tintColor; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).particleRender.material; tintColor=material.tintColor; tintColor.elements=value; material.tintColor=tintColor; } }else { material=(sprite3D).particleRender.material; tintColor=material.tintColor; tintColor.elements=value; material.tintColor=tintColor; } } AnimationNode._getMeshRenderSharedMaterialAlphaColor=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.sharedMaterial; return material.alphaColor.elements; }else return null; }else { material=(sprite3D).meshRender.sharedMaterial; return material.alphaColor.elements; } } AnimationNode._setMeshRenderSharedMaterialAlphaColor=function(animationNode,sprite3D,value){ var material,alphaColor; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.material; alphaColor=material.alphaColor; alphaColor.elements=value; material.alphaColor=alphaColor; } }else { material=(sprite3D).meshRender.material; alphaColor=material.alphaColor; alphaColor.elements=value; material.alphaColor=alphaColor; } } AnimationNode._getMeshRenderSharedMaterialBaseColor=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.sharedMaterial; return material.baseColor.elements; }else return null; }else { material=(sprite3D).meshRender.sharedMaterial; return material.baseColor.elements; } } AnimationNode._setMeshRenderSharedMaterialBaseColor=function(animationNode,sprite3D,value){ var material,baseColor; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.material; baseColor=material.baseColor; baseColor.elements=value; material.baseColor=baseColor; } }else { material=(sprite3D).meshRender.material; baseColor=material.baseColor; baseColor.elements=value; material.baseColor=baseColor; } } AnimationNode._getMeshRenderSharedMaterialDissolve=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.sharedMaterial; return material.dissolve; }else return 0.0; }else { material=(sprite3D).meshRender.sharedMaterial; return material.dissolve; } } AnimationNode._setMeshRenderSharedMaterialDissolve=function(animationNode,sprite3D,value){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.material; material.dissolve=value[0]; } }else { material=(sprite3D).meshRender.material; material.dissolve=value[0]; } } AnimationNode._getMeshRenderSharedMaterialDissolveSpeed=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.sharedMaterial; return material.dissolveSpeed; }else return 0.0; }else { material=(sprite3D).meshRender.sharedMaterial; return material.dissolveSpeed; } } AnimationNode._setMeshRenderSharedMaterialDissolveSpeed=function(animationNode,sprite3D,value){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.material; material.dissolveSpeed=value[0]; } }else { material=(sprite3D).meshRender.material; material.dissolveSpeed=value[0]; } } AnimationNode._getMeshRenderSharedMaterialMMultiplier=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.sharedMaterial; return material.mMultiplier; }else return 0.0; }else { material=(sprite3D).meshRender.sharedMaterial; return material.mMultiplier; } } AnimationNode._setMeshRenderSharedMaterialMMultiplier=function(animationNode,sprite3D,value){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.material; material.mMultiplier=value[0]; } }else { material=(sprite3D).meshRender.material; material.mMultiplier=value[0]; } } AnimationNode._getMeshRenderSharedMaterialBaseScrollSpeedX=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.sharedMaterial; return material.baseScrollSpeedX; }else return 0.0; }else { material=(sprite3D).meshRender.sharedMaterial; return material.baseScrollSpeedX; } } AnimationNode._setMeshRenderSharedMaterialBaseScrollSpeedX=function(animationNode,sprite3D,value){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.material; material.baseScrollSpeedX=value[0]; } }else { material=(sprite3D).meshRender.material; material.baseScrollSpeedX=value[0]; } } AnimationNode._getMeshRenderSharedMaterialBaseScrollSpeedY=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.sharedMaterial; return material.baseScrollSpeedY; }else return 0.0; }else { material=(sprite3D).meshRender.sharedMaterial; return material.baseScrollSpeedY; } } AnimationNode._setMeshRenderSharedMaterialBaseScrollSpeedY=function(animationNode,sprite3D,value){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.material; material.baseScrollSpeedY=value[0]; } }else { material=(sprite3D).meshRender.material; material.baseScrollSpeedY=value[0]; } } AnimationNode._getMeshRenderSharedMaterialSecondScrollSpeedX=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.sharedMaterial; return material.secondScrollSpeedX; }else return 0.0; }else { material=(sprite3D).meshRender.sharedMaterial; return material.secondScrollSpeedX; } } AnimationNode._setMeshRenderSharedMaterialSecondScrollSpeedX=function(animationNode,sprite3D,value){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.material; material.secondScrollSpeedX=value[0]; } }else { material=(sprite3D).meshRender.material; material.secondScrollSpeedX=value[0]; } } AnimationNode._getMeshRenderSharedMaterialSecondScrollSpeedY=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.sharedMaterial; return material.secondScrollSpeedY; }else return 0.0; }else { material=(sprite3D).meshRender.sharedMaterial; return material.secondScrollSpeedY; } } AnimationNode._setMeshRenderSharedMaterialSecondScrollSpeedY=function(animationNode,sprite3D,value){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.material; material.secondScrollSpeedY=value[0]; } }else { material=(sprite3D).meshRender.material; material.secondScrollSpeedY=value[0]; } } AnimationNode._getMeshRenderSharedMaterialAlpha=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.sharedMaterial; return material.alpha; }else return 0.0; }else { material=(sprite3D).meshRender.sharedMaterial; return material.alpha; } } AnimationNode._setMeshRenderSharedMaterialAlpha=function(animationNode,sprite3D,value){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.material; material.alpha=value[0]; } }else { material=(sprite3D).meshRender.material; material.alpha=value[0]; } } AnimationNode._getMeshRenderSharedMaterialIntensity=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.sharedMaterial; return material.intensity; }else return 0.0; }else { material=(sprite3D).meshRender.sharedMaterial; return material.intensity; } } AnimationNode._setMeshRenderSharedMaterialIntensity=function(animationNode,sprite3D,value){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.material; material.intensity=value[0]; } }else { material=(sprite3D).meshRender.material; material.intensity=value[0]; } } AnimationNode._getMeshRenderSharedMaterialDetailTilingOffset=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.sharedMaterial; return material.detailTilingOffset.elements; }else return null; }else { material=(sprite3D).meshRender.sharedMaterial; return material.detailTilingOffset.elements; } } AnimationNode._setMeshRenderSharedMaterialDetailTilingOffset=function(animationNode,sprite3D,value){ var material,detailTilingOffset; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.material; detailTilingOffset=material.detailTilingOffset; detailTilingOffset.elements=value; material.detailTilingOffset=detailTilingOffset; } }else { material=(sprite3D).meshRender.material; detailTilingOffset=material.detailTilingOffset; detailTilingOffset.elements=value; material.detailTilingOffset=detailTilingOffset; } } AnimationNode._getMeshRenderSharedMaterialDissolveTilingOffset=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.sharedMaterial; return material.dissolveTilingOffset.elements; }else return null; }else { material=(sprite3D).meshRender.sharedMaterial; return material.dissolveTilingOffset.elements; } } AnimationNode._setMeshRenderSharedMaterialDissolveTilingOffset=function(animationNode,sprite3D,value){ var material,dissolveTilingOffset; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.material; dissolveTilingOffset=material.dissolveTilingOffset; dissolveTilingOffset.elements=value; material.dissolveTilingOffset=dissolveTilingOffset; } }else { material=(sprite3D).meshRender.material; dissolveTilingOffset=material.dissolveTilingOffset; dissolveTilingOffset.elements=value; material.dissolveTilingOffset=dissolveTilingOffset; } } AnimationNode._getMeshRenderSharedMaterialMaskTilingOffset=function(animationNode,sprite3D){ var material; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.sharedMaterial; return material.maskTilingOffset.elements; }else return null; }else { material=(sprite3D).meshRender.sharedMaterial; return material.maskTilingOffset.elements; } } AnimationNode._setMeshRenderSharedMaterialMaskTilingOffset=function(animationNode,sprite3D,value){ var material,maskTilingOffset; if (animationNode){ var entity=animationNode.transform._entity; if (entity){ material=(entity.owner).meshRender.material; maskTilingOffset=material.maskTilingOffset; maskTilingOffset.elements=value; material.maskTilingOffset=maskTilingOffset; } }else { material=(sprite3D).meshRender.material; maskTilingOffset=material.maskTilingOffset; maskTilingOffset.elements=value; material.maskTilingOffset=maskTilingOffset; } } AnimationNode._propertyIDCounter=0; AnimationNode._propertyIndexDic={}; AnimationNode._propertySetFuncs=[]; AnimationNode._propertyGetFuncs=[]; return AnimationNode; })() /** *@private */ //class laya.d3.animation.Keyframe var Keyframe=(function(){ function Keyframe(){ this.startTime=NaN; this.inTangent=null; this.outTangent=null; this.data=null; this.duration=NaN; this.next=null; } __class(Keyframe,'laya.d3.animation.Keyframe'); return Keyframe; })() /** *@private */ //class laya.d3.animation.KeyframeNode var KeyframeNode=(function(){ function KeyframeNode(){ this._cacheProperty=false; this.path=null; this.componentType=null; //TODO:是否去掉 this.propertyNameID=0; this.keyFrameWidth=0; this.defaultData=null; this.keyFrames=null; } __class(KeyframeNode,'laya.d3.animation.KeyframeNode'); return KeyframeNode; })() /** *SplineCurvePositionVelocity 类用于通过顶点和速度创建闪光插值。 */ //class laya.d3.core.glitter.SplineCurvePositionVelocity var SplineCurvePositionVelocity=(function(){ function SplineCurvePositionVelocity(){ this._tempVector30=new Vector3(); this._tempVector31=new Vector3(); this._tempVector32=new Vector3(); this._a=new Vector3(); this._b=new Vector3(); this._c=new Vector3(); this._d=new Vector3(); } __class(SplineCurvePositionVelocity,'laya.d3.core.glitter.SplineCurvePositionVelocity'); var __proto=SplineCurvePositionVelocity.prototype; /** *初始化插值所需信息。 *@param position0 顶点0的位置。 *@param velocity0 顶点0的速度。 *@param position1 顶点1的位置。 *@param velocity1 顶点1的速度。 */ __proto.Init=function(position0,velocity0,position1,velocity1){ position0.cloneTo(this._d); velocity0.cloneTo(this._c); Vector3.scale(position0,2.0,this._a); Vector3.scale(position1,2.0,this._tempVector30); Vector3.subtract(this._a,this._tempVector30,this._a); Vector3.add(this._a,velocity0,this._a); Vector3.add(this._a,velocity1,this._a); Vector3.scale(position1,3.0,this._b); Vector3.scale(position0,3.0,this._tempVector30); Vector3.subtract(this._b,this._tempVector30,this._b); Vector3.subtract(this._b,velocity1,this._b); Vector3.scale(velocity0,2.0,this._tempVector30); Vector3.subtract(this._b,this._tempVector30,this._b); } /** *初始化插值所需信息。 *@param t 插值比例 *@param out 输出结果 */ __proto.Slerp=function(t,out){ Vector3.scale(this._a,t *t *t,this._tempVector30); Vector3.scale(this._b,t *t,this._tempVector31); Vector3.scale(this._c,t,this._tempVector32); Vector3.add(this._tempVector30,this._tempVector31,out); Vector3.add(out,this._tempVector32,out); Vector3.add(out,this._d,out); } return SplineCurvePositionVelocity; })() /** *HeightMap 类用于实现高度图数据。 */ //class laya.d3.core.HeightMap var HeightMap=(function(){ function HeightMap(width,height,minHeight,maxHeight){ /**@private */ this._datas=null; /**@private */ this._w=0; /**@private */ this._h=0; /**@private */ this._minHeight=NaN; /**@private */ this._maxHeight=NaN; this._datas=[]; this._w=width; this._h=height; this._minHeight=minHeight; this._maxHeight=maxHeight; } __class(HeightMap,'laya.d3.core.HeightMap'); var __proto=HeightMap.prototype; /**@private */ __proto._inBounds=function(row,col){ return row >=0 && row < this._h && col >=0 && col < this._w; } /** *获取高度。 *@param row 列数。 *@param col 行数。 *@return 高度。 */ __proto.getHeight=function(row,col){ if (this._inBounds(row,col)) return this._datas[row][col]; else return NaN; } /** *获取宽度。 *@return value 宽度。 */ __getset(0,__proto,'width',function(){ return this._w; }); /** *获取高度。 *@return value 高度。 */ __getset(0,__proto,'height',function(){ return this._h; }); /** *最大高度。 *@return value 最大高度。 */ __getset(0,__proto,'maxHeight',function(){ return this._maxHeight; }); /** *最大高度。 *@return value 最大高度。 */ __getset(0,__proto,'minHeight',function(){ return this._minHeight; }); HeightMap.creatFromMesh=function(mesh,width,height,outCellSize){ var vertices=[]; var indexs=[]; var submesheCount=mesh.getSubMeshCount(); for (var i=0;i < submesheCount;i++){ var subMesh=mesh.getSubMesh(i); var vertexBuffer=subMesh._getVertexBuffer(); var verts=vertexBuffer.getData(); var subMeshVertices=[]; for (var j=0;j < verts.length;j+=vertexBuffer.vertexDeclaration.vertexStride / 4){ var position=new Vector3(verts[j+0],verts[j+1],verts[j+2]); subMeshVertices.push(position); } vertices.push(subMeshVertices); var ib=subMesh._getIndexBuffer(); indexs.push(ib.getData()); }; var boundingBox=mesh.boundingBox; var minX=boundingBox.min.x; var minZ=boundingBox.min.z; var maxX=boundingBox.max.x; var maxZ=boundingBox.max.z; var minY=boundingBox.min.y; var maxY=boundingBox.max.y; var widthSize=maxX-minX; var heightSize=maxZ-minZ; var cellWidth=outCellSize.elements[0]=widthSize / (width-1); var cellHeight=outCellSize.elements[1]=heightSize / (height-1); var heightMap=new HeightMap(width,height,minY,maxY); var ray=HeightMap._tempRay; var rayDirE=ray.direction.elements; rayDirE[0]=0; rayDirE[1]=-1; rayDirE[2]=0; var heightOffset=0.1; var rayY=maxY+heightOffset; ray.origin.elements[1]=rayY; for (var h=0;h < height;h++){ var posZ=minZ+h *cellHeight; heightMap._datas[h]=[]; for (var w=0;w < width;w++){ var posX=minX+w *cellWidth; var rayOriE=ray.origin.elements; rayOriE[0]=posX; rayOriE[2]=posZ; var closestIntersection=HeightMap._getPosition(ray,vertices,indexs); heightMap._datas[h][w]=(closestIntersection===Number.MAX_VALUE)? NaN :rayY-closestIntersection; } } return heightMap; } HeightMap.createFromImage=function(texture,minHeight,maxHeight){ var textureWidth=texture.width; var textureHeight=texture.height; var heightMap=new HeightMap(textureWidth,textureHeight,minHeight,maxHeight); var compressionRatio=(maxHeight-minHeight)/ 254; var pixelsInfo=texture.getPixels(); var index=0; for (var h=0;h Layer 类用于实现层。 */ //class laya.d3.core.Layer var Layer=(function(){ function Layer(){ /**@private 编号。*/ //this._number=0; /**@private 蒙版值。*/ //this._mask=0; /**@private 是否显示。*/ //this._visible=false; /**@private 只读,不允许修改。*/ //this._nonRigidbodyOffset=0; /**@private 只读,不允许修改。*/ //this._colliders=null; /**名字。*/ //this.name=null; this._visible=true; this._nonRigidbodyOffset=0; this._colliders=[]; } __class(Layer,'laya.d3.core.Layer'); var __proto=Layer.prototype; /** *@private */ __proto._binarySearchIndex=function(){ var start=0; var end=Layer._collsionTestList.length-1; var mid=0; while (start <=end){ mid=Math.floor((start+end)/ 2); var midValue=Layer._collsionTestList[mid]; if (midValue==this._number) return mid; else if (midValue > this._number) end=mid-1; else start=mid+1; } return start; } /** *@private */ __proto._addCollider=function(collider){ (this._colliders.length===0)&& (Layer._collsionTestList.splice(this._binarySearchIndex(),0,this._number)); if (collider._isRigidbody){ this._colliders.unshift(collider); this._nonRigidbodyOffset++; }else { this._colliders.push(collider); } } /** *@private */ __proto._removeCollider=function(collider){ var index=this._colliders.indexOf(collider); if (index < this._nonRigidbodyOffset) this._nonRigidbodyOffset--; this._colliders.splice(index,1); (this._colliders.length===0)&& (Layer._collsionTestList.splice(Layer._collsionTestList.indexOf(this._number),1)); } /** *获取编号。 *@return 编号。 */ __getset(0,__proto,'number',function(){ return this._number; }); /** *设置是否显示。 *@param value 是否显示。 */ /** *获取是否显示。 *@return 是否显示。 */ __getset(0,__proto,'visible',function(){ return this._visible; },function(value){ this._visible=value; if (value) Layer._visibleLayers=Layer._visibleLayers | this.mask; else Layer._visibleLayers=Layer._visibleLayers & ~this.mask; }); /** *获取蒙版值。 *@return 蒙版值。 */ __getset(0,__proto,'mask',function(){ return this._mask; }); /** *设置Layer显示层。 *@param value 显示层。 */ /** *获取Layer显示层。 *@return 显示层。 */ __getset(1,Layer,'visibleLayers',function(){ return Layer._visibleLayers; },function(value){ Layer._visibleLayers=value; for (var i=0,n=Layer._layerList.length;i < n;i++){ var layer=Layer._layerList[i]; layer._visible=(layer._mask & Layer._visibleLayers)!==0; } }); Layer.__init__=function(){ Layer._layerList.length=31; for (var i=0;i < 31;i++){ var layer=new Layer(); Layer._layerList[i]=layer; if (i===0){ layer.name="Default Layer"; layer.visible=true; }else { layer.name="Layer-"+i; layer.visible=false; } layer._number=i; layer._mask=Math.pow(2,i); } Layer.currentCreationLayer=Layer._layerList[0]; } Layer.getLayerByNumber=function(number){ if (number < 0 || number > 30) throw new Error("无法返回指定Layer,该number超出范围!"); return Layer._layerList[number]; } Layer.getLayerByName=function(name){ for (var i=0;i < 31;i++){ if (Layer._layerList[i].name===name) return Layer._layerList[i]; } throw new Error("无法返回指定Layer,该name不存在"); } Layer.isVisible=function(mask){ return (mask & Layer._currentCameraCullingMask & Layer._visibleLayers)!=0; } Layer._layerList=[]; Layer._visibleLayers=2147483647; Layer._collsionTestList=[]; Layer._currentCameraCullingMask=2147483647; Layer.maxCount=31; Layer.currentCreationLayer=null; return Layer; })() /** *Burst 类用于粒子的爆裂描述。 */ //class laya.d3.core.particleShuriKen.module.Burst var Burst=(function(){ function Burst(time,minCount,maxCount){ /**@private 爆裂时间,单位为秒。*/ this._time=NaN; /**@private 爆裂的最小数量。*/ this._minCount=0; /**@private 爆裂的最大数量。*/ this._maxCount=0; this._time=time; this._minCount=minCount; this._maxCount=maxCount; } __class(Burst,'laya.d3.core.particleShuriKen.module.Burst'); var __proto=Burst.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destBurst=destObject; destBurst._time=this._time destBurst._minCount=this._minCount; destBurst._maxCount=this._maxCount; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destBurst=/*__JS__ */new this.constructor(); this.cloneTo(destBurst); return destBurst; } /** *获取爆裂时间,单位为秒。 *@return 爆裂时间,单位为秒。 */ __getset(0,__proto,'time',function(){ return this._time; }); /** *获取爆裂的最小数量。 *@return 爆裂的最小数量。 */ __getset(0,__proto,'minCount',function(){ return this._minCount; }); /** *获取爆裂的最大数量。 *@return 爆裂的最大数量。 */ __getset(0,__proto,'maxCount',function(){ return this._maxCount; }); return Burst; })() /** *ColorOverLifetime 类用于粒子的生命周期颜色。 */ //class laya.d3.core.particleShuriKen.module.ColorOverLifetime var ColorOverLifetime=(function(){ function ColorOverLifetime(color){ /**@private */ this._color=null; /**是否启用。*/ this.enbale=false; this._color=color; } __class(ColorOverLifetime,'laya.d3.core.particleShuriKen.module.ColorOverLifetime'); var __proto=ColorOverLifetime.prototype; /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destColorOverLifetime=destObject; this._color.cloneTo(destColorOverLifetime._color); destColorOverLifetime.enbale=this.enbale; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destColor; switch (this._color.type){ case 0: destColor=GradientColor.createByConstant(this._color.constant.clone()); break ; case 1: destColor=GradientColor.createByGradient(this._color.gradient.clone()); break ; case 2: destColor=GradientColor.createByRandomTwoConstant(this._color.constantMin.clone(),this._color.constantMax.clone()); break ; case 3: destColor=GradientColor.createByRandomTwoGradient(this._color.gradientMin.clone(),this._color.gradientMax.clone()); break ; }; var destColorOverLifetime=/*__JS__ */new this.constructor(destColor); destColorOverLifetime.enbale=this.enbale; return destColorOverLifetime; } /** *获取颜色。 */ __getset(0,__proto,'color',function(){ return this._color; }); return ColorOverLifetime; })() /** *Emission 类用于粒子发射器。 */ //class laya.d3.core.particleShuriKen.module.Emission var Emission=(function(){ function Emission(){ /**@private */ this._destroyed=false; /**@private 粒子发射速率,每秒发射的个数。*/ this._emissionRate=0; /**@private 粒子的爆裂,不允许修改。*/ this._bursts=null; /**是否启用。*/ this.enbale=false; this._destroyed=false; this.emissionRate=10; this._bursts=[]; } __class(Emission,'laya.d3.core.particleShuriKen.module.Emission'); var __proto=Emission.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true,"laya.resource.IDestroy":true}) /** *@private */ __proto._destroy=function(){ this._bursts=null; this._destroyed=true; } /** *获取粒子爆裂个数。 *@return 粒子爆裂个数。 */ __proto.getBurstsCount=function(){ return this._bursts.length; } /** *通过索引获取粒子爆裂。 *@param index 爆裂索引。 *@return 粒子爆裂。 */ __proto.getBurstByIndex=function(index){ return this._bursts[index]; } /** *增加粒子爆裂。 *@param burst 爆裂。 */ __proto.addBurst=function(burst){ var burstsCount=this._bursts.length; if (burstsCount > 0) for (var i=0;i < burstsCount;i++){ if (this._bursts[i].time > burst.time) this._bursts.splice(i,0,burst); } this._bursts.push(burst); } /** *移除粒子爆裂。 *@param burst 爆裂。 */ __proto.removeBurst=function(burst){ var index=this._bursts.indexOf(burst); if (index!==-1){ this._bursts.splice(index,1); } } /** *通过索引移除粒子爆裂。 *@param index 爆裂索引。 */ __proto.removeBurstByIndex=function(index){ this._bursts.splice(index,1); } /** *清空粒子爆裂。 */ __proto.clearBurst=function(){ this._bursts.length=0; } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destEmission=destObject; var destBursts=destEmission._bursts; destBursts.length=this._bursts.length; for (var i=0,n=this._bursts.length;i < n;i++){ var destBurst=destBursts[i]; if (destBurst) this._bursts[i].cloneTo(destBurst); else destBursts[i]=this._bursts[i].clone(); } destEmission._emissionRate=this._emissionRate; destEmission.enbale=this.enbale; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destEmission=/*__JS__ */new this.constructor(); this.cloneTo(destEmission); return destEmission; } /** *获取是否已销毁。 *@return 是否已销毁。 */ __getset(0,__proto,'destroyed',function(){ return this._destroyed; }); /** *设置粒子发射速率。 *@param emissionRate 粒子发射速率 (个/秒)。 */ /** *获取粒子发射速率。 *@return 粒子发射速率 (个/秒)。 */ __getset(0,__proto,'emissionRate',function(){ return this._emissionRate; },function(value){ if (value < 0) throw new Error("ParticleBaseShape:emissionRate value must large or equal than 0."); this._emissionRate=value; }); return Emission; })() /** *FrameOverTime 类用于创建时间帧。 */ //class laya.d3.core.particleShuriKen.module.FrameOverTime var FrameOverTime=(function(){ function FrameOverTime(){ /**@private */ this._type=0; /**@private */ this._constant=0; /**@private */ this._overTime=null; /**@private */ this._constantMin=0; /**@private */ this._constantMax=0; /**@private */ this._overTimeMin=null; /**@private */ this._overTimeMax=null; } __class(FrameOverTime,'laya.d3.core.particleShuriKen.module.FrameOverTime'); var __proto=FrameOverTime.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destFrameOverTime=destObject; destFrameOverTime._type=this._type; destFrameOverTime._constant=this._constant; this._overTime.cloneTo(destFrameOverTime._overTime); destFrameOverTime._constantMin=this._constantMin; destFrameOverTime._constantMax=this._constantMax; this._overTimeMin.cloneTo(destFrameOverTime._overTimeMin); this._overTimeMax.cloneTo(destFrameOverTime._overTimeMax); } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destFrameOverTime=/*__JS__ */new this.constructor(); this.cloneTo(destFrameOverTime); return destFrameOverTime; } /** *时间帧。 */ __getset(0,__proto,'frameOverTimeData',function(){ return this._overTime; }); /** *固定帧。 */ __getset(0,__proto,'constant',function(){ return this._constant; }); /** *生命周期旋转类型,0常量模式,1曲线模式,2随机双常量模式,3随机双曲线模式。 */ __getset(0,__proto,'type',function(){ return this._type; }); /** *最小时间帧。 */ __getset(0,__proto,'frameOverTimeDataMin',function(){ return this._overTimeMin; }); /** *最小固定帧。 */ __getset(0,__proto,'constantMin',function(){ return this._constantMin; }); /** *最大时间帧。 */ __getset(0,__proto,'frameOverTimeDataMax',function(){ return this._overTimeMax; }); /** *最大固定帧。 */ __getset(0,__proto,'constantMax',function(){ return this._constantMax; }); FrameOverTime.createByConstant=function(constant){ var rotationOverLifetime=new FrameOverTime(); rotationOverLifetime._type=0; rotationOverLifetime._constant=constant; return rotationOverLifetime; } FrameOverTime.createByOverTime=function(overTime){ var rotationOverLifetime=new FrameOverTime(); rotationOverLifetime._type=1; rotationOverLifetime._overTime=overTime; return rotationOverLifetime; } FrameOverTime.createByRandomTwoConstant=function(constantMin,constantMax){ var rotationOverLifetime=new FrameOverTime(); rotationOverLifetime._type=2; rotationOverLifetime._constantMin=constantMin; rotationOverLifetime._constantMax=constantMax; return rotationOverLifetime; } FrameOverTime.createByRandomTwoOverTime=function(gradientFrameMin,gradientFrameMax){ var rotationOverLifetime=new FrameOverTime(); rotationOverLifetime._type=3; rotationOverLifetime._overTimeMin=gradientFrameMin; rotationOverLifetime._overTimeMax=gradientFrameMax; return rotationOverLifetime; } return FrameOverTime; })() /** *GradientRotation 类用于创建渐变角速度。 */ //class laya.d3.core.particleShuriKen.module.GradientAngularVelocity var GradientAngularVelocity=(function(){ function GradientAngularVelocity(){ /**@private */ this._type=0; /**@private */ this._separateAxes=false; /**@private */ this._constant=NaN; /**@private */ this._constantSeparate=null; /**@private */ this._gradient=null; /**@private */ this._gradientX=null; /**@private */ this._gradientY=null; /**@private */ this._gradientZ=null; /**@private */ this._gradientW=null; /**@private */ this._constantMin=NaN; /**@private */ this._constantMax=NaN; /**@private */ this._constantMinSeparate=null; /**@private */ this._constantMaxSeparate=null; /**@private */ this._gradientMin=null; /**@private */ this._gradientMax=null; /**@private */ this._gradientXMin=null; /**@private */ this._gradientXMax=null; /**@private */ this._gradientYMin=null; /**@private */ this._gradientYMax=null; /**@private */ this._gradientZMin=null; /**@private */ this._gradientZMax=null; /**@private */ this._gradientWMin=null; /**@private */ this._gradientWMax=null; } __class(GradientAngularVelocity,'laya.d3.core.particleShuriKen.module.GradientAngularVelocity'); var __proto=GradientAngularVelocity.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destGradientAngularVelocity=destObject; destGradientAngularVelocity._type=this._type; destGradientAngularVelocity._separateAxes=this._separateAxes; destGradientAngularVelocity._constant=this._constant; this._constantSeparate.cloneTo(destGradientAngularVelocity._constantSeparate); this._gradient.cloneTo(destGradientAngularVelocity._gradient); this._gradientX.cloneTo(destGradientAngularVelocity._gradientX); this._gradientY.cloneTo(destGradientAngularVelocity._gradientY); this._gradientZ.cloneTo(destGradientAngularVelocity._gradientZ); destGradientAngularVelocity._constantMin=this._constantMin; destGradientAngularVelocity._constantMax=this._constantMax; this._constantMinSeparate.cloneTo(destGradientAngularVelocity._constantMinSeparate); this._constantMaxSeparate.cloneTo(destGradientAngularVelocity._constantMaxSeparate); this._gradientMin.cloneTo(destGradientAngularVelocity._gradientMin); this._gradientMax.cloneTo(destGradientAngularVelocity._gradientMax); this._gradientXMin.cloneTo(destGradientAngularVelocity._gradientXMin); this._gradientXMax.cloneTo(destGradientAngularVelocity._gradientXMax); this._gradientYMin.cloneTo(destGradientAngularVelocity._gradientYMin); this._gradientYMax.cloneTo(destGradientAngularVelocity._gradientYMax); this._gradientZMin.cloneTo(destGradientAngularVelocity._gradientZMin); this._gradientZMax.cloneTo(destGradientAngularVelocity._gradientZMax); } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destGradientAngularVelocity=/*__JS__ */new this.constructor(); this.cloneTo(destGradientAngularVelocity); return destGradientAngularVelocity; } /** *渐变角速度Z。 */ __getset(0,__proto,'gradientZ',function(){ return this._gradientZ; }); /** *固定角速度。 */ __getset(0,__proto,'constant',function(){ return this._constant; }); /** *渐变角速度。 */ __getset(0,__proto,'gradient',function(){ return this._gradient; }); /** *是否分轴。 */ __getset(0,__proto,'separateAxes',function(){ return this._separateAxes; }); /** *生命周期角速度类型,0常量模式,1曲线模式,2随机双常量模式,3随机双曲线模式。 */ __getset(0,__proto,'type',function(){ return this._type; }); /** *分轴固定角速度。 */ __getset(0,__proto,'constantSeparate',function(){ return this._constantSeparate; }); /** *渐变角角速度X。 */ __getset(0,__proto,'gradientX',function(){ return this._gradientX; }); /** *渐变角速度Y。 */ __getset(0,__proto,'gradientY',function(){ return this._gradientY; }); /** *渐变角速度Z。 */ __getset(0,__proto,'gradientW',function(){ return this._gradientW; }); /** *最小渐变角速度。 */ __getset(0,__proto,'gradientMin',function(){ return this._gradientMin; }); /** *最小随机双固定角速度。 */ __getset(0,__proto,'constantMin',function(){ return this._constantMin; }); /** *最大渐变角速度。 */ __getset(0,__proto,'gradientMax',function(){ return this._gradientMax; }); /** *最大随机双固定角速度。 */ __getset(0,__proto,'constantMax',function(){ return this._constantMax; }); /** *最小渐变角速度Z。 */ __getset(0,__proto,'gradientWMin',function(){ return this._gradientWMin; }); /** *最小分轴随机双固定角速度。 */ __getset(0,__proto,'constantMinSeparate',function(){ return this._constantMinSeparate; }); /** *最大分轴随机双固定角速度。 */ __getset(0,__proto,'constantMaxSeparate',function(){ return this._constantMaxSeparate; }); /** *最小渐变角速度X。 */ __getset(0,__proto,'gradientXMin',function(){ return this._gradientXMin; }); /** *最大渐变角速度X。 */ __getset(0,__proto,'gradientXMax',function(){ return this._gradientXMax; }); /** *最大渐变角速度Z。 */ __getset(0,__proto,'gradientWMax',function(){ return this._gradientWMax; }); /** *最小渐变角速度Y。 */ __getset(0,__proto,'gradientYMin',function(){ return this._gradientYMin; }); /** *最大渐变角速度Y。 */ __getset(0,__proto,'gradientYMax',function(){ return this._gradientYMax; }); /** *最小渐变角速度Z。 */ __getset(0,__proto,'gradientZMin',function(){ return this._gradientZMin; }); /** *最大渐变角速度Z。 */ __getset(0,__proto,'gradientZMax',function(){ return this._gradientZMax; }); GradientAngularVelocity.createByConstant=function(constant){ var gradientAngularVelocity=new GradientAngularVelocity(); gradientAngularVelocity._type=0; gradientAngularVelocity._separateAxes=false; gradientAngularVelocity._constant=constant; return gradientAngularVelocity; } GradientAngularVelocity.createByConstantSeparate=function(separateConstant){ var gradientAngularVelocity=new GradientAngularVelocity(); gradientAngularVelocity._type=0; gradientAngularVelocity._separateAxes=true; gradientAngularVelocity._constantSeparate=separateConstant; return gradientAngularVelocity; } GradientAngularVelocity.createByGradient=function(gradient){ var gradientAngularVelocity=new GradientAngularVelocity(); gradientAngularVelocity._type=1; gradientAngularVelocity._separateAxes=false; gradientAngularVelocity._gradient=gradient; return gradientAngularVelocity; } GradientAngularVelocity.createByGradientSeparate=function(gradientX,gradientY,gradientZ,gradientW){ var gradientAngularVelocity=new GradientAngularVelocity(); gradientAngularVelocity._type=1; gradientAngularVelocity._separateAxes=true; gradientAngularVelocity._gradientX=gradientX; gradientAngularVelocity._gradientY=gradientY; gradientAngularVelocity._gradientZ=gradientZ; gradientAngularVelocity._gradientW=gradientW; return gradientAngularVelocity; } GradientAngularVelocity.createByRandomTwoConstant=function(constantMin,constantMax){ var gradientAngularVelocity=new GradientAngularVelocity(); gradientAngularVelocity._type=2; gradientAngularVelocity._separateAxes=false; gradientAngularVelocity._constantMin=constantMin; gradientAngularVelocity._constantMax=constantMax; return gradientAngularVelocity; } GradientAngularVelocity.createByRandomTwoConstantSeparate=function(separateConstantMin,separateConstantMax){ var gradientAngularVelocity=new GradientAngularVelocity(); gradientAngularVelocity._type=2; gradientAngularVelocity._separateAxes=true; gradientAngularVelocity._constantMinSeparate=separateConstantMin; gradientAngularVelocity._constantMaxSeparate=separateConstantMax; return gradientAngularVelocity; } GradientAngularVelocity.createByRandomTwoGradient=function(gradientMin,gradientMax){ var gradientAngularVelocity=new GradientAngularVelocity(); gradientAngularVelocity._type=3; gradientAngularVelocity._separateAxes=false; gradientAngularVelocity._gradientMin=gradientMin; gradientAngularVelocity._gradientMax=gradientMax; return gradientAngularVelocity; } GradientAngularVelocity.createByRandomTwoGradientSeparate=function(gradientXMin,gradientXMax,gradientYMin,gradientYMax,gradientZMin,gradientZMax,gradientWMin,gradientWMax){ var gradientAngularVelocity=new GradientAngularVelocity(); gradientAngularVelocity._type=3; gradientAngularVelocity._separateAxes=true; gradientAngularVelocity._gradientXMin=gradientXMin; gradientAngularVelocity._gradientXMax=gradientXMax; gradientAngularVelocity._gradientYMin=gradientYMin; gradientAngularVelocity._gradientYMax=gradientYMax; gradientAngularVelocity._gradientZMin=gradientZMin; gradientAngularVelocity._gradientZMax=gradientZMax; gradientAngularVelocity._gradientWMin=gradientWMin; gradientAngularVelocity._gradientWMax=gradientWMax; return gradientAngularVelocity; } return GradientAngularVelocity; })() /** *GradientColor 类用于创建渐变颜色。 */ //class laya.d3.core.particleShuriKen.module.GradientColor var GradientColor=(function(){ function GradientColor(){ /**@private */ this._type=0; /**@private */ this._constant=null; /**@private */ this._constantMin=null; /**@private */ this._constantMax=null; /**@private */ this._gradient=null; /**@private */ this._gradientMin=null; /**@private */ this._gradientMax=null; } __class(GradientColor,'laya.d3.core.particleShuriKen.module.GradientColor'); var __proto=GradientColor.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destGradientColor=destObject; destGradientColor._type=this._type; this._constant.cloneTo(destGradientColor._constant); this._constantMin.cloneTo(destGradientColor._constantMin); this._constantMax.cloneTo(destGradientColor._constantMax); this._gradient.cloneTo(destGradientColor._gradient); this._gradientMin.cloneTo(destGradientColor._gradientMin); this._gradientMax.cloneTo(destGradientColor._gradientMax); } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destGradientColor=/*__JS__ */new this.constructor(); this.cloneTo(destGradientColor); return destGradientColor; } /** *渐变颜色。 */ __getset(0,__proto,'gradient',function(){ return this._gradient; }); /** *固定颜色。 */ __getset(0,__proto,'constant',function(){ return this._constant; }); /** *生命周期颜色类型,0为固定颜色模式,1渐变模式,2为随机双固定颜色模式,3随机双渐变模式。 */ __getset(0,__proto,'type',function(){ return this._type; }); /** *最小渐变颜色。 */ __getset(0,__proto,'gradientMin',function(){ return this._gradientMin; }); /** *最小固定颜色。 */ __getset(0,__proto,'constantMin',function(){ return this._constantMin; }); /** *最大渐变颜色。 */ __getset(0,__proto,'gradientMax',function(){ return this._gradientMax; }); /** *最大固定颜色。 */ __getset(0,__proto,'constantMax',function(){ return this._constantMax; }); GradientColor.createByConstant=function(constant){ var gradientColor=new GradientColor(); gradientColor._type=0; gradientColor._constant=constant; return gradientColor; } GradientColor.createByGradient=function(gradient){ var gradientColor=new GradientColor(); gradientColor._type=1; gradientColor._gradient=gradient; return gradientColor; } GradientColor.createByRandomTwoConstant=function(minConstant,maxConstant){ var gradientColor=new GradientColor(); gradientColor._type=2; gradientColor._constantMin=minConstant; gradientColor._constantMax=maxConstant; return gradientColor; } GradientColor.createByRandomTwoGradient=function(minGradient,maxGradient){ var gradientColor=new GradientColor(); gradientColor._type=3; gradientColor._gradientMin=minGradient; gradientColor._gradientMax=maxGradient; return gradientColor; } return GradientColor; })() /** *GradientDataColor 类用于创建颜色渐变。 */ //class laya.d3.core.particleShuriKen.module.GradientDataColor var GradientDataColor=(function(){ function GradientDataColor(){ /**@private */ this._alphaCurrentLength=0; /**@private */ this._rgbCurrentLength=0; /**@private 开发者禁止修改。*/ this._alphaElements=null; /**@private 开发者禁止修改。*/ this._rgbElements=null; this._alphaElements=new Float32Array(8); this._rgbElements=new Float32Array(16); } __class(GradientDataColor,'laya.d3.core.particleShuriKen.module.GradientDataColor'); var __proto=GradientDataColor.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *增加Alpha渐变。 *@param key 生命周期,范围为0到1。 *@param value rgb值。 */ __proto.addAlpha=function(key,value){ if (this._alphaCurrentLength < 8){ if ((this._alphaCurrentLength===6)&& ((key!==1))){ key=1; console.log("GradientDataColor warning:the forth key is be force set to 1."); } this._alphaElements[this._alphaCurrentLength++]=key; this._alphaElements[this._alphaCurrentLength++]=value; }else { console.log("GradientDataColor warning:data count must lessEqual than 4"); } } /** *增加RGB渐变。 *@param key 生命周期,范围为0到1。 *@param value RGB值。 */ __proto.addRGB=function(key,value){ if (this._rgbCurrentLength < 16){ if ((this._rgbCurrentLength===12)&& ((key!==1))){ key=1; console.log("GradientDataColor warning:the forth key is be force set to 1."); } this._rgbElements[this._rgbCurrentLength++]=key; this._rgbElements[this._rgbCurrentLength++]=value.x; this._rgbElements[this._rgbCurrentLength++]=value.y; this._rgbElements[this._rgbCurrentLength++]=value.z; }else { console.log("GradientDataColor warning:data count must lessEqual than 4"); } } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destGradientDataColor=destObject; var i=0,n=0; destGradientDataColor._alphaCurrentLength=this._alphaCurrentLength; var destAlphaElements=destGradientDataColor._alphaElements; destAlphaElements.length=this._alphaElements.length; for (i=0,n=this._alphaElements.length;i < n;i++) destAlphaElements[i]=this._alphaElements[i]; destGradientDataColor._rgbCurrentLength=this._rgbCurrentLength; var destRGBElements=destGradientDataColor._rgbElements; destRGBElements.length=this._rgbElements.length; for (i=0,n=this._rgbElements.length;i < n;i++) destRGBElements[i]=this._rgbElements[i]; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destGradientDataColor=/*__JS__ */new this.constructor(); this.cloneTo(destGradientDataColor); return destGradientDataColor; } /**渐变Alpha数量。*/ __getset(0,__proto,'alphaGradientCount',function(){ return this._alphaCurrentLength / 2; }); /**渐变RGB数量。*/ __getset(0,__proto,'rgbGradientCount',function(){ return this._rgbCurrentLength / 4; }); return GradientDataColor; })() /** *GradientDataInt 类用于创建整形渐变。 */ //class laya.d3.core.particleShuriKen.module.GradientDataInt var GradientDataInt=(function(){ function GradientDataInt(){ /**@private */ this._currentLength=0; /**@private 开发者禁止修改。*/ this._elements=null; this._elements=new Float32Array(8); } __class(GradientDataInt,'laya.d3.core.particleShuriKen.module.GradientDataInt'); var __proto=GradientDataInt.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *增加整形渐变。 *@param key 生命周期,范围为0到1。 *@param value 整形值。 */ __proto.add=function(key,value){ if (this._currentLength < 8){ if ((this._currentLength===6)&& ((key!==1))){ key=1; console.log("Warning:the forth key is be force set to 1."); } this._elements[this._currentLength++]=key; this._elements[this._currentLength++]=value; }else { console.log("Warning:data count must lessEqual than 4"); } } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destGradientDataInt=destObject; destGradientDataInt._currentLength=this._currentLength; var destElements=destGradientDataInt._elements; destElements.length=this._elements.length; for (var i=0,n=this._elements.length;i < n;i++){ destElements[i]=this._elements[i]; } } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destGradientDataInt=/*__JS__ */new this.constructor(); this.cloneTo(destGradientDataInt); return destGradientDataInt; } /**整形渐变数量。*/ __getset(0,__proto,'gradientCount',function(){ return this._currentLength / 2; }); return GradientDataInt; })() /** *GradientDataNumber 类用于创建浮点渐变。 */ //class laya.d3.core.particleShuriKen.module.GradientDataNumber var GradientDataNumber=(function(){ function GradientDataNumber(){ /**@private */ this._currentLength=0; /**@private 开发者禁止修改。*/ this._elements=null; this._elements=new Float32Array(8); } __class(GradientDataNumber,'laya.d3.core.particleShuriKen.module.GradientDataNumber'); var __proto=GradientDataNumber.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *增加浮点渐变。 *@param key 生命周期,范围为0到1。 *@param value 浮点值。 */ __proto.add=function(key,value){ if (this._currentLength < 8){ if ((this._currentLength===6)&& ((key!==1))){ key=1; console.log("GradientDataNumber warning:the forth key is be force set to 1."); } this._elements[this._currentLength++]=key; this._elements[this._currentLength++]=value; }else { console.log("GradientDataNumber warning:data count must lessEqual than 4"); } } /** *通过索引获取键。 *@param index 索引。 *@return value 键。 */ __proto.getKeyByIndex=function(index){ return this._elements[index *2]; } /** *通过索引获取值。 *@param index 索引。 *@return value 值。 */ __proto.getValueByIndex=function(index){ return this._elements[index *2+1]; } /** *获取平均值。 */ __proto.getAverageValue=function(){ var total=0; for (var i=0,n=this._currentLength-2;i < n;i+=2){ var subValue=this._elements[i+1]; subValue+=this._elements[i+3]; subValue=subValue *(this._elements[i+2]-this._elements[i]); } return total / 2; } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destGradientDataNumber=destObject; destGradientDataNumber._currentLength=this._currentLength; var destElements=destGradientDataNumber._elements; destElements.length=this._elements.length; for (var i=0,n=this._elements.length;i < n;i++) destElements[i]=this._elements[i]; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destGradientDataNumber=/*__JS__ */new this.constructor(); this.cloneTo(destGradientDataNumber); return destGradientDataNumber; } /**渐变浮点数量。*/ __getset(0,__proto,'gradientCount',function(){ return this._currentLength / 2; }); return GradientDataNumber; })() /** *GradientDataVector2 类用于创建二维向量渐变。 */ //class laya.d3.core.particleShuriKen.module.GradientDataVector2 var GradientDataVector2=(function(){ function GradientDataVector2(){ /**@private */ this._currentLength=0; /**@private 开发者禁止修改。*/ this._elements=null; this._elements=new Float32Array(12); } __class(GradientDataVector2,'laya.d3.core.particleShuriKen.module.GradientDataVector2'); var __proto=GradientDataVector2.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *增加二维向量渐变。 *@param key 生命周期,范围为0到1。 *@param value 二维向量值。 */ __proto.add=function(key,value){ if (this._currentLength < 8){ if ((this._currentLength===6)&& ((key!==1))){ key=1; console.log("GradientDataVector2 warning:the forth key is be force set to 1."); } this._elements[this._currentLength++]=key; this._elements[this._currentLength++]=value.x; this._elements[this._currentLength++]=value.y; }else { console.log("GradientDataVector2 warning:data count must lessEqual than 4"); } } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destGradientDataVector2=destObject; destGradientDataVector2._currentLength=this._currentLength; var destElements=destGradientDataVector2._elements; destElements.length=this._elements.length; for (var i=0,n=this._elements.length;i < n;i++){ destElements[i]=this._elements[i]; } } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destGradientDataVector2=/*__JS__ */new this.constructor(); this.cloneTo(destGradientDataVector2); return destGradientDataVector2; } /**二维向量渐变数量。*/ __getset(0,__proto,'gradientCount',function(){ return this._currentLength / 3; }); return GradientDataVector2; })() /** *GradientSize 类用于创建渐变尺寸。 */ //class laya.d3.core.particleShuriKen.module.GradientSize var GradientSize=(function(){ function GradientSize(){ /**@private */ this._type=0; /**@private */ this._separateAxes=false; /**@private */ this._gradient=null; /**@private */ this._gradientX=null; /**@private */ this._gradientY=null; /**@private */ this._gradientZ=null; /**@private */ this._constantMin=NaN; /**@private */ this._constantMax=NaN; /**@private */ this._constantMinSeparate=null; /**@private */ this._constantMaxSeparate=null; /**@private */ this._gradientMin=null; /**@private */ this._gradientMax=null; /**@private */ this._gradientXMin=null; /**@private */ this._gradientXMax=null; /**@private */ this._gradientYMin=null; /**@private */ this._gradientYMax=null; /**@private */ this._gradientZMin=null; /**@private */ this._gradientZMax=null; } __class(GradientSize,'laya.d3.core.particleShuriKen.module.GradientSize'); var __proto=GradientSize.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *获取最大尺寸。 */ __proto.getMaxSizeInGradient=function(){ var i=0,n=0; var maxSize=-Number.MAX_VALUE; switch (this._type){ case 0: if (this._separateAxes){ for (i=0,n=this._gradientX.gradientCount;i < n;i++) maxSize=Math.max(maxSize,this._gradientX.getValueByIndex(i)); for (i=0,n=this._gradientY.gradientCount;i < n;i++) maxSize=Math.max(maxSize,this._gradientY.getValueByIndex(i)); }else { for (i=0,n=this._gradient.gradientCount;i < n;i++) maxSize=Math.max(maxSize,this._gradient.getValueByIndex(i)); } break ; case 1: if (this._separateAxes){ maxSize=Math.max(this._constantMinSeparate.x,this._constantMaxSeparate.x); maxSize=Math.max(maxSize,this._constantMinSeparate.y); maxSize=Math.max(maxSize,this._constantMaxSeparate.y); }else { maxSize=Math.max(this._constantMin,this._constantMax); } break ; case 2: if (this._separateAxes){ for (i=0,n=this._gradientXMin.gradientCount;i < n;i++) maxSize=Math.max(maxSize,this._gradientXMin.getValueByIndex(i)); for (i=0,n=this._gradientXMax.gradientCount;i < n;i++) maxSize=Math.max(maxSize,this._gradientXMax.getValueByIndex(i)); for (i=0,n=this._gradientYMin.gradientCount;i < n;i++) maxSize=Math.max(maxSize,this._gradientYMin.getValueByIndex(i)); for (i=0,n=this._gradientZMax.gradientCount;i < n;i++) maxSize=Math.max(maxSize,this._gradientZMax.getValueByIndex(i)); }else { for (i=0,n=this._gradientMin.gradientCount;i < n;i++) maxSize=Math.max(maxSize,this._gradientMin.getValueByIndex(i)); for (i=0,n=this._gradientMax.gradientCount;i < n;i++) maxSize=Math.max(maxSize,this._gradientMax.getValueByIndex(i)); } break ; } return maxSize; } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destGradientSize=destObject; destGradientSize._type=this._type; destGradientSize._separateAxes=this._separateAxes; this._gradient.cloneTo(destGradientSize._gradient); this._gradientX.cloneTo(destGradientSize._gradientX); this._gradientY.cloneTo(destGradientSize._gradientY); this._gradientZ.cloneTo(destGradientSize._gradientZ); destGradientSize._constantMin=this._constantMin; destGradientSize._constantMax=this._constantMax; this._constantMinSeparate.cloneTo(destGradientSize._constantMinSeparate); this._constantMaxSeparate.cloneTo(destGradientSize._constantMaxSeparate); this._gradientMin.cloneTo(destGradientSize._gradientMin); this._gradientMax.cloneTo(destGradientSize._gradientMax); this._gradientXMin.cloneTo(destGradientSize._gradientXMin); this._gradientXMax.cloneTo(destGradientSize._gradientXMax); this._gradientYMin.cloneTo(destGradientSize._gradientYMin); this._gradientYMax.cloneTo(destGradientSize._gradientYMax); this._gradientZMin.cloneTo(destGradientSize._gradientZMin); this._gradientZMax.cloneTo(destGradientSize._gradientZMax); } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destGradientSize=/*__JS__ */new this.constructor(); this.cloneTo(destGradientSize); return destGradientSize; } /** *渐变尺寸Z。 */ __getset(0,__proto,'gradientZ',function(){ return this._gradientZ; }); /** *渐变尺寸。 */ __getset(0,__proto,'gradient',function(){ return this._gradient; }); /** *是否分轴。 */ __getset(0,__proto,'separateAxes',function(){ return this._separateAxes; }); /** *生命周期尺寸类型,0曲线模式,1随机双常量模式,2随机双曲线模式。 */ __getset(0,__proto,'type',function(){ return this._type; }); /** *渐变最小尺寸。 */ __getset(0,__proto,'gradientMin',function(){ return this._gradientMin; }); /** *最小随机双固定尺寸。 */ __getset(0,__proto,'constantMin',function(){ return this._constantMin; }); /** *渐变尺寸X。 */ __getset(0,__proto,'gradientX',function(){ return this._gradientX; }); /** *渐变尺寸Y。 */ __getset(0,__proto,'gradientY',function(){ return this._gradientY; }); /** *渐变最大尺寸。 */ __getset(0,__proto,'gradientMax',function(){ return this._gradientMax; }); /** *最大随机双固定尺寸。 */ __getset(0,__proto,'constantMax',function(){ return this._constantMax; }); /** *最小分轴随机双固定尺寸。 */ __getset(0,__proto,'constantMinSeparate',function(){ return this._constantMinSeparate; }); /** *最小分轴随机双固定尺寸。 */ __getset(0,__proto,'constantMaxSeparate',function(){ return this._constantMaxSeparate; }); /** *渐变最小尺寸X。 */ __getset(0,__proto,'gradientXMin',function(){ return this._gradientXMin; }); /** *渐变最大尺寸X。 */ __getset(0,__proto,'gradientXMax',function(){ return this._gradientXMax; }); /** *渐变最小尺寸Y。 */ __getset(0,__proto,'gradientYMin',function(){ return this._gradientYMin; }); /** *渐变最大尺寸Y。 */ __getset(0,__proto,'gradientYMax',function(){ return this._gradientYMax; }); /** *渐变最小尺寸Z。 */ __getset(0,__proto,'gradientZMin',function(){ return this._gradientZMin; }); /** *渐变最大尺寸Z。 */ __getset(0,__proto,'gradientZMax',function(){ return this._gradientZMax; }); GradientSize.createByGradient=function(gradient){ var gradientSize=new GradientSize(); gradientSize._type=0; gradientSize._separateAxes=false; gradientSize._gradient=gradient; return gradientSize; } GradientSize.createByGradientSeparate=function(gradientX,gradientY,gradientZ){ var gradientSize=new GradientSize(); gradientSize._type=0; gradientSize._separateAxes=true; gradientSize._gradientX=gradientX; gradientSize._gradientY=gradientY; gradientSize._gradientZ=gradientZ; return gradientSize; } GradientSize.createByRandomTwoConstant=function(constantMin,constantMax){ var gradientSize=new GradientSize(); gradientSize._type=1; gradientSize._separateAxes=false; gradientSize._constantMin=constantMin; gradientSize._constantMax=constantMax; return gradientSize; } GradientSize.createByRandomTwoConstantSeparate=function(constantMinSeparate,constantMaxSeparate){ var gradientSize=new GradientSize(); gradientSize._type=1; gradientSize._separateAxes=true; gradientSize._constantMinSeparate=constantMinSeparate; gradientSize._constantMaxSeparate=constantMaxSeparate; return gradientSize; } GradientSize.createByRandomTwoGradient=function(gradientMin,gradientMax){ var gradientSize=new GradientSize(); gradientSize._type=2; gradientSize._separateAxes=false; gradientSize._gradientMin=gradientMin; gradientSize._gradientMax=gradientMax; return gradientSize; } GradientSize.createByRandomTwoGradientSeparate=function(gradientXMin,gradientXMax,gradientYMin,gradientYMax,gradientZMin,gradientZMax){ var gradientSize=new GradientSize(); gradientSize._type=2; gradientSize._separateAxes=true; gradientSize._gradientXMin=gradientXMin; gradientSize._gradientXMax=gradientXMax; gradientSize._gradientYMin=gradientYMin; gradientSize._gradientYMax=gradientYMax; gradientSize._gradientZMin=gradientZMin; gradientSize._gradientZMax=gradientZMax; return gradientSize; } return GradientSize; })() /** *GradientVelocity 类用于创建渐变速度。 */ //class laya.d3.core.particleShuriKen.module.GradientVelocity var GradientVelocity=(function(){ function GradientVelocity(){ /**@private */ this._type=0; /**@private */ this._constant=null; /**@private */ this._gradientX=null; /**@private */ this._gradientY=null; /**@private */ this._gradientZ=null; /**@private */ this._constantMin=null; /**@private */ this._constantMax=null; /**@private */ this._gradientXMin=null; /**@private */ this._gradientXMax=null; /**@private */ this._gradientYMin=null; /**@private */ this._gradientYMax=null; /**@private */ this._gradientZMin=null; /**@private */ this._gradientZMax=null; } __class(GradientVelocity,'laya.d3.core.particleShuriKen.module.GradientVelocity'); var __proto=GradientVelocity.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destGradientVelocity=destObject; destGradientVelocity._type=this._type; this._constant.cloneTo(destGradientVelocity._constant); this._gradientX.cloneTo(destGradientVelocity._gradientX); this._gradientY.cloneTo(destGradientVelocity._gradientY); this._gradientZ.cloneTo(destGradientVelocity._gradientZ); this._constantMin.cloneTo(destGradientVelocity._constantMin); this._constantMax.cloneTo(destGradientVelocity._constantMax); this._gradientXMin.cloneTo(destGradientVelocity._gradientXMin); this._gradientXMax.cloneTo(destGradientVelocity._gradientXMax); this._gradientYMin.cloneTo(destGradientVelocity._gradientYMin); this._gradientYMax.cloneTo(destGradientVelocity._gradientYMax); this._gradientZMin.cloneTo(destGradientVelocity._gradientZMin); this._gradientZMax.cloneTo(destGradientVelocity._gradientZMax); } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destGradientVelocity=/*__JS__ */new this.constructor(); this.cloneTo(destGradientVelocity); return destGradientVelocity; } /** *渐变速度Z。 */ __getset(0,__proto,'gradientZ',function(){ return this._gradientZ; }); /**固定速度。*/ __getset(0,__proto,'constant',function(){ return this._constant; }); /** *生命周期速度类型,0常量模式,1曲线模式,2随机双常量模式,3随机双曲线模式。 */ __getset(0,__proto,'type',function(){ return this._type; }); /** *渐变最大速度X。 */ __getset(0,__proto,'gradientXMax',function(){ return this._gradientXMax; }); /**最小固定速度。*/ __getset(0,__proto,'constantMin',function(){ return this._constantMin; }); /** *渐变速度X。 */ __getset(0,__proto,'gradientX',function(){ return this._gradientX; }); /** *渐变速度Y。 */ __getset(0,__proto,'gradientY',function(){ return this._gradientY; }); /** *渐变最小速度X。 */ __getset(0,__proto,'gradientXMin',function(){ return this._gradientXMin; }); /**最大固定速度。*/ __getset(0,__proto,'constantMax',function(){ return this._constantMax; }); /** *渐变最小速度Y。 */ __getset(0,__proto,'gradientYMin',function(){ return this._gradientYMin; }); /** *渐变最大速度Y。 */ __getset(0,__proto,'gradientYMax',function(){ return this._gradientYMax; }); /** *渐变最小速度Z。 */ __getset(0,__proto,'gradientZMin',function(){ return this._gradientZMin; }); /** *渐变最大速度Z。 */ __getset(0,__proto,'gradientZMax',function(){ return this._gradientZMax; }); GradientVelocity.createByConstant=function(constant){ var gradientVelocity=new GradientVelocity(); gradientVelocity._type=0; gradientVelocity._constant=constant; return gradientVelocity; } GradientVelocity.createByGradient=function(gradientX,gradientY,gradientZ){ var gradientVelocity=new GradientVelocity(); gradientVelocity._type=1; gradientVelocity._gradientX=gradientX; gradientVelocity._gradientY=gradientY; gradientVelocity._gradientZ=gradientZ; return gradientVelocity; } GradientVelocity.createByRandomTwoConstant=function(constantMin,constantMax){ var gradientVelocity=new GradientVelocity(); gradientVelocity._type=2; gradientVelocity._constantMin=constantMin; gradientVelocity._constantMax=constantMax; return gradientVelocity; } GradientVelocity.createByRandomTwoGradient=function(gradientXMin,gradientXMax,gradientYMin,gradientYMax,gradientZMin,gradientZMax){ var gradientVelocity=new GradientVelocity(); gradientVelocity._type=3; gradientVelocity._gradientXMin=gradientXMin; gradientVelocity._gradientXMax=gradientXMax; gradientVelocity._gradientYMin=gradientYMin; gradientVelocity._gradientYMax=gradientYMax; gradientVelocity._gradientZMin=gradientZMin; gradientVelocity._gradientZMax=gradientZMax; return gradientVelocity; } return GradientVelocity; })() /** *RotationOverLifetime 类用于粒子的生命周期旋转。 */ //class laya.d3.core.particleShuriKen.module.RotationOverLifetime var RotationOverLifetime=(function(){ function RotationOverLifetime(angularVelocity){ /**@private */ this._angularVelocity=null; /**是否启用*/ this.enbale=false; this._angularVelocity=angularVelocity; } __class(RotationOverLifetime,'laya.d3.core.particleShuriKen.module.RotationOverLifetime'); var __proto=RotationOverLifetime.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destRotationOverLifetime=destObject; this._angularVelocity.cloneTo(destRotationOverLifetime._angularVelocity); destRotationOverLifetime.enbale=this.enbale; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destAngularVelocity; switch (this._angularVelocity.type){ case 0: if (this._angularVelocity.separateAxes) destAngularVelocity=GradientAngularVelocity.createByConstantSeparate(this._angularVelocity.constantSeparate.clone()); else destAngularVelocity=GradientAngularVelocity.createByConstant(this._angularVelocity.constant); break ; case 1: if (this._angularVelocity.separateAxes) destAngularVelocity=GradientAngularVelocity.createByGradientSeparate(this._angularVelocity.gradientX.clone(),this._angularVelocity.gradientY.clone(),this._angularVelocity.gradientZ.clone(),this._angularVelocity.gradientW.clone()); else destAngularVelocity=GradientAngularVelocity.createByGradient(this._angularVelocity.gradient.clone()); break ; case 2: if (this._angularVelocity.separateAxes) destAngularVelocity=GradientAngularVelocity.createByRandomTwoConstantSeparate(this._angularVelocity.constantMinSeparate.clone(),this._angularVelocity.constantMaxSeparate.clone()); else destAngularVelocity=GradientAngularVelocity.createByRandomTwoConstant(this._angularVelocity.constantMin,this._angularVelocity.constantMax); break ; case 3: if (this._angularVelocity.separateAxes) destAngularVelocity=GradientAngularVelocity.createByRandomTwoGradientSeparate(this._angularVelocity.gradientXMin.clone(),this._angularVelocity.gradientYMin.clone(),this._angularVelocity.gradientZMin.clone(),this._angularVelocity.gradientWMin.clone(),this._angularVelocity.gradientXMax.clone(),this._angularVelocity.gradientYMax.clone(),this._angularVelocity.gradientZMax.clone(),this._angularVelocity.gradientWMax.clone()); else destAngularVelocity=GradientAngularVelocity.createByRandomTwoGradient(this._angularVelocity.gradientMin.clone(),this._angularVelocity.gradientMax.clone()); break ; }; var destRotationOverLifetime=/*__JS__ */new this.constructor(destAngularVelocity); destRotationOverLifetime.enbale=this.enbale; return destRotationOverLifetime; } /** *获取角速度。 */ __getset(0,__proto,'angularVelocity',function(){ return this._angularVelocity; }); return RotationOverLifetime; })() /** *BaseShape 类用于粒子形状。 */ //class laya.d3.core.particleShuriKen.module.shape.BaseShape var BaseShape=(function(){ function BaseShape(){ /**是否启用。*/ this.enable=false; /**随机方向。*/ this.randomDirection=false; } __class(BaseShape,'laya.d3.core.particleShuriKen.module.shape.BaseShape'); var __proto=BaseShape.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /**@private */ __proto._getShapeBoundBox=function(boundBox){ throw new Error("BaseShape: must override it."); } /**@private */ __proto._getSpeedBoundBox=function(boundBox){ throw new Error("BaseShape: must override it."); } /** *用于生成粒子初始位置和方向。 *@param position 粒子位置。 *@param direction 粒子方向。 */ __proto.generatePositionAndDirection=function(position,direction,rand,randomSeeds){ throw new Error("BaseShape: must override it."); } /** *@private */ __proto._calculateProceduralBounds=function(boundBox,emitterPosScale,minMaxBounds){ this._getShapeBoundBox(boundBox); var min=boundBox.min; var max=boundBox.max; Vector3.multiply(min,emitterPosScale,min); Vector3.multiply(max,emitterPosScale,max); var speedBounds=new BoundBox(new Vector3(),new Vector3()); if (this.randomDirection){ speedBounds.min=new Vector3(-1,-1,-1); speedBounds.max=new Vector3(1,1,1); } else{ this._getSpeedBoundBox(speedBounds); }; var maxSpeedBound=new BoundBox(new Vector3(),new Vector3()); var maxSpeedMin=maxSpeedBound.min; var maxSpeedMax=maxSpeedBound.max; Vector3.scale(speedBounds.min,minMaxBounds.y,maxSpeedMin); Vector3.scale(speedBounds.max,minMaxBounds.y,maxSpeedMax); Vector3.add(boundBox.min,maxSpeedMin,maxSpeedMin); Vector3.add(boundBox.max,maxSpeedMax,maxSpeedMax); Vector3.min(boundBox.min,maxSpeedMin,boundBox.min); Vector3.max(boundBox.max,maxSpeedMin,boundBox.max); var minSpeedBound=new BoundBox(new Vector3(),new Vector3()); var minSpeedMin=minSpeedBound.min; var minSpeedMax=minSpeedBound.max; Vector3.scale(speedBounds.min,minMaxBounds.x,minSpeedMin); Vector3.scale(speedBounds.max,minMaxBounds.x,minSpeedMax); Vector3.min(minSpeedBound.min,minSpeedMax,maxSpeedMin); Vector3.max(minSpeedBound.min,minSpeedMax,maxSpeedMax); Vector3.min(boundBox.min,maxSpeedMin,boundBox.min); Vector3.max(boundBox.max,maxSpeedMin,boundBox.max); } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destShape=destObject; destShape.enable=this.enable; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destShape=/*__JS__ */new this.constructor(); this.cloneTo(destShape); return destShape; } return BaseShape; })() /** *... *@author ... */ //class laya.d3.core.particleShuriKen.module.shape.ShapeUtils var ShapeUtils=(function(){ function ShapeUtils(){} __class(ShapeUtils,'laya.d3.core.particleShuriKen.module.shape.ShapeUtils'); ShapeUtils._randomPointUnitArcCircle=function(arc,out,rand){ var outE=out.elements; var angle=NaN; if (rand) angle=rand.getFloat()*arc; else angle=Math.random()*arc; outE[0]=Math.cos(angle); outE[1]=Math.sin(angle); } ShapeUtils._randomPointInsideUnitArcCircle=function(arc,out,rand){ var outE=out.elements; ShapeUtils._randomPointUnitArcCircle(arc,out,rand); var range=NaN; if (rand) range=Math.pow(rand.getFloat(),1.0 / 2.0); else range=Math.pow(Math.random(),1.0 / 2.0); outE[0]=outE[0] *range; outE[1]=outE[1] *range; } ShapeUtils._randomPointUnitCircle=function(out,rand){ var outE=out.elements; var angle=NaN; if (rand) angle=rand.getFloat()*Math.PI *2; else angle=Math.random()*Math.PI *2; outE[0]=Math.cos(angle); outE[1]=Math.sin(angle); } ShapeUtils._randomPointInsideUnitCircle=function(out,rand){ var outE=out.elements; ShapeUtils._randomPointUnitCircle(out); var range=NaN; if (rand) range=Math.pow(rand.getFloat(),1.0 / 2.0); else range=Math.pow(Math.random(),1.0 / 2.0); outE[0]=outE[0] *range; outE[1]=outE[1] *range; } ShapeUtils._randomPointUnitSphere=function(out,rand){ var outE=out.elements; var z=NaN; var a=NaN; if (rand){ z=outE[2]=rand.getFloat()*2-1.0; a=rand.getFloat()*Math.PI *2; }else { z=outE[2]=Math.random()*2-1.0; a=Math.random()*Math.PI *2; }; var r=Math.sqrt(1.0-z *z); outE[0]=r *Math.cos(a); outE[1]=r *Math.sin(a); } ShapeUtils._randomPointInsideUnitSphere=function(out,rand){ var outE=out.elements; ShapeUtils._randomPointUnitSphere(out); var range=NaN; if (rand) range=Math.pow(rand.getFloat(),1.0 / 3.0); else range=Math.pow(Math.random(),1.0 / 3.0); outE[0]=outE[0] *range; outE[1]=outE[1] *range; outE[2]=outE[2] *range; } ShapeUtils._randomPointInsideHalfUnitBox=function(out,rand){ var outE=out.elements; if (rand){ outE[0]=(rand.getFloat()-0.5); outE[1]=(rand.getFloat()-0.5); outE[2]=(rand.getFloat()-0.5); }else { outE[0]=(Math.random()-0.5); outE[1]=(Math.random()-0.5); outE[2]=(Math.random()-0.5); } } return ShapeUtils; })() /** *SizeOverLifetime 类用于粒子的生命周期尺寸。 */ //class laya.d3.core.particleShuriKen.module.SizeOverLifetime var SizeOverLifetime=(function(){ function SizeOverLifetime(size){ /**@private */ this._size=null; /**是否启用*/ this.enbale=false; this._size=size; } __class(SizeOverLifetime,'laya.d3.core.particleShuriKen.module.SizeOverLifetime'); var __proto=SizeOverLifetime.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destSizeOverLifetime=destObject; this._size.cloneTo(destSizeOverLifetime._size); destSizeOverLifetime.enbale=this.enbale; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destSize; switch (this._size.type){ case 0: if (this._size.separateAxes) destSize=GradientSize.createByGradientSeparate(this._size.gradientX.clone(),this._size.gradientY.clone(),this._size.gradientZ.clone()); else destSize=GradientSize.createByGradient(this._size.gradient.clone()); break ; case 1: if (this._size.separateAxes) destSize=GradientSize.createByRandomTwoConstantSeparate(this._size.constantMinSeparate.clone(),this._size.constantMaxSeparate.clone()); else destSize=GradientSize.createByRandomTwoConstant(this._size.constantMin,this._size.constantMax); break ; case 2: if (this._size.separateAxes) destSize=GradientSize.createByRandomTwoGradientSeparate(this._size.gradientXMin.clone(),this._size.gradientYMin.clone(),this._size.gradientZMin.clone(),this._size.gradientXMax.clone(),this._size.gradientYMax.clone(),this._size.gradientZMax.clone()); else destSize=GradientSize.createByRandomTwoGradient(this._size.gradientMin.clone(),this._size.gradientMax.clone()); break ; }; var destSizeOverLifetime=/*__JS__ */new this.constructor(destSize); destSizeOverLifetime.enbale=this.enbale; return destSizeOverLifetime; } /** *获取尺寸。 */ __getset(0,__proto,'size',function(){ return this._size; }); return SizeOverLifetime; })() /** *StartFrame 类用于创建开始帧。 */ //class laya.d3.core.particleShuriKen.module.StartFrame var StartFrame=(function(){ function StartFrame(){ /**@private */ this._type=0; /**@private */ this._constant=NaN; /**@private */ this._constantMin=NaN; /**@private */ this._constantMax=NaN; } __class(StartFrame,'laya.d3.core.particleShuriKen.module.StartFrame'); var __proto=StartFrame.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destStartFrame=destObject; destStartFrame._type=this._type; destStartFrame._constant=this._constant; destStartFrame._constantMin=this._constantMin; destStartFrame._constantMax=this._constantMax; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destStartFrame=/*__JS__ */new this.constructor(); this.cloneTo(destStartFrame); return destStartFrame; } /** *固定帧。 */ __getset(0,__proto,'constant',function(){ return this._constant; }); /** *开始帧类型,0常量模式,1随机双常量模式。 */ __getset(0,__proto,'type',function(){ return this._type; }); /** *最小固定帧。 */ __getset(0,__proto,'constantMin',function(){ return this._constantMin; }); /** *最大固定帧。 */ __getset(0,__proto,'constantMax',function(){ return this._constantMax; }); StartFrame.createByConstant=function(constant){ var rotationOverLifetime=new StartFrame(); rotationOverLifetime._type=0; rotationOverLifetime._constant=constant; return rotationOverLifetime; } StartFrame.createByRandomTwoConstant=function(constantMin,constantMax){ var rotationOverLifetime=new StartFrame(); rotationOverLifetime._type=1; rotationOverLifetime._constantMin=constantMin; rotationOverLifetime._constantMax=constantMax; return rotationOverLifetime; } return StartFrame; })() /** *TextureSheetAnimation 类用于创建粒子帧动画。 */ //class laya.d3.core.particleShuriKen.module.TextureSheetAnimation var TextureSheetAnimation=(function(){ function TextureSheetAnimation(frame,startFrame){ /**@private */ this._frame=null; /**@private */ this._startFrame=null; /**纹理平铺。*/ this.tiles=null; /**类型,0为whole sheet、1为singal row。*/ this.type=0; /**是否随机行,type为1时有效。*/ this.randomRow=false; /**行索引,type为1时有效。*/ this.rowIndex=0; /**循环次数。*/ this.cycles=0; /**UV通道类型,0为Noting,1为Everything,待补充,暂不支持。*/ this.enableUVChannels=0; /**是否启用*/ this.enable=false; this.tiles=new Vector2(1,1); this.type=0; this.randomRow=true; this.rowIndex=0; this.cycles=1; this.enableUVChannels=1; this._frame=frame; this._startFrame=startFrame; } __class(TextureSheetAnimation,'laya.d3.core.particleShuriKen.module.TextureSheetAnimation'); var __proto=TextureSheetAnimation.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destTextureSheetAnimation=destObject; this.tiles.cloneTo(destTextureSheetAnimation.tiles); destTextureSheetAnimation.type=this.type; destTextureSheetAnimation.randomRow=this.randomRow; this._frame.cloneTo(destTextureSheetAnimation._frame); this._startFrame.cloneTo(destTextureSheetAnimation._startFrame); destTextureSheetAnimation.cycles=this.cycles; destTextureSheetAnimation.enableUVChannels=this.enableUVChannels; destTextureSheetAnimation.enable=this.enable; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destFrame; switch (this._frame.type){ case 0: destFrame=FrameOverTime.createByConstant(this._frame.constant); break ; case 1: destFrame=FrameOverTime.createByOverTime(this._frame.frameOverTimeData.clone()); break ; case 2: destFrame=FrameOverTime.createByRandomTwoConstant(this._frame.constantMin,this._frame.constantMax); break ; case 3: destFrame=FrameOverTime.createByRandomTwoOverTime(this._frame.frameOverTimeDataMin.clone(),this._frame.frameOverTimeDataMax.clone()); break ; }; var destStartFrame; switch (this._startFrame.type){ case 0: destStartFrame=StartFrame.createByConstant(this._startFrame.constant); break ; case 1: destStartFrame=StartFrame.createByRandomTwoConstant(this._startFrame.constantMin,this._startFrame.constantMax); break ; }; var destTextureSheetAnimation=/*__JS__ */new this.constructor(destFrame,destStartFrame); this.tiles.cloneTo(destTextureSheetAnimation.tiles); destTextureSheetAnimation.type=this.type; destTextureSheetAnimation.randomRow=this.randomRow; destTextureSheetAnimation.cycles=this.cycles; destTextureSheetAnimation.enableUVChannels=this.enableUVChannels; destTextureSheetAnimation.enable=this.enable; return destTextureSheetAnimation; } /**获取时间帧率。*/ __getset(0,__proto,'frame',function(){ return this._frame; }); /**获取开始帧率。*/ __getset(0,__proto,'startFrame',function(){ return this._startFrame; }); return TextureSheetAnimation; })() /** *VelocityOverLifetime 类用于粒子的生命周期速度。 */ //class laya.d3.core.particleShuriKen.module.VelocityOverLifetime var VelocityOverLifetime=(function(){ function VelocityOverLifetime(velocity){ /**@private */ this._velocity=null; /**是否启用*/ this.enbale=false; /**速度空间,0为local,1为world。*/ this.space=0; this._velocity=velocity; } __class(VelocityOverLifetime,'laya.d3.core.particleShuriKen.module.VelocityOverLifetime'); var __proto=VelocityOverLifetime.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destVelocityOverLifetime=destObject; this._velocity.cloneTo(destVelocityOverLifetime._velocity); destVelocityOverLifetime.enbale=this.enbale; destVelocityOverLifetime.space=this.space; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destVelocity; switch(this._velocity.type){ case 0: destVelocity=GradientVelocity.createByConstant(this._velocity.constant.clone()); break ; case 1: destVelocity=GradientVelocity.createByGradient(this._velocity.gradientX.clone(),this._velocity.gradientY.clone(),this._velocity.gradientZ.clone()); break ; case 2: destVelocity=GradientVelocity.createByRandomTwoConstant(this._velocity.constantMin.clone(),this._velocity.constantMax.clone()); break ; case 3: destVelocity=GradientVelocity.createByRandomTwoGradient(this._velocity.gradientXMin.clone(),this._velocity.gradientYMin.clone(),this._velocity.gradientZMin.clone(),this._velocity.gradientXMax.clone(),this._velocity.gradientYMax.clone(),this._velocity.gradientZMax.clone()); break ; }; var destVelocityOverLifetime=/*__JS__ */new this.constructor(destVelocity); destVelocityOverLifetime.enbale=this.enbale; destVelocityOverLifetime.space=this.space; return destVelocityOverLifetime; } /** *获取尺寸。 */ __getset(0,__proto,'velocity',function(){ return this._velocity; }); return VelocityOverLifetime; })() /** *@private */ //class laya.d3.core.particleShuriKen.ShurikenParticleData var ShurikenParticleData=(function(){ function ShurikenParticleData(){} __class(ShurikenParticleData,'laya.d3.core.particleShuriKen.ShurikenParticleData'); ShurikenParticleData._getStartLifetimeFromGradient=function(startLifeTimeGradient,emissionTime){ for (var i=1,n=startLifeTimeGradient.gradientCount;i < n;i++){ var key=startLifeTimeGradient.getKeyByIndex(i); if (key >=emissionTime){ var lastKey=startLifeTimeGradient.getKeyByIndex(i-1); var age=(emissionTime-lastKey)/ (key-lastKey); return MathUtil.lerp(startLifeTimeGradient.getValueByIndex(i-1),startLifeTimeGradient.getValueByIndex(i),age) } } throw new Error("ShurikenParticleData: can't get value foam startLifeTimeGradient."); } ShurikenParticleData._randomInvertRoationArray=function(rotatonE,outE,randomizeRotationDirection,rand,randomSeeds){ var randDic=NaN; if (rand){ rand.seed=randomSeeds[6]; randDic=rand.getFloat(); randomSeeds[6]=rand.seed; }else { randDic=Math.random(); } if (randDic < randomizeRotationDirection){ outE[0]=-rotatonE[0]; outE[1]=-rotatonE[1]; outE[2]=-rotatonE[2]; }else { outE[0]=rotatonE[0]; outE[1]=rotatonE[1]; outE[2]=rotatonE[2]; } } ShurikenParticleData._randomInvertRoation=function(rotaton,randomizeRotationDirection,rand,randomSeeds){ var randDic=NaN; if (rand){ rand.seed=randomSeeds[6]; randDic=rand.getFloat(); randomSeeds[6]=rand.seed; }else { randDic=Math.random(); } if (randDic < randomizeRotationDirection) rotaton=-rotaton; return rotaton; } ShurikenParticleData.create=function(particleSystem,particleRender,transform){ var autoRandomSeed=particleSystem.autoRandomSeed; var rand=particleSystem._rand; var randomSeeds=particleSystem._randomSeeds; switch (particleSystem.startColorType){ case 0:; var constantStartColorE=particleSystem.startColorConstant.elements; ShurikenParticleData.startColor[0]=constantStartColorE[0]; ShurikenParticleData.startColor[1]=constantStartColorE[1]; ShurikenParticleData.startColor[2]=constantStartColorE[2]; ShurikenParticleData.startColor[3]=constantStartColorE[3]; break ; case 2: if (autoRandomSeed){ MathUtil.lerpVector4(particleSystem.startColorConstantMin.elements,particleSystem.startColorConstantMax.elements,Math.random(),ShurikenParticleData.startColor); }else { rand.seed=randomSeeds[3]; MathUtil.lerpVector4(particleSystem.startColorConstantMin.elements,particleSystem.startColorConstantMax.elements,rand.getFloat(),ShurikenParticleData.startColor); randomSeeds[3]=rand.seed; } break ; }; var colorOverLifetime=particleSystem.colorOverLifetime; if (colorOverLifetime && colorOverLifetime.enbale){ var color=colorOverLifetime.color; switch (color.type){ case 0: ShurikenParticleData.startColor[0]=ShurikenParticleData.startColor[0] *color.constant.x; ShurikenParticleData.startColor[1]=ShurikenParticleData.startColor[1] *color.constant.y; ShurikenParticleData.startColor[2]=ShurikenParticleData.startColor[2] *color.constant.z; ShurikenParticleData.startColor[3]=ShurikenParticleData.startColor[3] *color.constant.w; break ; case 2:; var colorRandom=NaN; if (autoRandomSeed){ colorRandom=Math.random(); }else { rand.seed=randomSeeds[10]; colorRandom=rand.getFloat(); randomSeeds[10]=rand.seed; }; var minConstantColor=color.constantMin; var maxConstantColor=color.constantMax; ShurikenParticleData.startColor[0]=ShurikenParticleData.startColor[0] *MathUtil.lerp(minConstantColor.x,maxConstantColor.x,colorRandom); ShurikenParticleData.startColor[1]=ShurikenParticleData.startColor[1] *MathUtil.lerp(minConstantColor.y,maxConstantColor.y,colorRandom); ShurikenParticleData.startColor[2]=ShurikenParticleData.startColor[2] *MathUtil.lerp(minConstantColor.z,maxConstantColor.z,colorRandom); ShurikenParticleData.startColor[3]=ShurikenParticleData.startColor[3] *MathUtil.lerp(minConstantColor.w,maxConstantColor.w,colorRandom); break ; } }; var particleSize=ShurikenParticleData.startSize; switch (particleSystem.startSizeType){ case 0: if (particleSystem.threeDStartSize){ var startSizeConstantSeparate=particleSystem.startSizeConstantSeparate; particleSize[0]=startSizeConstantSeparate.x; particleSize[1]=startSizeConstantSeparate.y; particleSize[2]=startSizeConstantSeparate.z; }else { particleSize[0]=particleSize[1]=particleSize[2]=particleSystem.startSizeConstant; } break ; case 2: if (particleSystem.threeDStartSize){ var startSizeConstantMinSeparate=particleSystem.startSizeConstantMinSeparate; var startSizeConstantMaxSeparate=particleSystem.startSizeConstantMaxSeparate; if (autoRandomSeed){ particleSize[0]=MathUtil.lerp(startSizeConstantMinSeparate.x,startSizeConstantMaxSeparate.x,Math.random()); particleSize[1]=MathUtil.lerp(startSizeConstantMinSeparate.y,startSizeConstantMaxSeparate.y,Math.random()); particleSize[2]=MathUtil.lerp(startSizeConstantMinSeparate.z,startSizeConstantMaxSeparate.z,Math.random()); }else { rand.seed=randomSeeds[4]; particleSize[0]=MathUtil.lerp(startSizeConstantMinSeparate.x,startSizeConstantMaxSeparate.x,rand.getFloat()); particleSize[1]=MathUtil.lerp(startSizeConstantMinSeparate.y,startSizeConstantMaxSeparate.y,rand.getFloat()); particleSize[2]=MathUtil.lerp(startSizeConstantMinSeparate.z,startSizeConstantMaxSeparate.z,rand.getFloat()); randomSeeds[4]=rand.seed; } }else { if (autoRandomSeed){ particleSize[0]=particleSize[1]=particleSize[2]=MathUtil.lerp(particleSystem.startSizeConstantMin,particleSystem.startSizeConstantMax,Math.random()); }else { rand.seed=randomSeeds[4]; particleSize[0]=particleSize[1]=particleSize[2]=MathUtil.lerp(particleSystem.startSizeConstantMin,particleSystem.startSizeConstantMax,rand.getFloat()); randomSeeds[4]=rand.seed; } } break ; }; var sizeOverLifetime=particleSystem.sizeOverLifetime; if (sizeOverLifetime && sizeOverLifetime.enbale && sizeOverLifetime.size.type===1){ var size=sizeOverLifetime.size; if (size.separateAxes){ if (autoRandomSeed){ particleSize[0]=particleSize[0] *MathUtil.lerp(size.constantMinSeparate.x,size.constantMaxSeparate.x,Math.random()); particleSize[1]=particleSize[1] *MathUtil.lerp(size.constantMinSeparate.y,size.constantMaxSeparate.y,Math.random()); particleSize[2]=particleSize[2] *MathUtil.lerp(size.constantMinSeparate.z,size.constantMaxSeparate.z,Math.random()); }else { rand.seed=randomSeeds[11]; particleSize[0]=particleSize[0] *MathUtil.lerp(size.constantMinSeparate.x,size.constantMaxSeparate.x,rand.getFloat()); particleSize[1]=particleSize[1] *MathUtil.lerp(size.constantMinSeparate.y,size.constantMaxSeparate.y,rand.getFloat()); particleSize[2]=particleSize[2] *MathUtil.lerp(size.constantMinSeparate.z,size.constantMaxSeparate.z,rand.getFloat()); randomSeeds[11]=rand.seed; } }else { var randomSize=NaN; if (autoRandomSeed){ randomSize=MathUtil.lerp(size.constantMin,size.constantMax,Math.random()); }else { rand.seed=randomSeeds[11]; randomSize=MathUtil.lerp(size.constantMin,size.constantMax,rand.getFloat()); randomSeeds[11]=rand.seed; } particleSize[0]=particleSize[0] *randomSize; particleSize[1]=particleSize[1] *randomSize; particleSize[2]=particleSize[2] *randomSize; } }; var renderMode=particleRender.renderMode; if (renderMode!==1){ switch (particleSystem.startRotationType){ case 0: if (particleSystem.threeDStartRotation){ var startRotationConstantSeparate=particleSystem.startRotationConstantSeparate; var randomRotationE=ShurikenParticleData._tempVector30.elements; ShurikenParticleData._randomInvertRoationArray(startRotationConstantSeparate.elements,randomRotationE,particleSystem.randomizeRotationDirection,autoRandomSeed ? null :rand,randomSeeds); ShurikenParticleData.startRotation[0]=randomRotationE[0]; ShurikenParticleData.startRotation[1]=randomRotationE[1]; if (renderMode!==4) ShurikenParticleData.startRotation[2]=-randomRotationE[2]; else ShurikenParticleData.startRotation[2]=randomRotationE[2]; }else { ShurikenParticleData.startRotation[0]=ShurikenParticleData._randomInvertRoation(particleSystem.startRotationConstant,particleSystem.randomizeRotationDirection,autoRandomSeed ? null :rand,randomSeeds); } break ; case 2: if (particleSystem.threeDStartRotation){ var startRotationConstantMinSeparate=particleSystem.startRotationConstantMinSeparate; var startRotationConstantMaxSeparate=particleSystem.startRotationConstantMaxSeparate; var lerpRoationE=ShurikenParticleData._tempVector30.elements; if (autoRandomSeed){ lerpRoationE[0]=MathUtil.lerp(startRotationConstantMinSeparate.x,startRotationConstantMaxSeparate.x,Math.random()); lerpRoationE[1]=MathUtil.lerp(startRotationConstantMinSeparate.y,startRotationConstantMaxSeparate.y,Math.random()); lerpRoationE[2]=MathUtil.lerp(startRotationConstantMinSeparate.z,startRotationConstantMaxSeparate.z,Math.random()); }else { rand.seed=randomSeeds[5]; lerpRoationE[0]=MathUtil.lerp(startRotationConstantMinSeparate.x,startRotationConstantMaxSeparate.x,rand.getFloat()); lerpRoationE[1]=MathUtil.lerp(startRotationConstantMinSeparate.y,startRotationConstantMaxSeparate.y,rand.getFloat()); lerpRoationE[2]=MathUtil.lerp(startRotationConstantMinSeparate.z,startRotationConstantMaxSeparate.z,rand.getFloat()); randomSeeds[5]=rand.seed; } ShurikenParticleData._randomInvertRoationArray(lerpRoationE,lerpRoationE,particleSystem.randomizeRotationDirection,autoRandomSeed ? null :rand,randomSeeds); ShurikenParticleData.startRotation[0]=lerpRoationE[0]; ShurikenParticleData.startRotation[1]=lerpRoationE[1]; if (renderMode!==4) ShurikenParticleData.startRotation[2]=-lerpRoationE[2]; else ShurikenParticleData.startRotation[2]=lerpRoationE[2]; }else { if (autoRandomSeed){ ShurikenParticleData.startRotation[0]=ShurikenParticleData._randomInvertRoation(MathUtil.lerp(particleSystem.startRotationConstantMin,particleSystem.startRotationConstantMax,Math.random()),particleSystem.randomizeRotationDirection,autoRandomSeed ? null :rand,randomSeeds); }else { rand.seed=randomSeeds[5]; ShurikenParticleData.startRotation[0]=ShurikenParticleData._randomInvertRoation(MathUtil.lerp(particleSystem.startRotationConstantMin,particleSystem.startRotationConstantMax,rand.getFloat()),particleSystem.randomizeRotationDirection,autoRandomSeed ? null :rand,randomSeeds); randomSeeds[5]=rand.seed; } } break ; } } switch (particleSystem.startLifetimeType){ case 0: ShurikenParticleData.startLifeTime=particleSystem.startLifetimeConstant; break ; case 1: ShurikenParticleData.startLifeTime=ShurikenParticleData._getStartLifetimeFromGradient(particleSystem.startLifeTimeGradient,particleSystem.emissionTime); break ; case 2: if (autoRandomSeed){ ShurikenParticleData.startLifeTime=MathUtil.lerp(particleSystem.startLifetimeConstantMin,particleSystem.startLifetimeConstantMax,Math.random()); }else { rand.seed=randomSeeds[7]; ShurikenParticleData.startLifeTime=MathUtil.lerp(particleSystem.startLifetimeConstantMin,particleSystem.startLifetimeConstantMax,rand.getFloat()); randomSeeds[7]=rand.seed; } break ; case 3:; var emissionTime=particleSystem.emissionTime; if (autoRandomSeed){ ShurikenParticleData.startLifeTime=MathUtil.lerp(ShurikenParticleData._getStartLifetimeFromGradient(particleSystem.startLifeTimeGradientMin,emissionTime),ShurikenParticleData._getStartLifetimeFromGradient(particleSystem.startLifeTimeGradientMax,emissionTime),Math.random()); }else { rand.seed=randomSeeds[7]; ShurikenParticleData.startLifeTime=MathUtil.lerp(ShurikenParticleData._getStartLifetimeFromGradient(particleSystem.startLifeTimeGradientMin,emissionTime),ShurikenParticleData._getStartLifetimeFromGradient(particleSystem.startLifeTimeGradientMax,emissionTime),rand.getFloat()); randomSeeds[7]=rand.seed; } break ; } switch (particleSystem.startSpeedType){ case 0: ShurikenParticleData.startSpeed=particleSystem.startSpeedConstant; break ; case 2: if (autoRandomSeed){ ShurikenParticleData.startSpeed=MathUtil.lerp(particleSystem.startSpeedConstantMin,particleSystem.startSpeedConstantMax,Math.random()); }else { rand.seed=randomSeeds[8]; ShurikenParticleData.startSpeed=MathUtil.lerp(particleSystem.startSpeedConstantMin,particleSystem.startSpeedConstantMax,rand.getFloat()); randomSeeds[8]=rand.seed; } break ; }; var textureSheetAnimation=particleSystem.textureSheetAnimation; var enableSheetAnimation=textureSheetAnimation && textureSheetAnimation.enable; if (enableSheetAnimation){ var title=textureSheetAnimation.tiles; var titleX=title.x,titleY=title.y; var subU=1.0 / titleX,subV=1.0 / titleY; var startFrameCount=0; var startFrame=textureSheetAnimation.startFrame; switch (startFrame.type){ case 0: startFrameCount=startFrame.constant; break ; case 1: if (autoRandomSeed){ startFrameCount=MathUtil.lerp(startFrame.constantMin,startFrame.constantMax,Math.random()); }else { rand.seed=randomSeeds[14]; startFrameCount=MathUtil.lerp(startFrame.constantMin,startFrame.constantMax,rand.getFloat()); randomSeeds[14]=rand.seed; } break ; }; var frame=textureSheetAnimation.frame; switch (frame.type){ case 0: startFrameCount+=frame.constant; break ; case 2: if (autoRandomSeed){ startFrameCount+=MathUtil.lerp(frame.constantMin,frame.constantMax,Math.random()); }else { rand.seed=randomSeeds[15]; startFrameCount+=MathUtil.lerp(frame.constantMin,frame.constantMax,rand.getFloat()); randomSeeds[15]=rand.seed; } break ; }; var startRow=0; switch (textureSheetAnimation.type){ case 0: startRow=Math.floor(startFrameCount / titleX); break ; case 1: if (textureSheetAnimation.randomRow){ if (autoRandomSeed){ startRow=Math.floor(Math.random()*titleY); }else { rand.seed=randomSeeds[13]; startRow=Math.floor(rand.getFloat()*titleY); randomSeeds[13]=rand.seed; } }else { startRow=textureSheetAnimation.rowIndex; } break ; }; var startCol=Math.floor(startFrameCount % titleX); ShurikenParticleData.startUVInfo=ShurikenParticleData.startUVInfo; ShurikenParticleData.startUVInfo[0]=subU; ShurikenParticleData.startUVInfo[1]=subV; ShurikenParticleData.startUVInfo[2]=startCol *subU; ShurikenParticleData.startUVInfo[3]=startRow *subV; }else { ShurikenParticleData.startUVInfo=ShurikenParticleData.startUVInfo; ShurikenParticleData.startUVInfo[0]=1.0; ShurikenParticleData.startUVInfo[1]=1.0; ShurikenParticleData.startUVInfo[2]=0.0; ShurikenParticleData.startUVInfo[3]=0.0; } switch (particleSystem.simulationSpace){ case 0:; var positionE=transform.position.elements; ShurikenParticleData.simulationWorldPostion[0]=positionE[0]; ShurikenParticleData.simulationWorldPostion[1]=positionE[1]; ShurikenParticleData.simulationWorldPostion[2]=positionE[2]; var rotationE=transform.rotation.elements; ShurikenParticleData.simulationWorldRotation[0]=rotationE[0]; ShurikenParticleData.simulationWorldRotation[1]=rotationE[1]; ShurikenParticleData.simulationWorldRotation[2]=rotationE[2]; ShurikenParticleData.simulationWorldRotation[3]=rotationE[3]; break ; case 1: break ; default : throw new Error("ShurikenParticleMaterial: SimulationSpace value is invalid."); break ; } } ShurikenParticleData.startLifeTime=NaN; ShurikenParticleData.startSpeed=NaN; __static(ShurikenParticleData, ['_tempVector30',function(){return this._tempVector30=new Vector3();},'_tempQuaternion',function(){return this._tempQuaternion=new Quaternion();},'startColor',function(){return this.startColor=new Float32Array(4);},'startSize',function(){return this.startSize=new Float32Array(3);},'startRotation',function(){return this.startRotation=new Float32Array(3);},'startUVInfo',function(){return this.startUVInfo=new Float32Array(4);},'simulationWorldPostion',function(){return this.simulationWorldPostion=new Float32Array(3);},'simulationWorldRotation',function(){return this.simulationWorldRotation=new Float32Array(4);} ]); return ShurikenParticleData; })() /** *@private *PhasorSpriter3D 类用于创建矢量笔刷。 */ //class laya.d3.core.PhasorSpriter3D var PhasorSpriter3D=(function(){ function PhasorSpriter3D(){ this._tempInt0=0; this._tempInt1=0; this._tempUint0=0; this._tempUint1=0; this._tempUint2=0; this._tempUint3=0; this._tempUint4=0; this._tempUint5=0; this._tempUint6=0; this._tempUint7=0; this._tempNumver0=NaN; this._tempNumver1=NaN; this._tempNumver2=NaN; this._tempNumver3=NaN; this._floatSizePerVer=7; //顶点结构为Position(3个float)+Color(4个float) this._defaultBufferSize=600 *this._floatSizePerVer; this._vb=null; this._posInVBData=0; this._ib=null; this._posInIBData=0; this._primitiveType=NaN; this._hasBegun=false; this._numVertsPerPrimitive=0; this._camera=null; this._sharderNameID=0; this._shader=null; /**@private */ this._shaderCompile=null; this._vbData=new Float32Array(this._defaultBufferSize); this._ibData=new Uint16Array(this._defaultBufferSize); this._spriteShaderValue=new ValusArray(); ; this._vb=VertexBuffer3D.create(PhasorSpriter3D._vertexDeclaration,this._defaultBufferSize / this._floatSizePerVer,/*laya.webgl.WebGLContext.DYNAMIC_DRAW*/0x88E8); this._ib=IndexBuffer3D.create(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",this._defaultBufferSize,/*laya.webgl.WebGLContext.DYNAMIC_DRAW*/0x88E8); this._sharderNameID=Shader3D.nameKey.getID("LINE"); this._shaderCompile=ShaderCompile3D._preCompileShader[this._sharderNameID]; } __class(PhasorSpriter3D,'laya.d3.core.PhasorSpriter3D'); var __proto=PhasorSpriter3D.prototype; __proto.line=function(startPosition,startColor,endPosition,endColor){ if (!this._hasBegun || this._primitiveType!==/*laya.webgl.WebGLContext.LINES*/0x0001) this.drawLinesException(); if (this._posInVBData+2 *this._floatSizePerVer > this._vbData.length || this._posInIBData+2 > this._ibData.length) this.flush(); this._tempUint0=this._posInVBData / this._floatSizePerVer; this.addVertex(startPosition.x,startPosition.y,startPosition.z,startColor.x,startColor.y,startColor.z,startColor.w); this.addVertex(endPosition.x,endPosition.y,endPosition.z,endColor.x,endColor.y,endColor.z,endColor.w); this.addIndexes(this._tempUint0,this._tempUint0+1); return this; } __proto.circle=function(radius,numberOfPoints,r,g,b,a){ if (!this._hasBegun || (this._primitiveType!==/*laya.webgl.WebGLContext.LINES*/0x0001)) this.drawLinesException(); this._tempUint0=numberOfPoints *2; if (this._posInVBData+this._tempUint0 *this._floatSizePerVer > this._vbData.length || this._posInIBData+2 *this._tempUint0 > this._ibData.length) this.flush(); this._tempUint1=this._posInVBData / this._floatSizePerVer; for (this._tempNumver0=0,this._tempInt0=0;this._tempNumver0 < 3.1416 *2;this._tempNumver0=this._tempNumver0+(3.1416 / numberOfPoints),this._tempInt0++){ this.addVertex(Math.sin(this._tempNumver0)*radius,Math.cos(this._tempNumver0)*radius,0,r,g,b,a); if (this._tempInt0===0){ this.addIndexes(this._tempUint1); }else if (this._tempInt0===this._tempUint0-1){ this._tempUint2=this._tempUint1+this._tempInt0; this.addIndexes(this._tempUint2,this._tempUint2,this._tempUint1); }else { this._tempUint2=this._tempUint1+this._tempInt0; this.addIndexes(this._tempUint2,this._tempUint2); } } return this; } __proto.plane=function(positionX,positionY,positionZ,width,height,r,g,b,a){ if (!this._hasBegun || this._primitiveType!==/*laya.webgl.WebGLContext.TRIANGLES*/0x0004) this.drawTrianglesException(); if (this._posInVBData+4 *this._floatSizePerVer > this._vbData.length || this._posInIBData+6 > this._ibData.length) this.flush(); this._tempNumver0=width / 2; this._tempNumver1=height / 2; this._tempUint0=this._posInVBData / this._floatSizePerVer; this.addVertex(positionX-this._tempNumver0,positionY+this._tempNumver1,positionZ,r,g,b,a); this.addVertex(positionX+this._tempNumver0,positionY+this._tempNumver1,positionZ,r,g,b,a); this.addVertex(positionX-this._tempNumver0,positionY-this._tempNumver1,positionZ,r,g,b,a); this.addVertex(positionX+this._tempNumver0,positionY-this._tempNumver1,positionZ,r,g,b,a); this._tempUint1=this._tempUint0+1; this._tempUint2=this._tempUint0+2; this.addIndexes(this._tempUint0,this._tempUint1,this._tempUint2,this._tempUint2,this._tempUint1,this._tempUint0+3); return this; } __proto.box=function(positionX,positionY,positionZ,width,height,depth,r,g,b,a){ if (!this._hasBegun || this._primitiveType!==/*laya.webgl.WebGLContext.TRIANGLES*/0x0004) this.drawTrianglesException(); if (this._posInVBData+8 *this._floatSizePerVer > this._vbData.length || this._posInIBData+36 > this._ibData.length) this.flush(); this._tempNumver0=width / 2; this._tempNumver1=height / 2; this._tempNumver2=depth / 2; this._tempUint0=this._posInVBData / this._floatSizePerVer; this.addVertex(positionX-this._tempNumver0,positionY+this._tempNumver1,positionZ+this._tempNumver2,r,g,b,a); this.addVertex(positionX+this._tempNumver0,positionY+this._tempNumver1,positionZ+this._tempNumver2,r,g,b,a); this.addVertex(positionX-this._tempNumver0,positionY-this._tempNumver1,positionZ+this._tempNumver2,r,g,b,a); this.addVertex(positionX+this._tempNumver0,positionY-this._tempNumver1,positionZ+this._tempNumver2,r,g,b,a); this.addVertex(positionX+this._tempNumver0,positionY+this._tempNumver1,positionZ-this._tempNumver2,r,g,b,a); this.addVertex(positionX-this._tempNumver0,positionY+this._tempNumver1,positionZ-this._tempNumver2,r,g,b,a); this.addVertex(positionX+this._tempNumver0,positionY-this._tempNumver1,positionZ-this._tempNumver2,r,g,b,a); this.addVertex(positionX-this._tempNumver0,positionY-this._tempNumver1,positionZ-this._tempNumver2,r,g,b,a); this._tempUint1=this._tempUint0+1; this._tempUint2=this._tempUint0+2; this._tempUint3=this._tempUint0+3; this._tempUint4=this._tempUint0+4; this._tempUint5=this._tempUint0+5; this._tempUint6=this._tempUint0+6; this._tempUint7=this._tempUint0+7; this.addIndexes(this._tempUint0,this._tempUint1,this._tempUint2,this._tempUint2,this._tempUint1,this._tempUint3, this._tempUint4,this._tempUint5,this._tempUint6,this._tempUint6,this._tempUint5,this._tempUint7, this._tempUint5,this._tempUint0,this._tempUint7,this._tempUint7,this._tempUint0,this._tempUint2, this._tempUint1,this._tempUint4,this._tempUint3,this._tempUint3,this._tempUint4,this._tempUint6, this._tempUint5,this._tempUint4,this._tempUint0,this._tempUint0,this._tempUint4,this._tempUint1, this._tempUint2,this._tempUint3,this._tempUint7,this._tempUint7,this._tempUint3,this._tempUint6); return this; } __proto.cone=function(radius,length,Slices,r,g,b,a){ if (!this._hasBegun || this._primitiveType!==/*laya.webgl.WebGLContext.TRIANGLES*/0x0004) this.drawTrianglesException(); if (this._posInVBData+(2 *Slices+2)*this._floatSizePerVer > this._vbData.length || this._posInIBData+6 *Slices > this._ibData.length) this.flush(); this._tempUint0=this._posInVBData; this._tempUint1=this._posInVBData / this._floatSizePerVer; this._tempNumver0=Math.PI *2 / Slices; this.addVertexIndex(0,length,0,r,g,b,a,this._tempUint0); this.addVertexIndex(0,0,0,r,g,b,a,this._tempUint0+this._floatSizePerVer); this._tempInt0=2; this._tempNumver1=0; for (this._tempInt1=0;this._tempInt1 < Slices;this._tempInt1++){ this._tempNumver2=Math.cos(this._tempNumver1); this._tempNumver3=Math.sin(this._tempNumver1); this.addVertexIndex(radius *this._tempNumver2,0,radius *this._tempNumver3,r,g,b,a,this._tempUint0+this._tempInt0 *this._floatSizePerVer); this.addIndexes(this._tempUint1,this._tempUint1+this._tempInt0); if (this._tempInt1==Slices-1) this.addIndexes(this._tempUint1+2); else this.addIndexes(this._tempUint1+this._tempInt0+1); this.addVertexIndex(radius *this._tempNumver2,0,radius *this._tempNumver3,r,g,b,a,this._tempUint0+(this._tempInt0+Slices)*this._floatSizePerVer); this.addIndexes(this._tempUint1+1); if (this._tempInt1==Slices-1) this.addIndexes(this._tempUint1+Slices+2); else this.addIndexes(this._tempUint1+this._tempInt0+Slices+1); this.addIndexes(this._tempUint1+this._tempInt0+Slices); this._tempInt0++; this._tempNumver1+=this._tempNumver0; } return this; } __proto.boundingBoxLine=function(minX,minY,minZ,maxX,maxY,maxZ,r,g,b,a){ if (!this._hasBegun || this._primitiveType!==/*laya.webgl.WebGLContext.LINES*/0x0001) this.drawLinesException(); if (this._posInVBData+8 *this._floatSizePerVer > this._vbData.length || this._posInIBData+48 > this._ibData.length) this.flush(); this._tempUint0=this._posInVBData / this._floatSizePerVer; this.addVertex(minX,maxY,maxZ,r,g,b,a); this.addVertex(maxX,maxY,maxZ,r,g,b,a); this.addVertex(minX,minY,maxZ,r,g,b,a); this.addVertex(maxX,minY,maxZ,r,g,b,a); this.addVertex(maxX,maxY,minZ,r,g,b,a); this.addVertex(minX,maxY,minZ,r,g,b,a); this.addVertex(maxX,minY,minZ,r,g,b,a); this.addVertex(minX,minY,minZ,r,g,b,a); this._tempUint1=this._tempUint0+1; this._tempUint2=this._tempUint0+2; this._tempUint3=this._tempUint0+3; this._tempUint4=this._tempUint0+4; this._tempUint5=this._tempUint0+5; this._tempUint6=this._tempUint0+6; this._tempUint7=this._tempUint0+7; this.addIndexes(this._tempUint0,this._tempUint1,this._tempUint1,this._tempUint3,this._tempUint3,this._tempUint2,this._tempUint2,this._tempUint0, this._tempUint4,this._tempUint5,this._tempUint5,this._tempUint7,this._tempUint7,this._tempUint6,this._tempUint6,this._tempUint4, this._tempUint5,this._tempUint0,this._tempUint0,this._tempUint2,this._tempUint2,this._tempUint7,this._tempUint7,this._tempUint5, this._tempUint1,this._tempUint4,this._tempUint4,this._tempUint6,this._tempUint6,this._tempUint3,this._tempUint3,this._tempUint1, this._tempUint5,this._tempUint4,this._tempUint4,this._tempUint1,this._tempUint1,this._tempUint0,this._tempUint0,this._tempUint5, this._tempUint2,this._tempUint3,this._tempUint3,this._tempUint6,this._tempUint6,this._tempUint7,this._tempUint7,this._tempUint2); return this; } __proto.addVertex=function(x,y,z,r,g,b,a){ if (!this._hasBegun) this.addVertexIndexException(); this._vbData[this._posInVBData]=x,this._vbData[this._posInVBData+1]=y,this._vbData[this._posInVBData+2]=z; this._vbData[this._posInVBData+3]=r,this._vbData[this._posInVBData+4]=g,this._vbData[this._posInVBData+5]=b,this._vbData[this._posInVBData+6]=a; this._posInVBData+=this._floatSizePerVer; return this; } __proto.addVertexIndex=function(x,y,z,r,g,b,a,index){ if (!this._hasBegun) this.addVertexIndexException(); this._vbData[index]=x,this._vbData[index+1]=y,this._vbData[index+2]=z; this._vbData[index+3]=r,this._vbData[index+4]=g,this._vbData[index+5]=b,this._vbData[index+6]=a; index+=this._floatSizePerVer; if (index > this._posInVBData) this._posInVBData=index; return this; } __proto.addIndexes=function(__indexes){ var indexes=arguments; if (!this._hasBegun) this.addVertexIndexException(); for (var i=0;i < indexes.length;i++){ this._ibData[this._posInIBData]=indexes[i]; this._posInIBData++; } return this; } __proto.begin=function(primitive,camera){ if (this._hasBegun) this.beginException0(); if (primitive!==/*laya.webgl.WebGLContext.LINES*/0x0001 && primitive!==/*laya.webgl.WebGLContext.TRIANGLES*/0x0004) this.beginException1(); this._primitiveType=primitive; this._camera=camera; this._hasBegun=true; return this; } __proto.end=function(){ if (!this._hasBegun) this.endException(); this.flush(); this._hasBegun=false; return this; } __proto.flush=function(){ if (this._posInVBData===0) return; this._ib.setData(this._ibData); this._vb.setData(this._vbData); this._vb._bind(); this._ib._bind(); this._shader=this._shaderCompile.withCompile(0,0,0); this._shader.bind(); this._shader.uploadAttributes(PhasorSpriter3D._vertexDeclaration.shaderValues.data,null); this._spriteShaderValue.setValue(/*laya.d3.core.Sprite3D.MVPMATRIX*/1,(this._camera).projectionViewMatrix.elements); this._shader.uploadSpriteUniforms(this._spriteShaderValue.data); Stat.drawCall++; WebGL.mainContext.drawElements(this._primitiveType,this._posInIBData,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,0); this._posInIBData=0; this._posInVBData=0; } __proto.addVertexIndexException=function(){ throw new Error("请先调用begin()函数"); } __proto.beginException0=function(){ throw new Error("调用begin()前请确保已成功调用end()!"); } __proto.beginException1=function(){ throw new Error("只支持“LINES”和“TRIANGLES”两种基元!"); } __proto.endException=function(){ throw new Error("调用end()前请确保已成功调用begin()!"); } __proto.drawLinesException=function(){ throw new Error("您必须确保在此之前已调用begin()且使用“LINES”基元!"); } __proto.drawTrianglesException=function(){ throw new Error("您必须确保在此之前已调用begin()且使用“TRIANGLES”基元!"); } __static(PhasorSpriter3D, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(28,[new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0),new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1)]);} ]); return PhasorSpriter3D; })() /** *@private *RenderElement 类用于实现渲染物体。 */ //class laya.d3.core.render.RenderElement var RenderElement=(function(){ function RenderElement(){ /**@private */ this._id=0; /**@private 类型0为默认,2为DynamicBatch。*/ this._type=0; /**@private 排序ID。*/ this._mainSortID=0; /**@private */ this._render=null; /**@private 所属Sprite3D精灵。*/ this._sprite3D=null; /**@private 渲染所用材质。*/ this._material=null; /**@private 渲染元素。*/ this._renderObj=null; /**@private */ this._staticBatch=null; //...............临时........................... this._tempBatchIndexStart=0; //TODO: this._tempBatchIndexEnd=0; /**@private */ this._canDynamicBatch=false; /**当前ShaderValue。*/ this._shaderValue=null; this._onPreRenderFunction=null; this._id=++RenderElement._uniqueIDCounter; this._canDynamicBatch=true; this._shaderValue=new ValusArray(); } __class(RenderElement,'laya.d3.core.render.RenderElement'); var __proto=RenderElement.prototype; /** *@private */ __proto.getDynamicBatchBakedVertexs=function(index){ var byteSizeInFloat=4; var vb=this._renderObj._getVertexBuffer(index); var bakedVertexes=vb.getData().slice(); var vertexDeclaration=vb.vertexDeclaration; var positionOffset=vertexDeclaration.getVertexElementByUsage(/*laya.d3.graphics.VertexElementUsage.POSITION0*/0).offset / byteSizeInFloat; var normalOffset=vertexDeclaration.getVertexElementByUsage(/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3).offset / byteSizeInFloat; var transform=this._sprite3D.transform; var worldMatrix=transform.worldMatrix; var rotation=transform.rotation; var vertexFloatCount=vertexDeclaration.vertexStride / byteSizeInFloat; for (var i=0,n=bakedVertexes.length;i < n;i+=vertexFloatCount){ var posOffset=i+positionOffset; var norOffset=i+normalOffset; Utils3D.transformVector3ArrayToVector3ArrayCoordinate(bakedVertexes,posOffset,worldMatrix,bakedVertexes,posOffset); Utils3D.transformVector3ArrayByQuat(bakedVertexes,norOffset,rotation,bakedVertexes,norOffset); } return bakedVertexes; } /** *@private */ __proto.getBakedIndices=function(){ return this._renderObj._getIndexBuffer().getData(); } /** *@private */ __proto._destroy=function(){ (this._staticBatch)&& (this._staticBatch._manager._garbageCollection(this)); } /** *获取唯一标识ID,通常用于识别。 */ __getset(0,__proto,'id',function(){ return this._id; }); __getset(0,__proto,'renderObj',function(){ return this._renderObj; },function(value){ if (this._renderObj!==value){ this._renderObj=value; } }); RenderElement._uniqueIDCounter=0; return RenderElement; })() /** *@private *RenderQuene 类用于实现渲染队列。 */ //class laya.d3.core.render.RenderQueue var RenderQueue=(function(){ function RenderQueue(scene){ /**@private */ this._id=0; /**@private */ this._needSort=false; /**@private */ this._renderElements=null; /**@private */ this._renderableRenderObjects=null; /**@private */ this._dynamicBatchCombineRenderElements=null; /**@private */ this._finalElements=null; /**@private */ this._scene=null; this._id=++RenderQueue._uniqueIDCounter; this._needSort=false; this._scene=scene; this._renderElements=[]; this._renderableRenderObjects=[]; this._dynamicBatchCombineRenderElements=[]; } __class(RenderQueue,'laya.d3.core.render.RenderQueue'); var __proto=RenderQueue.prototype; __proto._sortOpaqueFunc=function(a,b){ if (a._render && b._render){ var renderQueue=a._material.renderQueue-b._material.renderQueue; if (renderQueue===0){ return a._render._distanceForSort-b._render._distanceForSort; }else { return renderQueue } }else { return 0; } } __proto._sortAlphaFunc=function(a,b){ if (a._render && b._render){ var renderQueue=a._material.renderQueue-b._material.renderQueue; if (renderQueue===0){ return b._render._distanceForSort-a._render._distanceForSort; }else { return renderQueue; } }else return 0; } /** *@private */ __proto._begainRenderElement=function(state,renderObj,material){ if (renderObj._beforeRender(state)){ return true; } return false; } /** *@private */ __proto._sortAlpha=function(cameraPos){ RenderQueue._cameraPosition=cameraPos; this._finalElements.sort(this._sortAlphaFunc); } /** *@private */ __proto._sortOpaque=function(cameraPos){ RenderQueue._cameraPosition=cameraPos; this._finalElements.sort(this._sortOpaqueFunc); } /** *@private *准备渲染队列。 *@param state 渲染状态。 */ __proto._preRender=function(state){ this._finalElements=this._renderElements.concat(this._dynamicBatchCombineRenderElements); } /** *@private *渲染队列。 *@param state 渲染状态。 */ __proto._render=function(state,isTarget){ var loopCount=Stat.loopCount; var scene=this._scene; var camera=state.camera; var cameraID=camera.id; var vbs; var vertexBuffer,vertexDeclaration,shader; var forceUploadParams=false; var lastStateMaterial,lastStateOwner; for (var i=0,n=this._finalElements.length;i < n;i++){ var renderElement=this._finalElements[i]; var renderObj,material,owner; if (renderElement._onPreRenderFunction !=null){ renderElement._onPreRenderFunction.call(renderElement._sprite3D,state); } if (renderElement._type===0){ state.owner=owner=renderElement._sprite3D; state.renderElement=renderElement; owner._preRenderUpdateComponents(state); renderObj=renderElement.renderObj,material=renderElement._material; if (this._begainRenderElement(state,renderObj,material)){ vbs=renderObj._getVertexBuffers(); vertexBuffer=renderObj._getVertexBuffer(0); vertexDeclaration=vertexBuffer.vertexDeclaration; shader=state._shader=material._getShader(scene._shaderDefineValue,vertexDeclaration.shaderDefineValue,owner._shaderDefineValue); forceUploadParams=shader.bind()|| (loopCount!==shader._uploadLoopCount); if (vbs){ if (shader._uploadVertexBuffer!==vbs || forceUploadParams){ for (var j=0;j < vbs.length;j++){ var vb=vbs[j]; shader.uploadAttributesX(vb.vertexDeclaration.shaderValues.data,vb); } shader._uploadVertexBuffer=vbs; } }else { if (shader._uploadVertexBuffer!==vertexBuffer || forceUploadParams){ shader.uploadAttributes(vertexDeclaration.shaderValues.data,null); shader._uploadVertexBuffer=vertexBuffer; } } if (shader._uploadScene!==scene || forceUploadParams){ shader.uploadSceneUniforms(scene._shaderValues.data); shader._uploadScene=scene; } if (camera!==shader._uploadCamera || shader._uploadSprite3D!==owner || forceUploadParams){ shader.uploadSpriteUniforms(owner._shaderValues.data); shader._uploadSprite3D=owner; } if (camera!==shader._uploadCamera || forceUploadParams){ shader.uploadCameraUniforms(camera._shaderValues.data); shader._uploadCamera=camera; } if (shader._uploadMaterial!==material || forceUploadParams){ material._upload(); shader._uploadMaterial=material; } if (lastStateMaterial!==material){ material._setRenderStateBlendDepth(); material._setRenderStateFrontFace(isTarget,owner.transform); lastStateMaterial=material; lastStateOwner=owner; }else { if (lastStateOwner!==owner){ material._setRenderStateFrontFace(isTarget,owner.transform); lastStateOwner=owner; } } renderObj._render(state); shader._uploadLoopCount=loopCount; } owner._postRenderUpdateComponents(state); }else if (renderElement._type===2){ var dynamicBatch=renderElement.renderObj; state.owner=owner=renderElement._sprite3D; state.renderElement=renderElement; state._batchIndexStart=renderElement._tempBatchIndexStart; state._batchIndexEnd=renderElement._tempBatchIndexEnd; renderObj=renderElement.renderObj,material=renderElement._material; if (this._begainRenderElement(state,renderObj,material)){ vertexBuffer=renderObj._getVertexBuffer(0); vertexDeclaration=vertexBuffer.vertexDeclaration; shader=state._shader=material._getShader(scene._shaderDefineValue,vertexDeclaration.shaderDefineValue,owner._shaderDefineValue); forceUploadParams=shader.bind()|| (loopCount!==shader._uploadLoopCount); if (shader._uploadVertexBuffer!==vertexBuffer || forceUploadParams){ shader.uploadAttributes(vertexDeclaration.shaderValues.data,null); shader._uploadVertexBuffer=vertexBuffer; } if (shader._uploadScene!==scene || forceUploadParams){ shader.uploadSceneUniforms(scene._shaderValues.data); shader._uploadScene=scene; } if (camera!==shader._uploadCamera || shader._uploadSprite3D!==owner || forceUploadParams){ shader.uploadSpriteUniforms(owner._shaderValues.data); shader._uploadSprite3D=owner; } if (camera!==shader._uploadCamera || forceUploadParams){ shader.uploadCameraUniforms(camera._shaderValues.data); shader._uploadCamera=camera; } if (shader._uploadMaterial!==material || forceUploadParams){ material._upload(); shader._uploadMaterial=material; } if (lastStateMaterial!==material){ material._setRenderStateBlendDepth(); material._setRenderStateFrontFace(isTarget,owner.transform); lastStateMaterial=material; lastStateOwner=owner; }else { if (lastStateOwner!==owner){ material._setRenderStateFrontFace(isTarget,owner.transform); lastStateOwner=owner; } } renderObj._render(state); shader._uploadLoopCount=loopCount; } } } } /** *@private *渲染队列。 *@param state 渲染状态。 */ __proto._renderShadow=function(state,isOnePSSM){ var loopCount=Stat.loopCount; var scene=this._scene; var camera=state.camera; var vertexBuffer,vertexDeclaration,shader; var forceUploadParams=false; var lastStateMaterial,lastStateOwner; for (var i=0,n=this._finalElements.length;i < n;i++){ var renderElement=this._finalElements[i]; var renderObj,material,owner; if (renderElement._type===0){ state.owner=owner=renderElement._sprite3D; if (!isOnePSSM && (owner._projectionViewWorldUpdateCamera!==camera || owner._projectionViewWorldUpdateLoopCount!==Stat.loopCount)){ owner._render._renderUpdate(state._projectionViewMatrix); owner._projectionViewWorldUpdateLoopCount=Stat.loopCount; owner._projectionViewWorldUpdateCamera=camera; } state.renderElement=renderElement; owner._preRenderUpdateComponents(state); renderObj=renderElement.renderObj,material=renderElement._material; if (this._begainRenderElement(state,renderObj,null)){ vertexBuffer=renderObj._getVertexBuffer(0); vertexDeclaration=vertexBuffer.vertexDeclaration; shader=state._shader=material._getShader(scene._shaderDefineValue,vertexDeclaration.shaderDefineValue,owner._shaderDefineValue); forceUploadParams=shader.bind()|| (loopCount!==shader._uploadLoopCount); if (shader._uploadVertexBuffer!==vertexBuffer || forceUploadParams){ shader.uploadAttributes(vertexDeclaration.shaderValues.data,null); shader._uploadVertexBuffer=vertexBuffer; } if (camera!==shader._uploadCamera || shader._uploadSprite3D!==owner || forceUploadParams){ shader.uploadSpriteUniforms(owner._shaderValues.data); shader._uploadSprite3D=owner; } if (camera!==shader._uploadCamera || forceUploadParams){ shader.uploadCameraUniforms(camera._shaderValues.data); shader._uploadCamera=camera; } if (shader._uploadMaterial!==material || forceUploadParams){ material._upload(); shader._uploadMaterial=material; } if (shader._uploadRenderElement!==renderElement || forceUploadParams){} if (lastStateMaterial!==material){ material._setRenderStateFrontFace(false,owner.transform); lastStateMaterial=material; lastStateOwner=owner; }else { if (lastStateOwner!==owner){ material._setRenderStateFrontFace(false,owner.transform); lastStateOwner=owner; } } renderObj._render(state); shader._uploadLoopCount=loopCount; } owner._postRenderUpdateComponents(state); } } } /** *清空队列中的渲染物体。 */ __proto._clearRenderElements=function(){ this._dynamicBatchCombineRenderElements.length=0; this._renderElements.length=0; this._needSort=true; } /** *添加渲染物体。 *@param renderObj 渲染物体。 */ __proto._addRenderElement=function(renderElement){ this._renderElements.push(renderElement); this._needSort=true; } /** *添加动态批处理。 *@param renderObj 动态批处理。 */ __proto._addDynamicBatchElement=function(dynamicBatchElement){ this._dynamicBatchCombineRenderElements.push(dynamicBatchElement); } /** *获取唯一标识ID(通常用于优化或识别)。 */ __getset(0,__proto,'id',function(){ return this._id; }); RenderQueue._uniqueIDCounter=0; RenderQueue._cameraPosition=null; return RenderQueue; })() /** *RenderState 类用于实现渲染状态。 */ //class laya.d3.core.render.RenderState var RenderState=(function(){ function RenderState(){ /**@private */ this._staticBatch=null; /**@private */ this._batchIndexStart=0; /**@private */ this._batchIndexEnd=0; /**@private */ this._viewMatrix=null; /**@private */ this._projectionMatrix=null; /**@private */ this._projectionViewMatrix=null; /**@private */ this._viewport=null; /**@private */ this._shader=null; /**距上一帧间隔时间。*/ this.elapsedTime=NaN; /**当前场景。*/ this.scene=null; /**当前渲染3D精灵。*/ this.owner=null; /**当前渲染物体。*/ this.renderElement=null; /**当前摄像机。*/ this.camera=null; } __class(RenderState,'laya.d3.core.render.RenderState'); RenderState.clientWidth=0; RenderState.clientHeight=0; return RenderState; })() //class laya.d3.core.scene.OctreeNode var OctreeNode=(function(){ function OctreeNode(scene,currentDepth){ this._exactBox=null; this._relaxBox=null; this._scene=null; this._parent=null; this._currentDepth=0; this._boundingSphere=new BoundSphere(new Vector3(),0); this._corners=/*new vector.<>*/[new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3()]; this._boundingBoxCenter=new Vector3(); this._children=__newvec(8); this._objects=[]; this._tempBoundBoxCorners=/*new vector.<>*/[new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3()]; this._scene=scene; this._currentDepth=currentDepth; } __class(OctreeNode,'laya.d3.core.scene.OctreeNode'); var __proto=OctreeNode.prototype; Laya.imps(__proto,{"laya.d3.core.scene.ITreeNode":true}) __proto.init=function(center,treeSize){ var min=new Vector3(); var max=new Vector3(); Vector3.scale(treeSize,-0.5,min); Vector3.scale(treeSize,0.5,max); Vector3.add(min,center,min); Vector3.add(max,center,max); this.exactBox=new BoundBox(min,max); this.relaxBox=new BoundBox(min,max); } __proto.addTreeNode=function(render){ if (Collision.boxContainsBox(this._relaxBox,render.boundingBox)===/*laya.d3.math.ContainmentType.Contains*/1) this.addNodeDown(render,0); else this.addObject(render); } __proto.addChild=function(index){ var child=this._children[index]; if (child==null){ child=new OctreeNode(this._scene,this._currentDepth+1); this._children[index]=child; child._parent=this; Vector3.subtract(this._exactBox.max,this._exactBox.min,OctreeNode.tempSize); Vector3.multiply(OctreeNode.tempSize,OctreeNode._octreeSplit[index],OctreeNode.tempCenter); Vector3.add(this._exactBox.min,OctreeNode.tempCenter,OctreeNode.tempCenter); Vector3.scale(OctreeNode.tempSize,0.25,OctreeNode.tempSize); var min=new Vector3(); var max=new Vector3(); Vector3.subtract(OctreeNode.tempCenter,OctreeNode.tempSize,min); Vector3.add(OctreeNode.tempCenter,OctreeNode.tempSize,max); child.exactBox=new BoundBox(min,max); Vector3.scale(OctreeNode.tempSize,OctreeNode.relax,OctreeNode.tempSize); var relaxMin=new Vector3(); var relaxMax=new Vector3(); Vector3.subtract(OctreeNode.tempCenter,OctreeNode.tempSize,relaxMin); Vector3.add(OctreeNode.tempCenter,OctreeNode.tempSize,relaxMax); child.relaxBox=new BoundBox(relaxMin,relaxMax); } return child; } __proto.addObject=function(object){ object._treeNode=this; this._objects.push(object); } __proto.removeObject=function(object){ if (object._treeNode !=this){ console.log("OctreeNode::removeObject error"); return false; }; var index=this._objects.indexOf(object); if (index!==-1){ this._objects.splice(index,1); return true; } return false; } __proto.clearObject=function(){ this._objects.length=0; } __proto.addNodeUp=function(render,depth){ if (this._parent && (Collision.boxContainsBox(this._exactBox,render.boundingBox)!==/*laya.d3.math.ContainmentType.Contains*/1)){ this._parent.addNodeUp(render,depth-1); }else this.addNodeDown(render,depth); } __proto.addNodeDown=function(render,depth){ if (depth < this._scene.treeLevel){ var childIndex=this.inChildIndex(render.boundingBoxCenter); var child=this.addChild(childIndex); if (Collision.boxContainsBox(child._relaxBox,render.boundingBox)===/*laya.d3.math.ContainmentType.Contains*/1){ child.addNodeDown(render,++depth); }else this.addObject(render); }else { this.addObject(render); } } __proto.inChildIndex=function(objectCenter){ var z=objectCenter.z < this._boundingBoxCenter.z ? 0 :1; var y=objectCenter.y < this._boundingBoxCenter.y ? 0 :1; var x=objectCenter.x < this._boundingBoxCenter.x ? 0 :1; return z *4+y *2+x; } __proto.updateObject=function(render){ if (Collision.boxContainsBox(this._relaxBox,render.boundingBox)===/*laya.d3.math.ContainmentType.Contains*/1){ this.removeObject(render); render._treeNode=null; this.addNodeDown(render,this._currentDepth); }else if (this._parent){ this.removeObject(render); render._treeNode=null; this._parent.addNodeUp(render,this._currentDepth-1); } } __proto.cullingObjects=function(boundFrustum,testVisible,flags,cameraPosition,projectionView){ var i=0,j=0,n=0,m=0; var dynamicBatchManager=this._scene._dynamicBatchManager; for (i=0,n=this._objects.length;i < n;i++){ var render=this._objects[i]; if (Layer.isVisible(render._owner.layer.mask)&& render.enable){ if (testVisible){ Stat.treeSpriteCollision+=1; if (boundFrustum.containsBoundSphere(render.boundingSphere)===/*laya.d3.math.ContainmentType.Disjoint*/0) continue ; } render._renderUpdate(projectionView); render._distanceForSort=Vector3.distance(render.boundingSphere.center,cameraPosition)+render.sortingFudge; var renderElements=render._renderElements; for (j=0,m=renderElements.length;j < m;j++){ var renderElement=renderElements[j]; var staticBatch=renderElement._staticBatch; if (staticBatch && (staticBatch._material===renderElement._material)){ staticBatch._addBatchRenderElement(renderElement); }else { var renderObj=renderElement.renderObj; if ((renderObj.triangleCount < /*laya.d3.graphics.DynamicBatch.maxCombineTriangleCount*/10)&& (renderObj._vertexBufferCount===1)&& (renderObj._getIndexBuffer())&& (renderElement._material.renderQueue < 2)&& renderElement._canDynamicBatch && (!render._owner.isStatic)) dynamicBatchManager._addPrepareRenderElement(renderElement); else this._scene.getRenderQueue(renderElement._material.renderQueue)._addRenderElement(renderElement); } } } } for (i=0;i < 8;i++){ var child=this._children[i]; if (child==null) continue ; var testVisibleChild=testVisible; if (testVisible){ var type=boundFrustum.containsBoundBox(child._relaxBox); Stat.treeNodeCollision+=1; if (type===/*laya.d3.math.ContainmentType.Disjoint*/0) continue ; testVisibleChild=(type===/*laya.d3.math.ContainmentType.Intersects*/2); } child.cullingObjects(boundFrustum,testVisibleChild,flags,cameraPosition,projectionView); } } /** *@private */ __proto.cullingShadowObjects=function(lightBoundFrustum,splitShadowQueues,testVisible,flags,scene){ var i=0,j=0,n=0,m=0; var dynamicBatchManager=this._scene._dynamicBatchManager; for (i=0,n=this._objects.length;i < n;i++){ var baseRender=this._objects[i]; if (baseRender.castShadow && Layer.isVisible(baseRender._owner.layer.mask)&& baseRender.enable){ if (testVisible && lightBoundFrustum[0].containsBoundSphere(baseRender.boundingSphere)===/*laya.d3.math.ContainmentType.Disjoint*/0) continue ; for (var k=1,kNum=lightBoundFrustum.length;k < kNum;k++){ var shadowQueue=splitShadowQueues[k-1]; if (lightBoundFrustum[k].containsBoundSphere(baseRender.boundingSphere)!==/*laya.d3.math.ContainmentType.Disjoint*/0){ var renderElements=baseRender._renderElements; for (j=0,m=renderElements.length;j < m;j++) shadowQueue._addRenderElement(renderElements[j]); } } } } for (i=0;i < 8;i++){ var child=this._children[i]; if (child==null) continue ; var testVisibleChild=testVisible; if (testVisible){ var type=lightBoundFrustum[0].containsBoundBox(child._relaxBox); if (type===/*laya.d3.math.ContainmentType.Disjoint*/0) continue ; testVisibleChild=(type===/*laya.d3.math.ContainmentType.Intersects*/2); } child.cullingShadowObjects(lightBoundFrustum,splitShadowQueues,testVisibleChild,flags,scene); } } /** *@private */ __proto.cullingShadowObjectsOnePSSM=function(lightBoundFrustum,splitShadowQueues,lightViewProjectMatrix,testVisible,flags,scene){ var shadowQueue=splitShadowQueues[0]; var i=0,j=0,n=0,m=0; for (i=0,n=this._objects.length;i < n;i++){ var baseRender=this._objects[i]; if (baseRender.castShadow && Layer.isVisible(baseRender._owner.layer.mask)&& baseRender.enable){ if (testVisible && lightBoundFrustum.containsBoundSphere(baseRender.boundingSphere)===/*laya.d3.math.ContainmentType.Disjoint*/0) continue ; baseRender._renderUpdate(lightViewProjectMatrix); var renderElements=baseRender._renderElements; for (j=0,m=renderElements.length;j < m;j++) shadowQueue._addRenderElement(renderElements[j]); } } for (i=0;i < 8;i++){ var child=this._children[i]; if (child==null) continue ; var testVisibleChild=testVisible; if (testVisible){ var type=lightBoundFrustum.containsBoundBox(child._relaxBox); if (type===/*laya.d3.math.ContainmentType.Disjoint*/0) continue ; testVisibleChild=(type===/*laya.d3.math.ContainmentType.Intersects*/2); } child.cullingShadowObjectsOnePSSM(lightBoundFrustum,splitShadowQueues,lightViewProjectMatrix,testVisibleChild,flags,scene); } } __proto.renderBoudingBox=function(linePhasor){ this._renderBoudingBox(linePhasor); for (var i=0;i < 8;++i){ var pChild=this._children[i]; if (pChild){ pChild.renderBoudingBox(linePhasor); } } } __proto.buildAllChild=function(depth){ if (depth < this._scene.treeLevel){ for (var i=0;i < 8;i++){ var child=this.addChild(i); child.buildAllChild(depth+1); } } } __proto._renderBoudingBox=function(linePhasor){} __getset(0,__proto,'exactBox',function(){ return this._exactBox; },function(value){ this._exactBox=value; Vector3.add(value.min,value.max,this._boundingBoxCenter); Vector3.scale(this._boundingBoxCenter,0.5,this._boundingBoxCenter); }); __getset(0,__proto,'relaxBox',function(){ return this._relaxBox; },function(value){ this._relaxBox=value; value.getCorners(this._corners); BoundSphere.createfromPoints(this._corners,this._boundingSphere); }); OctreeNode.debugMode=false; OctreeNode.relax=1.15; OctreeNode.CHILDNUM=8; __static(OctreeNode, ['tempVector0',function(){return this.tempVector0=new Vector3();},'tempSize',function(){return this.tempSize=new Vector3();},'tempCenter',function(){return this.tempCenter=new Vector3();},'_octreeSplit',function(){return this._octreeSplit=[new Vector3(0.250,0.250,0.250),new Vector3(0.750,0.250,0.250),new Vector3(0.250,0.750,0.250),new Vector3(0.750,0.750,0.250),new Vector3(0.250,0.250,0.750),new Vector3(0.750,0.250,0.750),new Vector3(0.250,0.750,0.750),new Vector3(0.750,0.750,0.750)];} ]); return OctreeNode; })() /** *... *@author ... */ //class laya.d3.core.scene.SceneManager var SceneManager=(function(){ function SceneManager(){} __class(SceneManager,'laya.d3.core.scene.SceneManager'); return SceneManager; })() //class laya.d3.core.trail.module.Color var Color$1=(function(){ function Color(r,g,b,a){ this._r=NaN; this._g=NaN; this._b=NaN; this._a=NaN; (r===void 0)&& (r=1); (g===void 0)&& (g=1); (b===void 0)&& (b=1); (a===void 0)&& (a=1); this._r=r; this._g=g; this._b=b; this._a=a; } __class(Color,'laya.d3.core.trail.module.Color',null,'Color$1'); var __proto=Color.prototype; __proto.cloneTo=function(destObject){ destObject._r=this._r; destObject._g=this._g; destObject._b=this._b; destObject._a=this._a; } __static(Color, ['RED',function(){return this.RED=new Color(1,0,0,1);},'GREEN',function(){return this.GREEN=new Color(0,1,0,1);},'BLUE',function(){return this.BLUE=new Color(0,0,1,1);},'CYAN',function(){return this.CYAN=new Color(0,1,1,1);},'YELLOW',function(){return this.YELLOW=new Color(1,0.92,0.016,1);},'MAGENTA',function(){return this.MAGENTA=new Color(1,0,1,1);},'GRAY',function(){return this.GRAY=new Color(0.5,0.5,0.5,1);},'WHITE',function(){return this.WHITE=new Color(1,1,1,1);},'BLACK',function(){return this.BLACK=new Color(0,0,0,1);} ]); return Color; })() //class laya.d3.core.trail.module.Gradient var Gradient=(function(){ function Gradient(){ /** *梯度模式 */ this._mode=0; /** *颜色值关键帧数据,最大长度为10 */ this._colorKeys=null; /** *透明度关键帧数据,最大长度为10 */ this._alphaKeys=null; this.index=0; this._colorKeyData=new Float32Array(40); this._alphaKeyData=new Float32Array(20); this._colorKeys=[]; this._alphaKeys=[]; } __class(Gradient,'laya.d3.core.trail.module.Gradient'); var __proto=Gradient.prototype; /** *设置渐变,使用一组颜色关键帧数据和透明度关键帧数据。 *@param colorKeys 渐变的颜色值关键帧数据(最大长度为10)。 *@param alphaKeys 渐变的透明度关键帧数据(最大长度为10)。 */ __proto.setKeys=function(colorKeys,alphaKeys){ this._colorKeys=colorKeys; this.index=0; var gradientColorKey; for (var i=0;i < colorKeys.length;i++){ gradientColorKey=colorKeys[i]; var color=gradientColorKey.color; this._colorKeyData[this.index++]=color._r; this._colorKeyData[this.index++]=color._g; this._colorKeyData[this.index++]=color._b; this._colorKeyData[this.index++]=gradientColorKey.time; } this._alphaKeys=alphaKeys; this.index=0; var gradientAlphaKey; for (var j=0;j < alphaKeys.length;j++){ gradientAlphaKey=alphaKeys[j]; this._alphaKeyData[this.index++]=gradientAlphaKey.alpha; this._alphaKeyData[this.index++]=gradientAlphaKey.time; } } __proto.cloneTo=function(destObject){ var i=0,j=0; var cks=this.colorKeys; var _cks=[]; for (i=0,j=cks.length;i < j;i++){ var _ck=new GradientColorKey(); cks[i].cloneTo(_ck); _cks.push(_ck); }; var aks=this.alphaKeys; var _aks=[]; for (i=0,j=aks.length;i < j;i++){ var _ak=new GradientAlphaKey(); aks[i].cloneTo(_ak); _aks.push(_ak); } destObject.setKeys(_cks,_aks); } /** *设置梯度模式。 *@param value 梯度模式。 */ /** *获取梯度模式。 *@return 梯度模式。 */ __getset(0,__proto,'mode',function(){ return this._mode; },function(value){ this._mode=value; }); /** *设置颜色值关键帧数据 */ /** *获取颜色值关键帧数据 */ __getset(0,__proto,'colorKeys',function(){ return this._colorKeys; },function(values){ this._colorKeys=values; this.index=0; for (var i=0;i < values.length;i++){ var value=values[i]; var color=value.color; this._colorKeyData[this.index++]=color._r; this._colorKeyData[this.index++]=color._g; this._colorKeyData[this.index++]=color._b; this._colorKeyData[this.index++]=value.time; } }); /** *设置透明度关键帧数据 */ /** *获取透明度关键帧数据 */ __getset(0,__proto,'alphaKeys',function(){ return this._alphaKeys; },function(values){ this._alphaKeys=values; this.index=0; for (var i=0;i < values.length;i++){ var value=values[i]; this._alphaKeyData[this.index++]=value.alpha; this._alphaKeyData[this.index++]=value.time; } }); return Gradient; })() //class laya.d3.core.trail.module.GradientAlphaKey var GradientAlphaKey=(function(){ function GradientAlphaKey(alpha,time){ this._alpha=NaN; this._time=NaN; (alpha===void 0)&& (alpha=0); (time===void 0)&& (time=0); this._alpha=alpha; this._time=time; } __class(GradientAlphaKey,'laya.d3.core.trail.module.GradientAlphaKey'); var __proto=GradientAlphaKey.prototype; __proto.cloneTo=function(destObject){ destObject.alpha=this.alpha; destObject.time=this.time; } /** *设置透明度。 *@param value 透明度。 */ /** *获取透明度。 *@return 透明度。 */ __getset(0,__proto,'alpha',function(){ return this._alpha; },function(value){ this._alpha=value; }); /** *设置时间。 *@param value 时间。 */ /** *获取时间。 *@return 时间。 */ __getset(0,__proto,'time',function(){ return this._time; },function(value){ this._time=value; }); return GradientAlphaKey; })() //class laya.d3.core.trail.module.GradientColorKey var GradientColorKey=(function(){ function GradientColorKey(color,time){ this._color=null; this._time=NaN; (time===void 0)&& (time=0); this._color=color||new Color$1(); this._time=time; } __class(GradientColorKey,'laya.d3.core.trail.module.GradientColorKey'); var __proto=GradientColorKey.prototype; __proto.cloneTo=function(destObject){ this.color.cloneTo(destObject.color); destObject.time=this.time; } /** *设置颜色值。 *@param value 颜色值。 */ /** *获取颜色值。 *@return 颜色值。 */ __getset(0,__proto,'color',function(){ return this._color; },function(value){ this._color=value; }); /** *设置时间。 *@param value 时间。 */ /** *获取时间。 *@return 时间。 */ __getset(0,__proto,'time',function(){ return this._time; },function(value){ this._time=value; }); return GradientColorKey; })() /** *... *@author ... */ //class laya.d3.core.trail.module.GradientMode var GradientMode=(function(){ function GradientMode(){} __class(GradientMode,'laya.d3.core.trail.module.GradientMode'); GradientMode.Blend=0; GradientMode.Fixed=1; return GradientMode; })() /** *... *@author ... */ //class laya.d3.core.trail.module.TextureMode var TextureMode=(function(){ function TextureMode(){} __class(TextureMode,'laya.d3.core.trail.module.TextureMode'); TextureMode.Stretch=0; TextureMode.Tile=1; return TextureMode; })() //class laya.d3.core.trail.module.TrailKeyFrame var TrailKeyFrame=(function(){ function TrailKeyFrame(){ this.time=NaN; this.inTangent=NaN; this.outTangent=NaN; this.value=NaN; } __class(TrailKeyFrame,'laya.d3.core.trail.module.TrailKeyFrame'); var __proto=TrailKeyFrame.prototype; __proto.cloneTo=function(destObject){ destObject.time=this.time; destObject.inTangent=this.inTangent; destObject.outTangent=this.outTangent; destObject.value=this.value; } return TrailKeyFrame; })() /** *... *@author ... */ //class laya.d3.core.trail.TrailRenderElement var TrailRenderElement=(function(){ function TrailRenderElement(owner){ this._id=0; this._owner=null; this._camera=null; this._vertexBuffers=null; //固定顶点个数 this._verticesCount=0; //虚拟顶点个数 this._virtualVerticesCount=0; this._maxVerticesCount=256; this._vertices1=null; this._vertexBuffer1=null; this._floatCountPerVertices1=8; this._verticesIndex1=0; this._everyAddVerticeCount1=0; this._delLength=0; this._vertices2=null; this._vertexBuffer2=null; this._floatCountPerVertices2=1; this._everyGroupVertexBirthTime=null; this._VerticesToTailLength=null; this._everyVertexToPreVertexDistance=null; this._pointe=null; this._pointAtoBVector3e=null; this._isStart=false; this._isFinish=false; this._isDead=false; this._curtime=NaN; this._curDisappearIndex=0; this._lastPosition=new Vector3(); this._curPosition=new Vector3(); this._delVector3=new Vector3(); this._lastFixedVertexPosition=new Vector3(); this._pointAtoBVector3=new Vector3(); this._pointA=new Vector3(); this._pointB=new Vector3(); this._owner=owner; this._id=TrailRenderElement.renderElementCount++; if (this._id==0){ owner._owner.transform.position.cloneTo(this._lastPosition); }else { owner._curSubTrailFinishPosition.cloneTo(this._lastPosition); } this._everyGroupVertexBirthTime=[]; this._VerticesToTailLength=new Float32Array(this._maxVerticesCount); this._everyVertexToPreVertexDistance=new Float32Array(this._maxVerticesCount); this._vertices1=new Float32Array(this._maxVerticesCount *this._floatCountPerVertices1); this._vertices2=new Float32Array(this._maxVerticesCount *this._floatCountPerVertices2); this._vertexBuffer1=new VertexBuffer3D(VertexTrail.vertexDeclaration1,this._maxVerticesCount,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._vertexBuffer2=new VertexBuffer3D(VertexTrail.vertexDeclaration2,this._maxVerticesCount,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._vertexBuffers=[]; this._vertexBuffers.push(this._vertexBuffer1); this._vertexBuffers.push(this._vertexBuffer2); } __class(TrailRenderElement,'laya.d3.core.trail.TrailRenderElement'); var __proto=TrailRenderElement.prototype; Laya.imps(__proto,{"laya.d3.core.render.IRenderable":true}) /** *@private *更新Trail数据 */ __proto._updateTrail=function(){ this._everyAddVerticeCount1=0; if (!this._isStart){ this._addTrailByFirstPosition(this._lastPosition,this._curPosition); } this._addTrailByNextPosition(this._curPosition); this._vertexBuffer1.setData(this._vertices1,this._verticesIndex1,this._verticesIndex1,this._everyAddVerticeCount1); this._verticesIndex1+=this._everyAddVerticeCount1; this._curPosition.cloneTo(this._lastPosition); if (this._virtualVerticesCount==2){ this._verticesIndex1-=this._floatCountPerVertices1 *2; } } /** *@private *通过起始位置添加TrailRenderElement起始数据 *@param firstPosition 起始位置 *@param secondPosition 第二次位置 */ __proto._addTrailByFirstPosition=function(firstPosition,secondPosition){ Vector3.subtract(secondPosition,firstPosition,this._delVector3); Vector3.cross(this._delVector3,this._camera.forward,this._pointAtoBVector3); Vector3.normalize(this._pointAtoBVector3,this._pointAtoBVector3); Vector3.scale(this._pointAtoBVector3,this._owner.widthMultiplier / 2,this._pointAtoBVector3); this._updateVerticesByPosition(firstPosition); firstPosition.cloneTo(this._lastFixedVertexPosition); this._verticesCount+=2; this._curtime=this._owner._hasLifeSubTrail ? this._owner._curSubTrailFinishCurTime :this._owner._curtime; this._everyGroupVertexBirthTime.push(this._curtime); this._isStart=true; this._owner._hasLifeSubTrail=true; } /** *@private *通过位置更新TrailRenderElement数据 *@param position 位置 */ __proto._addTrailByNextPosition=function(position){ Vector3.subtract(position,this._lastFixedVertexPosition,this._delVector3); Vector3.cross(this._delVector3,this._camera.forward,this._pointAtoBVector3); Vector3.normalize(this._pointAtoBVector3,this._pointAtoBVector3); Vector3.scale(this._pointAtoBVector3,this._owner.widthMultiplier / 2,this._pointAtoBVector3); this._delLength=Vector3.scalarLength(this._delVector3); if (this._delLength-this._owner.minVertexDistance >=MathUtils3D.zeroTolerance){ this._owner._trailTotalLength+=this._delLength; this._owner._trailSupplementLength=0; this._updateVerticesByPosition(position); position.cloneTo(this._lastFixedVertexPosition); this._verticesCount+=2; this._virtualVerticesCount=0; this._everyGroupVertexBirthTime.push(this._owner._curtime); if (this._verticesCount==this._maxVerticesCount){ this._onTrailRenderElementFinish(); } } else { this._owner._trailSupplementLength=this._delLength; this._updateVerticesByPosition(position); this._virtualVerticesCount=2; } } /** *@private *通过位置更新顶点数据 *@param position 位置 */ __proto._updateVerticesByPosition=function(position){ this._pointe=position.elements; this._pointAtoBVector3e=this._pointAtoBVector3.elements; this._curtime=this._owner._curtime; if (this._owner._hasLifeSubTrail && this._isStart==false){ this._pointe=this._owner._curSubTrailFinishPosition.elements; this._pointAtoBVector3e=this._owner._curSubTrailFinishDirection.elements; this._curtime=this._owner._curSubTrailFinishCurTime; } this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._pointe[0]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._pointe[1]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._pointe[2]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=-this._pointAtoBVector3e[0]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=-this._pointAtoBVector3e[1]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=-this._pointAtoBVector3e[2]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._curtime; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=1.0; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._pointe[0]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._pointe[1]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._pointe[2]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._pointAtoBVector3e[0]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._pointAtoBVector3e[1]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._pointAtoBVector3e[2]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._curtime; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=0.0; this._VerticesToTailLength[this._verticesCount / 2]=this._owner._trailTotalLength+this._owner._trailSupplementLength; if (this._owner._trailSupplementLength==0){ this._everyVertexToPreVertexDistance[this._verticesCount / 2]=this._delLength; }else { this._everyVertexToPreVertexDistance[this._verticesCount / 2]=this._isStart ? this._owner._trailSupplementLength :0; } } /** *更新VertexBuffer2数据 */ __proto._updateVertexBuffer2=function(){ var _uvIndex=0; var _uvX=0.0; var i=0,j=0; for (i=0,j=(this._verticesCount+this._virtualVerticesCount)/ 2;i < j;i++){ if (this._owner.textureMode==/*laya.d3.core.trail.module.TextureMode.Stretch*/0){ _uvX=(this._VerticesToTailLength[i]-this._owner._trailDeadLength)/ (this._owner._trailTotalLength+this._owner._trailSupplementLength-this._owner._trailDeadLength); }else { _uvX=this._owner._trailTotalLength+this._owner._trailSupplementLength-this._VerticesToTailLength[i]; } this._vertices2[_uvIndex++]=1.0-_uvX; this._vertices2[_uvIndex++]=1.0-_uvX; } this._vertexBuffer2.setData(this._vertices2,0,0,this._verticesCount+this._virtualVerticesCount); } /** *trailRenderElement完成时调用 *@param finishedPosition */ __proto._onTrailRenderElementFinish=function(){ this._lastFixedVertexPosition.cloneTo(this._owner._curSubTrailFinishPosition); this._pointAtoBVector3.cloneTo(this._owner._curSubTrailFinishDirection); this._owner._curSubTrailFinishCurTime=this._owner._curtime; this._isFinish=true; } /** *@private */ __proto._updateDisappear=function(){ var i=0,j=0; for (i=this._curDisappearIndex,j=(this._verticesCount+this._virtualVerticesCount)/ 2;i < j;i++){ if (this._owner._curtime-this._everyGroupVertexBirthTime[i] >=this._owner.time+MathUtils3D.zeroTolerance){ this._curDisappearIndex++; this._owner._trailDeadLength+=this._everyVertexToPreVertexDistance[this._curDisappearIndex]; if (this._curDisappearIndex >=(this._verticesCount+this._virtualVerticesCount)/ 2){ this._isDead=true; } } } } /** *渲染前调用 *@param state 渲染状态 *@return 是否渲染 */ __proto._beforeRender=function(state){ this._camera=state.camera; if (this._camera==null) return false; this._owner._owner.transform.position.cloneTo(this._curPosition); if (!this._isDead){ if (this._verticesCount < this._maxVerticesCount){ if (!this._owner._isStart){ this._owner._owner.transform.position.cloneTo(this._lastPosition); this._owner._isStart=true; } if (!Vector3.equals(this._lastPosition,this._curPosition)){ this._updateTrail(); } }else { if (this._isFinish){ this._isFinish=false; this._owner._curSubTrailFinished=true; } } if (this._verticesCount > 0){ this._updateVertexBuffer2(); this._updateDisappear(); return true; } } return false; } /** *渲染时调用 *@param state 渲染状态 */ __proto._render=function(state){ if (this._isDead) return; WebGL.mainContext.drawArrays(/*laya.webgl.WebGLContext.TRIANGLE_STRIP*/0x0005,this._curDisappearIndex *2,this._verticesCount+this._virtualVerticesCount-this._curDisappearIndex *2); Stat.drawCall++; Stat.trianglesFaces+=(this._verticesCount+this._virtualVerticesCount-this._curDisappearIndex *2-2); } /** *获取vertexBuffer *@param index vertexBuffer索引 *@return vertexBuffer */ __proto._getVertexBuffer=function(index){ (index===void 0)&& (index=0); if (index===0) return this._vertexBuffer1; else if (index===1) return this._vertexBuffer2; else return null; } /** *获取vertexBuffer数组 *@return vertexBuffer数组 */ __proto._getVertexBuffers=function(){ return this._vertexBuffers; } /** *获取顶点索引缓冲 *@return 顶点索引缓冲 */ __proto._getIndexBuffer=function(){ return null; } /** *重新激活该renderElement */ __proto.reActivate=function(){ this._id=laya.d3.core.trail.TrailRenderElement.renderElementCount++; this._isStart=false; this._isFinish=false; this._isDead=false; this._verticesCount=0; this._virtualVerticesCount=0; this._verticesIndex1=0; this._delLength=0; this._curDisappearIndex=0; this._everyGroupVertexBirthTime=[]; this._owner._curSubTrailFinishPosition.cloneTo(this._lastPosition); } /** *@private */ __proto._destroy=function(){ this._vertexBuffer1.dispose(); this._vertexBuffer2.dispose(); this._vertices1=null; this._vertexBuffer1=null; this._vertices2=null; this._vertexBuffer2=null; this._vertexBuffers=null; this._everyGroupVertexBirthTime=null; this._VerticesToTailLength=null; this._everyVertexToPreVertexDistance=null; this._lastPosition=null; this._curPosition=null; this._delVector3=null; this._lastFixedVertexPosition=null; this._pointAtoBVector3=null; this._pointe=null; this._pointAtoBVector3e=null; this._pointA=null; this._pointB=null; } /** *获取vertexBuffer数量 *@return vertexBuffer数量 */ __getset(0,__proto,'_vertexBufferCount',function(){ return this._vertexBuffers.length; }); /** *获取三角面数量 *@return 三角面数量 */ __getset(0,__proto,'triangleCount',function(){ return 0; }); TrailRenderElement.renderElementCount=0; return TrailRenderElement; })() /** *VertexTrail 类用于创建拖尾顶点结构。 */ //class laya.d3.core.trail.VertexTrail var VertexTrail=(function(){ function VertexTrail(){} __class(VertexTrail,'laya.d3.core.trail.VertexTrail'); var __proto=VertexTrail.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'vertexDeclaration',function(){ return VertexTrail._vertexDeclaration1; }); __getset(1,VertexTrail,'vertexDeclaration1',function(){ return VertexTrail._vertexDeclaration1; }); __getset(1,VertexTrail,'vertexDeclaration2',function(){ return VertexTrail._vertexDeclaration2; }); __static(VertexTrail, ['_vertexDeclaration1',function(){return this._vertexDeclaration1=new VertexDeclaration(32, [new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.OFFSETVECTOR*/41), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Single*/"single",/*laya.d3.graphics.VertexElementUsage.TIME0*/33), new VertexElement(28,/*laya.d3.graphics.VertexElementFormat.Single*/"single",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0Y*/40)]);},'_vertexDeclaration2',function(){return this._vertexDeclaration2=new VertexDeclaration(4, [new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Single*/"single",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0X*/38)]);} ]); return VertexTrail; })() /** *... *@author */ //class laya.d3.extension.domino.DominoKeyFrame var DominoKeyFrame=(function(){ function DominoKeyFrame(){ this.position=Vector3.ZERO; this.rotation=Quaternion.DEFAULT; this.scale=new Vector3(0.3,0.6,0.1); } __class(DominoKeyFrame,'laya.d3.extension.domino.DominoKeyFrame'); return DominoKeyFrame; })() /** *... *@author */ //class laya.d3.extension.domino.DominoRenderElement var DominoRenderElement=(function(){ function DominoRenderElement(owner){ this._owner=null; this.id=0; this._curDominoCount=0; this._perDominoVertexCount=24; this._perDominoIndiceCount=36; this._vertexBuffers=null; this._vertices1=null; this._vertexBuffer1=null; this._floatCountPerVertices1=4; this._verticesIndex1=0; this._everyAddVerticeCount1=0; this._vertices2=null; this._vertexBuffer2=null; this._floatCountPerVertices2=6; this._verticesIndex2=0; this._everyAddVerticeCount2=0; this._everyUpdateVerticeCount2=0; this._indices=null; this._indexBuffer=null; this._indicesIndex=0; this._everyAddindiceCount=0; this._index=0; this._color=new Vector4(Math.random(),Math.random(),Math.random(),1); this._topColor=this._color; this._buttomColor=this._color; this._leftColor=this._color; this._rightColor=this._color; this._frontColor=this._color; this._backColor=this._color; this._localMatrix=new Matrix4x4(); this._localPostion=new Vector3(); this._localNormal=new Vector3(); this._owner=owner; this.id=DominoRenderElement.renderElementCount++; var _maxVertexCount=this._owner.DominoRenderElementMaxDominoCount *this._perDominoVertexCount; this._vertices1=new Float32Array(_maxVertexCount *this._floatCountPerVertices1); this._vertices2=new Float32Array(_maxVertexCount *this._floatCountPerVertices2); this._vertexBuffer1=new VertexBuffer3D(DominoVertex.vertexDeclaration1,_maxVertexCount,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._vertexBuffer2=new VertexBuffer3D(DominoVertex.vertexDeclaration2,_maxVertexCount,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._vertexBuffers=[]; this._vertexBuffers.push(this._vertexBuffer1); this._vertexBuffers.push(this._vertexBuffer2); var _maxIndiceCount=this._owner.DominoRenderElementMaxDominoCount *this._perDominoIndiceCount; this._indices=new Uint16Array(_maxIndiceCount); this._indexBuffer=new IndexBuffer3D(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",_maxIndiceCount,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); } __class(DominoRenderElement,'laya.d3.extension.domino.DominoRenderElement'); var __proto=DominoRenderElement.prototype; Laya.imps(__proto,{"laya.d3.core.render.IRenderable":true}) __proto.addDomino=function(position,rotation,scale){ (position===void 0)&& (position=Vector3.ZERO); (rotation===void 0)&& (rotation=Quaternion.DEFAULT); (scale===void 0)&& (scale=Vector3.ONE); this._curDominoCount++; this._owner.dominoCount++; this._owner.dominoPosition.push(position); this.addDataForVertexBuffer1(); this.addDataForVertexBuffer2(position,rotation,scale); this.addDataForIndexBuffer(); } __proto.updateDomino=function(index,position,rotation,scale){ (position===void 0)&& (position=Vector3.ZERO); (rotation===void 0)&& (rotation=Quaternion.DEFAULT); (scale===void 0)&& (scale=Vector3.ONE); this._everyUpdateVerticeCount2=0; var offset=this._perDominoVertexCount *this._floatCountPerVertices2 *index; var positions=DominoFilter._positions; var positione,positionX=NaN,positionY=NaN,positionZ=NaN; var normals=DominoFilter._normals; var normale,normalX=NaN,normalY=NaN,normalZ=NaN; var i=0,length=positions.length; Matrix4x4.createAffineTransformation(position,rotation,scale,this._localMatrix); for (i=0;i < length;i++){ Vector3.transformCoordinate(positions[i],this._localMatrix,this._localPostion); positione=this._localPostion.elements; positionX=positione[0]; positionY=positione[1]; positionZ=positione[2]; this._vertices2[offset+this._everyUpdateVerticeCount2++]=positionX; this._vertices2[offset+this._everyUpdateVerticeCount2++]=positionY; this._vertices2[offset+this._everyUpdateVerticeCount2++]=positionZ; Vector3.TransformNormal(normals[i],this._localMatrix,this._localNormal); normale=this._localNormal.elements; normalX=normale[0]; normalY=normale[1]; normalZ=normale[2]; this._vertices2[offset+this._everyUpdateVerticeCount2++]=normalX; this._vertices2[offset+this._everyUpdateVerticeCount2++]=normalY; this._vertices2[offset+this._everyUpdateVerticeCount2++]=normalZ; } this._vertexBuffer2.setData(this._vertices2,offset,offset,this._everyUpdateVerticeCount2); } __proto.updateDominos=function(startIndex,count,keyFrames){ this._everyUpdateVerticeCount2=0; var offset=this._perDominoVertexCount *this._floatCountPerVertices2 *startIndex; var positions=DominoFilter._positions; var positione,positionX=NaN,positionY=NaN,positionZ=NaN; var normals=DominoFilter._normals; var normale,normalX=NaN,normalY=NaN,normalZ=NaN; var i=0,j=0,length=positions.length; var keyFrame; for (i=0;i < count;i++){ keyFrame=keyFrames[i]; Matrix4x4.createAffineTransformation(keyFrame.position,keyFrame.rotation,keyFrame.scale,this._localMatrix); for (j=0;j < length;j++){ Vector3.transformCoordinate(positions[j],this._localMatrix,this._localPostion); positione=this._localPostion.elements; positionX=positione[0]; positionY=positione[1]; positionZ=positione[2]; this._vertices2[offset+this._everyUpdateVerticeCount2++]=positionX; this._vertices2[offset+this._everyUpdateVerticeCount2++]=positionY; this._vertices2[offset+this._everyUpdateVerticeCount2++]=positionZ; Vector3.TransformNormal(normals[j],this._localMatrix,this._localNormal); normale=this._localNormal.elements; normalX=normale[0]; normalY=normale[1]; normalZ=normale[2]; this._vertices2[offset+this._everyUpdateVerticeCount2++]=normalX; this._vertices2[offset+this._everyUpdateVerticeCount2++]=normalY; this._vertices2[offset+this._everyUpdateVerticeCount2++]=normalZ; } } this._vertexBuffer2.setData(this._vertices2,offset,offset,this._everyUpdateVerticeCount2); } __proto.addDataForVertexBuffer1=function(){ this._everyAddVerticeCount1=0; this.addDataForVertices1(this._topColor); this.addDataForVertices1(this._buttomColor); this.addDataForVertices1(this._leftColor); this.addDataForVertices1(this._rightColor); this.addDataForVertices1(this._frontColor); this.addDataForVertices1(this._backColor); this._vertexBuffer1.setData(this._vertices1,this._verticesIndex1,this._verticesIndex1,this._everyAddVerticeCount1); this._verticesIndex1+=this._everyAddVerticeCount1; } __proto.addDataForVertexBuffer2=function(position,rotation,scale){ (position===void 0)&& (position=Vector3.ZERO); (rotation===void 0)&& (rotation=Quaternion.DEFAULT); (scale===void 0)&& (scale=Vector3.ONE); this._everyAddVerticeCount2=0; var positions=DominoFilter._positions; var positione,positionX=NaN,positionY=NaN,positionZ=NaN; var normals=DominoFilter._normals; var normale,normalX=NaN,normalY=NaN,normalZ=NaN; var i=0,j=0,length=positions.length; Matrix4x4.createAffineTransformation(position,rotation,scale,this._localMatrix); for (i=0;i < length;i++){ Vector3.transformCoordinate(positions[i],this._localMatrix,this._localPostion); positione=this._localPostion.elements; positionX=positione[0]; positionY=positione[1]; positionZ=positione[2]; this._vertices2[this._verticesIndex2+this._everyAddVerticeCount2++]=positionX; this._vertices2[this._verticesIndex2+this._everyAddVerticeCount2++]=positionY; this._vertices2[this._verticesIndex2+this._everyAddVerticeCount2++]=positionZ; Vector3.TransformNormal(normals[i],this._localMatrix,this._localNormal); normale=this._localNormal.elements; normalX=normale[0]; normalY=normale[1]; normalZ=normale[2]; this._vertices2[this._verticesIndex2+this._everyAddVerticeCount2++]=normalX; this._vertices2[this._verticesIndex2+this._everyAddVerticeCount2++]=normalY; this._vertices2[this._verticesIndex2+this._everyAddVerticeCount2++]=normalZ; } this._vertexBuffer2.setData(this._vertices2,this._verticesIndex2,this._verticesIndex2,this._everyAddVerticeCount2); this._verticesIndex2+=this._everyAddVerticeCount2; } __proto.addDataForIndexBuffer=function(){ this._everyAddindiceCount=0; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+0; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+1; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+2; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+2; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+3; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+0; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+4; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+7; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+6; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+6; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+5; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+4; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+8; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+9; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+10; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+10; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+11; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+8; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+12; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+15; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+14; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+14; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+13; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+12; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+16; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+17; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+18; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+18; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+19; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+16; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+20; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+23; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+22; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+22; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+21; this._indices[this._indicesIndex+this._everyAddindiceCount++]=this._index+20; this._indexBuffer.setData(this._indices,this._indicesIndex,this._indicesIndex,this._everyAddindiceCount); this._indicesIndex+=this._everyAddindiceCount; this._index+=this._perDominoVertexCount; } __proto.addDataForVertices1=function(color){ var colore=color.elements; var colorX=colore[0]; var colorY=colore[1]; var colorZ=colore[2]; var colorW=colore[3]; for (var i=0;i < 4;i++){ this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=colorX; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=colorY; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=colorZ; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=colorW; } } __proto._beforeRender=function(state){ this._indexBuffer._bind(); return true; } __proto._render=function(state){ WebGL.mainContext.drawElements(/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,this._indicesIndex,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,0); Stat.drawCall++; Stat.trianglesFaces+=this._indicesIndex / 3; } __proto._getIndexBuffer=function(){ return this._indexBuffer; } __proto._getVertexBuffer=function(index){ (index===void 0)&& (index=0); if (index===0) return this._vertexBuffer1; else if (index===1) return this._vertexBuffer2; else return null; } __proto._getVertexBuffers=function(){ return this._vertexBuffers; } __proto._getIndexBuffer=function(){ return null; } __getset(0,__proto,'_vertexBufferCount',function(){ return this._vertexBuffers.length; }); __getset(0,__proto,'triangleCount',function(){ return this._indicesIndex / 3; }); DominoRenderElement.renderElementCount=0; return DominoRenderElement; })() /** *DominoVertex 类用于创建多米诺顶点结构。 */ //class laya.d3.extension.domino.DominoVertex var DominoVertex=(function(){ function DominoVertex(){} __class(DominoVertex,'laya.d3.extension.domino.DominoVertex'); var __proto=DominoVertex.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'vertexDeclaration',function(){ return DominoVertex._vertexDeclaration1; }); __getset(1,DominoVertex,'vertexDeclaration1',function(){ return DominoVertex._vertexDeclaration1; }); __getset(1,DominoVertex,'vertexDeclaration2',function(){ return DominoVertex._vertexDeclaration2; }); __static(DominoVertex, ['_vertexDeclaration1',function(){return this._vertexDeclaration1=new VertexDeclaration(16, [new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1)]);},'_vertexDeclaration2',function(){return this._vertexDeclaration2=new VertexDeclaration(24, [new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3)]);} ]); return DominoVertex; })() /** *... *@author */ //class laya.d3.extension.lineRender.LineVertex var LineVertex=(function(){ function LineVertex(){} __class(LineVertex,'laya.d3.extension.lineRender.LineVertex'); var __proto=LineVertex.prototype; __getset(0,__proto,'vertexDeclaration',function(){ return LineVertex._vertexDeclaration1; }); __getset(1,LineVertex,'vertexDeclaration1',function(){ return LineVertex._vertexDeclaration1; }); __getset(1,LineVertex,'vertexDeclaration2',function(){ return LineVertex._vertexDeclaration2; }); __getset(1,LineVertex,'vertexDeclaration3',function(){ return LineVertex._vertexDeclaration3; }); __static(LineVertex, ['_vertexDeclaration1',function(){return this._vertexDeclaration1=new VertexDeclaration(16, [new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Single*/"single",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0Y*/40)]);},'_vertexDeclaration2',function(){return this._vertexDeclaration2=new VertexDeclaration(12, [new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.OFFSETVECTOR*/41)]);},'_vertexDeclaration3',function(){return this._vertexDeclaration3=new VertexDeclaration(8, [new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Single*/"single",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0X*/38), new VertexElement(4,/*laya.d3.graphics.VertexElementFormat.Single*/"single",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0X1*/39)]);} ]); return LineVertex; })() /** *@private *DynamicBatch 类用于动态批处理。 */ //class laya.d3.graphics.DynamicBatch var DynamicBatch=(function(){ function DynamicBatch(vertexDeclaration){ this._vertexDeclaration=null; this._vertexDatas=null; this._indexDatas=null; this._vertexBuffer=null; this._indexBuffer=null; this._currentCombineVertexCount=0; this._currentCombineIndexCount=0; this._combineRenderElements=null; this._materials=null; this._materialToRenderElementsOffsets=null; this._merageElements=null; this._combineRenderElementPool=null; this._combineRenderElementPoolIndex=0; this._currentCombineVertexCount=0; this._currentCombineIndexCount=0; this._combineRenderElements=[]; this._materialToRenderElementsOffsets=[]; this._materials=[]; this._merageElements=[]; this._combineRenderElementPool=[]; this._combineRenderElementPoolIndex=0; this._vertexDeclaration=vertexDeclaration; } __class(DynamicBatch,'laya.d3.graphics.DynamicBatch'); var __proto=DynamicBatch.prototype; Laya.imps(__proto,{"laya.d3.core.render.IRenderable":true}) __proto._getVertexBuffer=function(index){ (index===void 0)&& (index=0); if (index===0) return this._vertexBuffer; else return null; } __proto._getIndexBuffer=function(){ return this._indexBuffer; } __proto._getCombineRenderElementFromPool=function(view,projection,projectionView){ var renderElement=this._combineRenderElementPool[this._combineRenderElementPoolIndex++]; if (!renderElement){ this._combineRenderElementPool[this._combineRenderElementPoolIndex-1]=renderElement=new RenderElement(); renderElement._sprite3D=new MeshSprite3D(); } renderElement._sprite3D._render._renderUpdate(projectionView); return renderElement; } __proto._getRenderElement=function(view,projection,projectionView){ if (!this._vertexDatas){ this._vertexDatas=new Float32Array(this._vertexDeclaration.vertexStride / 4 *DynamicBatch.maxVertexCount); this._indexDatas=new Uint16Array(DynamicBatch.maxIndexCount); this._vertexBuffer=VertexBuffer3D.create(this._vertexDeclaration,DynamicBatch.maxVertexCount,/*laya.webgl.WebGLContext.DYNAMIC_DRAW*/0x88E8); this._indexBuffer=IndexBuffer3D.create(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",DynamicBatch.maxIndexCount,/*laya.webgl.WebGLContext.DYNAMIC_DRAW*/0x88E8); } this._merageElements.length=0; var curMerVerCount=0; var curIndexCount=0; for (var i=0,n=this._combineRenderElements.length;i < n;i++){ var renderElement=this._combineRenderElements[i]; var subVertexDatas=renderElement.getDynamicBatchBakedVertexs(0); var subIndexDatas=renderElement.getBakedIndices(); var isInvert=renderElement._sprite3D.transform._isFrontFaceInvert; var indexOffset=curMerVerCount / (this._vertexDeclaration.vertexStride / 4); var indexStart=curIndexCount; var indexEnd=indexStart+subIndexDatas.length; renderElement._tempBatchIndexStart=indexStart; renderElement._tempBatchIndexEnd=indexEnd; this._indexDatas.set(subIndexDatas,curIndexCount); var k=0; if (isInvert){ for (k=indexStart;k < indexEnd;k+=3){ this._indexDatas[k]=indexOffset+this._indexDatas[k]; var index1=this._indexDatas[k+1]; var index2=this._indexDatas[k+2]; this._indexDatas[k+1]=indexOffset+index2; this._indexDatas[k+2]=indexOffset+index1; } }else { for (k=indexStart;k < indexEnd;k+=3){ this._indexDatas[k]=indexOffset+this._indexDatas[k]; this._indexDatas[k+1]=indexOffset+this._indexDatas[k+1]; this._indexDatas[k+2]=indexOffset+this._indexDatas[k+2]; } } curIndexCount+=subIndexDatas.length; this._vertexDatas.set(subVertexDatas,curMerVerCount); curMerVerCount+=subVertexDatas.length; } this._vertexBuffer.setData(this._vertexDatas); this._indexBuffer.setData(this._indexDatas); this._combineRenderElementPoolIndex=0; for (i=0,n=this._materials.length;i < n;i++){ var merageElement=this._getCombineRenderElementFromPool(view,projection,projectionView); merageElement._type=2; merageElement._staticBatch=null; merageElement.renderObj=this; var renderElementStartIndex=this._combineRenderElements[this._materialToRenderElementsOffsets[i]]._tempBatchIndexStart; var renderElementEndIndex=(i+1===this._materialToRenderElementsOffsets.length)? curIndexCount :this._combineRenderElements[this._materialToRenderElementsOffsets[i+1]]._tempBatchIndexStart; merageElement._tempBatchIndexStart=renderElementStartIndex; merageElement._tempBatchIndexEnd=renderElementEndIndex; merageElement._material=this._materials[i]; this._merageElements.push(merageElement); } } __proto._addCombineRenderObjTest=function(renderElement){ var renderObj=renderElement.renderObj; var indexCount=this._currentCombineIndexCount+renderObj._getIndexBuffer().indexCount; var vertexCount=this._currentCombineVertexCount+renderObj._getVertexBuffer().vertexCount; if (vertexCount > DynamicBatch.maxVertexCount || indexCount > DynamicBatch.maxIndexCount){ return false; } return true; } __proto._addCombineRenderObj=function(renderElement){ var renderObj=renderElement.renderObj; this._combineRenderElements.push(renderElement); this._currentCombineIndexCount=this._currentCombineIndexCount+renderObj._getIndexBuffer().indexCount; this._currentCombineVertexCount=this._currentCombineVertexCount+renderObj._getVertexBuffer().vertexCount; } __proto._addCombineMaterial=function(material){ this._materials.push(material); } __proto._addMaterialToRenderElementOffset=function(offset){ this._materialToRenderElementsOffsets.push(offset); } __proto._clearRenderElements=function(){ this._combineRenderElements.length=0; this._materials.length=0; this._materialToRenderElementsOffsets.length=0; this._currentCombineVertexCount=0; this._currentCombineIndexCount=0; } __proto._addToRenderQueue=function(scene,view,projection,projectionView){ this._getRenderElement(view,projection,projectionView); for (var i=0,n=this._materials.length;i < n;i++) scene.getRenderQueue(this._materials[i].renderQueue)._addDynamicBatchElement(this._merageElements[i]); } __proto._beforeRender=function(state){ this._vertexBuffer._bind(); this._indexBuffer._bind(); return true; } __proto._render=function(state){ var indexCount=state._batchIndexEnd-state._batchIndexStart; WebGL.mainContext.drawElements(/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,indexCount,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,state._batchIndexStart *2); Stat.drawCall++; Stat.trianglesFaces+=indexCount / 3; } /** *@private */ __proto._getVertexBuffers=function(){ return null; } __getset(0,__proto,'_vertexBufferCount',function(){ return 1; }); __getset(0,__proto,'triangleCount',function(){ return this._indexBuffer.indexCount / 3; }); __getset(0,__proto,'combineRenderElementsCount',function(){ return this._combineRenderElements.length; }); DynamicBatch.maxVertexCount=20000; DynamicBatch.maxIndexCount=40000; DynamicBatch.maxCombineTriangleCount=10; return DynamicBatch; })() /** *@private *DynamicBatchManager 类用于管理动态批处理。 */ //class laya.d3.graphics.DynamicBatchManager var DynamicBatchManager=(function(){ function DynamicBatchManager(){ this._dynamicBatches=null; this._prepareDynamicBatchCombineElements=null; this._dynamicBatches={}; this._prepareDynamicBatchCombineElements=[]; } __class(DynamicBatchManager,'laya.d3.graphics.DynamicBatchManager'); var __proto=DynamicBatchManager.prototype; __proto.getDynamicBatch=function(_vertexDeclaration,number){ var dynamicBatch; var key=_vertexDeclaration.id.toString()+number; if (!this._dynamicBatches[key]){ this._dynamicBatches[key]=dynamicBatch=new DynamicBatch(_vertexDeclaration); }else { dynamicBatch=this._dynamicBatches[key]; } return dynamicBatch; } /**需手动调用*/ __proto._garbageCollection=function(){ for (var key in this._dynamicBatches) if (this._dynamicBatches[key].combineRenderElementsCount===0) delete this._dynamicBatches[key]; } __proto._addPrepareRenderElement=function(renderElement){ this._prepareDynamicBatchCombineElements.push(renderElement); } /**@private */ __proto._finishCombineDynamicBatch=function(scene){ this._prepareDynamicBatchCombineElements.sort(DynamicBatchManager._sortPrepareDynamicBatch); var lastMaterial; var lastVertexDeclaration; var lastRenderElement; var lastBatchNumber=-1; var lastCanMerage=true; var curMaterial; var curRenderElement; var curDynamicBatch; var curbatchNumber=0; var laterAddMaterial; var laterAddRenderElement; var laterAddMatToElementOffset=-1; for (var i=0,n=this._prepareDynamicBatchCombineElements.length;i < n;i++){ curRenderElement=this._prepareDynamicBatchCombineElements[i]; var curDeclaration=curRenderElement.renderObj._getVertexBuffer(0).vertexDeclaration; var declarationChanged=(lastVertexDeclaration!==curDeclaration); declarationChanged && (curbatchNumber=0,lastVertexDeclaration=curDeclaration); var batchNumbrChanged=(curbatchNumber!==lastBatchNumber); batchNumbrChanged && (lastBatchNumber=curbatchNumber); if ((declarationChanged)|| batchNumbrChanged){ curDynamicBatch=this.getDynamicBatch(curDeclaration,curbatchNumber); lastMaterial=null; } if (lastCanMerage){ if (curDynamicBatch._addCombineRenderObjTest(curRenderElement)){ curMaterial=curRenderElement._material; if (lastMaterial!==curMaterial){ if (laterAddMaterial){ scene.getRenderQueue(laterAddRenderElement._material.renderQueue)._addRenderElement(laterAddRenderElement); laterAddMaterial=null; laterAddRenderElement=null; laterAddMatToElementOffset=-1; } laterAddMaterial=curMaterial; laterAddMatToElementOffset=curDynamicBatch.combineRenderElementsCount; laterAddRenderElement=curRenderElement; lastMaterial=curMaterial; }else { if (laterAddMaterial){ var lastRenderObj=laterAddRenderElement.renderObj; var curRenderObj=curRenderElement.renderObj; if (((lastRenderObj._getVertexBuffer().vertexCount+curRenderObj._getVertexBuffer().vertexCount)> DynamicBatch.maxVertexCount)|| ((lastRenderObj._getIndexBuffer().indexCount+curRenderObj._getIndexBuffer().indexCount)> DynamicBatch.maxIndexCount)){ scene.getRenderQueue(laterAddRenderElement._material.renderQueue)._addRenderElement(laterAddRenderElement); laterAddMaterial=curMaterial; laterAddMatToElementOffset=curDynamicBatch.combineRenderElementsCount; laterAddRenderElement=curRenderElement; }else { curDynamicBatch._addCombineMaterial(laterAddMaterial); curDynamicBatch._addMaterialToRenderElementOffset(laterAddMatToElementOffset); curDynamicBatch._addCombineRenderObj(laterAddRenderElement); laterAddMaterial=null; laterAddRenderElement=null; laterAddMatToElementOffset=-1; curDynamicBatch._addCombineRenderObj(curRenderElement); } }else { curDynamicBatch._addCombineRenderObj(curRenderElement); } } lastCanMerage=true; }else { if (laterAddMaterial){ scene.getRenderQueue(laterAddRenderElement._material.renderQueue)._addRenderElement(laterAddRenderElement); laterAddMaterial=null; laterAddRenderElement=null; laterAddMatToElementOffset=-1; } curbatchNumber++; lastCanMerage=false; } }else { lastRenderElement=this._prepareDynamicBatchCombineElements[i-1]; curDynamicBatch._addMaterialToRenderElementOffset(curDynamicBatch.combineRenderElementsCount); lastMaterial=lastRenderElement._material; curDynamicBatch._addCombineMaterial(lastMaterial); curDynamicBatch._addCombineRenderObj(lastRenderElement); lastCanMerage=true; curMaterial=curRenderElement._material; if (lastMaterial!==curMaterial){ laterAddMaterial=curMaterial; laterAddMatToElementOffset=curDynamicBatch.combineRenderElementsCount; laterAddRenderElement=curRenderElement; }else { curDynamicBatch._addCombineRenderObj(curRenderElement); } lastMaterial=curMaterial; } } if (laterAddMaterial){ scene.getRenderQueue(laterAddRenderElement._material.renderQueue)._addRenderElement(laterAddRenderElement); laterAddMaterial=null; laterAddRenderElement=null; laterAddMatToElementOffset=-1; } this._prepareDynamicBatchCombineElements.length=0; } __proto._clearRenderElements=function(){ for (var key in this._dynamicBatches) this._dynamicBatches[key]._clearRenderElements(); } __proto._addToRenderQueue=function(scene,view,projection,projectionView){ for (var key in this._dynamicBatches){ var dynamicBatch=this._dynamicBatches[key]; (dynamicBatch.combineRenderElementsCount > 0)&& (dynamicBatch._addToRenderQueue(scene,view,projection,projectionView)); } } __proto.dispose=function(){ this._dynamicBatches=null; } DynamicBatchManager._sortPrepareDynamicBatch=function(a,b){ return a._mainSortID-b._mainSortID; } return DynamicBatchManager; })() /** *@private */ //class laya.d3.graphics.FrustumCulling var FrustumCulling=(function(){ function FrustumCulling(){} __class(FrustumCulling,'laya.d3.graphics.FrustumCulling'); FrustumCulling.renderShadowObjectCulling=function(scene,lightFrustum,shadowQueues,lightViewProjectMatrix,nPSSMNum){ var i=0,j=0,n=0,m=0; for (i=0,n=shadowQueues.length;i < n;i++){ var quene=shadowQueues[i]; (quene)&& (quene._clearRenderElements()); }; var frustumCullingObjects=scene._cullingRenders; var baseRender,shadowQueue,renderElements; if (nPSSMNum > 1){ for (i=0,n=scene._cullingRendersLength;i < n;i++){ baseRender=frustumCullingObjects[i]; if (baseRender.castShadow && Layer.isVisible(baseRender._owner.layer.mask)&& baseRender.enable){ for (var k=1,kNum=lightFrustum.length;k < kNum;k++){ shadowQueue=shadowQueues[k-1]; if (lightFrustum[k].containsBoundSphere(baseRender.boundingSphere)!==/*laya.d3.math.ContainmentType.Disjoint*/0){ renderElements=baseRender._renderElements; for (j=0,m=renderElements.length;j < m;j++) shadowQueue._addRenderElement(renderElements[j]); } } } } }else { for (i=0,n=scene._cullingRendersLength;i < n;i++){ baseRender=frustumCullingObjects[i]; if (baseRender.castShadow && Layer.isVisible(baseRender._owner.layer.mask)&& baseRender.enable){ if (lightFrustum[0].containsBoundSphere(baseRender.boundingSphere)!==/*laya.d3.math.ContainmentType.Disjoint*/0){ baseRender._renderUpdate(lightViewProjectMatrix); shadowQueue=shadowQueues[0]; renderElements=baseRender._renderElements; for (j=0,m=renderElements.length;j < m;j++) shadowQueue._addRenderElement(renderElements[j]); } } } } } FrustumCulling.renderShadowObjectCullingOctree=function(scene,lightFrustum,quenesResult,lightViewProjectMatrix,nPSSMNum){ for (var i=0,n=quenesResult.length;i < n;i++){ var quene=quenesResult[i]; (quene)&& (quene._clearRenderElements()); } if (nPSSMNum > 1){ scene.treeRoot.cullingShadowObjects(lightFrustum,quenesResult,true,0,scene); }else { scene.treeRoot.cullingShadowObjectsOnePSSM(lightFrustum[0],quenesResult,lightViewProjectMatrix,true,0,scene); } } FrustumCulling.renderObjectCulling=function(boundFrustum,scene,camera,view,projection,projectionView){ var i=0,n=0,j=0,m=0; var queues=scene._quenes; var dynamicBatchManager=scene._dynamicBatchManager; var frustumCullingObjects=scene._cullingRenders; for (i=0,n=queues.length;i < n;i++){ var queue=queues[i]; (queue)&& (queue._clearRenderElements()); }; var staticBatchManagers=StaticBatchManager._staticBatchManagers; for (i=0,n=staticBatchManagers.length;i < n;i++) staticBatchManagers[i]._clearRenderElements(); dynamicBatchManager._clearRenderElements(); var cameraPosition=camera.transform.position; for (i=0,n=scene._cullingRendersLength;i < n;i++){ var baseRender=frustumCullingObjects[i]; if (Layer.isVisible(baseRender._owner.layer.mask)&& baseRender.enable && (boundFrustum.containsBoundSphere(baseRender.boundingSphere)!==/*laya.d3.math.ContainmentType.Disjoint*/0)){ if (baseRender._renderUpdate(projectionView)){ baseRender._distanceForSort=Vector3.distance(baseRender.boundingSphere.center,cameraPosition)+baseRender.sortingFudge; var renderElements=baseRender._renderElements; for (j=0,m=renderElements.length;j < m;j++){ var renderElement=renderElements[j]; var staticBatch=renderElement._staticBatch; if (staticBatch && (staticBatch._material===renderElement._material)){ staticBatch._addBatchRenderElement(renderElement); }else { var renderObj=renderElement.renderObj; if ((renderObj.triangleCount < /*laya.d3.graphics.DynamicBatch.maxCombineTriangleCount*/10)&& (renderObj._vertexBufferCount===1)&& (renderObj._getIndexBuffer())&& (renderElement._material.renderQueue < 2)&& renderElement._canDynamicBatch && (!baseRender._owner.isStatic)) dynamicBatchManager._addPrepareRenderElement(renderElement); else scene.getRenderQueue(renderElement._material.renderQueue)._addRenderElement(renderElement); } } } } } for (i=0,n=staticBatchManagers.length;i < n;i++) staticBatchManagers[i]._addToRenderQueue(scene,view,projection,projectionView); dynamicBatchManager._finishCombineDynamicBatch(scene); dynamicBatchManager._addToRenderQueue(scene,view,projection,projectionView); } FrustumCulling.renderObjectCullingOctree=function(boundFrustum,scene,camera,view,projection,projectionView){ var i=0,n=0; var queues=scene._quenes; var dynamicBatchManager=scene._dynamicBatchManager; for (i=0,n=queues.length;i < n;i++){ var queue=queues[i]; (queue)&& (queue._clearRenderElements()); }; var staticBatchManagers=StaticBatchManager._staticBatchManagers; for (i=0,n=staticBatchManagers.length;i < n;i++) staticBatchManagers[i]._clearRenderElements(); dynamicBatchManager._clearRenderElements(); scene._cullingRenders.length=0; scene.treeRoot.cullingObjects(boundFrustum,true,0,camera.transform.position,projectionView); for (i=0,n=staticBatchManagers.length;i < n;i++) staticBatchManagers[i]._addToRenderQueue(scene,view,projection,projectionView); dynamicBatchManager._finishCombineDynamicBatch(scene); dynamicBatchManager._addToRenderQueue(scene,view,projection,projectionView); } FrustumCulling.renderObjectCullingNoBoundFrustum=function(scene,camera,view,projection,projectionView){ var i=0,n=0,j=0,m=0; var queues=scene._quenes; var dynamicBatchManager=scene._dynamicBatchManager; var frustumCullingObjects=scene._cullingRenders; for (i=0,n=queues.length;i < n;i++){ var queue=queues[i]; (queue)&& (queue._clearRenderElements()); }; var staticBatchManagers=StaticBatchManager._staticBatchManagers; for (i=0,n=staticBatchManagers.length;i < n;i++) staticBatchManagers[i]._clearRenderElements(); dynamicBatchManager._clearRenderElements(); var cameraPosition=camera.transform.position; for (i=0,n=scene._cullingRendersLength;i < n;i++){ var baseRender=frustumCullingObjects[i]; if (Layer.isVisible(baseRender._owner.layer.mask)&& baseRender.enable){ baseRender._renderUpdate(projectionView); baseRender._distanceForSort=Vector3.distance(baseRender.boundingSphere.center,cameraPosition)+baseRender.sortingFudge; var renderElements=baseRender._renderElements; for (j=0,m=renderElements.length;j < m;j++){ var renderElement=renderElements[j]; var staticBatch=renderElement._staticBatch; if (staticBatch && (staticBatch._material===renderElement._material)){ staticBatch._addBatchRenderElement(renderElement); }else { var renderObj=renderElement.renderObj; if ((renderObj.triangleCount < /*laya.d3.graphics.DynamicBatch.maxCombineTriangleCount*/10)&& (renderObj._vertexBufferCount===1)&& (renderObj._getIndexBuffer())&& (renderElement._material.renderQueue < 2)&& renderElement._canDynamicBatch && (!baseRender._owner.isStatic)) dynamicBatchManager._addPrepareRenderElement(renderElement); else scene.getRenderQueue(renderElement._material.renderQueue)._addRenderElement(renderElement); } } } } for (i=0,n=staticBatchManagers.length;i < n;i++) staticBatchManagers[i]._addToRenderQueue(scene,view,projection,projectionView); dynamicBatchManager._finishCombineDynamicBatch(scene); dynamicBatchManager._addToRenderQueue(scene,view,projection,projectionView); } return FrustumCulling; })() /** *@private *StaticBatchManager 类用于静态批处理管理的父类。 */ //class laya.d3.graphics.StaticBatchManager var StaticBatchManager=(function(){ function StaticBatchManager(){ /**@private */ this._initBatchRenderElements=null; /**@private */ this._staticBatches=null; this._initBatchRenderElements=[]; this._staticBatches={}; } __class(StaticBatchManager,'laya.d3.graphics.StaticBatchManager'); var __proto=StaticBatchManager.prototype; /** *@private */ __proto._finishInit=function(){ for (var key in this._staticBatches) this._staticBatches[key]._finishInit(); this._initBatchRenderElements.length=0; } /** *@private */ __proto._initStaticBatchs=function(rootSprite){ throw new Error("StaticBatchManager:must override this function."); } /** *@private */ __proto._addInitBatchSprite=function(renderableSprite3D){ var renderElements=renderableSprite3D._render._renderElements; for (var i=0,n=renderElements.length;i < n;i++) this._initBatchRenderElements.push(renderElements[i]); } /** *@private */ __proto._clearRenderElements=function(){ for (var key in this._staticBatches) this._staticBatches[key]._clearRenderElements(); } /** *@private */ __proto._garbageCollection=function(renderElement){ var staticBatch=renderElement._staticBatch; var initBatchRenderElements=staticBatch._initBatchRenderElements; var index=initBatchRenderElements.indexOf(renderElement); initBatchRenderElements.splice(index,1); if (initBatchRenderElements.length===0){ staticBatch.dispose(); delete this._staticBatches[staticBatch._key]; } } /** *@private */ __proto._addToRenderQueue=function(scene,view,projection,projectionView){ for (var key in this._staticBatches){ var staticBatch=this._staticBatches[key]; if (staticBatch._batchRenderElements.length > 0) staticBatch._updateToRenderQueue(scene,projectionView); } } __proto.dispose=function(){ this._staticBatches=null; } StaticBatchManager._addToStaticBatchQueue=function(sprite3D){ if ((sprite3D instanceof laya.d3.core.RenderableSprite3D )) (sprite3D)._addToInitStaticBatchManager(); for (var i=0,n=sprite3D.numChildren;i < n;i++) StaticBatchManager._addToStaticBatchQueue(sprite3D._childs [i]); } StaticBatchManager.combine=function(staticBatchRoot,renderableSprite3Ds){ var i=0,n=0,staticBatchManager; if (renderableSprite3Ds){ for (i=0,n=renderableSprite3Ds.length;i < n;i++){ var renderableSprite3D=renderableSprite3Ds[i]; renderableSprite3D._addToInitStaticBatchManager(); } }else { if (staticBatchRoot) StaticBatchManager._addToStaticBatchQueue(staticBatchRoot); } for (i=0,n=StaticBatchManager._staticBatchManagers.length;i < n;i++){ staticBatchManager=StaticBatchManager._staticBatchManagers[i]; staticBatchManager._initStaticBatchs(staticBatchRoot); staticBatchManager._finishInit(); } } StaticBatchManager._staticBatchManagers=[]; return StaticBatchManager; })() /** *StaticBatch 类用于静态合并的父类,该类为抽象类。 */ //class laya.d3.graphics.StaticBatch var StaticBatch=(function(){ function StaticBatch(key,manager,rootOwner){ /**@private */ this._combineRenderElementPoolIndex=0; /**@private */ this._combineRenderElementPool=null; /**@private */ this._initBatchRenderElements=null; /**@private */ this._batchRenderElements=null; /**@private */ this._material=null; /**@private */ this._rootOwner=null; /**@private */ this._key=null; /**@private */ this._manager=null; this._key=key; this._manager=manager; this._combineRenderElementPoolIndex=0; this._combineRenderElementPool=[]; this._initBatchRenderElements=[]; this._batchRenderElements=[]; this._rootOwner=rootOwner; } __class(StaticBatch,'laya.d3.graphics.StaticBatch'); var __proto=StaticBatch.prototype; Laya.imps(__proto,{"laya.d3.core.render.IRenderable":true,"laya.resource.IDispose":true}) /** *@private */ __proto._binarySearch=function(renderElement){ var start=0; var end=this._batchRenderElements.length-1; var mid=0; while (start <=end){ mid=Math.floor((start+end)/ 2); if (this._compareBatchRenderElement(this._batchRenderElements[mid],renderElement)) end=mid-1; else start=mid+1; } return start; } /** *@private */ __proto._compareBatchRenderElement=function(a,b){ throw new Error("StaticBatch:must override this function."); } /** *@private */ __proto._getVertexDecLightMap=function(vertexDeclaration){ if (vertexDeclaration===VertexPositionNormalTextureSkinSTangent.vertexDeclaration){ return VertexPositionNormalTexture0Texture1SkinSTangent.vertexDeclaration; }else if (vertexDeclaration===VertexPositionNormalTextureSkin.vertexDeclaration){ return VertexPositionNormalTexture0Texture1Skin.vertexDeclaration; }else if (vertexDeclaration===VertexPositionNormalColorTextureSTangent.vertexDeclaration){ return VertexPositionNormalColorTexture0Texture1STangent.vertexDeclaration; }else if (vertexDeclaration===VertexPositionNTBTexture.vertexDeclaration){ return null; }else if (vertexDeclaration===VertexPositionNormalColorTexture.vertexDeclaration){ return VertexPositionNormalColorTexture0Texture1.vertexDeclaration; }else if (vertexDeclaration===VertexPositionNormalTextureSTangent.vertexDeclaration){ return VertexPositionNormalTexture0Texture1STangent.vertexDeclaration; }else if (vertexDeclaration===VertexPositionNormalTexture.vertexDeclaration){ return VertexPositionNormalTexture0Texture1.vertexDeclaration; } if (vertexDeclaration===VertexPositionNormalTextureSkinTangent.vertexDeclaration){ return VertexPositionNormalTexture0Texture1SkinTangent.vertexDeclaration; }else if (vertexDeclaration===VertexPositionNormalTextureSkin.vertexDeclaration){ return VertexPositionNormalTexture0Texture1Skin.vertexDeclaration; }else if (vertexDeclaration===VertexPositionNormalColorTextureTangent.vertexDeclaration){ return VertexPositionNormalColorTexture0Texture1Tangent.vertexDeclaration; }else if (vertexDeclaration===VertexPositionNTBTexture.vertexDeclaration){ return null; }else if (vertexDeclaration===VertexPositionNormalColorTexture.vertexDeclaration){ return VertexPositionNormalColorTexture0Texture1.vertexDeclaration; }else if (vertexDeclaration===VertexPositionNormalTextureTangent.vertexDeclaration){ return VertexPositionNormalTexture0Texture1Tangent.vertexDeclaration; }else if (vertexDeclaration===VertexPositionNormalTexture.vertexDeclaration){ return VertexPositionNormalTexture0Texture1.vertexDeclaration; }else { return vertexDeclaration; } } /** *@private */ __proto._getCombineRenderElementFromPool=function(){ throw new Error("StaticBatch:must override this function."); } /** *@private */ __proto._addBatchRenderElement=function(renderElement){ this._batchRenderElements.splice(this._binarySearch(renderElement),0,renderElement); } /** *@private */ __proto._updateToRenderQueue=function(scene,projectionView){ this._combineRenderElementPoolIndex=0; this._getRenderElement(scene.getRenderQueue(this._material.renderQueue)._renderElements,scene,projectionView); } /** *@private */ __proto._getRenderElement=function(mergeElements,scene,projectionView){ throw new Error("StaticBatch:must override this function."); } /** *@private */ __proto._finishInit=function(){ throw new Error("StaticBatch:must override this function."); } /** *@private */ __proto._clearRenderElements=function(){ this._batchRenderElements.length=0; } /** *@private */ __proto.dispose=function(){} //..................临时................................. __proto._getVertexBuffer=function(index){ (index===void 0)&& (index=0); return null; } __proto._getIndexBuffer=function(){ return null; } __proto._beforeRender=function(state){ return true; } __proto._render=function(state){} /** *@private */ __proto._getVertexBuffers=function(){ return null; } //..................临时................................. __getset(0,__proto,'_vertexBufferCount',function(){ return 1; }); __getset(0,__proto,'triangleCount',function(){ return 0; }); StaticBatch.combine=function(staticBatchRoot){ console.log("StaticBatch: discard property,please use StaticBatchManager.combine() function instead."); StaticBatchManager.combine(staticBatchRoot); } StaticBatch.maxBatchVertexCount=65535; return StaticBatch; })() /** *... *@author ... */ //class laya.d3.graphics.VertexDeclaration var VertexDeclaration=(function(){ function VertexDeclaration(vertexStride,vertexElements){ this._id=0; this._shaderValues=null; this._shaderDefineValue=0; //private var _shaderAttribute:*; this._vertexStride=0; this._vertexElements=null; this._vertexElementsDic=null; this._id=++VertexDeclaration._uniqueIDCounter; if (this._id > VertexDeclaration.maxVertexDeclaration) throw new Error("VertexDeclaration: VertexDeclaration count should not large than ",VertexDeclaration.maxVertexDeclaration); this._shaderValues=new ValusArray(); this._vertexElementsDic={}; this._vertexStride=vertexStride; this._vertexElements=vertexElements; for (var i=0;i < vertexElements.length;i++){ var vertexElement=vertexElements[i]; var attributeName=vertexElement.elementUsage; this._vertexElementsDic[attributeName]=vertexElement; var value=[VertexDeclaration._getTypeSize(vertexElement.elementFormat)/ 4,/*laya.webgl.WebGLContext.FLOAT*/0x1406,false,this._vertexStride,vertexElement.offset]; this._shaderValues.setValue(attributeName,value); switch (attributeName){ case /*laya.d3.graphics.VertexElementUsage.COLOR0*/1: this._addShaderDefine(ShaderCompile3D.SHADERDEFINE_COLOR); break case /*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2: this._addShaderDefine(ShaderCompile3D.SHADERDEFINE_UV0); break ; case /*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE1*/15: this._addShaderDefine(ShaderCompile3D.SHADERDEFINE_UV1); break ; } } } __class(VertexDeclaration,'laya.d3.graphics.VertexDeclaration'); var __proto=VertexDeclaration.prototype; /** *增加Shader宏定义。 *@param value 宏定义。 */ __proto._addShaderDefine=function(value){ this._shaderDefineValue |=value; } /** *移除Shader宏定义。 *@param value 宏定义。 */ __proto._removeShaderDefine=function(value){ this._shaderDefineValue &=~value; } __proto.getVertexElements=function(){ return this._vertexElements.slice(); } __proto.getVertexElementByUsage=function(usage){ return this._vertexElementsDic[usage]; } __proto.unBinding=function(){} __getset(0,__proto,'shaderDefineValue',function(){ return this._shaderDefineValue; }); /** *获取唯一标识ID(通常用于优化或识别)。 *@return 唯一标识ID */ __getset(0,__proto,'id',function(){ return this._id; }); __getset(0,__proto,'vertexStride',function(){ return this._vertexStride; }); __getset(0,__proto,'shaderValues',function(){ return this._shaderValues; }); VertexDeclaration._getTypeSize=function(format){ switch (format){ case /*laya.d3.graphics.VertexElementFormat.Single*/"single": return 4; case /*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2": return 8; case /*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3": return 12; case /*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4": return 16; case /*laya.d3.graphics.VertexElementFormat.Color*/"color": return 4; case /*laya.d3.graphics.VertexElementFormat.Byte4*/"byte4": return 4; case /*laya.d3.graphics.VertexElementFormat.Short2*/"short2": return 4; case /*laya.d3.graphics.VertexElementFormat.Short4*/"short4": return 8; case /*laya.d3.graphics.VertexElementFormat.NormalizedShort2*/"normalizedshort2": return 4; case /*laya.d3.graphics.VertexElementFormat.NormalizedShort4*/"normalizedshort4": return 8; case /*laya.d3.graphics.VertexElementFormat.HalfVector2*/"halfvector2": return 4; case /*laya.d3.graphics.VertexElementFormat.HalfVector4*/"halfvector4": return 8; } return 0; } VertexDeclaration.getVertexStride=function(vertexElements){ var curStride=0; for (var i=0;i < vertexElements.Length;i++){ var element=vertexElements[i]; var stride=element.offset+VertexDeclaration._getTypeSize(element.elementFormat); if (curStride < stride){ curStride=stride; } } return curStride; } VertexDeclaration._maxVertexDeclarationBit=1000; VertexDeclaration._uniqueIDCounter=1; __static(VertexDeclaration, ['maxVertexDeclaration',function(){return this.maxVertexDeclaration=2147483647-Math.floor(2147483647 / 1000)*1000;} ]); return VertexDeclaration; })() /** *VertexElement 类用于创建顶点结构分配。 */ //class laya.d3.graphics.VertexElement var VertexElement=(function(){ function VertexElement(offset,elementFormat,elementUsage){ this.offset=0; this.elementFormat=null; this.elementUsage=0; this.offset=offset; this.elementFormat=elementFormat; this.elementUsage=elementUsage; } __class(VertexElement,'laya.d3.graphics.VertexElement'); return VertexElement; })() /** *... *@author ... */ //class laya.d3.graphics.VertexElementFormat var VertexElementFormat=(function(){ function VertexElementFormat(){} __class(VertexElementFormat,'laya.d3.graphics.VertexElementFormat'); VertexElementFormat.Single="single"; VertexElementFormat.Vector2="vector2"; VertexElementFormat.Vector3="vector3"; VertexElementFormat.Vector4="vector4"; VertexElementFormat.Color="color"; VertexElementFormat.Byte4="byte4"; VertexElementFormat.Short2="short2"; VertexElementFormat.Short4="short4"; VertexElementFormat.NormalizedShort2="normalizedshort2"; VertexElementFormat.NormalizedShort4="normalizedshort4"; VertexElementFormat.HalfVector2="halfvector2"; VertexElementFormat.HalfVector4="halfvector4"; return VertexElementFormat; })() /** *... *@author ... */ //class laya.d3.graphics.VertexElementUsage var VertexElementUsage=(function(){ function VertexElementUsage(){} __class(VertexElementUsage,'laya.d3.graphics.VertexElementUsage'); VertexElementUsage.POSITION0=0; VertexElementUsage.COLOR0=1; VertexElementUsage.TEXTURECOORDINATE0=2; VertexElementUsage.NORMAL0=3; VertexElementUsage.BINORMAL0=4; VertexElementUsage.TANGENT0=5; VertexElementUsage.BLENDINDICES0=6; VertexElementUsage.BLENDWEIGHT0=7; VertexElementUsage.DEPTH0=8; VertexElementUsage.FOG0=9; VertexElementUsage.POINTSIZE0=10; VertexElementUsage.SAMPLE0=11; VertexElementUsage.TESSELLATEFACTOR0=12; VertexElementUsage.COLOR1=13; VertexElementUsage.NEXTTEXTURECOORDINATE0=14; VertexElementUsage.TEXTURECOORDINATE1=15; VertexElementUsage.NEXTTEXTURECOORDINATE1=16; VertexElementUsage.CORNERTEXTURECOORDINATE0=17; VertexElementUsage.VELOCITY0=18; VertexElementUsage.STARTCOLOR0=19; VertexElementUsage.STARTSIZE=20; VertexElementUsage.AGEADDSCALE0=21; VertexElementUsage.STARTROTATION=22; VertexElementUsage.ENDCOLOR0=23; VertexElementUsage.STARTLIFETIME=24; VertexElementUsage.TIME0=33; VertexElementUsage.SHAPEPOSITIONSTARTLIFETIME=30; VertexElementUsage.DIRECTIONTIME=32; VertexElementUsage.SIZEROTATION0=27; VertexElementUsage.RADIUS0=28; VertexElementUsage.RADIAN0=29; VertexElementUsage.STARTSPEED=31; VertexElementUsage.RANDOM0=34; VertexElementUsage.RANDOM1=35; VertexElementUsage.SIMULATIONWORLDPOSTION=36; VertexElementUsage.SIMULATIONWORLDROTATION=37; VertexElementUsage.TEXTURECOORDINATE0X=38; VertexElementUsage.TEXTURECOORDINATE0X1=39; VertexElementUsage.TEXTURECOORDINATE0Y=40; VertexElementUsage.OFFSETVECTOR=41; return VertexElementUsage; })() /** *VertexPositionNormalColorTangent 类用于创建粒子顶点结构。 */ //class laya.d3.graphics.VertexGlitter var VertexGlitter=(function(){ function VertexGlitter(position,textureCoordinate,time){ this._position=null; this._textureCoordinate0=null; this._time=NaN; this._position=position; this._textureCoordinate0=textureCoordinate; this._time=time; } __class(VertexGlitter,'laya.d3.graphics.VertexGlitter'); var __proto=VertexGlitter.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'textureCoordinate',function(){ return this._textureCoordinate0; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'time',function(){ return this._time; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexGlitter._vertexDeclaration; }); __getset(1,VertexGlitter,'vertexDeclaration',function(){ return VertexGlitter._vertexDeclaration; }); __static(VertexGlitter, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(24, [new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(20,/*laya.d3.graphics.VertexElementFormat.Single*/"single",/*laya.d3.graphics.VertexElementUsage.TIME0*/33)]);} ]); return VertexGlitter; })() /** *VertexPositionNormalColorTangent 类用于创建粒子顶点结构。 */ //class laya.d3.graphics.VertexParticle var VertexParticle=(function(){ function VertexParticle(cornerTextureCoordinate,position,velocity,startColor,endColor,sizeRotation,radius,radian,ageAddScale,time){ this._cornerTextureCoordinate=null; this._position=null; this._velocity=null; this._startColor=null; this._endColor=null; this._sizeRotation=null; this._radius=null; this._radian=null; this._ageAddScale=NaN; this._time=NaN; this._cornerTextureCoordinate=cornerTextureCoordinate; this._position=position; this._velocity=velocity; this._startColor=startColor; this._endColor=endColor; this._sizeRotation=sizeRotation; this._radius=radius; this._radian=radian; this._ageAddScale=ageAddScale; this._time=time; } __class(VertexParticle,'laya.d3.graphics.VertexParticle'); var __proto=VertexParticle.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'endColor',function(){ return this._endColor; }); __getset(0,__proto,'cornerTextureCoordinate',function(){ return this._cornerTextureCoordinate; }); __getset(0,__proto,'sizeRotation',function(){ return this._sizeRotation; }); __getset(0,__proto,'velocity',function(){ return this._velocity; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'startColor',function(){ return this._startColor; }); __getset(0,__proto,'radius',function(){ return this._radius; }); __getset(0,__proto,'radian',function(){ return this._radian; }); __getset(0,__proto,'ageAddScale',function(){ return this._ageAddScale; }); __getset(0,__proto,'time',function(){ return this._time; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexParticle._vertexDeclaration; }); __getset(1,VertexParticle,'vertexDeclaration',function(){ return VertexParticle._vertexDeclaration; }); __static(VertexParticle, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(116, [new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.CORNERTEXTURECOORDINATE0*/17), new VertexElement(16,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(28,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.VELOCITY0*/18), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.STARTCOLOR0*/19), new VertexElement(56,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.ENDCOLOR0*/23), new VertexElement(72,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.SIZEROTATION0*/27), new VertexElement(84,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.RADIUS0*/28), new VertexElement(92,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.RADIAN0*/29), new VertexElement(108,/*laya.d3.graphics.VertexElementFormat.Single*/"single",/*laya.d3.graphics.VertexElementUsage.STARTLIFETIME*/24), new VertexElement(112,/*laya.d3.graphics.VertexElementFormat.Single*/"single",/*laya.d3.graphics.VertexElementUsage.TIME0*/33)]);} ]); return VertexParticle; })() //class laya.d3.graphics.VertexPosition var VertexPosition=(function(){ function VertexPosition(position){ this._position=null; this._position=position; } __class(VertexPosition,'laya.d3.graphics.VertexPosition'); var __proto=VertexPosition.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPosition._vertexDeclaration; }); /*INTERFACE laya.d3.graphics.IVertex */ __getset(1,VertexPosition,'vertexDeclaration',function(){ return VertexPosition._vertexDeclaration; }); __static(VertexPosition, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(12,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0)]);} ]); return VertexPosition; })() //class laya.d3.graphics.VertexPositionNormal var VertexPositionNormal=(function(){ function VertexPositionNormal(position,normal){ this._position=null; this._normal=null; this._position=position; this._normal=normal; } __class(VertexPositionNormal,'laya.d3.graphics.VertexPositionNormal'); var __proto=VertexPositionNormal.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormal._vertexDeclaration; }); /*INTERFACE laya.d3.graphics.IVertex */ __getset(1,VertexPositionNormal,'vertexDeclaration',function(){ return VertexPositionNormal._vertexDeclaration; }); __static(VertexPositionNormal, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(24,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3)]);} ]); return VertexPositionNormal; })() /** *VertexPositionNormalColor 类用于创建位置、法线、颜色顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColor var VertexPositionNormalColor=(function(){ function VertexPositionNormalColor(position,normal,color){ this._position=null; this._normal=null; this._color=null; this._position=position; this._normal=normal; this._color=color; } __class(VertexPositionNormalColor,'laya.d3.graphics.VertexPositionNormalColor'); var __proto=VertexPositionNormalColor.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColor._vertexDeclaration; }); __getset(1,VertexPositionNormalColor,'vertexDeclaration',function(){ return VertexPositionNormalColor._vertexDeclaration; }); __static(VertexPositionNormalColor, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(40,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1)]);} ]); return VertexPositionNormalColor; })() /** *VertexPositionNormalColorSkin 类用于创建位置、法线、颜色、骨骼索引、骨骼权重顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorSkin var VertexPositionNormalColorSkin=(function(){ function VertexPositionNormalColorSkin(position,normal,color,blendIndex,blendWeight){ this._position=null; this._normal=null; this._color=null; this._blendIndex=null; this._blendWeight=null; this._position=position; this._normal=normal; this._color=color; this._blendIndex=blendIndex; this._blendWeight=blendWeight; } __class(VertexPositionNormalColorSkin,'laya.d3.graphics.VertexPositionNormalColorSkin'); var __proto=VertexPositionNormalColorSkin.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'blendWeight',function(){ return this._blendWeight; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'blendIndex',function(){ return this._blendIndex; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorSkin._vertexDeclaration; }); __getset(1,VertexPositionNormalColorSkin,'vertexDeclaration',function(){ return VertexPositionNormalColorSkin._vertexDeclaration; }); __static(VertexPositionNormalColorSkin, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(72,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(56,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6)]);} ]); return VertexPositionNormalColorSkin; })() /** *VertexPositionNormalColorSkin 类用于创建位置、法线、颜色、骨骼索引、骨骼权重顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorSkinSTangent var VertexPositionNormalColorSkinSTangent=(function(){ function VertexPositionNormalColorSkinSTangent(position,normal,color,tangent,blendIndex,blendWeight){ this._position=null; this._normal=null; this._color=null; this._blendIndex=null; this._blendWeight=null; this._tangent=null; this._position=position; this._normal=normal; this._color=color; this._tangent=tangent; this._blendIndex=blendIndex; this._blendWeight=blendWeight; } __class(VertexPositionNormalColorSkinSTangent,'laya.d3.graphics.VertexPositionNormalColorSkinSTangent'); var __proto=VertexPositionNormalColorSkinSTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'blendWeight',function(){ return this._blendWeight; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'blendIndex',function(){ return this._blendIndex; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorSkinSTangent._vertexDeclaration; }); __getset(1,VertexPositionNormalColorSkinSTangent,'vertexDeclaration',function(){ return VertexPositionNormalColorSkinSTangent._vertexDeclaration; }); __static(VertexPositionNormalColorSkinSTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(88,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(56,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6), new VertexElement(72,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalColorSkinSTangent; })() /** *VertexPositionNormalColorSkin 类用于创建位置、法线、颜色、骨骼索引、骨骼权重顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorSkinTangent var VertexPositionNormalColorSkinTangent=(function(){ function VertexPositionNormalColorSkinTangent(position,normal,color,tangent,blendIndex,blendWeight){ this._position=null; this._normal=null; this._color=null; this._blendIndex=null; this._blendWeight=null; this._tangent=null; this._position=position; this._normal=normal; this._color=color; this._tangent=tangent; this._blendIndex=blendIndex; this._blendWeight=blendWeight; } __class(VertexPositionNormalColorSkinTangent,'laya.d3.graphics.VertexPositionNormalColorSkinTangent'); var __proto=VertexPositionNormalColorSkinTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'blendWeight',function(){ return this._blendWeight; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'blendIndex',function(){ return this._blendIndex; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorSkinTangent._vertexDeclaration; }); __getset(1,VertexPositionNormalColorSkinTangent,'vertexDeclaration',function(){ return VertexPositionNormalColorSkinTangent._vertexDeclaration; }); __static(VertexPositionNormalColorSkinTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(84,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(56,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6), new VertexElement(72,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalColorSkinTangent; })() /** *VertexPositionNormalColorTangent 类用于创建位置、法线、颜色、切线顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorSTangent var VertexPositionNormalColorSTangent=(function(){ function VertexPositionNormalColorSTangent(position,normal,color,tangent){ this._position=null; this._normal=null; this._color=null; this._tangent=null; this._position=position; this._normal=normal; this._color=color; this._tangent=tangent; } __class(VertexPositionNormalColorSTangent,'laya.d3.graphics.VertexPositionNormalColorSTangent'); var __proto=VertexPositionNormalColorSTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorSTangent._vertexDeclaration; }); __getset(1,VertexPositionNormalColorSTangent,'vertexDeclaration',function(){ return VertexPositionNormalColorSTangent._vertexDeclaration; }); __static(VertexPositionNormalColorSTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(56,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalColorSTangent; })() /** *VertexPositionNormalColorTangent 类用于创建位置、法线、颜色、切线顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorTangent var VertexPositionNormalColorTangent=(function(){ function VertexPositionNormalColorTangent(position,normal,color,tangent){ this._position=null; this._normal=null; this._color=null; this._tangent=null; this._position=position; this._normal=normal; this._color=color; this._tangent=tangent; } __class(VertexPositionNormalColorTangent,'laya.d3.graphics.VertexPositionNormalColorTangent'); var __proto=VertexPositionNormalColorTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorTangent._vertexDeclaration; }); __getset(1,VertexPositionNormalColorTangent,'vertexDeclaration',function(){ return VertexPositionNormalColorTangent._vertexDeclaration; }); __static(VertexPositionNormalColorTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(52,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalColorTangent; })() /** *VertexPositionNormalColorTexture 类用于创建位置、法线、颜色、纹理顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorTexture var VertexPositionNormalColorTexture=(function(){ function VertexPositionNormalColorTexture(position,normal,color,textureCoordinate){ this._position=null; this._normal=null; this._color=null; this._textureCoordinate=null; this._position=position; this._normal=normal; this._color=color; this._textureCoordinate=textureCoordinate; } __class(VertexPositionNormalColorTexture,'laya.d3.graphics.VertexPositionNormalColorTexture'); var __proto=VertexPositionNormalColorTexture.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'textureCoordinate',function(){ return this._textureCoordinate; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorTexture._vertexDeclaration; }); __getset(1,VertexPositionNormalColorTexture,'vertexDeclaration',function(){ return VertexPositionNormalColorTexture._vertexDeclaration; }); __static(VertexPositionNormalColorTexture, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(48,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2)]);} ]); return VertexPositionNormalColorTexture; })() /** *VertexPositionNormalColorTexture 类用于创建位置、法线、颜色、纹理顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorTexture0Texture1 var VertexPositionNormalColorTexture0Texture1=(function(){ function VertexPositionNormalColorTexture0Texture1(position,normal,color,textureCoordinate0,textureCoordinate1){ this._position=null; this._normal=null; this._color=null; this._textureCoordinate0=null; this._textureCoordinate1=null; this._position=position; this._normal=normal; this._color=color; this._textureCoordinate0=textureCoordinate0; this._textureCoordinate1=textureCoordinate1; } __class(VertexPositionNormalColorTexture0Texture1,'laya.d3.graphics.VertexPositionNormalColorTexture0Texture1'); var __proto=VertexPositionNormalColorTexture0Texture1.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'textureCoordinate0',function(){ return this._textureCoordinate0; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorTexture0Texture1._vertexDeclaration; }); __getset(0,__proto,'textureCoordinate1',function(){ return this._textureCoordinate1; }); __getset(1,VertexPositionNormalColorTexture0Texture1,'vertexDeclaration',function(){ return VertexPositionNormalColorTexture0Texture1._vertexDeclaration; }); __static(VertexPositionNormalColorTexture0Texture1, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(56,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE1*/15)]);} ]); return VertexPositionNormalColorTexture0Texture1; })() /** *VertexPositionNormalColorTextureSkin 类用于创建位置、法线、颜色、纹理、骨骼索引、骨骼权重顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorTexture0Texture1Skin var VertexPositionNormalColorTexture0Texture1Skin=(function(){ function VertexPositionNormalColorTexture0Texture1Skin(position,normal,color,textureCoordinate0,textureCoordinate1,blendIndex,blendWeight){ this._position=null; this._normal=null; this._color=null; this._textureCoordinate0=null; this._textureCoordinate1=null; this._blendIndex=null; this._blendWeight=null; this._position=position; this._normal=normal; this._color=color; this._textureCoordinate0=textureCoordinate0; this._textureCoordinate1=textureCoordinate1; this._blendIndex=blendIndex; this._blendWeight=blendWeight; } __class(VertexPositionNormalColorTexture0Texture1Skin,'laya.d3.graphics.VertexPositionNormalColorTexture0Texture1Skin'); var __proto=VertexPositionNormalColorTexture0Texture1Skin.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'blendWeight',function(){ return this._blendWeight; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'textureCoordinate0',function(){ return this._textureCoordinate0; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorTexture0Texture1Skin._vertexDeclaration; }); __getset(0,__proto,'textureCoordinate1',function(){ return this._textureCoordinate1; }); __getset(0,__proto,'blendIndex',function(){ return this._blendIndex; }); __getset(1,VertexPositionNormalColorTexture0Texture1Skin,'vertexDeclaration',function(){ return VertexPositionNormalColorTexture0Texture1Skin._vertexDeclaration; }); __static(VertexPositionNormalColorTexture0Texture1Skin, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(88,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE1*/15), new VertexElement(56,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(72,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6)]);} ]); return VertexPositionNormalColorTexture0Texture1Skin; })() /** *VertexPositionNormalTextureSkin 类用于创建位置、法线、纹理、骨骼索引、骨骼权重顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorTexture0Texture1SkinSTangent var VertexPositionNormalColorTexture0Texture1SkinSTangent=(function(){ function VertexPositionNormalColorTexture0Texture1SkinSTangent(position,normal,color,textureCoordinate0,textureCoordinate1,tangent,blendIndex,blendWeight){ this._position=null; this._normal=null; this._color=null; this._textureCoordinate0=null; this._textureCoordinate1=null; this._blendIndex=null; this._blendWeight=null; this._tangent=null; this._position=position; this._normal=normal; this._color=color; this._textureCoordinate0=textureCoordinate0; this._textureCoordinate1=textureCoordinate1; this._tangent=tangent; this._blendIndex=blendIndex; this._blendWeight=blendWeight; } __class(VertexPositionNormalColorTexture0Texture1SkinSTangent,'laya.d3.graphics.VertexPositionNormalColorTexture0Texture1SkinSTangent'); var __proto=VertexPositionNormalColorTexture0Texture1SkinSTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'blendWeight',function(){ return this._blendWeight; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'textureCoordinate0',function(){ return this._textureCoordinate0; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorTexture0Texture1SkinSTangent._vertexDeclaration; }); __getset(0,__proto,'textureCoordinate1',function(){ return this._textureCoordinate1; }); __getset(0,__proto,'blendIndex',function(){ return this._blendIndex; }); __getset(1,VertexPositionNormalColorTexture0Texture1SkinSTangent,'vertexDeclaration',function(){ return VertexPositionNormalColorTexture0Texture1SkinSTangent._vertexDeclaration; }); __static(VertexPositionNormalColorTexture0Texture1SkinSTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(104,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE1*/15), new VertexElement(56,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(72,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6), new VertexElement(88,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalColorTexture0Texture1SkinSTangent; })() /** *VertexPositionNormalTextureSkin 类用于创建位置、法线、纹理、骨骼索引、骨骼权重顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorTexture0Texture1SkinTangent var VertexPositionNormalColorTexture0Texture1SkinTangent=(function(){ function VertexPositionNormalColorTexture0Texture1SkinTangent(){ this._position=null; this._normal=null; this._color=null; this._textureCoordinate0=null; this._textureCoordinate1=null; this._blendIndex=null; this._blendWeight=null; this._tangent=null; } __class(VertexPositionNormalColorTexture0Texture1SkinTangent,'laya.d3.graphics.VertexPositionNormalColorTexture0Texture1SkinTangent'); var __proto=VertexPositionNormalColorTexture0Texture1SkinTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __proto.VertexPositionNormalColorTexture0SkinTangent=function(position,normal,color,textureCoordinate0,textureCoordinate1,tangent,blendIndex,blendWeight){ this._position=position; this._normal=normal; this._color=color; this._textureCoordinate0=textureCoordinate0; this._textureCoordinate1=textureCoordinate1; this._tangent=tangent; this._blendIndex=blendIndex; this._blendWeight=blendWeight; } __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'blendWeight',function(){ return this._blendWeight; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'textureCoordinate0',function(){ return this._textureCoordinate0; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorTexture0Texture1SkinTangent._vertexDeclaration; }); __getset(0,__proto,'textureCoordinate1',function(){ return this._textureCoordinate1; }); __getset(0,__proto,'blendIndex',function(){ return this._blendIndex; }); __getset(1,VertexPositionNormalColorTexture0Texture1SkinTangent,'vertexDeclaration',function(){ return VertexPositionNormalColorTexture0Texture1SkinTangent._vertexDeclaration; }); __static(VertexPositionNormalColorTexture0Texture1SkinTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(100,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE1*/15), new VertexElement(56,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(72,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6), new VertexElement(88,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalColorTexture0Texture1SkinTangent; })() /** *VertexPositionNormalColorTextureTangent 类用于创建位置、法线、颜色、纹理、切线顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorTexture0Texture1STangent var VertexPositionNormalColorTexture0Texture1STangent=(function(){ function VertexPositionNormalColorTexture0Texture1STangent(position,normal,color,textureCoordinate0,textureCoordinate1,tangent){ this._position=null; this._normal=null; this._color=null; this._textureCoordinate0=null; this._textureCoordinate1=null; this._tangent=null; this._position=position; this._normal=normal; this._color=color; this._textureCoordinate0=textureCoordinate0; this._textureCoordinate1=textureCoordinate1; this._tangent=tangent; } __class(VertexPositionNormalColorTexture0Texture1STangent,'laya.d3.graphics.VertexPositionNormalColorTexture0Texture1STangent'); var __proto=VertexPositionNormalColorTexture0Texture1STangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'textureCoordinate0',function(){ return this._textureCoordinate0; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorTexture0Texture1STangent._vertexDeclaration; }); __getset(0,__proto,'textureCoordinate1',function(){ return this._textureCoordinate1; }); __getset(1,VertexPositionNormalColorTexture0Texture1STangent,'vertexDeclaration',function(){ return VertexPositionNormalColorTexture0Texture1STangent._vertexDeclaration; }); __static(VertexPositionNormalColorTexture0Texture1STangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(72,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE1*/15), new VertexElement(56,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalColorTexture0Texture1STangent; })() /** *VertexPositionNormalColorTextureTangent 类用于创建位置、法线、颜色、纹理、切线顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorTexture0Texture1Tangent var VertexPositionNormalColorTexture0Texture1Tangent=(function(){ function VertexPositionNormalColorTexture0Texture1Tangent(){ this._position=null; this._normal=null; this._color=null; this._textureCoordinate0=null; this._textureCoordinate1=null; this._tangent=null; } __class(VertexPositionNormalColorTexture0Texture1Tangent,'laya.d3.graphics.VertexPositionNormalColorTexture0Texture1Tangent'); var __proto=VertexPositionNormalColorTexture0Texture1Tangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __proto.VertexPositionNormalColorTexture0Tangent=function(position,normal,color,textureCoordinate0,textureCoordinate1,tangent){ this._position=position; this._normal=normal; this._color=color; this._textureCoordinate0=textureCoordinate0; this._textureCoordinate1=textureCoordinate1; this._tangent=tangent; } __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'textureCoordinate0',function(){ return this._textureCoordinate0; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorTexture0Texture1Tangent._vertexDeclaration; }); __getset(0,__proto,'textureCoordinate1',function(){ return this._textureCoordinate1; }); __getset(1,VertexPositionNormalColorTexture0Texture1Tangent,'vertexDeclaration',function(){ return VertexPositionNormalColorTexture0Texture1Tangent._vertexDeclaration; }); __static(VertexPositionNormalColorTexture0Texture1Tangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(68,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE1*/15), new VertexElement(56,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalColorTexture0Texture1Tangent; })() /** *VertexPositionNormalColorTextureSkin 类用于创建位置、法线、颜色、纹理、骨骼索引、骨骼权重顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorTextureSkin var VertexPositionNormalColorTextureSkin=(function(){ function VertexPositionNormalColorTextureSkin(position,normal,color,textureCoordinate,blendIndex,blendWeight){ this._position=null; this._normal=null; this._color=null; this._textureCoordinate=null; this._blendIndex=null; this._blendWeight=null; this._position=position; this._normal=normal; this._color=color; this._textureCoordinate=textureCoordinate; this._blendIndex=blendIndex; this._blendWeight=blendWeight; } __class(VertexPositionNormalColorTextureSkin,'laya.d3.graphics.VertexPositionNormalColorTextureSkin'); var __proto=VertexPositionNormalColorTextureSkin.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'textureCoordinate',function(){ return this._textureCoordinate; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'blendWeight',function(){ return this._blendWeight; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'blendIndex',function(){ return this._blendIndex; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorTextureSkin._vertexDeclaration; }); __getset(1,VertexPositionNormalColorTextureSkin,'vertexDeclaration',function(){ return VertexPositionNormalColorTextureSkin._vertexDeclaration; }); __static(VertexPositionNormalColorTextureSkin, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(80,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(64,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6)]);} ]); return VertexPositionNormalColorTextureSkin; })() /** *VertexPositionNormalTextureSkin 类用于创建位置、法线、纹理、骨骼索引、骨骼权重顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorTextureSkinSTangent var VertexPositionNormalColorTextureSkinSTangent=(function(){ function VertexPositionNormalColorTextureSkinSTangent(position,normal,color,textureCoordinate,tangent,blendIndex,blendWeight){ this._position=null; this._normal=null; this._color=null; this._textureCoordinate=null; this._blendIndex=null; this._blendWeight=null; this._tangent=null; this._position=position; this._normal=normal; this._color=color; this._textureCoordinate=textureCoordinate; this._tangent=tangent; this._blendIndex=blendIndex; this._blendWeight=blendWeight; } __class(VertexPositionNormalColorTextureSkinSTangent,'laya.d3.graphics.VertexPositionNormalColorTextureSkinSTangent'); var __proto=VertexPositionNormalColorTextureSkinSTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'textureCoordinate',function(){ return this._textureCoordinate; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'blendWeight',function(){ return this._blendWeight; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'blendIndex',function(){ return this._blendIndex; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorTextureSkinSTangent._vertexDeclaration; }); __getset(1,VertexPositionNormalColorTextureSkinSTangent,'vertexDeclaration',function(){ return VertexPositionNormalColorTextureSkinSTangent._vertexDeclaration; }); __static(VertexPositionNormalColorTextureSkinSTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(96,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(64,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6), new VertexElement(80,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalColorTextureSkinSTangent; })() /** *VertexPositionNormalTextureSkin 类用于创建位置、法线、纹理、骨骼索引、骨骼权重顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorTextureSkinTangent var VertexPositionNormalColorTextureSkinTangent=(function(){ function VertexPositionNormalColorTextureSkinTangent(position,normal,color,textureCoordinate,tangent,blendIndex,blendWeight){ this._position=null; this._normal=null; this._color=null; this._textureCoordinate=null; this._blendIndex=null; this._blendWeight=null; this._tangent=null; this._position=position; this._normal=normal; this._color=color; this._textureCoordinate=textureCoordinate; this._tangent=tangent; this._blendIndex=blendIndex; this._blendWeight=blendWeight; } __class(VertexPositionNormalColorTextureSkinTangent,'laya.d3.graphics.VertexPositionNormalColorTextureSkinTangent'); var __proto=VertexPositionNormalColorTextureSkinTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'textureCoordinate',function(){ return this._textureCoordinate; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'blendWeight',function(){ return this._blendWeight; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'blendIndex',function(){ return this._blendIndex; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorTextureSkinTangent._vertexDeclaration; }); __getset(1,VertexPositionNormalColorTextureSkinTangent,'vertexDeclaration',function(){ return VertexPositionNormalColorTextureSkinTangent._vertexDeclaration; }); __static(VertexPositionNormalColorTextureSkinTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(92,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(64,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6), new VertexElement(80,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalColorTextureSkinTangent; })() /** *VertexPositionNormalColorTextureTangent 类用于创建位置、法线、颜色、纹理、切线顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorTextureSTangent var VertexPositionNormalColorTextureSTangent=(function(){ function VertexPositionNormalColorTextureSTangent(position,normal,color,textureCoordinate,tangent){ this._position=null; this._normal=null; this._color=null; this._textureCoordinate=null; this._tangent=null; this._position=position; this._normal=normal; this._color=color; this._textureCoordinate=textureCoordinate; this._tangent=tangent; } __class(VertexPositionNormalColorTextureSTangent,'laya.d3.graphics.VertexPositionNormalColorTextureSTangent'); var __proto=VertexPositionNormalColorTextureSTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'textureCoordinate',function(){ return this._textureCoordinate; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorTextureSTangent._vertexDeclaration; }); __getset(1,VertexPositionNormalColorTextureSTangent,'vertexDeclaration',function(){ return VertexPositionNormalColorTextureSTangent._vertexDeclaration; }); __static(VertexPositionNormalColorTextureSTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(64,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalColorTextureSTangent; })() /** *VertexPositionNormalColorTextureTangent 类用于创建位置、法线、颜色、纹理、切线顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalColorTextureTangent var VertexPositionNormalColorTextureTangent=(function(){ function VertexPositionNormalColorTextureTangent(position,normal,color,textureCoordinate,tangent){ this._position=null; this._normal=null; this._color=null; this._textureCoordinate=null; this._tangent=null; this._position=position; this._normal=normal; this._color=color; this._textureCoordinate=textureCoordinate; this._tangent=tangent; } __class(VertexPositionNormalColorTextureTangent,'laya.d3.graphics.VertexPositionNormalColorTextureTangent'); var __proto=VertexPositionNormalColorTextureTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'textureCoordinate',function(){ return this._textureCoordinate; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'color',function(){ return this._color; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalColorTextureTangent._vertexDeclaration; }); __getset(1,VertexPositionNormalColorTextureTangent,'vertexDeclaration',function(){ return VertexPositionNormalColorTextureTangent._vertexDeclaration; }); __static(VertexPositionNormalColorTextureTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(60,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalColorTextureTangent; })() //class laya.d3.graphics.VertexPositionNormalSTangent var VertexPositionNormalSTangent=(function(){ function VertexPositionNormalSTangent(position,normal,tangent){ this._position=null; this._normal=null; this._tangent=null; this._position=position; this._normal=normal; this._tangent=tangent; } __class(VertexPositionNormalSTangent,'laya.d3.graphics.VertexPositionNormalSTangent'); var __proto=VertexPositionNormalSTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalSTangent._vertexDeclaration; }); /*INTERFACE laya.d3.graphics.IVertex */ __getset(1,VertexPositionNormalSTangent,'vertexDeclaration',function(){ return VertexPositionNormalSTangent._vertexDeclaration; }); __static(VertexPositionNormalSTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(40,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalSTangent; })() //class laya.d3.graphics.VertexPositionNormalTangent var VertexPositionNormalTangent=(function(){ function VertexPositionNormalTangent(position,normal,tangent){ this._position=null; this._normal=null; this._tangent=null; this._position=position; this._normal=normal; this._tangent=tangent; } __class(VertexPositionNormalTangent,'laya.d3.graphics.VertexPositionNormalTangent'); var __proto=VertexPositionNormalTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalTangent._vertexDeclaration; }); /*INTERFACE laya.d3.graphics.IVertex */ __getset(1,VertexPositionNormalTangent,'vertexDeclaration',function(){ return VertexPositionNormalTangent._vertexDeclaration; }); __static(VertexPositionNormalTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(36,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalTangent; })() /** *VertexPositionNormalTexture 类用于创建位置、法线、纹理顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalTexture var VertexPositionNormalTexture=(function(){ function VertexPositionNormalTexture(position,normal,textureCoordinate){ this._position=null; this._normal=null; this._textureCoordinate=null; this._position=position; this._normal=normal; this._textureCoordinate=textureCoordinate; } __class(VertexPositionNormalTexture,'laya.d3.graphics.VertexPositionNormalTexture'); var __proto=VertexPositionNormalTexture.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'textureCoordinate',function(){ return this._textureCoordinate; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalTexture._vertexDeclaration; }); __getset(1,VertexPositionNormalTexture,'vertexDeclaration',function(){ return VertexPositionNormalTexture._vertexDeclaration; }); __static(VertexPositionNormalTexture, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(32,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2)]);} ]); return VertexPositionNormalTexture; })() /** *VertexPositionNormalTexture 类用于创建位置、法线、纹理顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalTexture0Texture1 var VertexPositionNormalTexture0Texture1=(function(){ function VertexPositionNormalTexture0Texture1(position,normal,textureCoordinate0,textureCoordinate1){ this._position=null; this._normal=null; this._textureCoordinate0=null; this._textureCoordinate1=null; this._position=position; this._normal=normal; this._textureCoordinate0=textureCoordinate0; this._textureCoordinate1=textureCoordinate1; } __class(VertexPositionNormalTexture0Texture1,'laya.d3.graphics.VertexPositionNormalTexture0Texture1'); var __proto=VertexPositionNormalTexture0Texture1.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'textureCoordinate0',function(){ return this._textureCoordinate0; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalTexture0Texture1._vertexDeclaration; }); __getset(0,__proto,'textureCoordinate1',function(){ return this._textureCoordinate1; }); __getset(1,VertexPositionNormalTexture0Texture1,'vertexDeclaration',function(){ return VertexPositionNormalTexture0Texture1._vertexDeclaration; }); __static(VertexPositionNormalTexture0Texture1, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(40,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(32,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE1*/15)]);} ]); return VertexPositionNormalTexture0Texture1; })() /** *VertexPositionNormalColorTextureSkin 类用于创建位置、法线、颜色、纹理、骨骼索引、骨骼权重顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalTexture0Texture1Skin var VertexPositionNormalTexture0Texture1Skin=(function(){ function VertexPositionNormalTexture0Texture1Skin(position,normal,textureCoordinate0,textureCoordinate1,blendIndex,blendWeight){ this._position=null; this._normal=null; this._textureCoordinate0=null; this._textureCoordinate1=null; this._blendIndex=null; this._blendWeight=null; this._position=position; this._normal=normal; this._textureCoordinate0=textureCoordinate0; this._textureCoordinate1=textureCoordinate1; this._blendIndex=blendIndex; this._blendWeight=blendWeight; } __class(VertexPositionNormalTexture0Texture1Skin,'laya.d3.graphics.VertexPositionNormalTexture0Texture1Skin'); var __proto=VertexPositionNormalTexture0Texture1Skin.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'textureCoordinate0',function(){ return this._textureCoordinate0; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalTexture0Texture1Skin._vertexDeclaration; }); __getset(0,__proto,'textureCoordinate1',function(){ return this._textureCoordinate1; }); __getset(0,__proto,'blendIndex',function(){ return this._blendIndex; }); __getset(0,__proto,'blendWeight',function(){ return this._blendWeight; }); __getset(1,VertexPositionNormalTexture0Texture1Skin,'vertexDeclaration',function(){ return VertexPositionNormalTexture0Texture1Skin._vertexDeclaration; }); __static(VertexPositionNormalTexture0Texture1Skin, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(72,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(32,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE1*/15), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(56,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6)]);} ]); return VertexPositionNormalTexture0Texture1Skin; })() /** *VertexPositionNormalTextureSkin 类用于创建位置、法线、纹理、骨骼索引、骨骼权重顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalTexture0Texture1SkinSTangent var VertexPositionNormalTexture0Texture1SkinSTangent=(function(){ function VertexPositionNormalTexture0Texture1SkinSTangent(position,normal,textureCoordinate0,textureCoordinate1,tangent,blendIndex,blendWeight){ this._position=null; this._normal=null; this._textureCoordinate0=null; this._textureCoordinate1=null; this._blendIndex=null; this._blendWeight=null; this._tangent=null; this._position=position; this._normal=normal; this._textureCoordinate0=textureCoordinate0; this._textureCoordinate1=textureCoordinate1; this._tangent=tangent; this._blendIndex=blendIndex; this._blendWeight=blendWeight; } __class(VertexPositionNormalTexture0Texture1SkinSTangent,'laya.d3.graphics.VertexPositionNormalTexture0Texture1SkinSTangent'); var __proto=VertexPositionNormalTexture0Texture1SkinSTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'textureCoordinate0',function(){ return this._textureCoordinate0; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalTexture0Texture1SkinSTangent._vertexDeclaration; }); __getset(0,__proto,'textureCoordinate1',function(){ return this._textureCoordinate1; }); __getset(0,__proto,'blendIndex',function(){ return this._blendIndex; }); __getset(0,__proto,'blendWeight',function(){ return this._blendWeight; }); __getset(1,VertexPositionNormalTexture0Texture1SkinSTangent,'vertexDeclaration',function(){ return VertexPositionNormalTexture0Texture1SkinSTangent._vertexDeclaration; }); __static(VertexPositionNormalTexture0Texture1SkinSTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(88,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(32,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE1*/15), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(56,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6), new VertexElement(72,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalTexture0Texture1SkinSTangent; })() /** *VertexPositionNormalTextureSkin 类用于创建位置、法线、纹理、骨骼索引、骨骼权重顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalTexture0Texture1SkinTangent var VertexPositionNormalTexture0Texture1SkinTangent=(function(){ function VertexPositionNormalTexture0Texture1SkinTangent(){ this._position=null; this._normal=null; this._textureCoordinate0=null; this._textureCoordinate1=null; this._blendIndex=null; this._blendWeight=null; this._tangent=null; } __class(VertexPositionNormalTexture0Texture1SkinTangent,'laya.d3.graphics.VertexPositionNormalTexture0Texture1SkinTangent'); var __proto=VertexPositionNormalTexture0Texture1SkinTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __proto.VertexPositionNormalTexture0SkinTangent=function(position,normal,textureCoordinate0,textureCoordinate1,tangent,blendIndex,blendWeight){ this._position=position; this._normal=normal; this._textureCoordinate0=textureCoordinate0; this._textureCoordinate1=textureCoordinate1; this._tangent=tangent; this._blendIndex=blendIndex; this._blendWeight=blendWeight; } __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'textureCoordinate0',function(){ return this._textureCoordinate0; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalTexture0Texture1SkinTangent._vertexDeclaration; }); __getset(0,__proto,'textureCoordinate1',function(){ return this._textureCoordinate1; }); __getset(0,__proto,'blendIndex',function(){ return this._blendIndex; }); __getset(0,__proto,'blendWeight',function(){ return this._blendWeight; }); __getset(1,VertexPositionNormalTexture0Texture1SkinTangent,'vertexDeclaration',function(){ return VertexPositionNormalTexture0Texture1SkinTangent._vertexDeclaration; }); __static(VertexPositionNormalTexture0Texture1SkinTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(84,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(32,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE1*/15), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(56,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6), new VertexElement(72,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalTexture0Texture1SkinTangent; })() /** *VertexPositionNormalTextureTangent 类用于创建位置、法线、纹理、切线顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalTexture0Texture1STangent var VertexPositionNormalTexture0Texture1STangent=(function(){ function VertexPositionNormalTexture0Texture1STangent(position,normal,textureCoordinate0,textureCoordinate1,tangent){ this._position=null; this._normal=null; this._textureCoordinate0=null; this._textureCoordinate1=null; this._tangent=null; this._position=position; this._normal=normal; this._textureCoordinate0=textureCoordinate0; this._textureCoordinate1=textureCoordinate1; this._tangent=tangent; } __class(VertexPositionNormalTexture0Texture1STangent,'laya.d3.graphics.VertexPositionNormalTexture0Texture1STangent'); var __proto=VertexPositionNormalTexture0Texture1STangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'textureCoordinate0',function(){ return this._textureCoordinate0; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalTexture0Texture1STangent._vertexDeclaration; }); __getset(0,__proto,'textureCoordinate1',function(){ return this._textureCoordinate1; }); __getset(1,VertexPositionNormalTexture0Texture1STangent,'vertexDeclaration',function(){ return VertexPositionNormalTexture0Texture1STangent._vertexDeclaration; }); __static(VertexPositionNormalTexture0Texture1STangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(56,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(32,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE1*/15), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalTexture0Texture1STangent; })() /** *VertexPositionNormalTextureTangent 类用于创建位置、法线、纹理、切线顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalTexture0Texture1Tangent var VertexPositionNormalTexture0Texture1Tangent=(function(){ function VertexPositionNormalTexture0Texture1Tangent(){ this._position=null; this._normal=null; this._textureCoordinate0=null; this._textureCoordinate1=null; this._tangent=null; } __class(VertexPositionNormalTexture0Texture1Tangent,'laya.d3.graphics.VertexPositionNormalTexture0Texture1Tangent'); var __proto=VertexPositionNormalTexture0Texture1Tangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __proto.VertexPositionNormalTexture0Tangent=function(position,normal,textureCoordinate0,textureCoordinate1,tangent){ this._position=position; this._normal=normal; this._textureCoordinate0=textureCoordinate0; this._textureCoordinate1=textureCoordinate1; this._tangent=tangent; } __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'textureCoordinate0',function(){ return this._textureCoordinate0; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalTexture0Texture1Tangent._vertexDeclaration; }); __getset(0,__proto,'textureCoordinate1',function(){ return this._textureCoordinate1; }); __getset(1,VertexPositionNormalTexture0Texture1Tangent,'vertexDeclaration',function(){ return VertexPositionNormalTexture0Texture1Tangent._vertexDeclaration; }); __static(VertexPositionNormalTexture0Texture1Tangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(52,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(32,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE1*/15), new VertexElement(40,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalTexture0Texture1Tangent; })() /** *VertexPositionNormalColorTextureSkin 类用于创建位置、法线、颜色、纹理、骨骼索引、骨骼权重顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalTextureSkin var VertexPositionNormalTextureSkin=(function(){ function VertexPositionNormalTextureSkin(position,normal,textureCoordinate,blendIndex,blendWeight){ this._position=null; this._normal=null; this._textureCoordinate=null; this._blendIndex=null; this._blendWeight=null; this._position=position; this._normal=normal; this._textureCoordinate=textureCoordinate; this._blendIndex=blendIndex; this._blendWeight=blendWeight; } __class(VertexPositionNormalTextureSkin,'laya.d3.graphics.VertexPositionNormalTextureSkin'); var __proto=VertexPositionNormalTextureSkin.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'textureCoordinate',function(){ return this._textureCoordinate; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'blendIndex',function(){ return this._blendIndex; }); __getset(0,__proto,'blendWeight',function(){ return this._blendWeight; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalTextureSkin._vertexDeclaration; }); __getset(1,VertexPositionNormalTextureSkin,'vertexDeclaration',function(){ return VertexPositionNormalTextureSkin._vertexDeclaration; }); __static(VertexPositionNormalTextureSkin, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(64,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(32,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6)]);} ]); return VertexPositionNormalTextureSkin; })() /** *VertexPositionNormalTextureSkin 类用于创建位置、法线、纹理、骨骼索引、骨骼权重顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalTextureSkinSTangent var VertexPositionNormalTextureSkinSTangent=(function(){ function VertexPositionNormalTextureSkinSTangent(position,normal,textureCoordinate,tangent,blendIndex,blendWeight){ this._position=null; this._normal=null; this._textureCoordinate=null; this._blendIndex=null; this._blendWeight=null; this._tangent=null; this._position=position; this._normal=normal; this._textureCoordinate=textureCoordinate; this._tangent=tangent; this._blendIndex=blendIndex; this._blendWeight=blendWeight; } __class(VertexPositionNormalTextureSkinSTangent,'laya.d3.graphics.VertexPositionNormalTextureSkinSTangent'); var __proto=VertexPositionNormalTextureSkinSTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'textureCoordinate',function(){ return this._textureCoordinate; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'blendIndex',function(){ return this._blendIndex; }); __getset(0,__proto,'blendWeight',function(){ return this._blendWeight; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalTextureSkinSTangent._vertexDeclaration; }); __getset(1,VertexPositionNormalTextureSkinSTangent,'vertexDeclaration',function(){ return VertexPositionNormalTextureSkinSTangent._vertexDeclaration; }); __static(VertexPositionNormalTextureSkinSTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(80,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(32,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6), new VertexElement(64,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalTextureSkinSTangent; })() /** *VertexPositionNormalTextureSkin 类用于创建位置、法线、纹理、骨骼索引、骨骼权重顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalTextureSkinTangent var VertexPositionNormalTextureSkinTangent=(function(){ function VertexPositionNormalTextureSkinTangent(position,normal,textureCoordinate,tangent,blendIndex,blendWeight){ this._position=null; this._normal=null; this._textureCoordinate=null; this._blendIndex=null; this._blendWeight=null; this._tangent=null; this._position=position; this._normal=normal; this._textureCoordinate=textureCoordinate; this._tangent=tangent; this._blendIndex=blendIndex; this._blendWeight=blendWeight; } __class(VertexPositionNormalTextureSkinTangent,'laya.d3.graphics.VertexPositionNormalTextureSkinTangent'); var __proto=VertexPositionNormalTextureSkinTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'textureCoordinate',function(){ return this._textureCoordinate; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'blendIndex',function(){ return this._blendIndex; }); __getset(0,__proto,'blendWeight',function(){ return this._blendWeight; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalTextureSkinTangent._vertexDeclaration; }); __getset(1,VertexPositionNormalTextureSkinTangent,'vertexDeclaration',function(){ return VertexPositionNormalTextureSkinTangent._vertexDeclaration; }); __static(VertexPositionNormalTextureSkinTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(76,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(32,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6), new VertexElement(64,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalTextureSkinTangent; })() /** *VertexPositionNormalTextureTangent 类用于创建位置、法线、纹理、切线顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalTextureSTangent var VertexPositionNormalTextureSTangent=(function(){ function VertexPositionNormalTextureSTangent(position,normal,textureCoordinate,tangent){ this._position=null; this._normal=null; this._textureCoordinate=null; this._tangent=null; this._position=position; this._normal=normal; this._textureCoordinate=textureCoordinate; this._tangent=tangent; } __class(VertexPositionNormalTextureSTangent,'laya.d3.graphics.VertexPositionNormalTextureSTangent'); var __proto=VertexPositionNormalTextureSTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'textureCoordinate',function(){ return this._textureCoordinate; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalTextureSTangent._vertexDeclaration; }); __getset(1,VertexPositionNormalTextureSTangent,'vertexDeclaration',function(){ return VertexPositionNormalTextureSTangent._vertexDeclaration; }); __static(VertexPositionNormalTextureSTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(48,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(32,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalTextureSTangent; })() /** *VertexPositionNormalTextureTangent 类用于创建位置、法线、纹理、切线顶点结构。 */ //class laya.d3.graphics.VertexPositionNormalTextureTangent var VertexPositionNormalTextureTangent=(function(){ function VertexPositionNormalTextureTangent(position,normal,textureCoordinate,tangent){ this._position=null; this._normal=null; this._textureCoordinate=null; this._tangent=null; this._position=position; this._normal=normal; this._textureCoordinate=textureCoordinate; this._tangent=tangent; } __class(VertexPositionNormalTextureTangent,'laya.d3.graphics.VertexPositionNormalTextureTangent'); var __proto=VertexPositionNormalTextureTangent.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'textureCoordinate',function(){ return this._textureCoordinate; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNormalTextureTangent._vertexDeclaration; }); __getset(1,VertexPositionNormalTextureTangent,'vertexDeclaration',function(){ return VertexPositionNormalTextureTangent._vertexDeclaration; }); __static(VertexPositionNormalTextureTangent, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(44,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(32,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5)]);} ]); return VertexPositionNormalTextureTangent; })() /** *VertexPositionNormalTexture 类用于创建位置、法线、纹理顶点结构。 */ //class laya.d3.graphics.VertexPositionNTBTexture var VertexPositionNTBTexture=(function(){ function VertexPositionNTBTexture(position,normal,textureCoordinate){ this._position=null; this._normal=null; this._textureCoordinate=null; this._position=position; this._normal=normal; this._textureCoordinate=textureCoordinate; } __class(VertexPositionNTBTexture,'laya.d3.graphics.VertexPositionNTBTexture'); var __proto=VertexPositionNTBTexture.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'textureCoordinate',function(){ return this._textureCoordinate; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNTBTexture._vertexDeclaration; }); __getset(1,VertexPositionNTBTexture,'vertexDeclaration',function(){ return VertexPositionNTBTexture._vertexDeclaration; }); __static(VertexPositionNTBTexture, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(56,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5), new VertexElement(36,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.BINORMAL0*/4), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2)]);} ]); return VertexPositionNTBTexture; })() /** *VertexPositionNormalTextureSkin 类用于创建位置、法线、纹理、骨骼索引、骨骼权重顶点结构。 */ //class laya.d3.graphics.VertexPositionNTBTexture0Texture1Skin var VertexPositionNTBTexture0Texture1Skin=(function(){ function VertexPositionNTBTexture0Texture1Skin(position,normal,binormal,textureCoordinate0,textureCoordinate1,tangent,blendIndex,blendWeight){ this._position=null; this._normal=null; this._textureCoordinate0=null; this._textureCoordinate1=null; this._blendIndex=null; this._blendWeight=null; this._tangent=null; this.binormal=null; this._position=position; this._normal=normal; this._textureCoordinate0=textureCoordinate0; this._textureCoordinate1=textureCoordinate1; this._tangent=tangent; binormal=binormal; this._blendIndex=blendIndex; this._blendWeight=blendWeight; } __class(VertexPositionNTBTexture0Texture1Skin,'laya.d3.graphics.VertexPositionNTBTexture0Texture1Skin'); var __proto=VertexPositionNTBTexture0Texture1Skin.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'tangent',function(){ return this._tangent; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'textureCoordinate0',function(){ return this._textureCoordinate0; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNTBTexture0Texture1Skin._vertexDeclaration; }); __getset(0,__proto,'textureCoordinate1',function(){ return this._textureCoordinate1; }); __getset(0,__proto,'blendIndex',function(){ return this._blendIndex; }); __getset(0,__proto,'blendWeight',function(){ return this._blendWeight; }); __getset(1,VertexPositionNTBTexture0Texture1Skin,'vertexDeclaration',function(){ return VertexPositionNTBTexture0Texture1Skin._vertexDeclaration; }); __static(VertexPositionNTBTexture0Texture1Skin, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(96,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5), new VertexElement(36,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.BINORMAL0*/4), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(56,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE1*/15), new VertexElement(64,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(80,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6)]);} ]); return VertexPositionNTBTexture0Texture1Skin; })() /** *VertexPositionNormalTexture 类用于创建位置、法线、纹理顶点结构。 */ //class laya.d3.graphics.VertexPositionNTBTextureSkin var VertexPositionNTBTextureSkin=(function(){ function VertexPositionNTBTextureSkin(position,normal,textureCoordinate){ this._position=null; this._normal=null; this._textureCoordinate=null; this._position=position; this._normal=normal; this._textureCoordinate=textureCoordinate; } __class(VertexPositionNTBTextureSkin,'laya.d3.graphics.VertexPositionNTBTextureSkin'); var __proto=VertexPositionNTBTextureSkin.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'textureCoordinate',function(){ return this._textureCoordinate; }); __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionNTBTextureSkin._vertexDeclaration; }); __getset(1,VertexPositionNTBTextureSkin,'vertexDeclaration',function(){ return VertexPositionNTBTextureSkin._vertexDeclaration; }); __static(VertexPositionNTBTextureSkin, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(88,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.TANGENT0*/5), new VertexElement(36,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.BINORMAL0*/4), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(56,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDWEIGHT0*/7), new VertexElement(72,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.BLENDINDICES0*/6)]);} ]); return VertexPositionNTBTextureSkin; })() /** *VertexPositionTerrain 类用于创建位置、法线、纹理1、纹理2顶点结构。 */ //class laya.d3.graphics.VertexPositionTerrain var VertexPositionTerrain=(function(){ function VertexPositionTerrain(position,normal,textureCoord0,textureCoord1){ this._position=null; this._normal=null; this._textureCoord0=null; this._textureCoord1=null; this._position=position; this._normal=normal; this._textureCoord0=textureCoord0; this._textureCoord1=textureCoord1; } __class(VertexPositionTerrain,'laya.d3.graphics.VertexPositionTerrain'); var __proto=VertexPositionTerrain.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'normal',function(){ return this._normal; }); __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'textureCoord0',function(){ return this._textureCoord0; }); __getset(0,__proto,'textureCoord1',function(){ return this._textureCoord1; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionTerrain._vertexDeclaration; }); __getset(1,VertexPositionTerrain,'vertexDeclaration',function(){ return VertexPositionTerrain._vertexDeclaration; }); __static(VertexPositionTerrain, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(40,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3), new VertexElement(24,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(32,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE1*/15)]);} ]); return VertexPositionTerrain; })() /** *VertexPositionNormalTexture 类用于创建位置、纹理顶点结构。 */ //class laya.d3.graphics.VertexPositionTexture0 var VertexPositionTexture0=(function(){ function VertexPositionTexture0(position,textureCoordinate0){ this._position=null; this._textureCoordinate0=null; this._position=position; this._textureCoordinate0=textureCoordinate0; } __class(VertexPositionTexture0,'laya.d3.graphics.VertexPositionTexture0'); var __proto=VertexPositionTexture0.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'position',function(){ return this._position; }); __getset(0,__proto,'textureCoordinate0',function(){ return this._textureCoordinate0; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexPositionTexture0._vertexDeclaration; }); __getset(1,VertexPositionTexture0,'vertexDeclaration',function(){ return VertexPositionTexture0._vertexDeclaration; }); __static(VertexPositionTexture0, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(20,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2)]);} ]); return VertexPositionTexture0; })() /** *VertexShurikenParticle 类用于创建粒子顶点结构。 */ //class laya.d3.graphics.VertexShurikenParticleBillboard var VertexShurikenParticleBillboard=(function(){ function VertexShurikenParticleBillboard(cornerTextureCoordinate,positionStartLifeTime,velocity,startColor,startSize,startRotation0,startRotation1,startRotation2,ageAddScale,time,startSpeed,randoms0,randoms1,simulationWorldPostion){ /**@private */ this._cornerTextureCoordinate=null; /**@private */ this._positionStartLifeTime=null; /**@private */ this._velocity=null; /**@private */ this._startColor=null; /**@private */ this._startSize=null; /**@private */ this._startRotation0=null; /**@private */ this._startRotation1=null; /**@private */ this._startRotation2=null; /**@private */ this._startLifeTime=NaN; /**@private */ this._time=NaN; /**@private */ this._startSpeed=NaN; /**@private */ this._randoms0=null; /**@private */ this._randoms1=null; /**@private */ this._simulationWorldPostion=null; this._cornerTextureCoordinate=cornerTextureCoordinate; this._positionStartLifeTime=positionStartLifeTime; this._velocity=velocity; this._startColor=startColor; this._startSize=startSize; this._startRotation0=startRotation0; this._startRotation1=startRotation1; this._startRotation2=startRotation2; this._startLifeTime=ageAddScale; this._time=time; this._startSpeed=startSpeed; this._randoms0=this.random0; this._randoms1=this.random1; this._simulationWorldPostion=simulationWorldPostion; } __class(VertexShurikenParticleBillboard,'laya.d3.graphics.VertexShurikenParticleBillboard'); var __proto=VertexShurikenParticleBillboard.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'cornerTextureCoordinate',function(){ return this._cornerTextureCoordinate; }); __getset(0,__proto,'random1',function(){ return this._randoms1; }); __getset(0,__proto,'startRotation2',function(){ return this._startRotation2; }); __getset(0,__proto,'positionStartLifeTime',function(){ return this._positionStartLifeTime; }); __getset(0,__proto,'velocity',function(){ return this._velocity; }); __getset(0,__proto,'random0',function(){ return this._randoms0; }); __getset(0,__proto,'startSize',function(){ return this._startSize; }); __getset(0,__proto,'startColor',function(){ return this._startColor; }); __getset(0,__proto,'startRotation0',function(){ return this._startRotation0; }); __getset(0,__proto,'startRotation1',function(){ return this._startRotation1; }); __getset(0,__proto,'startLifeTime',function(){ return this._startLifeTime; }); __getset(0,__proto,'time',function(){ return this._time; }); __getset(0,__proto,'startSpeed',function(){ return this._startSpeed; }); __getset(0,__proto,'simulationWorldPostion',function(){ return this._simulationWorldPostion; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexShurikenParticleBillboard._vertexDeclaration; }); __getset(1,VertexShurikenParticleBillboard,'vertexDeclaration',function(){ return VertexShurikenParticleBillboard._vertexDeclaration; }); __static(VertexShurikenParticleBillboard, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(152,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.CORNERTEXTURECOORDINATE0*/17), new VertexElement(16,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.SHAPEPOSITIONSTARTLIFETIME*/30), new VertexElement(32,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.DIRECTIONTIME*/32), new VertexElement(48,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.STARTCOLOR0*/19), new VertexElement(64,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.STARTSIZE*/20), new VertexElement(76,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.STARTROTATION*/22), new VertexElement(88,/*laya.d3.graphics.VertexElementFormat.Single*/"single",/*laya.d3.graphics.VertexElementUsage.STARTSPEED*/31), new VertexElement(92,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.RANDOM0*/34), new VertexElement(108,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.RANDOM1*/35), new VertexElement(124,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.SIMULATIONWORLDPOSTION*/36), new VertexElement(136,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.SIMULATIONWORLDROTATION*/37)]);} ]); return VertexShurikenParticleBillboard; })() /** *VertexShurikenParticle 类用于创建粒子顶点结构。 */ //class laya.d3.graphics.VertexShurikenParticleMesh var VertexShurikenParticleMesh=(function(){ function VertexShurikenParticleMesh(cornerTextureCoordinate,positionStartLifeTime,velocity,startColor,startSize,startRotation0,startRotation1,startRotation2,ageAddScale,time,startSpeed,randoms0,randoms1,simulationWorldPostion){ /**@private */ this._cornerTextureCoordinate=null; /**@private */ this._positionStartLifeTime=null; /**@private */ this._velocity=null; /**@private */ this._startColor=null; /**@private */ this._startSize=null; /**@private */ this._startRotation0=null; /**@private */ this._startRotation1=null; /**@private */ this._startRotation2=null; /**@private */ this._startLifeTime=NaN; /**@private */ this._time=NaN; /**@private */ this._startSpeed=NaN; /**@private */ this._randoms0=null; /**@private */ this._randoms1=null; /**@private */ this._simulationWorldPostion=null; this._cornerTextureCoordinate=cornerTextureCoordinate; this._positionStartLifeTime=positionStartLifeTime; this._velocity=velocity; this._startColor=startColor; this._startSize=startSize; this._startRotation0=startRotation0; this._startRotation1=startRotation1; this._startRotation2=startRotation2; this._startLifeTime=ageAddScale; this._time=time; this._startSpeed=startSpeed; this._randoms0=this.random0; this._randoms1=this.random1; this._simulationWorldPostion=simulationWorldPostion; } __class(VertexShurikenParticleMesh,'laya.d3.graphics.VertexShurikenParticleMesh'); var __proto=VertexShurikenParticleMesh.prototype; Laya.imps(__proto,{"laya.d3.graphics.IVertex":true}) __getset(0,__proto,'cornerTextureCoordinate',function(){ return this._cornerTextureCoordinate; }); __getset(0,__proto,'velocity',function(){ return this._velocity; }); __getset(0,__proto,'position',function(){ return this._positionStartLifeTime; }); __getset(0,__proto,'random0',function(){ return this._randoms0; }); __getset(0,__proto,'startSize',function(){ return this._startSize; }); __getset(0,__proto,'startColor',function(){ return this._startColor; }); __getset(0,__proto,'startRotation0',function(){ return this._startRotation0; }); __getset(0,__proto,'startRotation1',function(){ return this._startRotation1; }); __getset(0,__proto,'random1',function(){ return this._randoms1; }); __getset(0,__proto,'startRotation2',function(){ return this._startRotation2; }); __getset(0,__proto,'startLifeTime',function(){ return this._startLifeTime; }); __getset(0,__proto,'time',function(){ return this._time; }); __getset(0,__proto,'startSpeed',function(){ return this._startSpeed; }); __getset(0,__proto,'simulationWorldPostion',function(){ return this._simulationWorldPostion; }); __getset(0,__proto,'vertexDeclaration',function(){ return VertexShurikenParticleMesh._vertexDeclaration; }); __getset(1,VertexShurikenParticleMesh,'vertexDeclaration',function(){ return VertexShurikenParticleMesh._vertexDeclaration; }); __static(VertexShurikenParticleMesh, ['_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(172,[ new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0), new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.COLOR0*/1), new VertexElement(28,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2), new VertexElement(36,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.SHAPEPOSITIONSTARTLIFETIME*/30), new VertexElement(52,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.DIRECTIONTIME*/32), new VertexElement(68,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.STARTCOLOR0*/19), new VertexElement(84,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.STARTSIZE*/20), new VertexElement(96,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.STARTROTATION*/22), new VertexElement(108,/*laya.d3.graphics.VertexElementFormat.Single*/"single",/*laya.d3.graphics.VertexElementUsage.STARTSPEED*/31), new VertexElement(112,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.RANDOM0*/34), new VertexElement(128,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.RANDOM1*/35), new VertexElement(144,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.SIMULATIONWORLDPOSTION*/36), new VertexElement(156,/*laya.d3.graphics.VertexElementFormat.Vector4*/"vector4",/*laya.d3.graphics.VertexElementUsage.SIMULATIONWORLDROTATION*/37)]);} ]); return VertexShurikenParticleMesh; })() /** *@private *LoadModel 类用于模型加载。 */ //class laya.d3.loaders.LoadModelV01 var LoadModelV01=(function(){ function LoadModelV01(readData,version,mesh,materials,subMeshes,materialMap){ /**@private */ this._version=null; /**@private */ this._strings=['BLOCK','DATA',"STRINGS"]; /**@private */ this._materials=null; /**@private */ this._subMeshes=null; /**@private */ this._materialMap=null; /**@private */ this._readData=null; /**@private */ this._mesh=null; /**@private */ this._BLOCK={count:0}; /**@private */ this._DATA={offset:0,size:0}; /**@private */ this._STRINGS={offset:0,size:0}; /**@private */ this._shaderAttributes=null; this._mesh=mesh; this._materials=materials; this._subMeshes=subMeshes; this._materialMap=materialMap; this._version=version; this._onLoaded(readData); } __class(LoadModelV01,'laya.d3.loaders.LoadModelV01'); var __proto=LoadModelV01.prototype; /** *@private */ __proto._onLoaded=function(readData){ this._readData=readData; this.READ_BLOCK(); for (var i=0;i < this._BLOCK.count;i++){ var index=this._readData.getUint16(); var blockName=this._strings[index]; var fn=this["READ_"+blockName]; if (fn==null)throw new Error("model file err,no this function:"+index+" "+blockName); if (!fn.call(this))break ; } return this._mesh; } __proto.onError=function(){} /** *@private */ __proto._readString=function(){ return this._strings[this._readData.getUint16()]; } __proto.READ_BLOCK=function(){ var n=this._readData.getUint16(); this._BLOCK.count=this._readData.getUint16(); return true; } __proto.READ_DATA=function(){ this._DATA.offset=this._readData.getUint32(); this._DATA.size=this._readData.getUint32(); return true; } __proto.READ_STRINGS=function(){ this._STRINGS.offset=this._readData.getUint16(); this._STRINGS.size=this._readData.getUint16(); var ofs=this._readData.pos; this._readData.pos=this._STRINGS.offset+this._DATA.offset; for (var i=0;i < this._STRINGS.size;i++){ this._strings[i]=this._readData.readUTFString(); } this._readData.pos=ofs; return true; } __proto.READ_MATERIAL=function(){ var i=0,n=0; var index=this._readData.getUint16(); var shaderName=this._readString(); var url=this._readString(); if (url!=="null") this._materials[index]=Loader.getRes(this._materialMap[url]); else this._materials[index]=new BaseMaterial(); return true; } __proto.READ_MESH=function(){ var name=this._readString(); switch (this._version){ case "LAYAMODEL:01": console.log("Warning: The (.lm) file is converted by old fbxTools,please reConverted it use lastest fbxTools version,later we will remove the support of old version (.lm) support."); break ; case "LAYASKINANI:01": case "LAYAMODEL:02":; var arrayBuffer=this._readData.__getBuffer(); var i=0,n=0; var bindPoseStart=this._readData.getUint32(); var binPoseLength=this._readData.getUint32(); var bindPoseDatas=new Float32Array(arrayBuffer.slice(bindPoseStart+this._DATA.offset,bindPoseStart+this._DATA.offset+binPoseLength)); var inverseGlobalBindPoseStart=this._readData.getUint32(); var inverseGlobalBinPoseLength=this._readData.getUint32(); var invGloBindPoseDatas=new Float32Array(arrayBuffer.slice(inverseGlobalBindPoseStart+this._DATA.offset,inverseGlobalBindPoseStart+this._DATA.offset+inverseGlobalBinPoseLength)); this.mesh._inverseBindPoses=[]; for (i=0,n=invGloBindPoseDatas.length;i < n;i+=16){ var inverseGlobalBindPose=new Matrix4x4(invGloBindPoseDatas[i+0],invGloBindPoseDatas[i+1],invGloBindPoseDatas[i+2],invGloBindPoseDatas[i+3],invGloBindPoseDatas[i+4],invGloBindPoseDatas[i+5],invGloBindPoseDatas[i+6],invGloBindPoseDatas[i+7],invGloBindPoseDatas[i+8],invGloBindPoseDatas[i+9],invGloBindPoseDatas[i+10],invGloBindPoseDatas[i+11],invGloBindPoseDatas[i+12],invGloBindPoseDatas[i+13],invGloBindPoseDatas[i+14],invGloBindPoseDatas[i+15]); this.mesh._inverseBindPoses.push(inverseGlobalBindPose); } break ; default : throw new Error("LoadModel:unknown version."); } return true; } __proto.READ_SUBMESH=function(){ var className=this._readString(); var material=this._readData.getUint8(); var bufferAttribute=this._readString(); this._shaderAttributes=bufferAttribute.match(LoadModelV01._attrReg); var ibofs=this._readData.getUint32(); var ibsize=this._readData.getUint32(); var vbIndicesofs=this._readData.getUint32(); var vbIndicessize=this._readData.getUint32(); var vbofs=this._readData.getUint32(); var vbsize=this._readData.getUint32(); var boneDicofs=this._readData.getUint32(); var boneDicsize=this._readData.getUint32(); var arrayBuffer=this._readData.__getBuffer(); var submesh=new SubMesh(this._mesh); var vertexDeclaration=this._getVertexDeclaration(); var vb=VertexBuffer3D.create(vertexDeclaration,vbsize / vertexDeclaration.vertexStride,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); var vbStart=vbofs+this._DATA.offset; var vbArrayBuffer=arrayBuffer.slice(vbStart,vbStart+vbsize); vb.setData(new Float32Array(vbArrayBuffer)); submesh._vertexBuffer=vb; var vertexElements=vb.vertexDeclaration.getVertexElements(); for (var i=0;i < vertexElements.length;i++) submesh._bufferUsage[(vertexElements [i]).elementUsage]=vb; var ib=IndexBuffer3D.create(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",ibsize / 2,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); var ibStart=ibofs+this._DATA.offset; var ibArrayBuffer=arrayBuffer.slice(ibStart,ibStart+ibsize); ib.setData(new Uint16Array(ibArrayBuffer)); submesh._indexBuffer=ib; var boneDicArrayBuffer=arrayBuffer.slice(boneDicofs+this._DATA.offset,boneDicofs+this._DATA.offset+boneDicsize); submesh._boneIndicesList[0]=new Uint8Array(boneDicArrayBuffer); this._subMeshes.push(submesh); return true; } __proto.READ_DATAAREA=function(){ return false; } __proto._getVertexDeclaration=function(){ var position=false,normal=false,color=false,texcoord0=false,texcoord1=false,tangent=false,blendWeight=false,blendIndex=false; var binormal=false; for (var i=0;i < this._shaderAttributes.length;i+=8){ switch (this._shaderAttributes[i]){ case "POSITION": position=true; break ; case "NORMAL": normal=true; break ; case "COLOR": color=true; break ; case "UV": texcoord0=true; break ; case "UV1": texcoord1=true; break ; case "BLENDWEIGHT": blendWeight=true; break ; case "BLENDINDICES": blendIndex=true; break ; case "TANGENT": tangent=true; break ; case "BINORMAL": binormal=true; break ; } }; var vertexDeclaration; if (position && normal && color && texcoord0 && texcoord1 && blendWeight && blendIndex && tangent) vertexDeclaration=VertexPositionNormalColorTexture0Texture1SkinTangent.vertexDeclaration; else if (position && normal && color && texcoord0 && texcoord1 && blendWeight && blendIndex) vertexDeclaration=VertexPositionNormalColorTexture0Texture1Skin.vertexDeclaration; else if (position && normal && texcoord0 && texcoord1 && blendWeight && blendIndex && tangent) vertexDeclaration=VertexPositionNormalTexture0Texture1SkinTangent.vertexDeclaration; else if (position && normal && texcoord0 && texcoord1 && blendWeight && blendIndex) vertexDeclaration=VertexPositionNormalTexture0Texture1Skin.vertexDeclaration; else if (position && normal && color && texcoord0 && blendWeight && blendIndex && tangent) vertexDeclaration=VertexPositionNormalColorTextureSkinTangent.vertexDeclaration; else if (position && normal && color && texcoord0 && blendWeight && blendIndex) vertexDeclaration=VertexPositionNormalColorTextureSkin.vertexDeclaration; else if (position && normal && tangent && binormal && texcoord0 && blendWeight && blendIndex) vertexDeclaration=VertexPositionNTBTextureSkin.vertexDeclaration; else if (position && normal && texcoord0 && blendWeight && blendIndex && tangent) vertexDeclaration=VertexPositionNormalTextureSkinTangent.vertexDeclaration; else if (position && normal && texcoord0 && blendWeight && blendIndex) vertexDeclaration=VertexPositionNormalTextureSkin.vertexDeclaration; else if (position && normal && color && blendWeight && blendIndex && tangent) vertexDeclaration=VertexPositionNormalColorSkinTangent.vertexDeclaration; else if (position && normal && color && blendWeight && blendIndex) vertexDeclaration=VertexPositionNormalColorSkin.vertexDeclaration; else if (position && normal && color && texcoord0 && texcoord1 && tangent) vertexDeclaration=VertexPositionNormalColorTexture0Texture1Tangent.vertexDeclaration; else if (position && normal && color && texcoord0 && texcoord1) vertexDeclaration=VertexPositionNormalColorTexture0Texture1.vertexDeclaration; else if (position && normal && texcoord0 && texcoord1 && tangent) vertexDeclaration=VertexPositionNormalTexture0Texture1Tangent.vertexDeclaration; else if (position && normal && texcoord0 && texcoord1) vertexDeclaration=VertexPositionNormalTexture0Texture1.vertexDeclaration; else if (position && normal && color && texcoord0 && tangent) vertexDeclaration=VertexPositionNormalColorTextureTangent.vertexDeclaration; else if (position && normal && texcoord0 && tangent && binormal) vertexDeclaration=VertexPositionNTBTexture.vertexDeclaration; else if (position && normal && color && texcoord0) vertexDeclaration=VertexPositionNormalColorTexture.vertexDeclaration; else if (position && normal && texcoord0 && tangent) vertexDeclaration=VertexPositionNormalTextureTangent.vertexDeclaration; else if (position && normal && texcoord0) vertexDeclaration=VertexPositionNormalTexture.vertexDeclaration; else if (position && normal && color && tangent) vertexDeclaration=VertexPositionNormalColorTangent.vertexDeclaration; else if (position && normal && color) vertexDeclaration=VertexPositionNormalColor.vertexDeclaration; return vertexDeclaration; } __getset(0,__proto,'mesh',function(){ return this._mesh; }); LoadModelV01._attrReg=new RegExp("(\\w+)|([:,;])","g"); return LoadModelV01; })() /** *@private *LoadModel 类用于模型加载。 */ //class laya.d3.loaders.LoadModelV02 var LoadModelV02=(function(){ function LoadModelV02(){} __class(LoadModelV02,'laya.d3.loaders.LoadModelV02'); LoadModelV02.parse=function(readData,version,mesh,materials,subMeshes,materialMap){ LoadModelV02._mesh=mesh; LoadModelV02._materials=materials; LoadModelV02._subMeshes=subMeshes; LoadModelV02._materialMap=materialMap; LoadModelV02._version=version; LoadModelV02._readData=readData; LoadModelV02.READ_DATA(); LoadModelV02.READ_BLOCK(); LoadModelV02.READ_STRINGS(); for (var i=0,n=LoadModelV02._BLOCK.count;i < n;i++){ LoadModelV02._readData.pos=LoadModelV02._BLOCK.blockStarts[i]; var index=LoadModelV02._readData.getUint16(); var blockName=LoadModelV02._strings[index]; var fn=LoadModelV02["READ_"+blockName]; if (fn==null) throw new Error("model file err,no this function:"+index+" "+blockName); else fn.call(); } LoadModelV02._strings.length=0; LoadModelV02._readData=null; LoadModelV02._version=null; LoadModelV02._mesh=null; LoadModelV02._materials=null; LoadModelV02._subMeshes=null; LoadModelV02._materialMap=null; } LoadModelV02._readString=function(){ return LoadModelV02._strings[LoadModelV02._readData.getUint16()]; } LoadModelV02.READ_DATA=function(){ LoadModelV02._DATA.offset=LoadModelV02._readData.getUint32(); LoadModelV02._DATA.size=LoadModelV02._readData.getUint32(); } LoadModelV02.READ_BLOCK=function(){ var count=LoadModelV02._BLOCK.count=LoadModelV02._readData.getUint16(); var blockStarts=LoadModelV02._BLOCK.blockStarts=[]; var blockLengths=LoadModelV02._BLOCK.blockLengths=[]; for (var i=0;i < count;i++){ blockStarts.push(LoadModelV02._readData.getUint32()); blockLengths.push(LoadModelV02._readData.getUint32()); } } LoadModelV02.READ_STRINGS=function(){ var offset=LoadModelV02._readData.getUint32(); var count=LoadModelV02._readData.getUint16(); var prePos=LoadModelV02._readData.pos; LoadModelV02._readData.pos=offset+LoadModelV02._DATA.offset; for (var i=0;i < count;i++) LoadModelV02._strings[i]=LoadModelV02._readData.readUTFString(); LoadModelV02._readData.pos=prePos; } LoadModelV02.READ_MATERIAL=function(){ var i=0,n=0; var clasName=LoadModelV02._readString(); var shaderName=LoadModelV02._readString(); var url=LoadModelV02._readString(); if (url!=="") LoadModelV02._materials.push(Loader.getRes(LoadModelV02._materialMap[url])); return true; } LoadModelV02.READ_MESH=function(){ var name=LoadModelV02._readString(); var arrayBuffer=LoadModelV02._readData.__getBuffer(); var i=0,n=0; var vertexBufferCount=LoadModelV02._readData.getInt16(); var offset=LoadModelV02._DATA.offset; for (i=0;i < vertexBufferCount;i++){ var vbStart=offset+LoadModelV02._readData.getUint32(); var vbLength=LoadModelV02._readData.getUint32(); var vbDatas=new Float32Array(arrayBuffer.slice(vbStart,vbStart+vbLength)); var bufferAttribute=LoadModelV02._readString(); var shaderAttributes=bufferAttribute.match(LoadModelV02._attrReg); var vertexDeclaration=LoadModelV02._getVertexDeclaration(shaderAttributes); var vertexBuffer=VertexBuffer3D.create(vertexDeclaration,(vbDatas.length *4)/ vertexDeclaration.vertexStride,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); vertexBuffer.setData(vbDatas); LoadModelV02._mesh._vertexBuffers.push(vertexBuffer); }; var ibStart=offset+LoadModelV02._readData.getUint32(); var ibLength=LoadModelV02._readData.getUint32(); var ibDatas=new Uint16Array(arrayBuffer.slice(ibStart,ibStart+ibLength)); var indexBuffer=IndexBuffer3D.create(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",ibLength / 2,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); indexBuffer.setData(ibDatas); LoadModelV02._mesh._indexBuffer=indexBuffer; var boneNames=LoadModelV02._mesh._boneNames=[]; var boneCount=LoadModelV02._readData.getUint16(); boneNames.length=boneCount; for (i=0;i < boneCount;i++) boneNames[i]=LoadModelV02._strings[LoadModelV02._readData.getUint16()]; var bindPoseStart=LoadModelV02._readData.getUint32(); var binPoseLength=LoadModelV02._readData.getUint32(); var bindPoseDatas=new Float32Array(arrayBuffer.slice(offset+bindPoseStart,offset+bindPoseStart+binPoseLength)); var inverseGlobalBindPoseStart=LoadModelV02._readData.getUint32(); var inverseGlobalBinPoseLength=LoadModelV02._readData.getUint32(); var invGloBindPoseDatas=new Float32Array(arrayBuffer.slice(offset+inverseGlobalBindPoseStart,offset+inverseGlobalBindPoseStart+inverseGlobalBinPoseLength)); LoadModelV02._mesh._inverseBindPoses=[]; for (i=0,n=invGloBindPoseDatas.length;i < n;i+=16){ var inverseGlobalBindPose=new Matrix4x4(invGloBindPoseDatas[i+0],invGloBindPoseDatas[i+1],invGloBindPoseDatas[i+2],invGloBindPoseDatas[i+3],invGloBindPoseDatas[i+4],invGloBindPoseDatas[i+5],invGloBindPoseDatas[i+6],invGloBindPoseDatas[i+7],invGloBindPoseDatas[i+8],invGloBindPoseDatas[i+9],invGloBindPoseDatas[i+10],invGloBindPoseDatas[i+11],invGloBindPoseDatas[i+12],invGloBindPoseDatas[i+13],invGloBindPoseDatas[i+14],invGloBindPoseDatas[i+15]); LoadModelV02._mesh._inverseBindPoses.push(inverseGlobalBindPose); } LoadModelV02._mesh._skinnedDatas=new Float32Array(invGloBindPoseDatas.length*16); return true; } LoadModelV02.READ_SUBMESH=function(){ var arrayBuffer=LoadModelV02._readData.__getBuffer(); var submesh=new SubMesh(LoadModelV02._mesh); var vbIndex=LoadModelV02._readData.getInt16(); var vbStart=LoadModelV02._readData.getUint32(); var vbLength=LoadModelV02._readData.getUint32(); submesh._vertexBuffer=LoadModelV02._mesh._vertexBuffers[vbIndex]; submesh._vertexStart=vbStart; submesh._vertexCount=vbLength; var ibStart=LoadModelV02._readData.getUint32(); var ibCount=LoadModelV02._readData.getUint32(); var indexBuffer=LoadModelV02._mesh._indexBuffer; submesh._indexBuffer=indexBuffer; submesh._indexStart=ibStart; submesh._indexCount=ibCount; submesh._indices=new Uint16Array(indexBuffer.getData().buffer,ibStart *2,ibCount); var offset=LoadModelV02._DATA.offset; var subIndexBufferStart=submesh._subIndexBufferStart; var subIndexBufferCount=submesh._subIndexBufferCount; var boneIndicesList=submesh._boneIndicesList; var drawCount=LoadModelV02._readData.getUint16(); subIndexBufferStart.length=drawCount; subIndexBufferCount.length=drawCount; boneIndicesList.length=drawCount; for (var i=0;i < drawCount;i++){ subIndexBufferStart[i]=LoadModelV02._readData.getUint32(); subIndexBufferCount[i]=LoadModelV02._readData.getUint32(); var boneDicofs=LoadModelV02._readData.getUint32(); var boneDicsize=LoadModelV02._readData.getUint32(); submesh._boneIndicesList[i]=new Uint8Array(arrayBuffer.slice(offset+boneDicofs,offset+boneDicofs+boneDicsize)); } LoadModelV02._subMeshes.push(submesh); return true; } LoadModelV02._getVertexDeclaration=function(shaderAttributes){ var position=false,normal=false,color=false,texcoord0=false,texcoord1=false,tangent=false,blendWeight=false,blendIndex=false; var binormal=false; for (var i=0;i < shaderAttributes.length;i++){ switch (shaderAttributes[i]){ case "POSITION": position=true; break ; case "NORMAL": normal=true; break ; case "COLOR": color=true; break ; case "UV": texcoord0=true; break ; case "UV1": texcoord1=true; break ; case "BLENDWEIGHT": blendWeight=true; break ; case "BLENDINDICES": blendIndex=true; break ; case "TANGENT": tangent=true; break ; case "BINORMAL": binormal=true; break ; } }; var vertexDeclaration; if (position && normal && color && texcoord0 && texcoord1 && blendWeight && blendIndex && tangent) vertexDeclaration=VertexPositionNormalColorTexture0Texture1SkinTangent.vertexDeclaration; else if (position && normal && color && texcoord0 && texcoord1 && blendWeight && blendIndex) vertexDeclaration=VertexPositionNormalColorTexture0Texture1Skin.vertexDeclaration; else if (position && normal && texcoord0 && texcoord1 && blendWeight && blendIndex && tangent) vertexDeclaration=VertexPositionNormalTexture0Texture1SkinTangent.vertexDeclaration; else if (position && normal && texcoord0 && texcoord1 && blendWeight && blendIndex) vertexDeclaration=VertexPositionNormalTexture0Texture1Skin.vertexDeclaration; else if (position && normal && color && texcoord0 && blendWeight && blendIndex && tangent) vertexDeclaration=VertexPositionNormalColorTextureSkinTangent.vertexDeclaration; else if (position && normal && color && texcoord0 && blendWeight && blendIndex) vertexDeclaration=VertexPositionNormalColorTextureSkin.vertexDeclaration; else if (position && normal && texcoord0 && blendWeight && blendIndex && tangent) vertexDeclaration=VertexPositionNormalTextureSkinTangent.vertexDeclaration; else if (position && normal && texcoord0 && blendWeight && blendIndex) vertexDeclaration=VertexPositionNormalTextureSkin.vertexDeclaration; else if (position && normal && color && blendWeight && blendIndex && tangent) vertexDeclaration=VertexPositionNormalColorSkinTangent.vertexDeclaration; else if (position && normal && color && blendWeight && blendIndex) vertexDeclaration=VertexPositionNormalColorSkin.vertexDeclaration; else if (position && normal && color && texcoord0 && texcoord1 && tangent) vertexDeclaration=VertexPositionNormalColorTexture0Texture1Tangent.vertexDeclaration; else if (position && normal && color && texcoord0 && texcoord1) vertexDeclaration=VertexPositionNormalColorTexture0Texture1.vertexDeclaration; else if (position && normal && texcoord0 && texcoord1 && tangent) vertexDeclaration=VertexPositionNormalTexture0Texture1Tangent.vertexDeclaration; else if (position && normal && texcoord0 && texcoord1) vertexDeclaration=VertexPositionNormalTexture0Texture1.vertexDeclaration; else if (position && normal && color && texcoord0 && tangent) vertexDeclaration=VertexPositionNormalColorTextureTangent.vertexDeclaration; else if (position && normal && texcoord0 && tangent && binormal) vertexDeclaration=VertexPositionNTBTexture.vertexDeclaration; else if (position && normal && color && texcoord0) vertexDeclaration=VertexPositionNormalColorTexture.vertexDeclaration; else if (position && normal && texcoord0 && tangent) vertexDeclaration=VertexPositionNormalTextureTangent.vertexDeclaration; else if (position && normal && texcoord0) vertexDeclaration=VertexPositionNormalTexture.vertexDeclaration; else if (position && normal && color && tangent) vertexDeclaration=VertexPositionNormalColorTangent.vertexDeclaration; else if (position && normal && color) vertexDeclaration=VertexPositionNormalColor.vertexDeclaration; return vertexDeclaration; } LoadModelV02._attrReg=new RegExp("(\\w+)|([:,;])","g"); LoadModelV02._strings=[]; LoadModelV02._readData=null; LoadModelV02._version=null; LoadModelV02._mesh=null; LoadModelV02._materials=null; LoadModelV02._subMeshes=null; LoadModelV02._materialMap=null; __static(LoadModelV02, ['_BLOCK',function(){return this._BLOCK={count:0};},'_DATA',function(){return this._DATA={offset:0,size:0};} ]); return LoadModelV02; })() /** *@private *LoadModel 类用于模型加载。 */ //class laya.d3.loaders.LoadModelV03 var LoadModelV03=(function(){ function LoadModelV03(){} __class(LoadModelV03,'laya.d3.loaders.LoadModelV03'); LoadModelV03.parse=function(readData,version,mesh,subMeshes,materialMap){ LoadModelV03._mesh=mesh; LoadModelV03._subMeshes=subMeshes; LoadModelV03._materialMap=materialMap; LoadModelV03._version=version; LoadModelV03._readData=readData; LoadModelV03.READ_DATA(); LoadModelV03.READ_BLOCK(); LoadModelV03.READ_STRINGS(); for (var i=0,n=LoadModelV03._BLOCK.count;i < n;i++){ LoadModelV03._readData.pos=LoadModelV03._BLOCK.blockStarts[i]; var index=LoadModelV03._readData.getUint16(); var blockName=LoadModelV03._strings[index]; var fn=LoadModelV03["READ_"+blockName]; if (fn==null) throw new Error("model file err,no this function:"+index+" "+blockName); else fn.call(); } LoadModelV03._strings.length=0; LoadModelV03._readData=null; LoadModelV03._version=null; LoadModelV03._mesh=null; LoadModelV03._subMeshes=null; LoadModelV03._materialMap=null; } LoadModelV03._readString=function(){ return LoadModelV03._strings[LoadModelV03._readData.getUint16()]; } LoadModelV03.READ_DATA=function(){ LoadModelV03._DATA.offset=LoadModelV03._readData.getUint32(); LoadModelV03._DATA.size=LoadModelV03._readData.getUint32(); } LoadModelV03.READ_BLOCK=function(){ var count=LoadModelV03._BLOCK.count=LoadModelV03._readData.getUint16(); var blockStarts=LoadModelV03._BLOCK.blockStarts=[]; var blockLengths=LoadModelV03._BLOCK.blockLengths=[]; for (var i=0;i < count;i++){ blockStarts.push(LoadModelV03._readData.getUint32()); blockLengths.push(LoadModelV03._readData.getUint32()); } } LoadModelV03.READ_STRINGS=function(){ var offset=LoadModelV03._readData.getUint32(); var count=LoadModelV03._readData.getUint16(); var prePos=LoadModelV03._readData.pos; LoadModelV03._readData.pos=offset+LoadModelV03._DATA.offset; for (var i=0;i < count;i++) LoadModelV03._strings[i]=LoadModelV03._readData.readUTFString(); LoadModelV03._readData.pos=prePos; } LoadModelV03.READ_MESH=function(){ var name=LoadModelV03._readString(); var arrayBuffer=LoadModelV03._readData.__getBuffer(); var i=0,n=0; var vertexBufferCount=LoadModelV03._readData.getInt16(); var offset=LoadModelV03._DATA.offset; for (i=0;i < vertexBufferCount;i++){ var vbStart=offset+LoadModelV03._readData.getUint32(); var vbLength=LoadModelV03._readData.getUint32(); var vbDatas=new Float32Array(arrayBuffer.slice(vbStart,vbStart+vbLength)); var bufferAttribute=LoadModelV03._readString(); var vertexDeclaration; switch(LoadModelV03._version){ case "LAYAMODEL:03": vertexDeclaration=LoadModelV03._vertexDeclarationMap_Discard[bufferAttribute]; break ; case "LAYAMODEL:0301": vertexDeclaration=LoadModelV03._vertexDeclarationMap[bufferAttribute]; break ; default : throw new Error("LoadModelV03: unknown version."); } if (!vertexDeclaration) throw new Error("LoadModelV03: unknown vertexDeclaration."); var vertexBuffer=VertexBuffer3D.create(vertexDeclaration,(vbDatas.length *4)/ vertexDeclaration.vertexStride,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); vertexBuffer.setData(vbDatas); LoadModelV03._mesh._vertexBuffers.push(vertexBuffer); }; var ibStart=offset+LoadModelV03._readData.getUint32(); var ibLength=LoadModelV03._readData.getUint32(); var ibDatas=new Uint16Array(arrayBuffer.slice(ibStart,ibStart+ibLength)); var indexBuffer=IndexBuffer3D.create(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",ibLength / 2,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); indexBuffer.setData(ibDatas); LoadModelV03._mesh._indexBuffer=indexBuffer; var boneNames=LoadModelV03._mesh._boneNames=[]; var boneCount=LoadModelV03._readData.getUint16(); boneNames.length=boneCount; for (i=0;i < boneCount;i++) boneNames[i]=LoadModelV03._strings[LoadModelV03._readData.getUint16()]; LoadModelV03._readData.pos+=8; var inverseGlobalBindPoseStart=LoadModelV03._readData.getUint32(); var inverseGlobalBinPoseLength=LoadModelV03._readData.getUint32(); var invGloBindPoseDatas=new Float32Array(arrayBuffer.slice(offset+inverseGlobalBindPoseStart,offset+inverseGlobalBindPoseStart+inverseGlobalBinPoseLength)); LoadModelV03._mesh._inverseBindPoses=[]; for (i=0,n=invGloBindPoseDatas.length;i < n;i+=16){ var inverseGlobalBindPose=new Matrix4x4(invGloBindPoseDatas[i+0],invGloBindPoseDatas[i+1],invGloBindPoseDatas[i+2],invGloBindPoseDatas[i+3],invGloBindPoseDatas[i+4],invGloBindPoseDatas[i+5],invGloBindPoseDatas[i+6],invGloBindPoseDatas[i+7],invGloBindPoseDatas[i+8],invGloBindPoseDatas[i+9],invGloBindPoseDatas[i+10],invGloBindPoseDatas[i+11],invGloBindPoseDatas[i+12],invGloBindPoseDatas[i+13],invGloBindPoseDatas[i+14],invGloBindPoseDatas[i+15]); LoadModelV03._mesh._inverseBindPoses.push(inverseGlobalBindPose); } LoadModelV03._mesh._skinnedDatas=new Float32Array(invGloBindPoseDatas.length*16); return true; } LoadModelV03.READ_SUBMESH=function(){ var arrayBuffer=LoadModelV03._readData.__getBuffer(); var submesh=new SubMesh(LoadModelV03._mesh); var vbIndex=LoadModelV03._readData.getInt16(); var vbStart=LoadModelV03._readData.getUint32(); var vbLength=LoadModelV03._readData.getUint32(); submesh._vertexBuffer=LoadModelV03._mesh._vertexBuffers[vbIndex]; submesh._vertexStart=vbStart; submesh._vertexCount=vbLength; var ibStart=LoadModelV03._readData.getUint32(); var ibCount=LoadModelV03._readData.getUint32(); var indexBuffer=LoadModelV03._mesh._indexBuffer; submesh._indexBuffer=indexBuffer; submesh._indexStart=ibStart; submesh._indexCount=ibCount; submesh._indices=new Uint16Array(indexBuffer.getData().buffer,ibStart *2,ibCount); var offset=LoadModelV03._DATA.offset; var subIndexBufferStart=submesh._subIndexBufferStart; var subIndexBufferCount=submesh._subIndexBufferCount; var boneIndicesList=submesh._boneIndicesList; var drawCount=LoadModelV03._readData.getUint16(); subIndexBufferStart.length=drawCount; subIndexBufferCount.length=drawCount; boneIndicesList.length=drawCount; for (var i=0;i < drawCount;i++){ subIndexBufferStart[i]=LoadModelV03._readData.getUint32(); subIndexBufferCount[i]=LoadModelV03._readData.getUint32(); var boneDicofs=LoadModelV03._readData.getUint32(); var boneDicsize=LoadModelV03._readData.getUint32(); boneIndicesList[i]=new Uint8Array(arrayBuffer.slice(offset+boneDicofs,offset+boneDicofs+boneDicsize)); } LoadModelV03._subMeshes.push(submesh); return true; } LoadModelV03._strings=[]; LoadModelV03._readData=null; LoadModelV03._version=null; LoadModelV03._mesh=null; LoadModelV03._subMeshes=null; LoadModelV03._materialMap=null; __static(LoadModelV03, ['_vertexDeclarationMap_Discard',function(){return this._vertexDeclarationMap_Discard={ "POSITION,NORMAL,COLOR,UV,UV1,BLENDWEIGHT,BLENDINDICES,TANGENT":VertexPositionNormalColorTexture0Texture1SkinTangent.vertexDeclaration, "POSITION,NORMAL,COLOR,UV,UV1,BLENDWEIGHT,BLENDINDICES":VertexPositionNormalColorTexture0Texture1Skin.vertexDeclaration, "POSITION,NORMAL,TANGENT,BINORMAL,UV,UV1,BLENDWEIGHT,BLENDINDICES,":VertexPositionNTBTexture0Texture1Skin.vertexDeclaration, "POSITION,NORMAL,UV,UV1,BLENDWEIGHT,BLENDINDICES,TANGENT":VertexPositionNormalTexture0Texture1SkinTangent.vertexDeclaration, "POSITION,NORMAL,UV,UV1,BLENDWEIGHT,BLENDINDICES":VertexPositionNormalTexture0Texture1Skin.vertexDeclaration, "POSITION,NORMAL,COLOR,UV,BLENDWEIGHT,BLENDINDICES,TANGENT":VertexPositionNormalColorTextureSkinTangent.vertexDeclaration, "POSITION,NORMAL,COLOR,UV,BLENDWEIGHT,BLENDINDICES":VertexPositionNormalColorTextureSkin.vertexDeclaration, "POSITION,NORMAL,UV,BLENDWEIGHT,BLENDINDICES,TANGENT":VertexPositionNormalTextureSkinTangent.vertexDeclaration, "POSITION,NORMAL,UV,BLENDWEIGHT,BLENDINDICES":VertexPositionNormalTextureSkin.vertexDeclaration, "POSITION,NORMAL,COLOR,BLENDWEIGHT,BLENDINDICES,TANGENT":VertexPositionNormalColorSkinTangent.vertexDeclaration, "POSITION,NORMAL,COLOR,BLENDWEIGHT,BLENDINDICES":VertexPositionNormalColorSkin.vertexDeclaration, "POSITION,NORMAL,COLOR,UV,UV1,TANGENT":VertexPositionNormalColorTexture0Texture1Tangent.vertexDeclaration, "POSITION,NORMAL,COLOR,UV,UV1":VertexPositionNormalColorTexture0Texture1.vertexDeclaration, "POSITION,NORMAL,UV,UV1,TANGENT":VertexPositionNormalTexture0Texture1Tangent.vertexDeclaration, "POSITION,NORMAL,UV,UV1":VertexPositionNormalTexture0Texture1.vertexDeclaration, "POSITION,NORMAL,COLOR,UV,TANGENT":VertexPositionNormalColorTextureTangent.vertexDeclaration, "POSITION,NORMAL,UV,TANGENT,BINORMAL":VertexPositionNTBTexture.vertexDeclaration, "POSITION,NORMAL,COLOR,UV":VertexPositionNormalColorTexture.vertexDeclaration, "POSITION,NORMAL,UV,TANGENT":VertexPositionNormalTextureTangent.vertexDeclaration, "POSITION,NORMAL,UV":VertexPositionNormalTexture.vertexDeclaration, "POSITION,NORMAL,COLOR,TANGENT":VertexPositionNormalColorTangent.vertexDeclaration, "POSITION,NORMAL,COLOR":VertexPositionNormalColor.vertexDeclaration, "POSITION,NORMAL,TANGENT":VertexPositionNormalTangent.vertexDeclaration, "POSITION,NORMAL":VertexPositionNormal.vertexDeclaration, "POSITION,UV":VertexPositionTexture0.vertexDeclaration, "POSITION":VertexPosition.vertexDeclaration};},'_vertexDeclarationMap',function(){return this._vertexDeclarationMap={ "POSITION,NORMAL,COLOR,UV,UV1,BLENDWEIGHT,BLENDINDICES,TANGENT":VertexPositionNormalColorTexture0Texture1SkinSTangent.vertexDeclaration, "POSITION,NORMAL,COLOR,UV,UV1,BLENDWEIGHT,BLENDINDICES":VertexPositionNormalColorTexture0Texture1Skin.vertexDeclaration, "POSITION,NORMAL,TANGENT,BINORMAL,UV,UV1,BLENDWEIGHT,BLENDINDICES,":VertexPositionNTBTexture0Texture1Skin.vertexDeclaration, "POSITION,NORMAL,UV,UV1,BLENDWEIGHT,BLENDINDICES,TANGENT":VertexPositionNormalTexture0Texture1SkinSTangent.vertexDeclaration, "POSITION,NORMAL,UV,UV1,BLENDWEIGHT,BLENDINDICES":VertexPositionNormalTexture0Texture1Skin.vertexDeclaration, "POSITION,NORMAL,COLOR,UV,BLENDWEIGHT,BLENDINDICES,TANGENT":VertexPositionNormalColorTextureSkinSTangent.vertexDeclaration, "POSITION,NORMAL,COLOR,UV,BLENDWEIGHT,BLENDINDICES":VertexPositionNormalColorTextureSkin.vertexDeclaration, "POSITION,NORMAL,UV,BLENDWEIGHT,BLENDINDICES,TANGENT":VertexPositionNormalTextureSkinSTangent.vertexDeclaration, "POSITION,NORMAL,UV,BLENDWEIGHT,BLENDINDICES":VertexPositionNormalTextureSkin.vertexDeclaration, "POSITION,NORMAL,COLOR,BLENDWEIGHT,BLENDINDICES,TANGENT":VertexPositionNormalColorSkinSTangent.vertexDeclaration, "POSITION,NORMAL,COLOR,BLENDWEIGHT,BLENDINDICES":VertexPositionNormalColorSkin.vertexDeclaration, "POSITION,NORMAL,COLOR,UV,UV1,TANGENT":VertexPositionNormalColorTexture0Texture1STangent.vertexDeclaration, "POSITION,NORMAL,COLOR,UV,UV1":VertexPositionNormalColorTexture0Texture1.vertexDeclaration, "POSITION,NORMAL,UV,UV1,TANGENT":VertexPositionNormalTexture0Texture1STangent.vertexDeclaration, "POSITION,NORMAL,UV,UV1":VertexPositionNormalTexture0Texture1.vertexDeclaration, "POSITION,NORMAL,COLOR,UV,TANGENT":VertexPositionNormalColorTextureSTangent.vertexDeclaration, "POSITION,NORMAL,UV,TANGENT,BINORMAL":VertexPositionNTBTexture.vertexDeclaration, "POSITION,NORMAL,COLOR,UV":VertexPositionNormalColorTexture.vertexDeclaration, "POSITION,NORMAL,UV,TANGENT":VertexPositionNormalTextureSTangent.vertexDeclaration, "POSITION,NORMAL,UV":VertexPositionNormalTexture.vertexDeclaration, "POSITION,NORMAL,COLOR,TANGENT":VertexPositionNormalColorSTangent.vertexDeclaration, "POSITION,NORMAL,COLOR":VertexPositionNormalColor.vertexDeclaration, "POSITION,NORMAL,TANGENT":VertexPositionNormalSTangent.vertexDeclaration, "POSITION,NORMAL":VertexPositionNormal.vertexDeclaration, "POSITION,UV":VertexPositionTexture0.vertexDeclaration, "POSITION":VertexPosition.vertexDeclaration};},'_BLOCK',function(){return this._BLOCK={count:0};},'_DATA',function(){return this._DATA={offset:0,size:0};} ]); return LoadModelV03; })() /** *... *@author ... */ //class laya.d3.loaders.MeshReader var MeshReader=(function(){ function MeshReader(){} __class(MeshReader,'laya.d3.loaders.MeshReader'); MeshReader.read=function(data,mesh,materials,subMeshes,materialMap){ var readData=new Byte(data); readData.pos=0; var version=readData.readUTFString(); switch (version){ case "LAYAMODEL:01": case "LAYASKINANI:01": MeshReader._readVersion01(readData,version,mesh,materials,subMeshes,materialMap); break ; case "LAYAMODEL:02": LoadModelV02.parse(readData,version,mesh,materials,subMeshes,materialMap); break ; case "LAYAMODEL:03": case "LAYAMODEL:0301": LoadModelV03.parse(readData,version,mesh,subMeshes,materialMap); break ; default : throw new Error("MeshReader: unknown mesh version."); } mesh._setSubMeshes(subMeshes); } MeshReader._readVersion01=function(readData,version,mesh,materials,subMeshes,materialMap){ new LoadModelV01(readData,version,mesh,materials,subMeshes,materialMap); } return MeshReader; })() /** *BoundBox 类用于创建包围盒。 */ //class laya.d3.math.BoundBox var BoundBox=(function(){ function BoundBox(min,max){ /**最小顶点。*/ this.min=null; /**最大顶点。*/ this.max=null; this.min=min; this.max=max; } __class(BoundBox,'laya.d3.math.BoundBox'); var __proto=BoundBox.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *获取包围盒的8个角顶点。 *@param corners 返回顶点的输出队列。 */ __proto.getCorners=function(corners){ corners.length=8; var mine=this.min.elements; var maxe=this.max.elements; var minX=mine[0]; var minY=mine[1]; var minZ=mine[2]; var maxX=maxe[0]; var maxY=maxe[1]; var maxZ=maxe[2]; corners[0]=new Vector3(minX,maxY,maxZ); corners[1]=new Vector3(maxX,maxY,maxZ); corners[2]=new Vector3(maxX,minY,maxZ); corners[3]=new Vector3(minX,minY,maxZ); corners[4]=new Vector3(minX,maxY,minZ); corners[5]=new Vector3(maxX,maxY,minZ); corners[6]=new Vector3(maxX,minY,minZ); corners[7]=new Vector3(minX,minY,minZ); } __proto.toDefault=function(){ this.min.toDefault(); this.max.toDefault(); } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var dest=destObject; this.min.cloneTo(dest.min); this.max.cloneTo(dest.max); } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var dest=/*__JS__ */new this.constructor(new Vector3(),new Vector3()); this.cloneTo(dest); return dest; } BoundBox.createfromPoints=function(points,out){ if (points==null) throw new Error("points"); var min=out.min; var max=out.max; var minE=min.elements; minE[0]=Number.MAX_VALUE; minE[1]=Number.MAX_VALUE; minE[2]=Number.MAX_VALUE; var maxE=max.elements; maxE[0]=-Number.MAX_VALUE; maxE[1]=-Number.MAX_VALUE; maxE[2]=-Number.MAX_VALUE; for (var i=0,n=points.length;i < n;++i){ Vector3.min(min,points[i],min); Vector3.max(max,points[i],max); } } BoundBox.merge=function(box1,box2,out){ Vector3.min(box1.min,box2.min,out.min); Vector3.max(box1.max,box2.max,out.max); } return BoundBox; })() /** *BoundFrustum 类用于创建锥截体。 */ //class laya.d3.math.BoundFrustum var BoundFrustum=(function(){ function BoundFrustum(matrix){ /**4x4矩阵*/ this._matrix=null; /**近平面*/ this._near=null; /**远平面*/ this._far=null; /**左平面*/ this._left=null; /**右平面*/ this._right=null; /**顶平面*/ this._top=null; /**底平面*/ this._bottom=null; this._matrix=matrix; this._near=new Plane(new Vector3()); this._far=new Plane(new Vector3()); this._left=new Plane(new Vector3()); this._right=new Plane(new Vector3()); this._top=new Plane(new Vector3()); this._bottom=new Plane(new Vector3()); BoundFrustum._getPlanesFromMatrix(this._matrix,this._near,this._far,this._left,this._right,this._top,this._bottom); } __class(BoundFrustum,'laya.d3.math.BoundFrustum'); var __proto=BoundFrustum.prototype; /** *判断是否与其他锥截体相等。 *@param other 锥截体。 */ __proto.equalsBoundFrustum=function(other){ return this._matrix.equalsOtherMatrix(other.matrix) } /** *判断是否与其他对象相等。 *@param obj 对象。 */ __proto.equalsObj=function(obj){ if ((obj instanceof laya.d3.math.BoundFrustum )){ var bf=obj; return this.equalsBoundFrustum(bf); } return false; } /** *获取锥截体的任意一平面。 *0:近平面 *1:远平面 *2:左平面 *3:右平面 *4:顶平面 *5:底平面 *@param index 索引。 */ __proto.getPlane=function(index){ switch (index){ case 0: return this._near; case 1: return this._far; case 2: return this._left; case 3: return this._right; case 4: return this._top; case 5: return this._bottom; default : return null; } } /** *锥截体的8个顶点。 *@param corners 返回顶点的输出队列。 */ __proto.getCorners=function(corners){ BoundFrustum._get3PlaneInterPoint(this._near,this._bottom,this._right).cloneTo(corners[0]); BoundFrustum._get3PlaneInterPoint(this._near,this._top,this._right).cloneTo(corners[1]); BoundFrustum._get3PlaneInterPoint(this._near,this._top,this._left).cloneTo(corners[2]); BoundFrustum._get3PlaneInterPoint(this._near,this._bottom,this._left).cloneTo(corners[3]); BoundFrustum._get3PlaneInterPoint(this._far,this._bottom,this._right).cloneTo(corners[4]); BoundFrustum._get3PlaneInterPoint(this._far,this._top,this._right).cloneTo(corners[5]); BoundFrustum._get3PlaneInterPoint(this._far,this._top,this._left).cloneTo(corners[6]); BoundFrustum._get3PlaneInterPoint(this._far,this._bottom,this._left).cloneTo(corners[7]); } /** *与点的位置关系。返回-1,包涵;0,相交;1,不相交 *@param point 点。 */ __proto.containsPoint=function(point){ var result=Plane.PlaneIntersectionType_Front; var planeResult=Plane.PlaneIntersectionType_Front; for (var i=0;i < 6;i++){ switch (i){ case 0: planeResult=Collision.intersectsPlaneAndPoint(this._near,point); break ; case 1: planeResult=Collision.intersectsPlaneAndPoint(this._far,point); break ; case 2: planeResult=Collision.intersectsPlaneAndPoint(this._left,point); break ; case 3: planeResult=Collision.intersectsPlaneAndPoint(this._right,point); break ; case 4: planeResult=Collision.intersectsPlaneAndPoint(this._top,point); break ; case 5: planeResult=Collision.intersectsPlaneAndPoint(this._bottom,point); break ; } switch (planeResult){ case Plane.PlaneIntersectionType_Back: return /*laya.d3.math.ContainmentType.Disjoint*/0; case Plane.PlaneIntersectionType_Intersecting: result=Plane.PlaneIntersectionType_Intersecting; break ; } } switch (result){ case Plane.PlaneIntersectionType_Intersecting: return /*laya.d3.math.ContainmentType.Intersects*/2; default : return /*laya.d3.math.ContainmentType.Contains*/1; } } /** *与包围盒的位置关系。返回-1,包涵;0,相交;1,不相交 *@param box 包围盒。 */ __proto.containsBoundBox=function(box){ var p=BoundFrustum._tempV30,n=BoundFrustum._tempV31; var plane; var result=/*laya.d3.math.ContainmentType.Contains*/1; for (var i=0;i < 6;i++){ plane=this.getPlane(i); this._getBoxToPlanePVertexNVertex(box,plane.normal,p,n); if (Collision.intersectsPlaneAndPoint(plane,p)===Plane.PlaneIntersectionType_Back) return /*laya.d3.math.ContainmentType.Disjoint*/0; if (Collision.intersectsPlaneAndPoint(plane,n)===Plane.PlaneIntersectionType_Back) result=/*laya.d3.math.ContainmentType.Intersects*/2; } return result; } /** *与包围球的位置关系。返回-1,包涵;0,相交;1,不相交 *@param sphere 包围球。 */ __proto.containsBoundSphere=function(sphere){ var result=Plane.PlaneIntersectionType_Front; var planeResult=Plane.PlaneIntersectionType_Front; for (var i=0;i < 6;i++){ switch (i){ case 0: planeResult=Collision.intersectsPlaneAndSphere(this._near,sphere); break ; case 1: planeResult=Collision.intersectsPlaneAndSphere(this._far,sphere); break ; case 2: planeResult=Collision.intersectsPlaneAndSphere(this._left,sphere); break ; case 3: planeResult=Collision.intersectsPlaneAndSphere(this._right,sphere); break ; case 4: planeResult=Collision.intersectsPlaneAndSphere(this._top,sphere); break ; case 5: planeResult=Collision.intersectsPlaneAndSphere(this._bottom,sphere); break ; } switch (planeResult){ case Plane.PlaneIntersectionType_Back: return /*laya.d3.math.ContainmentType.Disjoint*/0; case Plane.PlaneIntersectionType_Intersecting: result=Plane.PlaneIntersectionType_Intersecting; break ; } } switch (result){ case Plane.PlaneIntersectionType_Intersecting: return /*laya.d3.math.ContainmentType.Intersects*/2; default : return /*laya.d3.math.ContainmentType.Contains*/1; } } /** *@private */ __proto._getBoxToPlanePVertexNVertex=function(box,planeNormal,outP,outN){ var boxMin=box.min; var boxMinE=boxMin.elements; var boxMax=box.max; var boxMaxE=boxMax.elements; var planeNorE=planeNormal.elements; var planeNorEX=planeNorE[0]; var planeNorEY=planeNorE[1]; var planeNorEZ=planeNorE[2]; boxMin.cloneTo(outP);; var outPE=outP.elements; if (planeNorEX >=0) outPE[0]=boxMaxE[0]; if (planeNorEY >=0) outPE[1]=boxMaxE[1]; if (planeNorEZ >=0) outPE[2]=boxMaxE[2]; boxMax.cloneTo(outN); var outNE=outN.elements; if (planeNorEX >=0) outNE[0]=boxMinE[0]; if (planeNorEY >=0) outNE[1]=boxMinE[1]; if (planeNorEZ >=0) outNE[2]=boxMinE[2]; } /** *获取顶平面。 *@return 顶平面。 */ __getset(0,__proto,'top',function(){ return this._top; }); /** *设置描述矩阵。 *@param matrix 描述矩阵。 */ /** *获取描述矩阵。 *@return 描述矩阵。 */ __getset(0,__proto,'matrix',function(){ return this._matrix; },function(matrix){ this._matrix=matrix; BoundFrustum._getPlanesFromMatrix(this._matrix,this._near,this._far,this._left,this._right,this._top,this._bottom); }); /** *获取近平面。 *@return 近平面。 */ __getset(0,__proto,'near',function(){ return this._near; }); /** *获取远平面。 *@return 远平面。 */ __getset(0,__proto,'far',function(){ return this._far; }); /** *获取左平面。 *@return 左平面。 */ __getset(0,__proto,'left',function(){ return this._left; }); /** *获取右平面。 *@return 右平面。 */ __getset(0,__proto,'right',function(){ return this._right; }); /** *获取底平面。 *@return 底平面。 */ __getset(0,__proto,'bottom',function(){ return this._bottom; }); BoundFrustum._getPlanesFromMatrix=function(m,np,fp,lp,rp,tp,bp){ var matrixE=m.elements; var m11=matrixE[0]; var m12=matrixE[1]; var m13=matrixE[2]; var m14=matrixE[3]; var m21=matrixE[4]; var m22=matrixE[5]; var m23=matrixE[6]; var m24=matrixE[7]; var m31=matrixE[8]; var m32=matrixE[9]; var m33=matrixE[10]; var m34=matrixE[11]; var m41=matrixE[12]; var m42=matrixE[13]; var m43=matrixE[14]; var m44=matrixE[15]; var nearNorE=np.normal.elements; nearNorE[0]=m14+m13; nearNorE[1]=m24+m23; nearNorE[2]=m34+m33; np.distance=m44+m43; np.normalize(); var farNorE=fp.normal.elements; farNorE[0]=m14-m13; farNorE[1]=m24-m23; farNorE[2]=m34-m33; fp.distance=m44-m43; fp.normalize(); var leftNorE=lp.normal.elements; leftNorE[0]=m14+m11; leftNorE[1]=m24+m21; leftNorE[2]=m34+m31; lp.distance=m44+m41; lp.normalize(); var rightNorE=rp.normal.elements; rightNorE[0]=m14-m11; rightNorE[1]=m24-m21; rightNorE[2]=m34-m31; rp.distance=m44-m41; rp.normalize(); var topNorE=tp.normal.elements; topNorE[0]=m14-m12; topNorE[1]=m24-m22; topNorE[2]=m34-m32; tp.distance=m44-m42; tp.normalize(); var bottomNorE=bp.normal.elements; bottomNorE[0]=m14+m12; bottomNorE[1]=m24+m22; bottomNorE[2]=m34+m32; bp.distance=m44+m42; bp.normalize(); } BoundFrustum._get3PlaneInterPoint=function(p1,p2,p3){ var p1Nor=p1.normal; var p2Nor=p2.normal; var p3Nor=p3.normal; Vector3.cross(p2Nor,p3Nor,BoundFrustum._tempV30); Vector3.cross(p3Nor,p1Nor,BoundFrustum._tempV31); Vector3.cross(p1Nor,p2Nor,BoundFrustum._tempV32); var a=Vector3.dot(p1Nor,BoundFrustum._tempV30); var b=Vector3.dot(p2Nor,BoundFrustum._tempV31); var c=Vector3.dot(p3Nor,BoundFrustum._tempV32); Vector3.scale(BoundFrustum._tempV30,-p1.distance / a,BoundFrustum._tempV33); Vector3.scale(BoundFrustum._tempV31,-p2.distance / b,BoundFrustum._tempV34); Vector3.scale(BoundFrustum._tempV32,-p3.distance / c,BoundFrustum._tempV35); Vector3.add(BoundFrustum._tempV33,BoundFrustum._tempV34,BoundFrustum._tempV36); Vector3.add(BoundFrustum._tempV35,BoundFrustum._tempV36,BoundFrustum._tempV37); var v=BoundFrustum._tempV37; return v; } __static(BoundFrustum, ['_tempV30',function(){return this._tempV30=new Vector3();},'_tempV31',function(){return this._tempV31=new Vector3();},'_tempV32',function(){return this._tempV32=new Vector3();},'_tempV33',function(){return this._tempV33=new Vector3();},'_tempV34',function(){return this._tempV34=new Vector3();},'_tempV35',function(){return this._tempV35=new Vector3();},'_tempV36',function(){return this._tempV36=new Vector3();},'_tempV37',function(){return this._tempV37=new Vector3();} ]); return BoundFrustum; })() /** *BoundSphere 类用于创建包围球。 */ //class laya.d3.math.BoundSphere var BoundSphere=(function(){ function BoundSphere(center,radius){ /**包围球的中心。*/ this.center=null; /**包围球的半径。*/ this.radius=NaN; this.center=center; this.radius=radius; } __class(BoundSphere,'laya.d3.math.BoundSphere'); var __proto=BoundSphere.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) __proto.toDefault=function(){ this.center.toDefault(); this.radius=0; } /** *判断射线是否与碰撞球交叉,并返回交叉距离。 *@param ray 射线。 *@return 距离交叉点的距离,-1表示不交叉。 */ __proto.intersectsRayDistance=function(ray){ return Collision.intersectsRayAndSphereRD(ray,this); } /** *判断射线是否与碰撞球交叉,并返回交叉点。 *@param ray 射线。 *@param outPoint 交叉点。 *@return 距离交叉点的距离,-1表示不交叉。 */ __proto.intersectsRayPoint=function(ray,outPoint){ return Collision.intersectsRayAndSphereRP(ray,this,outPoint); } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var dest=destObject; this.center.cloneTo(dest.center); dest.radius=this.radius; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var dest=/*__JS__ */new this.constructor(new Vector3(),new Vector3()); this.cloneTo(dest); return dest; } BoundSphere.createFromSubPoints=function(points,start,count,out){ if (points==null){ throw new Error("points"); } if (start < 0 || start >=points.length){ throw new Error("start"+start+"Must be in the range [0, "+(points.length-1)+"]"); } if (count < 0 || (start+count)> points.length){ throw new Error("count"+count+"Must be in the range <= "+points.length+"}"); }; var upperEnd=start+count; var center=BoundSphere._tempVector3; center.elements[0]=0; center.elements[1]=0; center.elements[2]=0; for (var i=start;i < upperEnd;++i){ Vector3.add(points[i],center,center); }; var outCenter=out.center; Vector3.scale(center,1 / count,outCenter); var radius=0.0; for (i=start;i < upperEnd;++i){ var distance=Vector3.distanceSquared(outCenter,points[i]); if (distance > radius) radius=distance; } out.radius=Math.sqrt(radius); } BoundSphere.createfromPoints=function(points,out){ if (points==null){ throw new Error("points"); } BoundSphere.createFromSubPoints(points,0,points.length,out); } __static(BoundSphere, ['_tempVector3',function(){return this._tempVector3=new Vector3();} ]); return BoundSphere; })() /** *Collision 类用于检测碰撞。 */ //class laya.d3.math.Collision var Collision=(function(){ /** *创建一个 Collision 实例。 */ function Collision(){} __class(Collision,'laya.d3.math.Collision'); Collision.distancePlaneToPoint=function(plane,point){ var dot=Vector3.dot(plane.normal,point); return dot-plane.distance; } Collision.distanceBoxToPoint=function(box,point){ var boxMine=box.min.elements; var boxMineX=boxMine[0]; var boxMineY=boxMine[1]; var boxMineZ=boxMine[2]; var boxMaxe=box.max.elements; var boxMaxeX=boxMaxe[0]; var boxMaxeY=boxMaxe[1]; var boxMaxeZ=boxMaxe[2]; var pointe=point.elements; var pointeX=pointe[0]; var pointeY=pointe[1]; var pointeZ=pointe[2]; var distance=0; if (pointeX < boxMineX) distance+=(boxMineX-pointeX)*(boxMineX-pointeX); if (pointeX > boxMaxeX) distance+=(boxMaxeX-pointeX)*(boxMaxeX-pointeX); if (pointeY < boxMineY) distance+=(boxMineY-pointeY)*(boxMineY-pointeY); if (pointeY > boxMaxeY) distance+=(boxMaxeY-pointeY)*(boxMaxeY-pointeY); if (pointeZ < boxMineZ) distance+=(boxMineZ-pointeZ)*(boxMineZ-pointeZ); if (pointeZ > boxMaxeZ) distance+=(boxMaxeZ-pointeZ)*(boxMaxeZ-pointeZ); return Math.sqrt(distance); } Collision.distanceBoxToBox=function(box1,box2){ var box1Mine=box1.min.elements; var box1MineX=box1Mine[0]; var box1MineY=box1Mine[1]; var box1MineZ=box1Mine[2]; var box1Maxe=box1.max.elements; var box1MaxeX=box1Maxe[0]; var box1MaxeY=box1Maxe[1]; var box1MaxeZ=box1Maxe[2]; var box2Mine=box2.min.elements; var box2MineX=box2Mine[0]; var box2MineY=box2Mine[1]; var box2MineZ=box2Mine[2]; var box2Maxe=box2.max.elements; var box2MaxeX=box2Maxe[0]; var box2MaxeY=box2Maxe[1]; var box2MaxeZ=box2Maxe[2]; var distance=0; var delta=NaN; if (box1MineX > box2MaxeX){ delta=box1MineX-box2MaxeX; distance+=delta *delta; }else if (box2MineX > box1MaxeX){ delta=box2MineX-box1MaxeX; distance+=delta *delta; } if (box1MineY > box2MaxeY){ delta=box1MineY-box2MaxeY; distance+=delta *delta; }else if (box2MineY > box1MaxeY){ delta=box2MineY-box1MaxeY; distance+=delta *delta; } if (box1MineZ > box2MaxeZ){ delta=box1MineZ-box2MaxeZ; distance+=delta *delta; }else if (box2MineZ > box1MaxeZ){ delta=box2MineZ-box1MaxeZ; distance+=delta *delta; } return Math.sqrt(distance); } Collision.distanceSphereToPoint=function(sphere,point){ var distance=Math.sqrt(Vector3.distanceSquared(sphere.center,point)); distance-=sphere.radius; return Math.max(distance,0); } Collision.distanceSphereToSphere=function(sphere1,sphere2){ var distance=Math.sqrt(Vector3.distanceSquared(sphere1.center,sphere2.center)); distance-=sphere1.radius+sphere2.radius; return Math.max(distance,0); } Collision.intersectsRayAndTriangleRD=function(ray,vertex1,vertex2,vertex3,out){ var rayO=ray.origin; var rayOe=rayO.elements; var rayOeX=rayOe[0]; var rayOeY=rayOe[1]; var rayOeZ=rayOe[2]; var rayD=ray.direction; var rayDe=rayD.elements; var rayDeX=rayDe[0]; var rayDeY=rayDe[1]; var rayDeZ=rayDe[2]; var v1e=vertex1.elements; var v1eX=v1e[0]; var v1eY=v1e[1]; var v1eZ=v1e[2]; var v2e=vertex2.elements; var v2eX=v2e[0]; var v2eY=v2e[1]; var v2eZ=v2e[2]; var v3e=vertex3.elements; var v3eX=v3e[0]; var v3eY=v3e[1]; var v3eZ=v3e[2]; var _tempV30e=Collision._tempV30.elements; var _tempV30eX=_tempV30e[0]; var _tempV30eY=_tempV30e[1]; var _tempV30eZ=_tempV30e[2]; _tempV30eX=v2eX-v1eX; _tempV30eY=v2eY-v1eY; _tempV30eZ=v2eZ-v1eZ; var _tempV31e=Collision._tempV31.elements; var _tempV31eX=_tempV31e[0]; var _tempV31eY=_tempV31e[1]; var _tempV31eZ=_tempV31e[2]; _tempV31eX=v3eX-v1eX; _tempV31eY=v3eY-v1eY; _tempV31eZ=v3eZ-v1eZ; var _tempV32e=Collision._tempV32.elements; var _tempV32eX=_tempV32e[0]; var _tempV32eY=_tempV32e[1]; var _tempV32eZ=_tempV32e[2]; _tempV32eX=(rayDeY *_tempV31eZ)-(rayDeZ *_tempV31eY); _tempV32eY=(rayDeZ *_tempV31eX)-(rayDeX *_tempV31eZ); _tempV32eZ=(rayDeX *_tempV31eY)-(rayDeY *_tempV31eX); var determinant=(_tempV30eX *_tempV32eX)+(_tempV30eY *_tempV32eY)+(_tempV30eZ *_tempV32eZ); if (MathUtils3D.isZero(determinant)){ out=0; return false; }; var inversedeterminant=1 / determinant; var _tempV33e=Collision._tempV33.elements; var _tempV33eX=_tempV33e[0]; var _tempV33eY=_tempV33e[1]; var _tempV33eZ=_tempV33e[2]; _tempV33eX=rayOeX-v1eX; _tempV33eY=rayOeY-v1eY; _tempV33eZ=rayOeZ-v1eZ; var triangleU=(_tempV33eX *_tempV32eX)+(_tempV33eY *_tempV32eY)+(_tempV33eZ *_tempV32eZ); triangleU *=inversedeterminant; if (triangleU < 0 || triangleU > 1){ out=0; return false; }; var _tempV34e=Collision._tempV34.elements; var _tempV34eX=_tempV34e[0]; var _tempV34eY=_tempV34e[1]; var _tempV34eZ=_tempV34e[2]; _tempV34eX=(_tempV33eY *_tempV30eZ)-(_tempV33eZ *_tempV30eY); _tempV34eY=(_tempV33eZ *_tempV30eX)-(_tempV33eX *_tempV30eZ); _tempV34eZ=(_tempV33eX *_tempV30eY)-(_tempV33eY *_tempV30eX); var triangleV=((rayDeX *_tempV34eX)+(rayDeY *_tempV34eY))+(rayDeZ *_tempV34eZ); triangleV *=inversedeterminant; if (triangleV < 0 || triangleU+triangleV > 1){ out=0; return false; }; var raydistance=(_tempV31eX *_tempV34eX)+(_tempV31eY *_tempV34eY)+(_tempV31eZ *_tempV34eZ); raydistance *=inversedeterminant; if (raydistance < 0){ out=0; return false; } out=raydistance; return true; } Collision.intersectsRayAndTriangleRP=function(ray,vertex1,vertex2,vertex3,out){ var distance=NaN; if (!Collision.intersectsRayAndTriangleRD(ray,vertex1,vertex2,vertex3,distance)){ out=Vector3.ZERO; return false; } Vector3.scale(ray.direction,distance,Collision._tempV30); Vector3.add(ray.origin,Collision._tempV30,out); return true; } Collision.intersectsRayAndPoint=function(ray,point){ Vector3.subtract(ray.origin,point,Collision._tempV30); var b=Vector3.dot(Collision._tempV30,ray.direction); var c=Vector3.dot(Collision._tempV30,Collision._tempV30)-MathUtils3D.zeroTolerance; if (c > 0 && b > 0) return false; var discriminant=b *b-c; if (discriminant < 0) return false; return true; } Collision.intersectsRayAndRay=function(ray1,ray2,out){ var ray1o=ray1.origin; var ray1oe=ray1o.elements; var ray1oeX=ray1oe[0]; var ray1oeY=ray1oe[1]; var ray1oeZ=ray1oe[2]; var ray1d=ray1.direction; var ray1de=ray1d.elements; var ray1deX=ray1de[0]; var ray1deY=ray1de[1]; var ray1deZ=ray1de[2]; var ray2o=ray2.origin; var ray2oe=ray2o.elements; var ray2oeX=ray2oe[0]; var ray2oeY=ray2oe[1]; var ray2oeZ=ray2oe[2]; var ray2d=ray2.direction; var ray2de=ray2d.elements; var ray2deX=ray2de[0]; var ray2deY=ray2de[1]; var ray2deZ=ray2de[2]; Vector3.cross(ray1d,ray2d,Collision._tempV30); var tempV3e=Collision._tempV30.elements; var denominator=Vector3.scalarLengthSquared(Collision._tempV30); if (MathUtils3D.isZero(denominator)){ if (MathUtils3D.nearEqual(ray2oeX,ray1oeX)&& MathUtils3D.nearEqual(ray2oeY,ray1oeY)&& MathUtils3D.nearEqual(ray2oeZ,ray1oeZ)){ Vector3.ZERO.cloneTo(out); return true; } }; var m11=ray2oeX-ray1oeX; var m12=ray2oeY-ray1oeY; var m13=ray2oeZ-ray1oeZ; var m21=ray2deX; var m22=ray2deY; var m23=ray2deZ; var m31=tempV3e[0]; var m32=tempV3e[1]; var m33=tempV3e[2]; var dets=m11 *m22 *m33+m12 *m23 *m31+m13 *m21 *m32-m11 *m23 *m32-m12 *m21 *m33-m13 *m22 *m31; m21=ray1deX; m22=ray1deY; m23=ray1deZ; var dett=m11 *m22 *m33+m12 *m23 *m31+m13 *m21 *m32-m11 *m23 *m32-m12 *m21 *m33-m13 *m22 *m31; var s=dets / denominator; var t=dett / denominator; Vector3.scale(ray1d,s,Collision._tempV30); Vector3.scale(ray2d,t,Collision._tempV31); Vector3.add(ray1o,Collision._tempV30,Collision._tempV32); Vector3.add(ray2o,Collision._tempV31,Collision._tempV33); var point1e=Collision._tempV32.elements; var point2e=Collision._tempV33.elements; if (!MathUtils3D.nearEqual(point2e[0],point1e[0])|| !MathUtils3D.nearEqual(point2e[1],point1e[1])|| !MathUtils3D.nearEqual(point2e[2],point1e[2])){ Vector3.ZERO.cloneTo(out); return false; } Collision._tempV32.cloneTo(out); return true; } Collision.intersectsPlaneAndTriangle=function(plane,vertex1,vertex2,vertex3){ var test1=Collision.intersectsPlaneAndPoint(plane,vertex1); var test2=Collision.intersectsPlaneAndPoint(plane,vertex2); var test3=Collision.intersectsPlaneAndPoint(plane,vertex3); if (test1==Plane.PlaneIntersectionType_Front && test2==Plane.PlaneIntersectionType_Front && test3==Plane.PlaneIntersectionType_Front) return Plane.PlaneIntersectionType_Front; if (test1==Plane.PlaneIntersectionType_Back && test2==Plane.PlaneIntersectionType_Back && test3==Plane.PlaneIntersectionType_Back) return Plane.PlaneIntersectionType_Back; return Plane.PlaneIntersectionType_Intersecting; } Collision.intersectsRayAndPlaneRD=function(ray,plane,out){ var planeNor=plane.normal; var direction=Vector3.dot(planeNor,ray.direction); if (MathUtils3D.isZero(direction)){ out=0; return false; }; var position=Vector3.dot(planeNor,ray.origin); out=(-plane.distance-position)/ direction; if (out < 0){ out=0; return false; } return true; } Collision.intersectsRayAndPlaneRP=function(ray,plane,out){ var distance=NaN; if (!Collision.intersectsRayAndPlaneRD(ray,plane,distance)){ out=Vector3.ZERO; return false; } Vector3.scale(ray.direction,distance,Collision._tempV30); Vector3.add(ray.origin,Collision._tempV30,Collision._tempV31); out=Collision._tempV31; return true; } Collision.intersectsRayAndBoxRD=function(ray,box){ var rayoe=ray.origin.elements; var rayoeX=rayoe[0]; var rayoeY=rayoe[1]; var rayoeZ=rayoe[2]; var rayde=ray.direction.elements; var raydeX=rayde[0]; var raydeY=rayde[1]; var raydeZ=rayde[2]; var boxMine=box.min.elements; var boxMineX=boxMine[0]; var boxMineY=boxMine[1]; var boxMineZ=boxMine[2]; var boxMaxe=box.max.elements; var boxMaxeX=boxMaxe[0]; var boxMaxeY=boxMaxe[1]; var boxMaxeZ=boxMaxe[2]; var out=0; var tmax=MathUtils3D.MaxValue; if (MathUtils3D.isZero(raydeX)){ if (rayoeX < boxMineX || rayoeX > boxMaxeX){ return-1; } }else { var inverse=1 / raydeX; var t1=(boxMineX-rayoeX)*inverse; var t2=(boxMaxeX-rayoeX)*inverse; if (t1 > t2){ var temp=t1; t1=t2; t2=temp; } out=Math.max(t1,out); tmax=Math.min(t2,tmax); if (out > tmax){ return-1; } } if (MathUtils3D.isZero(raydeY)){ if (rayoeY < boxMineY || rayoeY > boxMaxeY){ return-1; } }else { var inverse1=1 / raydeY; var t3=(boxMineY-rayoeY)*inverse1; var t4=(boxMaxeY-rayoeY)*inverse1; if (t3 > t4){ var temp1=t3; t3=t4; t4=temp1; } out=Math.max(t3,out); tmax=Math.min(t4,tmax); if (out > tmax){ return-1; } } if (MathUtils3D.isZero(raydeZ)){ if (rayoeZ < boxMineZ || rayoeZ > boxMaxeZ){ return-1; } }else { var inverse2=1 / raydeZ; var t5=(boxMineZ-rayoeZ)*inverse2; var t6=(boxMaxeZ-rayoeZ)*inverse2; if (t5 > t6){ var temp2=t5; t5=t6; t6=temp2; } out=Math.max(t5,out); tmax=Math.min(t6,tmax); if (out > tmax){ return-1; } } return out; } Collision.intersectsRayAndBoxRP=function(ray,box,out){ var distance=Collision.intersectsRayAndBoxRD(ray,box); if (distance===-1){ Vector3.ZERO.cloneTo(out); return distance; } Vector3.scale(ray.direction,distance,Collision._tempV30); Vector3.add(ray.origin,Collision._tempV30,Collision._tempV31); Collision._tempV31.cloneTo(out); return distance; } Collision.intersectsRayAndSphereRD=function(ray,sphere){ var sphereR=sphere.radius; Vector3.subtract(ray.origin,sphere.center,Collision._tempV30); var b=Vector3.dot(Collision._tempV30,ray.direction); var c=Vector3.dot(Collision._tempV30,Collision._tempV30)-(sphereR *sphereR); if (c > 0 && b > 0){ return-1; }; var discriminant=b *b-c; if (discriminant < 0){ return-1; }; var distance=-b-Math.sqrt(discriminant); if (distance < 0) distance=0; return distance; } Collision.intersectsRayAndSphereRP=function(ray,sphere,out){ var distance=Collision.intersectsRayAndSphereRD(ray,sphere); if (distance===-1){ Vector3.ZERO.cloneTo(out); return distance; } Vector3.scale(ray.direction,distance,Collision._tempV30); Vector3.add(ray.origin,Collision._tempV30,Collision._tempV31); Collision._tempV31.cloneTo(out); return distance; } Collision.intersectsSphereAndTriangle=function(sphere,vertex1,vertex2,vertex3){ var sphereC=sphere.center; var sphereR=sphere.radius; Collision.closestPointPointTriangle(sphereC,vertex1,vertex2,vertex3,Collision._tempV30); Vector3.subtract(Collision._tempV30,sphereC,Collision._tempV31); var dot=Vector3.dot(Collision._tempV31,Collision._tempV31); return dot <=sphereR *sphereR; } Collision.intersectsPlaneAndPoint=function(plane,point){ var distance=Vector3.dot(plane.normal,point)+plane.distance; if (distance > 0) return Plane.PlaneIntersectionType_Front; if (distance < 0) return Plane.PlaneIntersectionType_Back; return Plane.PlaneIntersectionType_Intersecting; } Collision.intersectsPlaneAndPlane=function(plane1,plane2){ Vector3.cross(plane1.normal,plane2.normal,Collision._tempV30); var denominator=Vector3.dot(Collision._tempV30,Collision._tempV30); if (MathUtils3D.isZero(denominator)) return false; return true; } Collision.intersectsPlaneAndPlaneRL=function(plane1,plane2,line){ var plane1nor=plane1.normal; var plane2nor=plane2.normal; Vector3.cross(plane1nor,plane2nor,Collision._tempV34); var denominator=Vector3.dot(Collision._tempV34,Collision._tempV34); if (MathUtils3D.isZero(denominator)) return false; Vector3.scale(plane2nor,plane1.distance,Collision._tempV30); Vector3.scale(plane1nor,plane2.distance,Collision._tempV31); Vector3.subtract(Collision._tempV30,Collision._tempV31,Collision._tempV32); Vector3.cross(Collision._tempV32,Collision._tempV34,Collision._tempV33); Vector3.normalize(Collision._tempV34,Collision._tempV34); line=new Ray(Collision._tempV33,Collision._tempV34); return true; } Collision.intersectsPlaneAndBox=function(plane,box){ var planeD=plane.distance; var planeNor=plane.normal; var planeNore=planeNor.elements; var planeNoreX=planeNore[0]; var planeNoreY=planeNore[1]; var planeNoreZ=planeNore[2]; var boxMine=box.min.elements; var boxMineX=boxMine[0]; var boxMineY=boxMine[1]; var boxMineZ=boxMine[2]; var boxMaxe=box.max.elements; var boxMaxeX=boxMaxe[0]; var boxMaxeY=boxMaxe[1]; var boxMaxeZ=boxMaxe[2]; Collision._tempV30.elements[0]=(planeNoreX > 0)? boxMineX :boxMaxeX; Collision._tempV30.elements[1]=(planeNoreY > 0)? boxMineY :boxMaxeY; Collision._tempV30.elements[2]=(planeNoreZ > 0)? boxMineZ :boxMaxeZ; Collision._tempV31.elements[0]=(planeNoreX > 0)? boxMaxeX :boxMineX; Collision._tempV31.elements[1]=(planeNoreY > 0)? boxMaxeY :boxMineY; Collision._tempV31.elements[2]=(planeNoreZ > 0)? boxMaxeZ :boxMineZ; var distance=Vector3.dot(planeNor,Collision._tempV30); if (distance+planeD > 0) return Plane.PlaneIntersectionType_Front; distance=Vector3.dot(planeNor,Collision._tempV31); if (distance+planeD < 0) return Plane.PlaneIntersectionType_Back; return Plane.PlaneIntersectionType_Intersecting; } Collision.intersectsPlaneAndSphere=function(plane,sphere){ var sphereR=sphere.radius; var distance=Vector3.dot(plane.normal,sphere.center)+plane.distance; if (distance > sphereR) return Plane.PlaneIntersectionType_Front; if (distance <-sphereR) return Plane.PlaneIntersectionType_Back; return Plane.PlaneIntersectionType_Intersecting; } Collision.intersectsBoxAndBox=function(box1,box2){ var box1Mine=box1.min.elements; var box1Maxe=box1.max.elements; var box2Mine=box2.min.elements; var box2Maxe=box2.max.elements; if (box1Mine[0] > box2Maxe[0] || box2Mine[0] > box1Maxe[0]) return false; if (box1Mine[1] > box2Maxe[1] || box2Mine[1] > box1Maxe[1]) return false; if (box1Mine[2] > box2Maxe[2] || box2Mine[2] > box1Maxe[2]) return false; return true; } Collision.intersectsBoxAndSphere=function(box,sphere){ var sphereC=sphere.center; var sphereR=sphere.radius; Vector3.Clamp(sphereC,box.min,box.max,Collision._tempV30); var distance=Vector3.distanceSquared(sphereC,Collision._tempV30); return distance <=sphereR *sphereR; } Collision.intersectsSphereAndSphere=function(sphere1,sphere2){ var radiisum=sphere1.radius+sphere2.radius; return Vector3.distanceSquared(sphere1.center,sphere2.center)<=radiisum *radiisum; } Collision.boxContainsPoint=function(box,point){ var boxMine=box.min.elements; var boxMaxe=box.max.elements; var pointe=point.elements; if (boxMine[0] <=pointe[0] && boxMaxe[0] >=pointe[0] && boxMine[1] <=pointe[1] && boxMaxe[1] >=pointe[1] && boxMine[2] <=pointe[2] && boxMaxe[2] >=pointe[2]) return /*laya.d3.math.ContainmentType.Contains*/1; return /*laya.d3.math.ContainmentType.Disjoint*/0; } Collision.boxContainsBox=function(box1,box2){ var box1Mine=box1.min.elements; var box1MineX=box1Mine[0]; var box1MineY=box1Mine[1]; var box1MineZ=box1Mine[2]; var box1Maxe=box1.max.elements; var box1MaxeX=box1Maxe[0]; var box1MaxeY=box1Maxe[1]; var box1MaxeZ=box1Maxe[2]; var box2Mine=box2.min.elements; var box2MineX=box2Mine[0]; var box2MineY=box2Mine[1]; var box2MineZ=box2Mine[2]; var box2Maxe=box2.max.elements; var box2MaxeX=box2Maxe[0]; var box2MaxeY=box2Maxe[1]; var box2MaxeZ=box2Maxe[2]; if (box1MaxeX < box2MineX || box1MineX > box2MaxeX) return /*laya.d3.math.ContainmentType.Disjoint*/0; if (box1MaxeY < box2MineY || box1MineY > box2MaxeY) return /*laya.d3.math.ContainmentType.Disjoint*/0; if (box1MaxeZ < box2MineZ || box1MineZ > box2MaxeZ) return /*laya.d3.math.ContainmentType.Disjoint*/0; if (box1MineX <=box2MineX && box2MaxeX <=box2MaxeX && box1MineY <=box2MineY && box2MaxeY <=box1MaxeY && box1MineZ <=box2MineZ && box2MaxeZ <=box1MaxeZ){ return /*laya.d3.math.ContainmentType.Contains*/1; } return /*laya.d3.math.ContainmentType.Intersects*/2; } Collision.boxContainsSphere=function(box,sphere){ var boxMin=box.min; var boxMine=boxMin.elements; var boxMineX=boxMine[0]; var boxMineY=boxMine[1]; var boxMineZ=boxMine[2]; var boxMax=box.max; var boxMaxe=boxMax.elements; var boxMaxeX=boxMaxe[0]; var boxMaxeY=boxMaxe[1]; var boxMaxeZ=boxMaxe[2]; var sphereC=sphere.center; var sphereCe=sphereC.elements; var sphereCeX=sphereCe[0]; var sphereCeY=sphereCe[1]; var sphereCeZ=sphereCe[2]; var sphereR=sphere.radius; Vector3.Clamp(sphereC,boxMin,boxMax,Collision._tempV30); var distance=Vector3.distanceSquared(sphereC,Collision._tempV30); if (distance > sphereR *sphereR) return /*laya.d3.math.ContainmentType.Disjoint*/0; if ((((boxMineX+sphereR <=sphereCeX)&& (sphereCeX <=boxMaxeX-sphereR))&& ((boxMaxeX-boxMineX > sphereR)&& (boxMineY+sphereR <=sphereCeY)))&& (((sphereCeY <=boxMaxeY-sphereR)&& (boxMaxeY-boxMineY > sphereR))&& (((boxMineZ+sphereR <=sphereCeZ)&& (sphereCeZ <=boxMaxeZ-sphereR))&& (boxMaxeZ-boxMineZ > sphereR)))) return /*laya.d3.math.ContainmentType.Contains*/1; return /*laya.d3.math.ContainmentType.Intersects*/2; } Collision.sphereContainsPoint=function(sphere,point){ if (Vector3.distanceSquared(point,sphere.center)<=sphere.radius *sphere.radius) return /*laya.d3.math.ContainmentType.Contains*/1; return /*laya.d3.math.ContainmentType.Disjoint*/0; } Collision.sphereContainsTriangle=function(sphere,vertex1,vertex2,vertex3){ var test1=Collision.sphereContainsPoint(sphere,vertex1); var test2=Collision.sphereContainsPoint(sphere,vertex2); var test3=Collision.sphereContainsPoint(sphere,vertex3); if (test1==/*laya.d3.math.ContainmentType.Contains*/1 && test2==/*laya.d3.math.ContainmentType.Contains*/1 && test3==/*laya.d3.math.ContainmentType.Contains*/1) return /*laya.d3.math.ContainmentType.Contains*/1; if (Collision.intersectsSphereAndTriangle(sphere,vertex1,vertex2,vertex3)) return /*laya.d3.math.ContainmentType.Intersects*/2; return /*laya.d3.math.ContainmentType.Disjoint*/0; } Collision.sphereContainsBox=function(sphere,box){ var sphereC=sphere.center; var sphereCe=sphereC.elements; var sphereCeX=sphereCe[0]; var sphereCeY=sphereCe[1]; var sphereCeZ=sphereCe[2]; var sphereR=sphere.radius; var boxMin=box.min; var boxMine=boxMin.elements; var boxMineX=boxMine[0]; var boxMineY=boxMine[1]; var boxMineZ=boxMine[2]; var boxMax=box.max; var boxMaxe=boxMax.elements; var boxMaxeX=boxMaxe[0]; var boxMaxeY=boxMaxe[1]; var boxMaxeZ=boxMaxe[2]; var _tempV30e=Collision._tempV30.elements; var _tempV30eX=_tempV30e[0]; var _tempV30eY=_tempV30e[1]; var _tempV30eZ=_tempV30e[2]; if (!Collision.intersectsBoxAndSphere(box,sphere)) return /*laya.d3.math.ContainmentType.Disjoint*/0; var radiusSquared=sphereR *sphereR; _tempV30eX=sphereCeX-boxMineX; _tempV30eY=sphereCeY-boxMaxeY; _tempV30eZ=sphereCeZ-boxMaxeZ; if (Vector3.scalarLengthSquared(Collision._tempV30)> radiusSquared) return /*laya.d3.math.ContainmentType.Intersects*/2; _tempV30eX=sphereCeX-boxMaxeX; _tempV30eY=sphereCeY-boxMaxeY; _tempV30eZ=sphereCeZ-boxMaxeZ; if (Vector3.scalarLengthSquared(Collision._tempV30)> radiusSquared) return /*laya.d3.math.ContainmentType.Intersects*/2; _tempV30eX=sphereCeX-boxMaxeX; _tempV30eY=sphereCeY-boxMineY; _tempV30eZ=sphereCeZ-boxMaxeZ; if (Vector3.scalarLengthSquared(Collision._tempV30)> radiusSquared) return /*laya.d3.math.ContainmentType.Intersects*/2; _tempV30eX=sphereCeX-boxMineX; _tempV30eY=sphereCeY-boxMineY; _tempV30eZ=sphereCeZ-boxMaxeZ; if (Vector3.scalarLengthSquared(Collision._tempV30)> radiusSquared) return /*laya.d3.math.ContainmentType.Intersects*/2; _tempV30eX=sphereCeX-boxMineX; _tempV30eY=sphereCeY-boxMaxeY; _tempV30eZ=sphereCeZ-boxMineZ; if (Vector3.scalarLengthSquared(Collision._tempV30)> radiusSquared) return /*laya.d3.math.ContainmentType.Intersects*/2; _tempV30eX=sphereCeX-boxMaxeX; _tempV30eY=sphereCeY-boxMaxeY; _tempV30eZ=sphereCeZ-boxMineZ; if (Vector3.scalarLengthSquared(Collision._tempV30)> radiusSquared) return /*laya.d3.math.ContainmentType.Intersects*/2; _tempV30eX=sphereCeX-boxMaxeX; _tempV30eY=sphereCeY-boxMineY; _tempV30eZ=sphereCeZ-boxMineZ; if (Vector3.scalarLengthSquared(Collision._tempV30)> radiusSquared) return /*laya.d3.math.ContainmentType.Intersects*/2; _tempV30eX=sphereCeX-boxMineX; _tempV30eY=sphereCeY-boxMineY; _tempV30eZ=sphereCeZ-boxMineZ; if (Vector3.scalarLengthSquared(Collision._tempV30)> radiusSquared) return /*laya.d3.math.ContainmentType.Intersects*/2; return /*laya.d3.math.ContainmentType.Contains*/1; } Collision.sphereContainsSphere=function(sphere1,sphere2){ var sphere1R=sphere1.radius; var sphere2R=sphere2.radius; var distance=Vector3.distance(sphere1.center,sphere2.center); if (sphere1R+sphere2R < distance) return /*laya.d3.math.ContainmentType.Disjoint*/0; if (sphere1R-sphere2R < distance) return /*laya.d3.math.ContainmentType.Intersects*/2; return /*laya.d3.math.ContainmentType.Contains*/1; } Collision.closestPointPointTriangle=function(point,vertex1,vertex2,vertex3,out){ Vector3.subtract(vertex2,vertex1,Collision._tempV30); Vector3.subtract(vertex3,vertex1,Collision._tempV31); Vector3.subtract(point,vertex1,Collision._tempV32); Vector3.subtract(point,vertex2,Collision._tempV33); Vector3.subtract(point,vertex3,Collision._tempV34); var d1=Vector3.dot(Collision._tempV30,Collision._tempV32); var d2=Vector3.dot(Collision._tempV31,Collision._tempV32); var d3=Vector3.dot(Collision._tempV30,Collision._tempV33); var d4=Vector3.dot(Collision._tempV31,Collision._tempV33); var d5=Vector3.dot(Collision._tempV30,Collision._tempV34); var d6=Vector3.dot(Collision._tempV31,Collision._tempV34); if (d1 <=0 && d2 <=0){ vertex1.cloneTo(out); return; } if (d3 >=0 && d4 <=d3){ vertex2.cloneTo(out); return; }; var vc=d1 *d4-d3 *d2; if (vc <=0 && d1 >=0 && d3 <=0){ var v=d1 / (d1-d3); Vector3.scale(Collision._tempV30,v,out); Vector3.add(vertex1,out,out); return; } if (d6 >=0 && d5 <=d6){ vertex3.cloneTo(out); return; }; var vb=d5 *d2-d1 *d6; if (vb <=0 && d2 >=0 && d6 <=0){ var w=d2 / (d2-d6); Vector3.scale(Collision._tempV31,w,out); Vector3.add(vertex1,out,out); return; }; var va=d3 *d6-d5 *d4; if (va <=0 && (d4-d3)>=0 && (d5-d6)>=0){ var w3=(d4-d3)/ ((d4-d3)+(d5-d6)); Vector3.subtract(vertex3,vertex2,out); Vector3.scale(out,w3,out); Vector3.add(vertex2,out,out); return; }; var denom=1 / (va+vb+vc); var v2=vb *denom; var w2=vc *denom; Vector3.scale(Collision._tempV30,v2,Collision._tempV35); Vector3.scale(Collision._tempV31,w2,Collision._tempV36); Vector3.add(Collision._tempV35,Collision._tempV36,out); Vector3.add(vertex1,out,out); } Collision.closestPointPlanePoint=function(plane,point,out){ var planeN=plane.normal; var t=Vector3.dot(planeN,point)-plane.distance; Vector3.scale(planeN,t,Collision._tempV30); Vector3.subtract(point,Collision._tempV30,out); } Collision.closestPointBoxPoint=function(box,point,out){ Vector3.max(point,box.min,Collision._tempV30); Vector3.min(Collision._tempV30,box.max,out); } Collision.closestPointSpherePoint=function(sphere,point,out){ var sphereC=sphere.center; Vector3.subtract(point,sphereC,out); Vector3.normalize(out,out); Vector3.scale(out,sphere.radius,out); Vector3.add(out,sphereC,out); } Collision.closestPointSphereSphere=function(sphere1,sphere2,out){ var sphere1C=sphere1.center; Vector3.subtract(sphere2.center,sphere1C,out); Vector3.normalize(out,out); Vector3.scale(out,sphere1.radius,out); Vector3.add(out,sphere1C,out); } __static(Collision, ['_tempV30',function(){return this._tempV30=new Vector3();},'_tempV31',function(){return this._tempV31=new Vector3();},'_tempV32',function(){return this._tempV32=new Vector3();},'_tempV33',function(){return this._tempV33=new Vector3();},'_tempV34',function(){return this._tempV34=new Vector3();},'_tempV35',function(){return this._tempV35=new Vector3();},'_tempV36',function(){return this._tempV36=new Vector3();} ]); return Collision; })() /** *ContainmentType 类用于定义空间物体位置关系。 */ //class laya.d3.math.ContainmentType var ContainmentType=(function(){ function ContainmentType(){} __class(ContainmentType,'laya.d3.math.ContainmentType'); ContainmentType.Disjoint=0; ContainmentType.Contains=1; ContainmentType.Intersects=2; return ContainmentType; })() /** *MathUtils 类用于创建数学工具。 */ //class laya.d3.math.MathUtils3D var MathUtils3D=(function(){ /** *创建一个 MathUtils 实例。 */ function MathUtils3D(){} __class(MathUtils3D,'laya.d3.math.MathUtils3D'); MathUtils3D.isZero=function(v){ return Math.abs(v)< MathUtils3D.zeroTolerance; } MathUtils3D.nearEqual=function(n1,n2){ if (MathUtils3D.isZero(n1-n2)) return true; return false; } MathUtils3D.fastInvSqrt=function(value){ if (MathUtils3D.isZero(value)) return value; return 1.0 / Math.sqrt(value); } __static(MathUtils3D, ['zeroTolerance',function(){return this.zeroTolerance=1e-6;},'MaxValue',function(){return this.MaxValue=3.40282347e+38;},'MinValue',function(){return this.MinValue=-3.40282347e+38;} ]); return MathUtils3D; })() /** *Matrix3x3 类用于创建3x3矩阵。 */ //class laya.d3.math.Matrix3x3 var Matrix3x3=(function(){ function Matrix3x3(){ /**矩阵元素数组*/ //this.elements=null; var e=this.elements=new Float32Array(9); e[0]=1; e[1]=0; e[2]=0; e[3]=0; e[4]=1; e[5]=0; e[6]=0; e[7]=0; e[8]=1; } __class(Matrix3x3,'laya.d3.math.Matrix3x3'); var __proto=Matrix3x3.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *计算3x3矩阵的行列式 *@return 矩阵的行列式 */ __proto.determinant=function(){ var f=this.elements; var a00=f[0],a01=f[1],a02=f[2]; var a10=f[3],a11=f[4],a12=f[5]; var a20=f[6],a21=f[7],a22=f[8]; return a00 *(a22 *a11-a12 *a21)+a01 *(-a22 *a10+a12 *a20)+a02 *(a21 *a10-a11 *a20); } /** *通过一个二维向量转换3x3矩阵 *@param tra 转换向量 *@param out 输出矩阵 */ __proto.translate=function(trans,out){ var e=out.elements; var f=this.elements; var g=trans.elements; var a00=f[0],a01=f[1],a02=f[2]; var a10=f[3],a11=f[4],a12=f[5]; var a20=f[6],a21=f[7],a22=f[8]; var x=g[0],y=g[1]; e[0]=a00; e[1]=a01; e[2]=a02; e[3]=a10; e[4]=a11; e[5]=a12; e[6]=x *a00+y *a10+a20; e[7]=x *a01+y *a11+a21; e[8]=x *a02+y *a12+a22; } /** *根据指定角度旋转3x3矩阵 *@param rad 旋转角度 *@param out 输出矩阵 */ __proto.rotate=function(rad,out){ var e=out.elements; var f=this.elements; var a00=f[0],a01=f[1],a02=f[2]; var a10=f[3],a11=f[4],a12=f[5]; var a20=f[6],a21=f[7],a22=f[8]; var s=Math.sin(rad); var c=Math.cos(rad); e[0]=c *a00+s *a10; e[1]=c *a01+s *a11; e[2]=c *a02+s *a12; e[3]=c *a10-s *a00; e[4]=c *a11-s *a01; e[5]=c *a12-s *a02; e[6]=a20; e[7]=a21; e[8]=a22; } /** *根据制定缩放3x3矩阵 *@param scale 缩放值 *@param out 输出矩阵 */ __proto.scale=function(scale,out){ var e=out.elements; var f=this.elements; var g=scale.elements; var x=g[0],y=g[1]; e[0]=x *f[0]; e[1]=x *f[1]; e[2]=x *f[2]; e[3]=y *f[3]; e[4]=y *f[4]; e[5]=y *f[5]; e[6]=f[6]; e[7]=f[7]; e[8]=f[8]; } /** *计算3x3矩阵的逆矩阵 *@param out 输出的逆矩阵 */ __proto.invert=function(out){ var e=out.elements; var f=this.elements; var a00=f[0],a01=f[1],a02=f[2]; var a10=f[3],a11=f[4],a12=f[5]; var a20=f[6],a21=f[7],a22=f[8]; var b01=a22 *a11-a12 *a21; var b11=-a22 *a10+a12 *a20; var b21=a21 *a10-a11 *a20; var det=a00 *b01+a01 *b11+a02 *b21; if (!det){ out=null; } det=1.0 / det; e[0]=b01 *det; e[1]=(-a22 *a01+a02 *a21)*det; e[2]=(a12 *a01-a02 *a11)*det; e[3]=b11 *det; e[4]=(a22 *a00-a02 *a20)*det; e[5]=(-a12 *a00+a02 *a10)*det; e[6]=b21 *det; e[7]=(-a21 *a00+a01 *a20)*det; e[8]=(a11 *a00-a01 *a10)*det; } /** *计算3x3矩阵的转置矩阵 *@param out 输出矩阵 */ __proto.transpose=function(out){ var e=out.elements; var f=this.elements; if (out===this){ var a01=f[1],a02=f[2],a12=f[5]; e[1]=f[3]; e[2]=f[6]; e[3]=a01; e[5]=f[7]; e[6]=a02; e[7]=a12; }else { e[0]=f[0]; e[1]=f[3]; e[2]=f[6]; e[3]=f[1]; e[4]=f[4]; e[5]=f[7]; e[6]=f[2]; e[7]=f[5]; e[8]=f[8]; } } /**设置已有的矩阵为单位矩阵*/ __proto.identity=function(){ var e=this.elements; e[0]=1; e[1]=0; e[2]=0; e[3]=0; e[4]=1; e[5]=0; e[6]=0; e[7]=0; e[8]=1; } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var i,s,d; s=this.elements; d=destObject.elements; if (s===d){ return; } for (i=0;i < 9;++i){ d[i]=s[i]; } } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var dest=/*__JS__ */new this.constructor(); this.cloneTo(dest); return dest; } Matrix3x3.createFromTranslation=function(trans,out){ var e=out.elements; var g=trans.elements; out[0]=1; out[1]=0; out[2]=0; out[3]=0; out[4]=1; out[5]=0; out[6]=g[0]; out[7]=g[1]; out[8]=1; } Matrix3x3.createFromRotation=function(rad,out){ var e=out.elements; var s=Math.sin(rad),c=Math.cos(rad); e[0]=c; e[1]=s; e[2]=0; e[3]=-s; e[4]=c; e[5]=0; e[6]=0; e[7]=0; e[8]=1; } Matrix3x3.createFromScaling=function(scale,out){ var e=out.elements; var g=scale.elements; e[0]=g[0]; e[1]=0; e[2]=0; e[3]=0; e[4]=g[1]; e[5]=0; e[6]=0; e[7]=0; e[8]=1; } Matrix3x3.createFromMatrix4x4=function(sou,out){ out[0]=sou[0]; out[1]=sou[1]; out[2]=sou[2]; out[3]=sou[4]; out[4]=sou[5]; out[5]=sou[6]; out[6]=sou[8]; out[7]=sou[9]; out[8]=sou[10]; } Matrix3x3.multiply=function(left,right,out){ var e=out.elements; var f=left.elements; var g=right.elements; var a00=f[0],a01=f[1],a02=f[2]; var a10=f[3],a11=f[4],a12=f[5]; var a20=f[6],a21=f[7],a22=f[8]; var b00=g[0],b01=g[1],b02=g[2]; var b10=g[3],b11=g[4],b12=g[5]; var b20=g[6],b21=g[7],b22=g[8]; e[0]=b00 *a00+b01 *a10+b02 *a20; e[1]=b00 *a01+b01 *a11+b02 *a21; e[2]=b00 *a02+b01 *a12+b02 *a22; e[3]=b10 *a00+b11 *a10+b12 *a20; e[4]=b10 *a01+b11 *a11+b12 *a21; e[5]=b10 *a02+b11 *a12+b12 *a22; e[6]=b20 *a00+b21 *a10+b22 *a20; e[7]=b20 *a01+b21 *a11+b22 *a21; e[8]=b20 *a02+b21 *a12+b22 *a22; } Matrix3x3.lookAt=function(eye,target,up,out){ Vector3.subtract(eye,target,Matrix3x3._tempV30); Vector3.normalize(Matrix3x3._tempV30,Matrix3x3._tempV30); Vector3.cross(up,Matrix3x3._tempV30,Matrix3x3._tempV31); Vector3.normalize(Matrix3x3._tempV31,Matrix3x3._tempV31); Vector3.cross(Matrix3x3._tempV30,Matrix3x3._tempV31,Matrix3x3._tempV32); var v0e=Matrix3x3._tempV30.elements; var v1e=Matrix3x3._tempV31.elements; var v2e=Matrix3x3._tempV32.elements; var me=out.elements; me[0]=v1e[0]; me[3]=v1e[1]; me[6]=v1e[2]; me[1]=v2e[0]; me[4]=v2e[1]; me[7]=v2e[2]; me[2]=v0e[0]; me[5]=v0e[1]; me[8]=v0e[2]; } Matrix3x3.DEFAULT=new Matrix3x3(); __static(Matrix3x3, ['_tempV30',function(){return this._tempV30=new Vector3();},'_tempV31',function(){return this._tempV31=new Vector3();},'_tempV32',function(){return this._tempV32=new Vector3();} ]); return Matrix3x3; })() /** *Matrix4x4 类用于创建4x4矩阵。 */ //class laya.d3.math.Matrix4x4 var Matrix4x4=(function(){ function Matrix4x4(m11,m12,m13,m14,m21,m22,m23,m24,m31,m32,m33,m34,m41,m42,m43,m44){ /**矩阵元素数组*/ //this.elements=null; (m11===void 0)&& (m11=1); (m12===void 0)&& (m12=0); (m13===void 0)&& (m13=0); (m14===void 0)&& (m14=0); (m21===void 0)&& (m21=0); (m22===void 0)&& (m22=1); (m23===void 0)&& (m23=0); (m24===void 0)&& (m24=0); (m31===void 0)&& (m31=0); (m32===void 0)&& (m32=0); (m33===void 0)&& (m33=1); (m34===void 0)&& (m34=0); (m41===void 0)&& (m41=0); (m42===void 0)&& (m42=0); (m43===void 0)&& (m43=0); (m44===void 0)&& (m44=1); var e=this.elements=new Float32Array(16); e[0]=m11; e[1]=m12; e[2]=m13; e[3]=m14; e[4]=m21; e[5]=m22; e[6]=m23; e[7]=m24; e[8]=m31; e[9]=m32; e[10]=m33; e[11]=m34; e[12]=m41; e[13]=m42; e[14]=m43; e[15]=m44; } __class(Matrix4x4,'laya.d3.math.Matrix4x4'); var __proto=Matrix4x4.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) __proto.getElementByRowColumn=function(row,column){ if (row < 0 || row > 3) throw new Error("row","Rows and columns for matrices run from 0 to 3, inclusive."); if (column < 0 || column > 3) throw new Error("column","Rows and columns for matrices run from 0 to 3, inclusive."); return this.elements[(row *4)+column]; } __proto.setElementByRowColumn=function(row,column,value){ if (row < 0 || row > 3) throw new Error("row","Rows and columns for matrices run from 0 to 3, inclusive."); if (column < 0 || column > 3) throw new Error("column","Rows and columns for matrices run from 0 to 3, inclusive."); this.elements[(row *4)+column]=value; } /** *判断两个4x4矩阵的值是否相等。 *@param other 4x4矩阵 */ __proto.equalsOtherMatrix=function(other){ var e=this.elements; var oe=other.elements; return (MathUtils3D.nearEqual(e[0],oe[0])&& MathUtils3D.nearEqual(e[1],oe[1])&& MathUtils3D.nearEqual(e[2],oe[2])&& MathUtils3D.nearEqual(e[3],oe[3])&& MathUtils3D.nearEqual(e[4],oe[4])&& MathUtils3D.nearEqual(e[5],oe[5])&& MathUtils3D.nearEqual(e[6],oe[6])&& MathUtils3D.nearEqual(e[7],oe[7])&& MathUtils3D.nearEqual(e[8],oe[8])&& MathUtils3D.nearEqual(e[9],oe[9])&& MathUtils3D.nearEqual(e[10],oe[10])&& MathUtils3D.nearEqual(e[11],oe[11])&& MathUtils3D.nearEqual(e[12],oe[12])&& MathUtils3D.nearEqual(e[13],oe[13])&& MathUtils3D.nearEqual(e[14],oe[14])&& MathUtils3D.nearEqual(e[15],oe[15])); } /** *分解矩阵为平移向量、旋转四元数、缩放向量。 *@param translation 平移向量。 *@param rotation 旋转四元数。 *@param scale 缩放向量。 *@return 是否分解成功。 */ __proto.decomposeTransRotScale=function(translation,rotation,scale){ var rotationMatrix=Matrix4x4._tempMatrix4x4; if (this.decomposeTransRotMatScale(translation,rotationMatrix,scale)){ Quaternion.createFromMatrix4x4(rotationMatrix,rotation); return true; }else { rotation.identity(); return false; } } /** *分解矩阵为平移向量、旋转矩阵、缩放向量。 *@param translation 平移向量。 *@param rotationMatrix 旋转矩阵。 *@param scale 缩放向量。 *@return 是否分解成功。 */ __proto.decomposeTransRotMatScale=function(translation,rotationMatrix,scale){ var e=this.elements; var te=translation.elements; var re=rotationMatrix.elements; var se=scale.elements; te[0]=e[12]; te[1]=e[13]; te[2]=e[14]; var m11=e[0],m12=e[1],m13=e[2]; var m21=e[4],m22=e[5],m23=e[6]; var m31=e[8],m32=e[9],m33=e[10]; var sX=se[0]=Math.sqrt((m11 *m11)+(m12 *m12)+(m13 *m13)); var sY=se[1]=Math.sqrt((m21 *m21)+(m22 *m22)+(m23 *m23)); var sZ=se[2]=Math.sqrt((m31 *m31)+(m32 *m32)+(m33 *m33)); if (MathUtils3D.isZero(sX)|| MathUtils3D.isZero(sY)|| MathUtils3D.isZero(sZ)){ re[1]=re[2]=re[3]=re[4]=re[6]=re[7]=re[8]=re[9]=re[11]=re[12]=re[13]=re[14]=0; re[0]=re[5]=re[10]=re[15]=1; return false; }; var at=Matrix4x4._tempVector0; var atE=at.elements; atE[0]=m31 / sZ; atE[1]=m32 / sZ; atE[2]=m33 / sZ; var tempRight=Matrix4x4._tempVector1; var tempRightE=tempRight.elements; tempRightE[0]=m11 / sX; tempRightE[1]=m12 / sX; tempRightE[2]=m13 / sX; var up=Matrix4x4._tempVector2; Vector3.cross(at,tempRight,up); var right=Matrix4x4._tempVector1; Vector3.cross(up,at,right); re[3]=re[7]=re[11]=re[12]=re[13]=re[14]=0; re[15]=1; re[0]=right.x; re[1]=right.y; re[2]=right.z; re[4]=up.x; re[5]=up.y; re[6]=up.z; re[8]=at.x; re[9]=at.y; re[10]=at.z; ((re[0] *m11+re[1] *m12+re[2] *m13)< 0.0)&& (se[0]=-sX); ((re[4] *m21+re[5] *m22+re[6] *m23)< 0.0)&& (se[1]=-sY); ((re[8] *m31+re[9] *m32+re[10] *m33)< 0.0)&& (se[2]=-sZ); return true; } /** *分解旋转矩阵的旋转为YawPitchRoll欧拉角。 *@param out float yaw *@param out float pitch *@param out float roll *@return */ __proto.decomposeYawPitchRoll=function(yawPitchRoll){ var yawPitchRollE=yawPitchRoll.elements; var pitch=Math.asin(-this.elements[9]); yawPitchRollE[1]=pitch; var test=Math.cos(pitch); if (test > MathUtils3D.zeroTolerance){ yawPitchRollE[2]=Math.atan2(this.elements[1],this.elements[5]); yawPitchRollE[0]=Math.atan2(this.elements[8],this.elements[10]); }else { yawPitchRollE[2]=Math.atan2(-this.elements[4],this.elements[0]); yawPitchRollE[0]=0.0; } } /**归一化矩阵 */ __proto.normalize=function(){ var v=this.elements; var c=v[0],d=v[1],e=v[2],g=Math.sqrt(c *c+d *d+e *e); if (g){ if (g==1) return; }else { v[0]=0; v[1]=0; v[2]=0; return; } g=1 / g; v[0]=c *g; v[1]=d *g; v[2]=e *g; } /**计算矩阵的转置矩阵*/ __proto.transpose=function(){ var e,t; e=this.elements; t=e[1]; e[1]=e[4]; e[4]=t; t=e[2]; e[2]=e[8]; e[8]=t; t=e[3]; e[3]=e[12]; e[12]=t; t=e[6]; e[6]=e[9]; e[9]=t; t=e[7]; e[7]=e[13]; e[13]=t; t=e[11]; e[11]=e[14]; e[14]=t; return this; } /** *计算一个矩阵的逆矩阵 *@param out 输出矩阵 */ __proto.invert=function(out){ var ae=this.elements; var oe=out.elements; var a00=ae[0],a01=ae[1],a02=ae[2],a03=ae[3],a10=ae[4],a11=ae[5],a12=ae[6],a13=ae[7],a20=ae[8],a21=ae[9],a22=ae[10],a23=ae[11],a30=ae[12],a31=ae[13],a32=ae[14],a33=ae[15], b00=a00 *a11-a01 *a10,b01=a00 *a12-a02 *a10,b02=a00 *a13-a03 *a10,b03=a01 *a12-a02 *a11,b04=a01 *a13-a03 *a11,b05=a02 *a13-a03 *a12,b06=a20 *a31-a21 *a30,b07=a20 *a32-a22 *a30,b08=a20 *a33-a23 *a30,b09=a21 *a32-a22 *a31,b10=a21 *a33-a23 *a31,b11=a22 *a33-a23 *a32, det=b00 *b11-b01 *b10+b02 *b09+b03 *b08-b04 *b07+b05 *b06; if (Math.abs(det)===0.0){ return; } det=1.0 / det; oe[0]=(a11 *b11-a12 *b10+a13 *b09)*det; oe[1]=(a02 *b10-a01 *b11-a03 *b09)*det; oe[2]=(a31 *b05-a32 *b04+a33 *b03)*det; oe[3]=(a22 *b04-a21 *b05-a23 *b03)*det; oe[4]=(a12 *b08-a10 *b11-a13 *b07)*det; oe[5]=(a00 *b11-a02 *b08+a03 *b07)*det; oe[6]=(a32 *b02-a30 *b05-a33 *b01)*det; oe[7]=(a20 *b05-a22 *b02+a23 *b01)*det; oe[8]=(a10 *b10-a11 *b08+a13 *b06)*det; oe[9]=(a01 *b08-a00 *b10-a03 *b06)*det; oe[10]=(a30 *b04-a31 *b02+a33 *b00)*det; oe[11]=(a21 *b02-a20 *b04-a23 *b00)*det; oe[12]=(a11 *b07-a10 *b09-a12 *b06)*det; oe[13]=(a00 *b09-a01 *b07+a02 *b06)*det; oe[14]=(a31 *b01-a30 *b03-a32 *b00)*det; oe[15]=(a20 *b03-a21 *b01+a22 *b00)*det; } /**设置矩阵为单位矩阵*/ __proto.identity=function(){ var e=this.elements; e[1]=e[2]=e[3]=e[4]=e[6]=e[7]=e[8]=e[9]=e[11]=e[12]=e[13]=e[14]=0; e[0]=e[5]=e[10]=e[15]=1; } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var i,s,d; s=this.elements; d=destObject.elements; if (s===d){ return; } for (i=0;i < 16;++i){ d[i]=s[i]; } } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var dest=/*__JS__ */new this.constructor(); this.cloneTo(dest); return dest; } /** *获取平移向量。 *@param out 平移向量。 */ __proto.getTranslationVector=function(out){ var me=this.elements; var te=out.elements; te[0]=me[12]; te[1]=me[13]; te[2]=me[14]; } /** *设置平移向量。 *@param translate 平移向量。 */ __proto.setTranslationVector=function(translate){ var me=this.elements; var ve=translate.elements; me[12]=ve[0]; me[13]=ve[1]; me[14]=ve[2]; } /** *获取前向量。 *@param out 前向量。 */ __proto.getForward=function(out){ var me=this.elements; var te=out.elements; te[0]=-me[8]; te[1]=-me[9]; te[2]=-me[10]; } /** *设置前向量。 *@param forward 前向量。 */ __proto.setForward=function(forward){ var me=this.elements; var ve=forward.elements; me[8]=-ve[0]; me[9]=-ve[1]; me[10]=-ve[2]; } Matrix4x4.createRotationX=function(rad,out){ var oe=out.elements; var s=Math.sin(rad),c=Math.cos(rad); oe[1]=oe[2]=oe[3]=oe[4]=oe[7]=oe[8]=oe[11]=oe[12]=oe[13]=oe[14]=0; oe[0]=oe[15]=1; oe[5]=oe[10]=c; oe[6]=s; oe[9]=-s; } Matrix4x4.createRotationY=function(rad,out){ var oe=out.elements; var s=Math.sin(rad),c=Math.cos(rad); oe[1]=oe[3]=oe[4]=oe[6]=oe[7]=oe[9]=oe[11]=oe[12]=oe[13]=oe[14]=0; oe[5]=oe[15]=1; oe[0]=oe[10]=c; oe[2]=-s; oe[8]=s; } Matrix4x4.createRotationZ=function(rad,out){ var oe=out.elements; var s=Math.sin(rad),c=Math.cos(rad); oe[2]=oe[3]=oe[6]=oe[7]=oe[8]=oe[9]=oe[11]=oe[12]=oe[13]=oe[14]=0; oe[10]=oe[15]=1; oe[0]=oe[5]=c; oe[1]=s; oe[4]=-s; } Matrix4x4.createRotationYawPitchRoll=function(yaw,pitch,roll,result){ Quaternion.createFromYawPitchRoll(yaw,pitch,roll,Matrix4x4._tempQuaternion); Matrix4x4.createRotationQuaternion(Matrix4x4._tempQuaternion,result); } Matrix4x4.createRotationAxis=function(axis,angle,result){ var axisE=axis.elements; var x=axisE[0]; var y=axisE[1]; var z=axisE[2]; var cos=Math.cos(angle); var sin=Math.sin(angle); var xx=x *x; var yy=y *y; var zz=z *z; var xy=x *y; var xz=x *z; var yz=y *z; var resultE=result.elements; resultE[3]=resultE[7]=resultE[11]=resultE[12]=resultE[13]=resultE[14]=0; resultE[15]=1.0; resultE[0]=xx+(cos *(1.0-xx)); resultE[1]=(xy-(cos *xy))+(sin *z); resultE[2]=(xz-(cos *xz))-(sin *y); resultE[4]=(xy-(cos *xy))-(sin *z); resultE[5]=yy+(cos *(1.0-yy)); resultE[6]=(yz-(cos *yz))+(sin *x); resultE[8]=(xz-(cos *xz))+(sin *y); resultE[9]=(yz-(cos *yz))-(sin *x); resultE[10]=zz+(cos *(1.0-zz)); } Matrix4x4.createRotationQuaternion=function(rotation,result){ var rotationE=rotation.elements; var resultE=result.elements; var rotationX=rotationE[0]; var rotationY=rotationE[1]; var rotationZ=rotationE[2]; var rotationW=rotationE[3]; var xx=rotationX *rotationX; var yy=rotationY *rotationY; var zz=rotationZ *rotationZ; var xy=rotationX *rotationY; var zw=rotationZ *rotationW; var zx=rotationZ *rotationX; var yw=rotationY *rotationW; var yz=rotationY *rotationZ; var xw=rotationX *rotationW; resultE[3]=resultE[7]=resultE[11]=resultE[12]=resultE[13]=resultE[14]=0; resultE[15]=1.0; resultE[0]=1.0-(2.0 *(yy+zz)); resultE[1]=2.0 *(xy+zw); resultE[2]=2.0 *(zx-yw); resultE[4]=2.0 *(xy-zw); resultE[5]=1.0-(2.0 *(zz+xx)); resultE[6]=2.0 *(yz+xw); resultE[8]=2.0 *(zx+yw); resultE[9]=2.0 *(yz-xw); resultE[10]=1.0-(2.0 *(yy+xx)); } Matrix4x4.createTranslate=function(trans,out){ var te=trans.elements; var oe=out.elements; oe[4]=oe[8]=oe[1]=oe[9]=oe[2]=oe[6]=oe[3]=oe[7]=oe[11]=0; oe[0]=oe[5]=oe[10]=oe[15]=1; oe[12]=te[0]; oe[13]=te[1]; oe[14]=te[2]; } Matrix4x4.createScaling=function(scale,out){ var se=scale.elements; var oe=out.elements; oe[0]=se[0]; oe[5]=se[1]; oe[10]=se[2]; oe[1]=oe[4]=oe[8]=oe[12]=oe[9]=oe[13]=oe[2]=oe[6]=oe[14]=oe[3]=oe[7]=oe[11]=0; oe[15]=1; } Matrix4x4.multiply=function(left,right,out){ var i,e,a,b,ai0,ai1,ai2,ai3; e=out.elements; a=left.elements; b=right.elements; if (e===b){ b=new Float32Array(16); for (i=0;i < 16;++i){ b[i]=e[i]; } } for (i=0;i < 4;i++){ ai0=a[i]; ai1=a[i+4]; ai2=a[i+8]; ai3=a[i+12]; e[i]=ai0 *b[0]+ai1 *b[1]+ai2 *b[2]+ai3 *b[3]; e[i+4]=ai0 *b[4]+ai1 *b[5]+ai2 *b[6]+ai3 *b[7]; e[i+8]=ai0 *b[8]+ai1 *b[9]+ai2 *b[10]+ai3 *b[11]; e[i+12]=ai0 *b[12]+ai1 *b[13]+ai2 *b[14]+ai3 *b[15]; } } Matrix4x4.createFromQuaternion=function(rotation,out){ var e=out.elements; var q=rotation.elements; var x=q[0],y=q[1],z=q[2],w=q[3]; var x2=x+x; var y2=y+y; var z2=z+z; var xx=x *x2; var yx=y *x2; var yy=y *y2; var zx=z *x2; var zy=z *y2; var zz=z *z2; var wx=w *x2; var wy=w *y2; var wz=w *z2; e[0]=1-yy-zz; e[1]=yx+wz; e[2]=zx-wy; e[3]=0; e[4]=yx-wz; e[5]=1-xx-zz; e[6]=zy+wx; e[7]=0; e[8]=zx+wy; e[9]=zy-wx; e[10]=1-xx-yy; e[11]=0; e[12]=0; e[13]=0; e[14]=0; e[15]=1; } Matrix4x4.createAffineTransformation=function(trans,rot,scale,out){ var te=trans.elements; var re=rot.elements; var se=scale.elements; var oe=out.elements; var x=re[0],y=re[1],z=re[2],w=re[3],x2=x+x,y2=y+y,z2=z+z; var xx=x *x2,xy=x *y2,xz=x *z2,yy=y *y2,yz=y *z2,zz=z *z2; var wx=w *x2,wy=w *y2,wz=w *z2,sx=se[0],sy=se[1],sz=se[2]; oe[0]=(1-(yy+zz))*sx; oe[1]=(xy+wz)*sx; oe[2]=(xz-wy)*sx; oe[3]=0; oe[4]=(xy-wz)*sy; oe[5]=(1-(xx+zz))*sy; oe[6]=(yz+wx)*sy; oe[7]=0; oe[8]=(xz+wy)*sz; oe[9]=(yz-wx)*sz; oe[10]=(1-(xx+yy))*sz; oe[11]=0; oe[12]=te[0]; oe[13]=te[1]; oe[14]=te[2]; oe[15]=1; } Matrix4x4.createLookAt=function(eye,target,up,out){ var oE=out.elements; var xaxis=Matrix4x4._tempVector0; var yaxis=Matrix4x4._tempVector1; var zaxis=Matrix4x4._tempVector2; Vector3.subtract(eye,target,zaxis); Vector3.normalize(zaxis,zaxis); Vector3.cross(up,zaxis,xaxis); Vector3.normalize(xaxis,xaxis); Vector3.cross(zaxis,xaxis,yaxis); out.identity(); oE[0]=xaxis.x; oE[4]=xaxis.y; oE[8]=xaxis.z; oE[1]=yaxis.x; oE[5]=yaxis.y; oE[9]=yaxis.z; oE[2]=zaxis.x; oE[6]=zaxis.y; oE[10]=zaxis.z; oE[12]=-Vector3.dot(xaxis,eye); oE[13]=-Vector3.dot(yaxis,eye); oE[14]=-Vector3.dot(zaxis,eye); } Matrix4x4.createPerspective=function(fov,aspect,near,far,out){ var oe=out.elements; var f=1.0 / Math.tan(fov / 2),nf=1 / (near-far); oe[0]=f / aspect; oe[5]=f; oe[10]=(far+near)*nf; oe[11]=-1; oe[14]=(2 *far *near)*nf; oe[1]=oe[2]=oe[3]=oe[4]=oe[6]=oe[7]=oe[8]=oe[9]=oe[12]=oe[13]=oe[15]=0; } Matrix4x4.createOrthoOffCenterRH=function(left,right,bottom,top,near,far,out){ var oe=out.elements; var lr=1 / (left-right); var bt=1 / (bottom-top); var nf=1 / (near-far); oe[1]=oe[2]=oe[3]=oe[4]=oe[6]=oe[7]=oe[8]=oe[9]=oe[11]=0; oe[15]=1; oe[0]=-2 *lr; oe[5]=-2 *bt; oe[10]=2 *nf; oe[12]=(left+right)*lr; oe[13]=(top+bottom)*bt; oe[14]=(far+near)*nf; } Matrix4x4.translation=function(v3,out){ var ve=v3.elements; var oe=out.elements; oe[0]=oe[5]=oe[10]=oe[15]=1; oe[12]=ve[0]; oe[13]=ve[1]; oe[14]=ve[2]; } __static(Matrix4x4, ['_tempMatrix4x4',function(){return this._tempMatrix4x4=new Matrix4x4();},'_tempVector0',function(){return this._tempVector0=new Vector3();},'_tempVector1',function(){return this._tempVector1=new Vector3();},'_tempVector2',function(){return this._tempVector2=new Vector3();},'_tempQuaternion',function(){return this._tempQuaternion=new Quaternion();},'DEFAULT',function(){return this.DEFAULT=new Matrix4x4();},'ZERO',function(){return this.ZERO=new Matrix4x4( 0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0);} ]); return Matrix4x4; })() /** *OrientedBoundBox 类用于创建OBB包围盒。 */ //class laya.d3.math.OrientedBoundBox var OrientedBoundBox=(function(){ function OrientedBoundBox(extents,transformation){ /**每个轴长度的一半*/ this.extents=null; /**这个矩阵表示包围盒的位置和缩放,它的平移向量表示该包围盒的中心*/ this.transformation=null; this.extents=extents; this.transformation=transformation; } __class(OrientedBoundBox,'laya.d3.math.OrientedBoundBox'); var __proto=OrientedBoundBox.prototype; /** *获取OBB包围盒的8个顶点。 *@param corners 返回顶点的输出队列。 */ __proto.getCorners=function(corners){ var xve=OrientedBoundBox._tempV30.elements; var yve=OrientedBoundBox._tempV31.elements; var zve=OrientedBoundBox._tempV32.elements; var extentsE=this.extents.elements; xve[0]=extentsE[0]; xve[1]=xve[2]=0; yve[1]=extentsE[1]; yve[0]=yve[2]=0; zve[2]=extentsE[2]; zve[0]=zve[1]=0; Vector3.TransformNormal(OrientedBoundBox._tempV30,this.transformation,OrientedBoundBox._tempV30); Vector3.TransformNormal(OrientedBoundBox._tempV31,this.transformation,OrientedBoundBox._tempV31); Vector3.TransformNormal(OrientedBoundBox._tempV32,this.transformation,OrientedBoundBox._tempV32); var center=OrientedBoundBox._tempV33; this.transformation.getTranslationVector(center); corners.length=8; Vector3.add(center,OrientedBoundBox._tempV30,OrientedBoundBox._tempV34); Vector3.add(OrientedBoundBox._tempV34,OrientedBoundBox._tempV31,OrientedBoundBox._tempV34); Vector3.add(OrientedBoundBox._tempV34,OrientedBoundBox._tempV32,corners[0]); Vector3.add(center,OrientedBoundBox._tempV30,OrientedBoundBox._tempV34); Vector3.add(OrientedBoundBox._tempV34,OrientedBoundBox._tempV31,OrientedBoundBox._tempV34); Vector3.subtract(OrientedBoundBox._tempV34,OrientedBoundBox._tempV32,corners[1]); Vector3.subtract(center,OrientedBoundBox._tempV30,OrientedBoundBox._tempV34); Vector3.add(OrientedBoundBox._tempV34,OrientedBoundBox._tempV31,OrientedBoundBox._tempV34); Vector3.subtract(OrientedBoundBox._tempV34,OrientedBoundBox._tempV32,corners[2]); Vector3.subtract(center,OrientedBoundBox._tempV30,OrientedBoundBox._tempV34); Vector3.add(OrientedBoundBox._tempV34,OrientedBoundBox._tempV31,OrientedBoundBox._tempV34); Vector3.add(OrientedBoundBox._tempV34,OrientedBoundBox._tempV32,corners[3]); Vector3.add(center,OrientedBoundBox._tempV30,OrientedBoundBox._tempV34); Vector3.subtract(OrientedBoundBox._tempV34,OrientedBoundBox._tempV31,OrientedBoundBox._tempV34); Vector3.add(OrientedBoundBox._tempV34,OrientedBoundBox._tempV32,corners[4]); Vector3.add(center,OrientedBoundBox._tempV30,OrientedBoundBox._tempV34); Vector3.subtract(OrientedBoundBox._tempV34,OrientedBoundBox._tempV31,OrientedBoundBox._tempV34); Vector3.subtract(OrientedBoundBox._tempV34,OrientedBoundBox._tempV32,corners[5]); Vector3.subtract(center,OrientedBoundBox._tempV30,OrientedBoundBox._tempV34); Vector3.subtract(OrientedBoundBox._tempV34,OrientedBoundBox._tempV31,OrientedBoundBox._tempV34); Vector3.subtract(OrientedBoundBox._tempV34,OrientedBoundBox._tempV32,corners[6]); Vector3.subtract(center,OrientedBoundBox._tempV30,OrientedBoundBox._tempV34); Vector3.subtract(OrientedBoundBox._tempV34,OrientedBoundBox._tempV31,OrientedBoundBox._tempV34); Vector3.add(OrientedBoundBox._tempV34,OrientedBoundBox._tempV32,corners[7]); } /** *变换该包围盒的矩阵信息。 *@param mat 矩阵 */ __proto.transform=function(mat){ Matrix4x4.multiply(this.transformation,mat,this.transformation); } /** *缩放该包围盒 *@param scaling 各轴的缩放比。 */ __proto.scale=function(scaling){ Vector3.multiply(this.extents,scaling,this.extents); } /** *平移该包围盒。 *@param translation 平移参数 */ __proto.translate=function(translation){ this.transformation.getTranslationVector(OrientedBoundBox._tempV30); Vector3.add(OrientedBoundBox._tempV30,translation,OrientedBoundBox._tempV31); this.transformation.setTranslationVector(OrientedBoundBox._tempV31); } /** *该包围盒的尺寸。 *@param out 输出 */ __proto.Size=function(out){ Vector3.scale(this.extents,2,out); } /** *该包围盒需要考虑的尺寸 *@param out 输出 */ __proto.getSize=function(out){ var extentsE=this.extents.elements; OrientedBoundBox._tempV30.x=extentsE[0]; OrientedBoundBox._tempV31.y=extentsE[1]; OrientedBoundBox._tempV32.z=extentsE[2]; Vector3.TransformNormal(OrientedBoundBox._tempV30,this.transformation,OrientedBoundBox._tempV30); Vector3.TransformNormal(OrientedBoundBox._tempV31,this.transformation,OrientedBoundBox._tempV31); Vector3.TransformNormal(OrientedBoundBox._tempV31,this.transformation,OrientedBoundBox._tempV32); var oe=out.elements; oe[0]=Vector3.scalarLength(OrientedBoundBox._tempV30); oe[1]=Vector3.scalarLength(OrientedBoundBox._tempV31); oe[2]=Vector3.scalarLength(OrientedBoundBox._tempV32); } /** *该包围盒需要考虑尺寸的平方 *@param out 输出 */ __proto.getSizeSquared=function(out){ var extentsE=this.extents.elements; OrientedBoundBox._tempV30.x=extentsE[0]; OrientedBoundBox._tempV31.y=extentsE[1]; OrientedBoundBox._tempV32.z=extentsE[2]; Vector3.TransformNormal(OrientedBoundBox._tempV30,this.transformation,OrientedBoundBox._tempV30); Vector3.TransformNormal(OrientedBoundBox._tempV31,this.transformation,OrientedBoundBox._tempV31); Vector3.TransformNormal(OrientedBoundBox._tempV31,this.transformation,OrientedBoundBox._tempV32); var oe=out.elements; oe[0]=Vector3.scalarLengthSquared(OrientedBoundBox._tempV30); oe[1]=Vector3.scalarLengthSquared(OrientedBoundBox._tempV31); oe[2]=Vector3.scalarLengthSquared(OrientedBoundBox._tempV32); } /** *该包围盒的几何中心 */ __proto.getCenter=function(center){ this.transformation.getTranslationVector(center); } /** *该包围盒是否包含空间中一点 *@param point 点 *@return 返回位置关系 */ __proto.containsPoint=function(point){ var extentsE=this.extents.elements; var extentsEX=extentsE[0]; var extentsEY=extentsE[1]; var extentsEZ=extentsE[2]; this.transformation.invert(OrientedBoundBox._tempM0); Vector3.transformCoordinate(point,OrientedBoundBox._tempM0,OrientedBoundBox._tempV30); var _tempV30e=OrientedBoundBox._tempV30.elements; var _tempV30ex=Math.abs(_tempV30e[0]); var _tempV30ey=Math.abs(_tempV30e[1]); var _tempV30ez=Math.abs(_tempV30e[2]); if (MathUtils3D.nearEqual(_tempV30ex,extentsEX)&& MathUtils3D.nearEqual(_tempV30ey,extentsEY)&& MathUtils3D.nearEqual(_tempV30ez,extentsEZ)) return /*laya.d3.math.ContainmentType.Intersects*/2; if (_tempV30ex < extentsEX && _tempV30ey < extentsEY && _tempV30ez < extentsEZ) return /*laya.d3.math.ContainmentType.Contains*/1; else return /*laya.d3.math.ContainmentType.Disjoint*/0; } /** *该包围盒是否包含空间中多点 *@param point 点 *@return 返回位置关系 */ __proto.containsPoints=function(points){ var extentse=this.extents.elements; var extentsex=extentse[0]; var extentsey=extentse[1]; var extentsez=extentse[2]; this.transformation.invert(OrientedBoundBox._tempM0); var containsAll=true; var containsAny=false; for (var i=0;i < points.length;i++){ Vector3.transformCoordinate(points[i],OrientedBoundBox._tempM0,OrientedBoundBox._tempV30); var _tempV30e=OrientedBoundBox._tempV30.elements; var _tempV30ex=Math.abs(_tempV30e[0]); var _tempV30ey=Math.abs(_tempV30e[1]); var _tempV30ez=Math.abs(_tempV30e[2]); if (MathUtils3D.nearEqual(_tempV30ex,extentsex)&& MathUtils3D.nearEqual(_tempV30ey,extentsey)&& MathUtils3D.nearEqual(_tempV30ez,extentsez)) containsAny=true; if (_tempV30ex < extentsex && _tempV30ey < extentsey && _tempV30ez < extentsez) containsAny=true; else containsAll=false; } if (containsAll) return /*laya.d3.math.ContainmentType.Contains*/1; else if (containsAny) return /*laya.d3.math.ContainmentType.Intersects*/2; else return /*laya.d3.math.ContainmentType.Disjoint*/0; } /** *该包围盒是否包含空间中一包围球 *@param sphere 包围球 *@param ignoreScale 是否考虑该包围盒的缩放 *@return 返回位置关系 */ __proto.containsSphere=function(sphere,ignoreScale){ (ignoreScale===void 0)&& (ignoreScale=false); var extentsE=this.extents.elements; var extentsEX=extentsE[0]; var extentsEY=extentsE[1]; var extentsEZ=extentsE[2]; var sphereR=sphere.radius; this.transformation.invert(OrientedBoundBox._tempM0); Vector3.transformCoordinate(sphere.center,OrientedBoundBox._tempM0,OrientedBoundBox._tempV30); var locRadius=NaN; if (ignoreScale){ locRadius=sphereR; }else { Vector3.scale(Vector3.UnitX,sphereR,OrientedBoundBox._tempV31); Vector3.TransformNormal(OrientedBoundBox._tempV31,OrientedBoundBox._tempM0,OrientedBoundBox._tempV31); locRadius=Vector3.scalarLength(OrientedBoundBox._tempV31); } Vector3.scale(this.extents,-1,OrientedBoundBox._tempV32); Vector3.Clamp(OrientedBoundBox._tempV30,OrientedBoundBox._tempV32,this.extents,OrientedBoundBox._tempV33); var distance=Vector3.distanceSquared(OrientedBoundBox._tempV30,OrientedBoundBox._tempV33); if (distance > locRadius *locRadius) return /*laya.d3.math.ContainmentType.Disjoint*/0; var tempV30e=OrientedBoundBox._tempV30.elements; var tempV30ex=tempV30e[0]; var tempV30ey=tempV30e[1]; var tempV30ez=tempV30e[2]; var tempV32e=OrientedBoundBox._tempV32.elements; var tempV32ex=tempV32e[0]; var tempV32ey=tempV32e[1]; var tempV32ez=tempV32e[2]; if ((((tempV32ex+locRadius <=tempV30ex)&& (tempV30ex <=extentsEX-locRadius))&& ((extentsEX-tempV32ex > locRadius)&& (tempV32ey+locRadius <=tempV30ey)))&& (((tempV30ey <=extentsEY-locRadius)&& (extentsEY-tempV32ey > locRadius))&& (((tempV32ez+locRadius <=tempV30ez)&& (tempV30ez <=extentsEZ-locRadius))&& (extentsEZ-tempV32ez > locRadius)))){ return /*laya.d3.math.ContainmentType.Contains*/1; } return /*laya.d3.math.ContainmentType.Intersects*/2; } /** *For accuracy,The transformation matrix for both must not have any scaling applied to it. *Anyway,scaling using Scale method will keep this method accurate. *该包围盒是否包含空间中另一OBB包围盒 *@param obb OBB包围盒 *@return 返回位置关系 */ __proto.containsOrientedBoundBox=function(obb){ var i=0,k=0; obb.getCorners(OrientedBoundBox._corners); var cornersCheck=this.containsPoints(OrientedBoundBox._corners); if (cornersCheck !=/*laya.d3.math.ContainmentType.Disjoint*/0) return cornersCheck; var sizeAe=this.extents.elements; obb.extents.cloneTo(OrientedBoundBox._tempV35); var sizeBe=OrientedBoundBox._tempV35.elements; OrientedBoundBox._getRows(this.transformation,OrientedBoundBox._rows1); OrientedBoundBox._getRows(obb.transformation,OrientedBoundBox._rows2); var extentA=NaN,extentB=NaN,separation=NaN,dotNumber=NaN; for (i=0;i < 4;i++){ for (k=0;k < 4;k++){ if (i==3 || k==3){ OrientedBoundBox._tempM0.setElementByRowColumn(i,k,0); OrientedBoundBox._tempM1.setElementByRowColumn(i,k,0); }else { dotNumber=Vector3.dot(OrientedBoundBox._rows1[i],OrientedBoundBox._rows2[k]); OrientedBoundBox._tempM0.setElementByRowColumn(i,k,dotNumber); OrientedBoundBox._tempM1.setElementByRowColumn(i,k,Math.abs(dotNumber)); } } } obb.getCenter(OrientedBoundBox._tempV34); this.getCenter(OrientedBoundBox._tempV36); Vector3.subtract(OrientedBoundBox._tempV34,OrientedBoundBox._tempV36,OrientedBoundBox._tempV30); var vsepAe=OrientedBoundBox._tempV31.elements; vsepAe[0]=Vector3.dot(OrientedBoundBox._tempV30,OrientedBoundBox._rows1[0]); vsepAe[1]=Vector3.dot(OrientedBoundBox._tempV30,OrientedBoundBox._rows1[1]); vsepAe[2]=Vector3.dot(OrientedBoundBox._tempV30,OrientedBoundBox._rows1[2]); var _tempV32e=OrientedBoundBox._tempV32.elements; var _tempV33e=OrientedBoundBox._tempV33.elements; for (i=0;i < 3;i++){ _tempV32e[0]=OrientedBoundBox._tempM1.getElementByRowColumn(i,0); _tempV32e[1]=OrientedBoundBox._tempM1.getElementByRowColumn(i,1); _tempV32e[2]=OrientedBoundBox._tempM1.getElementByRowColumn(i,2); extentA=sizeAe[i]; extentB=Vector3.dot(OrientedBoundBox._tempV35,OrientedBoundBox._tempV32); separation=Math.abs(vsepAe[i]); if (separation > extentA+extentB) return /*laya.d3.math.ContainmentType.Disjoint*/0; } for (k=0;k < 3;k++){ _tempV32e[0]=OrientedBoundBox._tempM1.getElementByRowColumn(0,k); _tempV32e[1]=OrientedBoundBox._tempM1.getElementByRowColumn(1,k); _tempV32e[2]=OrientedBoundBox._tempM1.getElementByRowColumn(2,k); _tempV33e[0]=OrientedBoundBox._tempM0.getElementByRowColumn(0,k); _tempV33e[1]=OrientedBoundBox._tempM0.getElementByRowColumn(1,k); _tempV33e[2]=OrientedBoundBox._tempM0.getElementByRowColumn(2,k); extentA=Vector3.dot(this.extents,OrientedBoundBox._tempV32); extentB=sizeBe[k]; separation=Math.abs(Vector3.dot(OrientedBoundBox._tempV31,OrientedBoundBox._tempV33)); if (separation > extentA+extentB) return /*laya.d3.math.ContainmentType.Disjoint*/0; } for (i=0;i < 3;i++){ for (k=0;k < 3;k++){ var i1=(i+1)% 3,i2=(i+2)% 3; var k1=(k+1)% 3,k2=(k+2)% 3; extentA=sizeAe[i1] *OrientedBoundBox._tempM1.getElementByRowColumn(i2,k)+sizeAe[i2] *OrientedBoundBox._tempM1.getElementByRowColumn(i1,k); extentB=sizeBe[k1] *OrientedBoundBox._tempM1.getElementByRowColumn(i,k2)+sizeBe[k2] *OrientedBoundBox._tempM1.getElementByRowColumn(i,k1); separation=Math.abs(vsepAe[i2] *OrientedBoundBox._tempM0.getElementByRowColumn(i1,k)-vsepAe[i1] *OrientedBoundBox._tempM0.getElementByRowColumn(i2,k)); if (separation > extentA+extentB) return /*laya.d3.math.ContainmentType.Disjoint*/0; } } return /*laya.d3.math.ContainmentType.Intersects*/2; } /** *该包围盒是否包含空间中一条线 *@param point1 点1 *@param point2 点2 *@return 返回位置关系 */ __proto.containsLine=function(point1,point2){ OrientedBoundBox._corners[0]=point1; OrientedBoundBox._corners[1]=point2; var cornersCheck=this.containsPoints(OrientedBoundBox._corners); if (cornersCheck !=/*laya.d3.math.ContainmentType.Disjoint*/0) return cornersCheck; var extentsE=this.extents.elements; var extentsX=extentsE[0]; var extentsY=extentsE[1]; var extentsZ=extentsE[2]; this.transformation.invert(OrientedBoundBox._tempM0); Vector3.transformCoordinate(point1,OrientedBoundBox._tempM0,OrientedBoundBox._tempV30); Vector3.transformCoordinate(point2,OrientedBoundBox._tempM0,OrientedBoundBox._tempV31); Vector3.add(OrientedBoundBox._tempV30,OrientedBoundBox._tempV31,OrientedBoundBox._tempV32); Vector3.scale(OrientedBoundBox._tempV32,0.5,OrientedBoundBox._tempV32); Vector3.subtract(OrientedBoundBox._tempV30,OrientedBoundBox._tempV32,OrientedBoundBox._tempV33); var _tempV33e=OrientedBoundBox._tempV33.elements; var _tempV33X=_tempV33e[0]; var _tempV33Y=_tempV33e[1]; var _tempV33Z=_tempV33e[2]; var _tempV34e=OrientedBoundBox._tempV34.elements; var _tempV34X=_tempV34e[0]=Math.abs(_tempV33e[0]); var _tempV34Y=_tempV34e[1]=Math.abs(_tempV33e[1]); var _tempV34Z=_tempV34e[2]=Math.abs(_tempV33e[2]); var _tempV32e=OrientedBoundBox._tempV32.elements; var _tempV32X=_tempV32e[0]; var _tempV32Y=_tempV32e[1]; var _tempV32Z=_tempV32e[2]; if (Math.abs(_tempV32X)> extentsX+_tempV34X) return /*laya.d3.math.ContainmentType.Disjoint*/0; if (Math.abs(_tempV32Y)> extentsY+_tempV34Y) return /*laya.d3.math.ContainmentType.Disjoint*/0; if (Math.abs(_tempV32Z)> extentsZ+_tempV34Z) return /*laya.d3.math.ContainmentType.Disjoint*/0; if (Math.abs(_tempV32Y *_tempV33Z-_tempV32Z *_tempV33Y)> (extentsY *_tempV34Z+extentsZ *_tempV34Y)) return /*laya.d3.math.ContainmentType.Disjoint*/0; if (Math.abs(_tempV32X *_tempV33Z-_tempV32Z *_tempV33X)> (extentsX *_tempV34Z+extentsZ *_tempV34X)) return /*laya.d3.math.ContainmentType.Disjoint*/0; if (Math.abs(_tempV32X *_tempV33Y-_tempV32Y *_tempV33X)> (extentsX *_tempV34Y+extentsY *_tempV34X)) return /*laya.d3.math.ContainmentType.Disjoint*/0; return /*laya.d3.math.ContainmentType.Intersects*/2; } /** *该包围盒是否包含空间中另一OBB包围盒 *@param box 包围盒 *@return 返回位置关系 */ __proto.containsBoundBox=function(box){ var i=0,k=0; var min=box.min; var max=box.max; box.getCorners(OrientedBoundBox._corners); var cornersCheck=this.containsPoints(OrientedBoundBox._corners); if (cornersCheck !=/*laya.d3.math.ContainmentType.Disjoint*/0) return cornersCheck; Vector3.subtract(max,min,OrientedBoundBox._tempV30); Vector3.scale(OrientedBoundBox._tempV30,0.5,OrientedBoundBox._tempV30); Vector3.add(min,OrientedBoundBox._tempV30,OrientedBoundBox._tempV30); Vector3.subtract(max,OrientedBoundBox._tempV30,OrientedBoundBox._tempV31); var sizeAe=this.extents.elements; var sizeBe=OrientedBoundBox._tempV31.elements; OrientedBoundBox._getRows(this.transformation,OrientedBoundBox._rows1); this.transformation.invert(OrientedBoundBox._tempM0); var extentA=NaN,extentB=NaN,separation=NaN,dotNumber=NaN; for (i=0;i < 3;i++){ for (k=0;k < 3;k++){ OrientedBoundBox._tempM1.setElementByRowColumn(i,k,Math.abs(OrientedBoundBox._tempM0.getElementByRowColumn(i,k))); } } this.getCenter(OrientedBoundBox._tempV35); Vector3.subtract(OrientedBoundBox._tempV30,OrientedBoundBox._tempV35,OrientedBoundBox._tempV32); var vsepAe=OrientedBoundBox._tempV31.elements; vsepAe[0]=Vector3.dot(OrientedBoundBox._tempV32,OrientedBoundBox._rows1[0]); vsepAe[1]=Vector3.dot(OrientedBoundBox._tempV32,OrientedBoundBox._rows1[1]); vsepAe[2]=Vector3.dot(OrientedBoundBox._tempV32,OrientedBoundBox._rows1[2]); var _tempV33e=OrientedBoundBox._tempV33.elements; var _tempV34e=OrientedBoundBox._tempV34.elements; for (i=0;i < 3;i++){ _tempV33e[0]=OrientedBoundBox._tempM1.getElementByRowColumn(i,0); _tempV33e[1]=OrientedBoundBox._tempM1.getElementByRowColumn(i,1); _tempV33e[2]=OrientedBoundBox._tempM1.getElementByRowColumn(i,2); extentA=sizeAe[i]; extentB=Vector3.dot(OrientedBoundBox._tempV31,OrientedBoundBox._tempV33); separation=Math.abs(vsepAe[i]); if (separation > extentA+extentB) return /*laya.d3.math.ContainmentType.Disjoint*/0; } for (k=0;k < 3;k++){ _tempV33e[0]=OrientedBoundBox._tempM1.getElementByRowColumn(0,k); _tempV33e[1]=OrientedBoundBox._tempM1.getElementByRowColumn(1,k); _tempV33e[2]=OrientedBoundBox._tempM1.getElementByRowColumn(2,k); _tempV34e[0]=OrientedBoundBox._tempM0.getElementByRowColumn(0,k); _tempV34e[1]=OrientedBoundBox._tempM0.getElementByRowColumn(1,k); _tempV34e[2]=OrientedBoundBox._tempM0.getElementByRowColumn(2,k); extentA=Vector3.dot(this.extents,OrientedBoundBox._tempV33); extentB=sizeBe[k]; separation=Math.abs(Vector3.dot(OrientedBoundBox._tempV31,OrientedBoundBox._tempV34)); if (separation > extentA+extentB) return /*laya.d3.math.ContainmentType.Disjoint*/0; } for (i=0;i < 3;i++){ for (k=0;k < 3;k++){ var i1=(i+1)% 3,i2=(i+2)% 3; var k1=(k+1)% 3,k2=(k+2)% 3; extentA=sizeAe[i1] *OrientedBoundBox._tempM1.getElementByRowColumn(i2,k)+sizeAe[i2] *OrientedBoundBox._tempM1.getElementByRowColumn(i1,k); extentB=sizeBe[k1] *OrientedBoundBox._tempM1.getElementByRowColumn(i,k2)+sizeBe[k2] *OrientedBoundBox._tempM1.getElementByRowColumn(i,k1); separation=Math.abs(vsepAe[i2] *OrientedBoundBox._tempM0.getElementByRowColumn(i1,k)-vsepAe[i1] *OrientedBoundBox._tempM0.getElementByRowColumn(i2,k)); if (separation > extentA+extentB) return /*laya.d3.math.ContainmentType.Disjoint*/0; } } return /*laya.d3.math.ContainmentType.Intersects*/2; } /** *该包围盒是否与空间中另一射线相交 *@param ray *@param out *@return */ __proto.intersectsRay=function(ray,out){ Vector3.scale(this.extents,-1,OrientedBoundBox._tempV30); this.transformation.invert(OrientedBoundBox._tempM0); Vector3.TransformNormal(ray.direction,OrientedBoundBox._tempM0,OrientedBoundBox._ray.direction); Vector3.transformCoordinate(ray.origin,OrientedBoundBox._tempM0,OrientedBoundBox._ray.origin); OrientedBoundBox._boxBound1.min=OrientedBoundBox._tempV30; OrientedBoundBox._boxBound1.max=this.extents; var intersects=Collision.intersectsRayAndBoxRP(OrientedBoundBox._ray,OrientedBoundBox._boxBound1,out); if (intersects!==-1) Vector3.transformCoordinate(out,this.transformation,out); return intersects; } __proto._getLocalCorners=function(corners){ corners.length=8; var extentsE=this.extents.elements; OrientedBoundBox._tempV30.x=extentsE[0]; OrientedBoundBox._tempV31.y=extentsE[1]; OrientedBoundBox._tempV32.z=extentsE[2]; Vector3.add(OrientedBoundBox._tempV30,OrientedBoundBox._tempV31,OrientedBoundBox._tempV33); Vector3.add(OrientedBoundBox._tempV33,OrientedBoundBox._tempV32,corners[0]); Vector3.add(OrientedBoundBox._tempV30,OrientedBoundBox._tempV31,OrientedBoundBox._tempV33); Vector3.subtract(OrientedBoundBox._tempV33,OrientedBoundBox._tempV32,corners[1]); Vector3.subtract(OrientedBoundBox._tempV31,OrientedBoundBox._tempV30,OrientedBoundBox._tempV33); Vector3.subtract(OrientedBoundBox._tempV33,OrientedBoundBox._tempV30,corners[2]); Vector3.subtract(OrientedBoundBox._tempV31,OrientedBoundBox._tempV30,OrientedBoundBox._tempV33); Vector3.add(OrientedBoundBox._tempV33,OrientedBoundBox._tempV32,corners[3]); Vector3.subtract(OrientedBoundBox._tempV30,OrientedBoundBox._tempV31,OrientedBoundBox._tempV33); Vector3.add(OrientedBoundBox._tempV33,OrientedBoundBox._tempV32,corners[4]); Vector3.subtract(OrientedBoundBox._tempV30,OrientedBoundBox._tempV31,OrientedBoundBox._tempV33); Vector3.subtract(OrientedBoundBox._tempV33,OrientedBoundBox._tempV32,corners[5]); Vector3.scale(corners[0],-1,corners[6]); Vector3.subtract(OrientedBoundBox._tempV32,OrientedBoundBox._tempV30,OrientedBoundBox._tempV33); Vector3.subtract(OrientedBoundBox._tempV33,OrientedBoundBox._tempV31,corners[7]); } /** *判断两个包围盒是否相等 *@param obb obb包围盒 *@return Boolean */ __proto.equals=function(obb){ return this.extents==obb.extents && this.transformation==obb.transformation; } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var dest=destObject; this.extents.cloneTo(dest.extents); this.transformation.cloneTo(dest.transformation); } OrientedBoundBox.createByBoundBox=function(box,out){ var min=box.min; var max=box.max; Vector3.subtract(max,min,OrientedBoundBox._tempV30); Vector3.scale(OrientedBoundBox._tempV30,0.5,OrientedBoundBox._tempV30); Vector3.add(min,OrientedBoundBox._tempV30,OrientedBoundBox._tempV31); Vector3.subtract(max,OrientedBoundBox._tempV31,OrientedBoundBox._tempV32); Matrix4x4.translation(OrientedBoundBox._tempV31,OrientedBoundBox._tempM0); var extents=OrientedBoundBox._tempV32.clone(); var transformation=OrientedBoundBox._tempM0.clone(); out.extents=extents; out.transformation=transformation; } OrientedBoundBox.createByMinAndMaxVertex=function(min,max){ Vector3.subtract(max,min,OrientedBoundBox._tempV30); Vector3.scale(OrientedBoundBox._tempV30,0.5,OrientedBoundBox._tempV30); Vector3.add(min,OrientedBoundBox._tempV30,OrientedBoundBox._tempV31); Vector3.subtract(max,OrientedBoundBox._tempV31,OrientedBoundBox._tempV32); Matrix4x4.translation(OrientedBoundBox._tempV31,OrientedBoundBox._tempM0); var obb=new OrientedBoundBox(OrientedBoundBox._tempV32,OrientedBoundBox._tempM0); return obb; } OrientedBoundBox._getRows=function(mat,out){ out.length=3; var mate=mat.elements; var row0e=out[0].elements; row0e[0]=mate[0]; row0e[1]=mate[1]; row0e[2]=mate[2]; var row1e=out[1].elements; row1e[0]=mate[4]; row1e[1]=mate[5]; row1e[2]=mate[6]; var row2e=out[2].elements; row2e[0]=mate[8]; row2e[1]=mate[9]; row2e[2]=mate[10]; } OrientedBoundBox.getObbtoObbMatrix4x4=function(a,b,noMatrixScaleApplied,out){ var at=a.transformation; var bt=b.transformation; if (noMatrixScaleApplied){ OrientedBoundBox._getRows(at,OrientedBoundBox._rows1); OrientedBoundBox._getRows(bt,OrientedBoundBox._rows2); for (var i=0;i < 3;i++){ for (var k=0;k < 3;k++){ out.setElementByRowColumn(i,k,Vector3.dot(OrientedBoundBox._rows2[i],OrientedBoundBox._rows1[k])); } } b.getCenter(OrientedBoundBox._tempV30); a.getCenter(OrientedBoundBox._tempV31); Vector3.subtract(OrientedBoundBox._tempV30,OrientedBoundBox._tempV31,OrientedBoundBox._tempV32); var AtoBMe=out.elements; AtoBMe[12]=Vector3.dot(OrientedBoundBox._tempV32,OrientedBoundBox._rows1[0]); AtoBMe[13]=Vector3.dot(OrientedBoundBox._tempV32,OrientedBoundBox._rows1[1]); AtoBMe[14]=Vector3.dot(OrientedBoundBox._tempV32,OrientedBoundBox._rows1[2]); AtoBMe[15]=1; }else { at.invert(OrientedBoundBox._tempM0); Matrix4x4.multiply(bt,OrientedBoundBox._tempM0,out); } } OrientedBoundBox.merge=function(a,b,noMatrixScaleApplied){ var ae=a.extents; var at=a.transformation; OrientedBoundBox.getObbtoObbMatrix4x4(a,b,noMatrixScaleApplied,OrientedBoundBox._tempM0); b._getLocalCorners(OrientedBoundBox._corners); Vector3.transformCoordinate(OrientedBoundBox._corners[0],OrientedBoundBox._tempM0,OrientedBoundBox._corners[0]); Vector3.transformCoordinate(OrientedBoundBox._corners[1],OrientedBoundBox._tempM0,OrientedBoundBox._corners[1]); Vector3.transformCoordinate(OrientedBoundBox._corners[2],OrientedBoundBox._tempM0,OrientedBoundBox._corners[2]); Vector3.transformCoordinate(OrientedBoundBox._corners[3],OrientedBoundBox._tempM0,OrientedBoundBox._corners[3]); Vector3.transformCoordinate(OrientedBoundBox._corners[4],OrientedBoundBox._tempM0,OrientedBoundBox._corners[4]); Vector3.transformCoordinate(OrientedBoundBox._corners[5],OrientedBoundBox._tempM0,OrientedBoundBox._corners[5]); Vector3.transformCoordinate(OrientedBoundBox._corners[6],OrientedBoundBox._tempM0,OrientedBoundBox._corners[6]); Vector3.transformCoordinate(OrientedBoundBox._corners[7],OrientedBoundBox._tempM0,OrientedBoundBox._corners[7]); Vector3.scale(ae,-1,OrientedBoundBox._boxBound1.min); ae.cloneTo(OrientedBoundBox._boxBound1.max); BoundBox.createfromPoints(OrientedBoundBox._corners,OrientedBoundBox._boxBound2); BoundBox.merge(OrientedBoundBox._boxBound2,OrientedBoundBox._boxBound1,OrientedBoundBox._boxBound3); var box3Min=OrientedBoundBox._boxBound3.min; var box3Max=OrientedBoundBox._boxBound3.max; Vector3.subtract(box3Max,box3Min,OrientedBoundBox._tempV30); Vector3.scale(OrientedBoundBox._tempV30,0.5,OrientedBoundBox._tempV30); Vector3.add(box3Min,OrientedBoundBox._tempV30,OrientedBoundBox._tempV32); Vector3.subtract(box3Max,OrientedBoundBox._tempV32,ae); Vector3.transformCoordinate(OrientedBoundBox._tempV32,at,OrientedBoundBox._tempV33); } __static(OrientedBoundBox, ['_tempV30',function(){return this._tempV30=new Vector3();},'_tempV31',function(){return this._tempV31=new Vector3();},'_tempV32',function(){return this._tempV32=new Vector3();},'_tempV33',function(){return this._tempV33=new Vector3();},'_tempV34',function(){return this._tempV34=new Vector3();},'_tempV35',function(){return this._tempV35=new Vector3();},'_tempV36',function(){return this._tempV36=new Vector3();},'_tempM0',function(){return this._tempM0=new Matrix4x4();},'_tempM1',function(){return this._tempM1=new Matrix4x4();},'_corners',function(){return this._corners=/*new vector.<>*/[new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3()];},'_rows1',function(){return this._rows1=/*new vector.<>*/[new Vector3(),new Vector3(),new Vector3()];},'_rows2',function(){return this._rows2=/*new vector.<>*/[new Vector3(),new Vector3(),new Vector3()];},'_ray',function(){return this._ray=new Ray(new Vector3(),new Vector3());},'_boxBound1',function(){return this._boxBound1=new BoundBox(new Vector3(),new Vector3());},'_boxBound2',function(){return this._boxBound2=new BoundBox(new Vector3(),new Vector3());},'_boxBound3',function(){return this._boxBound3=new BoundBox(new Vector3(),new Vector3());} ]); return OrientedBoundBox; })() /** *Plane 类用于创建平面。 */ //class laya.d3.math.Plane var Plane=(function(){ function Plane(normal,d){ /**平面的向量*/ this.normal=null; /**平面到坐标系原点的距离*/ this.distance=NaN; (d===void 0)&& (d=0); this.normal=normal; this.distance=d; } __class(Plane,'laya.d3.math.Plane'); var __proto=Plane.prototype; /** *更改平面法线向量的系数,使之成单位长度。 */ __proto.normalize=function(){ var normalE=this.normal.elements; var normalEX=normalE[0]; var normalEY=normalE[1]; var normalEZ=normalE[2]; var magnitude=1 / Math.sqrt(normalEX *normalEX+normalEY *normalEY+normalEZ *normalEZ); normalE[0]=normalEX *magnitude; normalE[1]=normalEY *magnitude; normalE[2]=normalEZ *magnitude; this.distance *=magnitude; } Plane.createPlaneBy3P=function(point1,point2,point3){ var point1e=point1.elements; var point2e=point2.elements; var point3e=point3.elements; var x1=point2e[0]-point1e[0]; var y1=point2e[1]-point1e[1]; var z1=point2e[2]-point1e[2]; var x2=point3e[0]-point1e[0]; var y2=point3e[1]-point1e[1]; var z2=point3e[2]-point1e[2]; var yz=(y1 *z2)-(z1 *y2); var xz=(z1 *x2)-(x1 *z2); var xy=(x1 *y2)-(y1 *x2); var invPyth=1 / (Math.sqrt((yz *yz)+(xz *xz)+(xy *xy))); var x=yz *invPyth; var y=xz *invPyth; var z=xy *invPyth; var TEMPVec3e=Plane._TEMPVec3.elements; TEMPVec3e[0]=x; TEMPVec3e[1]=y; TEMPVec3e[2]=z; var d=-((x *point1e[0])+(y *point1e[1])+(z *point1e[2])); var plane=new Plane(Plane._TEMPVec3,d); return plane; } Plane.PlaneIntersectionType_Back=0; Plane.PlaneIntersectionType_Front=1; Plane.PlaneIntersectionType_Intersecting=2; __static(Plane, ['_TEMPVec3',function(){return this._TEMPVec3=new Vector3();} ]); return Plane; })() /** *Quaternion 类用于创建四元数。 */ //class laya.d3.math.Quaternion var Quaternion=(function(){ function Quaternion(x,y,z,w){ this.elements=new Float32Array(4); (x===void 0)&& (x=0); (y===void 0)&& (y=0); (z===void 0)&& (z=0); (w===void 0)&& (w=1); this.elements[0]=x; this.elements[1]=y; this.elements[2]=z; this.elements[3]=w; } __class(Quaternion,'laya.d3.math.Quaternion'); var __proto=Quaternion.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *根据缩放值缩放四元数 *@param scale 缩放值 *@param out 输出四元数 */ __proto.scaling=function(scaling,out){ var e=out.elements; var f=this.elements; e[0]=f[0] *scaling; e[1]=f[1] *scaling; e[2]=f[2] *scaling; e[3]=f[3] *scaling; } /** *归一化四元数 *@param out 输出四元数 */ __proto.normalize=function(out){ var e=out.elements; var f=this.elements; var x=f[0],y=f[1],z=f[2],w=f[3]; var len=x *x+y *y+z *z+w *w; if (len > 0){ len=1 / Math.sqrt(len); e[0]=x *len; e[1]=y *len; e[2]=z *len; e[3]=w *len; } } /** *计算四元数的长度 *@return 长度 */ __proto.length=function(){ var f=this.elements; var x=f[0],y=f[1],z=f[2],w=f[3]; return Math.sqrt(x *x+y *y+z *z+w *w); } /** *根据绕X轴的角度旋转四元数 *@param rad 角度 *@param out 输出四元数 */ __proto.rotateX=function(rad,out){ var e=out.elements; var f=this.elements; rad *=0.5; var ax=f[0],ay=f[1],az=f[2],aw=f[3]; var bx=Math.sin(rad),bw=Math.cos(rad); e[0]=ax *bw+aw *bx; e[1]=ay *bw+az *bx; e[2]=az *bw-ay *bx; e[3]=aw *bw-ax *bx; } /** *根据绕Y轴的制定角度旋转四元数 *@param rad 角度 *@param out 输出四元数 */ __proto.rotateY=function(rad,out){ var e=out.elements; var f=this.elements; rad *=0.5; var ax=f[0],ay=f[1],az=f[2],aw=f[3],by=Math.sin(rad),bw=Math.cos(rad); e[0]=ax *bw-az *by; e[1]=ay *bw+aw *by; e[2]=az *bw+ax *by; e[3]=aw *bw-ay *by; } /** *根据绕Z轴的制定角度旋转四元数 *@param rad 角度 *@param out 输出四元数 */ __proto.rotateZ=function(rad,out){ var e=out.elements; var f=this.elements; rad *=0.5; var ax=f[0],ay=f[1],az=f[2],aw=f[3],bz=Math.sin(rad),bw=Math.cos(rad); e[0]=ax *bw+ay *bz; e[1]=ay *bw-ax *bz; e[2]=az *bw+aw *bz; e[3]=aw *bw-az *bz; } /** *分解四元数到欧拉角(顺序为Yaw、Pitch、Roll),参考自http://xboxforums.create.msdn.com/forums/p/4574/23988.aspx#23988,问题绕X轴翻转超过±90度时有,会产生瞬间反转 *@param quaternion 源四元数 *@param out 欧拉角值 */ __proto.getYawPitchRoll=function(out){ Vector3.transformQuat(Vector3.ForwardRH,this,Quaternion.TEMPVector31); Vector3.transformQuat(Vector3.Up,this,Quaternion.TEMPVector32); var upe=Quaternion.TEMPVector32.elements; Quaternion.angleTo(Vector3.ZERO,Quaternion.TEMPVector31,Quaternion.TEMPVector33); var anglee=Quaternion.TEMPVector33.elements; if (anglee[0]==Math.PI / 2){ anglee[1]=Quaternion.arcTanAngle(upe[2],upe[0]); anglee[2]=0; }else if (anglee[0]==-Math.PI / 2){ anglee[1]=Quaternion.arcTanAngle(-upe[2],-upe[0]); anglee[2]=0; }else { Matrix4x4.createRotationY(-anglee[1],Quaternion.TEMPMatrix0); Matrix4x4.createRotationX(-anglee[0],Quaternion.TEMPMatrix1); Vector3.transformCoordinate(Quaternion.TEMPVector32,Quaternion.TEMPMatrix0,Quaternion.TEMPVector32); Vector3.transformCoordinate(Quaternion.TEMPVector32,Quaternion.TEMPMatrix1,Quaternion.TEMPVector32); anglee[2]=Quaternion.arcTanAngle(upe[1],-upe[0]); } if (anglee[1] <=-Math.PI) anglee[1]=Math.PI; if (anglee[2] <=-Math.PI) anglee[2]=Math.PI; if (anglee[1] >=Math.PI && anglee[2] >=Math.PI){ anglee[1]=0; anglee[2]=0; anglee[0]=Math.PI-anglee[0]; }; var oe=out.elements; oe[0]=anglee[1]; oe[1]=anglee[0]; oe[2]=anglee[2]; } /** *求四元数的逆 *@param out 输出四元数 */ __proto.invert=function(out){ var e=out.elements; var f=this.elements; var a0=f[0],a1=f[1],a2=f[2],a3=f[3]; var dot=a0 *a0+a1 *a1+a2 *a2+a3 *a3; var invDot=dot ? 1.0 / dot :0; e[0]=-a0 *invDot; e[1]=-a1 *invDot; e[2]=-a2 *invDot; e[3]=a3 *invDot; } /** *设置四元数为单位算数 *@param out 输出四元数 */ __proto.identity=function(){ var e=this.elements; e[0]=0; e[1]=0; e[2]=0; e[3]=1; } /** *从Array数组拷贝值。 *@param array 数组。 *@param offset 数组偏移。 */ __proto.fromArray=function(array,offset){ (offset===void 0)&& (offset=0); this.elements[0]=array[offset+0]; this.elements[1]=array[offset+1]; this.elements[2]=array[offset+2]; this.elements[3]=array[offset+3]; } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var i,s,d; s=this.elements; d=destObject.elements; if (s===d){ return; } for (i=0;i < 4;++i){ d[i]=s[i]; } } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var dest=/*__JS__ */new this.constructor(); this.cloneTo(dest); return dest; } __proto.equals=function(b){ var ae=this.elements; var be=b.elements; return MathUtils3D.nearEqual(ae[0],be[0])&& MathUtils3D.nearEqual(ae[1],be[1])&& MathUtils3D.nearEqual(ae[2],be[2])&& MathUtils3D.nearEqual(ae[3],be[3]); } /** *计算长度的平方。 *@return 长度的平方。 */ __proto.lengthSquared=function(){ var x=this.elements[0]; var y=this.elements[1]; var z=this.elements[2]; var w=this.elements[3]; return (x *x)+(y *y)+(z *z)+(w *w); } /** *获取四元数的x值 */ __getset(0,__proto,'x',function(){ return this.elements[0]; }); /** *获取四元数的y值 */ __getset(0,__proto,'y',function(){ return this.elements[1]; }); /** *获取四元数的z值 */ __getset(0,__proto,'z',function(){ return this.elements[2]; }); /** *获取四元数的w值 */ __getset(0,__proto,'w',function(){ return this.elements[3]; }); Quaternion.createFromYawPitchRoll=function(yaw,pitch,roll,out){ var halfRoll=roll *0.5; var halfPitch=pitch *0.5; var halfYaw=yaw *0.5; var sinRoll=Math.sin(halfRoll); var cosRoll=Math.cos(halfRoll); var sinPitch=Math.sin(halfPitch); var cosPitch=Math.cos(halfPitch); var sinYaw=Math.sin(halfYaw); var cosYaw=Math.cos(halfYaw); var oe=out.elements; oe[0]=(cosYaw *sinPitch *cosRoll)+(sinYaw *cosPitch *sinRoll); oe[1]=(sinYaw *cosPitch *cosRoll)-(cosYaw *sinPitch *sinRoll); oe[2]=(cosYaw *cosPitch *sinRoll)-(sinYaw *sinPitch *cosRoll); oe[3]=(cosYaw *cosPitch *cosRoll)+(sinYaw *sinPitch *sinRoll); } Quaternion.multiply=function(left,right,out){ var le=left.elements; var re=right.elements; var oe=out.elements; var lx=le[0]; var ly=le[1]; var lz=le[2]; var lw=le[3]; var rx=re[0]; var ry=re[1]; var rz=re[2]; var rw=re[3]; var a=(ly *rz-lz *ry); var b=(lz *rx-lx *rz); var c=(lx *ry-ly *rx); var d=(lx *rx+ly *ry+lz *rz); oe[0]=(lx *rw+rx *lw)+a; oe[1]=(ly *rw+ry *lw)+b; oe[2]=(lz *rw+rz *lw)+c; oe[3]=lw *rw-d; } Quaternion.arcTanAngle=function(x,y){ if (x==0){ if (y==1) return Math.PI / 2; return-Math.PI / 2; } if (x > 0) return Math.atan(y / x); if (x < 0){ if (y > 0) return Math.atan(y / x)+Math.PI; return Math.atan(y / x)-Math.PI; } return 0; } Quaternion.angleTo=function(from,location,angle){ Vector3.subtract(location,from,Quaternion.TEMPVector30); Vector3.normalize(Quaternion.TEMPVector30,Quaternion.TEMPVector30); angle.elements[0]=Math.asin(Quaternion.TEMPVector30.y); angle.elements[1]=Quaternion.arcTanAngle(-Quaternion.TEMPVector30.z,-Quaternion.TEMPVector30.x); } Quaternion.createFromAxisAngle=function(axis,rad,out){ var e=out.elements; var f=axis.elements; rad=rad *0.5; var s=Math.sin(rad); e[0]=s *f[0]; e[1]=s *f[1]; e[2]=s *f[2]; e[3]=Math.cos(rad); } Quaternion.createFromMatrix3x3=function(sou,out){ var e=out.elements; var f=sou.elements; var fTrace=f[0]+f[4]+f[8]; var fRoot; if (fTrace > 0.0){ fRoot=Math.sqrt(fTrace+1.0); e[3]=0.5 *fRoot; fRoot=0.5 / fRoot; e[0]=(f[5]-f[7])*fRoot; e[1]=(f[6]-f[2])*fRoot; e[2]=(f[1]-f[3])*fRoot; }else { var i=0; if (f[4] > f[0]) i=1; if (f[8] > f[i *3+i]) i=2; var j=(i+1)% 3; var k=(i+2)% 3; fRoot=Math.sqrt(f[i *3+i]-f[j *3+j]-f[k *3+k]+1.0); e[i]=0.5 *fRoot; fRoot=0.5 / fRoot; e[3]=(f[j *3+k]-f[k *3+j])*fRoot; e[j]=(f[j *3+i]+f[i *3+j])*fRoot; e[k]=(f[k *3+i]+f[i *3+k])*fRoot; } return; } Quaternion.createFromMatrix4x4=function(mat,out){ var me=mat.elements; var oe=out.elements; var sqrt; var half; var scale=me[0]+me[5]+me[10]; if (scale > 0.0){ sqrt=Math.sqrt(scale+1.0); oe[3]=sqrt *0.5; sqrt=0.5 / sqrt; oe[0]=(me[6]-me[9])*sqrt; oe[1]=(me[8]-me[2])*sqrt; oe[2]=(me[1]-me[4])*sqrt; }else if ((me[0] >=me[5])&& (me[0] >=me[10])){ sqrt=Math.sqrt(1.0+me[0]-me[5]-me[10]); half=0.5 / sqrt; oe[0]=0.5 *sqrt; oe[1]=(me[1]+me[4])*half; oe[2]=(me[2]+me[8])*half; oe[3]=(me[6]-me[9])*half; }else if (me[5] > me[10]){ sqrt=Math.sqrt(1.0+me[5]-me[0]-me[10]); half=0.5 / sqrt; oe[0]=(me[4]+me[1])*half; oe[1]=0.5 *sqrt; oe[2]=(me[9]+me[6])*half; oe[3]=(me[8]-me[2])*half; }else { sqrt=Math.sqrt(1.0+me[10]-me[0]-me[5]); half=0.5 / sqrt; oe[0]=(me[8]+me[2])*half; oe[1]=(me[9]+me[6])*half; oe[2]=0.5 *sqrt; oe[3]=(me[1]-me[4])*half; } } Quaternion.slerp=function(left,right,t,out){ var a=left.elements; var b=right.elements; var oe=out.elements; var ax=a[0],ay=a[1],az=a[2],aw=a[3],bx=b[0],by=b[1],bz=b[2],bw=b[3]; var omega,cosom,sinom,scale0,scale1; cosom=ax *bx+ay *by+az *bz+aw *bw; if (cosom < 0.0){ cosom=-cosom; bx=-bx; by=-by; bz=-bz; bw=-bw; } if ((1.0-cosom)> 0.000001){ omega=Math.acos(cosom); sinom=Math.sin(omega); scale0=Math.sin((1.0-t)*omega)/ sinom; scale1=Math.sin(t *omega)/ sinom; }else { scale0=1.0-t; scale1=t; } oe[0]=scale0 *ax+scale1 *bx; oe[1]=scale0 *ay+scale1 *by; oe[2]=scale0 *az+scale1 *bz; oe[3]=scale0 *aw+scale1 *bw; return oe; } Quaternion.lerp=function(left,right,t,out){ var e=out.elements; var f=left.elements; var g=right.elements; var ax=f[0],ay=f[1],az=f[2],aw=f[3]; e[0]=ax+t *(g[0]-ax); e[1]=ay+t *(g[1]-ay); e[2]=az+t *(g[2]-az); e[3]=aw+t *(g[3]-aw); } Quaternion.add=function(left,right,out){ var e=out.elements; var f=left.elements; var g=right.elements; e[0]=f[0]+g[0]; e[1]=f[1]+g[1]; e[2]=f[2]+g[2]; e[3]=f[3]+g[3]; } Quaternion.dot=function(left,right){ var f=left.elements; var g=right.elements; return f[0] *g[0]+f[1] *g[1]+f[2] *g[2]+f[3] *g[3]; } Quaternion.rotationLookAt=function(forward,up,out){ Quaternion.lookAt(Vector3.ZERO,forward,up,out); } Quaternion.lookAt=function(eye,target,up,out){ Matrix3x3.lookAt(eye,target,up,Quaternion._tempMatrix3x3); Quaternion.rotationMatrix(Quaternion._tempMatrix3x3,out); } Quaternion.invert=function(value,out){ var vE=value.elements; var oE=out.elements; var lengthSq=value.lengthSquared(); if (!MathUtils3D.isZero(lengthSq)){ lengthSq=1.0 / lengthSq; oE[0]=-vE[0] *lengthSq; oE[1]=-vE[1] *lengthSq; oE[2]=-vE[2] *lengthSq; oE[3]=vE[3] *lengthSq; } } Quaternion.rotationMatrix=function(matrix3x3,out){ var me=matrix3x3.elements; var m11=me[0]; var m12=me[1]; var m13=me[2]; var m21=me[3]; var m22=me[4]; var m23=me[5]; var m31=me[6]; var m32=me[7]; var m33=me[8]; var oe=out.elements; var sqrt=NaN,half=NaN; var scale=m11+m22+m33; if (scale > 0){ sqrt=Math.sqrt(scale+1); oe[3]=sqrt *0.5; sqrt=0.5 / sqrt; oe[0]=(m23-m32)*sqrt; oe[1]=(m31-m13)*sqrt; oe[2]=(m12-m21)*sqrt; }else if ((m11 >=m22)&& (m11 >=m33)){ sqrt=Math.sqrt(1+m11-m22-m33); half=0.5 / sqrt; oe[0]=0.5 *sqrt; oe[1]=(m12+m21)*half; oe[2]=(m13+m31)*half; oe[3]=(m23-m32)*half; }else if (m22 > m33){ sqrt=Math.sqrt(1+m22-m11-m33); half=0.5 / sqrt; oe[0]=(m21+m12)*half; oe[1]=0.5 *sqrt; oe[2]=(m32+m23)*half; oe[3]=(m31-m13)*half; }else { sqrt=Math.sqrt(1+m33-m11-m22); half=0.5 / sqrt; oe[0]=(m31+m13)*half; oe[1]=(m32+m23)*half; oe[2]=0.5 *sqrt; oe[3]=(m12-m21)*half; } } Quaternion.DEFAULT=new Quaternion(); __static(Quaternion, ['TEMPVector30',function(){return this.TEMPVector30=new Vector3();},'TEMPVector31',function(){return this.TEMPVector31=new Vector3();},'TEMPVector32',function(){return this.TEMPVector32=new Vector3();},'TEMPVector33',function(){return this.TEMPVector33=new Vector3();},'TEMPMatrix0',function(){return this.TEMPMatrix0=new Matrix4x4();},'TEMPMatrix1',function(){return this.TEMPMatrix1=new Matrix4x4();},'_tempMatrix3x3',function(){return this._tempMatrix3x3=new Matrix3x3();},'NAN',function(){return this.NAN=new Quaternion(NaN,NaN,NaN,NaN);} ]); return Quaternion; })() /** *Rand 类用于通过32位无符号整型随机种子创建随机数。 */ //class laya.d3.math.Rand var Rand=(function(){ function Rand(seed){ this._temp=new Uint32Array(1); this.seeds=new Uint32Array(4); this.seeds[0]=seed; this.seeds[1]=this.seeds[0] *0x6C078965+1; this.seeds[2]=this.seeds[1] *0x6C078965+1; this.seeds[3]=this.seeds[2] *0x6C078965+1; } __class(Rand,'laya.d3.math.Rand'); var __proto=Rand.prototype; /** *获取无符号32位整形随机数。 *@return 无符号32位整形随机数。 */ __proto.getUint=function(){ this._temp[0]=this.seeds[0] ^ (this.seeds[0] << 11); this.seeds[0]=this.seeds[1]; this.seeds[1]=this.seeds[2]; this.seeds[2]=this.seeds[3]; this.seeds[3]=(this.seeds[3] ^ (this.seeds[3] >>> 19))^ (this._temp[0] ^ (this._temp[0] >>> 8)); return this.seeds[3]; } /** *获取0到1之间的浮点随机数。 *@return 0到1之间的浮点随机数。 */ __proto.getFloat=function(){ this.getUint(); return (this.seeds[3] & 0x007FFFFF)*(1.0 / 8388607.0); } /** *获取-1到1之间的浮点随机数。 *@return-1到1之间的浮点随机数。 */ __proto.getSignedFloat=function(){ return this.getFloat()*2.0-1.0; } /** *设置随机种子。 *@param seed 随机种子。 */ /** *获取随机种子。 *@return 随机种子。 */ __getset(0,__proto,'seed',function(){ return this.seeds[0]; },function(seed){ this.seeds[0]=seed; this.seeds[1]=this.seeds[0] *0x6C078965+1; this.seeds[2]=this.seeds[1] *0x6C078965+1; this.seeds[3]=this.seeds[2] *0x6C078965+1; }); Rand.getFloatFromInt=function(v){ return (v & 0x007FFFFF)*(1.0 / 8388607.0) } Rand.getByteFromInt=function(v){ return (v & 0x007FFFFF)>>> 15; } return Rand; })() /** *Rand 类用于通过128位整型种子创建随机数,算法来自:https://github.com/AndreasMadsen/xorshift。 */ //class laya.d3.math.RandX var RandX=(function(){ function RandX(seed){ /**@private */ this._state0U=NaN; /**@private */ this._state0L=NaN; /**@private */ this._state1U=NaN; /**@private */ this._state1L=NaN; if (!((seed instanceof Array))|| seed.length!==4) throw new Error('Rand:Seed must be an array with 4 numbers'); this._state0U=seed[0] | 0; this._state0L=seed[1] | 0; this._state1U=seed[2] | 0; this._state1L=seed[3] | 0; } __class(RandX,'laya.d3.math.RandX'); var __proto=RandX.prototype; /** *通过2x32位的数组,返回64位的随机数。 *@return 64位的随机数。 */ __proto.randomint=function(){ var s1U=this._state0U,s1L=this._state0L; var s0U=this._state1U,s0L=this._state1L; var sumL=(s0L >>> 0)+(s1L >>> 0); var resU=(s0U+s1U+(sumL / 2 >>> 31))>>> 0; var resL=sumL >>> 0; this._state0U=s0U; this._state0L=s0L; var t1U=0,t1L=0; var t2U=0,t2L=0; var a1=23; var m1=0xFFFFFFFF << (32-a1); t1U=(s1U << a1)| ((s1L & m1)>>> (32-a1)); t1L=s1L << a1; s1U=s1U ^ t1U; s1L=s1L ^ t1L; t1U=s1U ^ s0U; t1L=s1L ^ s0L; var a2=18; var m2=0xFFFFFFFF >>> (32-a2); t2U=s1U >>> a2; t2L=(s1L >>> a2)| ((s1U & m2)<< (32-a2)); t1U=t1U ^ t2U; t1L=t1L ^ t2L; var a3=5; var m3=0xFFFFFFFF >>> (32-a3); t2U=s0U >>> a3; t2L=(s0L >>> a3)| ((s0U & m3)<< (32-a3)); t1U=t1U ^ t2U; t1L=t1L ^ t2L; this._state1U=t1U; this._state1L=t1L; return [resU,resL]; } /** *返回[0,1)之间的随机数。 *@return */ __proto.random=function(){ var t2=this.randomint(); var t2U=t2[0]; var t2L=t2[1]; var eU=0x3FF << (52-32); var eL=0; var a1=12; var m1=0xFFFFFFFF >>> (32-a1); var sU=t2U >>> a1; var sL=(t2L >>> a1)| ((t2U & m1)<< (32-a1)); var xU=eU | sU; var xL=eL | sL; RandX._CONVERTION_BUFFER.setUint32(0,xU,false); RandX._CONVERTION_BUFFER.setUint32(4,xL,false); var d=/*__JS__ */Rand._CONVERTION_BUFFER.getFloat64(0,false); return d-1; } __static(RandX, ['_CONVERTION_BUFFER',function(){return this._CONVERTION_BUFFER=new DataView(new ArrayBuffer(8));},'defaultRand',function(){return this.defaultRand=/*__JS__ */new Rand([0,Date.now()/ 65536,0,Date.now()% 65536]);} ]); return RandX; })() /** *Ray 类用于创建射线。 */ //class laya.d3.math.Ray var Ray=(function(){ function Ray(origin,direction){ /**原点*/ this.origin=null; /**方向*/ this.direction=null; this.origin=origin; this.direction=direction; } __class(Ray,'laya.d3.math.Ray'); return Ray; })() /** *Vector2 类用于创建二维向量。 */ //class laya.d3.math.Vector2 var Vector2=(function(){ function Vector2(x,y){ this.elements=new Float32Array(2); (x===void 0)&& (x=0); (y===void 0)&& (y=0); var v=this.elements; v[0]=x; v[1]=y; } __class(Vector2,'laya.d3.math.Vector2'); var __proto=Vector2.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *从Array数组拷贝值。 *@param array 数组。 *@param offset 数组偏移。 */ __proto.fromArray=function(array,offset){ (offset===void 0)&& (offset=0); this.elements[0]=array[offset+0]; this.elements[1]=array[offset+1]; } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destVector2=destObject; var destE=destVector2.elements; var s=this.elements; destE[0]=s[0]; destE[1]=s[1]; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destVector2=/*__JS__ */new this.constructor(); this.cloneTo(destVector2); return destVector2; } /** *设置X轴坐标。 *@param value X轴坐标。 */ /** *获取X轴坐标。 *@return X轴坐标。 */ __getset(0,__proto,'x',function(){ return this.elements[0]; },function(value){ this.elements[0]=value; }); /** *设置Y轴坐标。 *@param value Y轴坐标。 */ /** *获取Y轴坐标。 *@return Y轴坐标。 */ __getset(0,__proto,'y',function(){ return this.elements[1]; },function(value){ this.elements[1]=value; }); Vector2.scale=function(a,b,out){ var e=out.elements; var f=a.elements; e[0]=f[0] *b; e[1]=f[1] *b; } __static(Vector2, ['ZERO',function(){return this.ZERO=new Vector2(0.0,0.0);},'ONE',function(){return this.ONE=new Vector2(1.0,1.0);} ]); return Vector2; })() /** *Vector3 类用于创建三维向量。 */ //class laya.d3.math.Vector3 var Vector3=(function(){ function Vector3(x,y,z){ this.elements=new Float32Array(3); (x===void 0)&& (x=0); (y===void 0)&& (y=0); (z===void 0)&& (z=0); var v=this.elements; v[0]=x; v[1]=y; v[2]=z; } __class(Vector3,'laya.d3.math.Vector3'); var __proto=Vector3.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *从Array数组拷贝值。 *@param array 数组。 *@param offset 数组偏移。 */ __proto.fromArray=function(array,offset){ (offset===void 0)&& (offset=0); this.elements[0]=array[offset+0]; this.elements[1]=array[offset+1]; this.elements[2]=array[offset+2]; } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destVector3=destObject; var destE=destVector3.elements; var s=this.elements; destE[0]=s[0]; destE[1]=s[1]; destE[2]=s[2]; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destVector3=/*__JS__ */new this.constructor(); this.cloneTo(destVector3); return destVector3; } __proto.toDefault=function(){ this.elements[0]=0; this.elements[1]=0; this.elements[2]=0; } /** *设置X轴坐标。 *@param value X轴坐标。 */ /** *获取X轴坐标。 *@return X轴坐标。 */ __getset(0,__proto,'x',function(){ return this.elements[0]; },function(value){ this.elements[0]=value; }); /** *设置Y轴坐标。 *@param value Y轴坐标。 */ /** *获取Y轴坐标。 *@return Y轴坐标。 */ __getset(0,__proto,'y',function(){ return this.elements[1]; },function(value){ this.elements[1]=value; }); /** *设置Z轴坐标。 *@param value Z轴坐标。 */ /** *获取Z轴坐标。 *@return Z轴坐标。 */ __getset(0,__proto,'z',function(){ return this.elements[2]; },function(value){ this.elements[2]=value; }); Vector3.distanceSquared=function(value1,value2){ var value1e=value1.elements; var value2e=value2.elements; var x=value1e[0]-value2e[0]; var y=value1e[1]-value2e[1]; var z=value1e[2]-value2e[2]; return (x *x)+(y *y)+(z *z); } Vector3.distance=function(value1,value2){ var value1e=value1.elements; var value2e=value2.elements; var x=value1e[0]-value2e[0]; var y=value1e[1]-value2e[1]; var z=value1e[2]-value2e[2]; return Math.sqrt((x *x)+(y *y)+(z *z)); } Vector3.min=function(a,b,out){ var e=out.elements; var f=a.elements; var g=b.elements e[0]=Math.min(f[0],g[0]); e[1]=Math.min(f[1],g[1]); e[2]=Math.min(f[2],g[2]); } Vector3.max=function(a,b,out){ var e=out.elements; var f=a.elements; var g=b.elements e[0]=Math.max(f[0],g[0]); e[1]=Math.max(f[1],g[1]); e[2]=Math.max(f[2],g[2]); } Vector3.transformQuat=function(source,rotation,out){ var destination=out.elements; var se=source.elements; var re=rotation.elements; var x=se[0],y=se[1],z=se[2],qx=re[0],qy=re[1],qz=re[2],qw=re[3], ix=qw *x+qy *z-qz *y,iy=qw *y+qz *x-qx *z,iz=qw *z+qx *y-qy *x,iw=-qx *x-qy *y-qz *z; destination[0]=ix *qw+iw *-qx+iy *-qz-iz *-qy; destination[1]=iy *qw+iw *-qy+iz *-qx-ix *-qz; destination[2]=iz *qw+iw *-qz+ix *-qy-iy *-qx; } Vector3.scalarLength=function(a){ var f=a.elements; var x=f[0],y=f[1],z=f[2]; return Math.sqrt(x *x+y *y+z *z); } Vector3.scalarLengthSquared=function(a){ var f=a.elements; var x=f[0],y=f[1],z=f[2]; return x *x+y *y+z *z; } Vector3.normalize=function(s,out){ var se=s.elements; var oe=out.elements; var x=se[0],y=se[1],z=se[2]; var len=x *x+y *y+z *z; if (len > 0){ len=1 / Math.sqrt(len); oe[0]=se[0] *len; oe[1]=se[1] *len; oe[2]=se[2] *len; } } Vector3.multiply=function(a,b,out){ var e=out.elements; var f=a.elements; var g=b.elements e[0]=f[0] *g[0]; e[1]=f[1] *g[1]; e[2]=f[2] *g[2]; } Vector3.scale=function(a,b,out){ var e=out.elements; var f=a.elements; e[0]=f[0] *b; e[1]=f[1] *b; e[2]=f[2] *b; } Vector3.lerp=function(a,b,t,out){ var e=out.elements; var f=a.elements; var g=b.elements; var ax=f[0],ay=f[1],az=f[2]; e[0]=ax+t *(g[0]-ax); e[1]=ay+t *(g[1]-ay); e[2]=az+t *(g[2]-az); } Vector3.transformV3ToV3=function(vector,transform,result){ var intermediate=Vector3._tempVector4; Vector3.transformV3ToV4(vector,transform,intermediate); var intermediateElem=intermediate.elements; var resultElem=result.elements; resultElem[0]=intermediateElem[0]; resultElem[1]=intermediateElem[1]; resultElem[2]=intermediateElem[2]; } Vector3.transformV3ToV4=function(vector,transform,result){ var vectorElem=vector.elements; var vectorX=vectorElem[0]; var vectorY=vectorElem[1]; var vectorZ=vectorElem[2]; var transformElem=transform.elements; var resultElem=result.elements; resultElem[0]=(vectorX *transformElem[0])+(vectorY *transformElem[4])+(vectorZ *transformElem[8])+transformElem[12]; resultElem[1]=(vectorX *transformElem[1])+(vectorY *transformElem[5])+(vectorZ *transformElem[9])+transformElem[13]; resultElem[2]=(vectorX *transformElem[2])+(vectorY *transformElem[6])+(vectorZ *transformElem[10])+transformElem[14]; resultElem[3]=(vectorX *transformElem[3])+(vectorY *transformElem[7])+(vectorZ *transformElem[11])+transformElem[15]; } Vector3.TransformNormal=function(normal,transform,result){ var normalElem=normal.elements; var normalX=normalElem[0]; var normalY=normalElem[1]; var normalZ=normalElem[2]; var transformElem=transform.elements; var resultElem=result.elements; resultElem[0]=(normalX *transformElem[0])+(normalY *transformElem[4])+(normalZ *transformElem[8]); resultElem[1]=(normalX *transformElem[1])+(normalY *transformElem[5])+(normalZ *transformElem[9]); resultElem[2]=(normalX *transformElem[2])+(normalY *transformElem[6])+(normalZ *transformElem[10]); } Vector3.transformCoordinate=function(coordinate,transform,result){ var vectorElem=Vector3._tempVector4.elements; var coordinateElem=coordinate.elements; var coordinateX=coordinateElem[0]; var coordinateY=coordinateElem[1]; var coordinateZ=coordinateElem[2]; var transformElem=transform.elements; vectorElem[0]=(coordinateX *transformElem[0])+(coordinateY *transformElem[4])+(coordinateZ *transformElem[8])+transformElem[12]; vectorElem[1]=(coordinateX *transformElem[1])+(coordinateY *transformElem[5])+(coordinateZ *transformElem[9])+transformElem[13]; vectorElem[2]=(coordinateX *transformElem[2])+(coordinateY *transformElem[6])+(coordinateZ *transformElem[10])+transformElem[14]; vectorElem[3]=1.0 / ((coordinateX *transformElem[3])+(coordinateY *transformElem[7])+(coordinateZ *transformElem[11])+transformElem[15]); var resultElem=result.elements; resultElem[0]=vectorElem[0] *vectorElem[3]; resultElem[1]=vectorElem[1] *vectorElem[3]; resultElem[2]=vectorElem[2] *vectorElem[3]; } Vector3.Clamp=function(value,min,max,out){ var valuee=value.elements; var x=valuee[0]; var y=valuee[1]; var z=valuee[2]; var mine=min.elements; var mineX=mine[0]; var mineY=mine[1]; var mineZ=mine[2]; var maxe=max.elements; var maxeX=maxe[0]; var maxeY=maxe[1]; var maxeZ=maxe[2]; var oute=out.elements; x=(x > maxeX)? maxeX :x; x=(x < mineX)? mineX :x; y=(y > maxeY)? maxeY :y; y=(y < mineY)? mineY :y; z=(z > maxeZ)? maxeZ :z; z=(z < mineZ)? mineZ :z; oute[0]=x; oute[1]=y; oute[2]=z; } Vector3.add=function(a,b,out){ var e=out.elements; var f=a.elements; var g=b.elements e[0]=f[0]+g[0]; e[1]=f[1]+g[1]; e[2]=f[2]+g[2]; } Vector3.subtract=function(a,b,o){ var oe=o.elements; var ae=a.elements; var be=b.elements; oe[0]=ae[0]-be[0]; oe[1]=ae[1]-be[1]; oe[2]=ae[2]-be[2]; } Vector3.cross=function(a,b,o){ var ae=a.elements; var be=b.elements; var oe=o.elements; var ax=ae[0],ay=ae[1],az=ae[2],bx=be[0],by=be[1],bz=be[2]; oe[0]=ay *bz-az *by; oe[1]=az *bx-ax *bz; oe[2]=ax *by-ay *bx; } Vector3.dot=function(a,b){ var ae=a.elements; var be=b.elements; var r=(ae[0] *be[0])+(ae[1] *be[1])+(ae[2] *be[2]); return r; } Vector3.equals=function(a,b){ var ae=a.elements; var be=b.elements; return MathUtils3D.nearEqual(Math.abs(ae[0]),Math.abs(be[0]))&& MathUtils3D.nearEqual(Math.abs(ae[1]),Math.abs(be[1]))&& MathUtils3D.nearEqual(Math.abs(ae[2]),Math.abs(be[2])); } Vector3.ZERO=new Vector3(0.0,0.0,0.0); Vector3.ONE=new Vector3(1.0,1.0,1.0); Vector3.NegativeUnitX=new Vector3(-1,0,0); Vector3.UnitX=new Vector3(1,0,0); Vector3.UnitY=new Vector3(0,1,0); Vector3.UnitZ=new Vector3(0,0,1); Vector3.ForwardRH=new Vector3(0,0,-1); Vector3.ForwardLH=new Vector3(0,0,1); Vector3.Up=new Vector3(0,1,0); Vector3.NAN=new Vector3(NaN,NaN,NaN); __static(Vector3, ['_tempVector4',function(){return this._tempVector4=new Vector4();} ]); return Vector3; })() /** *Vector4 类用于创建四维向量。 */ //class laya.d3.math.Vector4 var Vector4=(function(){ function Vector4(x,y,z,w){ this.elements=new Float32Array(4); (x===void 0)&& (x=0); (y===void 0)&& (y=0); (z===void 0)&& (z=0); (w===void 0)&& (w=0); var v=this.elements; v[0]=x; v[1]=y; v[2]=z; v[3]=w; } __class(Vector4,'laya.d3.math.Vector4'); var __proto=Vector4.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *从Array数组拷贝值。 *@param array 数组。 *@param offset 数组偏移。 */ __proto.fromArray=function(array,offset){ (offset===void 0)&& (offset=0); this.elements[0]=array[offset+0]; this.elements[1]=array[offset+1]; this.elements[2]=array[offset+2]; this.elements[3]=array[offset+3]; } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destVector4=destObject; var destE=destVector4.elements; var s=this.elements; destE[0]=s[0]; destE[1]=s[1]; destE[2]=s[2]; destE[3]=s[3]; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destVector4=/*__JS__ */new this.constructor(); this.cloneTo(destVector4); return destVector4; } /** *求四维向量的长度。 *@return 长度。 */ __proto.length=function(){ return Math.sqrt(this.x *this.x+this.y *this.y+this.z *this.z+this.w *this.w); } /** *求四维向量长度的平方。 *@return 长度的平方。 */ __proto.lengthSquared=function(){ return this.x *this.x+this.y *this.y+this.z *this.z+this.w *this.w; } /** *设置X轴坐标。 *@param value X轴坐标。 */ /** *获取X轴坐标。 *@return X轴坐标。 */ __getset(0,__proto,'x',function(){ return this.elements[0]; },function(value){ this.elements[0]=value; }); /** *设置Y轴坐标。 *@param value Y轴坐标。 */ /** *获取Y轴坐标。 *@return Y轴坐标。 */ __getset(0,__proto,'y',function(){ return this.elements[1]; },function(value){ this.elements[1]=value; }); /** *设置Z轴坐标。 *@param value Z轴坐标。 */ /** *获取Z轴坐标。 *@return Z轴坐标。 */ __getset(0,__proto,'z',function(){ return this.elements[2]; },function(value){ this.elements[2]=value; }); /** *设置W轴坐标。 *@param value W轴坐标。 */ /** *获取W轴坐标。 *@return W轴坐标。 */ __getset(0,__proto,'w',function(){ return this.elements[3]; },function(value){ this.elements[3]=value; }); Vector4.lerp=function(a,b,t,out){ var e=out.elements; var f=a.elements; var g=b.elements; var ax=f[0],ay=f[1],az=f[2],aw=f[3]; e[0]=ax+t *(g[0]-ax); e[1]=ay+t *(g[1]-ay); e[2]=az+t *(g[2]-az); e[3]=aw+t *(g[3]-aw); } Vector4.transformByM4x4=function(vector4,m4x4,out){ var ve=vector4.elements; var vx=ve[0]; var vy=ve[1]; var vz=ve[2]; var vw=ve[3]; var me=m4x4.elements; var oe=out.elements; oe[0]=vx *me[0]+vy *me[4]+vz *me[8]+vw *me[12]; oe[1]=vx *me[1]+vy *me[5]+vz *me[9]+vw *me[13]; oe[2]=vx *me[2]+vy *me[6]+vz *me[10]+vw *me[14]; oe[3]=vx *me[3]+vy *me[7]+vz *me[11]+vw *me[15]; } Vector4.equals=function(a,b){ var ae=a.elements; var be=b.elements; return MathUtils3D.nearEqual(Math.abs(ae[0]),Math.abs(be[0]))&& MathUtils3D.nearEqual(Math.abs(ae[1]),Math.abs(be[1]))&& MathUtils3D.nearEqual(Math.abs(ae[2]),Math.abs(be[2]))&& MathUtils3D.nearEqual(Math.abs(ae[3]),Math.abs(be[3])); } Vector4.normalize=function(s,out){ var se=s.elements; var oe=out.elements; var len=/*if err,please use iflash.method.xmlLength()*/s.length(); if (len > 0){ oe[0]=se[0] *len; oe[1]=se[1] *len; oe[2]=se[2] *len; oe[3]=se[3] *len; } } Vector4.add=function(a,b,out){ var oe=out.elements; var ae=a.elements; var be=b.elements; oe[0]=ae[0]+be[0]; oe[1]=ae[1]+be[1]; oe[2]=ae[2]+be[2]; oe[3]=ae[3]+be[3]; } Vector4.subtract=function(a,b,out){ var oe=out.elements; var ae=a.elements; var be=b.elements; oe[0]=ae[0]-be[0]; oe[1]=ae[1]-be[1]; oe[2]=ae[2]-be[2]; oe[3]=ae[3]-be[3]; } Vector4.multiply=function(a,b,out){ var oe=out.elements; var ae=a.elements; var be=b.elements; oe[0]=ae[0] *be[0]; oe[1]=ae[1] *be[1]; oe[2]=ae[2] *be[2]; oe[3]=ae[3] *be[3]; } Vector4.scale=function(a,b,out){ var oe=out.elements; var ae=a.elements; oe[0]=ae[0] *b; oe[1]=ae[1] *b; oe[2]=ae[2] *b; oe[3]=ae[3] *b; } Vector4.Clamp=function(value,min,max,out){ var valuee=value.elements; var x=valuee[0]; var y=valuee[1]; var z=valuee[2]; var w=valuee[3]; var mine=min.elements; var mineX=mine[0]; var mineY=mine[1]; var mineZ=mine[2]; var mineW=mine[3]; var maxe=max.elements; var maxeX=maxe[0]; var maxeY=maxe[1]; var maxeZ=maxe[2]; var maxeW=maxe[3]; var oute=out.elements; x=(x > maxeX)? maxeX :x; x=(x < mineX)? mineX :x; y=(y > maxeY)? maxeY :y; y=(y < mineY)? mineY :y; z=(z > maxeZ)? maxeZ :z; z=(z < mineZ)? mineZ :z; w=(w > maxeW)? maxeW :w; w=(w < mineW)? mineW :w; oute[0]=x; oute[1]=y; oute[2]=z; oute[3]=w; } Vector4.distanceSquared=function(value1,value2){ var value1e=value1.elements; var value2e=value2.elements; var x=value1e[0]-value2e[0]; var y=value1e[1]-value2e[1]; var z=value1e[2]-value2e[2]; var w=value1e[3]-value2e[3]; return (x *x)+(y *y)+(z *z)+(w *w); } Vector4.distance=function(value1,value2){ var value1e=value1.elements; var value2e=value2.elements; var x=value1e[0]-value2e[0]; var y=value1e[1]-value2e[1]; var z=value1e[2]-value2e[2]; var w=value1e[3]-value2e[3]; return Math.sqrt((x *x)+(y *y)+(z *z)+(w *w)); } Vector4.dot=function(a,b){ var ae=a.elements; var be=b.elements; var r=(ae[0] *be[0])+(ae[1] *be[1])+(ae[2] *be[2])+(ae[3] *be[3]); return r; } Vector4.min=function(a,b,out){ var e=out.elements; var f=a.elements; var g=b.elements e[0]=Math.min(f[0],g[0]); e[1]=Math.min(f[1],g[1]); e[2]=Math.min(f[2],g[2]); e[3]=Math.min(f[3],g[3]); } Vector4.max=function(a,b,out){ var e=out.elements; var f=a.elements; var g=b.elements e[0]=Math.max(f[0],g[0]); e[1]=Math.max(f[1],g[1]); e[2]=Math.max(f[2],g[2]); e[3]=Math.max(f[3],g[3]); } __static(Vector4, ['ZERO',function(){return this.ZERO=new Vector4();},'ONE',function(){return this.ONE=new Vector4(1.0,1.0,1.0,1.0);},'UnitX',function(){return this.UnitX=new Vector4(1.0,0.0,0.0,0.0);},'UnitY',function(){return this.UnitY=new Vector4(0.0,1.0,0.0,0.0);},'UnitZ',function(){return this.UnitZ=new Vector4(0.0,0.0,1.0,0.0);},'UnitW',function(){return this.UnitW=new Vector4(0.0,0.0,0.0,1.0);} ]); return Vector4; })() /** *Viewport 类用于创建视口。 */ //class laya.d3.math.Viewport var Viewport=(function(){ function Viewport(x,y,width,height){ /**X轴坐标*/ //this.x=NaN; /**Y轴坐标*/ //this.y=NaN; /**宽度*/ //this.width=NaN; /**高度*/ //this.height=NaN; /**最小深度*/ //this.minDepth=NaN; /**最大深度*/ //this.maxDepth=NaN; this.minDepth=0.0; this.maxDepth=1.0; this.x=x; this.y=y; this.width=width; this.height=height; } __class(Viewport,'laya.d3.math.Viewport'); var __proto=Viewport.prototype; /** *变换一个三维向量。 *@param source 源三维向量。 *@param matrix 变换矩阵。 *@param vector 输出三维向量。 */ __proto.project=function(source,matrix,out){ Vector3.transformV3ToV3(source,matrix,out); var sourceEleme=source.elements; var matrixEleme=matrix.elements; var outEleme=out.elements; var a=(((sourceEleme[0] *matrixEleme[3])+(sourceEleme[1] *matrixEleme[7]))+(sourceEleme[2] *matrixEleme[11]))+matrixEleme[15]; if (a!==1.0){ outEleme[0]=outEleme[0] / a; outEleme[1]=outEleme[1] / a; outEleme[2]=outEleme[2] / a; } outEleme[0]=(((outEleme[0]+1.0)*0.5)*this.width)+this.x; outEleme[1]=(((-outEleme[1]+1.0)*0.5)*this.height)+this.y; outEleme[2]=(outEleme[2] *(this.maxDepth-this.minDepth))+this.minDepth; } /** *反变换一个三维向量。 *@param source 源三维向量。 *@param matrix 变换矩阵。 *@param vector 输出三维向量。 */ __proto.unprojectFromMat=function(source,matrix,out){ var sourceEleme=source.elements; var matrixEleme=matrix.elements; var outEleme=out.elements; outEleme[0]=(((sourceEleme[0]-this.x)/ (this.width))*2.0)-1.0; outEleme[1]=-((((sourceEleme[1]-this.y)/ (this.height))*2.0)-1.0); var halfDepth=(this.maxDepth-this.minDepth)/ 2; outEleme[2]=(sourceEleme[2]-this.minDepth-halfDepth)/ halfDepth; var a=(((outEleme[0] *matrixEleme[3])+(outEleme[1] *matrixEleme[7]))+(outEleme[2] *matrixEleme[11]))+matrixEleme[15]; Vector3.transformV3ToV3(out,matrix,out); if (a!==1.0){ outEleme[0]=outEleme[0] / a; outEleme[1]=outEleme[1] / a; outEleme[2]=outEleme[2] / a; } } /** *反变换一个三维向量。 *@param source 源三维向量。 *@param projection 透视投影矩阵。 *@param view 视图矩阵。 *@param world 世界矩阵,可设置为null。 *@param out 输出向量。 */ __proto.unprojectFromWVP=function(source,projection,view,world,out){ Matrix4x4.multiply(projection,view,Viewport._tempMatrix4x4); (world)&& (Matrix4x4.multiply(Viewport._tempMatrix4x4,world,Viewport._tempMatrix4x4)); Viewport._tempMatrix4x4.invert(Viewport._tempMatrix4x4); this.unprojectFromMat(source,Viewport._tempMatrix4x4,out); } __static(Viewport, ['_tempMatrix4x4',function(){return this._tempMatrix4x4=new Matrix4x4();} ]); return Viewport; })() /** *Sky 类用于创建天空的父类,抽象类不允许实例。 */ //class laya.d3.resource.models.Sky var Sky=(function(){ function Sky(){ /**@private */ //this.__ownerCamera=null; /**@private 透明混合度。 */ this._alphaBlending=1.0; /**@private 颜色强度。 */ this._colorIntensity=1.0; /**@private */ //this._vertexBuffer=null; /**@private */ //this._indexBuffer=null; /**@private */ //this._sharderNameID=0; /**@private */ //this._shader=null; /**@private */ //this._shaderValue=null; /**@private */ //this._shaderCompile=null; /**@private */ //this._environmentDiffuse=null; /**@private */ //this._environmentSpecular=null; ; this._shaderValue=new ValusArray(); } __class(Sky,'laya.d3.resource.models.Sky'); var __proto=Sky.prototype; /** *@private */ __proto._setEnvironmentDiffuse=function(){ if (this._environmentDiffuse.loaded){ this.__ownerCamera._shaderValues.setValue(/*laya.d3.core.BaseCamera.ENVIRONMENTDIFFUSE*/7,this._environmentDiffuse); }else { this._environmentDiffuse.on(/*laya.events.Event.LOADED*/"loaded",this,this._environmentDiffuseLoaded); } } /** *@private */ __proto._setEnvironmentSpecular=function(){ if (this._environmentSpecular.loaded){ var si=this._environmentSpecular['simLodInfo']; if (si && (si instanceof Float32Array)) this.__ownerCamera._shaderValues.setValue(/*laya.d3.core.BaseCamera.SIMLODINFO*/9,si); this.__ownerCamera._shaderValues.setValue(/*laya.d3.core.BaseCamera.ENVIRONMENTSPECULAR*/8,this._environmentSpecular); }else { this._environmentSpecular.on(/*laya.events.Event.LOADED*/"loaded",this,this._environmentSpecularLoaded); } } /** *@private */ __proto._environmentDiffuseLoaded=function(){ this.__ownerCamera._shaderValues.setValue(/*laya.d3.core.BaseCamera.ENVIRONMENTDIFFUSE*/7,this._environmentDiffuse); } /** *@private */ __proto._environmentSpecularLoaded=function(){ var si=this._environmentSpecular['simLodInfo']; if (si && (si instanceof Float32Array)) this.__ownerCamera._shaderValues.setValue(/*laya.d3.core.BaseCamera.SIMLODINFO*/9,si); this.__ownerCamera._shaderValues.setValue(/*laya.d3.core.BaseCamera.ENVIRONMENTSPECULAR*/8,this._environmentSpecular); } /** *@private */ __proto._render=function(state){} /** *销毁天空。 */ __proto.destroy=function(){ this.__ownerCamera=null; } /** *@private */ __getset(0,__proto,'_ownerCamera',null,function(value){ this.__ownerCamera=value; (this._environmentDiffuse)&& (this._setEnvironmentDiffuse()); (this._environmentSpecular)&& (this._setEnvironmentSpecular()); }); /** *设置透明混合度。 *@param value 透明混合度。 */ /** *获取透明混合度。 *@return 透明混合度。 */ __getset(0,__proto,'alphaBlending',function(){ return this._alphaBlending; },function(value){ this._alphaBlending=value; if (this._alphaBlending < 0) this._alphaBlending=0; if (this._alphaBlending > 1) this._alphaBlending=1; }); __getset(0,__proto,'envDiffuseSHBlue',null,function(value){ this.__ownerCamera._shaderValues.setValue(/*laya.d3.core.BaseCamera.DIFFUSEIRRADMATB*/12,value); }); /** *设置颜色强度。 *@param value 颜色强度。 */ /** *获取颜色强度。 *@return 颜色强度。 */ __getset(0,__proto,'colorIntensity',function(){ return this._colorIntensity; },function(value){ this._colorIntensity=value; if (this._colorIntensity < 0) this._colorIntensity=0; }); __getset(0,__proto,'envDiffuseSHGreen',null,function(value){ this.__ownerCamera._shaderValues.setValue(/*laya.d3.core.BaseCamera.DIFFUSEIRRADMATG*/11,value); }); __getset(0,__proto,'envDiffuseSHRed',null,function(value){ this.__ownerCamera._shaderValues.setValue(/*laya.d3.core.BaseCamera.DIFFUSEIRRADMATR*/10,value); }); /** *设置环境漫反射贴图。 *@param value 环境漫反射贴图。 */ /** *获取环境漫反射贴图。 *@return 环境漫反射贴图。 */ __getset(0,__proto,'environmentDiffuse',function(){ return this._environmentDiffuse; },function(value){ value.minFifter=/*laya.webgl.WebGLContext.NEAREST*/0x2600; this._environmentDiffuse=value; (this.__ownerCamera)&& (this._setEnvironmentDiffuse()); }); /** *设置环境高光贴图。 *@param value 环境高光贴图。 */ /** *获取环境高光贴图。 *@return 环境高光贴图。 */ __getset(0,__proto,'environmentSpecular',function(){ return this._environmentSpecular; },function(value){ this._environmentSpecular=value; (this.__ownerCamera)&& (this._setEnvironmentSpecular()); }); Sky.MVPMATRIX=0; Sky.INTENSITY=1; Sky.ALPHABLENDING=2; Sky.DIFFUSETEXTURE=3; return Sky; })() /** *SubMesh 类用于创建子网格数据模板。 */ //class laya.d3.resource.models.SubMesh var SubMesh=(function(){ function SubMesh(mesh){ /**@private */ this._mesh=null; /**@private */ this._boneIndicesList=null; /**@private */ this._subIndexBufferStart=null; /**@private */ this._subIndexBufferCount=null; /**@private */ this._skinAnimationDatas=null; /**@private */ this._bufferUsage=null; /**@private */ this._indexInMesh=0; /**@private */ this._vertexBuffer=null; /**@private */ this._vertexStart=0; /**@private */ this._vertexCount=0; /**@private */ this._indexBuffer=null; /**@private */ this._indexStart=0; /**@private */ this._indexCount=0; /**@private */ this._indices=null; this._bufferUsage={}; this._mesh=mesh; this._boneIndicesList=[]; this._subIndexBufferStart=[]; this._subIndexBufferCount=[]; } __class(SubMesh,'laya.d3.resource.models.SubMesh'); var __proto=SubMesh.prototype; Laya.imps(__proto,{"laya.d3.core.render.IRenderable":true,"laya.resource.IDispose":true}) /** *@private */ __proto._getVertexBuffer=function(index){ (index===void 0)&& (index=0); if (index===0) return this._vertexBuffer; else return null; } /** *@private */ __proto._getIndexBuffer=function(){ return this._indexBuffer; } /** *@private */ __proto._getStaticBatchBakedVertexs=function(batchOwnerTransform,owner){ var byteSizeInFloat=4; var vertexBuffer=this._vertexBuffer; var vertexDeclaration=vertexBuffer.vertexDeclaration; var positionOffset=vertexDeclaration.getVertexElementByUsage(/*laya.d3.graphics.VertexElementUsage.POSITION0*/0).offset / byteSizeInFloat; var normalOffset=vertexDeclaration.getVertexElementByUsage(/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3).offset / byteSizeInFloat; var lightmapScaleOffset=owner.meshRender.lightmapScaleOffset; var i=0,n=0,bakedVertexes,bakedVertexFloatCount=0,lightingMapTexcoordOffset=0,uv1Element; var uv0Offset=0,oriVertexFloatCount=0; if (lightmapScaleOffset){ uv1Element=vertexDeclaration.getVertexElementByUsage(/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE1*/15); if (uv1Element){ bakedVertexFloatCount=vertexDeclaration.vertexStride / byteSizeInFloat; if (this._vertexCount > 0) bakedVertexes=vertexBuffer.getData().slice(this._vertexStart *bakedVertexFloatCount,(this._vertexStart+this._vertexCount)*bakedVertexFloatCount); else bakedVertexes=vertexBuffer.getData().slice(); lightingMapTexcoordOffset=uv1Element.offset / byteSizeInFloat; }else { oriVertexFloatCount=vertexDeclaration.vertexStride / byteSizeInFloat; bakedVertexFloatCount=oriVertexFloatCount+2; if (this._vertexCount) bakedVertexes=new Float32Array(this._vertexCount *(vertexBuffer.vertexDeclaration.vertexStride / byteSizeInFloat+2)); else bakedVertexes=new Float32Array(vertexBuffer.vertexCount *(vertexBuffer.vertexDeclaration.vertexStride / byteSizeInFloat+2)); uv0Offset=vertexDeclaration.getVertexElementByUsage(/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2).offset / byteSizeInFloat; lightingMapTexcoordOffset=uv0Offset+2; var oriVertexes=vertexBuffer.getData(); for (i=0,n=oriVertexes.length / oriVertexFloatCount;i < n;i++){ var oriVertexOffset=0; if (this._vertexCount > 0) oriVertexOffset=(this._vertexStart+i)*oriVertexFloatCount; else oriVertexOffset=i *oriVertexFloatCount; var bakedVertexOffset=i *bakedVertexFloatCount; var j=0; for (j=0;j < lightingMapTexcoordOffset;j++) bakedVertexes[bakedVertexOffset+j]=oriVertexes[oriVertexOffset+j]; for (j=lightingMapTexcoordOffset;j < oriVertexFloatCount;j++) bakedVertexes[bakedVertexOffset+j+2]=oriVertexes[oriVertexOffset+j]; } } }else { bakedVertexFloatCount=vertexDeclaration.vertexStride / byteSizeInFloat; if (this._vertexCount) bakedVertexes=vertexBuffer.getData().slice(this._vertexStart *bakedVertexFloatCount,(this._vertexStart+this._vertexCount)*bakedVertexFloatCount); else bakedVertexes=vertexBuffer.getData().slice(); } if (batchOwnerTransform){ var rootMat=batchOwnerTransform.worldMatrix; var rootInvertMat=SubMesh._tempMatrix4x40; rootMat.invert(rootInvertMat); var result=SubMesh._tempMatrix4x41; var transform=owner.transform.worldMatrix; Matrix4x4.multiply(rootInvertMat,transform,result); }else { result=owner.transform.worldMatrix; }; var rotation=SubMesh._tempQuaternion0; result.decomposeTransRotScale(SubMesh._tempVector30,rotation,SubMesh._tempVector31); for (i=0,n=bakedVertexes.length / bakedVertexFloatCount;i < n;i++){ var posOffset=i *bakedVertexFloatCount+positionOffset; var norOffset=i *bakedVertexFloatCount+normalOffset; Utils3D.transformVector3ArrayToVector3ArrayCoordinate(bakedVertexes,posOffset,result,bakedVertexes,posOffset); Utils3D.transformVector3ArrayByQuat(bakedVertexes,norOffset,rotation,bakedVertexes,norOffset); if (lightmapScaleOffset){ var lightingMapTexOffset=i *bakedVertexFloatCount+lightingMapTexcoordOffset; if (uv1Element){ Utils3D.transformLightingMapTexcoordByUV1Array(bakedVertexes,lightingMapTexOffset,lightmapScaleOffset,bakedVertexes,lightingMapTexOffset); }else { var tex0Offset=i *oriVertexFloatCount+uv0Offset; Utils3D.transformLightingMapTexcoordByUV0Array(oriVertexes,tex0Offset,lightmapScaleOffset,bakedVertexes,lightingMapTexOffset); } } } return bakedVertexes; } /** *@private */ __proto._getVertexBuffers=function(){ return null; } /** *@private */ __proto._beforeRender=function(state){ this._vertexBuffer._bind(); this._indexBuffer._bind(); return true; } /** *@private *渲染。 *@param state 渲染状态。 */ __proto._render=function(state){ var skinAnimationDatas; var indexCount=0; var renderElement=state.renderElement; if (this._indexCount > 1){ var boneIndicesListCount=this._boneIndicesList.length; if (boneIndicesListCount > 1){ for (var i=0;i < boneIndicesListCount;i++){ skinAnimationDatas=renderElement._skinAnimationDatas || this._skinAnimationDatas; if (skinAnimationDatas){ renderElement._shaderValue.setValue(/*laya.d3.core.SkinnedMeshSprite3D.BONES*/0,skinAnimationDatas[i]); state._shader.uploadRenderElementUniforms(renderElement._shaderValue.data); } WebGL.mainContext.drawElements(/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,this._subIndexBufferCount[i],/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,this._subIndexBufferStart[i] *2); } Stat.drawCall+=boneIndicesListCount; }else { skinAnimationDatas=renderElement._skinAnimationDatas || this._skinAnimationDatas; if (skinAnimationDatas){ renderElement._shaderValue.setValue(/*laya.d3.core.SkinnedMeshSprite3D.BONES*/0,skinAnimationDatas[0]); state._shader.uploadRenderElementUniforms(renderElement._shaderValue.data); } WebGL.mainContext.drawElements(/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,this._indexCount,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,this._indexStart *2); Stat.drawCall++; } indexCount=this._indexCount; }else { indexCount=this._indexBuffer.indexCount; skinAnimationDatas=renderElement._skinAnimationDatas || this._skinAnimationDatas; if (skinAnimationDatas){ renderElement._shaderValue.setValue(/*laya.d3.core.SkinnedMeshSprite3D.BONES*/0,skinAnimationDatas[0]); state._shader.uploadRenderElementUniforms(renderElement._shaderValue.data); } WebGL.mainContext.drawElements(/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,indexCount,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,0); Stat.drawCall++; } Stat.trianglesFaces+=indexCount / 3; } /** *@private */ __proto.getIndices=function(){ if (this._indexCount > 0) return this._indices; else return this._indexBuffer.getData(); } /** *

彻底清理资源。

*

注意:会强制解锁清理。

*/ __proto.dispose=function(){ this._indexBuffer.destroy(); this._vertexBuffer.destroy(); this._mesh=null; this._boneIndicesList=null; this._subIndexBufferStart=null; this._subIndexBufferCount=null; this._skinAnimationDatas=null; this._bufferUsage=null; this._vertexBuffer=null; this._indexBuffer=null; } /** *@private */ __getset(0,__proto,'_vertexBufferCount',function(){ return 1; }); /** *@private */ __getset(0,__proto,'triangleCount',function(){ return this._indexBuffer.indexCount / 3; }); __static(SubMesh, ['_tempVector30',function(){return this._tempVector30=new Vector3();},'_tempVector31',function(){return this._tempVector31=new Vector3();},'_tempQuaternion0',function(){return this._tempQuaternion0=new Quaternion();},'_tempMatrix4x40',function(){return this._tempMatrix4x40=new Matrix4x4();},'_tempMatrix4x41',function(){return this._tempMatrix4x41=new Matrix4x4();} ]); return SubMesh; })() /** *@private */ //class laya.d3.shader.ShaderDefines var ShaderDefines$1=(function(){ function ShaderDefines(shaderdefines){ /**@private [只读]*/ this.defineCounter=0; /**@private [只读]*/ this.defines=null; if (shaderdefines){ this.defineCounter=shaderdefines.defineCounter; this.defines=shaderdefines.defines.slice(); }else { this.defineCounter=0; this.defines=[]; } } __class(ShaderDefines,'laya.d3.shader.ShaderDefines',null,'ShaderDefines$1'); var __proto=ShaderDefines.prototype; /** *@private */ __proto.registerDefine=function(name){ var value=Math.pow(2,this.defineCounter++); this.defines[value]=name; return value; } return ShaderDefines; })() /** *@private *ShaderInit 类用于初始化内置Shader。 */ //class laya.d3.shader.ShaderInit3D var ShaderInit3D=(function(){ /** *创建一个 ShaderInit 实例。 */ function ShaderInit3D(){} __class(ShaderInit3D,'laya.d3.shader.ShaderInit3D'); ShaderInit3D.__init__=function(){ ShaderCompile3D._globalRegDefine("HIGHPRECISION",ShaderCompile3D.SHADERDEFINE_HIGHPRECISION); ShaderCompile3D._globalRegDefine("FOG",ShaderCompile3D.SHADERDEFINE_FOG); ShaderCompile3D._globalRegDefine("DIRECTIONLIGHT",ShaderCompile3D.SHADERDEFINE_DIRECTIONLIGHT); ShaderCompile3D._globalRegDefine("POINTLIGHT",ShaderCompile3D.SHADERDEFINE_POINTLIGHT); ShaderCompile3D._globalRegDefine("SPOTLIGHT",ShaderCompile3D.SHADERDEFINE_SPOTLIGHT); ShaderCompile3D._globalRegDefine("UV",ShaderCompile3D.SHADERDEFINE_UV0); ShaderCompile3D._globalRegDefine("COLOR",ShaderCompile3D.SHADERDEFINE_COLOR); ShaderCompile3D._globalRegDefine("UV1",ShaderCompile3D.SHADERDEFINE_UV1); ShaderCompile3D._globalRegDefine("CASTSHADOW",ParallelSplitShadowMap.SHADERDEFINE_CAST_SHADOW); ShaderCompile3D._globalRegDefine("SHADOWMAP_PSSM1",ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM1); ShaderCompile3D._globalRegDefine("SHADOWMAP_PSSM2",ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM2); ShaderCompile3D._globalRegDefine("SHADOWMAP_PSSM3",ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM3); ShaderCompile3D._globalRegDefine("SHADOWMAP_PCF_NO",ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF_NO); ShaderCompile3D._globalRegDefine("SHADOWMAP_PCF1",ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF1); ShaderCompile3D._globalRegDefine("SHADOWMAP_PCF2",ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF2); ShaderCompile3D._globalRegDefine("SHADOWMAP_PCF3",ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF3); ShaderCompile3D._globalRegDefine("DEPTHFOG",ShaderCompile3D.SAHDERDEFINE_DEPTHFOG); Shader3D.addInclude("LightHelper.glsl","\nstruct DirectionLight\n{\n vec3 Direction;\n vec3 Diffuse;\n};\n\nstruct PointLight\n{\n vec3 Diffuse;\n vec3 Attenuation;\n vec3 Position;\n float Range;\n};\n\nstruct SpotLight\n{\n vec3 Diffuse;\n vec3 Attenuation;\n vec3 Position;\n vec3 Direction;\n float Spot;\n float Range;\n};\n\n\nvec3 NormalSampleToWorldSpace(vec3 normalMapSample, vec3 unitNormal, vec3 tangent)\n{\n vec3 normalT = 2.0*normalMapSample - 1.0;\n\n // Build orthonormal basis.\n vec3 N = normalize(unitNormal);\n vec3 T = normalize(tangent- dot(tangent, N)*N);\n vec3 B = cross(T, N);\n\n mat3 TBN = mat3(T, B, N);\n\n // Transform from tangent space to world space.\n vec3 bumpedNormal = TBN*normalT;\n\n return bumpedNormal;\n}\n\n\nvoid computeDirectionLight(in vec3 matDif,in vec3 matAmb,in vec4 matSpe,in DirectionLight dirLight,in vec3 ambinentColor,in vec3 normal,in vec3 toEye,out vec3 dif,out vec3 amb,out vec3 spec)\n{\n dif=vec3(0.0);//不初始化在IOS中闪烁,PC中不会闪烁\n amb=vec3(0.0);\n spec=vec3(0.0);\n vec3 lightVec=-normalize(dirLight.Direction);\n \n amb=matAmb*ambinentColor;\n \n float diffuseFactor=dot(lightVec, normal);\n \n if(diffuseFactor>0.0)\n {\n vec3 v = reflect(-lightVec, normal);\n float specFactor = pow(max(dot(v, toEye), 0.0), matSpe.w);\n \n dif = diffuseFactor * matDif * dirLight.Diffuse;\n spec = specFactor * matSpe.rgb;\n }\n \n}\n\nvoid computePointLight(in vec3 matDif,in vec3 matAmb,in vec4 matSpe,in PointLight poiLight,in vec3 ambinentColor, in vec3 pos,in vec3 normal,in vec3 toEye,out vec3 dif,out vec3 amb,out vec3 spec)\n{\n dif=vec3(0.0);\n amb=vec3(0.0);\n spec=vec3(0.0);\n vec3 lightVec = poiLight.Position - pos;\n \n float d = length(lightVec);\n \n if( d > poiLight.Range )\n return;\n \n lightVec /= d; \n \n amb = matAmb*ambinentColor; \n\n float diffuseFactor = dot(lightVec, normal);\n\n if( diffuseFactor > 0.0 )\n {\n vec3 v= reflect(-lightVec, normal);\n float specFactor = pow(max(dot(v, toEye), 0.0), matSpe.w);\n \n dif = diffuseFactor * matDif * poiLight.Diffuse;\n spec = specFactor * matSpe.rgb;\n }\n\n float attenuate = 1.0 / dot(poiLight.Attenuation, vec3(1.0, d, d*d));\n\n dif *= attenuate;\n spec*= attenuate;\n}\n\nvoid ComputeSpotLight(in vec3 matDif,in vec3 matAmb,in vec4 matSpe,in SpotLight spoLight,in vec3 ambinentColor,in vec3 pos, in vec3 normal,in vec3 toEye,out vec3 dif,out vec3 amb,out vec3 spec)\n{\n amb = vec3(0.0);\n dif =vec3(0.0);\n spec= vec3(0.0);\n vec3 lightVec = spoLight.Position - pos;\n \n float d = length(lightVec);\n \n if( d > spoLight.Range)\n return;\n \n lightVec /= d; \n \n amb = matAmb*ambinentColor; \n\n float diffuseFactor = dot(lightVec, normal);\n\n if(diffuseFactor > 0.0)\n {\n vec3 v= reflect(-lightVec, normal);\n float specFactor = pow(max(dot(v, toEye), 0.0), matSpe.w);\n \n dif = diffuseFactor * matDif * spoLight.Diffuse;\n spec = specFactor * matSpe.rgb;\n }\n \n float spot = pow(max(dot(-lightVec, normalize(spoLight.Direction)), 0.0), spoLight.Spot);\n\n float attenuate = spot/dot(spoLight.Attenuation, vec3(1.0, d, d*d));\n\n amb *= spot;\n dif *= attenuate;\n spec*= attenuate;\n}\n\n"); Shader3D.addInclude("Lighting.glsl","\nstruct DirectionLight\n{\n vec3 Color;\n vec3 Direction;\n};\n\nstruct PointLight\n{\n vec3 Color;\n vec3 Position;\n float Range;\n};\n\nstruct SpotLight\n{\n vec3 Color;\n vec3 Position;\n vec3 Direction;\n float Spot;\n float Range;\n};\n\n// U3D中使用衰减纹理,此函数模拟并非正确\n//float U3DAttenuation(in vec3 L,in float invLightRadius)\n//{\n// float fRatio = clamp(length(L) * invLightRadius,0.0,1.0);\n// fRatio *= fRatio;\n// return 1.0 / (1.0 + 25.0 * fRatio)* clamp(4.0*(1.0 - fRatio),0.0,1.0); //fade to black as if 4 pixel texture\n//} \n\n// Same as Just Cause 2 and Crysis 2 (you can read GPU Pro 1 book for more information)\nfloat BasicAttenuation(in vec3 L,in float invLightRadius)\n{\n vec3 distance = L * invLightRadius;\n float attenuation = clamp(1.0 - dot(distance, distance),0.0,1.0); // Equals float attenuation = saturate(1.0f - dot(L, L) / (lightRadius * lightRadius)); \n return attenuation * attenuation;\n} \n\n// Inspired on http://fools.slindev.com/viewtopic.php?f=11&t=21&view=unread#unread \nfloat NaturalAttenuation(in vec3 L,in float invLightRadius)\n{\n float attenuationFactor = 30.0;\n vec3 distance = L * invLightRadius;\n float attenuation = dot(distance, distance); // Equals float attenuation = dot(L, L) / (lightRadius * lightRadius);\n attenuation = 1.0 / (attenuation * attenuationFactor + 1.0);\n // Second we move down the function therewith it reaches zero at abscissa 1:\n attenuationFactor = 1.0 / (attenuationFactor + 1.0); //attenuationFactor contains now the value we have to subtract\n attenuation = max(attenuation - attenuationFactor, 0.0); // The max fixes a bug.\n // Finally we expand the equation along the y-axis so that it starts with a function value of 1 again.\n attenuation /= 1.0 - attenuationFactor;\n return attenuation;\n} \n\nvoid LayaAirBlinnPhongLight (in vec3 specColor,in float specColorIntensity,in vec3 normal,in vec3 gloss, in vec3 viewDir,in vec3 lightColor, in vec3 lightVec,out vec3 diffuseColor,out vec3 specularColor)\n{\n mediump vec3 h = normalize(viewDir-lightVec);\n lowp float ln = max (0.0, dot (-lightVec,normal));\n float nh = max (0.0, dot (h,normal));\n diffuseColor=lightColor * ln;\n specularColor=lightColor *specColor*pow (nh, specColorIntensity*128.0) * gloss;\n}\n\nvoid LayaAirBlinnPhongDiectionLight (in vec3 specColor,in float specColorIntensity,in vec3 normal,in vec3 gloss, in vec3 viewDir, in DirectionLight light,out vec3 diffuseColor,out vec3 specularColor)\n{\n vec3 lightVec=normalize(light.Direction);\n LayaAirBlinnPhongLight(specColor,specColorIntensity,normal,gloss,viewDir,light.Color,lightVec,diffuseColor,specularColor);\n}\n\nvoid LayaAirBlinnPhongPointLight (in vec3 pos,in vec3 specColor,in float specColorIntensity,in vec3 normal,in vec3 gloss, in vec3 viewDir, in PointLight light,out vec3 diffuseColor,out vec3 specularColor)\n{\n vec3 lightVec = pos-light.Position;\n //if( length(lightVec) > light.Range )\n // return;\n LayaAirBlinnPhongLight(specColor,specColorIntensity,normal,gloss,viewDir,light.Color,lightVec/length(lightVec),diffuseColor,specularColor);\n float attenuate = BasicAttenuation(lightVec, 1.0/light.Range);\n diffuseColor *= attenuate;\n specularColor*= attenuate;\n}\n\nvoid LayaAirBlinnPhongSpotLight (in vec3 pos,in vec3 specColor,in float specColorIntensity,in vec3 normal,in vec3 gloss, in vec3 viewDir, in SpotLight light,out vec3 diffuseColor,out vec3 specularColor)\n{\n vec3 lightVec = pos-light.Position;\n //if( length(lightVec) > light.Range )\n // return;\n vec3 normalLightVec=lightVec/length(lightVec);\n LayaAirBlinnPhongLight(specColor,specColorIntensity,normal,gloss,viewDir,light.Color,normalLightVec,diffuseColor,specularColor);\n float spot = pow(max(dot(normalLightVec, normalize(light.Direction)), 0.0), light.Spot);\n float attenuate = spot*BasicAttenuation(lightVec, 1.0/light.Range);\n diffuseColor *= attenuate;\n specularColor*= attenuate;\n}\n\nvec3 NormalSampleToWorldSpace(vec3 normalMapSample, vec3 unitNormal, vec3 tangent,vec3 binormal)\n{\n vec3 normalT =vec3(2.0*normalMapSample.x - 1.0,1.0-2.0*normalMapSample.y,2.0*normalMapSample.z - 1.0);\n \n // Build orthonormal basis.\n vec3 N = normalize(unitNormal);\n vec3 T = normalize(tangent);\n vec3 B = normalize(binormal);\n mat3 TBN = mat3(T, B, N);\n \n // Transform from tangent space to world space.\n vec3 bumpedNormal = TBN*normalT;\n\n return bumpedNormal;\n}\n\n\n"); Shader3D.addInclude("ShadowHelper.glsl","uniform sampler2D u_shadowMap1;\nuniform sampler2D u_shadowMap2;\nuniform sampler2D u_shadowMap3;\nuniform vec2 u_shadowPCFoffset;\nuniform vec3 u_shadowPSSMDistance;\nvec4 packDepth(const in float depth)\n{\n const vec4 bitShift = vec4(256.0*256.0*256.0, 256.0*256.0, 256.0, 1.0);\n const vec4 bitMask = vec4(0.0, 1.0/256.0, 1.0/256.0, 1.0/256.0);\n vec4 res = mod(depth*bitShift*vec4(255), vec4(256))/vec4(255);\n res -= res.xxyz * bitMask;\n return res;\n}\nfloat unpackDepth(const in vec4 rgbaDepth)\n{\n const vec4 bitShift = vec4(1.0/(256.0*256.0*256.0), 1.0/(256.0*256.0), 1.0/256.0, 1.0);\n float depth = dot(rgbaDepth, bitShift);\n return depth;\n}\nfloat tex2DPCF( sampler2D shadowMap,vec2 texcoord,vec2 invsize,float zRef )\n{\n vec2 texelpos =texcoord / invsize;\n vec2 lerps = fract( texelpos );\n float sourcevals[4];\n sourcevals[0] = float( unpackDepth(texture2D(shadowMap,texcoord)) > zRef );\n sourcevals[1] = float( unpackDepth(texture2D(shadowMap,texcoord + vec2(invsize.x,0))) > zRef );\n sourcevals[2] = float( unpackDepth(texture2D(shadowMap,texcoord + vec2(0,invsize.y))) > zRef );\n sourcevals[3] = float( unpackDepth(texture2D(shadowMap,texcoord + vec2(invsize.x, invsize.y) )) > zRef );\n return mix( mix(sourcevals[0],sourcevals[2],lerps.y),mix(sourcevals[1],sourcevals[3],lerps.y),lerps.x );\n}\nfloat getShadowPSSM3( sampler2D shadowMap1,sampler2D shadowMap2,sampler2D shadowMap3,mat4 lightShadowVP[4],vec3 pssmDistance,vec2 shadowPCFOffset,vec3 worldPos,float posViewZ,float zBias )\n{\n float value = 1.0;\n int nPSNum = int(posViewZ>pssmDistance.x);\n nPSNum += int(posViewZ>pssmDistance.y);\n nPSNum += int(posViewZ>pssmDistance.z);\n //真SB,webgl不支持在PS中直接访问数组\n mat4 lightVP;\n if( nPSNum == 0 )\n {\n lightVP = lightShadowVP[1];\n }\n else if( nPSNum == 1 )\n {\n lightVP = lightShadowVP[2];\n }\n else if( nPSNum == 2 )\n {\n lightVP = lightShadowVP[3];\n }\n vec4 vLightMVPPos = lightVP * vec4(worldPos,1.0);\n //为了效率,在CPU计算/2.0 + 0.5\n //vec3 vText = (vLightMVPPos.xyz / vLightMVPPos.w)/2.0 + 0.5;\n vec3 vText = vLightMVPPos.xyz / vLightMVPPos.w;\n float fMyZ = vText.z - zBias;\n /*\n bvec4 bInFrustumVec = bvec4 ( vText.x >= 0.0, vText.x <= 1.0, vText.y >= 0.0, vText.y <= 1.0 );\n bool bInFrustum = all( bInFrustumVec );\n bvec2 bFrustumTestVec = bvec2( bInFrustum, fMyZ <= 1.0 );\n bool bFrustumTest = all( bFrustumTestVec );\n if ( bFrustumTest ) \n */\n if( fMyZ <= 1.0 )\n {\n float zdepth=0.0;\n#ifdef SHADOWMAP_PCF3\n if ( nPSNum == 0 )\n {\n value = tex2DPCF( shadowMap1, vText.xy,shadowPCFOffset,fMyZ );\n value += tex2DPCF( shadowMap1, vText.xy+vec2(shadowPCFOffset.xy),shadowPCFOffset, fMyZ );\n value += tex2DPCF( shadowMap1, vText.xy+vec2(shadowPCFOffset.x,0),shadowPCFOffset, fMyZ );\n value += tex2DPCF( shadowMap1, vText.xy+vec2(0,shadowPCFOffset.y),shadowPCFOffset, fMyZ );\n value = value/4.0;\n } \n else if( nPSNum == 1 )\n {\n value = tex2DPCF( shadowMap2,vText.xy,shadowPCFOffset,fMyZ);\n }\n else if( nPSNum == 2 )\n {\n vec4 color = texture2D( shadowMap3,vText.xy );\n zdepth = unpackDepth(color);\n value = float(fMyZ < zdepth);\n }\n#endif\n#ifdef SHADOWMAP_PCF2\n if ( nPSNum == 0 )\n {\n value = tex2DPCF( shadowMap1,vText.xy,shadowPCFOffset,fMyZ);\n }\n else if( nPSNum == 1 )\n {\n value = tex2DPCF( shadowMap2,vText.xy,shadowPCFOffset,fMyZ);\n }\n else if( nPSNum == 2 )\n {\n vec4 color = texture2D( shadowMap3,vText.xy );\n zdepth = unpackDepth(color);\n value = float(fMyZ < zdepth);\n }\n\n#endif\n#ifdef SHADOWMAP_PCF1\n if ( nPSNum == 0 )\n {\n value = tex2DPCF( shadowMap1,vText.xy,shadowPCFOffset,fMyZ);\n }\n else if( nPSNum == 1 )\n {\n vec4 color = texture2D( shadowMap2,vText.xy );\n zdepth = unpackDepth(color);\n value = float(fMyZ < zdepth);\n }\n else if( nPSNum == 2 )\n {\n vec4 color = texture2D( shadowMap3,vText.xy );\n zdepth = unpackDepth(color);\n value = float(fMyZ < zdepth);\n }\n#endif\n#ifdef SHADOWMAP_PCF_NO\n vec4 color;\n if ( nPSNum == 0 )\n {\n color = texture2D( shadowMap1,vText.xy );\n }\n else if( nPSNum == 1 )\n {\n color = texture2D( shadowMap2,vText.xy );\n }\n else if( nPSNum == 2 )\n {\n color = texture2D( shadowMap3,vText.xy );\n }\n zdepth = unpackDepth(color);\n value = float(fMyZ < zdepth);\n#endif\n }\n return value;\n}\nfloat getShadowPSSM2( sampler2D shadowMap1,sampler2D shadowMap2,mat4 lightShadowVP[4],vec3 pssmDistance,vec2 shadowPCFOffset,vec3 worldPos,float posViewZ,float zBias )\n{\n float value = 1.0;\n int nPSNum = int(posViewZ>pssmDistance.x);\n nPSNum += int(posViewZ>pssmDistance.y);\n //真SB,webgl不支持在PS中直接访问数组\n mat4 lightVP;\n if( nPSNum == 0 )\n {\n lightVP = lightShadowVP[1];\n }\n else if( nPSNum == 1 )\n {\n lightVP = lightShadowVP[2];\n }\n vec4 vLightMVPPos = lightVP * vec4(worldPos,1.0);\n //为了效率,在CPU计算/2.0 + 0.5\n //vec3 vText = (vLightMVPPos.xyz / vLightMVPPos.w)/2.0 + 0.5;\n vec3 vText = vLightMVPPos.xyz / vLightMVPPos.w;\n float fMyZ = vText.z - zBias;\n /*\n bvec4 bInFrustumVec = bvec4 ( vText.x >= 0.0, vText.x <= 1.0, vText.y >= 0.0, vText.y <= 1.0 );\n bool bInFrustum = all( bInFrustumVec );\n bvec2 bFrustumTestVec = bvec2( bInFrustum, fMyZ <= 1.0 );\n bool bFrustumTest = all( bFrustumTestVec );\n if ( bFrustumTest ) \n */\n if( fMyZ <= 1.0 )\n {\n float zdepth=0.0;\n#ifdef SHADOWMAP_PCF3\n if ( nPSNum == 0 )\n {\n value = tex2DPCF( shadowMap1, vText.xy,shadowPCFOffset,fMyZ );\n value += tex2DPCF( shadowMap1, vText.xy+vec2(shadowPCFOffset.xy),shadowPCFOffset, fMyZ );\n value += tex2DPCF( shadowMap1, vText.xy+vec2(shadowPCFOffset.x,0),shadowPCFOffset, fMyZ );\n value += tex2DPCF( shadowMap1, vText.xy+vec2(0,shadowPCFOffset.y),shadowPCFOffset, fMyZ );\n value = value/4.0;\n }\n else if( nPSNum == 1 )\n {\n value = tex2DPCF( shadowMap2,vText.xy,shadowPCFOffset,fMyZ);\n }\n#endif\n#ifdef SHADOWMAP_PCF2\n if ( nPSNum == 0 )\n {\n value = tex2DPCF( shadowMap1,vText.xy,shadowPCFOffset,fMyZ);\n }\n else if( nPSNum == 1 )\n {\n value = tex2DPCF( shadowMap2,vText.xy,shadowPCFOffset,fMyZ);\n }\n#endif\n#ifdef SHADOWMAP_PCF1\n if ( nPSNum == 0 )\n {\n value = tex2DPCF( shadowMap1,vText.xy,shadowPCFOffset,fMyZ);\n }\n else if( nPSNum == 1 )\n {\n vec4 color = texture2D( shadowMap2,vText.xy );\n zdepth = unpackDepth(color);\n value = float(fMyZ < zdepth);\n }\n#endif\n#ifdef SHADOWMAP_PCF_NO\n vec4 color;\n if ( nPSNum == 0 )\n {\n color = texture2D( shadowMap1,vText.xy );\n }\n else if( nPSNum == 1 )\n {\n color = texture2D( shadowMap2,vText.xy );\n }\n zdepth = unpackDepth(color);\n value = float(fMyZ < zdepth);\n#endif\n }\n return value;\n}\nfloat getShadowPSSM1( sampler2D shadowMap1,vec4 lightMVPPos,vec3 pssmDistance,vec2 shadowPCFOffset,float posViewZ,float zBias )\n{\n float value = 1.0;\n if( posViewZ < pssmDistance.x )\n {\n vec3 vText = lightMVPPos.xyz / lightMVPPos.w;\n float fMyZ = vText.z - zBias;\n /*\n bvec4 bInFrustumVec = bvec4 ( vText.x >= 0.0, vText.x <= 1.0, vText.y >= 0.0, vText.y <= 1.0 );\n bool bInFrustum = all( bInFrustumVec );\n bvec2 bFrustumTestVec = bvec2( bInFrustum, fMyZ <= 1.0 );\n bool bFrustumTest = all( bFrustumTestVec );\n */\n if ( fMyZ <= 1.0 ) \n {\n float zdepth=0.0;\n#ifdef SHADOWMAP_PCF3\n value = tex2DPCF( shadowMap1, vText.xy,shadowPCFOffset,fMyZ );\n value += tex2DPCF( shadowMap1, vText.xy+vec2(shadowPCFOffset.xy),shadowPCFOffset,fMyZ );\n value += tex2DPCF( shadowMap1, vText.xy+vec2(shadowPCFOffset.x,0),shadowPCFOffset,fMyZ );\n value += tex2DPCF( shadowMap1, vText.xy+vec2(0,shadowPCFOffset.y),shadowPCFOffset,fMyZ );\n value = value/4.0;\n#endif\n#ifdef SHADOWMAP_PCF2 \n value = tex2DPCF( shadowMap1,vText.xy,shadowPCFOffset,fMyZ);\n#endif\n#ifdef SHADOWMAP_PCF1\n value = tex2DPCF( shadowMap1,vText.xy,shadowPCFOffset,fMyZ);\n#endif\n#ifdef SHADOWMAP_PCF_NO \n vec4 color = texture2D( shadowMap1,vText.xy );\n zdepth = unpackDepth(color);\n value = float(fMyZ < zdepth);\n#endif\n }\n }\n return value;\n}"); Shader3D.addInclude("WaveFunction.glsl","\nuniform vec2 u_WaveInfoD[20];\nuniform vec4 u_WaveInfo[20];\n\nuniform float TEXWAVE_UV_SCALE ;//= 20.0; //每texwidth像素代表的实际距离\n/**\n 这里的计算都是\n*/\n\n/**\n* 计算一个波形\n* 开始计算的时候都按照z向上,最后输出的时候,颠倒一下。\n* @param tm {float} 毫秒\n*/\nvoid calcGerstnerWave(float curtm, vec3 pos, float deep, vec2 uvpos, out vec3 opos, out vec3 B, out vec3 T, out vec3 N, out float foamS){\n float tm = curtm/1000.;\n opos = pos;\n vec3 wpos=vec3(0.); //累加的位置\n N=vec3(0.,0.,0.); //输出的法线初始化一下\n T=vec3(0.,0.,0.);\n B=vec3(0.,0.,0.);\n vec2 cD ;//= D;\n //float deepAtt = max(0.,min(deep,1.0));\n //A*=deepAtt; //TODO\n \n for( int i=0; i<4; i++){\n cD = u_WaveInfoD[i];//vec2(wi.winfo[0],wi.winfo[1]);// wi.vDir;\n float Q = u_WaveInfo[i].x;//wi.QorK;\n float A = u_WaveInfo[i].y;//wi.A;\n float W = u_WaveInfo[i].z;//wi.omega;\n float P = u_WaveInfo[i].w;//wi.phi;\n float dop = dot(cD,uvpos);\n float c = cos(dop*W - tm*P);//TODO 优化\n float s = sin(dop*W - tm*P);\n float AWs = A*W*s;\n float AWc = A*W*c;\n float _QxyAWs = -Q*cD.x*cD.y*AWs;\n \n wpos += vec3(Q*A*cD.x*c,\n Q*A*cD.y*c,\n A*s);\n N += vec3(-cD.x*AWc,\n -cD.y*AWc,\n Q*AWs);//记得最后1-\n T += vec3(_QxyAWs,\n Q*cD.y*cD.y*AWs,//记得1-\n cD.y*AWc\n );\n B += vec3(Q*cD.x*cD.x*AWs,//记得1-\n _QxyAWs,\n cD.x*AWc\n );\n //float v1 = exp(-tan((dop*W - tm*P)/2.+1.07));//除2,+pi/2 这样正好能对齐\n#ifdef USE_FOAM \n float v1 = 0.5-sin((dop*W - tm*P)/1.+2.0)/2.;\n foamS += pow(v1,9.)/4.;\n#endif\n }\n T.y=1.-T.y; B.x=1.-B.x;N.z=1.-N.z;\n opos += vec3(wpos.x,wpos.z*min(deep/10.,1.),wpos.y);\n //y和z交换一下。现在根据uv计算的位置,所以直接交换yz就行。其他情况下有问题么\n T.xyz=T.xzy;\n B.xyz=B.xzy;\n N.xyz=N.xzy;\n}\n\n\nvoid calcWave(float curtm, vec2 uv, out vec3 B, out vec3 T, out vec3 N){\n float tm = curtm/1000.;\n N=vec3(0.,0.,0.); //输出的法线初始化一下\n vec2 uvpos = uv*TEXWAVE_UV_SCALE; //TODO 这个范围是什么 就是1?\n uvpos.y*=-1.;\n vec2 cD;// = D;\n const int NumWaves = 4;\n float scale = 1./float(NumWaves);\n for( int i=0; iShader3D 主要用数组的方式保存shader变量定义,后期合并ShaderValue不使用for in,性能较高。 */ //class laya.d3.shader.ValusArray var ValusArray=(function(){ function ValusArray(){ this._data=null; this._data=[]; } __class(ValusArray,'laya.d3.shader.ValusArray'); var __proto=ValusArray.prototype; __proto.setValue=function(name,value){ this._data[name]=value; } __getset(0,__proto,'data',function(){ return this._data; }); return ValusArray; })() /** *... *@author ... */ //class laya.d3.shadowMap.ParallelSplitShadowMap var ParallelSplitShadowMap=(function(){ function ParallelSplitShadowMap(){ /**@private */ //this.lastNearPlane=NaN; /**@private */ //this.lastFieldOfView=NaN; /**@private */ //this.lastAspectRatio=NaN; /**@private */ this._currentPSSM=-1; /**@private */ this._numberOfPSSM=3; /**@private */ this._maxDistance=200.0; /**@private */ this._ratioOfDistance=1.0 / this._numberOfPSSM; /**@private */ this._statesDirty=true; /**@private */ this._lightCulling=null; /**@private */ this._renderTarget=null; /**@private */ this._lightVPMatrix=null; /**@private */ this._lightCameras=null; /**@private */ this._shadowQuenes=null; /**@private */ this._shadowMapTextureSize=1024; /**@private */ this._scene=null; /**@private */ this._PCFType=0; /**@private */ this._shaderValueLightVP=null; /**@private */ this._shaderValueVPs=null; this._spiltDistance=new Array(/*CLASS CONST:laya.d3.shadowMap.ParallelSplitShadowMap.MAX_PSSM_COUNT*/3+1); this._globalParallelLightDir=new Vector3(0,-1,0); this._boundingSphere=new Array(/*CLASS CONST:laya.d3.shadowMap.ParallelSplitShadowMap.MAX_PSSM_COUNT*/3+1); this._boundingBox=new Array(/*CLASS CONST:laya.d3.shadowMap.ParallelSplitShadowMap.MAX_PSSM_COUNT*/3+1); this._frustumPos=new Array((/*CLASS CONST:laya.d3.shadowMap.ParallelSplitShadowMap.MAX_PSSM_COUNT*/3+1)*4); this._uniformDistance=new Array(/*CLASS CONST:laya.d3.shadowMap.ParallelSplitShadowMap.MAX_PSSM_COUNT*/3+1); this._logDistance=new Array(/*CLASS CONST:laya.d3.shadowMap.ParallelSplitShadowMap.MAX_PSSM_COUNT*/3+1); this._dimension=new Array(/*CLASS CONST:laya.d3.shadowMap.ParallelSplitShadowMap.MAX_PSSM_COUNT*/3+1); this._tempLookAt3=new Vector3(); this._tempLookAt4=new Vector4(); this._tempValue=new Vector4(); this._tempPos=new Vector3(); this._tempLightUp=new Vector3(); this._tempMin=new Vector4(); this._tempMax=new Vector4(); this._tempMatrix44=new Matrix4x4; this._splitFrustumCulling=new BoundFrustum(Matrix4x4.DEFAULT); this._tempScaleMatrix44=new Matrix4x4; this._shadowPCFOffset=new Vector2(1.0 / 1024.0,1.0 / 1024.0); this._shaderValueDistance=new Vector4(); var i=0; for (i=0;i < this._spiltDistance.length;i++){ this._spiltDistance[i]=0.0; } for (i=0;i < this._dimension.length;i++){ this._dimension[i]=new Vector2(); } for (i=0;i < this._frustumPos.length;i++){ this._frustumPos[i]=new Vector3(); } for (i=0;i < this._boundingBox.length;i++){ this._boundingBox[i]=new BoundBox(new Vector3(),new Vector3()); } for (i=0;i < this._boundingSphere.length;i++){ this._boundingSphere[i]=new BoundSphere(new Vector3(),0.0); } Matrix4x4.createScaling(new Vector3(0.5,0.5,1.0),this._tempScaleMatrix44); this._tempScaleMatrix44.elements[12]=0.5; this._tempScaleMatrix44.elements[13]=0.5; } __class(ParallelSplitShadowMap,'laya.d3.shadowMap.ParallelSplitShadowMap'); var __proto=ParallelSplitShadowMap.prototype; __proto.setInfo=function(scene,maxDistance,globalParallelDir,shadowMapTextureSize,numberOfPSSM,PCFType){ if (numberOfPSSM > /*CLASS CONST:laya.d3.shadowMap.ParallelSplitShadowMap.MAX_PSSM_COUNT*/3){ this._numberOfPSSM=/*CLASS CONST:laya.d3.shadowMap.ParallelSplitShadowMap.MAX_PSSM_COUNT*/3; } this._scene=scene; this._maxDistance=maxDistance; this.PSSMNum=numberOfPSSM; this._globalParallelLightDir=globalParallelDir; this._ratioOfDistance=1.0 / this._numberOfPSSM; for (var i=0;i < this._spiltDistance.length;i++){ this._spiltDistance[i]=0.0; } this._shadowMapTextureSize=shadowMapTextureSize; this._shadowPCFOffset.x=1.0 / this._shadowMapTextureSize; this._shadowPCFOffset.y=1.0 / this._shadowMapTextureSize; this.setPCFType(PCFType); this._statesDirty=true; } __proto.setPCFType=function(PCFtype){ this._PCFType=PCFtype; switch (this._PCFType){ case 0: this._scene.addShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF_NO); this._scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF1); this._scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF2); this._scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF3); break ; case 1: this._scene.addShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF1); this._scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF_NO); this._scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF2); this._scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF3); break ; case 2: this._scene.addShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF2); this._scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF_NO); this._scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF1); this._scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF3); break ; case 3: this._scene.addShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF3); this._scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF_NO); this._scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF1); this._scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF2); break ; } } __proto.getPCFType=function(){ return this._PCFType; } __proto.setFarDistance=function(value){ if (this._maxDistance !=value){ this._maxDistance=value; this._statesDirty=true; } } __proto.getFarDistance=function(){ return this._maxDistance; } __proto._setGlobalParallelLightDir=function(dir){ this._globalParallelLightDir=dir; } __proto.getGlobalParallelLightDir=function(){ return this._globalParallelLightDir; } __proto.getCurrentPSSM=function(){ return this._currentPSSM; } __proto.getLightCamera=function(index){ return this._lightCameras[index]; } /** *@private */ __proto._beginSampler=function(index,sceneCamera){ if (index < 0 || index > this._numberOfPSSM) throw new Error("ParallelSplitShadowMap: beginSample invalid index"); this._currentPSSM=index; this._update(sceneCamera); } /** *@private */ __proto.endSampler=function(sceneCamera){ this._currentPSSM=-1; } /** *@private */ __proto._calcAllLightCameraInfo=function(sceneCamera){ if (this._numberOfPSSM===1){ this._beginSampler(0,sceneCamera); this.endSampler(sceneCamera); }else { for (var i=0,n=this._numberOfPSSM+1;i < n;i++){ this._beginSampler(i,sceneCamera); this.endSampler(sceneCamera); } } } /** *@private */ __proto._recalculate=function(nearPlane,fieldOfView,aspectRatio){ this._calcSplitDistance(nearPlane); this._calcBoundingBox(fieldOfView,aspectRatio); this._rebuildRenderInfo(); } /** *@private */ __proto._update=function(sceneCamera){ var nearPlane=sceneCamera.nearPlane; var fieldOfView=sceneCamera.fieldOfView; var aspectRatio=(sceneCamera).aspectRatio; if (this._statesDirty || this.lastNearPlane!==nearPlane || this.lastFieldOfView!==fieldOfView || this.lastAspectRatio!==aspectRatio){ this._recalculate(nearPlane,fieldOfView,aspectRatio); this._uploadShaderValue(); this._statesDirty=false; this.lastNearPlane=nearPlane; this.lastFieldOfView=fieldOfView; this.lastAspectRatio=aspectRatio; } this._calcLightViewProject(sceneCamera); } /** *@private */ __proto._uploadShaderValue=function(){ var scene=this._scene; switch (this._numberOfPSSM){ case 1: scene.addShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM1); scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM2); scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM3); break ; case 2: scene.addShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM2); scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM1); scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM3); break ; case 3: scene.addShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM3); scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM1); scene.removeShaderDefine(laya.d3.shadowMap.ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM2); break ; }; var sceneSV=scene._shaderValues; sceneSV.setValue(/*laya.d3.core.scene.Scene.SHADOWDISTANCE*/15,this._shaderValueDistance.elements); sceneSV.setValue(/*laya.d3.core.scene.Scene.SHADOWLIGHTVIEWPROJECT*/16,this._shaderValueLightVP); sceneSV.setValue(/*laya.d3.core.scene.Scene.SHADOWMAPPCFOFFSET*/17,this._shadowPCFOffset.elements); switch (this._numberOfPSSM){ case 3: sceneSV.setValue(/*laya.d3.core.scene.Scene.SHADOWMAPTEXTURE1*/18,this.getRenderTarget(1)); sceneSV.setValue(/*laya.d3.core.scene.Scene.SHADOWMAPTEXTURE2*/19,this.getRenderTarget(2)); sceneSV.setValue(/*laya.d3.core.scene.Scene.SHADOWMAPTEXTURE3*/20,this.getRenderTarget(3)); break ; case 2: sceneSV.setValue(/*laya.d3.core.scene.Scene.SHADOWMAPTEXTURE1*/18,this.getRenderTarget(1)); sceneSV.setValue(/*laya.d3.core.scene.Scene.SHADOWMAPTEXTURE2*/19,this.getRenderTarget(2)); break ; case 1: sceneSV.setValue(/*laya.d3.core.scene.Scene.SHADOWMAPTEXTURE1*/18,this.getRenderTarget(1)); break ; } } /** *@private */ __proto._calcSplitDistance=function(nearPlane){ var far=this._maxDistance; var invNumberOfPSSM=1.0 / this._numberOfPSSM; var i=0; for (i=0;i <=this._numberOfPSSM;i++){ this._uniformDistance[i]=nearPlane+(far-nearPlane)*i *invNumberOfPSSM; }; var farDivNear=far / nearPlane; for (i=0;i <=this._numberOfPSSM;i++){ var n=Math.pow(farDivNear,i *invNumberOfPSSM); this._logDistance[i]=nearPlane *n; } for (i=0;i <=this._numberOfPSSM;i++){ this._spiltDistance[i]=this._uniformDistance[i] *this._ratioOfDistance+this._logDistance[i] *(1.0-this._ratioOfDistance); } this._shaderValueDistance.x=this._spiltDistance[1]; this._shaderValueDistance.y=this._spiltDistance[2]; this._shaderValueDistance.z=this._spiltDistance[3]; } /** *@private */ __proto._calcBoundingBox=function(fieldOfView,aspectRatio){ var fov=3.1415926 *fieldOfView / 180.0; var halfTanValue=Math.tan(fov / 2.0); var height=NaN; var width=NaN; var distance=NaN; var i=0; for (i=0;i <=this._numberOfPSSM;i++){ distance=this._spiltDistance[i]; height=distance *halfTanValue; width=height *aspectRatio; var temp=this._frustumPos[i *4+0].elements; temp[0]=-width; temp[1]=-height; temp[2]=-distance; temp=this._frustumPos[i *4+1].elements; temp[0]=width; temp[1]=-height; temp[2]=-distance; temp=this._frustumPos[i *4+2].elements; temp[0]=-width; temp[1]=height; temp[2]=-distance; temp=this._frustumPos[i *4+3].elements; temp[0]=width; temp[1]=height; temp[2]=-distance; temp=this._dimension[i].elements; temp[0]=width; temp[1]=height; }; var d; var min; var max; var center; for (i=1;i <=this._numberOfPSSM;i++){ d=this._dimension[i].elements; min=this._boundingBox[i].min.elements; min[0]=-d[0]; min[1]=-d[1]; min[2]=-this._spiltDistance[i]; max=this._boundingBox[i].max.elements; max[0]=d[0]; max[1]=d[1]; max[2]=-this._spiltDistance[i-1]; center=this._boundingSphere[i].center.elements; center[0]=(min[0]+max[0])*0.5; center[1]=(min[1]+max[1])*0.5; center[2]=(min[2]+max[2])*0.5; this._boundingSphere[i].radius=Math.sqrt(Math.pow(max[0]-min[0],2)+Math.pow(max[1]-min[1],2)+Math.pow(max[2]-min[2],2))*0.5; } min=this._boundingBox[0].min.elements; d=this._dimension[this._numberOfPSSM].elements; min[0]=-d[0]; min[1]=-d[1]; min[2]=-this._spiltDistance[this._numberOfPSSM]; max=this._boundingBox[0].max.elements; max[0]=d[0]; max[1]=d[1]; max[2]=-this._spiltDistance[0]; center=this._boundingSphere[0].center.elements; center[0]=(min[0]+max[0])*0.5; center[1]=(min[1]+max[1])*0.5; center[2]=(min[2]+max[2])*0.5; this._boundingSphere[0].radius=Math.sqrt(Math.pow(max[0]-min[0],2)+Math.pow(max[1]-min[1],2)+Math.pow(max[2]-min[2],2))*0.5; } __proto.calcSplitFrustum=function(sceneCamera){ if (this._currentPSSM > 0){ Matrix4x4.createPerspective(3.1416 *sceneCamera.fieldOfView / 180.0,(sceneCamera).aspectRatio,this._spiltDistance[this._currentPSSM-1],this._spiltDistance[this._currentPSSM],this._tempMatrix44); }else { Matrix4x4.createPerspective(3.1416 *sceneCamera.fieldOfView / 180.0,(sceneCamera).aspectRatio,this._spiltDistance[0],this._spiltDistance[this._numberOfPSSM],this._tempMatrix44); } Matrix4x4.multiply(this._tempMatrix44,(sceneCamera).viewMatrix,this._tempMatrix44); this._splitFrustumCulling.matrix=this._tempMatrix44; } /** *@private */ __proto._rebuildRenderInfo=function(){ var nNum=this._numberOfPSSM+1; var i=0; if (this._renderTarget==null){ this._renderTarget=__newvec(nNum); this._renderTarget[0]=null; for (i=1;i < nNum;i++){ this._renderTarget[i]=new RenderTexture(this._shadowMapTextureSize,this._shadowMapTextureSize,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,/*laya.webgl.WebGLContext.DEPTH_COMPONENT16*/0x81A5,false,false,/*laya.webgl.WebGLContext.NEAREST*/0x2600,/*laya.webgl.WebGLContext.NEAREST*/0x2600); } }else if (this._renderTarget.length !=nNum){ this.disposeAllRenderTarget(); this._renderTarget.length=nNum; this._renderTarget[0]=null; for (i=1;i < nNum;i++){ this._renderTarget[i]=new RenderTexture(this._shadowMapTextureSize,this._shadowMapTextureSize,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,/*laya.webgl.WebGLContext.DEPTH_COMPONENT16*/0x81A5,false,false,/*laya.webgl.WebGLContext.NEAREST*/0x2600,/*laya.webgl.WebGLContext.NEAREST*/0x2600); } }else { for (i=1;i < nNum;i++){ if (this._renderTarget[i]==null || this._renderTarget[i].width !=this._shadowMapTextureSize || this._renderTarget[i].height !=this._shadowMapTextureSize){ if (this._renderTarget[i] !=null){ this._renderTarget[i].destroy(); } this._renderTarget[i]=new RenderTexture(this._shadowMapTextureSize,this._shadowMapTextureSize,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,/*laya.webgl.WebGLContext.DEPTH_COMPONENT16*/0x81A5,false,false,/*laya.webgl.WebGLContext.NEAREST*/0x2600,/*laya.webgl.WebGLContext.NEAREST*/0x2600); } } } if (this._lightCulling==null || this._lightCulling.length !=nNum){ if (this._lightCulling){ this._lightCulling.length=nNum; }else { this._lightCulling=__newvec(nNum); } for (i=0;i < this._lightCulling.length;i++){ this._lightCulling[i]=new BoundFrustum(Matrix4x4.DEFAULT); } } if (this._lightVPMatrix==null || this._lightVPMatrix.length !=nNum){ if (this._lightVPMatrix){ this._lightVPMatrix.length=nNum; }else { this._lightVPMatrix=__newvec(nNum); } for (i=0;i < this._lightVPMatrix.length;i++){ this._lightVPMatrix[i]=new Matrix4x4(); } } if (this._lightCameras==null || this._lightCameras.length !=nNum){ if (this._lightCameras){ this._lightCameras.length=nNum; }else { this._lightCameras=__newvec(nNum); } for (i=0;i < this._lightCameras.length;i++){ this._lightCameras[i]=new Camera(); this._lightCameras[i].name="lightCamera"+i; } } if (this._shadowQuenes==null || this._shadowQuenes.length !=this._numberOfPSSM){ if (this._shadowQuenes){ this._shadowQuenes.length=this._numberOfPSSM; }else { this._shadowQuenes=__newvec(this._numberOfPSSM); } for (i=0;i < this._shadowQuenes.length;i++){ this._shadowQuenes[i]=new RenderQueue(this._scene); } } if (this._shaderValueVPs==null || this._shaderValueVPs.length !=nNum){ if (this._shaderValueVPs){ this._shaderValueVPs.length=nNum; }else { this._shaderValueVPs=__newvec(nNum); } this._shaderValueLightVP=new Float32Array(nNum *16); for (i=0;i < nNum;i++){ this._shaderValueVPs[i]=new Float32Array(this._shaderValueLightVP.buffer,i *64); } } } /** *@private */ __proto._calcLightViewProject=function(sceneCamera){ var boundSphere=this._boundingSphere[this._currentPSSM]; var cameraMatViewInv=sceneCamera.transform.worldMatrix; var radius=boundSphere.radius; boundSphere.center.cloneTo(this._tempLookAt3); Vector3.transformV3ToV4(this._tempLookAt3,cameraMatViewInv,this._tempLookAt4); var lookAt3Element=this._tempLookAt3.elements; var lookAt4Element=this._tempLookAt4.elements; lookAt3Element[0]=lookAt4Element[0]; lookAt3Element[1]=lookAt4Element[1]; lookAt3Element[2]=lookAt4Element[2]; var lightUpElement=this._tempLightUp.elements; var sceneCameraDir=sceneCamera.forward.elements; lightUpElement[0]=sceneCameraDir[0]; lightUpElement[1]=1.0; lightUpElement[2]=sceneCameraDir[2]; Vector3.normalize(this._tempLightUp,this._tempLightUp); Vector3.scale(this._globalParallelLightDir,boundSphere.radius *4,this._tempPos); Vector3.subtract(this._tempLookAt3,this._tempPos,this._tempPos); var curLightCamera=this._lightCameras[this._currentPSSM]; curLightCamera.transform.position=this._tempPos; curLightCamera.transform.lookAt(this._tempLookAt3,this._tempLightUp,false); var tempMaxElements=this._tempMax.elements; var tempMinElements=this._tempMin.elements; tempMaxElements[0]=tempMaxElements[1]=tempMaxElements[2]=-100000.0; tempMaxElements[3]=1.0; tempMinElements[0]=tempMinElements[1]=tempMinElements[2]=100000.0; tempMinElements[3]=1.0; Matrix4x4.multiply(curLightCamera.viewMatrix,cameraMatViewInv,this._tempMatrix44); var tempValueElement=this._tempValue.elements; var corners=[]; corners.length=8; this._boundingBox[this._currentPSSM].getCorners(corners); for (var i=0;i < 8;i++){ var frustumPosElements=corners[i].elements; tempValueElement[0]=frustumPosElements[0]; tempValueElement[1]=frustumPosElements[1]; tempValueElement[2]=frustumPosElements[2]; tempValueElement[3]=1.0; Vector4.transformByM4x4(this._tempValue,this._tempMatrix44,this._tempValue); tempMinElements[0]=(tempValueElement[0] < tempMinElements[0])? tempValueElement[0] :tempMinElements[0]; tempMinElements[1]=(tempValueElement[1] < tempMinElements[1])? tempValueElement[1] :tempMinElements[1]; tempMinElements[2]=(tempValueElement[2] < tempMinElements[2])? tempValueElement[2] :tempMinElements[2]; tempMaxElements[0]=(tempValueElement[0] > tempMaxElements[0])? tempValueElement[0] :tempMaxElements[0]; tempMaxElements[1]=(tempValueElement[1] > tempMaxElements[1])? tempValueElement[1] :tempMaxElements[1]; tempMaxElements[2]=(tempValueElement[2] > tempMaxElements[2])? tempValueElement[2] :tempMaxElements[2]; } Vector4.add(this._tempMax,this._tempMin,this._tempValue); tempValueElement[0] *=0.5; tempValueElement[1] *=0.5; tempValueElement[2] *=0.5; tempValueElement[3]=1; Vector4.transformByM4x4(this._tempValue,curLightCamera.transform.worldMatrix,this._tempValue); var distance=Math.abs(-this._tempMax.z); var farPlane=distance > this._maxDistance ? distance :this._maxDistance; Vector3.scale(this._globalParallelLightDir,farPlane,this._tempPos); var tempPosElement=this._tempPos.elements; tempPosElement[0]=tempValueElement[0]-tempPosElement[0]; tempPosElement[1]=tempValueElement[1]-tempPosElement[1]; tempPosElement[2]=tempValueElement[2]-tempPosElement[2]; curLightCamera.transform.position=this._tempPos; curLightCamera.transform.lookAt(this._tempLookAt3,this._tempLightUp,false); Matrix4x4.createOrthoOffCenterRH(tempMinElements[0],tempMaxElements[0],tempMinElements[1],tempMaxElements[1],1.0,farPlane+0.5 *(tempMaxElements[2]-tempMinElements[2]),curLightCamera.projectionMatrix); curLightCamera.projectionViewMatrix.cloneTo(this._lightVPMatrix[this._currentPSSM]); this._lightCulling[this._currentPSSM].matrix=this._lightVPMatrix[this._currentPSSM]; ParallelSplitShadowMap.multiplyMatrixOutFloat32Array(this._tempScaleMatrix44,this._lightVPMatrix[this._currentPSSM],this._shaderValueVPs[this._currentPSSM]); } __proto.getLightFrustumCulling=function(currentPSSM){ return this._lightCulling[currentPSSM]; } __proto.getSplitFrustumCulling=function(){ return this._splitFrustumCulling; } __proto.getSplitDistance=function(index){ return this._spiltDistance[index]; } __proto.setShadowMapTextureSize=function(size){ if (size!==this._shadowMapTextureSize){ this._shadowMapTextureSize=size; this._shadowPCFOffset.x=1 / this._shadowMapTextureSize; this._shadowPCFOffset.y=1 / this._shadowMapTextureSize; this._statesDirty=true; } } __proto.getShadowMapTextureSize=function(){ return this._shadowMapTextureSize; } __proto.beginRenderTarget=function(index){ this._renderTarget[index].start(); } __proto.endRenderTarget=function(index){ this._renderTarget[index].end(); } __proto.getRenderTarget=function(index){ return this._renderTarget[index]; } __proto.disposeAllRenderTarget=function(){ for (var i=0,n=this._numberOfPSSM+1;i < n;i++){ if (this._renderTarget[i]){ this._renderTarget[i].destroy(); this._renderTarget[i]=null; } } } __getset(0,__proto,'PSSMNum',function(){ return this._numberOfPSSM; },function(value){ value=value > 0 ? value :1; value=value <=3 ? value :3; if (this._numberOfPSSM !=value){ this._numberOfPSSM=value; this._ratioOfDistance=1.0 / this._numberOfPSSM; this._statesDirty=true; } }); ParallelSplitShadowMap.multiplyMatrixOutFloat32Array=function(left,right,out){ var i,a,b,ai0,ai1,ai2,ai3; a=left.elements; b=right.elements; for (i=0;i < 4;i++){ ai0=a[i]; ai1=a[i+4]; ai2=a[i+8]; ai3=a[i+12]; out[i]=ai0 *b[0]+ai1 *b[1]+ai2 *b[2]+ai3 *b[3]; out[i+4]=ai0 *b[4]+ai1 *b[5]+ai2 *b[6]+ai3 *b[7]; out[i+8]=ai0 *b[8]+ai1 *b[9]+ai2 *b[10]+ai3 *b[11]; out[i+12]=ai0 *b[12]+ai1 *b[13]+ai2 *b[14]+ai3 *b[15]; } } ParallelSplitShadowMap.SHADERDEFINE_RECEIVE_SHADOW=0x1; ParallelSplitShadowMap.SHADERDEFINE_CAST_SHADOW=0x200; ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM1=0x400; ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM2=0x800; ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM3=0x1000; ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF_NO=0x2000; ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF1=0x4000; ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF2=0x8000; ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PCF3=0x10000; ParallelSplitShadowMap.MAX_PSSM_COUNT=3; return ParallelSplitShadowMap; })() /** *TerrainLeaf Terrain的叶子节点 */ //class laya.d3.terrain.TerrainLeaf var TerrainLeaf=(function(){ function TerrainLeaf(){ this._boundingSphere=null; this._boundingBox=null; this._sizeOfY=null; this._currentLODLevel=0; this._lastDistanceToEye=NaN; this._originalBoundingSphere=null; this._originalBoundingBox=null; this._originalBoundingBoxCorners=null; this._bUseStrip=false; this._gridSize=NaN; this._beginGridX=0; //针对整个大地形的偏移 this._beginGridZ=0; //针对整个大地形的偏移 this._LODError=null; TerrainLeaf.__init__(); this._currentLODLevel=0; } __class(TerrainLeaf,'laya.d3.terrain.TerrainLeaf'); var __proto=TerrainLeaf.prototype; __proto.calcVertextNorml=function(x,z,terrainHeightData,heighDataWidth,heightDataHeight,normal){ var dZ=0,dX=0; dX=TerrainLeaf.getHeightFromTerrainHeightData(x-1,z-1,terrainHeightData,heighDataWidth,heightDataHeight)*-1.0; dX+=TerrainLeaf.getHeightFromTerrainHeightData(x-1,z,terrainHeightData,heighDataWidth,heightDataHeight)*-1.0; dX+=TerrainLeaf.getHeightFromTerrainHeightData(x-1,z+1,terrainHeightData,heighDataWidth,heightDataHeight)*-1.0; dX+=TerrainLeaf.getHeightFromTerrainHeightData(x+1,z-1,terrainHeightData,heighDataWidth,heightDataHeight)*1.0; dX+=TerrainLeaf.getHeightFromTerrainHeightData(x+1,z,terrainHeightData,heighDataWidth,heightDataHeight)*1.0; dX+=TerrainLeaf.getHeightFromTerrainHeightData(x+1,z+1,terrainHeightData,heighDataWidth,heightDataHeight)*1.0; dZ=TerrainLeaf.getHeightFromTerrainHeightData(x-1,z-1,terrainHeightData,heighDataWidth,heightDataHeight)*-1.0; dZ+=TerrainLeaf.getHeightFromTerrainHeightData(x,z-1,terrainHeightData,heighDataWidth,heightDataHeight)*-1.0; dZ+=TerrainLeaf.getHeightFromTerrainHeightData(x+1,z-1,terrainHeightData,heighDataWidth,heightDataHeight)*-1.0; dZ+=TerrainLeaf.getHeightFromTerrainHeightData(x-1,z+1,terrainHeightData,heighDataWidth,heightDataHeight)*1.0; dZ+=TerrainLeaf.getHeightFromTerrainHeightData(x,z+1,terrainHeightData,heighDataWidth,heightDataHeight)*1.0; dZ+=TerrainLeaf.getHeightFromTerrainHeightData(x+1,z+1,terrainHeightData,heighDataWidth,heightDataHeight)*1.0; normal.x=-dX; normal.y=6; normal.z=-dZ; Vector3.normalize(normal,normal); } __proto.calcVertextNormlUV=function(x,z,terrainWidth,terrainHeight,normal){ normal.x=x / terrainWidth; normal.y=z / terrainHeight; normal.z=z / terrainHeight; } __proto.calcVertextBuffer=function(offsetChunkX,offsetChunkZ,beginX,beginZ,girdSize,vertextBuffer,offset,strideSize,terrainHeightData,heighDataWidth,heightDataHeight,cameraCoordinateInverse){ if (cameraCoordinateInverse==true && !TerrainLeaf.__ADAPT_MATRIX__){ TerrainLeaf.__ADAPT_MATRIX__=new Matrix4x4(); var mat=new Matrix4x4(); Matrix4x4.createRotationY(Math.PI,TerrainLeaf.__ADAPT_MATRIX__); Matrix4x4.createTranslate(new Vector3(0,0,(heightDataHeight-1)*girdSize),mat); Matrix4x4.multiply(mat,TerrainLeaf.__ADAPT_MATRIX__,TerrainLeaf.__ADAPT_MATRIX__); TerrainLeaf.__ADAPT_MATRIX_INV__=new Matrix4x4(); TerrainLeaf.__ADAPT_MATRIX__.invert(TerrainLeaf.__ADAPT_MATRIX_INV__); } this._gridSize=girdSize; this._beginGridX=offsetChunkX *TerrainLeaf.CHUNK_GRID_NUM+beginX; this._beginGridZ=offsetChunkZ *TerrainLeaf.CHUNK_GRID_NUM+beginZ; var nNum=offset *strideSize; var minY=2147483647; var maxY=-2147483648; var normal=new Vector3(); for (var i=0,s=TerrainLeaf.LEAF_GRID_NUM+1;i < s;i++){ for (var j=0,s1=TerrainLeaf.LEAF_GRID_NUM+1;j < s1;j++){ TerrainLeaf.__VECTOR3__.x=(this._beginGridX+j)*this._gridSize; TerrainLeaf.__VECTOR3__.z=(this._beginGridZ+i)*this._gridSize; TerrainLeaf.__VECTOR3__.y=terrainHeightData[(this._beginGridZ+i)*(heighDataWidth)+(this._beginGridX+j)]; minY=TerrainLeaf.__VECTOR3__.y < minY ? TerrainLeaf.__VECTOR3__.y :minY; maxY=TerrainLeaf.__VECTOR3__.y > maxY ? TerrainLeaf.__VECTOR3__.y :maxY; if (TerrainLeaf.__ADAPT_MATRIX__){ Vector3.transformV3ToV3(TerrainLeaf.__VECTOR3__,TerrainLeaf.__ADAPT_MATRIX__,TerrainLeaf.__VECTOR3__); } vertextBuffer[nNum]=TerrainLeaf.__VECTOR3__.x; nNum++; vertextBuffer[nNum]=TerrainLeaf.__VECTOR3__.y; nNum++; vertextBuffer[nNum]=TerrainLeaf.__VECTOR3__.z; nNum++; this.calcVertextNormlUV(this._beginGridX+j,this._beginGridZ+i,heighDataWidth,heightDataHeight,normal); vertextBuffer[nNum]=normal.x; nNum++; vertextBuffer[nNum]=normal.y; nNum++; vertextBuffer[nNum]=normal.z; nNum++; vertextBuffer[nNum]=(beginX+j)/ TerrainLeaf.CHUNK_GRID_NUM; nNum++; vertextBuffer[nNum]=(beginZ+i)/ TerrainLeaf.CHUNK_GRID_NUM; nNum++; vertextBuffer[nNum]=this._beginGridX+j; nNum++; vertextBuffer[nNum]=this._beginGridZ+i; nNum++; } } this._sizeOfY=new Vector2(minY-1,maxY+1); this.calcLODErrors(terrainHeightData,heighDataWidth,heightDataHeight); this.calcOriginalBoudingBoxAndSphere(); } __proto.calcSkirtVertextBuffer=function(offsetChunkX,offsetChunkZ,beginX,beginZ,girdSize,vertextBuffer,offset,strideSize,terrainHeightData,heighDataWidth,heightDataHeight){ this._gridSize=girdSize; this._beginGridX=offsetChunkX *TerrainLeaf.CHUNK_GRID_NUM+beginX; this._beginGridZ=offsetChunkZ *TerrainLeaf.CHUNK_GRID_NUM+beginZ; var nNum=offset *strideSize; var i=0,j=0,s=TerrainLeaf.LEAF_GRID_NUM+1; var normal=new Vector3(); var hZIndex=0; var hXIndex=0; var h=0; var zh=0; var xh=0; for (i=0;i < 2;i++){ for (j=0;j < s;j++){ TerrainLeaf.__VECTOR3__.x=(this._beginGridX+j)*this._gridSize; TerrainLeaf.__VECTOR3__.y=(i==1 ? terrainHeightData[this._beginGridZ *heighDataWidth+(this._beginGridX+j)] :-this._gridSize); TerrainLeaf.__VECTOR3__.z=(this._beginGridZ+0)*this._gridSize; if (TerrainLeaf.__ADAPT_MATRIX__){ Vector3.transformV3ToV3(TerrainLeaf.__VECTOR3__,TerrainLeaf.__ADAPT_MATRIX__,TerrainLeaf.__VECTOR3__); } vertextBuffer[nNum]=TerrainLeaf.__VECTOR3__.x; nNum++; vertextBuffer[nNum]=TerrainLeaf.__VECTOR3__.y; nNum++; vertextBuffer[nNum]=TerrainLeaf.__VECTOR3__.z; nNum++; if (i==0){ hZIndex=(this._beginGridZ-1); }else { hZIndex=this._beginGridZ; } this.calcVertextNormlUV(this._beginGridX+j,hZIndex,heighDataWidth,heightDataHeight,normal); vertextBuffer[nNum]=normal.x; nNum++; vertextBuffer[nNum]=normal.y; nNum++; vertextBuffer[nNum]=normal.z; nNum++; vertextBuffer[nNum]=(beginX+j)/ TerrainLeaf.CHUNK_GRID_NUM; nNum++; vertextBuffer[nNum]=(beginZ+0)/ TerrainLeaf.CHUNK_GRID_NUM; nNum++; vertextBuffer[nNum]=this._beginGridX+j; nNum++; vertextBuffer[nNum]=hZIndex; nNum++; } } for (i=0;i < 2;i++){ for (j=0;j < s;j++){ TerrainLeaf.__VECTOR3__.x=(this._beginGridX+j)*this._gridSize; TerrainLeaf.__VECTOR3__.y=(i==0 ? terrainHeightData[(this._beginGridZ+TerrainLeaf.LEAF_GRID_NUM)*(heighDataWidth)+(this._beginGridX+j)] :-this._gridSize); TerrainLeaf.__VECTOR3__.z=(this._beginGridZ+TerrainLeaf.LEAF_GRID_NUM)*this._gridSize; if (TerrainLeaf.__ADAPT_MATRIX__){ Vector3.transformV3ToV3(TerrainLeaf.__VECTOR3__,TerrainLeaf.__ADAPT_MATRIX__,TerrainLeaf.__VECTOR3__); } vertextBuffer[nNum]=TerrainLeaf.__VECTOR3__.x; nNum++; vertextBuffer[nNum]=TerrainLeaf.__VECTOR3__.y; nNum++; vertextBuffer[nNum]=TerrainLeaf.__VECTOR3__.z; nNum++; if (i==0){ hZIndex=this._beginGridZ+TerrainLeaf.LEAF_GRID_NUM; }else { hZIndex=(this._beginGridZ+TerrainLeaf.LEAF_GRID_NUM+1); } this.calcVertextNormlUV(this._beginGridX+j,hZIndex,heighDataWidth,heightDataHeight,normal); vertextBuffer[nNum]=normal.x; nNum++; vertextBuffer[nNum]=normal.y; nNum++; vertextBuffer[nNum]=normal.z; nNum++; vertextBuffer[nNum]=(beginX+j)/ TerrainLeaf.CHUNK_GRID_NUM; nNum++; vertextBuffer[nNum]=(beginZ+TerrainLeaf.LEAF_GRID_NUM)/ TerrainLeaf.CHUNK_GRID_NUM; nNum++; vertextBuffer[nNum]=this._beginGridX+j; nNum++; vertextBuffer[nNum]=hZIndex; nNum++; } } for (i=0;i < 2;i++){ for (j=0;j < s;j++){ TerrainLeaf.__VECTOR3__.x=(this._beginGridX+0)*this._gridSize; TerrainLeaf.__VECTOR3__.y=(i==0 ? terrainHeightData[(this._beginGridZ+j)*(heighDataWidth)+(this._beginGridX+0)] :-this._gridSize); TerrainLeaf.__VECTOR3__.z=(this._beginGridZ+j)*this._gridSize; if (TerrainLeaf.__ADAPT_MATRIX__){ Vector3.transformV3ToV3(TerrainLeaf.__VECTOR3__,TerrainLeaf.__ADAPT_MATRIX__,TerrainLeaf.__VECTOR3__); } vertextBuffer[nNum]=TerrainLeaf.__VECTOR3__.x; nNum++; vertextBuffer[nNum]=TerrainLeaf.__VECTOR3__.y; nNum++; vertextBuffer[nNum]=TerrainLeaf.__VECTOR3__.z; nNum++; if (i==0){ hXIndex=this._beginGridX; }else { hXIndex=(this._beginGridX-1); } this.calcVertextNormlUV(hXIndex,this._beginGridZ+j,heighDataWidth,heightDataHeight,normal); vertextBuffer[nNum]=normal.x; nNum++; vertextBuffer[nNum]=normal.y; nNum++; vertextBuffer[nNum]=normal.z; nNum++; vertextBuffer[nNum]=(beginX+0)/ TerrainLeaf.CHUNK_GRID_NUM; nNum++; vertextBuffer[nNum]=(beginZ+j)/ TerrainLeaf.CHUNK_GRID_NUM; nNum++; vertextBuffer[nNum]=hXIndex; nNum++; vertextBuffer[nNum]=this._beginGridZ+j; nNum++; } } for (i=0;i < 2;i++){ for (j=0;j < s;j++){ TerrainLeaf.__VECTOR3__.x=(this._beginGridX+TerrainLeaf.LEAF_GRID_NUM)*this._gridSize; TerrainLeaf.__VECTOR3__.y=(i==1 ? terrainHeightData[(this._beginGridZ+j)*(heighDataWidth)+(this._beginGridX+TerrainLeaf.LEAF_GRID_NUM)] :-this._gridSize); TerrainLeaf.__VECTOR3__.z=(this._beginGridZ+j)*this._gridSize; if (TerrainLeaf.__ADAPT_MATRIX__){ Vector3.transformV3ToV3(TerrainLeaf.__VECTOR3__,TerrainLeaf.__ADAPT_MATRIX__,TerrainLeaf.__VECTOR3__); } vertextBuffer[nNum]=TerrainLeaf.__VECTOR3__.x; nNum++; vertextBuffer[nNum]=TerrainLeaf.__VECTOR3__.y; nNum++; vertextBuffer[nNum]=TerrainLeaf.__VECTOR3__.z; nNum++; if (i==0){ hXIndex=this._beginGridX+TerrainLeaf.LEAF_GRID_NUM+1; }else { hXIndex=this._beginGridX+TerrainLeaf.LEAF_GRID_NUM; } this.calcVertextNormlUV(hXIndex,this._beginGridZ+j,heighDataWidth,heightDataHeight,normal); vertextBuffer[nNum]=normal.x; nNum++; vertextBuffer[nNum]=normal.y; nNum++; vertextBuffer[nNum]=normal.z; nNum++; vertextBuffer[nNum]=(beginX+TerrainLeaf.LEAF_GRID_NUM)/ TerrainLeaf.CHUNK_GRID_NUM; nNum++; vertextBuffer[nNum]=(beginZ+j)/ TerrainLeaf.CHUNK_GRID_NUM; nNum++; vertextBuffer[nNum]=hXIndex; nNum++; vertextBuffer[nNum]=this._beginGridZ+j; nNum++; } } } __proto.calcOriginalBoudingBoxAndSphere=function(){ var min=new Vector3(this._beginGridX *this._gridSize,this._sizeOfY.x,this._beginGridZ *this._gridSize); var max=new Vector3((this._beginGridX+TerrainLeaf.LEAF_GRID_NUM)*this._gridSize,this._sizeOfY.y,(this._beginGridZ+TerrainLeaf.LEAF_GRID_NUM)*this._gridSize); if (TerrainLeaf.__ADAPT_MATRIX__){ Vector3.transformV3ToV3(min,TerrainLeaf.__ADAPT_MATRIX__,min); Vector3.transformV3ToV3(max,TerrainLeaf.__ADAPT_MATRIX__,max); } this._originalBoundingBox=new BoundBox(min,max); var size=new Vector3(); Vector3.subtract(max,min,size); Vector3.scale(size,0.5,size); var center=new Vector3(); Vector3.add(min,size,center); this._originalBoundingSphere=new BoundSphere(center,Vector3.scalarLength(size)); this._originalBoundingBoxCorners=__newvec(8,null); this._originalBoundingBox.getCorners(this._originalBoundingBoxCorners); this._boundingBox=new BoundBox(new Vector3(-0.5,-0.5,-0.5),new Vector3(0.5,0.5,0.5)); this._boundingSphere=new BoundSphere(new Vector3(0,0,0),1); } __proto.calcLeafBoudingBox=function(worldMatrix){ for (var i=0;i < 8;i++){ Vector3.transformCoordinate(this._originalBoundingBoxCorners[i],worldMatrix,BaseRender._tempBoundBoxCorners[i]); } BoundBox.createfromPoints(BaseRender._tempBoundBoxCorners,this._boundingBox); } __proto.calcLeafBoudingSphere=function(worldMatrix,maxScale){ Vector3.transformCoordinate(this._originalBoundingSphere.center,worldMatrix,this._boundingSphere.center); this._boundingSphere.radius=this._originalBoundingSphere.radius *maxScale; } __proto.calcLODErrors=function(terrainHeightData,heighDataWidth,heightDataHeight){ this._LODError=new Float32Array(TerrainLeaf._maxLODLevel+1); var step=1; for (var i=0,n=TerrainLeaf._maxLODLevel+1;i < n;i++){ var maxError=0; for (var y=0,n1=TerrainLeaf.LEAF_GRID_NUM;y < n1;y+=step){ for (var x=0,n2=TerrainLeaf.LEAF_GRID_NUM;x < n2;x+=step){ var z00=terrainHeightData[(this._beginGridZ+y)*heighDataWidth+(this._beginGridX+x)]; var z10=terrainHeightData[(this._beginGridZ+y)*heighDataWidth+(this._beginGridX+x)+step]; var z01=terrainHeightData[(this._beginGridZ+y+step)*heighDataWidth+(this._beginGridX+x)]; var z11=terrainHeightData[(this._beginGridZ+y+step)*heighDataWidth+(this._beginGridX+x)+step]; for (var j=0;j < step;j++){ var ys=j / step; for (var k=0;k < step;k++){ var xs=k / step; var z=terrainHeightData[(this._beginGridZ+y+j)*heighDataWidth+(this._beginGridX+x)+k]; var iz=(xs+ys <=1)? (z00+(z10-z00)*xs+(z01-z00)*ys):(z11+(z01-z11)*(1-xs)+(z10-z11)*(1-ys)); var error=Math.abs(iz-z); maxError=Math.max(maxError,error); } } } } step *=2; this._LODError[i]=maxError; } } __proto.determineLod=function(eyePos,perspectiveFactor,tolerance,tolerAndPerspectiveChanged){ var nDistanceToEye=Vector3.distance(eyePos,this._boundingSphere.center); var n=TerrainLeaf._maxLODLevel; if (!tolerAndPerspectiveChanged){ if (this._lastDistanceToEye==nDistanceToEye){ return this._currentLODLevel; }else if (this._lastDistanceToEye > nDistanceToEye){ n=this._currentLODLevel; } } for (var i=n;i >=1;i--){ if (Terrain.LOD_DISTANCE_FACTOR *this._LODError[i] / nDistanceToEye *perspectiveFactor < tolerance){ this._currentLODLevel=i; break ; } } this._lastDistanceToEye=nDistanceToEye; return this._currentLODLevel; } TerrainLeaf.__init__=function(){ if (!TerrainLeaf._bInit){ var nLeafNum=(TerrainLeaf.CHUNK_GRID_NUM / TerrainLeaf.LEAF_GRID_NUM)*(TerrainLeaf.CHUNK_GRID_NUM / TerrainLeaf.LEAF_GRID_NUM); TerrainLeaf._planeLODIndex=__newvec(nLeafNum); var i=0,j=0,k=0,n=0,n1=0,nOffset=0; var nOriginIndexArray=null,nTempIndex=null; for (i=0;i < nLeafNum;i++){ TerrainLeaf._planeLODIndex[i]=new Array(TerrainLeaf._maxLODLevel+1); } for (i=0,n=TerrainLeaf._maxLODLevel+1;i < n;i++){ TerrainLeaf._planeLODIndex[0][i]=TerrainLeaf.calcPlaneLODIndex(i); } for (i=1;i < nLeafNum;i++){ nOffset=i *TerrainLeaf.LEAF_PLANE_VERTEXT_COUNT; for (j=0,n1=TerrainLeaf._maxLODLevel+1;j < n1;j++){ nOriginIndexArray=TerrainLeaf._planeLODIndex[0][j]; nTempIndex=new Uint16Array(nOriginIndexArray.length); for (k=0;k < nOriginIndexArray.length;k++){ nTempIndex[k]=nOriginIndexArray[k]+nOffset; } TerrainLeaf._planeLODIndex[i][j]=nTempIndex; } } TerrainLeaf._skirtLODIndex=__newvec(nLeafNum); for (i=0;i < nLeafNum;i++){ TerrainLeaf._skirtLODIndex[i]=new Array(TerrainLeaf._maxLODLevel+1); } for (i=0,n=TerrainLeaf._maxLODLevel+1;i < n;i++){ TerrainLeaf._skirtLODIndex[0][i]=TerrainLeaf.calcSkirtLODIndex(i); } for (i=1;i < nLeafNum;i++){ nOffset=i *TerrainLeaf.LEAF_SKIRT_VERTEXT_COUNT; for (j=0,n1=TerrainLeaf._maxLODLevel+1;j < n1;j++){ nOriginIndexArray=TerrainLeaf._skirtLODIndex[0][j]; nTempIndex=new Uint16Array(nOriginIndexArray.length); for (k=0;k < nOriginIndexArray.length;k++){ nTempIndex[k]=nOriginIndexArray[k]+nOffset; } TerrainLeaf._skirtLODIndex[i][j]=nTempIndex; } } TerrainLeaf._bInit=true; } } TerrainLeaf.getPlaneLODIndex=function(leafIndex,LODLevel){ return TerrainLeaf._planeLODIndex[leafIndex][LODLevel]; } TerrainLeaf.getSkirtLODIndex=function(leafIndex,LODLevel){ return TerrainLeaf._skirtLODIndex[leafIndex][LODLevel]; } TerrainLeaf.calcPlaneLODIndex=function(level){ if (level > TerrainLeaf._maxLODLevel)level=TerrainLeaf._maxLODLevel; var nGridNumAddOne=TerrainLeaf.LEAF_GRID_NUM+1; var nNum=0; var indexBuffer=null; var nLODGridNum=laya.d3.terrain.TerrainLeaf.LEAF_GRID_NUM / Math.pow(2,level); indexBuffer=new Uint16Array(nLODGridNum *nLODGridNum *6); var nGridSpace=laya.d3.terrain.TerrainLeaf.LEAF_GRID_NUM / nLODGridNum; for (var i=0;i < TerrainLeaf.LEAF_GRID_NUM;i+=nGridSpace){ for (var j=0;j < TerrainLeaf.LEAF_GRID_NUM;j+=nGridSpace){ indexBuffer[nNum]=(i+nGridSpace)*nGridNumAddOne+j; nNum++; indexBuffer[nNum]=i *nGridNumAddOne+j; nNum++; indexBuffer[nNum]=i *nGridNumAddOne+j+nGridSpace; nNum++; indexBuffer[nNum]=i *nGridNumAddOne+j+nGridSpace; nNum++; indexBuffer[nNum]=(i+nGridSpace)*nGridNumAddOne+j+nGridSpace; nNum++; indexBuffer[nNum]=(i+nGridSpace)*nGridNumAddOne+j; nNum++; } } return indexBuffer; } TerrainLeaf.calcSkirtLODIndex=function(level){ if (level > TerrainLeaf._maxLODLevel)level=TerrainLeaf._maxLODLevel; var nSkirtIndexOffset=(TerrainLeaf.CHUNK_GRID_NUM / TerrainLeaf.LEAF_GRID_NUM)*(TerrainLeaf.CHUNK_GRID_NUM / TerrainLeaf.LEAF_GRID_NUM)*TerrainLeaf.LEAF_PLANE_VERTEXT_COUNT; var nGridNumAddOne=TerrainLeaf.LEAF_GRID_NUM+1; var nNum=0; var indexBuffer=null; var nLODGridNum=laya.d3.terrain.TerrainLeaf.LEAF_GRID_NUM / Math.pow(2,level); indexBuffer=new Uint16Array(nLODGridNum *4 *6); var nGridSpace=laya.d3.terrain.TerrainLeaf.LEAF_GRID_NUM / nLODGridNum; for (var j=0;j < 4;j++){ for (var i=0;i < TerrainLeaf.LEAF_GRID_NUM;i+=nGridSpace){ indexBuffer[nNum]=nSkirtIndexOffset+nGridNumAddOne+i; nNum++; indexBuffer[nNum]=nSkirtIndexOffset+i; nNum++; indexBuffer[nNum]=nSkirtIndexOffset+i+nGridSpace; nNum++; indexBuffer[nNum]=nSkirtIndexOffset+i+nGridSpace; nNum++; indexBuffer[nNum]=nSkirtIndexOffset+nGridNumAddOne+i+nGridSpace; nNum++; indexBuffer[nNum]=nSkirtIndexOffset+nGridNumAddOne+i; nNum++; } nSkirtIndexOffset+=nGridNumAddOne *2; } return indexBuffer; } TerrainLeaf.getHeightFromTerrainHeightData=function(x,z,terrainHeightData,heighDataWidth,heightDataHeight){ x=x < 0 ? 0 :x; x=(x >=heighDataWidth)? heighDataWidth-1 :x; z=z < 0 ? 0 :z; z=(z >=heightDataHeight)? heightDataHeight-1 :z; return terrainHeightData[z *heighDataWidth+x]; } TerrainLeaf.CHUNK_GRID_NUM=64; TerrainLeaf.LEAF_GRID_NUM=32; TerrainLeaf.__ADAPT_MATRIX__=null; TerrainLeaf.__ADAPT_MATRIX_INV__=null; TerrainLeaf._planeLODIndex=null; TerrainLeaf._skirtLODIndex=null; TerrainLeaf._bInit=false; __static(TerrainLeaf, ['LEAF_PLANE_VERTEXT_COUNT',function(){return this.LEAF_PLANE_VERTEXT_COUNT=(TerrainLeaf.LEAF_GRID_NUM+1)*(TerrainLeaf.LEAF_GRID_NUM+1);},'LEAF_SKIRT_VERTEXT_COUNT',function(){return this.LEAF_SKIRT_VERTEXT_COUNT=(TerrainLeaf.LEAF_GRID_NUM+1)*2 *4;},'LEAF_VERTEXT_COUNT',function(){return this.LEAF_VERTEXT_COUNT=TerrainLeaf.LEAF_PLANE_VERTEXT_COUNT+TerrainLeaf.LEAF_SKIRT_VERTEXT_COUNT;},'LEAF_PLANE_MAX_INDEX_COUNT',function(){return this.LEAF_PLANE_MAX_INDEX_COUNT=TerrainLeaf.LEAF_GRID_NUM *TerrainLeaf.LEAF_GRID_NUM *6;},'LEAF_SKIRT_MAX_INDEX_COUNT',function(){return this.LEAF_SKIRT_MAX_INDEX_COUNT=TerrainLeaf.LEAF_GRID_NUM *4 *6;},'LEAF_MAX_INDEX_COUNT',function(){return this.LEAF_MAX_INDEX_COUNT=TerrainLeaf.LEAF_PLANE_MAX_INDEX_COUNT+TerrainLeaf.LEAF_SKIRT_MAX_INDEX_COUNT;},'__VECTOR3__',function(){return this.__VECTOR3__=new Vector3();},'_maxLODLevel',function(){return this._maxLODLevel=/*__JS__ */Math.log2(TerrainLeaf.LEAF_GRID_NUM);} ]); return TerrainLeaf; })() /** *DetailTextureInfo 类用于描述地形细节纹理。 */ //class laya.d3.terrain.unit.ChunkInfo var ChunkInfo=(function(){ function ChunkInfo(){ this.alphaMap=null; this.detailID=null; this.normalMap=null; ; } __class(ChunkInfo,'laya.d3.terrain.unit.ChunkInfo'); return ChunkInfo; })() /** *DetailTextureInfo 类用于描述地形细节纹理。 */ //class laya.d3.terrain.unit.DetailTextureInfo var DetailTextureInfo=(function(){ function DetailTextureInfo(){ this.diffuseTexture=null; this.normalTexture=null; this.scale=null; this.offset=null; ; } __class(DetailTextureInfo,'laya.d3.terrain.unit.DetailTextureInfo'); return DetailTextureInfo; })() /** *MaterialInfo 类用于描述地形材质信息。 */ //class laya.d3.terrain.unit.MaterialInfo var MaterialInfo=(function(){ function MaterialInfo(){ this.ambientColor=null; this.diffuseColor=null; this.specularColor=null; ; } __class(MaterialInfo,'laya.d3.terrain.unit.MaterialInfo'); return MaterialInfo; })() /** *Physics 类用于简单物理检测。 */ //class laya.d3.utils.Physics var Physics=(function(){ /** *创建一个 Physics 实例。 */ function Physics(){} __class(Physics,'laya.d3.utils.Physics'); Physics.__init__=function(){ var maxCount=/*laya.d3.core.Layer.maxCount*/31; Physics._layerCollsionMatrix.length=maxCount; for (var i=0;i < maxCount;i++){ var collArray=[]; var count=maxCount-i; collArray.length=count; for (var j=0;j < count;j++) if (j===count-1) collArray[j]=true; else collArray[j]=false; Physics._layerCollsionMatrix[i]=collArray; } } Physics.setLayerCollision=function(layer1,layer2,collison){ Physics._layerCollsionMatrix[layer1.number][(/*laya.d3.core.Layer.maxCount*/31-1)-layer2.number]=collison; } Physics.getLayerCollision=function(layer1,layer2){ return Physics._layerCollsionMatrix[layer1.number][(/*laya.d3.core.Layer.maxCount*/31-1)-layer2.number]; } Physics.setColliderCollision=function(collider1,collider2,collsion){ if (collsion){ delete collider1._ignoreCollisonMap[collider2.id]; delete collider2._ignoreCollisonMap[collider1.id]; }else { collider1._ignoreCollisonMap[collider2.id]=collider2; collider2._ignoreCollisonMap[collider1.id]=collider1; } } Physics.getIColliderCollision=function(collider1,collider2){ return collider1._ignoreCollisonMap[collider2.id] ? true :false; } Physics.rayCast=function(ray,outHitInfo,distance,layer){ (distance===void 0)&& (distance=1.79e+308); (layer===void 0)&& (layer=0); Physics._outHitAllInfo.length=0; var colliders=Layer.getLayerByNumber(layer)._colliders; for (var i=0,n=colliders.length;i < n;i++){ var collider=colliders[i]; if (collider.enable){ collider.raycast(ray,Physics._outHitInfo,distance); if (Physics._outHitInfo.distance!==-1 && Physics._outHitInfo.distance <=distance){ var outHit=new RaycastHit(); Physics._outHitInfo.cloneTo(outHit); Physics._outHitAllInfo.push(outHit); } } } if (Physics._outHitAllInfo.length==0){ outHitInfo.sprite3D=null; outHitInfo.distance=-1; return; }; var minDistance=Number.MAX_VALUE; var minIndex=0; for (var j=0;j < Physics._outHitAllInfo.length;j++){ if (Physics._outHitAllInfo[j].distance < minDistance){ minDistance=Physics._outHitAllInfo[j].distance; minIndex=j; } } Physics._outHitAllInfo[minIndex].cloneTo(outHitInfo); } Physics.rayCastAll=function(ray,outHitAllInfo,distance,layer){ (distance===void 0)&& (distance=1.79e+308); (layer===void 0)&& (layer=0); outHitAllInfo.length=0; var colliders=Layer.getLayerByNumber(layer)._colliders; for (var i=0,n=colliders.length;i < n;i++){ var collider=colliders[i]; if (collider.enable){ Physics._outHitInfo.distance=-1; Physics._outHitInfo.sprite3D=null; collider.raycast(ray,Physics._outHitInfo,distance); if (Physics._outHitInfo.distance!==-1 && Physics._outHitInfo.distance <=distance){ var outHit=new RaycastHit(); Physics._outHitInfo.cloneTo(outHit); outHitAllInfo.push(outHit); } } } } Physics._outHitAllInfo=[]; Physics._layerCollsionMatrix=[]; __static(Physics, ['_outHitInfo',function(){return this._outHitInfo=new RaycastHit();},'collisionManager',function(){return this.collisionManager=new CollisionManager();},'gravity',function(){return this.gravity=new Vector3(0,-9.81,0);} ]); return Physics; })() /** *Picker 类用于创建拾取。 */ //class laya.d3.utils.Picker var Picker=(function(){ /** *创建一个 Picker 实例。 */ function Picker(){} __class(Picker,'laya.d3.utils.Picker'); Picker.calculateCursorRay=function(point,viewPort,projectionMatrix,viewMatrix,world,out){ var x=point.elements[0]; var y=point.elements[1]; var nearSource=Picker._tempVector30; var nerSourceE=nearSource.elements; nerSourceE[0]=x; nerSourceE[1]=y; nerSourceE[2]=viewPort.minDepth; var farSource=Picker._tempVector31; var farSourceE=farSource.elements; farSourceE[0]=x; farSourceE[1]=y; farSourceE[2]=viewPort.maxDepth; var nearPoint=out.origin; var farPoint=Picker._tempVector32; viewPort.unprojectFromWVP(nearSource,projectionMatrix,viewMatrix,world,nearPoint); viewPort.unprojectFromWVP(farSource,projectionMatrix,viewMatrix,world,farPoint); var outDire=out.direction.elements; outDire[0]=farPoint.x-nearPoint.x; outDire[1]=farPoint.y-nearPoint.y; outDire[2]=farPoint.z-nearPoint.z; Vector3.normalize(out.direction,out.direction); } Picker.rayIntersectsPositionsAndIndices=function(ray,vertexDatas,vertexDeclaration,indices,outHitInfo){ var vertexStrideFloatCount=vertexDeclaration.vertexStride / 4; var positionVertexElementOffset=vertexDeclaration.getVertexElementByUsage(/*laya.d3.graphics.VertexElementUsage.POSITION0*/0).offset / 4; var closestIntersection=Number.MAX_VALUE; var closestTriangleVertexIndex1=-1; var closestTriangleVertexIndex2=-1; var closestTriangleVertexIndex3=-1; for (var j=0;j < indices.length;j+=3){ var vertex1=Picker._tempVector35; var vertex1E=vertex1.elements; var vertex1Index=indices[j] *vertexStrideFloatCount; var vertex1PositionIndex=vertex1Index+positionVertexElementOffset; vertex1E[0]=vertexDatas[vertex1PositionIndex]; vertex1E[1]=vertexDatas[vertex1PositionIndex+1]; vertex1E[2]=vertexDatas[vertex1PositionIndex+2]; var vertex2=Picker._tempVector36; var vertex2E=vertex2.elements; var vertex2Index=indices[j+1] *vertexStrideFloatCount; var vertex2PositionIndex=vertex2Index+positionVertexElementOffset; vertex2E[0]=vertexDatas[vertex2PositionIndex]; vertex2E[1]=vertexDatas[vertex2PositionIndex+1]; vertex2E[2]=vertexDatas[vertex2PositionIndex+2]; var vertex3=Picker._tempVector37; var vertex3E=vertex3.elements; var vertex3Index=indices[j+2] *vertexStrideFloatCount; var vertex3PositionIndex=vertex3Index+positionVertexElementOffset; vertex3E[0]=vertexDatas[vertex3PositionIndex]; vertex3E[1]=vertexDatas[vertex3PositionIndex+1]; vertex3E[2]=vertexDatas[vertex3PositionIndex+2]; var intersection=laya.d3.utils.Picker.rayIntersectsTriangle(ray,vertex1,vertex2,vertex3); if (!isNaN(intersection)&& intersection < closestIntersection){ closestIntersection=intersection; closestTriangleVertexIndex1=vertex1Index; closestTriangleVertexIndex2=vertex2Index; closestTriangleVertexIndex3=vertex3Index; } } if (closestIntersection!==Number.MAX_VALUE){ outHitInfo.distance=closestIntersection; Vector3.scale(ray.direction,closestIntersection,outHitInfo.position); Vector3.add(ray.origin,outHitInfo.position,outHitInfo.position); var trianglePositions=outHitInfo.trianglePositions; var position0=trianglePositions[0]; var position1=trianglePositions[1]; var position2=trianglePositions[2]; var position0E=position0.elements; var position1E=position1.elements; var position2E=position2.elements; var closestVertex1PositionIndex=closestTriangleVertexIndex1+positionVertexElementOffset; position0E[0]=vertexDatas[closestVertex1PositionIndex]; position0E[1]=vertexDatas[closestVertex1PositionIndex+1]; position0E[2]=vertexDatas[closestVertex1PositionIndex+2]; var closestVertex2PositionIndex=closestTriangleVertexIndex2+positionVertexElementOffset; position1E[0]=vertexDatas[closestVertex2PositionIndex]; position1E[1]=vertexDatas[closestVertex2PositionIndex+1]; position1E[2]=vertexDatas[closestVertex2PositionIndex+2]; var closestVertex3PositionIndex=closestTriangleVertexIndex3+positionVertexElementOffset; position2E[0]=vertexDatas[closestVertex3PositionIndex]; position2E[1]=vertexDatas[closestVertex3PositionIndex+1]; position2E[2]=vertexDatas[closestVertex3PositionIndex+2]; var normalVertexElement=vertexDeclaration.getVertexElementByUsage(/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3); if (normalVertexElement){ var normalVertexElementOffset=normalVertexElement.offset / 4; var triangleNormals=outHitInfo.triangleNormals; var normal0=triangleNormals[0]; var normal1=triangleNormals[1]; var normal2=triangleNormals[2]; var normal0E=normal0.elements; var normal1E=normal1.elements; var normal2E=normal2.elements; var closestVertex1NormalIndex=closestTriangleVertexIndex1+normalVertexElementOffset; normal0E[0]=vertexDatas[closestVertex1NormalIndex]; normal0E[1]=vertexDatas[closestVertex1NormalIndex+1]; normal0E[2]=vertexDatas[closestVertex1NormalIndex+2]; var closestVertex2NormalIndex=closestTriangleVertexIndex2+normalVertexElementOffset; normal1E[0]=vertexDatas[closestVertex2NormalIndex]; normal1E[1]=vertexDatas[closestVertex2NormalIndex+1]; normal1E[2]=vertexDatas[closestVertex2NormalIndex+2]; var closestVertex3NormalIndex=closestTriangleVertexIndex3+normalVertexElementOffset; normal2E[0]=vertexDatas[closestVertex3NormalIndex]; normal2E[1]=vertexDatas[closestVertex3NormalIndex+1]; normal2E[2]=vertexDatas[closestVertex3NormalIndex+2]; } return true; }else { outHitInfo.position.toDefault(); outHitInfo.distance=Number.MAX_VALUE; outHitInfo.trianglePositions[0].toDefault(); outHitInfo.trianglePositions[1].toDefault(); outHitInfo.trianglePositions[2].toDefault(); outHitInfo.triangleNormals[0].toDefault(); outHitInfo.triangleNormals[1].toDefault(); outHitInfo.triangleNormals[2].toDefault(); return false; } } Picker.rayIntersectsTriangle=function(ray,vertex1,vertex2,vertex3){ var result; var edge1=Picker._tempVector30,edge2=Picker._tempVector31; Vector3.subtract(vertex2,vertex1,edge1); Vector3.subtract(vertex3,vertex1,edge2); var directionCrossEdge2=Picker._tempVector32; Vector3.cross(ray.direction,edge2,directionCrossEdge2); var determinant; determinant=Vector3.dot(edge1,directionCrossEdge2); if (determinant >-Number.MIN_VALUE && determinant < Number.MIN_VALUE){ result=Number.NaN; return result; }; var inverseDeterminant=1.0 / determinant; var distanceVector=Picker._tempVector33; Vector3.subtract(ray.origin,vertex1,distanceVector); var triangleU; triangleU=Vector3.dot(distanceVector,directionCrossEdge2); triangleU *=inverseDeterminant; if (triangleU < 0 || triangleU > 1){ result=Number.NaN; return result; }; var distanceCrossEdge1=Picker._tempVector34; Vector3.cross(distanceVector,edge1,distanceCrossEdge1); var triangleV; triangleV=Vector3.dot(ray.direction,distanceCrossEdge1); triangleV *=inverseDeterminant; if (triangleV < 0 || triangleU+triangleV > 1){ result=Number.NaN; return result; }; var rayDistance; rayDistance=Vector3.dot(edge2,distanceCrossEdge1); rayDistance *=inverseDeterminant; if (rayDistance < 0){ result=Number.NaN; return result; } result=rayDistance; return result; } __static(Picker, ['_tempVector30',function(){return this._tempVector30=new Vector3();},'_tempVector31',function(){return this._tempVector31=new Vector3();},'_tempVector32',function(){return this._tempVector32=new Vector3();},'_tempVector33',function(){return this._tempVector33=new Vector3();},'_tempVector34',function(){return this._tempVector34=new Vector3();},'_tempVector35',function(){return this._tempVector35=new Vector3();},'_tempVector36',function(){return this._tempVector36=new Vector3();},'_tempVector37',function(){return this._tempVector37=new Vector3();} ]); return Picker; })() /** *... *@author ... */ //class laya.d3.utils.RaycastHit var RaycastHit=(function(){ function RaycastHit(){ this.distance=NaN; this.trianglePositions=null; this.triangleNormals=null; this.position=null; this.sprite3D=null; this.distance=-1; this.trianglePositions=[new Vector3(),new Vector3(),new Vector3()]; this.trianglePositions.length=3; this.triangleNormals=[new Vector3(),new Vector3(),new Vector3()]; this.triangleNormals.length=3; this.position=new Vector3(); } __class(RaycastHit,'laya.d3.utils.RaycastHit'); var __proto=RaycastHit.prototype; __proto.cloneTo=function(dec){ dec.distance=this.distance; this.trianglePositions[0].cloneTo(dec.trianglePositions[0]); this.trianglePositions[1].cloneTo(dec.trianglePositions[1]); this.trianglePositions[2].cloneTo(dec.trianglePositions[2]); this.triangleNormals[0].cloneTo(dec.triangleNormals[0]); this.triangleNormals[1].cloneTo(dec.triangleNormals[1]); this.triangleNormals[2].cloneTo(dec.triangleNormals[2]); this.position.cloneTo(dec.position); dec.sprite3D=this.sprite3D; } return RaycastHit; })() //class laya.d3.utils.Size var Size=(function(){ function Size(width,height){ this._width=0; this._height=0; this._width=width; this._height=height; } __class(Size,'laya.d3.utils.Size'); var __proto=Size.prototype; __getset(0,__proto,'width',function(){ if (this._width===-1) return RenderState.clientWidth; return this._width; }); __getset(0,__proto,'height',function(){ if (this._height===-1) return RenderState.clientHeight; return this._height; }); __getset(1,Size,'fullScreen',function(){ return new Size(-1,-1); }); return Size; })() /** *Utils3D 类用于创建3D工具。 */ //class laya.d3.utils.Utils3D var Utils3D=(function(){ function Utils3D(){} __class(Utils3D,'laya.d3.utils.Utils3D'); Utils3D._rotationTransformScaleSkinAnimation=function(tx,ty,tz,qx,qy,qz,qw,sx,sy,sz,outArray,outOffset){ var re=Utils3D._tempArray16_0; var se=Utils3D._tempArray16_1; var tse=Utils3D._tempArray16_2; var x2=qx+qx; var y2=qy+qy; var z2=qz+qz; var xx=qx *x2; var yx=qy *x2; var yy=qy *y2; var zx=qz *x2; var zy=qz *y2; var zz=qz *z2; var wx=qw *x2; var wy=qw *y2; var wz=qw *z2; re[15]=1; re[0]=1-yy-zz; re[1]=yx+wz; re[2]=zx-wy; re[4]=yx-wz; re[5]=1-xx-zz; re[6]=zy+wx; re[8]=zx+wy; re[9]=zy-wx; re[10]=1-xx-yy; se[15]=1; se[0]=sx; se[5]=sy; se[10]=sz; var i,a,b,e,ai0,ai1,ai2,ai3; for (i=0;i < 4;i++){ ai0=re[i]; ai1=re[i+4]; ai2=re[i+8]; ai3=re[i+12]; tse[i]=ai0; tse[i+4]=ai1; tse[i+8]=ai2; tse[i+12]=ai0 *tx+ai1 *ty+ai2 *tz+ai3; } for (i=0;i < 4;i++){ ai0=tse[i]; ai1=tse[i+4]; ai2=tse[i+8]; ai3=tse[i+12]; outArray[i+outOffset]=ai0 *se[0]+ai1 *se[1]+ai2 *se[2]+ai3 *se[3]; outArray[i+outOffset+4]=ai0 *se[4]+ai1 *se[5]+ai2 *se[6]+ai3 *se[7]; outArray[i+outOffset+8]=ai0 *se[8]+ai1 *se[9]+ai2 *se[10]+ai3 *se[11]; outArray[i+outOffset+12]=ai0 *se[12]+ai1 *se[13]+ai2 *se[14]+ai3 *se[15]; } } Utils3D._createNodeByJson=function(rootNode,nodeData,node,innerResouMap){ if (!node){ switch (nodeData.type){ case "Sprite3D": node=new Sprite3D(); break ; case "MeshSprite3D": node=new MeshSprite3D(); break ; case "SkinnedMeshSprite3D": node=new SkinnedMeshSprite3D(); break ; case "ShuriKenParticle3D": node=new ShuriKenParticle3D(); break ; case "TrailSprite3D": node=new TrailSprite3D(); break ; break ; case "Terrain": node=new Terrain(); break ; case "Camera": node=new Camera(); break ; case "DirectionLight": node=new DirectionLight(); break ; default : throw new Error("Utils3D:unidentified class type in (.lh) file."); } }; var props=nodeData.props; if (props) for (var key in props) node[key]=props[key]; var customProps=nodeData.customProps; if (customProps){ if ((node instanceof laya.d3.core.Sprite3D )){ node._parseBaseCustomProps(customProps); node._parseCustomProps(rootNode,innerResouMap,customProps,nodeData); node._parseCustomComponent(rootNode,innerResouMap,nodeData.components); }else { node._parseCustomProps(rootNode,innerResouMap,customProps,nodeData); } }; var childData=nodeData.child; if (childData){ for (var i=0,n=childData.length;i < n;i++){ var child=Utils3D._createNodeByJson(rootNode,childData[i],null,innerResouMap) node.addChild(child); } } return node; } Utils3D._computeBoneAndAnimationDatasByBindPoseMatrxix=function(bones,curData,inverGlobalBindPose,outBonesDatas,outAnimationDatas,boneIndexToMesh){ var offset=0; var matOffset=0; var i; var parentOffset; var boneLength=bones.length; for (i=0;i < boneLength;offset+=bones[i].keyframeWidth,matOffset+=16,i++){ laya.d3.utils.Utils3D._rotationTransformScaleSkinAnimation(curData[offset+0],curData[offset+1],curData[offset+2],curData[offset+3],curData[offset+4],curData[offset+5],curData[offset+6],curData[offset+7],curData[offset+8],curData[offset+9],outBonesDatas,matOffset); if (i !=0){ parentOffset=bones[i].parentIndex *16; laya.d3.utils.Utils3D.mulMatrixByArray(outBonesDatas,parentOffset,outBonesDatas,matOffset,outBonesDatas,matOffset); } }; var n=inverGlobalBindPose.length; for (i=0;i < n;i++){ laya.d3.utils.Utils3D.mulMatrixByArrayAndMatrixFast(outBonesDatas,boneIndexToMesh[i] *16,inverGlobalBindPose[i],outAnimationDatas,i *16); } } Utils3D._computeAnimationDatasByArrayAndMatrixFast=function(inverGlobalBindPose,bonesDatas,outAnimationDatas,boneIndexToMesh){ for (var i=0,n=inverGlobalBindPose.length;i < n;i++) laya.d3.utils.Utils3D.mulMatrixByArrayAndMatrixFast(bonesDatas,boneIndexToMesh[i] *16,inverGlobalBindPose[i],outAnimationDatas,i *16); } Utils3D._computeBoneAndAnimationDatasByBindPoseMatrxixOld=function(bones,curData,inverGlobalBindPose,outBonesDatas,outAnimationDatas){ var offset=0; var matOffset=0; var i; var parentOffset; var boneLength=bones.length; for (i=0;i < boneLength;offset+=bones[i].keyframeWidth,matOffset+=16,i++){ laya.d3.utils.Utils3D._rotationTransformScaleSkinAnimation(curData[offset+7],curData[offset+8],curData[offset+9],curData[offset+3],curData[offset+4],curData[offset+5],curData[offset+6],curData[offset+0],curData[offset+1],curData[offset+2],outBonesDatas,matOffset); if (i !=0){ parentOffset=bones[i].parentIndex *16; laya.d3.utils.Utils3D.mulMatrixByArray(outBonesDatas,parentOffset,outBonesDatas,matOffset,outBonesDatas,matOffset); } }; var n=inverGlobalBindPose.length; for (i=0;i < n;i++){ var arrayOffset=i *16; laya.d3.utils.Utils3D.mulMatrixByArrayAndMatrixFast(outBonesDatas,arrayOffset,inverGlobalBindPose[i],outAnimationDatas,arrayOffset); } } Utils3D._computeAnimationDatasByArrayAndMatrixFastOld=function(inverGlobalBindPose,bonesDatas,outAnimationDatas){ var n=inverGlobalBindPose.length; for (var i=0;i < n;i++){ var arrayOffset=i *16; laya.d3.utils.Utils3D.mulMatrixByArrayAndMatrixFast(bonesDatas,arrayOffset,inverGlobalBindPose[i],outAnimationDatas,arrayOffset); } } Utils3D._computeRootAnimationData=function(bones,curData,animationDatas){ for (var i=0,offset=0,matOffset=0,boneLength=bones.length;i < boneLength;offset+=bones[i].keyframeWidth,matOffset+=16,i++) laya.d3.utils.Utils3D.createAffineTransformationArray(curData[offset+0],curData[offset+1],curData[offset+2],curData[offset+3],curData[offset+4],curData[offset+5],curData[offset+6],curData[offset+7],curData[offset+8],curData[offset+9],animationDatas,matOffset); } Utils3D.transformVector3ArrayByQuat=function(sourceArray,sourceOffset,rotation,outArray,outOffset){ var re=rotation.elements; var x=sourceArray[sourceOffset],y=sourceArray[sourceOffset+1],z=sourceArray[sourceOffset+2],qx=re[0],qy=re[1],qz=re[2],qw=re[3],ix=qw *x+qy *z-qz *y,iy=qw *y+qz *x-qx *z,iz=qw *z+qx *y-qy *x,iw=-qx *x-qy *y-qz *z; outArray[outOffset]=ix *qw+iw *-qx+iy *-qz-iz *-qy; outArray[outOffset+1]=iy *qw+iw *-qy+iz *-qx-ix *-qz; outArray[outOffset+2]=iz *qw+iw *-qz+ix *-qy-iy *-qx; } Utils3D.mulMatrixByArray=function(leftArray,leftOffset,rightArray,rightOffset,outArray,outOffset){ var i,ai0,ai1,ai2,ai3; if (outArray===rightArray){ rightArray=Utils3D._tempArray16_3; for (i=0;i < 16;++i){ rightArray[i]=outArray[outOffset+i]; } rightOffset=0; } for (i=0;i < 4;i++){ ai0=leftArray[leftOffset+i]; ai1=leftArray[leftOffset+i+4]; ai2=leftArray[leftOffset+i+8]; ai3=leftArray[leftOffset+i+12]; outArray[outOffset+i]=ai0 *rightArray[rightOffset+0]+ai1 *rightArray[rightOffset+1]+ai2 *rightArray[rightOffset+2]+ai3 *rightArray[rightOffset+3]; outArray[outOffset+i+4]=ai0 *rightArray[rightOffset+4]+ai1 *rightArray[rightOffset+5]+ai2 *rightArray[rightOffset+6]+ai3 *rightArray[rightOffset+7]; outArray[outOffset+i+8]=ai0 *rightArray[rightOffset+8]+ai1 *rightArray[rightOffset+9]+ai2 *rightArray[rightOffset+10]+ai3 *rightArray[rightOffset+11]; outArray[outOffset+i+12]=ai0 *rightArray[rightOffset+12]+ai1 *rightArray[rightOffset+13]+ai2 *rightArray[rightOffset+14]+ai3 *rightArray[rightOffset+15]; } } Utils3D.mulMatrixByArrayFast=function(leftArray,leftOffset,rightArray,rightOffset,outArray,outOffset){ var i,ai0,ai1,ai2,ai3; for (i=0;i < 4;i++){ ai0=leftArray[leftOffset+i]; ai1=leftArray[leftOffset+i+4]; ai2=leftArray[leftOffset+i+8]; ai3=leftArray[leftOffset+i+12]; outArray[outOffset+i]=ai0 *rightArray[rightOffset+0]+ai1 *rightArray[rightOffset+1]+ai2 *rightArray[rightOffset+2]+ai3 *rightArray[rightOffset+3]; outArray[outOffset+i+4]=ai0 *rightArray[rightOffset+4]+ai1 *rightArray[rightOffset+5]+ai2 *rightArray[rightOffset+6]+ai3 *rightArray[rightOffset+7]; outArray[outOffset+i+8]=ai0 *rightArray[rightOffset+8]+ai1 *rightArray[rightOffset+9]+ai2 *rightArray[rightOffset+10]+ai3 *rightArray[rightOffset+11]; outArray[outOffset+i+12]=ai0 *rightArray[rightOffset+12]+ai1 *rightArray[rightOffset+13]+ai2 *rightArray[rightOffset+14]+ai3 *rightArray[rightOffset+15]; } } Utils3D.mulMatrixByArrayAndMatrixFast=function(leftArray,leftOffset,rightMatrix,outArray,outOffset){ var i,ai0,ai1,ai2,ai3; var rightMatrixE=rightMatrix.elements; var m11=rightMatrixE[0],m12=rightMatrixE[1],m13=rightMatrixE[2],m14=rightMatrixE[3]; var m21=rightMatrixE[4],m22=rightMatrixE[5],m23=rightMatrixE[6],m24=rightMatrixE[7]; var m31=rightMatrixE[8],m32=rightMatrixE[9],m33=rightMatrixE[10],m34=rightMatrixE[11]; var m41=rightMatrixE[12],m42=rightMatrixE[13],m43=rightMatrixE[14],m44=rightMatrixE[15]; var ai0LeftOffset=leftOffset; var ai1LeftOffset=leftOffset+4; var ai2LeftOffset=leftOffset+8; var ai3LeftOffset=leftOffset+12; var ai0OutOffset=outOffset; var ai1OutOffset=outOffset+4; var ai2OutOffset=outOffset+8; var ai3OutOffset=outOffset+12; for (i=0;i < 4;i++){ ai0=leftArray[ai0LeftOffset+i]; ai1=leftArray[ai1LeftOffset+i]; ai2=leftArray[ai2LeftOffset+i]; ai3=leftArray[ai3LeftOffset+i]; outArray[ai0OutOffset+i]=ai0 *m11+ai1 *m12+ai2 *m13+ai3 *m14; outArray[ai1OutOffset+i]=ai0 *m21+ai1 *m22+ai2 *m23+ai3 *m24; outArray[ai2OutOffset+i]=ai0 *m31+ai1 *m32+ai2 *m33+ai3 *m34; outArray[ai3OutOffset+i]=ai0 *m41+ai1 *m42+ai2 *m43+ai3 *m44; } } Utils3D.createAffineTransformationArray=function(tX,tY,tZ,rX,rY,rZ,rW,sX,sY,sZ,outArray,outOffset){ var x2=rX+rX,y2=rY+rY,z2=rZ+rZ; var xx=rX *x2,xy=rX *y2,xz=rX *z2,yy=rY *y2,yz=rY *z2,zz=rZ *z2; var wx=rW *x2,wy=rW *y2,wz=rW *z2; outArray[outOffset+0]=(1-(yy+zz))*sX; outArray[outOffset+1]=(xy+wz)*sX; outArray[outOffset+2]=(xz-wy)*sX; outArray[outOffset+3]=0; outArray[outOffset+4]=(xy-wz)*sY; outArray[outOffset+5]=(1-(xx+zz))*sY; outArray[outOffset+6]=(yz+wx)*sY; outArray[outOffset+7]=0; outArray[outOffset+8]=(xz+wy)*sZ; outArray[outOffset+9]=(yz-wx)*sZ; outArray[outOffset+10]=(1-(xx+yy))*sZ; outArray[outOffset+11]=0; outArray[outOffset+12]=tX; outArray[outOffset+13]=tY; outArray[outOffset+14]=tZ; outArray[outOffset+15]=1; } Utils3D.transformVector3ArrayToVector3ArrayCoordinate=function(source,sourceOffset,transform,result,resultOffset){ var vectorElem=Utils3D._tempArray4_0; var coordinateX=source[sourceOffset+0]; var coordinateY=source[sourceOffset+1]; var coordinateZ=source[sourceOffset+2]; var transformElem=transform.elements; vectorElem[0]=(coordinateX *transformElem[0])+(coordinateY *transformElem[4])+(coordinateZ *transformElem[8])+transformElem[12]; vectorElem[1]=(coordinateX *transformElem[1])+(coordinateY *transformElem[5])+(coordinateZ *transformElem[9])+transformElem[13]; vectorElem[2]=(coordinateX *transformElem[2])+(coordinateY *transformElem[6])+(coordinateZ *transformElem[10])+transformElem[14]; vectorElem[3]=1.0 / ((coordinateX *transformElem[3])+(coordinateY *transformElem[7])+(coordinateZ *transformElem[11])+transformElem[15]); result[resultOffset+0]=vectorElem[0] *vectorElem[3]; result[resultOffset+1]=vectorElem[1] *vectorElem[3]; result[resultOffset+2]=vectorElem[2] *vectorElem[3]; } Utils3D.transformLightingMapTexcoordByUV0Array=function(source,sourceOffset,lightingMapScaleOffset,result,resultOffset){ var lightingMapScaleOffsetE=lightingMapScaleOffset.elements; result[resultOffset+0]=source[sourceOffset+0] *lightingMapScaleOffsetE[0]+lightingMapScaleOffsetE[2]; result[resultOffset+1]=(source[sourceOffset+1]-1.0)*lightingMapScaleOffsetE[1]+lightingMapScaleOffsetE[3]; } Utils3D.transformLightingMapTexcoordByUV1Array=function(source,sourceOffset,lightingMapScaleOffset,result,resultOffset){ var lightingMapScaleOffsetE=lightingMapScaleOffset.elements; result[resultOffset+0]=source[sourceOffset+0] *lightingMapScaleOffsetE[0]+lightingMapScaleOffsetE[2]; result[resultOffset+1]=1.0+source[sourceOffset+1] *lightingMapScaleOffsetE[1]+lightingMapScaleOffsetE[3]; } Utils3D.getURLVerion=function(url){ var index=url.indexOf("?"); return index >=0 ? url.substr(index):null; } Utils3D._quaternionCreateFromYawPitchRollArray=function(yaw,pitch,roll,out){ var halfRoll=roll *0.5; var halfPitch=pitch *0.5; var halfYaw=yaw *0.5; var sinRoll=Math.sin(halfRoll); var cosRoll=Math.cos(halfRoll); var sinPitch=Math.sin(halfPitch); var cosPitch=Math.cos(halfPitch); var sinYaw=Math.sin(halfYaw); var cosYaw=Math.cos(halfYaw); out[0]=(cosYaw *sinPitch *cosRoll)+(sinYaw *cosPitch *sinRoll); out[1]=(sinYaw *cosPitch *cosRoll)-(cosYaw *sinPitch *sinRoll); out[2]=(cosYaw *cosPitch *sinRoll)-(sinYaw *sinPitch *cosRoll); out[3]=(cosYaw *cosPitch *cosRoll)+(sinYaw *sinPitch *sinRoll); } Utils3D._createAffineTransformationArray=function(trans,rot,scale,outE){ var x=rot[0],y=rot[1],z=rot[2],w=rot[3],x2=x+x,y2=y+y,z2=z+z; var xx=x *x2,xy=x *y2,xz=x *z2,yy=y *y2,yz=y *z2,zz=z *z2; var wx=w *x2,wy=w *y2,wz=w *z2,sx=scale[0],sy=scale[1],sz=scale[2]; outE[0]=(1-(yy+zz))*sx; outE[1]=(xy+wz)*sx; outE[2]=(xz-wy)*sx; outE[3]=0; outE[4]=(xy-wz)*sy; outE[5]=(1-(xx+zz))*sy; outE[6]=(yz+wx)*sy; outE[7]=0; outE[8]=(xz+wy)*sz; outE[9]=(yz-wx)*sz; outE[10]=(1-(xx+yy))*sz; outE[11]=0; outE[12]=trans[0]; outE[13]=trans[1]; outE[14]=trans[2]; outE[15]=1; } Utils3D._mulMatrixArray=function(leftMatrixE,rightMatrix,outArray,outOffset){ var i,ai0,ai1,ai2,ai3; var rightMatrixE=rightMatrix.elements; var m11=rightMatrixE[0],m12=rightMatrixE[1],m13=rightMatrixE[2],m14=rightMatrixE[3]; var m21=rightMatrixE[4],m22=rightMatrixE[5],m23=rightMatrixE[6],m24=rightMatrixE[7]; var m31=rightMatrixE[8],m32=rightMatrixE[9],m33=rightMatrixE[10],m34=rightMatrixE[11]; var m41=rightMatrixE[12],m42=rightMatrixE[13],m43=rightMatrixE[14],m44=rightMatrixE[15]; var ai0OutOffset=outOffset; var ai1OutOffset=outOffset+4; var ai2OutOffset=outOffset+8; var ai3OutOffset=outOffset+12; for (i=0;i < 4;i++){ ai0=leftMatrixE[i]; ai1=leftMatrixE[i+4]; ai2=leftMatrixE[i+8]; ai3=leftMatrixE[i+12]; outArray[ai0OutOffset+i]=ai0 *m11+ai1 *m12+ai2 *m13+ai3 *m14; outArray[ai1OutOffset+i]=ai0 *m21+ai1 *m22+ai2 *m23+ai3 *m24; outArray[ai2OutOffset+i]=ai0 *m31+ai1 *m32+ai2 *m33+ai3 *m34; outArray[ai3OutOffset+i]=ai0 *m41+ai1 *m42+ai2 *m43+ai3 *m44; } } Utils3D.getYawPitchRoll=function(quaternion,out){ Utils3D.transformQuat(Vector3.ForwardRH,quaternion,Quaternion.TEMPVector31); Utils3D.transformQuat(Vector3.Up,quaternion,Quaternion.TEMPVector32); var upe=Quaternion.TEMPVector32.elements; Utils3D.angleTo(Vector3.ZERO,Quaternion.TEMPVector31,Quaternion.TEMPVector33); var anglee=Quaternion.TEMPVector33.elements; if (anglee[0]==Math.PI / 2){ anglee[1]=Utils3D.arcTanAngle(upe[2],upe[0]); anglee[2]=0; }else if (anglee[0]==-Math.PI / 2){ anglee[1]=Utils3D.arcTanAngle(-upe[2],-upe[0]); anglee[2]=0; }else { Matrix4x4.createRotationY(-anglee[1],Quaternion.TEMPMatrix0); Matrix4x4.createRotationX(-anglee[0],Quaternion.TEMPMatrix1); Vector3.transformCoordinate(Quaternion.TEMPVector32,Quaternion.TEMPMatrix0,Quaternion.TEMPVector32); Vector3.transformCoordinate(Quaternion.TEMPVector32,Quaternion.TEMPMatrix1,Quaternion.TEMPVector32); anglee[2]=Utils3D.arcTanAngle(upe[1],-upe[0]); } if (anglee[1] <=-Math.PI) anglee[1]=Math.PI; if (anglee[2] <=-Math.PI) anglee[2]=Math.PI; if (anglee[1] >=Math.PI && anglee[2] >=Math.PI){ anglee[1]=0; anglee[2]=0; anglee[0]=Math.PI-anglee[0]; } out[0]=anglee[1]; out[1]=anglee[0]; out[2]=anglee[2]; } Utils3D.arcTanAngle=function(x,y){ if (x==0){ if (y==1) return Math.PI / 2; return-Math.PI / 2; } if (x > 0) return Math.atan(y / x); if (x < 0){ if (y > 0) return Math.atan(y / x)+Math.PI; return Math.atan(y / x)-Math.PI; } return 0; } Utils3D.angleTo=function(from,location,angle){ Vector3.subtract(location,from,Quaternion.TEMPVector30); Vector3.normalize(Quaternion.TEMPVector30,Quaternion.TEMPVector30); angle.elements[0]=Math.asin(Quaternion.TEMPVector30.y); angle.elements[1]=Utils3D.arcTanAngle(-Quaternion.TEMPVector30.z,-Quaternion.TEMPVector30.x); } Utils3D.transformQuat=function(source,rotation,out){ var destination=out.elements; var se=source.elements; var re=rotation; var x=se[0],y=se[1],z=se[2],qx=re[0],qy=re[1],qz=re[2],qw=re[3], ix=qw *x+qy *z-qz *y,iy=qw *y+qz *x-qx *z,iz=qw *z+qx *y-qy *x,iw=-qx *x-qy *y-qz *z; destination[0]=ix *qw+iw *-qx+iy *-qz-iz *-qy; destination[1]=iy *qw+iw *-qy+iz *-qx-ix *-qz; destination[2]=iz *qw+iw *-qz+ix *-qy-iy *-qx; } Utils3D.quaterionNormalize=function(f,e){ var x=f[0],y=f[1],z=f[2],w=f[3]; var len=x *x+y *y+z *z+w *w; if (len > 0){ len=1 / Math.sqrt(len); e[0]=x *len; e[1]=y *len; e[2]=z *len; e[3]=w *len; } } Utils3D.matrix4x4MultiplyFFF=function(a,b,e){ var i,ai0,ai1,ai2,ai3; if (e===b){ b=new Float32Array(16); for (i=0;i < 16;++i){ b[i]=e[i]; } } for (i=0;i < 4;i++){ ai0=a[i]; ai1=a[i+4]; ai2=a[i+8]; ai3=a[i+12]; e[i]=ai0 *b[0]+ai1 *b[1]+ai2 *b[2]+ai3 *b[3]; e[i+4]=ai0 *b[4]+ai1 *b[5]+ai2 *b[6]+ai3 *b[7]; e[i+8]=ai0 *b[8]+ai1 *b[9]+ai2 *b[10]+ai3 *b[11]; e[i+12]=ai0 *b[12]+ai1 *b[13]+ai2 *b[14]+ai3 *b[15]; } } Utils3D.matrix4x4MultiplyMFM=function(left,right,out){ Utils3D.matrix4x4MultiplyFFF(left.elements,right,out.elements); } __static(Utils3D, ['_typeToFunO',function(){return this._typeToFunO={"INT16":"writeInt16","SHORT":"writeInt16","UINT16":"writeUint16","UINT32":"writeUint32","FLOAT32":"writeFloat32","INT":"writeInt32","UINT":"writeUint32","BYTE":"writeByte","STRING":"writeUTFString"};},'_tempVector3_0',function(){return this._tempVector3_0=new Vector3();},'_tempVector3_1',function(){return this._tempVector3_1=new Vector3();},'_tempVector3_2',function(){return this._tempVector3_2=new Vector3();},'_tempVector3_3',function(){return this._tempVector3_3=new Vector3();},'_tempVector3_4',function(){return this._tempVector3_4=new Vector3();},'_tempVector3_5',function(){return this._tempVector3_5=new Vector3();},'_tempVector3_6',function(){return this._tempVector3_6=new Vector3();},'_tempArray4_0',function(){return this._tempArray4_0=new Float32Array(4);},'_tempArray16_0',function(){return this._tempArray16_0=new Float32Array(16);},'_tempArray16_1',function(){return this._tempArray16_1=new Float32Array(16);},'_tempArray16_2',function(){return this._tempArray16_2=new Float32Array(16);},'_tempArray16_3',function(){return this._tempArray16_3=new Float32Array(16);} ]); return Utils3D; })() /** *Laya3D 类用于初始化3D设置。 */ //class Laya3D var Laya3D=(function(){ /** *创建一个 Laya3D 实例。 */ function Laya3D(){} __class(Laya3D,'Laya3D'); Laya3D._cancelLoadByUrl=function(url){ Laya.loader.cancelLoadByUrl(url); Laya3D._innerFirstLevelLoaderManager.cancelLoadByUrl(url); Laya3D._innerSecondLevelLoaderManager.cancelLoadByUrl(url); Laya3D._innerThirdLevelLoaderManager.cancelLoadByUrl(url); Laya3D._innerFourthLevelLoaderManager.cancelLoadByUrl(url); } Laya3D._changeWebGLSize=function(width,height){ WebGL.onStageResize(width,height); RenderState.clientWidth=width; RenderState.clientHeight=height; } Laya3D.__init__=function(){ var createMap=LoaderManager.createMap; createMap["lh"]=[Sprite3D,/*CLASS CONST:Laya3D.HIERARCHY*/"SPRITE3DHIERARCHY"]; createMap["ls"]=[Scene,/*CLASS CONST:Laya3D.HIERARCHY*/"SPRITE3DHIERARCHY"]; createMap["lm"]=[Mesh,/*CLASS CONST:Laya3D.MESH*/"MESH"]; createMap["lmat"]=[StandardMaterial,/*CLASS CONST:Laya3D.MATERIAL*/"MATERIAL"]; createMap["lpbr"]=[PBRMaterial,/*CLASS CONST:Laya3D.MATERIAL*/"MATERIAL"]; createMap["ltc"]=[TextureCube,/*CLASS CONST:Laya3D.TEXTURECUBE*/"TEXTURECUBE"]; createMap["jpg"]=[Texture2D,"nativeimage"]; createMap["jpeg"]=[Texture2D,"nativeimage"]; createMap["png"]=[Texture2D,"nativeimage"]; createMap["pkm"]=[Texture2D,/*laya.net.Loader.BUFFER*/"arraybuffer"]; createMap["lsani"]=[AnimationTemplet,/*laya.net.Loader.BUFFER*/"arraybuffer"]; createMap["lrani"]=[AnimationTemplet,/*laya.net.Loader.BUFFER*/"arraybuffer"]; createMap["raw"]=[DataTexture2D,/*laya.net.Loader.BUFFER*/"arraybuffer"]; createMap["mipmaps"]=[DataTexture2D,/*laya.net.Loader.BUFFER*/"arraybuffer"]; createMap["thdata"]=[TerrainHeightData,/*laya.net.Loader.BUFFER*/"arraybuffer"]; createMap["lt"]=[TerrainRes,/*CLASS CONST:Laya3D.TERRAIN*/"TERRAIN"]; createMap["lani"]=[AnimationClip,/*laya.net.Loader.BUFFER*/"arraybuffer"]; createMap["lav"]=[Avatar,/*laya.net.Loader.JSON*/"json"]; createMap["ani"]=[AnimationTemplet,/*laya.net.Loader.BUFFER*/"arraybuffer"]; Loader.parserMap[ /*CLASS CONST:Laya3D.HIERARCHY*/"SPRITE3DHIERARCHY"]=Laya3D._loadHierarchy; Loader.parserMap[ /*CLASS CONST:Laya3D.MESH*/"MESH"]=Laya3D._loadMesh; Loader.parserMap[ /*CLASS CONST:Laya3D.MATERIAL*/"MATERIAL"]=Laya3D._loadMaterial; Loader.parserMap[ /*CLASS CONST:Laya3D.TEXTURECUBE*/"TEXTURECUBE"]=Laya3D._loadTextureCube; Loader.parserMap[ /*CLASS CONST:Laya3D.TERRAIN*/"TERRAIN"]=Laya3D._loadTerrain; Laya3D._innerFirstLevelLoaderManager.on(/*laya.events.Event.ERROR*/"error",null,Laya3D._eventLoadManagerError); Laya3D._innerSecondLevelLoaderManager.on(/*laya.events.Event.ERROR*/"error",null,Laya3D._eventLoadManagerError); Laya3D._innerThirdLevelLoaderManager.on(/*laya.events.Event.ERROR*/"error",null,Laya3D._eventLoadManagerError); Laya3D._innerFourthLevelLoaderManager.on(/*laya.events.Event.ERROR*/"error",null,Laya3D._eventLoadManagerError); } Laya3D.READ_BLOCK=function(){ Laya3D._readData.pos+=4; return true; } Laya3D.READ_DATA=function(){ Laya3D._DATA.offset=Laya3D._readData.getUint32(); Laya3D._DATA.size=Laya3D._readData.getUint32(); return true; } Laya3D.READ_STRINGS=function(){ var materialUrls=[]; var _STRINGS={offset:0,size:0}; _STRINGS.offset=Laya3D._readData.getUint16(); _STRINGS.size=Laya3D._readData.getUint16(); var ofs=Laya3D._readData.pos; Laya3D._readData.pos=_STRINGS.offset+Laya3D._DATA.offset; for (var i=0;i < _STRINGS.size;i++){ var string=Laya3D._readData.readUTFString(); if (string.lastIndexOf(".lmat")!==-1 || string.lastIndexOf(".lpbr")!==-1) materialUrls.push(string); } return materialUrls; } Laya3D.formatRelativePath=function(base,value){ var path; var char1=value.charAt(0); if (char1==="."){ var parts=(base+value).split("/"); for (var i=0,len=parts.length;i < len;i++){ if (parts[i]=='..'){ var index=i-1; if (index > 0 && parts[index]!=='..'){ parts.splice(index,2); i-=2; } } } path=parts.join('/'); }else { path=base+value; } (URL.customFormat !=null)&&(path=URL.customFormat(path,null)); return path; } Laya3D._eventLoadManagerError=function(msg){ Laya.loader.event(/*laya.events.Event.ERROR*/"error",msg); } Laya3D._addHierarchyInnerUrls=function(urls,urlMap,urlVersion,hierarchyBasePath,path,clas){ var formatSubUrl=Laya3D.formatRelativePath(hierarchyBasePath,path); (urlVersion)&& (formatSubUrl=formatSubUrl+urlVersion); urls.push({url:formatSubUrl,clas:clas}); urlMap[path]=formatSubUrl; } Laya3D._getSprite3DHierarchyInnerUrls=function(node,firstLevelUrls,secondLevelUrls,fourthLelUrls,urlMap,urlVersion,hierarchyBasePath){ var i=0,n=0; var customProps; switch (node.type){ case "Scene":; var lightmaps=node.customProps.lightmaps; for (i=0,n=lightmaps.length;i < n;i++){ var lightMap=lightmaps[i].replace(".exr",".png"); Laya3D._addHierarchyInnerUrls(fourthLelUrls,urlMap,urlVersion,hierarchyBasePath,lightMap,Texture2D); } break ; case "MeshSprite3D": case "TrailSprite3D": case "LineSprite3D": case "SkinnedMeshSprite3D":; var meshPath; if (node.instanceParams){ meshPath=node.instanceParams.loadPath; (meshPath)&& (Laya3D._addHierarchyInnerUrls(firstLevelUrls,urlMap,urlVersion,hierarchyBasePath,meshPath,Mesh)); }else { customProps=node.customProps; meshPath=customProps.meshPath; (meshPath)&& (Laya3D._addHierarchyInnerUrls(firstLevelUrls,urlMap,urlVersion,hierarchyBasePath,meshPath,Mesh)); var materials=customProps.materials; if (materials) for (i=0,n=materials.length;i < n;i++){ var mat=materials[i]; var clasPaths=mat.type.split('.'); var clas=Browser.window; clasPaths.forEach(function(cls){ clas=clas[cls]; }); if (typeof(clas)=='function')Laya3D._addHierarchyInnerUrls(secondLevelUrls,urlMap,urlVersion,hierarchyBasePath,mat.path,clas); else { throw('_getSprite3DHierarchyInnerUrls 错误: '+mat.type+' 不是类'); } } } break ; case "ShuriKenParticle3D": customProps=node.customProps; var parMeshPath=customProps.meshPath; (parMeshPath)&& (Laya3D._addHierarchyInnerUrls(firstLevelUrls,urlMap,urlVersion,hierarchyBasePath,parMeshPath,Mesh)); var materialData=customProps.material; if (materialData){ clasPaths=materialData.type.split('.'); clas=Browser.window; clasPaths.forEach(function(cls){ clas=clas[cls]; }); Laya3D._addHierarchyInnerUrls(secondLevelUrls,urlMap,urlVersion,hierarchyBasePath,materialData.path,clas); }else { var materialPath=customProps.materialPath; if (materialPath){ Laya3D._addHierarchyInnerUrls(secondLevelUrls,urlMap,urlVersion,hierarchyBasePath,materialPath,ShurikenParticleMaterial); }else { var texturePath=customProps.texturePath; if (texturePath) Laya3D._addHierarchyInnerUrls(fourthLelUrls,urlMap,urlVersion,hierarchyBasePath,texturePath,Texture2D); } } break ; case "Terrain": Laya3D._addHierarchyInnerUrls(fourthLelUrls,urlMap,urlVersion,hierarchyBasePath,node.customProps.dataPath,TerrainRes); break ; }; var components=node.components; for (var k in components){ var component=components[k]; switch (k){ case "Animator":; var avatarPath=component.avatarPath; if (avatarPath){ Laya3D._addHierarchyInnerUrls(fourthLelUrls,urlMap,urlVersion,hierarchyBasePath,avatarPath,Avatar); }else { var avatarData=component.avatar; (avatarData)&& (Laya3D._addHierarchyInnerUrls(fourthLelUrls,urlMap,urlVersion,hierarchyBasePath,avatarData.path,Avatar)); }; var clipPaths=component.clipPaths; for (i=0,n=clipPaths.length;i < n;i++) Laya3D._addHierarchyInnerUrls(fourthLelUrls,urlMap,urlVersion,hierarchyBasePath,clipPaths[i],AnimationClip); break ; } }; var children=node.child; for (i=0,n=children.length;i < n;i++) Laya3D._getSprite3DHierarchyInnerUrls(children[i],firstLevelUrls,secondLevelUrls,fourthLelUrls,urlMap,urlVersion,hierarchyBasePath); } Laya3D._loadHierarchy=function(loader){ loader.on(/*laya.events.Event.LOADED*/"loaded",null,Laya3D._onHierarchylhLoaded,[loader,loader._class._getGroup()]); loader.load(loader.url,/*laya.net.Loader.JSON*/"json",false,null,true); } Laya3D._onHierarchylhLoaded=function(loader,group,lhData){ if (loader._class.destroyed){ loader.endLoad(); }else { var url=loader.url; var urlVersion=Utils3D.getURLVerion(url); var hierarchyBasePath=URL.getPath(url); var firstLevUrls=[]; var secondLevUrls=[]; var forthLevUrls=[]; var urlMap={}; Laya3D._getSprite3DHierarchyInnerUrls(lhData,firstLevUrls,secondLevUrls,forthLevUrls,urlMap,urlVersion,hierarchyBasePath); var urlCount=firstLevUrls.length+secondLevUrls.length+forthLevUrls.length; var totalProcessCount=urlCount+1; var weight=1 / totalProcessCount; Laya3D._onProcessChange(loader,0,weight,1.0); if (forthLevUrls.length > 0){ var processCeil=urlCount / totalProcessCount; var processHandler=Handler.create(null,Laya3D._onProcessChange,[loader,weight,processCeil],false); Laya3D._innerFourthLevelLoaderManager.create(forthLevUrls,Handler.create(null,Laya3D._onHierarchyInnerForthLevResouLoaded,[loader,group,processHandler,lhData,urlMap,firstLevUrls,secondLevUrls,weight+processCeil *forthLevUrls.length,processCeil]),processHandler,null,null,1,true,group); }else { Laya3D._onHierarchyInnerForthLevResouLoaded(loader,group,null,lhData,urlMap,firstLevUrls,secondLevUrls,weight,processCeil); } } } Laya3D._onHierarchyInnerForthLevResouLoaded=function(loader,group,processHandler,lhData,urlMap,firstLevUrls,secondLevUrls,processOffset,processCeil){ if (loader._class.destroyed){ loader.endLoad(); }else { (processHandler)&& (processHandler.recover()); if (secondLevUrls.length > 0){ var process=Handler.create(null,Laya3D._onProcessChange,[loader,processOffset,processCeil],false); Laya3D._innerSecondLevelLoaderManager.create(secondLevUrls,Handler.create(null,Laya3D._onHierarchyInnerSecondLevResouLoaded,[loader,group,process,lhData,urlMap,firstLevUrls,processOffset+processCeil *secondLevUrls.length,processCeil]),processHandler,null,null,1,true,group); }else { Laya3D._onHierarchyInnerSecondLevResouLoaded(loader,group,null,lhData,urlMap,firstLevUrls,processOffset,processCeil); } } } Laya3D._onHierarchyInnerSecondLevResouLoaded=function(loader,group,processHandler,lhData,urlMap,firstLevUrls,processOffset,processCeil){ if (loader._class.destroyed){ loader.endLoad(); }else { (processHandler)&& (processHandler.recover()); if (firstLevUrls.length > 0){ var process=Handler.create(null,Laya3D._onProcessChange,[loader,processOffset,processCeil],false); Laya3D._innerFirstLevelLoaderManager.create(firstLevUrls,Handler.create(null,Laya3D._onHierarchyInnerFirstLevResouLoaded,[loader,process,lhData,urlMap,]),processHandler,null,null,1,true,group); }else { Laya3D._onHierarchyInnerFirstLevResouLoaded(loader,null,lhData,urlMap); } } } Laya3D._onHierarchyInnerFirstLevResouLoaded=function(loader,processHandler,lhData,urlMap){ (processHandler)&& (processHandler.recover()); loader.endLoad([lhData,urlMap]); } Laya3D._loadTerrain=function(loader){ loader.on(/*laya.events.Event.LOADED*/"loaded",null,Laya3D._onTerrainLtLoaded,[loader,loader._class._getGroup()]); loader.load(loader.url,/*laya.net.Loader.JSON*/"json",false,null,true); } Laya3D._onTerrainLtLoaded=function(loader,group,ltData){ if (loader._class.destroyed){ loader.endLoad(); }else { var url=loader.url; var urlVersion=Utils3D.getURLVerion(url); var terrainBasePath=URL.getPath(url); var heightMapURL,textureURLs=[]; var urlMap={}; var formatUrl; var i=0,n=0,count=0; var heightData=ltData.heightData; heightMapURL=heightData.url; formatUrl=Laya3D.formatRelativePath(terrainBasePath,heightMapURL); (urlVersion)&& (formatUrl=formatUrl+urlVersion); urlMap[heightMapURL]=formatUrl; heightMapURL=formatUrl; var detailTextures=ltData.detailTexture; for (i=0,n=detailTextures.length;i < n;i++) textureURLs.push({url:detailTextures[i].diffuse}); var normalMaps=ltData.normalMap; for (i=0,n=normalMaps.length;i < n;i++) textureURLs.push({url:normalMaps[i]}); var alphaMaps=ltData.alphaMap; for (i=0,n=alphaMaps.length;i < n;i++) textureURLs.push({url:alphaMaps[i],params:[false,false,/*laya.webgl.WebGLContext.RGBA*/0x1908,true]}); for (i=0,n=textureURLs.length;i < n;i++){ var subUrl=textureURLs[i].url; formatUrl=Laya3D.formatRelativePath(terrainBasePath,subUrl); (urlVersion)&& (formatUrl=formatUrl+urlVersion); textureURLs[i].url=formatUrl; urlMap[subUrl]=formatUrl; }; var texsUrlCount=textureURLs.length; var totalProcessCount=texsUrlCount+2; var weight=1 / totalProcessCount; Laya3D._onProcessChange(loader,0,weight,1.0); var loadInfo={heightMapLoaded:false,texturesLoaded:false}; var hmProcessHandler=Handler.create(null,Laya3D._onProcessChange,[loader,weight,weight],false); Laya3D._innerFourthLevelLoaderManager.create(heightMapURL,Handler.create(null,Laya3D._onTerrainHeightMapLoaded,[loader,hmProcessHandler,ltData,urlMap,loadInfo]),hmProcessHandler,null,[heightData.numX,heightData.numZ,heightData.bitType,heightData.value],1,true,group); var texsProcessHandler=Handler.create(null,Laya3D._onProcessChange,[loader,weight *2,texsUrlCount / totalProcessCount],false); Laya3D._innerFourthLevelLoaderManager.create(textureURLs,Handler.create(null,Laya3D._onTerrainTexturesLoaded,[loader,texsProcessHandler,ltData,urlMap,loadInfo]),texsProcessHandler,null,null,1,true,group); } } Laya3D._onTerrainHeightMapLoaded=function(loader,processHandler,ltData,urlMap,loadInfo){ loadInfo.heightMapLoaded=true; if (loadInfo.texturesLoaded){ loader.endLoad([ltData,urlMap]); processHandler.recover(); } } Laya3D._onTerrainTexturesLoaded=function(loader,processHandler,ltData,urlMap,loadInfo){ loadInfo.texturesLoaded=true; if (loadInfo.heightMapLoaded){ loader.endLoad([ltData,urlMap]); processHandler.recover(); } } Laya3D._loadMesh=function(loader){ loader.on(/*laya.events.Event.LOADED*/"loaded",null,Laya3D._onMeshLmLoaded,[loader,loader._class._getGroup()]); loader.load(loader.url,/*laya.net.Loader.BUFFER*/"arraybuffer",false,null,true); } Laya3D._onMeshLmLoaded=function(loader,group,lmData){ if (loader._class.destroyed){ loader.endLoad(); }else { var url=loader.url; var urlVersion=Utils3D.getURLVerion(url); var meshBasePath=URL.getPath(url); var urls; var urlMap={}; var formatSubUrl; var i=0,n=0,count=0; Laya3D._readData=new Byte(lmData); Laya3D._readData.pos=0; var version=Laya3D._readData.readUTFString(); switch (version){ case "LAYAMODEL:02": case "LAYAMODEL:03": case "LAYAMODEL:0301":; var dataOffset=Laya3D._readData.getUint32(); Laya3D._readData.pos=Laya3D._readData.pos+4; count=Laya3D._readData.getUint16(); Laya3D._readData.pos=Laya3D._readData.pos+count *8; var offset=Laya3D._readData.getUint32(); count=Laya3D._readData.getUint16(); Laya3D._readData.pos=dataOffset+offset; urls=[]; for (i=0;i < count;i++){ var string=Laya3D._readData.readUTFString(); if (string.lastIndexOf(".lmat")!==-1) urls.push(string); } break ; default : Laya3D.READ_BLOCK(); for (i=0;i < 2;i++){ var index=Laya3D._readData.getUint16(); var blockName=Laya3D._strings[index]; var fn=Laya3D["READ_"+blockName]; if (fn==null)throw new Error("model file err,no this function:"+index+" "+blockName); if (i===1) urls=fn.call(); else fn.call() } } for (i=0,n=urls.length;i < n;i++){ var subUrl=urls[i]; formatSubUrl=Laya3D.formatRelativePath(meshBasePath,subUrl); (urlVersion)&& (formatSubUrl=formatSubUrl+urlVersion); urls[i]=formatSubUrl; urlMap[subUrl]=formatSubUrl; } if (urls.length > 0){ var urlCount=1; var totalProcessCount=urlCount+1; var lmatWeight=1 / totalProcessCount; Laya3D._onProcessChange(loader,0,lmatWeight,1.0); var processHandler=Handler.create(null,Laya3D._onProcessChange,[loader,lmatWeight,urlCount / totalProcessCount],false); Laya3D._innerSecondLevelLoaderManager.create(urls,Handler.create(null,Laya3D._onMeshMateialLoaded,[loader,processHandler,lmData,urlMap]),processHandler,null,null,1,true,group); }else { loader.endLoad([lmData,urlMap]); } } } Laya3D._onMeshMateialLoaded=function(loader,processHandler,lmData,urlMap){ loader.endLoad([lmData,urlMap]); processHandler.recover(); } Laya3D._getMaterialTexturePath=function(path,urlVersion,materialBath){ var extenIndex=path.length-4; if (path.indexOf(".dds")==extenIndex || path.indexOf(".tga")==extenIndex || path.indexOf(".exr")==extenIndex || path.indexOf(".DDS")==extenIndex || path.indexOf(".TGA")==extenIndex || path.indexOf(".EXR")==extenIndex) path=path.substr(0,extenIndex)+".png"; path=Laya3D.formatRelativePath(materialBath,path); (urlVersion)&& (path=path+urlVersion); return path; } Laya3D._loadMaterial=function(loader){ loader.on(/*laya.events.Event.LOADED*/"loaded",null,Laya3D._onMaterilLmatLoaded,[loader,loader._class._getGroup()]); loader.load(loader.url,/*laya.net.Loader.JSON*/"json",false,null,true); } Laya3D._onMaterilLmatLoaded=function(loader,group,lmatData){ if (loader._class.destroyed){ loader.endLoad(); }else { var url=loader.url; var urlVersion=Utils3D.getURLVerion(url); var materialBasePath=URL.getPath(url); var urls=[]; var urlMap={}; var customProps=lmatData.customProps; var formatSubUrl; var version=lmatData.version; if (version){ switch (version){ case "LAYAMATERIAL:01": case "LAYAMATERIAL:02":; var textures=lmatData.props.textures; for (var i=0,n=textures.length;i < n;i++){ var tex=textures[i]; var path=tex.path; if (path){ var extenIndex=path.length-4; if (path.indexOf(".exr")==extenIndex || path.indexOf(".EXR")==extenIndex) path=path.substr(0,extenIndex)+".png"; formatSubUrl=Laya3D.formatRelativePath(materialBasePath,path); (urlVersion)&& (formatSubUrl=formatSubUrl+urlVersion); urls.push({url:formatSubUrl,params:tex.params}); urlMap[path]=formatSubUrl; } } break ; default : throw new Error("Laya3D:unkonwn version."); } }else { var diffuseTexture=customProps.diffuseTexture.texture2D; if (diffuseTexture){ formatSubUrl=Laya3D._getMaterialTexturePath(diffuseTexture,urlVersion,materialBasePath); urls.push(formatSubUrl); urlMap[diffuseTexture]=formatSubUrl; } if (customProps.normalTexture){ var normalTexture=customProps.normalTexture.texture2D; if (normalTexture){ formatSubUrl=Laya3D._getMaterialTexturePath(normalTexture,urlVersion,materialBasePath); urls.push(formatSubUrl); urlMap[normalTexture]=formatSubUrl; } } if (customProps.specularTexture){ var specularTexture=customProps.specularTexture.texture2D; if (specularTexture){ formatSubUrl=Laya3D._getMaterialTexturePath(specularTexture,urlVersion,materialBasePath); urls.push(formatSubUrl); urlMap[specularTexture]=formatSubUrl; } } if (customProps.emissiveTexture){ var emissiveTexture=customProps.emissiveTexture.texture2D; if (emissiveTexture){ formatSubUrl=Laya3D._getMaterialTexturePath(emissiveTexture,urlVersion,materialBasePath); urls.push(formatSubUrl); urlMap[emissiveTexture]=formatSubUrl; } } if (customProps.ambientTexture){ var ambientTexture=customProps.ambientTexture.texture2D; if (ambientTexture){ formatSubUrl=Laya3D._getMaterialTexturePath(ambientTexture,urlVersion,materialBasePath); urls.push(formatSubUrl); urlMap[ambientTexture]=formatSubUrl; } } if (customProps.reflectTexture){ var reflectTexture=customProps.reflectTexture.texture2D; if (reflectTexture){ formatSubUrl=Laya3D._getMaterialTexturePath(reflectTexture,urlVersion,materialBasePath); urls.push(formatSubUrl); urlMap[reflectTexture]=formatSubUrl; } } }; var urlCount=urls.length; var totalProcessCount=urlCount+1; var lmatWeight=1 / totalProcessCount; Laya3D._onProcessChange(loader,0,lmatWeight,1.0); if (urlCount > 0){ var processHandler=Handler.create(null,Laya3D._onProcessChange,[loader,lmatWeight,urlCount / totalProcessCount],false); Laya3D._innerFourthLevelLoaderManager.create(urls,Handler.create(null,Laya3D._onMateialTexturesLoaded,[loader,processHandler,lmatData,urlMap]),processHandler,Texture2D,null,1,true,group); }else { Laya3D._onMateialTexturesLoaded(loader,null,lmatData,null); } } } Laya3D._onMateialTexturesLoaded=function(loader,processHandler,lmatData,urlMap){ loader.endLoad([lmatData,urlMap]); (processHandler)&& (processHandler.recover()); } Laya3D._loadTextureCube=function(loader){ loader.on(/*laya.events.Event.LOADED*/"loaded",null,Laya3D._onTextureCubeLtcLoaded,[loader]); loader.load(loader.url,/*laya.net.Loader.JSON*/"json",false,null,true); } Laya3D._onTextureCubeLtcLoaded=function(loader,ltcData){ if (loader._class.destroyed){ loader.endLoad(); }else { var ltcBasePath=URL.getPath(loader.url); var urls=[Laya3D.formatRelativePath(ltcBasePath,ltcData.px),Laya3D.formatRelativePath(ltcBasePath,ltcData.nx),Laya3D.formatRelativePath(ltcBasePath,ltcData.py),Laya3D.formatRelativePath(ltcBasePath,ltcData.ny),Laya3D.formatRelativePath(ltcBasePath,ltcData.pz),Laya3D.formatRelativePath(ltcBasePath,ltcData.nz)]; var ltcWeight=1.0 / 7.0; Laya3D._onProcessChange(loader,0,ltcWeight,1.0); var processHandler=Handler.create(null,Laya3D._onProcessChange,[loader,ltcWeight,6 / 7],false); Laya3D._innerFourthLevelLoaderManager.load(urls,Handler.create(null,Laya3D._onTextureCubeImagesLoaded,[loader,urls,processHandler]),processHandler,"nativeimage"); } } Laya3D._onTextureCubeImagesLoaded=function(loader,urls,processHandler){ var images=[]; images.length=6; for (var i=0;i < 6;i++){ var url=urls[i]; images[i]=Loader.getRes(url); Loader.clearRes(url); } loader.endLoad(images); processHandler.recover(); } Laya3D._onProcessChange=function(loader,offset,weight,process){ process=offset+process *weight; (process < 1.0)&& (loader.event(/*laya.events.Event.PROGRESS*/"progress",process)); } Laya3D.init=function(width,height,antialias,alpha,premultipliedAlpha,stencil){ (antialias===void 0)&& (antialias=false); (alpha===void 0)&& (alpha=false); (premultipliedAlpha===void 0)&& (premultipliedAlpha=true); (stencil===void 0)&& (stencil=true); if (Laya3D._isinit)return; Laya3D._isinit=true; RunDriver.update3DLoop=function (){ CollisionManager._triggerCollision(); } RunDriver.cancelLoadByUrl=function (url){ Laya3D._cancelLoadByUrl(url); } Config.isAntialias=antialias; Config.isAlpha=alpha; Config.premultipliedAlpha=premultipliedAlpha; Config.isStencil=stencil; if (!WebGL.enable()){ alert("Laya3D init error,must support webGL!"); return; } RunDriver.changeWebGLSize=Laya3D._changeWebGLSize; Render.is3DMode=true; Laya.init(width,height); Layer.__init__(); Physics.__init__(); ExtendTerrainMaterial.__init__(); ShaderInit3D.__init__(); MeshSprite3D.__init__(); AnimationNode.__init__(); Laya3D.__init__(); AtlasResourceManager.maxTextureCount=2; if (Laya3D.debugMode || OctreeNode.debugMode) Laya3D._debugPhasorSprite=new PhasorSpriter3D(); } Laya3D.HIERARCHY="SPRITE3DHIERARCHY"; Laya3D.MESH="MESH"; Laya3D.MATERIAL="MATERIAL"; Laya3D.PBRMATERIAL="PBRMTL"; Laya3D.TEXTURECUBE="TEXTURECUBE"; Laya3D.TERRAIN="TERRAIN"; Laya3D._readData=null; Laya3D._debugPhasorSprite=null; Laya3D.debugMode=false; Laya3D._isinit=false; __static(Laya3D, ['_DATA',function(){return this._DATA={offset:0,size:0};},'_strings',function(){return this._strings=['BLOCK','DATA',"STRINGS"];},'_innerFirstLevelLoaderManager',function(){return this._innerFirstLevelLoaderManager=new LoaderManager();},'_innerSecondLevelLoaderManager',function(){return this._innerSecondLevelLoaderManager=new LoaderManager();},'_innerThirdLevelLoaderManager',function(){return this._innerThirdLevelLoaderManager=new LoaderManager();},'_innerFourthLevelLoaderManager',function(){return this._innerFourthLevelLoaderManager=new LoaderManager();} ]); return Laya3D; })() /** *Transform3D 类用于实现3D变换。 */ //class laya.d3.animation.AnimationTransform3D extends laya.events.EventDispatcher var AnimationTransform3D=(function(_super){ function AnimationTransform3D(owner){ /**@private */ //this._localMatrix=null; /**@private */ //this._worldMatrix=null; /**@private */ //this._localPosition=null; /**@private */ //this._localRotation=null; /**@private */ //this._localScale=null; /**@private */ //this._localQuaternionUpdate=false; /**@private */ //this._locaEulerlUpdate=false; /**@private */ //this._localUpdate=false; /**@private */ //this._parent=null; /**@private */ //this._childs=null; /**@private */ //this._localRotationEuler=null; /**@private */ //this._owner=null; /**@private */ //this._worldUpdate=false; /**@private */ //this._entity=null; AnimationTransform3D.__super.call(this); this._owner=owner; this._childs=[]; this._localMatrix=new Float32Array(16); this._localQuaternionUpdate=false; this._locaEulerlUpdate=false; this._localUpdate=false; this._worldUpdate=true; } __class(AnimationTransform3D,'laya.d3.animation.AnimationTransform3D',_super); var __proto=AnimationTransform3D.prototype; /** *@private */ __proto._getlocalMatrix=function(){ if (this._localUpdate){ Utils3D._createAffineTransformationArray(this._localPosition,this._localRotation,this._localScale,this._localMatrix); this._localUpdate=false; } return this._localMatrix; } /** *@private */ __proto._onWorldTransform=function(){ if (!this._worldUpdate){ this._worldUpdate=true; for (var i=0,n=this._childs.length;i < n;i++) this._childs[i]._onWorldTransform(); } } /** *@private */ __proto._setWorldMatrixAndUpdate=function(matrix){ this._worldMatrix=matrix; if (this._parent==null){ throw new Error("don't need to set worldMatrix to root Node."); }else { if (this._parent._parent==null){ var locMat=this._getlocalMatrix(); for (var i=0;i < 16;++i) this._worldMatrix[i]=locMat[i]; }else { Utils3D.matrix4x4MultiplyFFF(this._parent.getWorldMatrix(),this._getlocalMatrix(),this._worldMatrix); } } this._worldUpdate=false; } /** *@private */ __proto._setWorldMatrixNoUpdate=function(matrix){ this._worldMatrix=matrix; } /** *@private */ __proto._setWorldMatrixIgnoreUpdate=function(matrix){ this._worldMatrix=matrix; this._worldUpdate=false; } /** *获取局部位置。 *@return 局部位置。 */ __proto.getLocalPosition=function(){ return this._localPosition; } /** *设置局部位置。 *@param value 局部位置。 */ __proto.setLocalPosition=function(value){ if (this._parent){ this._localPosition=value; this._localUpdate=true; this._onWorldTransform(); }else { var entityTransform=this._entity.owner._transform; var entityPosition=this._entity.localPosition; var entityPositionE=entityPosition.elements; entityPositionE[0]=value[0]; entityPositionE[1]=value[1]; entityPositionE[2]=value[2]; entityTransform.localPosition=entityPosition; } } /** *获取局部旋转。 *@return 局部旋转。 */ __proto.getLocalRotation=function(){ if (this._localQuaternionUpdate){ var eulerE=this._localRotationEuler; Utils3D._quaternionCreateFromYawPitchRollArray(eulerE[1] / AnimationTransform3D._angleToRandin,eulerE[0] / AnimationTransform3D._angleToRandin,eulerE[2] / AnimationTransform3D._angleToRandin,this._localRotation); this._localQuaternionUpdate=false; } return this._localRotation; } /** *设置局部旋转。 *@param value 局部旋转。 */ __proto.setLocalRotation=function(value){ if (this._parent){ this._localRotation=value; Utils3D.quaterionNormalize(this._localRotation,this._localRotation); this._locaEulerlUpdate=true; this._localQuaternionUpdate=false; this._localUpdate=true; this._onWorldTransform(); }else { var entityTransform=this._entity.owner._transform; var entityRotation=this._entity.localRotation; var entityRotationE=entityRotation.elements; entityRotationE[0]=value[0]; entityRotationE[1]=value[1]; entityRotationE[2]=value[2]; entityRotationE[3]=value[3]; entityTransform.localRotation=entityRotation; } } /** *获取局部缩放。 *@return 局部缩放。 */ __proto.getLocalScale=function(){ return this._localScale; } /** *设置局部缩放。 *@param value 局部缩放。 */ __proto.setLocalScale=function(value){ if (this._parent){ this._localScale=value; this._localUpdate=true; this._onWorldTransform(); }else { var entityTransform=this._entity.owner._transform; var entityScale=this._entity.localScale; var entityScaleE=entityScale.elements; entityScaleE[0]=value[0]; entityScaleE[1]=value[1]; entityScaleE[2]=value[2]; entityTransform.localScale=entityScale; } } /** *获取局部空间的旋转角度。 *@return 欧拉角的旋转值,顺序为x、y、z。 */ __proto.getLocalRotationEuler=function(){ if (this._locaEulerlUpdate){ Utils3D.getYawPitchRoll(this._localRotation,AnimationTransform3D._tempVector3); var eulerE=AnimationTransform3D._tempVector3; var localRotationEulerE=this._localRotationEuler; localRotationEulerE[0]=eulerE[1] *AnimationTransform3D._angleToRandin; localRotationEulerE[1]=eulerE[0] *AnimationTransform3D._angleToRandin; localRotationEulerE[2]=eulerE[2] *AnimationTransform3D._angleToRandin; this._locaEulerlUpdate=false; } return this._localRotationEuler; } /** *设置局部空间的旋转角度。 *@param value 欧拉角的旋转值,顺序为x、y、z。 */ __proto.setLocalRotationEuler=function(value){ if (this._parent){ Utils3D._quaternionCreateFromYawPitchRollArray(value[1] / AnimationTransform3D._angleToRandin,value[0] / AnimationTransform3D._angleToRandin,value[2] / AnimationTransform3D._angleToRandin,this._localRotation); this._localRotationEuler=value; this._locaEulerlUpdate=false; this._localQuaternionUpdate=false; this._localUpdate=true; this._onWorldTransform(); }else { var entityTransform=this._entity.owner._transform; var entityLocalRotationEuler=this._entity.localRotationEuler; var elements=entityLocalRotationEuler.elements; elements[0]=value[0]; elements[1]=value[1]; elements[2]=value[2]; entityTransform.localRotationEuler=entityLocalRotationEuler; } } /** *获取世界矩阵。 *@return 世界矩阵。 */ __proto.getWorldMatrix=function(){ if (this._worldUpdate){ if (this._parent._parent !=null){ Utils3D.matrix4x4MultiplyFFF(this._parent.getWorldMatrix(),this._getlocalMatrix(),this._worldMatrix); }else { var locMat=this._getlocalMatrix(); for (var i=0;i < 16;++i) this._worldMatrix[i]=locMat[i]; } this._worldUpdate=false; } return this._worldMatrix; } /** *设置父3D变换。 *@param value 父3D变换。 */ __proto.setParent=function(value){ if (this._parent!==value){ if (this._parent){ var parentChilds=this._parent._childs; var index=parentChilds.indexOf(this); parentChilds.splice(index,1); } if (value){ value._childs.push(this); (value)&& (this._onWorldTransform()); } this._parent=value; } } __static(AnimationTransform3D, ['_tempVector3',function(){return this._tempVector3=new Float32Array(3);},'_angleToRandin',function(){return this._angleToRandin=180 / Math.PI;} ]); return AnimationTransform3D; })(EventDispatcher) /** *Component3D 类用于创建组件的父类。 */ //class laya.d3.component.Component3D extends laya.events.EventDispatcher var Component3D=(function(_super){ function Component3D(){ /**@private */ this._destroyed=false; /**@private 唯一标识ID。*/ this._id=0; /**@private 是否启动。*/ this._enable=false; /**@private 所属Sprite3D节点。*/ this._owner=null; /**是否已执行start函数。*/ this.started=false; Component3D.__super.call(this); this._destroyed=false; this._id=Component3D._uniqueIDCounter; Component3D._uniqueIDCounter++; } __class(Component3D,'laya.d3.component.Component3D',_super); var __proto=Component3D.prototype; Laya.imps(__proto,{"laya.d3.core.render.IUpdate":true,"laya.resource.IDestroy":true}) /** *@private *初始化组件。 *@param owner 所属Sprite3D节点。 */ __proto._initialize=function(owner){ this._owner=owner; this._enable=true; this.started=false; this._load(owner); } /** *@private *销毁组件。 */ __proto._destroy=function(){ this._unload(this._owner); this._owner=null; this._destroyed=true; } /** *@private *载入组件时执行,可重写此函数。 */ __proto._load=function(owner){} /** *@private *在任意第一次更新时执行,可重写此函数。 */ __proto._start=function(state){} /** *@private *更新组件,可重写此函数。 *@param state 渲染状态参数。 */ __proto._update=function(state){} /** *@private *更新的最后阶段执行,可重写此函数。 *@param state 渲染状态参数。 */ __proto._lateUpdate=function(state){} /** *@private *渲染前设置组件相关参数,可重写此函数。 *@param state 渲染状态参数。 */ __proto._preRenderUpdate=function(state){} /** *@private *渲染的最后阶段执行,可重写此函数。 *@param state 渲染状态参数。 */ __proto._postRenderUpdate=function(state){} /** *@private *卸载组件时执行,可重写此函数。 */ __proto._unload=function(owner){ this.offAll(); } /** *@private */ __proto._cloneTo=function(dest){} /** *获取唯一标识ID。 *@return 唯一标识ID。 */ __getset(0,__proto,'id',function(){ return this._id; }); /** *获取是否已销毁。 *@return 是否已销毁。 */ __getset(0,__proto,'destroyed',function(){ return this._destroyed; }); /** *获取所属Sprite3D节点。 *@return 所属Sprite3D节点。 */ __getset(0,__proto,'owner',function(){ return this._owner; }); /** *设置是否启用。 *@param value 是否启动 */ /** *获取是否启用。 *@return 是否启动。 */ __getset(0,__proto,'enable',function(){ return this._enable; },function(value){ if (this._enable!==value){ this._enable=value; this.event(/*laya.events.Event.ENABLE_CHANGED*/"enablechanged",this._enable); } }); /** *获取是否为单实例组件。 *@return 是否为单实例组件。 */ __getset(0,__proto,'isSingleton',function(){ return Component3D._isSingleton; }); Component3D._isSingleton=true; Component3D._uniqueIDCounter=1; return Component3D; })(EventDispatcher) /** *GeometryFilter 类用于创建集合体过滤器,抽象类不允许实例。 */ //class laya.d3.core.GeometryFilter extends laya.events.EventDispatcher var GeometryFilter=(function(_super){ function GeometryFilter(){ /**@private */ this._destroyed=false; GeometryFilter.__super.call(this); this._destroyed=false; } __class(GeometryFilter,'laya.d3.core.GeometryFilter',_super); var __proto=GeometryFilter.prototype; Laya.imps(__proto,{"laya.resource.IDestroy":true}) /** *@private */ __proto._destroy=function(){ this.offAll(); this._destroyed=true; } /**@private */ __getset(0,__proto,'_isAsyncLoaded',function(){ return true; }); /** *@private */ __getset(0,__proto,'_originalBoundingBoxCorners',function(){ throw new Error("BaseRender: must override it."); }); /** *@private */ __getset(0,__proto,'_originalBoundingSphere',function(){ throw new Error("BaseRender: must override it."); }); /** *@private */ __getset(0,__proto,'_originalBoundingBox',function(){ throw new Error("BaseRender: must override it."); }); /** *获取是否已销毁。 *@return 是否已销毁。 */ __getset(0,__proto,'destroyed',function(){ return this._destroyed; }); return GeometryFilter; })(EventDispatcher) /** *Render 类用于渲染器的父类,抽象类不允许实例。 */ //class laya.d3.core.render.BaseRender extends laya.events.EventDispatcher var BaseRender=(function(_super){ function BaseRender(owner){ /**@private */ //this._id=0; /**@private */ //this._destroyed=false; /**@private */ //this._lightmapScaleOffset=null; /**@private */ //this._lightmapIndex=0; /**@private */ //this._enable=false; /**@private */ //this._receiveShadow=false; /**@private */ //this._materialsInstance=null; /**@private */ //this._boundingSphere=null; /**@private */ //this._boundingBox=null; /**@private */ //this._boundingBoxCenter=null; /**@private */ //this._boundingSphereNeedChange=false; /**@private */ //this._boundingBoxNeedChange=false; /**@private */ //this._boundingBoxCenterNeedChange=false; /**@private */ //this._octreeNodeNeedChange=false; /**@private */ //this._indexInSceneFrustumCullingObjects=0; /**@private */ //this._materials=null; /**@private */ //this._owner=null; /**@private */ //this._renderElements=null; /**@private */ //this._distanceForSort=NaN; /**@private */ //this._treeNode=null; /**@private */ //this._isPartOfStaticBatch=false; /**@private */ //this._staticBatchRootSprite3D=null; /**@private */ //this._staticBatchRenderElements=null; /**排序矫正值。*/ //this.sortingFudge=NaN; /**是否产生阴影。 */ //this.castShadow=false; BaseRender.__super.call(this); this._id=++BaseRender._uniqueIDCounter; this._indexInSceneFrustumCullingObjects=-1; this._boundingBox=new BoundBox(new Vector3(),new Vector3()); this._boundingBoxCenter=new Vector3(); this._boundingSphere=new BoundSphere(new Vector3(),0); this._boundingSphereNeedChange=true; this._boundingBoxNeedChange=true; this._boundingBoxCenterNeedChange=true; this._octreeNodeNeedChange=true; this._materials=[]; this._renderElements=[]; this._isPartOfStaticBatch=false; this._destroyed=false; this._owner=owner; this._enable=true; this._materialsInstance=[]; this.lightmapIndex=-1; this.castShadow=false; this.receiveShadow=false; this.sortingFudge=0.0; this._owner.transform.on(/*laya.events.Event.WORLDMATRIX_NEEDCHANGE*/"worldmatrixneedchanged",this,this._onWorldMatNeedChange); } __class(BaseRender,'laya.d3.core.render.BaseRender',_super); var __proto=BaseRender.prototype; Laya.imps(__proto,{"laya.resource.IDestroy":true}) /** *@private */ __proto._changeMaterialReference=function(lastValue,value){ (lastValue)&& (lastValue._removeReference()); value._addReference(); } /** *@private */ __proto._getInstanceMaterial=function(material,index){ var insMat=/*__JS__ */new material.constructor(); material.cloneTo(insMat); insMat.name=insMat.name+"(Instance)"; this._materialsInstance[index]=true; this._changeMaterialReference(this._materials[index],insMat); this._materials[index]=insMat; return insMat; } /** *@private */ __proto._setShaderValuelightMap=function(lightMap){ this._setShaderValueTexture(/*laya.d3.core.RenderableSprite3D.LIGHTMAP*/3,lightMap); } /** *@private */ __proto._onWorldMatNeedChange=function(){ this._boundingSphereNeedChange=true; this._boundingBoxNeedChange=true; this._boundingBoxCenterNeedChange=true; this._octreeNodeNeedChange=true; } /** *@private */ __proto._renderRenderableBoundBox=function(){ var linePhasor=Laya3D._debugPhasorSprite; var boundBox=this.boundingBox; var corners=BaseRender._tempBoundBoxCorners; boundBox.getCorners(corners); linePhasor.line(corners[0],BaseRender._greenColor,corners[1],BaseRender._greenColor); linePhasor.line(corners[2],BaseRender._greenColor,corners[3],BaseRender._greenColor); linePhasor.line(corners[4],BaseRender._greenColor,corners[5],BaseRender._greenColor); linePhasor.line(corners[6],BaseRender._greenColor,corners[7],BaseRender._greenColor); linePhasor.line(corners[0],BaseRender._greenColor,corners[3],BaseRender._greenColor); linePhasor.line(corners[1],BaseRender._greenColor,corners[2],BaseRender._greenColor); linePhasor.line(corners[2],BaseRender._greenColor,corners[6],BaseRender._greenColor); linePhasor.line(corners[3],BaseRender._greenColor,corners[7],BaseRender._greenColor); linePhasor.line(corners[0],BaseRender._greenColor,corners[4],BaseRender._greenColor); linePhasor.line(corners[1],BaseRender._greenColor,corners[5],BaseRender._greenColor); linePhasor.line(corners[4],BaseRender._greenColor,corners[7],BaseRender._greenColor); linePhasor.line(corners[5],BaseRender._greenColor,corners[6],BaseRender._greenColor); } /** *@private */ __proto._calculateBoundingSphere=function(){ throw("BaseRender: must override it."); } /** *@private */ __proto._calculateBoundingBox=function(){ throw("BaseRender: must override it."); } /** *@private */ __proto._setShaderValueTexture=function(shaderName,texture){ this._owner._shaderValues.setValue(shaderName,texture); } /** *@private */ __proto._setShaderValueMatrix4x4=function(shaderName,matrix4x4){ this._owner._shaderValues.setValue(shaderName,matrix4x4 ? matrix4x4.elements :null); } /** *设置颜色。 *@param shaderIndex shader索引。 *@param color 颜色向量。 */ __proto._setShaderValueColor=function(shaderIndex,color){ this._owner._shaderValues.setValue(shaderIndex,color ? color.elements :null); } /** *设置Buffer。 *@param shaderIndex shader索引。 *@param buffer buffer数据。 */ __proto._setShaderValueBuffer=function(shaderIndex,buffer){ this._owner._shaderValues.setValue(shaderIndex,buffer); } /** *设置整型。 *@param shaderIndex shader索引。 *@param i 整形。 */ __proto._setShaderValueInt=function(shaderIndex,i){ this._owner._shaderValues.setValue(shaderIndex,i); } /** *设置布尔。 *@param shaderIndex shader索引。 *@param b 布尔。 */ __proto._setShaderValueBool=function(shaderIndex,b){ this._owner._shaderValues.setValue(shaderIndex,b); } /** *设置浮点。 *@param shaderIndex shader索引。 *@param i 浮点。 */ __proto._setShaderValueNumber=function(shaderIndex,number){ this._owner._shaderValues.setValue(shaderIndex,number); } /** *设置二维向量。 *@param shaderIndex shader索引。 *@param vector2 二维向量。 */ __proto._setShaderValueVector2=function(shaderIndex,vector2){ this._owner._shaderValues.setValue(shaderIndex,vector2 ? vector2.elements :null); } /** *增加Shader宏定义。 *@param value 宏定义。 */ __proto._addShaderDefine=function(value){ this._owner._shaderDefineValue |=value; } /** *移除Shader宏定义。 *@param value 宏定义。 */ __proto._removeShaderDefine=function(value){ this._owner._shaderDefineValue &=~value; } /** *@private */ __proto._renderUpdate=function(projectionView){ return true; } /** *@private */ __proto._applyLightMapParams=function(){ if (this._lightmapIndex >=0){ var scene=this._owner.scene; if (scene){ var lightMaps=scene.getlightmaps(); var lightMap=lightMaps[this._lightmapIndex]; if (lightMap){ this._addShaderDefine(RenderableSprite3D.SAHDERDEFINE_LIGHTMAP); if (lightMap.loaded) this._setShaderValuelightMap(lightMap); else lightMap.once(/*laya.events.Event.LOADED*/"loaded",this,this._setShaderValuelightMap); }else { this._removeShaderDefine(RenderableSprite3D.SAHDERDEFINE_LIGHTMAP); } }else { this._removeShaderDefine(RenderableSprite3D.SAHDERDEFINE_LIGHTMAP); } }else { this._removeShaderDefine(RenderableSprite3D.SAHDERDEFINE_LIGHTMAP); } } /** *@private */ __proto._updateOctreeNode=function(){ var treeNode=this._treeNode; if (treeNode && this._octreeNodeNeedChange){ treeNode.updateObject(this); this._octreeNodeNeedChange=false; } } /** *@private */ __proto._destroy=function(){ this.offAll(); var i=0,n=0; for (i=0,n=this._renderElements.length;i < n;i++) this._renderElements[i]._destroy(); for (i=0,n=this._materials.length;i < n;i++) this._materials[i]._removeReference(); this._renderElements=null; this._owner=null; this._materials=null; this._boundingBox=null; this._boundingBoxCenter=null; this._boundingSphere=null; this._lightmapScaleOffset=null; this._destroyed=true; } /** *获取包围球,只读,不允许修改其值。 *@return 包围球。 */ __getset(0,__proto,'boundingSphere',function(){ if (this._boundingSphereNeedChange){ this._calculateBoundingSphere(); this._boundingSphereNeedChange=false; } return this._boundingSphere; }); /** *获取唯一标识ID,通常用于识别。 */ __getset(0,__proto,'id',function(){ return this._id; }); /** *设置第一个实例材质。 *@param value 第一个实例材质。 */ /** *返回第一个实例材质,第一次使用会拷贝实例对象。 *@return 第一个实例材质。 */ __getset(0,__proto,'material',function(){ var material=this._materials[0]; if (material && !this._materialsInstance[0]){ var insMat=this._getInstanceMaterial(material,0); this.event(/*laya.events.Event.MATERIAL_CHANGED*/"materialchanged",[this,0,insMat]); } return this._materials[0]; },function(value){ this.sharedMaterial=value; }); /** *设置第一个材质。 *@param value 第一个材质。 */ /** *返回第一个材质。 *@return 第一个材质。 */ __getset(0,__proto,'sharedMaterial',function(){ return this._materials[0]; },function(value){ var lastValue=this._materials[0]; if (lastValue!==value){ this._materials[0]=value; this._materialsInstance[0]=false; this._changeMaterialReference(lastValue,value); this.event(/*laya.events.Event.MATERIAL_CHANGED*/"materialchanged",[this,0,value]); } }); /** *设置光照贴图的索引。 *@param value 光照贴图的索引。 */ /** *获取光照贴图的索引。 *@return 光照贴图的索引。 */ __getset(0,__proto,'lightmapIndex',function(){ return this._lightmapIndex; },function(value){ this._lightmapIndex=value; this._applyLightMapParams(); }); /** *设置光照贴图的缩放和偏移。 *@param 光照贴图的缩放和偏移。 */ /** *获取光照贴图的缩放和偏移。 *@return 光照贴图的缩放和偏移。 */ __getset(0,__proto,'lightmapScaleOffset',function(){ return this._lightmapScaleOffset; },function(value){ this._lightmapScaleOffset=value; this._setShaderValueColor(/*laya.d3.core.RenderableSprite3D.LIGHTMAPSCALEOFFSET*/2,value); this._addShaderDefine(RenderableSprite3D.SHADERDEFINE_SCALEOFFSETLIGHTINGMAPUV); }); /** *设置是否可用。 *@param value 是否可用。 */ /** *获取是否可用。 *@return 是否可用。 */ __getset(0,__proto,'enable',function(){ return this._enable; },function(value){ this._enable=value; this.event(/*laya.events.Event.ENABLE_CHANGED*/"enablechanged",[this,value]); }); /** *设置实例材质列表。 *@param value 实例材质列表。 */ /** *获取潜拷贝实例材质列表,第一次使用会拷贝实例对象。 *@return 浅拷贝实例材质列表。 */ __getset(0,__proto,'materials',function(){ for (var i=0,n=this._materials.length;i < n;i++){ if (!this._materialsInstance[i]){ var insMat=this._getInstanceMaterial(this._materials[i],i); this.event(/*laya.events.Event.MATERIAL_CHANGED*/"materialchanged",[this,i,insMat]); } } return this._materials.slice(); },function(value){ this.sharedMaterials=value; }); /** *设置材质列表。 *@param value 材质列表。 */ /** *获取浅拷贝材质列表。 *@return 浅拷贝材质列表。 */ __getset(0,__proto,'sharedMaterials',function(){ var materials=this._materials.slice(); return materials; },function(value){ if (!value) throw new Error("MeshRender: shadredMaterials value can't be null."); var len=value.length; this._materialsInstance.length=len; for (var i=0;i < len;i++){ var lastValue=this._materials[i]; if (lastValue!==value[i]){ this._materialsInstance[i]=false; this._changeMaterialReference(lastValue,value[i]); this.event(/*laya.events.Event.MATERIAL_CHANGED*/"materialchanged",[this,i,value[i]]); } } this._materials=value; }); /** *获取包围盒,只读,不允许修改其值。 *@return 包围盒。 */ __getset(0,__proto,'boundingBox',function(){ if (this._boundingBoxNeedChange){ this._calculateBoundingBox(); this._boundingBoxNeedChange=false; } return this._boundingBox; }); /** *获取包围盒中心,不允许修改其值。 *@return 包围盒中心。 */ __getset(0,__proto,'boundingBoxCenter',function(){ if (this._boundingBoxCenterNeedChange){ var boundBox=this.boundingBox; Vector3.add(boundBox.min,boundBox.max,this._boundingBoxCenter); Vector3.scale(this._boundingBoxCenter,0.5,this._boundingBoxCenter); this._boundingBoxCenterNeedChange=false; } return this._boundingBoxCenter; }); /** *设置是否接收阴影属性 */ /** *获得是否接收阴影属性 */ __getset(0,__proto,'receiveShadow',function(){ return this._receiveShadow; },function(value){ if (this._receiveShadow!==value){ this._receiveShadow=value; if (value) this._addShaderDefine(ParallelSplitShadowMap.SHADERDEFINE_RECEIVE_SHADOW); else this._removeShaderDefine(ParallelSplitShadowMap.SHADERDEFINE_RECEIVE_SHADOW); } }); /** *获取是否已销毁。 *@return 是否已销毁。 */ __getset(0,__proto,'destroyed',function(){ return this._destroyed; }); BaseRender._uniqueIDCounter=0; __static(BaseRender, ['_tempBoundBoxCorners',function(){return this._tempBoundBoxCorners=/*new vector.<>*/[new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3()];},'_greenColor',function(){return this._greenColor=new Vector4(0.0,1.0,0.0,1.0);} ]); return BaseRender; })(EventDispatcher) /** *Transform3D 类用于实现3D变换。 */ //class laya.d3.core.Transform3D extends laya.events.EventDispatcher var Transform3D=(function(_super){ function Transform3D(owner){ /**@private */ this._owner=null; /**@private */ this._localQuaternionUpdate=false; /**@private */ this._locaEulerlUpdate=false; /**@private */ this._localUpdate=false; /**@private */ this._worldUpdate=true; /**@private */ this._positionUpdate=true; /**@private */ this._rotationUpdate=true; /**@private */ this._scaleUpdate=true; /**@private */ this._parent=null; /**@private */ this._childs=null; /**@private */ this._dummy=null; /**变换中心点,注意:该中心点不受变换的影响。*/ this.pivot=null; Transform3D.__super.call(this); this._localPosition=new Vector3(); this._localRotation=new Quaternion(0,0,0,1); this._localScale=new Vector3(1,1,1); this._localRotationEuler=new Vector3(); this._localMatrix=new Matrix4x4(); this._position=new Vector3(); this._rotation=new Quaternion(0,0,0,1); this._scale=new Vector3(1,1,1); this._worldMatrix=new Matrix4x4(); this._forward=new Vector3(); this._up=new Vector3(); this._right=new Vector3(); this._owner=owner; this._childs=[]; } __class(Transform3D,'laya.d3.core.Transform3D',_super); var __proto=Transform3D.prototype; /** *@private */ __proto._updateLocalMatrix=function(){ if (this.pivot && (this.pivot.x!==0 || this.pivot.y!==0 || this.pivot.z!==0)){ var scalePivot=Transform3D._tempVector30; Vector3.multiply(this.pivot,this._localScale,scalePivot); var scaleOffsetPosition=Transform3D._tempVector31; Vector3.subtract(scalePivot,this.pivot,scaleOffsetPosition); var rotationOffsetPosition=Transform3D._tempVector32; var localRot=this.localRotation; Vector3.transformQuat(scalePivot,localRot,rotationOffsetPosition); Vector3.subtract(rotationOffsetPosition,scalePivot,rotationOffsetPosition); var resultLocalPosition=Transform3D._tempVector33; Vector3.subtract(this._localPosition,scaleOffsetPosition,resultLocalPosition); Vector3.subtract(resultLocalPosition,rotationOffsetPosition,resultLocalPosition); Matrix4x4.createAffineTransformation(resultLocalPosition,localRot,this._localScale,this._localMatrix); }else { Matrix4x4.createAffineTransformation(this._localPosition,this.localRotation,this._localScale,this._localMatrix); } } /** *@private */ __proto._onWorldPositionRotationTransform=function(){ if (!this._worldUpdate || !this._positionUpdate || !this._rotationUpdate){ this._worldUpdate=this._positionUpdate=this._rotationUpdate=true; this.event(/*laya.events.Event.WORLDMATRIX_NEEDCHANGE*/"worldmatrixneedchanged"); for (var i=0,n=this._childs.length;i < n;i++) this._childs[i]._onWorldPositionRotationTransform(); } } /** *@private */ __proto._onWorldPositionScaleTransform=function(){ if (!this._worldUpdate || !this._positionUpdate || !this._scaleUpdate){ this._worldUpdate=this._positionUpdate=this._scaleUpdate=true; this.event(/*laya.events.Event.WORLDMATRIX_NEEDCHANGE*/"worldmatrixneedchanged"); for (var i=0,n=this._childs.length;i < n;i++) this._childs[i]._onWorldPositionScaleTransform(); } } /** *@private */ __proto._onWorldPositionTransform=function(){ if (!this._worldUpdate || !this._positionUpdate){ this._worldUpdate=this._positionUpdate=true; this.event(/*laya.events.Event.WORLDMATRIX_NEEDCHANGE*/"worldmatrixneedchanged"); for (var i=0,n=this._childs.length;i < n;i++) this._childs[i]._onWorldPositionTransform(); } } /** *@private */ __proto._onWorldRotationTransform=function(){ if (!this._worldUpdate || !this._rotationUpdate){ this._worldUpdate=this._rotationUpdate=true; this.event(/*laya.events.Event.WORLDMATRIX_NEEDCHANGE*/"worldmatrixneedchanged"); for (var i=0,n=this._childs.length;i < n;i++) this._childs[i]._onWorldPositionRotationTransform(); } } /** *@private */ __proto._onWorldScaleTransform=function(){ if (!this._worldUpdate || !this._scaleUpdate){ this._worldUpdate=this._scaleUpdate=true; this.event(/*laya.events.Event.WORLDMATRIX_NEEDCHANGE*/"worldmatrixneedchanged"); for (var i=0,n=this._childs.length;i < n;i++) this._childs[i]._onWorldPositionScaleTransform(); } } /** *@private */ __proto._onWorldTransform=function(){ if (!this._worldUpdate || !this._positionUpdate || !this._rotationUpdate || !this._scaleUpdate){ this._worldUpdate=this._positionUpdate=this._rotationUpdate=this._scaleUpdate=true; this.event(/*laya.events.Event.WORLDMATRIX_NEEDCHANGE*/"worldmatrixneedchanged"); for (var i=0,n=this._childs.length;i < n;i++) this._childs[i]._onWorldTransform(); } } /** *平移变换。 *@param translation 移动距离。 *@param isLocal 是否局部空间。 */ __proto.translate=function(translation,isLocal){ (isLocal===void 0)&& (isLocal=true); if (isLocal){ Matrix4x4.createFromQuaternion(this.localRotation,Transform3D._tempMatrix0); Vector3.transformCoordinate(translation,Transform3D._tempMatrix0,Transform3D._tempVector30); Vector3.add(this.localPosition,Transform3D._tempVector30,this._localPosition); this.localPosition=this._localPosition; }else { Vector3.add(this.position,translation,this._position); this.position=this._position; } } /** *旋转变换。 *@param rotations 旋转幅度。 *@param isLocal 是否局部空间。 *@param isRadian 是否弧度制。 */ __proto.rotate=function(rotation,isLocal,isRadian){ (isLocal===void 0)&& (isLocal=true); (isRadian===void 0)&& (isRadian=true); var rot; if (isRadian){ rot=rotation; }else { Vector3.scale(rotation,Math.PI / 180.0,Transform3D._tempVector30); rot=Transform3D._tempVector30; } Quaternion.createFromYawPitchRoll(rot.y,rot.x,rot.z,Transform3D._tempQuaternion0); if (isLocal){ Quaternion.multiply(this._localRotation,Transform3D._tempQuaternion0,this._localRotation); this.localRotation=this._localRotation; }else { Quaternion.multiply(Transform3D._tempQuaternion0,this.rotation,this._rotation); this.rotation=this._rotation; } } /** *观察目标位置。 *@param target 观察目标。 *@param up 向上向量。 *@param isLocal 是否局部空间。 */ __proto.lookAt=function(target,up,isLocal){ (isLocal===void 0)&& (isLocal=false); var targetE=target.elements; var eyeE; if (isLocal){ eyeE=this._localPosition.elements; if (Math.abs(eyeE[0]-targetE[0])< MathUtils3D.zeroTolerance && Math.abs(eyeE[1]-targetE[1])< MathUtils3D.zeroTolerance && Math.abs(eyeE[2]-targetE[2])< MathUtils3D.zeroTolerance) return; Quaternion.lookAt(this._localPosition,target,up,this._localRotation); this._localRotation.invert(this._localRotation); this.localRotation=this._localRotation; }else { var worldPosition=this.position; eyeE=worldPosition.elements; if (Math.abs(eyeE[0]-targetE[0])< MathUtils3D.zeroTolerance && Math.abs(eyeE[1]-targetE[1])< MathUtils3D.zeroTolerance && Math.abs(eyeE[2]-targetE[2])< MathUtils3D.zeroTolerance) return; Quaternion.lookAt(worldPosition,target,up,this._rotation); this._rotation.invert(this._rotation); this.rotation=this._rotation; } } /** *@private */ __getset(0,__proto,'_isFrontFaceInvert',function(){ var scale=this.scale; var isInvert=scale.x < 0; (scale.y < 0)&& (isInvert=!isInvert); (scale.z < 0)&& (isInvert=!isInvert); return isInvert; }); /** *获取所属精灵。 */ __getset(0,__proto,'owner',function(){ return this._owner; }); /** *设置局部旋转。 *@param value 局部旋转。 */ /** *获取局部旋转。 *@return 局部旋转。 */ __getset(0,__proto,'localRotation',function(){ if (this._localQuaternionUpdate){ var eulerE=this._localRotationEuler.elements; Quaternion.createFromYawPitchRoll(eulerE[1] / Transform3D._angleToRandin,eulerE[0] / Transform3D._angleToRandin,eulerE[2] / Transform3D._angleToRandin,this._localRotation); } return this._localRotation; },function(value){ this._localRotation=value; this._localRotation.normalize(this._localRotation); this._locaEulerlUpdate=true; this._localQuaternionUpdate=false; this._localUpdate=true; if (this.pivot && (this.pivot.x!==0 || this.pivot.y!==0 || this.pivot.z!==0)) this._onWorldPositionRotationTransform(); else this._onWorldRotationTransform(); }); /** *设置世界矩阵。 *@param value 世界矩阵。 */ /** *获取世界矩阵。 *@return 世界矩阵。 */ __getset(0,__proto,'worldMatrix',function(){ if (this._worldUpdate){ if (this._parent !=null) Matrix4x4.multiply(this._parent.worldMatrix,this.localMatrix,this._worldMatrix); else this.localMatrix.cloneTo(this._worldMatrix); this._worldUpdate=false; } return this._worldMatrix; },function(value){ if (this._parent===null){ value.cloneTo(this._localMatrix); }else { this._parent.worldMatrix.invert(this._localMatrix); Matrix4x4.multiply(this._localMatrix,value,this._localMatrix); } this.localMatrix=this._localMatrix; this._worldMatrix=value; this._worldUpdate=false; }); /** *获取世界矩阵是否需要更新。 *@return 世界矩阵是否需要更新。 */ __getset(0,__proto,'worldNeedUpdate',function(){ return this._worldUpdate; }); /** *设置局部矩阵。 *@param value 局部矩阵。 */ /** *获取局部矩阵。 *@return 局部矩阵。 */ __getset(0,__proto,'localMatrix',function(){ if (this._localUpdate){ this._updateLocalMatrix(); this._localUpdate=false; } return this._localMatrix; },function(value){ this._localMatrix=value; this._localMatrix.decomposeTransRotScale(this._localPosition,this._localRotation,this._localScale); this._localUpdate=false; this._onWorldTransform(); }); /** *设置关联虚拟变换。 *@param value 虚拟变换。 */ /** *获取关联虚拟变换。 *@return 虚拟变换。 */ __getset(0,__proto,'dummy',function(){ return this._dummy; },function(value){ if (this._dummy!==value){ (this._dummy)&& (this._dummy._entity=null); (value)&& (value._entity=this); this._dummy=value; } }); /** *设置局部位置。 *@param value 局部位置。 */ /** *获取局部位置。 *@return 局部位置。 */ __getset(0,__proto,'localPosition',function(){ return this._localPosition; },function(value){ this._localPosition=value; this._localUpdate=true; this._onWorldPositionTransform(); }); /** *设置世界位置。 *@param value 世界位置。 */ /** *获取世界位置。 *@return 世界位置。 */ __getset(0,__proto,'position',function(){ if (this._positionUpdate){ if (this._parent !=null){ var parentPosition=this._parent.position; Vector3.multiply(this._localPosition,this._parent.scale,Transform3D._tempVector30); Vector3.transformQuat(Transform3D._tempVector30,this._parent.rotation,Transform3D._tempVector30); Vector3.add(parentPosition,Transform3D._tempVector30,this._position); }else { this._localPosition.cloneTo(this._position); } this._positionUpdate=false; } return this._position; },function(value){ if (this._parent !=null){ Vector3.subtract(value,this._parent.position,this._localPosition); var parentScaleE=this._parent.scale.elements; var psX=parentScaleE[0],psY=parentScaleE[1],psZ=parentScaleE[2]; if (psX!==1.0 || psY!==1.0 || psZ!==1.0){ var invertScale=Transform3D._tempVector30; var invertScaleE=invertScale.elements; invertScaleE[0]=1.0 / psX; invertScaleE[1]=1.0 / psY; invertScaleE[2]=1.0 / psZ; Vector3.multiply(this._localPosition,invertScale,this._localPosition); }; var parentRotation=this._parent.rotation; parentRotation.invert(Transform3D._tempQuaternion0); Vector3.transformQuat(this._localPosition,Transform3D._tempQuaternion0,this._localPosition); }else { value.cloneTo(this._localPosition); } this.localPosition=this._localPosition; this._position=value; this._positionUpdate=false; }); /** *设置局部缩放。 *@param value 局部缩放。 */ /** *获取局部缩放。 *@return 局部缩放。 */ __getset(0,__proto,'localScale',function(){ return this._localScale; },function(value){ this._localScale=value; this._localUpdate=true; if (this.pivot && (this.pivot.x!==0 || this.pivot.y!==0 || this.pivot.z!==0)) this._onWorldPositionScaleTransform(); else this._onWorldScaleTransform(); }); /** *设置局部空间的旋转角度。 *@param value 欧拉角的旋转值,顺序为x、y、z。 */ /** *获取局部空间的旋转角度。 *@return 欧拉角的旋转值,顺序为x、y、z。 */ __getset(0,__proto,'localRotationEuler',function(){ if (this._locaEulerlUpdate){ this._localRotation.getYawPitchRoll(Transform3D._tempVector30); var eulerE=Transform3D._tempVector30.elements; var localRotationEulerE=this._localRotationEuler.elements; localRotationEulerE[0]=eulerE[1] *Transform3D._angleToRandin; localRotationEulerE[1]=eulerE[0] *Transform3D._angleToRandin; localRotationEulerE[2]=eulerE[2] *Transform3D._angleToRandin; } return this._localRotationEuler; },function(value){ this._localRotationEuler=value; this._locaEulerlUpdate=false; this._localQuaternionUpdate=true; this._localUpdate=true; if (this.pivot && (this.pivot.x!==0 || this.pivot.y!==0 || this.pivot.z!==0)) this._onWorldPositionRotationTransform(); else this._onWorldRotationTransform(); }); /** *设置世界旋转。 *@param value 世界旋转。 */ /** *获取世界旋转。 *@return 世界旋转。 */ __getset(0,__proto,'rotation',function(){ if (this._rotationUpdate){ if (this._parent !=null) Quaternion.multiply(this._parent.rotation,this.localRotation,this._rotation); else this.localRotation.cloneTo(this._rotation); this._rotationUpdate=false; } return this._rotation; },function(value){ if (this._parent !=null){ this._parent.rotation.invert(Transform3D._tempQuaternion0); Quaternion.multiply(value,Transform3D._tempQuaternion0,this._localRotation); }else { value.cloneTo(this._localRotation); } this.localRotation=this._localRotation; this._rotation=value; this._rotationUpdate=false; }); /** *设置世界缩放。 *@param value 世界缩放。 */ /** *获取世界缩放。 *@return 世界缩放。 */ __getset(0,__proto,'scale',function(){ if (!this._scaleUpdate) return this._scale; if (this._parent!==null) Vector3.multiply(this._parent.scale,this._localScale,this._scale); else this._localScale.cloneTo(this._scale); this._scaleUpdate=false; return this._scale; },function(value){ if (this._parent!==null){ var pScaleE=this._parent.scale.elements; var invPScaleE=Transform3D._tempVector30.elements; invPScaleE[0]=1.0 / pScaleE[0]; invPScaleE[1]=1.0 / pScaleE[1]; invPScaleE[2]=1.0 / pScaleE[2]; Vector3.multiply(value,Transform3D._tempVector30,this._localScale); }else { value.cloneTo(this._localScale); } this.localScale=this._localScale; this._scale=value; this._scaleUpdate=false; }); /** *设置局部空间的旋转角度。 *@param 欧拉角的旋转值,顺序为x、y、z。 */ __getset(0,__proto,'rotationEuler',null,function(value){ Quaternion.createFromYawPitchRoll(value.y,value.x,value.z,this._rotation); this.rotation=this._rotation; }); /** *获取向前方向。 *@return 向前方向。 */ __getset(0,__proto,'forward',function(){ var worldMatElem=this.worldMatrix.elements; this._forward.elements[0]=-worldMatElem[8]; this._forward.elements[1]=-worldMatElem[9]; this._forward.elements[2]=-worldMatElem[10]; return this._forward; }); /** *获取向上方向。 *@return 向上方向。 */ __getset(0,__proto,'up',function(){ var worldMatElem=this.worldMatrix.elements; this._up.elements[0]=worldMatElem[4]; this._up.elements[1]=worldMatElem[5]; this._up.elements[2]=worldMatElem[6]; return this._up; }); /** *获取向右方向。 *@return 向右方向。 */ __getset(0,__proto,'right',function(){ var worldMatElem=this.worldMatrix.elements; this._right.elements[0]=worldMatElem[0]; this._right.elements[1]=worldMatElem[1]; this._right.elements[2]=worldMatElem[2]; return this._right; }); /** *设置父3D变换。 *@param value 父3D变换。 */ /** *获取父3D变换。 *@return 父3D变换。 */ __getset(0,__proto,'parent',function(){ return this._parent; },function(value){ if (this._parent!==value){ if (this._parent){ var parentChilds=this._parent._childs; var index=parentChilds.indexOf(this); parentChilds.splice(index,1); } if (value){ value._childs.push(this); (value)&& (this._onWorldTransform()); } this._parent=value; } }); __static(Transform3D, ['_tempVector30',function(){return this._tempVector30=new Vector3();},'_tempVector31',function(){return this._tempVector31=new Vector3();},'_tempVector32',function(){return this._tempVector32=new Vector3();},'_tempVector33',function(){return this._tempVector33=new Vector3();},'_tempQuaternion0',function(){return this._tempQuaternion0=new Quaternion();},'_tempMatrix0',function(){return this._tempMatrix0=new Matrix4x4();},'_angleToRandin',function(){return this._angleToRandin=180 / Math.PI;} ]); return Transform3D; })(EventDispatcher) /** *TransformUV 类用于实现UV变换。 */ //class laya.d3.core.TransformUV extends laya.events.EventDispatcher var TransformUV=(function(_super){ function TransformUV(){ /**@private */ this._rotation=0; /**@private */ //this._tiling=null; /**@private */ this._matNeedUpdte=false; TransformUV.__super.call(this); this._matrix=new Matrix4x4(); this._offset=new Vector2(); this._tiling=new Vector2(1.0,1.0); } __class(TransformUV,'laya.d3.core.TransformUV',_super); var __proto=TransformUV.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *@private */ __proto._updateMatrix=function(){ TransformUV._tempOffsetV3.elements[0]=this._offset.x; TransformUV._tempOffsetV3.elements[1]=this._offset.y; Quaternion.createFromYawPitchRoll(0,0,this._rotation,TransformUV._tempRotationQua); TransformUV._tempTitlingV3.elements[0]=this._tiling.x; TransformUV._tempTitlingV3.elements[1]=this._tiling.y; Matrix4x4.createAffineTransformation(TransformUV._tempOffsetV3,TransformUV._tempRotationQua,TransformUV._tempTitlingV3,this._matrix); } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ destObject._matrix=this._matrix.clone(); destObject._offset=this._offset.clone(); destObject._rotation=this._rotation; destObject._tiling=this._tiling.clone(); } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var dest=/*__JS__ */new this.constructor(); this.cloneTo(dest); return dest; } /** *获取变换矩阵。 *@return 变换矩阵。 */ __getset(0,__proto,'matrix',function(){ if (this._matNeedUpdte){ this._updateMatrix(); this._matNeedUpdte=false; } return this._matrix; }); /** *设置平铺次数。 *@param value 平铺次数。 */ /** *获取平铺次数。 *@return 平铺次数。 */ __getset(0,__proto,'tiling',function(){ return this._tiling; },function(value){ this._tiling=value; this._matNeedUpdte=true; }); /** *设置偏移。 *@param value 偏移。 */ /** *获取偏移。 *@return 偏移。 */ __getset(0,__proto,'offset',function(){ return this._offset; },function(value){ this._offset=value; this._matNeedUpdte=true; }); /** *设置旋转。 *@param value 旋转。 */ /** *获取旋转。 *@return 旋转。 */ __getset(0,__proto,'rotation',function(){ return this._rotation; },function(value){ this._rotation=value; this._matNeedUpdte=true; }); __static(TransformUV, ['_tempOffsetV3',function(){return this._tempOffsetV3=new Vector3(0,0,0);},'_tempRotationQua',function(){return this._tempRotationQua=new Quaternion();},'_tempTitlingV3',function(){return this._tempTitlingV3=new Vector3(1,1,1);} ]); return TransformUV; })(EventDispatcher) /** *CollsionManager 类用于碰撞管理器。 */ //class laya.d3.utils.CollisionManager extends laya.events.EventDispatcher var CollisionManager=(function(_super){ /** *创建一个新的 CollsionManager 实例。 */ function CollisionManager(){ CollisionManager.__super.call(this); } __class(CollisionManager,'laya.d3.utils.CollisionManager',_super); CollisionManager._onTrigger=function(rigidCol,receiveCol,rigidScripts,receiveScripts,bothRigid){ var i=0,n=0; var rigidID=rigidCol.id; var receiveID=receiveCol.id; if (!rigidCol._ignoreCollisonMap[receiveID]){ var colMan=Physics.collisionManager; var needTest=rigidCol._runtimeCollisonTestMap[receiveID]; if (needTest !=null){ if (needTest){ if (rigidCol._collisonTo(receiveCol)){ if (rigidCol._runtimeCollisonMap[receiveID]){ for (i=0,n=rigidScripts.length;i < n;i++) rigidScripts[i].onTriggerStay(receiveCol); for (i=0,n=receiveScripts.length;i < n;i++) receiveScripts[i].onTriggerStay(rigidCol); colMan.event(/*laya.events.Event.TRIGGER_STAY*/"triggerstay",[rigidCol,receiveCol]); }else { rigidCol._runtimeCollisonMap[receiveID]=receiveCol; rigidCol._runtimeCollisonTestMap[receiveID]=false; receiveCol._runtimeCollisonMap[rigidID]=rigidCol; if (bothRigid) receiveCol._runtimeCollisonTestMap[rigidID]=false; for (i=0,n=rigidScripts.length;i < n;i++) rigidScripts[i].onTriggerEnter(receiveCol); for (i=0,n=receiveScripts.length;i < n;i++) receiveScripts[i].onTriggerEnter(rigidCol); colMan.event(/*laya.events.Event.TRIGGER_ENTER*/"triggerenter",[rigidCol,receiveCol]); } }else { var rigidMap=rigidCol._runtimeCollisonMap; if (rigidMap[receiveID]){ delete rigidMap[receiveID]; delete rigidCol._runtimeCollisonTestMap[receiveID]; delete receiveCol._runtimeCollisonMap[rigidID]; if (bothRigid) delete receiveCol._runtimeCollisonTestMap[rigidID]; for (i=0,n=rigidScripts.length;i < n;i++) rigidScripts[i].onTriggerExit(receiveCol); for (i=0,n=receiveScripts.length;i < n;i++) receiveScripts[i].onTriggerExit(rigidCol); colMan.event(/*laya.events.Event.TRIGGER_EXIT*/"triggerexit",[rigidCol,receiveCol]); } } }else { for (i=0,n=rigidScripts.length;i < n;i++) rigidScripts[i].onTriggerStay(receiveCol); for (i=0,n=receiveScripts.length;i < n;i++) receiveScripts[i].onTriggerStay(rigidCol); colMan.event(/*laya.events.Event.TRIGGER_STAY*/"triggerstay",[rigidCol,receiveCol]); } }else { if (rigidCol._collisonTo(receiveCol)){ rigidCol._runtimeCollisonMap[receiveID]=receiveCol; rigidCol._runtimeCollisonTestMap[receiveID]=false; receiveCol._runtimeCollisonMap[rigidID]=rigidCol; if (bothRigid) receiveCol._runtimeCollisonTestMap[rigidID]=false; for (i=0,n=rigidScripts.length;i < n;i++) rigidScripts[i].onTriggerEnter(receiveCol); for (i=0,n=receiveScripts.length;i < n;i++) receiveScripts[i].onTriggerEnter(rigidCol); colMan.event(/*laya.events.Event.TRIGGER_ENTER*/"triggerenter",[rigidCol,receiveCol]); } } } } CollisionManager._triggerCollision=function(){ var colList=Layer._collsionTestList; var colCount=colList.length; var colMat=Physics._layerCollsionMatrix; for (var i=0;i < colCount;i++){ var row=colList[i]; var rowLayer=Layer.getLayerByNumber(row); var rowColliders=rowLayer._colliders; var rowRigOffset=rowLayer._nonRigidbodyOffset; for (var j=colCount-1;j >=i;j--){ var col=colList[j]; var test=colMat[row][(/*laya.d3.core.Layer.maxCount*/31-1)-col]; if (test){ var k=0,c=0,x=0,z=0; var rowCol,colCol,rowScripts; var colLayer=Layer.getLayerByNumber(col); var colColliders=colLayer._colliders; var colRigOffset=colLayer._nonRigidbodyOffset; if (rowLayer!==colLayer){ for (k=0;k < rowRigOffset;k++){ rowCol=rowColliders[k]; if (rowCol.enable){ rowScripts=rowCol.owner._scripts; for (x=0,z=colRigOffset;x < z;x++){ colCol=colColliders[x]; (colCol.enable)&& (CollisionManager._onTrigger(rowCol,colCol,rowScripts,colCol.owner._scripts,true)); } for (x=colRigOffset,z=colColliders.length;x < z;x++){ colCol=colColliders[x]; (colCol.enable)&& (CollisionManager._onTrigger(rowCol,colCol,rowScripts,colCol.owner._scripts,false)); } } } for (k=rowRigOffset,c=rowColliders.length;k < c;k++){ rowCol=rowColliders[k]; if (rowCol.enable){ rowScripts=rowCol.owner._scripts; for (x=0,z=colLayer._nonRigidbodyOffset;x < z;x++){ colCol=colColliders[x]; (colCol.enable)&& (CollisionManager._onTrigger(colCol,rowCol,rowScripts,colCol.owner._scripts,false)); } } } }else { for (k=0;k < rowRigOffset;k++){ rowCol=rowColliders[k]; if (rowCol.enable){ rowScripts=rowCol.owner._scripts; for (x=k+1,z=rowRigOffset;x < z;x++){ colCol=colColliders[x]; (colCol.enable)&& (CollisionManager._onTrigger(rowCol,colCol,rowScripts,colCol.owner._scripts,true)); } for (x=rowRigOffset,z=rowColliders.length;x < z;x++){ colCol=colColliders[x]; (colCol.enable)&& (CollisionManager._onTrigger(rowCol,colCol,rowScripts,colCol.owner._scripts,false)); } } } } } } } } return CollisionManager; })(EventDispatcher) /** *SplineCurvePosition 类用于通过顶点创建闪光插值。 */ //class laya.d3.core.glitter.SplineCurvePosition extends laya.d3.core.glitter.SplineCurvePositionVelocity var SplineCurvePosition=(function(_super){ /** *创建一个 SplineCurvePosition 实例。 */ function SplineCurvePosition(){ SplineCurvePosition.__super.call(this); } __class(SplineCurvePosition,'laya.d3.core.glitter.SplineCurvePosition',_super); var __proto=SplineCurvePosition.prototype; /** *@private *计算速度。 */ __proto._CalcVelocity=function(left,right,out){ Vector3.subtract(left,right,out); Vector3.scale(out,0.5,out); } /** *初始化插值所需信息。 *@param lastPosition0 顶点0的上次位置。 *@param position0 顶点0的位置。 *@param lastPosition1 顶点1的上次位置。 *@param position1 顶点1的位置。 */ __proto.Init=function(lastPosition0,position0,lastPosition1,position1){ this._CalcVelocity(position0,lastPosition0,this._tempVector30); this._CalcVelocity(position1,lastPosition1,this._tempVector31); _super.prototype.Init.call(this,position0,this._tempVector30,position1,this._tempVector31); } return SplineCurvePosition; })(SplineCurvePositionVelocity) /** *BoxShape 类用于创建球形粒子形状。 */ //class laya.d3.core.particleShuriKen.module.shape.BoxShape extends laya.d3.core.particleShuriKen.module.shape.BaseShape var BoxShape=(function(_super){ function BoxShape(){ /**发射器X轴长度。*/ this.x=NaN; /**发射器Y轴长度。*/ this.y=NaN; /**发射器Z轴长度。*/ this.z=NaN; BoxShape.__super.call(this); this.x=1.0; this.y=1.0; this.z=1.0; this.randomDirection=false; } __class(BoxShape,'laya.d3.core.particleShuriKen.module.shape.BoxShape',_super); var __proto=BoxShape.prototype; /** *@inheritDoc */ __proto._getShapeBoundBox=function(boundBox){ var minE=boundBox.min.elements; minE[0]=-this.x *0.5; minE[1]=-this.y *0.5; minE[2]=-this.z *0.5; var maxE=boundBox.max.elements; maxE[0]=this.x *0.5; maxE[1]=this.y *0.5; maxE[2]=this.z *0.5; } /** *@inheritDoc */ __proto._getSpeedBoundBox=function(boundBox){ var minE=boundBox.min.elements; minE[0]=0.0; minE[1]=0.0; minE[2]=0.0; var maxE=boundBox.max.elements; maxE[0]=0.0; maxE[1]=1.0; maxE[2]=0.0; } /** *用于生成粒子初始位置和方向。 *@param position 粒子位置。 *@param direction 粒子方向。 */ __proto.generatePositionAndDirection=function(position,direction,rand,randomSeeds){ var rpE=position.elements; var rdE=direction.elements; if (rand){ rand.seed=randomSeeds[16]; ShapeUtils._randomPointInsideHalfUnitBox(position,rand); randomSeeds[16]=rand.seed; }else { ShapeUtils._randomPointInsideHalfUnitBox(position); } rpE[0]=this.x *rpE[0]; rpE[1]=this.y *rpE[1]; rpE[2]=this.z *rpE[2]; if (this.randomDirection){ if (rand){ rand.seed=randomSeeds[17]; ShapeUtils._randomPointUnitSphere(direction,rand); randomSeeds[17]=rand.seed; }else { ShapeUtils._randomPointUnitSphere(direction); } }else { rdE[0]=0.0; rdE[1]=0.0; rdE[2]=1.0; } } __proto.cloneTo=function(destObject){ _super.prototype.cloneTo.call(this,destObject); var destShape=destObject; destShape.x=this.x; destShape.y=this.y; destShape.z=this.z; destShape.randomDirection=this.randomDirection; } return BoxShape; })(BaseShape) /** *CircleShape 类用于创建环形粒子形状。 */ //class laya.d3.core.particleShuriKen.module.shape.CircleShape extends laya.d3.core.particleShuriKen.module.shape.BaseShape var CircleShape=(function(_super){ function CircleShape(){ /**发射器半径。*/ this.radius=NaN; /**环形弧度。*/ this.arc=NaN; /**从边缘发射。*/ this.emitFromEdge=false; CircleShape.__super.call(this); this.radius=1.0; this.arc=360.0 / 180.0 *Math.PI; this.emitFromEdge=false; this.randomDirection=false; } __class(CircleShape,'laya.d3.core.particleShuriKen.module.shape.CircleShape',_super); var __proto=CircleShape.prototype; /** *@inheritDoc */ __proto._getShapeBoundBox=function(boundBox){ var minE=boundBox.min.elements; minE[0]=minE[2]=-this.radius; minE[1]=0; var maxE=boundBox.max.elements; maxE[0]=maxE[2]=this.radius; maxE[1]=0; } /** *@inheritDoc */ __proto._getSpeedBoundBox=function(boundBox){ var minE=boundBox.min.elements; minE[0]=minE[1]=-1; minE[2]=0; var maxE=boundBox.max.elements; maxE[0]=maxE[1]=1; maxE[2]=0; } /** *用于生成粒子初始位置和方向。 *@param position 粒子位置。 *@param direction 粒子方向。 */ __proto.generatePositionAndDirection=function(position,direction,rand,randomSeeds){ var rpE=position.elements; var positionPointE=CircleShape._tempPositionPoint.elements; if (rand){ rand.seed=randomSeeds[16]; if (this.emitFromEdge) ShapeUtils._randomPointUnitArcCircle(this.arc,CircleShape._tempPositionPoint,rand); else ShapeUtils._randomPointInsideUnitArcCircle(this.arc,CircleShape._tempPositionPoint,rand); randomSeeds[16]=rand.seed; }else { if (this.emitFromEdge) ShapeUtils._randomPointUnitArcCircle(this.arc,CircleShape._tempPositionPoint); else ShapeUtils._randomPointInsideUnitArcCircle(this.arc,CircleShape._tempPositionPoint); } rpE[0]=-positionPointE[0]; rpE[1]=positionPointE[1]; rpE[2]=0; Vector3.scale(position,this.radius,position); if (this.randomDirection){ if (rand){ rand.seed=randomSeeds[17]; ShapeUtils._randomPointUnitSphere(direction,rand); randomSeeds[17]=rand.seed; }else { ShapeUtils._randomPointUnitSphere(direction); } }else { position.cloneTo(direction); } } __proto.cloneTo=function(destObject){ _super.prototype.cloneTo.call(this,destObject); var destShape=destObject; destShape.radius=this.radius; destShape.arc=this.arc; destShape.emitFromEdge=this.emitFromEdge; destShape.randomDirection=this.randomDirection; } __static(CircleShape, ['_tempPositionPoint',function(){return this._tempPositionPoint=new Vector2();} ]); return CircleShape; })(BaseShape) /** *ConeShape 类用于创建锥形粒子形状。 */ //class laya.d3.core.particleShuriKen.module.shape.ConeShape extends laya.d3.core.particleShuriKen.module.shape.BaseShape var ConeShape=(function(_super){ function ConeShape(){ /**发射角度。*/ this.angle=NaN; /**发射器半径。*/ this.radius=NaN; /**椎体长度。*/ this.length=NaN; /**发射类型,0为Base,1为BaseShell,2为Volume,3为VolumeShell。*/ this.emitType=0; ConeShape.__super.call(this); this.angle=25.0 / 180.0 *Math.PI; this.radius=1.0; this.length=5.0; this.emitType=0; this.randomDirection=false; } __class(ConeShape,'laya.d3.core.particleShuriKen.module.shape.ConeShape',_super); var __proto=ConeShape.prototype; /** *@inheritDoc */ __proto._getShapeBoundBox=function(boundBox){ var coneRadius2=this.radius+this.length *Math.sin(this.angle); var coneLength=this.length *Math.cos(this.angle); var minE=boundBox.min.elements; minE[0]=minE[1]=-coneRadius2; minE[2]=0; var maxE=boundBox.max.elements; maxE[0]=maxE[1]=coneRadius2; maxE[2]=coneLength; } /** *@inheritDoc */ __proto._getSpeedBoundBox=function(boundBox){ var sinA=Math.sin(this.angle); var minE=boundBox.min.elements; minE[0]=minE[1]=-sinA; minE[2]=0; var maxE=boundBox.max.elements; maxE[0]=minE[1]=sinA; maxE[2]=1; } /** *用于生成粒子初始位置和方向。 *@param position 粒子位置。 *@param direction 粒子方向。 */ __proto.generatePositionAndDirection=function(position,direction,rand,randomSeeds){ var rpE=position.elements; var rdE=direction.elements; var positionPointE=ConeShape._tempPositionPoint.elements; var positionX=NaN; var positionY=NaN; var directionPointE; var dirCosA=Math.cos(this.angle); var dirSinA=Math.sin(this.angle); switch (this.emitType){ case 0: if (rand){ rand.seed=randomSeeds[16]; ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempPositionPoint,rand); randomSeeds[16]=rand.seed; }else { ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempPositionPoint); } positionX=positionPointE[0]; positionY=positionPointE[1]; rpE[0]=positionX *this.radius; rpE[1]=positionY *this.radius; rpE[2]=0; if (this.randomDirection){ if (rand){ rand.seed=randomSeeds[17]; ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempDirectionPoint,rand); randomSeeds[17]=rand.seed; }else { ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempDirectionPoint); } directionPointE=ConeShape._tempDirectionPoint.elements; rdE[0]=directionPointE[0] *dirSinA; rdE[1]=directionPointE[1] *dirSinA; }else { rdE[0]=positionX *dirSinA; rdE[1]=positionY *dirSinA; } rdE[2]=dirCosA; break ; case 1: if (rand){ rand.seed=randomSeeds[16]; ShapeUtils._randomPointUnitCircle(ConeShape._tempPositionPoint,rand); randomSeeds[16]=rand.seed; }else { ShapeUtils._randomPointUnitCircle(ConeShape._tempPositionPoint); } positionX=positionPointE[0]; positionY=positionPointE[1]; rpE[0]=positionX *this.radius; rpE[1]=positionY *this.radius; rpE[2]=0; if (this.randomDirection){ if (rand){ rand.seed=randomSeeds[17]; ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempDirectionPoint,rand); randomSeeds[17]=rand.seed; }else { ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempDirectionPoint); } directionPointE=ConeShape._tempDirectionPoint.elements; rdE[0]=directionPointE[0] *dirSinA; rdE[1]=directionPointE[1] *dirSinA; }else { rdE[0]=positionX *dirSinA; rdE[1]=positionY *dirSinA; } rdE[2]=dirCosA; break ; case 2: if (rand){ rand.seed=randomSeeds[16]; ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempPositionPoint,rand); }else { ShapeUtils._randomPointInsideUnitCircle(ConeShape._tempPositionPoint); } positionX=positionPointE[0]; positionY=positionPointE[1]; rpE[0]=positionX *this.radius; rpE[1]=positionY *this.radius; rpE[2]=0; rdE[0]=positionX *dirSinA; rdE[1]=positionY *dirSinA; rdE[2]=dirCosA; Vector3.normalize(direction,direction); if (rand){ Vector3.scale(direction,this.length *rand.getFloat(),direction); randomSeeds[16]=rand.seed; }else { Vector3.scale(direction,this.length *Math.random(),direction); } Vector3.add(position,direction,position); if (this.randomDirection){ if (rand){ rand.seed=randomSeeds[17]; ShapeUtils._randomPointUnitSphere(direction,rand); randomSeeds[17]=rand.seed; }else { ShapeUtils._randomPointUnitSphere(direction); } } break ; case 3: if (rand){ rand.seed=randomSeeds[16]; ShapeUtils._randomPointUnitCircle(ConeShape._tempPositionPoint,rand); }else { ShapeUtils._randomPointUnitCircle(ConeShape._tempPositionPoint); } positionX=positionPointE[0]; positionY=positionPointE[1]; rpE[0]=positionX *this.radius; rpE[1]=positionY *this.radius; rpE[2]=0; rdE[0]=positionX *dirSinA; rdE[1]=positionY *dirSinA; rdE[2]=dirCosA; Vector3.normalize(direction,direction); if (rand){ Vector3.scale(direction,this.length *rand.getFloat(),direction); randomSeeds[16]=rand.seed; }else { Vector3.scale(direction,this.length *Math.random(),direction); } Vector3.add(position,direction,position); if (this.randomDirection){ if (rand){ rand.seed=randomSeeds[17]; ShapeUtils._randomPointUnitSphere(direction,rand); randomSeeds[17]=rand.seed; }else { ShapeUtils._randomPointUnitSphere(direction); } } break ; default : throw new Error("ConeShape:emitType is invalid."); } } __proto.cloneTo=function(destObject){ _super.prototype.cloneTo.call(this,destObject); var destShape=destObject; destShape.angle=this.angle; destShape.radius=this.radius; destShape.length=this.length; destShape.emitType=this.emitType; destShape.randomDirection=this.randomDirection; } __static(ConeShape, ['_tempPositionPoint',function(){return this._tempPositionPoint=new Vector2();},'_tempDirectionPoint',function(){return this._tempDirectionPoint=new Vector2();} ]); return ConeShape; })(BaseShape) /** *HemisphereShape 类用于创建半球形粒子形状。 */ //class laya.d3.core.particleShuriKen.module.shape.HemisphereShape extends laya.d3.core.particleShuriKen.module.shape.BaseShape var HemisphereShape=(function(_super){ function HemisphereShape(){ /**发射器半径。*/ this.radius=NaN; /**从外壳发射。*/ this.emitFromShell=false; HemisphereShape.__super.call(this); this.radius=1.0; this.emitFromShell=false; this.randomDirection=false; } __class(HemisphereShape,'laya.d3.core.particleShuriKen.module.shape.HemisphereShape',_super); var __proto=HemisphereShape.prototype; /** *@inheritDoc */ __proto._getShapeBoundBox=function(boundBox){ var minE=boundBox.min.elements; minE[0]=minE[1]=minE[2]=-this.radius; var maxE=boundBox.max.elements; maxE[0]=maxE[1]=this.radius; maxE[2]=0; } /** *@inheritDoc */ __proto._getSpeedBoundBox=function(boundBox){ var minE=boundBox.min.elements; minE[0]=minE[1]=-1; minE[2]=0; var maxE=boundBox.max.elements; maxE[0]=maxE[1]=maxE[2]=1; } /** *用于生成粒子初始位置和方向。 *@param position 粒子位置。 *@param direction 粒子方向。 */ __proto.generatePositionAndDirection=function(position,direction,rand,randomSeeds){ var rpE=position.elements; if (rand){ rand.seed=randomSeeds[16]; if (this.emitFromShell) ShapeUtils._randomPointUnitSphere(position,rand); else ShapeUtils._randomPointInsideUnitSphere(position,rand); randomSeeds[16]=rand.seed; }else { if (this.emitFromShell) ShapeUtils._randomPointUnitSphere(position); else ShapeUtils._randomPointInsideUnitSphere(position); } Vector3.scale(position,this.radius,position); var z=rpE[2]; (z < 0.0)&& (rpE[2]=z *-1.0); if (this.randomDirection){ if (rand){ rand.seed=randomSeeds[17]; ShapeUtils._randomPointUnitSphere(direction,rand); randomSeeds[17]=rand.seed; }else { ShapeUtils._randomPointUnitSphere(direction); } }else { position.cloneTo(direction); } } __proto.cloneTo=function(destObject){ _super.prototype.cloneTo.call(this,destObject); var destShape=destObject; destShape.radius=this.radius; destShape.emitFromShell=this.emitFromShell; destShape.randomDirection=this.randomDirection; } return HemisphereShape; })(BaseShape) /** *SphereShape 类用于创建球形粒子形状。 */ //class laya.d3.core.particleShuriKen.module.shape.SphereShape extends laya.d3.core.particleShuriKen.module.shape.BaseShape var SphereShape=(function(_super){ function SphereShape(){ /**发射器半径。*/ this.radius=NaN; /**从外壳发射。*/ this.emitFromShell=false; SphereShape.__super.call(this); this.radius=1.0; this.emitFromShell=false; this.randomDirection=false; } __class(SphereShape,'laya.d3.core.particleShuriKen.module.shape.SphereShape',_super); var __proto=SphereShape.prototype; /** *@inheritDoc */ __proto._getShapeBoundBox=function(boundBox){ var minE=boundBox.min.elements; minE[0]=minE[1]=minE[2]=-this.radius; var maxE=boundBox.max.elements; maxE[0]=maxE[1]=maxE[2]=this.radius; } /** *@inheritDoc */ __proto._getSpeedBoundBox=function(boundBox){ var minE=boundBox.min.elements; minE[0]=minE[1]=minE[2]=-1; var maxE=boundBox.max.elements; maxE[0]=maxE[1]=maxE[2]=1; } /** *用于生成粒子初始位置和方向。 *@param position 粒子位置。 *@param direction 粒子方向。 */ __proto.generatePositionAndDirection=function(position,direction,rand,randomSeeds){ if (rand){ rand.seed=randomSeeds[16]; if (this.emitFromShell) ShapeUtils._randomPointUnitSphere(position,rand); else ShapeUtils._randomPointInsideUnitSphere(position,rand); randomSeeds[16]=rand.seed; }else { if (this.emitFromShell) ShapeUtils._randomPointUnitSphere(position); else ShapeUtils._randomPointInsideUnitSphere(position); } Vector3.scale(position,this.radius,position); if (this.randomDirection){ if (rand){ rand.seed=randomSeeds[17]; ShapeUtils._randomPointUnitSphere(direction,rand); randomSeeds[17]=rand.seed; }else { ShapeUtils._randomPointUnitSphere(direction); } }else { position.cloneTo(direction); } } __proto.cloneTo=function(destObject){ _super.prototype.cloneTo.call(this,destObject); var destShape=destObject; destShape.radius=this.radius; destShape.emitFromShell=this.emitFromShell; destShape.randomDirection=this.randomDirection; } return SphereShape; })(BaseShape) /** *@private */ //class laya.d3.core.render.SubMeshRenderElement extends laya.d3.core.render.RenderElement var SubMeshRenderElement=(function(_super){ function SubMeshRenderElement(){ /**@private */ this._batchIndexStart=0; /**@private */ this._batchIndexEnd=0; /**@private */ this._skinAnimationDatas=null; SubMeshRenderElement.__super.call(this); } __class(SubMeshRenderElement,'laya.d3.core.render.SubMeshRenderElement',_super); return SubMeshRenderElement; })(RenderElement) /** *@private *ShaderCompile 类用于创建Shader编译类型。 */ //class laya.d3.shader.ShaderCompile3D extends laya.webgl.utils.ShaderCompile var ShaderCompile3D=(function(_super){ function ShaderCompile3D(name,vs,ps,attributeMap,uniformMap,includeFiles){ /**@private */ this._name=NaN; /**@private */ this._attributeMap=null; /**@private */ this._renderElementUniformMap=null; /**@private */ this._materialUniformMap=null; /**@private */ this._spriteUniformMap=null; /**@private */ this._cameraUniformMap=null; /**@private */ this._sceneUniformMap=null; this.sharders=null; /**@private */ this._spriteDefineCounter=3; /**@private */ this._spriteInt2name=[]; /**@private */ this._spriteName2Int={}; /**@private */ this._materialDefineCounter=1; /**@private */ this._materialInt2name=[]; /**@private */ this._materialName2Int={}; this._conchShader=null; this._name=name; this._renderElementUniformMap={}; this._materialUniformMap={}; this._spriteUniformMap={}; this._cameraUniformMap={}; this._sceneUniformMap={}; this.sharders=[]; this._spriteInt2name[ParallelSplitShadowMap.SHADERDEFINE_RECEIVE_SHADOW]="RECEIVESHADOW"; this._spriteInt2name[RenderableSprite3D.SHADERDEFINE_SCALEOFFSETLIGHTINGMAPUV]="SCALEOFFSETLIGHTINGMAPUV"; this._spriteInt2name[RenderableSprite3D.SAHDERDEFINE_LIGHTMAP]="LIGHTMAP"; this._spriteInt2name[SkinnedMeshSprite3D.SHADERDEFINE_BONE]="BONE"; this._materialInt2name[BaseMaterial.SHADERDEFINE_ALPHATEST]="ALPHATEST"; var defineMap={}; ShaderCompile3D.__super.call(this,name,vs,ps,null,defineMap); this._attributeMap=attributeMap; var renderElementUnifCount=0,materialUnifCount=0,spriteUnifCount=0; var key; for (key in uniformMap){ var uniformParam=uniformMap[key]; switch (uniformParam[1]){ case /*laya.d3.shader.Shader3D.PERIOD_RENDERELEMENT*/0: this._renderElementUniformMap[key]=uniformParam[0]; break ; case /*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1: this._materialUniformMap[key]=uniformParam[0]; break ; case /*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2: this._spriteUniformMap[key]=uniformParam[0]; break ; case /*laya.d3.shader.Shader3D.PERIOD_CAMERA*/3: this._cameraUniformMap[key]=uniformParam[0]; break ; case /*laya.d3.shader.Shader3D.PERIOD_SCENE*/4: this._sceneUniformMap[key]=uniformParam[0]; break ; default : throw new Error("ShaderCompile3D: period is unkonw."); } } } __class(ShaderCompile3D,'laya.d3.shader.ShaderCompile3D',_super); var __proto=ShaderCompile3D.prototype; /** *@private */ __proto._definesToNameDic=function(value,int2Name){ var o={}; var d=1; for (var i=0;i < 32;i++){ d=1 << i; if (d > value)break ; if (value & d){ var name=int2Name[d]; name && (o[name]=""); } } return o; } /** *根据宏动态生成shader文件,支持#include?COLOR_FILTER "parts/ColorFilter_ps_logic.glsl";条件嵌入文件 *@param name *@param vs *@param ps *@param define 宏定义,格式:{name:value...} *@return */ __proto.withCompile=function(publicDefine,spriteDefine,materialDefine){ var shader; var spriteDefShaders,materialDefShaders; spriteDefShaders=this.sharders[publicDefine]; if (spriteDefShaders){ materialDefShaders=spriteDefShaders[spriteDefine]; if (materialDefShaders){ shader=materialDefShaders[materialDefine]; if (shader) return shader; }else { materialDefShaders=spriteDefShaders[spriteDefine]=[]; } }else { spriteDefShaders=this.sharders[publicDefine]=[]; materialDefShaders=spriteDefShaders[spriteDefine]=[]; }; var publicDefGroup=this._definesToNameDic(publicDefine,ShaderCompile3D._globalInt2name); var spriteDefGroup=this._definesToNameDic(spriteDefine,this._spriteInt2name); var materialDefGroup=this._definesToNameDic(materialDefine,this._materialInt2name); var key; if (laya.d3.shader.ShaderCompile3D.debugMode){ var publicDefGroupStr=""; for (key in publicDefGroup) publicDefGroupStr+=key+" "; var spriteDefGroupStr=""; for (key in spriteDefGroup) spriteDefGroupStr+=key+" "; var materialDefGroupStr=""; for (key in materialDefGroup) materialDefGroupStr+=key+" "; console.log("ShaderCompile3DDebugMode---(Name:"+Shader3D.nameKey.getName(this._name)+" PublicDefine:"+publicDefine+" SpriteDefine:"+spriteDefine+" MaterialDefine:"+materialDefine+" PublicDefineGroup:"+publicDefGroupStr+" SpriteDefineGroup:"+spriteDefGroupStr+"MaterialDefineGroup: "+materialDefGroupStr+")---ShaderCompile3DDebugMode"); }; var defMap={}; var defineStr=""; if (publicDefGroup){ for (key in publicDefGroup){ defineStr+="#define "+key+"\n"; defMap[key]=true; } } if (spriteDefGroup){ for (key in spriteDefGroup){ defineStr+="#define "+key+"\n"; defMap[key]=true; } } if (materialDefGroup){ for (key in materialDefGroup){ defineStr+="#define "+key+"\n"; defMap[key]=true; } }; var vs=this._VS.toscript(defMap,[]); var ps=this._PS.toscript(defMap,[]); shader=Shader3D.create(defineStr+vs.join('\n'),defineStr+ps.join('\n'),this._attributeMap,this._sceneUniformMap,this._cameraUniformMap,this._spriteUniformMap,this._materialUniformMap,this._renderElementUniformMap); materialDefShaders[materialDefine]=shader; return shader; } /** *通过宏定义预编译shader。 *@param spriteIntToNameDic 精灵宏定义数组。 *@param publicDefine 公共宏定义值。 *@param spriteDefine 精灵宏定义值。 *@param materialDefine 材质宏定义值。 */ __proto.precompileShaderWithShaderDefine=function(publicDefine,spriteDefine,materialDefine){ this.withCompile(publicDefine,spriteDefine,materialDefine); } /** *注册材质宏定义。 *@param name 宏定义名称。 *@return */ __proto.addMaterialDefines=function(shaderdefines){ var defines=shaderdefines.defines; for (var k in defines){ var name=defines[k]; var i=parseInt(k); this._materialInt2name[i]=name; this._materialName2Int[name]=i; } } /** *注册精灵宏定义。 *@param name 宏定义名称。 *@return */ __proto.addSpriteDefines=function(shaderdefines){ var defines=shaderdefines.defines; for (var k in defines){ var name=defines[k]; var i=parseInt(k); this._spriteInt2name[i]=name; this._spriteName2Int[name]=i; } } /** *通过名称获取宏定义值。 *@param name 名称。 *@return 宏定义值。 */ __proto.getMaterialDefineByName=function(name){ return this._materialName2Int[name]; } /** *注册材质宏定义。 *@param name 宏定义名称。 *@return */ __proto.registerMaterialDefine=function(name){ var value=Math.pow(2,this._materialDefineCounter++); this._materialInt2name[value]=name; this._materialName2Int[name]=value; return value; } /** *注册精灵宏定义。 *@param name 宏定义名称。 *@return */ __proto.registerSpriteDefine=function(name){ var value=Math.pow(2,this._spriteDefineCounter++); this._spriteInt2name[value]=name; this._spriteName2Int[name]=value; return value; } ShaderCompile3D._globalRegDefine=function(name,value){ ShaderCompile3D._globalInt2name[value]=name; } ShaderCompile3D.add=function(nameID,vs,ps,attributeMap,uniformMap){ return laya.d3.shader.ShaderCompile3D._preCompileShader[nameID]=new ShaderCompile3D(nameID,vs,ps,attributeMap,uniformMap,ShaderCompile.includes); } ShaderCompile3D.get=function(name){ return laya.d3.shader.ShaderCompile3D._preCompileShader[Shader3D.nameKey.getID(name)]; } ShaderCompile3D._preCompileShader={}; ShaderCompile3D._globalInt2name=[]; ShaderCompile3D.debugMode=false; ShaderCompile3D.SHADERDEFINE_HIGHPRECISION=0x1; ShaderCompile3D.SHADERDEFINE_FOG=0x4; ShaderCompile3D.SHADERDEFINE_DIRECTIONLIGHT=0x8; ShaderCompile3D.SHADERDEFINE_POINTLIGHT=0x10; ShaderCompile3D.SHADERDEFINE_SPOTLIGHT=0x20; ShaderCompile3D.SHADERDEFINE_UV0=0x40; ShaderCompile3D.SHADERDEFINE_COLOR=0x80; ShaderCompile3D.SHADERDEFINE_UV1=0x100; ShaderCompile3D.SAHDERDEFINE_DEPTHFOG=0x20000; return ShaderCompile3D; })(ShaderCompile) /** *@private *MeshSprite3DStaticBatchManager 类用于网格精灵静态批处理管理。 */ //class laya.d3.graphics.MeshSprite3DStaticBatchManager extends laya.d3.graphics.StaticBatchManager var MeshSprite3DStaticBatchManager=(function(_super){ /**i *创建一个 MeshSprite3DStaticBatchManager 实例。 */ function MeshSprite3DStaticBatchManager(){ MeshSprite3DStaticBatchManager.__super.call(this); } __class(MeshSprite3DStaticBatchManager,'laya.d3.graphics.MeshSprite3DStaticBatchManager',_super); var __proto=MeshSprite3DStaticBatchManager.prototype; /** *@private */ __proto._getStaticBatch=function(rootOwner,vertexDeclaration,material,number){ var staticBatch; var key; if (rootOwner) key=rootOwner.id.toString()+material.id.toString()+vertexDeclaration.id.toString()+number.toString(); else key=material.id.toString()+vertexDeclaration.id.toString()+number.toString(); if (!this._staticBatches[key]) this._staticBatches[key]=staticBatch=new SubMeshStaticBatch(key,this,rootOwner,vertexDeclaration,material); else staticBatch=this._staticBatches[key]; return staticBatch; } /** *@inheritDoc */ __proto._initStaticBatchs=function(rootOwner){ this._initBatchRenderElements.sort(MeshSprite3DStaticBatchManager._sortPrepareStaticBatch); var lastMaterial; var lastVertexDeclaration; var lastCanMerage=false; var curStaticBatch; var batchNumber=0; for (var i=0,n=this._initBatchRenderElements.length;i < n;i++){ var renderElement=this._initBatchRenderElements[i]; var vb=renderElement.renderObj._getVertexBuffer(0); var originalOwner=renderElement._sprite3D; if ((lastVertexDeclaration===vb.vertexDeclaration)&& (lastMaterial===renderElement._material)){ var oldStaticBatch; if (!lastCanMerage){ var lastRenderObj=this._initBatchRenderElements[i-1]; var lastRenderElement=lastRenderObj.renderObj; var curRenderElement=renderElement.renderObj; if (((lastRenderElement._getVertexBuffer().vertexCount+curRenderElement._getVertexBuffer().vertexCount)> /*laya.d3.graphics.StaticBatch.maxBatchVertexCount*/65535)){ lastCanMerage=false; }else { curStaticBatch=this._getStaticBatch(rootOwner,lastVertexDeclaration,lastMaterial,batchNumber); oldStaticBatch=lastRenderObj._staticBatch; if (oldStaticBatch!==curStaticBatch){ (oldStaticBatch)&& (oldStaticBatch._deleteCombineBatchRenderObj(lastRenderObj)); curStaticBatch._addCombineBatchRenderObj(lastRenderObj); } oldStaticBatch=renderElement._staticBatch; if (oldStaticBatch!==curStaticBatch){ (oldStaticBatch)&& (oldStaticBatch._deleteCombineBatchRenderObj(renderElement)); curStaticBatch._addCombineBatchRenderObj(renderElement); } lastCanMerage=true; } }else { if (!curStaticBatch._addCombineBatchRenderObjTest(renderElement)){ lastCanMerage=false; batchNumber++; }else { oldStaticBatch=renderElement._staticBatch; if (oldStaticBatch!==curStaticBatch){ (oldStaticBatch)&& (oldStaticBatch._deleteCombineBatchRenderObj(renderElement)); curStaticBatch._addCombineBatchRenderObj(renderElement) } } } }else { lastCanMerage=false; batchNumber=0; } lastMaterial=renderElement._material; lastVertexDeclaration=vb.vertexDeclaration; } } MeshSprite3DStaticBatchManager._sortPrepareStaticBatch=function(a,b){ var aRender=a._render,bRender=b._render; var lightMapIndexOffset=aRender.lightmapIndex-bRender.lightmapIndex; if (lightMapIndexOffset===0){ var receiveShadowValue=/*__JS__ */aRender.receiveShadow-bRender.receiveShadow; if (receiveShadowValue===0){ var mainID=a._mainSortID-b._mainSortID; if (mainID===0){ return a.renderObj.triangleCount-b.renderObj.triangleCount; }else { return mainID; } }else { return receiveShadowValue; } }else { return lightMapIndexOffset; } } return MeshSprite3DStaticBatchManager; })(StaticBatchManager) /** *SubMeshStaticBatch 类用于网格静态合并。 */ //class laya.d3.graphics.SubMeshStaticBatch extends laya.d3.graphics.StaticBatch var SubMeshStaticBatch=(function(_super){ function SubMeshStaticBatch(key,manager,rootOwner,vertexDeclaration,material){ /**@private */ this._batchOwnerIndices=null; /**@private */ this._batchOwners=null; /**@private */ this._needFinishCombine=false; /**@private */ this._currentCombineVertexCount=0; /**@private */ this._currentCombineIndexCount=0; /**@private */ this._vertexDeclaration=null; /**@private */ this._vertexBuffer=null; /**@private */ this._indexBuffer=null; SubMeshStaticBatch.__super.call(this,key,manager,rootOwner); this._batchOwnerIndices=[]; this._batchOwners=[]; this._needFinishCombine=false; this._currentCombineVertexCount=0; this._currentCombineIndexCount=0; this._vertexDeclaration=vertexDeclaration; this._material=material; } __class(SubMeshStaticBatch,'laya.d3.graphics.SubMeshStaticBatch',_super); var __proto=SubMeshStaticBatch.prototype; /** *@inheritDoc */ __proto._compareBatchRenderElement=function(a,b){ return (a)._batchIndexStart > (b)._batchIndexStart; } /** *@private */ __proto._addCombineBatchRenderObjTest=function(renderElement){ var vertexCount=0; var subMeshVertexCount=(renderElement.renderObj)._vertexCount; if (subMeshVertexCount > 0) vertexCount=this._currentCombineVertexCount+subMeshVertexCount; else vertexCount=this._currentCombineVertexCount+renderElement.renderObj._getVertexBuffer().vertexCount; if (vertexCount > 65535) return false; return true; } /** *@private */ __proto._addCombineBatchRenderObj=function(renderElement){ var subMesh=renderElement.renderObj; var subMeshVertexCount=subMesh._vertexCount; this._initBatchRenderElements.push(renderElement); renderElement._staticBatch=this; if (subMeshVertexCount > 0){ this._currentCombineIndexCount+=subMesh._indexCount; this._currentCombineVertexCount+=subMeshVertexCount; }else { this._currentCombineIndexCount=this._currentCombineIndexCount+subMesh._getIndexBuffer().indexCount; this._currentCombineVertexCount=this._currentCombineVertexCount+subMesh._getVertexBuffer().vertexCount; } this._needFinishCombine=true; } /** *@private */ __proto._deleteCombineBatchRenderObj=function(renderElement){ var subMesh=renderElement.renderObj; var index=this._initBatchRenderElements.indexOf(renderElement); if (index!==-1){ this._initBatchRenderElements.splice(index,1); renderElement._staticBatch=null; var subMeshVertexCount=subMesh._vertexCount; if (subMeshVertexCount > 0){ this._currentCombineIndexCount=this._currentCombineIndexCount-subMesh._indexCount; this._currentCombineVertexCount=this._currentCombineVertexCount-subMeshVertexCount; }else { this._currentCombineIndexCount=this._currentCombineIndexCount-subMesh._getIndexBuffer().indexCount; this._currentCombineVertexCount=this._currentCombineVertexCount-subMesh._getVertexBuffer().vertexCount; } this._needFinishCombine=true; } } /** *@inheritDoc */ __proto._finishInit=function(){ if (this._needFinishCombine){ var curMerVerCount=0; var curIndexCount=0; if (this._initBatchRenderElements[0]._sprite3D._render.lightmapIndex >=0){ this._vertexDeclaration=this._getVertexDecLightMap(this._vertexDeclaration); }else { if ((this._material instanceof laya.d3.core.material.StandardMaterial )){ if ((this._material).ambientTexture) this._vertexDeclaration=this._getVertexDecLightMap(this._vertexDeclaration); } }; var vertexDatas=new Float32Array(this._vertexDeclaration.vertexStride / 4 *this._currentCombineVertexCount); var indexDatas=new Uint16Array(this._currentCombineIndexCount); if (this._vertexBuffer){ this._vertexBuffer.destroy(); this._indexBuffer.destroy(); } this._vertexBuffer=VertexBuffer3D.create(this._vertexDeclaration,this._currentCombineVertexCount,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4); this._indexBuffer=IndexBuffer3D.create(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",this._currentCombineIndexCount,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4); for (var i=0,n=this._initBatchRenderElements.length;i < n;i++){ var renderElement=this._initBatchRenderElements [i]; var subMesh=renderElement.renderObj; var subVertexDatas=subMesh._getStaticBatchBakedVertexs(this._rootOwner ? this._rootOwner._transform :null,renderElement._sprite3D); var subIndexDatas=subMesh.getIndices(); var isInvert=renderElement._sprite3D.transform._isFrontFaceInvert; var indexOffset=curMerVerCount / (this._vertexDeclaration.vertexStride / 4)-subMesh._vertexStart; var indexStart=curIndexCount; var indexEnd=indexStart+subIndexDatas.length; renderElement._batchIndexStart=indexStart; renderElement._batchIndexEnd=indexEnd; indexDatas.set(subIndexDatas,curIndexCount); var k=0; if (isInvert){ for (k=indexStart;k < indexEnd;k+=3){ indexDatas[k]=indexOffset+indexDatas[k]; var index1=indexDatas[k+1]; var index2=indexDatas[k+2]; indexDatas[k+1]=indexOffset+index2; indexDatas[k+2]=indexOffset+index1; } }else { for (k=indexStart;k < indexEnd;k+=3){ indexDatas[k]=indexOffset+indexDatas[k]; indexDatas[k+1]=indexOffset+indexDatas[k+1]; indexDatas[k+2]=indexOffset+indexDatas[k+2]; } } curIndexCount+=subIndexDatas.length; vertexDatas.set(subVertexDatas,curMerVerCount); curMerVerCount+=subVertexDatas.length; } this._vertexBuffer.setData(vertexDatas); this._indexBuffer.setData(indexDatas); this._needFinishCombine=false; } } /** *@inheritDoc */ __proto._getCombineRenderElementFromPool=function(){ var renderElement=this._combineRenderElementPool[this._combineRenderElementPoolIndex++]; return renderElement || (this._combineRenderElementPool[this._combineRenderElementPoolIndex-1]=new SubMeshRenderElement()); } /** *@inheritDoc */ __proto._getRenderElement=function(renderQueueElements,scene,projectionView){ var lastRenderElement,renderElement; var count=this._batchRenderElements.length; var canMerge=true; for (var i=0;i < count;i++){ renderElement=this._batchRenderElements [i]; var render=renderElement._sprite3D._render; var lastRender; if (i!==0){ lastRenderElement=this._batchRenderElements [i-1]; lastRender=lastRenderElement._sprite3D._render; canMerge=(lastRender.lightmapIndex!==render.lightmapIndex || lastRender.receiveShadow!==render.receiveShadow || lastRenderElement._batchIndexEnd!==renderElement._batchIndexStart); }; var merageElement; if (canMerge){ merageElement=this._getCombineRenderElementFromPool(); merageElement.renderObj=this; merageElement._material=this._material; merageElement._batchIndexStart=(renderElement)._batchIndexStart; merageElement._batchIndexEnd=(renderElement)._batchIndexEnd; var lightMapIndex=render.lightmapIndex; var cacheLightMapIndex=lightMapIndex+1; var lightMapBatchOwnerIndices=this._batchOwnerIndices[cacheLightMapIndex]; (lightMapBatchOwnerIndices)|| (lightMapBatchOwnerIndices=this._batchOwnerIndices[cacheLightMapIndex]=[]); var batchOwnerIndex=lightMapBatchOwnerIndices[renderElement._render.receiveShadow ? 1 :0]; var batchOwner; if (batchOwnerIndex===undefined){ lightMapBatchOwnerIndices[render.receiveShadow ? 1 :0]=this._batchOwners.length; batchOwner=new MeshSprite3D(null,"StaticBatchMeshSprite3D"); batchOwner._scene=scene; batchOwner._transform=this._rootOwner ? this._rootOwner._transform :null; batchOwner._render.lightmapIndex=lightMapIndex; batchOwner._render.receiveShadow=renderElement._render.receiveShadow; this._batchOwners.push(batchOwner); }else { batchOwner=this._batchOwners[batchOwnerIndex]; } batchOwner._render._renderUpdate(projectionView); merageElement._sprite3D=batchOwner; renderQueueElements.push(merageElement); }else { merageElement._batchIndexEnd=(renderElement)._batchIndexEnd; } } } /** *@inheritDoc */ __proto._beforeRender=function(state){ this._vertexBuffer._bind(); this._indexBuffer._bind(); return true; } /** *@inheritDoc */ __proto._render=function(state){ var renderElement=state.renderElement; var batchIndexStart=renderElement._batchIndexStart; var indexCount=renderElement._batchIndexEnd-batchIndexStart; WebGL.mainContext.drawElements(/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,indexCount,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,batchIndexStart *2); Stat.drawCall++; Stat.trianglesFaces+=indexCount / 3; } /** *@inheritDoc */ __proto.dispose=function(){ this._batchOwnerIndices=null; this._batchOwners=null; this._vertexDeclaration=null; this._vertexBuffer.destroy(); this._indexBuffer.destroy(); } //..................临时................................. __proto._getVertexBuffer=function(index){ (index===void 0)&& (index=0); return this._vertexBuffer; } return SubMeshStaticBatch; })(StaticBatch) /** *Sky 类用于创建天空盒。 */ //class laya.d3.resource.models.SkyBox extends laya.d3.resource.models.Sky var SkyBox=(function(_super){ function SkyBox(){ /**@private */ //this._numberVertices=0; /**@private */ //this._numberIndices=0; /**@private 天空立方体纹理。 */ //this._textureCube=null; SkyBox.__super.call(this); SkyBox._nameNumber++; this.loadShaderParams(); this.createResource(); this.alphaBlending=1; this.colorIntensity=1; } __class(SkyBox,'laya.d3.resource.models.SkyBox',_super); var __proto=SkyBox.prototype; /** *@private */ __proto._getShader=function(state){ var shaderDefineValue=state.scene._shaderDefineValue; this._shader=this._shaderCompile.withCompile(shaderDefineValue,0,0); return this._shader; } /** *@private */ __proto.createResource=function(){ this._numberVertices=36; this._numberIndices=36; var indices=new Uint16Array(this._numberIndices); var vertexFloatStride=SkyBox._vertexDeclaration.vertexStride / 4; var vertices=new Float32Array(this._numberVertices *vertexFloatStride); var width=1.0; var height=1.0; var depth=1.0; var halfWidth=width / 2.0; var halfHeight=height / 2.0; var halfDepth=depth / 2.0; var topLeftFront=new Vector3(-halfWidth,halfHeight,halfDepth); var bottomLeftFront=new Vector3(-halfWidth,-halfHeight,halfDepth); var topRightFront=new Vector3(halfWidth,halfHeight,halfDepth); var bottomRightFront=new Vector3(halfWidth,-halfHeight,halfDepth); var topLeftBack=new Vector3(-halfWidth,halfHeight,-halfDepth); var topRightBack=new Vector3(halfWidth,halfHeight,-halfDepth); var bottomLeftBack=new Vector3(-halfWidth,-halfHeight,-halfDepth); var bottomRightBack=new Vector3(halfWidth,-halfHeight,-halfDepth); var vertexCount=0; vertexCount=this._addVertex(vertices,vertexCount,topLeftFront); vertexCount=this._addVertex(vertices,vertexCount,bottomLeftFront); vertexCount=this._addVertex(vertices,vertexCount,topRightFront); vertexCount=this._addVertex(vertices,vertexCount,bottomLeftFront); vertexCount=this._addVertex(vertices,vertexCount,bottomRightFront); vertexCount=this._addVertex(vertices,vertexCount,topRightFront); vertexCount=this._addVertex(vertices,vertexCount,topLeftBack); vertexCount=this._addVertex(vertices,vertexCount,topRightBack); vertexCount=this._addVertex(vertices,vertexCount,bottomLeftBack); vertexCount=this._addVertex(vertices,vertexCount,bottomLeftBack); vertexCount=this._addVertex(vertices,vertexCount,topRightBack); vertexCount=this._addVertex(vertices,vertexCount,bottomRightBack); vertexCount=this._addVertex(vertices,vertexCount,topLeftFront); vertexCount=this._addVertex(vertices,vertexCount,topRightBack); vertexCount=this._addVertex(vertices,vertexCount,topLeftBack); vertexCount=this._addVertex(vertices,vertexCount,topLeftFront); vertexCount=this._addVertex(vertices,vertexCount,topRightFront); vertexCount=this._addVertex(vertices,vertexCount,topRightBack); vertexCount=this._addVertex(vertices,vertexCount,bottomLeftFront); vertexCount=this._addVertex(vertices,vertexCount,bottomLeftBack); vertexCount=this._addVertex(vertices,vertexCount,bottomRightBack); vertexCount=this._addVertex(vertices,vertexCount,bottomLeftFront); vertexCount=this._addVertex(vertices,vertexCount,bottomRightBack); vertexCount=this._addVertex(vertices,vertexCount,bottomRightFront); vertexCount=this._addVertex(vertices,vertexCount,topLeftFront); vertexCount=this._addVertex(vertices,vertexCount,bottomLeftBack); vertexCount=this._addVertex(vertices,vertexCount,bottomLeftFront); vertexCount=this._addVertex(vertices,vertexCount,topLeftBack); vertexCount=this._addVertex(vertices,vertexCount,bottomLeftBack); vertexCount=this._addVertex(vertices,vertexCount,topLeftFront); vertexCount=this._addVertex(vertices,vertexCount,topRightFront); vertexCount=this._addVertex(vertices,vertexCount,bottomRightFront); vertexCount=this._addVertex(vertices,vertexCount,bottomRightBack); vertexCount=this._addVertex(vertices,vertexCount,topRightBack); vertexCount=this._addVertex(vertices,vertexCount,topRightFront); vertexCount=this._addVertex(vertices,vertexCount,bottomRightBack); for (var i=0;i < 36;i++) indices[i]=i; this._vertexBuffer=new VertexBuffer3D(SkyBox._vertexDeclaration,this._numberVertices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._indexBuffer=new IndexBuffer3D(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",this._numberIndices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._vertexBuffer.setData(vertices); this._indexBuffer.setData(indices); } /** *@private */ __proto._addVertex=function(vertices,index,position){ var posE=position.elements; vertices[index+0]=posE[0]; vertices[index+1]=posE[1]; vertices[index+2]=posE[2]; return index+3; } /** *@private */ __proto.loadShaderParams=function(){ this._sharderNameID=Shader3D.nameKey.getID("SkyBox"); this._shaderCompile=ShaderCompile3D._preCompileShader[this._sharderNameID]; } __proto._render=function(state){ if (this._textureCube && this._textureCube.loaded){ this._vertexBuffer._bind(); this._indexBuffer._bind(); this._shader=this._getShader(state); this._shader.bind(); state.camera.transform.worldMatrix.cloneTo(SkyBox._tempMatrix4x40); SkyBox._tempMatrix4x40.transpose(); Matrix4x4.multiply(state._projectionMatrix,SkyBox._tempMatrix4x40,SkyBox._tempMatrix4x41); state.camera._shaderValues.setValue(/*laya.d3.core.BaseCamera.VPMATRIX_NO_TRANSLATE*/4,SkyBox._tempMatrix4x41.elements); this._shader.uploadCameraUniforms(state.camera._shaderValues.data); this._shaderValue.setValue(1,this._colorIntensity); this._shaderValue.setValue(2,this._alphaBlending); this._shaderValue.setValue(3,this.textureCube); this._shader.uploadAttributes(SkyBox._vertexDeclaration.shaderValues.data,null); this._shader.uploadMaterialUniforms(this._shaderValue.data); WebGL.mainContext.drawElements(/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,36,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,0); Stat.trianglesFaces+=12; Stat.drawCall++; } } /** *@inheritDoc */ __proto.destroy=function(){ _super.prototype.destroy.call(this); (this._textureCube)&& (this._textureCube._removeReference(),this._textureCube=null); } /** *设置天空立方体纹理。 *@param value 天空立方体纹理。 */ /** *获取天空立方体纹理。 *@return 天空立方体纹理。 */ __getset(0,__proto,'textureCube',function(){ return this._textureCube; },function(value){ if (this._textureCube!==value){ (this._textureCube)&& (this._textureCube._removeReference()); this._textureCube=value; (value)&& (value._addReference()); } }); SkyBox._nameNumber=1; __static(SkyBox, ['_tempMatrix4x40',function(){return this._tempMatrix4x40=new Matrix4x4();},'_tempMatrix4x41',function(){return this._tempMatrix4x41=new Matrix4x4();},'_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(12,[new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0)]);} ]); return SkyBox; })(Sky) /** *Sky 类用于创建天空盒。 */ //class laya.d3.resource.models.SkyDome extends laya.d3.resource.models.Sky var SkyDome=(function(_super){ function SkyDome(){ /**@private */ //this._numberVertices=0; /**@private */ //this._numberIndices=0; /**@private 天空立方体纹理。 */ //this._texture=null; this._stacks=16; this._slices=16; this._radius=1; SkyDome.__super.call(this); SkyDome._nameNumber++; this.loadShaderParams(); this.recreateResource(); this.alphaBlending=1; this.colorIntensity=1; } __class(SkyDome,'laya.d3.resource.models.SkyDome',_super); var __proto=SkyDome.prototype; /** *@private */ __proto._getShader=function(state){ var shaderDefineValue=state.scene._shaderDefineValue; this._shader=this._shaderCompile.withCompile(shaderDefineValue,0,0); return this._shader; } /** *@private */ __proto.recreateResource=function(){ this._numberVertices=(this._stacks+1)*(this._slices+1); this._numberIndices=(3 *this._stacks *(this._slices+1))*2; var indices=new Uint16Array(this._numberIndices); var vertexFloatStride=SkyDome._vertexDeclaration.vertexStride / 4; var vertices=new Float32Array(this._numberVertices *vertexFloatStride); var stackAngle=Math.PI / this._stacks; var sliceAngle=(Math.PI *2.0)/ this._slices; var vertexIndex=0; var vertexCount=0; var indexCount=0; for (var stack=0;stack < (this._stacks+1);stack++){ var r=Math.sin(stack *stackAngle); var y=Math.cos(stack *stackAngle); for (var slice=0;slice < (this._slices+1);slice++){ var x=r *Math.sin(slice *sliceAngle); var z=r *Math.cos(slice *sliceAngle); vertices[vertexCount+0]=x *this._radius; vertices[vertexCount+1]=y *this._radius; vertices[vertexCount+2]=z *this._radius; vertices[vertexCount+3]=-(slice / this._slices)+0.75; vertices[vertexCount+4]=stack / this._stacks; vertexCount+=vertexFloatStride; if (stack !=(this._stacks-1)){ indices[indexCount++]=vertexIndex+1; indices[indexCount++]=vertexIndex; indices[indexCount++]=vertexIndex+(this._slices+1); indices[indexCount++]=vertexIndex+(this._slices+1); indices[indexCount++]=vertexIndex; indices[indexCount++]=vertexIndex+(this._slices); vertexIndex++; } } } this._vertexBuffer=new VertexBuffer3D(SkyDome._vertexDeclaration,this._numberVertices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4); this._indexBuffer=new IndexBuffer3D(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",this._numberIndices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4); this._vertexBuffer.setData(vertices); this._indexBuffer.setData(indices); } /** *@private */ __proto.loadShaderParams=function(){ this._sharderNameID=Shader3D.nameKey.getID("SkyDome"); this._shaderCompile=ShaderCompile3D._preCompileShader[this._sharderNameID]; } __proto._render=function(state){ if (this._texture && this._texture.loaded){ this._vertexBuffer._bind(); this._indexBuffer._bind(); this._shader=this._getShader(state); this._shader.bind(); state.camera.transform.worldMatrix.cloneTo(SkyDome._tempMatrix4x40); SkyDome._tempMatrix4x40.transpose(); Matrix4x4.multiply(state._projectionMatrix,SkyDome._tempMatrix4x40,SkyDome._tempMatrix4x41); state.camera._shaderValues.setValue(/*laya.d3.core.BaseCamera.VPMATRIX_NO_TRANSLATE*/4,SkyDome._tempMatrix4x41.elements); this._shader.uploadCameraUniforms(state.camera._shaderValues.data); this._shaderValue.setValue(1,this._colorIntensity); this._shaderValue.setValue(2,this._alphaBlending); this._shaderValue.setValue(3,this.texture); this._shader.uploadAttributes(SkyDome._vertexDeclaration.shaderValues.data,null); this._shader.uploadMaterialUniforms(this._shaderValue.data); WebGL.mainContext.drawElements(/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,this._indexBuffer.indexCount,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,0); Stat.trianglesFaces+=this._numberIndices / 3; Stat.drawCall++; } } __proto.onEnvDescLoaded=function(envInfoFile){ var envPath=''; var ppos=Math.max(envInfoFile.lastIndexOf('/'),envInfoFile.lastIndexOf('\\')); if (ppos > 0){ envPath=envInfoFile.substr(0,ppos+1); }; var envinfoobj=Laya.loader.getRes(envInfoFile); if (envinfoobj.ev !=undefined && this.__ownerCamera) this.__ownerCamera._shaderValues.setValue(/*laya.d3.core.BaseCamera.HDREXPOSURE*/13,Math.pow(2,envinfoobj.ev)); else this.__ownerCamera._shaderValues.setValue(/*laya.d3.core.BaseCamera.HDREXPOSURE*/13,Math.pow(2,0.0)); this.texture=Texture2D.load(envPath+envinfoobj.skytex); this.environmentSpecular=DataTexture2D.load(envPath+envinfoobj.prefiltedEnv); var irrdMat=new Float32Array(envinfoobj.IrradianceMat); this.envDiffuseSHRed=irrdMat.slice(0,16); this.envDiffuseSHGreen=irrdMat.slice(16,32); this.envDiffuseSHBlue=irrdMat.slice(32,48); } __proto.loadEnvInfo=function(envInfo){ Laya.loader.load(envInfo,Handler.create(this,this.onEnvDescLoaded,[envInfo])); } /** *@inheritDoc */ __proto.destroy=function(){ _super.prototype.destroy.call(this); (this._texture)&& (this._texture._removeReference(),this._texture=null); } /** *设置天空纹理。 *@param value 天空纹理。 */ /** *获取天空立方体纹理。 *@return 天空立方体纹理。 */ __getset(0,__proto,'texture',function(){ return this._texture; },function(value){ if (this._texture!==value){ (this._texture)&& (this._texture._removeReference()); this._texture=value; (value)&& (value._addReference()); } }); SkyDome._nameNumber=1; __static(SkyDome, ['_tempMatrix4x40',function(){return this._tempMatrix4x40=new Matrix4x4();},'_tempMatrix4x41',function(){return this._tempMatrix4x41=new Matrix4x4();},'_vertexDeclaration',function(){return this._vertexDeclaration=new VertexDeclaration(20,[new VertexElement(0,/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3",/*laya.d3.graphics.VertexElementUsage.POSITION0*/0),new VertexElement(12,/*laya.d3.graphics.VertexElementFormat.Vector2*/"vector2",/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2)]);} ]); return SkyDome; })(Sky) /** *@private *ComponentNode 类用于实现组件精灵,该类为抽象类。 */ //class laya.d3.core.ComponentNode extends laya.display.Node var ComponentNode=(function(_super){ function ComponentNode(){ /**@private */ this._componentsMap=null; /**@private */ this._typeComponentsIndices=null; /**@private */ this._components=null; /**@private */ this._scripts=null; ComponentNode.__super.call(this); this._componentsMap=[]; this._typeComponentsIndices=[]; this._components=[]; this._scripts=[]; } __class(ComponentNode,'laya.d3.core.ComponentNode',_super); var __proto=ComponentNode.prototype; /** *添加指定类型组件。 *@param type 组件类型。 *@return 组件。 */ __proto.addComponent=function(type){ var typeComponentIndex; var index=this._componentsMap.indexOf(type); if (index===-1){ typeComponentIndex=[]; this._componentsMap.push(type); this._typeComponentsIndices.push(typeComponentIndex); }else { typeComponentIndex=this._typeComponentsIndices[index]; if (this._components[typeComponentIndex[0]].isSingleton) throw new Error("无法单实例创建"+type+"组件"+","+type+"组件已存在!"); }; var component=ClassUtils.getInstance(type); typeComponentIndex.push(this._components.length); this._components.push(component); if ((component instanceof laya.d3.component.Script )) this._scripts.push(component); component._initialize(this); return component; } /** *@private */ __proto._removeComponent=function(mapIndex,index){ var componentIndices=this._typeComponentsIndices[mapIndex]; var componentIndex=componentIndices[index]; var component=this._components[componentIndex]; this._components.splice(componentIndex,1); if ((component instanceof laya.d3.component.Script )) this._scripts.splice(this._scripts.indexOf(component),1); componentIndices.splice(index,1); (componentIndices.length===0)&& (this._typeComponentsIndices.splice(mapIndex,1),this._componentsMap.splice(mapIndex,1)); for (var i=0,n=this._componentsMap.length;i < n;i++){ componentIndices=this._typeComponentsIndices[i]; for (var j=componentIndices.length-1;j >=0;j--){ var oldComponentIndex=componentIndices[j]; if (oldComponentIndex > componentIndex) componentIndices[j]=--oldComponentIndex; else break ; } } component._destroy(); } /** *通过指定类型和类型索引获得组件。 *@param type 组件类型。 *@param typeIndex 类型索引。 *@return 组件。 */ __proto.getComponentByType=function(type,typeIndex){ (typeIndex===void 0)&& (typeIndex=0); var mapIndex=this._componentsMap.indexOf(type); if (mapIndex===-1) return null; return this._components[this._typeComponentsIndices[mapIndex][typeIndex]]; } /** *通过指定类型获得所有组件。 *@param type 组件类型。 *@param components 组件输出队列。 */ __proto.getComponentsByType=function(type,components){ var index=this._componentsMap.indexOf(type); if (index===-1){ components.length=0; return; }; var typeComponents=this._typeComponentsIndices[index]; var count=typeComponents.length; components.length=count; for (var i=0;i < count;i++) components[i]=this._components[typeComponents[i]]; } /** *通过指定索引获得组件。 *@param index 索引。 *@return 组件。 */ __proto.getComponentByIndex=function(index){ return this._components[index]; } /** *通过指定类型和类型索引移除组件。 *@param type 组件类型。 *@param typeIndex 类型索引。 */ __proto.removeComponentByType=function(type,typeIndex){ (typeIndex===void 0)&& (typeIndex=0); var mapIndex=this._componentsMap.indexOf(type); if (mapIndex===-1) return; this._removeComponent(mapIndex,typeIndex); } /** *通过指定类型移除所有组件。 *@param type 组件类型。 */ __proto.removeComponentsByType=function(type){ var mapIndex=this._componentsMap.indexOf(type); if (mapIndex===-1) return; var componentIndices=this._typeComponentsIndices[mapIndex]; for (var i=0,n=componentIndices.length;i < n;componentIndices.length < n ? n--:i++) this._removeComponent(mapIndex,i); } /** *移除全部组件。 */ __proto.removeAllComponent=function(){ for (var i=0,n=this._componentsMap.length;i < n;this._componentsMap.length < n ? n--:i++) this.removeComponentsByType(this._componentsMap[i]); } /** *@private */ __proto._updateComponents=function(state){ for (var i=0,n=this._components.length;i < n;i++){ var component=this._components[i]; (!component.started)&& (component._start(state),component.started=true); (component.enable)&& (component._update(state)); } } /** *@private */ __proto._lateUpdateComponents=function(state){ for (var i=0;i < this._components.length;i++){ var component=this._components[i]; (!component.started)&& (component._start(state),component.started=true); (component.enable)&& (component._lateUpdate(state)); } } /** *@private */ __proto._preRenderUpdateComponents=function(state){ for (var i=0;i < this._components.length;i++){ var component=this._components[i]; (!component.started)&& (component._start(state),component.started=true); (component.enable)&& (component._preRenderUpdate(state)); } } /** *@private */ __proto._postRenderUpdateComponents=function(state){ for (var i=0;i < this._components.length;i++){ var component=this._components[i]; (!component.started)&& (component._start(state),component.started=true); (component.enable)&& (component._postRenderUpdate(state)); } } return ComponentNode; })(Node) /** *AnimationClip 类用于动画片段资源。 */ //class laya.d3.animation.AnimationClip extends laya.resource.Resource var AnimationClip=(function(_super){ function AnimationClip(){ /**@private */ this._realTimeCurrentFrameIndexes=null; /**@private */ this._realTimeCurrentTimes=null; /**@private */ this._fullKeyframeIndicesCache=null; /**@private */ this._animationDatasCache=null; /**@private */ this._avatarDatasCache=null; /**@private */ this._skinnedDatasCache=null; /**@private */ this._version=null; /**@private */ this._nodes=null; /**@private */ this._nodesMap=null; /**@private */ this._cachePropertyMap=null; /**@private */ this._nodeToCachePropertyMap=null; /**@private */ this._unCachePropertyMap=null; /**@private */ this._duration=NaN; /**@private */ this._frameRate=0; /**@private */ this._animationEvents=null; /**@private */ this._publicClipDatas=null; /**是否循环。*/ this.islooping=false; AnimationClip.__super.call(this); this._fullKeyframeIndicesCache={}; this._animationDatasCache=[]; this._avatarDatasCache=[]; this._skinnedDatasCache=[]; this._animationEvents=[]; } __class(AnimationClip,'laya.d3.animation.AnimationClip',_super); var __proto=AnimationClip.prototype; /** *获取动画片段时长。 */ __proto.duration=function(){ return this._duration; } /** *@private */ __proto._hermiteInterpolate=function(frame,t,dur,out){ var p0=frame.data; var tan0=frame.outTangent; var nextFrame=frame.next; var p1=nextFrame.data; var tan1=nextFrame.inTangent; var isComputeParams=false; var a=NaN,b=NaN,c=NaN,d=NaN; for (var i=0,n=out.length;i < n;i++){ var t0=tan0[i],t1=tan1[i]; if (/*__JS__ */Number.isFinite(t0)&& Number.isFinite(t1)){ if (!isComputeParams){ var t2=t *t; var t3=t2 *t; a=2.0 *t3-3.0 *t2+1.0; b=t3-2.0 *t2+t; c=t3-t2; d=-2.0 *t3+3.0 *t2; isComputeParams=true; } out[i]=a *p0[i]+b *t0 *dur+c *t1 *dur+d *p1[i]; }else out[i]=p0[i]; } } /** *@private */ __proto._getFullKeyframeIndicesWithCache=function(cacheInterval){ return this._fullKeyframeIndicesCache[cacheInterval]; } /** *@private */ __proto._cacheFullKeyframeIndices=function(cacheInterval,datas){ this._fullKeyframeIndicesCache[cacheInterval]=datas; } /** *@private */ __proto._getAnimationDataWithCache=function(cacheRate,frameIndex){ var cacheDatas=this._animationDatasCache[cacheRate]; if (!cacheDatas) return null; else { return cacheDatas[frameIndex]; } } /** *@private */ __proto._cacheAnimationData=function(cacheRate,frameIndex,datas){ var aniDatasCache=(this._animationDatasCache[cacheRate])|| (this._animationDatasCache[cacheRate]=[]); aniDatasCache[frameIndex]=datas; } /** *@private */ __proto._getAvatarDataWithCache=function(avatar,cacheRate,frameIndex){ var clipCache=this._avatarDatasCache[avatar.id]; if (!clipCache){ return null; }else { var rateCache=clipCache[cacheRate]; if (!rateCache) return null; else { return rateCache[frameIndex]; } } } /** *@private */ __proto._cacheAvatarData=function(avatar,cacheRate,frameIndex,datas){ var clipCache=(this._avatarDatasCache[avatar.id])|| (this._avatarDatasCache[avatar.id]=[]); var rateCache=(clipCache[cacheRate])|| (clipCache[cacheRate]=[]); rateCache[frameIndex]=datas; } /** *@private */ __proto._evaluateAnimationlDatasCacheMode=function(nodeOwners,nodesFrameIndices,animator,clipDatas,propertyMap){ var j=0,m=0; for (var i=0,n=propertyMap ? propertyMap.length :this._nodes.length;i < n;i++){ var nodeIndex=propertyMap ? propertyMap[i] :i; var node=this._nodes[nodeIndex]; var cacheProperty=node._cacheProperty; if (!nodeOwners[nodeIndex]) continue ; var frameIndices=nodesFrameIndices[nodeIndex]; var realFrameIndex=frameIndices[animator.currentFrameIndex]; var outDatas; var lastFrameIndex=0; if (realFrameIndex!==-1){ var frame=node.keyFrames[realFrameIndex]; var nextKeyFrame=frame.next; if (nextKeyFrame){ if (propertyMap && !cacheProperty){ outDatas=clipDatas[nodeIndex]; (outDatas)|| (outDatas=clipDatas[nodeIndex]=new Float32Array(node.keyFrameWidth)); }else { outDatas=new Float32Array(node.keyFrameWidth); clipDatas[i]=outDatas; }; var t=NaN; var d=frame.duration; if (d!==0) t=(animator.currentFrameTime-frame.startTime)/ d; else t=0; this._hermiteInterpolate(frame,t,d,outDatas); }else { if (propertyMap && !cacheProperty){ outDatas=clipDatas[nodeIndex]; (outDatas)|| (outDatas=clipDatas[nodeIndex]=new Float32Array(node.keyFrameWidth)); }else { lastFrameIndex=animator._lastFrameIndex; if (lastFrameIndex!==-1 && frameIndices[lastFrameIndex]===realFrameIndex) continue ; outDatas=new Float32Array(node.keyFrameWidth); clipDatas[i]=outDatas; }; var frameData=frame.data; for (j=0,m=outDatas.length;j < m;j++) outDatas[j]=frameData[j]; } }else { if (propertyMap && !cacheProperty){ outDatas=clipDatas[nodeIndex]; (outDatas)|| (outDatas=clipDatas[nodeIndex]=new Float32Array(node.keyFrameWidth)); }else { lastFrameIndex=animator._lastFrameIndex; if (lastFrameIndex!==-1 && frameIndices[lastFrameIndex]===realFrameIndex) continue ; outDatas=new Float32Array(node.keyFrameWidth); clipDatas[i]=outDatas; }; var firstFrameDatas=node.keyFrames[0].data; for (j=0,m=outDatas.length;j < m;j++) outDatas[j]=firstFrameDatas[j]; } } } /** *@private */ __proto._evaluateAnimationlDatasRealTime=function(nodeOwners,playCurTime,outAnimationDatas,propertyMap){ var i=0,n=0; var nodes=this._nodes; if (!this._realTimeCurrentFrameIndexes){ this._realTimeCurrentFrameIndexes=new Int32Array(nodes.length); for (i=0,n=nodes.length;i < n;i++) this._realTimeCurrentFrameIndexes[i]=-1; this._realTimeCurrentTimes=new Float32Array(nodes.length); } for (i=0,n=propertyMap ? propertyMap.length :this._nodes.length;i < n;i++){ var index=propertyMap ? propertyMap[i] :i; var node=nodes[index]; if (playCurTime < this._realTimeCurrentTimes[index]) this._realTimeCurrentFrameIndexes[index]=-1; this._realTimeCurrentTimes[index]=playCurTime; var nextFrameIndex=this._realTimeCurrentFrameIndexes[index]+1; var keyFrames=node.keyFrames; var keyFramesCount=keyFrames.length; while (nextFrameIndex < keyFramesCount){ if (keyFrames[nextFrameIndex].startTime > playCurTime){ this._realTimeCurrentFrameIndexes[index]=nextFrameIndex-1; break ; } nextFrameIndex++; } (nextFrameIndex===keyFramesCount)&& (this._realTimeCurrentFrameIndexes[index]=keyFramesCount-1); var j=0,m=0; var outDatas=outAnimationDatas[index]; (outDatas)|| (outDatas=outAnimationDatas[index]=new Float32Array(node.keyFrameWidth)); var frame=keyFrames[this._realTimeCurrentFrameIndexes[index]]; if (frame){ var nextFarme=frame.next; if (nextFarme){ var d=frame.duration; var t=NaN; if (d!==0) t=(playCurTime-frame.startTime)/ d; else t=0; this._hermiteInterpolate(frame,t,d,outDatas); }else { var frameData=frame.data; for (j=0,m=outDatas.length;j < m;j++) outDatas[j]=frameData[j]; } }else { var firstFrameDatas=node.keyFrames[0].data; for (j=0,m=outDatas.length;j < m;j++) outDatas[j]=firstFrameDatas[j]; }; var owner=nodeOwners[index]; if (owner){ if (propertyMap) AnimationNode._propertySetFuncs[node.propertyNameID](owner,null,outDatas); else AnimationNode._propertySetFuncs[node.propertyNameID](null,owner,outDatas); } } } /** *@private */ __proto._binarySearchEventIndex=function(time){ var start=0; var end=this._animationEvents.length-1; var mid=0; while (start <=end){ mid=Math.floor((start+end)/ 2); var midValue=this._animationEvents[mid].time; if (midValue==time) return mid; else if (midValue > time) end=mid-1; else start=mid+1; } return start; } /** *添加动画事件。 */ __proto.addEvent=function(event){ var index=this._binarySearchEventIndex(event.time); this._animationEvents.splice(index,0,event); } /** *@inheritDoc */ __proto.onAsynLoaded=function(url,data,params){ var reader=new Byte(data); this._version=reader.readUTFString(); switch (this._version){ case "LAYAANIMATION:01": AnimationClipParser01.parse(this,reader); break ; case "LAYAANIMATION:02": AnimationClipParser02.parse(this,reader); break ; } this.completeCreate(); this._endLoaded(); } /** *@inheritDoc */ __proto.disposeResource=function(){ this._realTimeCurrentFrameIndexes=null; this._realTimeCurrentTimes=null; this._fullKeyframeIndicesCache=null; this._animationDatasCache=null; this._avatarDatasCache=null; this._skinnedDatasCache=null; this._version=null; this._nodes=null; this._nodesMap=null; this._cachePropertyMap=null; this._nodeToCachePropertyMap=null; this._unCachePropertyMap=null; this._publicClipDatas=null; } AnimationClip.load=function(url){ return Laya.loader.create(url,null,null,AnimationClip); } return AnimationClip; })(Resource) /** *Avatar 类用于创建Avatar。 */ //class laya.d3.core.Avatar extends laya.resource.Resource var Avatar=(function(_super){ function Avatar(){ /**@private */ //this._version=null; /**@private */ //this._rootNode=null; Avatar.__super.call(this); } __class(Avatar,'laya.d3.core.Avatar',_super); var __proto=Avatar.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *@private */ __proto._initCloneToAnimator=function(destNode,destAnimator){ destAnimator._avatarNodeMap[destNode.name]=destNode; destAnimator._avatarNodes.push(destNode); for (var i=0,n=destNode.getChildCount();i < n;i++) this._initCloneToAnimator(destNode.getChildByIndex(i),destAnimator); } /** *@private */ __proto._parseNode=function(nodaData,node){ var name=nodaData.props.name; node.name=name; if (node._parent){ var customProps=nodaData.customProps; var transform=node.transform; transform._localRotationEuler=new Float32Array(3); transform.setLocalPosition(new Float32Array(customProps.translate)); transform.setLocalRotation(new Float32Array(customProps.rotation)); transform.setLocalScale(new Float32Array(customProps.scale)); transform._setWorldMatrixAndUpdate(new Float32Array(16)); }; var childrenData=nodaData.child; for (var i=0,n=childrenData.length;i < n;i++){ var childData=childrenData[i]; var childBone=new AnimationNode(); node.addChild(childBone); this._parseNode(childData,childBone); } } /** *@inheritDoc */ __proto.onAsynLoaded=function(url,data,params){ this._rootNode=new AnimationNode(); if (data.version){ this._version=data.version; var rootNode=data.rootNode; (rootNode)&& (this._parseNode(rootNode,this._rootNode)); }else { this._parseNode(data,this._rootNode); } this._endLoaded(); } /** *克隆数据到Avatr。 *@param destObject 克隆源。 */ __proto._cloneDatasToAnimator=function(destAnimator){ var destRoot=this._rootNode.clone(); destRoot.transform._setWorldMatrixIgnoreUpdate(null); var avatarNodes=[]; destAnimator._avatarNodeMap={}; destAnimator._avatarNodes=avatarNodes; this._initCloneToAnimator(destRoot,destAnimator); } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destAvatar=destObject; var destRoot=this._rootNode.clone(); destAvatar._rootNode=destRoot; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var dest=/*__JS__ */new this.constructor(); this.cloneTo(dest); return dest; } Avatar.load=function(url){ return Laya.loader.create(url,null,null,Avatar); } return Avatar; })(Resource) /** *BaseMaterial 类用于创建材质,抽象类,不允许实例。 */ //class laya.d3.core.material.BaseMaterial extends laya.resource.Resource var BaseMaterial=(function(_super){ function BaseMaterial(){ /**@private */ //this._shader=null; /**@private */ //this._shaderCompile=null; /**@private */ //this._shaderDefineValue=0; /**@private */ //this._disablePublicShaderDefine=0; /**@private */ //this._alphaTest=false; /**@private */ //this._shaderValues=null; /**@private */ //this._values=null; /**渲染剔除状态。*/ //this.cull=0; /**透明混合。*/ //this.blend=0; /**源混合参数,在blend为BLEND_ENABLE_ALL时生效。*/ //this.srcBlend=0; /**目标混合参数,在blend为BLEND_ENABLE_ALL时生效。*/ //this.dstBlend=0; /**RGB源混合参数,在blend为BLEND_ENABLE_SEPERATE时生效。*/ //this.srcBlendRGB=0; /**RGB目标混合参数,在blend为BLEND_ENABLE_SEPERATE时生效。*/ //this.dstBlendRGB=0; /**Alpha源混合参数,在blend为BLEND_ENABLE_SEPERATE时生效。*/ //this.srcBlendAlpha=0; /**Alpha目标混合参数,在blend为BLEND_ENABLE_SEPERATE时生效。*/ //this.dstBlendAlpha=0; /**混合常量颜色。*/ //this.blendConstColor=null; /**混合方程。*/ //this.blendEquation=0; /**RGB混合方程。*/ //this.blendEquationRGB=0; /**Alpha混合方程。*/ //this.blendEquationAlpha=0; /**深度测试函数。*/ //this.depthTest=0; /**是否深度写入。*/ //this.depthWrite=false; /**所属渲染队列. */ //this.renderQueue=0; /**@private */ //this._conchMaterial=null; BaseMaterial.__super.call(this); this._shaderDefineValue=0; this._disablePublicShaderDefine=0; this._shaderValues=new ValusArray(); this._values=[]; this.renderQueue=/*CLASS CONST:laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this._alphaTest=false; this.cull=2; this.blend=0; this.srcBlend=1; this.dstBlend=0; this.srcBlendRGB=1; this.dstBlendRGB=0; this.srcBlendAlpha=1; this.dstBlendAlpha=0; this.blendConstColor=new Vector4(1,1,1,1); this.blendEquation=0; this.blendEquationRGB=0; this.blendEquationAlpha=0; this.depthTest=0x0201; this.depthWrite=true; } __class(BaseMaterial,'laya.d3.core.material.BaseMaterial',_super); var __proto=BaseMaterial.prototype; Laya.imps(__proto,{"laya.d3.core.IClone":true}) /** *增加Shader宏定义。 *@param value 宏定义。 */ __proto._addShaderDefine=function(value){ this._shaderDefineValue |=value; } /** *移除Shader宏定义。 *@param value 宏定义。 */ __proto._removeShaderDefine=function(value){ this._shaderDefineValue &=~value; } /** *增加禁用宏定义。 *@param value 宏定义。 */ __proto._addDisablePublicShaderDefine=function(value){ this._disablePublicShaderDefine |=value; } /** *移除禁用宏定义。 *@param value 宏定义。 */ __proto._removeDisablePublicShaderDefine=function(value){ this._disablePublicShaderDefine &=~value; } /** *设置Buffer。 *@param shaderIndex shader索引。 *@param buffer buffer数据。 */ __proto._setBuffer=function(shaderIndex,buffer){ var shaderValue=this._shaderValues; shaderValue.setValue(shaderIndex,buffer); this._values[shaderIndex]=buffer; } /** *获取Buffer。 *@param shaderIndex shader索引。 *@return */ __proto._getBuffer=function(shaderIndex){ return this._values[shaderIndex]; } /** *设置矩阵。 *@param shaderIndex shader索引。 *@param matrix4x4 矩阵。 */ __proto._setMatrix4x4=function(shaderIndex,matrix4x4){ this._shaderValues.setValue(shaderIndex,matrix4x4 ? matrix4x4.elements :null); this._values[shaderIndex]=matrix4x4; } /** *获取矩阵。 *@param shaderIndex shader索引。 *@return 矩阵。 */ __proto._getMatrix4x4=function(shaderIndex){ return this._values[shaderIndex]; } /** *设置整型。 *@param shaderIndex shader索引。 *@param i 整形。 */ __proto._setInt=function(shaderIndex,i){ var shaderValue=this._shaderValues; shaderValue.setValue(shaderIndex,i); this._values[shaderIndex]=i; } /** *获取整形。 *@param shaderIndex shader索引。 *@return 整形。 */ __proto._getInt=function(shaderIndex){ return this._values[shaderIndex]; } /** *设置浮点。 *@param shaderIndex shader索引。 *@param i 浮点。 */ __proto._setNumber=function(shaderIndex,number){ var shaderValue=this._shaderValues; shaderValue.setValue(shaderIndex,number); this._values[shaderIndex]=number; } /** *获取浮点。 *@param shaderIndex shader索引。 *@return 浮点。 */ __proto._getNumber=function(shaderIndex){ return this._values[shaderIndex]; } /** *设置布尔。 *@param shaderIndex shader索引。 *@param b 布尔。 */ __proto._setBool=function(shaderIndex,b){ var shaderValue=this._shaderValues; shaderValue.setValue(shaderIndex,b); this._values[shaderIndex]=b; } /** *获取布尔。 *@param shaderIndex shader索引。 *@return 布尔。 */ __proto._getBool=function(shaderIndex){ return this._values[shaderIndex]; } /** *设置二维向量。 *@param shaderIndex shader索引。 *@param vector2 二维向量。 */ __proto._setVector2=function(shaderIndex,vector2){ var shaderValue=this._shaderValues; shaderValue.setValue(shaderIndex,vector2 ? vector2.elements :null); this._values[shaderIndex]=vector2; } /** *获取二维向量。 *@param shaderIndex shader索引。 *@return 二维向量。 */ __proto._getVector2=function(shaderIndex){ return this._values[shaderIndex]; } /** *设置颜色。 *@param shaderIndex shader索引。 *@param color 颜色向量。 */ __proto._setColor=function(shaderIndex,color){ var shaderValue=this._shaderValues; shaderValue.setValue(shaderIndex,color ? color.elements :null); this._values[shaderIndex]=color; } /** *获取颜色。 *@param shaderIndex shader索引。 *@return 颜色向量。 */ __proto._getColor=function(shaderIndex){ return this._values[shaderIndex]; } /** *设置纹理。 *@param shaderIndex shader索引。 *@param texture 纹理。 */ __proto._setTexture=function(shaderIndex,texture){ var lastValue=this._values[shaderIndex]; this._values[shaderIndex]=texture; this._shaderValues.setValue(shaderIndex,texture); if (this.referenceCount > 0){ (lastValue)&& (lastValue._removeReference()); (texture)&& (texture._addReference()); } } /** *获取纹理。 *@param shaderIndex shader索引。 *@return 纹理。 */ __proto._getTexture=function(shaderIndex){ return this._values[shaderIndex]; } /** *上传材质。 *@param state 相关渲染状态。 *@param bufferUsageShader Buffer相关绑定。 *@param shader 着色器。 *@return 是否成功。 */ __proto._upload=function(){ this._shader.uploadMaterialUniforms(this._shaderValues.data); } /** *@private */ __proto._getShader=function(sceneDefineValue,vertexDefineValue,spriteDefineValue){ var publicDefineValue=(sceneDefineValue | vertexDefineValue)& (~this._disablePublicShaderDefine); this._shader=this._shaderCompile.withCompile(publicDefineValue,spriteDefineValue,this._shaderDefineValue); return this._shader; } /** *设置渲染相关状态。 */ __proto._setRenderStateBlendDepth=function(){ var gl=WebGL.mainContext; WebGLContext.setDepthMask(gl,this.depthWrite); if (this.depthTest===0) WebGLContext.setDepthTest(gl,false); else { WebGLContext.setDepthTest(gl,true); WebGLContext.setDepthFunc(gl,this.depthTest); } switch (this.blend){ case 0: WebGLContext.setBlend(gl,false); break ; case 1: WebGLContext.setBlend(gl,true); WebGLContext.setBlendFunc(gl,this.srcBlend,this.dstBlend); break ; case 2: WebGLContext.setBlend(gl,true); break ; } } /** *设置渲染相关状态。 */ __proto._setRenderStateFrontFace=function(isTarget,transform){ var gl=WebGL.mainContext; var forntFace=0; switch (this.cull){ case 0: WebGLContext.setCullFace(gl,false); break ; case 1: WebGLContext.setCullFace(gl,true); if (isTarget){ if (transform && transform._isFrontFaceInvert) forntFace=/*laya.webgl.WebGLContext.CCW*/0x0901; else forntFace=/*laya.webgl.WebGLContext.CW*/0x0900; }else { if (transform && transform._isFrontFaceInvert) forntFace=/*laya.webgl.WebGLContext.CW*/0x0900; else forntFace=/*laya.webgl.WebGLContext.CCW*/0x0901; } WebGLContext.setFrontFace(gl,forntFace); break ; case 2: WebGLContext.setCullFace(gl,true); if (isTarget){ if (transform && transform._isFrontFaceInvert) forntFace=/*laya.webgl.WebGLContext.CW*/0x0900; else forntFace=/*laya.webgl.WebGLContext.CCW*/0x0901; }else { if (transform && transform._isFrontFaceInvert) forntFace=/*laya.webgl.WebGLContext.CCW*/0x0901; else forntFace=/*laya.webgl.WebGLContext.CW*/0x0900; } WebGLContext.setFrontFace(gl,forntFace); break ; } } /** *@inheritDoc */ __proto.onAsynLoaded=function(url,data,params){ var jsonData=data[0]; var textureMap=data[1]; switch (jsonData.version){ case "LAYAMATERIAL:01":; var i=0,n=0; var props=jsonData.props; for (var key in props){ switch (key){ case "vectors":; var vectors=props[key]; for (i=0,n=vectors.length;i < n;i++){ var vector=vectors[i]; var vectorValue=vector.value; switch (vectorValue.length){ case 2: this[vector.name]=new Vector2(vectorValue[0],vectorValue[1]); break ; case 3: this[vector.name]=new Vector3(vectorValue[0],vectorValue[1],vectorValue[2]); break ; case 4: this[vector.name]=new Vector4(vectorValue[0],vectorValue[1],vectorValue[2],vectorValue[3]); break ; default : throw new Error("BaseMaterial:unkonwn color length."); } } break ; case "textures":; var textures=props[key]; for (i=0,n=textures.length;i < n;i++){ var texture=textures[i]; var path=texture.path; (path)&& (this[texture.name]=Loader.getRes(textureMap[path])); } break ; case "defines":; var defineNames=props[key]; for (i=0,n=defineNames.length;i < n;i++){ var define=this._shaderCompile.getMaterialDefineByName(defineNames[i]); this._addShaderDefine(define); } break ; case "cull": case "blend": case "srcBlend": case "dstBlend": case "depthWrite": this[key]=props[key]; break ; case "renderQueue":; var queue=props[key]; switch (queue){ case 1: this.renderQueue=2000; break ; case 2: this.renderQueue=3000; break ; default : } break ; default : this[key]=props[key]; } } break ; case "LAYAMATERIAL:02": props=jsonData.props; for (key in props){ switch (key){ case "vectors": vectors=props[key]; for (i=0,n=vectors.length;i < n;i++){ vector=vectors[i]; vectorValue=vector.value; switch (vectorValue.length){ case 2: this[vector.name]=new Vector2(vectorValue[0],vectorValue[1]); break ; case 3: this[vector.name]=new Vector3(vectorValue[0],vectorValue[1],vectorValue[2]); break ; case 4: this[vector.name]=new Vector4(vectorValue[0],vectorValue[1],vectorValue[2],vectorValue[3]); break ; default : throw new Error("BaseMaterial:unkonwn color length."); } } break ; case "textures": textures=props[key]; for (i=0,n=textures.length;i < n;i++){ texture=textures[i]; path=texture.path; (path)&& (this[texture.name]=Loader.getRes(textureMap[path])); } break ; case "defines": defineNames=props[key]; for (i=0,n=defineNames.length;i < n;i++){ define=this._shaderCompile.getMaterialDefineByName(defineNames[i]); this._addShaderDefine(define); } break ; default : this[key]=props[key]; } } break ; default : throw new Error("BaseMaterial:unkonwn version."); } this._endLoaded(); } /** *@inheritDoc */ __proto._addReference=function(){ _super.prototype._addReference.call(this); var valueCount=this._values.length; for (var i=0,n=valueCount;i < n;i++){ var value=this._values[i]; if (value && (value instanceof laya.d3.resource.BaseTexture )) (value)._addReference(); } } /** *@inheritDoc */ __proto._removeReference=function(){ _super.prototype._removeReference.call(this); var valueCount=this._values.length; for (var i=0,n=valueCount;i < n;i++){ var value=this._values[i]; if (value && (value instanceof laya.d3.resource.BaseTexture )) (value)._removeReference(); } } /** *@inheritDoc */ __proto.disposeResource=function(){ this.blendConstColor=null; this._shader=null; this._shaderValues=null; var valueCount=this._values.length; for (var i=0,n=valueCount;i < n;i++){ var value=this._values[i]; if (value && (value instanceof laya.d3.resource.BaseTexture )) (value)._removeReference(); } this._values=null; } /** *设置使用Shader名字。 *@param name 名称。 */ __proto.setShaderName=function(name){ var nameID=Shader3D.nameKey.getID(name); if (nameID===-1) throw new Error("BaseMaterial: unknown shader name."); this._shaderCompile=ShaderCompile3D._preCompileShader[nameID]; } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var destBaseMaterial=destObject; destBaseMaterial.name=this.name; destBaseMaterial.cull=this.cull; destBaseMaterial.blend=this.blend; destBaseMaterial.srcBlend=this.srcBlend; destBaseMaterial.dstBlend=this.dstBlend; destBaseMaterial.srcBlendRGB=this.srcBlendRGB; destBaseMaterial.dstBlendRGB=this.dstBlendRGB; destBaseMaterial.srcBlendAlpha=this.srcBlendAlpha; destBaseMaterial.dstBlendAlpha=this.dstBlendAlpha; this.blendConstColor.cloneTo(destBaseMaterial.blendConstColor); destBaseMaterial.blendEquation=this.blendEquation; destBaseMaterial.blendEquationRGB=this.blendEquationRGB; destBaseMaterial.blendEquationAlpha=this.blendEquationAlpha; destBaseMaterial.depthTest=this.depthTest; destBaseMaterial.depthWrite=this.depthWrite; destBaseMaterial.renderQueue=this.renderQueue; destBaseMaterial._shader=this._shader; destBaseMaterial._disablePublicShaderDefine=this._disablePublicShaderDefine; destBaseMaterial._shaderDefineValue=this._shaderDefineValue; var i=0,n=0; var destShaderValues=destBaseMaterial._shaderValues; destBaseMaterial._shaderValues.data.length=this._shaderValues.data.length; var valueCount=this._values.length; var destValues=destBaseMaterial._values; destValues.length=valueCount; for (i=0,n=valueCount;i < n;i++){ var value=this._values[i]; if (value){ if ((typeof value=='number')){ destValues[i]=value; destShaderValues.data[i]=value; }else if (((typeof value=='number')&& Math.floor(value)==value)){ destValues[i]=value; destShaderValues.data[i]=value; }else if ((typeof value=='boolean')){ destValues[i]=value; destShaderValues.data[i]=value; }else if ((value instanceof laya.d3.math.Vector2 )){ var v2=(destValues[i])|| (destValues[i]=new Vector2()); (value).cloneTo(v2); destShaderValues.data[i]=v2.elements; }else if ((value instanceof laya.d3.math.Vector3 )){ var v3=(destValues[i])|| (destValues[i]=new Vector3()); (value).cloneTo(v3); destShaderValues.data[i]=v3.elements; }else if ((value instanceof laya.d3.math.Vector4 )){ var v4=(destValues[i])|| (destValues[i]=new Vector4()); (value).cloneTo(v4); destShaderValues.data[i]=v4.elements; }else if ((value instanceof laya.d3.math.Matrix4x4 )){ var mat=(destValues[i])|| (destValues[i]=new Matrix4x4()); (value).cloneTo(mat); destShaderValues.data[i]=mat.elements; }else if ((value instanceof laya.d3.resource.BaseTexture )){ destValues[i]=value; destShaderValues.data[i]=value; } } } } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destBaseMaterial=/*__JS__ */new this.constructor(); this.cloneTo(destBaseMaterial); return destBaseMaterial; } /** *设置透明测试模式裁剪值。 *@param value 透明测试模式裁剪值。 */ /** *获取透明测试模式裁剪值。 *@return 透明测试模式裁剪值。 */ __getset(0,__proto,'alphaTestValue',function(){ return this._getNumber(0); },function(value){ this._setNumber(0,value); }); /** *设置是否透明裁剪。 *@param value 是否透明裁剪。 */ /** *获取是否透明裁剪。 *@return 是否透明裁剪。 */ __getset(0,__proto,'alphaTest',function(){ return this._alphaTest; },function(value){ this._alphaTest=value; if (value) this._addShaderDefine(laya.d3.core.material.BaseMaterial.SHADERDEFINE_ALPHATEST); else this._removeShaderDefine(laya.d3.core.material.BaseMaterial.SHADERDEFINE_ALPHATEST); }); BaseMaterial.__init__=function(){ BaseMaterial.SHADERDEFINE_ALPHATEST=BaseMaterial.shaderDefines.registerDefine("ALPHATEST"); } BaseMaterial.RENDERQUEUE_OPAQUE=2000; BaseMaterial.RENDERQUEUE_ALPHATEST=2450; BaseMaterial.RENDERQUEUE_TRANSPARENT=3000; BaseMaterial.CULL_NONE=0; BaseMaterial.CULL_FRONT=1; BaseMaterial.CULL_BACK=2; BaseMaterial.BLEND_DISABLE=0; BaseMaterial.BLEND_ENABLE_ALL=1; BaseMaterial.BLEND_ENABLE_SEPERATE=2; BaseMaterial.BLENDPARAM_ZERO=0; BaseMaterial.BLENDPARAM_ONE=1; BaseMaterial.BLENDPARAM_SRC_COLOR=0x0300; BaseMaterial.BLENDPARAM_ONE_MINUS_SRC_COLOR=0x0301; BaseMaterial.BLENDPARAM_DST_COLOR=0x0306; BaseMaterial.BLENDPARAM_ONE_MINUS_DST_COLOR=0x0307; BaseMaterial.BLENDPARAM_SRC_ALPHA=0x0302; BaseMaterial.BLENDPARAM_ONE_MINUS_SRC_ALPHA=0x0303; BaseMaterial.BLENDPARAM_DST_ALPHA=0x0304; BaseMaterial.BLENDPARAM_ONE_MINUS_DST_ALPHA=0x0305; BaseMaterial.BLENDPARAM_SRC_ALPHA_SATURATE=0x0308; BaseMaterial.BLENDEQUATION_ADD=0; BaseMaterial.BLENDEQUATION_SUBTRACT=1; BaseMaterial.BLENDEQUATION_REVERSE_SUBTRACT=2; BaseMaterial.DEPTHTEST_OFF=0; BaseMaterial.DEPTHTEST_NEVER=0x0200; BaseMaterial.DEPTHTEST_LESS=0x0201; BaseMaterial.DEPTHTEST_EQUAL=0x0202; BaseMaterial.DEPTHTEST_LEQUAL=0x0203; BaseMaterial.DEPTHTEST_GREATER=0x0204; BaseMaterial.DEPTHTEST_NOTEQUAL=0x0205; BaseMaterial.DEPTHTEST_GEQUAL=0x0206; BaseMaterial.DEPTHTEST_ALWAYS=0x0207; BaseMaterial.SHADERDEFINE_ALPHATEST=0x1; BaseMaterial.ALPHATESTVALUE=0; __static(BaseMaterial, ['shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1();} ]); return BaseMaterial; })(Resource) /** *BaseTexture 纹理的父类,抽象类,不允许实例。 */ //class laya.d3.resource.BaseTexture extends laya.resource.Resource var BaseTexture=(function(_super){ function BaseTexture(){ /**@private */ this._type=0; /**@private */ this._width=0; /**@private */ this._height=0; /**@private */ this._size=null; /**@private */ this._repeat=false; /**@private */ this._mipmap=false; /**@private */ this._minFifter=0; /**@private */ this._magFifter=0; /**@private */ this._format=0; /**@private */ this._source=null; /**@private */ this._conchTexture=null; /**@private */ this._wrapModeU=0; /**@private */ this._wrapModeV=0; BaseTexture.__super.call(this); this._repeat=true; this.mipmap=true; this.minFifter=-1; this.magFifter=-1; } __class(BaseTexture,'laya.d3.resource.BaseTexture',_super); var __proto=BaseTexture.prototype; /** *获取宽度。 */ __getset(0,__proto,'width',function(){ return this._width; }); /** *是否使用重复模式纹理寻址 */ /** *是否使用重复模式纹理寻址 */ __getset(0,__proto,'repeat',function(){ return this._repeat; },function(value){ if (this._repeat!==value){ this._repeat=value; if (this._source){ var gl=WebGL.mainContext; WebGLContext.bindTexture(gl,this._type,this._source); var isPot=Arith.isPOT(this._width,this._height); if (isPot && this._repeat){ gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,/*laya.webgl.WebGLContext.REPEAT*/0x2901); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,/*laya.webgl.WebGLContext.REPEAT*/0x2901); }else { gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); } } } }); /** *获取高度。 */ __getset(0,__proto,'height',function(){ return this._height; }); /** *放大过滤器 */ /** *放大过滤器 */ __getset(0,__proto,'magFifter',function(){ return this._magFifter; },function(value){ this._magFifter=value; if (value !=this._magFifter){ this._conchTexture && this._conchTexture.setMaxFifter(value); } }); /** *获取纹理纵向循环模式。 */ __getset(0,__proto,'wrapModeV',function(){ return this._wrapModeV; }); /** *获取尺寸。 */ __getset(0,__proto,'size',function(){ return this._size; }); /** *获取纹理横向循环模式。 */ __getset(0,__proto,'wrapModeU',function(){ return this._wrapModeU; }); /** *是否使用mipLevel */ /** *是否使用mipLevel */ __getset(0,__proto,'mipmap',function(){ return this._mipmap; },function(value){ this._mipmap=value; if (this._mipmap !=value){ this._conchTexture && this._conchTexture.setMipMap(value); } }); /** *缩小过滤器 */ /** *缩小过滤器 */ __getset(0,__proto,'minFifter',function(){ return this._minFifter; },function(value){ this._minFifter=value; if (this._minFifter !=value){ this._conchTexture && this._conchTexture.setMinFifter(value); } }); /** *纹理格式 */ __getset(0,__proto,'format',function(){ return this._format; }); /** *获取纹理资源。 */ __getset(0,__proto,'source',function(){ this.activeResource(); return this._source; }); /** *获取纹理资源。 */ __getset(0,__proto,'defaulteTexture',function(){ return SolidColorTexture2D.grayTexture; }); BaseTexture.WARPMODE_REPEAT=0; BaseTexture.WARPMODE_CLAMP=1; return BaseTexture; })(Resource) /** *BaseMesh 类用于创建网格,抽象类,不允许实例。 */ //class laya.d3.resource.models.BaseMesh extends laya.resource.Resource var BaseMesh=(function(_super){ function BaseMesh(){ /**@private */ this._subMeshCount=0; /**@private */ this._boundingBox=null; /**@private */ this._boundingSphere=null; /**@private */ this._boundingBoxCorners=null; /**@private 只读,不允许修改。*/ this._positions=null; BaseMesh.__super.call(this); this._boundingBoxCorners=__newvec(8,null); } __class(BaseMesh,'laya.d3.resource.models.BaseMesh',_super); var __proto=BaseMesh.prototype; /** *获取网格顶点,请重载此方法。 *@return 网格顶点。 */ __proto._getPositions=function(){ throw new Error("未Override,请重载该属性!"); } /** *@private */ __proto._generateBoundingObject=function(){ this._boundingSphere=new BoundSphere(new Vector3(),0); BoundSphere.createfromPoints(this._positions,this._boundingSphere); this._boundingBox=new BoundBox(new Vector3(),new Vector3()); BoundBox.createfromPoints(this._positions,this._boundingBox); this._boundingBox.getCorners(this._boundingBoxCorners); } /** *获取渲染单元数量,请重载此方法。 *@return 渲染单元数量。 */ __proto.getRenderElementsCount=function(){ throw new Error("未Override,请重载该属性!"); } /** *获取渲染单元,请重载此方法。 *@param index 索引。 *@return 渲染单元。 */ __proto.getRenderElement=function(index){ throw new Error("未Override,请重载该属性!"); } /** *获取SubMesh的个数。 *@return SubMesh的个数。 */ __getset(0,__proto,'subMeshCount',function(){ return this._subMeshCount; }); /** *获取AABB包围盒,禁止修改其数据。 *@return AABB包围盒。 */ __getset(0,__proto,'boundingBox',function(){ return this._boundingBox; }); /** *获取包围球顶点,禁止修改其数据。 *@return 包围球。 */ __getset(0,__proto,'boundingBoxCorners',function(){ return this._boundingBoxCorners; }); /** *获取包围球,禁止修改其数据。 *@return 包围球。 */ __getset(0,__proto,'boundingSphere',function(){ return this._boundingSphere; }); return BaseMesh; })(Resource) /** *TerrainHeightData 类用于描述地形高度信息。 */ //class laya.d3.terrain.TerrainHeightData extends laya.resource.Resource var TerrainHeightData=(function(_super){ function TerrainHeightData(){ this._terrainHeightData=null; this._width=0; this._height=0; this._bitType=0; this._value=NaN; TerrainHeightData.__super.call(this); } __class(TerrainHeightData,'laya.d3.terrain.TerrainHeightData',_super); var __proto=TerrainHeightData.prototype; /** *异步回调 */ __proto.onAsynLoaded=function(url,data,params){ this._width=params[0]; this._height=params[1]; this._bitType=params[2]; this._value=params[3]; var buffer; var ratio=NaN; if (this._bitType==8){ buffer=new Uint8Array(data); ratio=1.0 / 255.0; } else if (this._bitType==16){ buffer=new Int16Array(data); ratio=1.0 / 32766.0; } this._terrainHeightData=new Float32Array(this._height *this._width); for (var i=0,n=this._height *this._width;i < n;i++){ this._terrainHeightData[i]=(buffer[i] *ratio *this._value)/2; } this._endLoaded(); } TerrainHeightData.load=function(url,widht,height,bitType,value){ return Laya.loader.create(url,null,null,TerrainHeightData,[widht,height,bitType,value],1,false); } return TerrainHeightData; })(Resource) /** *TerrainRes 类用于描述地形信息。 */ //class laya.d3.terrain.TerrainRes extends laya.resource.Resource var TerrainRes=(function(_super){ function TerrainRes(){ this._version=NaN; this._cameraCoordinateInverse=false; this._gridSize=NaN; this._chunkNumX=0; this._chunkNumZ=0; this._heightDataX=0; this._heightDataZ=0; this._heightDataBitType=0; this._heightDataValue=NaN; this._heightDataUrl=null; this._detailTextureInfos=null; this._chunkInfos=null; this._heightData=null; this._materialInfo=null; this._alphaMaps=null; this._normalMaps=null; TerrainRes.__super.call(this); } __class(TerrainRes,'laya.d3.terrain.TerrainRes',_super); var __proto=TerrainRes.prototype; __proto.parseData=function(data){ var json=data[0]; var resouMap=data[1]; this._version=json.version; if (this._version==1.0){ this._cameraCoordinateInverse=json.cameraCoordinateInverse; this._gridSize=json.gridSize; this._chunkNumX=json.chunkNumX; this._chunkNumZ=json.chunkNumZ; var heightData=json.heightData; this._heightDataX=heightData.numX; this._heightDataZ=heightData.numZ; this._heightDataBitType=heightData.bitType; this._heightDataValue=heightData.value; this._heightDataUrl=resouMap[heightData.url]; this._materialInfo=new MaterialInfo(); if (json.material){ var ambient=json.material.ambient; var diffuse=json.material.diffuse; var specular=json.material.specular; this._materialInfo.ambientColor=new Vector3(ambient[0],ambient[1],ambient[2]); this._materialInfo.diffuseColor=new Vector3(diffuse[0],diffuse[1],diffuse[2]); this._materialInfo.specularColor=new Vector4(specular[0],specular[1],specular[2],specular[3]); }; var detailTextures=json.detailTexture; this._detailTextureInfos=__newvec(detailTextures.length); for (var i=0;i < detailTextures.length;i++){ var detail=detailTextures[i]; var info=new DetailTextureInfo(); info.diffuseTexture=resouMap[detail.diffuse]; info.normalTexture=detail.normal ? resouMap[detail.normal] :null; if (detail.scale){ info.scale=new Vector2(detail.scale[0],detail.scale[1]); }else { info.scale=new Vector2(1,1); } if (detail.offset){ info.offset=new Vector2(detail.offset[0],detail.offset[1]); }else { info.offset=new Vector2(0,0); } this._detailTextureInfos[i]=info; }; var alphaMaps=json.alphaMap; this._alphaMaps=__newvec(alphaMaps.length); for (i=0;i < this._alphaMaps.length;i++){ this._alphaMaps[i]=json.alphaMap[i]; }; var normalMaps=json.normalMap; this._normalMaps=__newvec(normalMaps.length); for (i=0;i < this._normalMaps.length;i++){ this._normalMaps[i]=json.normalMap[i]; }; var jchunks=json.chunkInfo; if (this._chunkNumX *this._chunkNumZ !=jchunks.length){ alert("terrain data error"); return false; } this._chunkInfos=__newvec(jchunks.length); for (i=0;i < jchunks.length;i++){ var jchunk=jchunks[i]; var chunkinfo=new ChunkInfo(); var nAlphaMapNum=jchunk.alphaMap.length; var nDetailIDNum=jchunk.detailID.length; if (nAlphaMapNum !=nDetailIDNum){ alert("terrain chunk data error"); return false; } chunkinfo.alphaMap=__newvec(nAlphaMapNum); chunkinfo.detailID=__newvec(nDetailIDNum); chunkinfo.normalMap=resouMap[this._normalMaps[jchunk.normalMap]]; for (var j=0;j < nAlphaMapNum;j++){ chunkinfo.alphaMap[j]=resouMap[this._alphaMaps[jchunk.alphaMap[j]]]; var jid=jchunk.detailID[j]; var nIDNum=jid.length; chunkinfo.detailID[j]=new Uint8Array(nIDNum); for (var k=0;k < nIDNum;k++){ chunkinfo.detailID[j][k]=jid[k]; } } this._chunkInfos[i]=chunkinfo; } this._heightData=Loader.getRes(this._heightDataUrl); this.onLoadTerrainComplete(this._heightData); } return true; } __proto.onLoadTerrainComplete=function(heightData){ this._endLoaded(); } /** *异步回调 */ __proto.onAsynLoaded=function(url,data,params){ this.parseData(data); } TerrainRes.load=function(url){ return Laya.loader.create(url,null,null,TerrainRes,null,1,false); } return TerrainRes; })(Resource) /** *KeyframeAnimation 类用于帧动画组件的父类。 */ //class laya.d3.component.animation.KeyframeAnimations extends laya.d3.component.Component3D var KeyframeAnimations=(function(_super){ function KeyframeAnimations(){ /**动画播放器。*/ this._player=null; /**@private */ this._templet=null; KeyframeAnimations.__super.call(this); this._player=new AnimationPlayer(); } __class(KeyframeAnimations,'laya.d3.component.animation.KeyframeAnimations',_super); var __proto=KeyframeAnimations.prototype; /** *@private */ __proto._updateAnimtionPlayer=function(){ this._player._update(Laya.timer.delta); } /** *@private */ __proto._addUpdatePlayerToTimer=function(){ Laya.timer.frameLoop(1,this,this._updateAnimtionPlayer); } /** *@private */ __proto._removeUpdatePlayerToTimer=function(){ Laya.timer.clear(this,this._updateAnimtionPlayer); } /** *@private */ __proto._onOwnerActiveHierarchyChanged=function(active){ if ((this._owner).displayedInStage){ if (active) this._addUpdatePlayerToTimer(); else this._removeUpdatePlayerToTimer(); } } /** *@private *载入组件时执行 */ __proto._load=function(owner){ ((owner).activeInHierarchy)&& (this._addUpdatePlayerToTimer()); owner.on(/*laya.events.Event.ACTIVE_IN_HIERARCHY_CHANGED*/"activeinhierarchychanged",this,this._onOwnerActiveHierarchyChanged); } /** *@private *卸载组件时执行 */ __proto._unload=function(owner){ _super.prototype._unload.call(this,owner); ((owner).activeInHierarchy)&& (this._removeUpdatePlayerToTimer()); owner.off(/*laya.events.Event.ACTIVE_IN_HIERARCHY_CHANGED*/"activeinhierarchychanged",this,this._onOwnerActiveHierarchyChanged); this._player._destroy(); this._player=null; this._templet=null; } /** *设置url地址。 *@param value 地址。 */ __getset(0,__proto,'url',null,function(value){ console.log("Warning: discard property,please use templet property instead."); var templet=Laya.loader.create(value,null,null,AnimationTemplet); if (this._templet!==templet){ if (this._player.state!==/*laya.ani.AnimationState.stopped*/0) this._player.stop(true); this._templet=templet; this._player.templet=templet; this.event(/*laya.events.Event.ANIMATION_CHANGED*/"animationchanged",this); } }); /** *获取动画播放器。 *@return 动画播放器。 */ __getset(0,__proto,'player',function(){ return this._player; }); /** *设置动画模板。 *@param value 设置动画模板。 */ /** *获取动画模板。 *@return value 动画模板。 */ __getset(0,__proto,'templet',function(){ return this._templet; },function(value){ if (this._templet!==value){ if (this._player.state!==/*laya.ani.AnimationState.stopped*/0) this._player.stop(true); this._templet=value; this._player.templet=value; this.event(/*laya.events.Event.ANIMATION_CHANGED*/"animationchanged",this); } }); /** *获取播放器帧数。 *@return 播放器帧数。 */ __getset(0,__proto,'currentFrameIndex',function(){ return this._player.currentKeyframeIndex; }); /** *获取播放器的动画索引。 *@return 动画索引。 */ __getset(0,__proto,'currentAnimationClipIndex',function(){ return this._player.currentAnimationClipIndex; }); /** *获取播放器当前动画的节点数量。 *@return 节点数量。 */ __getset(0,__proto,'nodeCount',function(){ return this._templet.getNodeCount(this._player.currentAnimationClipIndex); }); return KeyframeAnimations; })(Component3D) /** *Animations 类用于创建动画组件。 */ //class laya.d3.component.Animator extends laya.d3.component.Component3D var Animator=(function(_super){ function Animator(){ /**@private */ //this._updateTransformPropertyLoopCount=0; /**@private */ //this._cacheFrameRateInterval=NaN; /**@private */ //this._cacheFrameRate=0; /**@private */ //this._cachePlayRate=NaN; /**@private */ //this._currentPlayClip=null; /**@private */ //this._currentPlayClipIndex=0; /**@private */ //this._stoped=false; /**@private */ //this._currentTime=NaN; /**@private */ //this._currentFrameTime=NaN; /**@private */ //this._currentFrameIndex=0; /**@private */ //this._elapsedPlaybackTime=NaN; /**@private */ //this._startUpdateLoopCount=NaN; /**@private */ //this._clipNames=null; /**@private */ //this._clips=null; /**@private */ //this._playStartFrames=null; /**@private */ //this._playEndFrames=null; /**@private */ //this._playEventIndex=0; /**@private */ //this._defaultClipIndex=0; /**@private */ //this._avatar=null; /**@private */ //this._cacheNodesDefaultlValues=null; /**@private 无Avatar时缓存场景树中的精灵节点。*/ //this._cacheNodesSpriteOwners=null; /**@private 有Avatar时缓存Avatar树中的AnimationNode节点。*/ //this._cacheNodesAvatarOwners=null; /**@private */ //this._lastPlayAnimationClip=null; /**@private */ //this._lastPlayAnimationClipIndex=0; /**@private */ //this._publicClipsDatas=null; /**@private */ //this._publicAvatarNodeDatas=null; /**@private */ //this._curAvatarNodeDatas=null; /**@private */ //this._cacheNodesToSpriteMap=null; /**@private */ //this._cacheSpriteToNodesMap=null; /**@private */ //this._cacheFullFrames=null; /**@private */ //this._linkSpritesData=null; /**@private */ //this._avatarNodeMap=null; /**@private */ //this._avatarNodes=null; /**@private */ //this._canCache=false; /**@private */ //this._lastFrameIndex=0; /**是否为缓存模式*/ //this.isCache=false; /**播放速率*/ //this.playbackRate=NaN; /**激活时是否自动播放*/ //this.playOnWake=false; Animator.__super.call(this); this._clipNames=[]; this._clips=[]; this._playStartFrames=[]; this._playEndFrames=[]; this._cacheNodesSpriteOwners=[]; this._cacheNodesAvatarOwners=[]; this._cacheNodesDefaultlValues=[]; this._cacheNodesToSpriteMap=[]; this._cacheSpriteToNodesMap=[]; this._cacheFullFrames=[]; this._publicClipsDatas=[]; this._playEventIndex=-1; this._updateTransformPropertyLoopCount=-1; this._lastFrameIndex=-1; this._defaultClipIndex=-1; this._cachePlayRate=1.0; this._currentPlayClip=null; this._currentFrameIndex=-1; this._currentTime=0.0; this._elapsedPlaybackTime=0; this._startUpdateLoopCount=-1; this.isCache=true; this.cacheFrameRate=60; this.playbackRate=1.0; this.playOnWake=true; } __class(Animator,'laya.d3.component.Animator',_super); var __proto=Animator.prototype; Laya.imps(__proto,{"laya.resource.IDestroy":true}) /** *@private */ __proto._getAvatarOwnersByClip=function(clipIndex){ var frameNodes=this._clips[clipIndex]._nodes; var frameNodesCount=frameNodes.length; var owners=this._cacheNodesAvatarOwners[clipIndex]; owners.length=frameNodesCount; var defaultValues=this._cacheNodesDefaultlValues[clipIndex]; defaultValues.length=frameNodesCount; for (var i=0;i < frameNodesCount;i++){ var nodeOwner=this._avatarNodes[0]; var node=frameNodes[i]; var path=node.path; for (var j=0,m=path.length;j < m;j++){ var p=path[j]; if (p===""){ break ; }else { nodeOwner=nodeOwner.getChildByName(p); if (!nodeOwner) break ; } } if (!nodeOwner) continue ; owners[i]=nodeOwner; var datas=AnimationNode._propertyGetFuncs[node.propertyNameID](nodeOwner); if (datas){ var cacheDatas=new Float32Array(node.keyFrameWidth); defaultValues[i]=cacheDatas; for (j=0,m=datas.length;j < m;j++) cacheDatas[j]=datas[j]; } } } /** *@private */ __proto._handleSpriteOwnersByClip=function(clipIndex){ var frameNodes=this._clips[clipIndex]._nodes; var frameNodesCount=frameNodes.length; var owners=this._cacheNodesSpriteOwners[clipIndex]; owners.length=frameNodesCount; var defaultValues=this._cacheNodesDefaultlValues[clipIndex]; defaultValues.length=frameNodesCount; for (var i=0;i < frameNodesCount;i++){ var nodeOwner=this._owner; var node=frameNodes[i]; var path=node.path; var j=0,m=0; for (j=0,m=path.length;j < m;j++){ var p=path[j]; if (p===""){ break ; }else { nodeOwner=nodeOwner.getChildByName(p); if (!nodeOwner) break ; } } if (nodeOwner){ owners[i]=nodeOwner; var datas=AnimationNode._propertyGetFuncs[node.propertyNameID](null,nodeOwner); if (datas){ var cacheDatas=new Float32Array(node.keyFrameWidth); defaultValues[i]=cacheDatas; for (j=0,m=datas.length;j < m;j++) cacheDatas[j]=datas[j]; } } } } /** *@private */ __proto._offClipAndAvatarRelateEvent=function(avatar,clip){ if (avatar.loaded){ if (!clip.loaded) clip.off(/*laya.events.Event.LOADED*/"loaded",this,this._getAvatarOwnersByClip); }else { avatar.off(/*laya.events.Event.LOADED*/"loaded",this,this._getAvatarOwnersAndInitDatasAsync); } } /** *@private */ __proto._getAvatarOwnersByClipAsync=function(clipIndex,clip){ if (clip.loaded) this._getAvatarOwnersByClip(clipIndex); else clip.once(/*laya.events.Event.LOADED*/"loaded",this,this._getAvatarOwnersByClip,[clipIndex]); } /** *@private */ __proto._offGetSpriteOwnersByClipAsyncEvent=function(clip){ if (!clip.loaded) clip.off(/*laya.events.Event.LOADED*/"loaded",this,this._getSpriteOwnersByClipAsync); } /** *@private */ __proto._getSpriteOwnersByClipAsync=function(clipIndex,clip){ if (clip.loaded) this._handleSpriteOwnersByClip(clipIndex); else clip.once(/*laya.events.Event.LOADED*/"loaded",this,this._handleSpriteOwnersByClip,[clipIndex]); } /** *@private */ __proto._getAvatarOwnersAndInitDatasAsync=function(){ for (var i=0,n=this._clips.length;i < n;i++) this._getAvatarOwnersByClipAsync(i,this._clips[i]); this._avatar._cloneDatasToAnimator(this); for (i=0,n=this._avatarNodes.length;i < n;i++) this._checkAnimationNode(this._avatarNodes[i],this._owner); } /** *@private */ __proto._offGetClipCacheFullKeyframeIndicesEvent=function(clip){ (clip.loaded)|| (clip.off(/*laya.events.Event.LOADED*/"loaded",this,this._computeCacheFullKeyframeIndices)); } /** *@private */ __proto._computeCacheFullKeyframeIndices=function(clipIndex){ var clip=this._clips[clipIndex]; var cacheInterval=this._cacheFrameRateInterval *this._cachePlayRate; var clipCacheFullFrames=clip._getFullKeyframeIndicesWithCache(cacheInterval); if (clipCacheFullFrames){ this._cacheFullFrames[clipIndex]=clipCacheFullFrames; return; }else { clipCacheFullFrames=this._cacheFullFrames[clipIndex]=[]; var nodes=clip._nodes; var nodeCount=nodes.length; clipCacheFullFrames.length=nodeCount; var frameCount=Math.ceil(clip._duration / cacheInterval-0.00001)+1; for (var i=0;i < nodeCount;i++){ var node=nodes[i]; var nodeFullFrames=new Int32Array(frameCount); (nodeFullFrames).fill(-1); var keyFrames=node.keyFrames; for (var j=0,n=keyFrames.length;j < n;j++){ var keyFrame=keyFrames[j]; var startTime=keyFrame.startTime; var endTime=startTime+keyFrame.duration; while (startTime <=endTime){ var frameIndex=Math.ceil(startTime / cacheInterval-0.00001); nodeFullFrames[frameIndex]=j; startTime+=cacheInterval; } } clipCacheFullFrames[i]=nodeFullFrames; } clip._cacheFullKeyframeIndices(cacheInterval,clipCacheFullFrames); } } /** *@private */ __proto._updateAnimtionPlayer=function(){ this._updatePlayer(Laya.timer.delta / 1000.0); } /** *@private */ __proto._onOwnerActiveHierarchyChanged=function(){ var owner=this._owner; if (owner.activeInHierarchy){ Laya.timer.frameLoop(1,this,this._updateAnimtionPlayer); (this.playOnWake && this.clip)&& (this.play()); }else { (this.playState!==/*laya.ani.AnimationState.stopped*/0)&& (this._stoped=true); Laya.timer.clear(this,this._updateAnimtionPlayer); } } /** *@private */ __proto._eventScript=function(from,to){ var events=this._currentPlayClip._animationEvents; for (var n=events.length;this._playEventIndex < n;this._playEventIndex++){ var eve=events[this._playEventIndex]; var eventTime=eve.time; if (from <=eventTime && eventTime < to){ var scripts=this._owner._scripts; for (var j=0,m=scripts.length;j < m;j++){ var script=scripts[j]; var fun=script[eve.eventName]; (fun)&& (fun.apply(script,eve.params)); } }else { break ; } } } /** *@private */ __proto._setPlayParams=function(time,cacheFrameInterval){ var lastTime=this._currentTime; this._currentTime=time; this._currentFrameIndex=Math.max(Math.floor(this.currentPlayTime / cacheFrameInterval-0.00001),0); this._currentFrameTime=this._currentFrameIndex *cacheFrameInterval; this._eventScript(lastTime,time); } /** *@private */ __proto._setPlayParamsWhenStop=function(aniClipPlayDuration,cacheFrameInterval){ var lastTime=this._currentTime; this._currentTime=aniClipPlayDuration; this._currentFrameIndex=Math.max(Math.floor(aniClipPlayDuration / cacheFrameInterval-0.00001),0); this._currentFrameTime=this._currentFrameIndex *cacheFrameInterval; this._eventScript(lastTime,aniClipPlayDuration); this._currentPlayClip=null; } /** *@private */ __proto._revertKeyframeNodes=function(clip,clipIndex){ var originalValues=this._cacheNodesDefaultlValues[clipIndex]; var frameNodes=clip._nodes; if (this._avatar){ var avatarOwners=this._cacheNodesAvatarOwners[clipIndex]; for (var i=0,n=avatarOwners.length;i < n;i++){ var avatarOwner=avatarOwners[i]; (avatarOwner)&& (AnimationNode._propertySetFuncs[frameNodes[i].propertyNameID](avatarOwner,null,originalValues[i])); } }else { var spriteOwners=this._cacheNodesSpriteOwners[clipIndex]; for (i=0,n=spriteOwners.length;i < n;i++){ var spriteOwner=spriteOwners[i]; (spriteOwner)&& (AnimationNode._propertySetFuncs[frameNodes[i].propertyNameID](null,spriteOwner,originalValues[i])); } } } /** *@private */ __proto._onAnimationStop=function(){ var i=0,n=0; var frameNode,keyFrames,endKeyframeData; this._lastFrameIndex=-1; var frameNodes=this._currentPlayClip._nodes; if (this._avatar){ var avatarOwners=this._cacheNodesAvatarOwners[this._currentPlayClipIndex]; for (i=0,n=avatarOwners.length;i < n;i++){ var nodeOwner=avatarOwners[i]; frameNode=frameNodes[i]; keyFrames=frameNode.keyFrames; endKeyframeData=keyFrames[keyFrames.length-1].data; (nodeOwner)&& (AnimationNode._propertySetFuncs[frameNode.propertyNameID](nodeOwner,null,endKeyframeData)); } }else { var spriteOwners=this._cacheNodesSpriteOwners[this._currentPlayClipIndex]; for (i=0,n=spriteOwners.length;i < n;i++){ var spriteOwner=spriteOwners[i]; frameNode=frameNodes[i]; keyFrames=frameNode.keyFrames; endKeyframeData=keyFrames[keyFrames.length-1].data; (spriteOwner)&& (AnimationNode._propertySetFuncs[frameNode.propertyNameID](null,spriteOwner,endKeyframeData)); } } } /** *@private */ __proto._setAnimationClipPropertyToAnimationNode=function(nodeOwners,propertyMap,clipDatas){ for (var i=0,n=propertyMap.length;i < n;i++){ var nodexIndex=propertyMap[i]; var owner=nodeOwners[nodexIndex]; if (owner){ var ketframeNode=this._currentPlayClip._nodes[nodexIndex]; var datas=clipDatas[nodexIndex]; (datas)&& (AnimationNode._propertySetFuncs[ketframeNode.propertyNameID](owner,null,datas)); } } } /** *@private */ __proto._setAnimationClipPropertyToSprite3D=function(nodeOwners,curClipAnimationDatas){ for (var i=0,n=nodeOwners.length;i < n;i++){ var owner=nodeOwners[i]; if (owner){ var ketframeNode=this._currentPlayClip._nodes[i]; var datas=curClipAnimationDatas[i]; (datas)&& (AnimationNode._propertySetFuncs[ketframeNode.propertyNameID](null,owner,datas)); } } } /** *@private */ __proto._handleSpriteOwnersBySprite=function(clipIndex,isLink,path,sprite){ var clip=this._clips[clipIndex]; var nodePath=path.join("/"); var ownersNodes=clip._nodesMap[nodePath]; if (ownersNodes){ var owners=this._cacheNodesSpriteOwners[clipIndex]; var nodes=clip._nodes; var defaultValues=this._cacheNodesDefaultlValues[clipIndex]; for (var i=0,n=ownersNodes.length;i < n;i++){ var node=ownersNodes[i]; var index=nodes.indexOf(node); if (isLink){ owners[index]=sprite; var datas=AnimationNode._propertyGetFuncs[node.propertyNameID](null,sprite); if (datas){ var cacheDatas=defaultValues[index]; (cacheDatas)|| (defaultValues[index]=cacheDatas=new Float32Array(node.keyFrameWidth)); for (var j=0,m=datas.length;j < m;j++) cacheDatas[j]=datas[j]; } }else { owners[index]=null; } } } } /** *@private */ __proto._evaluateAvatarNodesCacheMode=function(avatarOwners,clip,publicClipDatas,avatarNodeDatas,unCacheMap){ clip._evaluateAnimationlDatasCacheMode(avatarOwners,this._cacheFullFrames[this._currentPlayClipIndex],this,publicClipDatas,unCacheMap); this._setAnimationClipPropertyToAnimationNode(avatarOwners,unCacheMap,publicClipDatas); for (var i=0,n=this._avatarNodes.length;i < n;i++){ var node=this._avatarNodes[i]; var nodeTransform=node.transform; if (nodeTransform._worldUpdate){ var nodeMatrix=new Float32Array(16); avatarNodeDatas[i]=nodeMatrix; nodeTransform._setWorldMatrixAndUpdate(nodeMatrix); }else { var mat=nodeTransform.getWorldMatrix(); avatarNodeDatas[i]=mat ? mat :Animator.deafaultMatrix; } } } /** *@private */ __proto._evaluateAvatarNodesRealTime=function(avatarOwners,clip,publicClipDatas,avatarNodeDatas,unCacheMap){ clip._evaluateAnimationlDatasRealTime(avatarOwners,this.currentPlayTime,publicClipDatas,unCacheMap); this._setAnimationClipPropertyToAnimationNode(avatarOwners,unCacheMap,publicClipDatas); for (var i=0,n=this._avatarNodes.length;i < n;i++){ var transform=this._avatarNodes[i].transform; if (transform._worldUpdate) transform._setWorldMatrixNoUpdate(avatarNodeDatas[i]); else avatarNodeDatas[i]=Animator.deafaultMatrix; } } /** *@private */ __proto._updateAvatarNodesToSpriteCacheMode=function(clip,avatarNodeDatas){ for (var i=0,n=this._cacheSpriteToNodesMap.length;i < n;i++){ var nodeIndex=this._cacheSpriteToNodesMap[i]; var nodeMatrix=avatarNodeDatas[nodeIndex]; if (nodeMatrix!==Animator.deafaultMatrix){ var spriteTransform=this._avatarNodes[nodeIndex].transform._entity; var spriteWorldMatrix=spriteTransform.worldMatrix; Utils3D.matrix4x4MultiplyMFM((this._owner)._transform.worldMatrix,nodeMatrix,spriteWorldMatrix); spriteTransform.worldMatrix=spriteWorldMatrix; } } } /** *@private */ __proto._updateAvatarNodesToSpriteRealTime=function(){ for (var i=0,n=this._cacheSpriteToNodesMap.length;i < n;i++){ var node=this._avatarNodes[this._cacheSpriteToNodesMap[i]]; var spriteTransform=node.transform._entity; var nodeTransform=node.transform; if (nodeTransform._worldUpdate){ var nodeMatrix=Animator._tempMatrix4x40; nodeTransform._setWorldMatrixAndUpdate(nodeMatrix); var spriteWorldMatrix=spriteTransform.worldMatrix; Utils3D.matrix4x4MultiplyMFM((this._owner)._transform.worldMatrix,nodeMatrix,spriteWorldMatrix); spriteTransform.worldMatrix=spriteWorldMatrix; } } } /** *@private */ __proto._updatePlayer=function(elapsedTime){ if (this._currentPlayClip==null || this._stoped || !this._currentPlayClip.loaded) return; var cacheFrameInterval=this._cacheFrameRateInterval *this._cachePlayRate; var time=0; (this._startUpdateLoopCount!==Stat.loopCount)&& (time=elapsedTime *this.playbackRate,this._elapsedPlaybackTime+=time); var frameRate=this._currentPlayClip._frameRate; var playStart=this._playStartFrames[this._currentPlayClipIndex] / frameRate; var playEnd=Math.min(this._playEndFrames[this._currentPlayClipIndex] / frameRate,this._currentPlayClip._duration); var aniClipPlayDuration=playEnd-playStart; if ((!this._currentPlayClip.islooping && this._elapsedPlaybackTime >=aniClipPlayDuration)){ this._onAnimationStop(); this._setPlayParamsWhenStop(aniClipPlayDuration,cacheFrameInterval); this.event(/*laya.events.Event.STOPPED*/"stopped"); return; } time+=this._currentTime; if (aniClipPlayDuration > 0){ if (time >=aniClipPlayDuration){ do { time-=aniClipPlayDuration; if (time < aniClipPlayDuration){ this._setPlayParams(time,cacheFrameInterval); this.event(/*laya.events.Event.COMPLETE*/"complete"); } this._playEventIndex=0; this._eventScript(0,time); }while (time >=aniClipPlayDuration) }else { this._setPlayParams(time,cacheFrameInterval); } }else { this._currentTime=this._currentFrameTime=this._currentFrameIndex=this._playEventIndex=0; this.event(/*laya.events.Event.COMPLETE*/"complete"); } } /** *@private *更新蒙皮动画组件。 *@param state 渲染状态参数。 */ __proto._update=function(state){ var clip=this._currentPlayClip; if (this.playState!==/*laya.ani.AnimationState.playing*/2 || !clip || !clip.loaded) return; var rate=this.playbackRate *Laya.timer.scale; var cacheRate=this._cachePlayRate; this._canCache=this.isCache && rate >=cacheRate; var frameIndex=-1; var clipDatas; if (this._canCache){ frameIndex=this._currentFrameIndex; if (this._lastFrameIndex===frameIndex) return; clipDatas=clip._getAnimationDataWithCache(cacheRate,frameIndex); if (this._avatar){ var avatarOwners=this._cacheNodesAvatarOwners[this._currentPlayClipIndex]; var cacheMap=clip._cachePropertyMap; var cacheMapCount=cacheMap.length; if (cacheMapCount > 0){ if (!clipDatas){ clipDatas=[]; clipDatas.length=cacheMapCount; clip._cacheAnimationData(cacheRate,frameIndex,clipDatas); clip._evaluateAnimationlDatasCacheMode(avatarOwners,this._cacheFullFrames[this._currentPlayClipIndex],this,clipDatas,cacheMap); } this._setAnimationClipPropertyToAnimationNode(avatarOwners,cacheMap,clipDatas); } this._curAvatarNodeDatas=clip._getAvatarDataWithCache(this._avatar,this._cachePlayRate,frameIndex); if (!this._curAvatarNodeDatas){ this._curAvatarNodeDatas=[]; this._curAvatarNodeDatas.length=this._avatarNodes.length; clip._cacheAvatarData(this._avatar,this._cachePlayRate,frameIndex,this._curAvatarNodeDatas); this._evaluateAvatarNodesCacheMode(avatarOwners,clip,clip._publicClipDatas,this._curAvatarNodeDatas,clip._unCachePropertyMap); } this._updateAvatarNodesToSpriteCacheMode(clip,this._curAvatarNodeDatas); }else { var spriteOwners=this._cacheNodesSpriteOwners[this._currentPlayClipIndex]; if (!clipDatas){ clipDatas=[]; clipDatas.length=this._currentPlayClip._nodes.length; clip._evaluateAnimationlDatasCacheMode(spriteOwners,this._cacheFullFrames[this._currentPlayClipIndex],this,clipDatas,null); clip._cacheAnimationData(cacheRate,frameIndex,clipDatas); } this._setAnimationClipPropertyToSprite3D(spriteOwners,clipDatas); } }else { clipDatas=clip._publicClipDatas; if (this._avatar){ clip._evaluateAnimationlDatasRealTime(this._cacheNodesAvatarOwners[this._currentPlayClipIndex],this.currentPlayTime,clipDatas,clip._cachePropertyMap); if (!this._publicAvatarNodeDatas){ this._publicAvatarNodeDatas=[]; var nodeCount=this._avatarNodes.length; this._publicAvatarNodeDatas.length=nodeCount; for (var i=1;i < nodeCount;i++) this._publicAvatarNodeDatas[i]=new Float32Array(16); } this._curAvatarNodeDatas=this._publicAvatarNodeDatas; this._evaluateAvatarNodesRealTime(this._cacheNodesAvatarOwners[this._currentPlayClipIndex],clip,clipDatas,this._curAvatarNodeDatas,clip._unCachePropertyMap); this._updateAvatarNodesToSpriteRealTime(); }else { clip._evaluateAnimationlDatasRealTime(this._cacheNodesSpriteOwners[this._currentPlayClipIndex],this.currentPlayTime,clipDatas,null); } } this._lastFrameIndex=frameIndex; } /** *@private */ __proto._checkAnimationNode=function(node,sprite){ if (node.name===sprite.name && !sprite._transform.dummy) sprite._isLinkSpriteToAnimationNode(this,node,true); for (var i=0,n=sprite._childs.length;i < n;i++) this._checkAnimationNode(node,sprite.getChildAt(i)); } /** *@inheritDoc */ __proto._load=function(owner){ ((owner).activeInHierarchy)&& (Laya.timer.frameLoop(1,this,this._updateAnimtionPlayer)); this._owner.on(/*laya.events.Event.ACTIVE_IN_HIERARCHY_CHANGED*/"activeinhierarchychanged",this,this._onOwnerActiveHierarchyChanged); } /** *@inheritDoc */ __proto._unload=function(owner){ _super.prototype._unload.call(this,owner); ((owner).activeInHierarchy)&& (Laya.timer.clear(this,this._updateAnimtionPlayer)); this._owner.off(/*laya.events.Event.ACTIVE_IN_HIERARCHY_CHANGED*/"activeinhierarchychanged",this,this._onOwnerActiveHierarchyChanged); this._curAvatarNodeDatas=null; } /** *@private */ __proto._destroy=function(){ _super.prototype._destroy.call(this); for (var i=0,n=this._clips.length;i < n;i++) this._clips[i]._removeReference(); this._currentPlayClip=null; this._clipNames=null; this._cacheNodesSpriteOwners=null; this._cacheNodesAvatarOwners=null; this._cacheNodesDefaultlValues=null; this._clips=null; this._cacheFullFrames=null; } /** *@private */ __proto._cloneTo=function(dest){ var animator=dest; animator.avatar=this.avatar; var clipCount=this._clips.length; for (var i=0,n=this._clips.length;i < n;i++) animator.addClip(this._clips[i]); if (this.clip){ animator.clip=this.clip; } if (this._linkSpritesData){ animator._linkSpritesData={}; for (var k in this._linkSpritesData) animator._linkSpritesData[k]=this._linkSpritesData[k].slice(); } } /** *添加动画片段。 *@param clip 动画片段。 *@param playName 动画片段播放名称,如果为null,则使用clip.name作为播放名称。 *@param 开始帧率。 *@param 结束帧率。 */ __proto.addClip=function(clip,playName,startFrame,endFrame){ (startFrame===void 0)&& (startFrame=0); (endFrame===void 0)&& (endFrame=4294967295); playName=playName || clip.name; var index=this._clipNames.indexOf(playName); if (index!==-1){ if (this._clips[index]!==clip) throw new Error("Animation:this playName has exist with another clip."); }else { var clipIndex=this._clips.indexOf(clip); if (startFrame < 0 || endFrame < 0) throw new Error("Animator:startFrame and endFrame must large than zero."); if (startFrame > endFrame) throw new Error("Animator:startFrame must less than endFrame."); this._clipNames.push(playName); this._clips.push(clip); this._playStartFrames.push(startFrame); this._playEndFrames.push(endFrame); this._cacheNodesSpriteOwners.push([]); this._cacheNodesAvatarOwners.push([]); this._cacheNodesDefaultlValues.push([]); this._publicClipsDatas.push([]); clip._addReference(); clipIndex=this._clips.length-1; if (this._avatar){ if (this._avatar.loaded) this._getAvatarOwnersByClipAsync(clipIndex,clip); else this._avatar.once(/*laya.events.Event.LOADED*/"loaded",this,this._getAvatarOwnersByClipAsync,[clipIndex,clip]); }else { this._getSpriteOwnersByClipAsync(clipIndex,clip); } if (clip.loaded) this._computeCacheFullKeyframeIndices(clipIndex); else clip.once(/*laya.events.Event.LOADED*/"loaded",this,this._computeCacheFullKeyframeIndices,[clipIndex]); } } /** *移除动画片段。 *@param clip 动画片段。 */ __proto.removeClip=function(clip){ var index=this._clips.indexOf(clip); if (index!==-1){ if (this._avatar) this._offClipAndAvatarRelateEvent(this._avatar,clip) else this._offGetSpriteOwnersByClipAsyncEvent(clip); this._offGetClipCacheFullKeyframeIndicesEvent(clip); this._clipNames.splice(index,1); this._clips.splice(index,1); this._playStartFrames.splice(index,1); this._playEndFrames.splice(index,1); this._cacheNodesSpriteOwners.splice(index,1); this._cacheNodesAvatarOwners.splice(index,1); this._cacheNodesDefaultlValues.splice(index,1); this._publicClipsDatas.splice(index,1); clip._removeReference(); } } /** *通过播放名字移除动画片段。 *@param playName 播放名字。 */ __proto.removeClipByName=function(playName){ var index=this._clipNames.indexOf(playName); if (index!==-1){ var clip=this._clips[index]; if (this._avatar) this._offClipAndAvatarRelateEvent(this._avatar,clip); else this._offGetSpriteOwnersByClipAsyncEvent(clip); this._offGetClipCacheFullKeyframeIndicesEvent(clip); this._clipNames.splice(index,1); this._clips.splice(index,1); this._playStartFrames.splice(index,1); this._playEndFrames.splice(index,1); this._cacheNodesSpriteOwners.splice(index,1); this._cacheNodesAvatarOwners.splice(index,1); this._cacheNodesDefaultlValues.splice(index,1); this._publicClipsDatas.splice(index,1); } } /** *通过播放名字获取动画片段。 *@param playName 播放名字。 *@return 动画片段。 */ __proto.getClip=function(playName){ var index=this._clipNames.indexOf(playName); if (index!==-1){ return this._clips[index]; }else { return null; } } /** *获取动画片段个数。 *@return 动画个数。 */ __proto.getClipCount=function(){ return this._clips.length; } /** *播放动画。 *@param name 如果为null则播放默认动画,否则按名字播放动画片段。 *@param playbackRate 播放速率。 *@param startFrame 开始帧率。 *@param endFrame 结束帧率.-1表示为最大结束帧率。 */ __proto.play=function(name,playbackRate){ (playbackRate===void 0)&& (playbackRate=1.0); if (!name && this._defaultClipIndex==-1) throw new Error("Animator:must have default clip value,please set clip property."); if (name){ this._currentPlayClipIndex=this._clipNames.indexOf(name); this._currentPlayClip=this._clips[this._currentPlayClipIndex]; }else { this._currentPlayClipIndex=this._defaultClipIndex; this._currentPlayClip=this._clips[this._defaultClipIndex]; } this._currentTime=0; this._currentFrameTime=0; this._elapsedPlaybackTime=0; this._playEventIndex=0; this.playbackRate=playbackRate; this._stoped=false; this._currentFrameIndex=0; this._startUpdateLoopCount=Stat.loopCount; if (this._lastPlayAnimationClip) (this._lastPlayAnimationClip!==this._currentPlayClip)&& (this._revertKeyframeNodes(this._lastPlayAnimationClip,this._lastPlayAnimationClipIndex)); this._updatePlayer(0); this._lastPlayAnimationClip=this._currentPlayClip; this._lastPlayAnimationClipIndex=this._currentPlayClipIndex; } /** *停止播放当前动画 */ __proto.stop=function(){ if (this.playState!==/*laya.ani.AnimationState.stopped*/0){ this._stoped=true; this.event(/*laya.events.Event.STOPPED*/"stopped"); } } /** *@private */ __proto._getLinkSpritePath=function(sprite3D,path){ path.unshift(sprite3D.name); var parent=sprite3D._parent; if (parent._hierarchyAnimator===this) this._getLinkSpritePath(parent,path); else path.shift(); } /** *关联精灵节点到Avatar节点,此Animator必须有Avatar文件。 *@param nodeName 关联节点的名字。 *@param sprite3D 精灵节点。 *@return 是否关联成功。 */ __proto.linkSprite3DToAvatarNode=function(nodeName,sprite3D){ if (sprite3D._hierarchyAnimator===this){ if (this._avatar){ var node=this._avatarNodeMap[nodeName]; if (node){this._linkSpritesData=this._linkSpritesData|| {}; var path=[]; this._getLinkSpritePath(sprite3D,path); this._linkSpritesData[nodeName]=path; sprite3D._isLinkSpriteToAnimationNode(this,node,true); return true; }else { return false; } }else { return false; } }else { throw("Animator:sprite3D must belong to this Animator"); return false; } } /** *解除精灵节点到Avatar节点的关联,此Animator必须有Avatar文件。 *@param sprite3D 精灵节点。 *@return 是否解除关联成功。 */ __proto.unLinkSprite3DToAvatarNode=function(sprite3D){ if (this._avatar){ var dummy=sprite3D.transform.dummy; if (dummy){ var node=this._avatarNodeMap[dummy._owner.name]; sprite3D._isLinkSpriteToAnimationNode(this,node,false); return true; }else { return false; } }else { return false; } } /** *获取当前播放状态 *@return 当前播放状态 */ __getset(0,__proto,'playState',function(){ if (this._currentPlayClip==null) return /*laya.ani.AnimationState.stopped*/0; if (this._stoped) return /*laya.ani.AnimationState.stopped*/0; return /*laya.ani.AnimationState.playing*/2; }); /** *设置avatar。 *@param value avatar。 */ /** *获取avatar。 *@return avator。 */ __getset(0,__proto,'avatar',function(){ return this._avatar; },function(value){ if (this._avatar!==value){ var lastAvatar=this._avatar; this._avatar=value; var clipLength=this._clips.length; for (var i=0;i < clipLength;i++) this._offClipAndAvatarRelateEvent(lastAvatar,this._clips[i]); if (value){ if (value.loaded) this._getAvatarOwnersAndInitDatasAsync(); else value.once(/*laya.events.Event.LOADED*/"loaded",this,this._getAvatarOwnersAndInitDatasAsync); } } }); /** *设置缓存播放帧率,缓存模式下生效。注意:修改此值会有计算开销。* *@return value 缓存播放帧率 */ /** *获取缓存播放帧,缓存模式下生效。 *@return value 缓存播放帧率。 */ __getset(0,__proto,'cacheFrameRate',function(){ return this._cacheFrameRate; },function(value){ if (this._cacheFrameRate!==value){ this._cacheFrameRate=value; this._cacheFrameRateInterval=1.0 / this._cacheFrameRate; for (var i=0,n=this._clips.length;i < n;i++) (this._clips[i].loaded)&& (this._computeCacheFullKeyframeIndices(i)); } }); /** *设置默认动画片段,AnimationClip名称为默认playName。 *@param value 默认动画片段。 */ /** *获取默认动画片段。 *@return 默认动画片段。 */ __getset(0,__proto,'clip',function(){ return this._clips[this._defaultClipIndex]; },function(value){ var index=value ? this._clips.indexOf(value):-1; if (this._defaultClipIndex!==index){ (this._defaultClipIndex!==-1)&& (this.removeClip(this._clips[this._defaultClipIndex])); (index!==-1)&& (this.addClip(value,value.name)); this._defaultClipIndex=index; } }); /** *获取当前帧数 *@return 当前帧数 */ __getset(0,__proto,'currentFrameIndex',function(){ return this._currentFrameIndex; }); /** *设置缓存播放速率,缓存模式下生效。注意:修改此值会有计算开销。* *@return value 缓存播放速率。 */ /** *获取缓存播放速率,缓存模式下生效。* *@return 缓存播放速率。 */ __getset(0,__proto,'cachePlayRate',function(){ return this._cachePlayRate; },function(value){ if (this._cachePlayRate!==value){ this._cachePlayRate=value; for (var i=0,n=this._clips.length;i < n;i++) (this._clips[i].loaded)&& (this._computeCacheFullKeyframeIndices(i)); } }); /** *获取当前帧时间,不包括重播时间 *@return value 当前时间 */ __getset(0,__proto,'currentFrameTime',function(){ return this._currentFrameTime; }); /** *获取当前动画索引 *@return value 当前动画索引 */ __getset(0,__proto,'currentPlayClip',function(){ return this._currentPlayClip; }); /** *获取当前精确时间,不包括重播时间 *@return value 当前时间 */ __getset(0,__proto,'currentPlayTime',function(){ return this._currentTime+(this._playStartFrames[this._currentPlayClipIndex] / this._currentPlayClip._frameRate); }); /** *设置当前播放位置 *@param value 当前时间 */ __getset(0,__proto,'playbackTime',null,function(value){ if (this._currentPlayClip==null || !this._currentPlayClip || !this._currentPlayClip.loaded) return; this._startUpdateLoopCount=Stat.loopCount; var cacheFrameInterval=this._cacheFrameRateInterval *this._cachePlayRate; this._currentTime=value; this._currentFrameIndex=Math.floor(this.currentPlayTime / cacheFrameInterval); this._currentFrameTime=this._currentFrameIndex *cacheFrameInterval; }); /** *设置是否暂停 *@param value 是否暂停 */ /** *获取当前是否暂停 *@return 是否暂停 */ __getset(0,__proto,'paused',function(){ return this._stoped; },function(value){ this._stoped=value; value && this.event(/*laya.events.Event.PAUSED*/"paused"); }); __static(Animator, ['deafaultMatrix',function(){return this.deafaultMatrix=new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]);},'_tempMatrix4x40',function(){return this._tempMatrix4x40=new Float32Array(16);} ]); return Animator; })(Component3D) /** *AttachPoint 类用于创建挂点组件。 */ //class laya.d3.component.AttachPoint extends laya.d3.component.Component3D var AttachPoint=(function(_super){ function AttachPoint(){ /**@private */ this._attachSkeleton=null; /**@private */ this._extenData=null; /**挂点骨骼的名称。*/ this.attachBones=null; /**挂点骨骼的变换矩阵。*/ this.matrixs=null; AttachPoint.__super.call(this); this.attachBones=[]; this.matrixs=[]; } __class(AttachPoint,'laya.d3.component.AttachPoint',_super); var __proto=AttachPoint.prototype; /** *@private *初始化载入挂点组件。 *@param owner 所属精灵对象。 */ __proto._load=function(owner){ _super.prototype._load.call(this,owner); this._attachSkeleton=(owner).getComponentByType(SkinAnimations); } /** *@private *更新挂点组件。 *@param state 渲染状态。 */ __proto._update=function(state){ if (!this._attachSkeleton||this._attachSkeleton.destroyed || this._attachSkeleton.player.state===/*laya.ani.AnimationState.stopped*/0 || !this._attachSkeleton.curBonesDatas) return; var player=this._attachSkeleton.player; var templet=this._attachSkeleton.templet; this.matrixs.length=this.attachBones.length; var boneDatas=this._attachSkeleton.curBonesDatas; var worldMatrix=(this.owner).transform.worldMatrix; for (var i=0,n=this.attachBones.length;i < n;i++){ var startIndex=templet.getNodeIndexWithName(player.currentAnimationClipIndex,this.attachBones[i])*16; var matrix=this.matrixs[i]; matrix || (matrix=this.matrixs[i]=new Matrix4x4()); var matrixE=matrix.elements; for (var j=0;j < 16;j++) matrixE[j]=boneDatas[startIndex+j]; Matrix4x4.multiply(worldMatrix,matrix,matrix); } this.event(/*laya.events.Event.COMPLETE*/"complete"); } return AttachPoint; })(Component3D) /** *Collider 类用于创建碰撞器的父类,抽象类,不允许实例。 */ //class laya.d3.component.physics.Collider extends laya.d3.component.Component3D var Collider=(function(_super){ function Collider(){ /**@private */ //this._needUpdate=false; /**@private 只读,不允许修改。*/ //this._isRigidbody=false; /**@private */ //this._runtimeCollisonMap=null; /**@private */ //this._runtimeCollisonTestMap=null; /**@private */ //this._ignoreCollisonMap=null; /**是否为触发器。*/ //this.isTrigger=false; Collider.__super.call(this); this._isRigidbody=false; this._runtimeCollisonMap={}; this._runtimeCollisonTestMap={}; this._ignoreCollisonMap={}; this.isTrigger=true; } __class(Collider,'laya.d3.component.physics.Collider',_super); var __proto=Collider.prototype; /** *@private */ __proto._clearCollsionMap=function(){ for (var k in this._runtimeCollisonMap){ var otherCollider=this._runtimeCollisonMap[k]; delete otherCollider._runtimeCollisonMap[this.id]; if (otherCollider._isRigidbody) delete otherCollider._runtimeCollisonTestMap[this.id]; var otherID=otherCollider.id; delete this._runtimeCollisonMap[otherID]; if (this._isRigidbody) delete this._runtimeCollisonTestMap[otherID]; } } /** *@inheritDoc */ __proto._unload=function(owner){ for (var k in this._runtimeCollisonMap){ var otherCollider=this._runtimeCollisonMap[k]; delete otherCollider._runtimeCollisonMap[this.id]; if (otherCollider._isRigidbody) delete otherCollider._runtimeCollisonTestMap[this.id]; delete this._ignoreCollisonMap[k]._ignoreCollisonMap[this.id]; } } /** *@private */ __proto._setIsRigidbody=function(value){ if (this._isRigidbody!==value){ this._isRigidbody=value; var owner=this._owner; if (owner.displayedInStage){ var layer=owner.layer; layer._removeCollider(this); layer._addCollider(this); } } } /** *@private */ __proto._getType=function(){ return-1; } /** *@private */ __proto._collisonTo=function(other){ return false; } /** *在场景中投下可与球体碰撞器碰撞的一条光线,获取发生碰撞的球体碰撞器信息。 *@param ray 射线 *@param outHitInfo 与该射线发生碰撞球体碰撞器的碰撞信息 *@param distance 射线长度,默认为最大值 */ __proto.raycast=function(ray,hitInfo,maxDistance){ (maxDistance===void 0)&& (maxDistance=1.79e+308); throw new Error("Collider:Must override it."); } /** *@inheritDoc */ __getset(0,__proto,'enable',_super.prototype._$get_enable,function(value){ if (this._enable!==value){ var owner=this._owner; if (owner.displayedInStage) (value)|| (this._clearCollsionMap()); this._enable=value; this.event(/*laya.events.Event.ENABLE_CHANGED*/"enablechanged",this._enable); } }); /** *@inheritDoc */ __getset(0,__proto,'isSingleton',function(){ return Collider._isSingleton; }); Collider._isSingleton=false; return Collider; })(Component3D) /** *Rigidbody 类用于创建动画组件。 */ //class laya.d3.component.Rigidbody extends laya.d3.component.Component3D var Rigidbody=(function(_super){ /** *创建一个 Rigidbody 实例。 */ function Rigidbody(){ Rigidbody.__super.call(this); } __class(Rigidbody,'laya.d3.component.Rigidbody',_super); var __proto=Rigidbody.prototype; /** *@inheritDoc */ __getset(0,__proto,'enable',_super.prototype._$get_enable,function(value){ if (this._enable!==value){ var colliders=(this._owner)._colliders; for (var i=0,n=colliders.length;i < n;i++){ var collider=colliders[i]; collider._setIsRigidbody(value); var runtimeCollisonMap=collider._runtimeCollisonMap; var runtimeCollisonTestMap=collider._runtimeCollisonTestMap; if (!value){ for (var k in runtimeCollisonMap) delete runtimeCollisonTestMap[k]; } } this._enable=value; this.event(/*laya.events.Event.ENABLE_CHANGED*/"enablechanged",this._enable); } }); return Rigidbody; })(Component3D) /** *Script 类用于创建脚本的父类。 */ //class laya.d3.component.Script extends laya.d3.component.Component3D var Script=(function(_super){ /** *创建一个新的 Script 实例。 */ function Script(){ Script.__super.call(this); } __class(Script,'laya.d3.component.Script',_super); var __proto=Script.prototype; /** *当其他碰撞器进入时触发。 */ __proto.onTriggerEnter=function(other){} /** *当其他碰撞器退出时触发。 */ __proto.onTriggerExit=function(other){} /** *当其他碰撞器保持进入状态时逐帧触发。 */ __proto.onTriggerStay=function(other){} /** *@inheritDoc */ __getset(0,__proto,'isSingleton',function(){ return Script._isSingleton; }); Script._isSingleton=false; return Script; })(Component3D) /** *... *@author ... */ //class laya.d3.core.GlitterRender extends laya.d3.core.render.BaseRender var GlitterRender=(function(_super){ function GlitterRender(owner){ GlitterRender.__super.call(this,owner); } __class(GlitterRender,'laya.d3.core.GlitterRender',_super); var __proto=GlitterRender.prototype; __proto._calculateBoundingBox=function(){ var minE=this._boundingBox.min.elements; minE[0]=-Number.MAX_VALUE; minE[1]=-Number.MAX_VALUE; minE[2]=-Number.MAX_VALUE; var maxE=this._boundingBox.min.elements; maxE[0]=Number.MAX_VALUE; maxE[1]=Number.MAX_VALUE; maxE[2]=Number.MAX_VALUE; } __proto._calculateBoundingSphere=function(){ var centerE=this._boundingSphere.center.elements; centerE[0]=0; centerE[1]=0; centerE[2]=0; this._boundingSphere.radius=Number.MAX_VALUE; } /** *@private */ __proto._renderUpdate=function(projectionView){ this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.WORLDMATRIX*/0,this._owner.transform.worldMatrix); var projViewWorld=this._owner.getProjectionViewWorldMatrix(projectionView); this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.MVPMATRIX*/1,projViewWorld); var templet=(this._owner).templet; this._setShaderValueNumber(/*laya.d3.core.glitter.Glitter.DURATION*/3,templet.lifeTime); this._setShaderValueNumber(/*laya.d3.core.glitter.Glitter.CURRENTTIME*/2,templet._currentTime); return true; } return GlitterRender; })(BaseRender) /** *MeshFilter 类用于创建网格过滤器。 */ //class laya.d3.core.MeshFilter extends laya.d3.core.GeometryFilter var MeshFilter=(function(_super){ function MeshFilter(owner){ /**@private */ this._owner=null; /**@private */ this._sharedMesh=null; MeshFilter.__super.call(this); this._owner=owner; } __class(MeshFilter,'laya.d3.core.MeshFilter',_super); var __proto=MeshFilter.prototype; /** *@private */ __proto._sharedMeshLoaded=function(){ this.event(/*laya.events.Event.LOADED*/"loaded"); } /** *@inheritDoc */ __proto._destroy=function(){ _super.prototype._destroy.call(this); this._owner=null; (this._sharedMesh)&& (this._sharedMesh._removeReference(),this._sharedMesh=null); } /** *设置共享网格。 *@return value 共享网格。 */ /** *获取共享网格。 *@return 共享网格。 */ __getset(0,__proto,'sharedMesh',function(){ return this._sharedMesh; },function(value){ var lastValue=this._sharedMesh; (lastValue)&& (lastValue._removeReference()); this._sharedMesh=value; value._addReference(); this.event(/*laya.events.Event.MESH_CHANGED*/"meshchanged",[this,lastValue,value]); if (!value.loaded){ this._sharedMesh.once(/*laya.events.Event.LOADED*/"loaded",this,this._sharedMeshLoaded); } }); /** *@inheritDoc */ __getset(0,__proto,'_isAsyncLoaded',function(){ return this._sharedMesh.loaded; }); /** *@inheritDoc */ __getset(0,__proto,'_originalBoundingBoxCorners',function(){ return this._sharedMesh.boundingBoxCorners; }); /** *@inheritDoc */ __getset(0,__proto,'_originalBoundingSphere',function(){ return this._sharedMesh.boundingSphere; }); /** *@inheritDoc */ __getset(0,__proto,'_originalBoundingBox',function(){ return this._sharedMesh.boundingBox; }); return MeshFilter; })(GeometryFilter) /** *MeshRender 类用于网格渲染器。 */ //class laya.d3.core.MeshRender extends laya.d3.core.render.BaseRender var MeshRender=(function(_super){ /** *创建一个新的 MeshRender 实例。 */ function MeshRender(owner){ MeshRender.__super.call(this,owner); (owner).meshFilter.on(/*laya.events.Event.MESH_CHANGED*/"meshchanged",this,this._onMeshChanged); } __class(MeshRender,'laya.d3.core.MeshRender',_super); var __proto=MeshRender.prototype; /** *@private */ __proto._onMeshChanged=function(meshFilter,oldMesh,mesh){ if (mesh.loaded){ this._boundingSphereNeedChange=this._boundingBoxNeedChange=this._boundingBoxCenterNeedChange=this._octreeNodeNeedChange=true; }else { mesh.once(/*laya.events.Event.LOADED*/"loaded",this,this._onMeshLoaed); } } /** *@private */ __proto._onMeshLoaed=function(sender,enable){ this._boundingSphereNeedChange=this._boundingBoxNeedChange=this._boundingBoxCenterNeedChange=this._octreeNodeNeedChange=true; } /** *@private */ __proto._calculateBoundingSphereByInitSphere=function(boundSphere){ var maxScale=NaN; var transform=this._owner.transform; var scaleE=transform.scale.elements; var scaleX=Math.abs(scaleE[0]); var scaleY=Math.abs(scaleE[1]); var scaleZ=Math.abs(scaleE[2]); if (scaleX >=scaleY && scaleX >=scaleZ) maxScale=scaleX; else maxScale=scaleY >=scaleZ ? scaleY :scaleZ; Vector3.transformCoordinate(boundSphere.center,transform.worldMatrix,this._boundingSphere.center); this._boundingSphere.radius=boundSphere.radius *maxScale; } /** *@private */ __proto._calculateBoundBoxByInitCorners=function(corners){ var worldMat=(this._owner).transform.worldMatrix; for (var i=0;i < 8;i++) Vector3.transformCoordinate(corners[i],worldMat,BaseRender._tempBoundBoxCorners[i]); BoundBox.createfromPoints(BaseRender._tempBoundBoxCorners,this._boundingBox); } /** *@inheritDoc */ __proto._calculateBoundingSphere=function(){ var sharedMesh=(this._owner).meshFilter.sharedMesh; if (sharedMesh==null || sharedMesh.boundingSphere==null) this._boundingSphere.toDefault(); else this._calculateBoundingSphereByInitSphere(sharedMesh.boundingSphere); } /** *@inheritDoc */ __proto._calculateBoundingBox=function(){ var sharedMesh=(this._owner).meshFilter.sharedMesh; if (sharedMesh==null || sharedMesh.boundingBox==null) this._boundingBox.toDefault(); else this._calculateBoundBoxByInitCorners(sharedMesh.boundingBoxCorners); } /** *@private */ __proto._renderUpdate=function(projectionView){ var transform=this._owner.transform; if (transform){ this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.WORLDMATRIX*/0,transform.worldMatrix); var projViewWorld=this._owner.getProjectionViewWorldMatrix(projectionView); this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.MVPMATRIX*/1,projViewWorld); }else { this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.WORLDMATRIX*/0,Matrix4x4.DEFAULT); this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.MVPMATRIX*/1,projectionView); } if (Laya3D.debugMode) this._renderRenderableBoundBox(); return true; } return MeshRender; })(BaseRender) /** *ShurikenParticleSystem 类用于创建3D粒子数据模板。 */ //class laya.d3.core.particleShuriKen.ShurikenParticleSystem extends laya.d3.core.GeometryFilter var ShurikenParticleSystem=(function(_super){ function ShurikenParticleSystem(owner){ /**@private */ //this._boundingSphere=null; /**@private */ //this._boundingBox=null; /**@private */ //this._boundingBoxCorners=null; /**@private */ //this._owner=null; /**@private */ //this._ownerRender=null; /**@private */ //this._vertices=null; /**@private */ //this._floatCountPerVertex=0; /**@private */ //this._startLifeTimeIndex=0; /**@private */ //this._timeIndex=0; /**@private */ //this._simulateUpdate=false; /**@private */ //this._firstActiveElement=0; /**@private */ //this._firstNewElement=0; /**@private */ //this._firstFreeElement=0; /**@private */ //this._firstRetiredElement=0; /**@private */ //this._drawCounter=0; /**@private */ //this._vertexBuffer=null; /**@private */ //this._indexBuffer=null; /**@private */ //this._bufferMaxParticles=0; /**@private */ //this._emission=null; /**@private */ //this._shape=null; /**@private */ //this._isEmitting=false; /**@private */ //this._isPlaying=false; /**@private */ //this._isPaused=false; /**@private */ //this._playStartDelay=NaN; /**@private 发射的累计时间。*/ //this._frameRateTime=NaN; /**@private 一次循环内的累计时间。*/ //this._emissionTime=NaN; /**@private */ //this._totalDelayTime=NaN; /**@private */ //this._burstsIndex=0; /**@private */ //this._velocityOverLifetime=null; /**@private */ //this._colorOverLifetime=null; /**@private */ //this._sizeOverLifetime=null; /**@private */ //this._rotationOverLifetime=null; /**@private */ //this._textureSheetAnimation=null; /**@private */ //this._startLifetimeType=0; /**@private */ //this._startLifetimeConstant=NaN; /**@private */ //this._startLifeTimeGradient=null; /**@private */ //this._startLifetimeConstantMin=NaN; /**@private */ //this._startLifetimeConstantMax=NaN; /**@private */ //this._startLifeTimeGradientMin=null; /**@private */ //this._startLifeTimeGradientMax=null; /**@private */ //this._maxStartLifetime=NaN; /**@private */ //this._vertexStride=0; /**@private */ //this._indexStride=0; /**@private */ //this._currentTime=NaN; /**@private */ //this._startUpdateLoopCount=0; /**@private */ //this._rand=null; /**@private */ //this._randomSeeds=null; /**粒子运行的总时长,单位为秒。*/ //this.duration=NaN; /**是否循环。*/ //this.looping=false; /**是否预热。暂不支持*/ //this.prewarm=false; /**开始延迟类型,0为常量模式,1为随机随机双常量模式,不能和prewarm一起使用。*/ //this.startDelayType=0; /**开始播放延迟,不能和prewarm一起使用。*/ //this.startDelay=NaN; /**开始播放最小延迟,不能和prewarm一起使用。*/ //this.startDelayMin=NaN; /**开始播放最大延迟,不能和prewarm一起使用。*/ //this.startDelayMax=NaN; /**开始速度模式,0为恒定速度,2为两个恒定速度的随机插值。缺少1、3模式*/ //this.startSpeedType=0; /**开始速度,0模式。*/ //this.startSpeedConstant=NaN; /**最小开始速度,1模式。*/ //this.startSpeedConstantMin=NaN; /**最大开始速度,1模式。*/ //this.startSpeedConstantMax=NaN; /**开始尺寸是否为3D模式。*/ //this.threeDStartSize=false; /**开始尺寸模式,0为恒定尺寸,2为两个恒定尺寸的随机插值。缺少1、3模式和对应的二种3D模式*/ //this.startSizeType=0; /**开始尺寸,0模式。*/ //this.startSizeConstant=NaN; /**开始三维尺寸,0模式。*/ //this.startSizeConstantSeparate=null; /**最小开始尺寸,2模式。*/ //this.startSizeConstantMin=NaN; /**最大开始尺寸,2模式。*/ //this.startSizeConstantMax=NaN; /**最小三维开始尺寸,2模式。*/ //this.startSizeConstantMinSeparate=null; /**最大三维开始尺寸,2模式。*/ //this.startSizeConstantMaxSeparate=null; /**3D开始旋转,暂不支持*/ //this.threeDStartRotation=false; /**开始旋转模式,0为恒定尺寸,2为两个恒定旋转的随机插值,缺少2种模式,和对应的四种3D模式。*/ //this.startRotationType=0; /**开始旋转,0模式。*/ //this.startRotationConstant=NaN; /**开始三维旋转,0模式。*/ //this.startRotationConstantSeparate=null; /**最小开始旋转,1模式。*/ //this.startRotationConstantMin=NaN; /**最大开始旋转,1模式。*/ //this.startRotationConstantMax=NaN; /**最小开始三维旋转,1模式。*/ //this.startRotationConstantMinSeparate=null; /**最大开始三维旋转,1模式。*/ //this.startRotationConstantMaxSeparate=null; /**随机旋转方向,范围为0.0到1.0*/ //this.randomizeRotationDirection=NaN; /**开始颜色模式,0为恒定颜色,2为两个恒定颜色的随机插值,缺少2种模式。*/ //this.startColorType=0; /**开始颜色,0模式。*/ //this.startColorConstant=null; /**最小开始颜色,1模式。*/ //this.startColorConstantMin=null; /**最大开始颜色,1模式。*/ //this.startColorConstantMax=null; /**重力敏感度。*/ //this.gravityModifier=NaN; /**模拟器空间,0为World,1为Local。暂不支持Custom。*/ //this.simulationSpace=0; /**缩放模式,0为Hiercachy,1为Local,2为World。暂不支持1,2*/ //this.scaleMode=0; /**激活时是否自动播放。*/ //this.playOnAwake=false; /**随机种子,注:play()前设置有效。*/ //this.randomSeed=null; /**是否使用随机种子。 */ //this.autoRandomSeed=false; /**是否为性能模式,性能模式下会延迟粒子释放。*/ //this.isPerformanceMode=false; ShurikenParticleSystem.__super.call(this); this._tempRotationMatrix=new Matrix4x4(); this._uvLength=new Vector2(); this._firstActiveElement=0; this._firstNewElement=0; this._firstFreeElement=0; this._firstRetiredElement=0; this._owner=owner; this._ownerRender=owner.particleRender; this._boundingBoxCorners=__newvec(8,null); this._boundingSphere=new BoundSphere(new Vector3(),Number.MAX_VALUE); this._boundingBox=new BoundBox(new Vector3(-Number.MAX_VALUE,-Number.MAX_VALUE,-Number.MAX_VALUE),new Vector3(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)); this._currentTime=0; this._isEmitting=false; this._isPlaying=false; this._isPaused=false; this._burstsIndex=0; this._frameRateTime=0; this._emissionTime=0; this._totalDelayTime=0; this._simulateUpdate=false; this._bufferMaxParticles=1; this.duration=5.0; this.looping=true; this.prewarm=false; this.startDelayType=0; this.startDelay=0.0; this.startDelayMin=0.0; this.startDelayMax=0.0; this._startLifetimeType=0; this._startLifetimeConstant=5.0; this._startLifeTimeGradient=new GradientDataNumber(); this._startLifetimeConstantMin=0.0; this._startLifetimeConstantMax=5.0; this._startLifeTimeGradientMin=new GradientDataNumber(); this._startLifeTimeGradientMax=new GradientDataNumber(); this._maxStartLifetime=5.0; this.startSpeedType=0; this.startSpeedConstant=5.0; this.startSpeedConstantMin=0.0; this.startSpeedConstantMax=5.0; this.threeDStartSize=false; this.startSizeType=0; this.startSizeConstant=1; this.startSizeConstantSeparate=new Vector3(1,1,1); this.startSizeConstantMin=0; this.startSizeConstantMax=1; this.startSizeConstantMinSeparate=new Vector3(0,0,0); this.startSizeConstantMaxSeparate=new Vector3(1,1,1); this.threeDStartRotation=false; this.startRotationType=0; this.startRotationConstant=0; this.startRotationConstantSeparate=new Vector3(0,0,0); this.startRotationConstantMin=0.0; this.startRotationConstantMax=0.0; this.startRotationConstantMinSeparate=new Vector3(0,0,0); this.startRotationConstantMaxSeparate=new Vector3(0,0,0); this.randomizeRotationDirection=0.0; this.startColorType=0; this.startColorConstant=new Vector4(1,1,1,1); this.startColorConstantMin=new Vector4(1,1,1,1); this.startColorConstantMax=new Vector4(1,1,1,1); this.gravityModifier=0.0; this.simulationSpace=1; this.scaleMode=0; this.playOnAwake=true; this._rand=new Rand(0); this.autoRandomSeed=true; this.randomSeed=new Uint32Array(1); this._randomSeeds=new Uint32Array(ShurikenParticleSystem._RANDOMOFFSET.length); this.isPerformanceMode=true; this._emission=new Emission(); this._emission.enbale=true; this._owner.on(/*laya.events.Event.ACTIVE_IN_HIERARCHY_CHANGED*/"activeinhierarchychanged",this,this._onOwnerActiveHierarchyChanged); } __class(ShurikenParticleSystem,'laya.d3.core.particleShuriKen.ShurikenParticleSystem',_super); var __proto=ShurikenParticleSystem.prototype; Laya.imps(__proto,{"laya.d3.core.render.IRenderable":true,"laya.d3.core.IClone":true}) __proto._getVertexBuffer=function(index){ (index===void 0)&& (index=0); if (index===0) return this._vertexBuffer; else return null; } __proto._getIndexBuffer=function(){ return this._indexBuffer; } /** *@private */ __proto._generateBoundingSphere=function(){ var centerE=this._boundingSphere.center.elements; centerE[0]=0; centerE[1]=0; centerE[2]=0; this._boundingSphere.radius=Number.MAX_VALUE; } /** *@private */ __proto._generateBoundingBox=function(){ var particle=this._owner; var particleRender=particle.particleRender; var boundMin=this._boundingBox.min; var boundMax=this._boundingBox.max; var i=0,n=0; var maxStartLifeTime=NaN; switch (this.startLifetimeType){ case 0: maxStartLifeTime=this.startLifetimeConstant; break ; case 1: maxStartLifeTime=-Number.MAX_VALUE; var startLifeTimeGradient=startLifeTimeGradient; for (i=0,n=startLifeTimeGradient.gradientCount;i < n;i++) maxStartLifeTime=Math.max(maxStartLifeTime,startLifeTimeGradient.getValueByIndex(i)); break ; case 2: maxStartLifeTime=Math.max(this.startLifetimeConstantMin,this.startLifetimeConstantMax); break ; case 3: maxStartLifeTime=-Number.MAX_VALUE; var startLifeTimeGradientMin=startLifeTimeGradientMin; for (i=0,n=startLifeTimeGradientMin.gradientCount;i < n;i++) maxStartLifeTime=Math.max(maxStartLifeTime,startLifeTimeGradientMin.getValueByIndex(i)); var startLifeTimeGradientMax=startLifeTimeGradientMax; for (i=0,n=startLifeTimeGradientMax.gradientCount;i < n;i++) maxStartLifeTime=Math.max(maxStartLifeTime,startLifeTimeGradientMax.getValueByIndex(i)); break ; }; var minStartSpeed=NaN,maxStartSpeed=NaN; switch (this.startSpeedType){ case 0: minStartSpeed=maxStartSpeed=this.startSpeedConstant; break ; case 1: break ; case 2: minStartSpeed=this.startLifetimeConstantMin; maxStartSpeed=this.startLifetimeConstantMax; break ; case 3: break ; }; var minPosition,maxPosition,minDirection,maxDirection; if (this._shape && this._shape.enable){ }else { minPosition=maxPosition=Vector3.ZERO; minDirection=Vector3.ZERO; maxDirection=Vector3.UnitZ; }; var startMinVelocity=new Vector3(minDirection.x *minStartSpeed,minDirection.y *minStartSpeed,minDirection.z *minStartSpeed); var startMaxVelocity=new Vector3(maxDirection.x *maxStartSpeed,maxDirection.y *maxStartSpeed,maxDirection.z *maxStartSpeed); if (this._velocityOverLifetime && this._velocityOverLifetime.enbale){ var lifeMinVelocity; var lifeMaxVelocity; var velocity=this._velocityOverLifetime.velocity; switch (velocity.type){ case 0: lifeMinVelocity=lifeMaxVelocity=velocity.constant; break ; case 1: lifeMinVelocity=lifeMaxVelocity=new Vector3(velocity.gradientX.getAverageValue(),velocity.gradientY.getAverageValue(),velocity.gradientZ.getAverageValue()); break ; case 2: lifeMinVelocity=velocity.constantMin; lifeMaxVelocity=velocity.constantMax; break ; case 3: lifeMinVelocity=new Vector3(velocity.gradientXMin.getAverageValue(),velocity.gradientYMin.getAverageValue(),velocity.gradientZMin.getAverageValue()); lifeMaxVelocity=new Vector3(velocity.gradientXMax.getAverageValue(),velocity.gradientYMax.getAverageValue(),velocity.gradientZMax.getAverageValue()); break ; } }; var positionScale,velocityScale; var transform=this._owner.transform; var worldPosition=transform.position; var sizeScale=ShurikenParticleSystem._tempVector39; var sizeScaleE=sizeScale.elements; var renderMode=particleRender.renderMode; switch (this.scaleMode){ case 0:; var scale=transform.scale; positionScale=scale; sizeScaleE[0]=scale.x; sizeScaleE[1]=scale.z; sizeScaleE[2]=scale.y; (renderMode===1)&& (velocityScale=scale); break ; case 1:; var localScale=transform.localScale; positionScale=localScale; sizeScaleE[0]=localScale.x; sizeScaleE[1]=localScale.z; sizeScaleE[2]=localScale.y; (renderMode===1)&& (velocityScale=localScale); break ; case 2: positionScale=transform.scale; sizeScaleE[0]=sizeScaleE[1]=sizeScaleE[2]=1; (renderMode===1)&& (velocityScale=Vector3.ONE); break ; }; var minStratPosition,maxStratPosition; if (this._velocityOverLifetime && this._velocityOverLifetime.enbale){ }else { minStratPosition=new Vector3(startMinVelocity.x *maxStartLifeTime,startMinVelocity.y *maxStartLifeTime,startMinVelocity.z *maxStartLifeTime); maxStratPosition=new Vector3(startMaxVelocity.x *maxStartLifeTime,startMaxVelocity.y *maxStartLifeTime,startMaxVelocity.z *maxStartLifeTime); if (this.scaleMode !=2){ Vector3.add(minPosition,minStratPosition,boundMin); Vector3.multiply(positionScale,boundMin,boundMin); Vector3.add(maxPosition,maxStratPosition,boundMax); Vector3.multiply(positionScale,boundMax,boundMax); }else { Vector3.multiply(positionScale,minPosition,boundMin); Vector3.add(boundMin,minStratPosition,boundMin); Vector3.multiply(positionScale,maxPosition,boundMax); Vector3.add(boundMax,maxStratPosition,boundMax); } } switch (this.simulationSpace){ case 0: break ; case 1: Vector3.add(boundMin,worldPosition,boundMin); Vector3.add(boundMax,worldPosition,boundMax); break ; }; var maxSize=NaN,maxSizeY=NaN; switch (this.startSizeType){ case 0: if (this.threeDStartSize){ var startSizeConstantSeparate=startSizeConstantSeparate; maxSize=Math.max(startSizeConstantSeparate.x,startSizeConstantSeparate.y); if (renderMode===1) maxSizeY=startSizeConstantSeparate.y; }else { maxSize=this.startSizeConstant; if (renderMode===1) maxSizeY=this.startSizeConstant; } break ; case 1: break ; case 2: if (this.threeDStartSize){ var startSizeConstantMaxSeparate=startSizeConstantMaxSeparate; maxSize=Math.max(startSizeConstantMaxSeparate.x,startSizeConstantMaxSeparate.y); if (renderMode===1) maxSizeY=startSizeConstantMaxSeparate.y; }else { maxSize=this.startSizeConstantMax; if (renderMode===1) maxSizeY=this.startSizeConstantMax; } break ; case 3: break ; } if (this._sizeOverLifetime && this._sizeOverLifetime.enbale){ var size=this._sizeOverLifetime.size; maxSize *=this._sizeOverLifetime.size.getMaxSizeInGradient(); }; var threeDMaxSize=ShurikenParticleSystem._tempVector30; var threeDMaxSizeE=threeDMaxSize.elements; var rotSize=NaN,nonRotSize=NaN; switch (renderMode){ case 0: rotSize=maxSize *ShurikenParticleSystem.halfKSqrtOf2; Vector3.scale(sizeScale,maxSize,threeDMaxSize); Vector3.subtract(boundMin,threeDMaxSize,boundMin); Vector3.add(boundMax,threeDMaxSize,boundMax); break ; case 1:; var maxStretchPosition=ShurikenParticleSystem._tempVector31; var maxStretchVelocity=ShurikenParticleSystem._tempVector32; var minStretchVelocity=ShurikenParticleSystem._tempVector33; var minStretchPosition=ShurikenParticleSystem._tempVector34; if (this._velocityOverLifetime && this._velocityOverLifetime.enbale){ }else { Vector3.multiply(velocityScale,startMaxVelocity,maxStretchVelocity); Vector3.multiply(velocityScale,startMinVelocity,minStretchVelocity); }; var sizeStretch=maxSizeY *particleRender.stretchedBillboardLengthScale; var maxStretchLength=Vector3.scalarLength(maxStretchVelocity)*particleRender.stretchedBillboardSpeedScale+sizeStretch; var minStretchLength=Vector3.scalarLength(minStretchVelocity)*particleRender.stretchedBillboardSpeedScale+sizeStretch; var norMaxStretchVelocity=ShurikenParticleSystem._tempVector35; var norMinStretchVelocity=ShurikenParticleSystem._tempVector36; Vector3.normalize(maxStretchVelocity,norMaxStretchVelocity); Vector3.scale(norMaxStretchVelocity,maxStretchLength,minStretchPosition); Vector3.subtract(maxStratPosition,minStretchPosition,minStretchPosition); Vector3.normalize(minStretchVelocity,norMinStretchVelocity); Vector3.scale(norMinStretchVelocity,minStretchLength,maxStretchPosition); Vector3.add(minStratPosition,maxStretchPosition,maxStretchPosition); rotSize=maxSize *ShurikenParticleSystem.halfKSqrtOf2; Vector3.scale(sizeScale,rotSize,threeDMaxSize); var halfNorMaxStretchVelocity=ShurikenParticleSystem._tempVector37; var halfNorMinStretchVelocity=ShurikenParticleSystem._tempVector38; Vector3.scale(norMaxStretchVelocity,0.5,halfNorMaxStretchVelocity); Vector3.scale(norMinStretchVelocity,0.5,halfNorMinStretchVelocity); Vector3.multiply(halfNorMaxStretchVelocity,sizeScale,halfNorMaxStretchVelocity); Vector3.multiply(halfNorMinStretchVelocity,sizeScale,halfNorMinStretchVelocity); Vector3.add(boundMin,halfNorMinStretchVelocity,boundMin); Vector3.min(boundMin,minStretchPosition,boundMin); Vector3.subtract(boundMin,threeDMaxSize,boundMin); Vector3.subtract(boundMax,halfNorMaxStretchVelocity,boundMax); Vector3.max(boundMax,maxStretchPosition,boundMax); Vector3.add(boundMax,threeDMaxSize,boundMax); break ; case 2: maxSize *=Math.cos(0.78539816339744830961566084581988); nonRotSize=maxSize *0.5; threeDMaxSizeE[0]=sizeScale.x *nonRotSize; threeDMaxSizeE[1]=sizeScale.z *nonRotSize; Vector3.subtract(boundMin,threeDMaxSize,boundMin); Vector3.add(boundMax,threeDMaxSize,boundMax); break ; case 3: maxSize *=Math.cos(0.78539816339744830961566084581988); nonRotSize=maxSize *0.5; Vector3.scale(sizeScale,nonRotSize,threeDMaxSize); Vector3.subtract(boundMin,threeDMaxSize,boundMin); Vector3.add(boundMax,threeDMaxSize,boundMax); break ; } this._boundingBox.getCorners(this._boundingBoxCorners); } /** *@private */ __proto._updateEmission=function(){ if (!Laya.stage.isVisibility||!this.isAlive) return; if (this._simulateUpdate){ this._simulateUpdate=false; } else{ var elapsedTime=(this._startUpdateLoopCount!==Stat.loopCount && !this._isPaused)?Laya.timer.delta / 1000.0:0; elapsedTime=Math.min(ShurikenParticleSystem._maxElapsedTime,elapsedTime); this._updateParticles(elapsedTime); } } /** *@private */ __proto._updateParticles=function(elapsedTime){ if (this._ownerRender.renderMode===4 && !this._ownerRender.mesh) return; this._currentTime+=elapsedTime; this._retireActiveParticles(); this._freeRetiredParticles(); this._totalDelayTime+=elapsedTime; if (this._totalDelayTime < this._playStartDelay){ return; } if (this._emission.enbale&&this._isEmitting &&!this._isPaused) this._advanceTime(elapsedTime,this._currentTime); } /** *@private */ __proto._updateParticlesSimulationRestart=function(time){ this._firstActiveElement=0; this._firstNewElement=0; this._firstFreeElement=0; this._firstRetiredElement=0; this._burstsIndex=0; this._frameRateTime=time; this._emissionTime=0; this._totalDelayTime=0; this._currentTime=time; var delayTime=time; if (delayTime < this._playStartDelay){ this._totalDelayTime=delayTime; return; } if (this._emission.enbale) this._advanceTime(time,time); } /** *@private */ __proto._addUpdateEmissionToTimer=function(){ Laya.timer.frameLoop(1,this,this._updateEmission); } /** *@private */ __proto._removeUpdateEmissionToTimer=function(){ Laya.timer.clear(this,this._updateEmission); } /** *@private */ __proto._onOwnerActiveHierarchyChanged=function(active){ if (this._owner.displayedInStage){ if (active) this._addUpdateEmissionToTimer(); else this._removeUpdateEmissionToTimer(); } } /** *@private */ __proto._retireActiveParticles=function(){ var epsilon=0.0001; while (this._firstActiveElement !=this._firstNewElement){ var index=this._firstActiveElement *this._floatCountPerVertex *this._vertexStride; var timeIndex=index+this._timeIndex; var particleAge=this._currentTime-this._vertices[timeIndex]; if (particleAge+epsilon < this._vertices[index+this._startLifeTimeIndex]) break ; this._vertices[timeIndex]=this._drawCounter; this._firstActiveElement++; if (this._firstActiveElement >=this._bufferMaxParticles) this._firstActiveElement=0; } } /** *@private */ __proto._freeRetiredParticles=function(){ while (this._firstRetiredElement !=this._firstActiveElement){ var age=this._drawCounter-this._vertices[this._firstRetiredElement *this._floatCountPerVertex *this._vertexStride+this._timeIndex]; if (this.isPerformanceMode) if (age < 3) break ; this._firstRetiredElement++; if (this._firstRetiredElement >=this._bufferMaxParticles) this._firstRetiredElement=0; } } /** *@private */ __proto._burst=function(fromTime,toTime){ var totalEmitCount=0; var bursts=this._emission._bursts; for (var n=bursts.length;this._burstsIndex < n;this._burstsIndex++){ var burst=bursts[this._burstsIndex]; var burstTime=burst.time; if (fromTime<=burstTime && burstTime < toTime){ var emitCount=0; if (this.autoRandomSeed){ emitCount=MathUtil.lerp(burst.minCount,burst.maxCount,Math.random()); }else { this._rand.seed=this._randomSeeds[0]; emitCount=MathUtil.lerp(burst.minCount,burst.maxCount,this._rand.getFloat()); this._randomSeeds[0]=this._rand.seed; } totalEmitCount+=emitCount; }else { break ; } } return totalEmitCount; } /** *@private */ __proto._advanceTime=function(elapsedTime,emitTime){ var i=0; var lastEmissionTime=this._emissionTime; this._emissionTime+=elapsedTime; var totalEmitCount=0; if (this._emissionTime > this.duration){ if (this.looping){ totalEmitCount+=this._burst(lastEmissionTime,this._emissionTime); this._emissionTime-=this.duration; this.event(/*laya.events.Event.COMPLETE*/"complete"); this._burstsIndex=0; totalEmitCount+=this._burst(0,this._emissionTime); }else { totalEmitCount=Math.min(this.maxParticles-this.aliveParticleCount,totalEmitCount); for (i=0;i < totalEmitCount;i++) this.emit(emitTime); this._isPlaying=false; this.stop(); return; } }else { totalEmitCount+=this._burst(lastEmissionTime,this._emissionTime); } totalEmitCount=Math.min(this.maxParticles-this.aliveParticleCount,totalEmitCount); for (i=0;i < totalEmitCount;i++) this.emit(emitTime); var emissionRate=this.emission.emissionRate; if (emissionRate>0){ var minEmissionTime=1/emissionRate; this._frameRateTime+=minEmissionTime; this._frameRateTime=this._currentTime-(this._currentTime-this._frameRateTime)% this._maxStartLifetime; while (this._frameRateTime <=emitTime){ if (this.emit(this._frameRateTime)) this._frameRateTime+=minEmissionTime; else break ; } this._frameRateTime=Math.floor(emitTime / minEmissionTime)*minEmissionTime; } } /** *@private */ __proto._initBufferDatas=function(){ if (this._vertexBuffer){ this._vertexBuffer.destroy(); this._indexBuffer.destroy(); }; var render=this._ownerRender; var renderMode=render.renderMode; if (renderMode!==-1 && this.maxParticles > 0){ var indices,i=0,j=0,m=0,indexOffset=0,perPartOffset=0,vertexDeclaration;; var mesh=render.mesh; if (renderMode===4){ if(mesh){ var vertexBufferCount=mesh._vertexBuffers.length; if (vertexBufferCount > 1){ throw new Error("ShurikenParticleSystem: submesh Count mesh be One or all subMeshes have the same vertexDeclaration."); }else { vertexDeclaration=VertexShurikenParticleMesh.vertexDeclaration; this._floatCountPerVertex=vertexDeclaration.vertexStride/4; this._startLifeTimeIndex=12; this._timeIndex=16; this._vertexStride=mesh._vertexBuffers[0].vertexCount; var totalVertexCount=this._bufferMaxParticles *this._vertexStride; var vbCount=Math.floor(totalVertexCount / 65535)+1; var lastVBVertexCount=totalVertexCount % 65535; if (vbCount > 1){ throw new Error("ShurikenParticleSystem:the maxParticleCount multiply mesh vertexCount is large than 65535."); } this._vertexBuffer=VertexBuffer3D.create(vertexDeclaration,lastVBVertexCount,/*laya.webgl.WebGLContext.DYNAMIC_DRAW*/0x88E8); this._vertices=new Float32Array(this._floatCountPerVertex *lastVBVertexCount); this._indexStride=mesh._indexBuffer.indexCount; var indexDatas=mesh._indexBuffer.getData(); var indexCount=this._bufferMaxParticles *this._indexStride; this._indexBuffer=IndexBuffer3D.create(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",indexCount,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4); indices=new Uint16Array(indexCount); indexOffset=0; for (i=0;i < this._bufferMaxParticles;i++){ var indexValueOffset=i *this._vertexStride; for (j=0,m=indexDatas.length;j < m;j++) indices[indexOffset++]=indexValueOffset+indexDatas[j]; } this._indexBuffer.setData(indices); } } }else { vertexDeclaration=VertexShurikenParticleBillboard.vertexDeclaration; this._floatCountPerVertex=vertexDeclaration.vertexStride/4; this._startLifeTimeIndex=7; this._timeIndex=11; this._vertexStride=4; this._vertexBuffer=VertexBuffer3D.create(vertexDeclaration,this._bufferMaxParticles *this._vertexStride,/*laya.webgl.WebGLContext.DYNAMIC_DRAW*/0x88E8); this._vertices=new Float32Array(this._floatCountPerVertex *this._bufferMaxParticles *this._vertexStride); for (i=0;i < this._bufferMaxParticles;i++){ perPartOffset=i *this._floatCountPerVertex *this._vertexStride; this._vertices[perPartOffset]=-0.5; this._vertices[perPartOffset+1]=-0.5; this._vertices[perPartOffset+2]=0; this._vertices[perPartOffset+3]=1; perPartOffset+=this._floatCountPerVertex; this._vertices[perPartOffset]=0.5; this._vertices[perPartOffset+1]=-0.5; this._vertices[perPartOffset+2]=1; this._vertices[perPartOffset+3]=1; perPartOffset+=this._floatCountPerVertex this._vertices[perPartOffset]=0.5; this._vertices[perPartOffset+1]=0.5; this._vertices[perPartOffset+2]=1; this._vertices[perPartOffset+3]=0; perPartOffset+=this._floatCountPerVertex this._vertices[perPartOffset]=-0.5; this._vertices[perPartOffset+1]=0.5; this._vertices[perPartOffset+2]=0; this._vertices[perPartOffset+3]=0; } this._indexStride=6; this._indexBuffer=IndexBuffer3D.create(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",this._bufferMaxParticles *6,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4); indices=new Uint16Array(this._bufferMaxParticles *6); for (i=0;i < this._bufferMaxParticles;i++){ indexOffset=i *6; var firstVertex=i *this._vertexStride,secondVertex=firstVertex+2; indices[indexOffset++]=firstVertex; indices[indexOffset++]=secondVertex; indices[indexOffset++]=firstVertex+1; indices[indexOffset++]=firstVertex; indices[indexOffset++]=firstVertex+3; indices[indexOffset++]=secondVertex; } this._indexBuffer.setData(indices); } } } /** *@private */ __proto._destroy=function(){ _super.prototype._destroy.call(this); (this._owner.activeInHierarchy)&& (this._removeUpdateEmissionToTimer()); this._vertexBuffer.destroy(); this._indexBuffer.destroy(); this._emission._destroy(); this._owner=null; this._vertices=null; this._vertexBuffer=null; this._indexBuffer=null; this._emission=null; this._shape=null; this.startLifeTimeGradient=null; this.startLifeTimeGradientMin=null; this.startLifeTimeGradientMax=null; this.startSizeConstantSeparate=null; this.startSizeConstantMinSeparate=null; this.startSizeConstantMaxSeparate=null; this.startRotationConstantSeparate=null; this.startRotationConstantMinSeparate=null; this.startRotationConstantMaxSeparate=null; this.startColorConstant=null; this.startColorConstantMin=null; this.startColorConstantMax=null; this._velocityOverLifetime=null; this._colorOverLifetime=null; this._sizeOverLifetime=null; this._rotationOverLifetime=null; this._textureSheetAnimation=null; } /** *发射一个粒子。 */ __proto.emit=function(time){ var position=ShurikenParticleSystem._tempPosition; var direction=ShurikenParticleSystem._tempDirection; if (this._shape&&this._shape.enable){ if (this.autoRandomSeed) this._shape.generatePositionAndDirection(position,direction); else this._shape.generatePositionAndDirection(position,direction,this._rand,this._randomSeeds); }else { var positionE=position.elements; var directionE=direction.elements; positionE[0]=positionE[1]=positionE[2]=0; directionE[0]=directionE[1]=0; directionE[2]=1; } return this.addParticle(position,direction,time); } //TODO:提前判断优化 __proto.addParticle=function(position,direction,time){ Vector3.normalize(direction,direction); var nextFreeParticle=this._firstFreeElement+1; if (nextFreeParticle >=this._bufferMaxParticles) nextFreeParticle=0; if (nextFreeParticle===this._firstRetiredElement) return false; ShurikenParticleData.create(this,this._ownerRender,this._owner.transform); var particleAge=this._currentTime-time; if (particleAge >=ShurikenParticleData.startLifeTime) return true; var randomVelocityX=NaN,randomVelocityY=NaN,randomVelocityZ=NaN,randomColor=NaN,randomSize=NaN,randomRotation=NaN,randomTextureAnimation=NaN; var needRandomVelocity=this._velocityOverLifetime && this._velocityOverLifetime.enbale; if (needRandomVelocity){ var velocityType=this._velocityOverLifetime.velocity.type; if (velocityType===2 || velocityType===3){ if (this.autoRandomSeed){ randomVelocityX=Math.random(); randomVelocityY=Math.random(); randomVelocityZ=Math.random(); }else { this._rand.seed=this._randomSeeds[9]; randomVelocityX=this._rand.getFloat(); randomVelocityY=this._rand.getFloat(); randomVelocityZ=this._rand.getFloat(); this._randomSeeds[9]=this._rand.seed; } }else { needRandomVelocity=false; } }else { needRandomVelocity=false; }; var needRandomColor=this._colorOverLifetime && this._colorOverLifetime.enbale; if (needRandomColor){ var colorType=this._colorOverLifetime.color.type; if (colorType===3){ if (this.autoRandomSeed){ randomColor=Math.random(); }else { this._rand.seed=this._randomSeeds[10]; randomColor=this._rand.getFloat(); this._randomSeeds[10]=this._rand.seed; } }else { needRandomColor=false; } }else { needRandomColor=false; }; var needRandomSize=this._sizeOverLifetime && this._sizeOverLifetime.enbale; if (needRandomSize){ var sizeType=this._sizeOverLifetime.size.type; if (sizeType===3){ if (this.autoRandomSeed){ randomSize=Math.random(); }else { this._rand.seed=this._randomSeeds[11]; randomSize=this._rand.getFloat(); this._randomSeeds[11]=this._rand.seed; } }else { needRandomSize=false; } }else { needRandomSize=false; }; var needRandomRotation=this._rotationOverLifetime && this._rotationOverLifetime.enbale; if (needRandomRotation){ var rotationType=this._rotationOverLifetime.angularVelocity.type; if (rotationType===2 || rotationType===3){ if (this.autoRandomSeed){ randomRotation=Math.random(); }else { this._rand.seed=this._randomSeeds[12]; randomRotation=this._rand.getFloat(); this._randomSeeds[12]=this._rand.seed; } }else { needRandomRotation=false; } }else { needRandomRotation=false; }; var needRandomTextureAnimation=this._textureSheetAnimation && this._textureSheetAnimation.enable; if (needRandomTextureAnimation){ var textureAnimationType=this._textureSheetAnimation.frame.type; if (textureAnimationType===3){ if (this.autoRandomSeed){ randomTextureAnimation=Math.random(); }else { this._rand.seed=this._randomSeeds[15]; randomTextureAnimation=this._rand.getFloat(); this._randomSeeds[15]=this._rand.seed; } }else { needRandomTextureAnimation=false; } }else { needRandomTextureAnimation=false; }; var startIndex=this._firstFreeElement *this._floatCountPerVertex *this._vertexStride; var subU=ShurikenParticleData.startUVInfo[0]; var subV=ShurikenParticleData.startUVInfo[1]; var startU=ShurikenParticleData.startUVInfo[2]; var startV=ShurikenParticleData.startUVInfo[3]; var positionE=position.elements; var directionE=direction.elements; var meshVertices,meshVertexStride=0,meshPosOffset=0,meshCorOffset=0,meshUVOffset=0,meshVertexIndex=0; var render=this._ownerRender; if (render.renderMode===4){ var meshVB=render.mesh._vertexBuffers[0]; meshVertices=meshVB.getData(); var meshVertexDeclaration=meshVB.vertexDeclaration; meshPosOffset=meshVertexDeclaration.getVertexElementByUsage(/*laya.d3.graphics.VertexElementUsage.POSITION0*/0).offset / 4; var colorElement=meshVertexDeclaration.getVertexElementByUsage(/*laya.d3.graphics.VertexElementUsage.COLOR0*/1); meshCorOffset=colorElement?colorElement.offset / 4:-1; var uvElement=meshVertexDeclaration.getVertexElementByUsage(/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2); meshUVOffset=uvElement?uvElement.offset / 4:-1; meshVertexStride=meshVertexDeclaration.vertexStride / 4; meshVertexIndex=0; }else { this._vertices[startIndex+2]=startU; this._vertices[startIndex+3]=startV+subV; var secondOffset=startIndex+this._floatCountPerVertex; this._vertices[secondOffset+2]=startU+subU; this._vertices[secondOffset+3]=startV+subV; var thirdOffset=secondOffset+this._floatCountPerVertex; this._vertices[thirdOffset+2]=startU+subU; this._vertices[thirdOffset+3]=startV; var fourthOffset=thirdOffset+this._floatCountPerVertex; this._vertices[fourthOffset+2]=startU; this._vertices[fourthOffset+3]=startV; } for (var i=startIndex,n=startIndex+this._floatCountPerVertex *this._vertexStride;i < n;i+=this._floatCountPerVertex){ var offset=0; if (render.renderMode===4){ offset=i; var vertexOffset=meshVertexStride *(meshVertexIndex++); var meshOffset=vertexOffset+meshPosOffset; this._vertices[offset++]=meshVertices[meshOffset++]; this._vertices[offset++]=meshVertices[meshOffset++]; this._vertices[offset++]=meshVertices[meshOffset]; if (meshCorOffset===-1){ this._vertices[offset++]=1.0; this._vertices[offset++]=1.0; this._vertices[offset++]=1.0; this._vertices[offset++]=1.0; } else{ meshOffset=vertexOffset+meshCorOffset; this._vertices[offset++]=meshVertices[meshOffset++]; this._vertices[offset++]=meshVertices[meshOffset++]; this._vertices[offset++]=meshVertices[meshOffset++]; this._vertices[offset++]=meshVertices[meshOffset]; } if (meshUVOffset===-1){ this._vertices[offset++]=0.0; this._vertices[offset++]=0.0; } else{ meshOffset=vertexOffset+meshUVOffset; this._vertices[offset++]=startU+meshVertices[meshOffset++] *subU; this._vertices[offset++]=startV+meshVertices[meshOffset] *subV; } }else { offset=i+4; } this._vertices[offset++]=positionE[0]; this._vertices[offset++]=positionE[1]; this._vertices[offset++]=positionE[2]; this._vertices[offset++]=ShurikenParticleData.startLifeTime; this._vertices[offset++]=directionE[0]; this._vertices[offset++]=directionE[1]; this._vertices[offset++]=directionE[2]; this._vertices[offset++]=time; this._vertices[offset++]=ShurikenParticleData.startColor[0]; this._vertices[offset++]=ShurikenParticleData.startColor[1]; this._vertices[offset++]=ShurikenParticleData.startColor[2]; this._vertices[offset++]=ShurikenParticleData.startColor[3]; this._vertices[offset++]=ShurikenParticleData.startSize[0]; this._vertices[offset++]=ShurikenParticleData.startSize[1]; this._vertices[offset++]=ShurikenParticleData.startSize[2]; this._vertices[offset++]=ShurikenParticleData.startRotation[0]; this._vertices[offset++]=ShurikenParticleData.startRotation[1]; this._vertices[offset++]=ShurikenParticleData.startRotation[2]; this._vertices[offset++]=ShurikenParticleData.startSpeed; needRandomColor && (this._vertices[offset+1]=randomColor); needRandomSize && (this._vertices[offset+2]=randomSize); needRandomRotation && (this._vertices[offset+3]=randomRotation); needRandomTextureAnimation && (this._vertices[offset+4]=randomTextureAnimation); if (needRandomVelocity){ this._vertices[offset+5]=randomVelocityX; this._vertices[offset+6]=randomVelocityY; this._vertices[offset+7]=randomVelocityZ; } switch(this.simulationSpace){ case 0: offset+=8; this._vertices[offset++]=ShurikenParticleData.simulationWorldPostion[0]; this._vertices[offset++]=ShurikenParticleData.simulationWorldPostion[1]; this._vertices[offset++]=ShurikenParticleData.simulationWorldPostion[2]; this._vertices[offset++]=ShurikenParticleData.simulationWorldRotation[0]; this._vertices[offset++]=ShurikenParticleData.simulationWorldRotation[1]; this._vertices[offset++]=ShurikenParticleData.simulationWorldRotation[2]; this._vertices[offset++]=ShurikenParticleData.simulationWorldRotation[3]; break ; case 1: break ; default : throw new Error("ShurikenParticleMaterial: SimulationSpace value is invalid."); } } this._firstFreeElement=nextFreeParticle; return true; } __proto.addNewParticlesToVertexBuffer=function(){ var start=0; if (this._firstNewElement < this._firstFreeElement){ start=this._firstNewElement *this._vertexStride *this._floatCountPerVertex; this._vertexBuffer.setData(this._vertices,start,start,(this._firstFreeElement-this._firstNewElement)*this._vertexStride *this._floatCountPerVertex); }else { start=this._firstNewElement *this._vertexStride *this._floatCountPerVertex; this._vertexBuffer.setData(this._vertices,start,start,(this._bufferMaxParticles-this._firstNewElement)*this._vertexStride *this._floatCountPerVertex); if (this._firstFreeElement > 0){ this._vertexBuffer.setData(this._vertices,0,0,this._firstFreeElement *this._vertexStride *this._floatCountPerVertex); } } this._firstNewElement=this._firstFreeElement; } __proto._beforeRender=function(state){ if (this._firstNewElement !=this._firstFreeElement) this.addNewParticlesToVertexBuffer(); this._drawCounter++; if (this._firstActiveElement !=this._firstFreeElement){ this._vertexBuffer._bind(); this._indexBuffer._bind(); return true; } return false; } /** *@private */ __proto._render=function(state){ var indexCount=0; var gl=WebGL.mainContext; if (this._firstActiveElement < this._firstFreeElement){ indexCount=(this._firstFreeElement-this._firstActiveElement)*this._indexStride; gl.drawElements(/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,indexCount,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,2 *this._firstActiveElement *this._indexStride); Stat.trianglesFaces+=indexCount / 3; Stat.drawCall++; }else { indexCount=(this._bufferMaxParticles-this._firstActiveElement)*this._indexStride; gl.drawElements(/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,indexCount,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,2 *this._firstActiveElement *this._indexStride); Stat.trianglesFaces+=indexCount / 3; Stat.drawCall++; if (this._firstFreeElement > 0){ indexCount=this._firstFreeElement *this._indexStride; gl.drawElements(/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,indexCount,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,0); Stat.trianglesFaces+=indexCount / 3; Stat.drawCall++; } } } /** *开始发射粒子。 */ __proto.play=function(){ this._burstsIndex=0; this._isEmitting=true; this._isPlaying=true; this._isPaused=false; this._emissionTime=0; this._totalDelayTime=0; if (!this.autoRandomSeed){ for (var i=0,n=this._randomSeeds.length;i < n;i++) this._randomSeeds[i]=this.randomSeed[0]+ShurikenParticleSystem._RANDOMOFFSET[i]; } switch (this.startDelayType){ case 0: this._playStartDelay=this.startDelay; break ; case 1: if (this.autoRandomSeed){ this._playStartDelay=MathUtil.lerp(this.startDelayMin,this.startDelayMax,Math.random()); }else { this._rand.seed=this._randomSeeds[2]; this._playStartDelay=MathUtil.lerp(this.startDelayMin,this.startDelayMax,this._rand.getFloat()); this._randomSeeds[2]=this._rand.seed; } break ; default : throw new Error("Utils3D: startDelayType is invalid."); } this._frameRateTime=this._currentTime+this._playStartDelay; this._startUpdateLoopCount=Stat.loopCount; this.event(/*laya.events.Event.PLAYED*/"played"); } /** *暂停发射粒子。 */ __proto.pause=function(){ this._isPaused=true; this.event(/*laya.events.Event.PAUSED*/"paused"); } /** *通过指定时间增加粒子播放进度,并暂停播放。 *@param time 进度时间.如果restart为true,粒子播放时间会归零后再更新进度。 *@param restart 是否重置播放状态。 */ __proto.simulate=function(time,restart){ (restart===void 0)&& (restart=true); this._simulateUpdate=true; if (restart){ this._updateParticlesSimulationRestart(time); } else{ this._isPaused=false; this._updateParticles(time); } this.pause(); } /** *停止发射粒子。 */ __proto.stop=function(){ this._burstsIndex=0; this._isEmitting=false; this._emissionTime=0; this.event(/*laya.events.Event.STOPPED*/"stopped"); } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ var dest=destObject; dest.duration=this.duration; dest.looping=this.looping; dest.prewarm=this.prewarm; dest.startDelayType=this.startDelayType; dest.startDelay=this.startDelay; dest.startDelayMin=this.startDelayMin; dest.startDelayMax=this.startDelayMax; dest._maxStartLifetime=this._maxStartLifetime; dest.startLifetimeType=this.startLifetimeType; dest.startLifetimeConstant=this.startLifetimeConstant; this.startLifeTimeGradient.cloneTo(dest.startLifeTimeGradient); dest.startLifetimeConstantMin=this.startLifetimeConstantMin; dest.startLifetimeConstantMax=this.startLifetimeConstantMax; this.startLifeTimeGradientMin.cloneTo(dest.startLifeTimeGradientMin); this.startLifeTimeGradientMax.cloneTo(dest.startLifeTimeGradientMax); dest.startSpeedType=this.startSpeedType; dest.startSpeedConstant=this.startSpeedConstant; dest.startSpeedConstantMin=this.startSpeedConstantMin; dest.startSpeedConstantMax=this.startSpeedConstantMax; dest.threeDStartSize=this.threeDStartSize; dest.startSizeType=this.startSizeType; dest.startSizeConstant=this.startSizeConstant; this.startSizeConstantSeparate.cloneTo(dest.startSizeConstantSeparate); dest.startSizeConstantMin=this.startSizeConstantMin; dest.startSizeConstantMax=this.startSizeConstantMax; this.startSizeConstantMinSeparate.cloneTo(dest.startSizeConstantMinSeparate); this.startSizeConstantMaxSeparate.cloneTo(dest.startSizeConstantMaxSeparate); dest.threeDStartRotation=this.threeDStartRotation; dest.startRotationType=this.startRotationType; dest.startRotationConstant=this.startRotationConstant; this.startRotationConstantSeparate.cloneTo(dest.startRotationConstantSeparate); dest.startRotationConstantMin=this.startRotationConstantMin; dest.startRotationConstantMax=this.startRotationConstantMax; this.startRotationConstantMinSeparate.cloneTo(dest.startRotationConstantMinSeparate); this.startRotationConstantMaxSeparate.cloneTo(dest.startRotationConstantMaxSeparate); dest.randomizeRotationDirection=this.randomizeRotationDirection; dest.startColorType=this.startColorType; this.startColorConstant.cloneTo(dest.startColorConstant); this.startColorConstantMin.cloneTo(dest.startColorConstantMin); this.startColorConstantMax.cloneTo(dest.startColorConstantMax); dest.gravityModifier=this.gravityModifier; dest.simulationSpace=this.simulationSpace; dest.scaleMode=this.scaleMode; dest.playOnAwake=this.playOnAwake; dest.maxParticles=this.maxParticles; (this._emission)&& (dest._emission=this._emission.clone()); (this.shape)&& (dest.shape=this.shape.clone()); (this.velocityOverLifetime)&& (dest.velocityOverLifetime=this.velocityOverLifetime.clone()); (this.colorOverLifetime)&& (dest.colorOverLifetime=this.colorOverLifetime.clone()); (this.sizeOverLifetime)&& (dest.sizeOverLifetime=this.sizeOverLifetime.clone()); (this.rotationOverLifetime)&& (dest.rotationOverLifetime=this.rotationOverLifetime.clone()); (this.textureSheetAnimation)&& (dest.textureSheetAnimation=this.textureSheetAnimation.clone()); dest.isPerformanceMode=this.isPerformanceMode; dest._isEmitting=this._isEmitting; dest._isPlaying=this._isPlaying; dest._isPaused=this._isPaused; dest._playStartDelay=this._playStartDelay; dest._frameRateTime=this._frameRateTime; dest._emissionTime=this._emissionTime; dest._totalDelayTime=this._totalDelayTime; dest._burstsIndex=this._burstsIndex; } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var dest=/*__JS__ */new this.constructor(); this.cloneTo(dest); return dest; } /** *@private */ __proto._getVertexBuffers=function(){ return null; } /**设置最大粒子数,注意:谨慎修改此属性,有性能损耗。*/ /**获取最大粒子数。*/ __getset(0,__proto,'maxParticles',function(){ return this._bufferMaxParticles-1; },function(value){ var newMaxParticles=value+1; if (newMaxParticles!==this._bufferMaxParticles){ this._bufferMaxParticles=newMaxParticles; this._initBufferDatas(); } }); /** *是否正在发射。 */ __getset(0,__proto,'isEmitting',function(){ return this._isEmitting; }); /** *是否存活。 */ __getset(0,__proto,'isAlive',function(){ if (this._isPlaying || this.aliveParticleCount > 0) return true; return false; }); /** *设置形状。 */ /** *获取形状。 */ __getset(0,__proto,'shape',function(){ return this._shape; },function(value){ if (this._shape!==value){ if (value&&value.enable) this._ownerRender._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_SHAPE); else this._ownerRender._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_SHAPE); this._shape=value; } }); /** *设置生命周期旋转,注意:如修改该值的某些属性,需重新赋值此属性才可生效。 *@param value 生命周期旋转。 */ /** *获取生命周期旋转,注意:如修改该值的某些属性,需重新赋值此属性才可生效。 *@return 生命周期旋转。 */ __getset(0,__proto,'rotationOverLifetime',function(){ return this._rotationOverLifetime; },function(value){ var render=this._ownerRender; if (value){ var rotation=value.angularVelocity; if (!rotation) return; var rotationSeparate=rotation.separateAxes; var rotationType=rotation.type; if (value.enbale){ if (rotationSeparate) render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMESEPERATE); else render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIME); switch (rotationType){ case 0: render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMECONSTANT); break ; case 1: render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMECURVE); break ; case 2: render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCONSTANTS); break ; case 3: render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCURVES); break ; } }else { render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIME); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMESEPERATE); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMECONSTANT); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMECURVE); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCONSTANTS); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCURVES); } switch (rotationType){ case 0: if (rotationSeparate){ render._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYCONSTSEPRARATE*/35,rotation.constantSeparate); }else { render._setShaderValueNumber(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYCONST*/34,rotation.constant); } break ; case 1: if (rotationSeparate){ render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTX*/37,rotation.gradientX._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTY*/38,rotation.gradientY._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTZ*/39,rotation.gradientZ._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTW*/40,rotation.gradientW._elements); }else { render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENT*/36,rotation.gradient._elements); } break ; case 2: if (rotationSeparate){ render._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYCONSTSEPRARATE*/35,rotation.constantMinSeparate); render._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYCONSTMAXSEPRARATE*/42,rotation.constantMaxSeparate); }else { render._setShaderValueNumber(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYCONST*/34,rotation.constantMin); render._setShaderValueNumber(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYCONSTMAX*/41,rotation.constantMax); } break ; case 3: if (rotationSeparate){ render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTX*/37,rotation.gradientXMin._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTXMAX*/44,rotation.gradientXMax._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTY*/38,rotation.gradientYMin._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTYMAX*/45,rotation.gradientYMax._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTZ*/39,rotation.gradientZMin._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTZMAX*/46,rotation.gradientZMax._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTW*/40,rotation.gradientWMin._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTWMAX*/47,rotation.gradientWMax._elements); }else { render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENT*/36,rotation.gradientMin._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTMAX*/43,rotation.gradientMax._elements); } break ; } }else { render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIME); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMESEPERATE); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMECONSTANT); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMECURVE); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCONSTANTS); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCURVES); render._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYCONSTSEPRARATE*/35,null); render._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYCONSTMAXSEPRARATE*/42,null); render._setShaderValueNumber(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYCONST*/34,undefined); render._setShaderValueNumber(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYCONSTMAX*/41,undefined); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTX*/37,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTXMAX*/44,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTY*/38,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTYMAX*/45,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTZ*/39,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTZMAX*/46,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTW*/40,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTWMAX*/47,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENT*/36,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTMAX*/43,null); } this._rotationOverLifetime=value; }); /** *获取发射器。 */ __getset(0,__proto,'emission',function(){ return this._emission; }); /** *获取一次循环内的累计时间。 *@return 一次循环内的累计时间。 */ __getset(0,__proto,'emissionTime',function(){ return this._emissionTime > this.duration ? this.duration :this._emissionTime; }); /** *粒子存活个数。 */ __getset(0,__proto,'aliveParticleCount',function(){ if (this._firstNewElement >=this._firstRetiredElement) return this._firstNewElement-this._firstRetiredElement; else return this._bufferMaxParticles-this._firstRetiredElement+this._firstNewElement; }); /** *是否正在播放。 */ __getset(0,__proto,'isPlaying',function(){ return this._isPlaying; }); /** *是否已暂停。 */ __getset(0,__proto,'isPaused',function(){ return this._isPaused; }); /** *设置开始生命周期模式,0为固定时间,1为渐变时间,2为两个固定之间的随机插值,3为两个渐变时间的随机插值。 */ /** *获取开始生命周期模式,0为固定时间,1为渐变时间,2为两个固定之间的随机插值,3为两个渐变时间的随机插值。 */ __getset(0,__proto,'startLifetimeType',function(){ return this._startLifetimeType; },function(value){ var i=0,n=0; switch (this.startLifetimeType){ case 0: this._maxStartLifetime=this.startLifetimeConstant; break ; case 1: this._maxStartLifetime=-Number.MAX_VALUE; var startLifeTimeGradient=startLifeTimeGradient; for (i=0,n=startLifeTimeGradient.gradientCount;i < n;i++) this._maxStartLifetime=Math.max(this._maxStartLifetime,startLifeTimeGradient.getValueByIndex(i)); break ; case 2: this._maxStartLifetime=Math.max(this.startLifetimeConstantMin,this.startLifetimeConstantMax); break ; case 3: this._maxStartLifetime=-Number.MAX_VALUE; var startLifeTimeGradientMin=startLifeTimeGradientMin; for (i=0,n=startLifeTimeGradientMin.gradientCount;i < n;i++) this._maxStartLifetime=Math.max(this._maxStartLifetime,startLifeTimeGradientMin.getValueByIndex(i)); var startLifeTimeGradientMax=startLifeTimeGradientMax; for (i=0,n=startLifeTimeGradientMax.gradientCount;i < n;i++) this._maxStartLifetime=Math.max(this._maxStartLifetime,startLifeTimeGradientMax.getValueByIndex(i)); break ; } this._startLifetimeType=value; }); /** *@inheritDoc */ __getset(0,__proto,'_originalBoundingSphere',function(){ return this._boundingSphere; }); /** *设置开始生命周期,0模式,单位为秒。 */ /** *获取开始生命周期,0模式,单位为秒。 */ __getset(0,__proto,'startLifetimeConstant',function(){ return this._startLifetimeConstant; },function(value){ if(this._startLifetimeType===0) this._maxStartLifetime=value; this._startLifetimeConstant=value; }); /** *设置最小开始生命周期,2模式,单位为秒。 */ /** *获取最小开始生命周期,2模式,单位为秒。 */ __getset(0,__proto,'startLifetimeConstantMin',function(){ return this._startLifetimeConstantMin; },function(value){ if (this._startLifetimeType===2) this._maxStartLifetime=Math.max(value,this._startLifetimeConstantMax); this._startLifetimeConstantMin=value; }); /** *设置开始渐变生命周期,1模式,单位为秒。 */ /** *获取开始渐变生命周期,1模式,单位为秒。 */ __getset(0,__proto,'startLifeTimeGradient',function(){ return this._startLifeTimeGradient; },function(value){ if (this._startLifetimeType===1){ this._maxStartLifetime=-Number.MAX_VALUE; for (var i=0,n=value.gradientCount;i < n;i++) this._maxStartLifetime=Math.max(this._maxStartLifetime,value.getValueByIndex(i)); } this._startLifeTimeGradient=value; }); /** *设置最大开始生命周期,2模式,单位为秒。 */ /** *获取最大开始生命周期,2模式,单位为秒。 */ __getset(0,__proto,'startLifetimeConstantMax',function(){ return this._startLifetimeConstantMax; },function(value){ if (this._startLifetimeType===2) this._maxStartLifetime=Math.max(this._startLifetimeConstantMin,value); this._startLifetimeConstantMax=value; }); /** *设置开始渐变最小生命周期,3模式,单位为秒。 */ /** *获取开始渐变最小生命周期,3模式,单位为秒。 */ __getset(0,__proto,'startLifeTimeGradientMin',function(){ return this._startLifeTimeGradientMin; },function(value){ if (this._startLifetimeType===3){ var i=0,n=0; this._maxStartLifetime=-Number.MAX_VALUE; for (i=0,n=value.gradientCount;i < n;i++) this._maxStartLifetime=Math.max(this._maxStartLifetime,value.getValueByIndex(i)); for (i=0,n=this._startLifeTimeGradientMax.gradientCount;i < n;i++) this._maxStartLifetime=Math.max(this._maxStartLifetime,this._startLifeTimeGradientMax.getValueByIndex(i)); } this._startLifeTimeGradientMin=value; }); /** *设置开始渐变最大生命周期,3模式,单位为秒。 */ /** *获取开始渐变最大生命周期,3模式,单位为秒。 */ __getset(0,__proto,'startLifeTimeGradientMax',function(){ return this._startLifeTimeGradientMax; },function(value){ if (this._startLifetimeType===3){ var i=0,n=0; this._maxStartLifetime=-Number.MAX_VALUE; for (i=0,n=this._startLifeTimeGradientMin.gradientCount;i < n;i++) this._maxStartLifetime=Math.max(this._maxStartLifetime,this._startLifeTimeGradientMin.getValueByIndex(i)); for (i=0,n=value.gradientCount;i < n;i++) this._maxStartLifetime=Math.max(this._maxStartLifetime,value.getValueByIndex(i)); } this._startLifeTimeGradientMax=value; }); /** *设置生命周期速度,注意:如修改该值的某些属性,需重新赋值此属性才可生效。 *@param value 生命周期速度. */ /** *获取生命周期速度,注意:如修改该值的某些属性,需重新赋值此属性才可生效。 *@return 生命周期速度. */ __getset(0,__proto,'velocityOverLifetime',function(){ return this._velocityOverLifetime; },function(value){ var render=this._ownerRender; if (value){ var velocity=value.velocity; var velocityType=velocity.type; if (value.enbale){ switch (velocityType){ case 0: render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMECONSTANT); break ; case 1: render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMECURVE); break ; case 2: render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCONSTANT); break ; case 3: render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCURVE); break ; } }else { render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMECONSTANT); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMECURVE); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCONSTANT); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCURVE); } switch (velocityType){ case 0: render._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYCONST*/13,velocity.constant); break ; case 1: render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTX*/14,velocity.gradientX._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTY*/15,velocity.gradientY._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTZ*/16,velocity.gradientZ._elements); break ; case 2: render._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYCONST*/13,velocity.constantMin); render._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYCONSTMAX*/17,velocity.constantMax); break ; case 3: render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTX*/14,velocity.gradientXMin._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTXMAX*/18,velocity.gradientXMax._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTY*/15,velocity.gradientYMin._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTYMAX*/19,velocity.gradientYMax._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTZ*/16,velocity.gradientZMin._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTZMAX*/20,velocity.gradientZMax._elements); break ; } render._setShaderValueInt(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLSPACETYPE*/21,value.space); }else { render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMECONSTANT); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMECURVE); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCONSTANT); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCURVE); render._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYCONST*/13,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTX*/14,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTY*/15,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTZ*/16,null); render._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYCONST*/13,null); render._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYCONSTMAX*/17,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTX*/14,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTXMAX*/18,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTY*/15,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTYMAX*/19,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTZ*/16,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTZMAX*/20,null); render._setShaderValueInt(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLSPACETYPE*/21,undefined); } this._velocityOverLifetime=value; }); /** *设置生命周期颜色,注意:如修改该值的某些属性,需重新赋值此属性才可生效。 *@param value 生命周期颜色 */ /** *获取生命周期颜色,注意:如修改该值的某些属性,需重新赋值此属性才可生效。 *@return 生命周期颜色 */ __getset(0,__proto,'colorOverLifetime',function(){ return this._colorOverLifetime; },function(value){ var render=this._ownerRender; if (value){ var color=value.color; if (value.enbale){ switch (color.type){ case 1: render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_COLOROVERLIFETIME); break ; case 3: render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_RANDOMCOLOROVERLIFETIME); break ; } }else { render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_COLOROVERLIFETIME); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_RANDOMCOLOROVERLIFETIME); } switch (color.type){ case 1:; var gradientColor=color.gradient; render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.COLOROVERLIFEGRADIENTALPHAS*/22,gradientColor._alphaElements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.COLOROVERLIFEGRADIENTCOLORS*/23,gradientColor._rgbElements); break ; case 3:; var minGradientColor=color.gradientMin; var maxGradientColor=color.gradientMax; render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.COLOROVERLIFEGRADIENTALPHAS*/22,minGradientColor._alphaElements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.COLOROVERLIFEGRADIENTCOLORS*/23,minGradientColor._rgbElements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.MAXCOLOROVERLIFEGRADIENTALPHAS*/24,maxGradientColor._alphaElements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.MAXCOLOROVERLIFEGRADIENTCOLORS*/25,maxGradientColor._rgbElements); break ; } }else { render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_COLOROVERLIFETIME); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_RANDOMCOLOROVERLIFETIME); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.COLOROVERLIFEGRADIENTALPHAS*/22,gradientColor._alphaElements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.COLOROVERLIFEGRADIENTCOLORS*/23,gradientColor._rgbElements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.COLOROVERLIFEGRADIENTALPHAS*/22,minGradientColor._alphaElements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.COLOROVERLIFEGRADIENTCOLORS*/23,minGradientColor._rgbElements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.MAXCOLOROVERLIFEGRADIENTALPHAS*/24,maxGradientColor._alphaElements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.MAXCOLOROVERLIFEGRADIENTCOLORS*/25,maxGradientColor._rgbElements); } this._colorOverLifetime=value; }); /** *设置生命周期尺寸,注意:如修改该值的某些属性,需重新赋值此属性才可生效。 *@param value 生命周期尺寸 */ /** *获取生命周期尺寸,注意:如修改该值的某些属性,需重新赋值此属性才可生效。 *@return 生命周期尺寸 */ __getset(0,__proto,'sizeOverLifetime',function(){ return this._sizeOverLifetime; },function(value){ var render=this._ownerRender; if (value){ var size=value.size; var sizeSeparate=size.separateAxes; var sizeType=size.type; if (value.enbale){ switch (sizeType){ case 0: if (sizeSeparate) render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMECURVESEPERATE); else render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMECURVE); break ; case 2: if (sizeSeparate) render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVESSEPERATE); else render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVES); break ; } }else { render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMECURVE); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMECURVESEPERATE); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVES); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVESSEPERATE); } switch (sizeType){ case 0: if (sizeSeparate){ render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENTX*/27,size.gradientX._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENTY*/28,size.gradientY._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSizeGradientZ*/29,size.gradientZ._elements); }else { render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENT*/26,size.gradient._elements); } break ; case 2: if (sizeSeparate){ render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENTX*/27,size.gradientXMin._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENTXMAX*/31,size.gradientXMax._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENTY*/28,size.gradientYMin._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENTYMAX*/32,size.gradientYMax._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSizeGradientZ*/29,size.gradientZMin._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSizeGradientZMAX*/33,size.gradientZMax._elements); }else { render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENT*/26,size.gradientMin._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSizeGradientMax*/30,size.gradientMax._elements); } break ; } }else { render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMECURVE); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMECURVESEPERATE); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVES); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVESSEPERATE); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENTX*/27,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENTXMAX*/31,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENTY*/28,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENTYMAX*/32,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSizeGradientZ*/29,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSizeGradientZMAX*/33,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENT*/26,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSizeGradientMax*/30,null); } this._sizeOverLifetime=value; }); /** *设置生命周期纹理动画,注意:如修改该值的某些属性,需重新赋值此属性才可生效。 *@param value 生命周期纹理动画。 */ /** *获取生命周期纹理动画,注意:如修改该值的某些属性,需重新赋值此属性才可生效。 *@return 生命周期纹理动画。 */ __getset(0,__proto,'textureSheetAnimation',function(){ return this._textureSheetAnimation; },function(value){ var render=this._ownerRender; if (value){ var frameOverTime=value.frame; var textureAniType=frameOverTime.type; if (value.enable){ switch (textureAniType){ case 1: render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_TEXTURESHEETANIMATIONCURVE); break ; case 3: render._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_TEXTURESHEETANIMATIONRANDOMCURVE); break ; } }else { render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_TEXTURESHEETANIMATIONCURVE); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_TEXTURESHEETANIMATIONRANDOMCURVE); } if (textureAniType===1 || textureAniType===3){ render._setShaderValueInt(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.TEXTURESHEETANIMATIONCYCLES*/48,value.cycles); var title=value.tiles; var _uvLengthE=this._uvLength.elements; _uvLengthE[0]=1.0 / title.x; _uvLengthE[1]=1.0 / title.y; render._setShaderValueVector2(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.TEXTURESHEETANIMATIONSUBUVLENGTH*/49,this._uvLength); } switch (textureAniType){ case 1: render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.TEXTURESHEETANIMATIONGRADIENTUVS*/50,frameOverTime.frameOverTimeData._elements); break ; case 3: render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.TEXTURESHEETANIMATIONGRADIENTUVS*/50,frameOverTime.frameOverTimeDataMin._elements); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.TEXTURESHEETANIMATIONGRADIENTMAXUVS*/51,frameOverTime.frameOverTimeDataMax._elements); break ; } }else { render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_TEXTURESHEETANIMATIONCURVE); render._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_TEXTURESHEETANIMATIONRANDOMCURVE); render._setShaderValueInt(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.TEXTURESHEETANIMATIONCYCLES*/48,undefined); render._setShaderValueVector2(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.TEXTURESHEETANIMATIONSUBUVLENGTH*/49,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.TEXTURESHEETANIMATIONGRADIENTUVS*/50,null); render._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.TEXTURESHEETANIMATIONGRADIENTMAXUVS*/51,null); } this._textureSheetAnimation=value; }); __getset(0,__proto,'_vertexBufferCount',function(){ return 1; }); __getset(0,__proto,'triangleCount',function(){ return this._indexBuffer?this._indexBuffer.indexCount / 3:0; }); /** *@inheritDoc */ __getset(0,__proto,'_originalBoundingBox',function(){ return this._boundingBox; }); /** *@inheritDoc */ __getset(0,__proto,'_originalBoundingBoxCorners',function(){ return this._boundingBoxCorners; }); ShurikenParticleSystem.halfKSqrtOf2=1.42 *0.5; __static(ShurikenParticleSystem, ['_RANDOMOFFSET',function(){return this._RANDOMOFFSET=new Uint32Array([0x23571a3e,0xc34f56fe,0x13371337,0x12460f3b,0x6aed452e,0xdec4aea1,0x96aa4de3,0x8d2c8431,0xf3857f6f,0xe0fbd834,0x13740583,0x591bc05c,0x40eb95e4,0xbc524e5f,0xaf502044,0xa614b381,0x1034e524,0xfc524e5f]);},'_maxElapsedTime',function(){return this._maxElapsedTime=1.0 / 3.0;},'_tempVector30',function(){return this._tempVector30=new Vector3();},'_tempVector31',function(){return this._tempVector31=new Vector3();},'_tempVector32',function(){return this._tempVector32=new Vector3();},'_tempVector33',function(){return this._tempVector33=new Vector3();},'_tempVector34',function(){return this._tempVector34=new Vector3();},'_tempVector35',function(){return this._tempVector35=new Vector3();},'_tempVector36',function(){return this._tempVector36=new Vector3();},'_tempVector37',function(){return this._tempVector37=new Vector3();},'_tempVector38',function(){return this._tempVector38=new Vector3();},'_tempVector39',function(){return this._tempVector39=new Vector3();},'_tempPosition',function(){return this._tempPosition=new Vector3();},'_tempDirection',function(){return this._tempDirection=new Vector3();} ]); return ShurikenParticleSystem; })(GeometryFilter) /** *ShurikenParticleRender 类用于创建3D粒子渲染器。 */ //class laya.d3.core.particleShuriKen.ShurikenParticleRender extends laya.d3.core.render.BaseRender var ShurikenParticleRender=(function(_super){ function ShurikenParticleRender(owner){ /**@private */ //this._defaultBoundBox=null; /**@private */ //this._renderMode=0; /**@private */ //this._mesh=null; /**拉伸广告牌模式摄像机速度缩放,暂不支持。*/ //this.stretchedBillboardCameraSpeedScale=NaN; /**拉伸广告牌模式速度缩放。*/ //this.stretchedBillboardSpeedScale=NaN; /**拉伸广告牌模式长度缩放。*/ //this.stretchedBillboardLengthScale=NaN; this._finalGravity=new Vector3(); this._tempRotationMatrix=new Matrix4x4(); ShurikenParticleRender.__super.call(this,owner); this._defaultBoundBox=new BoundBox(new Vector3(),new Vector3()); this._renderMode=-1; this.stretchedBillboardCameraSpeedScale=0.0; this.stretchedBillboardSpeedScale=0.0; this.stretchedBillboardLengthScale=1.0; } __class(ShurikenParticleRender,'laya.d3.core.particleShuriKen.ShurikenParticleRender',_super); var __proto=ShurikenParticleRender.prototype; /** *@inheritDoc */ __proto._calculateBoundingBox=function(){ var minE=this._boundingBox.min.elements; minE[0]=-Number.MAX_VALUE; minE[1]=-Number.MAX_VALUE; minE[2]=-Number.MAX_VALUE; var maxE=this._boundingBox.min.elements; maxE[0]=Number.MAX_VALUE; maxE[1]=Number.MAX_VALUE; maxE[2]=Number.MAX_VALUE; } /** *@inheritDoc */ __proto._calculateBoundingSphere=function(){ var oriBoundSphere=(this._owner).particleSystem._boundingSphere; var maxScale=NaN; var transform=this._owner.transform; var scaleE=transform.scale.elements; var scaleX=Math.abs(scaleE[0]); var scaleY=Math.abs(scaleE[1]); var scaleZ=Math.abs(scaleE[2]); if (scaleX >=scaleY && scaleX >=scaleZ) maxScale=scaleX; else maxScale=scaleY >=scaleZ ? scaleY :scaleZ; Vector3.transformCoordinate(oriBoundSphere.center,transform.worldMatrix,this._boundingSphere.center); this._boundingSphere.radius=oriBoundSphere.radius *maxScale; } /** *@inheritDoc */ __proto._renderUpdate=function(projectionView){ var particleSystem=(this._owner).particleSystem; if (!Laya.stage.isVisibility||!particleSystem.isAlive) return false; var transform=this._owner.transform; switch (particleSystem.simulationSpace){ case 0: break ; case 1: this._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.WORLDPOSITION*/0,transform.position); this._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.WORLDROTATION*/1,transform.rotation); break ; default : throw new Error("ShurikenParticleMaterial: SimulationSpace value is invalid."); } switch (particleSystem.scaleMode){ case 0:; var scale=transform.scale; this._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.POSITIONSCALE*/4,scale); this._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SIZESCALE*/5,scale); break ; case 1:; var localScale=transform.localScale; this._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.POSITIONSCALE*/4,localScale); this._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SIZESCALE*/5,localScale); break ; case 2: this._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.POSITIONSCALE*/4,transform.scale); this._setShaderValueColor(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SIZESCALE*/5,Vector3.ONE); break ; }; var finalGravityE=this._finalGravity.elements; var gravityE=Physics.gravity.elements; var gravityModifier=particleSystem.gravityModifier; finalGravityE[0]=gravityE[0] *gravityModifier; finalGravityE[1]=gravityE[1] *gravityModifier; finalGravityE[2]=gravityE[2] *gravityModifier; this._setShaderValueBuffer(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.GRAVITY*/7,finalGravityE); this._setShaderValueInt(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SIMULATIONSPACE*/11,particleSystem.simulationSpace); this._setShaderValueBool(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.THREEDSTARTROTATION*/8,particleSystem.threeDStartRotation); this._setShaderValueInt(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SCALINGMODE*/6,particleSystem.scaleMode); this._setShaderValueInt(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.STRETCHEDBILLBOARDLENGTHSCALE*/9,this.stretchedBillboardLengthScale); this._setShaderValueInt(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.STRETCHEDBILLBOARDSPEEDSCALE*/10,this.stretchedBillboardSpeedScale); this._setShaderValueNumber(/*laya.d3.core.particleShuriKen.ShuriKenParticle3D.CURRENTTIME*/12,particleSystem._currentTime); if (Laya3D.debugMode) this._renderRenderableBoundBox(); return true; } /** *@inheritDoc */ __proto._destroy=function(){ _super.prototype._destroy.call(this); (this._mesh)&& (this._mesh._removeReference(),this._mesh=null); } /** *@inheritDoc */ __getset(0,__proto,'boundingBox',function(){ if (!(this._owner).particleSystem.isAlive){ return this._defaultBoundBox; }else { if (this._boundingBoxNeedChange){ this._calculateBoundingBox(); this._boundingBoxNeedChange=false; } return this._boundingBox; } }); /** *设置渲染模式,0为BILLBOARD、1为STRETCHEDBILLBOARD、2为HORIZONTALBILLBOARD、3为VERTICALBILLBOARD、4为MESH。 *@param value 渲染模式。 */ /** *获取渲染模式。 *@return 渲染模式。 */ __getset(0,__proto,'renderMode',function(){ return this._renderMode; },function(value){ if (this._renderMode!==value){ switch (this._renderMode){ case 0: this._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_BILLBOARD); break ; case 1: this._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_STRETCHEDBILLBOARD); break ; case 2: this._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_HORIZONTALBILLBOARD); break ; case 3: this._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_VERTICALBILLBOARD); break ; case 4: this._removeShaderDefine(ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_MESH); break ; } this._renderMode=value; switch (value){ case 0: this._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_BILLBOARD); break ; case 1: this._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_STRETCHEDBILLBOARD); break ; case 2: this._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_HORIZONTALBILLBOARD); break ; case 3: this._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_VERTICALBILLBOARD); break ; case 4: this._addShaderDefine(ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_MESH); break ; default : throw new Error("ShurikenParticleRender: unknown renderMode Value."); } (this._owner).particleSystem._initBufferDatas(); } }); /** *设置网格渲染模式所使用的Mesh,rendderMode为4时生效。 *@param value 网格模式所使用Mesh。 */ /** *获取网格渲染模式所使用的Mesh,rendderMode为4时生效。 *@return 网格模式所使用Mesh。 */ __getset(0,__proto,'mesh',function(){ return this._mesh },function(value){ if (this._mesh!==value){ (this._mesh)&& (this._mesh._removeReference()); this._mesh=value; (value)&& (value._addReference()); (this._owner).particleSystem._initBufferDatas(); } }); return ShurikenParticleRender; })(BaseRender) /** *... *@author ... */ //class laya.d3.core.trail.TrailFilter extends laya.d3.core.GeometryFilter var TrailFilter=(function(_super){ function TrailFilter(owner){ this._owner=null; this._trailRenderElements=null; this._minVertexDistance=NaN; this._widthMultiplier=NaN; this._time=NaN; this._widthCurve=null; this._colorGradient=null; this._textureMode=0; this._curtime=0; this._curSubTrailFinishCurTime=0; this._curSubTrailFinished=false; this._hasLifeSubTrail=false; this._trailTotalLength=0; this._trailSupplementLength=0; this._trailDeadLength=0; this._isStart=false; this._trailRenderElementIndex=0; TrailFilter.__super.call(this); this._curSubTrailFinishPosition=new Vector3(); this._curSubTrailFinishDirection=new Vector3(); this._owner=owner; this._trailRenderElements=[]; this.addRenderElement(); } __class(TrailFilter,'laya.d3.core.trail.TrailFilter',_super); var __proto=TrailFilter.prototype; __proto.getRenderElementsCount=function(){ return this._trailRenderElements.length; } __proto.addRenderElement=function(){ for (var i=0;i < this._trailRenderElements.length;i++){ if (this._trailRenderElements[i]._isDead==true){ this._trailRenderElements[i].reActivate(); return i; } }; var _trailRenderElement=new TrailRenderElement(this); this._trailRenderElements.push(_trailRenderElement); return this._trailRenderElements.length-1; } __proto.getRenderElement=function(index){ return this._trailRenderElements[index]; } __proto._update=function(state){ this._curtime+=state.elapsedTime / 1000; this._owner._render._setShaderValueNumber(/*laya.d3.core.trail.TrailSprite3D.CURTIME*/3,this._curtime); if (this._curSubTrailFinished){ this._curSubTrailFinished=false; this._trailRenderElementIndex=this.addRenderElement(); this.event(/*laya.events.Event.TRAIL_FILTER_CHANGE*/"trailfilterchange",[this._trailRenderElementIndex,this._trailRenderElements[this._trailRenderElementIndex]]); } } __proto.reset=function(){ for (var i=0;i < this._trailRenderElements.length;i++){ this._trailRenderElements[i].reActivate(); } this._isStart=false; this._hasLifeSubTrail=false; this._curSubTrailFinished=false; this._curSubTrailFinishCurTime=0; this._trailTotalLength=0; this._trailSupplementLength=0; this._trailDeadLength=0; } /** *@private */ __proto._destroy=function(){ _super.prototype._destroy.call(this); for (var i=0;i < this._trailRenderElements.length;i++){ this._trailRenderElements[i]._destroy(); } this._trailRenderElements=null; this._widthCurve=null; this._colorGradient=null; this._curSubTrailFinishPosition=null; this._curSubTrailFinishDirection=null; } /** *设置宽度倍数。 *@param value 宽度倍数。 */ /** *获取宽度倍数。 *@return 宽度倍数。 */ __getset(0,__proto,'widthMultiplier',function(){ return this._widthMultiplier; },function(value){ this._widthMultiplier=value; }); /** *设置淡出时间。 *@param value 淡出时间。 */ /** *获取淡出时间。 *@return 淡出时间。 */ __getset(0,__proto,'time',function(){ return this._time; },function(value){ this._time=value; this._owner._render._setShaderValueNumber(/*laya.d3.core.trail.TrailSprite3D.LIFETIME*/4,value); }); /** *设置宽度曲线。 *@param value 宽度曲线。 */ /** *获取宽度曲线。 *@return 宽度曲线。 */ __getset(0,__proto,'widthCurve',function(){ return this._widthCurve; },function(value){ this._widthCurve=value; var widthCurveFloatArray=new Float32Array(value.length *4); var i=0,j=0,index=0; for (i=0,j=value.length;i < j;i++){ widthCurveFloatArray[index++]=value[i].time; widthCurveFloatArray[index++]=value[i].inTangent; widthCurveFloatArray[index++]=value[i].outTangent; widthCurveFloatArray[index++]=value[i].value; } this._owner._render._setShaderValueBuffer(/*laya.d3.core.trail.TrailSprite3D.WIDTHCURVE*/5,widthCurveFloatArray); this._owner._render._setShaderValueInt(/*laya.d3.core.trail.TrailSprite3D.WIDTHCURVEKEYLENGTH*/6,value.length); }); /** *设置新旧顶点之间最小距离。 *@param value 新旧顶点之间最小距离。 */ /** *获取新旧顶点之间最小距离。 *@return 新旧顶点之间最小距离。 */ __getset(0,__proto,'minVertexDistance',function(){ return this._minVertexDistance; },function(value){ this._minVertexDistance=value; }); /** *设置颜色梯度。 *@param value 颜色梯度。 */ /** *获取颜色梯度。 *@return 颜色梯度。 */ __getset(0,__proto,'colorGradient',function(){ return this._colorGradient; },function(value){ this._colorGradient=value; this._owner._render._setShaderValueBuffer(/*laya.d3.core.trail.TrailSprite3D.GRADIENTCOLORKEY*/7,value._colorKeyData); this._owner._render._setShaderValueBuffer(/*laya.d3.core.trail.TrailSprite3D.GRADIENTALPHAKEY*/8,value._alphaKeyData); if (value.mode==/*laya.d3.core.trail.module.GradientMode.Blend*/0){ this._owner._render._addShaderDefine(TrailSprite3D.SHADERDEFINE_GRADIENTMODE_BLEND); } else{ this._owner._render._removeShaderDefine(TrailSprite3D.SHADERDEFINE_GRADIENTMODE_BLEND); } }); /** *设置纹理模式。 *@param value 纹理模式。 */ /** *获取纹理模式。 *@return 纹理模式。 */ __getset(0,__proto,'textureMode',function(){ return this._textureMode; },function(value){ this._textureMode=value; }); return TrailFilter; })(GeometryFilter) /** *... *@author ... */ //class laya.d3.core.trail.TrailRenderer extends laya.d3.core.render.BaseRender var TrailRenderer=(function(_super){ function TrailRenderer(owner){ TrailRenderer.__super.call(this,owner); } __class(TrailRenderer,'laya.d3.core.trail.TrailRenderer',_super); var __proto=TrailRenderer.prototype; __proto._calculateBoundingBox=function(){ var minE=this._boundingBox.min.elements; minE[0]=-Number.MAX_VALUE; minE[1]=-Number.MAX_VALUE; minE[2]=-Number.MAX_VALUE; var maxE=this._boundingBox.min.elements; maxE[0]=Number.MAX_VALUE; maxE[1]=Number.MAX_VALUE; maxE[2]=Number.MAX_VALUE; } __proto._calculateBoundingSphere=function(){ var centerE=this._boundingSphere.center.elements; centerE[0]=0; centerE[1]=0; centerE[2]=0; this._boundingSphere.radius=Number.MAX_VALUE; } __proto._renderUpdate=function(projectionView){ return true; } return TrailRenderer; })(BaseRender) /** *... *@author */ //class laya.d3.extension.domino.DominoFilter extends laya.d3.core.GeometryFilter var DominoFilter=(function(_super){ function DominoFilter(owner){ this._owner=null; this.dominoCount=0; this.DominoRenderElementMaxDominoCount=2000; this._dominoRenderElements=null; DominoFilter.__super.call(this); this.dominoPosition=[]; this._owner=owner; this.initPositionsAndNormal(); this._dominoRenderElements=[]; this.addDominoRenderElement(); } __class(DominoFilter,'laya.d3.extension.domino.DominoFilter',_super); var __proto=DominoFilter.prototype; __proto.addDomino=function(position,rotation,scale){ (position===void 0)&& (position=Vector3.ZERO); (rotation===void 0)&& (rotation=Quaternion.DEFAULT); (scale===void 0)&& (scale=Vector3.ZERO); var curDominoRenderElement=this._dominoRenderElements[this._dominoRenderElements.length-1]; if (curDominoRenderElement._curDominoCount >=this.DominoRenderElementMaxDominoCount){ var index=this.addDominoRenderElement(); this.event(/*laya.events.Event.DOMINO_FILTER_CHANGE*/"dominofilterchange",[index,this._dominoRenderElements[index]]); } curDominoRenderElement=this._dominoRenderElements[this._dominoRenderElements.length-1]; curDominoRenderElement.addDomino(position,rotation,scale); } __proto.updateDomino=function(index,position,rotation,scale){ (position===void 0)&& (position=Vector3.ZERO); (rotation===void 0)&& (rotation=Quaternion.DEFAULT); (scale===void 0)&& (scale=Vector3.ZERO); var needUpdateDominoRenderElementId=Math.floor(index / this.DominoRenderElementMaxDominoCount); var needUpdateDominoRenderElementIndex=index % this.DominoRenderElementMaxDominoCount; var needUpdateDominoRenderElement=this._dominoRenderElements[needUpdateDominoRenderElementId]; needUpdateDominoRenderElement.updateDomino(needUpdateDominoRenderElementIndex,position,rotation,scale); } __proto.updateDominos=function(startIndex,count,keyFrames){ var endIndex=startIndex+count-1; var startNeedUpdateDominoRenderElementId=Math.floor(startIndex / this.DominoRenderElementMaxDominoCount); var endNeedUpdateDominoRenderElementId=Math.floor(endIndex / this.DominoRenderElementMaxDominoCount); var startNeedUpdateDominoRenderElementIndex=startIndex % this.DominoRenderElementMaxDominoCount; var endNeedUpdateDominoRenderElementIndex=endIndex % this.DominoRenderElementMaxDominoCount; var needUpdateDominoRenderElementCount=endNeedUpdateDominoRenderElementId-startNeedUpdateDominoRenderElementId+1; var needUpdateDominoRenderElement; if (needUpdateDominoRenderElementCount <=1){ needUpdateDominoRenderElement=this._dominoRenderElements[startNeedUpdateDominoRenderElementId]; needUpdateDominoRenderElement.updateDominos(startNeedUpdateDominoRenderElementIndex,count,keyFrames); return; }; var keyFrameDatas; var curStartIndex=0,curCount=0,curSliceIndex=0; for (var i=0;i < needUpdateDominoRenderElementCount;i++){ needUpdateDominoRenderElement=this._dominoRenderElements[startNeedUpdateDominoRenderElementId+i]; if (i==0){ curStartIndex=startNeedUpdateDominoRenderElementIndex; curCount=this.DominoRenderElementMaxDominoCount-curStartIndex; keyFrameDatas=keyFrames.slice(0,curCount); curSliceIndex+=curCount; }else if (i==needUpdateDominoRenderElementCount-1){ curStartIndex=0; curCount=endNeedUpdateDominoRenderElementIndex+1; keyFrameDatas=keyFrames.slice(curSliceIndex,keyFrames.length); }else { curStartIndex=0; curCount=this.DominoRenderElementMaxDominoCount; keyFrameDatas=keyFrames.slice(curSliceIndex,curSliceIndex+this.DominoRenderElementMaxDominoCount); curSliceIndex+=this.DominoRenderElementMaxDominoCount; } needUpdateDominoRenderElement.updateDominos(curStartIndex,curCount,keyFrameDatas); } } __proto.addDominoRenderElement=function(){ var _dominoRenderElement=new DominoRenderElement(this); this._dominoRenderElements.push(_dominoRenderElement); return this._dominoRenderElements.length-1; } __proto.getDominoRenderElementsCount=function(){ return this._dominoRenderElements.length; } __proto.getRenderElement=function(index){ return this._dominoRenderElements[index]; } __proto._update=function(state){} __proto.initPositionsAndNormal=function(){ if (DominoFilter._positions.length !=0 && DominoFilter._normals.length !=0){ return; } DominoFilter._positions.push(new Vector3(-0.5,0.5,-0.5)); DominoFilter._positions.push(new Vector3(0.5,0.5,-0.5)); DominoFilter._positions.push(new Vector3(0.5,0.5,0.5)); DominoFilter._positions.push(new Vector3(-0.5,0.5,0.5)); DominoFilter._positions.push(new Vector3(-0.5,-0.5,-0.5)); DominoFilter._positions.push(new Vector3(0.5,-0.5,-0.5)); DominoFilter._positions.push(new Vector3(0.5,-0.5,0.5)); DominoFilter._positions.push(new Vector3(-0.5,-0.5,0.5)); DominoFilter._positions.push(new Vector3(-0.5,0.5,-0.5)); DominoFilter._positions.push(new Vector3(-0.5,0.5,0.5)); DominoFilter._positions.push(new Vector3(-0.5,-0.5,0.5)); DominoFilter._positions.push(new Vector3(-0.5,-0.5,-0.5)); DominoFilter._positions.push(new Vector3(0.5,0.5,-0.5)); DominoFilter._positions.push(new Vector3(0.5,0.5,0.5)); DominoFilter._positions.push(new Vector3(0.5,-0.5,0.5)); DominoFilter._positions.push(new Vector3(0.5,-0.5,-0.5)); DominoFilter._positions.push(new Vector3(-0.5,0.5,0.5)); DominoFilter._positions.push(new Vector3(0.5,0.5,0.5)); DominoFilter._positions.push(new Vector3(0.5,-0.5,0.5)); DominoFilter._positions.push(new Vector3(-0.5,-0.5,0.5)); DominoFilter._positions.push(new Vector3(-0.5,0.5,-0.5)); DominoFilter._positions.push(new Vector3(0.5,0.5,-0.5)); DominoFilter._positions.push(new Vector3(0.5,-0.5,-0.5)); DominoFilter._positions.push(new Vector3(-0.5,-0.5,-0.5)); DominoFilter._normals.push(new Vector3(0,1,0)); DominoFilter._normals.push(new Vector3(0,1,0)); DominoFilter._normals.push(new Vector3(0,1,0)); DominoFilter._normals.push(new Vector3(0,1,0)); DominoFilter._normals.push(new Vector3(0,-1,0)); DominoFilter._normals.push(new Vector3(0,-1,0)); DominoFilter._normals.push(new Vector3(0,-1,0)); DominoFilter._normals.push(new Vector3(0,-1,0)); DominoFilter._normals.push(new Vector3(-1,0,0)); DominoFilter._normals.push(new Vector3(-1,0,0)); DominoFilter._normals.push(new Vector3(-1,0,0)); DominoFilter._normals.push(new Vector3(-1,0,0)); DominoFilter._normals.push(new Vector3(1,0,0)); DominoFilter._normals.push(new Vector3(1,0,0)); DominoFilter._normals.push(new Vector3(1,0,0)); DominoFilter._normals.push(new Vector3(1,0,0)); DominoFilter._normals.push(new Vector3(0,0,1)); DominoFilter._normals.push(new Vector3(0,0,1)); DominoFilter._normals.push(new Vector3(0,0,1)); DominoFilter._normals.push(new Vector3(0,0,1)); DominoFilter._normals.push(new Vector3(0,0,-1)); DominoFilter._normals.push(new Vector3(0,0,-1)); DominoFilter._normals.push(new Vector3(0,0,-1)); DominoFilter._normals.push(new Vector3(0,0,-1)); } DominoFilter._positions=[]; DominoFilter._normals=[]; return DominoFilter; })(GeometryFilter) /** *... *@author */ //class laya.d3.extension.lineRender.LineFilter extends laya.d3.core.GeometryFilter var LineFilter=(function(_super){ function LineFilter(owner){ this._owner=null; this._camera=null; this._useWorldSpace=false; this._widthMultiplier=0.02; this._widthCurve=null; this._colorGradient=null; this._textureMode=0; this._curFixedNum=0; this._vertexBuffers=null; this._maxVertexCount=512; this._vertexCount=0; this._vertices1=null; this._vertexBuffer1=null; this._verticesIndex1=0; this._everyAddVerticeCount1=0; this._floatCountPerVertices1=4; this._vertices2=null; this._vertexBuffer2=null; this._verticesIndex2=0; this._everyAddVerticeCount2=0; this._floatCountPerVertices2=3; this._vertices3=null; this._vertexBuffer3=null; this._verticesIndex3=0; this._everyAddVerticeCount3=0; this._floatCountPerVertices3=2; this._delLength=0; this._pointe=null; this._pointAtoBVector3e=null; this._everyToFirstDistance=null; this._curTotalLength=0; LineFilter.__super.call(this); this._positions=[]; this._normals=[]; this._firstPosition=new Vector3(); this._delVector3=new Vector3(); this._lastPosition=new Vector3(); this._pointAtoBVector3=new Vector3(); this._cameraToPointV3=new Vector3(); this._curDirection=new Vector3(); this._lastDirection=new Vector3(); this._fixedDirection=new Vector3(); this._owner=owner; this._initData(); this._vertices1=new Float32Array(this._maxVertexCount *this._floatCountPerVertices1); this._vertices2=new Float32Array(this._maxVertexCount *this._floatCountPerVertices2); this._vertices3=new Float32Array(this._maxVertexCount *this._floatCountPerVertices3); this._vertexBuffer1=new VertexBuffer3D(LineVertex.vertexDeclaration1,this._maxVertexCount,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._vertexBuffer2=new VertexBuffer3D(LineVertex.vertexDeclaration2,this._maxVertexCount,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._vertexBuffer3=new VertexBuffer3D(LineVertex.vertexDeclaration3,this._maxVertexCount,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._vertexBuffers=[]; this._vertexBuffers.push(this._vertexBuffer1); this._vertexBuffers.push(this._vertexBuffer2); this._vertexBuffers.push(this._vertexBuffer3); this._everyToFirstDistance=new Float32Array(this._maxVertexCount / 2); } __class(LineFilter,'laya.d3.extension.lineRender.LineFilter',_super); var __proto=LineFilter.prototype; Laya.imps(__proto,{"laya.d3.core.render.IRenderable":true}) __proto.addPosition=function(position,normal){ var v30=new Vector3(); position.cloneTo(v30); this._positions.push(v30); var v31=new Vector3(); normal.cloneTo(v31); this._normals.push(v31); this._updateVertexBuffer1(v30); this._vertexCount+=2; } __proto._updateVertexBuffer1=function(position){ this._everyAddVerticeCount1=0; this._pointe=position.elements; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._pointe[0]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._pointe[1]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._pointe[2]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=1.0; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._pointe[0]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._pointe[1]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=this._pointe[2]; this._vertices1[this._verticesIndex1+this._everyAddVerticeCount1++]=0.0; this._vertexBuffer1.setData(this._vertices1,this._verticesIndex1,this._verticesIndex1,this._everyAddVerticeCount1); this._verticesIndex1+=this._everyAddVerticeCount1; } __proto._updateVertexBuffer2=function(){ this._verticesIndex2=0; for (var i=this._curFixedNum;i < this._positions.length;i++){ if (i==0){ Vector3.subtract(this._positions[1],this._positions[0],this._delVector3); Vector3.cross(this._delVector3,this._normals[0],this._pointAtoBVector3); Vector3.normalize(this._pointAtoBVector3,this._pointAtoBVector3); Vector3.scale(this._pointAtoBVector3,this._widthMultiplier / 2,this._pointAtoBVector3); this._everyToFirstDistance[i]=0; this._updateVertices2(this._positions[0],0); } else{ Vector3.subtract(this._positions[i],this._positions[i-1],this._delVector3); Vector3.cross(this._delVector3,this._normals[i],this._pointAtoBVector3); Vector3.normalize(this._pointAtoBVector3,this._pointAtoBVector3); Vector3.scale(this._pointAtoBVector3,this._widthMultiplier / 2,this._pointAtoBVector3); this._delLength=Vector3.scalarLength(this._delVector3); this._curTotalLength=this._everyToFirstDistance[i]=this._curTotalLength+this._delLength; this._updateVertices2(this._positions[i],i); } this._curFixedNum=i+1; } this._vertexBuffer2.setData(this._vertices2,0,0,this._verticesIndex2); } __proto._updateVertexBuffer3=function(){ var _uvIndex=0; var _uvX=0.0; var _uvX1=0.0; var i=0,j=0; for (i=0,j=this._vertexCount / 2;i < j;i++){ _uvX=this._everyToFirstDistance[i] / this._curTotalLength; _uvX1=this._everyToFirstDistance[i]; this._vertices3[_uvIndex++]=_uvX; this._vertices3[_uvIndex++]=_uvX1; this._vertices3[_uvIndex++]=_uvX; this._vertices3[_uvIndex++]=_uvX1; } this._vertexBuffer3.setData(this._vertices3,0,0,this._vertexCount *2); } __proto._beforeRender=function(state){ if (this._camera==null){ this._camera=state.camera; return false; } if (this._vertexCount > 0){ this._updateVertexBuffer2(); this._updateVertexBuffer3(); return true; } return false; } __proto._render=function(state){ WebGL.mainContext.drawArrays(/*laya.webgl.WebGLContext.TRIANGLE_STRIP*/0x0005,0,this._vertexCount); Stat.drawCall++; } __proto._updateVertices2=function(position,index){ this._everyAddVerticeCount2=0; this._pointAtoBVector3e=this._pointAtoBVector3.elements; this._vertices2[this._verticesIndex2+this._everyAddVerticeCount2++]=this._pointAtoBVector3e[0]; this._vertices2[this._verticesIndex2+this._everyAddVerticeCount2++]=this._pointAtoBVector3e[1]; this._vertices2[this._verticesIndex2+this._everyAddVerticeCount2++]=this._pointAtoBVector3e[2]; this._vertices2[this._verticesIndex2+this._everyAddVerticeCount2++]=-this._pointAtoBVector3e[0]; this._vertices2[this._verticesIndex2+this._everyAddVerticeCount2++]=-this._pointAtoBVector3e[1]; this._vertices2[this._verticesIndex2+this._everyAddVerticeCount2++]=-this._pointAtoBVector3e[2]; this._verticesIndex2+=this._everyAddVerticeCount2; } __proto._initData=function(){ this.useWorldSpace=true; this.widthMultiplier=0.02; this.textureMode=0; var widthKeyFrames=[]; var widthKeyFrame1=new TrailKeyFrame(); widthKeyFrame1.time=0; widthKeyFrame1.inTangent=0; widthKeyFrame1.outTangent=0; widthKeyFrame1.value=1; widthKeyFrames.push(widthKeyFrame1); var widthKeyFrame2=new TrailKeyFrame(); widthKeyFrame2.time=1; widthKeyFrame2.inTangent=0; widthKeyFrame2.outTangent=0; widthKeyFrame2.value=1; widthKeyFrames.push(widthKeyFrame2); this.widthCurve=widthKeyFrames; var gradient=new Gradient(); gradient.mode=/*laya.d3.core.trail.module.GradientMode.Blend*/0; var colorKeys=[]; var colorKey1=new GradientColorKey(); colorKey1.time=0; colorKey1.color=Color$1.WHITE; colorKeys.push(colorKey1); var colorKey2=new GradientColorKey(); colorKey2.time=1; colorKey2.color=Color$1.WHITE; colorKeys.push(colorKey2); var alphaKeys=[]; var alphaKey1=new GradientAlphaKey(); alphaKey1.time=0; alphaKey1.alpha=1; alphaKeys.push(alphaKey1); var alphaKey2=new GradientAlphaKey(); alphaKey2.time=1; alphaKey2.alpha=1; alphaKeys.push(alphaKey2); gradient.setKeys(colorKeys,alphaKeys); this.colorGradient=gradient; } __proto._update=function(state){} __proto._getVertexBuffer=function(index){ (index===void 0)&& (index=0); if (index===0) return this._vertexBuffer1; else return null; } __proto._getVertexBuffers=function(){ return this._vertexBuffers; } __proto._getIndexBuffer=function(){ return null; } /** *@private */ __proto._destroy=function(){ _super.prototype._destroy.call(this); this._vertexBuffer1.destroy(); this._vertexBuffer2.destroy(); this._vertexBuffer3.destroy(); this._vertexBuffers=null; this._vertices1=null; this._vertices2=null; this._vertices3=null; this._owner=null; this._camera=null; this._widthCurve=null; this._colorGradient=null; this._positions=null; this._normals=null; this._firstPosition=null; this._delVector3=null; this._lastPosition=null; this._pointAtoBVector3=null; this._cameraToPointV3=null; this._delVector3=null; this._pointe=null; this._pointAtoBVector3e=null; this._curDirection=null; this._lastDirection=null; this._fixedDirection=null; this._everyToFirstDistance=null; } /** *设置宽度曲线。 *@param value 宽度曲线。 */ /** *获取宽度曲线。 *@return 宽度曲线。 */ __getset(0,__proto,'widthCurve',function(){ return this._widthCurve; },function(value){ this._widthCurve=value; var widthCurveFloatArray=new Float32Array(value.length *4); var i=0,j=0,index=0; for (i=0,j=value.length;i < j;i++){ widthCurveFloatArray[index++]=value[i].time; widthCurveFloatArray[index++]=value[i].inTangent; widthCurveFloatArray[index++]=value[i].outTangent; widthCurveFloatArray[index++]=value[i].value; } this._owner._render._setShaderValueBuffer(/*laya.d3.extension.lineRender.LineSprite3D.WIDTHCURVE*/3,widthCurveFloatArray); this._owner._render._setShaderValueInt(/*laya.d3.extension.lineRender.LineSprite3D.WIDTHCURVEKEYLENGTH*/4,value.length); }); /** *设置是否世界空间。 *@param value 是否世界空间。 */ /** *获取是否世界空间。 *@return 是否世界空间。 */ __getset(0,__proto,'useWorldSpace',function(){ return this._useWorldSpace; },function(value){ this._useWorldSpace=value; if (value){ this._owner._render._addShaderDefine(LineSprite3D.SHADERDEFINE_WORLDSPACE); } else{ this._owner._render._removeShaderDefine(LineSprite3D.SHADERDEFINE_WORLDSPACE); } }); __getset(0,__proto,'triangleCount',function(){ return 0; }); /** *设置宽度倍数。 *@param value 宽度倍数。 */ /** *获取宽度倍数。 *@return 宽度倍数。 */ __getset(0,__proto,'widthMultiplier',function(){ return this._widthMultiplier; },function(value){ this._widthMultiplier=value; }); /** *设置颜色梯度。 *@param value 颜色梯度。 */ /** *获取颜色梯度。 *@return 颜色梯度。 */ __getset(0,__proto,'colorGradient',function(){ return this._colorGradient; },function(value){ this._colorGradient=value; this._owner._render._setShaderValueBuffer(/*laya.d3.extension.lineRender.LineSprite3D.GRADIENTCOLORKEY*/5,value._colorKeyData); this._owner._render._setShaderValueBuffer(/*laya.d3.extension.lineRender.LineSprite3D.GRADIENTALPHAKEY*/6,value._alphaKeyData); if (value.mode==/*laya.d3.core.trail.module.GradientMode.Blend*/0){ this._owner._render._addShaderDefine(LineSprite3D.SHADERDEFINE_GRADIENTMODE_BLEND); } else{ this._owner._render._removeShaderDefine(LineSprite3D.SHADERDEFINE_GRADIENTMODE_BLEND); } }); /** *设置纹理模式。 *@param value 纹理模式。 */ /** *获取纹理模式。 *@return 纹理模式。 */ __getset(0,__proto,'textureMode',function(){ return this._textureMode; },function(value){ this._textureMode=value; if (value==/*laya.d3.core.trail.module.TextureMode.Stretch*/0){ this._owner._render._addShaderDefine(LineSprite3D.SHADERDEFINE_TEXTUREMODE_STRETCH); } else{ this._owner._render._removeShaderDefine(LineSprite3D.SHADERDEFINE_TEXTUREMODE_STRETCH); } }); __getset(0,__proto,'_vertexBufferCount',function(){ return this._vertexBuffers.length; }); return LineFilter; })(GeometryFilter) /** *... *@author */ //class laya.d3.extension.domino.DominoRenderer extends laya.d3.core.render.BaseRender var DominoRenderer=(function(_super){ function DominoRenderer(owner){ DominoRenderer.__super.call(this,owner); } __class(DominoRenderer,'laya.d3.extension.domino.DominoRenderer',_super); var __proto=DominoRenderer.prototype; __proto._calculateBoundingBox=function(){ var minE=this._boundingBox.min.elements; minE[0]=-Number.MAX_VALUE; minE[1]=-Number.MAX_VALUE; minE[2]=-Number.MAX_VALUE; var maxE=this._boundingBox.min.elements; maxE[0]=Number.MAX_VALUE; maxE[1]=Number.MAX_VALUE; maxE[2]=Number.MAX_VALUE; } __proto._calculateBoundingSphere=function(){ var centerE=this._boundingSphere.center.elements; centerE[0]=0; centerE[1]=0; centerE[2]=0; this._boundingSphere.radius=Number.MAX_VALUE; } __proto._renderUpdate=function(projectionView){ var transform=this._owner.transform; if (transform){ this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.WORLDMATRIX*/0,transform.worldMatrix); var projViewWorld=this._owner.getProjectionViewWorldMatrix(projectionView); this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.MVPMATRIX*/1,projViewWorld); }else { this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.WORLDMATRIX*/0,Matrix4x4.DEFAULT); this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.MVPMATRIX*/1,projectionView); } return true; } return DominoRenderer; })(BaseRender) /** *... *@author */ //class laya.d3.extension.lineRender.LineRenderer extends laya.d3.core.render.BaseRender var LineRenderer=(function(_super){ function LineRenderer(owner){ LineRenderer.__super.call(this,owner); } __class(LineRenderer,'laya.d3.extension.lineRender.LineRenderer',_super); var __proto=LineRenderer.prototype; __proto._calculateBoundingBox=function(){ var minE=this._boundingBox.min.elements; minE[0]=-Number.MAX_VALUE; minE[1]=-Number.MAX_VALUE; minE[2]=-Number.MAX_VALUE; var maxE=this._boundingBox.min.elements; maxE[0]=Number.MAX_VALUE; maxE[1]=Number.MAX_VALUE; maxE[2]=Number.MAX_VALUE; } __proto._calculateBoundingSphere=function(){ var centerE=this._boundingSphere.center.elements; centerE[0]=0; centerE[1]=0; centerE[2]=0; this._boundingSphere.radius=Number.MAX_VALUE; } __proto._renderUpdate=function(projectionView){ var transform=this._owner.transform; if (transform){ this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.WORLDMATRIX*/0,transform.worldMatrix); var projViewWorld=this._owner.getProjectionViewWorldMatrix(projectionView); this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.MVPMATRIX*/1,projViewWorld); }else { this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.WORLDMATRIX*/0,Matrix4x4.DEFAULT); this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.MVPMATRIX*/1,projectionView); } return true; } return LineRenderer; })(BaseRender) /** *@private *GlitterTemplet 类用于创建闪光数据模板。 */ //class laya.d3.resource.tempelet.GlitterTemplet extends laya.d3.core.GeometryFilter var GlitterTemplet=(function(_super){ function GlitterTemplet(owner){ this._floatCountPerVertex=6; //顶点结构为Position(3个float)+UV(2个float)+Time(1个float) this._owner=null; this._vertices=null; this._vertexBuffer=null; this._firstActiveElement=0; this._firstNewElement=0; this._firstFreeElement=0; this._firstRetiredElement=0; this._currentTime=NaN; this._drawCounter=0; this.scLeft=null; this.scRight=null; this._numPositionMode=0; this._numPositionVelocityMode=0; this._lastTime=NaN; this._needPatch=false; this._lastPatchAddPos0=null; this._lastPatchAddPos1=null; this._lastPatchAddTime=NaN; /**声明周期。 */ this.lifeTime=NaN; /**最小分段距离。 */ this.minSegmentDistance=NaN; /**最小插值距离。 */ this.minInterpDistance=NaN; /**最大插值数量。 */ this.maxSlerpCount=0; /**最大段数。 */ this._maxSegments=0; GlitterTemplet.__super.call(this); this._tempVector0=new Vector3(); this._tempVector1=new Vector3(); this._tempVector2=new Vector3(); this._tempVector3=new Vector3(); this._posModeLastPosition0=new Vector3(); this._posModeLastPosition1=new Vector3(); this._posModePosition0=new Vector3(); this._posModePosition1=new Vector3(); this._posVelModePosition0=new Vector3(); this._posVelModeVelocity0=new Vector3(); this._posVelModePosition1=new Vector3(); this._posVelModeVelocity1=new Vector3(); this._owner=owner; this._lastTime=0 this._firstActiveElement=0; this._firstNewElement=0; this._firstFreeElement=0; this._firstRetiredElement=0; this._currentTime=0; this._drawCounter=0; this._needPatch=false; this._lastPatchAddPos0=new Vector3(); this._lastPatchAddPos1=new Vector3(); this.scLeft=new SplineCurvePositionVelocity(); this.scRight=new SplineCurvePositionVelocity(); this.lifeTime=0.5; this.minSegmentDistance=0.1; this.minInterpDistance=0.6; this.maxSlerpCount=128; this._maxSegments=200; this._owner.on(/*laya.events.Event.ACTIVE_IN_HIERARCHY_CHANGED*/"activeinhierarchychanged",this,this._onActiveHierarchyChanged); } __class(GlitterTemplet,'laya.d3.resource.tempelet.GlitterTemplet',_super); var __proto=GlitterTemplet.prototype; Laya.imps(__proto,{"laya.d3.core.render.IRenderable":true}) __proto._getVertexBuffer=function(index){ (index===void 0)&& (index=0); if (index===0) return this._vertexBuffer; else return null; } __proto._getIndexBuffer=function(){ return null; } /** *@private */ __proto._initialize=function(){ this._vertexBuffer=VertexBuffer3D.create(VertexGlitter.vertexDeclaration,this.maxSegments *2,/*laya.webgl.WebGLContext.DYNAMIC_DRAW*/0x88E8); this._vertices=new Float32Array(this.maxSegments *this._floatCountPerVertex *2); } __proto._onActiveHierarchyChanged=function(active){ if (!active){ this._numPositionMode=0; this._numPositionVelocityMode=0; this._firstActiveElement=0; this._firstNewElement=0; this._firstFreeElement=0; this._firstRetiredElement=0; this._currentTime=0; this._drawCounter=0; } } /** *@private */ __proto._updateTextureCoordinates=function(){ if (this._firstActiveElement < this._firstFreeElement){ this._updateSubTextureCoordinates(this._firstActiveElement,(this._firstFreeElement-this._firstActiveElement)*2); }else { this._updateSubTextureCoordinates(this._firstActiveElement,(this.maxSegments-this._firstActiveElement)*2); if (this._firstFreeElement > 0) this._updateSubTextureCoordinates(0,this._firstFreeElement *2); } } /** *@private */ __proto._updateSubTextureCoordinates=function(start,count){ var startOffset=start *2; for (var i=0;i < count;i+=2){ var vertexOffset=startOffset+i; var upVertexOffset=vertexOffset *this._floatCountPerVertex; var downVertexOffset=(vertexOffset+1)*this._floatCountPerVertex; this._vertices[upVertexOffset+3]=this._vertices[downVertexOffset+3]=(this._vertices[upVertexOffset+5]-this._currentTime)/ this.lifeTime; } } /** *@private */ __proto._retireActiveGlitter=function(){ var particleDuration=this.lifeTime; var _floatCountOneSegement=this._floatCountPerVertex *2; while (this._firstActiveElement !=this._firstNewElement){ var index=this._firstActiveElement *_floatCountOneSegement+5; var particleAge=this._currentTime-this._vertices[index]; if (particleAge < particleDuration) break ; this._vertices[index]=this._drawCounter; this._firstActiveElement++; if (this._firstActiveElement >=this.maxSegments) this._firstActiveElement=0; } } /** *@private */ __proto._freeRetiredGlitter=function(){ var _floatCountOneSegement=this._floatCountPerVertex *2; while (this._firstRetiredElement !=this._firstActiveElement){ var age=this._drawCounter-this._vertices[this._firstRetiredElement *_floatCountOneSegement+5]; if (age < 3) break ; this._firstRetiredElement++; if (this._firstRetiredElement >=this.maxSegments) this._firstRetiredElement=0; } } /** *@private */ __proto._calcVelocity=function(left,right,out){ Vector3.subtract(left,right,out); Vector3.scale(out,0.5,out); } /** *@private */ __proto._addNewGlitterSegementToVertexBuffer=function(){ var start=0; if (this._firstActiveElement < this._firstFreeElement){ start=this._firstActiveElement *2 *this._floatCountPerVertex; this._vertexBuffer.setData(this._vertices,start,start,(this._firstFreeElement-this._firstActiveElement)*2 *this._floatCountPerVertex); }else { start=this._firstActiveElement *2 *this._floatCountPerVertex; this._vertexBuffer.setData(this._vertices,start,start,(this.maxSegments-this._firstActiveElement)*2 *this._floatCountPerVertex); if (this._firstFreeElement > 0){ this._vertexBuffer.setData(this._vertices,0,0,this._firstFreeElement *2 *this._floatCountPerVertex); } } this._firstNewElement=this._firstFreeElement; } /** *@private */ __proto._addGlitter=function(position0,position1,time){ if (this._needPatch){ this._needPatch=false; this._addGlitter(this._lastPatchAddPos0,this._lastPatchAddPos1,this._lastPatchAddTime); }; var nextFreeParticle=this._firstFreeElement+1; if (nextFreeParticle >=this.maxSegments){ nextFreeParticle=0; position0.cloneTo(this._lastPatchAddPos0); position1.cloneTo(this._lastPatchAddPos1); this._lastPatchAddTime=time; this._needPatch=true; } if (nextFreeParticle===this._firstRetiredElement) console.log("GlitterTemplet:current segement count have large than maxSegments,please adjust the value of maxSegments or add Glitter Vertex Frequency."); var position0e=position0.elements; var position1e=position1.elements; var j=0; var positionIndex=this._firstFreeElement *this._floatCountPerVertex *2; for (j=0;j < 3;j++) this._vertices[positionIndex+j]=position0e[j]; this._vertices[positionIndex+3]=0.0; this._vertices[positionIndex+4]=0.0; this._vertices[positionIndex+5]=time; var nextPositionIndex=positionIndex+this._floatCountPerVertex; for (j=0;j < 3;j++) this._vertices[nextPositionIndex+j]=position1e[j]; this._vertices[nextPositionIndex+3]=0.0; this._vertices[nextPositionIndex+4]=1.0; this._vertices[nextPositionIndex+5]=time; this._firstFreeElement=nextFreeParticle; } /** *@private *更新闪光。 *@param elapsedTime 间隔时间 */ __proto._update=function(elapsedTime){ this._currentTime+=elapsedTime / 1000; this._retireActiveGlitter(); this._freeRetiredGlitter(); if (this._firstActiveElement==this._firstFreeElement) this._currentTime=0; if (this._firstRetiredElement==this._firstActiveElement) this._drawCounter=0; this._updateTextureCoordinates(); } //实时更新纹理坐标 __proto._beforeRender=function(state){ if (this._firstNewElement !=this._firstFreeElement){ this._addNewGlitterSegementToVertexBuffer(); } this._drawCounter++; if (this._firstActiveElement !=this._firstFreeElement){ this._vertexBuffer.bindWithIndexBuffer(null); return true; } return false; } /** *@private *渲染闪光。 *@param state 相关渲染状态 */ __proto._render=function(state){ var drawVertexCount=0; var glContext=WebGL.mainContext; if (this._firstActiveElement < this._firstFreeElement){ drawVertexCount=(this._firstFreeElement-this._firstActiveElement)*2; glContext.drawArrays(/*laya.webgl.WebGLContext.TRIANGLE_STRIP*/0x0005,this._firstActiveElement *2,drawVertexCount); Stat.trianglesFaces+=drawVertexCount-2; Stat.drawCall++; }else { drawVertexCount=(this.maxSegments-this._firstActiveElement)*2; glContext.drawArrays(/*laya.webgl.WebGLContext.TRIANGLE_STRIP*/0x0005,this._firstActiveElement *2,drawVertexCount); Stat.trianglesFaces+=drawVertexCount-2; Stat.drawCall++; if (this._firstFreeElement > 0){ drawVertexCount=this._firstFreeElement *2; glContext.drawArrays(/*laya.webgl.WebGLContext.TRIANGLE_STRIP*/0x0005,0,drawVertexCount); Stat.trianglesFaces+=drawVertexCount-2; Stat.drawCall++; } } } /** *通过位置添加刀光。 *@param position0 位置0。 *@param position1 位置1。 */ __proto.addVertexPosition=function(position0,position1){ if (this._owner.activeInHierarchy){ if (this._numPositionMode < 2){ if (this._numPositionMode===0){ position0.cloneTo(this._posModeLastPosition0); position1.cloneTo(this._posModeLastPosition1); }else { position0.cloneTo(this._posModePosition0); position1.cloneTo(this._posModePosition1); } this._numPositionMode++; }else { var v0=this._tempVector2; this._calcVelocity(position0,this._posModeLastPosition0,v0); var v1=this._tempVector3; this._calcVelocity(position1,this._posModeLastPosition1,v1); this.addVertexPositionVelocity(this._posModePosition0,v0,this._posModePosition1,v1); this._posModePosition0.cloneTo(this._posModeLastPosition0); this._posModePosition1.cloneTo(this._posModeLastPosition1); position0.cloneTo(this._posModePosition0); position1.cloneTo(this._posModePosition1); } } } /** *通过位置和速度添加刀光。 *@param position0 位置0。 *@param velocity0 速度0。 *@param position1 位置1。 *@param velocity1 速度1。 */ __proto.addVertexPositionVelocity=function(position0,velocity0,position1,velocity1){ if (this._owner.activeInHierarchy){ if (this._numPositionVelocityMode===0){ this._numPositionVelocityMode++; }else { var d=this._tempVector0; Vector3.subtract(position0,this._posVelModePosition0,d); var distance0=Vector3.scalarLength(d); Vector3.subtract(position1,this._posVelModePosition1,d); var distance1=Vector3.scalarLength(d); var slerpCount=0; var minSegmentDistance=minSegmentDistance; if (distance0 < minSegmentDistance && distance1 < minSegmentDistance) return; slerpCount=1+Math.floor(Math.max(distance0,distance1)/ this.minInterpDistance); if (slerpCount===1){ this._addGlitter(position0,position1,this._currentTime); }else { slerpCount=Math.min(slerpCount,this.maxSlerpCount); this.scLeft.Init(this._posVelModePosition0,this._posVelModeVelocity0,position0,velocity0); this.scRight.Init(this._posVelModePosition1,this._posVelModeVelocity1,position1,velocity1); var segment=1.0 / slerpCount; var addSegment=segment; var timeOffset=this._currentTime-this._lastTime; for (var i=1;i <=slerpCount;i++){ var pos0=this._tempVector0; this.scLeft.Slerp(addSegment,pos0); var pos1=this._tempVector1; this.scRight.Slerp(addSegment,pos1); var time=this._lastTime+timeOffset *i / slerpCount; this._addGlitter(pos0,pos1,time); addSegment+=segment; } } } this._lastTime=this._currentTime; position0.cloneTo(this._posVelModePosition0); velocity0.cloneTo(this._posVelModeVelocity0); position1.cloneTo(this._posVelModePosition1); velocity1.cloneTo(this._posVelModeVelocity1); } } __proto._destroy=function(){ _super.prototype._destroy.call(this); this._tempVector0=null; this._tempVector1=null; this._tempVector2=null; this._tempVector3=null; this._owner=null; this._vertices=null; this._vertexBuffer.destroy(); this._vertexBuffer=null; this.scLeft=null; this.scRight=null; this._posModeLastPosition0=null; this._posModeLastPosition1=null; this._posModePosition0=null; this._posModePosition1=null; this._posVelModePosition0=null; this._posVelModeVelocity0=null; this._posVelModePosition1=null; this._posVelModeVelocity1=null; this._lastPatchAddPos0=null; this._lastPatchAddPos1=null; } /** *@private */ __proto._getVertexBuffers=function(){ return null; } /**设置最大分段数,注意:谨慎修改此属性,有性能损耗。*/ /**获取最大分段数。*/ __getset(0,__proto,'maxSegments',function(){ return this._maxSegments-1; },function(value){ var newMaxSegments=value+1; if (newMaxSegments!==this._maxSegments){ this._maxSegments=newMaxSegments; if (this._vertexBuffer){ this._vertexBuffer.destroy(); } this._initialize(); } }); __getset(0,__proto,'_vertexBufferCount',function(){ return 1; }); __getset(0,__proto,'triangleCount',function(){ var drawVertexCount=0; if (this._firstActiveElement < this._firstFreeElement){ drawVertexCount=(this._firstFreeElement-this._firstActiveElement)*2-2; }else { drawVertexCount=(this.maxSegments-this._firstActiveElement)*2-2; drawVertexCount+=this._firstFreeElement *2-2; } return drawVertexCount; }); /** *@inheritDoc */ __getset(0,__proto,'_originalBoundingSphere',function(){ return Laya.superGet(GeometryFilter,this,'_originalBoundingSphere'); }); /** *@inheritDoc */ __getset(0,__proto,'_originalBoundingBox',function(){ return Laya.superGet(GeometryFilter,this,'_originalBoundingBox'); }); return GlitterTemplet; })(GeometryFilter) /** *TerrainFilter 类用于创建TerrainFilter过滤器。 */ //class laya.d3.terrain.TerrainFilter extends laya.d3.core.GeometryFilter var TerrainFilter=(function(_super){ function TerrainFilter(owner,chunkOffsetX,chunkOffsetZ,gridSize,terrainHeightData,heightDataWidth,heightDataHeight,cameraCoordinateInverse){ this._owner=null; this._gridSize=NaN; this.memorySize=0; this._numberVertices=0; this._maxNumberIndices=0; this._currentNumberIndices=0; this._numberTriangle=0; this._vertexBuffer=null; this._indexBuffer=null; this._boundingSphere=null; this._boundingBox=null; this._indexArrayBuffer=null; this._boundingBoxCorners=null; this._leafs=null; this._leafNum=0; this._terrainHeightData=null; this._terrainHeightDataWidth=0; this._terrainHeightDataHeight=0; this._chunkOffsetX=0; this._chunkOffsetZ=0; this._cameraCoordinateInverse=false; this._cameraPos=null; this._currentLOD=0; //LOD级别 4个叶子节点 第1个叶子的level<<24+第2个叶子的level<<16+第3个叶子的level<<8+第4个叶子的level this._perspectiveFactor=NaN; this._LODTolerance=0; TerrainFilter.__super.call(this); this._owner=owner; this._cameraPos=new Vector3(); this._chunkOffsetX=chunkOffsetX; this._chunkOffsetZ=chunkOffsetZ; this._gridSize=gridSize; this._terrainHeightData=terrainHeightData; this._terrainHeightDataWidth=heightDataWidth; this._terrainHeightDataHeight=heightDataHeight; this._leafNum=(TerrainLeaf.CHUNK_GRID_NUM / TerrainLeaf.LEAF_GRID_NUM)*(TerrainLeaf.CHUNK_GRID_NUM / TerrainLeaf.LEAF_GRID_NUM); this._leafs=__newvec(this._leafNum); this._cameraCoordinateInverse=cameraCoordinateInverse; for (var i=0;i < this._leafNum;i++){ this._leafs[i]=new TerrainLeaf(); } this.recreateResource(); } __class(TerrainFilter,'laya.d3.terrain.TerrainFilter',_super); var __proto=TerrainFilter.prototype; Laya.imps(__proto,{"laya.d3.core.render.IRenderable":true}) /** *@inheritDoc */ __proto._destroy=function(){ _super.prototype._destroy.call(this); this._owner=null; if (this._vertexBuffer)this._vertexBuffer.destroy(); if (this._indexBuffer)this._indexBuffer.destroy(); } __proto.recreateResource=function(){ this._currentNumberIndices=0; this._numberTriangle=0; var nLeafVertexCount=TerrainLeaf.LEAF_VERTEXT_COUNT; var nLeafIndexCount=TerrainLeaf.LEAF_MAX_INDEX_COUNT; this._numberVertices=nLeafVertexCount *this._leafNum; this._maxNumberIndices=nLeafIndexCount *this._leafNum; this._indexArrayBuffer=new Uint16Array(this._maxNumberIndices); var vertexDeclaration=VertexPositionTerrain.vertexDeclaration; var vertexFloatStride=vertexDeclaration.vertexStride / 4; var vertices=new Float32Array(this._numberVertices *vertexFloatStride); var nNum=TerrainLeaf.CHUNK_GRID_NUM / TerrainLeaf.LEAF_GRID_NUM; var i=0,x=0,z=0; for (i=0;i < this._leafNum;i++){ x=i % nNum; z=Math.floor(i / nNum); this._leafs[i].calcVertextBuffer(this._chunkOffsetX,this._chunkOffsetZ,x *TerrainLeaf.LEAF_GRID_NUM,z *TerrainLeaf.LEAF_GRID_NUM,this._gridSize,vertices,i *TerrainLeaf.LEAF_PLANE_VERTEXT_COUNT,vertexFloatStride,this._terrainHeightData,this._terrainHeightDataWidth,this._terrainHeightDataHeight,this._cameraCoordinateInverse); } for (i=0;i < this._leafNum;i++){ x=i % nNum; z=Math.floor(i / nNum); this._leafs[i].calcSkirtVertextBuffer(this._chunkOffsetX,this._chunkOffsetZ,x *TerrainLeaf.LEAF_GRID_NUM,z *TerrainLeaf.LEAF_GRID_NUM,this._gridSize,vertices,this._leafNum *TerrainLeaf.LEAF_PLANE_VERTEXT_COUNT+i *TerrainLeaf.LEAF_SKIRT_VERTEXT_COUNT,vertexFloatStride,this._terrainHeightData,this._terrainHeightDataWidth,this._terrainHeightDataHeight); } this.assembleIndexInit(); this._vertexBuffer=new VertexBuffer3D(vertexDeclaration,this._numberVertices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,false); this._indexBuffer=new IndexBuffer3D(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",this._maxNumberIndices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,false); this._vertexBuffer.setData(vertices); this._indexBuffer.setData(this._indexArrayBuffer); this.memorySize=(this._vertexBuffer._byteLength+this._indexBuffer._byteLength)*2; this.calcOriginalBoudingBoxAndSphere(); } __proto.setLODLevel=function(leafsLODLevel){ if (leafsLODLevel.length !=4)return true; var nLOD=((leafsLODLevel[0]+1)<< 24)+((leafsLODLevel[1]+1)<< 16)+((leafsLODLevel[2]+1)<< 8)+(leafsLODLevel[3]+1); if (this._currentLOD==nLOD){ return false; } this._currentLOD=nLOD; return true; } __proto.assembleIndexInit=function(){ this._currentNumberIndices=0; this._numberTriangle=0; var nOffsetIndex=0; for (var i=0;i < this._leafNum;i++){ var planeLODIndex=TerrainLeaf.getPlaneLODIndex(i,0); this._indexArrayBuffer.set(planeLODIndex,nOffsetIndex); nOffsetIndex+=planeLODIndex.length; var skirtLODIndex=TerrainLeaf.getSkirtLODIndex(i,0); this._indexArrayBuffer.set(skirtLODIndex,nOffsetIndex); nOffsetIndex+=skirtLODIndex.length; this._currentNumberIndices+=(planeLODIndex.length+skirtLODIndex.length); } this._numberTriangle=this._currentNumberIndices / 3; } __proto.isNeedAssemble=function(camera,cameraPostion){ var perspectiveFactor=Math.min(camera.viewport.width,camera.viewport.height)/ (2 *Math.tan(Math.PI *camera.fieldOfView / 180.0)); if (this._perspectiveFactor !=perspectiveFactor){ this._perspectiveFactor=perspectiveFactor; return 1; } if (this._LODTolerance !=Terrain.LOD_TOLERANCE_VALUE){ this._LODTolerance=Terrain.LOD_TOLERANCE_VALUE; return 1; } if (Vector3.equals(cameraPostion,this._cameraPos)==false){ this._cameraPos.x=cameraPostion.x; this._cameraPos.y=cameraPostion.y; this._cameraPos.z=cameraPostion.z; return 2; } return 0; } __proto.assembleIndex=function(camera,cameraPostion){ var nNeedType=this.isNeedAssemble(camera,cameraPostion); if (nNeedType > 0){ for (var i=0;i < this._leafNum;i++){ TerrainFilter._TEMP_ARRAY_BUFFER[i]=this._leafs[i].determineLod(cameraPostion,this._perspectiveFactor,Terrain.LOD_TOLERANCE_VALUE,nNeedType==1); } if (this.setLODLevel(TerrainFilter._TEMP_ARRAY_BUFFER)){ this._currentNumberIndices=0; this._numberTriangle=0; var nOffsetIndex=0; for (i=0;i < this._leafNum;i++){ var nLODLevel=TerrainFilter._TEMP_ARRAY_BUFFER[i]; var planeLODIndex=TerrainLeaf.getPlaneLODIndex(i,nLODLevel); this._indexArrayBuffer.set(planeLODIndex,nOffsetIndex); nOffsetIndex+=planeLODIndex.length; var skirtLODIndex=TerrainLeaf.getSkirtLODIndex(i,nLODLevel); this._indexArrayBuffer.set(skirtLODIndex,nOffsetIndex); nOffsetIndex+=skirtLODIndex.length; this._currentNumberIndices+=(planeLODIndex.length+skirtLODIndex.length); } this._numberTriangle=this._currentNumberIndices / 3; return true; } } return false; } __proto.calcOriginalBoudingBoxAndSphere=function(){ var sizeOfY=new Vector2(2147483647,-2147483647); for (var i=0;i < this._leafNum;i++){ sizeOfY.x=this._leafs[i]._sizeOfY.x < sizeOfY.x ? this._leafs[i]._sizeOfY.x :sizeOfY.x; sizeOfY.y=this._leafs[i]._sizeOfY.y > sizeOfY.y ? this._leafs[i]._sizeOfY.y :sizeOfY.y; }; var min=new Vector3(this._chunkOffsetX *TerrainLeaf.CHUNK_GRID_NUM *this._gridSize,sizeOfY.x,this._chunkOffsetZ *TerrainLeaf.CHUNK_GRID_NUM *this._gridSize); var max=new Vector3((this._chunkOffsetX+1)*TerrainLeaf.CHUNK_GRID_NUM *this._gridSize,sizeOfY.y,(this._chunkOffsetZ+1)*TerrainLeaf.CHUNK_GRID_NUM *this._gridSize); if (TerrainLeaf.__ADAPT_MATRIX__){ Vector3.transformV3ToV3(min,TerrainLeaf.__ADAPT_MATRIX__,min); Vector3.transformV3ToV3(max,TerrainLeaf.__ADAPT_MATRIX__,max); } this._boundingBox=new BoundBox(min,max); var size=new Vector3(); Vector3.subtract(max,min,size); Vector3.scale(size,0.5,size); var center=new Vector3(); Vector3.add(min,size,center); this._boundingSphere=new BoundSphere(center,Vector3.scalarLength(size)); this._boundingBoxCorners=__newvec(8,null); this._boundingBox.getCorners(this._boundingBoxCorners); } __proto.calcLeafBoudingBox=function(worldMatrix){ for (var i=0;i < this._leafNum;i++){ this._leafs[i].calcLeafBoudingBox(worldMatrix); } } __proto.calcLeafBoudingSphere=function(worldMatrix,maxScale){ for (var i=0;i < this._leafNum;i++){ this._leafs[i].calcLeafBoudingSphere(worldMatrix,maxScale); } } __proto._getVertexBuffer=function(index){ (index===void 0)&& (index=0); if (index==0){ return this._vertexBuffer; } return null; } __proto._getIndexBuffer=function(){ return this._indexBuffer; } __proto._beforeRender=function(state){ this._vertexBuffer._bind(); this._indexBuffer._bind(); var terrainMaterial=state.renderElement._material; if (terrainMaterial.blend==/*laya.d3.core.material.BaseMaterial.BLEND_DISABLE*/0){ var camera=state.camera; if (this.assembleIndex(camera,camera.position)){ this._indexBuffer.setData(this._indexArrayBuffer); } } return true; } /** *@private */ __proto._getVertexBuffers=function(){ return null; } __proto._render=function(state){ WebGL.mainContext.drawElements(Terrain.RENDER_LINE_MODEL ? /*laya.webgl.WebGLContext.LINES*/0x0001 :/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,this._currentNumberIndices,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,0); Stat.trianglesFaces+=this._numberTriangle; Stat.drawCall++; } /** *@inheritDoc */ __getset(0,__proto,'_originalBoundingSphere',function(){ return this._boundingSphere; }); /** *@inheritDoc */ __getset(0,__proto,'_originalBoundingBox',function(){ return this._boundingBox; }); __getset(0,__proto,'_vertexBufferCount',function(){ return this._numberVertices; }); __getset(0,__proto,'triangleCount',function(){ return this._numberTriangle; }); __static(TerrainFilter, ['_TEMP_ARRAY_BUFFER',function(){return this._TEMP_ARRAY_BUFFER=new Uint32Array(TerrainLeaf.CHUNK_GRID_NUM / TerrainLeaf.LEAF_GRID_NUM *TerrainLeaf.CHUNK_GRID_NUM / TerrainLeaf.LEAF_GRID_NUM);} ]); return TerrainFilter; })(GeometryFilter) /** *MeshRender 类用于网格渲染器。 */ //class laya.d3.terrain.TerrainRender extends laya.d3.core.render.BaseRender var TerrainRender=(function(_super){ function TerrainRender(owner){ /**@private */ this._terrainSprite3DOwner=null; TerrainRender.__super.call(this,owner); this._terrainSprite3DOwner=owner; } __class(TerrainRender,'laya.d3.terrain.TerrainRender',_super); var __proto=TerrainRender.prototype; __proto._calculateBoundingSphere=function(){ var terrainFilter=this._terrainSprite3DOwner.terrainFilter; if (terrainFilter==null){ this._boundingSphere.toDefault(); }else { var meshBoundingSphere=terrainFilter._originalBoundingSphere; var maxScale=NaN; var transform=this._terrainSprite3DOwner.transform; var scale=transform.scale; if (scale.x >=scale.y && scale.x >=scale.z) maxScale=scale.x; else maxScale=scale.y >=scale.z ? scale.y :scale.z; Vector3.transformCoordinate(meshBoundingSphere.center,transform.worldMatrix,this._boundingSphere.center); this._boundingSphere.radius=meshBoundingSphere.radius *maxScale; terrainFilter.calcLeafBoudingSphere(transform.worldMatrix,maxScale); } } __proto._calculateBoundingBox=function(){ var terrainFilter=this._terrainSprite3DOwner.terrainFilter; if (terrainFilter==null){ this._boundingBox.toDefault(); }else { var worldMat=this._terrainSprite3DOwner.transform.worldMatrix; var corners=terrainFilter._boundingBoxCorners; for (var i=0;i < 8;i++) Vector3.transformCoordinate(corners[i],worldMat,BaseRender._tempBoundBoxCorners[i]); BoundBox.createfromPoints(BaseRender._tempBoundBoxCorners,this._boundingBox); terrainFilter.calcLeafBoudingBox(worldMat); } } /** *@private */ __proto._renderUpdate=function(projectionView){ this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.WORLDMATRIX*/0,this._owner.transform.worldMatrix); var projViewWorld=this._owner.getProjectionViewWorldMatrix(projectionView); this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.MVPMATRIX*/1,projViewWorld); return true; } /** *@private */ __proto._destroy=function(){ _super.prototype._destroy.call(this); this._terrainSprite3DOwner=null; } return TerrainRender; })(BaseRender) /** *... *@author ... */ //class laya.d3.water.WaterRender extends laya.d3.core.render.BaseRender var WaterRender=(function(_super){ function WaterRender(owner){ WaterRender.__super.call(this,owner); } __class(WaterRender,'laya.d3.water.WaterRender',_super); var __proto=WaterRender.prototype; __proto._calculateBoundingSphere=function(){} __proto._calculateBoundingBox=function(){} __proto._destroy=function(){ _super.prototype._destroy.call(this); } return WaterRender; })(BaseRender) /** *BaseScene 类用于实现场景。 */ //class laya.d3.core.scene.Scene extends laya.display.Sprite var Scene=(function(_super){ function Scene(){ this._time=0; /**@private */ //this.__loaded=false; /**@private */ //this._url=null; /**@private */ //this._group=null; /**@private */ //this._lightmaps=null; /**@private */ this._enableLightCount=3; /**@private */ //this._renderTargetTexture=null; /**@private */ this._customRenderQueneIndex=11; /**@private */ //this._lastCurrentTime=NaN; /**@private */ //this._enableFog=false; /**@private */ //this._enableDepthFog=false; /**@private */ //this._fogStart=NaN; /**@private */ //this._fogRange=NaN; /**@private */ //this._fogColor=null; /**@private */ //this._ambientColor=null; /**@private */ //this._shaderValues=null; /**@private */ //this._shaderDefineValue=0; /**@private */ //this._cullingRendersLength=0; /**@private */ //this._cullingRenders=null; /**@private */ //this._dynamicBatchManager=null; /**是否启用灯光。*/ this.enableLight=true; /**四/八叉树的根节点。*/ //this.treeRoot=null; /**四/八叉树的尺寸。*/ //this.treeSize=null; /**四/八叉树的层数。*/ //this.treeLevel=0; //阴影相关变量 //this.parallelSplitShadowMaps=null; /**@private */ //this._componentsMap=null; /**@private */ //this._typeComponentsIndices=null; /**@private */ //this._components=null; Scene.__super.call(this); this._renderState=new RenderState(); this._lights=[]; this._quenes=[]; this._cameraPool=[]; this._renderableSprite3Ds=[]; this.__loaded=true; this._lightmaps=[]; this._shaderValues=new ValusArray(); this.parallelSplitShadowMaps=[]; this._dynamicBatchManager=new DynamicBatchManager(); this._cullingRenders=[]; this._cullingRendersLength=0; this.enableFog=false; this.fogStart=300; this.fogRange=1000; this.fogColor=new Vector3(0.7,0.7,0.7); this.ambientColor=new Vector3(0.212,0.227,0.259); (WebGL.shaderHighPrecision)&& (this.addShaderDefine(ShaderCompile3D.SHADERDEFINE_HIGHPRECISION)); this.on(/*laya.events.Event.DISPLAY*/"display",this,this._display); this.on(/*laya.events.Event.UNDISPLAY*/"undisplay",this,this._unDisplay); this._componentsMap=[]; this._typeComponentsIndices=[]; this._components=[]; } __class(Scene,'laya.d3.core.scene.Scene',_super); var __proto=Scene.prototype; Laya.imps(__proto,{"laya.webgl.submit.ISubmit":true,"laya.resource.ICreateResource":true}) /** *@private */ __proto._setUrl=function(url){ this._url=url; } /** *@private */ __proto._getGroup=function(){ return this._group; } /** *@private */ __proto._setGroup=function(value){ this._group=value; } /** *@private */ __proto._display=function(){ Laya.stage._scenes.push(this); Laya.stage._scenes.sort(Scene._sortScenes); for (var i=0,n=this._childs.length;i < n;i++){ var spr=this._childs[i]; (spr.active)&& (spr._activeHierarchy()); } } /** *@private */ __proto._unDisplay=function(){ var scenes=Laya.stage._scenes; scenes.splice(scenes.indexOf(this),1); for (var i=0,n=this._childs.length;i < n;i++){ var spr=this._childs[i]; (spr.active)&& (spr._inActiveHierarchy()); } } /** *@private */ __proto._addChild3D=function(sprite3D){ sprite3D.transform._onWorldTransform(); sprite3D._setBelongScene(this); (this.displayedInStage && sprite3D.active)&& (sprite3D._activeHierarchy()); } /** *@private */ __proto._removeChild3D=function(sprite3D){ sprite3D.transform.parent=null; (this.displayedInStage && sprite3D.active)&& (sprite3D._inActiveHierarchy()); sprite3D._setUnBelongScene(); } /** *初始化八叉树。 *@param width 八叉树宽度。 *@param height 八叉树高度。 *@param depth 八叉树深度。 *@param center 八叉树中心点 *@param level 八叉树层级。 */ __proto.initOctree=function(width,height,depth,center,level){ (level===void 0)&& (level=6); this.treeSize=new Vector3(width,height,depth); this.treeLevel=level; this.treeRoot=new OctreeNode(this,0); this.treeRoot.init(center,this.treeSize); } /** *@private *场景相关渲染准备设置。 *@param gl WebGL上下文。 *@return state 渲染状态。 */ __proto._prepareUpdateToRenderState=function(gl,state){ state.elapsedTime=this._lastCurrentTime ? this.timer.currTimer-this._lastCurrentTime :0; this._lastCurrentTime=this.timer.currTimer; state.scene=this; } /** *@private */ __proto._prepareSceneToRender=function(state){ var lightCount=this._lights.length; if (lightCount > 0){ var renderLightCount=0; for (var i=0;i < lightCount;i++){ if (!this._lights[i]._prepareToScene(state)) continue ; renderLightCount++; if (renderLightCount >=this._enableLightCount) break ; } } } /** *@private */ __proto._updateChilds=function(state){ for (var i=0,n=this._childs.length;i < n;++i) this._childs[i]._update(state); } /** *@private */ __proto._preRenderScene=function(gl,state,boundFrustum){ var view=state._viewMatrix; var projection=state._projectionMatrix; var projectionView=state._projectionViewMatrix; var i=0,iNum=0; var camera=state.camera; if (camera.useOcclusionCulling){ if (this.treeRoot) FrustumCulling.renderObjectCullingOctree(boundFrustum,this,camera,view,projection,projectionView); else FrustumCulling.renderObjectCulling(boundFrustum,this,camera,view,projection,projectionView); }else { FrustumCulling.renderObjectCullingNoBoundFrustum(this,camera,view,projection,projectionView); } for (i=0,iNum=this._quenes.length;i < iNum;i++) (this._quenes[i])&& (this._quenes[i]._preRender(state)); } /** *@private */ __proto._clear=function(gl,state){ var viewport=state._viewport; var camera=state.camera; var vpX=viewport.x; var vpY=camera.renderTargetSize.height-viewport.y-viewport.height; var vpWidth=viewport.width; var vpHeight=viewport.height; gl.viewport(vpX,vpY,vpWidth,vpHeight); var flag=/*laya.webgl.WebGLContext.DEPTH_BUFFER_BIT*/0x00000100; var renderTarget=camera.renderTarget; switch (camera.clearFlag){ case /*laya.d3.core.BaseCamera.CLEARFLAG_SOLIDCOLOR*/0:; var clearColor=camera.clearColor; if (clearColor){ gl.enable(/*laya.webgl.WebGLContext.SCISSOR_TEST*/0x0C11); gl.scissor(vpX,vpY,vpWidth,vpHeight); var clearColorE=clearColor.elements; gl.clearColor(clearColorE[0],clearColorE[1],clearColorE[2],clearColorE[3]); flag |=/*laya.webgl.WebGLContext.COLOR_BUFFER_BIT*/0x00004000; } if (renderTarget){ (clearColor)|| (flag=/*laya.webgl.WebGLContext.COLOR_BUFFER_BIT*/0x00004000); switch (renderTarget.depthStencilFormat){ case /*laya.webgl.WebGLContext.DEPTH_COMPONENT16*/0x81A5: flag |=/*laya.webgl.WebGLContext.DEPTH_BUFFER_BIT*/0x00000100; break ; case /*laya.webgl.WebGLContext.STENCIL_INDEX8*/0x8D48: flag |=/*laya.webgl.WebGLContext.STENCIL_BUFFER_BIT*/0x00000400; break ; case /*laya.webgl.WebGLContext.DEPTH_STENCIL*/0x84F9: flag |=/*laya.webgl.WebGLContext.DEPTH_BUFFER_BIT*/0x00000100; flag |=/*laya.webgl.WebGLContext.STENCIL_BUFFER_BIT*/0x00000400; break ; } } gl.clear(flag); if (clearColor) gl.disable(/*laya.webgl.WebGLContext.SCISSOR_TEST*/0x0C11); break ; case /*laya.d3.core.BaseCamera.CLEARFLAG_SKY*/1: case /*laya.d3.core.BaseCamera.CLEARFLAG_DEPTHONLY*/2: if (renderTarget){ flag=/*laya.webgl.WebGLContext.COLOR_BUFFER_BIT*/0x00004000; switch (renderTarget.depthStencilFormat){ case /*laya.webgl.WebGLContext.DEPTH_COMPONENT16*/0x81A5: flag |=/*laya.webgl.WebGLContext.DEPTH_BUFFER_BIT*/0x00000100; break ; case /*laya.webgl.WebGLContext.STENCIL_INDEX8*/0x8D48: flag |=/*laya.webgl.WebGLContext.STENCIL_BUFFER_BIT*/0x00000400; break ; case /*laya.webgl.WebGLContext.DEPTH_STENCIL*/0x84F9: flag |=/*laya.webgl.WebGLContext.DEPTH_BUFFER_BIT*/0x00000100; flag |=/*laya.webgl.WebGLContext.STENCIL_BUFFER_BIT*/0x00000400 break ; } } gl.clear(flag); break ; case /*laya.d3.core.BaseCamera.CLEARFLAG_NONE*/3: break ; default : throw new Error("BaseScene:camera clearFlag invalid."); } } /** *@private */ __proto._renderScene=function(gl,state){ var camera=state.camera; var i=0,n=0; var queue; for (i=0;i < 2;i++){ queue=this._quenes[i]; if (queue){ camera.renderTarget ? queue._render(state,true):queue._render(state,false); } } if (camera.clearFlag===/*laya.d3.core.BaseCamera.CLEARFLAG_SKY*/1){ var sky=camera.sky; if (sky){ WebGLContext.setCullFace(gl,false); WebGLContext.setDepthFunc(gl,/*laya.webgl.WebGLContext.LEQUAL*/0x0203); WebGLContext.setDepthMask(gl,false); sky._render(state); WebGLContext.setDepthFunc(gl,/*laya.webgl.WebGLContext.LESS*/0x0201); WebGLContext.setDepthMask(gl,true); } } for (i=2,n=this._quenes.length;i < n;i++){ queue=this._quenes[i]; if (queue){ queue._sortAlpha(state.camera.transform.position); camera.renderTarget ? queue._render(state,true):queue._render(state,false); } } } /** *@private */ __proto._set3DRenderConfig=function(gl){ gl.disable(/*laya.webgl.WebGLContext.BLEND*/0x0BE2); WebGLContext._blend=false; gl.blendFunc(/*laya.webgl.WebGLContext.SRC_ALPHA*/0x0302,/*laya.webgl.WebGLContext.ONE_MINUS_SRC_ALPHA*/0x0303); WebGLContext._sFactor=/*laya.webgl.WebGLContext.SRC_ALPHA*/0x0302; WebGLContext._dFactor=/*laya.webgl.WebGLContext.ONE_MINUS_SRC_ALPHA*/0x0303; gl.disable(/*laya.webgl.WebGLContext.DEPTH_TEST*/0x0B71); WebGLContext._depthTest=false; gl.enable(/*laya.webgl.WebGLContext.CULL_FACE*/0x0B44); WebGLContext._cullFace=true; gl.depthMask(1); WebGLContext._depthMask=true; gl.frontFace(/*laya.webgl.WebGLContext.CW*/0x0900); WebGLContext._frontFace=/*laya.webgl.WebGLContext.CW*/0x0900; } /** *@private */ __proto._set2DRenderConfig=function(gl){ WebGLContext.setBlend(gl,true); WebGLContext.setBlendFunc(gl,/*laya.webgl.WebGLContext.ONE*/1,/*laya.webgl.WebGLContext.ONE_MINUS_SRC_ALPHA*/0x0303); WebGLContext.setDepthTest(gl,false); WebGLContext.setCullFace(gl,false); WebGLContext.setDepthMask(gl,true); WebGLContext.setFrontFace(gl,/*laya.webgl.WebGLContext.CCW*/0x0901); gl.viewport(0,0,RenderState2D.width,RenderState2D.height); } /** *@private */ __proto._parseCustomProps=function(rootNode,innerResouMap,customProps,nodeData){ var lightMapsData=nodeData.customProps.lightmaps; var lightMapCount=lightMapsData.length; var lightmaps=this._lightmaps; lightmaps.length=lightMapCount; for (var i=0;i < lightMapCount;i++) lightmaps[i]=Loader.getRes(innerResouMap[lightMapsData[i].replace(".exr",".png")]); this.setlightmaps(lightmaps); var ambientColorData=nodeData.customProps.ambientColor; (ambientColorData)&& (this.ambientColor=new Vector3(ambientColorData[0],ambientColorData[1],ambientColorData[2])); var fogColorData=nodeData.customProps.fogColor; (fogColorData)&& (this.fogColor=new Vector3(fogColorData[0],fogColorData[1],fogColorData[2])); } /** *@private */ __proto._addLight=function(light){ if (this._lights.indexOf(light)< 0)this._lights.push(light); } /** *@private */ __proto._removeLight=function(light){ var index=this._lights.indexOf(light); index >=0 && (this._lights.splice(index,1)); } /** *@private */ __proto._updateScene=function(){ var renderState=this._renderState; this._prepareUpdateToRenderState(WebGL.mainContext,renderState); this._updateComponents(renderState); this._updateChilds(renderState); this._lateUpdateComponents(renderState); this._time+=renderState.elapsedTime / 1000; this._shaderValues.setValue(/*CLASS CONST:laya.d3.core.scene.Scene.TIME*/22,this._time); } /** *@private */ __proto._updateSceneConch=function(){ var renderState=this._renderState; this._prepareUpdateToRenderState(WebGL.mainContext,renderState); this._updateComponents(renderState); this._lateUpdateComponents(renderState); this._prepareSceneToRender(renderState); for (var i=0,n=this._cameraPool.length;i < n;i++){ var camera=this._cameraPool[i]; renderState.camera=camera; camera._prepareCameraToRender(); } } /** *@private */ __proto._preRenderShadow=function(state,lightFrustum,shdowQueues,lightViewProjectMatrix,nPSSMNum){ if (this.treeRoot){ FrustumCulling.renderShadowObjectCullingOctree(this,lightFrustum,shdowQueues,lightViewProjectMatrix,nPSSMNum); }else { FrustumCulling.renderShadowObjectCulling(this,lightFrustum,shdowQueues,lightViewProjectMatrix,nPSSMNum); } for (var i=0,iNum=shdowQueues.length;i < iNum;i++) (shdowQueues[i])&& (shdowQueues[i]._preRender(state)); } /** *@private */ __proto._renderShadowMap=function(gl,state,sceneCamera){ var parallelSplitShadowMap=this.parallelSplitShadowMaps[0]; parallelSplitShadowMap._calcAllLightCameraInfo(sceneCamera); var pssmNum=parallelSplitShadowMap.PSSMNum; this._preRenderShadow(state,parallelSplitShadowMap._lightCulling,parallelSplitShadowMap._shadowQuenes,parallelSplitShadowMap._lightVPMatrix[0],pssmNum); this.addShaderDefine(ParallelSplitShadowMap.SHADERDEFINE_CAST_SHADOW); var renderTarget,shadowQuene,lightCamera; if (pssmNum > 1){ for (var i=0;i < pssmNum;i++){ renderTarget=parallelSplitShadowMap.getRenderTarget(i+1); parallelSplitShadowMap.beginRenderTarget(i+1); gl.clearColor(1,1,1,1); gl.clear(/*laya.webgl.WebGLContext.COLOR_BUFFER_BIT*/0x00004000 | /*laya.webgl.WebGLContext.DEPTH_BUFFER_BIT*/0x00000100); gl.viewport(0,0,renderTarget.width,renderTarget.height); state.camera=lightCamera=parallelSplitShadowMap.getLightCamera(i); lightCamera._prepareCameraToRender(); lightCamera._prepareCameraViewProject(lightCamera.viewMatrix,lightCamera.projectionMatrix); state._projectionViewMatrix=parallelSplitShadowMap._lightVPMatrix[i+1]; shadowQuene=parallelSplitShadowMap._shadowQuenes[i]; shadowQuene._preRender(state); shadowQuene._renderShadow(state,false); parallelSplitShadowMap.endRenderTarget(i+1); } }else { renderTarget=parallelSplitShadowMap.getRenderTarget(1); parallelSplitShadowMap.beginRenderTarget(1); gl.clearColor(1,1,1,1); gl.clear(/*laya.webgl.WebGLContext.COLOR_BUFFER_BIT*/0x00004000 | /*laya.webgl.WebGLContext.DEPTH_BUFFER_BIT*/0x00000100); gl.viewport(0,0,renderTarget.width,renderTarget.height); state.camera=lightCamera=parallelSplitShadowMap.getLightCamera(0); lightCamera._prepareCameraToRender(); lightCamera._prepareCameraViewProject(lightCamera.viewMatrix,lightCamera.projectionMatrix); state._projectionViewMatrix=parallelSplitShadowMap._lightVPMatrix[0]; shadowQuene=parallelSplitShadowMap._shadowQuenes[0]; shadowQuene._preRender(state); shadowQuene._renderShadow(state,true); parallelSplitShadowMap.endRenderTarget(1); } this.removeShaderDefine(ParallelSplitShadowMap.SHADERDEFINE_CAST_SHADOW); } /** *@private */ __proto.addTreeNode=function(renderObj){ this.treeRoot.addTreeNode(renderObj); } /** *@private */ __proto.removeTreeNode=function(renderObj){ if (!this.treeSize)return; if (renderObj._treeNode){ renderObj._treeNode.removeObject(renderObj); } } /** *设置光照贴图。 *@param value 光照贴图。 */ __proto.setlightmaps=function(value){ this._lightmaps=value; for (var i=0,n=this._renderableSprite3Ds.length;i < n;i++) this._renderableSprite3Ds[i]._render._applyLightMapParams(); } /** *获取光照贴图。 *@return 获取光照贴图。 */ __proto.getlightmaps=function(){ return this._lightmaps; } /** *@inheritDoc */ __proto.addChildAt=function(node,index){ if (!((node instanceof laya.d3.core.Sprite3D ))) throw new Error("Sprite3D:Node type must Sprite3D."); if (!node || this.destroyed || node===this)return node; if ((node).zOrder)this._set$P("hasZorder",true); if (index >=0 && index <=this._childs.length){ if (node._parent===this){ var oldIndex=this.getChildIndex(node); this._childs.splice(oldIndex,1); this._childs.splice(index,0,node); if (this.conchModel){ this.conchModel.removeChild(node.conchModel); this.conchModel.addChildAt(node.conchModel,index); } this._childChanged(); }else { node.parent && node.parent.removeChild(node); this._childs===Node.ARRAY_EMPTY && (this._childs=[]); this._childs.splice(index,0,node); this.conchModel && this.conchModel.addChildAt(node.conchModel,index); node.parent=this; this._addChild3D(node); } return node; }else { throw new Error("appendChildAt:The index is out of bounds"); } } /** *@inheritDoc */ __proto.addChild=function(node){ if (!((node instanceof laya.d3.core.Sprite3D ))) throw new Error("Sprite3D:Node type must Sprite3D."); if (!node || this.destroyed || node===this)return node; if ((node).zOrder)this._set$P("hasZorder",true); if (node._parent===this){ var index=this.getChildIndex(node); if (index!==this._childs.length-1){ this._childs.splice(index,1); this._childs.push(node); if (this.conchModel){ this.conchModel.removeChild(node.conchModel); this.conchModel.addChildAt(node.conchModel,this._childs.length-1); } this._childChanged(); } }else { node.parent && node.parent.removeChild(node); this._childs===Node.ARRAY_EMPTY && (this._childs=[]); this._childs.push(node); this.conchModel && this.conchModel.addChildAt(node.conchModel,this._childs.length-1); node.parent=this; this._childChanged(); this._addChild3D(node); } return node; } /** *@inheritDoc */ __proto.removeChildAt=function(index){ var node=this.getChildAt(index); if (node){ this._removeChild3D(node); this._childs.splice(index,1); this.conchModel && this.conchModel.removeChild(node.conchModel); node.parent=null; } return node; } /** *@inheritDoc */ __proto.removeChildren=function(beginIndex,endIndex){ (beginIndex===void 0)&& (beginIndex=0); (endIndex===void 0)&& (endIndex=0x7fffffff); if (this._childs && this._childs.length > 0){ var childs=this._childs; if (beginIndex===0 && endIndex >=n){ var arr=childs; this._childs=Node.ARRAY_EMPTY; }else { arr=childs.splice(beginIndex,endIndex-beginIndex); } for (var i=0,n=arr.length;i < n;i++){ this._removeChild3D(arr [i]); arr[i].parent=null; this.conchModel && this.conchModel.removeChild(arr[i].conchModel); } } return this; } /** *@inheritDoc */ __proto.addFrustumCullingObject=function(renderObject){ if (this.treeRoot){ this.addTreeNode(renderObject); }else { if (this._cullingRendersLength===this._cullingRenders.length) this._cullingRenders.push(renderObject); else this._cullingRenders[this._cullingRendersLength]=renderObject; renderObject._indexInSceneFrustumCullingObjects=this._cullingRendersLength++; } } /** *@private */ __proto.removeFrustumCullingObject=function(renderObject){ if (this.treeRoot){ this.removeTreeNode(renderObject); }else { this._cullingRendersLength--; var indexInSceneFrustumCullingObjects=renderObject._indexInSceneFrustumCullingObjects; if (indexInSceneFrustumCullingObjects!==this._cullingRendersLength){ var endRender=this._cullingRenders[this._cullingRendersLength]; this._cullingRenders[indexInSceneFrustumCullingObjects]=endRender; endRender._indexInSceneFrustumCullingObjects=indexInSceneFrustumCullingObjects; renderObject._indexInSceneFrustumCullingObjects=-1; } } } /** *获得某个渲染队列。 *@param index 渲染队列索引。 *@return 渲染队列。 */ __proto.getRenderQueue=function(index){ if (index < 3000) return this._quenes[1] || (this._quenes[1]=new RenderQueue(this)); else return this._quenes[2] || (this._quenes[2]=new RenderQueue(this)); } /** *添加渲染队列。 *@param renderConfig 渲染队列配置文件。 */ __proto.addRenderQuene=function(){ this._quenes[this._customRenderQueneIndex++]=new RenderQueue(this); } /** *增加shader宏定义。 *@param define shader宏定义。 */ __proto.addShaderDefine=function(define){ this._shaderDefineValue |=define; } /** *移除shader宏定义。 *@param define shader宏定义。 */ __proto.removeShaderDefine=function(define){ this._shaderDefineValue &=~define; } /** *添加指定类型脚本。 *@param type 脚本类型。 *@return 组件。 */ __proto.addScript=function(type){ return this._addComponent(type); } /** *通过指定类型和类型索引获得脚本。 *@param type 脚本类型。 *@param typeIndex 脚本索引。 *@return 脚本。 */ __proto.getScriptByType=function(type,typeIndex){ (typeIndex===void 0)&& (typeIndex=0); return this._getComponentByType(type,typeIndex); } /** *通过指定类型获得所有脚本。 *@param type 脚本类型。 *@param scripts 脚本输出队列。 */ __proto.getScriptsByType=function(type,scripts){ this._getComponentsByType(type,scripts); } /** *通过指定索引获得脚本。 *@param index 索引。 *@return 脚本。 */ __proto.getScriptByIndex=function(index){ return this._getComponentByIndex(index); } /** *通过指定类型和类型索引移除脚本。 *@param type 脚本类型。 *@param typeIndex 类型索引。 */ __proto.removeScriptByType=function(type,typeIndex){ (typeIndex===void 0)&& (typeIndex=0); this._removeComponentByType(type,typeIndex); } /** *通过指定类型移除所有脚本。 *@param type 组件类型。 */ __proto.removeScriptsByType=function(type){ this._removeComponentByType(type); } /** *移除全部脚本。 */ __proto.removeAllScript=function(){ this._removeAllComponent(); } /** *@private */ __proto.render=function(context,x,y){ (Render._context.ctx)._renderKey=0; this._childs.length > 0 && context.addRenderObject(this); } /** *@private */ __proto.renderSubmit=function(){ var gl=WebGL.mainContext; var renderState=this._renderState; this._set3DRenderConfig(gl); this._prepareSceneToRender(this._renderState); var i=0,n=0,camera; if (Laya3D.debugMode || OctreeNode.debugMode){ for (i=0,n=this._cameraPool.length;i < n;i++){ camera=this._cameraPool[i]; Laya3D._debugPhasorSprite.begin(/*laya.webgl.WebGLContext.LINES*/0x0001,camera); (camera.activeInHierarchy)&& (camera._renderCamera(gl,renderState,this)); Laya3D._debugPhasorSprite.end(); } }else { for (i=0,n=this._cameraPool.length;i < n;i++){ camera=this._cameraPool[i]; (camera.activeInHierarchy)&& (camera._renderCamera(gl,renderState,this)); } } this._set2DRenderConfig(gl); return 1; } /** *@private */ __proto.onAsynLoaded=function(url,data,params){ var json=data[0] if (json.type!=="Scene") throw new Error("Scene: the .lh file root type must be Scene,please use other function to load this file."); var innerResouMap=data[1]; Utils3D._createNodeByJson(this,json,this,innerResouMap); this.event(/*laya.events.Event.HIERARCHY_LOADED*/"hierarchyloaded",[this]); this.__loaded=true; } /** *@private */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); if (this.destroyed) return; _super.prototype.destroy.call(this,destroyChild); this._renderState=null; this._lights=null; this._lightmaps=null; this._renderTargetTexture=null; this._shaderValues=null; this._cullingRenders=null; this._dynamicBatchManager=null; this._quenes=null; this._cameraPool=null; this._renderableSprite3Ds=null; this.treeRoot=null; this.treeSize=null; this.parallelSplitShadowMaps=null; this._typeComponentsIndices=null; this._components=null; Loader.clearRes(this.url); (this.loaded)|| (Laya3D._cancelLoadByUrl(this.url)); } /** *@private */ __proto.getRenderType=function(){ return 0; } /** *@private */ __proto.releaseRender=function(){} /** *@private */ __proto._addComponent=function(type){ var typeComponentIndex; var index=this._componentsMap.indexOf(type); if (index===-1){ typeComponentIndex=[]; this._componentsMap.push(type); this._typeComponentsIndices.push(typeComponentIndex); }else { typeComponentIndex=this._typeComponentsIndices[index]; if (this._components[typeComponentIndex[0]].isSingleton) throw new Error("无法单实例创建"+type+"组件"+","+type+"组件已存在!"); }; var component=ClassUtils.getInstance(type); typeComponentIndex.push(this._components.length); this._components.push(component); var _this=this; component._initialize(_this); return component; } /** *@private */ __proto._removeComponent=function(mapIndex,index){ var componentIndices=this._typeComponentsIndices[mapIndex]; var componentIndex=componentIndices[index]; var component=this._components[componentIndex]; this._components.splice(componentIndex,1); componentIndices.splice(index,1); (componentIndices.length===0)&& (this._typeComponentsIndices.splice(mapIndex,1),this._componentsMap.splice(mapIndex,1)); for (var i=0,n=this._componentsMap.length;i < n;i++){ componentIndices=this._typeComponentsIndices[i]; for (var j=componentIndices.length-1;j >=0;j--){ var oldComponentIndex=componentIndices[j]; if (oldComponentIndex > componentIndex) componentIndices[j]=--oldComponentIndex; else break ; } } component._destroy(); } /** *@private */ __proto._getComponentByType=function(type,typeIndex){ (typeIndex===void 0)&& (typeIndex=0); var mapIndex=this._componentsMap.indexOf(type); if (mapIndex===-1) return null; return this._components[this._typeComponentsIndices[mapIndex][typeIndex]]; } /** *@private */ __proto._getComponentsByType=function(type,components){ var index=this._componentsMap.indexOf(type); if (index===-1){ components.length=0; return; }; var typeComponents=this._typeComponentsIndices[index]; var count=typeComponents.length; components.length=count; for (var i=0;i < count;i++) components[i]=this._components[typeComponents[i]]; } /** *@private */ __proto._getComponentByIndex=function(index){ return this._components[index]; } /** *@private */ __proto._removeComponentByType=function(type,typeIndex){ (typeIndex===void 0)&& (typeIndex=0); var mapIndex=this._componentsMap.indexOf(type); if (mapIndex===-1) return; this._removeComponent(mapIndex,typeIndex); } /** *@private */ __proto._removeComponentsByType=function(type){ var mapIndex=this._componentsMap.indexOf(type); if (mapIndex===-1) return; var componentIndices=this._typeComponentsIndices[mapIndex]; for (var i=0,n=componentIndices.length;i < n;componentIndices.length < n ? n--:i++) this._removeComponent(mapIndex,i); } /** *@private */ __proto._removeAllComponent=function(){ for (var i=0,n=this._componentsMap.length;i < n;this._componentsMap.length < n ? n--:i++) this._removeComponentsByType(this._componentsMap[i]); } /** *@private */ __proto._updateComponents=function(state){ for (var i=0,n=this._components.length;i < n;i++){ var component=this._components[i]; (!component.started)&& (component._start(state),component.started=true); (component.enable)&& (component._update(state)); } } /** *@private */ __proto._lateUpdateComponents=function(state){ for (var i=0;i < this._components.length;i++){ var component=this._components[i]; (!component.started)&& (component._start(state),component.started=true); (component.enable)&& (component._lateUpdate(state)); } } /** *@private */ __proto._preRenderUpdateComponents=function(state){ for (var i=0;i < this._components.length;i++){ var component=this._components[i]; (!component.started)&& (component._start(state),component.started=true); (component.enable)&& (component._preRenderUpdate(state)); } } /** *@private */ __proto._postRenderUpdateComponents=function(state){ for (var i=0;i < this._components.length;i++){ var component=this._components[i]; (!component.started)&& (component._start(state),component.started=true); (component.enable)&& (component._postRenderUpdate(state)); } } /** *@private */ __getset(0,__proto,'_loaded',null,function(value){ this.__loaded=value; }); /** *设置雾化颜色。 *@param value 雾化颜色。 */ /** *获取雾化颜色。 *@return 雾化颜色。 */ __getset(0,__proto,'fogColor',function(){ return this._fogColor; },function(value){ this._fogColor=value; this._shaderValues.setValue(/*CLASS CONST:laya.d3.core.scene.Scene.FOGCOLOR*/0,value.elements); }); /** *设置是否允许雾化。 *@param value 是否允许雾化。 */ /** *获取是否允许雾化。 *@return 是否允许雾化。 */ __getset(0,__proto,'enableFog',function(){ return this._enableFog; },function(value){ if (this._enableFog!==value){ this._enableFog=value; if (value){ this.addShaderDefine(ShaderCompile3D.SHADERDEFINE_FOG); this.removeShaderDefine(ShaderCompile3D.SAHDERDEFINE_DEPTHFOG); }else this.removeShaderDefine(ShaderCompile3D.SHADERDEFINE_FOG); } }); /** *获取资源的URL地址。 *@return URL地址。 */ __getset(0,__proto,'url',function(){ return this._url; }); /** *获取是否已加载完成。 */ __getset(0,__proto,'loaded',function(){ return this.__loaded; }); __getset(0,__proto,'enableDepthFog',function(){ return this._enableDepthFog; },function(v){ if (this._enableDepthFog !=v){ this._enableDepthFog=v; if (v){ this.addShaderDefine(ShaderCompile3D.SAHDERDEFINE_DEPTHFOG); this.removeShaderDefine(ShaderCompile3D.SHADERDEFINE_FOG); }else { this.removeShaderDefine(ShaderCompile3D.SAHDERDEFINE_DEPTHFOG); } } }); /** *设置雾化起始位置。 *@param value 雾化起始位置。 */ /** *获取雾化起始位置。 *@return 雾化起始位置。 */ __getset(0,__proto,'fogStart',function(){ return this._fogStart; },function(value){ this._fogStart=value; this._shaderValues.setValue(/*CLASS CONST:laya.d3.core.scene.Scene.FOGSTART*/1,value); }); /** *设置雾化范围。 *@param value 雾化范围。 */ /** *获取雾化范围。 *@return 雾化范围。 */ __getset(0,__proto,'fogRange',function(){ return this._fogRange; },function(value){ this._fogRange=value; this._shaderValues.setValue(/*CLASS CONST:laya.d3.core.scene.Scene.FOGRANGE*/2,value); }); /** *设置环境光颜色。 *@param value 环境光颜色。 */ /** *获取环境光颜色。 *@return 环境光颜色。 */ __getset(0,__proto,'ambientColor',function(){ return this._ambientColor; },function(value){ this._ambientColor=value; this._shaderValues.setValue(/*CLASS CONST:laya.d3.core.scene.Scene.AMBIENTCOLOR*/21,value.elements); }); /** *获取当前场景。 *@return 当前场景。 */ __getset(0,__proto,'scene',function(){ return this; }); /** *获取场景的可渲染精灵。 */ __getset(0,__proto,'renderableSprite3Ds',function(){ return this._renderableSprite3Ds.slice(); }); Scene._sortScenes=function(a,b){ if (a.parent===Laya.stage && b.parent===Laya.stage){ var stageChildren=Laya.stage._childs; return stageChildren.indexOf(a)-stageChildren.indexOf(b); }else if (a.parent!==Laya.stage && b.parent!==Laya.stage){ return Scene._sortScenes(a.parent,b.parent); }else { return (a.parent===Laya.stage)?-1 :1; } } Scene.load=function(url){ return Laya.loader.create(url,null,null,Scene); } Scene.FOGCOLOR=0; Scene.FOGSTART=1; Scene.FOGRANGE=2; Scene.LIGHTDIRECTION=3; Scene.LIGHTDIRCOLOR=4; Scene.POINTLIGHTPOS=5; Scene.POINTLIGHTRANGE=6; Scene.POINTLIGHTATTENUATION=7; Scene.POINTLIGHTCOLOR=8; Scene.SPOTLIGHTPOS=9; Scene.SPOTLIGHTDIRECTION=10; Scene.SPOTLIGHTSPOT=11; Scene.SPOTLIGHTRANGE=12; Scene.SPOTLIGHTATTENUATION=13; Scene.SPOTLIGHTCOLOR=14; Scene.SHADOWDISTANCE=15; Scene.SHADOWLIGHTVIEWPROJECT=16; Scene.SHADOWMAPPCFOFFSET=17; Scene.SHADOWMAPTEXTURE1=18; Scene.SHADOWMAPTEXTURE2=19; Scene.SHADOWMAPTEXTURE3=20; Scene.AMBIENTCOLOR=21; Scene.TIME=22; return Scene; })(Sprite) /** *Sprite3D 类用于实现3D精灵。 */ //class laya.d3.core.Sprite3D extends laya.d3.core.ComponentNode var Sprite3D=(function(_super){ function Sprite3D(name){ /**@private */ //this._projectionViewWorldMatrix=null; /**@private */ //this._projectionViewWorldUpdateLoopCount=0; /**@private */ //this._projectionViewWorldUpdateCamera=null; /**@private */ //this._id=0; /**@private */ //this.__loaded=false; /**@private */ //this._url=null; /**@private */ //this._group=null; /**@private */ //this._active=false; /**@private */ //this._activeInHierarchy=false; /**@private */ //this._layer=null; /**@private */ //this._shaderDefineValue=0; /**@private */ //this._shaderValues=null; /**@private */ //this._colliders=null; /**@private */ //this._scene=null; /**@private */ //this._transform=null; /**@private */ //this._hierarchyAnimator=null; /**是否静态,静态包含一系列的静态处理。*/ //this.isStatic=false; Sprite3D.__super.call(this); this.__loaded=true; this._projectionViewWorldUpdateLoopCount=-1; this._activeInHierarchy=false; this._projectionViewWorldMatrix=new Matrix4x4(); this._shaderValues=new ValusArray(); this._colliders=[]; this._id=++Sprite3D._uniqueIDCounter; this._transform=new Transform3D(this); this.name=name ? name :"Sprite3D-"+Sprite3D._nameNumberCounter++; this.layer=Layer.currentCreationLayer; this.active=true; } __class(Sprite3D,'laya.d3.core.Sprite3D',_super); var __proto=Sprite3D.prototype; Laya.imps(__proto,{"laya.d3.core.render.IUpdate":true,"laya.resource.ICreateResource":true,"laya.d3.core.IClone":true}) /** *@private */ __proto._setUrl=function(url){ this._url=url; } /** *@private */ __proto._getGroup=function(){ return this._group; } /** *@private */ __proto._setGroup=function(value){ this._group=value; } /** *@private */ __proto._addChild3D=function(sprite3D){ sprite3D.transform.parent=this.transform; if (this._hierarchyAnimator){ (!sprite3D._hierarchyAnimator)&& (sprite3D._setHierarchyAnimator(this._hierarchyAnimator,null)); this._getAnimatorToLinkSprite3D(sprite3D,true,/*new vector.<>*/[sprite3D.name]); } if (this._scene){ sprite3D._setBelongScene(this._scene); (this._activeInHierarchy && sprite3D._active)&& (sprite3D._activeHierarchy()); } } /** *@private */ __proto._removeChild3D=function(sprite3D){ sprite3D.transform.parent=null; if (this._scene){ (this._activeInHierarchy && sprite3D._active)&& (sprite3D._inActiveHierarchy()); sprite3D._setUnBelongScene(); } if (this._hierarchyAnimator){ ((sprite3D._hierarchyAnimator==this._hierarchyAnimator))&& (sprite3D._clearHierarchyAnimator(this._hierarchyAnimator,null)); this._getAnimatorToLinkSprite3D(sprite3D,false,/*new vector.<>*/[sprite3D.name]); } } /** *@private */ __proto._parseBaseCustomProps=function(customProps){ var loccalPosition=this.transform.localPosition; loccalPosition.fromArray(customProps.translate); this.transform.localPosition=loccalPosition; var localRotation=this.transform.localRotation; localRotation.fromArray(customProps.rotation); this.transform.localRotation=localRotation; var localScale=this.transform.localScale; localScale.fromArray(customProps.scale); this.transform.localScale=localScale; var layerData=customProps.layer; (layerData !=null)&& (this.layer=Layer.getLayerByNumber(layerData)); } /** *@private */ __proto._parseCustomComponent=function(rootNode,innerResouMap,componentsData){ for (var k in componentsData){ var component=componentsData[k]; switch (k){ case "Animator":; var animator=this.addComponent(Animator); if (component.avatarPath){ animator.avatar=Loader.getRes(innerResouMap[component.avatarPath]); }else { var avatarData=component.avatar; if (avatarData){ animator.avatar=Loader.getRes(innerResouMap[avatarData.path]); var linkSprites=avatarData.linkSprites; (linkSprites)&& (rootNode.once(/*laya.events.Event.HIERARCHY_LOADED*/"hierarchyloaded",this,this._onRootNodeHierarchyLoaded,[animator,linkSprites])); } }; var clipPaths=component.clipPaths; var clipCount=clipPaths.length; for (var i=0;i < clipCount;i++) animator.addClip(Loader.getRes(innerResouMap[clipPaths[i]])); animator.clip=Loader.getRes(innerResouMap[clipPaths[0]]); var playOnWake=component.playOnWake; (playOnWake!==undefined)&& (animator.playOnWake=playOnWake); break ; case "Rigidbody":; var rigidbody=this.addComponent(Rigidbody); break ; case "SphereCollider":; var sphereCollider=this.addComponent(SphereCollider); sphereCollider.isTrigger=component.isTrigger; var center=sphereCollider.center; center.fromArray(component.center); sphereCollider.center=center; sphereCollider.radius=component.radius; break ; case "BoxCollider":; var boxCollider=this.addComponent(BoxCollider); boxCollider.isTrigger=component.isTrigger; boxCollider.center.fromArray(component.center); var size=boxCollider.size; size.fromArray(component.size); boxCollider.size=size; break ; case "MeshCollider":; var meshCollider=this.addComponent(MeshCollider); break ; default : } } } /** *@private */ __proto._onRootNodeHierarchyLoaded=function(animator,linkSprites){ for (var k in linkSprites){ var nodeOwner=this; var path=linkSprites[k]; for (var j=0,m=path.length;j < m;j++){ var p=path[j]; if (p===""){ break ; }else { nodeOwner=nodeOwner.getChildByName(p); if (!nodeOwner) break ; } } (nodeOwner)&& (animator.linkSprite3DToAvatarNode(k,nodeOwner)); } } /** *@private */ __proto._setHierarchyAnimator=function(animator,parentAnimator){ this._changeHierarchyAnimator(animator); for (var i=0,n=this._childs.length;i < n;i++){ var child=this._childs[i]; (child._hierarchyAnimator==parentAnimator)&& (child._setHierarchyAnimator(animator,parentAnimator)); } } /** *@private */ __proto._clearHierarchyAnimator=function(animator,parentAnimator){ this._changeHierarchyAnimator(parentAnimator); for (var i=0,n=this._childs.length;i < n;i++){ var child=this._childs[i]; (child._hierarchyAnimator==animator)&& (child._clearHierarchyAnimator(animator,parentAnimator)); } } /** *@private */ __proto._getAnimatorToLinkSprite3D=function(sprite3D,isLink,path){ var animator=this.getComponentByType(Animator); if (animator){ if (animator.avatar){ (animator.avatar._version)|| (sprite3D._setAnimatorToLinkAvatar(animator,isLink)); }else { sprite3D._setAnimatorToLinkSprite3DNoAvatar(animator,isLink,path); } } if (this._parent && (this._parent instanceof laya.d3.core.Sprite3D )){ path.unshift(this._parent.name); var p=this._parent; (p._hierarchyAnimator)&& (p._getAnimatorToLinkSprite3D(sprite3D,isLink,path)); } } /** *@private */ __proto._setAnimatorToLinkSprite3DNoAvatar=function(animator,isLink,path){ var i=0,n=0; for (i=0,n=animator.getClipCount();i < n;i++) animator._handleSpriteOwnersBySprite(i,isLink,path,this); for (i=0,n=this._childs.length;i < n;i++){ var child=this._childs[i]; var index=path.length; path.push(child.name); child._setAnimatorToLinkSprite3DNoAvatar(animator,isLink,path); path.splice(index,1); } } /** *@private */ __proto._changeHierarchyAnimator=function(animator){ this._hierarchyAnimator=animator; } /** *@private */ __proto._isLinkSpriteToAnimationNode=function(animator,node,isLink){ var nodeIndex=animator._avatarNodes.indexOf(node); var cacheSpriteToNodesMap=animator._cacheSpriteToNodesMap; if (isLink){ this._transform.dummy=node.transform; animator._cacheNodesToSpriteMap[nodeIndex]=cacheSpriteToNodesMap.length; cacheSpriteToNodesMap.push(nodeIndex); }else { this._transform.dummy=null; var index=animator._cacheNodesToSpriteMap[nodeIndex]; animator._cacheNodesToSpriteMap[nodeIndex]=null; cacheSpriteToNodesMap.splice(index,1); } } /** *@private */ __proto._setBelongScene=function(scene){ this._scene=scene; for (var i=0,n=this._childs.length;i < n;i++) (this._childs [i])._setBelongScene(scene); } /** *@private */ __proto._setUnBelongScene=function(){ this._scene=null; for (var i=0,n=this._childs.length;i < n;i++) (this._childs [i])._setUnBelongScene(); } /** *@private */ __proto._activeHierarchy=function(){ var i=0,n=0; this._activeInHierarchy=true; this._addSelfRenderObjects(); for (i=0,n=this._colliders.length;i < n;i++) this._layer._addCollider(this._colliders[i]); this.event(/*laya.events.Event.ACTIVE_IN_HIERARCHY_CHANGED*/"activeinhierarchychanged",true); for (i=0,n=this._childs.length;i < n;i++){ var child=this._childs [i]; (child._active)&& (child._activeHierarchy()); } } /** *@private */ __proto._inActiveHierarchy=function(){ var i=0,n=0; this._activeInHierarchy=false; this._clearSelfRenderObjects(); for (i=0,n=this._colliders.length;i < n;i++){ var col=this._colliders[i]; col._clearCollsionMap(); this._layer._removeCollider(col); } this.event(/*laya.events.Event.ACTIVE_IN_HIERARCHY_CHANGED*/"activeinhierarchychanged",false); for (i=0,n=this._childs.length;i < n;i++){ var child=this._childs [i]; (child._active)&& (child._inActiveHierarchy()); } } /** *@private */ __proto.addComponent=function(type){ var typeComponentIndex; var index=this._componentsMap.indexOf(type); if (index===-1){ typeComponentIndex=[]; this._componentsMap.push(type); this._typeComponentsIndices.push(typeComponentIndex); }else { typeComponentIndex=this._typeComponentsIndices[index]; if (this._components[typeComponentIndex[0]].isSingleton) throw new Error("无法单实例创建"+type+"组件"+","+type+"组件已存在!"); }; var component=ClassUtils.getInstance(type); typeComponentIndex.push(this._components.length); this._components.push(component); if ((component instanceof laya.d3.component.physics.Collider )){ var rigidbody=this.getComponentByType(Rigidbody); (rigidbody)&& ((component)._isRigidbody=true); (this._activeInHierarchy)&& (this._layer._addCollider(component)); this._colliders.push(component); }else if ((component instanceof laya.d3.component.Animator )){ var animator=component; this._setHierarchyAnimator(animator,this._parent ? (this._parent)._hierarchyAnimator :null); this._setAnimatorToLinkSprite3DNoAvatar(animator,true,/*new vector.<>*/[]); }else if ((component instanceof laya.d3.component.Rigidbody )){ for (var i=0,n=this._colliders.length;i < n;i++) this._colliders[i]._setIsRigidbody(true); } if ((component instanceof laya.d3.component.Script )) this._scripts.push(component); component._initialize(this); return component; } /** *@inheritDoc */ __proto._removeComponent=function(mapIndex,index){ var i=0,n=0; var componentIndices=this._typeComponentsIndices[mapIndex]; var componentIndex=componentIndices[index]; var component=this._components[componentIndex]; if ((component instanceof laya.d3.component.physics.Collider )){ var colliderComponent=component; (this._activeInHierarchy)&& (this._layer._removeCollider(colliderComponent)); this._colliders.splice(this._colliders.indexOf(colliderComponent),1); }else if ((component instanceof laya.d3.component.Animator )){ var animator=component; this._clearHierarchyAnimator(animator,this._parent ? (this._parent)._hierarchyAnimator :null); }else if ((component instanceof laya.d3.component.Rigidbody )){ for (i=0,n=this._colliders.length;i < n;i++){ var collider=this._colliders[i]; collider._setIsRigidbody(false); var runtimeCollisonMap=collider._runtimeCollisonMap; var runtimeCollisonTestMap=collider._runtimeCollisonTestMap; for (var k in runtimeCollisonMap) delete runtimeCollisonTestMap[k]; } } this._components.splice(componentIndex,1); if ((component instanceof laya.d3.component.Script )) this._scripts.splice(this._scripts.indexOf(component),1); componentIndices.splice(index,1); (componentIndices.length===0)&& (this._typeComponentsIndices.splice(mapIndex,1),this._componentsMap.splice(mapIndex,1)); for (i=0,n=this._componentsMap.length;i < n;i++){ componentIndices=this._typeComponentsIndices[i]; for (var j=componentIndices.length-1;j >=0;j--){ var oldComponentIndex=componentIndices[j]; if (oldComponentIndex > componentIndex) componentIndices[j]=--oldComponentIndex; else break ; } } component._destroy(); } /** *清理自身渲染物体,请重载此函数。 */ __proto._clearSelfRenderObjects=function(){} /** *添加自身渲染物体,请重载此函数。 */ __proto._addSelfRenderObjects=function(){} /** *@private */ __proto._parseCustomProps=function(rootNode,innerResouMap,customProps,nodeData){} /** *更新子节点。 *@param state 渲染相关状态。 */ __proto._updateChilds=function(state){ var n=this._childs.length; if (n===0)return; for (var i=0;i < n;++i) this._childs[i]._update((state)); } /** *排序函数。 *@param state 渲染相关状态。 */ __proto._getSortID=function(renderElement,material){ return material.id */*laya.d3.graphics.VertexDeclaration._maxVertexDeclarationBit*/1000+renderElement._getVertexBuffer().vertexDeclaration.id; } /** *更新 *@param state 渲染相关状态 */ __proto._update=function(state){ state.owner=this; if (this._activeInHierarchy){ this._updateComponents(state); this._lateUpdateComponents(state); Stat.spriteCount++; this._childs.length && this._updateChilds(state); } } /** *获取投影视图世界矩阵。 *@param projectionViewMatrix 投影视图矩阵。 *@return 投影视图世界矩阵。 */ __proto.getProjectionViewWorldMatrix=function(projectionViewMatrix){ Matrix4x4.multiply(projectionViewMatrix,this.transform.worldMatrix,this._projectionViewWorldMatrix); return this._projectionViewWorldMatrix; } /** *加载层级文件,并作为该节点的子节点。 *@param url */ __proto.loadHierarchy=function(url){ this.addChild(laya.d3.core.Sprite3D.load(url)); } /** *@inheritDoc */ __proto.addChildAt=function(node,index){ if (!((node instanceof laya.d3.core.Sprite3D ))) throw new Error("Sprite3D:Node type must Sprite3D."); if (!node || this.destroyed || node===this)return node; if ((node).zOrder)this._set$P("hasZorder",true); if (index >=0 && index <=this._childs.length){ if (node._parent===this){ var oldIndex=this.getChildIndex(node); this._childs.splice(oldIndex,1); this._childs.splice(index,0,node); if (this.conchModel){ this.conchModel.removeChild(node.conchModel); this.conchModel.addChildAt(node.conchModel,index); } this._childChanged(); }else { node.parent && node.parent.removeChild(node); this._childs===Node.ARRAY_EMPTY && (this._childs=[]); this._childs.splice(index,0,node); this.conchModel && this.conchModel.addChildAt(node.conchModel,index); node.parent=this; this._addChild3D(node); } return node; }else { throw new Error("appendChildAt:The index is out of bounds"); } } /** *@inheritDoc */ __proto.addChild=function(node){ if (!((node instanceof laya.d3.core.Sprite3D ))) throw new Error("Sprite3D:Node type must Sprite3D."); if (!node || this.destroyed || node===this)return node; if ((node).zOrder)this._set$P("hasZorder",true); if (node._parent===this){ var index=this.getChildIndex(node); if (index!==this._childs.length-1){ this._childs.splice(index,1); this._childs.push(node); if (this.conchModel){ this.conchModel.removeChild(node.conchModel); this.conchModel.addChildAt(node.conchModel,this._childs.length-1); } this._childChanged(); } }else { node.parent && node.parent.removeChild(node); this._childs===Node.ARRAY_EMPTY && (this._childs=[]); this._childs.push(node); this.conchModel && this.conchModel.addChildAt(node.conchModel,this._childs.length-1); node.parent=this; this._childChanged(); this._addChild3D(node); } return node; } /** *@inheritDoc */ __proto.removeChildAt=function(index){ var node=this.getChildAt(index); if (node){ this._removeChild3D(node); this._childs.splice(index,1); this.conchModel && this.conchModel.removeChild(node.conchModel); node.parent=null; } return node; } /** *@inheritDoc */ __proto.removeChildren=function(beginIndex,endIndex){ (beginIndex===void 0)&& (beginIndex=0); (endIndex===void 0)&& (endIndex=0x7fffffff); if (this._childs && this._childs.length > 0){ var childs=this._childs; if (beginIndex===0 && endIndex >=n){ var arr=childs; this._childs=Node.ARRAY_EMPTY; }else { arr=childs.splice(beginIndex,endIndex-beginIndex); } for (var i=0,n=arr.length;i < n;i++){ this._removeChild3D(arr [i]); arr[i].parent=null; this.conchModel && this.conchModel.removeChild(arr[i].conchModel); } } return this; } /** *@private */ __proto.onAsynLoaded=function(url,data,params){ var json=data[0]; if (json.type!=="Sprite3D") throw new Error("Sprite3D: The .lh file root type must be Sprite3D,please use other function to load this file."); var innerResouMap=data[1]; Utils3D._createNodeByJson(this,json,this,innerResouMap); this.event(/*laya.events.Event.HIERARCHY_LOADED*/"hierarchyloaded",[this]); this.__loaded=true; } /** *克隆。 *@param destObject 克隆源。 */ __proto.cloneTo=function(destObject){ if (this.destroyed) throw new Error("Sprite3D: Can't be cloned if the Sprite3D has destroyed."); var destSprite3D=destObject; destSprite3D.name=this.name; destSprite3D._destroyed=this._destroyed; destSprite3D.timer=this.timer; destSprite3D._$P=this._$P; destSprite3D.active=this._active; var destLocalPosition=destSprite3D.transform.localPosition; this.transform.localPosition.cloneTo(destLocalPosition); destSprite3D.transform.localPosition=destLocalPosition; var destLocalRotation=destSprite3D.transform.localRotation; this.transform.localRotation.cloneTo(destLocalRotation); destSprite3D.transform.localRotation=destLocalRotation; var destLocalScale=destSprite3D.transform.localScale; this.transform.localScale.cloneTo(destLocalScale); destSprite3D.transform.localScale=destLocalScale; destSprite3D.isStatic=this.isStatic; var i=0,n=0; for (i=0,n=this._componentsMap.length;i < n;i++){ var destComponent=destSprite3D.addComponent(this._componentsMap[i]); this._components[i]._cloneTo(destComponent); } for (i=0,n=this._childs.length;i < n;i++) destSprite3D.addChild(this._childs[i].clone()); var destAnimator=destSprite3D.getComponentByType(Animator); if (destAnimator){ var destLinkSpritesData=destAnimator._linkSpritesData; if (destLinkSpritesData){ for (var k in destLinkSpritesData){ var path=destLinkSpritesData[k]; var sp=destSprite3D; for (var j=0,m=path.length;j < m;j++){ sp=sp.getChildByName(path[j]); if (!sp) break ; } if (sp){ var node=destAnimator._avatarNodeMap[k]; sp._isLinkSpriteToAnimationNode(destAnimator,node,true); } } } } } /** *克隆。 *@return 克隆副本。 */ __proto.clone=function(){ var destSprite3D=/*__JS__ */new this.constructor(); this.cloneTo(destSprite3D); return destSprite3D; } /** *@inheritDoc */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); if (this.destroyed) return; laya.display.Node.prototype.destroy.call(this,destroyChild); var i=0,n=0; for (i=0,n=this._components.length;i < n;i++) this._components[i]._destroy(); this._components=null; this._componentsMap=null; this._typeComponentsIndices=null; this._transform=null; this._colliders=null; Loader.clearRes(this.url); (this.loaded)|| (Laya3D._cancelLoadByUrl(this.url)); } /** *@private */ __proto._handleSpriteToAvatar=function(animator,isLink){ var i=0,n=0; var avatarNodes=animator._avatarNodes; var node=animator._avatarNodeMap[this.name]; if (node && node.name===this.name && !this._transform.dummy) this._isLinkSpriteToAnimationNode(animator,node,isLink); } /** *@private */ __proto._setAnimatorToLinkAvatar=function(animator,isLink){ this._handleSpriteToAvatar(animator,isLink); for (var i=0,n=this._childs.length;i < n;i++){ var child=this._childs[i]; child._setAnimatorToLinkAvatar(animator,isLink); } } /** *获取在场景中是否激活。 *@return 在场景中是否激活。 */ __getset(0,__proto,'activeInHierarchy',function(){ return this._activeInHierarchy; }); /** *@private */ __getset(0,__proto,'_loaded',null,function(value){ this.__loaded=value; }); /** *设置是否激活。 *@param value 是否激活。 */ /** *获取自身是否激活。 *@return 自身是否激活。 */ __getset(0,__proto,'active',function(){ return this._active; },function(value){ if (this._active!==value){ this._active=value; if (this._parent){ if ((this._parent===this._scene && this._parent.displayedInStage)|| (this._parent)._activeInHierarchy){ if (value) this._activeHierarchy(); else this._inActiveHierarchy(); } } } }); /** *获得组件的数量。 *@return 组件数量。 */ __getset(0,__proto,'componentsCount',function(){ return this._components.length; }); /** *获取是否已加载完成。 */ __getset(0,__proto,'loaded',function(){ return this.__loaded; }); /** *获取唯一标识ID。 *@return 唯一标识ID。 */ __getset(0,__proto,'id',function(){ return this._id; }); /** *获取资源的URL地址。 *@return URL地址。 */ __getset(0,__proto,'url',function(){ return this._url; }); /** *设置蒙版。 *@param value 蒙版。 */ /** *获取蒙版。 *@return 蒙版。 */ __getset(0,__proto,'layer',function(){ return this._layer; },function(value){ if (this._layer!==value){ if (value){ if (this._activeInHierarchy){ var i=0,n=this._colliders.length; if (this._layer){ for (i=0;i < n;i++) this._layer._removeCollider(this._colliders[i]); } for (i=0;i < n;i++) value._addCollider(this._colliders[i]); } this._layer=value; this.event(/*laya.events.Event.LAYER_CHANGED*/"layerchanged",value); }else { throw new Error("Layer value can be null."); } } }); /** *获得所属场景。 *@return 场景。 */ __getset(0,__proto,'scene',function(){ return this._scene; }); /** *获取精灵变换。 */ __getset(0,__proto,'transform',function(){ return this._transform; }); Sprite3D.instantiate=function(original,parent,worldPositionStays,position,rotation){ (worldPositionStays===void 0)&& (worldPositionStays=true); var destSprite3D=original.clone(); (parent)&& (parent.addChild(destSprite3D)); var transform=destSprite3D.transform; if (worldPositionStays){ var worldMatrix=transform.worldMatrix; original.transform.worldMatrix.cloneTo(worldMatrix); transform.worldMatrix=worldMatrix; }else { (position)&& (transform.position=position); (rotation)&& (transform.rotation=rotation); } return destSprite3D; } Sprite3D.load=function(url){ return Laya.loader.create(url,null,null,Sprite3D); } Sprite3D.WORLDMATRIX=0; Sprite3D.MVPMATRIX=1; Sprite3D._uniqueIDCounter=0; Sprite3D._nameNumberCounter=0; return Sprite3D; })(ComponentNode) /** *BlinnPhongMaterial 类用于实现Blinn-Phong材质。 */ //class laya.d3.core.material.BlinnPhongMaterial extends laya.d3.core.material.BaseMaterial var BlinnPhongMaterial=(function(_super){ function BlinnPhongMaterial(){ /**@private */ //this._albedoColor=null; /**@private */ //this._albedoIntensity=NaN; /**@private */ //this._enableLighting=false; BlinnPhongMaterial.__super.call(this); this.setShaderName("BLINNPHONG"); this._albedoIntensity=1.0; this._albedoColor=new Vector4(1.0,1.0,1.0,1.0); this._setColor(6,new Vector4(1.0,1.0,1.0,1.0)); this._setColor(8,new Vector3(1.0,1.0,1.0)); this._setNumber(9,0.078125); this._setColor(10,new Vector3(1.0,1.0,1.0)); this._setNumber(0,0.5); this._setColor(11,new Vector4(1.0,1.0,0.0,0.0)); this._enableLighting=true; this.renderMode=0; } __class(BlinnPhongMaterial,'laya.d3.core.material.BlinnPhongMaterial',_super); var __proto=BlinnPhongMaterial.prototype; /** *禁用灯光。 */ __proto.disableLight=function(){ this._addDisablePublicShaderDefine(ShaderCompile3D.SHADERDEFINE_POINTLIGHT | ShaderCompile3D.SHADERDEFINE_SPOTLIGHT | ShaderCompile3D.SHADERDEFINE_DIRECTIONLIGHT); } /** *禁用雾化。 */ __proto.disableFog=function(){ this._addDisablePublicShaderDefine(ShaderCompile3D.SHADERDEFINE_FOG); } /** *@inheritDoc */ __proto.cloneTo=function(destObject){ _super.prototype.cloneTo.call(this,destObject); var destMaterial=destObject; destMaterial._enableLighting=this._enableLighting; destMaterial._albedoIntensity=this._albedoIntensity; this._albedoColor.cloneTo(destMaterial._albedoColor); } /** *设置渲染模式。 *@return 渲染模式。 */ __getset(0,__proto,'renderMode',null,function(value){ switch (value){ case 0: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=true; this.cull=2; this.blend=0; this.alphaTest=false; this.depthTest=0x0201; this._removeShaderDefine(BlinnPhongMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 1: this.depthWrite=true; this.cull=2; this.blend=0; this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.alphaTest=true; this.depthTest=0x0201; this._removeShaderDefine(BlinnPhongMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 2: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=false; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; this.alphaTest=false; this.depthTest=0x0201; this._removeShaderDefine(BlinnPhongMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 3: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=false; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; this.alphaTest=false; this.depthTest=0x0201; this._addShaderDefine(BlinnPhongMaterial.SHADERDEFINE_ADDTIVEFOG); break ; default : throw new Error("Material:renderMode value error."); } this._conchMaterial && this._conchMaterial.setRenderMode(value); }); /** *设置法线贴图。 *@param value 法线贴图。 */ /** *获取法线贴图。 *@return 法线贴图。 */ __getset(0,__proto,'normalTexture',function(){ return this._getTexture(2); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.BlinnPhongMaterial.SHADERDEFINE_NORMALMAP); else this._removeShaderDefine(laya.d3.core.material.BlinnPhongMaterial.SHADERDEFINE_NORMALMAP); this._setTexture(2,value); }); /** *设置反射颜色。 *@param value 反射颜色。 */ /** *获取反射颜色。 *@return value 反射颜色。 */ __getset(0,__proto,'reflectColor',function(){ return this._getColor(10); },function(value){ this._setColor(10,value); }); /** *获取纹理平铺和偏移。 *@param value 纹理平铺和偏移。 */ /** *获取纹理平铺和偏移。 *@return 纹理平铺和偏移。 */ __getset(0,__proto,'tilingOffset',function(){ return this._getColor(11); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(laya.d3.core.material.BlinnPhongMaterial.SHADERDEFINE_TILINGOFFSET); else this._removeShaderDefine(laya.d3.core.material.BlinnPhongMaterial.SHADERDEFINE_TILINGOFFSET); }else { this._removeShaderDefine(laya.d3.core.material.BlinnPhongMaterial.SHADERDEFINE_TILINGOFFSET); } this._setColor(11,value); }); /** *设置高光颜色。 *@param value 高光颜色。 */ /** *获取高光颜色。 *@return 高光颜色。 */ __getset(0,__proto,'specularColor',function(){ return this._getColor(8); },function(value){ this._setColor(8,value); }); /** *设置漫反射颜色。 *@param value 漫反射颜色。 */ /** *获取漫反射颜色。 *@return 漫反射颜色。 */ __getset(0,__proto,'albedoColor',function(){ return this._albedoColor; },function(value){ var finalAlbedo=this._getColor(6); Vector4.scale(value,this._albedoIntensity,finalAlbedo); this._albedoColor=value; }); /** *设置漫反射颜色。 *@param value 漫反射颜色。 */ /** *获取漫反射颜色。 *@return 漫反射颜色。 */ __getset(0,__proto,'albedoIntensity',function(){ return this._albedoIntensity; },function(value){ if (this._albedoIntensity!==value){ var finalAlbedo=this._getColor(6); Vector4.scale(this._albedoColor,value,finalAlbedo); this._albedoIntensity=value; } }); /** *设置漫反射贴图。 *@param value 漫反射贴图。 */ /** *获取漫反射贴图。 *@return 漫反射贴图。 */ __getset(0,__proto,'albedoTexture',function(){ return this._getTexture(1); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.BlinnPhongMaterial.SHADERDEFINE_DIFFUSEMAP); else this._removeShaderDefine(laya.d3.core.material.BlinnPhongMaterial.SHADERDEFINE_DIFFUSEMAP); this._setTexture(1,value); }); /** *设置高光强度,范围为0到1。 *@param value 高光强度。 */ /** *获取高光强度,范围为0到1。 *@return 高光强度。 */ __getset(0,__proto,'shininess',function(){ return this._getNumber(9); },function(value){ value=Math.max(0.0,Math.min(1.0,value)); this._setNumber(9,value); }); /** *设置高光贴图,高光强度则从该贴图RGB值中获取,如果该值为空则从漫反射贴图的Alpha通道获取。 *@param value 高光贴图。 */ /** *获取高光贴图。 *@return 高光贴图。 */ __getset(0,__proto,'specularTexture',function(){ return this._getTexture(3); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.BlinnPhongMaterial.SHADERDEFINE_SPECULARMAP); else this._removeShaderDefine(laya.d3.core.material.BlinnPhongMaterial.SHADERDEFINE_SPECULARMAP); this._setTexture(3,value); }); /** *设置反射贴图。 *@param value 反射贴图。 */ /** *获取反射贴图。 *@return 反射贴图。 */ __getset(0,__proto,'reflectTexture',function(){ return this._getTexture(5); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.BlinnPhongMaterial.SHADERDEFINE_REFLECTMAP); else this._removeShaderDefine(laya.d3.core.material.BlinnPhongMaterial.SHADERDEFINE_REFLECTMAP); this._setTexture(5,value); }); /** *设置是否启用光照。 *@param value 是否启用光照。 */ /** *获取是否启用光照。 *@return 是否启用光照。 */ __getset(0,__proto,'enableLighting',function(){ return this._enableLighting; },function(value){ if (this._enableLighting!==value){ if (value) this._removeDisablePublicShaderDefine(ShaderCompile3D.SHADERDEFINE_POINTLIGHT | ShaderCompile3D.SHADERDEFINE_SPOTLIGHT | ShaderCompile3D.SHADERDEFINE_DIRECTIONLIGHT); else this._addDisablePublicShaderDefine(ShaderCompile3D.SHADERDEFINE_POINTLIGHT | ShaderCompile3D.SHADERDEFINE_SPOTLIGHT | ShaderCompile3D.SHADERDEFINE_DIRECTIONLIGHT); this._enableLighting=value; } }); BlinnPhongMaterial.__init__=function(){ BlinnPhongMaterial.SHADERDEFINE_DIFFUSEMAP=BlinnPhongMaterial.shaderDefines.registerDefine("DIFFUSEMAP"); BlinnPhongMaterial.SHADERDEFINE_NORMALMAP=BlinnPhongMaterial.shaderDefines.registerDefine("NORMALMAP"); BlinnPhongMaterial.SHADERDEFINE_SPECULARMAP=BlinnPhongMaterial.shaderDefines.registerDefine("SPECULARMAP"); BlinnPhongMaterial.SHADERDEFINE_REFLECTMAP=BlinnPhongMaterial.shaderDefines.registerDefine("REFLECTMAP"); BlinnPhongMaterial.SHADERDEFINE_TILINGOFFSET=BlinnPhongMaterial.shaderDefines.registerDefine("TILINGOFFSET"); BlinnPhongMaterial.SHADERDEFINE_ADDTIVEFOG=BlinnPhongMaterial.shaderDefines.registerDefine("ADDTIVEFOG"); } BlinnPhongMaterial.load=function(url){ return Laya.loader.create(url,null,null,BlinnPhongMaterial); } BlinnPhongMaterial.SPECULARSOURCE_DIFFUSEMAPALPHA=0; BlinnPhongMaterial.SPECULARSOURCE_SPECULARMAP=0; BlinnPhongMaterial.RENDERMODE_OPAQUE=0; BlinnPhongMaterial.RENDERMODE_CUTOUT=1; BlinnPhongMaterial.RENDERMODE_TRANSPARENT=2; BlinnPhongMaterial.RENDERMODE_ADDTIVE=3; BlinnPhongMaterial.SHADERDEFINE_DIFFUSEMAP=0; BlinnPhongMaterial.SHADERDEFINE_NORMALMAP=0; BlinnPhongMaterial.SHADERDEFINE_SPECULARMAP=0; BlinnPhongMaterial.SHADERDEFINE_REFLECTMAP=0; BlinnPhongMaterial.SHADERDEFINE_TILINGOFFSET=0; BlinnPhongMaterial.SHADERDEFINE_ADDTIVEFOG=0; BlinnPhongMaterial.ALBEDOTEXTURE=1; BlinnPhongMaterial.NORMALTEXTURE=2; BlinnPhongMaterial.SPECULARTEXTURE=3; BlinnPhongMaterial.EMISSIVETEXTURE=4; BlinnPhongMaterial.REFLECTTEXTURE=5; BlinnPhongMaterial.ALBEDOCOLOR=6; BlinnPhongMaterial.MATERIALSPECULAR=8; BlinnPhongMaterial.SHININESS=9; BlinnPhongMaterial.MATERIALREFLECT=10; BlinnPhongMaterial.TILINGOFFSET=11; __static(BlinnPhongMaterial, ['defaultMaterial',function(){return this.defaultMaterial=new BlinnPhongMaterial();},'shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return BlinnPhongMaterial; })(BaseMaterial) /** *... *@author ... */ //class laya.d3.core.material.ExtendTerrainMaterial extends laya.d3.core.material.BaseMaterial var ExtendTerrainMaterial=(function(_super){ //NATIVE function ExtendTerrainMaterial(){ ExtendTerrainMaterial.__super.call(this); this.setShaderName("ExtendTerrain"); this.renderMode=1; } __class(ExtendTerrainMaterial,'laya.d3.core.material.ExtendTerrainMaterial',_super); var __proto=ExtendTerrainMaterial.prototype; __proto._setDetailNum=function(value){ switch (value){ case 1: this._addShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5); break ; case 2: this._addShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5); break ; case 3: this._addShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5); break ; case 4: this._addShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5); break ; case 5: this._addShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3); this._removeShaderDefine(laya.d3.core.material.ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4); break ; } } /** *设置禁受光照影响。 */ __proto.disableLight=function(){ this._addDisablePublicShaderDefine(ShaderCompile3D.SHADERDEFINE_POINTLIGHT | ShaderCompile3D.SHADERDEFINE_SPOTLIGHT | ShaderCompile3D.SHADERDEFINE_DIRECTIONLIGHT); } __getset(0,__proto,'diffuseScaleOffset2',null,function(scaleOffset2){ this._setColor(7,scaleOffset2); }); /** *设置splatAlpha贴图。 *@param value splatAlpha贴图。 */ /** *获取splatAlpha贴图。 *@return splatAlpha贴图。 */ __getset(0,__proto,'splatAlphaTexture',function(){ return this._getTexture(0); },function(value){ this._setTexture(0,value); }); __getset(0,__proto,'diffuseScaleOffset3',null,function(scaleOffset3){ this._setColor(8,scaleOffset3); }); /** *设置第一层贴图。 *@param value 第一层贴图。 */ __getset(0,__proto,'diffuseTexture1',null,function(value){ this._setTexture(1,value); this._setDetailNum(1); }); /** *设置渲染模式。 *@return 渲染模式。 */ __getset(0,__proto,'renderMode',null,function(value){ switch (value){ case 1: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=true; this.cull=2; this.blend=0; this.depthTest=0x0201; break ; case 2: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=false; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; this.depthTest=0x0203; break ; default : throw new Error("ExtendTerrainMaterial:renderMode value error."); } this._conchMaterial && this._conchMaterial.setRenderMode(value); }); /** *设置第二层贴图。 *@param value 第二层贴图。 */ /** *获取第二层贴图。 *@return 第二层贴图。 */ __getset(0,__proto,'diffuseTexture2',function(){ return this._getTexture(2); },function(value){ this._setTexture(2,value); this._setDetailNum(2); }); __getset(0,__proto,'diffuseScaleOffset1',null,function(scaleOffset1){ this._setColor(6,scaleOffset1); }); /** *设置第三层贴图。 *@param value 第三层贴图。 */ /** *获取第三层贴图。 *@return 第三层贴图。 */ __getset(0,__proto,'diffuseTexture3',function(){ return this._getTexture(3); },function(value){ this._setTexture(3,value); this._setDetailNum(3); }); /** *设置第四层贴图。 *@param value 第四层贴图。 */ /** *获取第四层贴图。 *@return 第四层贴图。 */ __getset(0,__proto,'diffuseTexture4',function(){ return this._getTexture(4); },function(value){ this._setTexture(4,value); this._setDetailNum(4); }); /** *设置第五层贴图。 *@param value 第五层贴图。 */ /** *获取第五层贴图。 *@return 第五层贴图。 */ __getset(0,__proto,'diffuseTexture5',function(){ return this._getTexture(5); },function(value){ this._setTexture(5,value); this._setDetailNum(5); }); __getset(0,__proto,'diffuseScaleOffset4',null,function(scaleOffset4){ this._setColor(9,scaleOffset4); }); __getset(0,__proto,'diffuseScaleOffset5',null,function(scaleOffset5){ this._setColor(10,scaleOffset5); }); /** *设置反射率颜色。 *@param value 反射率颜色。 */ /** *获取反射率颜色。 *@return 反射率颜色。 */ __getset(0,__proto,'albedo',function(){ return this._getColor(14); },function(value){ this._setColor(14,value); }); /** *设置环境光颜色。 *@param value 环境光颜色 */ /** *获取环境光颜色。 *@return 环境光颜色。 */ __getset(0,__proto,'ambientColor',function(){ return this._getColor(11); },function(value){ this._setColor(11,value); }); /** *设置漫反射颜色。 *@param value 漫反射颜色。 */ /** *获取漫反射颜色。 *@return 漫反射颜色。 */ __getset(0,__proto,'diffuseColor',function(){ return this._getColor(12); },function(value){ this._setColor(12,value); }); /** *设置高光颜色。 *@param value 高光颜色。 */ /** *获取高光颜色。 *@return 高光颜色。 */ __getset(0,__proto,'specularColor',function(){ return this._getColor(13); },function(value){ this._setColor(13,value); }); ExtendTerrainMaterial.__init__=function(){ ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1=ExtendTerrainMaterial.shaderDefines.registerDefine("ExtendTerrain_DETAIL_NUM1"); ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2=ExtendTerrainMaterial.shaderDefines.registerDefine("ExtendTerrain_DETAIL_NUM2"); ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3=ExtendTerrainMaterial.shaderDefines.registerDefine("ExtendTerrain_DETAIL_NUM3"); ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4=ExtendTerrainMaterial.shaderDefines.registerDefine("ExtendTerrain_DETAIL_NUM4"); ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5=ExtendTerrainMaterial.shaderDefines.registerDefine("ExtendTerrain_DETAIL_NUM5"); } ExtendTerrainMaterial.RENDERMODE_OPAQUE=1; ExtendTerrainMaterial.RENDERMODE_TRANSPARENT=2; ExtendTerrainMaterial.SPLATALPHATEXTURE=0; ExtendTerrainMaterial.DIFFUSETEXTURE1=1; ExtendTerrainMaterial.DIFFUSETEXTURE2=2; ExtendTerrainMaterial.DIFFUSETEXTURE3=3; ExtendTerrainMaterial.DIFFUSETEXTURE4=4; ExtendTerrainMaterial.DIFFUSETEXTURE5=5; ExtendTerrainMaterial.DIFFUSESCALEOFFSET1=6; ExtendTerrainMaterial.DIFFUSESCALEOFFSET2=7; ExtendTerrainMaterial.DIFFUSESCALEOFFSET3=8; ExtendTerrainMaterial.DIFFUSESCALEOFFSET4=9; ExtendTerrainMaterial.DIFFUSESCALEOFFSET5=10; ExtendTerrainMaterial.MATERIALAMBIENT=11; ExtendTerrainMaterial.MATERIALDIFFUSE=12; ExtendTerrainMaterial.MATERIALSPECULAR=13; ExtendTerrainMaterial.MATERIALALBEDO=14; ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM1=0; ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM2=0; ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM3=0; ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM4=0; ExtendTerrainMaterial.SHADERDEFINE_DETAIL_NUM5=0; __static(ExtendTerrainMaterial, ['shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return ExtendTerrainMaterial; })(BaseMaterial) /** *... *@author ... */ //class laya.d3.core.material.GlitterMaterial extends laya.d3.core.material.BaseMaterial var GlitterMaterial=(function(_super){ function GlitterMaterial(){ GlitterMaterial.__super.call(this); this.setShaderName("GLITTER"); this.renderMode=1; this._setColor(3,new Vector4(1.0,1.0,1.0,1.0)); this._setColor(2,new Vector4(1.0,1.0,1.0,1.0)); } __class(GlitterMaterial,'laya.d3.core.material.GlitterMaterial',_super); var __proto=GlitterMaterial.prototype; /** *@inheritDoc */ __proto.setShaderName=function(name){ _super.prototype.setShaderName.call(this,name); } /** *设置渲染模式。 *@return 渲染模式。 */ __getset(0,__proto,'renderMode',null,function(value){ switch (value){ case 1: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=true; this.cull=2; this.blend=0; break ; case 2: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=true; this.cull=0; this.blend=0; break ; case 13: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=true; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; break ; case 14: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=true; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; break ; case 15: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=true; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; break ; case 16: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=true; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; break ; case 5: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=false; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; break ; case 6: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=false; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; break ; case 7: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=false; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; break ; case 8: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=false; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; break ; case 9: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthTest=0x0201; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; break ; case 10: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthTest=0x0201; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; break ; case 11: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthTest=0x0201; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; break ; case 12: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthTest=0x0201; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; break ; default : throw new Error("Material:renderMode value error."); } this._conchMaterial && this._conchMaterial.setRenderMode(value); }); /** *设置漫反射贴图。 *@param value 漫反射贴图。 */ /** *获取漫反射贴图。 *@return 漫反射贴图。 */ __getset(0,__proto,'diffuseTexture',function(){ return this._getTexture(1); },function(value){ this._setTexture(1,value); }); /** *设置反射率。 *@param value 反射率。 */ /** *获取反射率。 *@return 反射率。 */ __getset(0,__proto,'albedo',function(){ return this._getColor(2); },function(value){ this._setColor(2,value); }); /** *设置颜色。 *@param value 颜色。 */ /** *获取颜色。 *@return 漫反射颜色。 */ __getset(0,__proto,'color',function(){ return this._getColor(3); },function(value){ this._setColor(3,value); }); GlitterMaterial.load=function(url){ return Laya.loader.create(url,null,null,GlitterMaterial); } GlitterMaterial.RENDERMODE_OPAQUE=1; GlitterMaterial.RENDERMODE_OPAQUEDOUBLEFACE=2; GlitterMaterial.RENDERMODE_TRANSPARENT=13; GlitterMaterial.RENDERMODE_TRANSPARENTDOUBLEFACE=14; GlitterMaterial.RENDERMODE_ADDTIVE=15; GlitterMaterial.RENDERMODE_ADDTIVEDOUBLEFACE=16; GlitterMaterial.RENDERMODE_DEPTHREAD_TRANSPARENT=5; GlitterMaterial.RENDERMODE_DEPTHREAD_TRANSPARENTDOUBLEFACE=6; GlitterMaterial.RENDERMODE_DEPTHREAD_ADDTIVE=7; GlitterMaterial.RENDERMODE_DEPTHREAD_ADDTIVEDOUBLEFACE=8; GlitterMaterial.RENDERMODE_NONDEPTH_TRANSPARENT=9; GlitterMaterial.RENDERMODE_NONDEPTH_TRANSPARENTDOUBLEFACE=10; GlitterMaterial.RENDERMODE_NONDEPTH_ADDTIVE=11; GlitterMaterial.RENDERMODE_NONDEPTH_ADDTIVEDOUBLEFACE=12; GlitterMaterial.DIFFUSETEXTURE=1; GlitterMaterial.ALBEDO=2; GlitterMaterial.UNICOLOR=3; __static(GlitterMaterial, ['defaultMaterial',function(){return this.defaultMaterial=new GlitterMaterial();} ]); return GlitterMaterial; })(BaseMaterial) //class laya.d3.shader.Shader3D extends laya.webgl.shader.BaseShader var Shader3D=(function(_super){ function Shader3D(vs,ps,attributeMap,sceneUniformMap,cameraUniformMap,spriteUniformMap,materialUniformMap,renderElementUniformMap){ //this._attributeMap=null; //this._sceneUniformMap=null; //this._cameraUniformMap=null; //this._spriteUniformMap=null; //this._materialUniformMap=null; //this._renderElementUniformMap=null; //this._vs=null; //this._ps=null; this._curActTexIndex=0; //this._reCompile=false; //this._vshader=null; //this._pshader=null; this._program=null; this._attributeParams=null; this._uniformParams=null; this._attributeParamsMap=[]; this._sceneUniformParamsMap=[]; this._cameraUniformParamsMap=[]; this._spriteUniformParamsMap=[]; this._materialUniformParamsMap=[]; this._renderElementUniformParamsMap=[]; //this._id=0; /**@private */ //this._uploadLoopCount=0; /**@private */ //this._uploadRenderElement=null; /**@private */ //this._uploadMaterial=null; /**@private */ //this._uploadSprite3D=null; /**@private */ //this._uploadCamera=null; /**@private */ //this._uploadScene=null; /**@private */ //this._uploadVertexBuffer=null; Shader3D.__super.call(this); if ((!vs)|| (!ps))throw "Shader Error"; this._id=++Shader3D._count; this._vs=vs; this._ps=ps; this._attributeMap=attributeMap; this._sceneUniformMap=sceneUniformMap; this._cameraUniformMap=cameraUniformMap; this._spriteUniformMap=spriteUniformMap; this._materialUniformMap=materialUniformMap; this._renderElementUniformMap=renderElementUniformMap; this.recreateResource(); } __class(Shader3D,'laya.d3.shader.Shader3D',_super); var __proto=Shader3D.prototype; __proto.recreateResource=function(){ this._compile(); this.completeCreate(); this.memorySize=0; } //忽略尺寸尺寸 __proto.disposeResource=function(){ WebGL.mainContext.deleteShader(this._vshader); WebGL.mainContext.deleteShader(this._pshader); WebGL.mainContext.deleteProgram(this._program); this._vshader=this._pshader=this._program=null; this._attributeParams=null; this._uniformParams=null; this.memorySize=0; this._curActTexIndex=0; } __proto._compile=function(){ if (!this._vs || !this._ps || this._attributeParams || this._uniformParams) return; this._reCompile=true; this._attributeParams=[]; this._uniformParams=[]; var text=[this._vs,this._ps]; var result; var gl=WebGL.mainContext; this._program=gl.createProgram(); this._vshader=Shader3D._createShader(gl,text[0],/*laya.webgl.WebGLContext.VERTEX_SHADER*/0x8B31); this._pshader=Shader3D._createShader(gl,text[1],/*laya.webgl.WebGLContext.FRAGMENT_SHADER*/0x8B30); gl.attachShader(this._program,this._vshader); gl.attachShader(this._program,this._pshader); gl.linkProgram(this._program); if (!Render.isConchApp && ShaderCompile3D.debugMode && !gl.getProgramParameter(this._program,/*laya.webgl.WebGLContext.LINK_STATUS*/0x8B82)) throw gl.getProgramInfoLog(this._program); var one,i=0,j=0,n=0,location; var attribNum=0; if (Render.isConchApp){ attribNum=gl.getProgramParameterEx(this._vs,this._ps,"",/*laya.webgl.WebGLContext.ACTIVE_ATTRIBUTES*/0x8B89); } else{ attribNum=gl.getProgramParameter(this._program,/*laya.webgl.WebGLContext.ACTIVE_ATTRIBUTES*/0x8B89); } for (i=0;i < attribNum;i++){ var attrib=null; if (Render.isConchApp){ attrib=gl.getActiveAttribEx(this._vs,this._ps,"",i); } else{ attrib=gl.getActiveAttrib(this._program,i); } location=gl.getAttribLocation(this._program,attrib.name); one={vartype:"attribute",ivartype:0,attrib:attrib,location:location,name:attrib.name,type:attrib.type,isArray:false,isSame:false,preValue:null,indexOfParams:0}; this._attributeParams.push(one); }; var nUniformNum=0; if (Render.isConchApp){ nUniformNum=gl.getProgramParameterEx(this._vs,this._ps,"",/*laya.webgl.WebGLContext.ACTIVE_UNIFORMS*/0x8B86); } else{ nUniformNum=gl.getProgramParameter(this._program,/*laya.webgl.WebGLContext.ACTIVE_UNIFORMS*/0x8B86); } for (i=0;i < nUniformNum;i++){ var uniform=null; if (Render.isConchApp){ uniform=gl.getActiveUniformEx(this._vs,this._ps,"",i); } else{ uniform=gl.getActiveUniform(this._program,i); } location=gl.getUniformLocation(this._program,uniform.name); one={vartype:"uniform",ivartype:1,attrib:attrib,location:location,name:uniform.name,type:uniform.type,isArray:false,isSame:false,preValue:null,indexOfParams:0}; if (one.name.indexOf('[0]')> 0){ one.name=one.name.substr(0,one.name.length-3); one.isArray=true; one.location=gl.getUniformLocation(this._program,one.name); } this._uniformParams.push(one); } for (i=0,n=this._attributeParams.length;i < n;i++){ one=this._attributeParams[i]; one.indexOfParams=i; one.index=1; one.value=[one.location,null]; one.codename=one.name; one.name=(this._attributeMap[one.codename] !=null)? this._attributeMap[one.codename] :one.codename; this._attributeParamsMap.push(one.name); this._attributeParamsMap.push(one); one._this=this; one.uploadedValue=[]; one.fun=this._attribute; } for (i=0,n=this._uniformParams.length;i < n;i++){ one=this._uniformParams[i]; one.indexOfParams=i; one.index=1; one.value=[one.location,null]; one.codename=one.name; if (this._sceneUniformMap[one.codename] !=null){ one.name=this._sceneUniformMap[one.codename]; this._sceneUniformParamsMap.push(one.name); this._sceneUniformParamsMap.push(one); }else if (this._cameraUniformMap[one.codename] !=null){ one.name=this._cameraUniformMap[one.codename]; this._cameraUniformParamsMap.push(one.name); this._cameraUniformParamsMap.push(one); }else if (this._spriteUniformMap[one.codename] !=null){ one.name=this._spriteUniformMap[one.codename]; this._spriteUniformParamsMap.push(one.name); this._spriteUniformParamsMap.push(one); }else if (this._materialUniformMap[one.codename] !=null){ one.name=this._materialUniformMap[one.codename]; this._materialUniformParamsMap.push(one.name); this._materialUniformParamsMap.push(one); }else if (this._renderElementUniformMap[one.codename] !=null){ one.name=this._renderElementUniformMap[one.codename]; this._renderElementUniformParamsMap.push(one.name); this._renderElementUniformParamsMap.push(one); }else { console.log("Shader:can't find uinform name:"+one.codename+" in shader file."); } one._this=this; one.uploadedValue=[]; switch (one.type){ case /*laya.webgl.WebGLContext.INT*/0x1404: one.fun=one.isArray ? this._uniform1iv :this._uniform1i; break ; case /*laya.webgl.WebGLContext.FLOAT*/0x1406: one.fun=one.isArray ? this._uniform1fv :this._uniform1f; break ; case /*laya.webgl.WebGLContext.FLOAT_VEC2*/0x8B50: one.fun=one.isArray ? this._uniform_vec2v :this._uniform_vec2; break ; case /*laya.webgl.WebGLContext.FLOAT_VEC3*/0x8B51: one.fun=one.isArray ? this._uniform_vec3v :this._uniform_vec3; break ; case /*laya.webgl.WebGLContext.FLOAT_VEC4*/0x8B52: one.fun=one.isArray ? this._uniform_vec4v :this._uniform_vec4; break ; case /*laya.webgl.WebGLContext.SAMPLER_2D*/0x8B5E: one.fun=this._uniform_sampler2D; break ; case /*laya.webgl.WebGLContext.SAMPLER_CUBE*/0x8B60: one.fun=this._uniform_samplerCube; break ; case /*laya.webgl.WebGLContext.FLOAT_MAT4*/0x8B5C: one.fun=this._uniformMatrix4fv; break ; case /*laya.webgl.WebGLContext.BOOL*/0x8B56: one.fun=this._uniform1i; break ; case /*laya.webgl.WebGLContext.FLOAT_MAT2*/0x8B5A: one.fun=this._uinformMatrix2fv; break ; case /*laya.webgl.WebGLContext.FLOAT_MAT3*/0x8B5B: one.fun=this._uinformMatrix3fv; break ; default : throw new Error("compile shader err!"); break ; } } } __proto._attribute=function(one,value){ var gl=WebGL.mainContext; var enableAtributes=Buffer._enableAtributes; var location=one.location; (enableAtributes[location])|| (gl.enableVertexAttribArray(location)); gl.vertexAttribPointer(location,value[0],value[1],value[2],value[3],value[4]); enableAtributes[location]=Buffer._bindVertexBuffer; return 1; } __proto._uniform1f=function(one,value){ var uploadedValue=one.uploadedValue; if (uploadedValue[0]!==value){ WebGL.mainContext.uniform1f(one.location,uploadedValue[0]=value); return 1; } return 0; } __proto._uniform1fv=function(one,value){ if (value.length < 4){ var uploadedValue=one.uploadedValue; if (uploadedValue[0]!==value[0] || uploadedValue[1]!==value[1] || uploadedValue[2]!==value[2] || uploadedValue[3]!==value[3]){ WebGL.mainContext.uniform1fv(one.location,value); uploadedValue[0]=value[0]; uploadedValue[1]=value[1]; uploadedValue[2]=value[2]; uploadedValue[3]=value[3]; return 1; } return 0; }else { WebGL.mainContext.uniform1fv(one.location,value); return 1; } } __proto._uniform_vec2=function(one,value){ var uploadedValue=one.uploadedValue; if (uploadedValue[0]!==value[0] || uploadedValue[1]!==value[1]){ WebGL.mainContext.uniform2f(one.location,uploadedValue[0]=value[0],uploadedValue[1]=value[1]); return 1; } return 0; } __proto._uniform_vec2v=function(one,value){ if (value.length < 2){ var uploadedValue=one.uploadedValue; if (uploadedValue[0]!==value[0] || uploadedValue[1]!==value[1] || uploadedValue[2]!==value[2] || uploadedValue[3]!==value[3]){ WebGL.mainContext.uniform2fv(one.location,value); uploadedValue[0]=value[0]; uploadedValue[1]=value[1]; uploadedValue[2]=value[2]; uploadedValue[3]=value[3]; return 1; } return 0; }else { WebGL.mainContext.uniform2fv(one.location,value); return 1; } } __proto._uniform_vec3=function(one,value){ var uploadedValue=one.uploadedValue; if (uploadedValue[0]!==value[0] || uploadedValue[1]!==value[1] || uploadedValue[2]!==value[2]){ WebGL.mainContext.uniform3f(one.location,uploadedValue[0]=value[0],uploadedValue[1]=value[1],uploadedValue[2]=value[2]); return 1; } return 0; } __proto._uniform_vec3v=function(one,value){ WebGL.mainContext.uniform3fv(one.location,value); return 1; } __proto._uniform_vec4=function(one,value){ var uploadedValue=one.uploadedValue; if (uploadedValue[0]!==value[0] || uploadedValue[1]!==value[1] || uploadedValue[2]!==value[2] || uploadedValue[3]!==value[3]){ WebGL.mainContext.uniform4f(one.location,uploadedValue[0]=value[0],uploadedValue[1]=value[1],uploadedValue[2]=value[2],uploadedValue[3]=value[3]); return 1; } return 0; } __proto._uniform_vec4v=function(one,value){ WebGL.mainContext.uniform4fv(one.location,value); return 1; } __proto._uniformMatrix2fv=function(one,value){ WebGL.mainContext.uniformMatrix2fv(one.location,false,value); return 1; } __proto._uniformMatrix3fv=function(one,value){ WebGL.mainContext.uniformMatrix3fv(one.location,false,value); return 1; } __proto._uniformMatrix4fv=function(one,value){ WebGL.mainContext.uniformMatrix4fv(one.location,false,value); return 1; } __proto._uinformMatrix2fv=function(one,value){ WebGL.mainContext.uniformMatrix2fv(one.location,false,value); return 1; } __proto._uinformMatrix3fv=function(one,value){ WebGL.mainContext.uniformMatrix3fv(one.location,false,value); return 1; } __proto._uniform1i=function(one,value){ var uploadedValue=one.uploadedValue; if (uploadedValue[0]!==value){ WebGL.mainContext.uniform1i(one.location,uploadedValue[0]=value); return 1; } return 0; } __proto._uniform1iv=function(one,value){ WebGL.mainContext.uniform1iv(one.location,value); return 1; } __proto._uniform_ivec2=function(one,value){ var uploadedValue=one.uploadedValue; if (uploadedValue[0]!==value[0] || uploadedValue[1]!==value[1]){ WebGL.mainContext.uniform2i(one.location,uploadedValue[0]=value[0],uploadedValue[1]=value[1]); return 1; } return 0; } __proto._uniform_ivec2v=function(one,value){ WebGL.mainContext.uniform2iv(one.location,value); return 1; } __proto._uniform_vec3i=function(one,value){ var uploadedValue=one.uploadedValue; if (uploadedValue[0]!==value[0] || uploadedValue[1]!==value[1] || uploadedValue[2]!==value[2]){ WebGL.mainContext.uniform3i(one.location,uploadedValue[0]=value[0],uploadedValue[1]=value[1],uploadedValue[2]=value[2]); return 1; } return 0; } __proto._uniform_vec3vi=function(one,value){ WebGL.mainContext.uniform3iv(one.location,value); return 1; } __proto._uniform_vec4i=function(one,value){ var uploadedValue=one.uploadedValue; if (uploadedValue[0]!==value[0] || uploadedValue[1]!==value[1] || uploadedValue[2]!==value[2] || uploadedValue[3]!==value[3]){ WebGL.mainContext.uniform4i(one.location,uploadedValue[0]=value[0],uploadedValue[1]=value[1],uploadedValue[2]=value[2],uploadedValue[3]=value[3]); return 1; } return 0; } __proto._uniform_vec4vi=function(one,value){ WebGL.mainContext.uniform4iv(one.location,value); return 1; } __proto._uniform_sampler2D=function(one,texture){ var value=texture.source || texture.defaulteTexture.source; var gl=WebGL.mainContext; var uploadedValue=one.uploadedValue; if (uploadedValue[0]==null){ if (this._curActTexIndex > 7) throw new Error("Shader3D: shader support textures max count is 8,can't large than it."); uploadedValue[0]=this._curActTexIndex; gl.uniform1i(one.location,this._curActTexIndex); gl.activeTexture(Shader3D._TEXTURES[this._curActTexIndex]); if (value) WebGLContext.bindTexture(gl,/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,value); this._curActTexIndex++; return 1; }else { gl.activeTexture(Shader3D._TEXTURES[uploadedValue[0]]); if (value) WebGLContext.bindTexture(gl,/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,value); return 0; } } __proto._uniform_samplerCube=function(one,texture){ var value=texture.source || texture.defaulteTexture.source; var gl=WebGL.mainContext; var uploadedValue=one.uploadedValue; if (uploadedValue[0]==null){ if (this._curActTexIndex > 7) throw new Error("Shader3D: shader support textures max count is 8,can't large than it."); uploadedValue[0]=this._curActTexIndex; gl.uniform1i(one.location,this._curActTexIndex); gl.activeTexture(Shader3D._TEXTURES[this._curActTexIndex]); if (value) WebGLContext.bindTexture(gl,/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP*/0x8513,value); else WebGLContext.bindTexture(gl,/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP*/0x8513,SolidColorTextureCube.grayTexture.source); this._curActTexIndex++; return 1; }else { gl.activeTexture(Shader3D._TEXTURES[uploadedValue[0]]); if (value) WebGLContext.bindTexture(gl,/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP*/0x8513,value); else WebGLContext.bindTexture(gl,/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP*/0x8513,SolidColorTextureCube.grayTexture.source); return 0; } } __proto._noSetValue=function(one){ console.log("no....:"+one.name); } //throw new Error("upload shader err,must set value:"+one.name); __proto.bind=function(){ BaseShader.activeShader=this; BaseShader.bindShader=this; this.activeResource(); return WebGLContext.UseProgram(this._program); } /** *按数组的定义提交 *@param shaderValue 数组格式[name,value,...] */ __proto.uploadAttributes=function(attributeShaderValue,_bufferUsage){ var value; var one,shaderCall=0; for (var i=0,n=this._attributeParamsMap.length;i < n;i+=2){ one=this._attributeParamsMap[i+1]; value=attributeShaderValue[this._attributeParamsMap[i]]; if (value !=null){ _bufferUsage && _bufferUsage[one.name] && _bufferUsage[one.name].bind(); shaderCall+=one.fun.call(this,one,value); } } Stat.shaderCall+=shaderCall; } /** *按数组的定义提交 *@param shaderValue 数组格式[name,value,...] */ __proto.uploadAttributesX=function(attributeShaderValue,vb){ var value; var one,shaderCall=0; for (var i=0,n=this._attributeParamsMap.length;i < n;i+=2){ one=this._attributeParamsMap[i+1]; value=attributeShaderValue[this._attributeParamsMap[i]]; if (value !=null){ vb._bind(); shaderCall+=one.fun.call(this,one,value); } } Stat.shaderCall+=shaderCall; } /** *按数组的定义提交 *@param shaderValue 数组格式[name,value,...] */ __proto.uploadSceneUniforms=function(shaderValue){ var value; var one,shaderCall=0; for (var i=0,n=this._sceneUniformParamsMap.length;i < n;i+=2){ one=this._sceneUniformParamsMap[i+1]; value=shaderValue[this._sceneUniformParamsMap[i]]; if (value !=null) shaderCall+=one.fun.call(this,one,value); } Stat.shaderCall+=shaderCall; } /** *按数组的定义提交 *@param shaderValue 数组格式[name,value,...] */ __proto.uploadCameraUniforms=function(shaderValue){ var value; var one,shaderCall=0; for (var i=0,n=this._cameraUniformParamsMap.length;i < n;i+=2){ one=this._cameraUniformParamsMap[i+1]; value=shaderValue[this._cameraUniformParamsMap[i]]; if (value !=null) shaderCall+=one.fun.call(this,one,value); } Stat.shaderCall+=shaderCall; } /** *按数组的定义提交 *@param shaderValue 数组格式[name,value,...] */ __proto.uploadSpriteUniforms=function(shaderValue){ var value; var one,shaderCall=0; for (var i=0,n=this._spriteUniformParamsMap.length;i < n;i+=2){ one=this._spriteUniformParamsMap[i+1]; value=shaderValue[this._spriteUniformParamsMap[i]]; if (value !=null) shaderCall+=one.fun.call(this,one,value); } Stat.shaderCall+=shaderCall; } /** *按数组的定义提交 *@param shaderValue 数组格式[name,value,...] */ __proto.uploadMaterialUniforms=function(shaderValue){ var value; var one,shaderCall=0; for (var i=0,n=this._materialUniformParamsMap.length;i < n;i+=2){ one=this._materialUniformParamsMap[i+1]; value=shaderValue[this._materialUniformParamsMap[i]]; if (value !=null) shaderCall+=one.fun.call(this,one,value); } Stat.shaderCall+=shaderCall; } /** *按数组的定义提交 *@param shaderValue 数组格式[name,value,...] */ __proto.uploadRenderElementUniforms=function(shaderValue){ var value; var one,shaderCall=0; for (var i=0,n=this._renderElementUniformParamsMap.length;i < n;i+=2){ one=this._renderElementUniformParamsMap[i+1]; value=shaderValue[this._renderElementUniformParamsMap[i]]; if (value !=null) shaderCall+=one.fun.call(this,one,value); } Stat.shaderCall+=shaderCall; } Shader3D.create=function(vs,ps,attributeMap,sceneUniformMap,cameraUniformMap,spriteUniformMap,materialUniformMap,renderElementUniformMap){ return new Shader3D(vs,ps,attributeMap,sceneUniformMap,cameraUniformMap,spriteUniformMap,materialUniformMap,renderElementUniformMap); } Shader3D.addInclude=function(fileName,txt){ ShaderCompile.addInclude(fileName,txt); } Shader3D._createShader=function(gl,str,type){ var shader=gl.createShader(type); gl.shaderSource(shader,str); gl.compileShader(shader); if (ShaderCompile3D.debugMode && !gl.getShaderParameter(shader,/*laya.webgl.WebGLContext.COMPILE_STATUS*/0x8B81)) throw gl.getShaderInfoLog(shader); return shader; } Shader3D.PERIOD_RENDERELEMENT=0; Shader3D.PERIOD_MATERIAL=1; Shader3D.PERIOD_SPRITE=2; Shader3D.PERIOD_CAMERA=3; Shader3D.PERIOD_SCENE=4; Shader3D._TEXTURES=[ /*laya.webgl.WebGLContext.TEXTURE0*/0x84C0,/*laya.webgl.WebGLContext.TEXTURE1*/0x84C1,/*laya.webgl.WebGLContext.TEXTURE2*/0x84C2,/*laya.webgl.WebGLContext.TEXTURE3*/0x84C3,/*laya.webgl.WebGLContext.TEXTURE4*/0x84C4,/*laya.webgl.WebGLContext.TEXTURE5*/0x84C5,/*laya.webgl.WebGLContext.TEXTURE6*/0x84C6,/*laya.webgl.WebGLContext.TEXTURE7*/0x84C7]; Shader3D._count=0; __static(Shader3D, ['shaderParamsMap',function(){return this.shaderParamsMap={"float":/*laya.webgl.WebGLContext.FLOAT*/0x1406,"int":/*laya.webgl.WebGLContext.INT*/0x1404,"bool":/*laya.webgl.WebGLContext.BOOL*/0x8B56,"vec2":/*laya.webgl.WebGLContext.FLOAT_VEC2*/0x8B50,"vec3":/*laya.webgl.WebGLContext.FLOAT_VEC3*/0x8B51,"vec4":/*laya.webgl.WebGLContext.FLOAT_VEC4*/0x8B52,"ivec2":/*laya.webgl.WebGLContext.INT_VEC2*/0x8B53,"ivec3":/*laya.webgl.WebGLContext.INT_VEC3*/0x8B54,"ivec4":/*laya.webgl.WebGLContext.INT_VEC4*/0x8B55,"bvec2":/*laya.webgl.WebGLContext.BOOL_VEC2*/0x8B57,"bvec3":/*laya.webgl.WebGLContext.BOOL_VEC3*/0x8B58,"bvec4":/*laya.webgl.WebGLContext.BOOL_VEC4*/0x8B59,"mat2":/*laya.webgl.WebGLContext.FLOAT_MAT2*/0x8B5A,"mat3":/*laya.webgl.WebGLContext.FLOAT_MAT3*/0x8B5B,"mat4":/*laya.webgl.WebGLContext.FLOAT_MAT4*/0x8B5C,"sampler2D":/*laya.webgl.WebGLContext.SAMPLER_2D*/0x8B5E,"samplerCube":/*laya.webgl.WebGLContext.SAMPLER_CUBE*/0x8B60};},'nameKey',function(){return this.nameKey=new StringKey();} ]); return Shader3D; })(BaseShader) //class laya.d3.core.material.PBRMaterial extends laya.d3.core.material.BaseMaterial var PBRMaterial=(function(_super){ function PBRMaterial(){ /**@private */ this._transformUV=null; PBRMaterial.__super.call(this); if (!laya.d3.core.material.PBRMaterial.pbrlutTex){ var lutdt=Browser.window['__pbrlutdata']; if (!lutdt){ alert('no pbr lutdata, need pbrlut.js'); throw 'no pbr lutdata, need pbrlut.js'; }; var luttex=DataTexture2D.create((new Uint32Array(lutdt)).buffer,256,256,/*laya.webgl.WebGLContext.NEAREST*/0x2600,/*laya.webgl.WebGLContext.NEAREST*/0x2600,false); laya.d3.core.material.PBRMaterial.pbrlutTex=luttex; } this._setTexture(4,laya.d3.core.material.PBRMaterial.pbrlutTex); this.setShaderName("PBR"); this._setNumber(0,0.5); this.use_groundtruth=false; } __class(PBRMaterial,'laya.d3.core.material.PBRMaterial',_super); var __proto=PBRMaterial.prototype; /** *禁用灯光。 */ __proto.disableLight=function(){ this._addDisablePublicShaderDefine(ShaderCompile3D.SHADERDEFINE_POINTLIGHT | ShaderCompile3D.SHADERDEFINE_SPOTLIGHT | ShaderCompile3D.SHADERDEFINE_DIRECTIONLIGHT); } /** *禁用雾化。 */ __proto.disableFog=function(){ this._addDisablePublicShaderDefine(ShaderCompile3D.SHADERDEFINE_FOG); } __proto.onAsynLoaded=function(url,data,params){ _super.prototype.onAsynLoaded.call(this,url,data,params); } /** *vdc算法产生的序列。这个比random要均匀一些。 */ __proto.radicalInverse_VdC=function(bits){ var tmpUint=new Uint32Array(1); return (function(bits){ bits=(bits << 16)| (bits >>> 16); bits=((bits & 0x55555555)<< 1)| ((bits & 0xAAAAAAAA)>>> 1); bits=((bits & 0x33333333)<< 2)| ((bits & 0xCCCCCCCC)>>> 2); bits=((bits & 0x0F0F0F0F)<< 4)| ((bits & 0xF0F0F0F0)>>> 4); bits=((bits & 0x00FF00FF)<< 8)| ((bits & 0xFF00FF00)>>> 8); tmpUint[0]=bits; return tmpUint[0] *2.3283064365386963e-10; })(bits); } /** * */ __proto.createHammersleyTex=function(w,h){ var ret=new Uint8Array(w *h *4); var ri=0; var ci=0; for (ci=0;ci < w *h;ci++){ var v=this.radicalInverse_VdC(ci); ret[ri++]=v *255; ret[ri++]=0; ret[ri++]=0; ret[ri++]=255; } return ret; } /** *设置法线贴图。 *@param value 法线贴图。 */ /** *获取法线贴图。 *@return 法线贴图。 */ __getset(0,__proto,'normalTexture',function(){ return this._getTexture(2); },function(value){ this._setTexture(2,value); }); __getset(0,__proto,'has_tangent',null,function(v){ this._addShaderDefine(PBRMaterial.SHADERDEFINE_HAS_TANGENT); }); /** *设置粗糙度的值,0为特别光滑,1为特别粗糙。 *@param value 粗糙度。 */ /** *获取粗糙度的值,0为特别光滑,1为特别粗糙。 *@return 粗糙度的值。 */ __getset(0,__proto,'roughness',function(){ return this._getNumber(6); },function(value){ this._setNumber(6,value); this._addShaderDefine(PBRMaterial.SHADERDEFINE_FIX_ROUGHNESS); }); __getset(0,__proto,'metaless',function(){ return this._getNumber(7); },function(v){ this._setNumber(7,v); this._addShaderDefine(PBRMaterial.SHADERDEFINE_FIX_METALESS); }); /** *设置PBRLUT贴图。 *@param value PBRLUT贴图。 */ /** *获取PBRLUT贴图。 *@return PBRLUT贴图。 */ __getset(0,__proto,'pbrlutTexture',function(){ return this._getTexture(4); },function(value){ this._setTexture(4,value); }); __getset(0,__proto,'use_groundtruth',null,function(v){ if (v){ this._addShaderDefine(PBRMaterial.SHADERDEFINE_USE_GROUNDTRUTH); if (!laya.d3.core.material.PBRMaterial.HammersleyNoiseTex){ var texdata=this.createHammersleyTex(32,32); laya.d3.core.material.PBRMaterial.HammersleyNoiseTex=DataTexture2D.create(texdata.buffer,32,32,/*laya.webgl.WebGLContext.NEAREST*/0x2600,/*laya.webgl.WebGLContext.NEAREST*/0x2600,false); } this._setTexture(15,PBRMaterial.HammersleyNoiseTex); }else { laya.d3.core.material.PBRMaterial.HammersleyNoiseTex=null; this._removeShaderDefine(PBRMaterial.SHADERDEFINE_USE_GROUNDTRUTH); } }); /** *设置UV变换。 *@param value UV变换。 */ /** *获取UV变换。 *@return UV变换。 */ __getset(0,__proto,'transformUV',function(){ return this._transformUV; },function(value){ this._transformUV=value; this._setMatrix4x4(8,value.matrix); if (this._conchMaterial){ this._conchMaterial.setShaderValue(8,value.matrix.elements,0); } }); /** *设置漫反射贴图。 *@param value 漫反射贴图。 */ /** *获取漫反射贴图。 *@return 漫反射贴图。 */ __getset(0,__proto,'diffuseTexture',function(){ return this._getTexture(1); },function(value){ this._setTexture(1,value); }); __getset(0,__proto,'renderMode',null,function(value){ switch (value){ case 1: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=true; this.cull=2; this.blend=0; this.alphaTest=false; break ; case 2: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=true; this.cull=0; this.blend=0; this.alphaTest=false; break ; case 3: this.depthWrite=true; this.cull=2; this.blend=0; this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; break ; case 13: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=true; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; break ; default : throw new Error("PBRMaterial:renderMode value error."); } }); /** *设置pbr信息贴图。 *@param value pbr信息贴图。 */ /** *获取pbr信息贴图。 *@return pbr信息贴图。 */ __getset(0,__proto,'pbrInfoTexture',function(){ return this._getTexture(3); },function(value){ this._setTexture(3,value); this._addShaderDefine(PBRMaterial.SHADERDEFINE_HAS_PBRINFO); }); __getset(0,__proto,'testClipZ',null,function(v){ this._addShaderDefine(PBRMaterial.SHADERDEFINE_TEST_CLIPZ); }); PBRMaterial.__init__=function(){ PBRMaterial.SHADERDEFINE_FIX_METALESS=PBRMaterial.shaderDefines.registerDefine("FIX_METALESS"); PBRMaterial.SHADERDEFINE_FIX_ROUGHNESS=PBRMaterial.shaderDefines.registerDefine("FIX_ROUGHNESS"); PBRMaterial.SHADERDEFINE_HAS_TANGENT=PBRMaterial.shaderDefines.registerDefine("HAS_TANGENT"); PBRMaterial.SHADERDEFINE_HAS_PBRINFO=PBRMaterial.shaderDefines.registerDefine("HAS_PBRINFO"); PBRMaterial.SHADERDEFINE_USE_GROUNDTRUTH=PBRMaterial.shaderDefines.registerDefine("USE_GROUNDTRUTH"); PBRMaterial.SHADERDEFINE_TEST_CLIPZ=PBRMaterial.shaderDefines.registerDefine("CLIPZ"); } PBRMaterial.load=function(url){ return Laya.loader.create(url,null,null,PBRMaterial); } PBRMaterial.DIFFUSETEXTURE=1; PBRMaterial.NORMALTEXTURE=2; PBRMaterial.PBRINFOTEXTURE=3; PBRMaterial.PBRLUTTEXTURE=4; PBRMaterial.UVANIAGE=5; PBRMaterial.MATERIALROUGHNESS=6; PBRMaterial.MATERIALMETALESS=7; PBRMaterial.UVMATRIX=8; PBRMaterial.UVAGE=9; PBRMaterial.AOOBJPOS=14; PBRMaterial.HSNOISETEXTURE=15; PBRMaterial.SHADERDEFINE_FIX_ROUGHNESS=0; PBRMaterial.SHADERDEFINE_FIX_METALESS=0; PBRMaterial.SHADERDEFINE_HAS_TANGENT=0; PBRMaterial.SHADERDEFINE_TEST_CLIPZ=0; PBRMaterial.SHADERDEFINE_HAS_PBRINFO=0; PBRMaterial.SHADERDEFINE_USE_GROUNDTRUTH=0; PBRMaterial.RENDERMODE_OPAQUE=1; PBRMaterial.RENDERMODE_OPAQUEDOUBLEFACE=2; PBRMaterial.RENDERMODE_CUTOUT=3; PBRMaterial.RENDERMODE_CUTOUTDOUBLEFACE=4; PBRMaterial.RENDERMODE_TRANSPARENT=13; PBRMaterial.pbrlutTex=null; PBRMaterial.HammersleyNoiseTex=null; __static(PBRMaterial, ['defaultMaterial',function(){return this.defaultMaterial=new PBRMaterial();},'shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return PBRMaterial; })(BaseMaterial) /** *... *@author WuTaiLang */ //class laya.d3.core.material.PBRSpecularMaterial extends laya.d3.core.material.BaseMaterial var PBRSpecularMaterial=(function(_super){ function PBRSpecularMaterial(){ PBRSpecularMaterial.__super.call(this); this.setShaderName("PBRSpecular"); this._setColor(7,new Vector4(1.0,1.0,1.0,1.0)); this._setColor(9,new Vector4(0.0,0.0,0.0,0.0)); this._setColor(8,new Vector4(0.2,0.2,0.2,0.2)); this._setNumber(10,0.5); this._setNumber(11,1.0); this._setNumber(12,0); this._setNumber(13,1.0); this._setNumber(14,1.0); this._setNumber(15,0.001); this._setBool(16,false); this._setNumber(0,0.5); } __class(PBRSpecularMaterial,'laya.d3.core.material.PBRSpecularMaterial',_super); var __proto=PBRSpecularMaterial.prototype; /** *设置漫反射颜色。 *@param value 漫反射颜色。 */ /** *获取漫反射颜色。 *@return 漫反射颜色。 */ __getset(0,__proto,'albedoColor',function(){ return this._getColor(7); },function(value){ this._setColor(7,value); }); /** *设置高光贴图。 *@param value 高光贴图。 */ /** *获取高光贴图。 *@return 高光贴图。 */ __getset(0,__proto,'specularTexture',function(){ return this._getTexture(2); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_SPECULARTEXTURE); else this._removeShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_SPECULARTEXTURE); this._setTexture(2,value); }); /** *设置漫反射贴图。 *@param value 漫反射贴图。 */ /** *获取漫反射贴图。 *@return 漫反射贴图。 */ __getset(0,__proto,'albedoTexture',function(){ return this._getTexture(1); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_DIFFUSETEXTURE); else this._removeShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_DIFFUSETEXTURE); this._setTexture(1,value); }); /** *设置遮挡贴图。 *@param value 遮挡贴图。 */ /** *获取遮挡贴图。 *@return 遮挡贴图。 */ __getset(0,__proto,'occlusionTexture',function(){ return this._getTexture(5); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_OCCLUSIONTEXTURE); else this._removeShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_OCCLUSIONTEXTURE); this._setTexture(5,value); }); /** *设置法线贴图。 *@param value 法线贴图。 */ /** *获取法线贴图。 *@return 法线贴图。 */ __getset(0,__proto,'normalTexture',function(){ return this._getTexture(3); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_NORMALTEXTURE); else this._removeShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_NORMALTEXTURE); this._setTexture(3,value); }); /** *设置视差贴图。 *@param value 视察贴图。 */ /** *获取视差贴图。 *@return 视察贴图。 */ __getset(0,__proto,'parallaxTexture',function(){ return this._getTexture(4); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_PARALLAXTEXTURE); else this._removeShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_PARALLAXTEXTURE); this._setTexture(4,value); }); /** *设置放射颜色。 *@param value 放射颜色。 */ /** *获取放射颜色。 *@return 放射颜色。 */ __getset(0,__proto,'emissionColor',function(){ return this._getColor(9); },function(value){ this._setColor(9,value); }); /** *设置法线贴图缩放系数。 *@param value 法线贴图缩放系数。 */ /** *获取法线贴图缩放系数。 *@return 法线贴图缩放系数。 */ __getset(0,__proto,'normalTextureScale',function(){ return this._getNumber(14); },function(value){ this._setNumber(14,value); }); /** *设置视差贴图缩放系数。 *@param value 视差缩放系数。 */ /** *获取视差贴图缩放系数。 *@return 视差缩放系数。 */ __getset(0,__proto,'parallaxTextureScale',function(){ return this._getNumber(15); },function(value){ value=Math.max(0.005,Math.min(0.08,value)); this._setNumber(15,value); }); /** *设置遮挡贴图强度。 *@param value 遮挡贴图强度,范围为0到1。 */ /** *获取遮挡贴图强度。 *@return 遮挡贴图强度,范围为0到1。 */ __getset(0,__proto,'occlusionTextureStrength',function(){ return this._getNumber(13); },function(value){ value=Math.max(0.0,Math.min(1.0,value)); this._setNumber(13,value); }); /** *设置高光颜色。 *@param value 高光颜色。 */ /** *获取高光颜色。 *@return 高光颜色。 */ __getset(0,__proto,'specularColor',function(){ return this._getColor(8); },function(value){ this._setColor(8,value); }); /** *设置光滑度。 *@param value 光滑度,范围为0到1。 */ /** *获取光滑度。 *@return 光滑度,范围为0到1。 */ __getset(0,__proto,'smoothness',function(){ return this._getNumber(10); },function(value){ value=Math.max(0.0,Math.min(1.0,value)); this._setNumber(10,value); }); /** *设置光滑度缩放系数。 *@param value 光滑度缩放系数,范围为0到1。 */ /** *获取光滑度缩放系数。 *@return 光滑度缩放系数,范围为0到1。 */ __getset(0,__proto,'smoothnessTextureScale',function(){ return this._getNumber(11); },function(value){ value=Math.max(0.0,Math.min(1.0,value)); this._setNumber(11,value); }); /** *设置光滑度数据源。 *@param value 光滑滑度数据源,0或1。 */ /** *获取光滑度数据源 *@return 光滑滑度数据源,0或1。 */ __getset(0,__proto,'smoothnessSource',function(){ return this._getNumber(12); },function(value){ if (value==1) this._addShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_DIFFUSETEXTURE_ALPHA); else{ this._removeShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_DIFFUSETEXTURE_ALPHA); value=0; } this._setNumber(12,value); }); /** *设置是否激活放射属性。 *@param value 是否激活放射属性 */ /** *获取是否激活放射属性。 *@return 是否激活放射属性。 */ __getset(0,__proto,'enableEmission',function(){ return this._getBool(16); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_EMISSION); else{ this._removeShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_EMISSION); } this._setBool(16,value); }); /** *设置放射贴图。 *@param value 放射贴图。 */ /** *获取放射贴图。 *@return 放射贴图。 */ __getset(0,__proto,'emissionTexture',function(){ return this._getTexture(6); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_EMISSIONTEXTURE); else this._removeShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_EMISSIONTEXTURE); this._setTexture(6,value); }); /** *设置纹理平铺和偏移。 *@param value 纹理平铺和偏移。 */ /** *获取纹理平铺和偏移。 *@return 纹理平铺和偏移。 */ __getset(0,__proto,'tilingOffset',function(){ return this._getColor(17); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_TILINGOFFSET); else this._removeShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_TILINGOFFSET); }else { this._removeShaderDefine(laya.d3.core.material.PBRSpecularMaterial.SHADERDEFINE_TILINGOFFSET); } this._setColor(17,value); }); PBRSpecularMaterial.__init__=function(){ PBRSpecularMaterial.SHADERDEFINE_DIFFUSETEXTURE=PBRSpecularMaterial.shaderDefines.registerDefine("DIFFUSETEXTURE"); PBRSpecularMaterial.SHADERDEFINE_SPECULARTEXTURE=PBRSpecularMaterial.shaderDefines.registerDefine("SPECULARTEXTURE"); PBRSpecularMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_DIFFUSETEXTURE_ALPHA=PBRSpecularMaterial.shaderDefines.registerDefine("SMOOTHNESSSOURCE_DIFFUSETEXTURE_ALPHA"); PBRSpecularMaterial.SHADERDEFINE_NORMALTEXTURE=PBRSpecularMaterial.shaderDefines.registerDefine("NORMALTEXTURE"); PBRSpecularMaterial.SHADERDEFINE_PARALLAXTEXTURE=PBRSpecularMaterial.shaderDefines.registerDefine("PARALLAXTEXTURE"); PBRSpecularMaterial.SHADERDEFINE_OCCLUSIONTEXTURE=PBRSpecularMaterial.shaderDefines.registerDefine("OCCLUSIONTEXTURE"); PBRSpecularMaterial.SHADERDEFINE_EMISSION=PBRSpecularMaterial.shaderDefines.registerDefine("EMISSION"); PBRSpecularMaterial.SHADERDEFINE_EMISSIONTEXTURE=PBRSpecularMaterial.shaderDefines.registerDefine("EMISSIONTEXTURE"); PBRSpecularMaterial.SHADERDEFINE_TILINGOFFSET=PBRSpecularMaterial.shaderDefines.registerDefine("TILINGOFFSET"); } PBRSpecularMaterial.SmoothnessSource_MetallicGlossTexture_Alpha=0; PBRSpecularMaterial.SmoothnessSource_DiffuseTexture_Alpha=1; PBRSpecularMaterial.SHADERDEFINE_DIFFUSETEXTURE=0; PBRSpecularMaterial.SHADERDEFINE_NORMALTEXTURE=0; PBRSpecularMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_DIFFUSETEXTURE_ALPHA=0; PBRSpecularMaterial.SHADERDEFINE_SPECULARTEXTURE=0; PBRSpecularMaterial.SHADERDEFINE_OCCLUSIONTEXTURE=0; PBRSpecularMaterial.SHADERDEFINE_PARALLAXTEXTURE=0; PBRSpecularMaterial.SHADERDEFINE_EMISSION=0; PBRSpecularMaterial.SHADERDEFINE_EMISSIONTEXTURE=0; PBRSpecularMaterial.SHADERDEFINE_TILINGOFFSET=0; PBRSpecularMaterial.DIFFUSETEXTURE=1; PBRSpecularMaterial.SPECULARTEXTURE=2; PBRSpecularMaterial.NORMALTEXTURE=3; PBRSpecularMaterial.PARALLAXTEXTURE=4; PBRSpecularMaterial.OCCLUSIONTEXTURE=5; PBRSpecularMaterial.EMISSIONTEXTURE=6; PBRSpecularMaterial.DIFFUSECOLOR=7; PBRSpecularMaterial.SPECULARCOLOR=8; PBRSpecularMaterial.EMISSIONCOLOR=9; PBRSpecularMaterial.SMOOTHNESS=10; PBRSpecularMaterial.SMOOTHNESSSCALE=11; PBRSpecularMaterial.SMOOTHNESSSOURCE=12; PBRSpecularMaterial.OCCLUSIONSTRENGTH=13; PBRSpecularMaterial.NORMALSCALE=14; PBRSpecularMaterial.PARALLAXSCALE=15; PBRSpecularMaterial.ENABLEEMISSION=16; PBRSpecularMaterial.TILINGOFFSET=17; __static(PBRSpecularMaterial, ['shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return PBRSpecularMaterial; })(BaseMaterial) /** *... *@author WuTaiLang */ //class laya.d3.core.material.PBRStandardMaterial extends laya.d3.core.material.BaseMaterial var PBRStandardMaterial=(function(_super){ function PBRStandardMaterial(){ PBRStandardMaterial.__super.call(this); this.setShaderName("PBRStandard"); this._setColor(7,new Vector4(1.0,1.0,1.0,1.0)); this._setColor(8,new Vector4(0.0,0.0,0.0,0.0)); this._setNumber(9,0.0); this._setNumber(10,0.5); this._setNumber(11,1.0); this._setNumber(12,0); this._setNumber(13,1.0); this._setNumber(14,1.0); this._setNumber(15,0.001); this._setBool(16,false); this._setNumber(0,0.5); } __class(PBRStandardMaterial,'laya.d3.core.material.PBRStandardMaterial',_super); var __proto=PBRStandardMaterial.prototype; /** *设置漫反射颜色。 *@param value 漫反射颜色。 */ /** *获取漫反射颜色。 *@return 漫反射颜色。 */ __getset(0,__proto,'albedoColor',function(){ return this._getColor(7); },function(value){ this._setColor(7,value); }); /** *设置漫反射贴图。 *@param value 漫反射贴图。 */ /** *获取漫反射贴图。 *@return 漫反射贴图。 */ __getset(0,__proto,'albedoTexture',function(){ return this._getTexture(1); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_DIFFUSETEXTURE); else this._removeShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_DIFFUSETEXTURE); this._setTexture(1,value); }); /** *设置是否激活放射属性。 *@param value 是否激活放射属性 */ /** *获取是否激活放射属性。 *@return 是否激活放射属性。 */ __getset(0,__proto,'enableEmission',function(){ return this._getBool(16); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_EMISSION); else { this._removeShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_EMISSION); } this._setBool(16,value); }); /** *设置金属光滑度贴图。 *@param value 金属光滑度贴图。 */ /** *获取金属光滑度贴图。 *@return 金属光滑度贴图。 */ __getset(0,__proto,'metallicGlossTexture',function(){ return this._getTexture(2); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_METALLICGLOSSTEXTURE); else this._removeShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_METALLICGLOSSTEXTURE); this._setTexture(2,value); }); /** *设置遮挡贴图。 *@param value 遮挡贴图。 */ /** *获取遮挡贴图。 *@return 遮挡贴图。 */ __getset(0,__proto,'occlusionTexture',function(){ return this._getTexture(5); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_OCCLUSIONTEXTURE); else this._removeShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_OCCLUSIONTEXTURE); this._setTexture(5,value); }); /** *设置法线贴图。 *@param value 法线贴图。 */ /** *获取法线贴图。 *@return 法线贴图。 */ __getset(0,__proto,'normalTexture',function(){ return this._getTexture(3); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_NORMALTEXTURE); else this._removeShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_NORMALTEXTURE); this._setTexture(3,value); }); /** *设置视差贴图。 *@param value 视察贴图。 */ /** *获取视差贴图。 *@return 视察贴图。 */ __getset(0,__proto,'parallaxTexture',function(){ return this._getTexture(4); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_PARALLAXTEXTURE); else this._removeShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_PARALLAXTEXTURE); this._setTexture(4,value); }); /** *设置放射颜色。 *@param value 放射颜色。 */ /** *获取放射颜色。 *@return 放射颜色。 */ __getset(0,__proto,'emissionColor',function(){ return this._getColor(8); },function(value){ this._setColor(8,value); }); /** *设置法线贴图缩放系数。 *@param value 法线贴图缩放系数。 */ /** *获取法线贴图缩放系数。 *@return 法线贴图缩放系数。 */ __getset(0,__proto,'normalTextureScale',function(){ return this._getNumber(14); },function(value){ this._setNumber(14,value); }); /** *设置视差贴图缩放系数。 *@param value 视差缩放系数。 */ /** *获取视差贴图缩放系数。 *@return 视差缩放系数。 */ __getset(0,__proto,'parallaxTextureScale',function(){ return this._getNumber(15); },function(value){ value=Math.max(0.005,Math.min(0.08,value)); this._setNumber(15,value); }); /** *设置遮挡贴图强度。 *@param value 遮挡贴图强度,范围为0到1。 */ /** *获取遮挡贴图强度。 *@return 遮挡贴图强度,范围为0到1。 */ __getset(0,__proto,'occlusionTextureStrength',function(){ return this._getNumber(13); },function(value){ value=Math.max(0.0,Math.min(1.0,value)); this._setNumber(13,value); }); /** *设置金属度。 *@param value 金属度,范围为0到1。 */ /** *获取金属度。 *@return 金属度,范围为0到1。 */ __getset(0,__proto,'metallic',function(){ return this._getNumber(9); },function(value){ value=Math.max(0.0,Math.min(1.0,value)); this._setNumber(9,value); }); /** *设置光滑度。 *@param value 光滑度,范围为0到1。 */ /** *获取光滑度。 *@return 光滑度,范围为0到1。 */ __getset(0,__proto,'smoothness',function(){ return this._getNumber(10); },function(value){ value=Math.max(0.0,Math.min(1.0,value)); this._setNumber(10,value); }); /** *设置光滑度缩放系数。 *@param value 光滑度缩放系数,范围为0到1。 */ /** *获取光滑度缩放系数。 *@return 光滑度缩放系数,范围为0到1。 */ __getset(0,__proto,'smoothnessTextureScale',function(){ return this._getNumber(11); },function(value){ value=Math.max(0.0,Math.min(1.0,value)); this._setNumber(11,value); }); /** *设置光滑度数据源。 *@param value 光滑滑度数据源,0或1。 */ /** *获取光滑度数据源 *@return 光滑滑度数据源,0或1。 */ __getset(0,__proto,'smoothnessSource',function(){ return this._getNumber(12); },function(value){ if (value==1) this._addShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_DIFFUSETEXTURE_ALPHA); else { this._removeShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_DIFFUSETEXTURE_ALPHA); value=0; } this._setNumber(12,value); }); /** *设置放射贴图。 *@param value 放射贴图。 */ /** *获取放射贴图。 *@return 放射贴图。 */ __getset(0,__proto,'emissionTexture',function(){ return this._getTexture(6); },function(value){ if (value) this._addShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_EMISSIONTEXTURE); else this._removeShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_EMISSIONTEXTURE); this._setTexture(6,value); }); /** *设置纹理平铺和偏移。 *@param value 纹理平铺和偏移。 */ /** *获取纹理平铺和偏移。 *@return 纹理平铺和偏移。 */ __getset(0,__proto,'tilingOffset',function(){ return this._getColor(17); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_TILINGOFFSET); else this._removeShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_TILINGOFFSET); }else { this._removeShaderDefine(laya.d3.core.material.PBRStandardMaterial.SHADERDEFINE_TILINGOFFSET); } this._setColor(17,value); }); PBRStandardMaterial.__init__=function(){ PBRStandardMaterial.SHADERDEFINE_DIFFUSETEXTURE=PBRStandardMaterial.shaderDefines.registerDefine("DIFFUSETEXTURE"); PBRStandardMaterial.SHADERDEFINE_METALLICGLOSSTEXTURE=PBRStandardMaterial.shaderDefines.registerDefine("METALLICGLOSSTEXTURE"); PBRStandardMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_DIFFUSETEXTURE_ALPHA=PBRStandardMaterial.shaderDefines.registerDefine("SMOOTHNESSSOURCE_DIFFUSETEXTURE_ALPHA"); PBRStandardMaterial.SHADERDEFINE_NORMALTEXTURE=PBRStandardMaterial.shaderDefines.registerDefine("NORMALTEXTURE"); PBRStandardMaterial.SHADERDEFINE_PARALLAXTEXTURE=PBRStandardMaterial.shaderDefines.registerDefine("PARALLAXTEXTURE"); PBRStandardMaterial.SHADERDEFINE_OCCLUSIONTEXTURE=PBRStandardMaterial.shaderDefines.registerDefine("OCCLUSIONTEXTURE"); PBRStandardMaterial.SHADERDEFINE_EMISSION=PBRStandardMaterial.shaderDefines.registerDefine("EMISSION"); PBRStandardMaterial.SHADERDEFINE_EMISSIONTEXTURE=PBRStandardMaterial.shaderDefines.registerDefine("EMISSIONTEXTURE"); PBRStandardMaterial.SHADERDEFINE_TILINGOFFSET=PBRStandardMaterial.shaderDefines.registerDefine("TILINGOFFSET"); } PBRStandardMaterial.SmoothnessSource_MetallicGlossTexture_Alpha=0; PBRStandardMaterial.SmoothnessSource_DiffuseTexture_Alpha=1; PBRStandardMaterial.SHADERDEFINE_DIFFUSETEXTURE=0; PBRStandardMaterial.SHADERDEFINE_NORMALTEXTURE=0; PBRStandardMaterial.SHADERDEFINE_SMOOTHNESSSOURCE_DIFFUSETEXTURE_ALPHA=0; PBRStandardMaterial.SHADERDEFINE_METALLICGLOSSTEXTURE=0; PBRStandardMaterial.SHADERDEFINE_OCCLUSIONTEXTURE=0; PBRStandardMaterial.SHADERDEFINE_PARALLAXTEXTURE=0; PBRStandardMaterial.SHADERDEFINE_EMISSION=0; PBRStandardMaterial.SHADERDEFINE_EMISSIONTEXTURE=0; PBRStandardMaterial.SHADERDEFINE_TILINGOFFSET=0; PBRStandardMaterial.DIFFUSETEXTURE=1; PBRStandardMaterial.METALLICGLOSSTEXTURE=2; PBRStandardMaterial.NORMALTEXTURE=3; PBRStandardMaterial.PARALLAXTEXTURE=4; PBRStandardMaterial.OCCLUSIONTEXTURE=5; PBRStandardMaterial.EMISSIONTEXTURE=6; PBRStandardMaterial.DIFFUSECOLOR=7; PBRStandardMaterial.EMISSIONCOLOR=8; PBRStandardMaterial.METALLIC=9; PBRStandardMaterial.SMOOTHNESS=10; PBRStandardMaterial.SMOOTHNESSSCALE=11; PBRStandardMaterial.SMOOTHNESSSOURCE=12; PBRStandardMaterial.OCCLUSIONSTRENGTH=13; PBRStandardMaterial.NORMALSCALE=14; PBRStandardMaterial.PARALLAXSCALE=15; PBRStandardMaterial.ENABLEEMISSION=16; PBRStandardMaterial.TILINGOFFSET=17; __static(PBRStandardMaterial, ['shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return PBRStandardMaterial; })(BaseMaterial) /** *... *@author ... */ //class laya.d3.core.material.StandardMaterial extends laya.d3.core.material.BaseMaterial var StandardMaterial=(function(_super){ function StandardMaterial(){ /**@private */ this._transformUV=null; StandardMaterial.__super.call(this); this.setShaderName("SIMPLE"); this._setColor(9,new Vector3(0.6,0.6,0.6)); this._setColor(10,new Vector3(1.0,1.0,1.0)); this._setColor(11,new Vector4(1.0,1.0,1.0,8.0)); this._setColor(12,new Vector3(1.0,1.0,1.0)); this._setColor(7,new Vector4(1.0,1.0,1.0,1.0)); this._setNumber(0,0.5); this._setColor(15,new Vector4(1.0,1.0,0.0,0.0)); this.renderMode=1; } __class(StandardMaterial,'laya.d3.core.material.StandardMaterial',_super); var __proto=StandardMaterial.prototype; /** *禁用灯光。 */ __proto.disableLight=function(){ this._addDisablePublicShaderDefine(ShaderCompile3D.SHADERDEFINE_POINTLIGHT | ShaderCompile3D.SHADERDEFINE_SPOTLIGHT | ShaderCompile3D.SHADERDEFINE_DIRECTIONLIGHT); } /** *禁用雾化。 */ __proto.disableFog=function(){ this._addDisablePublicShaderDefine(ShaderCompile3D.SHADERDEFINE_FOG); } /** *@inheritDoc */ __proto.onAsynLoaded=function(url,data,params){ var jsonData=data[0]; if (jsonData.version){ _super.prototype.onAsynLoaded.call(this,url,data,params); }else { var textureMap=data[1]; var props=jsonData.props; for (var prop in props) this[prop]=props[prop]; StandardMaterial._parseStandardMaterial(textureMap,this,jsonData); this._endLoaded(); } } /** *@inheritDoc */ __proto.cloneTo=function(destObject){ _super.prototype.cloneTo.call(this,destObject); var dest=destObject; (this._transformUV)&& (dest._transformUV=this._transformUV.clone()); } /** *设置环境光颜色。 *@param value 环境光颜色。 */ __getset(0,__proto,'ambientColor',function(){ return this._getColor(9); },function(value){ this._setColor(9,value); }); /** *设置环境贴图。 *@param value 环境贴图。 */ /** *获取环境贴图。 *@return 环境贴图。 */ __getset(0,__proto,'ambientTexture',function(){ return this._getTexture(5); },function(value){ if (value){ this._addShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_AMBIENTMAP); }else { this._removeShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_AMBIENTMAP); } this._setTexture(5,value); }); /** *设置渲染模式。 *@return 渲染模式。 */ __getset(0,__proto,'renderMode',null,function(value){ switch (value){ case 1: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=true; this.cull=2; this.blend=0; this.alphaTest=false; this._removeShaderDefine(StandardMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 2: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=true; this.cull=0; this.blend=0; this.alphaTest=false; this._removeShaderDefine(StandardMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 3: this.depthWrite=true; this.cull=2; this.blend=0; this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.alphaTest=true; this._removeShaderDefine(StandardMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 4: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=true; this.cull=0; this.blend=0; this.alphaTest=true; this._removeShaderDefine(StandardMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 13: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=true; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; this.alphaTest=false; this._removeShaderDefine(StandardMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 14: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=true; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; this.alphaTest=false; this._removeShaderDefine(StandardMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 15: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=true; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; this.alphaTest=false; this._addShaderDefine(StandardMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 16: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=true; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; this.alphaTest=false; this._addShaderDefine(StandardMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 5: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=false; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; this.alphaTest=false; this._removeShaderDefine(StandardMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 6: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=false; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; this.alphaTest=false; this._removeShaderDefine(StandardMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 7: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=false; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; this.alphaTest=false; this._addShaderDefine(StandardMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 8: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=false; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; this.alphaTest=false; this._addShaderDefine(StandardMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 9: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthTest=0x0201; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; this.alphaTest=false; this._removeShaderDefine(StandardMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 10: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthTest=0x0201; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; this.alphaTest=false; this._removeShaderDefine(StandardMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 11: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthTest=0x0201; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; this.alphaTest=false; this._addShaderDefine(StandardMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 12: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthTest=0x0201; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; this.alphaTest=false; this._addShaderDefine(StandardMaterial.SHADERDEFINE_ADDTIVEFOG); break ; default : throw new Error("Material:renderMode value error."); } this._conchMaterial && this._conchMaterial.setRenderMode(value); }); /** *设置反射颜色。 *@param value 反射颜色。 */ __getset(0,__proto,'reflectColor',function(){ return this._getColor(12); },function(value){ this._setColor(12,value); }); /** *获取纹理平铺和偏移。 *@param value 纹理平铺和偏移。 */ /** *获取纹理平铺和偏移。 *@return 纹理平铺和偏移。 */ __getset(0,__proto,'tilingOffset',function(){ return this._getColor(15); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_TILINGOFFSET); else this._removeShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_TILINGOFFSET); }else { this._removeShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_TILINGOFFSET); } this._setColor(15,value); }); /** *设置反射率。 *@param value 反射率。 */ __getset(0,__proto,'albedo',function(){ return this._getColor(7); },function(value){ this._setColor(7,value); }); /** *设置漫反射光颜色。 *@param value 漫反射光颜色。 */ __getset(0,__proto,'diffuseColor',function(){ return this._getColor(10); },function(value){ this._setColor(10,value); }); /** *设置反射率。 *@param value 反射率。 */ __getset(0,__proto,'albedoColor',function(){ return this._getColor(7); },function(value){ this._setColor(7,value); }); /** *设置高光颜色。 *@param value 高光颜色。 */ __getset(0,__proto,'specularColor',function(){ return this._getColor(11); },function(value){ this._setColor(11,value); }); /** *设置漫反射贴图。 *@param value 漫反射贴图。 */ /** *获取漫反射贴图。 *@return 漫反射贴图。 */ __getset(0,__proto,'diffuseTexture',function(){ return this._getTexture(1); },function(value){ if (value){ this._addShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_DIFFUSEMAP); }else { this._removeShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_DIFFUSEMAP); } this._setTexture(1,value); }); /** *设置法线贴图。 *@param value 法线贴图。 */ /** *获取法线贴图。 *@return 法线贴图。 */ __getset(0,__proto,'normalTexture',function(){ return this._getTexture(2); },function(value){ if (value){ this._addShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_NORMALMAP); }else { this._removeShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_NORMALMAP); } this._setTexture(2,value); }); /** *设置高光贴图。 *@param value 高光贴图。 */ /** *获取高光贴图。 *@return 高光贴图。 */ __getset(0,__proto,'specularTexture',function(){ return this._getTexture(3); },function(value){ if (value){ this._addShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_SPECULARMAP); }else { this._removeShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_SPECULARMAP); } this._setTexture(3,value); }); /** *设置放射贴图。 *@param value 放射贴图。 */ /** *获取放射贴图。 *@return 放射贴图。 */ __getset(0,__proto,'emissiveTexture',function(){ return this._getTexture(4); },function(value){ if (value){ this._addShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_EMISSIVEMAP); }else { this._removeShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_EMISSIVEMAP); } this._setTexture(4,value); }); /** *设置反射贴图。 *@param value 反射贴图。 */ /** *获取反射贴图。 *@return 反射贴图。 */ __getset(0,__proto,'reflectTexture',function(){ return this._getTexture(6); },function(value){ if (value){ this._addShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_REFLECTMAP); }else { this._removeShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_REFLECTMAP); } this._setTexture(6,value); }); /** *设置UV变换。 *@param value UV变换。 */ /** *获取UV变换。 *@return UV变换。 */ __getset(0,__proto,'transformUV',function(){ return this._transformUV; },function(value){ this._transformUV=value; this._setMatrix4x4(13,value.matrix); if (value) this._addShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_UVTRANSFORM); else this._removeShaderDefine(laya.d3.core.material.StandardMaterial.SHADERDEFINE_UVTRANSFORM); if (this._conchMaterial){ this._conchMaterial.setShaderValue(13,value.matrix.elements,0); } }); StandardMaterial.__init__=function(){ StandardMaterial.SHADERDEFINE_DIFFUSEMAP=StandardMaterial.shaderDefines.registerDefine("DIFFUSEMAP"); StandardMaterial.SHADERDEFINE_NORMALMAP=StandardMaterial.shaderDefines.registerDefine("NORMALMAP"); StandardMaterial.SHADERDEFINE_SPECULARMAP=StandardMaterial.shaderDefines.registerDefine("SPECULARMAP"); StandardMaterial.SHADERDEFINE_EMISSIVEMAP=StandardMaterial.shaderDefines.registerDefine("EMISSIVEMAP"); StandardMaterial.SHADERDEFINE_AMBIENTMAP=StandardMaterial.shaderDefines.registerDefine("AMBIENTMAP"); StandardMaterial.SHADERDEFINE_REFLECTMAP=StandardMaterial.shaderDefines.registerDefine("REFLECTMAP"); StandardMaterial.SHADERDEFINE_UVTRANSFORM=StandardMaterial.shaderDefines.registerDefine("UVTRANSFORM"); StandardMaterial.SHADERDEFINE_TILINGOFFSET=StandardMaterial.shaderDefines.registerDefine("TILINGOFFSET"); StandardMaterial.SHADERDEFINE_ADDTIVEFOG=StandardMaterial.shaderDefines.registerDefine("ADDTIVEFOG"); } StandardMaterial.load=function(url){ return Laya.loader.create(url,null,null,StandardMaterial); } StandardMaterial._parseStandardMaterial=function(textureMap,material,json){ var customProps=json.customProps; var ambientColorValue=customProps.ambientColor; material.ambientColor=new Vector3(ambientColorValue[0],ambientColorValue[1],ambientColorValue[2]); var diffuseColorValue=customProps.diffuseColor; material.diffuseColor=new Vector3(diffuseColorValue[0],diffuseColorValue[1],diffuseColorValue[2]); var specularColorValue=customProps.specularColor; material.specularColor=new Vector4(specularColorValue[0],specularColorValue[1],specularColorValue[2],specularColorValue[3]); var reflectColorValue=customProps.reflectColor; material.reflectColor=new Vector3(reflectColorValue[0],reflectColorValue[1],reflectColorValue[2]); var albedoColorValue=customProps.albedoColor; (albedoColorValue)&& (material.albedo=new Vector4(albedoColorValue[0],albedoColorValue[1],albedoColorValue[2],albedoColorValue[3])); var diffuseTexture=customProps.diffuseTexture.texture2D; (diffuseTexture)&& (material.diffuseTexture=Loader.getRes(textureMap[diffuseTexture])); var normalTexture=customProps.normalTexture.texture2D; (normalTexture)&& (material.normalTexture=Loader.getRes(textureMap[normalTexture])); var specularTexture=customProps.specularTexture.texture2D; (specularTexture)&& (material.specularTexture=Loader.getRes(textureMap[specularTexture])); var emissiveTexture=customProps.emissiveTexture.texture2D; (emissiveTexture)&& (material.emissiveTexture=Loader.getRes(textureMap[emissiveTexture])); var ambientTexture=customProps.ambientTexture.texture2D; (ambientTexture)&& (material.ambientTexture=Loader.getRes(textureMap[ambientTexture])); var reflectTexture=customProps.reflectTexture.texture2D; (reflectTexture)&& (material.reflectTexture=Loader.getRes(textureMap[reflectTexture])); } StandardMaterial.RENDERMODE_OPAQUE=1; StandardMaterial.RENDERMODE_OPAQUEDOUBLEFACE=2; StandardMaterial.RENDERMODE_CUTOUT=3; StandardMaterial.RENDERMODE_CUTOUTDOUBLEFACE=4; StandardMaterial.RENDERMODE_TRANSPARENT=13; StandardMaterial.RENDERMODE_TRANSPARENTDOUBLEFACE=14; StandardMaterial.RENDERMODE_ADDTIVE=15; StandardMaterial.RENDERMODE_ADDTIVEDOUBLEFACE=16; StandardMaterial.RENDERMODE_DEPTHREAD_TRANSPARENT=5; StandardMaterial.RENDERMODE_DEPTHREAD_TRANSPARENTDOUBLEFACE=6; StandardMaterial.RENDERMODE_DEPTHREAD_ADDTIVE=7; StandardMaterial.RENDERMODE_DEPTHREAD_ADDTIVEDOUBLEFACE=8; StandardMaterial.RENDERMODE_NONDEPTH_TRANSPARENT=9; StandardMaterial.RENDERMODE_NONDEPTH_TRANSPARENTDOUBLEFACE=10; StandardMaterial.RENDERMODE_NONDEPTH_ADDTIVE=11; StandardMaterial.RENDERMODE_NONDEPTH_ADDTIVEDOUBLEFACE=12; StandardMaterial.SHADERDEFINE_DIFFUSEMAP=0; StandardMaterial.SHADERDEFINE_NORMALMAP=0; StandardMaterial.SHADERDEFINE_SPECULARMAP=0; StandardMaterial.SHADERDEFINE_EMISSIVEMAP=0; StandardMaterial.SHADERDEFINE_AMBIENTMAP=0; StandardMaterial.SHADERDEFINE_REFLECTMAP=0; StandardMaterial.SHADERDEFINE_UVTRANSFORM=0; StandardMaterial.SHADERDEFINE_TILINGOFFSET=0; StandardMaterial.SHADERDEFINE_ADDTIVEFOG=0; StandardMaterial.DIFFUSETEXTURE=1; StandardMaterial.NORMALTEXTURE=2; StandardMaterial.SPECULARTEXTURE=3; StandardMaterial.EMISSIVETEXTURE=4; StandardMaterial.AMBIENTTEXTURE=5; StandardMaterial.REFLECTTEXTURE=6; StandardMaterial.ALBEDO=7; StandardMaterial.UVANIAGE=8; StandardMaterial.MATERIALAMBIENT=9; StandardMaterial.MATERIALDIFFUSE=10; StandardMaterial.MATERIALSPECULAR=11; StandardMaterial.MATERIALREFLECT=12; StandardMaterial.UVMATRIX=13; StandardMaterial.UVAGE=14; StandardMaterial.TILINGOFFSET=15; __static(StandardMaterial, ['defaultMaterial',function(){return this.defaultMaterial=new StandardMaterial();},'shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return StandardMaterial; })(BaseMaterial) /** *... *@author ... */ //class laya.d3.core.material.TerrainMaterial extends laya.d3.core.material.BaseMaterial var TerrainMaterial=(function(_super){ function TerrainMaterial(){ this._diffuseScale1=null; this._diffuseScale2=null; this._diffuseScale3=null; this._diffuseScale4=null; TerrainMaterial.__super.call(this); this.setShaderName("Terrain"); this.renderMode=1; this._diffuseScale1=new Vector2(); this._diffuseScale2=new Vector2(); this._diffuseScale3=new Vector2(); this._diffuseScale4=new Vector2(); this.ambientColor=new Vector3(0.6,0.6,0.6); this.diffuseColor=new Vector3(1.0,1.0,1.0); this.specularColor=new Vector4(0.2,0.2,0.2,32.0); } __class(TerrainMaterial,'laya.d3.core.material.TerrainMaterial',_super); var __proto=TerrainMaterial.prototype; __proto.setDiffuseScale1=function(x,y){ this._diffuseScale1.x=x; this._diffuseScale1.y=y; this._setColor(6,this._diffuseScale1); } __proto.setDiffuseScale2=function(x,y){ this._diffuseScale2.x=x; this._diffuseScale2.y=y; this._setColor(7,this._diffuseScale2); } __proto.setDiffuseScale3=function(x,y){ this._diffuseScale3.x=x; this._diffuseScale3.y=y; this._setColor(8,this._diffuseScale3); } __proto.setDiffuseScale4=function(x,y){ this._diffuseScale4.x=x; this._diffuseScale4.y=y; this._setColor(9,this._diffuseScale4); } __proto.setDetailNum=function(value){ switch (value){ case 1: this._addShaderDefine(laya.d3.core.material.TerrainMaterial.SHADERDEFINE_DETAIL_NUM1); this._removeShaderDefine(laya.d3.core.material.TerrainMaterial.SHADERDEFINE_DETAIL_NUM2); this._removeShaderDefine(laya.d3.core.material.TerrainMaterial.SHADERDEFINE_DETAIL_NUM3); this._removeShaderDefine(laya.d3.core.material.TerrainMaterial.SHADERDEFINE_DETAIL_NUM4); break ; case 2: this._addShaderDefine(laya.d3.core.material.TerrainMaterial.SHADERDEFINE_DETAIL_NUM2); this._removeShaderDefine(laya.d3.core.material.TerrainMaterial.SHADERDEFINE_DETAIL_NUM1); this._removeShaderDefine(laya.d3.core.material.TerrainMaterial.SHADERDEFINE_DETAIL_NUM3); this._removeShaderDefine(laya.d3.core.material.TerrainMaterial.SHADERDEFINE_DETAIL_NUM4); break ; case 3: this._addShaderDefine(laya.d3.core.material.TerrainMaterial.SHADERDEFINE_DETAIL_NUM3); this._removeShaderDefine(laya.d3.core.material.TerrainMaterial.SHADERDEFINE_DETAIL_NUM1); this._removeShaderDefine(laya.d3.core.material.TerrainMaterial.SHADERDEFINE_DETAIL_NUM2); this._removeShaderDefine(laya.d3.core.material.TerrainMaterial.SHADERDEFINE_DETAIL_NUM4); break ; case 4: this._addShaderDefine(laya.d3.core.material.TerrainMaterial.SHADERDEFINE_DETAIL_NUM4); this._removeShaderDefine(laya.d3.core.material.TerrainMaterial.SHADERDEFINE_DETAIL_NUM1); this._removeShaderDefine(laya.d3.core.material.TerrainMaterial.SHADERDEFINE_DETAIL_NUM2); this._removeShaderDefine(laya.d3.core.material.TerrainMaterial.SHADERDEFINE_DETAIL_NUM3); break ; } } __proto.disableLight=function(){ this._addDisablePublicShaderDefine(ShaderCompile3D.SHADERDEFINE_POINTLIGHT | ShaderCompile3D.SHADERDEFINE_SPOTLIGHT | ShaderCompile3D.SHADERDEFINE_DIRECTIONLIGHT); } /** *@inheritDoc */ __proto.setShaderName=function(name){ _super.prototype.setShaderName.call(this,name); } /** *设置渲染模式。 *@return 渲染模式。 */ __getset(0,__proto,'renderMode',null,function(value){ switch (value){ case 1: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=true; this.cull=2; this.blend=0; this.depthTest=0x0201; break ; case 2: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=false; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; this.depthTest=0x0203; break ; default : throw new Error("TerrainMaterial:renderMode value error."); } this._conchMaterial && this._conchMaterial.setRenderMode(value); }); /** *设置第二层贴图。 *@param value 第二层贴图。 */ /** *获取第二层贴图。 *@return 第二层贴图。 */ __getset(0,__proto,'diffuseTexture2',function(){ return this._getTexture(3); },function(value){ this._setTexture(3,value); }); __getset(0,__proto,'ambientColor',function(){ return this._getColor(10); },function(value){ this._setColor(10,value); }); /** *设置第四层贴图。 *@param value 第四层贴图。 */ /** *获取第四层贴图。 *@return 第四层贴图。 */ __getset(0,__proto,'diffuseTexture4',function(){ return this._getTexture(5); },function(value){ this._setTexture(5,value); }); __getset(0,__proto,'diffuseColor',function(){ return this._getColor(11); },function(value){ this._setColor(11,value); }); /** *设置第一层贴图。 *@param value 第一层贴图。 */ /** *获取第一层贴图。 *@return 第一层贴图。 */ __getset(0,__proto,'diffuseTexture1',function(){ return this._getTexture(2); },function(value){ this._setTexture(2,value); }); __getset(0,__proto,'specularColor',function(){ return this._getColor(12); },function(value){ this._setColor(12,value); }); /** *设置第三层贴图。 *@param value 第三层贴图。 */ /** *获取第三层贴图。 *@return 第三层贴图。 */ __getset(0,__proto,'diffuseTexture3',function(){ return this._getTexture(4); },function(value){ this._setTexture(4,value); }); /** *设置splatAlpha贴图。 *@param value splatAlpha贴图。 */ /** *获取splatAlpha贴图。 *@return splatAlpha贴图。 */ __getset(0,__proto,'splatAlphaTexture',function(){ return this._getTexture(0); },function(value){ this._setTexture(0,value); }); __getset(0,__proto,'normalTexture',function(){ return this._getTexture(1); },function(value){ this._setTexture(1,value); }); TerrainMaterial.__init__=function(){ TerrainMaterial.SHADERDEFINE_DETAIL_NUM1=TerrainMaterial.shaderDefines.registerDefine("DETAIL_NUM1"); TerrainMaterial.SHADERDEFINE_DETAIL_NUM2=TerrainMaterial.shaderDefines.registerDefine("DETAIL_NUM2"); TerrainMaterial.SHADERDEFINE_DETAIL_NUM4=TerrainMaterial.shaderDefines.registerDefine("DETAIL_NUM4"); TerrainMaterial.SHADERDEFINE_DETAIL_NUM3=TerrainMaterial.shaderDefines.registerDefine("DETAIL_NUM3"); } TerrainMaterial.load=function(url){ return Laya.loader.create(url,null,null,TerrainMaterial); } TerrainMaterial.RENDERMODE_OPAQUE=1; TerrainMaterial.RENDERMODE_TRANSPARENT=2; TerrainMaterial.SPLATALPHATEXTURE=0; TerrainMaterial.NORMALTEXTURE=1; TerrainMaterial.DIFFUSETEXTURE1=2; TerrainMaterial.DIFFUSETEXTURE2=3; TerrainMaterial.DIFFUSETEXTURE3=4; TerrainMaterial.DIFFUSETEXTURE4=5; TerrainMaterial.DIFFUSESCALE1=6; TerrainMaterial.DIFFUSESCALE2=7; TerrainMaterial.DIFFUSESCALE3=8; TerrainMaterial.DIFFUSESCALE4=9; TerrainMaterial.MATERIALAMBIENT=10; TerrainMaterial.MATERIALDIFFUSE=11; TerrainMaterial.MATERIALSPECULAR=12; TerrainMaterial.SHADERDEFINE_DETAIL_NUM1=0; TerrainMaterial.SHADERDEFINE_DETAIL_NUM2=0; TerrainMaterial.SHADERDEFINE_DETAIL_NUM3=0; TerrainMaterial.SHADERDEFINE_DETAIL_NUM4=0; __static(TerrainMaterial, ['defaultMaterial',function(){return this.defaultMaterial=new TerrainMaterial();},'shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return TerrainMaterial; })(BaseMaterial) //class laya.d3.core.material.WaterMaterial extends laya.d3.core.material.BaseMaterial var WaterMaterial=(function(_super){ function WaterMaterial(){ this._useVertexDeep=false; WaterMaterial.__super.call(this); this.setShaderName("Water"); } __class(WaterMaterial,'laya.d3.core.material.WaterMaterial',_super); var __proto=WaterMaterial.prototype; /** *禁用雾化。 */ __proto.disableFog=function(){ this._addDisablePublicShaderDefine(ShaderCompile3D.SHADERDEFINE_FOG); } __proto.onAsynLoaded=function(url,data,params){ _super.prototype.onAsynLoaded.call(this,url,data,params); } /** *设置漫反射贴图。 *@param value 漫反射贴图。 */ /** *获取漫反射贴图。 *@return 漫反射贴图。 */ __getset(0,__proto,'diffuseTexture',function(){ return this._getTexture(1); },function(value){ this._setTexture(1,value); }); /** *设置法线贴图。 *@param value 法线贴图。 */ /** *获取法线贴图。 *@return 法线贴图。 */ __getset(0,__proto,'normalTexture',function(){ return this._getTexture(2); },function(value){ this._setTexture(2,value); }); __getset(0,__proto,'underWaterTexture',function(){ return this._getTexture(3); },function(value){ this._setTexture(3,value); }); __getset(0,__proto,'deepColorTexture',function(){ return this._getTexture(10); },function(v){ this._setTexture(10,v); }); __getset(0,__proto,'useFoam',null,function(v){ if (v){ this._addShaderDefine(WaterMaterial.SHADERDEFINE_USE_FOAM); }else { this._removeShaderDefine(WaterMaterial.SHADERDEFINE_USE_FOAM); } }); __getset(0,__proto,'skyTexture',function(){ return this._getTexture(11); },function(v){ this._setTexture(11,v); }); __getset(0,__proto,'deepScale',function(){ return this._getNumber(20); },function(v){ this._setNumber(20,v); }); __getset(0,__proto,'detailTexture',function(){ return this._getTexture(9); },function(value){ this._setTexture(9,value); }); __getset(0,__proto,'foamTexture',function(){ return this._getTexture(17); },function(v){ this._setTexture(17,v); }); __getset(0,__proto,'waterInfoTexture',function(){ return this._getTexture(16); },function(v){ this._setTexture(16,v); }); /** *对定点进行变换的纹理。现在不用 */ __getset(0,__proto,'vertexDispTexture',function(){ return this._getTexture(4); },function(value){ this._setTexture(4,value); }); __getset(0,__proto,'currentTm',function(){ return this._getNumber(8); },function(v){ this._setNumber(8,v); }); __getset(0,__proto,'waveInfo',function(){ return this._getBuffer(12); },function(v){ this._setBuffer(12,v); }); __getset(0,__proto,'waveInfoD',function(){ return this._getBuffer(13); },function(v){ this._setBuffer(13,v); }); __getset(0,__proto,'waveMainDir',function(){ return this._getNumber(14); },function(deg){ this._setNumber(14,deg *Math.PI / 180); }); __getset(0,__proto,'geoWaveUVScale',function(){ return this._getNumber(18); },function(v){ this._setNumber(18,v); }); __getset(0,__proto,'windSpeed',function(){ return 0; },function(s){ }); __getset(0,__proto,'scrsize',null,function(v){ this._setBuffer(15,v); }); __getset(0,__proto,'seaColor',function(){ return this._getBuffer(19); },function(v){ this._setBuffer(19,v); }); __getset(0,__proto,'useVertexDeep',function(){ return this._useVertexDeep; },function(v){ this._useVertexDeep=v; if (v) this._addShaderDefine(WaterMaterial.SHADERDEFINE_USEVERTEXHEIGHT); else { this._removeShaderDefine(WaterMaterial.SHADERDEFINE_USEVERTEXHEIGHT); } }); __getset(0,__proto,'windDir',function(){ return 0; },function(d){ }); __getset(0,__proto,'useRefractTexture',null,function(v){ if (v){ this._addShaderDefine(WaterMaterial.SHADERDEFINE_USE_REFRACT_TEX); }else { this._removeShaderDefine(WaterMaterial.SHADERDEFINE_USE_REFRACT_TEX); } }); __getset(0,__proto,'renderMode',null,function(value){ switch (value){ case 1: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=true; this.cull=2; this.blend=0; this.alphaTest=false; break ; case 2: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=true; this.cull=0; this.blend=0; this.alphaTest=false; break ; case 3: this.depthWrite=true; this.cull=2; this.blend=0; this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; break ; case 13: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=true; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; break ; default : throw new Error("PBRMaterial:renderMode value error."); } }); WaterMaterial.__init__=function(){ WaterMaterial.SHADERDEFINE_CUBE_ENV=WaterMaterial.shaderDefines.registerDefine("CUBE_ENV"); WaterMaterial.SHADERDEFINE_HDR_ENV=WaterMaterial.shaderDefines.registerDefine("HDR_ENV"); WaterMaterial.SHADERDEFINE_SHOW_NORMAL=WaterMaterial.shaderDefines.registerDefine("SHOW_NORMAL"); WaterMaterial.SHADERDEFINE_USEVERTEXHEIGHT=WaterMaterial.shaderDefines.registerDefine("USE_VERTEX_DEEPINFO"); WaterMaterial.SHADERDEFINE_USE_FOAM=WaterMaterial.shaderDefines.registerDefine("USE_FOAM"); WaterMaterial.SHADERDEFINE_USE_REFRACT_TEX=WaterMaterial.shaderDefines.registerDefine("USE_REFR_TEX"); } WaterMaterial.load=function(url){ return Laya.loader.create(url,null,null,WaterMaterial); } WaterMaterial.DIFFUSETEXTURE=1; WaterMaterial.NORMALTEXTURE=2; WaterMaterial.UNDERWATERTEXTURE=3; WaterMaterial.VERTEXDISPTEXTURE=4; WaterMaterial.UVANIAGE=5; WaterMaterial.UVMATRIX=6; WaterMaterial.UVAGE=7; WaterMaterial.CURTM=8; WaterMaterial.DETAILTEXTURE=9; WaterMaterial.DEEPCOLORTEXTURE=10; WaterMaterial.SKYTEXTURE=11; WaterMaterial.WAVEINFO=12; WaterMaterial.WAVEINFOD=13; WaterMaterial.WAVEMAINDIR=14; WaterMaterial.SCRSIZE=15; WaterMaterial.WATERINFO=16; WaterMaterial.FOAMTEXTURE=17; WaterMaterial.GEOWAVE_UV_SCALE=18; WaterMaterial.SEA_COLOR=19; WaterMaterial.WAVEINFODEEPSCALE=20; WaterMaterial.SHADERDEFINE_SHOW_NORMAL=0; WaterMaterial.SHADERDEFINE_CUBE_ENV=0; WaterMaterial.SHADERDEFINE_HDR_ENV=0; WaterMaterial.SHADERDEFINE_USE_FOAM=0; WaterMaterial.SHADERDEFINE_USE_REFRACT_TEX=0; WaterMaterial.SHADERDEFINE_USEVERTEXHEIGHT=0; WaterMaterial.RENDERMODE_OPAQUE=1; WaterMaterial.RENDERMODE_OPAQUEDOUBLEFACE=2; WaterMaterial.RENDERMODE_CUTOUT=3; WaterMaterial.RENDERMODE_CUTOUTDOUBLEFACE=4; WaterMaterial.RENDERMODE_TRANSPARENT=13; __static(WaterMaterial, ['defaultMaterial',function(){return this.defaultMaterial=new WaterMaterial();},'shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return WaterMaterial; })(BaseMaterial) /** *IndexBuffer3D 类用于创建索引缓冲。 */ //class laya.d3.graphics.IndexBuffer3D extends laya.webgl.utils.Buffer var IndexBuffer3D=(function(_super){ function IndexBuffer3D(indexType,indexCount,bufferUsage,canRead){ /**@private */ this._indexType=null; /**@private */ this._indexTypeByteCount=0; /**@private */ this._indexCount=0; /**@private */ this._canRead=false; (bufferUsage===void 0)&& (bufferUsage=/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4); (canRead===void 0)&& (canRead=false); IndexBuffer3D.__super.call(this); this._indexType=indexType; this._indexCount=indexCount; this._bufferUsage=bufferUsage; this._bufferType=/*laya.webgl.WebGLContext.ELEMENT_ARRAY_BUFFER*/0x8893; this._canRead=canRead; var byteLength=0; if (indexType==/*CLASS CONST:laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort") this._indexTypeByteCount=2; else if (indexType==/*CLASS CONST:laya.d3.graphics.IndexBuffer3D.INDEXTYPE_UBYTE*/"ubyte") this._indexTypeByteCount=1; else throw new Error("unidentification index type."); byteLength=this._indexTypeByteCount *indexCount; this._byteLength=byteLength; this._bind(); Buffer._gl.bufferData(this._bufferType,byteLength,this._bufferUsage); if (canRead){ if (indexType==/*CLASS CONST:laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort") this._buffer=new Uint16Array(indexCount); else if (indexType==/*CLASS CONST:laya.d3.graphics.IndexBuffer3D.INDEXTYPE_UBYTE*/"ubyte") this._buffer=new Uint8Array(indexCount); this.memorySize=byteLength *2; }else { this.memorySize=byteLength; } } __class(IndexBuffer3D,'laya.d3.graphics.IndexBuffer3D',_super); var __proto=IndexBuffer3D.prototype; /** *设置数据。 *@param data 索引数据。 *@param bufferOffset 索引缓冲中的偏移。 *@param dataStartIndex 索引数据的偏移。 *@param dataCount 索引数据的数量。 */ __proto.setData=function(data,bufferOffset,dataStartIndex,dataCount){ (bufferOffset===void 0)&& (bufferOffset=0); (dataStartIndex===void 0)&& (dataStartIndex=0); (dataCount===void 0)&& (dataCount=4294967295); var byteCount=0; if (this._indexType==/*CLASS CONST:laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort"){ byteCount=2; if (dataStartIndex!==0 || dataCount!==4294967295) data=new Uint16Array(data.buffer,dataStartIndex *byteCount,dataCount); }else if (this._indexType==/*CLASS CONST:laya.d3.graphics.IndexBuffer3D.INDEXTYPE_UBYTE*/"ubyte"){ byteCount=1; if (dataStartIndex!==0 || dataCount!==4294967295) data=new Uint8Array(data.buffer,dataStartIndex *byteCount,dataCount); } this._bind(); Buffer._gl.bufferSubData(this._bufferType,bufferOffset *byteCount,data); if (this._canRead){ if (bufferOffset!==0 || dataStartIndex!==0 || dataCount!==4294967295){ var maxLength=this._buffer.length-bufferOffset; if (dataCount > maxLength) dataCount=maxLength; for (var i=0;i < dataCount;i++) this._buffer[bufferOffset+i]=data[i]; }else { this._buffer=data; } } } /** *获取索引数据。 *@return 索引数据。 */ __proto.getData=function(){ if (this._canRead) return this._buffer; else throw new Error("Can't read data from VertexBuffer with only write flag!"); } /** *@inheritDoc */ __proto.disposeResource=function(){ _super.prototype.disposeResource.call(this); this._buffer=null; this.memorySize=0; } /** *获取索引类型。 *@return 索引类型。 */ __getset(0,__proto,'indexType',function(){ return this._indexType; }); /** *获取索引类型字节数量。 *@return 索引类型字节数量。 */ __getset(0,__proto,'indexTypeByteCount',function(){ return this._indexTypeByteCount; }); /** *获取索引个数。 *@return 索引个数。 */ __getset(0,__proto,'indexCount',function(){ return this._indexCount; }); /** *获取是否可读。 *@return 是否可读。 */ __getset(0,__proto,'canRead',function(){ return this._canRead; }); IndexBuffer3D.INDEXTYPE_UBYTE="ubyte"; IndexBuffer3D.INDEXTYPE_USHORT="ushort"; IndexBuffer3D.create=function(indexType,indexCount,bufferUsage,canRead){ (bufferUsage===void 0)&& (bufferUsage=/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4); (canRead===void 0)&& (canRead=false); return new IndexBuffer3D(indexType,indexCount,bufferUsage,canRead); } return IndexBuffer3D; })(Buffer) /** *... *@author ... */ //class laya.d3.core.particleShuriKen.ShurikenParticleMaterial extends laya.d3.core.material.BaseMaterial var ShurikenParticleMaterial=(function(_super){ function ShurikenParticleMaterial(){ ShurikenParticleMaterial.__super.call(this); this.setShaderName("PARTICLESHURIKEN"); this.renderMode=6; } __class(ShurikenParticleMaterial,'laya.d3.core.particleShuriKen.ShurikenParticleMaterial',_super); var __proto=ShurikenParticleMaterial.prototype; /** *@private */ __proto.onAsynLoaded=function(url,data,params){ var jsonData=data[0]; if (jsonData.version){ _super.prototype.onAsynLoaded.call(this,url,data,params); }else { var textureMap=data[1]; var props=jsonData.props; for (var prop in props) this[prop]=props[prop]; ShurikenParticleMaterial._parseShurikenParticleMaterial(textureMap,this,jsonData); this._endLoaded(); } } /** *设置渲染模式。 *@return 渲染模式。 */ __getset(0,__proto,'renderMode',null,function(value){ switch (value){ case 1: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=true; this.cull=2; this.blend=0; this.alphaTest=false; this._removeShaderDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 2: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=true; this.cull=0; this.blend=0; this.alphaTest=false; this._removeShaderDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 3: this.depthWrite=true; this.cull=2; this.blend=0; this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.alphaTest=true; this._removeShaderDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 4: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_OPAQUE*/2000; this.depthWrite=true; this.cull=0; this.blend=0; this.alphaTest=true; this._removeShaderDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 13: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=true; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; this.alphaTest=false; this._removeShaderDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 14: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=true; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; this.alphaTest=false; this._removeShaderDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 15: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=true; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; this.alphaTest=false; this._addShaderDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 16: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=true; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; this.alphaTest=false; this._addShaderDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 5: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=false; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; this.alphaTest=false; this._removeShaderDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 6: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=false; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; this.alphaTest=false; this._removeShaderDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 7: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=false; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; this.alphaTest=false; this._addShaderDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 8: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthWrite=false; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; this.alphaTest=false; this._addShaderDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 9: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthTest=0x0201; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; this.alphaTest=false; this._removeShaderDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 10: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthTest=0x0201; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=0x0303; this.alphaTest=false; this._removeShaderDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 11: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthTest=0x0201; this.cull=2; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; this.alphaTest=false; this._addShaderDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG); break ; case 12: this.renderQueue=/*laya.d3.core.material.BaseMaterial.RENDERQUEUE_TRANSPARENT*/3000; this.depthTest=0x0201; this.cull=0; this.blend=1; this.srcBlend=0x0302; this.dstBlend=1; this.alphaTest=false; this._addShaderDefine(ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG); break ; default : throw new Error("Material:renderMode value error."); } this._conchMaterial && this._conchMaterial.setRenderMode(value); }); /** *设置颜色。 *@param value 颜色。 */ /** *获取颜色。 *@return 颜色。 */ __getset(0,__proto,'tintColor',function(){ return this._getColor(2); },function(value){ if (value) this._addShaderDefine(laya.d3.core.particleShuriKen.ShurikenParticleMaterial.SHADERDEFINE_TINTCOLOR); else this._removeShaderDefine(laya.d3.core.particleShuriKen.ShurikenParticleMaterial.SHADERDEFINE_TINTCOLOR); this._setColor(2,value); }); /** *获取纹理平铺和偏移。 *@param value 纹理平铺和偏移。 */ /** *获取纹理平铺和偏移。 *@return 纹理平铺和偏移。 */ __getset(0,__proto,'tilingOffset',function(){ return this._getColor(3); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(laya.d3.core.particleShuriKen.ShurikenParticleMaterial.SHADERDEFINE_TILINGOFFSET); else this._removeShaderDefine(laya.d3.core.particleShuriKen.ShurikenParticleMaterial.SHADERDEFINE_TILINGOFFSET); }else { this._removeShaderDefine(laya.d3.core.particleShuriKen.ShurikenParticleMaterial.SHADERDEFINE_TILINGOFFSET); } this._setColor(3,value); }); /** *设置漫反射贴图。 *@param value 漫反射贴图。 */ /** *获取漫反射贴图。 *@return 漫反射贴图。 */ __getset(0,__proto,'diffuseTexture',function(){ return this._getTexture(1); },function(value){ if (value) this._addShaderDefine(laya.d3.core.particleShuriKen.ShurikenParticleMaterial.SHADERDEFINE_DIFFUSEMAP); else this._removeShaderDefine(laya.d3.core.particleShuriKen.ShurikenParticleMaterial.SHADERDEFINE_DIFFUSEMAP); this._setTexture(1,value); }); ShurikenParticleMaterial.__init__=function(){ ShurikenParticleMaterial.SHADERDEFINE_DIFFUSEMAP=ShurikenParticleMaterial.shaderDefines.registerDefine("DIFFUSEMAP"); ShurikenParticleMaterial.SHADERDEFINE_TINTCOLOR=ShurikenParticleMaterial.shaderDefines.registerDefine("TINTCOLOR"); ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG=ShurikenParticleMaterial.shaderDefines.registerDefine("ADDTIVEFOG"); ShurikenParticleMaterial.SHADERDEFINE_TILINGOFFSET=ShurikenParticleMaterial.shaderDefines.registerDefine("TILINGOFFSET"); } ShurikenParticleMaterial.load=function(url){ return Laya.loader.create(url,null,null,ShurikenParticleMaterial); } ShurikenParticleMaterial._parseShurikenParticleMaterial=function(textureMap,material,json){ var customProps=json.customProps; var diffuseTexture=customProps.diffuseTexture.texture2D; (diffuseTexture)&& (material.diffuseTexture=Loader.getRes(textureMap[diffuseTexture])); var tintColorValue=customProps.tintColor; (tintColorValue)&& (material.tintColor=new Vector4(tintColorValue[0],tintColorValue[1],tintColorValue[2],tintColorValue[3])); } ShurikenParticleMaterial.RENDERMODE_OPAQUE=1; ShurikenParticleMaterial.RENDERMODE_OPAQUEDOUBLEFACE=2; ShurikenParticleMaterial.RENDERMODE_CUTOUT=3; ShurikenParticleMaterial.RENDERMODE_CUTOUTDOUBLEFACE=4; ShurikenParticleMaterial.RENDERMODE_TRANSPARENT=13; ShurikenParticleMaterial.RENDERMODE_TRANSPARENTDOUBLEFACE=14; ShurikenParticleMaterial.RENDERMODE_ADDTIVE=15; ShurikenParticleMaterial.RENDERMODE_ADDTIVEDOUBLEFACE=16; ShurikenParticleMaterial.RENDERMODE_DEPTHREAD_TRANSPARENT=5; ShurikenParticleMaterial.RENDERMODE_DEPTHREAD_TRANSPARENTDOUBLEFACE=6; ShurikenParticleMaterial.RENDERMODE_DEPTHREAD_ADDTIVE=7; ShurikenParticleMaterial.RENDERMODE_DEPTHREAD_ADDTIVEDOUBLEFACE=8; ShurikenParticleMaterial.RENDERMODE_NONDEPTH_TRANSPARENT=9; ShurikenParticleMaterial.RENDERMODE_NONDEPTH_TRANSPARENTDOUBLEFACE=10; ShurikenParticleMaterial.RENDERMODE_NONDEPTH_ADDTIVE=11; ShurikenParticleMaterial.RENDERMODE_NONDEPTH_ADDTIVEDOUBLEFACE=12; ShurikenParticleMaterial.SHADERDEFINE_DIFFUSEMAP=0; ShurikenParticleMaterial.SHADERDEFINE_TINTCOLOR=0; ShurikenParticleMaterial.SHADERDEFINE_TILINGOFFSET=0; ShurikenParticleMaterial.SHADERDEFINE_ADDTIVEFOG=0; ShurikenParticleMaterial.DIFFUSETEXTURE=1; ShurikenParticleMaterial.TINTCOLOR=2; ShurikenParticleMaterial.TILINGOFFSET=3; __static(ShurikenParticleMaterial, ['defaultMaterial',function(){return this.defaultMaterial=new ShurikenParticleMaterial();},'shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return ShurikenParticleMaterial; })(BaseMaterial) /** *VertexBuffer3D 类用于创建顶点缓冲。 */ //class laya.d3.graphics.VertexBuffer3D extends laya.webgl.utils.Buffer var VertexBuffer3D=(function(_super){ function VertexBuffer3D(vertexDeclaration,vertexCount,bufferUsage,canRead){ /**@private */ this._vertexDeclaration=null; /**@private */ this._vertexCount=0; /**@private */ this._canRead=false; (canRead===void 0)&& (canRead=false); VertexBuffer3D.__super.call(this); this._vertexDeclaration=vertexDeclaration; this._vertexCount=vertexCount; this._bufferUsage=bufferUsage; this._bufferType=/*laya.webgl.WebGLContext.ARRAY_BUFFER*/0x8892; this._canRead=canRead; this.memorySize=this._byteLength=this._vertexDeclaration.vertexStride *vertexCount; this._bind(); Buffer._gl.bufferData(this._bufferType,this._byteLength,this._bufferUsage); canRead && (this._buffer=new Float32Array(this._byteLength / 4)); } __class(VertexBuffer3D,'laya.d3.graphics.VertexBuffer3D',_super); var __proto=VertexBuffer3D.prototype; /** *和索引缓冲一起绑定。 *@param ib 索引缓冲。 */ __proto.bindWithIndexBuffer=function(ib){ (ib)&& (ib._bind()); this._bind(); } /** *设置数据。 *@param data 顶点数据。 *@param bufferOffset 顶点缓冲中的偏移。 *@param dataStartIndex 顶点数据的偏移。 *@param dataCount 顶点数据的数量。 */ __proto.setData=function(data,bufferOffset,dataStartIndex,dataCount){ (bufferOffset===void 0)&& (bufferOffset=0); (dataStartIndex===void 0)&& (dataStartIndex=0); (dataCount===void 0)&& (dataCount=4294967295); if (dataStartIndex!==0 || dataCount!==4294967295) data=new Float32Array(data.buffer,dataStartIndex *4,dataCount); this._bind(); Buffer._gl.bufferSubData(this._bufferType,bufferOffset *4,data); if (this._canRead){ if (bufferOffset!==0 || dataStartIndex!==0 || dataCount!==4294967295){ var maxLength=this._buffer.length-bufferOffset; if (dataCount > maxLength) dataCount=maxLength; for (var i=0;i < dataCount;i++) this._buffer[bufferOffset+i]=data[i]; }else { this._buffer=data; } } } /** *获取顶点数据。 *@return 顶点数据。 */ __proto.getData=function(){ if (this._canRead) return this._buffer; else throw new Error("Can't read data from VertexBuffer with only write flag!"); } /**销毁顶点缓冲。*/ __proto.disposeResource=function(){ var gl=WebGL.mainContext; var elements=this._vertexDeclaration.getVertexElements(); var enableAtributes=Buffer._enableAtributes; for (var i=0,n=elements.length;i < n;i++){ if (enableAtributes[i]===this._glBuffer){ gl.disableVertexAttribArray(i); enableAtributes[i]=null; } } _super.prototype.disposeResource.call(this); this._buffer=null; this._vertexDeclaration=null; this.memorySize=0; } /** *获取顶点结构声明。 *@return 顶点结构声明。 */ __getset(0,__proto,'vertexDeclaration',function(){ return this._vertexDeclaration; }); /** *获取顶点个数。 *@return 顶点个数。 */ __getset(0,__proto,'vertexCount',function(){ return this._vertexCount; }); /** *获取是否可读。 *@return 是否可读。 */ __getset(0,__proto,'canRead',function(){ return this._canRead; }); VertexBuffer3D.create=function(vertexDeclaration,vertexCount,bufferUsage,canRead){ (bufferUsage===void 0)&& (bufferUsage=/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4); (canRead===void 0)&& (canRead=false); return new VertexBuffer3D(vertexDeclaration,vertexCount,bufferUsage,canRead); } return VertexBuffer3D; })(Buffer) /** *... *@author ... */ //class laya.d3.core.trail.TrailMaterial extends laya.d3.core.material.BaseMaterial var TrailMaterial=(function(_super){ function TrailMaterial(){ TrailMaterial.__super.call(this); this.setShaderName("Trail"); this._setColor(2,new Vector4(1.0,1.0,1.0,1.0)); } __class(TrailMaterial,'laya.d3.core.trail.TrailMaterial',_super); var __proto=TrailMaterial.prototype; /** *设置颜色。 *@param value 颜色。 */ /** *获取颜色。 *@return 颜色。 */ __getset(0,__proto,'tintColor',function(){ return this._getColor(2); },function(value){ this._setColor(2,value); }); /** *设置贴图。 *@param value 贴图。 */ /** *获取贴图。 *@return 贴图。 */ __getset(0,__proto,'diffuseTexture',function(){ return this._getTexture(1); },function(value){ if (value) this._addShaderDefine(laya.d3.core.trail.TrailMaterial.SHADERDEFINE_DIFFUSETEXTURE); else this._removeShaderDefine(laya.d3.core.trail.TrailMaterial.SHADERDEFINE_DIFFUSETEXTURE); this._setTexture(1,value); }); /** *设置纹理平铺和偏移。 *@param value 纹理平铺和偏移。 */ /** *获取纹理平铺和偏移。 *@return 纹理平铺和偏移。 */ __getset(0,__proto,'tilingOffset',function(){ return this._getColor(3); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(laya.d3.core.trail.TrailMaterial.SHADERDEFINE_TILINGOFFSET); else this._removeShaderDefine(laya.d3.core.trail.TrailMaterial.SHADERDEFINE_TILINGOFFSET); }else { this._removeShaderDefine(laya.d3.core.trail.TrailMaterial.SHADERDEFINE_TILINGOFFSET); } this._setColor(3,value); }); TrailMaterial.__init__=function(){ TrailMaterial.SHADERDEFINE_DIFFUSETEXTURE=TrailMaterial.shaderDefines.registerDefine("DIFFUSETEXTURE"); TrailMaterial.SHADERDEFINE_TILINGOFFSET=TrailMaterial.shaderDefines.registerDefine("TILINGOFFSET"); } TrailMaterial.load=function(url){ return Laya.loader.create(url,null,null,TrailMaterial); } TrailMaterial.SHADERDEFINE_DIFFUSETEXTURE=0; TrailMaterial.SHADERDEFINE_TILINGOFFSET=0; TrailMaterial.DIFFUSETEXTURE=1; TrailMaterial.TINTCOLOR=2; TrailMaterial.TILINGOFFSET=3; __static(TrailMaterial, ['defaultMaterial',function(){return this.defaultMaterial=new TrailMaterial();},'shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return TrailMaterial; })(BaseMaterial) //class laya.d3.extension.cartoonRender.CartoonMaterial extends laya.d3.core.material.BaseMaterial var CartoonMaterial=(function(_super){ function CartoonMaterial(){ CartoonMaterial.__super.call(this); this.setShaderName("CartoonShader"); this._setColor(5,new Vector4(0.6663285,0.6544118,1,1)); this._setNumber(6,0); this._setNumber(7,0.7956449); this._setNumber(8,0.9820514); this._setNumber(9,1); } __class(CartoonMaterial,'laya.d3.extension.cartoonRender.CartoonMaterial',_super); var __proto=CartoonMaterial.prototype; /** *设置高光贴图。 *@param value 高光贴图。 */ /** *获取高光贴图。 *@return 高光贴图。 */ __getset(0,__proto,'specularTexture',function(){ return this._getTexture(2); },function(value){ if (value) this._addShaderDefine(laya.d3.extension.cartoonRender.CartoonMaterial.SHADERDEFINE_SPECULARTEXTURE); else this._removeShaderDefine(laya.d3.extension.cartoonRender.CartoonMaterial.SHADERDEFINE_SPECULARTEXTURE); this._setTexture(2,value); }); /** *设置漫反射贴图。 *@param value 漫反射贴图。 */ /** *获取漫反射贴图。 *@return 漫反射贴图。 */ __getset(0,__proto,'albedoTexture',function(){ return this._getTexture(1); },function(value){ if (value) this._addShaderDefine(laya.d3.extension.cartoonRender.CartoonMaterial.SHADERDEFINE_ALBEDOTEXTURE); else this._removeShaderDefine(laya.d3.extension.cartoonRender.CartoonMaterial.SHADERDEFINE_ALBEDOTEXTURE); this._setTexture(1,value); }); /** *设置阴影颜色。 *@param value 阴影颜色。 */ /** *获取阴影颜色。 *@return 阴影颜色。 */ __getset(0,__proto,'shadowColor',function(){ return this._getColor(5); },function(value){ this._setColor(5,value); }); /** *设置阴影强度。 *@param value 阴影强度,范围为0到1。 */ /** *获取阴影强度。 *@return 阴影强度,范围为0到1。 */ __getset(0,__proto,'shadowIntensity',function(){ return this._getNumber(7); },function(value){ value=Math.max(0.0,Math.min(1.0,value)); this._setNumber(7,value); }); /** *设置阴影范围。 *@param value 阴影范围,范围为0到1。 */ /** *获取阴影范围。 *@return 阴影范围,范围为0到1。 */ __getset(0,__proto,'shadowRange',function(){ return this._getNumber(6); },function(value){ value=Math.max(0.0,Math.min(1.0,value)); this._setNumber(6,value); }); /** *设置纹理平铺和偏移。 *@param value 纹理平铺和偏移。 */ /** *获取纹理平铺和偏移。 *@return 纹理平铺和偏移。 */ __getset(0,__proto,'tilingOffset',function(){ return this._getColor(4); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(laya.d3.extension.cartoonRender.CartoonMaterial.SHADERDEFINE_TILINGOFFSET); else this._removeShaderDefine(laya.d3.extension.cartoonRender.CartoonMaterial.SHADERDEFINE_TILINGOFFSET); }else { this._removeShaderDefine(laya.d3.extension.cartoonRender.CartoonMaterial.SHADERDEFINE_TILINGOFFSET); } this._setColor(4,value); }); /** *设置高光范围。 *@param value 高光范围,范围为0.9到1。 */ /** *获取高光范围。 *@return 高光范围,范围为0.9到1。 */ __getset(0,__proto,'specularRange',function(){ return this._getNumber(8); },function(value){ value=Math.max(0.9,Math.min(1.0,value)); this._setNumber(8,value); }); /** *设置高光强度。 *@param value 高光范围,范围为0到1。 */ /** *获取高光强度。 *@return 高光强度,范围为0到1。 */ __getset(0,__proto,'specularIntensity',function(){ return this._getNumber(9); },function(value){ value=Math.max(0.0,Math.min(1.0,value)); this._setNumber(9,value); }); CartoonMaterial.__init__=function(){ CartoonMaterial.SHADERDEFINE_ALBEDOTEXTURE=CartoonMaterial.shaderDefines.registerDefine("DIFFUSETEXTURE"); CartoonMaterial.SHADERDEFINE_SPECULARTEXTURE=CartoonMaterial.shaderDefines.registerDefine("SPECULARTEXTURE"); } CartoonMaterial.initShader=function(){ var attributeMap={ 'a_Position':/*laya.d3.graphics.VertexElementUsage.POSITION0*/0, 'a_Normal':/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3, 'a_Texcoord0':/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2 }; var uniformMap={ 'u_MvpMatrix':[ /*laya.d3.core.Sprite3D.MVPMATRIX*/1,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_WorldMat':[ /*laya.d3.core.Sprite3D.WORLDMATRIX*/0,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_CameraPos':[ /*laya.d3.core.BaseCamera.CAMERAPOS*/0,/*laya.d3.shader.Shader3D.PERIOD_CAMERA*/3], 'u_AlbedoTexture':[ /*CLASS CONST:laya.d3.extension.cartoonRender.CartoonMaterial.ALBEDOTEXTURE*/1,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_SpecularTexture':[ /*CLASS CONST:laya.d3.extension.cartoonRender.CartoonMaterial.SPECULARTEXTURE*/2,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_ShadowColor':[ /*CLASS CONST:laya.d3.extension.cartoonRender.CartoonMaterial.SHADOWCOLOR*/5,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_ShadowRange':[ /*CLASS CONST:laya.d3.extension.cartoonRender.CartoonMaterial.SHADOWRANGE*/6,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_ShadowIntensity':[ /*CLASS CONST:laya.d3.extension.cartoonRender.CartoonMaterial.SHADOWINTENSITY*/7,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_SpecularRange':[ /*CLASS CONST:laya.d3.extension.cartoonRender.CartoonMaterial.SPECULARRANGE*/8,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_SpecularIntensity':[ /*CLASS CONST:laya.d3.extension.cartoonRender.CartoonMaterial.SPECULARINTENSITY*/9,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_DirectionLight.Direction':[ /*laya.d3.core.scene.Scene.LIGHTDIRECTION*/3,/*laya.d3.shader.Shader3D.PERIOD_SCENE*/4], 'u_DirectionLight.Color':[ /*laya.d3.core.scene.Scene.LIGHTDIRCOLOR*/4,/*laya.d3.shader.Shader3D.PERIOD_SCENE*/4] }; var cartoonShader=Shader3D.nameKey.add("CartoonShader"); var vs="attribute vec4 a_Position;\nattribute vec3 a_Normal;\nattribute vec2 a_Texcoord0;\n\nuniform mat4 u_MvpMatrix;\nuniform mat4 u_WorldMat;\nuniform vec3 u_CameraPos;\n\nvarying vec2 v_Texcoord0;\nvarying vec3 v_Normal;\nvarying vec3 v_PositionWorld;\nvarying vec3 v_ViewDir;\n\nvoid main()\n{\n gl_Position = u_MvpMatrix * a_Position;\n \n mat3 worldMat = mat3(u_WorldMat);\n v_PositionWorld = (u_WorldMat * a_Position).xyz;\n v_Normal = worldMat * a_Normal;\n v_Texcoord0 = a_Texcoord0;\n \n v_ViewDir = u_CameraPos - v_PositionWorld;\n}"; var ps="#ifdef FSHIGHPRECISION\n precision highp float;\n#else\n precision mediump float;\n#endif\n\nstruct DirectionLight\n{\n vec3 Color;\n vec3 Direction;\n};\n\nvarying vec2 v_Texcoord0;\nvarying vec3 v_Normal;\nvarying vec3 v_PositionWorld;\nvarying vec3 v_ViewDir;\n\n#ifdef ALBEDOTEXTURE\n uniform sampler2D u_AlbedoTexture;\n#endif\n\n#ifdef SPECULARTEXTURE\n uniform sampler2D u_SpecularTexture;\n#endif\n\nuniform vec4 u_ShadowColor;\nuniform float u_ShadowRange;\nuniform float u_ShadowIntensity;\nuniform float u_SpecularRange;\nuniform float u_SpecularIntensity;\n\nuniform DirectionLight u_DirectionLight;\n\nvoid main()\n{\n vec3 normal = normalize(v_Normal);\n vec3 viewdir = normalize(v_ViewDir);\n vec3 lightDir = normalize(u_DirectionLight.Direction);\n \n vec4 albedoTextureColor = vec4(1.0);\n #ifdef ALBEDOTEXTURE\n albedoTextureColor = texture2D(u_AlbedoTexture, v_Texcoord0);\n #endif\n \n vec4 specularTextureColor = vec4(1.0); \n #ifdef SPECULARTEXTURE\n specularTextureColor = texture2D(u_SpecularTexture, v_Texcoord0);\n #endif\n \n specularTextureColor = specularTextureColor;\n \n //specularTextureColor = vec4(1.0, 1.0, 1.0, 1.0);\n \n float specTexColorG = specularTextureColor.g;\n \n //Overlay BlendMode 叠加\n vec3 albedoColor;\n albedoColor.r = albedoTextureColor.r > 0.5 ? 1.0 - 2.0 * (1.0 - albedoTextureColor.r) * (1.0 - specTexColorG) : 2.0 * albedoTextureColor.r * specTexColorG;\n albedoColor.g = albedoTextureColor.g > 0.5 ? 1.0 - 2.0 * (1.0 - albedoTextureColor.g) * (1.0 - specTexColorG) : 2.0 * albedoTextureColor.g * specTexColorG;\n albedoColor.b = albedoTextureColor.b > 0.5 ? 1.0 - 2.0 * (1.0 - albedoTextureColor.b) * (1.0 - specTexColorG) : 2.0 * albedoTextureColor.b * specTexColorG;\n \n albedoColor = clamp(albedoColor, 0.0, 1.0);\n \n float nl = max(dot(normal, -lightDir), 0.0);\n \n float shadowValue = nl + specTexColorG - 0.5;\n float shadow = step(shadowValue, u_ShadowRange);\n if(u_ShadowRange > (shadowValue + 0.01))\n shadow = 1.0;\n else if(u_ShadowRange < (shadowValue - 0.01))\n shadow = 0.0;\n else\n shadow = (u_ShadowRange - (shadowValue - 0.01)) / 0.02;\n \n shadow = clamp(shadow, 0.0, 1.0);\n \n //specularTextureColor.r 影响高光范围\n float specular = step(u_SpecularRange, clamp(pow(nl, specularTextureColor.r), 0.0, 1.0));\n //specularTextureColor.b 影响高光强度\n specular = step(0.1, specular * specularTextureColor.b);\n \n vec3 albedoAreaColor = (1.0 - shadow) * albedoColor;\n vec3 shadowAreaColor = shadow * albedoColor * u_ShadowColor.rgb * u_ShadowIntensity;\n vec3 speculAreaColor = (1.0 - shadow) * albedoColor * u_SpecularIntensity * specular;\n \n vec3 finalColor = albedoAreaColor + speculAreaColor + shadowAreaColor;\n \n gl_FragColor = vec4(finalColor, 1.0);\n}\n"; var cartoonShaderCompile3D=ShaderCompile3D.add(cartoonShader,vs,ps,attributeMap,uniformMap); laya.d3.extension.cartoonRender.CartoonMaterial.SHADERDEFINE_ALBEDOTEXTURE=cartoonShaderCompile3D.registerMaterialDefine("ALBEDOTEXTURE"); laya.d3.extension.cartoonRender.CartoonMaterial.SHADERDEFINE_SPECULARTEXTURE=cartoonShaderCompile3D.registerMaterialDefine("SPECULARTEXTURE"); laya.d3.extension.cartoonRender.CartoonMaterial.SHADERDEFINE_TILINGOFFSET=cartoonShaderCompile3D.registerMaterialDefine("TILINGOFFSET"); } CartoonMaterial.ALBEDOTEXTURE=1; CartoonMaterial.SPECULARTEXTURE=2; CartoonMaterial.TILINGOFFSET=4; CartoonMaterial.SHADOWCOLOR=5; CartoonMaterial.SHADOWRANGE=6; CartoonMaterial.SHADOWINTENSITY=7; CartoonMaterial.SPECULARRANGE=8; CartoonMaterial.SPECULARINTENSITY=9; CartoonMaterial.SHADERDEFINE_ALBEDOTEXTURE=0; CartoonMaterial.SHADERDEFINE_SPECULARTEXTURE=0; CartoonMaterial.SHADERDEFINE_TILINGOFFSET=0; __static(CartoonMaterial, ['shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return CartoonMaterial; })(BaseMaterial) /** *... *@author ... */ //class laya.d3.extension.cartoonRender.OutlineMaterial extends laya.d3.core.material.BaseMaterial var OutlineMaterial=(function(_super){ function OutlineMaterial(){ OutlineMaterial.__super.call(this); this.setShaderName("OutlineShader"); this._setNumber(2,0.01581197); this._setNumber(3,1); } __class(OutlineMaterial,'laya.d3.extension.cartoonRender.OutlineMaterial',_super); var __proto=OutlineMaterial.prototype; /** *设置轮廓贴图。 *@param value 轮廓贴图。 */ /** *获取漫轮廓贴图。 *@return 轮廓贴图。 */ __getset(0,__proto,'outlineTexture',function(){ return this._getTexture(1); },function(value){ if (value) this._addShaderDefine(laya.d3.extension.cartoonRender.OutlineMaterial.SHADERDEFINE_OUTLINETEXTURE); else this._removeShaderDefine(laya.d3.extension.cartoonRender.OutlineMaterial.SHADERDEFINE_OUTLINETEXTURE); this._setTexture(1,value); }); /** *设置轮廓宽度。 *@param value 轮廓宽度,范围为0到0.05。 */ /** *获取轮廓宽度。 *@return 轮廓宽度,范围为0到0.05。 */ __getset(0,__proto,'outlineWidth',function(){ return this._getNumber(2); },function(value){ value=Math.max(0.0,Math.min(0.05,value)); this._setNumber(2,value); }); /** *设置轮廓亮度。 *@param value 轮廓亮度,范围为0到1。 */ /** *获取轮廓亮度。 *@return 轮廓亮度,范围为0到1。 */ __getset(0,__proto,'outlineLightness',function(){ return this._getNumber(3); },function(value){ value=Math.max(0.0,Math.min(1.0,value)); this._setNumber(3,value); }); OutlineMaterial.__init__=function(){ OutlineMaterial.SHADERDEFINE_OUTLINETEXTURE=OutlineMaterial.shaderDefines.registerDefine("OUTLINETEXTURE"); } OutlineMaterial.initShader=function(){ var attributeMap={ 'a_Position':/*laya.d3.graphics.VertexElementUsage.POSITION0*/0, 'a_Normal':/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3, 'a_Texcoord0':/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2 }; var uniformMap={ 'u_MvpMatrix':[ /*laya.d3.core.Sprite3D.MVPMATRIX*/1,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_OutlineTexture':[ /*CLASS CONST:laya.d3.extension.cartoonRender.OutlineMaterial.OUTLINETEXTURE*/1,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_OutlineWidth':[ /*CLASS CONST:laya.d3.extension.cartoonRender.OutlineMaterial.OUTLINEWIDTH*/2,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_OutlineLightness':[ /*CLASS CONST:laya.d3.extension.cartoonRender.OutlineMaterial.OUTLINELIGHTNESS*/3,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1] }; var outlineShader=Shader3D.nameKey.add("OutlineShader"); var vs="attribute vec4 a_Position;\nattribute vec3 a_Normal;\nattribute vec2 a_Texcoord0;\n\nuniform mat4 u_MvpMatrix;\nuniform float u_OutlineWidth;\n\nvarying vec2 v_Texcoord0;\n\nvoid main()\n{\n v_Texcoord0 = a_Texcoord0;\n \n vec4 position = vec4(a_Position.xyz + a_Normal * u_OutlineWidth, 1.0);\n gl_Position = u_MvpMatrix * position;\n}"; var ps="#ifdef FSHIGHPRECISION\n precision highp float;\n#else\n precision mediump float;\n#endif\n\nstruct DirectionLight\n{\n vec3 Color;\n vec3 Direction;\n};\n\nvarying vec2 v_Texcoord0;\n\n#ifdef OUTLINETEXTURE\n uniform sampler2D u_OutlineTexture;\n#endif\nuniform float u_OutlineLightness;\n\nvoid main()\n{\n vec4 outlineTextureColor = vec4(1.0);\n #ifdef OUTLINETEXTURE\n outlineTextureColor = texture2D(u_OutlineTexture, v_Texcoord0);\n #endif\n \n vec3 finalColor = outlineTextureColor.rgb * u_OutlineLightness;\n \n gl_FragColor = vec4(finalColor,0.0);\n}\n"; var outlineShaderCompile3D=ShaderCompile3D.add(outlineShader,vs,ps,attributeMap,uniformMap); laya.d3.extension.cartoonRender.OutlineMaterial.SHADERDEFINE_OUTLINETEXTURE=outlineShaderCompile3D.registerMaterialDefine("OUTLINETEXTURE"); } OutlineMaterial.OUTLINETEXTURE=1; OutlineMaterial.OUTLINEWIDTH=2; OutlineMaterial.OUTLINELIGHTNESS=3; OutlineMaterial.SHADERDEFINE_OUTLINETEXTURE=0; __static(OutlineMaterial, ['shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return OutlineMaterial; })(BaseMaterial) /** *... *@author */ //class laya.d3.extension.domino.DominoMaterial extends laya.d3.core.material.BaseMaterial var DominoMaterial=(function(_super){ function DominoMaterial(){ DominoMaterial.__super.call(this); this.setShaderName("DominoShader"); } __class(DominoMaterial,'laya.d3.extension.domino.DominoMaterial',_super); DominoMaterial.__init__=function(){} DominoMaterial.initShader=function(){ var attributeMap={ 'a_Position':/*laya.d3.graphics.VertexElementUsage.POSITION0*/0, 'a_Normal':/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3, 'a_Color' :/*laya.d3.graphics.VertexElementUsage.COLOR0*/1 }; var uniformMap={ 'u_MvpMatrix':[ /*laya.d3.core.Sprite3D.MVPMATRIX*/1,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_WorldMat':[ /*laya.d3.core.Sprite3D.WORLDMATRIX*/0,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_CameraPos':[ /*laya.d3.core.BaseCamera.CAMERAPOS*/0,/*laya.d3.shader.Shader3D.PERIOD_CAMERA*/3], 'u_DirectionLight.Direction':[ /*laya.d3.core.scene.Scene.LIGHTDIRECTION*/3,/*laya.d3.shader.Shader3D.PERIOD_SCENE*/4], 'u_DirectionLight.Color':[ /*laya.d3.core.scene.Scene.LIGHTDIRCOLOR*/4,/*laya.d3.shader.Shader3D.PERIOD_SCENE*/4], }; var dominoShader=Shader3D.nameKey.add("DominoShader"); var vs="attribute vec4 a_Position;\nattribute vec3 a_Normal;\nattribute vec2 a_Texcoord0;\nattribute vec4 a_Color;\n\nuniform mat4 u_MvpMatrix;\nuniform mat4 u_WorldMat;\nuniform vec3 u_CameraPos;\n\nvarying vec2 v_Texcoord0;\nvarying vec4 v_Color;\nvarying vec3 v_PositionWorld;\nvarying vec3 v_Normal;\nvarying vec3 v_ViewDir;\n\nvoid main()\n{\n v_Texcoord0 = a_Texcoord0;\n v_Color = a_Color;\n \n gl_Position = u_MvpMatrix * a_Position;\n \n v_Normal = mat3(u_WorldMat) * a_Normal;\n v_PositionWorld = (u_WorldMat * a_Position).xyz;\n v_ViewDir = u_CameraPos - v_PositionWorld;\n}"; var ps="#ifdef FSHIGHPRECISION\n precision highp float;\n#else\n precision mediump float;\n#endif\n\nstruct DirectionLight\n{\n vec3 Color;\n vec3 Direction;\n};\nuniform DirectionLight u_DirectionLight;\n\nvarying vec2 v_Texcoord0;\nvarying vec4 v_Color;\nvarying vec3 v_ViewDir; \nvarying vec3 v_Normal;\n\nvoid LayaAirBlinnPhongDiectionLight (in vec3 normal, in vec3 viewDir, in DirectionLight light,out vec3 diffuseColor)\n{\n vec3 lightVec = normalize(light.Direction);\n \n //mediump vec3 h = normalize(viewDir-light.Direction);\n //float nh = max (0.0, dot (h,normal));\n \n lowp float ln = max (0.0, dot (-lightVec,normal));\n diffuseColor = light.Color * ln;\n}\n\nvoid main()\n{\n vec3 diffuseColor;\n vec3 normal = normalize(v_Normal);\n vec3 viewDir = normalize(v_ViewDir);\n LayaAirBlinnPhongDiectionLight(normal, viewDir, u_DirectionLight, diffuseColor);\n \n gl_FragColor.xyz = diffuseColor * v_Color.xyz * 2.0;\n}\n\n"; var dominoShaderCompile3D=ShaderCompile3D.add(dominoShader,vs,ps,attributeMap,uniformMap); } __static(DominoMaterial, ['defaultMaterial',function(){return this.defaultMaterial=new DominoMaterial();},'shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return DominoMaterial; })(BaseMaterial) /** *... *@author */ //class laya.d3.extension.lineRender.LineMaterial extends laya.d3.core.material.BaseMaterial var LineMaterial=(function(_super){ function LineMaterial(){ LineMaterial.__super.call(this); this.setShaderName("LineShader"); this._setColor(2,new Vector4(1.0,1.0,1.0,1.0)); this.cull=0; } __class(LineMaterial,'laya.d3.extension.lineRender.LineMaterial',_super); var __proto=LineMaterial.prototype; /** *设置颜色。 *@param value 颜色。 */ /** *获取颜色。 *@return 颜色。 */ __getset(0,__proto,'tintColor',function(){ return this._getColor(2); },function(value){ this._setColor(2,value); }); /** *设置贴图。 *@param value 贴图。 */ /** *获取贴图。 *@return 贴图。 */ __getset(0,__proto,'diffuseTexture',function(){ return this._getTexture(1); },function(value){ if (value) this._addShaderDefine(laya.d3.extension.lineRender.LineMaterial.SHADERDEFINE_DIFFUSETEXTURE); else this._removeShaderDefine(laya.d3.extension.lineRender.LineMaterial.SHADERDEFINE_DIFFUSETEXTURE); this._setTexture(1,value); }); /** *设置纹理平铺和偏移。 *@param value 纹理平铺和偏移。 */ /** *获取纹理平铺和偏移。 *@return 纹理平铺和偏移。 */ __getset(0,__proto,'tilingOffset',function(){ return this._getColor(3); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(laya.d3.extension.lineRender.LineMaterial.SHADERDEFINE_TILINGOFFSET); else this._removeShaderDefine(laya.d3.extension.lineRender.LineMaterial.SHADERDEFINE_TILINGOFFSET); }else { this._removeShaderDefine(laya.d3.extension.lineRender.LineMaterial.SHADERDEFINE_TILINGOFFSET); } this._setColor(3,value); }); LineMaterial.__init__=function(){ LineMaterial.SHADERDEFINE_DIFFUSETEXTURE=LineMaterial.shaderDefines.registerDefine("DIFFUSETEXTURE"); LineMaterial.SHADERDEFINE_TILINGOFFSET=LineMaterial.shaderDefines.registerDefine("TILINGOFFSET"); } LineMaterial.load=function(url){ return Laya.loader.create(url,null,null,LineMaterial); } LineMaterial.initShader=function(){ var attributeMap={ 'a_Position':/*laya.d3.graphics.VertexElementUsage.POSITION0*/0, 'a_OffsetVector':/*laya.d3.graphics.VertexElementUsage.OFFSETVECTOR*/41, 'a_Texcoord0X' :/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0X*/38, 'a_Texcoord0X1' :/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0X1*/39, 'a_Texcoord0Y' :/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0Y*/40 }; var uniformMap={ 'u_MvpMatrix':[ /*laya.d3.core.Sprite3D.MVPMATRIX*/1,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_VMatrix':[ /*laya.d3.core.BaseCamera.VIEWMATRIX*/1,/*laya.d3.shader.Shader3D.PERIOD_CAMERA*/3], 'u_PMatrix':[ /*laya.d3.core.BaseCamera.PROJECTMATRIX*/2,/*laya.d3.shader.Shader3D.PERIOD_CAMERA*/3], 'u_TilingOffset':[ /*CLASS CONST:laya.d3.extension.lineRender.LineMaterial.TILINGOFFSET*/3,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_MainTexture':[ /*CLASS CONST:laya.d3.extension.lineRender.LineMaterial.DIFFUSETEXTURE*/1,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_MainColor':[ /*CLASS CONST:laya.d3.extension.lineRender.LineMaterial.TINTCOLOR*/2,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_WidthCurve' :[ /*laya.d3.extension.lineRender.LineSprite3D.WIDTHCURVE*/3,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_WidthCurveKeyLength' :[ /*laya.d3.extension.lineRender.LineSprite3D.WIDTHCURVEKEYLENGTH*/4,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_GradientColorkey' :[ /*laya.d3.extension.lineRender.LineSprite3D.GRADIENTCOLORKEY*/5,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_GradientAlphakey' :[ /*laya.d3.extension.lineRender.LineSprite3D.GRADIENTALPHAKEY*/6,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2] }; var lineShader=Shader3D.nameKey.add("LineShader"); var vs="attribute vec3 a_Position;\nattribute vec3 a_OffsetVector;\nattribute float a_Texcoord0X;\nattribute float a_Texcoord0X1;\nattribute float a_Texcoord0Y;\n\nuniform mat4 u_MvpMatrix;\nuniform mat4 u_VMatrix;\nuniform mat4 u_PMatrix;\n\nuniform vec4 u_TilingOffset;\n\nuniform vec4 u_WidthCurve[10];\nuniform int u_WidthCurveKeyLength;\n\nuniform vec4 u_GradientColorkey[10];\nuniform vec2 u_GradientAlphakey[10];\n\nvarying vec4 v_Color;\nvarying vec2 v_Texcoord0;\n\nfloat hermiteInterpolate(float t, float outTangent, float inTangent, float duration, float value1, float value2)\n{\n float t2 = t * t;\n float t3 = t2 * t;\n float a = 2.0 * t3 - 3.0 * t2 + 1.0;\n float b = t3 - 2.0 * t2 + t;\n float c = t3 - t2;\n float d = -2.0 * t3 + 3.0 * t2;\n return a * value1 + b * outTangent * duration + c * inTangent * duration + d * value2;\n}\n\nfloat getCurWidth(in float normalizeTime)\n{\n if(normalizeTime == 0.0){\n return u_WidthCurve[0].w;\n }\n else if(normalizeTime >= 1.0){\n return u_WidthCurve[u_WidthCurveKeyLength - 1].w;\n }\n else{\n for(int i = 0; i < 10; i ++ )\n {\n if(normalizeTime == u_WidthCurve[i].x)\n {\n return u_WidthCurve[i].w;\n }\n \n vec4 lastFrame = u_WidthCurve[i];\n vec4 nextFrame = u_WidthCurve[i + 1];\n if(normalizeTime > lastFrame.x && normalizeTime < nextFrame.x)\n {\n float duration = nextFrame.x - lastFrame.x;\n float t = (normalizeTime - lastFrame.x) / duration;\n float outTangent = lastFrame.z;\n float inTangent = nextFrame.y;\n float value1 = lastFrame.w;\n float value2 = nextFrame.w;\n return hermiteInterpolate(t, outTangent, inTangent, duration, value1, value2);\n }\n } \n }\n} \n\nvec4 getColorFromGradientByBlend(in vec4 gradientColors[10], in vec2 gradientAlphas[10], in float normalizeTime)\n{\n vec4 color;\n for(int i = 1; i < 10; i++)\n {\n vec4 gradientColor = gradientColors[i];\n float colorKey = gradientColor.w;\n if(colorKey >= normalizeTime)\n {\n vec4 lastGradientColor = gradientColors[i-1];\n float lastColorKey = lastGradientColor.w;\n float age = (normalizeTime - lastColorKey) / (colorKey - lastColorKey);\n color.rgb = mix(gradientColors[i-1].xyz, gradientColor.xyz, age);\n break;\n }\n }\n for(int i = 1; i < 10; i++)\n {\n vec2 gradientAlpha = gradientAlphas[i];\n float alphaKey = gradientAlpha.y;\n if(alphaKey >= normalizeTime)\n {\n vec2 lastGradientAlpha = gradientAlphas[i-1];\n float lastAlphaKey = lastGradientAlpha.y;\n float age = (normalizeTime - lastAlphaKey) / (alphaKey - lastAlphaKey);\n color.a = mix(lastGradientAlpha.x, gradientAlpha.x, age);\n break;\n }\n }\n return color;\n}\n\nvec4 getColorFromGradientByFixed(in vec4 gradientColors[10], in vec2 gradientAlphas[10], in float normalizeTime)\n{\n vec4 color;\n for(int i = 0; i < 10; i++)\n {\n vec4 gradientColor = gradientColors[i];\n if(gradientColor.w >= normalizeTime)\n {\n color.rgb = gradientColor.xyz;\n break;\n }\n }\n for(int i = 0; i < 10; i++)\n {\n vec2 gradientAlpha = gradientAlphas[i];\n if(gradientAlpha.y >= normalizeTime)\n {\n color.a = gradientAlpha.x;\n break;\n }\n }\n return color;\n}\n\nvoid main()\n{\n #ifdef TEXTUREMODE_STRETCH\n v_Texcoord0 = vec2(a_Texcoord0X, a_Texcoord0Y);\n #else\n v_Texcoord0 = vec2(a_Texcoord0X1, a_Texcoord0Y);\n #endif\n \n #ifdef TILINGOFFSET\n v_Texcoord0 = v_Texcoord0 * u_TilingOffset.xy + u_TilingOffset.zw;\n #endif\n \n #ifdef GRADIENTMODE_BLEND\n v_Color = getColorFromGradientByBlend(u_GradientColorkey, u_GradientAlphakey, a_Texcoord0X);\n #else\n v_Color = getColorFromGradientByFixed(u_GradientColorkey, u_GradientAlphakey, a_Texcoord0X);\n #endif\n \n #ifdef WORLDSPACE\n gl_Position = u_PMatrix * u_VMatrix * vec4(a_Position + a_OffsetVector * getCurWidth(a_Texcoord0X),1.0);\n #else\n gl_Position = u_MvpMatrix * vec4(a_Position + a_OffsetVector * getCurWidth(a_Texcoord0X),1.0);\n #endif\n}"; var ps="#ifdef FSHIGHPRECISION\n precision highp float;\n#else\n precision mediump float;\n#endif\n\nuniform sampler2D u_MainTexture;\nuniform vec4 u_MainColor;\n\nvarying vec2 v_Texcoord0;\nvarying vec4 v_Color;\n\nvoid main()\n{\n vec4 color = 2.0 * u_MainColor * v_Color;\n #ifdef DIFFUSETEXTURE\n vec4 mainTextureColor = texture2D(u_MainTexture, v_Texcoord0);\n color *= mainTextureColor;\n #endif\n gl_FragColor = color;\n}\n\n"; var lineShaderCompile3D=ShaderCompile3D.add(lineShader,vs,ps,attributeMap,uniformMap); laya.d3.extension.lineRender.LineMaterial.SHADERDEFINE_DIFFUSETEXTURE=lineShaderCompile3D.registerMaterialDefine("DIFFUSETEXTURE"); laya.d3.extension.lineRender.LineMaterial.SHADERDEFINE_TILINGOFFSET=lineShaderCompile3D.registerMaterialDefine("TILINGOFFSET"); LineSprite3D.SHADERDEFINE_GRADIENTMODE_BLEND=lineShaderCompile3D.registerSpriteDefine("GRADIENTMODE_BLEND"); LineSprite3D.SHADERDEFINE_TEXTUREMODE_STRETCH=lineShaderCompile3D.registerSpriteDefine("TEXTUREMODE_STRETCH"); LineSprite3D.SHADERDEFINE_WORLDSPACE=lineShaderCompile3D.registerSpriteDefine("WORLDSPACE"); } LineMaterial.SHADERDEFINE_DIFFUSETEXTURE=0; LineMaterial.SHADERDEFINE_TILINGOFFSET=0; LineMaterial.DIFFUSETEXTURE=1; LineMaterial.TINTCOLOR=2; LineMaterial.TILINGOFFSET=3; __static(LineMaterial, ['defaultMaterial',function(){return this.defaultMaterial=new LineMaterial();},'shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return LineMaterial; })(BaseMaterial) /** *... *@author */ //class laya.d3.extension.lulingmen.DissolveMaterial extends laya.d3.core.material.BaseMaterial var DissolveMaterial=(function(_super){ function DissolveMaterial(){ DissolveMaterial.__super.call(this); this.setShaderName("Dissolve"); this._setColor(9,new Vector4(1,1,1,1)); this._setNumber(7,0.0); this._setNumber(8,5.0); } __class(DissolveMaterial,'laya.d3.extension.lulingmen.DissolveMaterial',_super); var __proto=DissolveMaterial.prototype; /** *设置基础颜色。 *@param value 基础颜色。 */ /** *获取基础颜色。 *@return 基础颜色。 */ __getset(0,__proto,'albedoColor',function(){ return this._getColor(9); },function(value){ this._setColor(9,value); }); /** *设置主贴图。 *@param value 主贴图。 */ /** *获取主贴图。 *@return 主贴图。 */ __getset(0,__proto,'mainTexture',function(){ return this._getTexture(1); },function(value){ if (value) this._addShaderDefine(laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_MAINTEXTURE); else this._removeShaderDefine(laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_MAINTEXTURE); this._setTexture(1,value); }); /** *设置溶解速率。 *@param value 溶解速率。 */ /** *获取溶解速率。 *@return 溶解速率。 */ __getset(0,__proto,'dissolveSpeed',function(){ return this._getNumber(8); },function(value){ this._setNumber(8,value); }); /** *设置主纹理平铺和偏移。 *@param value 主纹理平铺和偏移。 */ /** *获取主纹理平铺和偏移。 *@return 主纹理平铺和偏移。 */ __getset(0,__proto,'tilingOffset',function(){ return this._getColor(4); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_MAINTILINGOFFSET); else this._removeShaderDefine(laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_MAINTILINGOFFSET); }else { this._removeShaderDefine(laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_MAINTILINGOFFSET); } this._setColor(4,value); }); /** *设置溶解贴图。 *@param value 溶解贴图。 */ /** *获取溶解贴图。 *@return 溶解贴图。 */ __getset(0,__proto,'dissolveTexture',function(){ return this._getTexture(2); },function(value){ if (value) this._addShaderDefine(laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_DISSOLVETEXTURE); else this._removeShaderDefine(laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_DISSOLVETEXTURE); this._setTexture(2,value); }); /** *设置遮罩贴图。 *@param value 遮罩贴图。 */ /** *获取遮罩贴图。 *@return 遮罩贴图。 */ __getset(0,__proto,'maskTexture',function(){ return this._getTexture(3); },function(value){ if (value) this._addShaderDefine(laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_MASKTEXTURE); else this._removeShaderDefine(laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_MASKTEXTURE); this._setTexture(3,value); }); /** *设置溶解纹理平铺和偏移。 *@param value 溶解纹理平铺和偏移。 */ /** *获取溶解纹理平铺和偏移。 *@return 溶解纹理平铺和偏移。 */ __getset(0,__proto,'dissolveTilingOffset',function(){ return this._getColor(5); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_DISSOLVETILINGOFFSET); else this._removeShaderDefine(laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_DISSOLVETILINGOFFSET); }else { this._removeShaderDefine(laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_DISSOLVETILINGOFFSET); } this._setColor(5,value); }); /** *设置遮罩纹理平铺和偏移。 *@param value 遮罩纹理平铺和偏移。 */ /** *获取遮罩纹理平铺和偏移。 *@return 遮罩纹理平铺和偏移。 */ __getset(0,__proto,'maskTilingOffset',function(){ return this._getColor(6); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_MASKTILINGOFFSET); else this._removeShaderDefine(laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_MASKTILINGOFFSET); }else { this._removeShaderDefine(laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_MASKTILINGOFFSET); } this._setColor(6,value); }); /** *设置溶解值。 *@param value 溶解值。 */ /** *获取溶解值。 *@return 溶解值。 */ __getset(0,__proto,'dissolve',function(){ return this._getNumber(7); },function(value){ this._setNumber(7,value); }); DissolveMaterial.__init__=function(){ DissolveMaterial.SHADERDEFINE_MAINTEXTURE=DissolveMaterial.shaderDefines.registerDefine("MAINTEXTURE"); DissolveMaterial.SHADERDEFINE_DISSOLVETEXTURE=DissolveMaterial.shaderDefines.registerDefine("DISSOLVETEXTURE"); DissolveMaterial.SHADERDEFINE_MASKTEXTURE=DissolveMaterial.shaderDefines.registerDefine("MASKTEXTURE"); DissolveMaterial.SHADERDEFINE_MAINTILINGOFFSET=DissolveMaterial.shaderDefines.registerDefine("MAINTILINGOFFSET"); DissolveMaterial.SHADERDEFINE_DISSOLVETILINGOFFSET=DissolveMaterial.shaderDefines.registerDefine("DISSOLVETILINGOFFSET"); DissolveMaterial.SHADERDEFINE_MASKTILINGOFFSET=DissolveMaterial.shaderDefines.registerDefine("MASKTILINGOFFSET"); } DissolveMaterial.initShader=function(){ var attributeMap={ 'a_Position':/*laya.d3.graphics.VertexElementUsage.POSITION0*/0, 'a_Normal':/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3, 'a_Texcoord0':/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2 }; var uniformMap={ 'u_MvpMatrix':[ /*laya.d3.core.Sprite3D.MVPMATRIX*/1,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_MainTexture':[ /*CLASS CONST:laya.d3.extension.lulingmen.DissolveMaterial.MAINTEXTURE*/1,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_DissolveTexture':[ /*CLASS CONST:laya.d3.extension.lulingmen.DissolveMaterial.DISSOLVETEXTURE*/2,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_MaskTexture':[ /*CLASS CONST:laya.d3.extension.lulingmen.DissolveMaterial.MASKTEXTURE*/3,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_BaseColor':[ /*CLASS CONST:laya.d3.extension.lulingmen.DissolveMaterial.BASECOLOR*/9,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_MainTilingOffset':[ /*CLASS CONST:laya.d3.extension.lulingmen.DissolveMaterial.MAINTILINGOFFSET*/4,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_DissolveTilingOffset':[ /*CLASS CONST:laya.d3.extension.lulingmen.DissolveMaterial.DISSOLVETILINGOFFSET*/5,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_MaskTilingOffset':[ /*CLASS CONST:laya.d3.extension.lulingmen.DissolveMaterial.MASKTILINGOFFSET*/6,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_Dissolve':[ /*CLASS CONST:laya.d3.extension.lulingmen.DissolveMaterial.DISSOLVE*/7,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_DissolveSpeed':[ /*CLASS CONST:laya.d3.extension.lulingmen.DissolveMaterial.DISSOLVESPEED*/8,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1] }; var shader=Shader3D.nameKey.add("Dissolve"); var vs="attribute vec4 a_Position;\nattribute vec3 a_Normal;\nattribute vec2 a_Texcoord0;\n\nuniform mat4 u_MvpMatrix;\n\nuniform vec4 u_MainTilingOffset;\nuniform vec4 u_DissolveTilingOffset;\nuniform vec4 u_MaskTilingOffset;\n\nvarying vec2 v_Texcoord0;\nvarying vec2 v_Texcoord1;\nvarying vec2 v_Texcoord2;\n\nvoid main()\n{\n v_Texcoord0 = a_Texcoord0;\n #ifdef MAINTILINGOFFSET\n v_Texcoord0 = (vec2(v_Texcoord0.x, v_Texcoord0.y - 1.0) * u_MainTilingOffset.xy) + u_MainTilingOffset.zw;\n v_Texcoord0 = vec2(v_Texcoord0.x, 1.0 + v_Texcoord0.y);\n #endif\n \n v_Texcoord1 = a_Texcoord0;\n #ifdef DISSOLVETILINGOFFSET\n v_Texcoord1 = (vec2(v_Texcoord1.x, v_Texcoord1.y - 1.0) * u_DissolveTilingOffset.xy) + u_DissolveTilingOffset.zw;\n v_Texcoord1 = vec2(v_Texcoord1.x, 1.0 + v_Texcoord1.y);\n #endif\n \n v_Texcoord2 = a_Texcoord0;\n \n gl_Position = u_MvpMatrix * a_Position;\n}"; var ps="#ifdef FSHIGHPRECISION\n precision highp float;\n#else\n precision mediump float;\n#endif\n\nvarying vec2 v_Texcoord0;\nvarying vec2 v_Texcoord1;\nvarying vec2 v_Texcoord2;\n\n#ifdef MAINTEXTURE\n uniform sampler2D u_MainTexture;\n#endif\n\n#ifdef DISSOLVETEXTURE\n uniform sampler2D u_DissolveTexture;\n#endif\n\n#ifdef MASKTEXTURE\n uniform sampler2D u_MaskTexture;\n#endif\n\nuniform vec4 u_BaseColor;\nuniform float u_Dissolve;\nuniform float u_DissolveSpeed;\n\nvoid main()\n{\n vec4 mainColor = u_BaseColor;\n mainColor.a = 1.0;\n #ifdef MAINTEXTURE\n mainColor *= texture2D(u_MainTexture, v_Texcoord0);\n #endif\n \n vec4 dissolveColor = vec4(1.0);\n #ifdef DISSOLVETEXTURE\n dissolveColor = texture2D(u_DissolveTexture, v_Texcoord1);\n #endif\n \n vec4 maskColor = vec4(1.0);\n #ifdef MASKTEXTURE\n maskColor = texture2D(u_MaskTexture, v_Texcoord2);\n #endif\n \n vec4 outColor = mix(vec4(0.0), mainColor, maskColor);\n if(dissolveColor.a <= u_Dissolve){\n float alpha = clamp(outColor.a - u_Dissolve * 2.0 + dissolveColor.a, 0.0, 1.0);\n alpha = pow(alpha, u_DissolveSpeed);\n outColor.a = alpha;\n }\n \n gl_FragColor = outColor;\n}\n"; var shaderCompile3D=ShaderCompile3D.add(shader,vs,ps,attributeMap,uniformMap); laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_MAINTEXTURE=shaderCompile3D.registerMaterialDefine("MAINTEXTURE"); laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_DISSOLVETEXTURE=shaderCompile3D.registerMaterialDefine("DISSOLVETEXTURE"); laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_MASKTEXTURE=shaderCompile3D.registerMaterialDefine("MASKTEXTURE"); laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_MAINTILINGOFFSET=shaderCompile3D.registerMaterialDefine("MAINTILINGOFFSET"); laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_DISSOLVETILINGOFFSET=shaderCompile3D.registerMaterialDefine("DISSOLVETILINGOFFSET"); laya.d3.extension.lulingmen.DissolveMaterial.SHADERDEFINE_MASKTILINGOFFSET=shaderCompile3D.registerMaterialDefine("MASKTILINGOFFSET"); } DissolveMaterial.MAINTEXTURE=1; DissolveMaterial.DISSOLVETEXTURE=2; DissolveMaterial.MASKTEXTURE=3; DissolveMaterial.MAINTILINGOFFSET=4; DissolveMaterial.DISSOLVETILINGOFFSET=5; DissolveMaterial.MASKTILINGOFFSET=6; DissolveMaterial.DISSOLVE=7; DissolveMaterial.DISSOLVESPEED=8; DissolveMaterial.BASECOLOR=9; DissolveMaterial.SHADERDEFINE_MAINTEXTURE=0; DissolveMaterial.SHADERDEFINE_DISSOLVETEXTURE=0; DissolveMaterial.SHADERDEFINE_MASKTEXTURE=0; DissolveMaterial.SHADERDEFINE_MAINTILINGOFFSET=0; DissolveMaterial.SHADERDEFINE_DISSOLVETILINGOFFSET=0; DissolveMaterial.SHADERDEFINE_MASKTILINGOFFSET=0; __static(DissolveMaterial, ['shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return DissolveMaterial; })(BaseMaterial) /** *... *@author */ //class laya.d3.extension.lulingmen.MeshParticleMaterial extends laya.d3.core.material.BaseMaterial var MeshParticleMaterial=(function(_super){ function MeshParticleMaterial(){ MeshParticleMaterial.__super.call(this); this.setShaderName("MeshParticle"); this._setColor(3,new Vector4(1,1,1,1)); this._setColor(4,new Vector4(1,1,1,1)); this._setNumber(5,1.0); this._setNumber(6,1.0); } __class(MeshParticleMaterial,'laya.d3.extension.lulingmen.MeshParticleMaterial',_super); var __proto=MeshParticleMaterial.prototype; __getset(0,__proto,'alpha',function(){ return this._getNumber(6); },function(value){ value=Math.max(0.0,Math.min(1.0,value)); this._setNumber(6,value); }); /** *设置第一层贴图。 *@param value 第一层贴图。 */ /** *获取第一层贴图。 *@return 第一层贴图。 */ __getset(0,__proto,'mainTexture',function(){ return this._getTexture(1); },function(value){ if (value) this._addShaderDefine(laya.d3.extension.lulingmen.MeshParticleMaterial.SHADERDEFINE_MAINTEXTURE); else this._removeShaderDefine(laya.d3.extension.lulingmen.MeshParticleMaterial.SHADERDEFINE_MAINTEXTURE); this._setTexture(1,value); }); /** *设置第二层贴图。 *@param value 第二层贴图。 */ /** *获取第二层贴图。 *@return 第二层贴图。 */ __getset(0,__proto,'maskTexture',function(){ return this._getTexture(2); },function(value){ if (value) this._addShaderDefine(laya.d3.extension.lulingmen.MeshParticleMaterial.SHADERDEFINE_MASKTEXTURE); else this._removeShaderDefine(laya.d3.extension.lulingmen.MeshParticleMaterial.SHADERDEFINE_MASKTEXTURE); this._setTexture(2,value); }); /** *设置基础颜色。 *@param value 基础颜色。 */ /** *获取基础颜色。 *@return 基础颜色。 */ __getset(0,__proto,'albedoColor',function(){ return this._getColor(3); },function(value){ this._setColor(3,value); }); __getset(0,__proto,'intensity',function(){ return this._getNumber(5); },function(value){ this._setNumber(5,value); }); /** *设置透明颜色。 *@param value 透明颜色。 */ /** *获取透明颜色。 *@return 透明颜色。 */ __getset(0,__proto,'alphaColor',function(){ return this._getColor(4); },function(value){ this._setColor(4,value); }); /** *设置纹理平铺和偏移。 *@param value 纹理平铺和偏移。 */ /** *获取纹理平铺和偏移。 *@return 纹理平铺和偏移。 */ __getset(0,__proto,'tilingOffset',function(){ return this._getColor(7); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(laya.d3.extension.lulingmen.MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET1); else this._removeShaderDefine(laya.d3.extension.lulingmen.MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET1); }else { this._removeShaderDefine(laya.d3.extension.lulingmen.MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET1); } this._setColor(7,value); }); /** *设置纹理平铺和偏移。 *@param value 纹理平铺和偏移。 */ /** *获取纹理平铺和偏移。 *@return 纹理平铺和偏移。 */ __getset(0,__proto,'maskTilingOffset',function(){ return this._getColor(8); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(laya.d3.extension.lulingmen.MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET2); else this._removeShaderDefine(laya.d3.extension.lulingmen.MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET2); }else { this._removeShaderDefine(laya.d3.extension.lulingmen.MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET2); } this._setColor(8,value); }); MeshParticleMaterial.__init__=function(){ MeshParticleMaterial.SHADERDEFINE_MAINTEXTURE=MeshParticleMaterial.shaderDefines.registerDefine("MAINTEXTURE"); MeshParticleMaterial.SHADERDEFINE_MASKTEXTURE=MeshParticleMaterial.shaderDefines.registerDefine("MASKTEXTURE"); MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET1=MeshParticleMaterial.shaderDefines.registerDefine("TILINGOFFSET1"); MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET2=MeshParticleMaterial.shaderDefines.registerDefine("TILINGOFFSET2"); } MeshParticleMaterial.initShader=function(){ var attributeMap={ 'a_Position':/*laya.d3.graphics.VertexElementUsage.POSITION0*/0, 'a_Normal':/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3, 'a_Color':/*laya.d3.graphics.VertexElementUsage.COLOR0*/1, 'a_Texcoord0':/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2 }; var uniformMap={ 'u_MvpMatrix':[ /*laya.d3.core.Sprite3D.MVPMATRIX*/1,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_MainTexture':[ /*CLASS CONST:laya.d3.extension.lulingmen.MeshParticleMaterial.MAINTEXTURE*/1,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_MaskTexture':[ /*CLASS CONST:laya.d3.extension.lulingmen.MeshParticleMaterial.MASKTEXTURE*/2,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_BaseColor':[ /*CLASS CONST:laya.d3.extension.lulingmen.MeshParticleMaterial.BASECOLOR*/3,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_AlphaColor':[ /*CLASS CONST:laya.d3.extension.lulingmen.MeshParticleMaterial.ALPHACOLOR*/4,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_Instensity':[ /*CLASS CONST:laya.d3.extension.lulingmen.MeshParticleMaterial.INTENSITY*/5,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_Alpha':[ /*CLASS CONST:laya.d3.extension.lulingmen.MeshParticleMaterial.ALPHA*/6,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_TilingOffset1':[ /*CLASS CONST:laya.d3.extension.lulingmen.MeshParticleMaterial.TILINGOFFSET1*/7,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_TilingOffset2':[ /*CLASS CONST:laya.d3.extension.lulingmen.MeshParticleMaterial.TILINGOFFSET2*/8,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1] }; var shader=Shader3D.nameKey.add("MeshParticle"); var vs="attribute vec4 a_Position;\nattribute vec3 a_Normal;\nattribute vec2 a_Texcoord0;\nattribute vec4 a_Color;\n\nuniform mat4 u_MvpMatrix;\n\nuniform vec4 u_TilingOffset1;\nuniform vec4 u_TilingOffset2;\n\nvarying vec2 v_Texcoord0;\nvarying vec2 v_Texcoord1;\nvarying vec4 v_Color;\n\nvoid main()\n{\n v_Texcoord0 = a_Texcoord0;\n #ifdef TILINGOFFSET1\n v_Texcoord0 = (vec2(v_Texcoord0.x, v_Texcoord0.y - 1.0) * u_TilingOffset1.xy) + u_TilingOffset1.zw;\n v_Texcoord0 = vec2(v_Texcoord0.x, 1.0 + v_Texcoord0.y);\n #endif\n \n v_Texcoord1 = a_Texcoord0;\n #ifdef TILINGOFFSET2\n v_Texcoord1 = (vec2(v_Texcoord1.x, v_Texcoord1.y - 1.0) * u_TilingOffset2.xy) + u_TilingOffset2.zw;\n v_Texcoord1 = vec2(v_Texcoord1.x, 1.0 + v_Texcoord1.y);\n #endif\n \n v_Color = vec4(1.0);\n #ifdef COLOR\n v_Color = a_Color;\n #endif\n \n gl_Position = u_MvpMatrix * a_Position;\n}"; var ps="#ifdef FSHIGHPRECISION\n precision highp float;\n#else\n precision mediump float;\n#endif\n\nvarying vec2 v_Texcoord0;\nvarying vec2 v_Texcoord1;\nvarying vec4 v_Color;\n\n#ifdef MAINTEXTURE\n uniform sampler2D u_MainTexture;\n#endif\n\n#ifdef MASKTEXTURE\n uniform sampler2D u_MaskTexture;\n#endif\n\nuniform vec4 u_BaseColor;\nuniform vec4 u_AlphaColor;\nuniform float u_Instensity;\nuniform float u_Alpha;\n\nvoid main()\n{\n vec4 mainTextureColor = vec4(1.0);\n #ifdef MAINTEXTURE\n mainTextureColor = texture2D(u_MainTexture, v_Texcoord0);\n #endif\n \n vec4 maskTextureColor = vec4(1.0);\n #ifdef MASKTEXTURE\n maskTextureColor = texture2D(u_MaskTexture, v_Texcoord1);\n #endif\n \n vec4 outColor = mix(vec4(0.0), mainTextureColor, maskTextureColor);\n \n gl_FragColor = 2.0 * outColor * u_BaseColor * u_AlphaColor * u_Instensity * v_Color;\n gl_FragColor.a *= u_Alpha;\n}\n"; var shaderCompile3D=ShaderCompile3D.add(shader,vs,ps,attributeMap,uniformMap); laya.d3.extension.lulingmen.MeshParticleMaterial.SHADERDEFINE_MAINTEXTURE=shaderCompile3D.registerMaterialDefine("MAINTEXTURE"); laya.d3.extension.lulingmen.MeshParticleMaterial.SHADERDEFINE_MASKTEXTURE=shaderCompile3D.registerMaterialDefine("MASKTEXTURE"); laya.d3.extension.lulingmen.MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET1=shaderCompile3D.registerMaterialDefine("TILINGOFFSET1"); laya.d3.extension.lulingmen.MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET2=shaderCompile3D.registerMaterialDefine("TILINGOFFSET2"); } MeshParticleMaterial.MAINTEXTURE=1; MeshParticleMaterial.MASKTEXTURE=2; MeshParticleMaterial.BASECOLOR=3; MeshParticleMaterial.ALPHACOLOR=4; MeshParticleMaterial.INTENSITY=5; MeshParticleMaterial.ALPHA=6; MeshParticleMaterial.TILINGOFFSET1=7; MeshParticleMaterial.TILINGOFFSET2=8; MeshParticleMaterial.SHADERDEFINE_MAINTEXTURE=0; MeshParticleMaterial.SHADERDEFINE_MASKTEXTURE=0; MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET1=0; MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET2=0; __static(MeshParticleMaterial, ['shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return MeshParticleMaterial; })(BaseMaterial) /** *... *@author */ //class laya.d3.extension.lulingmen.ParticleMaterial extends laya.d3.core.material.BaseMaterial var ParticleMaterial=(function(_super){ function ParticleMaterial(){ ParticleMaterial.__super.call(this); this.setShaderName("Particle"); this._setColor(3,new Vector4(1,1,1,1)); this._setColor(4,new Vector4(1,1,1,1)); this._setNumber(5,1.0); this._setNumber(6,1.0); } __class(ParticleMaterial,'laya.d3.extension.lulingmen.ParticleMaterial',_super); var __proto=ParticleMaterial.prototype; __getset(0,__proto,'alpha',function(){ return this._getNumber(6); },function(value){ value=Math.max(0.0,Math.min(1.0,value)); this._setNumber(6,value); }); /** *设置基础颜色。 *@param value 基础颜色。 */ /** *获取基础颜色。 *@return 基础颜色。 */ __getset(0,__proto,'tintColor',function(){ return this._getColor(3); },function(value){ this._setColor(3,value); }); /** *设置第一层贴图。 *@param value 第一层贴图。 */ /** *获取第一层贴图。 *@return 第一层贴图。 */ __getset(0,__proto,'mainTexture',function(){ return this._getTexture(1); },function(value){ if (value) this._addShaderDefine(MeshParticleMaterial.SHADERDEFINE_MAINTEXTURE); else this._removeShaderDefine(MeshParticleMaterial.SHADERDEFINE_MAINTEXTURE); this._setTexture(1,value); }); /** *设置第二层贴图。 *@param value 第二层贴图。 */ /** *获取第二层贴图。 *@return 第二层贴图。 */ __getset(0,__proto,'maskTexture',function(){ return this._getTexture(2); },function(value){ if (value) this._addShaderDefine(MeshParticleMaterial.SHADERDEFINE_MASKTEXTURE); else this._removeShaderDefine(MeshParticleMaterial.SHADERDEFINE_MASKTEXTURE); this._setTexture(2,value); }); __getset(0,__proto,'intensity',function(){ return this._getNumber(5); },function(value){ this._setNumber(5,value); }); /** *设置透明颜色。 *@param value 透明颜色。 */ /** *获取透明颜色。 *@return 透明颜色。 */ __getset(0,__proto,'alphaColor',function(){ return this._getColor(4); },function(value){ this._setColor(4,value); }); /** *设置纹理平铺和偏移。 *@param value 纹理平铺和偏移。 */ /** *获取纹理平铺和偏移。 *@return 纹理平铺和偏移。 */ __getset(0,__proto,'tilingOffset',function(){ return this._getColor(7); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET1); else this._removeShaderDefine(MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET1); }else { this._removeShaderDefine(MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET1); } this._setColor(7,value); }); /** *设置纹理平铺和偏移。 *@param value 纹理平铺和偏移。 */ /** *获取纹理平铺和偏移。 *@return 纹理平铺和偏移。 */ __getset(0,__proto,'maskTilingOffset',function(){ return this._getColor(8); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET2); else this._removeShaderDefine(MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET2); }else { this._removeShaderDefine(MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET2); } this._setColor(8,value); }); ParticleMaterial.__init__=function(){ ParticleMaterial.SHADERDEFINE_MAINTEXTURE=ParticleMaterial.shaderDefines.registerDefine("MAINTEXTURE"); ParticleMaterial.SHADERDEFINE_MASKTEXTURE=ParticleMaterial.shaderDefines.registerDefine("MASKTEXTURE"); ParticleMaterial.SHADERDEFINE_TILINGOFFSET1=ParticleMaterial.shaderDefines.registerDefine("TILINGOFFSET1"); ParticleMaterial.SHADERDEFINE_TILINGOFFSET2=ParticleMaterial.shaderDefines.registerDefine("TILINGOFFSET2"); } ParticleMaterial.initShader=function(){ var attributeMap={ 'a_CornerTextureCoordinate':/*laya.d3.graphics.VertexElementUsage.CORNERTEXTURECOORDINATE0*/17, 'a_MeshPosition':/*laya.d3.graphics.VertexElementUsage.POSITION0*/0, 'a_MeshColor':/*laya.d3.graphics.VertexElementUsage.COLOR0*/1, 'a_MeshTextureCoordinate':/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2, 'a_ShapePositionStartLifeTime':/*laya.d3.graphics.VertexElementUsage.SHAPEPOSITIONSTARTLIFETIME*/30, 'a_DirectionTime':/*laya.d3.graphics.VertexElementUsage.DIRECTIONTIME*/32, 'a_StartColor':/*laya.d3.graphics.VertexElementUsage.STARTCOLOR0*/19, 'a_EndColor':/*laya.d3.graphics.VertexElementUsage.ENDCOLOR0*/23, 'a_StartSize':/*laya.d3.graphics.VertexElementUsage.STARTSIZE*/20, 'a_StartRotation0':/*laya.d3.graphics.VertexElementUsage.STARTROTATION*/22, 'a_StartSpeed':/*laya.d3.graphics.VertexElementUsage.STARTSPEED*/31, 'a_Random0':/*laya.d3.graphics.VertexElementUsage.RANDOM0*/34, 'a_Random1':/*laya.d3.graphics.VertexElementUsage.RANDOM1*/35, 'a_SimulationWorldPostion':/*laya.d3.graphics.VertexElementUsage.SIMULATIONWORLDPOSTION*/36, 'a_SimulationWorldRotation':/*laya.d3.graphics.VertexElementUsage.SIMULATIONWORLDROTATION*/37 }; var uniformMap={ 'u_MainTexture':[ /*laya.d3.extension.lulingmen.MeshParticleMaterial.MAINTEXTURE*/1,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_MaskTexture':[ /*laya.d3.extension.lulingmen.MeshParticleMaterial.MASKTEXTURE*/2,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_BaseColor':[ /*laya.d3.extension.lulingmen.MeshParticleMaterial.BASECOLOR*/3,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_AlphaColor':[ /*laya.d3.extension.lulingmen.MeshParticleMaterial.ALPHACOLOR*/4,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_Instensity':[ /*laya.d3.extension.lulingmen.MeshParticleMaterial.INTENSITY*/5,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_Alpha':[ /*laya.d3.extension.lulingmen.MeshParticleMaterial.ALPHA*/6,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_TilingOffset1':[ /*laya.d3.extension.lulingmen.MeshParticleMaterial.TILINGOFFSET1*/7,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_TilingOffset2':[ /*laya.d3.extension.lulingmen.MeshParticleMaterial.TILINGOFFSET2*/8,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_WorldPosition':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.WORLDPOSITION*/0,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_WorldRotation':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.WORLDROTATION*/1,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_PositionScale':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.POSITIONSCALE*/4,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_SizeScale':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SIZESCALE*/5,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ScalingMode':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SCALINGMODE*/6,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_Gravity':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.GRAVITY*/7,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ThreeDStartRotation':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.THREEDSTARTROTATION*/8,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_StretchedBillboardLengthScale':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.STRETCHEDBILLBOARDLENGTHSCALE*/9,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_StretchedBillboardSpeedScale':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.STRETCHEDBILLBOARDSPEEDSCALE*/10,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_SimulationSpace':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SIMULATIONSPACE*/11,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_CurrentTime':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.CURRENTTIME*/12,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ColorOverLifeGradientAlphas':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.COLOROVERLIFEGRADIENTALPHAS*/22,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ColorOverLifeGradientColors':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.COLOROVERLIFEGRADIENTCOLORS*/23,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_MaxColorOverLifeGradientAlphas':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.MAXCOLOROVERLIFEGRADIENTALPHAS*/24,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_MaxColorOverLifeGradientColors':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.MAXCOLOROVERLIFEGRADIENTCOLORS*/25,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_VOLVelocityConst':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYCONST*/13,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_VOLVelocityGradientX':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTX*/14,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_VOLVelocityGradientY':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTY*/15,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_VOLVelocityGradientZ':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTZ*/16,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_VOLVelocityConstMax':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYCONSTMAX*/17,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_VOLVelocityGradientMaxX':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTXMAX*/18,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_VOLVelocityGradientMaxY':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTYMAX*/19,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_VOLVelocityGradientMaxZ':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLVELOCITYGRADIENTZMAX*/20,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_VOLSpaceType':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.VOLSPACETYPE*/21,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_SOLSizeGradient':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENT*/26,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_SOLSizeGradientX':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENTX*/27,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_SOLSizeGradientY':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENTY*/28,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_SOLSizeGradientZ':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSizeGradientZ*/29,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_SOLSizeGradientMax':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSizeGradientMax*/30,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_SOLSizeGradientMaxX':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENTXMAX*/31,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_SOLSizeGradientMaxY':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSIZEGRADIENTYMAX*/32,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_SOLSizeGradientMaxZ':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.SOLSizeGradientZMAX*/33,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ROLAngularVelocityConst':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYCONST*/34,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ROLAngularVelocityConstSeprarate':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYCONSTSEPRARATE*/35,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ROLAngularVelocityGradient':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENT*/36,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ROLAngularVelocityGradientX':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTX*/37,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ROLAngularVelocityGradientY':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTY*/38,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ROLAngularVelocityGradientZ':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTZ*/39,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ROLAngularVelocityGradientW':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTW*/40,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ROLAngularVelocityConstMax':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYCONSTMAX*/41,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ROLAngularVelocityConstMaxSeprarate':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYCONSTMAXSEPRARATE*/42,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ROLAngularVelocityGradientMax':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTMAX*/43,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ROLAngularVelocityGradientMaxX':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTXMAX*/44,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ROLAngularVelocityGradientMaxY':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTYMAX*/45,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ROLAngularVelocityGradientMaxZ':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTZMAX*/46,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_ROLAngularVelocityGradientMaxW':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTWMAX*/47,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_TSACycles':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.TEXTURESHEETANIMATIONCYCLES*/48,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_TSASubUVLength':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.TEXTURESHEETANIMATIONSUBUVLENGTH*/49,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_TSAGradientUVs':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.TEXTURESHEETANIMATIONGRADIENTUVS*/50,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_TSAMaxGradientUVs':[ /*laya.d3.core.particleShuriKen.ShuriKenParticle3D.TEXTURESHEETANIMATIONGRADIENTMAXUVS*/51,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_CameraPosition':[ /*laya.d3.core.BaseCamera.CAMERAPOS*/0,/*laya.d3.shader.Shader3D.PERIOD_CAMERA*/3], 'u_CameraDirection':[ /*laya.d3.core.BaseCamera.CAMERADIRECTION*/5,/*laya.d3.shader.Shader3D.PERIOD_CAMERA*/3], 'u_CameraUp':[ /*laya.d3.core.BaseCamera.CAMERAUP*/6,/*laya.d3.shader.Shader3D.PERIOD_CAMERA*/3], 'u_View':[ /*laya.d3.core.BaseCamera.VIEWMATRIX*/1,/*laya.d3.shader.Shader3D.PERIOD_CAMERA*/3], 'u_Projection':[ /*laya.d3.core.BaseCamera.PROJECTMATRIX*/2,/*laya.d3.shader.Shader3D.PERIOD_CAMERA*/3], 'u_FogStart':[ /*laya.d3.core.scene.Scene.FOGSTART*/1,/*laya.d3.shader.Shader3D.PERIOD_SCENE*/4], 'u_FogRange':[ /*laya.d3.core.scene.Scene.FOGRANGE*/2,/*laya.d3.shader.Shader3D.PERIOD_SCENE*/4], 'u_FogColor':[ /*laya.d3.core.scene.Scene.FOGCOLOR*/0,/*laya.d3.shader.Shader3D.PERIOD_SCENE*/4] }; var PARTICLESHURIKEN=Shader3D.nameKey.add("Particle"); var vs="#ifdef HIGHPRECISION\n precision highp float;\n#else\n precision mediump float;\n#endif\n\n#if defined(SPHERHBILLBOARD)||defined(STRETCHEDBILLBOARD)||defined(HORIZONTALBILLBOARD)||defined(VERTICALBILLBOARD)\n attribute vec4 a_CornerTextureCoordinate;\n#endif\n#ifdef RENDERMODE_MESH\n attribute vec3 a_MeshPosition;\n attribute vec4 a_MeshColor;\n attribute vec2 a_MeshTextureCoordinate;\n varying vec4 v_MeshColor;\n#endif\n\nattribute vec4 a_ShapePositionStartLifeTime;\nattribute vec4 a_DirectionTime;\nattribute vec4 a_StartColor;\nattribute vec3 a_StartSize;\nattribute vec3 a_StartRotation0;\nattribute float a_StartSpeed;\n#if defined(COLOROVERLIFETIME)||defined(RANDOMCOLOROVERLIFETIME)||defined(SIZEOVERLIFETIMERANDOMCURVES)||defined(SIZEOVERLIFETIMERANDOMCURVESSEPERATE)||defined(ROTATIONOVERLIFETIMERANDOMCONSTANTS)||defined(ROTATIONOVERLIFETIMERANDOMCURVES)\n attribute vec4 a_Random0;\n#endif\n#if defined(TEXTURESHEETANIMATIONRANDOMCURVE)||defined(VELOCITYOVERLIFETIMERANDOMCONSTANT)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)\n attribute vec4 a_Random1;\n#endif\nattribute vec3 a_SimulationWorldPostion;\nattribute vec4 a_SimulationWorldRotation;\n\nvarying float v_Discard;\nvarying vec4 v_Color;\n#ifdef MAINTEXTURE\n varying vec2 v_TextureCoordinate;\n #ifdef TILINGOFFSET1\n uniform vec4 u_TilingOffset1;\n #endif\n#endif\n\n#ifdef MASKTEXTURE\n #ifdef TILINGOFFSET2\n uniform vec4 u_TilingOffset2;\n #endif\n#endif\n\nvarying vec2 v_Texcoord0;\nvarying vec2 v_Texcoord1;\n\nuniform float u_CurrentTime;\nuniform vec3 u_Gravity;\n\nuniform vec3 u_WorldPosition;\nuniform vec4 u_WorldRotation;\nuniform bool u_ThreeDStartRotation;\nuniform int u_ScalingMode;\nuniform vec3 u_PositionScale;\nuniform vec3 u_SizeScale;\nuniform mat4 u_View;\nuniform mat4 u_Projection;\n\n#ifdef STRETCHEDBILLBOARD\n uniform vec3 u_CameraPosition;\n#endif\nuniform vec3 u_CameraDirection;//TODO:只有几种广告牌模式需要用\nuniform vec3 u_CameraUp;\n\nuniform float u_StretchedBillboardLengthScale;\nuniform float u_StretchedBillboardSpeedScale;\nuniform int u_SimulationSpace;\n\n#if defined(VELOCITYOVERLIFETIMECONSTANT)||defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCONSTANT)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)\n uniform int u_VOLSpaceType;\n#endif\n#if defined(VELOCITYOVERLIFETIMECONSTANT)||defined(VELOCITYOVERLIFETIMERANDOMCONSTANT)\n uniform vec3 u_VOLVelocityConst;\n#endif\n#if defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)\n uniform vec2 u_VOLVelocityGradientX[4];//x为key,y为速度\n uniform vec2 u_VOLVelocityGradientY[4];//x为key,y为速度\n uniform vec2 u_VOLVelocityGradientZ[4];//x为key,y为速度\n#endif\n#ifdef VELOCITYOVERLIFETIMERANDOMCONSTANT\n uniform vec3 u_VOLVelocityConstMax;\n#endif\n#ifdef VELOCITYOVERLIFETIMERANDOMCURVE\n uniform vec2 u_VOLVelocityGradientMaxX[4];//x为key,y为速度\n uniform vec2 u_VOLVelocityGradientMaxY[4];//x为key,y为速度\n uniform vec2 u_VOLVelocityGradientMaxZ[4];//x为key,y为速度\n#endif\n\n#ifdef COLOROVERLIFETIME\n uniform vec4 u_ColorOverLifeGradientColors[4];//x为key,yzw为Color\n uniform vec2 u_ColorOverLifeGradientAlphas[4];//x为key,y为Alpha\n#endif\n#ifdef RANDOMCOLOROVERLIFETIME\n uniform vec4 u_ColorOverLifeGradientColors[4];//x为key,yzw为Color\n uniform vec2 u_ColorOverLifeGradientAlphas[4];//x为key,y为Alpha\n uniform vec4 u_MaxColorOverLifeGradientColors[4];//x为key,yzw为Color\n uniform vec2 u_MaxColorOverLifeGradientAlphas[4];//x为key,y为Alpha\n#endif\n\n\n#if defined(SIZEOVERLIFETIMECURVE)||defined(SIZEOVERLIFETIMERANDOMCURVES)\n uniform vec2 u_SOLSizeGradient[4];//x为key,y为尺寸\n#endif\n#ifdef SIZEOVERLIFETIMERANDOMCURVES\n uniform vec2 u_SOLSizeGradientMax[4];//x为key,y为尺寸\n#endif\n#if defined(SIZEOVERLIFETIMECURVESEPERATE)||defined(SIZEOVERLIFETIMERANDOMCURVESSEPERATE)\n uniform vec2 u_SOLSizeGradientX[4];//x为key,y为尺寸\n uniform vec2 u_SOLSizeGradientY[4];//x为key,y为尺寸\n uniform vec2 u_SOLSizeGradientZ[4];//x为key,y为尺寸\n#endif\n#ifdef SIZEOVERLIFETIMERANDOMCURVESSEPERATE\n uniform vec2 u_SOLSizeGradientMaxX[4];//x为key,y为尺寸\n uniform vec2 u_SOLSizeGradientMaxY[4];//x为key,y为尺寸\n uniform vec2 u_SOLSizeGradientMaxZ[4];//x为key,y为尺寸\n#endif\n\n\n#ifdef ROTATIONOVERLIFETIME\n #if defined(ROTATIONOVERLIFETIMECONSTANT)||defined(ROTATIONOVERLIFETIMERANDOMCONSTANTS)\n uniform float u_ROLAngularVelocityConst;\n #endif\n #ifdef ROTATIONOVERLIFETIMERANDOMCONSTANTS\n uniform float u_ROLAngularVelocityConstMax;\n #endif\n #if defined(ROTATIONOVERLIFETIMECURVE)||defined(ROTATIONOVERLIFETIMERANDOMCURVES)\n uniform vec2 u_ROLAngularVelocityGradient[4];//x为key,y为旋转\n #endif\n #ifdef ROTATIONOVERLIFETIMERANDOMCURVES\n uniform vec2 u_ROLAngularVelocityGradientMax[4];//x为key,y为旋转\n #endif\n#endif\n#ifdef ROTATIONOVERLIFETIMESEPERATE\n #if defined(ROTATIONOVERLIFETIMECONSTANT)||defined(ROTATIONOVERLIFETIMERANDOMCONSTANTS)\n uniform vec3 u_ROLAngularVelocityConstSeprarate;\n #endif\n #ifdef ROTATIONOVERLIFETIMERANDOMCONSTANTS\n uniform vec3 u_ROLAngularVelocityConstMaxSeprarate;\n #endif\n #if defined(ROTATIONOVERLIFETIMECURVE)||defined(ROTATIONOVERLIFETIMERANDOMCURVES)\n uniform vec2 u_ROLAngularVelocityGradientX[4];\n uniform vec2 u_ROLAngularVelocityGradientY[4];\n uniform vec2 u_ROLAngularVelocityGradientZ[4];\n uniform vec2 u_ROLAngularVelocityGradientW[4];\n #endif\n #ifdef ROTATIONOVERLIFETIMERANDOMCURVES\n uniform vec2 u_ROLAngularVelocityGradientMaxX[4];\n uniform vec2 u_ROLAngularVelocityGradientMaxY[4];\n uniform vec2 u_ROLAngularVelocityGradientMaxZ[4];\n uniform vec2 u_ROLAngularVelocityGradientMaxW[4];\n #endif\n#endif\n\n#if defined(TEXTURESHEETANIMATIONCURVE)||defined(TEXTURESHEETANIMATIONRANDOMCURVE)\n uniform float u_TSACycles;\n uniform vec2 u_TSASubUVLength;\n uniform vec2 u_TSAGradientUVs[4];//x为key,y为frame\n#endif\n#ifdef TEXTURESHEETANIMATIONRANDOMCURVE\n uniform vec2 u_TSAMaxGradientUVs[4];//x为key,y为frame\n#endif\n\n#ifdef FOG\n varying vec3 v_PositionWorld;\n#endif\n\nvec3 rotationByEuler(in vec3 vector,in vec3 rot)\n{\n float halfRoll = rot.z * 0.5;\n float halfPitch = rot.x * 0.5;\n float halfYaw = rot.y * 0.5;\n\n float sinRoll = sin(halfRoll);\n float cosRoll = cos(halfRoll);\n float sinPitch = sin(halfPitch);\n float cosPitch = cos(halfPitch);\n float sinYaw = sin(halfYaw);\n float cosYaw = cos(halfYaw);\n\n float quaX = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);\n float quaY = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);\n float quaZ = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);\n float quaW = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);\n \n //vec4 q=vec4(quaX,quaY,quaZ,quaW);\n //vec3 temp = cross(q.xyz, vector) + q.w * vector;\n //return (cross(temp, -q.xyz) + dot(q.xyz,vector) * q.xyz + q.w * temp);\n \n float x = quaX + quaX;\n float y = quaY + quaY;\n float z = quaZ + quaZ;\n float wx = quaW * x;\n float wy = quaW * y;\n float wz = quaW * z;\n float xx = quaX * x;\n float xy = quaX * y;\n float xz = quaX * z;\n float yy = quaY * y;\n float yz = quaY * z;\n float zz = quaZ * z;\n\n return vec3(((vector.x * ((1.0 - yy) - zz)) + (vector.y * (xy - wz))) + (vector.z * (xz + wy)),\n ((vector.x * (xy + wz)) + (vector.y * ((1.0 - xx) - zz))) + (vector.z * (yz - wx)),\n ((vector.x * (xz - wy)) + (vector.y * (yz + wx))) + (vector.z * ((1.0 - xx) - yy)));\n \n}\n\n//假定axis已经归一化\nvec3 rotationByAxis(in vec3 vector,in vec3 axis, in float angle)\n{\n float halfAngle = angle * 0.5;\n float sin = sin(halfAngle);\n \n float quaX = axis.x * sin;\n float quaY = axis.y * sin;\n float quaZ = axis.z * sin;\n float quaW = cos(halfAngle);\n \n //vec4 q=vec4(quaX,quaY,quaZ,quaW);\n //vec3 temp = cross(q.xyz, vector) + q.w * vector;\n //return (cross(temp, -q.xyz) + dot(q.xyz,vector) * q.xyz + q.w * temp);\n \n float x = quaX + quaX;\n float y = quaY + quaY;\n float z = quaZ + quaZ;\n float wx = quaW * x;\n float wy = quaW * y;\n float wz = quaW * z;\n float xx = quaX * x;\n float xy = quaX * y;\n float xz = quaX * z;\n float yy = quaY * y;\n float yz = quaY * z;\n float zz = quaZ * z;\n\n return vec3(((vector.x * ((1.0 - yy) - zz)) + (vector.y * (xy - wz))) + (vector.z * (xz + wy)),\n ((vector.x * (xy + wz)) + (vector.y * ((1.0 - xx) - zz))) + (vector.z * (yz - wx)),\n ((vector.x * (xz - wy)) + (vector.y * (yz + wx))) + (vector.z * ((1.0 - xx) - yy)));\n \n}\n\nvec3 rotationByQuaternions(in vec3 v,in vec4 q) \n{\n return v + 2.0 * cross(q.xyz, cross(q.xyz, v) + q.w * v);\n}\n\n \n#if defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)||defined(SIZEOVERLIFETIMECURVE)||defined(SIZEOVERLIFETIMECURVESEPERATE)||defined(SIZEOVERLIFETIMERANDOMCURVES)||defined(SIZEOVERLIFETIMERANDOMCURVESSEPERATE)\nfloat getCurValueFromGradientFloat(in vec2 gradientNumbers[4],in float normalizedAge)\n{\n float curValue;\n for(int i=1;i<4;i++)\n {\n vec2 gradientNumber=gradientNumbers[i];\n float key=gradientNumber.x;\n if(key>=normalizedAge)\n {\n vec2 lastGradientNumber=gradientNumbers[i-1];\n float lastKey=lastGradientNumber.x;\n float age=(normalizedAge-lastKey)/(key-lastKey);\n curValue=mix(lastGradientNumber.y,gradientNumber.y,age);\n break;\n }\n }\n return curValue;\n}\n#endif\n\n#if defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)||defined(ROTATIONOVERLIFETIMECURVE)||defined(ROTATIONOVERLIFETIMERANDOMCURVES)\nfloat getTotalValueFromGradientFloat(in vec2 gradientNumbers[4],in float normalizedAge)\n{\n float totalValue=0.0;\n for(int i=1;i<4;i++)\n {\n vec2 gradientNumber=gradientNumbers[i];\n float key=gradientNumber.x;\n vec2 lastGradientNumber=gradientNumbers[i-1];\n float lastValue=lastGradientNumber.y;\n \n if(key>=normalizedAge){\n float lastKey=lastGradientNumber.x;\n float age=(normalizedAge-lastKey)/(key-lastKey);\n totalValue+=(lastValue+mix(lastValue,gradientNumber.y,age))/2.0*a_ShapePositionStartLifeTime.w*(normalizedAge-lastKey);\n break;\n }\n else{\n totalValue+=(lastValue+gradientNumber.y)/2.0*a_ShapePositionStartLifeTime.w*(key-lastGradientNumber.x);\n }\n }\n return totalValue;\n}\n#endif\n\n#if defined(COLOROVERLIFETIME)||defined(RANDOMCOLOROVERLIFETIME)\nvec4 getColorFromGradient(in vec2 gradientAlphas[4],in vec4 gradientColors[4],in float normalizedAge)\n{\n vec4 overTimeColor;\n for(int i=1;i<4;i++)\n {\n vec2 gradientAlpha=gradientAlphas[i];\n float alphaKey=gradientAlpha.x;\n if(alphaKey>=normalizedAge)\n {\n vec2 lastGradientAlpha=gradientAlphas[i-1];\n float lastAlphaKey=lastGradientAlpha.x;\n float age=(normalizedAge-lastAlphaKey)/(alphaKey-lastAlphaKey);\n overTimeColor.a=mix(lastGradientAlpha.y,gradientAlpha.y,age);\n break;\n }\n }\n \n for(int i=1;i<4;i++)\n {\n vec4 gradientColor=gradientColors[i];\n float colorKey=gradientColor.x;\n if(colorKey>=normalizedAge)\n {\n vec4 lastGradientColor=gradientColors[i-1];\n float lastColorKey=lastGradientColor.x;\n float age=(normalizedAge-lastColorKey)/(colorKey-lastColorKey);\n overTimeColor.rgb=mix(gradientColors[i-1].yzw,gradientColor.yzw,age);\n break;\n }\n }\n return overTimeColor;\n}\n#endif\n\n\n#if defined(TEXTURESHEETANIMATIONCURVE)||defined(TEXTURESHEETANIMATIONRANDOMCURVE)\nfloat getFrameFromGradient(in vec2 gradientFrames[4],in float normalizedAge)\n{\n float overTimeFrame;\n for(int i=1;i<4;i++)\n {\n vec2 gradientFrame=gradientFrames[i];\n float key=gradientFrame.x;\n if(key>=normalizedAge)\n {\n vec2 lastGradientFrame=gradientFrames[i-1];\n float lastKey=lastGradientFrame.x;\n float age=(normalizedAge-lastKey)/(key-lastKey);\n overTimeFrame=mix(lastGradientFrame.y,gradientFrame.y,age);\n break;\n }\n }\n return floor(overTimeFrame);\n}\n#endif\n\n#if defined(VELOCITYOVERLIFETIMECONSTANT)||defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCONSTANT)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)\nvec3 computeParticleLifeVelocity(in float normalizedAge)\n{\n vec3 outLifeVelocity;\n #ifdef VELOCITYOVERLIFETIMECONSTANT\n outLifeVelocity=u_VOLVelocityConst; \n #endif\n #ifdef VELOCITYOVERLIFETIMECURVE\n outLifeVelocity= vec3(getCurValueFromGradientFloat(u_VOLVelocityGradientX,normalizedAge),getCurValueFromGradientFloat(u_VOLVelocityGradientY,normalizedAge),getCurValueFromGradientFloat(u_VOLVelocityGradientZ,normalizedAge));\n #endif\n #ifdef VELOCITYOVERLIFETIMERANDOMCONSTANT\n outLifeVelocity=mix(u_VOLVelocityConst,u_VOLVelocityConstMax,vec3(a_Random1.y,a_Random1.z,a_Random1.w)); \n #endif\n #ifdef VELOCITYOVERLIFETIMERANDOMCURVE\n outLifeVelocity=vec3(mix(getCurValueFromGradientFloat(u_VOLVelocityGradientX,normalizedAge),getCurValueFromGradientFloat(u_VOLVelocityGradientMaxX,normalizedAge),a_Random1.y),\n mix(getCurValueFromGradientFloat(u_VOLVelocityGradientY,normalizedAge),getCurValueFromGradientFloat(u_VOLVelocityGradientMaxY,normalizedAge),a_Random1.z),\n mix(getCurValueFromGradientFloat(u_VOLVelocityGradientZ,normalizedAge),getCurValueFromGradientFloat(u_VOLVelocityGradientMaxZ,normalizedAge),a_Random1.w));\n #endif\n \n return outLifeVelocity;\n} \n#endif\n\nvec3 computeParticlePosition(in vec3 startVelocity, in vec3 lifeVelocity,in float age,in float normalizedAge,vec3 gravityVelocity,vec4 worldRotation)\n{\n vec3 startPosition;\n vec3 lifePosition;\n #if defined(VELOCITYOVERLIFETIMECONSTANT)||defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCONSTANT)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)\n #ifdef VELOCITYOVERLIFETIMECONSTANT\n startPosition=startVelocity*age;\n lifePosition=lifeVelocity*age;\n #endif\n #ifdef VELOCITYOVERLIFETIMECURVE\n startPosition=startVelocity*age;\n lifePosition=vec3(getTotalValueFromGradientFloat(u_VOLVelocityGradientX,normalizedAge),getTotalValueFromGradientFloat(u_VOLVelocityGradientY,normalizedAge),getTotalValueFromGradientFloat(u_VOLVelocityGradientZ,normalizedAge));\n #endif\n #ifdef VELOCITYOVERLIFETIMERANDOMCONSTANT\n startPosition=startVelocity*age;\n lifePosition=lifeVelocity*age;\n #endif\n #ifdef VELOCITYOVERLIFETIMERANDOMCURVE\n startPosition=startVelocity*age;\n lifePosition=vec3(mix(getTotalValueFromGradientFloat(u_VOLVelocityGradientX,normalizedAge),getTotalValueFromGradientFloat(u_VOLVelocityGradientMaxX,normalizedAge),a_Random1.y)\n ,mix(getTotalValueFromGradientFloat(u_VOLVelocityGradientY,normalizedAge),getTotalValueFromGradientFloat(u_VOLVelocityGradientMaxY,normalizedAge),a_Random1.z)\n ,mix(getTotalValueFromGradientFloat(u_VOLVelocityGradientZ,normalizedAge),getTotalValueFromGradientFloat(u_VOLVelocityGradientMaxZ,normalizedAge),a_Random1.w));\n #endif\n \n vec3 finalPosition;\n if(u_VOLSpaceType==0){\n if(u_ScalingMode!=2)\n finalPosition =rotationByQuaternions(u_PositionScale*(a_ShapePositionStartLifeTime.xyz+startPosition+lifePosition),worldRotation);\n else\n finalPosition =rotationByQuaternions(u_PositionScale*a_ShapePositionStartLifeTime.xyz+startPosition+lifePosition,worldRotation);\n }\n else{\n if(u_ScalingMode!=2)\n finalPosition = rotationByQuaternions(u_PositionScale*(a_ShapePositionStartLifeTime.xyz+startPosition),worldRotation)+lifePosition;\n else\n finalPosition = rotationByQuaternions(u_PositionScale*a_ShapePositionStartLifeTime.xyz+startPosition,worldRotation)+lifePosition;\n }\n #else\n startPosition=startVelocity*age;\n vec3 finalPosition;\n if(u_ScalingMode!=2)\n finalPosition = rotationByQuaternions(u_PositionScale*(a_ShapePositionStartLifeTime.xyz+startPosition),worldRotation);\n else\n finalPosition = rotationByQuaternions(u_PositionScale*a_ShapePositionStartLifeTime.xyz+startPosition,worldRotation);\n #endif\n \n if(u_SimulationSpace==0)\n finalPosition=finalPosition+a_SimulationWorldPostion;\n else if(u_SimulationSpace==1) \n finalPosition=finalPosition+u_WorldPosition;\n \n finalPosition+=0.5*gravityVelocity*age;\n \n return finalPosition;\n}\n\n\nvec4 computeParticleColor(in vec4 color,in float normalizedAge)\n{\n #ifdef COLOROVERLIFETIME\n color*=getColorFromGradient(u_ColorOverLifeGradientAlphas,u_ColorOverLifeGradientColors,normalizedAge);\n #endif\n \n #ifdef RANDOMCOLOROVERLIFETIME\n color*=mix(getColorFromGradient(u_ColorOverLifeGradientAlphas,u_ColorOverLifeGradientColors,normalizedAge),getColorFromGradient(u_MaxColorOverLifeGradientAlphas,u_MaxColorOverLifeGradientColors,normalizedAge),a_Random0.y);\n #endif\n\n return color;\n}\n\nvec2 computeParticleSizeBillbard(in vec2 size,in float normalizedAge)\n{\n #ifdef SIZEOVERLIFETIMECURVE\n size*=getCurValueFromGradientFloat(u_SOLSizeGradient,normalizedAge);\n #endif\n #ifdef SIZEOVERLIFETIMERANDOMCURVES\n size*=mix(getCurValueFromGradientFloat(u_SOLSizeGradient,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientMax,normalizedAge),a_Random0.z); \n #endif\n #ifdef SIZEOVERLIFETIMECURVESEPERATE\n size*=vec2(getCurValueFromGradientFloat(u_SOLSizeGradientX,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientY,normalizedAge));\n #endif\n #ifdef SIZEOVERLIFETIMERANDOMCURVESSEPERATE\n size*=vec2(mix(getCurValueFromGradientFloat(u_SOLSizeGradientX,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientMaxX,normalizedAge),a_Random0.z)\n ,mix(getCurValueFromGradientFloat(u_SOLSizeGradientY,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientMaxY,normalizedAge),a_Random0.z));\n #endif\n return size;\n}\n\n#ifdef RENDERMODE_MESH\nvec3 computeParticleSizeMesh(in vec3 size,in float normalizedAge)\n{\n #ifdef SIZEOVERLIFETIMECURVE\n size*=getCurValueFromGradientFloat(u_SOLSizeGradient,normalizedAge);\n #endif\n #ifdef SIZEOVERLIFETIMERANDOMCURVES\n size*=mix(getCurValueFromGradientFloat(u_SOLSizeGradient,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientMax,normalizedAge),a_Random0.z); \n #endif\n #ifdef SIZEOVERLIFETIMECURVESEPERATE\n size*=vec3(getCurValueFromGradientFloat(u_SOLSizeGradientX,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientY,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientZ,normalizedAge));\n #endif\n #ifdef SIZEOVERLIFETIMERANDOMCURVESSEPERATE\n size*=vec3(mix(getCurValueFromGradientFloat(u_SOLSizeGradientX,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientMaxX,normalizedAge),a_Random0.z)\n ,mix(getCurValueFromGradientFloat(u_SOLSizeGradientY,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientMaxY,normalizedAge),a_Random0.z)\n ,mix(getCurValueFromGradientFloat(u_SOLSizeGradientZ,normalizedAge),getCurValueFromGradientFloat(u_SOLSizeGradientMaxZ,normalizedAge),a_Random0.z));\n #endif\n return size;\n}\n#endif\n\nfloat computeParticleRotationFloat(in float rotation,in float age,in float normalizedAge)\n{ \n #ifdef ROTATIONOVERLIFETIME\n #ifdef ROTATIONOVERLIFETIMECONSTANT\n float ageRot=u_ROLAngularVelocityConst*age;\n rotation+=ageRot;\n #endif\n #ifdef ROTATIONOVERLIFETIMECURVE\n rotation+=getTotalValueFromGradientFloat(u_ROLAngularVelocityGradient,normalizedAge);\n #endif\n #ifdef ROTATIONOVERLIFETIMERANDOMCONSTANTS\n float ageRot=mix(u_ROLAngularVelocityConst,u_ROLAngularVelocityConstMax,a_Random0.w)*age;\n rotation+=ageRot;\n #endif\n #ifdef ROTATIONOVERLIFETIMERANDOMCURVES\n rotation+=mix(getTotalValueFromGradientFloat(u_ROLAngularVelocityGradient,normalizedAge),getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientMax,normalizedAge),a_Random0.w);\n #endif\n #endif\n #ifdef ROTATIONOVERLIFETIMESEPERATE\n #ifdef ROTATIONOVERLIFETIMECONSTANT\n float ageRot=u_ROLAngularVelocityConstSeprarate.z*age;\n rotation+=ageRot;\n #endif\n #ifdef ROTATIONOVERLIFETIMECURVE\n rotation+=getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientZ,normalizedAge);\n #endif\n #ifdef ROTATIONOVERLIFETIMERANDOMCONSTANTS\n float ageRot=mix(u_ROLAngularVelocityConstSeprarate.z,u_ROLAngularVelocityConstMaxSeprarate.z,a_Random0.w)*age;\n rotation+=ageRot;\n #endif\n #ifdef ROTATIONOVERLIFETIMERANDOMCURVES\n rotation+=mix(getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientZ,normalizedAge),getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientMaxZ,normalizedAge),a_Random0.w));\n #endif\n #endif\n return rotation;\n}\n\n\n#if defined(RENDERMODE_MESH)&&(defined(ROTATIONOVERLIFETIME)||defined(ROTATIONOVERLIFETIMESEPERATE))\nvec3 computeParticleRotationVec3(in vec3 rotation,in float age,in float normalizedAge)\n{ \n #ifdef ROTATIONOVERLIFETIME\n #ifdef ROTATIONOVERLIFETIMECONSTANT\n float ageRot=u_ROLAngularVelocityConst*age;\n rotation+=ageRot;\n #endif\n #ifdef ROTATIONOVERLIFETIMECURVE\n rotation+=getTotalValueFromGradientFloat(u_ROLAngularVelocityGradient,normalizedAge);\n #endif\n #ifdef ROTATIONOVERLIFETIMERANDOMCONSTANTS\n float ageRot=mix(u_ROLAngularVelocityConst,u_ROLAngularVelocityConstMax,a_Random0.w)*age;\n rotation+=ageRot;\n #endif\n #ifdef ROTATIONOVERLIFETIMERANDOMCURVES\n rotation+=mix(getTotalValueFromGradientFloat(u_ROLAngularVelocityGradient,normalizedAge),getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientMax,normalizedAge),a_Random0.w);\n #endif\n #endif\n #ifdef ROTATIONOVERLIFETIMESEPERATE\n #ifdef ROTATIONOVERLIFETIMECONSTANT\n vec3 ageRot=u_ROLAngularVelocityConstSeprarate*age;\n rotation+=ageRot;\n #endif\n #ifdef ROTATIONOVERLIFETIMECURVE\n rotation+=vec3(getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientX,normalizedAge),getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientY,normalizedAge),getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientZ,normalizedAge));\n #endif\n #ifdef ROTATIONOVERLIFETIMERANDOMCONSTANTS\n vec3 ageRot=mix(u_ROLAngularVelocityConstSeprarate,u_ROLAngularVelocityConstMaxSeprarate,a_Random0.w)*age;\n rotation+=ageRot;\n #endif\n #ifdef ROTATIONOVERLIFETIMERANDOMCURVES\n rotation+=vec3(mix(getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientX,normalizedAge),getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientMaxX,normalizedAge),a_Random0.w)\n ,mix(getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientY,normalizedAge),getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientMaxY,normalizedAge),a_Random0.w)\n ,mix(getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientZ,normalizedAge),getTotalValueFromGradientFloat(u_ROLAngularVelocityGradientMaxZ,normalizedAge),a_Random0.w));\n #endif\n #endif\n return rotation;\n}\n#endif\n\nvec2 computeParticleUV(in vec2 uv,in float normalizedAge)\n{ \n #ifdef TEXTURESHEETANIMATIONCURVE\n float cycleNormalizedAge=normalizedAge*u_TSACycles;\n float frame=getFrameFromGradient(u_TSAGradientUVs,cycleNormalizedAge-floor(cycleNormalizedAge));\n float totalULength=frame*u_TSASubUVLength.x;\n float floorTotalULength=floor(totalULength);\n uv.x+=totalULength-floorTotalULength;\n uv.y+=floorTotalULength*u_TSASubUVLength.y;\n #endif\n #ifdef TEXTURESHEETANIMATIONRANDOMCURVE\n float cycleNormalizedAge=normalizedAge*u_TSACycles;\n float uvNormalizedAge=cycleNormalizedAge-floor(cycleNormalizedAge);\n float frame=floor(mix(getFrameFromGradient(u_TSAGradientUVs,uvNormalizedAge),getFrameFromGradient(u_TSAMaxGradientUVs,uvNormalizedAge),a_Random1.x));\n float totalULength=frame*u_TSASubUVLength.x;\n float floorTotalULength=floor(totalULength);\n uv.x+=totalULength-floorTotalULength;\n uv.y+=floorTotalULength*u_TSASubUVLength.y;\n #endif\n return uv;\n}\n\nvoid main()\n{\n float age = u_CurrentTime - a_DirectionTime.w;\n float normalizedAge = age/a_ShapePositionStartLifeTime.w;\n vec3 lifeVelocity;\n if(normalizedAge<1.0){ \n vec3 startVelocity=a_DirectionTime.xyz*a_StartSpeed;\n #if defined(VELOCITYOVERLIFETIMECONSTANT)||defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCONSTANT)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)\n lifeVelocity= computeParticleLifeVelocity(normalizedAge);//计算粒子生命周期速度\n #endif \n vec3 gravityVelocity=u_Gravity*age;\n \n vec4 worldRotation;\n if(u_SimulationSpace==0)\n worldRotation=a_SimulationWorldRotation;\n else\n worldRotation=u_WorldRotation;\n \n vec3 center=computeParticlePosition(startVelocity, lifeVelocity, age, normalizedAge,gravityVelocity,worldRotation);//计算粒子位置\n \n \n #ifdef SPHERHBILLBOARD\n vec2 corner=a_CornerTextureCoordinate.xy;//Billboard模式z轴无效\n vec3 cameraUpVector =normalize(u_CameraUp);//TODO:是否外面归一化\n vec3 sideVector = normalize(cross(u_CameraDirection,cameraUpVector));\n vec3 upVector = normalize(cross(sideVector,u_CameraDirection));\n corner*=computeParticleSizeBillbard(a_StartSize.xy,normalizedAge);\n #if defined(ROTATIONOVERLIFETIME)||defined(ROTATIONOVERLIFETIMESEPERATE)\n if(u_ThreeDStartRotation){\n vec3 rotation=vec3(a_StartRotation0.xy,computeParticleRotationFloat(a_StartRotation0.z,age,normalizedAge));\n center += u_SizeScale.xzy*rotationByEuler(corner.x*sideVector+corner.y*upVector,rotation);\n }\n else{\n float rot = computeParticleRotationFloat(a_StartRotation0.x, age,normalizedAge);\n float c = cos(rot);\n float s = sin(rot);\n mat2 rotation= mat2(c, -s, s, c);\n corner=rotation*corner;\n center += u_SizeScale.xzy*(corner.x*sideVector+corner.y*upVector);\n }\n #else\n if(u_ThreeDStartRotation){\n center += u_SizeScale.xzy*rotationByEuler(corner.x*sideVector+corner.y*upVector,a_StartRotation0);\n }\n else{\n float c = cos(a_StartRotation0.x);\n float s = sin(a_StartRotation0.x);\n mat2 rotation= mat2(c, -s, s, c);\n corner=rotation*corner;\n center += u_SizeScale.xzy*(corner.x*sideVector+corner.y*upVector);\n }\n #endif\n #endif\n \n #ifdef STRETCHEDBILLBOARD\n vec2 corner=a_CornerTextureCoordinate.xy;//Billboard模式z轴无效\n vec3 velocity;\n #if defined(VELOCITYOVERLIFETIMECONSTANT)||defined(VELOCITYOVERLIFETIMECURVE)||defined(VELOCITYOVERLIFETIMERANDOMCONSTANT)||defined(VELOCITYOVERLIFETIMERANDOMCURVE)\n if(u_VOLSpaceType==0)\n velocity=rotationByQuaternions(u_SizeScale*(startVelocity+lifeVelocity),worldRotation)+gravityVelocity;\n else\n velocity=rotationByQuaternions(u_SizeScale*startVelocity,worldRotation)+lifeVelocity+gravityVelocity;\n #else\n velocity= rotationByQuaternions(u_SizeScale*startVelocity,worldRotation)+gravityVelocity;\n #endif \n vec3 cameraUpVector = normalize(velocity);\n vec3 direction = normalize(center-u_CameraPosition);\n vec3 sideVector = normalize(cross(direction,normalize(velocity)));\n \n sideVector=u_SizeScale.xzy*sideVector;\n cameraUpVector=length(vec3(u_SizeScale.x,0.0,0.0))*cameraUpVector;\n \n vec2 size=computeParticleSizeBillbard(a_StartSize.xy,normalizedAge);\n \n const mat2 rotaionZHalfPI=mat2(0.0, -1.0, 1.0, 0.0);\n corner=rotaionZHalfPI*corner;\n corner.y=corner.y-abs(corner.y);\n \n float speed=length(velocity);//TODO:\n center +=sign(u_SizeScale.x)*(sign(u_StretchedBillboardLengthScale)*size.x*corner.x*sideVector+(speed*u_StretchedBillboardSpeedScale+size.y*u_StretchedBillboardLengthScale)*corner.y*cameraUpVector);\n #endif\n \n #ifdef HORIZONTALBILLBOARD\n vec2 corner=a_CornerTextureCoordinate.xy;//Billboard模式z轴无效\n const vec3 cameraUpVector=vec3(0.0,0.0,1.0);\n const vec3 sideVector = vec3(-1.0,0.0,0.0);\n \n float rot = computeParticleRotationFloat(a_StartRotation0.x, age,normalizedAge);\n float c = cos(rot);\n float s = sin(rot);\n mat2 rotation= mat2(c, -s, s, c);\n corner=rotation*corner*cos(0.78539816339744830961566084581988);//TODO:临时缩小cos45,不确定U3D原因\n corner*=computeParticleSizeBillbard(a_StartSize.xy,normalizedAge);\n center +=u_SizeScale.xzy*(corner.x*sideVector+ corner.y*cameraUpVector);\n #endif\n \n #ifdef VERTICALBILLBOARD\n vec2 corner=a_CornerTextureCoordinate.xy;//Billboard模式z轴无效\n const vec3 cameraUpVector =vec3(0.0,1.0,0.0);\n vec3 sideVector = normalize(cross(u_CameraDirection,cameraUpVector));\n \n float rot = computeParticleRotationFloat(a_StartRotation0.x, age,normalizedAge);\n float c = cos(rot);\n float s = sin(rot);\n mat2 rotation= mat2(c, -s, s, c);\n corner=rotation*corner*cos(0.78539816339744830961566084581988);//TODO:临时缩小cos45,不确定U3D原因\n corner*=computeParticleSizeBillbard(a_StartSize.xy,normalizedAge);\n center +=u_SizeScale.xzy*(corner.x*sideVector+ corner.y*cameraUpVector);\n #endif\n \n #ifdef RENDERMODE_MESH\n vec3 size=computeParticleSizeMesh(a_StartSize,normalizedAge);\n #if defined(ROTATIONOVERLIFETIME)||defined(ROTATIONOVERLIFETIMESEPERATE)\n if(u_ThreeDStartRotation){\n vec3 rotation=vec3(a_StartRotation0.xy,-computeParticleRotationFloat(a_StartRotation0.z, age,normalizedAge));\n center+= rotationByQuaternions(u_SizeScale*rotationByEuler(a_MeshPosition*size,rotation),worldRotation);\n }\n else{\n #ifdef ROTATIONOVERLIFETIME\n float angle=computeParticleRotationFloat(a_StartRotation0.x, age,normalizedAge);\n if(a_ShapePositionStartLifeTime.x!=0.0||a_ShapePositionStartLifeTime.y!=0.0){\n center+= (rotationByQuaternions(rotationByAxis(u_SizeScale*a_MeshPosition*size,normalize(cross(vec3(0.0,0.0,1.0),vec3(a_ShapePositionStartLifeTime.xy,0.0))),angle),worldRotation));//已验证\n }\n else{\n #ifdef SHAPE\n center+= u_SizeScale.xzy*(rotationByQuaternions(rotationByAxis(a_MeshPosition*size,vec3(0.0,-1.0,0.0),angle),worldRotation));\n #else\n if(u_SimulationSpace==0)\n center+=rotationByAxis(u_SizeScale*a_MeshPosition*size,vec3(0.0,0.0,-1.0),angle);//已验证\n else if(u_SimulationSpace==1)\n center+=rotationByQuaternions(u_SizeScale*rotationByAxis(a_MeshPosition*size,vec3(0.0,0.0,-1.0),angle),worldRotation);//已验证\n #endif\n }\n #endif\n #ifdef ROTATIONOVERLIFETIMESEPERATE\n //TODO:是否应合并if(u_ThreeDStartRotation)分支代码,待测试\n vec3 angle=computeParticleRotationVec3(vec3(0.0,0.0,a_StartRotation0.z), age,normalizedAge);\n center+= (rotationByQuaternions(rotationByEuler(u_SizeScale*a_MeshPosition*size,vec3(angle.x,angle.y,angle.z)),worldRotation));//已验证\n #endif \n }\n #else\n if(u_ThreeDStartRotation){\n center+= rotationByQuaternions(u_SizeScale*rotationByEuler(a_MeshPosition*size,a_StartRotation0),worldRotation);//已验证\n }\n else{\n if(a_ShapePositionStartLifeTime.x!=0.0||a_ShapePositionStartLifeTime.y!=0.0){\n if(u_SimulationSpace==0)\n center+= rotationByAxis(u_SizeScale*a_MeshPosition*size,normalize(cross(vec3(0.0,0.0,1.0),vec3(a_ShapePositionStartLifeTime.xy,0.0))),a_StartRotation0.x);\n else if(u_SimulationSpace==1)\n center+= (rotationByQuaternions(u_SizeScale*rotationByAxis(a_MeshPosition*size,normalize(cross(vec3(0.0,0.0,1.0),vec3(a_ShapePositionStartLifeTime.xy,0.0))),a_StartRotation0.x),worldRotation));//已验证\n }\n else{\n #ifdef SHAPE\n if(u_SimulationSpace==0)\n center+= u_SizeScale*rotationByAxis(a_MeshPosition*size,vec3(0.0,-1.0,0.0),a_StartRotation0.x);\n else if(u_SimulationSpace==1)\n center+= rotationByQuaternions(u_SizeScale*rotationByAxis(a_MeshPosition*size,vec3(0.0,-1.0,0.0),a_StartRotation0.x),worldRotation); \n #else\n if(u_SimulationSpace==0)\n center+= rotationByAxis(u_SizeScale*a_MeshPosition*size,vec3(0.0,0.0,-1.0),a_StartRotation0.x);\n else if(u_SimulationSpace==1)\n center+= rotationByQuaternions(u_SizeScale*rotationByAxis(a_MeshPosition*size,vec3(0.0,0.0,-1.0),a_StartRotation0.x),worldRotation);//已验证\n #endif\n }\n }\n #endif\n v_MeshColor=a_MeshColor;\n #endif\n \n gl_Position=u_Projection*u_View*vec4(center,1.0);\n v_Color = computeParticleColor(a_StartColor, normalizedAge);\n #ifdef MAINTEXTURE\n #if defined(SPHERHBILLBOARD)||defined(STRETCHEDBILLBOARD)||defined(HORIZONTALBILLBOARD)||defined(VERTICALBILLBOARD)\n v_TextureCoordinate =computeParticleUV(a_CornerTextureCoordinate.zw, normalizedAge);\n #endif\n #ifdef RENDERMODE_MESH\n v_TextureCoordinate =computeParticleUV(a_MeshTextureCoordinate, normalizedAge);\n #endif\n \n v_Texcoord0 = v_TextureCoordinate;\n #ifdef TILINGOFFSET1 \n v_Texcoord0=vec2(v_TextureCoordinate.x,1.0-v_TextureCoordinate.y)*u_TilingOffset1.xy+vec2(u_TilingOffset1.z,-u_TilingOffset1.w);//需要特殊处理\n v_Texcoord0=vec2(v_TextureCoordinate.x,1.0-v_TextureCoordinate.y);//需要特殊处理\n #endif\n \n v_Texcoord1 = v_TextureCoordinate;\n #ifdef TILINGOFFSET2 \n v_Texcoord1=vec2(v_TextureCoordinate.x,1.0-v_TextureCoordinate.y)*u_TilingOffset2.xy+vec2(u_TilingOffset2.z,-u_TilingOffset2.w);//需要特殊处理\n v_Texcoord1=vec2(v_TextureCoordinate.x,1.0-v_TextureCoordinate.y);//需要特殊处理\n #endif\n \n #endif\n v_Discard=0.0;\n \n #ifdef FOG\n v_PositionWorld=center;\n #endif\n }\n else\n {\n v_Discard=1.0;\n }\n}\n\n"; var ps="#ifdef HIGHPRECISION\n precision highp float;\n#else\n precision mediump float;\n#endif\n\nvarying float v_Discard;\nvarying vec4 v_Color;\nvarying vec2 v_Texcoord0;\nvarying vec2 v_Texcoord1;\n\nuniform vec4 u_BaseColor;\nuniform vec4 u_AlphaColor;\nuniform float u_Instensity;\nuniform float u_Alpha;\n\n#ifdef MAINTEXTURE\n uniform sampler2D u_MainTexture;\n#endif\n\n#ifdef MASKTEXTURE\n uniform sampler2D u_MaskTexture;\n#endif\n\n#ifdef RENDERMODE_MESH\n varying vec4 v_MeshColor;\n#endif\n\n#ifdef FOG\n varying vec3 v_PositionWorld;\n uniform vec3 u_CameraPosition;\n uniform float u_FogStart;\n uniform float u_FogRange;\n #ifdef ADDTIVEFOG\n #else\n uniform vec3 u_FogColor;\n #endif\n#endif\n\n\nvoid main()\n{ \n #ifdef RENDERMODE_MESH\n gl_FragColor=v_MeshColor;\n #else\n gl_FragColor=vec4(1.0); \n #endif\n \n vec4 mainTextureColor = vec4(1.0);\n #ifdef MAINTEXTURE\n mainTextureColor = texture2D(u_MainTexture, v_Texcoord0);\n #endif\n \n vec4 maskTextureColor = vec4(1.0);\n #ifdef MASKTEXTURE\n maskTextureColor = texture2D(u_MaskTexture, v_Texcoord1);\n #endif\n \n vec4 outColor = mix(vec4(0.0), mainTextureColor, maskTextureColor);\n \n gl_FragColor *= 2.0 * outColor * u_BaseColor * u_AlphaColor * v_Color * u_Instensity;\n gl_FragColor.a *= u_Alpha;\n \n #ifdef FOG\n vec3 toEye=u_CameraPosition-v_PositionWorld;\n float toEyeLength=length(toEye);\n toEye/=toEyeLength;\n \n float lerpFact=clamp((toEyeLength-u_FogStart)/u_FogRange,0.0,1.0);\n #ifdef ADDTIVEFOG\n gl_FragColor.rgb=mix(gl_FragColor.rgb,vec3(0.0,0.0,0.0),lerpFact);\n #else\n gl_FragColor.rgb=mix(gl_FragColor.rgb,u_FogColor,lerpFact);\n #endif\n #endif\n}"; var shaderCompile=ShaderCompile3D.add(PARTICLESHURIKEN,vs,ps,attributeMap,uniformMap); MeshParticleMaterial.SHADERDEFINE_MAINTEXTURE=shaderCompile.registerMaterialDefine("MAINTEXTURE"); MeshParticleMaterial.SHADERDEFINE_MASKTEXTURE=shaderCompile.registerMaterialDefine("MASKTEXTURE"); MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET1=shaderCompile.registerMaterialDefine("TILINGOFFSET1"); MeshParticleMaterial.SHADERDEFINE_TILINGOFFSET2=shaderCompile.registerMaterialDefine("TILINGOFFSET2"); ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_BILLBOARD=shaderCompile.registerSpriteDefine("SPHERHBILLBOARD"); ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_STRETCHEDBILLBOARD=shaderCompile.registerSpriteDefine("STRETCHEDBILLBOARD"); ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_HORIZONTALBILLBOARD=shaderCompile.registerSpriteDefine("HORIZONTALBILLBOARD"); ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_VERTICALBILLBOARD=shaderCompile.registerSpriteDefine("VERTICALBILLBOARD"); ShuriKenParticle3D.SHADERDEFINE_COLOROVERLIFETIME=shaderCompile.registerSpriteDefine("COLOROVERLIFETIME"); ShuriKenParticle3D.SHADERDEFINE_RANDOMCOLOROVERLIFETIME=shaderCompile.registerSpriteDefine("RANDOMCOLOROVERLIFETIME"); ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMECONSTANT=shaderCompile.registerSpriteDefine("VELOCITYOVERLIFETIMECONSTANT"); ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMECURVE=shaderCompile.registerSpriteDefine("VELOCITYOVERLIFETIMECURVE"); ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCONSTANT=shaderCompile.registerSpriteDefine("VELOCITYOVERLIFETIMERANDOMCONSTANT"); ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCURVE=shaderCompile.registerSpriteDefine("VELOCITYOVERLIFETIMERANDOMCURVE"); ShuriKenParticle3D.SHADERDEFINE_TEXTURESHEETANIMATIONCURVE=shaderCompile.registerSpriteDefine("TEXTURESHEETANIMATIONCURVE"); ShuriKenParticle3D.SHADERDEFINE_TEXTURESHEETANIMATIONRANDOMCURVE=shaderCompile.registerSpriteDefine("TEXTURESHEETANIMATIONRANDOMCURVE"); ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIME=shaderCompile.registerSpriteDefine("ROTATIONOVERLIFETIME"); ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMESEPERATE=shaderCompile.registerSpriteDefine("ROTATIONOVERLIFETIMESEPERATE"); ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMECONSTANT=shaderCompile.registerSpriteDefine("ROTATIONOVERLIFETIMECONSTANT"); ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMECURVE=shaderCompile.registerSpriteDefine("ROTATIONOVERLIFETIMECURVE"); ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCONSTANTS=shaderCompile.registerSpriteDefine("ROTATIONOVERLIFETIMERANDOMCONSTANTS"); ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCURVES=shaderCompile.registerSpriteDefine("ROTATIONOVERLIFETIMERANDOMCURVES"); ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMECURVE=shaderCompile.registerSpriteDefine("SIZEOVERLIFETIMECURVE"); ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMECURVESEPERATE=shaderCompile.registerSpriteDefine("SIZEOVERLIFETIMECURVESEPERATE"); ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVES=shaderCompile.registerSpriteDefine("SIZEOVERLIFETIMERANDOMCURVES"); ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVESSEPERATE=shaderCompile.registerSpriteDefine("SIZEOVERLIFETIMERANDOMCURVESSEPERATE"); ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_MESH=shaderCompile.registerSpriteDefine("RENDERMODE_MESH"); ShuriKenParticle3D.SHADERDEFINE_SHAPE=shaderCompile.registerSpriteDefine("SHAPE"); } ParticleMaterial.MAINTEXTURE=1; ParticleMaterial.MASKTEXTURE=2; ParticleMaterial.BASECOLOR=3; ParticleMaterial.ALPHACOLOR=4; ParticleMaterial.INTENSITY=5; ParticleMaterial.ALPHA=6; ParticleMaterial.TILINGOFFSET1=7; ParticleMaterial.TILINGOFFSET2=8; ParticleMaterial.SHADERDEFINE_MAINTEXTURE=0; ParticleMaterial.SHADERDEFINE_MASKTEXTURE=0; ParticleMaterial.SHADERDEFINE_TILINGOFFSET1=0; ParticleMaterial.SHADERDEFINE_TILINGOFFSET2=0; __static(ParticleMaterial, ['shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return ParticleMaterial; })(BaseMaterial) /** *... *@author */ //class laya.d3.extension.lulingmen.UVSineMaterial extends laya.d3.core.material.BaseMaterial var UVSineMaterial=(function(_super){ function UVSineMaterial(){ UVSineMaterial.__super.call(this); this.setShaderName("UVSine"); this._setColor(3,new Vector4(1,1,1,1)); this._setNumber(4,0.0); this._setNumber(5,0.0); this._setNumber(6,0.0); this._setNumber(7,0.0); this._setNumber(8,1.0); this._setNumber(9,1.0); } __class(UVSineMaterial,'laya.d3.extension.lulingmen.UVSineMaterial',_super); var __proto=UVSineMaterial.prototype; __getset(0,__proto,'alpha',function(){ return this._getNumber(9); },function(value){ value=Math.max(0.0,Math.min(1.0,value)); this._setNumber(9,value); }); /** *设置第一层贴图。 *@param value 第一层贴图。 */ /** *获取第一层贴图。 *@return 第一层贴图。 */ __getset(0,__proto,'baseTexture',function(){ return this._getTexture(1); },function(value){ if (value) this._addShaderDefine(laya.d3.extension.lulingmen.UVSineMaterial.SHADERDEFINE_BASETEXTURE); else this._removeShaderDefine(laya.d3.extension.lulingmen.UVSineMaterial.SHADERDEFINE_BASETEXTURE); this._setTexture(1,value); }); /** *设置第一层滚动速度X。 *@param value 第一层滚动速度X。 */ /** *获取第一层滚动速度X。 *@return 第一层滚动速度X。 */ __getset(0,__proto,'baseScrollSpeedX',function(){ return this._getNumber(4); },function(value){ this._setNumber(4,value); }); /** *设置第二层贴图。 *@param value 第二层贴图。 */ /** *获取第二层贴图。 *@return 第二层贴图。 */ __getset(0,__proto,'secondTexture',function(){ return this._getTexture(2); },function(value){ if (value) this._addShaderDefine(laya.d3.extension.lulingmen.UVSineMaterial.SHADERDEFINE_SECONDTEXTURE); else this._removeShaderDefine(laya.d3.extension.lulingmen.UVSineMaterial.SHADERDEFINE_SECONDTEXTURE); this._setTexture(2,value); }); __getset(0,__proto,'mMultiplier',function(){ return this._getNumber(8); },function(value){ this._setNumber(8,value); }); /** *设置第一层滚动速度Y。 *@param value 第一层滚动速度Y。 */ /** *获取第一层滚动速度Y。 *@return 第一层滚动速度Y。 */ __getset(0,__proto,'baseScrollSpeedY',function(){ return this._getNumber(5); },function(value){ this._setNumber(5,value); }); /** *设置基础颜色。 *@param value 基础颜色。 */ /** *获取基础颜色。 *@return 基础颜色。 */ __getset(0,__proto,'albedoColor',function(){ return this._getColor(3); },function(value){ this._setColor(3,value); }); /** *设置第二层滚动速度X。 *@param value 第二层滚动速度X。 */ /** *获取第二层滚动速度X。 *@return 第二层滚动速度X。 */ __getset(0,__proto,'secondScrollSpeedX',function(){ return this._getNumber(6); },function(value){ this._setNumber(6,value); }); /** *设置第二层滚动速度Y。 *@param value 第二层滚动速度Y。 */ /** *获取第二层滚动速度Y。 *@return 第二层滚动速度Y。 */ __getset(0,__proto,'secondScrollSpeedY',function(){ return this._getNumber(7); },function(value){ this._setNumber(7,value); }); /** *设置纹理平铺和偏移。 *@param value 纹理平铺和偏移。 */ /** *获取纹理平铺和偏移。 *@return 纹理平铺和偏移。 */ __getset(0,__proto,'tilingOffset',function(){ return this._getColor(10); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(laya.d3.extension.lulingmen.UVSineMaterial.SHADERDEFINE_TILINGOFFSET1); else this._removeShaderDefine(laya.d3.extension.lulingmen.UVSineMaterial.SHADERDEFINE_TILINGOFFSET1); }else { this._removeShaderDefine(laya.d3.extension.lulingmen.UVSineMaterial.SHADERDEFINE_TILINGOFFSET1); } this._setColor(10,value); }); /** *设置纹理平铺和偏移。 *@param value 纹理平铺和偏移。 */ /** *获取纹理平铺和偏移。 *@return 纹理平铺和偏移。 */ __getset(0,__proto,'detailTilingOffset',function(){ return this._getColor(11); },function(value){ if (value){ var valueE=value.elements; if (valueE[0] !=1 || valueE[1] !=1 || valueE[2] !=0 || valueE[3] !=0) this._addShaderDefine(laya.d3.extension.lulingmen.UVSineMaterial.SHADERDEFINE_TILINGOFFSET2); else this._removeShaderDefine(laya.d3.extension.lulingmen.UVSineMaterial.SHADERDEFINE_TILINGOFFSET2); }else { this._removeShaderDefine(laya.d3.extension.lulingmen.UVSineMaterial.SHADERDEFINE_TILINGOFFSET2); } this._setColor(11,value); }); UVSineMaterial.__init__=function(){ UVSineMaterial.SHADERDEFINE_BASETEXTURE=UVSineMaterial.shaderDefines.registerDefine("BASETEXTURE"); UVSineMaterial.SHADERDEFINE_SECONDTEXTURE=UVSineMaterial.shaderDefines.registerDefine("SECONDTEXTURE"); UVSineMaterial.SHADERDEFINE_TILINGOFFSET1=UVSineMaterial.shaderDefines.registerDefine("TILINGOFFSET1"); UVSineMaterial.SHADERDEFINE_TILINGOFFSET2=UVSineMaterial.shaderDefines.registerDefine("TILINGOFFSET2"); } UVSineMaterial.initShader=function(){ var attributeMap={ 'a_Position':/*laya.d3.graphics.VertexElementUsage.POSITION0*/0, 'a_Normal':/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3, 'a_Color':/*laya.d3.graphics.VertexElementUsage.COLOR0*/1, 'a_Texcoord0':/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2 }; var uniformMap={ 'u_MvpMatrix':[ /*laya.d3.core.Sprite3D.MVPMATRIX*/1,/*laya.d3.shader.Shader3D.PERIOD_SPRITE*/2], 'u_Time':[ /*laya.d3.core.scene.Scene.TIME*/22,/*laya.d3.shader.Shader3D.PERIOD_SCENE*/4], 'u_BaseTexture':[ /*CLASS CONST:laya.d3.extension.lulingmen.UVSineMaterial.BASETEXTURE*/1,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_SecondTexture':[ /*CLASS CONST:laya.d3.extension.lulingmen.UVSineMaterial.SECONDTEXTURE*/2,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_BaseColor':[ /*CLASS CONST:laya.d3.extension.lulingmen.UVSineMaterial.BASECOLOR*/3,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_BaseScrollSpeedX':[ /*CLASS CONST:laya.d3.extension.lulingmen.UVSineMaterial.BASESCROLLSPEEDX*/4,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_BaseScrollSpeedY':[ /*CLASS CONST:laya.d3.extension.lulingmen.UVSineMaterial.BASESCROLLSPEEDY*/5,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_SecondScrollSpeedX':[ /*CLASS CONST:laya.d3.extension.lulingmen.UVSineMaterial.SECONDSCROLLSPEEDX*/6,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_SecondScrollSpeedY':[ /*CLASS CONST:laya.d3.extension.lulingmen.UVSineMaterial.SECONDSCROLLSPEEDY*/7,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_MMultiplier':[ /*CLASS CONST:laya.d3.extension.lulingmen.UVSineMaterial.MMULTIPLIER*/8,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_Alpha':[ /*CLASS CONST:laya.d3.extension.lulingmen.UVSineMaterial.ALPHA*/9,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_TilingOffset1':[ /*CLASS CONST:laya.d3.extension.lulingmen.UVSineMaterial.TILINGOFFSET1*/10,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_TilingOffset2':[ /*CLASS CONST:laya.d3.extension.lulingmen.UVSineMaterial.TILINGOFFSET2*/11,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1] }; var shader=Shader3D.nameKey.add("UVSine"); var vs="attribute vec4 a_Position;\nattribute vec3 a_Normal;\nattribute vec2 a_Texcoord0;\nattribute vec4 a_Color;\n\nuniform mat4 u_MvpMatrix;\nuniform float u_Time;\nuniform float u_BaseScrollSpeedX;\nuniform float u_BaseScrollSpeedY;\nuniform float u_SecondScrollSpeedX;\nuniform float u_SecondScrollSpeedY;\n\nuniform vec4 u_TilingOffset1;\nuniform vec4 u_TilingOffset2;\n\nvarying vec2 v_Texcoord0;\nvarying vec2 v_Texcoord1;\nvarying vec4 v_Color;\n\nvoid main()\n{\n v_Texcoord0 = a_Texcoord0;\n #ifdef TILINGOFFSET1\n v_Texcoord0 = (vec2(v_Texcoord0.x, v_Texcoord0.y - 1.0) * u_TilingOffset1.xy) + u_TilingOffset1.zw;\n v_Texcoord0 = vec2(v_Texcoord0.x, 1.0 + v_Texcoord0.y);\n #endif\n \n v_Texcoord1 = a_Texcoord0;\n #ifdef TILINGOFFSET2\n v_Texcoord1 = (vec2(v_Texcoord1.x, v_Texcoord1.y - 1.0) * u_TilingOffset2.xy) + u_TilingOffset2.zw;\n v_Texcoord1 = vec2(v_Texcoord1.x, 1.0 + v_Texcoord1.y);\n #endif\n \n v_Texcoord0 = v_Texcoord0 + vec2(fract(u_BaseScrollSpeedX * u_Time / 20.0), fract(-u_BaseScrollSpeedY * u_Time));\n v_Texcoord1 = v_Texcoord1 + vec2(fract(u_SecondScrollSpeedX * u_Time / 20.0), fract(-u_SecondScrollSpeedY * u_Time));\n \n v_Color = vec4(1.0);\n #ifdef COLOR\n v_Color = a_Color;\n #endif\n \n gl_Position = u_MvpMatrix * a_Position;\n}"; var ps="#ifdef FSHIGHPRECISION\n precision highp float;\n#else\n precision mediump float;\n#endif\n\nvarying vec2 v_Texcoord0;\nvarying vec2 v_Texcoord1;\nvarying vec4 v_Color;\n\n#ifdef BASETEXTURE\n uniform sampler2D u_BaseTexture;\n#endif\n\n#ifdef SECONDTEXTURE\n uniform sampler2D u_SecondTexture;\n#endif\n\nuniform vec4 u_BaseColor;\nuniform float u_MMultiplier;\nuniform float u_Alpha;\n\nvoid main()\n{\n vec4 baseTextureColor = vec4(1.0);\n #ifdef BASETEXTURE\n baseTextureColor = texture2D(u_BaseTexture, v_Texcoord0);\n #endif\n \n vec4 secondTextureColor = vec4(1.0);\n #ifdef SECONDTEXTURE\n secondTextureColor = texture2D(u_SecondTexture, v_Texcoord1);\n #endif\n \n gl_FragColor = baseTextureColor * secondTextureColor * u_BaseColor * u_MMultiplier * v_Color;\n gl_FragColor.a *= u_Alpha;\n}\n"; var shaderCompile3D=ShaderCompile3D.add(shader,vs,ps,attributeMap,uniformMap); laya.d3.extension.lulingmen.UVSineMaterial.SHADERDEFINE_BASETEXTURE=shaderCompile3D.registerMaterialDefine("BASETEXTURE"); laya.d3.extension.lulingmen.UVSineMaterial.SHADERDEFINE_SECONDTEXTURE=shaderCompile3D.registerMaterialDefine("SECONDTEXTURE"); laya.d3.extension.lulingmen.UVSineMaterial.SHADERDEFINE_TILINGOFFSET1=shaderCompile3D.registerMaterialDefine("TILINGOFFSET1"); laya.d3.extension.lulingmen.UVSineMaterial.SHADERDEFINE_TILINGOFFSET2=shaderCompile3D.registerMaterialDefine("TILINGOFFSET2"); } UVSineMaterial.BASETEXTURE=1; UVSineMaterial.SECONDTEXTURE=2; UVSineMaterial.BASECOLOR=3; UVSineMaterial.BASESCROLLSPEEDX=4; UVSineMaterial.BASESCROLLSPEEDY=5; UVSineMaterial.SECONDSCROLLSPEEDX=6; UVSineMaterial.SECONDSCROLLSPEEDY=7; UVSineMaterial.MMULTIPLIER=8; UVSineMaterial.ALPHA=9; UVSineMaterial.TILINGOFFSET1=10; UVSineMaterial.TILINGOFFSET2=11; UVSineMaterial.SHADERDEFINE_BASETEXTURE=0; UVSineMaterial.SHADERDEFINE_SECONDTEXTURE=0; UVSineMaterial.SHADERDEFINE_TILINGOFFSET1=0; UVSineMaterial.SHADERDEFINE_TILINGOFFSET2=0; __static(UVSineMaterial, ['shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(BaseMaterial.shaderDefines);} ]); return UVSineMaterial; })(BaseMaterial) /** *... *@author ... */ //class laya.d3.water.WaterDetailMaterial extends laya.d3.core.material.BaseMaterial var WaterDetailMaterial=(function(_super){ function WaterDetailMaterial(){ this._startTm=0; WaterDetailMaterial.__super.call(this); laya.d3.water.WaterDetailMaterial.init(); this.setShaderName('WaterDetail'); this.cull=0; this._startTm=Laya.timer.currTimer; } __class(WaterDetailMaterial,'laya.d3.water.WaterDetailMaterial',_super); var __proto=WaterDetailMaterial.prototype; __getset(0,__proto,'currentTm',function(){ return this._getNumber(1); },function(v){ this._setNumber(1,v-this._startTm); }); __getset(0,__proto,'waveInfo',function(){ return this._getBuffer(12); },function(v){ this._setBuffer(12,v); }); __getset(0,__proto,'waveInfoD',function(){ return this._getBuffer(13); },function(v){ this._setBuffer(13,v); }); __getset(0,__proto,'texWaveUVScale',function(){ return this._getNumber(15); },function(v){ this._setNumber(15,v); }); WaterDetailMaterial.init=function(){ if (laya.d3.water.WaterDetailMaterial._bInited) return; laya.d3.water.WaterDetailMaterial._bInited=true; var attributeMap={ 'a_position':/*laya.d3.graphics.VertexElementUsage.POSITION0*/0, 'a_normal':/*laya.d3.graphics.VertexElementUsage.NORMAL0*/3, 'uv':/*laya.d3.graphics.VertexElementUsage.TEXTURECOORDINATE0*/2 }; var uniformMap={ 'u_curTm':[1,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_WaveInfo':[12,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'u_WaveInfoD':[13,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1], 'TEXWAVE_UV_SCALE':[15,/*laya.d3.shader.Shader3D.PERIOD_MATERIAL*/1] }; var WaterDetail=Shader3D.nameKey.add("WaterDetail"); var vs="\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec2 uv;\n\nvarying vec2 vUv;\nvarying vec3 vWorldNorm;\nvarying vec3 vWorldTangent;\nvarying vec3 vWorldBinormal;\n\n\nvoid main() {\n vec3 pos = a_position;\n if(pos.z!=0.)pos.y=pos.z;\n pos.z=0.5;\n gl_Position = vec4(pos,1.);\n vUv = uv;\n //vWorldNorm = normalize((modelMat*vec4(a_normal,0.0)).xyz);\n //vWorldTangent = normalize((modelMat*vec4(tangent,0.0)).xyz);\n //vWorldBinormal = normalize((modelMat*vec4(binormal,0.0)).xyz);\n}\n"; var ps="precision highp float;\nprecision lowp int;\n\nconst float PI = 3.14159265358979323846264;\nconst float _2PI = 6.2831853071796;\nvarying vec2 vUv;\nvarying vec3 vWorldNorm;\nvarying vec3 vWorldTangent;\nvarying vec3 vWorldBinormal;\n\nuniform float u_curTm;\n\n#include \"WaveFunction.glsl\"\n\nvoid main() {\n vec3 wave_N,wave_B,wave_T;\n calcWave(u_curTm, vUv,wave_B,wave_T,wave_N);\n gl_FragColor.rgb = normalize(wave_N)*0.5+vec3(0.5);// vec3(0.1,.4,0.1);\n gl_FragColor.a = 1.0;\n}\n"; var shaderCompile=ShaderCompile3D.add(WaterDetail,vs,ps,attributeMap,uniformMap); } WaterDetailMaterial.CURTM=1; WaterDetailMaterial.WAVEINFO=12; WaterDetailMaterial.WAVEINFOD=13; WaterDetailMaterial.WAVEMAINDIR=14; WaterDetailMaterial.TEXWAVE_UV_SCALE=15; WaterDetailMaterial._bInited=false; return WaterDetailMaterial; })(BaseMaterial) /** *RigidAnimations 类用于创建变换动画组件。 */ //class laya.d3.component.animation.RigidAnimations extends laya.d3.component.animation.KeyframeAnimations var RigidAnimations=(function(_super){ function RigidAnimations(){ /**@private */ this._animationSprites=null; /**@private */ this._animationSpritesInitLocalMatrix=null; /**@private */ this._tempCurAnimationData=null; /**@private */ this._curOriginalData=null; /**@private */ this._lastFrameIndex=-1; /**@private */ this._curAnimationDatas=null; RigidAnimations.__super.call(this); this._animationSprites=[]; this._animationSpritesInitLocalMatrix=[]; } __class(RigidAnimations,'laya.d3.component.animation.RigidAnimations',_super); var __proto=RigidAnimations.prototype; /** *@private */ __proto._init=function(){ var nodes=this._templet.getNodes(this.currentAnimationClipIndex); var curParentSprite=this._owner; var nodeLength=nodes.length; var pathStart=0; var extentDatas=new Uint16Array(this._templet.getPublicExtData()); for (var i=0;i < nodeLength;i++){ var hierarchys=extentDatas.slice(pathStart+1,pathStart+1+extentDatas[pathStart]); pathStart+=(extentDatas[pathStart]+1); for (var j=1;j < hierarchys.length;j++){ var childIndex=hierarchys[j]; curParentSprite=curParentSprite._childs[hierarchys[j]]; }; var curSprite=curParentSprite.getChildByName(nodes[i].name); if (!curSprite) break ; this._animationSprites[i]=curSprite; var localMatrix=this._animationSpritesInitLocalMatrix[i]; (localMatrix)|| (localMatrix=this._animationSpritesInitLocalMatrix[i]=new Matrix4x4()); curSprite.transform.localMatrix.cloneTo(localMatrix); curParentSprite=this._owner; } } /** *@private */ __proto._animtionPlay=function(){ if (this._templet.loaded) this._init(); else this._templet.once(/*laya.events.Event.LOADED*/"loaded",this,this._init); } /** *@private */ __proto._animtionStop=function(){ this._lastFrameIndex=-1; if (this._player.returnToZeroStopped){ this._curAnimationDatas=null; for (var i=0;i < this._animationSprites.length;i++) this._animationSprites[i].transform.localMatrix=this._animationSpritesInitLocalMatrix[i]; } } /** *@private *摄像机动画作用函数。 */ __proto._effectAnimation=function(nodes){ for (var nodeIndex=0,nodeLength=this._animationSprites.length;nodeIndex < nodeLength;nodeIndex++){ var sprite=this._animationSprites[nodeIndex]; var matrix=sprite.transform.localMatrix; var matrixE=matrix.elements; for (var i=0;i < 16;i++) matrixE[i]=this._curAnimationDatas[nodeIndex *16+i]; sprite.transform.localMatrix=matrix; } } /** *@private *初始化载入摄像机动画组件。 *@param owner 所属精灵对象。 */ __proto._load=function(owner){ _super.prototype._load.call(this,owner); this._player.on(/*laya.events.Event.STOPPED*/"stopped",this,this._animtionStop); this._player.on(/*laya.events.Event.PLAYED*/"played",this,this._animtionPlay); } /** *@private *更新摄像机动画组件。 *@param state 渲染状态。 */ __proto._update=function(state){ if (this._player.state!==/*laya.ani.AnimationState.playing*/2 || !this._templet || !this._templet.loaded) return; var rate=this._player.playbackRate *Laya.timer.scale; var cachePlayRate=this._player.cachePlayRate; var isCache=this._player.isCache && rate >=cachePlayRate; var frameIndex=isCache ? this.currentFrameIndex :-1; if (frameIndex!==-1 && this._lastFrameIndex===frameIndex) return; var animationClipIndex=this.currentAnimationClipIndex; var nodes=this._templet.getNodes(animationClipIndex); var animationDatasCache=this._templet._animationDatasCache; if (isCache){ var cacheData=this._templet.getAnimationDataWithCache(cachePlayRate,animationDatasCache,animationClipIndex,frameIndex); if (cacheData){ this._curAnimationDatas=cacheData; this._lastFrameIndex=frameIndex; this._effectAnimation(nodes); return; } }; var nodeFloatCount=nodes.length *16; if (isCache){ this._curAnimationDatas=new Float32Array(nodeFloatCount); }else{ (this._tempCurAnimationData)|| (this._tempCurAnimationData=new Float32Array(nodeFloatCount)); this._curAnimationDatas=this._tempCurAnimationData; } this._curOriginalData || (this._curOriginalData=new Float32Array(this._templet.getTotalkeyframesLength(animationClipIndex))); if (isCache) this._templet.getOriginalData(animationClipIndex,this._curOriginalData,this._player._fullFrames[animationClipIndex],frameIndex,this._player.currentFrameTime); else this._templet.getOriginalDataUnfixedRate(animationClipIndex,this._curOriginalData,this._player.currentPlayTime); Utils3D._computeRootAnimationData(nodes,this._curOriginalData,this._curAnimationDatas); if (isCache){ this._templet.setAnimationDataWithCache(cachePlayRate,animationDatasCache,animationClipIndex,frameIndex,this._curAnimationDatas); } this._lastFrameIndex=frameIndex; this._effectAnimation(nodes); } /** *@private *卸载组件时执行。 */ __proto._unload=function(owner){ _super.prototype._unload.call(this,owner); this._animationSprites=null; this._animationSpritesInitLocalMatrix=null; this._tempCurAnimationData=null; this._curOriginalData=null; this._curAnimationDatas=null; } /** *设置url地址。 *@param value 地址。 */ __getset(0,__proto,'url',null,function(value){ console.log("Warning: discard property,please use templet property instead."); var templet=Laya.loader.create(value,null,null,AnimationTemplet); if (this._templet!==templet){ if (this._player.state!==/*laya.ani.AnimationState.stopped*/0) this._player.stop(true); this._templet=templet; this._player.templet=templet; this._curOriginalData=null; this._curAnimationDatas=null; this._tempCurAnimationData=null; (this._templet._animationDatasCache)|| (this._templet._animationDatasCache=[]); this.event(/*laya.events.Event.ANIMATION_CHANGED*/"animationchanged",this); } }); __getset(0,__proto,'templet',_super.prototype._$get_templet,function(value){ if (this._templet!==value){ if (this._player.state!==/*laya.ani.AnimationState.stopped*/0) this._player.stop(true); this._templet=value; this._player.templet=value; this._curOriginalData=null; this._curAnimationDatas=null; this._tempCurAnimationData=null; (this._templet._animationDatasCache)|| (this._templet._animationDatasCache=[]); this.event(/*laya.events.Event.ANIMATION_CHANGED*/"animationchanged",this); } }); return RigidAnimations; })(KeyframeAnimations) /** *SkinAnimations 类用于创建蒙皮动画组件。 */ //class laya.d3.component.animation.SkinAnimations extends laya.d3.component.animation.KeyframeAnimations var SkinAnimations=(function(_super){ function SkinAnimations(){ /**@private */ this._tempCurAnimationData=null; /**@private */ this._tempCurBonesData=null; /**@private */ this._curOriginalData=null; /**@private */ this._lastFrameIndex=-1; /**@private */ this._curMeshAnimationData=null; /**@private */ this._curBonesDatas=null; /**@private */ this._curAnimationDatas=null; /**@private */ this._ownerMesh=null; /**@private */ this._boneIndexToMeshList=null; /**@private */ this._oldVersion=false; SkinAnimations.__super.call(this); this._boneIndexToMeshList=[]; } __class(SkinAnimations,'laya.d3.component.animation.SkinAnimations',_super); var __proto=SkinAnimations.prototype; /** *@private */ __proto._computeBoneIndexToMeshOnTemplet=function(){ if (this._templet.loaded) this._computeBoneIndexToMeshOnMesh(); else this._templet.once(/*laya.events.Event.LOADED*/"loaded",this,this._computeBoneIndexToMeshOnMesh); } /** *@private */ __proto._computeBoneIndexToMeshOnMesh=function(){ if (this._templet._aniVersion==="LAYAANIMATION:02") this._oldVersion=false; else this._oldVersion=true; var mesh=(this._owner).meshFilter.sharedMesh; if (mesh.loaded) this._computeBoneIndexToMesh(mesh); else mesh.on(/*laya.events.Event.LOADED*/"loaded",this,this._computeBoneIndexToMesh); } /** *@private */ __proto._computeBoneIndexToMesh=function(mesh){ var meshBoneNames=mesh._boneNames; if (meshBoneNames){ var binPoseCount=meshBoneNames.length; var anis=this._templet._anis; for (var i=0,n=anis.length;i < n;i++){ var boneIndexToMesh=this._boneIndexToMeshList[i]; (boneIndexToMesh)|| (boneIndexToMesh=this._boneIndexToMeshList[i]=[]); boneIndexToMesh.length=binPoseCount; var ani=anis[i]; for (var j=0;j < binPoseCount;j++) boneIndexToMesh[j]=ani.bone3DMap[meshBoneNames[j]]; } } } /**@private */ __proto._getAnimationDatasWithCache=function(rate,mesh,cacheDatas,aniIndex,frameIndex){ var aniDatas=cacheDatas[aniIndex]; if (!aniDatas){ return null; }else { var rateDatas=aniDatas[rate]; if (!rateDatas) return null; else { var meshDatas=rateDatas[mesh.id]; if (!meshDatas) return null; else return meshDatas[frameIndex]; } } } /**@private */ __proto._setAnimationDatasWithCache=function(rate,mesh,cacheDatas,aniIndex,frameIndex,animationDatas){ var aniDatas=(cacheDatas[aniIndex])|| (cacheDatas[aniIndex]={}); var rateDatas=(aniDatas[rate])|| (aniDatas[rate]={}); var meshDatas=(rateDatas[mesh.id])|| (rateDatas[mesh.id]=[]); meshDatas[frameIndex]=animationDatas; } /**@private */ __proto._onAnimationPlayMeshLoaded=function(){ var renderElements=this._ownerMesh.meshRender._renderElements; for (var i=0,n=renderElements.length;i < n;i++) renderElements[i]._canDynamicBatch=false; } /**@private */ __proto._onAnimationPlay=function(){ this._ownerMesh._render._addShaderDefine(SkinnedMeshSprite3D.SHADERDEFINE_BONE); var mesh=this._ownerMesh.meshFilter.sharedMesh; if (mesh.loaded) this._onAnimationPlayMeshLoaded(); else mesh.once(/*laya.events.Event.LOADED*/"loaded",this,this._onAnimationPlayMeshLoaded); } /**@private */ __proto._onAnimationStop=function(){ this._lastFrameIndex=-1; if (this._player.returnToZeroStopped){ this._curBonesDatas=null; this._curAnimationDatas=null; this._ownerMesh._render._removeShaderDefine(SkinnedMeshSprite3D.SHADERDEFINE_BONE); }; var renderElements=this._ownerMesh.meshRender._renderElements; for (var i=0,n=renderElements.length;i < n;i++) renderElements[i]._canDynamicBatch=true; } /** *@private *初始化载入蒙皮动画组件。 *@param owner 所属精灵对象。 */ __proto._load=function(owner){ _super.prototype._load.call(this,owner); this._ownerMesh=(owner); this._player.on(/*laya.events.Event.PLAYED*/"played",this,this._onAnimationPlay); this._player.on(/*laya.events.Event.STOPPED*/"stopped",this,this._onAnimationStop); (this._owner).meshFilter.on(/*laya.events.Event.MESH_CHANGED*/"meshchanged",this,this._computeBoneIndexToMeshOnTemplet); } /** *@private *更新蒙皮动画组件。 *@param state 渲染状态参数。 */ __proto._update=function(state){ var mesh=this._ownerMesh.meshFilter.sharedMesh; if (this._player.state!==/*laya.ani.AnimationState.playing*/2 || !this._templet || !this._templet.loaded || !mesh.loaded) return; var rate=this._player.playbackRate *Laya.timer.scale; var cachePlayRate=this._player.cachePlayRate; var isCache=this._player.isCache && rate >=cachePlayRate; var frameIndex=isCache ? this.currentFrameIndex :-1; if (frameIndex!==-1 && this._lastFrameIndex===frameIndex) return; var animationClipIndex=this.currentAnimationClipIndex; var boneDatasCache=this._templet._animationDatasCache[0]; var animationDatasCache=this._templet._animationDatasCache[1]; if (isCache){ var cacheAnimationDatas=this._getAnimationDatasWithCache(cachePlayRate,mesh,animationDatasCache,animationClipIndex,frameIndex); if (cacheAnimationDatas){ this._curAnimationDatas=cacheAnimationDatas; this._curBonesDatas=this._templet.getAnimationDataWithCache(cachePlayRate,boneDatasCache,animationClipIndex,frameIndex); this._lastFrameIndex=frameIndex; return; } }; var isCacheBonesDatas=false; if (isCache){ this._curBonesDatas=this._templet.getAnimationDataWithCache(cachePlayRate,boneDatasCache,animationClipIndex,frameIndex); isCacheBonesDatas=this._curBonesDatas ? true :false; }; var bones=this._templet.getNodes(animationClipIndex); var boneFloatCount=bones.length *16; var inverseAbsoluteBindPoses=mesh.InverseAbsoluteBindPoses; if (this._oldVersion) (this._curMeshAnimationData)|| (this._curMeshAnimationData=new Float32Array(boneFloatCount)); else (this._curMeshAnimationData)|| (this._curMeshAnimationData=new Float32Array(inverseAbsoluteBindPoses.length *16)); var i=0,n=0,j=0; var curSubAnimationDatas,subMesh,boneIndicesCount=0; var subMeshCount=mesh.getSubMeshCount(); if (isCache){ this._curAnimationDatas=[]; this._curAnimationDatas.length=subMeshCount; for (i=0;i < subMeshCount;i++){ curSubAnimationDatas=this._curAnimationDatas[i]=[]; subMesh=mesh.getSubMesh(i); boneIndicesCount=subMesh._boneIndicesList.length; curSubAnimationDatas.length=boneIndicesCount; for (j=0;j < boneIndicesCount;j++) curSubAnimationDatas[j]=new Float32Array(subMesh._boneIndicesList[j].length *16); } (isCacheBonesDatas)|| (this._curBonesDatas=new Float32Array(boneFloatCount)); }else { if (!this._tempCurAnimationData){ this._tempCurAnimationData=[]; this._tempCurAnimationData.length=subMeshCount; for (i=0;i < subMeshCount;i++){ curSubAnimationDatas=this._tempCurAnimationData[i]=[]; subMesh=mesh.getSubMesh(i); boneIndicesCount=subMesh._boneIndicesList.length; curSubAnimationDatas.length=boneIndicesCount; for (j=0;j < boneIndicesCount;j++) curSubAnimationDatas[j]=new Float32Array(subMesh._boneIndicesList[j].length *16); } } (this._tempCurBonesData)|| (this._tempCurBonesData=new Float32Array(boneFloatCount)); this._curAnimationDatas=this._tempCurAnimationData; this._curBonesDatas=this._tempCurBonesData; } this._curOriginalData || (this._curOriginalData=new Float32Array(this._templet.getTotalkeyframesLength(animationClipIndex))); if (isCache) this._templet.getOriginalData(animationClipIndex,this._curOriginalData,this._player._fullFrames[animationClipIndex],frameIndex,this._player.currentFrameTime); else this._templet.getOriginalDataUnfixedRate(animationClipIndex,this._curOriginalData,this._player.currentPlayTime); if (this._oldVersion){ if (isCache && isCacheBonesDatas) Utils3D._computeAnimationDatasByArrayAndMatrixFastOld(inverseAbsoluteBindPoses,this._curBonesDatas,this._curMeshAnimationData); else Utils3D._computeBoneAndAnimationDatasByBindPoseMatrxixOld(bones,this._curOriginalData,inverseAbsoluteBindPoses,this._curBonesDatas,this._curMeshAnimationData); }else { var boneIndexToMesh=this._boneIndexToMeshList[animationClipIndex]; if (isCache && isCacheBonesDatas) Utils3D._computeAnimationDatasByArrayAndMatrixFast(inverseAbsoluteBindPoses,this._curBonesDatas,this._curMeshAnimationData,boneIndexToMesh); else Utils3D._computeBoneAndAnimationDatasByBindPoseMatrxix(bones,this._curOriginalData,inverseAbsoluteBindPoses,this._curBonesDatas,this._curMeshAnimationData,boneIndexToMesh); } for (i=0;i < subMeshCount;i++){ var boneIndicesList=mesh.getSubMesh(i)._boneIndicesList; boneIndicesCount=boneIndicesList.length; curSubAnimationDatas=this._curAnimationDatas[i] for (j=0;j < boneIndicesCount;j++) SkinAnimations._splitAnimationDatas(boneIndicesList[j],this._curMeshAnimationData,curSubAnimationDatas[j]); } if (isCache){ this._setAnimationDatasWithCache(cachePlayRate,mesh,animationDatasCache,animationClipIndex,frameIndex,this._curAnimationDatas); (isCacheBonesDatas)|| (this._templet.setAnimationDataWithCache(cachePlayRate,boneDatasCache,animationClipIndex,frameIndex,this._curBonesDatas)); } this._lastFrameIndex=frameIndex; } /** *@private *在渲染前更新蒙皮动画组件渲染参数。 *@param state 渲染状态参数。 */ __proto._preRenderUpdate=function(state){ var subMesh=state.renderElement.renderObj; if (this._curAnimationDatas) subMesh._skinAnimationDatas=this._curAnimationDatas[subMesh._indexInMesh]; else subMesh._skinAnimationDatas=null; } /** *@private *卸载组件时执行 */ __proto._unload=function(owner){ (this.player.state==/*laya.ani.AnimationState.playing*/2)&& (this._ownerMesh._render._removeShaderDefine(SkinnedMeshSprite3D.SHADERDEFINE_BONE)); (this._templet && !this._templet.loaded)&& (this._templet.off(/*laya.events.Event.LOADED*/"loaded",this,this._computeBoneIndexToMeshOnMesh)); var mesh=this._ownerMesh.meshFilter.sharedMesh; (mesh.loaded)|| (mesh.off(/*laya.events.Event.LOADED*/"loaded",this,this._onAnimationPlayMeshLoaded)); _super.prototype._unload.call(this,owner); this._tempCurAnimationData=null; this._tempCurBonesData=null; this._curOriginalData=null; this._curMeshAnimationData=null; this._curBonesDatas=null; this._curAnimationDatas=null; this._ownerMesh=null; } /** *获取骨骼数据。 *@return 骨骼数据。 */ __getset(0,__proto,'curBonesDatas',function(){ return this._curBonesDatas; }); __getset(0,__proto,'templet',_super.prototype._$get_templet,function(value){ if (this._templet!==value){ if (this._player.state!==/*laya.ani.AnimationState.stopped*/0) this._player.stop(true); this._templet=value; this._player.templet=value; this._computeBoneIndexToMeshOnTemplet(); this._curOriginalData=null; this._curMeshAnimationData=null; this._tempCurBonesData=null; this._tempCurAnimationData=null; (this._templet._animationDatasCache)|| (this._templet._animationDatasCache=[[],[]]); this.event(/*laya.events.Event.ANIMATION_CHANGED*/"animationchanged",this); } }); SkinAnimations._splitAnimationDatas=function(indices,bonesData,subAnimationDatas){ for (var i=0,n=indices.length,ii=0;i < n;i++){ for (var j=0;j < 16;j++,ii++){ subAnimationDatas[ii]=bonesData[(indices[i] << 4)+j]; } } } return SkinAnimations; })(KeyframeAnimations) /** *BoxCollider 类用于创建盒子碰撞器。 */ //class laya.d3.component.physics.BoxCollider extends laya.d3.component.physics.Collider var BoxCollider=(function(_super){ function BoxCollider(){ /**@private */ this._size=null; /**@private */ this._transformOrientedBoundBox=null; /**中心点 */ this.center=null; BoxCollider.__super.call(this); this._needUpdate=false; } __class(BoxCollider,'laya.d3.component.physics.BoxCollider',_super); var __proto=BoxCollider.prototype; /** *@private */ __proto._updateCollider=function(){ if (this._needUpdate){ var obbMat=this._transformOrientedBoundBox.transformation; var transform=(this._owner).transform; var rotation=transform.rotation; var scale=transform.scale; var centerE=this.center.elements; if (centerE[0]===0.0 && centerE[1]===0.0 && centerE[2]===0.0){ Matrix4x4.createAffineTransformation(transform.position,rotation,Vector3.ONE,obbMat); }else { Vector3.multiply(this.center,scale,BoxCollider._deviationV3); Vector3.transformQuat(BoxCollider._deviationV3,rotation,BoxCollider._deviationV3); Vector3.add(transform.position,BoxCollider._deviationV3,BoxCollider._deviationV3); Matrix4x4.createAffineTransformation(BoxCollider._deviationV3,rotation,Vector3.ONE,obbMat); } this._transformOrientedBoundBox.transformation=obbMat; var extentsE=this._transformOrientedBoundBox.extents.elements; var sizeE=this._size.elements; var scaleE=scale.elements; extentsE[0]=sizeE[0] *0.5 *scaleE[0]; extentsE[1]=sizeE[1] *0.5 *scaleE[1]; extentsE[2]=sizeE[2] *0.5 *scaleE[2]; this._needUpdate=false; } } /** *@private */ __proto._onWorldMatrixChanged=function(){ this._needUpdate=true; for (var k in this._runtimeCollisonMap){ this._runtimeCollisonTestMap[k]=true; this._runtimeCollisonMap[k]._runtimeCollisonTestMap[this.id]=true; } } /** *@inheritDoc */ __proto._initialize=function(owner){ laya.d3.component.Component3D.prototype._initialize.call(this,owner); this._transformOrientedBoundBox=new OrientedBoundBox(new Vector3(),new Matrix4x4()); this._size=new Vector3(); this.center=new Vector3(); (owner).transform.on(/*laya.events.Event.WORLDMATRIX_NEEDCHANGE*/"worldmatrixneedchanged",this,this._onWorldMatrixChanged); this._needUpdate=true; } /** *@inheritDoc */ __proto._getType=function(){ return 1; } /** *@inheritDoc */ __proto._collisonTo=function(other){ switch (other._getType()){ case 0: return this.boundBox.containsSphere((other).boundSphere)!==/*laya.d3.math.ContainmentType.Disjoint*/0; break ; case 1: return this.boundBox.containsOrientedBoundBox((other).boundBox)!==/*laya.d3.math.ContainmentType.Disjoint*/0; break ; case 2:; var meshCollider=other; if (this.boundBox.containsBoundBox(meshCollider._boundBox)!==/*laya.d3.math.ContainmentType.Disjoint*/0){ var positions=(other).mesh._positions; for (var i=0,n=positions.length;i < n;i++){ if (this.boundBox.containsPoint(positions[i])===/*laya.d3.math.ContainmentType.Contains*/1) return true } return false; }else { return false; } break ; default : throw new Error("BoxCollider:unknown collider type."); } } /** *@inheritDoc */ __proto._cloneTo=function(dest){ var destBoxCollider=dest; var destSize=destBoxCollider.size; this.size.cloneTo(destSize); destBoxCollider.size=destSize; this.center.cloneTo(destBoxCollider.center); } /** *@inheritDoc */ __proto.raycast=function(ray,hitInfo,maxDistance){ (maxDistance===void 0)&& (maxDistance=1.79e+308); this._updateCollider(); var distance=this._transformOrientedBoundBox.intersectsRay(ray,hitInfo.position); if (distance!==-1 && distance <=maxDistance){ hitInfo.distance=distance; hitInfo.sprite3D=this._owner; return true; }else { hitInfo.distance=-1; hitInfo.sprite3D=null; return false; } } /** *从AABB碰撞盒设置center和Size。 *@param boundBox 碰撞盒。 */ __proto.setFromBoundBox=function(boundBox){ OrientedBoundBox.createByBoundBox(boundBox,this._transformOrientedBoundBox); var extents=this._transformOrientedBoundBox.extents; this._size=new Vector3(extents.x *2,extents.y *2,extents.z *2); this.center=new Vector3(); Vector3.add(boundBox.min,boundBox.max,this.center); Vector3.scale(this.center,0.5,this.center); this._needUpdate=true; } /** *获取包围盒子,只读,不允许修改。 *@return 包围球。 */ __getset(0,__proto,'boundBox',function(){ this._updateCollider(); return this._transformOrientedBoundBox; }); /** *设置盒子碰撞器长宽高的一半。 *@param 长宽高的一半。 */ /** *获取盒子碰撞器长宽高的一半。 *@return 长宽高的一半。 */ __getset(0,__proto,'size',function(){ return this._size; },function(value){ this._size=value; this._needUpdate=true; }); __static(BoxCollider, ['_deviationV3',function(){return this._deviationV3=new Vector3();},'_obbCenterV3',function(){return this._obbCenterV3=new Vector3();} ]); return BoxCollider; })(Collider) /** *MeshCollider 类用于创建网格碰撞器。 */ //class laya.d3.component.physics.MeshCollider extends laya.d3.component.physics.Collider var MeshCollider=(function(_super){ function MeshCollider(){ /**@private */ this._transformBoundingBox=null; /**@private */ this._mesh=null; MeshCollider.__super.call(this); this._transformBoundingBox=new BoundBox(new Vector3(),new Vector3()); this._needUpdate=false; } __class(MeshCollider,'laya.d3.component.physics.MeshCollider',_super); var __proto=MeshCollider.prototype; /** *@private */ __proto._updateBoundBoxCollider=function(){ if (this._needUpdate){ var worldMat=(this._owner).transform.worldMatrix; var corners=this._mesh.boundingBoxCorners; for (var i=0;i < 8;i++) Vector3.transformCoordinate(corners[i],worldMat,MeshCollider._tempBoundBoxCorners[i]); BoundBox.createfromPoints(MeshCollider._tempBoundBoxCorners,this._transformBoundingBox); this._needUpdate=false; } } /** *@private */ __proto._raycastMesh=function(ray,sprite3D,outHitInfo,maxDistance){ (maxDistance===void 0)&& (maxDistance=1.79e+308); var worldMatrix=sprite3D.transform.worldMatrix; var invertWorldMatrix=MeshCollider._tempMatrix4x40; worldMatrix.invert(invertWorldMatrix); var rayOrigin=ray.origin; var rayDirection=ray.direction; var transformRay=MeshCollider._tempRay0; Vector3.transformCoordinate(rayOrigin,invertWorldMatrix,transformRay.origin); Vector3.TransformNormal(rayDirection,invertWorldMatrix,transformRay.direction); var curMinDistance=Number.MAX_VALUE; for (var i=0,n=this._mesh.getRenderElementsCount();i < n;i++){ var renderObj=this._mesh.getRenderElement(i); var vertexBuffer=renderObj._getVertexBuffer(0); var vertexDatas=vertexBuffer.getData(); var indexDatas=renderObj._getIndexBuffer().getData(); var elementRaycastHit=MeshCollider._tempRaycastHit; var isHit=Picker.rayIntersectsPositionsAndIndices(transformRay,vertexDatas,vertexBuffer.vertexDeclaration,indexDatas,elementRaycastHit); if (isHit){ Vector3.transformCoordinate(elementRaycastHit.position,worldMatrix,elementRaycastHit.position); var rayOriToPos=MeshCollider._tempVector30; Vector3.subtract(rayOrigin,elementRaycastHit.position,rayOriToPos); var distance=Vector3.scalarLength(rayOriToPos); if ((distance < maxDistance)&& (distance < curMinDistance)){ elementRaycastHit.distance=distance; elementRaycastHit.sprite3D=sprite3D; var trianglePositions=elementRaycastHit.trianglePositions; Vector3.transformCoordinate(trianglePositions[0],worldMatrix,trianglePositions[0]); Vector3.transformCoordinate(trianglePositions[1],worldMatrix,trianglePositions[1]); Vector3.transformCoordinate(trianglePositions[2],worldMatrix,trianglePositions[2]); var triangleNormals=elementRaycastHit.triangleNormals; Vector3.transformCoordinate(triangleNormals[0],worldMatrix,triangleNormals[0]); Vector3.transformCoordinate(triangleNormals[1],worldMatrix,triangleNormals[1]); Vector3.transformCoordinate(triangleNormals[2],worldMatrix,triangleNormals[2]); curMinDistance=distance; elementRaycastHit.cloneTo(outHitInfo); return true; } return false; } } return false; } /** *@private */ __proto._onWorldMatrixChanged=function(){ this._needUpdate=true; } /** *@inheritDoc */ __proto._initialize=function(owner){ laya.d3.component.Component3D.prototype._initialize.call(this,owner); (owner).transform.on(/*laya.events.Event.WORLDMATRIX_NEEDCHANGE*/"worldmatrixneedchanged",this,this._onWorldMatrixChanged); this._needUpdate=true; } /** *@inheritDoc */ __proto._getType=function(){ return 2; } /** *@inheritDoc */ __proto._collisonTo=function(other){ var i=0,n=0; var positions=this.mesh._positions; switch (other._getType()){ case 0:; var otherSphere=other; if (Collision.sphereContainsBox(otherSphere.boundSphere,this._boundBox)!==/*laya.d3.math.ContainmentType.Disjoint*/0){ for (i=0,n=positions.length;i < n;i++){ if (Collision.sphereContainsPoint(otherSphere.boundSphere,positions[i])===/*laya.d3.math.ContainmentType.Contains*/1) return true } return false; }else { return false; } break ; case 1:; var otherBox=other; if (otherBox.boundBox.containsBoundBox(this._boundBox)!==/*laya.d3.math.ContainmentType.Disjoint*/0){ for (i=0,n=positions.length;i < n;i++){ if (otherBox.boundBox.containsPoint(positions[i])===/*laya.d3.math.ContainmentType.Contains*/1) return true } return false; break ; }else { return false; } case 2:; var otherMesh=other; if (Collision.intersectsBoxAndBox(otherMesh._boundBox,this._boundBox)!==/*laya.d3.math.ContainmentType.Contains*/1){ return true; }else { return false; } throw new Error("MeshCollider:unknown collider type."); break ; default : throw new Error("MeshCollider:unknown collider type."); } } /** *@inheritDoc */ __proto._cloneTo=function(dest){ var destCollider=dest; destCollider.mesh=this._mesh; } /** *@inheritDoc */ __proto.raycast=function(ray,hitInfo,maxDistance){ (maxDistance===void 0)&& (maxDistance=1.79e+308); if (this._mesh==null || !this._mesh.loaded) return false; var distance=Collision.intersectsRayAndBoxRD(ray,this._boundBox); if (distance!==-1 && distance <=maxDistance && this._raycastMesh(ray,this._owner,hitInfo,maxDistance)){ return true; }else { hitInfo.distance=-1; hitInfo.sprite3D=null; return false; } } /** *@private 只读,不允许修改。 */ __getset(0,__proto,'_boundBox',function(){ this._updateBoundBoxCollider(); return this._transformBoundingBox; }); /** *设置碰撞器网格。 *@param value 碰撞其网格。 */ /** *获取碰撞器网格。 *@return 碰撞其网格。 */ __getset(0,__proto,'mesh',function(){ return this._mesh; },function(value){ this._mesh=value; }); __static(MeshCollider, ['_tempRay0',function(){return this._tempRay0=new Ray(new Vector3(),new Vector3());},'_tempVector30',function(){return this._tempVector30=new Vector3();},'_tempMatrix4x40',function(){return this._tempMatrix4x40=new Matrix4x4();},'_tempRaycastHit',function(){return this._tempRaycastHit=new RaycastHit();},'_tempBoundBoxCorners',function(){return this._tempBoundBoxCorners=/*new vector.<>*/[new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3(),new Vector3()];} ]); return MeshCollider; })(Collider) /** *SphereCollider 类用于创建球碰撞器。 */ //class laya.d3.component.physics.SphereCollider extends laya.d3.component.physics.Collider var SphereCollider=(function(_super){ function SphereCollider(){ /**@private */ this._originalBoundSphere=null; /**@private */ this._transformBoundSphere=null; SphereCollider.__super.call(this); this._needUpdate=false; } __class(SphereCollider,'laya.d3.component.physics.SphereCollider',_super); var __proto=SphereCollider.prototype; /** *@private */ __proto._updateCollider=function(){ if (this._needUpdate){ var maxScale=NaN; var transform=(this._owner).transform; var scale=transform.scale; if (scale.x >=scale.y && scale.x >=scale.z) maxScale=scale.x; else maxScale=scale.y >=scale.z ? scale.y :scale.z; Vector3.transformCoordinate(this._originalBoundSphere.center,transform.worldMatrix,this._transformBoundSphere.center); this._transformBoundSphere.radius=this._originalBoundSphere.radius *maxScale; this._needUpdate=false; } } /** *@private */ __proto._onWorldMatrixChanged=function(){ this._needUpdate=true; for (var k in this._runtimeCollisonMap){ this._runtimeCollisonTestMap[k]=true; this._runtimeCollisonMap[k]._runtimeCollisonTestMap[this.id]=true; } } /** *@inheritDoc */ __proto._initialize=function(owner){ laya.d3.component.Component3D.prototype._initialize.call(this,owner); this._originalBoundSphere=new BoundSphere(new Vector3(0,0,0),0.5); this._transformBoundSphere=new BoundSphere(new Vector3(0,0,0),0.5); (owner).transform.on(/*laya.events.Event.WORLDMATRIX_NEEDCHANGE*/"worldmatrixneedchanged",this,this._onWorldMatrixChanged); this._needUpdate=true; } /** *@inheritDoc */ __proto._getType=function(){ return 0; } /** *@inheritDoc */ __proto._collisonTo=function(other){ switch (other._getType()){ case 0: return Collision.sphereContainsSphere(this.boundSphere,(other).boundSphere)!==/*laya.d3.math.ContainmentType.Disjoint*/0; break ; case 1: return (other).boundBox.containsSphere(this.boundSphere)!==/*laya.d3.math.ContainmentType.Disjoint*/0; break ; case 2:; var meshCollider=other; if (Collision.sphereContainsBox(this.boundSphere,meshCollider._boundBox)!==/*laya.d3.math.ContainmentType.Disjoint*/0){ var positions=meshCollider.mesh._positions; for (var i=0,n=positions.length;i < n;i++){ if (Collision.sphereContainsPoint(this.boundSphere,positions[i])===/*laya.d3.math.ContainmentType.Contains*/1) return true } return false; }else { return false; } break ; default : throw new Error("SphereCollider:unknown collider type."); } } /** *@inheritDoc */ __proto._cloneTo=function(dest){ var destCollider=dest; destCollider.radius=this.radius; var destCenter=destCollider.center; this.center.cloneTo(destCenter); destCollider.center=destCenter; } /** *@inheritDoc */ __proto.raycast=function(ray,hitInfo,maxDistance){ (maxDistance===void 0)&& (maxDistance=1.79e+308); this._updateCollider(); var distance=this._transformBoundSphere.intersectsRayPoint(ray,hitInfo.position); if (distance!==-1 && distance <=maxDistance){ hitInfo.distance=distance; hitInfo.sprite3D=this._owner; return true; }else { hitInfo.distance=-1; hitInfo.sprite3D=null; return false; } } /** *设置中心点。 *@param value 中心点。 */ /** *获取中心点。 *@return 中心点。 */ __getset(0,__proto,'center',function(){ return this._originalBoundSphere.center; },function(value){ this._originalBoundSphere.center=value; }); /** *设置半径。 *@param value 半径。 */ /** *获取半径。 *@return 半径。 */ __getset(0,__proto,'radius',function(){ return this._originalBoundSphere.radius; },function(value){ this._originalBoundSphere.radius=value; }); /** *获取包围球,只读,不允许修改。 *@return 包围球。 */ __getset(0,__proto,'boundSphere',function(){ this._updateCollider(); return this._transformBoundSphere; }); return SphereCollider; })(Collider) //class laya.d3.resource.DataTexture2D extends laya.d3.resource.BaseTexture var DataTexture2D=(function(_super){ function DataTexture2D(){ this.simLodInfo=null; /**@private 文件路径全名。*/ this._src=null; /**@private Imagedata */ this._buffer=null; this._mipmaps=null; /**@private 异步加载锁*/ this._recreateLock=false; /**@private 异步加载完成后是否需要释放(有可能在恢复过程中,再次被释放,用此变量做标记)*/ this._needReleaseAgain=false; DataTexture2D.__super.call(this); this._type=/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1; } __class(DataTexture2D,'laya.d3.resource.DataTexture2D',_super); var __proto=DataTexture2D.prototype; __proto.genDebugMipmaps=function(){ var ret=[]; ret.push(new Uint8Array((new Uint32Array(512 *256)).fill(0xff0000ff).buffer)); ret.push(new Uint8Array((new Uint32Array(256 *128)).fill(0xff0080ff).buffer)); ret.push(new Uint8Array((new Uint32Array(128 *64)).fill(0xff00ffff).buffer)); ret.push(new Uint8Array((new Uint32Array(64 *32)).fill(0xff00ff00).buffer)); ret.push(new Uint8Array((new Uint32Array(32 *16)).fill(0xff804000).buffer)); ret.push(new Uint8Array((new Uint32Array(16 *8)).fill(0xffff0000).buffer)); ret.push(new Uint8Array((new Uint32Array(8 *4)).fill(0xffff0080).buffer)); ret.push(new Uint8Array((new Uint32Array(4 *2)).fill(0x0).buffer)); ret.push(new Uint8Array((new Uint32Array(2 *1)).fill(0xff808080).buffer)); ret.push(new Uint8Array((new Uint32Array(1 *1)).fill(0xffffffff).buffer)); return ret; } /** *@private */ __proto._onTextureLoaded=function(buff){} /** *@private */ __proto._createWebGlTexture=function(){ if (!this._buffer && !this._mipmaps) throw "create GLTextur err:no data"; var gl=WebGL.mainContext; gl.getExtension("EXT_shader_texture_lod"); var glTexture=this._source=gl.createTexture(); var w=this._width; var h=this._height; var preTarget=WebGLContext.curBindTexTarget; var preTexture=WebGLContext.curBindTexValue; WebGLContext.bindTexture(gl,this._type,glTexture); if (this._mipmaps){ if (laya.d3.resource.DataTexture2D.lodasatlas){ var infoi=0; gl.texImage2D(this._type,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,this._width,this._height,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,null); for (var i=0;i < this._mipmaps.length;i++){ if (this._mipmaps[i].byteLength !=cw *ch *4){ throw "mipmap size error level:"+i; } gl.texSubImage2D(this._type,0,DataTexture2D.simLodRect[infoi++],DataTexture2D.simLodRect[infoi++],DataTexture2D.simLodRect[infoi++],DataTexture2D.simLodRect[infoi++],/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,new Uint8Array(this._mipmaps[i])); } this.minFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601; this.magFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601; }else { var cw=this._width; var ch=this._height; infoi=0; gl.texImage2D(this._type,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,this._width,this._height,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,null); for (i=0;i < this._mipmaps.length;i++){ if (this._mipmaps[i].byteLength !=cw *ch *4){ throw "mipmap size error level:"+i; } gl.texImage2D(this._type,i,/*laya.webgl.WebGLContext.RGBA*/0x1908,cw,ch,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,new Uint8Array(this._mipmaps[i])); cw /=2; ch /=2; if (cw < 1)cw=1; if (ch < 1)ch=1; this.minFifter=/*laya.webgl.WebGLContext.LINEAR_MIPMAP_LINEAR*/0x2703; this.magFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601; } } this.mipmap=false; }else { gl.texImage2D(this._type,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,w,h,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,new Uint8Array(this._buffer)); }; var minFifter=this._minFifter; var magFifter=this._magFifter; var repeat=this._repeat ? /*laya.webgl.WebGLContext.REPEAT*/0x2901 :/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F; var isPot=Arith.isPOT(w,h); if (isPot){ if (this._mipmap || this._mipmaps) (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR_MIPMAP_LINEAR*/0x2703); else (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (magFifter!==-1)|| (magFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MIN_FILTER*/0x2801,minFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MAG_FILTER*/0x2800,magFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,repeat); if (this._mipmaps) gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); else gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,repeat); this._mipmap && gl.generateMipmap(this._type); }else { throw "data texture must be POT"; } (preTarget && preTexture)&& (WebGLContext.bindTexture(gl,preTarget,preTexture)); if (this.src && this.src.length > 0) this._buffer=null; if (isPot) this.memorySize=w *h *4 *(1+1 / 3); else this.memorySize=w *h *4; this._recreateLock=false; } /** *重新创建资源,如果异步创建中被强制释放再创建,则需等待释放完成后再重新加载创建。 */ __proto.recreateResource=function(){ if (!this._buffer && (this._src==null || this._src==="")) return; this._needReleaseAgain=false; if (!this._buffer && !this._mipmaps){ this._recreateLock=true; var _this=this; }else { if (this._recreateLock){ return; } this._createWebGlTexture(); this.completeCreate(); } } /** *@private */ __proto.onAsynLoaded=function(url,data,params){ var imgdata; if (params){ imgdata=params[0].call(this,data); } if (imgdata){ this._width=imgdata.width; this._height=imgdata.height; this._buffer=imgdata.data; } this._src=url; this._size=new Size(this._width,this._height); if (this._conchTexture){ alert('怎么给runtime传递datatexture数据'); }else this.activeResource(); this._endLoaded(); } /** *返回图片像素。 *@return 图片像素。 */ __proto.getPixels=function(){ return new Uint8Array(this._buffer); } /** *销毁资源。 */ __proto.disposeResource=function(){ if (this._recreateLock){ this._needReleaseAgain=true; } if (this._source){ WebGL.mainContext.deleteTexture(this._source); this._source=null; this._buffer=null; this.memorySize=0; } } /** *获取文件路径全名。 */ __getset(0,__proto,'src',function(){ return this._src; }); DataTexture2D.create=function(data,w,h,magfilter,minfilter,mipmap){ (magfilter===void 0)&& (magfilter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (minfilter===void 0)&& (minfilter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (mipmap===void 0)&& (mipmap=true); if (!data || data.byteLength < (w *h *4)) throw 'DataTexture2D create error'; var ret=new DataTexture2D(); ret._buffer=data; ret._width=w; ret._height=h; ret._mipmap=mipmap; ret._magFifter=magfilter; ret._minFifter=minfilter; ret._size=new Size(ret._width,ret._height); if (ret._conchTexture){ alert('怎么给runtime传递datatexture数据'); }else ret.activeResource(); return ret; } DataTexture2D.load=function(url,w,h,magfilter,minfilter){ (w===void 0)&& (w=0); (h===void 0)&& (h=0); (magfilter===void 0)&& (magfilter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (minfilter===void 0)&& (minfilter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); var extension=Utils.getFileExtension(url); if (extension==='mipmaps'){ var ret=Laya.loader.create(url,null,null,DataTexture2D,[function(data){ this._mipmaps=[]; var szinfo=new Uint32Array(data); this._width=szinfo[0]; var validw=512; if (laya.d3.resource.DataTexture2D.lodasatlas){ this._width *=2; validw=1024; } if (this._width !=validw){ console.error("现在只支持512x256的环境贴图。当前的是"+szinfo[0]); throw "现在只支持512x256的环境贴图。当前的是"+szinfo[0]; } this._height=szinfo[1]; var curw=laya.d3.resource.DataTexture2D.lodasatlas ? this._width / 2 :this._width; var curh=this._height; var cursz=8; while (true){ var curbufsz=curw *curh *4; if (cursz+curbufsz > data.byteLength){ throw "load mipmaps data size error "; }; var tbuf=new Uint8Array(data,cursz,curbufsz); this._mipmaps.push(tbuf); cursz+=curbufsz; if (curw==1 && curh==1){ break ; } curw /=2; curh /=2; if (curw < 1)curw=1; if (curh < 1)curh=1; } return null; }]); if (laya.d3.resource.DataTexture2D.lodasatlas){ ret.simLodInfo=new Float32Array(40); for (var i=0;i < ret.simLodInfo.length;){ ret.simLodInfo[i]=(DataTexture2D.simLodRect[i]+0.5)/ 1024; i++; ret.simLodInfo[i]=(DataTexture2D.simLodRect[i]+0.5)/ 256; i++; ret.simLodInfo[i]=Math.max(DataTexture2D.simLodRect[i]-1,0.1)/ 1024; i++; ret.simLodInfo[i]=Math.max(DataTexture2D.simLodRect[i]-1.5,0.1)/ 256; i++; } } return ret; }else if (typeof(w)=='number'){ return Laya.loader.create(url,null,null,DataTexture2D,[function(data){ this._width=w; this._height=h; this._buffer=data; return null; }]); }else if (typeof(w)=='function'){ return Laya.loader.create(url,null,null,DataTexture2D,[w]); }else { throw new Error("unknown params."); } } DataTexture2D.lodasatlas=false; __static(DataTexture2D, ['simLodRect',function(){return this.simLodRect=new Uint32Array([ 0,0,512,256, 512,0,256,128, 512+256,0,128,64, 512+256+128,0,64,32, 512+256+128+64,0,32,16, 512+256+128+64+32,0,16,8, 512+256+128+64+32+16,0,8,4, 512+256+128+64+32+16+8,0,4,2, 512+256+128+64+32+16+8+4,0,2,1, 512+256+128+64+32+16+8+4+2,0,1,1]);} ]); return DataTexture2D; })(BaseTexture) /** *@private *PrimitiveMesh 类用于创建基本网格的父类。 */ //class laya.d3.resource.models.PrimitiveMesh extends laya.d3.resource.models.BaseMesh var PrimitiveMesh=(function(_super){ function PrimitiveMesh(){ this._numberVertices=0; this._numberIndices=0; this._vertexBuffer=null; this._indexBuffer=null; PrimitiveMesh.__super.call(this); } __class(PrimitiveMesh,'laya.d3.resource.models.PrimitiveMesh',_super); var __proto=PrimitiveMesh.prototype; Laya.imps(__proto,{"laya.d3.core.render.IRenderable":true}) __proto._getVertexBuffer=function(index){ (index===void 0)&& (index=0); if (index===0) return this._vertexBuffer; else return null; } __proto._getVertexBuffers=function(){ return null; } __proto._getIndexBuffer=function(){ return this._indexBuffer; } /** *获取网格顶点 *@return 网格顶点。 */ __proto._getPositions=function(){ var vertices=[]; var positionElement; var vertexElements=this._vertexBuffer.vertexDeclaration.getVertexElements(); var j=0; for (j=0;j < vertexElements.length;j++){ var vertexElement=vertexElements[j]; if (vertexElement.elementFormat===/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3" && vertexElement.elementUsage===/*laya.d3.graphics.VertexElementUsage.POSITION0*/0){ positionElement=vertexElement; break ; } }; var verticesData=this._vertexBuffer.getData(); for (j=0;j < verticesData.length;j+=this._vertexBuffer.vertexDeclaration.vertexStride / 4){ var ofset=j+positionElement.offset / 4; var position=new Vector3(verticesData[ofset+0],verticesData[ofset+1],verticesData[ofset+2]); vertices.push(position); } return vertices; } __proto.getRenderElement=function(index){ return this; } __proto.getRenderElementsCount=function(){ return 1; } __proto.disposeResource=function(){ (this._vertexBuffer)&& (this._vertexBuffer.destroy(),this._vertexBuffer=null); (this._indexBuffer)&& (this._indexBuffer.destroy(),this._indexBuffer=null); this.memorySize=0; } __proto._beforeRender=function(state){ this._vertexBuffer._bind(); this._indexBuffer._bind(); return true; } __proto._render=function(state){ WebGL.mainContext.drawElements(/*laya.webgl.WebGLContext.TRIANGLES*/0x0004,this._numberIndices,/*laya.webgl.WebGLContext.UNSIGNED_SHORT*/0x1403,0); Stat.drawCall++; Stat.trianglesFaces+=this._numberIndices / 3; } __getset(0,__proto,'_vertexBufferCount',function(){ return 1; }); __getset(0,__proto,'triangleCount',function(){ return this._indexBuffer.indexCount / 3; }); return PrimitiveMesh; })(BaseMesh) /** *Mesh 类用于创建文件网格数据模板。 */ //class laya.d3.resource.models.Mesh extends laya.d3.resource.models.BaseMesh var Mesh=(function(_super){ function Mesh(){ /**@private */ this._materials=null; /**@private */ this._subMeshes=null; /**@private */ this._vertexBuffers=null; /**@private */ this._indexBuffer=null; /**@private */ this._boneNames=null; /**@private */ this._inverseBindPoses=null; /**@private */ this._skinnedDatas=null; Mesh.__super.call(this); this._subMeshes=[]; this._materials=[]; this._vertexBuffers=[]; } __class(Mesh,'laya.d3.resource.models.Mesh',_super); var __proto=Mesh.prototype; /** *获取网格顶点,并产生数据 *@return 网格顶点。 */ __proto._getPositions=function(){ var vertices=[]; var i=0,j=0,vertexBuffer,positionElement,vertexElements,vertexElement,ofset=0,verticesData; if (this._vertexBuffers.length!==0){ var vertexBufferCount=this._vertexBuffers.length; for (i=0;i < vertexBufferCount;i++){ vertexBuffer=this._vertexBuffers[i]; vertexElements=vertexBuffer.vertexDeclaration.getVertexElements(); for (j=0;j < vertexElements.length;j++){ vertexElement=vertexElements[j]; if (vertexElement.elementFormat===/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3" && vertexElement.elementUsage===/*laya.d3.graphics.VertexElementUsage.POSITION0*/0){ positionElement=vertexElement; break ; } } verticesData=vertexBuffer.getData(); for (j=0;j < verticesData.length;j+=vertexBuffer.vertexDeclaration.vertexStride / 4){ ofset=j+positionElement.offset / 4; vertices.push(new Vector3(verticesData[ofset+0],verticesData[ofset+1],verticesData[ofset+2])); } } }else { var submesheCount=this._subMeshes.length; for (i=0;i < submesheCount;i++){ var subMesh=this._subMeshes[i]; vertexBuffer=subMesh._getVertexBuffer(); vertexElements=vertexBuffer.vertexDeclaration.getVertexElements(); for (j=0;j < vertexElements.length;j++){ vertexElement=vertexElements[j]; if (vertexElement.elementFormat===/*laya.d3.graphics.VertexElementFormat.Vector3*/"vector3" && vertexElement.elementUsage===/*laya.d3.graphics.VertexElementUsage.POSITION0*/0){ positionElement=vertexElement; break ; } } verticesData=vertexBuffer.getData(); for (j=0;j < verticesData.length;j+=vertexBuffer.vertexDeclaration.vertexStride / 4){ ofset=j+positionElement.offset / 4; vertices.push(new Vector3(verticesData[ofset+0],verticesData[ofset+1],verticesData[ofset+2])); } } } return vertices; } /** *添加子网格(开发者禁止修改)。 *@param subMesh 子网格。 */ __proto._setSubMeshes=function(subMeshes){ this._subMeshes=subMeshes this._subMeshCount=subMeshes.length; for (var i=0;i < this._subMeshCount;i++) subMeshes[i]._indexInMesh=i; this._positions=this._getPositions(); this._generateBoundingObject(); } /** *@private */ __proto.onAsynLoaded=function(url,data,params){ var bufferData=data[0]; var textureMap=data[1]; MeshReader.read(bufferData,this,this._materials,this._subMeshes,textureMap); this.completeCreate(); this._endLoaded(); } /** *获得子网格。 *@param index 子网格索引。 *@return 子网格。 */ __proto.getSubMesh=function(index){ return this._subMeshes[index]; } /** *获得子网格数量。 *@return 子网格数量。 */ __proto.getSubMeshCount=function(){ return this._subMeshes.length; } /** *@inheritDoc */ __proto.getRenderElementsCount=function(){ return this._subMeshes.length; } /** *@inheritDoc */ __proto.getRenderElement=function(index){ return this._subMeshes[index]; } /** *@inheritDoc */ __proto.disposeResource=function(){ for (var i=0;i < this._subMeshes.length;i++) this._subMeshes[i].dispose(); this._materials=null; this._subMeshes=null; this._vertexBuffers=null; this._indexBuffer=null; this._boneNames=null; this._inverseBindPoses=null; } /** *获取材质队列的浅拷贝。 *@return 材质队列的浅拷贝。 */ __getset(0,__proto,'materials',function(){ return this._materials.slice(); }); /** *获取网格的全局默认绑定动作逆矩阵。 *@return 网格的全局默认绑定动作逆矩阵。 */ __getset(0,__proto,'InverseAbsoluteBindPoses',function(){ return this._inverseBindPoses; }); Mesh.load=function(url){ return Laya.loader.create(url,null,null,Mesh); } return Mesh; })(BaseMesh) /** *RenderTarget 类用于创建渲染目标。 */ //class laya.d3.resource.RenderTexture extends laya.d3.resource.BaseTexture var RenderTexture=(function(_super){ function RenderTexture(width,height,surfaceFormat,surfaceType,depthStencilFormat,mipMap,repeat,minFifter,magFifter){ /**@private */ this._alreadyResolved=false; /**@private */ this._surfaceFormat=0; /**@private */ this._surfaceType=0; /**@private */ this._depthStencilFormat=0; /**@private */ this._frameBuffer=null; /**@private */ this._depthStencilBuffer=null; (surfaceFormat===void 0)&& (surfaceFormat=/*laya.webgl.WebGLContext.RGBA*/0x1908); (surfaceType===void 0)&& (surfaceType=/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401); (depthStencilFormat===void 0)&& (depthStencilFormat=/*laya.webgl.WebGLContext.DEPTH_COMPONENT16*/0x81A5); (mipMap===void 0)&& (mipMap=false); (repeat===void 0)&& (repeat=false); (minFifter===void 0)&& (minFifter=-1); (magFifter===void 0)&& (magFifter=-1); RenderTexture.__super.call(this); this._type=/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1; this._width=width; this._height=height; this._size=new Size(width,height); this._surfaceFormat=surfaceFormat; this._surfaceType=surfaceType; this._depthStencilFormat=depthStencilFormat; if (Render.isConchWebGL && this._depthStencilFormat===/*laya.webgl.WebGLContext.DEPTH_STENCIL*/0x84F9){ this._depthStencilFormat=/*laya.webgl.WebGLContext.DEPTH_COMPONENT16*/0x81A5; } this._mipmap=mipMap; this._repeat=repeat; this._minFifter=minFifter; this._magFifter=magFifter; this.activeResource(); this._alreadyResolved=true; } __class(RenderTexture,'laya.d3.resource.RenderTexture',_super); var __proto=RenderTexture.prototype; __proto.recreateResource=function(){ var gl=WebGL.mainContext; this._frameBuffer=gl.createFramebuffer(); this._source=gl.createTexture(); var preTarget=WebGLContext.curBindTexTarget; var preTexture=WebGLContext.curBindTexValue; WebGLContext.bindTexture(gl,this._type,this._source); gl.texImage2D(this._type,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,this._width,this._height,0,this._surfaceFormat,this._surfaceType,null); var minFifter=this._minFifter; var magFifter=this._magFifter; var repeat=this._repeat ? /*laya.webgl.WebGLContext.REPEAT*/0x2901 :/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F; var isPot=Arith.isPOT(this._width,this._height); if (isPot){ if (this._mipmap) (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR_MIPMAP_LINEAR*/0x2703); else (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (magFifter!==-1)|| (magFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MIN_FILTER*/0x2801,minFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MAG_FILTER*/0x2800,magFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,repeat); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,repeat); this._mipmap && gl.generateMipmap(this._type); }else { (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (magFifter!==-1)|| (magFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MIN_FILTER*/0x2801,minFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MAG_FILTER*/0x2800,magFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); } gl.bindFramebuffer(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40,this._frameBuffer); gl.framebufferTexture2D(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40,/*laya.webgl.WebGLContext.COLOR_ATTACHMENT0*/0x8CE0,/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1,this._source,0); if (this._depthStencilFormat){ this._depthStencilBuffer=gl.createRenderbuffer(); gl.bindRenderbuffer(/*laya.webgl.WebGLContext.RENDERBUFFER*/0x8D41,this._depthStencilBuffer); gl.renderbufferStorage(/*laya.webgl.WebGLContext.RENDERBUFFER*/0x8D41,this._depthStencilFormat,this._width,this._height); switch (this._depthStencilFormat){ case /*laya.webgl.WebGLContext.DEPTH_COMPONENT16*/0x81A5: gl.framebufferRenderbuffer(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40,/*laya.webgl.WebGLContext.DEPTH_ATTACHMENT*/0x8D00,/*laya.webgl.WebGLContext.RENDERBUFFER*/0x8D41,this._depthStencilBuffer); break ; case /*laya.webgl.WebGLContext.STENCIL_INDEX8*/0x8D48: gl.framebufferRenderbuffer(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40,/*laya.webgl.WebGLContext.STENCIL_ATTACHMENT*/0x8D20,/*laya.webgl.WebGLContext.RENDERBUFFER*/0x8D41,this._depthStencilBuffer); break ; case /*laya.webgl.WebGLContext.DEPTH_STENCIL*/0x84F9: gl.framebufferRenderbuffer(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40,/*laya.webgl.WebGLContext.DEPTH_STENCIL_ATTACHMENT*/0x821A,/*laya.webgl.WebGLContext.RENDERBUFFER*/0x8D41,this._depthStencilBuffer); break ; } } gl.bindFramebuffer(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40,null); (preTarget && preTexture)&& (WebGLContext.bindTexture(gl,preTarget,preTexture)); gl.bindRenderbuffer(/*laya.webgl.WebGLContext.RENDERBUFFER*/0x8D41,null); this.memorySize=this._width *this._height *4; this.completeCreate(); } /** *开始绑定。 */ __proto.start=function(){ WebGL.mainContext.bindFramebuffer(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40,this.frameBuffer); RenderTexture._currentRenderTarget=this; this._alreadyResolved=false; } /** *结束绑定。 */ __proto.end=function(){ WebGL.mainContext.bindFramebuffer(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40,null); RenderTexture._currentRenderTarget=null; this._alreadyResolved=true; } /** *获得像素数据。 *@param x X像素坐标。 *@param y Y像素坐标。 *@param width 宽度。 *@param height 高度。 *@return 像素数据。 */ __proto.getData=function(x,y,width,height){ var gl=WebGL.mainContext; gl.bindFramebuffer(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40,this._frameBuffer); var canRead=(gl.checkFramebufferStatus(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40)===/*laya.webgl.WebGLContext.FRAMEBUFFER_COMPLETE*/0x8CD5); if (!canRead){ gl.bindFramebuffer(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40,null); return null; }; var pixels=new Uint8Array(this._width *this._height *4); gl.readPixels(x,y,width,height,this._surfaceFormat,this._surfaceType,pixels); gl.bindFramebuffer(/*laya.webgl.WebGLContext.FRAMEBUFFER*/0x8D40,null); return pixels; } /** *销毁资源。 */ __proto.disposeResource=function(){ if (this._frameBuffer){ var gl=WebGL.mainContext; gl.deleteTexture(this._source); gl.deleteFramebuffer(this._frameBuffer); gl.deleteRenderbuffer(this._depthStencilBuffer); this._source=null; this._frameBuffer=null; this._depthStencilBuffer=null; this.memorySize=0; } } /** *获取表面格式。 *@return 表面格式。 */ __getset(0,__proto,'surfaceFormat',function(){ return this._surfaceFormat; }); /** *获取表面类型。 *@return 表面类型。 */ __getset(0,__proto,'surfaceType',function(){ return this._surfaceType; }); /** *获取深度格式。 *@return 深度格式。 */ __getset(0,__proto,'depthStencilFormat',function(){ return this._depthStencilFormat; }); /** *获取RenderTarget数据源,如果alreadyResolved等于false,则返回null。 *@return RenderTarget数据源。 */ __getset(0,__proto,'source',function(){ if (this._alreadyResolved) return Laya.superGet(BaseTexture,this,'source'); else return null; }); __getset(0,__proto,'depthStencilBuffer',function(){ return this._depthStencilBuffer; }); __getset(0,__proto,'frameBuffer',function(){ return this._frameBuffer; }); RenderTexture._currentRenderTarget=null; return RenderTexture; })(BaseTexture) /** *SolidColorTexture2D 二维纯色纹理。 */ //class laya.d3.resource.SolidColorTexture2D extends laya.d3.resource.BaseTexture var SolidColorTexture2D=(function(_super){ function SolidColorTexture2D(color){ /**@private */ this._color=null; /**@private */ this._pixels=null; SolidColorTexture2D.__super.call(this); this._type=/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1; this._width=1; this._height=1; this._size=new Size(this.width,this.height); this._color=color; this._pixels=new Uint8Array([color.x *255,color.y *255,color.z *255,color.w *255]); } __class(SolidColorTexture2D,'laya.d3.resource.SolidColorTexture2D',_super); var __proto=SolidColorTexture2D.prototype; /** *@private */ __proto._createWebGlTexture=function(){ var gl=WebGL.mainContext; var glTex=this._source=gl.createTexture(); var w=this._width; var h=this._height; var preTarget=WebGLContext.curBindTexTarget; var preTexture=WebGLContext.curBindTexValue; WebGLContext.bindTexture(gl,this._type,glTex); gl.texImage2D(this._type,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,w,h,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._pixels); var minFifter=this._minFifter; var magFifter=this._magFifter; var repeat=this._repeat ? /*laya.webgl.WebGLContext.REPEAT*/0x2901 :/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F; var isPot=Arith.isPOT(w,h); if (isPot){ if (this._mipmap) (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR_MIPMAP_LINEAR*/0x2703); else (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (magFifter!==-1)|| (magFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MIN_FILTER*/0x2801,minFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MAG_FILTER*/0x2800,magFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,repeat); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,repeat); this._mipmap && gl.generateMipmap(this._type); }else { (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (magFifter!==-1)|| (magFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MIN_FILTER*/0x2801,minFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MAG_FILTER*/0x2800,magFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); } (preTarget && preTexture)&& (WebGLContext.bindTexture(gl,preTarget,preTexture)); if (isPot) this.memorySize=w *h *4 *(1+1 / 3); else this.memorySize=w *h *4; } /** *重新创建资源,如果异步创建中被强制释放再创建,则需等待释放完成后再重新加载创建。 */ __proto.recreateResource=function(){ this._createWebGlTexture(); this.completeCreate(); } /** *销毁资源。 */ __proto.disposeResource=function(){ if (this._source){ WebGL.mainContext.deleteTexture(this._source); this._source=null; this.memorySize=0; } } __static(SolidColorTexture2D, ['magentaTexture',function(){return this.magentaTexture=new SolidColorTexture2D(new Vector4(1.0,0.0,1.0,1.0));},'grayTexture',function(){return this.grayTexture=new SolidColorTexture2D(new Vector4(0.5,0.5,0.5,1.0));} ]); return SolidColorTexture2D; })(BaseTexture) //class laya.d3.resource.SolidColorTextureCube extends laya.d3.resource.BaseTexture var SolidColorTextureCube=(function(_super){ function SolidColorTextureCube(color){ /**@private */ this._color=null; /**@private */ this._pixels=null; /**@private */ this._texCount=6; SolidColorTextureCube.__super.call(this); this._type=/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP*/0x8513; this._width=1; this._height=1; this._size=new Size(this.width,this.height); this._color=color; this._pixels=new Uint8Array([color.x *255,color.y *255,color.z *255,color.w *255]); } __class(SolidColorTextureCube,'laya.d3.resource.SolidColorTextureCube',_super); var __proto=SolidColorTextureCube.prototype; __proto._createWebGlTexture=function(){ var gl=WebGL.mainContext; var glTex=this._source=gl.createTexture(); var w=this._width; var h=this._height; var preTarget=WebGLContext.curBindTexTarget; var preTexture=WebGLContext.curBindTexValue; WebGLContext.bindTexture(gl,this._type,glTex); gl.texImage2D(/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP_POSITIVE_X*/0x8515,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,w,h,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._pixels); gl.texImage2D(/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP_NEGATIVE_X*/0x8516,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,w,h,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._pixels); gl.texImage2D(/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP_POSITIVE_Y*/0x8517,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,w,h,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._pixels); gl.texImage2D(/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP_NEGATIVE_Y*/0x8518,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,w,h,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._pixels); gl.texImage2D(/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP_POSITIVE_Z*/0x8519,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,w,h,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._pixels); gl.texImage2D(/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP_NEGATIVE_Z*/0x851A,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,w,h,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._pixels); var minFifter=this.minFifter; var magFifter=this.magFifter; var repeat=this._repeat ? /*laya.webgl.WebGLContext.REPEAT*/0x2901 :/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F; var isPOT=Arith.isPOT(w,h); if (isPOT){ if (this.mipmap) (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR_MIPMAP_LINEAR*/0x2703); else (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (magFifter!==-1)|| (magFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MIN_FILTER*/0x2801,minFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MAG_FILTER*/0x2800,magFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,repeat); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,repeat); this.mipmap && gl.generateMipmap(this._type); }else { (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (magFifter!==-1)|| (magFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MIN_FILTER*/0x2801,minFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MAG_FILTER*/0x2800,magFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); } (preTarget && preTexture)&& (WebGLContext.bindTexture(gl,preTarget,preTexture)); if (isPOT) this.memorySize=w *h *4 *(1+1 / 3)*this._texCount; else this.memorySize=w *h *4 *this._texCount; } __proto.recreateResource=function(){ this._createWebGlTexture(); this.completeCreate(); } //处理创建完成后相关操作 __proto.disposeResource=function(){ if (this._source){ WebGL.mainContext.deleteTexture(this._source); this._source=null; this.memorySize=0; } } __static(SolidColorTextureCube, ['magentaTexture',function(){return this.magentaTexture=new SolidColorTextureCube(new Vector4(1.0,0.0,1.0,1.0));},'grayTexture',function(){return this.grayTexture=new SolidColorTextureCube(new Vector4(0.5,0.5,0.5,1.0));} ]); return SolidColorTextureCube; })(BaseTexture) /** *Texture2D 二维纹理。 */ //class laya.d3.resource.Texture2D extends laya.d3.resource.BaseTexture var Texture2D=(function(_super){ function Texture2D(canRead,reapeat,format,mipmap){ /**@private */ this._canRead=false; /**@private HTML Image*/ this._image=null; /**@private */ this._pixels=null; (canRead===void 0)&& (canRead=false); (reapeat===void 0)&& (reapeat=true); (format===void 0)&& (format=/*laya.webgl.WebGLContext.RGBA*/0x1908); (mipmap===void 0)&& (mipmap=true); Texture2D.__super.call(this); this._type=/*laya.webgl.WebGLContext.TEXTURE_2D*/0x0DE1; this._repeat=reapeat; this._canRead=canRead; this._format=format; this._mipmap=mipmap; } __class(Texture2D,'laya.d3.resource.Texture2D',_super); var __proto=Texture2D.prototype; /** *@private */ __proto._createWebGlTexture=function(){ if (!this._image) throw "create GLTextur err:no data:"+this._image; var gl=WebGL.mainContext; var glTexture=this._source=gl.createTexture(); var w=this._width; var h=this._height; var preTarget=WebGLContext.curBindTexTarget; var preTexture=WebGLContext.curBindTexValue; WebGLContext.bindTexture(gl,this._type,glTexture); switch (this._format){ case /*laya.webgl.WebGLContext.RGB*/0x1907: case /*laya.webgl.WebGLContext.RGBA*/0x1908: if (this._canRead) gl.texImage2D(this._type,0,this._format,w,h,0,this._format,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._pixels); else gl.texImage2D(this._type,0,this._format,this._format,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._image); break ; case WebGL.compressEtc1.COMPRESSED_RGB_ETC1_WEBGL: gl.compressedTexImage2D(this._type,0,this._format,this._width,this._height,0,this._image); break ; }; var minFifter=this._minFifter; var magFifter=this._magFifter; var repeat=this._repeat ? /*laya.webgl.WebGLContext.REPEAT*/0x2901 :/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F; var wrapModeU=this._wrapModeU==0 ? /*laya.webgl.WebGLContext.REPEAT*/0x2901 :/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F; var wrapModeV=this._wrapModeV==0 ? /*laya.webgl.WebGLContext.REPEAT*/0x2901 :/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F; var isPot=Arith.isPOT(w,h); if (isPot){ if (this._mipmap) (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR_MIPMAP_LINEAR*/0x2703); else (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (magFifter!==-1)|| (magFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MIN_FILTER*/0x2801,minFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MAG_FILTER*/0x2800,magFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,repeat); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,repeat); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,wrapModeU); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,wrapModeV); this._mipmap && gl.generateMipmap(this._type); }else { (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (magFifter!==-1)|| (magFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MIN_FILTER*/0x2801,minFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MAG_FILTER*/0x2800,magFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); } (preTarget && preTexture)&& (WebGLContext.bindTexture(gl,preTarget,preTexture)); this._image.onload=null; this._image=null; if (isPot) this.memorySize=w *h *4 *(1+1 / 3); else this.memorySize=w *h *4; } /** *重新创建资源,如果异步创建中被强制释放再创建,则需等待释放完成后再重新加载创建。 */ __proto.recreateResource=function(){ this._createWebGlTexture(); this.completeCreate(); } /** *@private */ __proto.onAsynLoaded=function(url,data,params){ if (params){ var canRead=params[0]; (canRead!==undefined)&& (this._canRead=canRead); var repeat=params[1]; (repeat!==undefined)&& (this._repeat=repeat); var format=params[2]; (format!==undefined)&& (this._format=format); var mipmap=params[3]; (mipmap!==undefined)&& (this._mipmap=mipmap); var wrapModeU=params.wrapModeU; (wrapModeU!==undefined)&& (this._wrapModeU=wrapModeU); var wrapModeV=params.wrapModeV; (wrapModeV!==undefined)&& (this._wrapModeV=wrapModeV); } switch (this._format){ case /*laya.webgl.WebGLContext.RGB*/0x1907: case /*laya.webgl.WebGLContext.RGBA*/0x1908: this._image=data; var w=data.width; var h=data.height; this._width=w; this._height=h; this._size=new Size(w,h); if (this._canRead){ if (Render.isConchApp){ if (/*__JS__ */data instanceof window.HTMLElement){ this._pixels=new Uint8Array(data.getImageData(0,0,w,h)); } } else { Browser.canvas.size(w,h); Browser.canvas.clear(); Browser.context.drawImage(data,0,0,w,h); this._pixels=new Uint8Array(Browser.context.getImageData(0,0,w,h).data.buffer); } } break ; case WebGL.compressEtc1.COMPRESSED_RGB_ETC1_WEBGL:; var readData=new Byte(data); var magicNumber=readData.readUTFBytes(4); var version=readData.readUTFBytes(2); var dataType=readData.getInt16(); readData.endian=/*laya.utils.Byte.BIG_ENDIAN*/"bigEndian"; this._width=readData.getInt16(); this._height=readData.getInt16(); this._size=new Size(this._width,this._height); var originalWidth=readData.getInt16(); var originalHeight=readData.getInt16(); this._image=new Uint8Array(data,readData.pos); } this.recreateResource(); this._endLoaded(); } /** *返回图片像素。 *@return 图片像素。 */ __proto.getPixels=function(){ if (this._canRead) return this._pixels; else throw new Error("Texture2D: must set texture canRead is true."); } /** *销毁资源。 */ __proto.disposeResource=function(){ if (this._source){ WebGL.mainContext.deleteTexture(this._source); this._source=null; this._image=null; this.memorySize=0; } } /**@private */ __getset(0,__proto,'_src',function(){ return this.url; }); /**@private */ __getset(0,__proto,'src',function(){ return this.url; }); Texture2D.load=function(url){ return Laya.loader.create(url,null,null,Texture2D); } return Texture2D; })(BaseTexture) //class laya.d3.resource.TextureCube extends laya.d3.resource.BaseTexture var TextureCube=(function(_super){ function TextureCube(){ /**@private */ //this._images=null; TextureCube.__super.call(this); this._type=/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP*/0x8513; } __class(TextureCube,'laya.d3.resource.TextureCube',_super); var __proto=TextureCube.prototype; /** *@private */ __proto._onTextureLoaded=function(images){ this._images=images; var minWidth=2147483647; var minHeight=2147483647; for (var i=0;i < 6;i++){ var image=images[i]; minWidth=Math.min(minWidth,image.width); minHeight=Math.min(minHeight,image.height); } this._width=minWidth; this._height=minHeight; this._size=new Size(minWidth,minHeight); } __proto._createWebGlTexture=function(){ var texCount=6; var i=0; for (i=0;i < texCount;i++){ if (!this._images[i]){ throw "create GLTextur err:no data:"+this._images[i]; } }; var gl=WebGL.mainContext; var glTex=this._source=gl.createTexture(); var w=this._width; var h=this._height; var preTarget=WebGLContext.curBindTexTarget; var preTexture=WebGLContext.curBindTexValue; WebGLContext.bindTexture(gl,this._type,glTex); gl.texImage2D(/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP_POSITIVE_X*/0x8515,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._images[0]); gl.texImage2D(/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP_NEGATIVE_X*/0x8516,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._images[1]); gl.texImage2D(/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP_POSITIVE_Y*/0x8517,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._images[2]); gl.texImage2D(/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP_NEGATIVE_Y*/0x8518,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._images[3]); gl.texImage2D(/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP_POSITIVE_Z*/0x8519,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._images[4]); gl.texImage2D(/*laya.webgl.WebGLContext.TEXTURE_CUBE_MAP_NEGATIVE_Z*/0x851A,0,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,this._images[5]); var minFifter=this.minFifter; var magFifter=this.magFifter; var repeat=this._repeat ? /*laya.webgl.WebGLContext.REPEAT*/0x2901 :/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F; var isPOT=Arith.isPOT(w,h); if (isPOT){ if (this.mipmap) (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR_MIPMAP_LINEAR*/0x2703); else (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (magFifter!==-1)|| (magFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MIN_FILTER*/0x2801,minFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MAG_FILTER*/0x2800,magFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,repeat); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,repeat); this.mipmap && gl.generateMipmap(this._type); }else { (minFifter!==-1)|| (minFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); (magFifter!==-1)|| (magFifter=/*laya.webgl.WebGLContext.LINEAR*/0x2601); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MIN_FILTER*/0x2801,minFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_MAG_FILTER*/0x2800,magFifter); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_S*/0x2802,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); gl.texParameteri(this._type,/*laya.webgl.WebGLContext.TEXTURE_WRAP_T*/0x2803,/*laya.webgl.WebGLContext.CLAMP_TO_EDGE*/0x812F); } (preTarget && preTexture)&& (WebGLContext.bindTexture(gl,preTarget,preTexture)); for (i=0;i < 6;i++){ this._images[i].onload=null; this._images[i]=null; } if (isPOT) this.memorySize=w *h *4 *(1+1 / 3)*texCount; else this.memorySize=w *h *4 *texCount; } __proto.recreateResource=function(){ if (this._url==null) return; this._createWebGlTexture(); this.completeCreate(); } /** *@private */ __proto.onAsynLoaded=function(url,data,params){ this._onTextureLoaded(data); this.activeResource(); this._endLoaded(); } __proto.disposeResource=function(){ if (this._source){ WebGL.mainContext.deleteTexture(this._source); this._source=null; this.memorySize=0; } } /** *@inheritDoc */ __getset(0,__proto,'defaulteTexture',function(){ return SolidColorTextureCube.grayTexture; }); TextureCube.load=function(url){ return Laya.loader.create(url,null,null,TextureCube); } return TextureCube; })(BaseTexture) /** *SkinMeshRender 类用于蒙皮渲染器。 */ //class laya.d3.core.SkinnedMeshRender extends laya.d3.core.MeshRender var SkinnedMeshRender=(function(_super){ function SkinnedMeshRender(owner){ /**@private */ //this._cacheAvatar=null; /**@private */ //this._cacheMesh=null; /**@private */ //this._cacheAnimationNode=null; /**@private */ //this._cacheAnimationNodeIndex=null; /**@private */ //this._subSkinnedDatas=null; /**@private */ //this._localBoundingBoxCorners=null; /**@private */ //this._localBoundBox=null; /**@private */ //this._cacheAnimator=null; /**@private */ //this._rootIndex=0; /**@private */ //this._rootBone=null; /**用于裁剪的包围球。 */ //this.localBoundSphere=null; //.......................................兼容代码........................................ this._hasIndependentBound=true; SkinnedMeshRender.__super.call(this,owner); this._owner.transform.off(/*laya.events.Event.WORLDMATRIX_NEEDCHANGE*/"worldmatrixneedchanged",this,this._onWorldMatNeedChange); this._cacheAnimationNodeIndex=[]; this._cacheAnimationNode=[]; this._localBoundingBoxCorners=__newvec(8,null); (this._owner).meshFilter.on(/*laya.events.Event.MESH_CHANGED*/"meshchanged",this,this._$3__onMeshChanged); } __class(SkinnedMeshRender,'laya.d3.core.SkinnedMeshRender',_super); var __proto=SkinnedMeshRender.prototype; /** *@private */ __proto._getCacheAnimationNodes=function(){ var meshBoneNames=this._cacheMesh._boneNames; var binPoseCount=meshBoneNames.length; this._cacheAnimationNode.length=binPoseCount; this._cacheAnimationNodeIndex.length=binPoseCount; var avatarNodes=this._cacheAnimator._avatarNodes; var nodeMap=this._cacheAnimator._avatarNodeMap; for (var i=0;i < binPoseCount;i++){ var node=nodeMap[meshBoneNames[i]]; this._cacheAnimationNode[i]=node; this._cacheAnimationNodeIndex[i]=avatarNodes.indexOf(node); } } /** *@private */ __proto._offComputeBoneIndexToMeshEvent=function(avatar,mesh){ if (avatar.loaded){ if (!mesh.loaded) mesh.off(/*laya.events.Event.LOADED*/"loaded",this,this._getCacheAnimationNodes); }else { avatar.off(/*laya.events.Event.LOADED*/"loaded",this,this._computeBoneIndexToMeshWithAsyncMesh); } } /** *@private */ __proto._computeBoneIndexToMeshWithAsyncAvatar=function(){ if (this._cacheAvatar.loaded) this._computeBoneIndexToMeshWithAsyncMesh(); else this._cacheAvatar.once(/*laya.events.Event.LOADED*/"loaded",this,this._computeBoneIndexToMeshWithAsyncMesh); } /** *@private */ __proto._computeBoneIndexToMeshWithAsyncMesh=function(){ if (this._cacheMesh.loaded) this._getCacheAnimationNodes(); else this._cacheMesh.on(/*laya.events.Event.LOADED*/"loaded",this,this._getCacheAnimationNodes); } /** *@private */ __proto._$3__onMeshChanged=function(meshFilter,lastMesh,mesh){ this._cacheMesh=mesh; (lastMesh && !lastMesh.loaded)&& (mesh.off(/*laya.events.Event.LOADED*/"loaded",this,this._onMeshLoaded)); if (mesh.loaded) this._onMeshLoaded(mesh); else mesh.on(/*laya.events.Event.LOADED*/"loaded",this,this._onMeshLoaded); if (this._cacheAvatar){ (lastMesh)&& (this._offComputeBoneIndexToMeshEvent(this._cacheAvatar,lastMesh)); (mesh)&& (this._computeBoneIndexToMeshWithAsyncAvatar()); } } /** *@private */ __proto._onMeshLoaded=function(mesh){ var subMeshCount=mesh.subMeshCount; this._subSkinnedDatas=[]; this._subSkinnedDatas.length=subMeshCount; for (var i=0;i < subMeshCount;i++){ var subMeshDatas=this._subSkinnedDatas[i]=[]; var boneIndicesList=mesh.getSubMesh(i)._boneIndicesList; for (var j=0,m=boneIndicesList.length;j < m;j++) subMeshDatas[j]=new Float32Array(boneIndicesList[j].length *16); } } /** *@private */ __proto._setCacheAnimator=function(animator){ this._cacheAnimator=animator; (this._rootBone)&& (this._rootIndex=animator._avatarNodes.indexOf(animator._avatarNodeMap[this._rootBone])); } /** *@private */ __proto._setRootBone=function(name){ this._rootBone=name; (this._cacheAnimator)&& (this._rootIndex=this._cacheAnimator._avatarNodes.indexOf(this._cacheAnimator._avatarNodeMap[name])); } /** *@private */ __proto._setCacheAvatar=function(value){ if (this._cacheAvatar!==value){ if (this._cacheMesh){ (this._cacheAvatar)&& (this._offComputeBoneIndexToMeshEvent(this._cacheAvatar,this._cacheMesh)); this._cacheAvatar=value; if (value){ this._addShaderDefine(SkinnedMeshSprite3D.SHADERDEFINE_BONE); this._computeBoneIndexToMeshWithAsyncAvatar(); } }else { this._cacheAvatar=value; } } } /** *@inheritDoc */ __proto._calculateBoundingBox=function(){ if (this._hasIndependentBound){ if (this._cacheAnimator){ var ownerTrans=this._owner.transform; var ownWorMat=ownerTrans.worldMatrix; if (this._cacheAnimator._canCache){ var curAvatarAnimationDatas=this._cacheAnimator._curAvatarNodeDatas; Utils3D.matrix4x4MultiplyMFM((this._cacheAnimator.owner).transform.worldMatrix,curAvatarAnimationDatas[this._rootIndex],ownWorMat); }else { Utils3D.matrix4x4MultiplyMFM((this._cacheAnimator.owner).transform.worldMatrix,this._cacheAnimator._avatarNodeMap[this._rootBone].transform.getWorldMatrix(),ownWorMat); } ownerTrans.worldMatrix=ownWorMat; var rootBone=this._cacheAnimator._avatarNodeMap[this._rootBone]; if (rootBone==null || this._localBoundBox==null) this._boundingBox.toDefault(); else this._calculateBoundBoxByInitCorners(this._localBoundingBoxCorners); } }else { _super.prototype._calculateBoundingBox.call(this); } } /** *@inheritDoc */ __proto._calculateBoundingSphere=function(){ if (this._hasIndependentBound){ if (this._cacheAnimator){ var ownerTrans=this._owner.transform; var ownWorMat=ownerTrans.worldMatrix; if (this._cacheAnimator._canCache){ var curAvatarAnimationDatas=this._cacheAnimator._curAvatarNodeDatas; Utils3D.matrix4x4MultiplyMFM((this._cacheAnimator.owner).transform.worldMatrix,curAvatarAnimationDatas[this._rootIndex],ownWorMat); }else Utils3D.matrix4x4MultiplyMFM((this._cacheAnimator.owner).transform.worldMatrix,this._cacheAnimator._avatarNodeMap[this._rootBone].transform.getWorldMatrix(),ownWorMat); ownerTrans.worldMatrix=ownWorMat; var rootBone=this._cacheAnimator._avatarNodeMap[this._rootBone]; if (rootBone==null || this.localBoundSphere==null) this._boundingSphere.toDefault(); else this._calculateBoundingSphereByInitSphere(this.localBoundSphere); } }else { _super.prototype._calculateBoundingSphere.call(this); } } /** *@inheritDoc */ __proto._updateOctreeNode=function(){ var treeNode=this._treeNode; if (treeNode){ treeNode.updateObject(this); } } /** *@inheritDoc */ __proto._renderUpdate=function(projectionView){ var projViewWorld; var animator=this._cacheAnimator; var subMeshCount=this._cacheMesh.subMeshCount; var ownerTrans=this._owner.transform; if (animator){ var cache=animator._canCache; var curAvatarAnimationDatas=this._cacheAnimator._curAvatarNodeDatas; var aniOwner=animator.owner; this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.WORLDMATRIX*/0,aniOwner._transform.worldMatrix); projViewWorld=aniOwner.getProjectionViewWorldMatrix(projectionView); this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.MVPMATRIX*/1,projViewWorld); if (this._cacheMesh && this._cacheMesh.loaded && this._cacheAvatar && this._cacheAvatar.loaded){ var i=0,n=0; var inverseBindPoses=this._cacheMesh._inverseBindPoses; var skinnedDatas=this._cacheMesh._skinnedDatas; if (cache){ for (i=0,n=inverseBindPoses.length;i < n;i++) Utils3D._mulMatrixArray(curAvatarAnimationDatas[this._cacheAnimationNodeIndex[i]],inverseBindPoses[i],skinnedDatas,i *16); }else { for (i=0,n=inverseBindPoses.length;i < n;i++) Utils3D._mulMatrixArray(this._cacheAnimationNode[i].transform.getWorldMatrix(),inverseBindPoses[i],skinnedDatas,i *16); } for (i=0;i < subMeshCount;i++){ var boneIndicesList=this._cacheMesh.getSubMesh(i)._boneIndicesList; var boneIndicesCount=boneIndicesList.length; var subSkinnedDatas=this._subSkinnedDatas[i]; for (var j=0;j < boneIndicesCount;j++) SkinnedMeshRender._splitAnimationDatas(boneIndicesList[j],skinnedDatas,subSkinnedDatas[j]); (this._renderElements [i])._skinAnimationDatas=subSkinnedDatas; } } }else { this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.WORLDMATRIX*/0,ownerTrans.worldMatrix); projViewWorld=this._owner.getProjectionViewWorldMatrix(projectionView); this._setShaderValueMatrix4x4(/*laya.d3.core.Sprite3D.MVPMATRIX*/1,projViewWorld); } if (Laya3D.debugMode) this._renderRenderableBoundBox(); return true; } /** *设置包围球。 *@param value */ /** *获取包围球。 *@return 包围球。 */ __getset(0,__proto,'localBoundBox',function(){ return this._localBoundBox; },function(value){ this._localBoundBox=value; value.getCorners(this._localBoundingBoxCorners); }); /** *@inheritDoc */ __getset(0,__proto,'boundingSphere',function(){ this._calculateBoundingSphere(); return this._boundingSphere; }); /** *@inheritDoc */ __getset(0,__proto,'boundingBox',function(){ this._calculateBoundingBox(); return this._boundingBox; }); /** *@inheritDoc */ __getset(0,__proto,'boundingBoxCenter',function(){ var boundBox=this.boundingBox; Vector3.add(boundBox.min,boundBox.max,this._boundingBoxCenter); Vector3.scale(this._boundingBoxCenter,0.5,this._boundingBoxCenter); return this._boundingBoxCenter; }); SkinnedMeshRender._splitAnimationDatas=function(indices,bonesData,subAnimationDatas){ for (var i=0,n=indices.length,ii=0;i < n;i++){ var index=indices[i] << 4; for (var j=0;j < 16;j++,ii++) subAnimationDatas[ii]=bonesData[index+j]; } } return SkinnedMeshRender; })(MeshRender) /** *BaseCamera 类用于创建摄像机的父类。 */ //class laya.d3.core.BaseCamera extends laya.d3.core.Sprite3D var BaseCamera=(function(_super){ function BaseCamera(nearPlane,farPlane){ /**@private */ //this._tempVector3=null; /**@private 位置。*/ //this._position=null; /**@private 向上向量。*/ //this._up=null; /**@private 前向量。*/ //this._forward=null; /**@private 右向量。*/ //this._right=null; /**@private 渲染顺序。*/ //this._renderingOrder=0; /**@private 渲染目标尺寸。*/ //this._renderTargetSize=null; /**@private 近裁剪面。*/ //this._nearPlane=NaN; /**@private 远裁剪面。*/ //this._farPlane=NaN; /**@private 视野。*/ //this._fieldOfView=NaN; /**@private 正交投影的垂直尺寸。*/ //this._orthographicVerticalSize=NaN; /**@private 天空。*/ //this._sky=null; /**@private */ //this._orthographic=false; /**@private 渲染目标。*/ //this._renderTarget=null; /**@private 是否使用用户自定义投影矩阵,如果使用了用户投影矩阵,摄像机投影矩阵相关的参数改变则不改变投影矩阵的值,需调用ResetProjectionMatrix方法。*/ //this._useUserProjectionMatrix=false; /**@private 表明视口是否使用裁剪空间表达。*/ //this._viewportExpressedInClipSpace=false; /**清楚标记。*/ //this.clearFlag=0; /**摄像机的清除颜色。*/ //this.clearColor=null; /**可视遮罩图层。 */ //this.cullingMask=0; /**渲染时是否用遮挡剔除。 */ //this.useOcclusionCulling=false; BaseCamera.__super.call(this); (nearPlane===void 0)&& (nearPlane=0.3); (farPlane===void 0)&& (farPlane=1000); this._tempVector3=new Vector3(); this._position=new Vector3(); this._up=new Vector3(); this._forward=new Vector3(); this._right=new Vector3(); this._fieldOfView=60; this._useUserProjectionMatrix=false; this._orthographic=false; this._viewportExpressedInClipSpace=true; this._renderTargetSize=Size.fullScreen; this._orthographicVerticalSize=10; this.renderingOrder=0; this._nearPlane=nearPlane; this._farPlane=farPlane; this.cullingMask=2147483647; this.clearFlag=/*CLASS CONST:laya.d3.core.BaseCamera.CLEARFLAG_SOLIDCOLOR*/0; this.useOcclusionCulling=true; this._calculateProjectionMatrix(); Laya.stage.on(/*laya.events.Event.RESIZE*/"resize",this,this._onScreenSizeChanged); } __class(BaseCamera,'laya.d3.core.BaseCamera',_super); var __proto=BaseCamera.prototype; /** *通过RenderingOrder属性对摄像机机型排序。 */ __proto._sortCamerasByRenderingOrder=function(){ if (this._displayedInStage){ var cameraPool=this.scene._cameraPool; var n=cameraPool.length-1; for (var i=0;i < n;i++){ if (cameraPool[i].renderingOrder > cameraPool[n].renderingOrder){ var tempCamera=cameraPool[i]; cameraPool[i]=cameraPool[n]; cameraPool[n]=tempCamera; } } } } /** *@private */ __proto._calculateProjectionMatrix=function(){} /** *@private */ __proto._onScreenSizeChanged=function(){ this._calculateProjectionMatrix(); } /** *@private */ __proto._prepareCameraToRender=function(){ Layer._currentCameraCullingMask=this.cullingMask; var cameraSV=this._shaderValues; cameraSV.setValue(/*CLASS CONST:laya.d3.core.BaseCamera.CAMERAPOS*/0,this.transform.position.elements); cameraSV.setValue(/*CLASS CONST:laya.d3.core.BaseCamera.CAMERADIRECTION*/5,this.forward.elements); cameraSV.setValue(/*CLASS CONST:laya.d3.core.BaseCamera.CAMERAUP*/6,this.up.elements); } /** *@private */ __proto._prepareCameraViewProject=function(viewMatrix,projectMatrix){ var cameraSV=this._shaderValues; cameraSV.setValue(/*CLASS CONST:laya.d3.core.BaseCamera.VIEWMATRIX*/1,viewMatrix.elements); cameraSV.setValue(/*CLASS CONST:laya.d3.core.BaseCamera.PROJECTMATRIX*/2,projectMatrix.elements); } /** *@private */ __proto._renderCamera=function(gl,state,scene){} /** *增加可视图层。 *@param layer 图层。 */ __proto.addLayer=function(layer){ if (layer.number===29 || layer.number==30) return; this.cullingMask=this.cullingMask | layer.mask; } /** *移除可视图层。 *@param layer 图层。 */ __proto.removeLayer=function(layer){ if (layer.number===29 || layer.number==30) return; this.cullingMask=this.cullingMask & ~layer.mask; } /** *增加所有图层。 */ __proto.addAllLayers=function(){ this.cullingMask=2147483647; } /** *移除所有图层。 */ __proto.removeAllLayers=function(){ this.cullingMask=0 | Layer.getLayerByNumber(29).mask | Layer.getLayerByNumber(30).mask; } __proto.ResetProjectionMatrix=function(){ this._useUserProjectionMatrix=false; this._calculateProjectionMatrix(); } /** *向前移动。 *@param distance 移动距离。 */ __proto.moveForward=function(distance){ this._tempVector3.elements[0]=this._tempVector3.elements[1]=0; this._tempVector3.elements[2]=distance; this.transform.translate(this._tempVector3); } /** *向右移动。 *@param distance 移动距离。 */ __proto.moveRight=function(distance){ this._tempVector3.elements[1]=this._tempVector3.elements[2]=0; this._tempVector3.elements[0]=distance; this.transform.translate(this._tempVector3); } /** *向上移动。 *@param distance 移动距离。 */ __proto.moveVertical=function(distance){ this._tempVector3.elements[0]=this._tempVector3.elements[2]=0; this._tempVector3.elements[1]=distance; this.transform.translate(this._tempVector3,false); } //}// BoundingFrustumWorldSpace __proto._addSelfRenderObjects=function(){ var cameraPool=this.scene._cameraPool; var cmaeraCount=cameraPool.length; if (cmaeraCount > 0){ for (var i=cmaeraCount-1;i >=0;i--){ if (this.renderingOrder <=cameraPool[i].renderingOrder){ cameraPool.splice(i+1,0,this); break ; } } }else { cameraPool.push(this); if (this.scene.conchModel){ this.scene.conchModel.setCurrentCamera(this.conchModel); } } } __proto._clearSelfRenderObjects=function(){ var cameraPool=this.scene._cameraPool; cameraPool.splice(cameraPool.indexOf(this),1); } /** *@inheritDoc */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); (this._sky)&& (this._sky.destroy()); this.renderTarget=null; Laya.stage.off(/*laya.events.Event.RESIZE*/"resize",this,this._onScreenSizeChanged); _super.prototype.destroy.call(this,destroyChild); } /**设置天空。*/ /**获取天空。*/ __getset(0,__proto,'sky',function(){ return this._sky; },function(value){ this._sky=value; value._ownerCamera=this; }); /** *获取前向量。 *@return 前向量。 */ __getset(0,__proto,'forward',function(){ var worldMatrixe=this.transform.worldMatrix.elements; var forwarde=this._forward.elements; forwarde[0]=-worldMatrixe[8]; forwarde[1]=-worldMatrixe[9]; forwarde[2]=-worldMatrixe[10]; return this._forward; }); /**获取位置。*/ __getset(0,__proto,'position',function(){ var worldMatrixe=this.transform.worldMatrix.elements; var positione=this._position.elements; positione[0]=worldMatrixe[12]; positione[1]=worldMatrixe[13]; positione[2]=worldMatrixe[14]; return this._position; }); /** *设置渲染场景的渲染目标。 *@param value 渲染场景的渲染目标。 */ /** *获取渲染场景的渲染目标。 *@return 渲染场景的渲染目标。 */ __getset(0,__proto,'renderTarget',function(){ return this._renderTarget; },function(value){ this._renderTarget=value; if (value !=null) this._renderTargetSize=value.size; }); /** *获取上向量。 *@return 上向量。 */ __getset(0,__proto,'up',function(){ var worldMatrixe=this.transform.worldMatrix.elements; var upe=this._up.elements; upe[0]=worldMatrixe[4]; upe[1]=worldMatrixe[5]; upe[2]=worldMatrixe[6]; return this._up; }); /** *获取右向量。 *@return 右向量。 */ __getset(0,__proto,'right',function(){ var worldMatrixe=this.transform.worldMatrix.elements; var righte=this._right.elements; righte[0]=worldMatrixe[0]; righte[1]=worldMatrixe[1]; righte[2]=worldMatrixe[2]; return this._right; }); /** *设置渲染目标的尺寸 *@param value 渲染目标的尺寸。 */ /** *获取渲染目标的尺寸 *@return 渲染目标的尺寸。 */ __getset(0,__proto,'renderTargetSize',function(){ return this._renderTargetSize; },function(value){ if (this.renderTarget !=null && this._renderTargetSize !=value){} this._renderTargetSize=value; this._calculateProjectionMatrix(); }); /** *设置视野。 *@param value 视野。 */ /** *获取视野。 *@return 视野。 */ __getset(0,__proto,'fieldOfView',function(){ return this._fieldOfView; },function(value){ this._fieldOfView=value; this._calculateProjectionMatrix(); }); /** *设置近裁面。 *@param value 近裁面。 */ /** *获取近裁面。 *@return 近裁面。 */ __getset(0,__proto,'nearPlane',function(){ return this._nearPlane; },function(value){ this._nearPlane=value; this._calculateProjectionMatrix(); }); /** *设置远裁面。 *@param value 远裁面。 */ /** *获取远裁面。 *@return 远裁面。 */ __getset(0,__proto,'farPlane',function(){ return this._farPlane; },function(vaule){ this._farPlane=vaule; this._calculateProjectionMatrix(); }); /** *设置是否正交投影矩阵。 *@param 是否正交投影矩阵。 */ /** *获取是否正交投影矩阵。 *@return 是否正交投影矩阵。 */ __getset(0,__proto,'orthographic',function(){ return this._orthographic; },function(vaule){ this._orthographic=vaule; this._calculateProjectionMatrix(); }); /** *设置正交投影垂直矩阵尺寸。 *@param 正交投影垂直矩阵尺寸。 */ /** *获取正交投影垂直矩阵尺寸。 *@return 正交投影垂直矩阵尺寸。 */ __getset(0,__proto,'orthographicVerticalSize',function(){ return this._orthographicVerticalSize; },function(vaule){ this._orthographicVerticalSize=vaule; this._calculateProjectionMatrix(); }); __getset(0,__proto,'renderingOrder',function(){ return this._renderingOrder; },function(value){ this._renderingOrder=value; this._sortCamerasByRenderingOrder(); }); BaseCamera.CAMERAPOS=0; BaseCamera.VIEWMATRIX=1; BaseCamera.PROJECTMATRIX=2; BaseCamera.VPMATRIX=3; BaseCamera.VPMATRIX_NO_TRANSLATE=4; BaseCamera.CAMERADIRECTION=5; BaseCamera.CAMERAUP=6; BaseCamera.ENVIRONMENTDIFFUSE=7; BaseCamera.ENVIRONMENTSPECULAR=8; BaseCamera.SIMLODINFO=9; BaseCamera.DIFFUSEIRRADMATR=10; BaseCamera.DIFFUSEIRRADMATG=11; BaseCamera.DIFFUSEIRRADMATB=12; BaseCamera.HDREXPOSURE=13; BaseCamera.RENDERINGTYPE_DEFERREDLIGHTING="DEFERREDLIGHTING"; BaseCamera.RENDERINGTYPE_FORWARDRENDERING="FORWARDRENDERING"; BaseCamera.CLEARFLAG_SOLIDCOLOR=0; BaseCamera.CLEARFLAG_SKY=1; BaseCamera.CLEARFLAG_DEPTHONLY=2; BaseCamera.CLEARFLAG_NONE=3; __static(BaseCamera, ['_invertYScaleMatrix',function(){return this._invertYScaleMatrix=new Matrix4x4(1,0,0,0,0,-1,0,0,0,0,1,0,0,0,0,1);},'_invertYProjectionMatrix',function(){return this._invertYProjectionMatrix=new Matrix4x4();},'_invertYProjectionViewMatrix',function(){return this._invertYProjectionViewMatrix=new Matrix4x4();} ]); return BaseCamera; })(Sprite3D) /** *RenderableSprite3D 类用于可渲染3D精灵的父类,抽象类不允许实例。 */ //class laya.d3.core.RenderableSprite3D extends laya.d3.core.Sprite3D var RenderableSprite3D=(function(_super){ function RenderableSprite3D(name){ /**@private */ this._render=null; /**@private */ this._geometryFilter=null; RenderableSprite3D.__super.call(this,name) } __class(RenderableSprite3D,'laya.d3.core.RenderableSprite3D',_super); var __proto=RenderableSprite3D.prototype; /** *@private */ __proto._addToInitStaticBatchManager=function(){} /** *@inheritDoc */ __proto._setBelongScene=function(scene){ _super.prototype._setBelongScene.call(this,scene); scene._renderableSprite3Ds.push(this); this._render._applyLightMapParams(); } /** *@inheritDoc */ __proto._setUnBelongScene=function(){ var renderableSprite3Ds=this._scene._renderableSprite3Ds; var index=renderableSprite3Ds.indexOf(this); renderableSprite3Ds.splice(index,1); this._render._removeShaderDefine(laya.d3.core.RenderableSprite3D.SAHDERDEFINE_LIGHTMAP); _super.prototype._setUnBelongScene.call(this); } /** *@inheritDoc */ __proto._update=function(state){ state.owner=this; if (this._activeInHierarchy){ this._updateComponents(state); this._render._updateOctreeNode(); this._lateUpdateComponents(state); Stat.spriteCount++; this._childs.length && this._updateChilds(state); } } /** *@inheritDoc */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); _super.prototype.destroy.call(this,destroyChild); this._render._destroy(); this._render=null; } RenderableSprite3D.__init__=function(){ RenderableSprite3D.SHADERDEFINE_SCALEOFFSETLIGHTINGMAPUV=RenderableSprite3D.shaderDefines.registerDefine("SCALEOFFSETLIGHTINGMAPUV"); RenderableSprite3D.SAHDERDEFINE_LIGHTMAP=RenderableSprite3D.shaderDefines.registerDefine("LIGHTMAP"); } RenderableSprite3D.SHADERDEFINE_SCALEOFFSETLIGHTINGMAPUV=0x2; RenderableSprite3D.SAHDERDEFINE_LIGHTMAP=0x4; RenderableSprite3D.LIGHTMAPSCALEOFFSET=2; RenderableSprite3D.LIGHTMAP=3; __static(RenderableSprite3D, ['shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1();} ]); return RenderableSprite3D; })(Sprite3D) /** *LightSprite 类用于创建灯光的父类。 */ //class laya.d3.core.light.LightSprite extends laya.d3.core.Sprite3D var LightSprite=(function(_super){ function LightSprite(){ /**@private */ this._intensityColor=null; /**@private */ this._intensity=NaN; /**@private */ this._shadow=false; /**@private */ this._shadowFarPlane=0; /**@private */ this._shadowMapSize=0; /**@private */ this._shadowMapCount=0; /**@private */ this._shadowMapPCFType=0; /**@private */ this._parallelSplitShadowMap=null; /**@private */ this._lightmapBakedType=0; /**灯光颜色。 */ this.color=null; LightSprite.__super.call(this); this._intensity=1.0; this._intensityColor=new Vector3(); this.color=new Vector3(1.0,1.0,1.0); this._shadow=false; this._shadowFarPlane=8; this._shadowMapSize=512; this._shadowMapCount=1; this._shadowMapPCFType=0; this._lightmapBakedType=LightSprite.LIGHTMAPBAKEDTYPE_REALTIME; } __class(LightSprite,'laya.d3.core.light.LightSprite',_super); var __proto=LightSprite.prototype; /** *@inheritDoc */ __proto._parseCustomProps=function(rootNode,innerResouMap,customProps,nodeData){ var colorData=customProps.color; var colorE=this.color.elements; colorE[0]=colorData[0]; colorE[1]=colorData[1]; colorE[2]=colorData[2]; } /** *@inheritDoc */ __proto._addSelfRenderObjects=function(){ (this.lightmapBakedType!==LightSprite.LIGHTMAPBAKEDTYPE_BAKED)&& (this._scene._addLight(this)); } /** *@inheritDoc */ __proto._clearSelfRenderObjects=function(){ (this.lightmapBakedType!==LightSprite.LIGHTMAPBAKEDTYPE_BAKED)&& (this._scene._removeLight(this)); } /** *更新灯光相关渲染状态参数。 *@param state 渲染状态参数。 */ __proto._prepareToScene=function(state){ return false; } /** *设置灯光烘培类型。 */ /** *获取灯光烘培类型。 */ __getset(0,__proto,'lightmapBakedType',function(){ return this._lightmapBakedType; },function(value){ if (this._lightmapBakedType!==value){ this._lightmapBakedType=value; if (this._activeInHierarchy){ if (value!==LightSprite.LIGHTMAPBAKEDTYPE_BAKED) this._scene._addLight(this); else this._scene._removeLight(this); } } }); /** *设置阴影PCF类型。 *@param value PCF类型。 */ /** *获取阴影PCF类型。 *@return PCF类型。 */ __getset(0,__proto,'shadowPCFType',function(){ return this._shadowMapPCFType; },function(value){ this._shadowMapPCFType=value; (this._parallelSplitShadowMap)&& (this._parallelSplitShadowMap.setPCFType(value)); }); /** *设置灯光强度。 *@param value 灯光强度 */ /** *获取灯光强度。 *@return 灯光强度 */ __getset(0,__proto,'intensity',function(){ return this._intensity; },function(value){ this._intensity=value; }); /** *设置是否产生阴影。 *@param value 是否产生阴影。 */ /** *获取是否产生阴影。 *@return 是否产生阴影。 */ __getset(0,__proto,'shadow',function(){ return this._shadow; },function(value){ throw new Error("LightSprite: must override it."); }); /** *设置阴影最远范围。 *@param value 阴影最远范围。 */ /** *获取阴影最远范围。 *@return 阴影最远范围。 */ __getset(0,__proto,'shadowDistance',function(){ return this._shadowFarPlane; },function(value){ this._shadowFarPlane=value; (this._parallelSplitShadowMap)&& (this._parallelSplitShadowMap.setFarDistance(value)); }); /** *设置阴影分段数。 *@param value 阴影分段数。 */ /** *获取阴影分段数。 *@return 阴影分段数。 */ __getset(0,__proto,'shadowPSSMCount',function(){ return this._shadowMapCount; },function(value){ this._shadowMapCount=value; (this._parallelSplitShadowMap)&& (this._parallelSplitShadowMap.PSSMNum=value); }); /** *设置阴影贴图尺寸。 *@param value 阴影贴图尺寸。 */ /** *获取阴影贴图尺寸。 *@return 阴影贴图尺寸。 */ __getset(0,__proto,'shadowResolution',function(){ return this._shadowMapSize; },function(value){ this._shadowMapSize=value; (this._parallelSplitShadowMap)&& (this._parallelSplitShadowMap.setShadowMapTextureSize(value)); }); /** *设置灯光的漫反射颜色。 *@param value 灯光的漫反射颜色。 */ /** *获取灯光的漫反射颜色。 *@return 灯光的漫反射颜色。 */ __getset(0,__proto,'diffuseColor',function(){ console.log("LightSprite: discard property,please use color property instead."); return this.color; },function(value){ console.log("LightSprite: discard property,please use color property instead."); this.color=value; }); LightSprite.LIGHTMAPBAKEDTYPE_REALTIME=0; LightSprite.LIGHTMAPBAKEDTYPE_MIXED=1; LightSprite.LIGHTMAPBAKEDTYPE_BAKED=2; return LightSprite; })(Sprite3D) /** *Terrain 类用于创建地块。 */ //class laya.d3.terrain.Terrain extends laya.d3.core.Sprite3D var Terrain=(function(_super){ function Terrain(terrainRes){ this._terrainRes=null; this._lightmapScaleOffset=null; Terrain.__super.call(this); this._lightmapScaleOffset=new Vector4(1,1,0,0); if (terrainRes){ this._terrainRes=terrainRes; if (terrainRes.loaded) this.buildTerrain(terrainRes); else terrainRes.once(/*laya.events.Event.LOADED*/"loaded",this,this.buildTerrain); } } __class(Terrain,'laya.d3.terrain.Terrain',_super); var __proto=Terrain.prototype; /** *@inheritDoc */ __proto._parseCustomProps=function(rootNode,innerResouMap,customProps,json){ this.terrainRes=Loader.getRes(innerResouMap[customProps.dataPath]); var lightmapIndex=customProps.lightmapIndex; if (lightmapIndex !=null) this.setLightmapIndex(lightmapIndex); var lightmapScaleOffsetArray=customProps.lightmapScaleOffset; if (lightmapScaleOffsetArray) this.setLightmapScaleOffset(new Vector4(lightmapScaleOffsetArray[0],lightmapScaleOffsetArray[1],lightmapScaleOffsetArray[2],lightmapScaleOffsetArray[3])); } __proto.setLightmapIndex=function(value){ for (var i=0;i < this._childs.length;i++){ var terrainChunk=this._childs[i]; terrainChunk.terrainRender.lightmapIndex=value; } } __proto.setLightmapScaleOffset=function(value){ if (!value)return; value.cloneTo(this._lightmapScaleOffset); for (var i=0;i < this._childs.length;i++){ var terrainChunk=this._childs[i]; terrainChunk.terrainRender.lightmapScaleOffset=this._lightmapScaleOffset; } } __proto.disableLight=function(){ for (var i=0,n=this._childs.length;i < n;i++){ var terrainChunk=this._childs[i]; for (var j=0,m=terrainChunk._render.sharedMaterials.length;j < m;j++){ var terrainMaterial=terrainChunk._render.sharedMaterials [j]; terrainMaterial.disableLight(); } } } __proto.buildTerrain=function(terrainRes){ var chunkNumX=terrainRes._chunkNumX; var chunkNumZ=terrainRes._chunkNumZ; var heightData=terrainRes._heightData; var n=0; for (var i=0;i < chunkNumZ;i++){ for (var j=0;j < chunkNumX;j++){ var terrainChunk=new TerrainChunk(j,i,terrainRes._gridSize,heightData._terrainHeightData,heightData._width,heightData._height,terrainRes._cameraCoordinateInverse); var chunkInfo=terrainRes._chunkInfos[n++]; for (var k=0;k < chunkInfo.alphaMap.length;k++){ var nNum=chunkInfo.detailID[k].length; var sDetialTextureUrl1=(nNum > 0)? terrainRes._detailTextureInfos[chunkInfo.detailID[k][0]].diffuseTexture :null; var sDetialTextureUrl2=(nNum > 1)? terrainRes._detailTextureInfos[chunkInfo.detailID[k][1]].diffuseTexture :null; var sDetialTextureUrl3=(nNum > 2)? terrainRes._detailTextureInfos[chunkInfo.detailID[k][2]].diffuseTexture :null; var sDetialTextureUrl4=(nNum > 3)? terrainRes._detailTextureInfos[chunkInfo.detailID[k][3]].diffuseTexture :null; var detialScale1=(nNum > 0)? terrainRes._detailTextureInfos[chunkInfo.detailID[k][0]].scale :null; var detialScale2=(nNum > 1)? terrainRes._detailTextureInfos[chunkInfo.detailID[k][1]].scale :null; var detialScale3=(nNum > 2)? terrainRes._detailTextureInfos[chunkInfo.detailID[k][2]].scale :null; var detialScale4=(nNum > 3)? terrainRes._detailTextureInfos[chunkInfo.detailID[k][3]].scale :null; terrainChunk.buildRenderElementAndMaterial(nNum,chunkInfo.normalMap,chunkInfo.alphaMap[k],sDetialTextureUrl1,sDetialTextureUrl2,sDetialTextureUrl3,sDetialTextureUrl4,terrainRes._materialInfo.ambientColor,terrainRes._materialInfo.diffuseColor,terrainRes._materialInfo.specularColor,detialScale1 ? detialScale1.x :1,detialScale1 ? detialScale1.y :1,detialScale2 ? detialScale2.x :1,detialScale2 ? detialScale2.y :1,detialScale3 ? detialScale3.x :1,detialScale3 ? detialScale3.y :1,detialScale4 ? detialScale4.x :1,detialScale4 ? detialScale4.y :1); } terrainChunk.terrainRender.receiveShadow=true; terrainChunk.terrainRender.lightmapScaleOffset=this._lightmapScaleOffset; this.addChild(terrainChunk); } } } /** *获取地形X轴长度。 *@return 地形X轴长度。 */ __proto.width=function(){ return this._terrainRes._chunkNumX *TerrainLeaf.CHUNK_GRID_NUM *this._terrainRes._gridSize; } /** *获取地形Z轴长度。 *@return 地形Z轴长度。 */ __proto.depth=function(){ return this._terrainRes._chunkNumZ *TerrainLeaf.CHUNK_GRID_NUM *this._terrainRes._gridSize; } /** *获取地形高度。 *@param x X轴坐标。 *@param z Z轴坐标。 */ __proto.getHeightXZ=function(x,z){ if (!this._terrainRes || !this._terrainRes.loaded) return NaN; x-=this.transform.position.x; z-=this.transform.position.z; if (!Terrain.__VECTOR3__){ Terrain.__VECTOR3__=new Vector3(); } Terrain.__VECTOR3__.elements[0]=x; Terrain.__VECTOR3__.elements[1]=0; Terrain.__VECTOR3__.elements[2]=z; Vector3.transformV3ToV3(Terrain.__VECTOR3__,TerrainLeaf.__ADAPT_MATRIX_INV__,Terrain.__VECTOR3__); x=Terrain.__VECTOR3__.elements[0]; z=Terrain.__VECTOR3__.elements[2]; if (x < 0 || x > this.width()|| z < 0 || z > this.depth()) return NaN; var gridSize=this._terrainRes._gridSize; var nIndexX=parseInt(""+x / gridSize); var nIndexZ=parseInt(""+z / gridSize); var offsetX=x-nIndexX *gridSize; var offsetZ=z-nIndexZ *gridSize; var h1=NaN; var h2=NaN; var h3=NaN; var u=NaN; var v=NaN; var heightData=this._terrainRes._heightData; if (offsetX+offsetZ > gridSize){ h1=heightData._terrainHeightData[(nIndexZ+1-1)*heightData._width+nIndexX+1]; h2=heightData._terrainHeightData[(nIndexZ+1-1)*heightData._width+nIndexX]; h3=heightData._terrainHeightData[(nIndexZ-1)*heightData._width+nIndexX+1]; u=(gridSize-offsetX)/ gridSize; v=(gridSize-offsetZ)/ gridSize; return h1+(h2-h1)*u+(h3-h1)*v; }else { h1=heightData._terrainHeightData[Math.max(0.0,nIndexZ-1)*heightData._width+nIndexX]; h2=heightData._terrainHeightData[Math.min(heightData._width *heightData._height-1,(nIndexZ+1-1)*heightData._width+nIndexX)]; h3=heightData._terrainHeightData[Math.min(heightData._width *heightData._height-1,Math.max(0.0,nIndexZ-1)*heightData._width+nIndexX+1)]; u=offsetX / gridSize; v=offsetZ / gridSize; return h1+(h2-h1)*v+(h3-h1)*u; } } __getset(0,__proto,'terrainRes',null,function(value){ if (value){ this._terrainRes=value; if (value.loaded) this.buildTerrain(value); else value.once(/*laya.events.Event.LOADED*/"loaded",this,this.buildTerrain); } }); Terrain.load=function(url){ return Laya.loader.create(url,null,null,Terrain,null,1,false); } Terrain.RENDER_LINE_MODEL=false; Terrain.LOD_TOLERANCE_VALUE=4; Terrain.LOD_DISTANCE_FACTOR=2.0; Terrain.__VECTOR3__=null; return Terrain; })(Sprite3D) /** *Sphere 类用于创建方体。 */ //class laya.d3.resource.models.BoxMesh extends laya.d3.resource.models.PrimitiveMesh var BoxMesh=(function(_super){ function BoxMesh(long,width,height){ /**@private */ this._long=NaN; /**@private */ this._width=NaN; /**@private */ this._height=NaN; (long===void 0)&& (long=1); (width===void 0)&& (width=1); (height===void 0)&& (height=1); BoxMesh.__super.call(this); this._long=long; this._width=width; this._height=height; this.activeResource(); this._positions=this._getPositions(); this._generateBoundingObject(); } __class(BoxMesh,'laya.d3.resource.models.BoxMesh',_super); var __proto=BoxMesh.prototype; __proto.recreateResource=function(){ this._numberVertices=24; this._numberIndices=36; var vertexDeclaration=VertexPositionNormalTexture.vertexDeclaration; var vertexFloatStride=vertexDeclaration.vertexStride / 4; var halfLong=this._long / 2; var halfHeight=this._height / 2; var halfWidth=this._width / 2; var vertices=new Float32Array([ -halfLong,halfHeight,-halfWidth,0,1,0,0,0,halfLong,halfHeight,-halfWidth,0,1,0,1,0,halfLong,halfHeight,halfWidth,0,1,0,1,1,-halfLong,halfHeight,halfWidth,0,1,0,0,1, -halfLong,-halfHeight,-halfWidth,0,-1,0,0,1,halfLong,-halfHeight,-halfWidth,0,-1,0,1,1,halfLong,-halfHeight,halfWidth,0,-1,0,1,0,-halfLong,-halfHeight,halfWidth,0,-1,0,0,0, -halfLong,halfHeight,-halfWidth,-1,0,0,0,0,-halfLong,halfHeight,halfWidth,-1,0,0,1,0,-halfLong,-halfHeight,halfWidth,-1,0,0,1,1,-halfLong,-halfHeight,-halfWidth,-1,0,0,0,1, halfLong,halfHeight,-halfWidth,1,0,0,1,0,halfLong,halfHeight,halfWidth,1,0,0,0,0,halfLong,-halfHeight,halfWidth,1,0,0,0,1,halfLong,-halfHeight,-halfWidth,1,0,0,1,1, -halfLong,halfHeight,halfWidth,0,0,1,0,0,halfLong,halfHeight,halfWidth,0,0,1,1,0,halfLong,-halfHeight,halfWidth,0,0,1,1,1,-halfLong,-halfHeight,halfWidth,0,0,1,0,1, -halfLong,halfHeight,-halfWidth,0,0,-1,1,0,halfLong,halfHeight,-halfWidth,0,0,-1,0,0,halfLong,-halfHeight,-halfWidth,0,0,-1,0,1,-halfLong,-halfHeight,-halfWidth,0,0,-1,1,1]); var indices=new Uint16Array([ 0,1,2,2,3,0, 4,7,6,6,5,4, 8,9,10,10,11,8, 12,15,14,14,13,12, 16,17,18,18,19,16, 20,23,22,22,21,20]); this._vertexBuffer=new VertexBuffer3D(vertexDeclaration,this._numberVertices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._indexBuffer=new IndexBuffer3D(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",this._numberIndices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._vertexBuffer.setData(vertices); this._indexBuffer.setData(indices); this.memorySize=(this._vertexBuffer._byteLength+this._indexBuffer._byteLength)*2; this.completeCreate(); } /** *设置长度(改变此属性会重新生成顶点和索引) *@param value 长度 */ /** *返回长度 *@return 长 */ __getset(0,__proto,'long',function(){ return this._long; },function(value){ if (this._long!==value){ this._long=value; this.releaseResource(); this.activeResource(); } }); /** *设置宽度(改变此属性会重新生成顶点和索引) *@param value 宽度 */ /** *返回宽度 *@return 宽 */ __getset(0,__proto,'width',function(){ return this._width; },function(value){ if (this._width!==value){ this._width=value; this.releaseResource(); this.activeResource(); } }); /** *设置高度(改变此属性会重新生成顶点和索引) *@param value 高度 */ /** *返回高度 *@return 高 */ __getset(0,__proto,'height',function(){ return this._height; },function(value){ if (this._height!==value){ this._height=value; this.releaseResource(); this.activeResource(); } }); return BoxMesh; })(PrimitiveMesh) /** *CapsuleMesh 类用于创建胶囊体。 */ //class laya.d3.resource.models.CapsuleMesh extends laya.d3.resource.models.PrimitiveMesh var CapsuleMesh=(function(_super){ function CapsuleMesh(radius,height,stacks,slices){ /**@private */ this._radius=NaN; /**@private */ this._height=NaN; /**@private */ this._slices=0; /**@private */ this._stacks=0; (radius===void 0)&& (radius=0.5); (height===void 0)&& (height=2); (stacks===void 0)&& (stacks=16); (slices===void 0)&& (slices=32); CapsuleMesh.__super.call(this); this._radius=radius; this._height=height < radius *2 ? radius *2 :height; this._stacks=stacks; this._slices=slices; this.recreateResource(); this._positions=this._getPositions(); this._generateBoundingObject(); } __class(CapsuleMesh,'laya.d3.resource.models.CapsuleMesh',_super); var __proto=CapsuleMesh.prototype; __proto.recreateResource=function(){ this._numberVertices=(this._stacks+1)*(this.slices+1)*2+(this._slices+1)*2; this._numberIndices=(3 *this._stacks *(this._slices+1))*2 *2+2 *this._slices *3; var vertexDeclaration=VertexPositionNormalTexture.vertexDeclaration; var vertexFloatStride=vertexDeclaration.vertexStride / 4; var vertices=new Float32Array(this._numberVertices *vertexFloatStride); var indices=new Uint16Array(this._numberIndices); var stackAngle=(Math.PI / 2.0)/ this._stacks; var sliceAngle=(Math.PI *2.0)/ this._slices; var hcHeight=this._height / 2-this._radius; var posX=0; var posY=0; var posZ=0; var vc=0; var ic=0; var verticeCount=0; var stack=0,slice=0; for (stack=0;stack <=this._stacks;stack++){ for (slice=0;slice <=this._slices;slice++){ posX=this._radius *Math.cos(stack *stackAngle)*Math.cos(slice *sliceAngle+Math.PI); posY=this._radius *Math.sin(stack *stackAngle); posZ=this._radius *Math.cos(stack *stackAngle)*Math.sin(slice *sliceAngle+Math.PI); vertices[vc++]=posX; vertices[vc++]=posY+hcHeight; vertices[vc++]=posZ; vertices[vc++]=posX; vertices[vc++]=posY; vertices[vc++]=posZ; vertices[vc++]=1-slice / this._slices; vertices[vc++]=(1-stack / this._stacks)*((Math.PI *this._radius / 2)/ (this._height+Math.PI *this._radius)); if (stack < this._stacks){ indices[ic++]=(stack *(this._slices+1))+slice+(this._slices+1); indices[ic++]=(stack *(this._slices+1))+slice; indices[ic++]=(stack *(this._slices+1))+slice+1; indices[ic++]=(stack *(this._slices+1))+slice+(this._slices); indices[ic++]=(stack *(this._slices+1))+slice; indices[ic++]=(stack *(this._slices+1))+slice+(this._slices+1); } } } verticeCount+=(this._stacks+1)*(this._slices+1); for (stack=0;stack <=this._stacks;stack++){ for (slice=0;slice <=this._slices;slice++){ posX=this._radius *Math.cos(stack *stackAngle)*Math.cos(slice *sliceAngle+Math.PI); posY=this._radius *Math.sin(-stack *stackAngle); posZ=this._radius *Math.cos(stack *stackAngle)*Math.sin(slice *sliceAngle+Math.PI); vertices[vc++]=posX; vertices[vc++]=posY-hcHeight; vertices[vc++]=posZ; vertices[vc++]=posX; vertices[vc++]=posY; vertices[vc++]=posZ; vertices[vc++]=1-slice / this._slices; vertices[vc++]=((stack / this._stacks)*(Math.PI *this._radius / 2)+(this._height+Math.PI *this._radius / 2))/ (this._height+Math.PI *this._radius); if (stack < this._stacks){ indices[ic++]=verticeCount+(stack *(this._slices+1))+slice; indices[ic++]=verticeCount+(stack *(this._slices+1))+slice+(this._slices+1); indices[ic++]=verticeCount+(stack *(this._slices+1))+slice+1; indices[ic++]=verticeCount+(stack *(this._slices+1))+slice; indices[ic++]=verticeCount+(stack *(this._slices+1))+slice+(this._slices); indices[ic++]=verticeCount+(stack *(this._slices+1))+slice+(this._slices+1); } } } verticeCount+=(this._stacks+1)*(this._slices+1); for (slice=0;slice <=this._slices;slice++){ posX=this._radius *Math.cos(slice *sliceAngle+Math.PI); posY=hcHeight; posZ=this._radius *Math.sin(slice *sliceAngle+Math.PI); vertices[vc++]=posX; vertices[vc+(this._slices+1)*8-1]=posX; vertices[vc++]=posY; vertices[vc+(this._slices+1)*8-1]=-posY; vertices[vc++]=posZ; vertices[vc+(this._slices+1)*8-1]=posZ; vertices[vc++]=posX; vertices[vc+(this._slices+1)*8-1]=posX; vertices[vc++]=0; vertices[vc+(this._slices+1)*8-1]=0; vertices[vc++]=posZ; vertices[vc+(this._slices+1)*8-1]=posZ; vertices[vc++]=1-slice *1 / this._slices; vertices[vc+(this._slices+1)*8-1]=1-slice *1 / this._slices; vertices[vc++]=(Math.PI *this._radius / 2)/ (this._height+Math.PI *this._radius); vertices[vc+(this._slices+1)*8-1]=(Math.PI *this._radius / 2+this._height)/ (this._height+Math.PI *this._radius); } for (slice=0;slice < this._slices;slice++){ indices[ic++]=slice+verticeCount+(this._slices+1); indices[ic++]=slice+verticeCount+1; indices[ic++]=slice+verticeCount; indices[ic++]=slice+verticeCount+(this._slices+1); indices[ic++]=slice+verticeCount+(this._slices+1)+1; indices[ic++]=slice+verticeCount+1; } verticeCount+=2 *(this._slices+1); this._vertexBuffer=new VertexBuffer3D(vertexDeclaration,this._numberVertices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._indexBuffer=new IndexBuffer3D(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",this._numberIndices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._vertexBuffer.setData(vertices); this._indexBuffer.setData(indices); this.memorySize=(this._vertexBuffer._byteLength+this._indexBuffer._byteLength)*2; this.completeCreate(); } /** *设置半径(改变此属性会重新生成顶点和索引) *@param value 半径 */ /** *返回半径 *@return 半径 */ __getset(0,__proto,'radius',function(){ return this._radius; },function(value){ if (this._radius!==value){ this._radius=value; this.releaseResource(); this.activeResource(); } }); /** *设置高度(改变此属性会重新生成顶点和索引) *@param value 高度 */ /** *返回高度 *@return 高度 */ __getset(0,__proto,'height',function(){ return this._height; },function(value){ if (this._height!==value){ this._height=value; this.releaseResource(); this.activeResource(); } }); /** *设置高度分段(改变此属性会重新生成顶点和索引) *@param value高度分段 */ /** *获取高度分段 *@return 高度分段 */ __getset(0,__proto,'stacks',function(){ return this._stacks; },function(value){ if (this._stacks!==value){ this._stacks=value; this.releaseResource(); this.activeResource(); } }); /** *设置宽度分段(改变此属性会重新生成顶点和索引) *@param value 宽度分段 */ /** *获取宽度分段 *@return 宽度分段 */ __getset(0,__proto,'slices',function(){ return this._slices; },function(value){ if (this._slices!==value){ this._slices=value; this.releaseResource(); this.activeResource(); } }); return CapsuleMesh; })(PrimitiveMesh) /** *CylinderMesh 类用于创建圆柱体。 */ //class laya.d3.resource.models.CylinderMesh extends laya.d3.resource.models.PrimitiveMesh var CylinderMesh=(function(_super){ function CylinderMesh(radius,height,slices){ /**@private */ this._radius=NaN; /**@private */ this._height=NaN; /**@private */ this._slices=0; (radius===void 0)&& (radius=0.5); (height===void 0)&& (height=2); (slices===void 0)&& (slices=32); CylinderMesh.__super.call(this); this._radius=radius; this._height=height; this._slices=slices; this.recreateResource(); this._positions=this._getPositions(); this._generateBoundingObject(); } __class(CylinderMesh,'laya.d3.resource.models.CylinderMesh',_super); var __proto=CylinderMesh.prototype; __proto.recreateResource=function(){ this._numberVertices=(this._slices+1+1)+(this._slices+1)*2+(this._slices+1+1); this._numberIndices=3 *this._slices+6 *this._slices+3 *this._slices; var vertexDeclaration=VertexPositionNormalTexture.vertexDeclaration; var vertexFloatStride=vertexDeclaration.vertexStride / 4; var vertices=new Float32Array(this._numberVertices *vertexFloatStride); var indices=new Uint16Array(this._numberIndices); var sliceAngle=(Math.PI *2.0)/ this._slices; var halfHeight=this._height / 2; var curAngle=0; var verticeCount=0; var posX=0; var posY=0; var posZ=0; var vc=0; var ic=0; for (var tv=0;tv <=this._slices;tv++){ if (tv===0){ vertices[vc++]=0; vertices[vc++]=halfHeight; vertices[vc++]=0; vertices[vc++]=0; vertices[vc++]=1; vertices[vc++]=0; vertices[vc++]=0.5; vertices[vc++]=0.5; } curAngle=tv *sliceAngle; posX=Math.cos(curAngle)*this._radius; posY=halfHeight; posZ=Math.sin(curAngle)*this._radius; vertices[vc++]=posX; vertices[vc++]=posY; vertices[vc++]=posZ; vertices[vc++]=0; vertices[vc++]=1; vertices[vc++]=0; vertices[vc++]=0.5+Math.cos(curAngle)*0.5; vertices[vc++]=0.5+Math.sin(curAngle)*0.5; } for (var ti=0;ti < this._slices;ti++){ indices[ic++]=0; indices[ic++]=ti+1; indices[ic++]=ti+2; } verticeCount+=this._slices+1+1; for (var rv=0;rv <=this._slices;rv++){ curAngle=rv *sliceAngle; posX=Math.cos(curAngle+Math.PI)*this._radius; posY=halfHeight; posZ=Math.sin(curAngle+Math.PI)*this._radius; vertices[vc++]=posX; vertices[vc+(this._slices+1)*8-1]=posX; vertices[vc++]=posY; vertices[vc+(this._slices+1)*8-1]=-posY; vertices[vc++]=posZ; vertices[vc+(this._slices+1)*8-1]=posZ; vertices[vc++]=posX; vertices[vc+(this._slices+1)*8-1]=posX; vertices[vc++]=0; vertices[vc+(this._slices+1)*8-1]=0; vertices[vc++]=posZ; vertices[vc+(this._slices+1)*8-1]=posZ; vertices[vc++]=1-rv *1 / this._slices; vertices[vc+(this._slices+1)*8-1]=1-rv *1 / this._slices; vertices[vc++]=0; vertices[vc+(this._slices+1)*8-1]=1; } vc+=(this._slices+1)*8; for (var ri=0;ri < this._slices;ri++){ indices[ic++]=ri+verticeCount+(this._slices+1); indices[ic++]=ri+verticeCount+1; indices[ic++]=ri+verticeCount; indices[ic++]=ri+verticeCount+(this._slices+1); indices[ic++]=ri+verticeCount+(this._slices+1)+1; indices[ic++]=ri+verticeCount+1; } verticeCount+=2 *(this._slices+1); for (var bv=0;bv <=this._slices;bv++){ if (bv===0){ vertices[vc++]=0; vertices[vc++]=-halfHeight; vertices[vc++]=0; vertices[vc++]=0; vertices[vc++]=-1; vertices[vc++]=0; vertices[vc++]=0.5; vertices[vc++]=0.5; } curAngle=bv *sliceAngle; posX=Math.cos(curAngle+Math.PI)*this._radius; posY=-halfHeight; posZ=Math.sin(curAngle+Math.PI)*this._radius; vertices[vc++]=posX; vertices[vc++]=posY; vertices[vc++]=posZ; vertices[vc++]=0; vertices[vc++]=-1; vertices[vc++]=0; vertices[vc++]=0.5+Math.cos(curAngle)*0.5; vertices[vc++]=0.5+Math.sin(curAngle)*0.5; } for (var bi=0;bi < this._slices;bi++){ indices[ic++]=0+verticeCount; indices[ic++]=bi+2+verticeCount; indices[ic++]=bi+1+verticeCount; } verticeCount+=this._slices+1+1; this._vertexBuffer=new VertexBuffer3D(vertexDeclaration,this._numberVertices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._indexBuffer=new IndexBuffer3D(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",this._numberIndices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._vertexBuffer.setData(vertices); this._indexBuffer.setData(indices); this.memorySize=(this._vertexBuffer._byteLength+this._indexBuffer._byteLength)*2; this.completeCreate(); } /** *设置半径(改变此属性会重新生成顶点和索引) *@param value 半径 */ /** *返回半径 *@return 半径 */ __getset(0,__proto,'radius',function(){ return this._radius; },function(value){ if (this._radius!==value){ this._radius=value; this.releaseResource(); this.activeResource(); } }); /** *设置高度(改变此属性会重新生成顶点和索引) *@param value 高度 */ /** *返回高度 *@return 高度 */ __getset(0,__proto,'height',function(){ return this._height; },function(value){ if (this._height!==value){ this._height=value; this.releaseResource(); this.activeResource(); } }); /** *设置宽度分段(改变此属性会重新生成顶点和索引) *@param value 宽度分段 */ /** *获取宽度分段 *@return 宽度分段 */ __getset(0,__proto,'slices',function(){ return this._slices; },function(value){ if (this._slices!==value){ this._slices=value; this.releaseResource(); this.activeResource(); } }); return CylinderMesh; })(PrimitiveMesh) /** *QuadMesh 类用于创建平面。 */ //class laya.d3.resource.models.PlaneMesh extends laya.d3.resource.models.PrimitiveMesh var PlaneMesh=(function(_super){ function PlaneMesh(long,width,stacks,slices){ /**@private */ this._long=NaN; /**@private */ this._width=NaN; /**@private */ this._stacks=0; /**@private */ this._slices=0; (long===void 0)&& (long=10); (width===void 0)&& (width=10); (stacks===void 0)&& (stacks=10); (slices===void 0)&& (slices=10); PlaneMesh.__super.call(this); this._long=long; this._width=width; this._stacks=stacks; this._slices=slices; this.activeResource(); this._positions=this._getPositions(); this._generateBoundingObject(); } __class(PlaneMesh,'laya.d3.resource.models.PlaneMesh',_super); var __proto=PlaneMesh.prototype; __proto.recreateResource=function(){ this._numberVertices=(this._stacks+1)*(this._slices+1); this._numberIndices=this._stacks *this._slices *2 *3; var indices=new Uint16Array(this._numberIndices); var vertexDeclaration=VertexPositionNormalTexture.vertexDeclaration; var vertexFloatStride=vertexDeclaration.vertexStride / 4; var vertices=new Float32Array(this._numberVertices *vertexFloatStride); var halfLong=this._long / 2; var halfWidth=this._width / 2; var stacksLong=this._long / this._stacks; var slicesWidth=this._width / this._slices; var verticeCount=0; for (var i=0;i <=this._slices;i++){ for (var j=0;j <=this._stacks;j++){ vertices[verticeCount++]=j *stacksLong-halfLong; vertices[verticeCount++]=0; vertices[verticeCount++]=i *slicesWidth-halfWidth; vertices[verticeCount++]=0; vertices[verticeCount++]=1; vertices[verticeCount++]=0; vertices[verticeCount++]=j *1 / this._stacks; vertices[verticeCount++]=i *1 / this._slices; } }; var indiceIndex=0; for (i=0;i < this._slices;i++){ for (j=0;j < this._stacks;j++){ indices[indiceIndex++]=(i+1)*(this._stacks+1)+j; indices[indiceIndex++]=i *(this._stacks+1)+j; indices[indiceIndex++]=(i+1)*(this._stacks+1)+j+1; indices[indiceIndex++]=i *(this._stacks+1)+j; indices[indiceIndex++]=i *(this._stacks+1)+j+1; indices[indiceIndex++]=(i+1)*(this._stacks+1)+j+1; } } this._vertexBuffer=new VertexBuffer3D(vertexDeclaration,this._numberVertices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._indexBuffer=new IndexBuffer3D(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",this._numberIndices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._vertexBuffer.setData(vertices); this._indexBuffer.setData(indices); this.memorySize=(this._vertexBuffer._byteLength+this._indexBuffer._byteLength)*2; this.completeCreate(); } /** *设置长度(改变此属性会重新生成顶点和索引) *@param value 长度 */ /** *返回长度 *@return 长 */ __getset(0,__proto,'long',function(){ return this._long; },function(value){ if (this._long!==value){ this._long=value; this.releaseResource(); this.activeResource(); } }); /** *设置宽度(改变此属性会重新生成顶点和索引) *@param value 宽度 */ /** *返回宽度 *@return 宽 */ __getset(0,__proto,'width',function(){ return this._width; },function(value){ if (this._width!==value){ this._width=value; this.releaseResource(); this.activeResource(); } }); /** *设置长度分段(改变此属性会重新生成顶点和索引) *@param value长度分段 */ /** *获取长度分段 *@return 长度分段 */ __getset(0,__proto,'stacks',function(){ return this._stacks; },function(value){ if (this._stacks!==value){ this._stacks=value; this.releaseResource(); this.activeResource(); } }); /** *设置宽度分段(改变此属性会重新生成顶点和索引) *@param value 宽度分段 */ /** *获取宽度分段 *@return 宽度分段 */ __getset(0,__proto,'slices',function(){ return this._slices; },function(value){ if (this._slices!==value){ this._slices=value; this.releaseResource(); this.activeResource(); } }); return PlaneMesh; })(PrimitiveMesh) /** *QuadMesh 类用于创建四边形。 */ //class laya.d3.resource.models.QuadMesh extends laya.d3.resource.models.PrimitiveMesh var QuadMesh=(function(_super){ function QuadMesh(long,width){ /**@private */ this._long=NaN; /**@private */ this._width=NaN; (long===void 0)&& (long=1); (width===void 0)&& (width=1); QuadMesh.__super.call(this); this._long=long; this._width=width; this.activeResource(); this._positions=this._getPositions(); this._generateBoundingObject(); } __class(QuadMesh,'laya.d3.resource.models.QuadMesh',_super); var __proto=QuadMesh.prototype; __proto.recreateResource=function(){ this._numberVertices=4; this._numberIndices=6; var vertexDeclaration=VertexPositionNormalTexture.vertexDeclaration; var vertexFloatStride=vertexDeclaration.vertexStride / 4; var halfLong=this._long / 2; var halfWidth=this._width / 2; var vertices=new Float32Array([ -halfLong,halfWidth,0,0,0,1,0,0,halfLong,halfWidth,0,0,0,1,1,0,-halfLong,-halfWidth,0,0,0,1,0,1,halfLong,-halfWidth,0,0,0,1,1,1,]); var indices=new Uint16Array([ 0,1,2,3,2,1,]); this._vertexBuffer=new VertexBuffer3D(vertexDeclaration,this._numberVertices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._indexBuffer=new IndexBuffer3D(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",this._numberIndices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._vertexBuffer.setData(vertices); this._indexBuffer.setData(indices); this.memorySize=(this._vertexBuffer._byteLength+this._indexBuffer._byteLength)*2; this.completeCreate(); } /** *设置长度(改变此属性会重新生成顶点和索引) *@param value 长度 */ /** *返回长度 *@return 长 */ __getset(0,__proto,'long',function(){ return this._long; },function(value){ if (this._long!==value){ this._long=value; this.releaseResource(); this.activeResource(); } }); /** *设置宽度(改变此属性会重新生成顶点和索引) *@param value 宽度 */ /** *返回宽度 *@return 宽 */ __getset(0,__proto,'width',function(){ return this._width; },function(value){ if (this._width!==value){ this._width=value; this.releaseResource(); this.activeResource(); } }); return QuadMesh; })(PrimitiveMesh) /** *Sphere 类用于创建球体。 */ //class laya.d3.resource.models.SphereMesh extends laya.d3.resource.models.PrimitiveMesh var SphereMesh=(function(_super){ function SphereMesh(radius,stacks,slices){ /**@private */ this._radius=NaN; /**@private */ this._slices=0; /**@private */ this._stacks=0; (radius===void 0)&& (radius=0.5); (stacks===void 0)&& (stacks=32); (slices===void 0)&& (slices=32); SphereMesh.__super.call(this); this._radius=radius; this._stacks=stacks; this._slices=slices; this.activeResource(); this._positions=this._getPositions(); this._generateBoundingObject(); } __class(SphereMesh,'laya.d3.resource.models.SphereMesh',_super); var __proto=SphereMesh.prototype; __proto.recreateResource=function(){ this._numberVertices=(this._stacks+1)*(this._slices+1); this._numberIndices=(3 *this._stacks *(this._slices+1))*2; var indices=new Uint16Array(this._numberIndices); var vertexDeclaration=VertexPositionNormalTexture.vertexDeclaration; var vertexFloatStride=vertexDeclaration.vertexStride / 4; var vertices=new Float32Array(this._numberVertices *vertexFloatStride); var stackAngle=Math.PI / this._stacks; var sliceAngle=(Math.PI *2.0)/ this._slices; var vertexIndex=0; var vertexCount=0; var indexCount=0; for (var stack=0;stack < (this._stacks+1);stack++){ var r=Math.sin(stack *stackAngle); var y=Math.cos(stack *stackAngle); for (var slice=0;slice < (this._slices+1);slice++){ var x=r *Math.sin(slice *sliceAngle+Math.PI *1 / 2); var z=r *Math.cos(slice *sliceAngle+Math.PI *1 / 2); vertices[vertexCount+0]=x *this._radius; vertices[vertexCount+1]=y *this._radius; vertices[vertexCount+2]=z *this._radius; vertices[vertexCount+3]=x; vertices[vertexCount+4]=y; vertices[vertexCount+5]=z; vertices[vertexCount+6]=slice / this._slices; vertices[vertexCount+7]=stack / this._stacks; vertexCount+=vertexFloatStride; if (stack !=(this._stacks-1)){ indices[indexCount++]=vertexIndex+(this._slices+1); indices[indexCount++]=vertexIndex; indices[indexCount++]=vertexIndex+1; indices[indexCount++]=vertexIndex+(this._slices); indices[indexCount++]=vertexIndex; indices[indexCount++]=vertexIndex+(this._slices+1); vertexIndex++; } } } this._vertexBuffer=new VertexBuffer3D(vertexDeclaration,this._numberVertices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._indexBuffer=new IndexBuffer3D(/*laya.d3.graphics.IndexBuffer3D.INDEXTYPE_USHORT*/"ushort",this._numberIndices,/*laya.webgl.WebGLContext.STATIC_DRAW*/0x88E4,true); this._vertexBuffer.setData(vertices); this._indexBuffer.setData(indices); this.memorySize=(this._vertexBuffer._byteLength+this._indexBuffer._byteLength)*2; this.completeCreate(); } /** *设置半径(改变此属性会重新生成顶点和索引) *@param value 半径 */ /** *返回半径 *@return 半径 */ __getset(0,__proto,'radius',function(){ return this._radius; },function(value){ if (this._radius!==value){ this._radius=value; this.releaseResource(); this.activeResource(); } }); /** *设置宽度分段(改变此属性会重新生成顶点和索引) *@param value 宽度分段 */ /** *获取宽度分段 *@return 宽度分段 */ __getset(0,__proto,'slices',function(){ return this._slices; },function(value){ if (this._slices!==value){ this._slices=value; this.releaseResource(); this.activeResource(); } }); /** *设置高度分段(改变此属性会重新生成顶点和索引) *@param value高度分段 */ /** *获取高度分段 *@return 高度分段 */ __getset(0,__proto,'stacks',function(){ return this._stacks; },function(value){ if (this._stacks!==value){ this._stacks=value; this.releaseResource(); this.activeResource(); } }); return SphereMesh; })(PrimitiveMesh) /** *Camera 类用于创建摄像机。 */ //class laya.d3.core.Camera extends laya.d3.core.BaseCamera var Camera=(function(_super){ function Camera(aspectRatio,nearPlane,farPlane){ /**@private */ //this._aspectRatio=NaN; /**@private */ //this._viewport=null; /**@private */ //this._normalizedViewport=null; /**@private */ //this._viewMatrix=null; /**@private */ //this._projectionMatrix=null; /**@private */ //this._projectionViewMatrix=null; /**@private */ //this._boundFrustumUpdate=false; /**@private */ //this._boundFrustum=null; /**@private */ //this._orientedBoundBox=null; (aspectRatio===void 0)&& (aspectRatio=0); (nearPlane===void 0)&& (nearPlane=0.3); (farPlane===void 0)&& (farPlane=1000); this._viewMatrix=new Matrix4x4(); this._projectionMatrix=new Matrix4x4(); this._projectionViewMatrix=new Matrix4x4(); this._viewport=new Viewport(0,0,0,0); this._normalizedViewport=new Viewport(0,0,1,1); this._aspectRatio=aspectRatio; this._boundFrustumUpdate=true; this._boundFrustum=new BoundFrustum(Matrix4x4.DEFAULT); Camera.__super.call(this,nearPlane,farPlane); this.transform.on(/*laya.events.Event.WORLDMATRIX_NEEDCHANGE*/"worldmatrixneedchanged",this,this._onWorldMatrixChanged); } __class(Camera,'laya.d3.core.Camera',_super); var __proto=Camera.prototype; /** *@private */ __proto._onWorldMatrixChanged=function(){ this._boundFrustumUpdate=true; } /** *@inheritDoc */ __proto._parseCustomProps=function(rootNode,innerResouMap,customProps,json){ var color=customProps.clearColor; this.clearColor=new Vector4(color[0],color[1],color[2],color[3]); var viewport=customProps.viewport; this.normalizedViewport=new Viewport(viewport[0],viewport[1],viewport[2],viewport[3]); } /** *@inheritDoc */ __proto._calculateProjectionMatrix=function(){ if (!this._useUserProjectionMatrix){ if (this._orthographic){ var halfWidth=this.orthographicVerticalSize *this.aspectRatio *0.5; var halfHeight=this.orthographicVerticalSize *0.5; Matrix4x4.createOrthoOffCenterRH(-halfWidth,halfWidth,-halfHeight,halfHeight,this.nearPlane,this.farPlane,this._projectionMatrix); }else { Matrix4x4.createPerspective(3.1416 *this.fieldOfView / 180.0,this.aspectRatio,this.nearPlane,this.farPlane,this._projectionMatrix); } } this._boundFrustumUpdate=true; } /** *@inheritDoc */ __proto._update=function(state){ if (this.conchModel){ this.conchModel.setViewMatrix(this.viewMatrix.elements); this.conchModel.setProjectMatrix(this.projectionMatrix.elements); } laya.d3.core.Sprite3D.prototype._update.call(this,state); } /** *@inheritDoc */ __proto._renderCamera=function(gl,state,scene){ (scene.parallelSplitShadowMaps[0])&& (scene._renderShadowMap(gl,state,this)); state.camera=this; this._prepareCameraToRender(); scene._preRenderUpdateComponents(state); var viewMat,projectMat; viewMat=state._viewMatrix=this.viewMatrix; var renderTar=this._renderTarget; if (renderTar){ renderTar.start(); Matrix4x4.multiply(BaseCamera._invertYScaleMatrix,this._projectionMatrix,BaseCamera._invertYProjectionMatrix); Matrix4x4.multiply(BaseCamera._invertYScaleMatrix,this.projectionViewMatrix,BaseCamera._invertYProjectionViewMatrix); projectMat=state._projectionMatrix=BaseCamera._invertYProjectionMatrix; state._projectionViewMatrix=BaseCamera._invertYProjectionViewMatrix; }else { projectMat=state._projectionMatrix=this._projectionMatrix; state._projectionViewMatrix=this.projectionViewMatrix; } this._prepareCameraViewProject(viewMat,projectMat); state._viewport=this.viewport; scene._preRenderScene(gl,state,this.boundFrustum); scene._clear(gl,state); scene._renderScene(gl,state); scene._postRenderUpdateComponents(state); (renderTar)&& (renderTar.end()); } /** *计算从屏幕空间生成的射线。 *@param point 屏幕空间的位置位置。 *@return out 输出射线。 */ __proto.viewportPointToRay=function(point,out){ Picker.calculateCursorRay(point,this.viewport,this._projectionMatrix,this.viewMatrix,null,out); } /** *计算从裁切空间生成的射线。 *@param point 裁切空间的位置。。 *@return out 输出射线。 */ __proto.normalizedViewportPointToRay=function(point,out){ var finalPoint=Camera._tempVector20; var vp=this.viewport; var nVpPosE=point.elements; var vpPosE=finalPoint.elements; vpPosE[0]=nVpPosE[0] *vp.width; vpPosE[1]=nVpPosE[1] *vp.height; Picker.calculateCursorRay(finalPoint,this.viewport,this._projectionMatrix,this.viewMatrix,null,out); } /** *计算从世界空间准换三维坐标到屏幕空间。 *@param position 世界空间的位置。 *@return out 输出位置。 */ __proto.worldToViewportPoint=function(position,out){ Matrix4x4.multiply(this._projectionMatrix,this._viewMatrix,this._projectionViewMatrix); this.viewport.project(position,this._projectionViewMatrix,out); var outE=out.elements; outE[0]=outE[0] / Laya.stage.clientScaleX; outE[1]=outE[1] / Laya.stage.clientScaleY; } /** *计算从世界空间准换三维坐标到裁切空间。 *@param position 世界空间的位置。 *@return out 输出位置。 */ __proto.worldToNormalizedViewportPoint=function(position,out){ Matrix4x4.multiply(this._projectionMatrix,this._viewMatrix,this._projectionViewMatrix); this.normalizedViewport.project(position,this._projectionViewMatrix,out); var outE=out.elements; outE[0]=outE[0] / Laya.stage.clientScaleX; outE[1]=outE[1] / Laya.stage.clientScaleY; } /** *转换2D屏幕坐标系统到3D正交投影下的坐标系统,注:只有正交模型下有效。 *@param source 源坐标。 *@param out 输出坐标。 *@return 是否转换成功。 */ __proto.convertScreenCoordToOrthographicCoord=function(source,out){ if (this._orthographic){ var clientWidth=RenderState.clientWidth; var clientHeight=RenderState.clientHeight; var ratioX=this.orthographicVerticalSize *this.aspectRatio / clientWidth; var ratioY=this.orthographicVerticalSize / clientHeight; var sE=source.elements; var oE=out.elements; oE[0]=(-clientWidth / 2+sE[0])*ratioX; oE[1]=(clientHeight / 2-sE[1])*ratioY; oE[2]=(this.nearPlane-this.farPlane)*(sE[2]+1)/ 2-this.nearPlane; Vector3.transformCoordinate(out,this.transform.worldMatrix,out); return true; }else { return false; } } /** *获取视图投影矩阵。 *@return 视图投影矩阵。 */ __getset(0,__proto,'projectionViewMatrix',function(){ Matrix4x4.multiply(this.projectionMatrix,this.viewMatrix,this._projectionViewMatrix); return this._projectionViewMatrix; }); /** *设置横纵比。 *@param value 横纵比。 */ /** *获取横纵比。 *@return 横纵比。 */ __getset(0,__proto,'aspectRatio',function(){ if (this._aspectRatio===0){ var vp=this.viewport; return vp.width / vp.height; } return this._aspectRatio; },function(value){ if (value < 0) throw new Error("Camera: the aspect ratio has to be a positive real number."); this._aspectRatio=value; this._calculateProjectionMatrix(); }); /** *获取摄像机视锥。 */ __getset(0,__proto,'boundFrustum',function(){ if (this._boundFrustumUpdate) this._boundFrustum.matrix=this.projectionViewMatrix; return this._boundFrustum; }); __getset(0,__proto,'needViewport',function(){ var nVp=this.normalizedViewport; return nVp.x===0 && nVp.y===0 && nVp.width===1 && nVp.height===1; }); /** *设置屏幕空间的视口。 *@param 屏幕空间的视口。 */ /** *获取屏幕空间的视口。 *@return 屏幕空间的视口。 */ __getset(0,__proto,'viewport',function(){ if (this._viewportExpressedInClipSpace){ var nVp=this._normalizedViewport; var size=this.renderTargetSize; var sizeW=size.width; var sizeH=size.height; this._viewport.x=nVp.x *sizeW; this._viewport.y=nVp.y *sizeH; this._viewport.width=nVp.width *sizeW; this._viewport.height=nVp.height *sizeH; } return this._viewport; },function(value){ if (this.renderTarget !=null && (value.x < 0 || value.y < 0 || value.width==0 || value.height==0)) throw new Error("Camera: viewport size invalid.","value"); this._viewportExpressedInClipSpace=false; this._viewport=value; this._calculateProjectionMatrix(); }); /** *设置裁剪空间的视口。 *@return 裁剪空间的视口。 */ /** *获取裁剪空间的视口。 *@return 裁剪空间的视口。 */ __getset(0,__proto,'normalizedViewport',function(){ if (!this._viewportExpressedInClipSpace){ var vp=this._viewport; var size=this.renderTargetSize; var sizeW=size.width; var sizeH=size.height; this._normalizedViewport.x=vp.x / sizeW; this._normalizedViewport.y=vp.y / sizeH; this._normalizedViewport.width=vp.width / sizeW; this._normalizedViewport.height=vp.height / sizeH; } return this._normalizedViewport; },function(value){ if (value.x < 0){ value.x=0; console.warn("Camera: viewport.x must large than 0.0."); } if (value.y < 0){ value.y=0; console.warn("Camera: viewport.y must large than 0.0."); } if (value.x+value.width > 1.0){ value.width=1.0-value.x; console.warn("Camera: viewport.width + viewport.x must less than 1.0."); } if ((value.y+value.height)> 1.0){ value.height=1.0-value.y; console.warn("Camera: viewport.height + viewport.y must less than 1.0."); } this._viewportExpressedInClipSpace=true; this._normalizedViewport=value; this._calculateProjectionMatrix(); }); /**设置投影矩阵。*/ /**获取投影矩阵。*/ __getset(0,__proto,'projectionMatrix',function(){ return this._projectionMatrix; },function(value){ this._projectionMatrix=value; this._useUserProjectionMatrix=true; }); /** *获取视图矩阵。 *@return 视图矩阵。 */ __getset(0,__proto,'viewMatrix',function(){ this.transform.worldMatrix.invert(this._viewMatrix); return this._viewMatrix; }); __static(Camera, ['_tempVector20',function(){return this._tempVector20=new Vector2();} ]); return Camera; })(BaseCamera) /** *Glitter 类用于创建闪光。 */ //class laya.d3.core.glitter.Glitter extends laya.d3.core.RenderableSprite3D var Glitter=(function(_super){ /** *创建一个 Glitter 实例。 *@param settings 配置信息。 */ function Glitter(){ Glitter.__super.call(this); this._render=new GlitterRender(this); this._render.on(/*laya.events.Event.MATERIAL_CHANGED*/"materialchanged",this,this._onMaterialChanged); var material=new GlitterMaterial(); this._render.sharedMaterial=material; this._geometryFilter=new GlitterTemplet(this); material.renderMode=/*laya.d3.core.material.GlitterMaterial.RENDERMODE_DEPTHREAD_ADDTIVEDOUBLEFACE*/8; this._changeRenderObject(0); } __class(Glitter,'laya.d3.core.glitter.Glitter',_super); var __proto=Glitter.prototype; /**@private */ __proto._changeRenderObject=function(index){ var renderObjects=this._render._renderElements; var renderElement=renderObjects[index]; (renderElement)|| (renderElement=renderObjects[index]=new RenderElement()); renderElement._render=this._render; var material=this._render.sharedMaterials[index]; (material)|| (material=GlitterMaterial.defaultMaterial); var element=this._geometryFilter; renderElement._mainSortID=0; renderElement._sprite3D=this; renderElement.renderObj=element; renderElement._material=material; return renderElement; } /**@private */ __proto._onMaterialChanged=function(_glitterRender,index,material){ var renderElementCount=_glitterRender._renderElements.length; (index < renderElementCount)&& this._changeRenderObject(index); } /**@private */ __proto._clearSelfRenderObjects=function(){ this.scene.removeFrustumCullingObject(this._render); } /**@private */ __proto._addSelfRenderObjects=function(){ this.scene.addFrustumCullingObject(this._render); } __proto._update=function(state){ (this._geometryFilter)._update(state.elapsedTime); _super.prototype._update.call(this,state); } /** *通过位置添加刀光。 *@param position0 位置0。 *@param position1 位置1。 */ __proto.addGlitterByPositions=function(position0,position1){ (this._geometryFilter).addVertexPosition(position0,position1); } /** *通过位置和速度添加刀光。 *@param position0 位置0。 *@param velocity0 速度0。 *@param position1 位置1。 *@param velocity1 速度1。 */ __proto.addGlitterByPositionsVelocitys=function(position0,velocity0,position1,velocity1){ (this._geometryFilter).addVertexPositionVelocity(position0,velocity0,position1,velocity1); } __proto.cloneTo=function(destObject){ var destGlitter=destObject; var destTemplet=destGlitter.templet; var templet=this._geometryFilter; destTemplet.lifeTime=templet.lifeTime; destTemplet.minSegmentDistance=templet.minSegmentDistance; destTemplet.minInterpDistance=templet.minInterpDistance; destTemplet.maxSlerpCount=templet.maxSlerpCount; destTemplet._maxSegments=templet._maxSegments; var destGlitterRender=destGlitter._render; var glitterRender=this._render; destGlitterRender.sharedMaterials=glitterRender.sharedMaterials; destGlitterRender.enable=glitterRender.enable; laya.d3.core.Sprite3D.prototype.cloneTo.call(this,destObject); } /** *

销毁此对象。

*@param destroyChild 是否同时销毁子节点,若值为true,则销毁子节点,否则不销毁子节点。 */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); if (this.destroyed) return; _super.prototype.destroy.call(this,destroyChild); this._geometryFilter._destroy(); this._geometryFilter=null; } /** *获取闪光模板。 *@return 闪光模板。 */ __getset(0,__proto,'templet',function(){ return this._geometryFilter; }); /** *获取刀光渲染器。 *@return 刀光渲染器。 */ __getset(0,__proto,'glitterRender',function(){ return this._render; }); Glitter.CURRENTTIME=2; Glitter.DURATION=3; return Glitter; })(RenderableSprite3D) /** *DirectionLight 类用于创建平行光。 */ //class laya.d3.core.light.DirectionLight extends laya.d3.core.light.LightSprite var DirectionLight=(function(_super){ function DirectionLight(){ /**@private */ this._direction=null; /**@private */ this._updateDirection=false; DirectionLight.__super.call(this); this._updateDirection=false; this._direction=new Vector3(); this.transform.on(/*laya.events.Event.WORLDMATRIX_NEEDCHANGE*/"worldmatrixneedchanged",this,this._onWorldMatrixChange); } __class(DirectionLight,'laya.d3.core.light.DirectionLight',_super); var __proto=DirectionLight.prototype; /** *@private */ __proto._initShadow=function(){ if (this._shadow){ this._parallelSplitShadowMap=new ParallelSplitShadowMap(); this.scene.parallelSplitShadowMaps.push(this._parallelSplitShadowMap); this.transform.worldMatrix.getForward(this._direction); Vector3.normalize(this._direction,this._direction); this._parallelSplitShadowMap.setInfo(this.scene,this._shadowFarPlane,this._direction,this._shadowMapSize,this._shadowMapCount,this._shadowMapPCFType); }else { var parallelSplitShadowMaps=this.scene.parallelSplitShadowMaps; parallelSplitShadowMaps.splice(parallelSplitShadowMaps.indexOf(this._parallelSplitShadowMap),1); this._parallelSplitShadowMap.disposeAllRenderTarget(); this._parallelSplitShadowMap=null; this.scene.removeShaderDefine(ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM1); this.scene.removeShaderDefine(ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM2); this.scene.removeShaderDefine(ParallelSplitShadowMap.SHADERDEFINE_SHADOW_PSSM3); } } /** *@inheritDoc */ __proto._addSelfRenderObjects=function(){ _super.prototype._addSelfRenderObjects.call(this); this._shadow && (this._initShadow()); } /** *@inheritDoc */ __proto._clearSelfRenderObjects=function(){ var scene=this.scene; var shaderValue=scene._shaderValues; shaderValue.setValue(/*laya.d3.core.scene.Scene.LIGHTDIRCOLOR*/4,null); shaderValue.setValue(/*laya.d3.core.scene.Scene.LIGHTDIRECTION*/3,null); scene.removeShaderDefine(ShaderCompile3D.SHADERDEFINE_DIRECTIONLIGHT); } /** *更新平行光相关渲染状态参数。 *@param state 渲染状态参数。 */ __proto._prepareToScene=function(state){ var scene=state.scene; if (scene.enableLight && this._activeInHierarchy){ var shaderValue=scene._shaderValues; scene.addShaderDefine(ShaderCompile3D.SHADERDEFINE_DIRECTIONLIGHT); Vector3.scale(this.color,this._intensity,this._intensityColor); shaderValue.setValue(/*laya.d3.core.scene.Scene.LIGHTDIRCOLOR*/4,this._intensityColor.elements); this.transform.worldMatrix.getForward(this._direction); Vector3.normalize(this._direction,this._direction); shaderValue.setValue(/*laya.d3.core.scene.Scene.LIGHTDIRECTION*/3,this._direction.elements); return true; }else { scene.removeShaderDefine(ShaderCompile3D.SHADERDEFINE_DIRECTIONLIGHT); return false; } } /** *@private */ __proto._onWorldMatrixChange=function(){ this._updateDirection=true; } /** *@inheritDoc */ __getset(0,__proto,'shadow',_super.prototype._$get_shadow,function(value){ if (this._shadow!==value){ this._shadow=value; (this.scene)&& (this._initShadow()); } }); /** *设置平行光的方向。 *@param value 平行光的方向。 */ /** *获取平行光的方向。 *@return 平行光的方向。 */ __getset(0,__proto,'direction',function(){ console.log("Warning: discard property,please use transform's property instead."); if (this._updateDirection){ this.transform.worldMatrix.getForward(this._direction); Vector3.normalize(this._direction,this._direction); this._updateDirection=false; } return this._direction; },function(value){ console.log("Warning: discard property,please use transform's property instead."); var worldMatrix=this.transform.worldMatrix; worldMatrix.setForward(value); this.transform.worldMatrix=worldMatrix; Vector3.normalize(value,value); this._direction=value; (this.shadow && this._parallelSplitShadowMap)&& (this._parallelSplitShadowMap._setGlobalParallelLightDir(this._direction)); }); return DirectionLight; })(LightSprite) /** *PointLight 类用于创建点光。 */ //class laya.d3.core.light.PointLight extends laya.d3.core.light.LightSprite var PointLight=(function(_super){ function PointLight(){ /**@private */ this._range=NaN; /**@private */ this._attenuation=null; PointLight.__super.call(this); this._range=6.0; this._attenuation=new Vector3(0.6,0.6,0.6); } __class(PointLight,'laya.d3.core.light.PointLight',_super); var __proto=PointLight.prototype; /** *@inheritDoc */ __proto._clearSelfRenderObjects=function(){ var scene=this.scene; var shaderValue=scene._shaderValues; shaderValue.setValue(/*laya.d3.core.scene.Scene.POINTLIGHTCOLOR*/8,null); shaderValue.setValue(/*laya.d3.core.scene.Scene.POINTLIGHTPOS*/5,null); shaderValue.setValue(/*laya.d3.core.scene.Scene.POINTLIGHTRANGE*/6,null); shaderValue.setValue(/*laya.d3.core.scene.Scene.POINTLIGHTATTENUATION*/7,null); scene.removeShaderDefine(ShaderCompile3D.SHADERDEFINE_POINTLIGHT); } /** *更新点光相关渲染状态参数。 *@param state 渲染状态参数。 */ __proto._prepareToScene=function(state){ var scene=state.scene; if (scene.enableLight && this._activeInHierarchy){ var shaderValue=scene._shaderValues; scene.addShaderDefine(ShaderCompile3D.SHADERDEFINE_POINTLIGHT); Vector3.scale(this.color,this._intensity,this._intensityColor); shaderValue.setValue(/*laya.d3.core.scene.Scene.POINTLIGHTCOLOR*/8,this._intensityColor.elements); shaderValue.setValue(/*laya.d3.core.scene.Scene.POINTLIGHTPOS*/5,this.transform.position.elements); shaderValue.setValue(/*laya.d3.core.scene.Scene.POINTLIGHTRANGE*/6,this.range); shaderValue.setValue(/*laya.d3.core.scene.Scene.POINTLIGHTATTENUATION*/7,this.attenuation.elements); return true; }else { scene.removeShaderDefine(ShaderCompile3D.SHADERDEFINE_POINTLIGHT); return false; } } /** *设置点光的范围。 *@param value 点光的范围。 */ /** *获取点光的范围。 *@return 点光的范围。 */ __getset(0,__proto,'range',function(){ return this._range; },function(value){ this._range=value; }); /** *设置点光的衰减。 *@param value 点光的衰减。 */ /** *获取点光的衰减。 *@return 点光的衰减。 */ __getset(0,__proto,'attenuation',function(){ return this._attenuation; },function(value){ this._attenuation=value; }); return PointLight; })(LightSprite) /** *SpotLight 类用于创建聚光。 */ //class laya.d3.core.light.SpotLight extends laya.d3.core.light.LightSprite var SpotLight=(function(_super){ function SpotLight(){ /**@private */ this._updateDirection=false; /**@private */ this._direction=null; /**@private */ this._spot=NaN; /**@private */ this._range=NaN; /**@private */ this._attenuation=null; SpotLight.__super.call(this); this._updateDirection=false; this.direction=new Vector3(0.0,-1.0,-1.0); this._attenuation=new Vector3(0.6,0.6,0.6); this._spot=96.0; this._range=6.0; this.transform.on(/*laya.events.Event.WORLDMATRIX_NEEDCHANGE*/"worldmatrixneedchanged",this,this._onWorldMatrixChange); } __class(SpotLight,'laya.d3.core.light.SpotLight',_super); var __proto=SpotLight.prototype; /** *@private */ __proto._onWorldMatrixChange=function(){ this._updateDirection=true; } /** *@inheritDoc */ __proto._clearSelfRenderObjects=function(){ var scene=this.scene; var shaderValue=scene._shaderValues; shaderValue.setValue(/*laya.d3.core.scene.Scene.SPOTLIGHTCOLOR*/14,null); shaderValue.setValue(/*laya.d3.core.scene.Scene.SPOTLIGHTPOS*/9,null); shaderValue.setValue(/*laya.d3.core.scene.Scene.SPOTLIGHTDIRECTION*/10,null); shaderValue.setValue(/*laya.d3.core.scene.Scene.SPOTLIGHTRANGE*/12,null); shaderValue.setValue(/*laya.d3.core.scene.Scene.SPOTLIGHTSPOT*/11,null); shaderValue.setValue(/*laya.d3.core.scene.Scene.SPOTLIGHTATTENUATION*/13,null); scene.removeShaderDefine(ShaderCompile3D.SHADERDEFINE_SPOTLIGHT); } /** *更新聚光相关渲染状态参数。 *@param state 渲染状态参数。 */ __proto._prepareToScene=function(state){ var scene=state.scene; if (scene.enableLight && this._activeInHierarchy){ var shaderValue=scene._shaderValues; scene.addShaderDefine(ShaderCompile3D.SHADERDEFINE_SPOTLIGHT); Vector3.scale(this.color,this._intensity,this._intensityColor); shaderValue.setValue(/*laya.d3.core.scene.Scene.SPOTLIGHTCOLOR*/14,this._intensityColor.elements); shaderValue.setValue(/*laya.d3.core.scene.Scene.SPOTLIGHTPOS*/9,this.transform.position.elements); this.transform.worldMatrix.getForward(this._direction); Vector3.normalize(this._direction,this._direction); shaderValue.setValue(/*laya.d3.core.scene.Scene.SPOTLIGHTDIRECTION*/10,this._direction.elements); shaderValue.setValue(/*laya.d3.core.scene.Scene.SPOTLIGHTRANGE*/12,this.range); shaderValue.setValue(/*laya.d3.core.scene.Scene.SPOTLIGHTSPOT*/11,this.spot); shaderValue.setValue(/*laya.d3.core.scene.Scene.SPOTLIGHTATTENUATION*/13,this.attenuation.elements); return true; }else { scene.removeShaderDefine(ShaderCompile3D.SHADERDEFINE_SPOTLIGHT); return false; } } /** *设置聚光的聚光值。 *@param value 聚光的聚光值。 */ /** *获取聚光的聚光值。 *@return 聚光的聚光值。 */ __getset(0,__proto,'spot',function(){ return this._spot; },function(value){ this._spot=value; }); /** *设置平行光的方向。 *@param value 平行光的方向。 */ /** *获取平行光的方向。 *@return 平行光的方向。 */ __getset(0,__proto,'direction',function(){ console.log("Warning: discard property,please use transform's property instead."); if (this._updateDirection){ this.transform.worldMatrix.getForward(this._direction); this._updateDirection=false; } return this._direction; },function(value){ console.log("Warning: discard property,please use transform's property instead."); var worldMatrix=this.transform.worldMatrix; worldMatrix.setForward(value); this.transform.worldMatrix=worldMatrix; this._direction=value; }); /** *设置聚光的范围。 *@param value 聚光的范围值。 */ /** *获取聚光的范围。 *@return 聚光的范围值。 */ __getset(0,__proto,'range',function(){ return this._range; },function(value){ this._range=value; }); /** *设置聚光的衰减。 *@param value 聚光的衰减。 */ /** *获取聚光的衰减。 *@return 聚光的衰减。 */ __getset(0,__proto,'attenuation',function(){ return this._attenuation; },function(value){ this._attenuation=value; }); return SpotLight; })(LightSprite) /** *MeshSprite3D 类用于创建网格。 */ //class laya.d3.core.MeshSprite3D extends laya.d3.core.RenderableSprite3D var MeshSprite3D=(function(_super){ /** *创建一个 MeshSprite3D 实例。 *@param mesh 网格,同时会加载网格所用默认材质。 *@param name 名字。 */ function MeshSprite3D(mesh,name){ MeshSprite3D.__super.call(this,name); this._geometryFilter=new MeshFilter(this); this._render=new MeshRender(this); this._geometryFilter.on(/*laya.events.Event.MESH_CHANGED*/"meshchanged",this,this._onMeshChanged); this._render.on(/*laya.events.Event.MATERIAL_CHANGED*/"materialchanged",this,this._onMaterialChanged); if (mesh){ (this._geometryFilter).sharedMesh=mesh; if ((mesh instanceof laya.d3.resource.models.Mesh )) if (mesh.loaded) this._render.sharedMaterials=(mesh).materials; else mesh.once(/*laya.events.Event.LOADED*/"loaded",this,this._applyMeshMaterials); } } __class(MeshSprite3D,'laya.d3.core.MeshSprite3D',_super); var __proto=MeshSprite3D.prototype; /** *@private */ __proto._changeRenderObjectByMesh=function(index){ var renderObjects=this._render._renderElements; var renderElement=renderObjects[index]; (renderElement)|| (renderElement=renderObjects[index]=new SubMeshRenderElement()); renderElement._render=this._render; var material=this._render.sharedMaterials[index]; (material)|| (material=StandardMaterial.defaultMaterial); var renderObj=(this._geometryFilter).sharedMesh.getRenderElement(index); renderElement._mainSortID=this._getSortID(renderObj,material); renderElement._sprite3D=this; renderElement.renderObj=renderObj; renderElement._material=material; return renderElement; } /** *@private */ __proto._changeRenderObjectByMaterial=function(index,material){ var renderElement=this._render._renderElements[index]; (material)|| (material=StandardMaterial.defaultMaterial); var renderObj=(this._geometryFilter).sharedMesh.getRenderElement(index); renderElement._mainSortID=this._getSortID(renderObj,material); renderElement._sprite3D=this; renderElement.renderObj=renderObj; renderElement._material=material; return renderElement; } /** *@private */ __proto._changeRenderObjectsByMesh=function(){ var renderElementsCount=(this._geometryFilter).sharedMesh.getRenderElementsCount(); this._render._renderElements.length=renderElementsCount; for (var i=0;i < renderElementsCount;i++) this._changeRenderObjectByMesh(i); } /** *@private */ __proto._onMeshChanged=function(meshFilter){ var mesh=meshFilter.sharedMesh; if (mesh.loaded) this._changeRenderObjectsByMesh(); else mesh.once(/*laya.events.Event.LOADED*/"loaded",this,this._onMeshLoaded); } /** *@private */ __proto._onMeshLoaded=function(sender){ (sender===this.meshFilter.sharedMesh)&& (this._changeRenderObjectsByMesh()); } /** *@private */ __proto._onMaterialChanged=function(meshRender,index,material){ var renderElementCount=this._render._renderElements.length; (index < renderElementCount)&& this._changeRenderObjectByMaterial(index,material); } /** *@inheritDoc */ __proto._clearSelfRenderObjects=function(){ this.scene.removeFrustumCullingObject(this._render); } /** *@inheritDoc */ __proto._addSelfRenderObjects=function(){ this.scene.addFrustumCullingObject(this._render); } /** *@inheritDoc */ __proto._parseCustomProps=function(rootNode,innerResouMap,customProps,json){ var render=this.meshRender; var lightmapIndex=customProps.lightmapIndex; (lightmapIndex !=null)&& (render.lightmapIndex=lightmapIndex); var lightmapScaleOffsetArray=customProps.lightmapScaleOffset; (lightmapScaleOffsetArray)&& (render.lightmapScaleOffset=new Vector4(lightmapScaleOffsetArray[0],lightmapScaleOffsetArray[1],lightmapScaleOffsetArray[2],lightmapScaleOffsetArray[3])); var meshPath,mesh; if (json.instanceParams){ meshPath=json.instanceParams.loadPath; if (meshPath){ mesh=Loader.getRes(innerResouMap[meshPath]); this.meshFilter.sharedMesh=mesh; if (mesh.loaded) render.sharedMaterials=mesh.materials; else mesh.once(/*laya.events.Event.LOADED*/"loaded",this,this._applyMeshMaterials); } }else { meshPath=customProps.meshPath; if (meshPath){ mesh=Loader.getRes(innerResouMap[meshPath]); this.meshFilter.sharedMesh=mesh; }; var materials=customProps.materials; if (materials){ var sharedMaterials=render.sharedMaterials; var materialCount=materials.length; sharedMaterials.length=materialCount; for (var i=0;i < materialCount;i++) sharedMaterials[i]=Loader.getRes(innerResouMap[materials[i].path]); render.sharedMaterials=sharedMaterials; } } } /** *@private */ __proto._applyMeshMaterials=function(mesh){ var shaderMaterials=this._render.sharedMaterials; var meshMaterials=mesh.materials; for (var i=0,n=meshMaterials.length;i < n;i++) (shaderMaterials[i])|| (shaderMaterials[i]=meshMaterials[i]); this._render.sharedMaterials=shaderMaterials; } /** *@inheritDoc */ __proto._addToInitStaticBatchManager=function(){ MeshSprite3D._staticBatchManager._addInitBatchSprite(this); } /** *@inheritDoc */ __proto.cloneTo=function(destObject){ var meshSprite3D=destObject; (meshSprite3D._geometryFilter).sharedMesh=(this._geometryFilter).sharedMesh; var meshRender=this._render; var destMeshRender=meshSprite3D._render; destMeshRender.enable=meshRender.enable; destMeshRender.sharedMaterials=meshRender.sharedMaterials; destMeshRender.castShadow=meshRender.castShadow; var lightmapScaleOffset=meshRender.lightmapScaleOffset; lightmapScaleOffset && (destMeshRender.lightmapScaleOffset=lightmapScaleOffset.clone()); destMeshRender.lightmapIndex=meshRender.lightmapIndex; destMeshRender.receiveShadow=meshRender.receiveShadow; destMeshRender.sortingFudge=meshRender.sortingFudge; laya.d3.core.Sprite3D.prototype.cloneTo.call(this,destObject); } /** *@inheritDoc */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); if (this.destroyed) return; var mesh=this.meshFilter.sharedMesh; (mesh.loaded)|| (mesh.off(/*laya.events.Event.LOADED*/"loaded",this,this._applyMeshMaterials)); _super.prototype.destroy.call(this,destroyChild); (this._geometryFilter)._destroy(); } /** *获取网格过滤器。 *@return 网格过滤器。 */ __getset(0,__proto,'meshFilter',function(){ return this._geometryFilter; }); /** *获取网格渲染器。 *@return 网格渲染器。 */ __getset(0,__proto,'meshRender',function(){ return this._render; }); MeshSprite3D.__init__=function(){ StaticBatchManager._staticBatchManagers.push(MeshSprite3D._staticBatchManager); } MeshSprite3D.load=function(url){ return Laya.loader.create(url,null,null,MeshSprite3D); } __static(MeshSprite3D, ['_staticBatchManager',function(){return this._staticBatchManager=new MeshSprite3DStaticBatchManager();} ]); return MeshSprite3D; })(RenderableSprite3D) /** *ShuriKenParticle3D 3D粒子。 */ //class laya.d3.core.particleShuriKen.ShuriKenParticle3D extends laya.d3.core.RenderableSprite3D var ShuriKenParticle3D=(function(_super){ /** *创建一个 Particle3D 实例。 *@param settings value 粒子配置。 */ function ShuriKenParticle3D(material){ ShuriKenParticle3D.__super.call(this); this._render=new ShurikenParticleRender(this); this._render.on(/*laya.events.Event.MATERIAL_CHANGED*/"materialchanged",this,this._onMaterialChanged); this._geometryFilter=new ShurikenParticleSystem(this); this._createRenderElement(0); (material)&& (this._render.sharedMaterial=material); } __class(ShuriKenParticle3D,'laya.d3.core.particleShuriKen.ShuriKenParticle3D',_super); var __proto=ShuriKenParticle3D.prototype; /** *@private */ __proto._initParticleVelocity=function(gradientData){ var gradient=new GradientDataNumber(); var velocitysData=gradientData.velocitys; for (var i=0,n=velocitysData.length;i < n;i++){ var valueData=velocitysData[i]; gradient.add(valueData.key,valueData.value); } return gradient; } /** *@private */ __proto._initParticleColor=function(gradientColorData){ var gradientColor=new GradientDataColor(); var alphasData=gradientColorData.alphas; var i=0,n=0; for (i=0,n=alphasData.length;i < n;i++){ var alphaData=alphasData[i]; gradientColor.addAlpha(alphaData.key,alphaData.value); }; var rgbsData=gradientColorData.rgbs; for (i=0,n=rgbsData.length;i < n;i++){ var rgbData=rgbsData[i]; var rgbValue=rgbData.value; gradientColor.addRGB(rgbData.key,new Vector3(rgbValue[0],rgbValue[1],rgbValue[2])); } return gradientColor; } /** *@private */ __proto._initParticleSize=function(gradientSizeData){ var gradientSize=new GradientDataNumber(); var sizesData=gradientSizeData.sizes; for (var i=0,n=sizesData.length;i < n;i++){ var valueData=sizesData[i]; gradientSize.add(valueData.key,valueData.value); } return gradientSize; } /** *@private */ __proto._initParticleRotation=function(gradientData){ var gradient=new GradientDataNumber(); var angularVelocitysData=gradientData.angularVelocitys; for (var i=0,n=angularVelocitysData.length;i < n;i++){ var valueData=angularVelocitysData[i]; gradient.add(valueData.key,valueData.value / 180.0 *Math.PI); } return gradient; } /** *@private */ __proto._initParticleFrame=function(overTimeFramesData){ var overTimeFrame=new GradientDataInt(); var framesData=overTimeFramesData.frames; for (var i=0,n=framesData.length;i < n;i++){ var frameData=framesData[i]; overTimeFrame.add(frameData.key,frameData.value); } return overTimeFrame; } /** *@private */ __proto._createRenderElement=function(index){ var elements=this._render._renderElements; var element=elements[index]=new RenderElement(); element._render=this._render; var material=this._render.sharedMaterials[index]; (material)|| (material=ShurikenParticleMaterial.defaultMaterial); var renderable=this._geometryFilter; element._mainSortID=0; element._sprite3D=this; element.renderObj=renderable; element._material=material; } /**@private */ __proto._onMaterialChanged=function(_particleRender,index,material){ var elements=_particleRender._renderElements; if (index < elements.length){ var element=elements[index]; element._material=material || ShurikenParticleMaterial.defaultMaterial; } } /**@private */ __proto._clearSelfRenderObjects=function(){ this.scene.removeFrustumCullingObject(this._render); } /**@private */ __proto._addSelfRenderObjects=function(){ this.scene.addFrustumCullingObject(this._render); } /** *@inheritDoc */ __proto._parseCustomProps=function(rootNode,innerResouMap,customProps,nodeData){ var anglelToRad=Math.PI / 180.0; var i=0,n=0; var particleRender=this.particleRender; var material; var materialData=customProps.material; if (materialData){ material=Loader.getRes(innerResouMap[materialData.path]); }else { var materialPath=customProps.materialPath; if (materialPath){ material=Loader.getRes(innerResouMap[materialPath]); }else { material=new ShurikenParticleMaterial(); material.diffuseTexture=innerResouMap ? Loader.getRes(innerResouMap[customProps.texturePath]):Texture2D.load(customProps.texturePath); } } particleRender.sharedMaterial=material; var meshPath=customProps.meshPath; (meshPath)&& (particleRender.mesh=Loader.getRes(innerResouMap[meshPath])); particleRender.renderMode=customProps.renderMode; particleRender.stretchedBillboardCameraSpeedScale=customProps.stretchedBillboardCameraSpeedScale; particleRender.stretchedBillboardSpeedScale=customProps.stretchedBillboardSpeedScale; particleRender.stretchedBillboardLengthScale=customProps.stretchedBillboardLengthScale; particleRender.sortingFudge=customProps.sortingFudge ? customProps.sortingFudge :0.0; var particleSystem=this.particleSystem; particleSystem.isPerformanceMode=customProps.isPerformanceMode; particleSystem.duration=customProps.duration; particleSystem.looping=customProps.looping; particleSystem.prewarm=customProps.prewarm; particleSystem.startDelayType=customProps.startDelayType; particleSystem.startDelay=customProps.startDelay; particleSystem.startDelayMin=customProps.startDelayMin; particleSystem.startDelayMax=customProps.startDelayMax; particleSystem.startLifetimeType=customProps.startLifetimeType; particleSystem.startLifetimeConstant=customProps.startLifetimeConstant; particleSystem.startLifeTimeGradient=ShuriKenParticle3D._initStartLife(customProps.startLifetimeGradient); particleSystem.startLifetimeConstantMin=customProps.startLifetimeConstantMin; particleSystem.startLifetimeConstantMax=customProps.startLifetimeConstantMax; particleSystem.startLifeTimeGradientMin=ShuriKenParticle3D._initStartLife(customProps.startLifetimeGradientMin); particleSystem.startLifeTimeGradientMax=ShuriKenParticle3D._initStartLife(customProps.startLifetimeGradientMax); particleSystem.startSpeedType=customProps.startSpeedType; particleSystem.startSpeedConstant=customProps.startSpeedConstant; particleSystem.startSpeedConstantMin=customProps.startSpeedConstantMin; particleSystem.startSpeedConstantMax=customProps.startSpeedConstantMax; particleSystem.threeDStartSize=customProps.threeDStartSize; particleSystem.startSizeType=customProps.startSizeType; particleSystem.startSizeConstant=customProps.startSizeConstant; var startSizeConstantSeparateArray=customProps.startSizeConstantSeparate; var startSizeConstantSeparateElement=particleSystem.startSizeConstantSeparate.elements; startSizeConstantSeparateElement[0]=startSizeConstantSeparateArray[0]; startSizeConstantSeparateElement[1]=startSizeConstantSeparateArray[1]; startSizeConstantSeparateElement[2]=startSizeConstantSeparateArray[2]; particleSystem.startSizeConstantMin=customProps.startSizeConstantMin; particleSystem.startSizeConstantMax=customProps.startSizeConstantMax; var startSizeConstantMinSeparateArray=customProps.startSizeConstantMinSeparate; var startSizeConstantMinSeparateElement=particleSystem.startSizeConstantMinSeparate.elements; startSizeConstantMinSeparateElement[0]=startSizeConstantMinSeparateArray[0]; startSizeConstantMinSeparateElement[1]=startSizeConstantMinSeparateArray[1]; startSizeConstantMinSeparateElement[2]=startSizeConstantMinSeparateArray[2]; var startSizeConstantMaxSeparateArray=customProps.startSizeConstantMaxSeparate; var startSizeConstantMaxSeparateElement=particleSystem.startSizeConstantMaxSeparate.elements; startSizeConstantMaxSeparateElement[0]=startSizeConstantMaxSeparateArray[0]; startSizeConstantMaxSeparateElement[1]=startSizeConstantMaxSeparateArray[1]; startSizeConstantMaxSeparateElement[2]=startSizeConstantMaxSeparateArray[2]; particleSystem.threeDStartRotation=customProps.threeDStartRotation; particleSystem.startRotationType=customProps.startRotationType; particleSystem.startRotationConstant=customProps.startRotationConstant *anglelToRad; var startRotationConstantSeparateArray=customProps.startRotationConstantSeparate; var startRotationConstantSeparateElement=particleSystem.startRotationConstantSeparate.elements; startRotationConstantSeparateElement[0]=startRotationConstantSeparateArray[0] *anglelToRad; startRotationConstantSeparateElement[1]=startRotationConstantSeparateArray[1] *anglelToRad; startRotationConstantSeparateElement[2]=startRotationConstantSeparateArray[2] *anglelToRad; particleSystem.startRotationConstantMin=customProps.startRotationConstantMin *anglelToRad; particleSystem.startRotationConstantMax=customProps.startRotationConstantMax *anglelToRad; var startRotationConstantMinSeparateArray=customProps.startRotationConstantMinSeparate; var startRotationConstantMinSeparateElement=particleSystem.startRotationConstantMinSeparate.elements; startRotationConstantMinSeparateElement[0]=startRotationConstantMinSeparateArray[0] *anglelToRad; startRotationConstantMinSeparateElement[1]=startRotationConstantMinSeparateArray[1] *anglelToRad; startRotationConstantMinSeparateElement[2]=startRotationConstantMinSeparateArray[2] *anglelToRad; var startRotationConstantMaxSeparateArray=customProps.startRotationConstantMaxSeparate; var startRotationConstantMaxSeparateElement=particleSystem.startRotationConstantMaxSeparate.elements; startRotationConstantMaxSeparateElement[0]=startRotationConstantMaxSeparateArray[0] *anglelToRad; startRotationConstantMaxSeparateElement[1]=startRotationConstantMaxSeparateArray[1] *anglelToRad; startRotationConstantMaxSeparateElement[2]=startRotationConstantMaxSeparateArray[2] *anglelToRad; particleSystem.randomizeRotationDirection=customProps.randomizeRotationDirection; particleSystem.startColorType=customProps.startColorType; var startColorConstantArray=customProps.startColorConstant; var startColorConstantElement=particleSystem.startColorConstant.elements; startColorConstantElement[0]=startColorConstantArray[0]; startColorConstantElement[1]=startColorConstantArray[1]; startColorConstantElement[2]=startColorConstantArray[2]; startColorConstantElement[3]=startColorConstantArray[3]; var startColorConstantMinArray=customProps.startColorConstantMin; var startColorConstantMinElement=particleSystem.startColorConstantMin.elements; startColorConstantMinElement[0]=startColorConstantMinArray[0]; startColorConstantMinElement[1]=startColorConstantMinArray[1]; startColorConstantMinElement[2]=startColorConstantMinArray[2]; startColorConstantMinElement[3]=startColorConstantMinArray[3]; var startColorConstantMaxArray=customProps.startColorConstantMax; var startColorConstantMaxElement=particleSystem.startColorConstantMax.elements; startColorConstantMaxElement[0]=startColorConstantMaxArray[0]; startColorConstantMaxElement[1]=startColorConstantMaxArray[1]; startColorConstantMaxElement[2]=startColorConstantMaxArray[2]; startColorConstantMaxElement[3]=startColorConstantMaxArray[3]; particleSystem.gravityModifier=customProps.gravityModifier; particleSystem.simulationSpace=customProps.simulationSpace; particleSystem.scaleMode=customProps.scaleMode; particleSystem.playOnAwake=customProps.playOnAwake; particleSystem.maxParticles=customProps.maxParticles; var autoRandomSeed=customProps.autoRandomSeed; (autoRandomSeed !=null)&& (particleSystem.autoRandomSeed=autoRandomSeed); var randomSeed=customProps.randomSeed; (randomSeed !=null)&& (particleSystem.randomSeed[0]=randomSeed); var emissionData=customProps.emission; var emission=particleSystem.emission; if (emissionData){ emission.emissionRate=emissionData.emissionRate; var burstsData=emissionData.bursts; if (burstsData) for (i=0,n=burstsData.length;i < n;i++){ var brust=burstsData[i]; emission.addBurst(new Burst(brust.time,brust.min,brust.max)); } emission.enbale=emissionData.enable; }else { emission.enbale=false; }; var shapeData=customProps.shape; if (shapeData){ var shape; switch (shapeData.shapeType){ case 0:; var sphereShape; shape=sphereShape=new SphereShape(); sphereShape.radius=shapeData.sphereRadius; sphereShape.emitFromShell=shapeData.sphereEmitFromShell; sphereShape.randomDirection=shapeData.sphereRandomDirection; break ; case 1:; var hemiSphereShape; shape=hemiSphereShape=new HemisphereShape(); hemiSphereShape.radius=shapeData.hemiSphereRadius; hemiSphereShape.emitFromShell=shapeData.hemiSphereEmitFromShell; hemiSphereShape.randomDirection=shapeData.hemiSphereRandomDirection; break ; case 2:; var coneShape; shape=coneShape=new ConeShape(); coneShape.angle=shapeData.coneAngle *anglelToRad; coneShape.radius=shapeData.coneRadius; coneShape.length=shapeData.coneLength; coneShape.emitType=shapeData.coneEmitType; coneShape.randomDirection=shapeData.coneRandomDirection; break ; case 3:; var boxShape; shape=boxShape=new BoxShape(); boxShape.x=shapeData.boxX; boxShape.y=shapeData.boxY; boxShape.z=shapeData.boxZ; boxShape.randomDirection=shapeData.boxRandomDirection; break ; case 7:; var circleShape; shape=circleShape=new CircleShape(); circleShape.radius=shapeData.circleRadius; circleShape.arc=shapeData.circleArc *anglelToRad; circleShape.emitFromEdge=shapeData.circleEmitFromEdge; circleShape.randomDirection=shapeData.circleRandomDirection; break ; default :; var tempShape; shape=tempShape=new CircleShape(); tempShape.radius=shapeData.circleRadius; tempShape.arc=shapeData.circleArc *anglelToRad; tempShape.emitFromEdge=shapeData.circleEmitFromEdge; tempShape.randomDirection=shapeData.circleRandomDirection; break ; } shape.enable=shapeData.enable; particleSystem.shape=shape; }; var velocityOverLifetimeData=customProps.velocityOverLifetime; if (velocityOverLifetimeData){ var velocityData=velocityOverLifetimeData.velocity; var velocity; switch (velocityData.type){ case 0:; var constantData=velocityData.constant; velocity=GradientVelocity.createByConstant(new Vector3(constantData[0],constantData[1],constantData[2])); break ; case 1: velocity=GradientVelocity.createByGradient(this._initParticleVelocity(velocityData.gradientX),this._initParticleVelocity(velocityData.gradientY),this._initParticleVelocity(velocityData.gradientZ)); break ; case 2:; var constantMinData=velocityData.constantMin; var constantMaxData=velocityData.constantMax; velocity=GradientVelocity.createByRandomTwoConstant(new Vector3(constantMinData[0],constantMinData[1],constantMinData[2]),new Vector3(constantMaxData[0],constantMaxData[1],constantMaxData[2])); break ; case 3: velocity=GradientVelocity.createByRandomTwoGradient(this._initParticleVelocity(velocityData.gradientXMin),this._initParticleVelocity(velocityData.gradientXMax),this._initParticleVelocity(velocityData.gradientYMin),this._initParticleVelocity(velocityData.gradientYMax),this._initParticleVelocity(velocityData.gradientZMin),this._initParticleVelocity(velocityData.gradientZMax)); break ; }; var velocityOverLifetime=new VelocityOverLifetime(velocity); velocityOverLifetime.space=velocityOverLifetimeData.space; velocityOverLifetime.enbale=velocityOverLifetimeData.enable; particleSystem.velocityOverLifetime=velocityOverLifetime; }; var colorOverLifetimeData=customProps.colorOverLifetime; if (colorOverLifetimeData){ var colorData=colorOverLifetimeData.color; var color; switch (colorData.type){ case 0:; var constColorData=colorData.constant; color=GradientColor.createByConstant(new Vector4(constColorData[0],constColorData[1],constColorData[2],constColorData[3])); break ; case 1: color=GradientColor.createByGradient(this._initParticleColor(colorData.gradient)); break ; case 2:; var minConstColorData=colorData.constantMin; var maxConstColorData=colorData.constantMax; color=GradientColor.createByRandomTwoConstant(new Vector4(minConstColorData[0],minConstColorData[1],minConstColorData[2],minConstColorData[3]),new Vector4(maxConstColorData[0],maxConstColorData[1],maxConstColorData[2],maxConstColorData[3])); break ; case 3: color=GradientColor.createByRandomTwoGradient(this._initParticleColor(colorData.gradientMin),this._initParticleColor(colorData.gradientMax)); break ; }; var colorOverLifetime=new ColorOverLifetime(color); colorOverLifetime.enbale=colorOverLifetimeData.enable; particleSystem.colorOverLifetime=colorOverLifetime; }; var sizeOverLifetimeData=customProps.sizeOverLifetime; if (sizeOverLifetimeData){ var sizeData=sizeOverLifetimeData.size; var size; switch (sizeData.type){ case 0: if (sizeData.separateAxes){ size=GradientSize.createByGradientSeparate(this._initParticleSize(sizeData.gradientX),this._initParticleSize(sizeData.gradientY),this._initParticleSize(sizeData.gradientZ)); }else { size=GradientSize.createByGradient(this._initParticleSize(sizeData.gradient)); } break ; case 1: if (sizeData.separateAxes){ var constantMinSeparateData=sizeData.constantMinSeparate; var constantMaxSeparateData=sizeData.constantMaxSeparate; size=GradientSize.createByRandomTwoConstantSeparate(new Vector3(constantMinSeparateData[0],constantMinSeparateData[1],constantMinSeparateData[2]),new Vector3(constantMaxSeparateData[0],constantMaxSeparateData[1],constantMaxSeparateData[2])); }else { size=GradientSize.createByRandomTwoConstant(sizeData.constantMin,sizeData.constantMax); } break ; case 2: if (sizeData.separateAxes){ size=GradientSize.createByRandomTwoGradientSeparate(this._initParticleSize(sizeData.gradientXMin),this._initParticleSize(sizeData.gradientYMin),this._initParticleSize(sizeData.gradientZMin),this._initParticleSize(sizeData.gradientXMax),this._initParticleSize(sizeData.gradientYMax),this._initParticleSize(sizeData.gradientZMax)); }else { size=GradientSize.createByRandomTwoGradient(this._initParticleSize(sizeData.gradientMin),this._initParticleSize(sizeData.gradientMax)); } break ; }; var sizeOverLifetime=new SizeOverLifetime(size); sizeOverLifetime.enbale=sizeOverLifetimeData.enable; particleSystem.sizeOverLifetime=sizeOverLifetime; }; var rotationOverLifetimeData=customProps.rotationOverLifetime; if (rotationOverLifetimeData){ var angularVelocityData=rotationOverLifetimeData.angularVelocity; var angularVelocity; switch (angularVelocityData.type){ case 0: if (angularVelocityData.separateAxes){ }else { angularVelocity=GradientAngularVelocity.createByConstant(angularVelocityData.constant *anglelToRad); } break ; case 1: if (angularVelocityData.separateAxes){ }else { angularVelocity=GradientAngularVelocity.createByGradient(this._initParticleRotation(angularVelocityData.gradient)); } break ; case 2: if (angularVelocityData.separateAxes){ var minSep=angularVelocityData.constantMinSeparate; var maxSep=angularVelocityData.constantMaxSeparate; angularVelocity=GradientAngularVelocity.createByRandomTwoConstantSeparate(new Vector3(minSep[0]*anglelToRad,minSep[1]*anglelToRad,minSep[2]*anglelToRad),new Vector3(maxSep[0]*anglelToRad,maxSep[1]*anglelToRad,maxSep[2]*anglelToRad)); }else { angularVelocity=GradientAngularVelocity.createByRandomTwoConstant(angularVelocityData.constantMin *anglelToRad,angularVelocityData.constantMax *anglelToRad); } break ; case 3: if (angularVelocityData.separateAxes){ }else { angularVelocity=GradientAngularVelocity.createByRandomTwoGradient(this._initParticleRotation(angularVelocityData.gradientMin),this._initParticleRotation(angularVelocityData.gradientMax)); } break ; }; var rotationOverLifetime=new RotationOverLifetime(angularVelocity); rotationOverLifetime.enbale=rotationOverLifetimeData.enable; particleSystem.rotationOverLifetime=rotationOverLifetime; }; var textureSheetAnimationData=customProps.textureSheetAnimation; if (textureSheetAnimationData){ var frameData=textureSheetAnimationData.frame; var frameOverTime; switch (frameData.type){ case 0: frameOverTime=FrameOverTime.createByConstant(frameData.constant); break ; case 1: frameOverTime=FrameOverTime.createByOverTime(this._initParticleFrame(frameData.overTime)); break ; case 2: frameOverTime=FrameOverTime.createByRandomTwoConstant(frameData.constantMin,frameData.constantMax); break ; case 3: frameOverTime=FrameOverTime.createByRandomTwoOverTime(this._initParticleFrame(frameData.overTimeMin),this._initParticleFrame(frameData.overTimeMax)); break ; }; var startFrameData=textureSheetAnimationData.startFrame; var startFrame; switch (startFrameData.type){ case 0: startFrame=StartFrame.createByConstant(startFrameData.constant); break ; case 1: startFrame=StartFrame.createByRandomTwoConstant(startFrameData.constantMin,startFrameData.constantMax); break ; }; var textureSheetAnimation=new TextureSheetAnimation(frameOverTime,startFrame); textureSheetAnimation.enable=textureSheetAnimationData.enable; var tilesData=textureSheetAnimationData.tiles; textureSheetAnimation.tiles=new Vector2(tilesData[0],tilesData[1]); textureSheetAnimation.type=textureSheetAnimationData.type; textureSheetAnimation.randomRow=textureSheetAnimationData.randomRow; var rowIndex=textureSheetAnimationData.rowIndex; (rowIndex!==undefined)&& (textureSheetAnimation.rowIndex=rowIndex); textureSheetAnimation.cycles=textureSheetAnimationData.cycles; particleSystem.textureSheetAnimation=textureSheetAnimation; } } /** *@inheritDoc */ __proto._activeHierarchy=function(){ laya.d3.core.Sprite3D.prototype._activeHierarchy.call(this); (this.particleSystem.playOnAwake)&& (this.particleSystem.play()); } /** *@inheritDoc */ __proto._inActiveHierarchy=function(){ laya.d3.core.Sprite3D.prototype._inActiveHierarchy.call(this); (this.particleSystem.isAlive)&& (this.particleSystem.simulate(0,true)); } /** *@private */ __proto.cloneTo=function(destObject){ var destShuriKenParticle3D=destObject; var destParticleSystem=destShuriKenParticle3D._geometryFilter; (this._geometryFilter).cloneTo(destParticleSystem); var destParticleRender=destShuriKenParticle3D._render; var particleRender=this._render; destParticleRender.sharedMaterials=particleRender.sharedMaterials; destParticleRender.enable=particleRender.enable; destParticleRender.renderMode=particleRender.renderMode; destParticleRender.mesh=particleRender.mesh; destParticleRender.stretchedBillboardCameraSpeedScale=particleRender.stretchedBillboardCameraSpeedScale; destParticleRender.stretchedBillboardSpeedScale=particleRender.stretchedBillboardSpeedScale; destParticleRender.stretchedBillboardLengthScale=particleRender.stretchedBillboardLengthScale; destParticleRender.sortingFudge=particleRender.sortingFudge; laya.d3.core.Sprite3D.prototype.cloneTo.call(this,destObject); } /** *

销毁此对象。

*@param destroyChild 是否同时销毁子节点,若值为true,则销毁子节点,否则不销毁子节点。 */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); if (this.destroyed) return; _super.prototype.destroy.call(this,destroyChild); (this._geometryFilter)._destroy(); this._geometryFilter=null; } /** *获取粒子系统。 *@return 粒子系统。 */ __getset(0,__proto,'particleSystem',function(){ return this._geometryFilter; }); /** *获取粒子渲染器。 *@return 粒子渲染器。 */ __getset(0,__proto,'particleRender',function(){ return this._render; }); ShuriKenParticle3D.__init__=function(){ ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_BILLBOARD=ShuriKenParticle3D.shaderDefines.registerDefine("SPHERHBILLBOARD"); ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_STRETCHEDBILLBOARD=ShuriKenParticle3D.shaderDefines.registerDefine("STRETCHEDBILLBOARD"); ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_HORIZONTALBILLBOARD=ShuriKenParticle3D.shaderDefines.registerDefine("HORIZONTALBILLBOARD"); ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_VERTICALBILLBOARD=ShuriKenParticle3D.shaderDefines.registerDefine("VERTICALBILLBOARD"); ShuriKenParticle3D.SHADERDEFINE_COLOROVERLIFETIME=ShuriKenParticle3D.shaderDefines.registerDefine("COLOROVERLIFETIME"); ShuriKenParticle3D.SHADERDEFINE_RANDOMCOLOROVERLIFETIME=ShuriKenParticle3D.shaderDefines.registerDefine("RANDOMCOLOROVERLIFETIME"); ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMECONSTANT=ShuriKenParticle3D.shaderDefines.registerDefine("VELOCITYOVERLIFETIMECONSTANT"); ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMECURVE=ShuriKenParticle3D.shaderDefines.registerDefine("VELOCITYOVERLIFETIMECURVE"); ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCONSTANT=ShuriKenParticle3D.shaderDefines.registerDefine("VELOCITYOVERLIFETIMERANDOMCONSTANT"); ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCURVE=ShuriKenParticle3D.shaderDefines.registerDefine("VELOCITYOVERLIFETIMERANDOMCURVE"); ShuriKenParticle3D.SHADERDEFINE_TEXTURESHEETANIMATIONCURVE=ShuriKenParticle3D.shaderDefines.registerDefine("TEXTURESHEETANIMATIONCURVE"); ShuriKenParticle3D.SHADERDEFINE_TEXTURESHEETANIMATIONRANDOMCURVE=ShuriKenParticle3D.shaderDefines.registerDefine("TEXTURESHEETANIMATIONRANDOMCURVE"); ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIME=ShuriKenParticle3D.shaderDefines.registerDefine("ROTATIONOVERLIFETIME"); ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMESEPERATE=ShuriKenParticle3D.shaderDefines.registerDefine("ROTATIONOVERLIFETIMESEPERATE"); ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMECONSTANT=ShuriKenParticle3D.shaderDefines.registerDefine("ROTATIONOVERLIFETIMECONSTANT"); ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMECURVE=ShuriKenParticle3D.shaderDefines.registerDefine("ROTATIONOVERLIFETIMECURVE"); ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCONSTANTS=ShuriKenParticle3D.shaderDefines.registerDefine("ROTATIONOVERLIFETIMERANDOMCURVES"); ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCURVES=ShuriKenParticle3D.shaderDefines.registerDefine("ROTATIONOVERLIFETIMERANDOMCURVES"); ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMECURVE=ShuriKenParticle3D.shaderDefines.registerDefine("SIZEOVERLIFETIMECURVE"); ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMECURVESEPERATE=ShuriKenParticle3D.shaderDefines.registerDefine("SIZEOVERLIFETIMECURVESEPERATE"); ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVES=ShuriKenParticle3D.shaderDefines.registerDefine("SIZEOVERLIFETIMERANDOMCURVES"); ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVESSEPERATE=ShuriKenParticle3D.shaderDefines.registerDefine("SIZEOVERLIFETIMERANDOMCURVESSEPERATE"); ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_MESH=ShuriKenParticle3D.shaderDefines.registerDefine("RENDERMODE_MESH"); ShuriKenParticle3D.SHADERDEFINE_SHAPE=ShuriKenParticle3D.shaderDefines.registerDefine("SHAPE"); } ShuriKenParticle3D.load=function(url){ return Laya.loader.create(url,null,null,ShuriKenParticle3D); } ShuriKenParticle3D._initStartLife=function(gradientData){ var gradient=new GradientDataNumber(); var startLifetimesData=gradientData.startLifetimes; for (var i=0,n=startLifetimesData.length;i < n;i++){ var valueData=startLifetimesData[i]; gradient.add(valueData.key,valueData.value); } return gradient; } ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_BILLBOARD=0; ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_STRETCHEDBILLBOARD=0; ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_HORIZONTALBILLBOARD=0; ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_VERTICALBILLBOARD=0; ShuriKenParticle3D.SHADERDEFINE_COLOROVERLIFETIME=0; ShuriKenParticle3D.SHADERDEFINE_RANDOMCOLOROVERLIFETIME=0; ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMECONSTANT=0; ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMECURVE=0; ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCONSTANT=0; ShuriKenParticle3D.SHADERDEFINE_VELOCITYOVERLIFETIMERANDOMCURVE=0; ShuriKenParticle3D.SHADERDEFINE_TEXTURESHEETANIMATIONCURVE=0; ShuriKenParticle3D.SHADERDEFINE_TEXTURESHEETANIMATIONRANDOMCURVE=0; ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIME=0; ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMESEPERATE=0; ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMECONSTANT=0; ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMECURVE=0; ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCONSTANTS=0; ShuriKenParticle3D.SHADERDEFINE_ROTATIONOVERLIFETIMERANDOMCURVES=0; ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMECURVE=0; ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMECURVESEPERATE=0; ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVES=0; ShuriKenParticle3D.SHADERDEFINE_SIZEOVERLIFETIMERANDOMCURVESSEPERATE=0; ShuriKenParticle3D.SHADERDEFINE_RENDERMODE_MESH=0; ShuriKenParticle3D.SHADERDEFINE_SHAPE=0; ShuriKenParticle3D.WORLDPOSITION=0; ShuriKenParticle3D.WORLDROTATION=1; ShuriKenParticle3D.POSITIONSCALE=4; ShuriKenParticle3D.SIZESCALE=5; ShuriKenParticle3D.SCALINGMODE=6; ShuriKenParticle3D.GRAVITY=7; ShuriKenParticle3D.THREEDSTARTROTATION=8; ShuriKenParticle3D.STRETCHEDBILLBOARDLENGTHSCALE=9; ShuriKenParticle3D.STRETCHEDBILLBOARDSPEEDSCALE=10; ShuriKenParticle3D.SIMULATIONSPACE=11; ShuriKenParticle3D.CURRENTTIME=12; ShuriKenParticle3D.VOLVELOCITYCONST=13; ShuriKenParticle3D.VOLVELOCITYGRADIENTX=14; ShuriKenParticle3D.VOLVELOCITYGRADIENTY=15; ShuriKenParticle3D.VOLVELOCITYGRADIENTZ=16; ShuriKenParticle3D.VOLVELOCITYCONSTMAX=17; ShuriKenParticle3D.VOLVELOCITYGRADIENTXMAX=18; ShuriKenParticle3D.VOLVELOCITYGRADIENTYMAX=19; ShuriKenParticle3D.VOLVELOCITYGRADIENTZMAX=20; ShuriKenParticle3D.VOLSPACETYPE=21; ShuriKenParticle3D.COLOROVERLIFEGRADIENTALPHAS=22; ShuriKenParticle3D.COLOROVERLIFEGRADIENTCOLORS=23; ShuriKenParticle3D.MAXCOLOROVERLIFEGRADIENTALPHAS=24; ShuriKenParticle3D.MAXCOLOROVERLIFEGRADIENTCOLORS=25; ShuriKenParticle3D.SOLSIZEGRADIENT=26; ShuriKenParticle3D.SOLSIZEGRADIENTX=27; ShuriKenParticle3D.SOLSIZEGRADIENTY=28; ShuriKenParticle3D.SOLSizeGradientZ=29; ShuriKenParticle3D.SOLSizeGradientMax=30; ShuriKenParticle3D.SOLSIZEGRADIENTXMAX=31; ShuriKenParticle3D.SOLSIZEGRADIENTYMAX=32; ShuriKenParticle3D.SOLSizeGradientZMAX=33; ShuriKenParticle3D.ROLANGULARVELOCITYCONST=34; ShuriKenParticle3D.ROLANGULARVELOCITYCONSTSEPRARATE=35; ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENT=36; ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTX=37; ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTY=38; ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTZ=39; ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTW=40; ShuriKenParticle3D.ROLANGULARVELOCITYCONSTMAX=41; ShuriKenParticle3D.ROLANGULARVELOCITYCONSTMAXSEPRARATE=42; ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTMAX=43; ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTXMAX=44; ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTYMAX=45; ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTZMAX=46; ShuriKenParticle3D.ROLANGULARVELOCITYGRADIENTWMAX=47; ShuriKenParticle3D.TEXTURESHEETANIMATIONCYCLES=48; ShuriKenParticle3D.TEXTURESHEETANIMATIONSUBUVLENGTH=49; ShuriKenParticle3D.TEXTURESHEETANIMATIONGRADIENTUVS=50; ShuriKenParticle3D.TEXTURESHEETANIMATIONGRADIENTMAXUVS=51; __static(ShuriKenParticle3D, ['shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(RenderableSprite3D.shaderDefines);} ]); return ShuriKenParticle3D; })(RenderableSprite3D) /** *SkinnedMeshSprite3D 类用于创建网格。 */ //class laya.d3.core.SkinnedMeshSprite3D extends laya.d3.core.RenderableSprite3D var SkinnedMeshSprite3D=(function(_super){ function SkinnedMeshSprite3D(mesh,name){ /**@private */ this._subMeshOffset=null; SkinnedMeshSprite3D.__super.call(this,name); this._subMeshOffset=[]; this._geometryFilter=new MeshFilter(this); this._render=new SkinnedMeshRender(this); this._geometryFilter.on(/*laya.events.Event.MESH_CHANGED*/"meshchanged",this,this._onMeshChanged); this._render.on(/*laya.events.Event.MATERIAL_CHANGED*/"materialchanged",this,this._onMaterialChanged); (mesh)&& ((this._geometryFilter).sharedMesh=mesh); } __class(SkinnedMeshSprite3D,'laya.d3.core.SkinnedMeshSprite3D',_super); var __proto=SkinnedMeshSprite3D.prototype; /** *@private */ __proto._changeRenderObjectByMesh=function(index){ var renderObjects=this._render._renderElements; var renderElement=renderObjects[index]; (renderElement)|| (renderElement=renderObjects[index]=new SubMeshRenderElement()); renderElement._render=this._render; var material=this._render.sharedMaterials[index]; (material)|| (material=StandardMaterial.defaultMaterial); var renderObj=(this._geometryFilter).sharedMesh.getRenderElement(index); renderElement._mainSortID=this._getSortID(renderObj,material); renderElement._sprite3D=this; renderElement.renderObj=renderObj; renderElement._material=material; return renderElement; } /** *@private */ __proto._changeRenderObjectByMaterial=function(index,material){ var renderElement=this._render._renderElements[index]; (material)|| (material=StandardMaterial.defaultMaterial); var renderObj=(this._geometryFilter).sharedMesh.getRenderElement(index); renderElement._mainSortID=this._getSortID(renderObj,material); renderElement._sprite3D=this; renderElement.renderObj=renderObj; renderElement._material=material; return renderElement; } /** *@private */ __proto._changeRenderObjectsByMesh=function(){ var renderElementsCount=(this._geometryFilter).sharedMesh.getRenderElementsCount(); this._render._renderElements.length=renderElementsCount; for (var i=0;i < renderElementsCount;i++) this._changeRenderObjectByMesh(i); } /** *@private */ __proto._onMeshChanged=function(meshFilter){ var mesh=meshFilter.sharedMesh; if (mesh.loaded) this._changeRenderObjectsByMesh(); else mesh.once(/*laya.events.Event.LOADED*/"loaded",this,this._changeRenderObjectsByMesh); } /** *@private */ __proto._onMaterialChanged=function(meshRender,index,material){ var renderElementCount=this._render._renderElements.length; (index < renderElementCount)&& this._changeRenderObjectByMaterial(index,material); } /** *@inheritDoc */ __proto._parseCustomProps=function(rootNode,innerResouMap,customProps,json){ var render=this.skinnedMeshRender; var lightmapIndex=customProps.lightmapIndex; (lightmapIndex !=null)&& (render.lightmapIndex=lightmapIndex); var lightmapScaleOffsetArray=customProps.lightmapScaleOffset; (lightmapScaleOffsetArray)&& (render.lightmapScaleOffset=new Vector4(lightmapScaleOffsetArray[0],lightmapScaleOffsetArray[1],lightmapScaleOffsetArray[2],lightmapScaleOffsetArray[3])); var meshPath,mesh; if (json.instanceParams){ meshPath=json.instanceParams.loadPath; if (meshPath){ mesh=Loader.getRes(innerResouMap[meshPath]); this.meshFilter.sharedMesh=mesh; if (mesh.loaded) render.sharedMaterials=mesh.materials; else mesh.once(/*laya.events.Event.LOADED*/"loaded",this,this._applyMeshMaterials); } }else { meshPath=customProps.meshPath; if (meshPath){ mesh=Loader.getRes(innerResouMap[meshPath]); this.meshFilter.sharedMesh=mesh; }; var materials=customProps.materials; if (materials){ var sharedMaterials=render.sharedMaterials; var materialCount=materials.length; sharedMaterials.length=materialCount; for (var i=0;i < materialCount;i++) sharedMaterials[i]=Loader.getRes(innerResouMap[materials[i].path]); render.sharedMaterials=sharedMaterials; }; var rootBone=customProps.rootBone; (rootBone)&& (render._setRootBone(rootBone)); var boundBox=customProps.boundBox; if (boundBox){ var min=boundBox.min; var max=boundBox.max; var localBoundBox=new BoundBox(new Vector3(min[0],min[1],min[2]),new Vector3(max[0],max[1],max[2])); render.localBoundBox=localBoundBox; }else { render._hasIndependentBound=false; }; var boundSphere=customProps.boundSphere; if (boundSphere){ var center=boundSphere.center; var localBoundSphere=new BoundSphere(new Vector3(center[0],center[1],center[2]),boundSphere.radius); render.localBoundSphere=localBoundSphere; } } } /** *@inheritDoc */ __proto._changeHierarchyAnimator=function(animator){ if (animator){ var render=this.skinnedMeshRender; render._setCacheAnimator(animator); var avatar=animator.avatar; (avatar)&& (render._setCacheAvatar(avatar)); } laya.d3.core.Sprite3D.prototype._changeHierarchyAnimator.call(this,animator); } /** *@inheritDoc */ __proto._clearSelfRenderObjects=function(){ this._scene.removeFrustumCullingObject(this._render); } /** *@inheritDoc */ __proto._addSelfRenderObjects=function(){ this._scene.addFrustumCullingObject(this._render); } /** *@private */ __proto._applyMeshMaterials=function(mesh){ var shaderMaterials=this._render.sharedMaterials; var meshMaterials=mesh.materials; for (var i=0,n=meshMaterials.length;i < n;i++) (shaderMaterials[i])|| (shaderMaterials[i]=meshMaterials[i]); this._render.sharedMaterials=shaderMaterials; } /** *@inheritDoc */ __proto.cloneTo=function(destObject){ var meshSprite3D=destObject; (meshSprite3D._geometryFilter).sharedMesh=(this._geometryFilter).sharedMesh; var meshRender=this._render; var destMeshRender=meshSprite3D._render; destMeshRender.enable=meshRender.enable; destMeshRender.sharedMaterials=meshRender.sharedMaterials; destMeshRender.castShadow=meshRender.castShadow; var lightmapScaleOffset=meshRender.lightmapScaleOffset; lightmapScaleOffset && (destMeshRender.lightmapScaleOffset=lightmapScaleOffset.clone()); destMeshRender.receiveShadow=meshRender.receiveShadow; destMeshRender.sortingFudge=meshRender.sortingFudge; destMeshRender._rootBone=meshRender._rootBone; var lbp=meshRender.localBoundSphere; (lbp)&& (destMeshRender.localBoundSphere=lbp.clone()); var lbb=meshRender.localBoundBox; (lbb)&& (destMeshRender.localBoundBox=lbb.clone()); destMeshRender._hasIndependentBound=meshRender._hasIndependentBound; laya.d3.core.Sprite3D.prototype.cloneTo.call(this,destObject); } /** *@inheritDoc */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); if (this.destroyed) return; _super.prototype.destroy.call(this,destroyChild); (this._geometryFilter)._destroy(); } /** *获取网格过滤器。 *@return 网格过滤器。 */ __getset(0,__proto,'meshFilter',function(){ return this._geometryFilter; }); /** *获取网格渲染器。 *@return 网格渲染器。 */ __getset(0,__proto,'skinnedMeshRender',function(){ return this._render; }); SkinnedMeshSprite3D.__init__=function(){ SkinnedMeshSprite3D.SHADERDEFINE_BONE=SkinnedMeshSprite3D.shaderDefines.registerDefine("BONE"); } SkinnedMeshSprite3D.load=function(url){ return Laya.loader.create(url,null,null,SkinnedMeshSprite3D); } SkinnedMeshSprite3D.SHADERDEFINE_BONE=0x8; SkinnedMeshSprite3D.BONES=0; __static(SkinnedMeshSprite3D, ['shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(RenderableSprite3D.shaderDefines);} ]); return SkinnedMeshSprite3D; })(RenderableSprite3D) /** *Camera 类用于创建VR摄像机。 */ //class laya.d3.core.VRCamera extends laya.d3.core.BaseCamera var VRCamera=(function(_super){ function VRCamera(pupilDistande,leftAspectRatio,rightAspectRatio,nearPlane,farPlane){ /**@private */ //this._tempMatrix=null; /**@private 左横纵比。*/ //this._leftAspectRatio=NaN; /**@private 在屏幕空间中摄像机的左视口。*/ //this._leftViewport=null; /**@private 在裁剪空间中摄像机的视口。*/ //this._leftNormalizedViewport=null; /**@private 左视图矩阵。*/ //this._leftViewMatrix=null; /**@private 左投影矩阵。*/ //this._leftProjectionMatrix=null; /**@private 左投影视图矩阵。*/ //this._leftProjectionViewMatrix=null; /**@private 左横纵比。*/ //this._rightAspectRatio=NaN; /**@private 在屏幕空间中摄像机的左视口。*/ //this._rightViewport=null; /**@private 在裁剪空间中摄像机的视口。*/ //this._rightNormalizedViewport=null; /**@private 左视图矩阵。*/ //this._rightViewMatrix=null; /**@private 左投影矩阵。*/ //this._rightProjectionMatrix=null; /**@private 左投影视图矩阵。*/ //this._rightProjectionViewMatrix=null; /**@private 瞳距。*/ //this._pupilDistande=0; /**@private */ //this._leftBoundFrustumUpdate=false; /**@private */ //this._rightBoundFrustumUpdate=false; /**@private */ //this._leftBoundFrustum=null; /**@private */ //this._rightBoundFrustum=null; (pupilDistande===void 0)&& (pupilDistande=0.1); (leftAspectRatio===void 0)&& (leftAspectRatio=0); (rightAspectRatio===void 0)&& (rightAspectRatio=0); (nearPlane===void 0)&& (nearPlane=0.3); (farPlane===void 0)&& (farPlane=1000); this._tempMatrix=new Matrix4x4(); this._leftViewMatrix=new Matrix4x4(); this._leftProjectionMatrix=new Matrix4x4(); this._leftProjectionViewMatrix=new Matrix4x4(); this._leftViewport=new Viewport(0,0,0,0); this._leftNormalizedViewport=new Viewport(0,0,0.5,1); this._leftAspectRatio=leftAspectRatio; this._rightViewMatrix=new Matrix4x4(); this._rightProjectionMatrix=new Matrix4x4(); this._rightProjectionViewMatrix=new Matrix4x4(); this._rightViewport=new Viewport(0,0,0,0); this._rightNormalizedViewport=new Viewport(0.5,0,0.5,1); this._rightAspectRatio=rightAspectRatio; this._pupilDistande=pupilDistande; this._leftBoundFrustumUpdate=true; this._leftBoundFrustum=new BoundFrustum(Matrix4x4.DEFAULT); this._rightBoundFrustumUpdate=true; this._rightBoundFrustum=new BoundFrustum(Matrix4x4.DEFAULT); VRCamera.__super.call(this,nearPlane,farPlane); this.transform.on(/*laya.events.Event.WORLDMATRIX_NEEDCHANGE*/"worldmatrixneedchanged",this,this._onWorldMatrixChanged); } __class(VRCamera,'laya.d3.core.VRCamera',_super); var __proto=VRCamera.prototype; /** *@private */ __proto._onWorldMatrixChanged=function(){ this._leftBoundFrustumUpdate=this._rightBoundFrustumUpdate=true; } /** *@private *计算瞳距。 */ __proto._calculatePupilOffset=function(){ var offset=this._tempVector3; Vector3.scale(this.right,this._pupilDistande / 2,offset); return offset.elements; } /** *@private *计算左投影矩阵。 */ __proto._calculateLeftProjectionMatrix=function(){ if (!this._useUserProjectionMatrix){ if (this._orthographic){ var leftHalfWidth=this.orthographicVerticalSize *this.leftAspectRatio *0.5; var leftHalfHeight=this.orthographicVerticalSize *0.5; Matrix4x4.createOrthoOffCenterRH(-leftHalfWidth,leftHalfWidth,-leftHalfHeight,leftHalfHeight,this.nearPlane,this.farPlane,this._leftProjectionMatrix); }else { Matrix4x4.createPerspective(3.1416 *this.fieldOfView / 180.0,this.leftAspectRatio,this.nearPlane,this.farPlane,this._rightProjectionMatrix); } } this._leftBoundFrustumUpdate=true; } /** *@private *计算右投影矩阵。 */ __proto._calculateRightProjectionMatrix=function(){ if (!this._useUserProjectionMatrix){ if (this._orthographic){ var rightHalfWidth=this.orthographicVerticalSize *this.rightAspectRatio *0.5; var rightHalfHeight=this.orthographicVerticalSize *0.5; Matrix4x4.createOrthoOffCenterRH(-rightHalfWidth,rightHalfWidth,rightHalfHeight,rightHalfHeight,this.nearPlane,this.farPlane,this._rightProjectionMatrix); }else { Matrix4x4.createPerspective(3.1416 *this.fieldOfView / 180.0,this.rightAspectRatio,this.nearPlane,this.farPlane,this._rightProjectionMatrix); } } this._rightBoundFrustumUpdate=true; } /** *@inheritDoc */ __proto._calculateProjectionMatrix=function(){ if (!this._useUserProjectionMatrix){ if (this._orthographic){ var leftHalfWidth=this.orthographicVerticalSize *this.leftAspectRatio *0.5; var leftHalfHeight=this.orthographicVerticalSize *0.5; var rightHalfWidth=this.orthographicVerticalSize *this.rightAspectRatio *0.5; var rightHalfHeight=this.orthographicVerticalSize *0.5; Matrix4x4.createOrthoOffCenterRH(-leftHalfWidth,leftHalfWidth,-leftHalfHeight,leftHalfHeight,this.nearPlane,this.farPlane,this._leftProjectionMatrix); Matrix4x4.createOrthoOffCenterRH(-rightHalfWidth,rightHalfWidth,rightHalfHeight,rightHalfHeight,this.nearPlane,this.farPlane,this._rightProjectionMatrix); }else { Matrix4x4.createPerspective(3.1416 *this.fieldOfView / 180.0,this.leftAspectRatio,this.nearPlane,this.farPlane,this._leftProjectionMatrix); Matrix4x4.createPerspective(3.1416 *this.fieldOfView / 180.0,this.rightAspectRatio,this.nearPlane,this.farPlane,this._rightProjectionMatrix); } } this._leftBoundFrustumUpdate=this._rightBoundFrustumUpdate=true; } /** *@inheritDoc */ __proto._renderCamera=function(gl,state,scene){ state.camera=this; this._prepareCameraToRender(); scene._preRenderUpdateComponents(state); var leftViewMat,leftProjectMatrix; leftViewMat=state._viewMatrix=this.leftViewMatrix; var renderTar=this._renderTarget; if (renderTar){ renderTar.start(); Matrix4x4.multiply(BaseCamera._invertYScaleMatrix,this._leftProjectionMatrix,BaseCamera._invertYProjectionMatrix); Matrix4x4.multiply(BaseCamera._invertYScaleMatrix,this.leftProjectionViewMatrix,BaseCamera._invertYProjectionViewMatrix); leftProjectMatrix=state._projectionMatrix=BaseCamera._invertYProjectionMatrix; state._projectionViewMatrix=BaseCamera._invertYProjectionViewMatrix; }else { leftProjectMatrix=state._projectionMatrix=this._leftProjectionMatrix; state._projectionViewMatrix=this.leftProjectionViewMatrix; } this._prepareCameraViewProject(leftViewMat,leftProjectMatrix); state._viewport=this.leftViewport; scene._preRenderScene(gl,state,this.leftBoundFrustum); scene._clear(gl,state); scene._renderScene(gl,state); var rightViewMat,rightProjectMatrix; rightViewMat=state._viewMatrix=this.rightViewMatrix; if (renderTar){ renderTar.start(); Matrix4x4.multiply(BaseCamera._invertYScaleMatrix,this._rightProjectionMatrix,BaseCamera._invertYProjectionMatrix); Matrix4x4.multiply(BaseCamera._invertYScaleMatrix,this.rightProjectionViewMatrix,BaseCamera._invertYProjectionViewMatrix); state._projectionMatrix=BaseCamera._invertYProjectionMatrix; rightProjectMatrix=state._projectionViewMatrix=BaseCamera._invertYProjectionViewMatrix; }else { rightProjectMatrix=state._projectionMatrix=this._rightProjectionMatrix; state._projectionViewMatrix=this.rightProjectionViewMatrix; } this._prepareCameraViewProject(rightViewMat,rightProjectMatrix); state._viewport=this.rightViewport; scene._preRenderScene(gl,state,this.rightBoundFrustum); scene._clear(gl,state); scene._renderScene(gl,state); scene._postRenderUpdateComponents(state); (renderTar)&& (renderTar.end()); } /** *获取摄像机右视锥。 */ __getset(0,__proto,'rightBoundFrustum',function(){ if (this._rightBoundFrustumUpdate) this._rightBoundFrustum.matrix=this.rightProjectionViewMatrix; return this._rightBoundFrustum; }); /** *获取裁剪空间的左视口。 *@return 裁剪空间的左视口。 */ __getset(0,__proto,'leftNormalizedViewport',function(){ if (!this._viewportExpressedInClipSpace){ var vp=this._leftViewport; var size=this.renderTargetSize; var sizeW=size.width; var sizeH=size.height; this._leftNormalizedViewport.x=vp.x / sizeW; this._leftNormalizedViewport.y=vp.y / sizeH; this._leftNormalizedViewport.width=vp.width / sizeW; this._leftNormalizedViewport.height=vp.height / sizeH; } return this._leftNormalizedViewport; }); /** *获取屏幕空间的右视口。 *@return 屏幕空间的右视口。 */ __getset(0,__proto,'rightViewport',function(){ if (this._viewportExpressedInClipSpace){ var nVp=this._rightNormalizedViewport; var size=this.renderTargetSize; var sizeW=size.width; var sizeH=size.height; this._rightViewport.x=nVp.x *sizeW; this._rightViewport.y=nVp.y *sizeH; this._rightViewport.width=nVp.width *sizeW; this._rightViewport.height=nVp.height *sizeH; } return this._rightViewport; }); /** *设置屏幕空间的视口。 *@param 屏幕空间的视口。 */ __getset(0,__proto,'viewport',null,function(value){ if (this.renderTarget !=null && (value.x < 0 || value.y < 0 || value.width==0 || value.height==0)) throw new Error("VRCamera: viewport size invalid.","value"); this._viewportExpressedInClipSpace=false; this._leftViewport=new Viewport(0,0,value.width / 2,value.height); this._rightViewport=new Viewport(value.width / 2,0,value.width / 2,value.height); this._calculateProjectionMatrix(); }); /** *获取左横纵比。 *@return 左横纵比。 */ __getset(0,__proto,'leftAspectRatio',function(){ if (this._leftAspectRatio===0){ var lVp=this.leftViewport; return lVp.width / lVp.height; } return this._leftAspectRatio; }); /** *获取右横纵比。 *@return 右横纵比。 */ __getset(0,__proto,'rightAspectRatio',function(){ if (this._rightAspectRatio===0){ var rVp=this.rightViewport; return rVp.width / rVp.height; } return this._rightAspectRatio; }); /** *设置横纵比。 *@param value 横纵比。 */ __getset(0,__proto,'aspectRatio',null,function(value){ if (value < 0) throw new Error("VRCamera: the aspect ratio has to be a positive real number."); this._leftAspectRatio=value; this._rightAspectRatio=value; this._calculateRightProjectionMatrix(); }); /** *获取裁剪空间的右视口。 *@return 裁剪空间的右视口。 */ __getset(0,__proto,'rightNormalizedViewport',function(){ if (!this._viewportExpressedInClipSpace){ var vp=this._rightViewport; var size=this.renderTargetSize; var sizeW=size.width; var sizeH=size.height; this._rightNormalizedViewport.x=vp.x / sizeW; this._rightNormalizedViewport.y=vp.y / sizeH; this._rightNormalizedViewport.width=vp.width / sizeW; this._rightNormalizedViewport.height=vp.height / sizeH; } return this._rightNormalizedViewport; }); /** *设置裁剪空间的视口。 *@return 裁剪空间的视口。 */ __getset(0,__proto,'normalizedViewport',null,function(value){ if (value.x < 0 || value.y < 0 || (value.x+value.width)> 1 || (value.x+value.height)> 1) throw new Error("VRCamera: viewport size invalid.","value"); this._viewportExpressedInClipSpace=true; this._leftNormalizedViewport=new Viewport(0,0,value.width / 2,value.height); this._rightNormalizedViewport=new Viewport(value.width / 2,0,value.width / 2,value.height); this._calculateProjectionMatrix(); }); /** *获取屏幕空间的左视口。 *@return 屏幕空间的左视口。 */ __getset(0,__proto,'leftViewport',function(){ if (this._viewportExpressedInClipSpace){ var nVp=this._leftNormalizedViewport; var size=this.renderTargetSize; var sizeW=size.width; var sizeH=size.height; this._leftViewport.x=nVp.x *sizeW; this._leftViewport.y=nVp.y *sizeH; this._leftViewport.width=nVp.width *sizeW; this._leftViewport.height=nVp.height *sizeH; } return this._leftViewport; }); __getset(0,__proto,'needLeftViewport',function(){ var nVp=this.leftNormalizedViewport; return nVp.x===0 && nVp.y===0 && nVp.width===1 && nVp.height===1; }); __getset(0,__proto,'needRightViewport',function(){ var nVp=this.rightNormalizedViewport; return nVp.x===0 && nVp.y===0 && nVp.width===1 && nVp.height===1; }); /** *获取左视图矩阵。 *@return 左视图矩阵。 */ __getset(0,__proto,'leftViewMatrix',function(){ var offsetE=this._calculatePupilOffset(); var tempWorldMat=this._tempMatrix; this.transform.worldMatrix.cloneTo(tempWorldMat); var worldMatE=tempWorldMat.elements; worldMatE[12]-=offsetE[0]; worldMatE[13]-=offsetE[1]; worldMatE[14]-=offsetE[2]; tempWorldMat.invert(this._leftViewMatrix); return this._leftViewMatrix; }); /** *获取右视图矩阵。 *@return 右视图矩阵。 */ __getset(0,__proto,'rightViewMatrix',function(){ var offsetE=this._calculatePupilOffset(); var tempWorldMat=this._tempMatrix; this.transform.worldMatrix.cloneTo(tempWorldMat); var worldMatE=tempWorldMat.elements; worldMatE[12]+=offsetE[0]; worldMatE[13]+=offsetE[1]; worldMatE[14]+=offsetE[2]; tempWorldMat.invert(this._rightViewMatrix); return this._rightViewMatrix; }); /** *获取左投影矩阵。 *@return 左投影矩阵。 */ __getset(0,__proto,'leftProjectionMatrix',function(){ return this._leftProjectionMatrix; }); /** *获取左投影视图矩阵。 *@return 左投影视图矩阵。 */ __getset(0,__proto,'leftProjectionViewMatrix',function(){ Matrix4x4.multiply(this.leftProjectionMatrix,this.leftViewMatrix,this._leftProjectionViewMatrix); return this._leftProjectionViewMatrix; }); /** *获取右投影矩阵。 *@return 右投影矩阵。 */ __getset(0,__proto,'rightProjectionMatrix',function(){ return this._rightProjectionMatrix; }); /** *获取右投影视图矩阵。 *@return 右投影视图矩阵。 */ __getset(0,__proto,'rightProjectionViewMatrix',function(){ Matrix4x4.multiply(this.rightProjectionMatrix,this.rightViewMatrix,this._rightProjectionViewMatrix); return this._rightProjectionViewMatrix; }); /** *获取摄像机左视锥。 */ __getset(0,__proto,'leftBoundFrustum',function(){ if (this._leftBoundFrustumUpdate) this._leftBoundFrustum.matrix=this.leftProjectionViewMatrix; return this._leftBoundFrustum; }); return VRCamera; })(BaseCamera) /** *... *@author ... */ //class laya.d3.core.trail.TrailSprite3D extends laya.d3.core.RenderableSprite3D var TrailSprite3D=(function(_super){ function TrailSprite3D(){ TrailSprite3D.__super.call(this); this._geometryFilter=new TrailFilter(this); this._render=new TrailRenderer(this); this._changeRenderObjectsByMaterial(this._render,0,TrailMaterial.defaultMaterial); this._render.on(/*laya.events.Event.MATERIAL_CHANGED*/"materialchanged",this,this._changeRenderObjectsByMaterial); this._geometryFilter.on(/*laya.events.Event.TRAIL_FILTER_CHANGE*/"trailfilterchange",this,this._changeRenderObjectsByRenderElement); } __class(TrailSprite3D,'laya.d3.core.trail.TrailSprite3D',_super); var __proto=TrailSprite3D.prototype; __proto._changeRenderObjectsByMaterial=function(sender,index,material){ var renderElementsCount=(this._geometryFilter).getRenderElementsCount(); this._render._renderElements.length=renderElementsCount; for (var i=0;i < renderElementsCount;i++){ this._changeRenderObjectByMaterial(i,material); } } __proto._changeRenderObjectByMaterial=function(index,material){ var renderObjects=this._render._renderElements; (material)|| (material=TrailMaterial.defaultMaterial); var renderElement=renderObjects[index]; (renderElement)|| (renderElement=renderObjects[index]=new RenderElement()); renderElement._sprite3D=this; renderElement.renderObj=(this._geometryFilter).getRenderElement(index); renderElement._render=this._render; renderElement._material=material; } __proto._changeRenderObjectsByRenderElement=function(index,trailRenderElement){ var renderObjects=this._render._renderElements; var renderElement=renderObjects[index]; (renderElement)|| (renderElement=renderObjects[index]=new RenderElement()); renderElement._sprite3D=this; renderElement.renderObj=trailRenderElement; renderElement._render=this._render; renderElement._material=this._render.sharedMaterial; } /**@private */ __proto._clearSelfRenderObjects=function(){ this.scene.removeFrustumCullingObject(this._render); } /**@private */ __proto._addSelfRenderObjects=function(){ this.scene.addFrustumCullingObject(this._render); } __proto._update=function(state){ _super.prototype._update.call(this,state); (this._geometryFilter)._update(state); } /** *@inheritDoc */ __proto._parseCustomProps=function(rootNode,innerResouMap,customProps,json){ var render=this._render; var filter=this._geometryFilter; var i=0,j=0; var materials=customProps.materials; if (materials){ var sharedMaterials=render.sharedMaterials; var materialCount=materials.length; sharedMaterials.length=materialCount; for (i=0;i < materialCount;i++) sharedMaterials[i]=Loader.getRes(innerResouMap[materials[i].path]); render.sharedMaterials=sharedMaterials; }; var props=json.props; filter.time=props.time; filter.minVertexDistance=props.minVertexDistance; filter.widthMultiplier=props.widthMultiplier; filter.textureMode=props.textureMode; var _widthCurve=[]; var widthCurve=customProps.widthCurve; for (i=0,j=widthCurve.length;i < j;i++){ var trailkeyframe=new TrailKeyFrame(); trailkeyframe.time=widthCurve[i].time; trailkeyframe.inTangent=widthCurve[i].inTangent; trailkeyframe.outTangent=widthCurve[i].outTangent; trailkeyframe.value=widthCurve[i].value; _widthCurve.push(trailkeyframe); } filter.widthCurve=_widthCurve; var colorGradientNode=customProps.colorGradient; var _colorGradient=new Gradient(); _colorGradient.mode=colorGradientNode.mode; var colorKeys=[]; var colorKey; var _colorKeys=colorGradientNode.colorKeys; var _colorKey; for (i=0,j=_colorKeys.length;i < j;i++){ _colorKey=_colorKeys[i]; colorKey=new GradientColorKey(new Color$1(_colorKey.value[0],_colorKey.value[1],_colorKey.value[2],1.0),_colorKey.time); colorKeys.push(colorKey); }; var alphaKeys=[]; var alphaKey; var _alphaKeys=colorGradientNode.alphaKeys; var _alphaKey; for (i=0,j=_alphaKeys.length;i < j;i++){ _alphaKey=_alphaKeys[i]; alphaKey=new GradientAlphaKey(_alphaKey.value,_alphaKey.time); alphaKeys.push(alphaKey); } _colorGradient.setKeys(colorKeys,alphaKeys); filter.colorGradient=_colorGradient; } __proto.reset=function(){ this.trailFilter.reset(); } /** *@inheritDoc */ __proto.cloneTo=function(destObject){ laya.d3.core.Sprite3D.prototype.cloneTo.call(this,destObject); var i=0,j=0; var _trailSprite3D=destObject; var _trailFilter=_trailSprite3D.trailFilter; _trailFilter.time=this.trailFilter.time; _trailFilter.minVertexDistance=this.trailFilter.minVertexDistance; _trailFilter.widthMultiplier=this.trailFilter.widthMultiplier; var widthCurve=this.trailFilter.widthCurve; var _widthCurve=[]; for (i=0,j=widthCurve.length;i < j;i++){ var _keyFrame=new TrailKeyFrame(); widthCurve[i].cloneTo(_keyFrame); _widthCurve.push(_keyFrame); } _trailFilter.widthCurve=_widthCurve; var _colorGradient=new Gradient(); this.trailFilter.colorGradient.cloneTo(_colorGradient); _trailFilter.colorGradient=_colorGradient; _trailFilter.textureMode=this.trailFilter.textureMode; var _trailRender=_trailSprite3D.trailRender; _trailRender.sharedMaterial=this.trailRender.sharedMaterial; } /** *

销毁此对象。

*@param destroyChild 是否同时销毁子节点,若值为true,则销毁子节点,否则不销毁子节点。 */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); if (this.destroyed) return; _super.prototype.destroy.call(this,destroyChild); (this._geometryFilter)._destroy(); this._geometryFilter=null; } /** *获取Trail过滤器。 *@return Trail过滤器。 */ __getset(0,__proto,'trailFilter',function(){ return this._geometryFilter; }); /** *获取Trail渲染器。 *@return Trail渲染器。 */ __getset(0,__proto,'trailRender',function(){ return this._render; }); TrailSprite3D.__init__=function(){ TrailSprite3D.SHADERDEFINE_GRADIENTMODE_BLEND=TrailSprite3D.shaderDefines.registerDefine("GRADIENTMODE_BLEND"); } TrailSprite3D.CURTIME=3; TrailSprite3D.LIFETIME=4; TrailSprite3D.WIDTHCURVE=5; TrailSprite3D.WIDTHCURVEKEYLENGTH=6; TrailSprite3D.GRADIENTCOLORKEY=7; TrailSprite3D.GRADIENTALPHAKEY=8; TrailSprite3D.SHADERDEFINE_GRADIENTMODE_BLEND=0; __static(TrailSprite3D, ['shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(RenderableSprite3D.shaderDefines);} ]); return TrailSprite3D; })(RenderableSprite3D) /** *... *@author */ //class laya.d3.extension.domino.DominoSprite3D extends laya.d3.core.RenderableSprite3D var DominoSprite3D=(function(_super){ function DominoSprite3D(){ DominoSprite3D.__super.call(this); this._defaultScale=new Vector3(0.4,1.0,0.12); this._geometryFilter=new DominoFilter(this); this._render=new DominoRenderer(this); this._changeRenderObjects(this._render,0,DominoMaterial.defaultMaterial); this._render.on(/*laya.events.Event.MATERIAL_CHANGED*/"materialchanged",this,this._changeRenderObjects); this._geometryFilter.on(/*laya.events.Event.DOMINO_FILTER_CHANGE*/"dominofilterchange",this,this._changeRenderObjectsByRenderElement); } __class(DominoSprite3D,'laya.d3.extension.domino.DominoSprite3D',_super); var __proto=DominoSprite3D.prototype; __proto.addDomino=function(position,rotation,scale){ (position===void 0)&& (position=Vector3.ZERO); (rotation===void 0)&& (rotation=Quaternion.DEFAULT); (scale===void 0)&& (scale=this._defaultScale); (this._geometryFilter).addDomino(position,rotation,scale); } __proto.updateDomino=function(index,position,rotation,scale){ (position===void 0)&& (position=Vector3.ZERO); (rotation===void 0)&& (rotation=Quaternion.DEFAULT); (scale===void 0)&& (scale=this._defaultScale); (this._geometryFilter).updateDomino(index,position,rotation,scale); } __proto.updateDominos=function(startIndex,count,keyFrames){ if (count > keyFrames.length){ throw Error("Update domino count can't more than keyFrames Count!"); } (this._geometryFilter).updateDominos(startIndex,count,keyFrames); } __proto._changeRenderObjects=function(sender,index,material){ var renderElementsCount=(this._geometryFilter).getDominoRenderElementsCount(); this._render._renderElements.length=renderElementsCount; for (var i=0;i < renderElementsCount;i++){ this._changeRenderObject(i,material); } } __proto._changeRenderObject=function(index,material){ var renderObjects=this._render._renderElements; (material)|| (material=DominoMaterial.defaultMaterial); var renderElement=renderObjects[index]; (renderElement)|| (renderElement=renderObjects[index]=new RenderElement()); renderElement._sprite3D=this; renderElement.renderObj=(this._geometryFilter).getRenderElement(index); renderElement._render=this._render; renderElement._material=material; } __proto._changeRenderObjectsByRenderElement=function(index,dominoRenderElement){ var renderObjects=this._render._renderElements; var renderElement=renderObjects[index]; (renderElement)|| (renderElement=renderObjects[index]=new RenderElement()); renderElement._sprite3D=this; renderElement.renderObj=dominoRenderElement; renderElement._render=this._render; renderElement._material=this._render.sharedMaterial ? this._render.sharedMaterial :DominoMaterial.defaultMaterial; } /**@private */ __proto._clearSelfRenderObjects=function(){ this.scene.removeFrustumCullingObject(this._render); } /**@private */ __proto._addSelfRenderObjects=function(){ this.scene.addFrustumCullingObject(this._render); } __proto._update=function(state){ _super.prototype._update.call(this,state); (this._geometryFilter)._update(state); } /** *获取多米诺过滤器。 *@return 多米诺过滤器。 */ __getset(0,__proto,'dominoFilter',function(){ return this._geometryFilter; }); /** *获取多米诺渲染器。 *@return 多米诺渲染器。 */ __getset(0,__proto,'dominoRender',function(){ return this._render; }); return DominoSprite3D; })(RenderableSprite3D) /** *... *@author */ //class laya.d3.extension.lineRender.LineSprite3D extends laya.d3.core.RenderableSprite3D var LineSprite3D=(function(_super){ function LineSprite3D(){ LineSprite3D.__super.call(this); this._position=new Vector3(); this._render=new LineRenderer(this); this._geometryFilter=new LineFilter(this); this._changeRenderObjects(this._render,0,LineMaterial.defaultMaterial); this._render.on(/*laya.events.Event.MATERIAL_CHANGED*/"materialchanged",this,this._changeRenderObjects); } __class(LineSprite3D,'laya.d3.extension.lineRender.LineSprite3D',_super); var __proto=LineSprite3D.prototype; __proto.addPosition=function(position,normal){ (this._geometryFilter).addPosition(position,normal); } __proto._changeRenderObjects=function(sender,index,material){ var renderObjects=this._render._renderElements; (material)|| (material=LineMaterial.defaultMaterial); var renderElement=renderObjects[index]; (renderElement)|| (renderElement=renderObjects[index]=new RenderElement()); renderElement._sprite3D=this; renderElement.renderObj=this._geometryFilter; renderElement._render=this._render; renderElement._material=material; } /**@private */ __proto._clearSelfRenderObjects=function(){ this.scene.removeFrustumCullingObject(this._render); } /**@private */ __proto._addSelfRenderObjects=function(){ this.scene.addFrustumCullingObject(this._render); } __proto._update=function(state){ _super.prototype._update.call(this,state); (this._geometryFilter)._update(state); } /** *@inheritDoc */ __proto._parseCustomProps=function(rootNode,innerResouMap,customProps,json){ var render=this._render; var filter=this._geometryFilter; var i=0,j=0; var materials=customProps.materials; if (materials){ var sharedMaterials=render.sharedMaterials; var materialCount=materials.length; sharedMaterials.length=materialCount; for (i=0;i < materialCount;i++) sharedMaterials[i]=Loader.getRes(innerResouMap[materials[i].path]); render.sharedMaterials=sharedMaterials; }; var props=json.props; filter.widthMultiplier=props.widthMultiplier; filter.textureMode=props.textureMode; var _widthCurve=[]; var widthCurve=customProps.widthCurve; for (i=0,j=widthCurve.length;i < j;i++){ var trailkeyframe=new TrailKeyFrame(); trailkeyframe.time=widthCurve[i].time; trailkeyframe.inTangent=widthCurve[i].inTangent; trailkeyframe.outTangent=widthCurve[i].outTangent; trailkeyframe.value=widthCurve[i].value; _widthCurve.push(trailkeyframe); } filter.widthCurve=_widthCurve; var colorGradientNode=customProps.colorGradient; var _colorGradient=new Gradient(); _colorGradient.mode=colorGradientNode.mode; var colorKeys=[]; var colorKey; var _colorKeys=colorGradientNode.colorKeys; var _colorKey; for (i=0,j=_colorKeys.length;i < j;i++){ _colorKey=_colorKeys[i]; colorKey=new GradientColorKey(new Color$1(_colorKey.value[0],_colorKey.value[1],_colorKey.value[2],1.0),_colorKey.time); colorKeys.push(colorKey); }; var alphaKeys=[]; var alphaKey; var _alphaKeys=colorGradientNode.alphaKeys; var _alphaKey; for (i=0,j=_alphaKeys.length;i < j;i++){ _alphaKey=_alphaKeys[i]; alphaKey=new GradientAlphaKey(_alphaKey.value,_alphaKey.time); alphaKeys.push(alphaKey); } _colorGradient.setKeys(colorKeys,alphaKeys); filter.colorGradient=_colorGradient; var positions=customProps.positions; var positionSize=positions.size; var positionsValue=positions.values; var position; for (i=0;i < positionSize;i++){ position=positionsValue[i]; this._position.x=position[0]; this._position.y=position[1]; this._position.z=position[2]; this.addPosition(this._position); } } /** *@inheritDoc */ __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); if (this.destroyed) return; _super.prototype.destroy.call(this,destroyChild); (this._geometryFilter)._destroy(); this._position=null; } /** *获取line过滤器。 *@return line过滤器。 */ __getset(0,__proto,'lineFilter',function(){ return this._geometryFilter; }); /** *获取line渲染器。 *@return line渲染器。 */ __getset(0,__proto,'lineRender',function(){ return this._render; }); LineSprite3D.__init__=function(){ LineSprite3D.SHADERDEFINE_GRADIENTMODE_BLEND=LineSprite3D.shaderDefines.registerDefine("GRADIENTMODE_BLEND"); LineSprite3D.SHADERDEFINE_TEXTUREMODE_STRETCH=LineSprite3D.shaderDefines.registerDefine("TEXTUREMODE"); LineSprite3D.SHADERDEFINE_WORLDSPACE=LineSprite3D.shaderDefines.registerDefine("WORLDSPACE"); } LineSprite3D.WIDTHCURVE=3; LineSprite3D.WIDTHCURVEKEYLENGTH=4; LineSprite3D.GRADIENTCOLORKEY=5; LineSprite3D.GRADIENTALPHAKEY=6; LineSprite3D.SHADERDEFINE_WORLDSPACE=0; LineSprite3D.SHADERDEFINE_GRADIENTMODE_BLEND=0; LineSprite3D.SHADERDEFINE_TEXTUREMODE_STRETCH=0; __static(LineSprite3D, ['shaderDefines',function(){return this.shaderDefines=new ShaderDefines$1(RenderableSprite3D.shaderDefines);} ]); return LineSprite3D; })(RenderableSprite3D) /** *TerrainChunk 类用于创建地块。 */ //class laya.d3.terrain.TerrainChunk extends laya.d3.core.RenderableSprite3D var TerrainChunk=(function(_super){ /** *创建一个 MeshSprite3D 实例。 *@param mesh 网格,同时会加载网格所用默认材质。 *@param name 名字。 */ function TerrainChunk(chunkOffsetX,chunkOffsetZ,girdSize,terrainHeightData,heightDataWidth,heightDataHeight,cameraCoordinateInverse,name){ TerrainChunk.__super.call(this,name); this._geometryFilter=new TerrainFilter(this,chunkOffsetX,chunkOffsetZ,girdSize,terrainHeightData,heightDataWidth,heightDataHeight,cameraCoordinateInverse); this._render=new TerrainRender(this); } __class(TerrainChunk,'laya.d3.terrain.TerrainChunk',_super); var __proto=TerrainChunk.prototype; __proto.buildRenderElementAndMaterial=function(detailNum,normalMap,alphaMapUrl,detailUrl1,detailUrl2,detailUrl3,detailUrl4,ambientColor,diffuseColor,specularColor,sx1,sy1,sx2,sy2,sx3,sy3,sx4,sy4){ (sx1===void 0)&& (sx1=1); (sy1===void 0)&& (sy1=1); (sx2===void 0)&& (sx2=1); (sy2===void 0)&& (sy2=1); (sx3===void 0)&& (sx3=1); (sy3===void 0)&& (sy3=1); (sx4===void 0)&& (sx4=1); (sy4===void 0)&& (sy4=1); var terrainMaterial=new TerrainMaterial(); if (diffuseColor)terrainMaterial.diffuseColor=diffuseColor; if (ambientColor)terrainMaterial.ambientColor=ambientColor; if (specularColor)terrainMaterial.specularColor=specularColor; terrainMaterial.splatAlphaTexture=Loader.getRes(alphaMapUrl); terrainMaterial.normalTexture=normalMap ? Loader.getRes(normalMap):null; terrainMaterial.diffuseTexture1=detailUrl1 ? Loader.getRes(detailUrl1):null; terrainMaterial.diffuseTexture2=detailUrl2 ? Loader.getRes(detailUrl2):null; terrainMaterial.diffuseTexture3=detailUrl3 ? Loader.getRes(detailUrl3):null; terrainMaterial.diffuseTexture4=detailUrl4 ? Loader.getRes(detailUrl4):null; terrainMaterial.setDiffuseScale1(sx1,sy1); terrainMaterial.setDiffuseScale2(sx2,sy2); terrainMaterial.setDiffuseScale3(sx3,sy3); terrainMaterial.setDiffuseScale4(sx4,sy4); terrainMaterial.setDetailNum(detailNum); if (this._render._renderElements.length !=0){ terrainMaterial.renderMode=/*laya.d3.core.material.TerrainMaterial.RENDERMODE_TRANSPARENT*/2; }; var renderElement=new RenderElement(); renderElement._mainSortID=0; renderElement._sprite3D=this; renderElement.renderObj=this._geometryFilter; renderElement._material=terrainMaterial; this._render._materials.push(terrainMaterial); this._render._renderElements.push(renderElement); } /** *@private */ __proto._clearSelfRenderObjects=function(){ this.scene.removeFrustumCullingObject(this._render); } /** *@private */ __proto._addSelfRenderObjects=function(){ this.scene.addFrustumCullingObject(this._render); } /** *@private */ __proto._applyMeshMaterials=function(mesh){ var shaderMaterials=this._render.sharedMaterials; var meshMaterials=mesh.materials; for (var i=0,n=meshMaterials.length;i < n;i++) (shaderMaterials[i])|| (shaderMaterials[i]=meshMaterials[i]); this._render.sharedMaterials=shaderMaterials; } __proto.cloneTo=function(destObject){ console.log("Terrain Chunk can't clone"); } __proto.destroy=function(destroyChild){ (destroyChild===void 0)&& (destroyChild=true); if (this.destroyed) return; _super.prototype.destroy.call(this,destroyChild); (this._geometryFilter)._destroy(); } /** *获取地形过滤器。 *@return 地形过滤器。 */ __getset(0,__proto,'terrainFilter',function(){ return this._geometryFilter; }); /** *获取地形渲染器。 *@return 地形渲染器。 */ __getset(0,__proto,'terrainRender',function(){ return this._render; }); TerrainChunk.load=function(url){ return Laya.loader.create(url,null,null,TerrainChunk,null,1,false); } return TerrainChunk; })(RenderableSprite3D) /** *TerrainMeshSprite3D 类用于创建网格。 */ //class laya.d3.core.MeshTerrainSprite3D extends laya.d3.core.MeshSprite3D var MeshTerrainSprite3D=(function(_super){ function MeshTerrainSprite3D(mesh,heightMap,name){ /**@private */ this._minX=NaN; /**@private */ this._minZ=NaN; /**@private */ this._cellSize=null; /**@private */ this._heightMap=null; MeshTerrainSprite3D.__super.call(this,mesh,name); this._heightMap=heightMap; this._cellSize=new Vector2(); } __class(MeshTerrainSprite3D,'laya.d3.core.MeshTerrainSprite3D',_super); var __proto=MeshTerrainSprite3D.prototype; /** *@private */ __proto._disableRotation=function(){ var rotation=this.transform.rotation; rotation.elements[0]=0; rotation.elements[1]=0; rotation.elements[2]=0; rotation.elements[3]=1; this.transform.rotation=rotation; } /** *@private */ __proto._getScaleX=function(){ var worldMat=this.transform.worldMatrix; var worldMatE=worldMat.elements; var m11=worldMatE[0]; var m12=worldMatE[1]; var m13=worldMatE[2]; return Math.sqrt((m11 *m11)+(m12 *m12)+(m13 *m13)); } /** *@private */ __proto._getScaleZ=function(){ var worldMat=this.transform.worldMatrix; var worldMatE=worldMat.elements; var m31=worldMatE[8]; var m32=worldMatE[9]; var m33=worldMatE[10]; return Math.sqrt((m31 *m31)+(m32 *m32)+(m33 *m33)); } /** *@private */ __proto._initCreateFromMesh=function(heightMapWidth,heightMapHeight){ this._heightMap=HeightMap.creatFromMesh(this.meshFilter.sharedMesh,heightMapWidth,heightMapHeight,this._cellSize); var boundingBox=this.meshFilter.sharedMesh.boundingBox; var min=boundingBox.min; var max=boundingBox.max; this._minX=min.x; this._minZ=min.z; } /** *@private */ __proto._initCreateFromMeshHeightMap=function(texture,minHeight,maxHeight){ var _$this=this; var boundingBox=this.meshFilter.sharedMesh.boundingBox; if (texture.loaded){ this._heightMap=HeightMap.createFromImage(texture,minHeight,maxHeight); this._computeCellSize(boundingBox); }else { texture.once(/*laya.events.Event.LOADED*/"loaded",null,function(){ _$this._heightMap=HeightMap.createFromImage(texture,minHeight,maxHeight); _$this._computeCellSize(boundingBox); }); }; var min=boundingBox.min; var max=boundingBox.max; this._minX=min.x; this._minZ=min.z; } /** *@private */ __proto._computeCellSize=function(boundingBox){ var min=boundingBox.min; var max=boundingBox.max; var minX=min.x; var minZ=min.z; var maxX=max.x; var maxZ=max.z; var widthSize=maxX-minX; var heightSize=maxZ-minZ; this._cellSize.elements[0]=widthSize / (this._heightMap.width-1); this._cellSize.elements[1]=heightSize / (this._heightMap.height-1); } /** *@private */ __proto._update=function(state){ this._disableRotation(); laya.d3.core.RenderableSprite3D.prototype._update.call(this,state); } /** *获取地形高度。 *@param x X轴坐标。 *@param z Z轴坐标。 */ __proto.getHeight=function(x,z){ MeshTerrainSprite3D._tempVector3.elements[0]=x; MeshTerrainSprite3D._tempVector3.elements[1]=0; MeshTerrainSprite3D._tempVector3.elements[2]=z; this._disableRotation(); var worldMat=this.transform.worldMatrix; worldMat.invert(MeshTerrainSprite3D._tempMatrix4x4); Vector3.transformCoordinate(MeshTerrainSprite3D._tempVector3,MeshTerrainSprite3D._tempMatrix4x4,MeshTerrainSprite3D._tempVector3); x=MeshTerrainSprite3D._tempVector3.elements[0]; z=MeshTerrainSprite3D._tempVector3.elements[2]; var c=(x-this._minX)/ this._cellSize.x; var d=(z-this._minZ)/ this._cellSize.y; var row=Math.floor(d); var col=Math.floor(c); var s=c-col; var t=d-row; var uy=NaN; var vy=NaN; var worldMatE=worldMat.elements; var m21=worldMatE[4]; var m22=worldMatE[5]; var m23=worldMatE[6]; var scaleY=Math.sqrt((m21 *m21)+(m22 *m22)+(m23 *m23)); var translateY=worldMatE[13]; var h01=this._heightMap.getHeight(row,col+1); var h10=this._heightMap.getHeight((row+1),col); if (isNaN(h01)|| isNaN(h10)) return NaN; if (s+t <=1.0){ var h00=this._heightMap.getHeight(row,col); if (isNaN(h00)) return NaN; uy=h01-h00; vy=h10-h00; return (h00+s *uy+t *vy)*scaleY+translateY; }else { var h11=this._heightMap.getHeight((row+1),col+1); if (isNaN(h11)) return NaN; uy=h10-h11; vy=h01-h11; return (h11+(1.0-s)*uy+(1.0-t)*vy)*scaleY+translateY; } } /** *获取地形X轴最小位置。 *@return 地形X轴最小位置。 */ __getset(0,__proto,'minX',function(){ var worldMat=this.transform.worldMatrix; var worldMatE=worldMat.elements; return this._minX *this._getScaleX()+worldMatE[12]; }); /** *获取地形X轴长度。 *@return 地形X轴长度。 */ __getset(0,__proto,'width',function(){ return (this._heightMap.width-1)*this._cellSize.x *this._getScaleX(); }); /** *获取地形Z轴最小位置。 *@return 地形X轴最小位置。 */ __getset(0,__proto,'minZ',function(){ var worldMat=this.transform.worldMatrix; var worldMatE=worldMat.elements; return this._minZ *this._getScaleZ()+worldMatE[14]; }); /** *获取地形Z轴长度。 *@return 地形Z轴长度。 */ __getset(0,__proto,'depth',function(){ return (this._heightMap.height-1)*this._cellSize.y *this._getScaleZ(); }); MeshTerrainSprite3D.createFromMesh=function(mesh,heightMapWidth,heightMapHeight,name){ var meshTerrainSprite3D=new MeshTerrainSprite3D(mesh,null,name); if (mesh.loaded) meshTerrainSprite3D._initCreateFromMesh(heightMapWidth,heightMapHeight); else mesh.once(/*laya.events.Event.LOADED*/"loaded",meshTerrainSprite3D,meshTerrainSprite3D._initCreateFromMesh,[heightMapWidth,heightMapHeight]); return meshTerrainSprite3D; } MeshTerrainSprite3D.createFromMeshAndHeightMap=function(mesh,texture,minHeight,maxHeight,name){ var meshTerrainSprite3D=new MeshTerrainSprite3D(mesh,null,name); if (mesh.loaded) meshTerrainSprite3D._initCreateFromMeshHeightMap(texture,minHeight,maxHeight); else mesh.once(/*laya.events.Event.LOADED*/"loaded",meshTerrainSprite3D,meshTerrainSprite3D._initCreateFromMeshHeightMap,[texture,minHeight,maxHeight]); return meshTerrainSprite3D; } __static(MeshTerrainSprite3D, ['_tempVector3',function(){return this._tempVector3=new Vector3();},'_tempMatrix4x4',function(){return this._tempMatrix4x4=new Matrix4x4();} ]); return MeshTerrainSprite3D; })(MeshSprite3D) /** *... *@author ... */ //class laya.d3.water.WaterSprite extends laya.d3.core.MeshSprite3D var WaterSprite=(function(_super){ function WaterSprite(mesh,name){ this.mtl=null; this.detailMtl=null; this.mesh=null; this.useRefrTex=true; this.renderDetailWav=true; this._stop=false; this._texWave=null; this._texRefract=null; this._detailMesh=null; //贴图纹理的旋转矩阵 this._texWaveDegTest=0; this._shownormal=false; this._refractQueue=null; this._waterLoaded=false; this._waterFogStart=0; this._waterFogRange=20; this.startTm=0; this.curTm=0; this._syncObj=null; this.afterDescLoaded=null; this._geoWaveInfo=new Float32Array(WaterSprite._waveInfoEleNum *4); this._geoWaveInfoDir=new Float32Array(2 *4); this._texWaveInfo=new Float32Array(WaterSprite._waveInfoEleNum *15); this._texWaveInfoDir=new Float32Array(2 *15); this._texWaveTrans=new Float32Array(9); this._refractObjStack=[]; this._refractObjecs=[]; this._scrSizeInfo=new Float32Array(2); this._waterColor=new Vector3(); WaterSprite.__super.call(this,mesh,name); this.mtl=new WaterMaterial(); this.startTm=Laya.timer.currTimer; this.curTm=0; } __class(WaterSprite,'laya.d3.water.WaterSprite',_super); var __proto=WaterSprite.prototype; __proto._getWaveInfo=function(out,outdir,i,deg,L,Q,A){ var st=i *WaterSprite._waveInfoEleNum; var dirst=i *2; var r=deg *WaterSprite.deg2rad; outdir[dirst++]=Math.cos(r); outdir[dirst++]=Math.sin(r); out[st++]=Q; out[st++]=A; out[st++]=WaterSprite._2pi / L; out[st++]=7.846987702957 / Math.sqrt(L); } __proto.onDescLoaded=function(desc){ var _$this=this; var mesh=Mesh.load(desc.mesh); this._texWave=new RenderTexture(desc.detailTexSize[0],desc.detailTexSize[1],/*laya.webgl.WebGLContext.RGBA*/0x1908,/*laya.webgl.WebGLContext.UNSIGNED_BYTE*/0x1401,/*laya.webgl.WebGLContext.DEPTH_COMPONENT16*/0x81A5,false,false); if(this.useRefrTex){ this._texRefract=new RenderTexture(desc.refracTexSize[0],desc.refracTexSize[1]); this._texRefract.repeat=false; this._texRefract.mipmap=true; this.mtl.useRefractTexture=true; }else { this.mtl.useRefractTexture=false; } (this._geometryFilter).sharedMesh=mesh; mesh.once(/*laya.events.Event.LOADED*/"loaded",this,this._applyMeshMaterials); mesh.on(/*laya.events.Event.LOADED*/"loaded",this,this.onMeshLoaded); if (desc.skyTexture.substr(desc.skyTexture.length-4).toLowerCase()==='.ltc'){ this.mtl.skyTexture=TextureCube.load(desc.skyTexture); this.mtl._addShaderDefine(WaterMaterial.SHADERDEFINE_CUBE_ENV); }else { this.mtl.skyTexture=Texture2D.load(desc.skyTexture); this.mtl._removeShaderDefine(WaterMaterial.SHADERDEFINE_CUBE_ENV); } if (desc.hdrsky){ this.mtl._addShaderDefine(WaterMaterial.SHADERDEFINE_HDR_ENV); } if (desc.deepScale !=undefined) this.mtl.deepScale=desc.deepScale; if (desc.useVertexDeep){ this.mtl.useVertexDeep=true; } this.mtl.skyTexture.repeat=true; var infotex=Texture2D.load(desc.infoTexture); infotex.repeat=false; this.mtl.waterInfoTexture=infotex; var foamTex=Texture2D.load(desc.foamTexture); foamTex.repeat=true; this.mtl.foamTexture=foamTex; this.mtl.renderMode=/*laya.d3.core.material.WaterMaterial.RENDERMODE_TRANSPARENT*/13; this.mtl.waveMainDir=desc.geoWaveData[0].dir; this.mtl.geoWaveUVScale=desc.geoWaveUVScale; this._detailMesh=new QuadMesh(2,2); this.detailMtl=new WaterDetailMaterial(); this.detailMtl.texWaveUVScale=desc.detailWaveUVScale; if (desc.geoWaveData.length !=4)throw "error 3"; if (desc.detailData.length !=4)throw "error 4"; (desc.geoWaveData).forEach(function(v,i){ _$this._getWaveInfo(_$this._geoWaveInfo,_$this._geoWaveInfoDir,i,v.dir,v.L,v.Q,v.A); }); var kAmp_over_L=0.01; (desc.detailData).forEach(function(v,i){ _$this._getWaveInfo(_$this._texWaveInfo,_$this._texWaveInfoDir,i,v.dir,v.L,1.5,v.L *kAmp_over_L); }); this._waterColor.x=desc.color[0]/255;this._waterColor.y=desc.color[1]/255;this._waterColor.z=desc.color[2]/255; this.mtl.seaColor=new Float32Array([this._waterColor.x,this._waterColor.y,this._waterColor.z]); this._waterFogStart=desc.fogStart; this._waterFogRange=desc.fogRange; if (this.afterDescLoaded){ this.afterDescLoaded.call(this); } } __proto.onMeshLoaded=function(){ this._refractQueue=new RenderQueue(this._scene); this._scrSizeInfo[0]=Laya.stage.width; this._scrSizeInfo[1]=Laya.stage.height; this.mtl.scrsize=this._scrSizeInfo; this.meshRender.sharedMaterial=this.mtl; if (this._render._renderElements.length > 0){ this._render._renderElements[0]._onPreRenderFunction=this.onPreRender; }else { throw "error2"; } this._waterLoaded=true; } __proto.stop=function(){ this._stop=!this._stop; } __proto.addRefractObj=function(obj){ this._refractObjStack.push(obj); this._refractObjecs.push(obj); } /** *渲染之前,生成必要的数据。 *@param state */ __proto.onPreRender=function(state){ var _$this=this; if (!this._waterLoaded) return; if (this._refractObjStack.length){ for (var i=0;i < this._refractObjStack.length;i++){ var obj=this._refractObjStack[i]; if (obj._render._renderElements.length){ obj._render._renderElements.forEach(function(v){_$this._refractQueue._addRenderElement(v);}); this._refractObjStack.splice(i,1); i--; } } }; var gl=WebGL.mainContext; var olddf=gl.getParameter(/*laya.webgl.WebGLContext.DEPTH_TEST*/0x0B71); var oldcf=gl.getParameter(/*laya.webgl.WebGLContext.CULL_FACE*/0x0B44); var oldvp=gl.getParameter(/*laya.webgl.WebGLContext.VIEWPORT*/0x0BA2); var needRestoreVP=false; if(this.useRefrTex){ this._texRefract.start(); needRestoreVP=true; gl.viewport(0,0,this._texRefract.width,this._texRefract.height); gl.clearColor(this._waterColor.x,this._waterColor.y,this._waterColor.z,1.); gl.clear(/*laya.webgl.WebGLContext.DEPTH_BUFFER_BIT*/0x00000100 | /*laya.webgl.WebGLContext.COLOR_BUFFER_BIT*/0x00004000); this._refractObjecs.forEach(function(v){ v._renderUpdate(state._projectionViewMatrix); }); this._refractQueue._preRender(state); this._refractQueue._render(state,false); this._texRefract.end(); this._texRefract.repeat=true; } if(this.renderDetailWav){ this._texWave.start(); gl.disable(/*laya.webgl.WebGLContext.DEPTH_TEST*/0x0B71); gl.disable(/*laya.webgl.WebGLContext.CULL_FACE*/0x0B44); needRestoreVP=true; gl.viewport(0,0,WaterSprite.detailTexWidth,WaterSprite.detailTexHeight); var re=this._detailMesh.getRenderElement(0); re._beforeRender(state); this.detailMtl.currentTm=Laya.timer.currTimer; this.detailMtl.waveInfo=this._texWaveInfo; this.detailMtl.waveInfoD=this._texWaveInfoDir; var detailShader=this.detailMtl._getShader(0,0,0); detailShader.bind(); var vb=this._detailMesh._getVertexBuffer(0); detailShader.uploadAttributes(vb.vertexDeclaration.shaderValues.data,null); this.detailMtl._upload(); re._render(state); this._texWave.end(); olddf && gl.enable(/*laya.webgl.WebGLContext.DEPTH_TEST*/0x0B71); oldcf && gl.enable(/*laya.webgl.WebGLContext.CULL_FACE*/0x0B44); } if(needRestoreVP) gl.viewport(oldvp[0],oldvp[1],oldvp[2],oldvp[3]); if (this._syncObj){ this.mtl.detailTexture=this._syncObj._texWave; }else this.mtl.detailTexture=this._texWave; this.mtl.waveInfo=this._geoWaveInfo; this.mtl.waveInfoD=this._geoWaveInfoDir; this.mtl.underWaterTexture=this._texRefract; if (!this._stop){ if (this._syncObj)this.curTm=this._syncObj.curTm; else this.curTm=Laya.timer.currTimer-this.startTm; this.mtl._setNumber(/*laya.d3.core.material.WaterMaterial.CURTM*/8,this.curTm); }else {} if (/*__JS__ */window.shownormal && !this._shownormal){ this._shownormal=true; this.mtl._addShaderDefine(WaterMaterial.SHADERDEFINE_SHOW_NORMAL); } if(/*__JS__ */window.shownormal && this._shownormal){ this._shownormal=false; this.mtl._removeShaderDefine(WaterMaterial.SHADERDEFINE_SHOW_NORMAL); } } __proto._update=function(state){ laya.d3.core.RenderableSprite3D.prototype._update.call(this,state); } __getset(0,__proto,'src',null,function(v){ var ld=new Loader(); ld.on(/*laya.events.Event.COMPLETE*/"complete",this,this.onDescLoaded); ld.load(v); }); __getset(0,__proto,'syncObj',null,function(obj){ this._syncObj=obj; this.renderDetailWav=false; }); WaterSprite._waveInfoEleNum=4; WaterSprite.detailTexWidth=256; WaterSprite.detailTexHeight=256; __static(WaterSprite, ['deg2rad',function(){return this.deg2rad=Math.PI / 180;},'_2pi',function(){return this._2pi=2 *Math.PI;} ]); return WaterSprite; })(MeshSprite3D) })(window,document,Laya); if (typeof define === 'function' && define.amd){ define('laya.core', ['require', "exports"], function(require, exports) { 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); for (var i in Laya) { var o = Laya[i]; o && o.__isclass && (exports[i] = o); } }); }