@galacean/engine-core 2.0.0-alpha.36 → 2.0.0-alpha.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/module.js CHANGED
@@ -3848,7 +3848,7 @@ TiledSpriteAssembler = __decorate([
3848
3848
  sprite.name === name && outSprites.push(sprite);
3849
3849
  }
3850
3850
  } else {
3851
- console.warn("The name of the sprite you want to find is not exit in SpriteAtlas.");
3851
+ console.warn("There is no sprite named " + name + " in the atlas.");
3852
3852
  }
3853
3853
  return outSprites;
3854
3854
  };
@@ -6059,6 +6059,9 @@ __decorate([
6059
6059
  __decorate([
6060
6060
  ignoreClone
6061
6061
  ], Transform.prototype, "_isParentDirty", void 0);
6062
+ __decorate([
6063
+ ignoreClone
6064
+ ], Transform.prototype, "_parentTransformCache", void 0);
6062
6065
  __decorate([
6063
6066
  ignoreClone
6064
6067
  ], Transform.prototype, "_dirtyFlag", void 0);
@@ -17071,9 +17074,10 @@ var ComponentCloner = /*#__PURE__*/ function() {
17071
17074
  };
17072
17075
  /**
17073
17076
  * Get the components which match the type of the entity and it's children.
17077
+ * @remarks The components are returned in depth-first pre-order: the entity itself first, then each child's subtree in sibling order.
17074
17078
  * @param type - The component type
17075
17079
  * @param results - The components collection
17076
- * @returns The components collection which match the type
17080
+ * @returns The components collection which match the type
17077
17081
  */ _proto.getComponentsIncludeChildren = function getComponentsIncludeChildren(type, results) {
17078
17082
  results.length = 0;
17079
17083
  this._getComponentsInChildren(type, results);
@@ -17378,14 +17382,16 @@ var ComponentCloner = /*#__PURE__*/ function() {
17378
17382
  }
17379
17383
  };
17380
17384
  _proto._getComponentsInChildren = function _getComponentsInChildren(type, results) {
17381
- for(var i = this._components.length - 1; i >= 0; i--){
17382
- var component = this._components[i];
17385
+ var components = this._components;
17386
+ for(var i = 0, n = components.length; i < n; i++){
17387
+ var component = components[i];
17383
17388
  if (_instanceof(component, type)) {
17384
17389
  results.push(component);
17385
17390
  }
17386
17391
  }
17387
- for(var i1 = this._children.length - 1; i1 >= 0; i1--){
17388
- this._children[i1]._getComponentsInChildren(type, results);
17392
+ var children = this._children;
17393
+ for(var i1 = 0, n1 = children.length; i1 < n1; i1++){
17394
+ children[i1]._getComponentsInChildren(type, results);
17389
17395
  }
17390
17396
  };
17391
17397
  _proto._setActiveComponents = function _setActiveComponents(isActive, activeChangeFlag) {
@@ -18817,37 +18823,39 @@ var MultiExecutor = /*#__PURE__*/ function() {
18817
18823
  this._contentRestorerPool = null;
18818
18824
  this._loadingPromises = null;
18819
18825
  };
18820
- _proto._assignDefaultOptions = function _assignDefaultOptions(assetInfo) {
18821
- var _assetInfo_type;
18822
- assetInfo.type = (_assetInfo_type = assetInfo.type) != null ? _assetInfo_type : ResourceManager._getTypeByUrl(assetInfo.url);
18826
+ _proto._resolveLoadItemOptions = function _resolveLoadItemOptions(assetInfo, virtualResourceEntry) {
18827
+ var _assetInfo;
18828
+ var _virtualResourceEntry_type, _ref;
18829
+ assetInfo.type = (_ref = (_virtualResourceEntry_type = virtualResourceEntry == null ? void 0 : virtualResourceEntry.type) != null ? _virtualResourceEntry_type : assetInfo.type) != null ? _ref : ResourceManager._getTypeByUrl(assetInfo.url);
18823
18830
  if (assetInfo.type === undefined) {
18824
18831
  throw "asset type should be specified: " + assetInfo.url;
18825
18832
  }
18833
+ var _params;
18834
+ (_params = (_assetInfo = assetInfo).params) != null ? _params : _assetInfo.params = virtualResourceEntry == null ? void 0 : virtualResourceEntry.params;
18826
18835
  var _assetInfo_retryCount;
18827
18836
  assetInfo.retryCount = (_assetInfo_retryCount = assetInfo.retryCount) != null ? _assetInfo_retryCount : this.retryCount;
18828
18837
  var _assetInfo_timeout;
18829
18838
  assetInfo.timeout = (_assetInfo_timeout = assetInfo.timeout) != null ? _assetInfo_timeout : this.timeout;
18830
18839
  var _assetInfo_retryInterval;
18831
18840
  assetInfo.retryInterval = (_assetInfo_retryInterval = assetInfo.retryInterval) != null ? _assetInfo_retryInterval : this.retryInterval;
18832
- var _assetInfo_url;
18833
- assetInfo.url = (_assetInfo_url = assetInfo.url) != null ? _assetInfo_url : assetInfo.urls.join(",");
18834
- return assetInfo;
18835
18841
  };
18836
18842
  _proto._loadSingleItem = function _loadSingleItem(itemOrURL) {
18837
18843
  var _this = this;
18838
- var item = this._assignDefaultOptions(typeof itemOrURL === "string" ? {
18844
+ var item = typeof itemOrURL === "string" ? {
18839
18845
  url: itemOrURL
18840
- } : itemOrURL);
18841
- var url = item.url;
18842
- // Not absolute and base url is set
18843
- if (!Utils.isAbsoluteUrl(url) && this.baseUrl) url = Utils.resolveAbsoluteUrl(this.baseUrl, url);
18846
+ } : itemOrURL;
18847
+ var _item_url;
18848
+ item.url = (_item_url = item.url) != null ? _item_url : item.urls.join(",");
18844
18849
  // Parse url
18845
- var _this__parseURL = this._parseURL(url), assetBaseURL = _this__parseURL.assetBaseURL, queryPath = _this__parseURL.queryPath;
18850
+ var _this__parseURL = this._parseURL(item.url), assetBaseURL = _this__parseURL.assetBaseURL, queryPath = _this__parseURL.queryPath;
18846
18851
  var paths = queryPath ? this._parseQueryPath(queryPath) : [];
18847
18852
  // Get remote asset base url
18848
- var remoteConfig = this._virtualPathResourceMap[assetBaseURL];
18849
- var _remoteConfig_path;
18850
- var remoteAssetBaseURL = (_remoteConfig_path = remoteConfig == null ? void 0 : remoteConfig.path) != null ? _remoteConfig_path : assetBaseURL;
18853
+ var virtualResourceEntry = this._virtualPathResourceMap[assetBaseURL];
18854
+ this._resolveLoadItemOptions(item, virtualResourceEntry);
18855
+ // Not absolute and base url is set
18856
+ item.url = !Utils.isAbsoluteUrl(assetBaseURL) && this.baseUrl ? Utils.resolveAbsoluteUrl(this.baseUrl, assetBaseURL) : assetBaseURL;
18857
+ var _virtualResourceEntry_path;
18858
+ var remoteAssetBaseURL = (_virtualResourceEntry_path = virtualResourceEntry == null ? void 0 : virtualResourceEntry.path) != null ? _virtualResourceEntry_path : item.url;
18851
18859
  // Check cache
18852
18860
  var cacheObject = this._assetUrlPool[remoteAssetBaseURL];
18853
18861
  if (cacheObject) {
@@ -18881,25 +18889,24 @@ var MultiExecutor = /*#__PURE__*/ function() {
18881
18889
  if (!loader) {
18882
18890
  throw "loader not found: " + item.type;
18883
18891
  }
18884
- var subpackageName = remoteConfig == null ? void 0 : remoteConfig.subpackageName;
18892
+ var subpackageName = virtualResourceEntry == null ? void 0 : virtualResourceEntry.subpackageName;
18885
18893
  // Check sub asset
18886
18894
  if (queryPath) {
18887
18895
  // Check whether load main asset
18888
- var mainPromise = loadingPromises[remoteAssetBaseURL] || this._loadSubpackageAndMainAsset(loader, item, remoteAssetBaseURL, assetBaseURL, subpackageName);
18896
+ var mainPromise = loadingPromises[remoteAssetBaseURL] || this._loadSubpackageAndMainAsset(loader, item, remoteAssetBaseURL, subpackageName);
18889
18897
  mainPromise.catch(function(e) {
18890
18898
  _this._onSubAssetFail(remoteAssetBaseURL, queryPath, e);
18891
18899
  });
18892
18900
  return this._createSubAssetPromiseCallback(remoteAssetBaseURL, remoteAssetURL, queryPath);
18893
18901
  }
18894
- return this._loadSubpackageAndMainAsset(loader, item, remoteAssetBaseURL, assetBaseURL, subpackageName);
18902
+ return this._loadSubpackageAndMainAsset(loader, item, remoteAssetBaseURL, subpackageName);
18895
18903
  };
18896
18904
  // For adapter mini-game platform
18897
- _proto._loadSubpackageAndMainAsset = function _loadSubpackageAndMainAsset(loader, item, remoteAssetBaseURL, assetBaseURL, subpackageName) {
18898
- return this._loadMainAsset(loader, item, remoteAssetBaseURL, assetBaseURL);
18905
+ _proto._loadSubpackageAndMainAsset = function _loadSubpackageAndMainAsset(loader, item, remoteAssetBaseURL, subpackageName) {
18906
+ return this._loadMainAsset(loader, item, remoteAssetBaseURL);
18899
18907
  };
18900
- _proto._loadMainAsset = function _loadMainAsset(loader, item, remoteAssetBaseURL, assetBaseURL) {
18908
+ _proto._loadMainAsset = function _loadMainAsset(loader, item, remoteAssetBaseURL) {
18901
18909
  var _this = this;
18902
- item.url = assetBaseURL;
18903
18910
  var loadingPromises = this._loadingPromises;
18904
18911
  var promise = loader.load(item, this);
18905
18912
  loadingPromises[remoteAssetBaseURL] = promise;
@@ -19026,10 +19033,9 @@ var MultiExecutor = /*#__PURE__*/ function() {
19026
19033
  return AssetPromise.resolve(null);
19027
19034
  }
19028
19035
  var loadUrl = key ? url + "?q=" + key : url;
19036
+ // type and params omitted: resolved from the virtualPath map, the single source of truth
19029
19037
  var promise = this.load({
19030
- url: loadUrl,
19031
- type: mapped.type,
19032
- params: mapped.params
19038
+ url: loadUrl
19033
19039
  });
19034
19040
  return isClone ? promise.then(function(item) {
19035
19041
  return item.clone();
@@ -20436,6 +20442,13 @@ __decorate([
20436
20442
  this._phasedActiveInScene && this._nativeCollider.addForce(force);
20437
20443
  };
20438
20444
  /**
20445
+ * Apply a force to the DynamicCollider at a given position in world space.
20446
+ * @param force - The force to apply, in world space
20447
+ * @param position - The position where the force is applied, in world space
20448
+ */ _proto.applyForceAtPosition = function applyForceAtPosition(force, position) {
20449
+ this._phasedActiveInScene && this._nativeCollider.addForceAtPosition(force, position);
20450
+ };
20451
+ /**
20439
20452
  * Apply a torque to the DynamicCollider.
20440
20453
  * @param torque - The force make the collider rotate
20441
20454
  */ _proto.applyTorque = function applyTorque(torque) {
@@ -26788,6 +26801,7 @@ CascadedShadowCasterPass._tempMatrix0 = new Matrix();
26788
26801
  depthOnlyPass.release();
26789
26802
  camera.shaderData.setTexture(Camera._cameraDepthTextureProperty, engine._basicResources.whiteTexture2D);
26790
26803
  }
26804
+ var pool = engine._renderTargetPool;
26791
26805
  // Check if need to create internal color texture or grab texture
26792
26806
  if (independentCanvasEnabled) {
26793
26807
  var depthFormat;
@@ -26803,26 +26817,12 @@ CascadedShadowCasterPass._tempMatrix0 = new Matrix();
26803
26817
  depthFormat = null;
26804
26818
  }
26805
26819
  var viewport = camera.pixelViewport;
26806
- var internalColorTarget = PipelineUtils.recreateRenderTargetIfNeeded(engine, this._internalColorTarget, viewport.width, viewport.height, camera._getInternalColorTextureFormat(), depthFormat, false, false, !camera.enableHDR, msaaSamples, TextureWrapMode.Clamp, TextureFilterMode.Bilinear);
26820
+ this._internalColorTarget = pool.allocateRenderTarget(viewport.width, viewport.height, camera._getInternalColorTextureFormat(), depthFormat, false, false, !camera.enableHDR, msaaSamples, TextureWrapMode.Clamp, TextureFilterMode.Bilinear);
26807
26821
  if (this._shouldCopyBackgroundColor) {
26808
26822
  var _camera_renderTarget;
26809
26823
  var colorTexture = (_camera_renderTarget = camera.renderTarget) == null ? void 0 : _camera_renderTarget.getColorTexture(0);
26810
26824
  var _colorTexture_format, _colorTexture_isSRGBColorSpace;
26811
- var copyBackgroundTexture = PipelineUtils.recreateTextureIfNeeded(engine, this._copyBackgroundTexture, viewport.width, viewport.height, (_colorTexture_format = colorTexture == null ? void 0 : colorTexture.format) != null ? _colorTexture_format : TextureFormat.R8G8B8A8, false, (_colorTexture_isSRGBColorSpace = colorTexture == null ? void 0 : colorTexture.isSRGBColorSpace) != null ? _colorTexture_isSRGBColorSpace : false, TextureWrapMode.Clamp, TextureFilterMode.Bilinear);
26812
- this._copyBackgroundTexture = copyBackgroundTexture;
26813
- }
26814
- this._internalColorTarget = internalColorTarget;
26815
- } else {
26816
- var internalColorTarget1 = this._internalColorTarget;
26817
- var copyBackgroundTexture1 = this._copyBackgroundTexture;
26818
- var pool = engine._renderTargetPool;
26819
- if (internalColorTarget1) {
26820
- pool.freeRenderTarget(internalColorTarget1);
26821
- this._internalColorTarget = null;
26822
- }
26823
- if (copyBackgroundTexture1) {
26824
- pool.freeTexture(copyBackgroundTexture1);
26825
- this._copyBackgroundTexture = null;
26825
+ this._copyBackgroundTexture = pool.allocateTexture(viewport.width, viewport.height, (_colorTexture_format = colorTexture == null ? void 0 : colorTexture.format) != null ? _colorTexture_format : TextureFormat.R8G8B8A8, false, (_colorTexture_isSRGBColorSpace = colorTexture == null ? void 0 : colorTexture.isSRGBColorSpace) != null ? _colorTexture_isSRGBColorSpace : false, TextureWrapMode.Clamp, TextureFilterMode.Bilinear);
26826
26826
  }
26827
26827
  }
26828
26828
  // Scalable ambient obscurance pass
@@ -26835,6 +26835,15 @@ CascadedShadowCasterPass._tempMatrix0 = new Matrix();
26835
26835
  this._saoPass.release();
26836
26836
  }
26837
26837
  this._drawRenderPass(context, camera, finalClearFlags, cubeFace, mipLevel);
26838
+ // Return the per-frame leases so the next camera with matching shape can reuse them
26839
+ if (this._internalColorTarget) {
26840
+ pool.freeRenderTarget(this._internalColorTarget);
26841
+ this._internalColorTarget = null;
26842
+ }
26843
+ if (this._copyBackgroundTexture) {
26844
+ pool.freeTexture(this._copyBackgroundTexture);
26845
+ this._copyBackgroundTexture = null;
26846
+ }
26838
26847
  };
26839
26848
  _proto._drawRenderPass = function _drawRenderPass(context, camera, finalClearFlags, cubeFace, mipLevel) {
26840
26849
  var cullingResults = this._cullingResults;
@@ -27168,7 +27177,9 @@ var OverlayCamera = function OverlayCamera() {
27168
27177
  _inherits(Engine, EventDispatcher);
27169
27178
  function Engine(canvas, hardwareRenderer, configuration) {
27170
27179
  var _this;
27171
- _this = EventDispatcher.call(this) || this, /** @internal */ _this._renderingStatistics = new RenderingStatistics(), /** @internal */ _this._isDeviceLost = false, /** @internal */ _this._frameInProcess = false, /** @internal */ _this._pendingDestroyObjects = [], /** @internal */ _this._processingPendingDestroys = false, /** @internal */ _this._physicsInitialized = false, /* @internal */ _this._lastRenderState = new RenderState(), /* @internal */ _this._renderElementPool = new ClearableObjectPool(RenderElement), /* @internal */ _this._textRenderElementPool = new ClearableObjectPool(RenderElement), /* @internal */ _this._charRenderInfoPool = new ReturnableObjectPool(CharRenderInfo, 50), /* @internal */ _this._renderContext = new RenderContext(), /* @internal */ _this._renderCount = 0, /* @internal */ _this._shaderProgramMaps = [], /** @internal */ _this._fontMap = {}, /** @internal */ _this._macroCollection = new ShaderMacroCollection(), /** @internal */ _this._postProcessPassNeedRefresh = false, _this._settings = {}, _this._resourceManager = new ResourceManager(_this), _this._sceneManager = new SceneManager(_this), _this._vSyncCount = 1, _this._targetFrameRate = 60, _this._time = new Time(), _this._isPaused = true, _this._vSyncCounter = 1, _this._targetFrameInterval = 1000 / 60, _this._destroyed = false, _this._waitingDestroy = false, _this._waitingGC = false, _this._postProcessPasses = new Array(), _this._activePostProcessPasses = new Array(), _this._animate = function() {
27180
+ _this = EventDispatcher.call(this) || this, /** @internal */ _this._renderingStatistics = new RenderingStatistics(), /** @internal */ _this._isDeviceLost = false, /** @internal */ _this._frameInProcess = false, /** @internal */ _this._pendingDestroyObjects = [], /** @internal */ _this._processingPendingDestroys = false, /** @internal */ _this._physicsInitialized = false, /* @internal */ _this._lastRenderState = new RenderState(), /* @internal */ _this._renderElementPool = new ClearableObjectPool(RenderElement), /* @internal */ _this._textRenderElementPool = new ClearableObjectPool(RenderElement), /* @internal */ _this._charRenderInfoPool = new ReturnableObjectPool(CharRenderInfo, 50), /* @internal */ _this._renderContext = new RenderContext(), /* @internal */ _this._renderCount = 0, /* @internal */ _this._shaderProgramMaps = [], /** @internal */ _this._fontMap = {}, /** @internal */ _this._macroCollection = new ShaderMacroCollection(), /** @internal */ _this._postProcessPassNeedRefresh = false, _this._settings = {}, _this._resourceManager = new ResourceManager(_this), _this._sceneManager = new SceneManager(_this), _this._vSyncCount = 1, _this._targetFrameRate = 60, _this._time = new Time(), _this._isPaused = true, _this._vSyncCounter = 1, _this._targetFrameInterval = 1000 / 60, _this._destroyed = false, _this._waitingDestroy = false, _this._waitingGC = false, _this._postProcessPasses = new Array(), _this._activePostProcessPasses = new Array(), _this._onCanvasResize = function() {
27181
+ return _this._renderTargetPool.gc();
27182
+ }, _this._animate = function() {
27172
27183
  if (_this._vSyncCount) {
27173
27184
  var _this_xrManager;
27174
27185
  var raf = ((_this_xrManager = _this.xrManager) == null ? void 0 : _this_xrManager._getRequestAnimationFrame()) || requestAnimationFrame;
@@ -27189,6 +27200,7 @@ var OverlayCamera = function OverlayCamera() {
27189
27200
  _this._textDefaultFont.isGCIgnored = true;
27190
27201
  _this._batcherManager = new BatcherManager(_this);
27191
27202
  _this._renderTargetPool = new RenderTargetPool(_this);
27203
+ canvas._sizeUpdateFlagManager.addListener(_this._onCanvasResize);
27192
27204
  _this.inputManager = new InputManager(_this, configuration.input);
27193
27205
  var xrDevice = configuration.xrDevice;
27194
27206
  if (xrDevice) {
@@ -27392,6 +27404,7 @@ var OverlayCamera = function OverlayCamera() {
27392
27404
  var _this_xrManager;
27393
27405
  this._destroyed = true;
27394
27406
  this._waitingDestroy = false;
27407
+ this._canvas._sizeUpdateFlagManager.removeListener(this._onCanvasResize);
27395
27408
  this._sceneManager._destroyAllScene();
27396
27409
  this._resourceManager._destroy();
27397
27410
  this.inputManager._destroy();
@@ -29726,7 +29739,7 @@ var PointerMethods = /*#__PURE__*/ function(PointerMethods) {
29726
29739
  for(var _len = arguments.length, signalArgs = new Array(_len), _key = 0; _key < _len; _key++){
29727
29740
  signalArgs[_key] = arguments[_key];
29728
29741
  }
29729
- return (_target = target)[methodName].apply(_target, [].concat(args, signalArgs));
29742
+ return (_target = target)[methodName].apply(_target, [].concat(signalArgs, args));
29730
29743
  } : function() {
29731
29744
  for(var _len = arguments.length, signalArgs = new Array(_len), _key = 0; _key < _len; _key++){
29732
29745
  signalArgs[_key] = arguments[_key];
@@ -30160,7 +30173,7 @@ AnimationCurveOwner.registerAssembler(SkinnedMeshRenderer, "blendShapeWeights",
30160
30173
  */ var AnimationClipCurveBinding = /*#__PURE__*/ function() {
30161
30174
  function AnimationClipCurveBinding() {
30162
30175
  /** The index of the component that is animated. */ this.typeIndex = 0;
30163
- this._tempCurveOwner = {};
30176
+ this._tempCurveOwner = new WeakMap();
30164
30177
  }
30165
30178
  var _proto = AnimationClipCurveBinding.prototype;
30166
30179
  /**
@@ -30186,11 +30199,12 @@ AnimationCurveOwner.registerAssembler(SkinnedMeshRenderer, "blendShapeWeights",
30186
30199
  /**
30187
30200
  * @internal
30188
30201
  */ _proto._getTempCurveOwner = function _getTempCurveOwner(entity, component) {
30189
- var instanceId = entity.instanceId;
30190
- if (!this._tempCurveOwner[instanceId]) {
30191
- this._tempCurveOwner[instanceId] = this._createCurveOwner(entity, component);
30202
+ var owner = this._tempCurveOwner.get(entity);
30203
+ if (!owner) {
30204
+ owner = this._createCurveOwner(entity, component);
30205
+ this._tempCurveOwner.set(entity, owner);
30192
30206
  }
30193
- return this._tempCurveOwner[instanceId];
30207
+ return owner;
30194
30208
  };
30195
30209
  return AnimationClipCurveBinding;
30196
30210
  }();
@@ -30272,11 +30286,10 @@ AnimationCurveOwner.registerAssembler(SkinnedMeshRenderer, "blendShapeWeights",
30272
30286
  this._length = 0;
30273
30287
  };
30274
30288
  /**
30275
- * @internal
30276
30289
  * Samples an animation at a given time.
30277
30290
  * @param entity - The animated entity
30278
30291
  * @param time - The time to sample an animation
30279
- */ _proto._sampleAnimation = function _sampleAnimation(entity, time) {
30292
+ */ _proto.sampleAnimation = function sampleAnimation(entity, time) {
30280
30293
  var _this = this, curveBindings = _this._curveBindings;
30281
30294
  var components = AnimationCurveOwner._components;
30282
30295
  for(var i = curveBindings.length - 1; i >= 0; i--){
@@ -31451,12 +31464,6 @@ var AnimatorLayerBlendingMode = /*#__PURE__*/ function(AnimatorLayerBlendingMode
31451
31464
  return LayerState;
31452
31465
  }({});
31453
31466
 
31454
- /**
31455
- * @internal
31456
- */ var AnimationEventHandler = function AnimationEventHandler() {
31457
- this.handlers = [];
31458
- };
31459
-
31460
31467
  /**
31461
31468
  * Animation wrap mode.
31462
31469
  */ var WrapMode = /*#__PURE__*/ function(WrapMode) {
@@ -31465,6 +31472,12 @@ var AnimatorLayerBlendingMode = /*#__PURE__*/ function(AnimatorLayerBlendingMode
31465
31472
  return WrapMode;
31466
31473
  }({});
31467
31474
 
31475
+ /**
31476
+ * @internal
31477
+ */ var AnimationEventHandler = function AnimationEventHandler() {
31478
+ this.handlers = [];
31479
+ };
31480
+
31468
31481
  /**
31469
31482
  * @internal
31470
31483
  */ var AnimatorStatePlayData = /*#__PURE__*/ function() {
@@ -31505,19 +31518,21 @@ var AnimatorLayerBlendingMode = /*#__PURE__*/ function(AnimatorLayerBlendingMode
31505
31518
  this.playedTime += deltaTime;
31506
31519
  var instance = this.instance;
31507
31520
  var state = instance._state;
31521
+ var clipLength = state.clip.length;
31522
+ var clipStartTime = state.clipStartTime;
31508
31523
  var time = this.playedTime + this.offsetFrameTime;
31509
- var duration = state._getDuration();
31524
+ var duration = (state.clipEndTime - clipStartTime) * clipLength;
31510
31525
  this.playState = AnimatorStatePlayState.Playing;
31511
31526
  if (instance.wrapMode === WrapMode.Loop) {
31512
31527
  time = duration ? time % duration : 0;
31513
- } else {
31514
- if (Math.abs(time) >= duration) {
31515
- time = time < 0 ? -duration : duration;
31516
- this.playState = AnimatorStatePlayState.Finished;
31517
- }
31528
+ } else if (time >= duration || time <= -duration) {
31529
+ time = time < 0 ? -duration : duration;
31530
+ this.playState = AnimatorStatePlayState.Finished;
31531
+ }
31532
+ if (time < 0) {
31533
+ time += duration;
31518
31534
  }
31519
- time < 0 && (time += duration);
31520
- this.clipTime = time + state.clipStartTime * state.clip.length;
31535
+ this.clipTime = time + clipStartTime * clipLength;
31521
31536
  if (this._changedOrientation) {
31522
31537
  !this.isForward && this._correctTime();
31523
31538
  this._changedOrientation = false;
@@ -31530,6 +31545,26 @@ var AnimatorLayerBlendingMode = /*#__PURE__*/ function(AnimatorLayerBlendingMode
31530
31545
  this.clipTime = state.clipEndTime * state.clip.length;
31531
31546
  }
31532
31547
  };
31548
+ _create_class(AnimatorStatePlayData, [
31549
+ {
31550
+ key: "state",
31551
+ get: function get() {
31552
+ return this.instance._state;
31553
+ }
31554
+ },
31555
+ {
31556
+ key: "speed",
31557
+ get: function get() {
31558
+ return this.instance.speed;
31559
+ }
31560
+ },
31561
+ {
31562
+ key: "wrapMode",
31563
+ get: function get() {
31564
+ return this.instance.wrapMode;
31565
+ }
31566
+ }
31567
+ ]);
31533
31568
  return AnimatorStatePlayData;
31534
31569
  }();
31535
31570
 
@@ -31708,8 +31743,8 @@ function _type_of(obj) {
31708
31743
  * @internal
31709
31744
  */ var AnimatorLayerData = /*#__PURE__*/ function() {
31710
31745
  function AnimatorLayerData() {
31711
- this.curveOwnerPool = Object.create(null);
31712
- this.animatorStateDataMap = new WeakMap();
31746
+ this.curveOwnerPool = new WeakMap();
31747
+ this.animatorStateDataMap = new Map();
31713
31748
  this.instanceMap = new WeakMap();
31714
31749
  this.srcPlayData = null;
31715
31750
  this.destPlayData = null;
@@ -31728,15 +31763,6 @@ function _type_of(obj) {
31728
31763
  }
31729
31764
  return instance;
31730
31765
  };
31731
- _proto.completeCrossFade = function completeCrossFade() {
31732
- this.srcPlayData = this.destPlayData;
31733
- this.destPlayData = null;
31734
- this.crossFadeTransition = null;
31735
- };
31736
- _proto.clearCrossFadeSlot = function clearCrossFadeSlot() {
31737
- this.destPlayData = null;
31738
- this.crossFadeTransition = null;
31739
- };
31740
31766
  _proto.resetCurrentCheckIndex = function resetCurrentCheckIndex() {
31741
31767
  this.layer.stateMachine._entryTransitionCollection.needResetCurrentCheckIndex = true;
31742
31768
  this.layer.stateMachine._anyStateTransitionCollection.needResetCurrentCheckIndex = true;
@@ -31760,7 +31786,7 @@ function _type_of(obj) {
31760
31786
  _inherits(Animator, Component);
31761
31787
  function Animator(entity) {
31762
31788
  var _this;
31763
- _this = Component.call(this, entity) || this, /** Culling mode of this Animator. */ _this.cullingMode = AnimatorCullingMode.None, /** The playback speed of the Animator, 1.0 is normal playback speed. */ _this.speed = 1.0, /** @internal */ _this._playFrameCount = -1, /** @internal */ _this._onUpdateIndex = -1, _this._updateMark = 0, _this._animatorLayersData = new Array(), _this._curveOwnerPool = Object.create(null), _this._parametersValueMap = Object.create(null), _this._tempAnimatorStateInfo = {
31789
+ _this = Component.call(this, entity) || this, /** Culling mode of this Animator. */ _this.cullingMode = AnimatorCullingMode.None, /** The playback speed of the Animator, 1.0 is normal playback speed. */ _this.speed = 1.0, /** Whether the Animator sends AnimationEvent callbacks. */ _this.fireEvents = true, /** @internal */ _this._playFrameCount = -1, /** @internal */ _this._onUpdateIndex = -1, _this._updateMark = 0, _this._animatorLayersData = new Array(), _this._curveOwnerPool = new WeakMap(), _this._parametersValueMap = Object.create(null), _this._tempAnimatorStateInfo = {
31764
31790
  layerIndex: -1,
31765
31791
  state: null
31766
31792
  }, _this._controlledRenderers = new Array();
@@ -31943,16 +31969,21 @@ function _type_of(obj) {
31943
31969
  /**
31944
31970
  * @internal
31945
31971
  */ _proto._reset = function _reset() {
31946
- var _this = this, animationCurveOwners = _this._curveOwnerPool;
31947
- for(var instanceId in animationCurveOwners){
31948
- var propertyOwners = animationCurveOwners[instanceId];
31949
- for(var property in propertyOwners){
31950
- var owner = propertyOwners[property];
31951
- owner.revertDefaultValue();
31972
+ var layersData = this._animatorLayersData;
31973
+ for(var i = 0, n = layersData.length; i < n; i++){
31974
+ var layerData = layersData[i];
31975
+ if (!layerData) continue;
31976
+ for(var _iterator = _create_for_of_iterator_helper_loose(layerData.animatorStateDataMap.values()), _step; !(_step = _iterator()).done;){
31977
+ var stateData = _step.value;
31978
+ var layerOwners = stateData.curveLayerOwner;
31979
+ for(var k = 0, l = layerOwners.length; k < l; k++){
31980
+ var _layerOwners_k_curveOwner, _layerOwners_k;
31981
+ (_layerOwners_k = layerOwners[k]) == null ? void 0 : (_layerOwners_k_curveOwner = _layerOwners_k.curveOwner) == null ? void 0 : _layerOwners_k_curveOwner.revertDefaultValue();
31982
+ }
31952
31983
  }
31953
31984
  }
31954
31985
  this._animatorLayersData.length = 0;
31955
- this._curveOwnerPool = Object.create(null);
31986
+ this._curveOwnerPool = new WeakMap();
31956
31987
  this._parametersValueMap = Object.create(null);
31957
31988
  if (this._controllerUpdateFlag) {
31958
31989
  this._controllerUpdateFlag.flag = false;
@@ -31975,6 +32006,7 @@ function _type_of(obj) {
31975
32006
  };
31976
32007
  _proto._onDestroy = function _onDestroy() {
31977
32008
  Component.prototype._onDestroy.call(this);
32009
+ this._reset();
31978
32010
  var controller = this._animatorController;
31979
32011
  if (controller) {
31980
32012
  var _this__controllerUpdateFlag;
@@ -31988,7 +32020,8 @@ function _type_of(obj) {
31988
32020
  if (!state) {
31989
32021
  return;
31990
32022
  }
31991
- var manuallyTransition = this._getAnimatorLayerData(playLayerIndex).manuallyTransition;
32023
+ var animatorLayerData = this._getAnimatorLayerData(playLayerIndex);
32024
+ var manuallyTransition = animatorLayerData.manuallyTransition;
31992
32025
  manuallyTransition.duration = duration;
31993
32026
  manuallyTransition.offset = normalizedTimeOffset;
31994
32027
  manuallyTransition.isFixedDuration = isFixedDuration;
@@ -32043,20 +32076,30 @@ function _type_of(obj) {
32043
32076
  var relativePath = curve.relativePath;
32044
32077
  var targetEntity = curve.relativePath === "" ? entity : entity.findByPath(curve.relativePath);
32045
32078
  if (targetEntity) {
32046
- var _curveOwnerPool, _instanceId, _propertyOwners, _property, _layerCurveOwnerPool, _instanceId1, _layerPropertyOwners, _property1;
32079
+ var _layerPropertyOwners, _property;
32047
32080
  var component = curve.typeIndex > 0 ? targetEntity.getComponents(curve.type, components)[curve.typeIndex] : targetEntity.getComponent(curve.type);
32048
32081
  components.length = 0;
32049
32082
  if (!component) {
32050
32083
  continue;
32051
32084
  }
32052
32085
  var property = curve.property;
32053
- var instanceId = component.instanceId;
32054
- // Get owner
32055
- var propertyOwners = (_curveOwnerPool = curveOwnerPool)[_instanceId = instanceId] || (_curveOwnerPool[_instanceId] = Object.create(null));
32056
- var owner = (_propertyOwners = propertyOwners)[_property = property] || (_propertyOwners[_property] = curve._createCurveOwner(targetEntity, component));
32057
- // Get layer owner
32058
- var layerPropertyOwners = (_layerCurveOwnerPool = layerCurveOwnerPool)[_instanceId1 = instanceId] || (_layerCurveOwnerPool[_instanceId1] = Object.create(null));
32059
- var layerOwner = (_layerPropertyOwners = layerPropertyOwners)[_property1 = property] || (_layerPropertyOwners[_property1] = curve._createCurveLayerOwner(owner));
32086
+ // Key owner lookup by Component identity instead of instanceId.
32087
+ var propertyOwners = curveOwnerPool.get(component);
32088
+ if (!propertyOwners) {
32089
+ propertyOwners = Object.create(null);
32090
+ curveOwnerPool.set(component, propertyOwners);
32091
+ }
32092
+ var owner = propertyOwners[property];
32093
+ if (!owner) {
32094
+ owner = curve._createCurveOwner(targetEntity, component);
32095
+ propertyOwners[property] = owner;
32096
+ }
32097
+ var layerPropertyOwners = layerCurveOwnerPool.get(component);
32098
+ if (!layerPropertyOwners) {
32099
+ layerPropertyOwners = Object.create(null);
32100
+ layerCurveOwnerPool.set(component, layerPropertyOwners);
32101
+ }
32102
+ var layerOwner = (_layerPropertyOwners = layerPropertyOwners)[_property = property] || (_layerPropertyOwners[_property] = curve._createCurveLayerOwner(owner));
32060
32103
  if (mask && mask.pathMasks.length) {
32061
32104
  var _mask_getPathMask;
32062
32105
  var _mask_getPathMask_active;
@@ -32070,8 +32113,6 @@ function _type_of(obj) {
32070
32113
  }
32071
32114
  };
32072
32115
  _proto._ensureEventHandlers = function _ensureEventHandlers(state, animatorStateData) {
32073
- // state._updateFlagManager dispatches on both clip-swap and clip-events-mutation,
32074
- // so its version covers every input that affects eventHandlers binding
32075
32116
  var stateVersion = state._updateFlagManager.version;
32076
32117
  var scriptsVersion = this._entity._scriptsVersion;
32077
32118
  if (animatorStateData.eventsBuiltVersion === stateVersion && animatorStateData.eventsBuiltScriptsVersion === scriptsVersion) {
@@ -32195,8 +32236,8 @@ function _type_of(obj) {
32195
32236
  };
32196
32237
  _proto._updatePlayingState = function _updatePlayingState(layerData, weight, additive, deltaTime, aniUpdate) {
32197
32238
  var srcPlayData = layerData.srcPlayData;
32198
- var state = srcPlayData.instance._state;
32199
- var playSpeed = srcPlayData.instance.speed * this.speed;
32239
+ var state = srcPlayData.state;
32240
+ var playSpeed = srcPlayData.speed * this.speed;
32200
32241
  var playDeltaTime = playSpeed * deltaTime;
32201
32242
  srcPlayData.updateOrientation(playDeltaTime);
32202
32243
  var lastClipTime = srcPlayData.clipTime, lastPlayState = srcPlayData.playState;
@@ -32240,14 +32281,13 @@ function _type_of(obj) {
32240
32281
  this._evaluatePlayingState(srcPlayData, weight, additive, aniUpdate);
32241
32282
  this._fireAnimationEventsAndCallScripts(layerData.layerIndex, srcPlayData, state, lastClipTime, lastPlayState, playCostTime);
32242
32283
  if (transition) {
32243
- // Remove speed factor, use actual cost time. Per-instance speed=0 means the source
32244
- // state is paused, so it consumes no time — pass deltaTime through to the destination.
32284
+ // Remove speed factor, use actual cost time
32245
32285
  var remainDeltaTime = playSpeed === 0 ? deltaTime : deltaTime - playCostTime / playSpeed;
32246
32286
  remainDeltaTime > 0 && this._updateState(layerData, remainDeltaTime, aniUpdate);
32247
32287
  }
32248
32288
  };
32249
32289
  _proto._evaluatePlayingState = function _evaluatePlayingState(playData, weight, additive, aniUpdate) {
32250
- var curveBindings = playData.instance.clip._curveBindings;
32290
+ var curveBindings = playData.state.clip._curveBindings;
32251
32291
  var finished = playData.playState === AnimatorStatePlayState.Finished;
32252
32292
  if (aniUpdate || finished) {
32253
32293
  var curveLayerOwner = playData.stateData.curveLayerOwner;
@@ -32270,14 +32310,14 @@ function _type_of(obj) {
32270
32310
  _proto._updateCrossFadeState = function _updateCrossFadeState(layerData, weight, additive, deltaTime, aniUpdate) {
32271
32311
  var srcPlayData = layerData.srcPlayData, destPlayData = layerData.destPlayData, layerIndex = layerData.layerIndex;
32272
32312
  var speed = this.speed;
32273
- var srcState = srcPlayData.instance._state;
32274
- var destState = destPlayData.instance._state;
32313
+ var srcState = srcPlayData.state;
32314
+ var destState = destPlayData.state;
32275
32315
  var transitionDuration = layerData.crossFadeTransition._getFixedDuration();
32276
32316
  if (this._tryCrossFadeInterrupt(layerData, transitionDuration, destState, deltaTime, aniUpdate)) {
32277
32317
  return;
32278
32318
  }
32279
- var srcPlaySpeed = srcPlayData.instance.speed * speed;
32280
- var dstPlaySpeed = destPlayData.instance.speed * speed;
32319
+ var srcPlaySpeed = srcPlayData.speed * speed;
32320
+ var dstPlaySpeed = destPlayData.speed * speed;
32281
32321
  var dstPlayDeltaTime = dstPlaySpeed * deltaTime;
32282
32322
  srcPlayData.updateOrientation(srcPlaySpeed * deltaTime);
32283
32323
  destPlayData.updateOrientation(dstPlayDeltaTime);
@@ -32320,8 +32360,8 @@ function _type_of(obj) {
32320
32360
  };
32321
32361
  _proto._evaluateCrossFadeState = function _evaluateCrossFadeState(layerData, srcPlayData, destPlayData, weight, crossWeight, additive, aniUpdate) {
32322
32362
  var crossLayerOwnerCollection = layerData.crossLayerOwnerCollection;
32323
- var _srcPlayData_instance_clip = srcPlayData.instance.clip, srcCurves = _srcPlayData_instance_clip._curveBindings;
32324
- var destState = destPlayData.instance._state;
32363
+ var _srcPlayData_state_clip = srcPlayData.state.clip, srcCurves = _srcPlayData_state_clip._curveBindings;
32364
+ var destState = destPlayData.state;
32325
32365
  var _destState_clip = destState.clip, destCurves = _destState_clip._curveBindings;
32326
32366
  var finished = destPlayData.playState === AnimatorStatePlayState.Finished;
32327
32367
  if (aniUpdate || finished) {
@@ -32340,12 +32380,12 @@ function _type_of(obj) {
32340
32380
  };
32341
32381
  _proto._updateCrossFadeFromPoseState = function _updateCrossFadeFromPoseState(layerData, weight, additive, deltaTime, aniUpdate) {
32342
32382
  var destPlayData = layerData.destPlayData;
32343
- var state = destPlayData.instance._state;
32383
+ var state = destPlayData.state;
32344
32384
  var transitionDuration = layerData.crossFadeTransition._getFixedDuration();
32345
32385
  if (this._tryCrossFadeInterrupt(layerData, transitionDuration, state, deltaTime, aniUpdate)) {
32346
32386
  return;
32347
32387
  }
32348
- var playSpeed = destPlayData.instance.speed * this.speed;
32388
+ var playSpeed = destPlayData.speed * this.speed;
32349
32389
  var playDeltaTime = playSpeed * deltaTime;
32350
32390
  destPlayData.updateOrientation(playDeltaTime);
32351
32391
  var lastDestClipTime = destPlayData.clipTime, lastPlayState = destPlayData.playState;
@@ -32382,7 +32422,7 @@ function _type_of(obj) {
32382
32422
  };
32383
32423
  _proto._evaluateCrossFadeFromPoseState = function _evaluateCrossFadeFromPoseState(layerData, destPlayData, weight, crossWeight, additive, aniUpdate) {
32384
32424
  var crossLayerOwnerCollection = layerData.crossLayerOwnerCollection;
32385
- var state = destPlayData.instance._state;
32425
+ var state = destPlayData.state;
32386
32426
  var _state_clip = state.clip, curveBindings = _state_clip._curveBindings;
32387
32427
  var destClipTime = destPlayData.clipTime, playState = destPlayData.playState;
32388
32428
  var finished = playState === AnimatorStatePlayState.Finished;
@@ -32394,7 +32434,7 @@ function _type_of(obj) {
32394
32434
  if (!owner) continue;
32395
32435
  var curveIndex = layerOwner.crossDestCurveIndex;
32396
32436
  this._checkRevertOwner(owner, additive);
32397
- var value = layerOwner.curveOwner.crossFadeFromPoseAndApplyValue(curveIndex >= 0 ? curveBindings[curveIndex].curve : null, destClipTime, crossWeight, additive);
32437
+ var value = owner.crossFadeFromPoseAndApplyValue(curveIndex >= 0 ? curveBindings[curveIndex].curve : null, destClipTime, crossWeight, additive);
32398
32438
  aniUpdate && owner.applyValue(value, weight, additive);
32399
32439
  finished && layerOwner.saveFinalValue();
32400
32440
  }
@@ -32402,8 +32442,8 @@ function _type_of(obj) {
32402
32442
  };
32403
32443
  _proto._updateFinishedState = function _updateFinishedState(layerData, weight, additive, deltaTime, aniUpdate) {
32404
32444
  var playData = layerData.srcPlayData;
32405
- var state = playData.instance._state;
32406
- var actualSpeed = playData.instance.speed * this.speed;
32445
+ var state = playData.state;
32446
+ var actualSpeed = playData.speed * this.speed;
32407
32447
  var actualDeltaTime = actualSpeed * deltaTime;
32408
32448
  playData.updateOrientation(actualDeltaTime);
32409
32449
  var clipTime = playData.clipTime, isForward = playData.isForward;
@@ -32421,7 +32461,7 @@ function _type_of(obj) {
32421
32461
  return;
32422
32462
  }
32423
32463
  var curveLayerOwner = playData.stateData.curveLayerOwner;
32424
- var _playData_instance_clip = playData.instance.clip, curveBindings = _playData_instance_clip._curveBindings;
32464
+ var _playData_state_clip = playData.state.clip, curveBindings = _playData_state_clip._curveBindings;
32425
32465
  for(var i = curveBindings.length - 1; i >= 0; i--){
32426
32466
  var layerOwner = curveLayerOwner[i];
32427
32467
  var owner = layerOwner == null ? void 0 : layerOwner.curveOwner;
@@ -32437,12 +32477,14 @@ function _type_of(obj) {
32437
32477
  } else {
32438
32478
  layerData.layerState = LayerState.Playing;
32439
32479
  }
32440
- layerData.completeCrossFade();
32480
+ layerData.srcPlayData = destPlayData;
32481
+ layerData.destPlayData = null;
32482
+ layerData.crossFadeTransition = null;
32441
32483
  };
32442
32484
  _proto._preparePlayOwner = function _preparePlayOwner(layerData, playState) {
32443
32485
  if (layerData.layerState === LayerState.Playing) {
32444
32486
  var srcPlayData = layerData.srcPlayData;
32445
- if (srcPlayData.instance._state !== playState) {
32487
+ if (srcPlayData.state !== playState) {
32446
32488
  var curveLayerOwner = srcPlayData.stateData.curveLayerOwner;
32447
32489
  for(var i = curveLayerOwner.length - 1; i >= 0; i--){
32448
32490
  var _curveLayerOwner_i;
@@ -32457,17 +32499,17 @@ function _type_of(obj) {
32457
32499
  }
32458
32500
  };
32459
32501
  _proto._applyStateTransitions = function _applyStateTransitions(layerData, isForward, playData, transitionCollection, lastClipTime, clipTime, deltaTime, aniUpdate) {
32460
- var state = playData.instance._state;
32461
- var clipDuration = state.clip.length;
32502
+ var state = playData.state;
32462
32503
  var targetTransition = null;
32463
- var startTime = state.clipStartTime * clipDuration;
32464
- var endTime = state.clipEndTime * clipDuration;
32465
32504
  if (transitionCollection.noExitTimeCount) {
32466
32505
  targetTransition = this._checkNoExitTimeTransitions(layerData, transitionCollection, aniUpdate);
32467
32506
  if (targetTransition) {
32468
32507
  return targetTransition;
32469
32508
  }
32470
32509
  }
32510
+ var clipDuration = state.clip.length;
32511
+ var startTime = state.clipStartTime * clipDuration;
32512
+ var endTime = state.clipEndTime * clipDuration;
32471
32513
  if (isForward) {
32472
32514
  if (lastClipTime + deltaTime >= endTime) {
32473
32515
  targetTransition = this._checkSubTransition(layerData, state, transitionCollection, lastClipTime, endTime, aniUpdate);
@@ -32574,9 +32616,8 @@ function _type_of(obj) {
32574
32616
  var playData = animatorLayerData.getOrCreateInstance(state)._playData;
32575
32617
  playData.reset(animatorStateData, state._getClipActualEndTime() * normalizedTimeOffset);
32576
32618
  animatorLayerData.srcPlayData = playData;
32577
- // Drop any dangling cross-fade slot from a previously-interrupted crossFade
32578
- // so a later crossFade(B) isn't wrongly no-op'd by the active-dest guard.
32579
- animatorLayerData.clearCrossFadeSlot();
32619
+ animatorLayerData.destPlayData = null;
32620
+ animatorLayerData.crossFadeTransition = null;
32580
32621
  animatorLayerData.resetCurrentCheckIndex();
32581
32622
  return true;
32582
32623
  };
@@ -32660,9 +32701,7 @@ function _type_of(obj) {
32660
32701
  return false;
32661
32702
  }
32662
32703
  var animatorLayerData = this._getAnimatorLayerData(layerIndex);
32663
- // Self/active-dest cross-fade is a no-op: each state has one persistent
32664
- // instance per layer, so a second concurrent fade has nowhere to live.
32665
- if (((_animatorLayerData_srcPlayData = animatorLayerData.srcPlayData) == null ? void 0 : _animatorLayerData_srcPlayData.instance._state) === crossState || ((_animatorLayerData_destPlayData = animatorLayerData.destPlayData) == null ? void 0 : _animatorLayerData_destPlayData.instance._state) === crossState) {
32704
+ if (((_animatorLayerData_srcPlayData = animatorLayerData.srcPlayData) == null ? void 0 : _animatorLayerData_srcPlayData.state) === crossState || ((_animatorLayerData_destPlayData = animatorLayerData.destPlayData) == null ? void 0 : _animatorLayerData_destPlayData.state) === crossState) {
32666
32705
  return false;
32667
32706
  }
32668
32707
  var animatorStateData = this._getAnimatorStateData(crossState, animatorLayerData, layerIndex);
@@ -32694,23 +32733,27 @@ function _type_of(obj) {
32694
32733
  return true;
32695
32734
  };
32696
32735
  _proto._fireAnimationEvents = function _fireAnimationEvents(playData, eventHandlers, lastClipTime, deltaTime) {
32697
- var isForward = playData.isForward, clipTime = playData.clipTime;
32698
- var state = playData.instance._state;
32736
+ var state = playData.state, isForward = playData.isForward, clipTime = playData.clipTime, wrapMode = playData.wrapMode;
32699
32737
  var startTime = state._getClipActualStartTime();
32700
32738
  var endTime = state._getClipActualEndTime();
32739
+ var canWrap = wrapMode === WrapMode.Loop;
32701
32740
  if (isForward) {
32702
32741
  if (lastClipTime + deltaTime >= endTime) {
32703
32742
  this._fireSubAnimationEvents(playData, eventHandlers, lastClipTime, endTime);
32704
- playData.currentEventIndex = 0;
32705
- this._fireSubAnimationEvents(playData, eventHandlers, startTime, clipTime);
32743
+ if (canWrap) {
32744
+ playData.currentEventIndex = 0;
32745
+ this._fireSubAnimationEvents(playData, eventHandlers, startTime, clipTime);
32746
+ }
32706
32747
  } else {
32707
32748
  this._fireSubAnimationEvents(playData, eventHandlers, lastClipTime, clipTime);
32708
32749
  }
32709
32750
  } else {
32710
32751
  if (lastClipTime + deltaTime <= startTime) {
32711
32752
  this._fireBackwardSubAnimationEvents(playData, eventHandlers, lastClipTime, startTime);
32712
- playData.currentEventIndex = eventHandlers.length - 1;
32713
- this._fireBackwardSubAnimationEvents(playData, eventHandlers, endTime, clipTime);
32753
+ if (canWrap) {
32754
+ playData.currentEventIndex = eventHandlers.length - 1;
32755
+ this._fireBackwardSubAnimationEvents(playData, eventHandlers, endTime, clipTime);
32756
+ }
32714
32757
  } else {
32715
32758
  this._fireBackwardSubAnimationEvents(playData, eventHandlers, lastClipTime, clipTime);
32716
32759
  }
@@ -32726,8 +32769,10 @@ function _type_of(obj) {
32726
32769
  }
32727
32770
  var handlers = eventHandler.handlers;
32728
32771
  if (time >= lastClipTime) {
32729
- for(var j = handlers.length - 1; j >= 0; j--){
32730
- handlers[j](parameter);
32772
+ if (this.fireEvents) {
32773
+ for(var j = handlers.length - 1; j >= 0; j--){
32774
+ handlers[j](parameter);
32775
+ }
32731
32776
  }
32732
32777
  playState.currentEventIndex = Math.min(eventIndex + 1, n - 1);
32733
32778
  }
@@ -32743,8 +32788,10 @@ function _type_of(obj) {
32743
32788
  }
32744
32789
  if (time <= lastClipTime) {
32745
32790
  var handlers = eventHandler.handlers;
32746
- for(var j = handlers.length - 1; j >= 0; j--){
32747
- handlers[j](parameter);
32791
+ if (this.fireEvents) {
32792
+ for(var j = handlers.length - 1; j >= 0; j--){
32793
+ handlers[j](parameter);
32794
+ }
32748
32795
  }
32749
32796
  playState.currentEventIndex = Math.max(eventIndex - 1, 0);
32750
32797
  }
@@ -32775,9 +32822,6 @@ function _type_of(obj) {
32775
32822
  owner.updateMark = this._updateMark;
32776
32823
  };
32777
32824
  _proto._fireAnimationEventsAndCallScripts = function _fireAnimationEventsAndCallScripts(layerIndex, playData, state, lastClipTime, lastPlayState, deltaTime) {
32778
- // Re-check whether the clip events/scripts changed since the last build —
32779
- // play()/crossFade() entry points already ensure on enter, but addEvent()
32780
- // or addComponent(Script) after play() must also flow through.
32781
32825
  this._ensureEventHandlers(state, playData.stateData);
32782
32826
  var eventHandlers = playData.stateData.eventHandlers;
32783
32827
  eventHandlers.length && this._fireAnimationEvents(playData, eventHandlers, lastClipTime, deltaTime);
@@ -32845,6 +32889,9 @@ Animator._tempScripts = [];
32845
32889
  __decorate([
32846
32890
  assignmentClone
32847
32891
  ], Animator.prototype, "speed", void 0);
32892
+ __decorate([
32893
+ assignmentClone
32894
+ ], Animator.prototype, "fireEvents", void 0);
32848
32895
  __decorate([
32849
32896
  assignmentClone
32850
32897
  ], Animator.prototype, "_animatorController", void 0);
@@ -32916,7 +32963,10 @@ function _assert_this_initialized(self) {
32916
32963
  /** @internal */ _this._parametersMap = {},
32917
32964
  /** @internal */ _this._layers = [],
32918
32965
  /** @internal */ _this._layersMap = {},
32919
- _this._updateFlagManager = new UpdateFlagManager()
32966
+ _this._updateFlagManager = new UpdateFlagManager(),
32967
+ _this._onStatesInvalidate = function() {
32968
+ return _this._updateFlagManager.dispatch();
32969
+ }
32920
32970
  ][0];
32921
32971
  return _assert_this_initialized(_this);
32922
32972
  }
@@ -32971,6 +33021,7 @@ function _assert_this_initialized(self) {
32971
33021
  */ _proto.addLayer = function addLayer(layer) {
32972
33022
  this._layers.push(layer);
32973
33023
  this._layersMap[layer.name] = layer;
33024
+ layer._setStatesInvalidateCallback(this._onStatesInvalidate);
32974
33025
  layer._setEngine(this._engine);
32975
33026
  this._updateFlagManager.dispatch();
32976
33027
  };
@@ -32980,13 +33031,18 @@ function _assert_this_initialized(self) {
32980
33031
  */ _proto.removeLayer = function removeLayer(layerIndex) {
32981
33032
  var theLayer = this.layers[layerIndex];
32982
33033
  this._layers.splice(layerIndex, 1);
33034
+ theLayer._setStatesInvalidateCallback(null);
32983
33035
  delete this._layersMap[theLayer.name];
32984
33036
  this._updateFlagManager.dispatch();
32985
33037
  };
32986
33038
  /**
32987
33039
  * Clear layers.
32988
33040
  */ _proto.clearLayers = function clearLayers() {
32989
- this._layers.length = 0;
33041
+ var _this = this, layers = _this._layers;
33042
+ for(var i = 0, n = layers.length; i < n; i++){
33043
+ layers[i]._setStatesInvalidateCallback(null);
33044
+ }
33045
+ layers.length = 0;
32990
33046
  for(var name in this._layersMap){
32991
33047
  delete this._layersMap[name];
32992
33048
  }
@@ -33002,7 +33058,9 @@ function _assert_this_initialized(self) {
33002
33058
  */ _proto._setEngine = function _setEngine(engine) {
33003
33059
  var _this = this, layers = _this._layers;
33004
33060
  for(var i = 0, n = layers.length; i < n; i++){
33005
- layers[i]._setEngine(engine);
33061
+ var layer = layers[i];
33062
+ layer._setStatesInvalidateCallback(this._onStatesInvalidate);
33063
+ layer._setEngine(engine);
33006
33064
  }
33007
33065
  };
33008
33066
  _proto._addParameter = function _addParameter(name, defaultValue, isTrigger) {
@@ -33389,6 +33447,7 @@ function _assert_this_initialized(self) {
33389
33447
  */ var AnimatorStateMachine = /*#__PURE__*/ function() {
33390
33448
  function AnimatorStateMachine() {
33391
33449
  /** The list of states. */ this.states = [];
33450
+ this._onStatesInvalidate = null;
33392
33451
  /**
33393
33452
  * The state will be played automatically.
33394
33453
  * @remarks When the Animator's AnimatorController changed or the Animator's onEnable be triggered. Cleared to `null` if the state is removed via `removeState`.
@@ -33425,6 +33484,7 @@ function _assert_this_initialized(self) {
33425
33484
  if (this.defaultState === state) {
33426
33485
  this.defaultState = null;
33427
33486
  }
33487
+ this._onStatesInvalidate == null ? void 0 : this._onStatesInvalidate.call(this);
33428
33488
  }
33429
33489
  };
33430
33490
  /**
@@ -33484,6 +33544,11 @@ function _assert_this_initialized(self) {
33484
33544
  states[i]._setEngine(engine);
33485
33545
  }
33486
33546
  };
33547
+ /**
33548
+ * @internal
33549
+ */ _proto._setStatesInvalidateCallback = function _setStatesInvalidateCallback(onStatesInvalidate) {
33550
+ this._onStatesInvalidate = onStatesInvalidate;
33551
+ };
33487
33552
  _create_class(AnimatorStateMachine, [
33488
33553
  {
33489
33554
  key: "entryTransitions",
@@ -33512,14 +33577,43 @@ function _assert_this_initialized(self) {
33512
33577
  this.name = name;
33513
33578
  this./** The blending weight that the layers has. It is not taken into account for the first layer. */ weight = 1.0;
33514
33579
  this./** The blending mode used by the layer. It is not taken into account for the first layer. */ blendingMode = AnimatorLayerBlendingMode.Override;
33515
- this.stateMachine = new AnimatorStateMachine();
33580
+ this._onStatesInvalidate = null;
33581
+ this._stateMachine = new AnimatorStateMachine();
33516
33582
  }
33517
33583
  var _proto = AnimatorControllerLayer.prototype;
33518
33584
  /**
33519
33585
  * @internal
33520
33586
  */ _proto._setEngine = function _setEngine(engine) {
33521
- this.stateMachine._setEngine(engine);
33587
+ this._engine = engine;
33588
+ this._stateMachine._setEngine(engine);
33522
33589
  };
33590
+ /**
33591
+ * @internal
33592
+ */ _proto._setStatesInvalidateCallback = function _setStatesInvalidateCallback(onStatesInvalidate) {
33593
+ this._onStatesInvalidate = onStatesInvalidate;
33594
+ this._stateMachine._setStatesInvalidateCallback(onStatesInvalidate);
33595
+ };
33596
+ _create_class(AnimatorControllerLayer, [
33597
+ {
33598
+ key: "stateMachine",
33599
+ get: /**
33600
+ * The state machine for the layer.
33601
+ */ function get() {
33602
+ return this._stateMachine;
33603
+ },
33604
+ set: function set(value) {
33605
+ var lastStateMachine = this._stateMachine;
33606
+ if (lastStateMachine === value) {
33607
+ return;
33608
+ }
33609
+ lastStateMachine._setStatesInvalidateCallback(null);
33610
+ this._stateMachine = value;
33611
+ value._setStatesInvalidateCallback(this._onStatesInvalidate);
33612
+ this._engine && value._setEngine(this._engine);
33613
+ this._onStatesInvalidate == null ? void 0 : this._onStatesInvalidate.call(this);
33614
+ }
33615
+ }
33616
+ ]);
33523
33617
  return AnimatorControllerLayer;
33524
33618
  }();
33525
33619
 
@@ -33888,8 +33982,10 @@ var ParticleStopMode = /*#__PURE__*/ function(ParticleStopMode) {
33888
33982
  /**
33889
33983
  * @internal
33890
33984
  */ _proto._onEnable = function _onEnable() {
33891
- if (this.generator.main.playOnEnabled) {
33892
- this.generator.play(false);
33985
+ var generator = this.generator;
33986
+ generator._setTransformFeedback();
33987
+ if (generator.main.playOnEnabled) {
33988
+ generator.play(false);
33893
33989
  }
33894
33990
  };
33895
33991
  /**
@@ -34484,6 +34580,14 @@ ParticleTransformFeedbackSimulator._deltaTimeProperty = ShaderProperty.getByName
34484
34580
  return ParticleGradientMode;
34485
34581
  }({});
34486
34582
 
34583
+ /**
34584
+ * Particle sub emitter trigger type.
34585
+ */ var ParticleSubEmitterType = /*#__PURE__*/ function(ParticleSubEmitterType) {
34586
+ /** Triggered when a parent particle is born. */ ParticleSubEmitterType[ParticleSubEmitterType["Birth"] = 0] = "Birth";
34587
+ /** Triggered when a parent particle dies (lifetime expired). */ ParticleSubEmitterType[ParticleSubEmitterType["Death"] = 1] = "Death";
34588
+ return ParticleSubEmitterType;
34589
+ }({});
34590
+
34487
34591
  /**
34488
34592
  * @internal
34489
34593
  */ var ParticleRandomSubSeeds = /*#__PURE__*/ function(ParticleRandomSubSeeds) {
@@ -34505,6 +34609,7 @@ ParticleTransformFeedbackSimulator._deltaTimeProperty = ShaderProperty.getByName
34505
34609
  ParticleRandomSubSeeds[ParticleRandomSubSeeds["ForceOverLifetime"] = 3875246972] = "ForceOverLifetime";
34506
34610
  ParticleRandomSubSeeds[ParticleRandomSubSeeds["LimitVelocityOverLifetime"] = 3047300990] = "LimitVelocityOverLifetime";
34507
34611
  ParticleRandomSubSeeds[ParticleRandomSubSeeds["Noise"] = 4105357473] = "Noise";
34612
+ ParticleRandomSubSeeds[ParticleRandomSubSeeds["SubEmitter"] = 2622110509] = "SubEmitter";
34508
34613
  ParticleRandomSubSeeds[ParticleRandomSubSeeds["EmissionRate"] = 2625893077] = "EmissionRate";
34509
34614
  return ParticleRandomSubSeeds;
34510
34615
  }({});
@@ -34574,6 +34679,12 @@ ParticleTransformFeedbackSimulator._deltaTimeProperty = ShaderProperty.getByName
34574
34679
  * @param colorKeys - The color keys
34575
34680
  * @param alphaKeys - The alpha keys
34576
34681
  */ _proto.setKeys = function setKeys(colorKeys, alphaKeys) {
34682
+ if (colorKeys.length > 4) {
34683
+ throw new Error("Gradient can only have 4 color keys");
34684
+ }
34685
+ if (alphaKeys.length > 4) {
34686
+ throw new Error("Gradient can only have 4 alpha keys");
34687
+ }
34577
34688
  var currentColorKeys = this._colorKeys;
34578
34689
  var currentAlphaKeys = this._alphaKeys;
34579
34690
  for(var i = 0, n = currentColorKeys.length; i < n; i++){
@@ -34628,6 +34739,60 @@ ParticleTransformFeedbackSimulator._deltaTimeProperty = ShaderProperty.getByName
34628
34739
  }
34629
34740
  return typeArray;
34630
34741
  };
34742
+ /**
34743
+ * @internal
34744
+ */ _proto._evaluate = function _evaluate(time, out) {
34745
+ var alphaKeys = this._alphaKeys;
34746
+ var alphaCount = alphaKeys.length;
34747
+ if (alphaCount === 0) {
34748
+ out.a = 0;
34749
+ } else {
34750
+ var alphaMaxTime = alphaKeys[alphaCount - 1].time;
34751
+ var alphaT = Math.min(time, alphaMaxTime);
34752
+ for(var i = 0; i < alphaCount; i++){
34753
+ var key = alphaKeys[i];
34754
+ if (alphaT <= key.time) {
34755
+ if (i === 0) {
34756
+ out.a = key.alpha;
34757
+ } else {
34758
+ var lastKey = alphaKeys[i - 1];
34759
+ var age = (alphaT - lastKey.time) / (key.time - lastKey.time);
34760
+ out.a = lastKey.alpha + (key.alpha - lastKey.alpha) * age;
34761
+ }
34762
+ break;
34763
+ }
34764
+ }
34765
+ }
34766
+ var colorKeys = this._colorKeys;
34767
+ var colorCount = colorKeys.length;
34768
+ if (colorCount === 0) {
34769
+ out.r = 0;
34770
+ out.g = 0;
34771
+ out.b = 0;
34772
+ } else {
34773
+ var colorMaxTime = colorKeys[colorCount - 1].time;
34774
+ var colorT = Math.min(time, colorMaxTime);
34775
+ for(var i1 = 0; i1 < colorCount; i1++){
34776
+ var key1 = colorKeys[i1];
34777
+ if (colorT <= key1.time) {
34778
+ var c = key1.color;
34779
+ if (i1 === 0) {
34780
+ out.r = c.r;
34781
+ out.g = c.g;
34782
+ out.b = c.b;
34783
+ } else {
34784
+ var lastKey1 = colorKeys[i1 - 1];
34785
+ var last = lastKey1.color;
34786
+ var age1 = (colorT - lastKey1.time) / (key1.time - lastKey1.time);
34787
+ out.r = last.r + (c.r - last.r) * age1;
34788
+ out.g = last.g + (c.g - last.g) * age1;
34789
+ out.b = last.b + (c.b - last.b) * age1;
34790
+ }
34791
+ break;
34792
+ }
34793
+ }
34794
+ }
34795
+ };
34631
34796
  _proto._addKey = function _addKey(keys, key) {
34632
34797
  var time = key.time;
34633
34798
  var count = keys.length;
@@ -34807,6 +34972,17 @@ __decorate([
34807
34972
  case ParticleGradientMode.TwoConstants:
34808
34973
  Color.lerp(this.constantMin, this.constantMax, lerpFactor, out);
34809
34974
  break;
34975
+ case ParticleGradientMode.Gradient:
34976
+ this.gradientMax._evaluate(time, out);
34977
+ break;
34978
+ case ParticleGradientMode.TwoGradients:
34979
+ {
34980
+ var tmp = ParticleCompositeGradient._tempColor;
34981
+ this.gradientMin._evaluate(time, tmp);
34982
+ this.gradientMax._evaluate(time, out);
34983
+ Color.lerp(tmp, out, lerpFactor, out);
34984
+ break;
34985
+ }
34810
34986
  }
34811
34987
  };
34812
34988
  _create_class(ParticleCompositeGradient, [
@@ -34835,6 +35011,7 @@ __decorate([
34835
35011
  ]);
34836
35012
  return ParticleCompositeGradient;
34837
35013
  }();
35014
+ ParticleCompositeGradient._tempColor = new Color();
34838
35015
  __decorate([
34839
35016
  deepClone
34840
35017
  ], ParticleCompositeGradient.prototype, "constantMin", void 0);
@@ -35012,7 +35189,33 @@ __decorate([
35012
35189
  };
35013
35190
  /**
35014
35191
  * @internal
35192
+ */ _proto._evaluateCumulative = function _evaluateCumulative(normalizedAge, lerpFactor) {
35193
+ switch(this.mode){
35194
+ case ParticleCurveMode.Constant:
35195
+ return this.constantMax * normalizedAge;
35196
+ case ParticleCurveMode.TwoConstants:
35197
+ return (this.constantMin + (this.constantMax - this.constantMin) * lerpFactor) * normalizedAge;
35198
+ case ParticleCurveMode.Curve:
35199
+ var _this_curveMax;
35200
+ var _this_curveMax__evaluateCumulative;
35201
+ return (_this_curveMax__evaluateCumulative = (_this_curveMax = this.curveMax) == null ? void 0 : _this_curveMax._evaluateCumulative(normalizedAge)) != null ? _this_curveMax__evaluateCumulative : 0;
35202
+ case ParticleCurveMode.TwoCurves:
35203
+ {
35204
+ var _this_curveMin, _this_curveMax1;
35205
+ var _this_curveMin__evaluateCumulative;
35206
+ var min = (_this_curveMin__evaluateCumulative = (_this_curveMin = this.curveMin) == null ? void 0 : _this_curveMin._evaluateCumulative(normalizedAge)) != null ? _this_curveMin__evaluateCumulative : 0;
35207
+ var _this_curveMax__evaluateCumulative1;
35208
+ var max = (_this_curveMax__evaluateCumulative1 = (_this_curveMax1 = this.curveMax) == null ? void 0 : _this_curveMax1._evaluateCumulative(normalizedAge)) != null ? _this_curveMax__evaluateCumulative1 : 0;
35209
+ return min + (max - min) * lerpFactor;
35210
+ }
35211
+ default:
35212
+ return 0;
35213
+ }
35214
+ };
35215
+ /**
35216
+ * @internal
35015
35217
  */ _proto._getMax = function _getMax() {
35218
+ var minMaxRange = ParticleCompositeCurve._minMaxRange;
35016
35219
  switch(this.mode){
35017
35220
  case ParticleCurveMode.Constant:
35018
35221
  return this.constantMax;
@@ -35020,17 +35223,18 @@ __decorate([
35020
35223
  return Math.max(this.constantMin, this.constantMax);
35021
35224
  case ParticleCurveMode.Curve:
35022
35225
  var _this_curveMax;
35023
- return this._getMaxKeyValue((_this_curveMax = this.curveMax) == null ? void 0 : _this_curveMax.keys);
35226
+ this._getKeyMinMax((_this_curveMax = this.curveMax) == null ? void 0 : _this_curveMax.keys, minMaxRange);
35227
+ return minMaxRange.y;
35024
35228
  case ParticleCurveMode.TwoCurves:
35025
35229
  var _this_curveMin, _this_curveMax1;
35026
- var min = this._getMaxKeyValue((_this_curveMin = this.curveMin) == null ? void 0 : _this_curveMin.keys);
35027
- var max = this._getMaxKeyValue((_this_curveMax1 = this.curveMax) == null ? void 0 : _this_curveMax1.keys);
35028
- return min > max ? min : max;
35230
+ this._getKeyMinMax((_this_curveMin = this.curveMin) == null ? void 0 : _this_curveMin.keys, minMaxRange);
35231
+ var maxCurveMin = minMaxRange.y;
35232
+ this._getKeyMinMax((_this_curveMax1 = this.curveMax) == null ? void 0 : _this_curveMax1.keys, minMaxRange);
35233
+ return maxCurveMin > minMaxRange.y ? maxCurveMin : minMaxRange.y;
35029
35234
  }
35030
35235
  };
35031
35236
  /**
35032
35237
  * @internal
35033
-
35034
35238
  */ _proto._getMinMax = function _getMinMax(out) {
35035
35239
  switch(this.mode){
35036
35240
  case ParticleCurveMode.Constant:
@@ -35040,23 +35244,40 @@ __decorate([
35040
35244
  out.set(Math.min(this.constantMin, this.constantMax), Math.max(this.constantMin, this.constantMax));
35041
35245
  break;
35042
35246
  case ParticleCurveMode.Curve:
35043
- var _this_curveMax, _this_curveMax1;
35044
- out.set(this._getMinKeyValue((_this_curveMax = this.curveMax) == null ? void 0 : _this_curveMax.keys), this._getMaxKeyValue((_this_curveMax1 = this.curveMax) == null ? void 0 : _this_curveMax1.keys));
35247
+ var _this_curveMax;
35248
+ this._getKeyMinMax((_this_curveMax = this.curveMax) == null ? void 0 : _this_curveMax.keys, out);
35045
35249
  break;
35046
35250
  case ParticleCurveMode.TwoCurves:
35047
- var _this_curveMax2, _this_curveMin, _this_curveMax3, _this_curveMin1;
35048
- var minCurveMax = this._getMinKeyValue((_this_curveMax2 = this.curveMax) == null ? void 0 : _this_curveMax2.keys);
35049
- var minCurveMin = this._getMinKeyValue((_this_curveMin = this.curveMin) == null ? void 0 : _this_curveMin.keys);
35050
- var maxCurveMax = this._getMaxKeyValue((_this_curveMax3 = this.curveMax) == null ? void 0 : _this_curveMax3.keys);
35051
- var maxCurveMin = this._getMaxKeyValue((_this_curveMin1 = this.curveMin) == null ? void 0 : _this_curveMin1.keys);
35052
- var min = minCurveMax < minCurveMin ? minCurveMax : minCurveMin;
35053
- var max = maxCurveMax > maxCurveMin ? maxCurveMax : maxCurveMin;
35054
- out.set(min, max);
35251
+ var _this_curveMin, _this_curveMax1;
35252
+ this._getKeyMinMax((_this_curveMin = this.curveMin) == null ? void 0 : _this_curveMin.keys, out);
35253
+ var minCurveMin = out.x;
35254
+ var maxCurveMin = out.y;
35255
+ this._getKeyMinMax((_this_curveMax1 = this.curveMax) == null ? void 0 : _this_curveMax1.keys, out);
35256
+ var minCurveMax = out.x;
35257
+ var maxCurveMax = out.y;
35258
+ out.set(minCurveMax < minCurveMin ? minCurveMax : minCurveMin, maxCurveMax > maxCurveMin ? maxCurveMax : maxCurveMin);
35055
35259
  break;
35056
35260
  }
35057
35261
  };
35058
35262
  /**
35059
35263
  * @internal
35264
+ */ _proto._isZero = function _isZero() {
35265
+ var minMax = ParticleCompositeCurve._minMaxRange;
35266
+ this._getMinMax(minMax);
35267
+ return minMax.x === 0 && minMax.y === 0;
35268
+ };
35269
+ /**
35270
+ * @internal
35271
+ */ _proto._isCurveMode = function _isCurveMode() {
35272
+ return this._mode === ParticleCurveMode.Curve || this._mode === ParticleCurveMode.TwoCurves;
35273
+ };
35274
+ /**
35275
+ * @internal
35276
+ */ _proto._isRandomMode = function _isRandomMode() {
35277
+ return this._mode === ParticleCurveMode.TwoConstants || this._mode === ParticleCurveMode.TwoCurves;
35278
+ };
35279
+ /**
35280
+ * @internal
35060
35281
  */ _proto._registerOnValueChanged = function _registerOnValueChanged(listener) {
35061
35282
  this._updateManager.addListener(listener);
35062
35283
  };
@@ -35065,31 +35286,20 @@ __decorate([
35065
35286
  */ _proto._unRegisterOnValueChanged = function _unRegisterOnValueChanged(listener) {
35066
35287
  this._updateManager.removeListener(listener);
35067
35288
  };
35068
- _proto._getMaxKeyValue = function _getMaxKeyValue(keys) {
35069
- var max = undefined;
35070
- var _keys_length;
35071
- var count = (_keys_length = keys == null ? void 0 : keys.length) != null ? _keys_length : 0;
35072
- if (count > 0) {
35073
- max = keys[0].value;
35074
- for(var i = 1; i < count; i++){
35075
- var value = keys[i].value;
35076
- max = Math.max(max, value);
35077
- }
35078
- }
35079
- return max;
35080
- };
35081
- _proto._getMinKeyValue = function _getMinKeyValue(keys) {
35289
+ _proto._getKeyMinMax = function _getKeyMinMax(keys, out) {
35082
35290
  var min = undefined;
35291
+ var max = undefined;
35083
35292
  var _keys_length;
35084
35293
  var count = (_keys_length = keys == null ? void 0 : keys.length) != null ? _keys_length : 0;
35085
35294
  if (count > 0) {
35086
- min = keys[0].value;
35295
+ min = max = keys[0].value;
35087
35296
  for(var i = 1; i < count; i++){
35088
35297
  var value = keys[i].value;
35089
35298
  min = Math.min(min, value);
35299
+ max = Math.max(max, value);
35090
35300
  }
35091
35301
  }
35092
- return min;
35302
+ out.set(min != null ? min : 0, max != null ? max : 0);
35093
35303
  };
35094
35304
  _proto._onCurveChange = function _onCurveChange(lastValue, value) {
35095
35305
  var dispatch = this._updateDispatch;
@@ -35195,6 +35405,7 @@ __decorate([
35195
35405
  ]);
35196
35406
  return ParticleCompositeCurve;
35197
35407
  }();
35408
+ ParticleCompositeCurve._minMaxRange = new Vector2();
35198
35409
  __decorate([
35199
35410
  ignoreClone
35200
35411
  ], ParticleCompositeCurve.prototype, "_updateManager", void 0);
@@ -36856,6 +37067,34 @@ __decorate([
36856
37067
  };
36857
37068
  /**
36858
37069
  * @internal
37070
+ */ _proto._evaluateCumulative = function _evaluateCumulative(normalizedAge) {
37071
+ var keys = this.keys;
37072
+ var length = keys.length;
37073
+ if (length === 0) return 0;
37074
+ // Single key is a constant curve (matches `_evaluate`); its integral is value × age.
37075
+ if (length === 1) return keys[0].value * normalizedAge;
37076
+ var firstKey = keys[0];
37077
+ if (normalizedAge <= firstKey.time) return firstKey.value * normalizedAge;
37078
+ var cumulative = firstKey.value * firstKey.time;
37079
+ for(var i = 1; i < length; i++){
37080
+ var key = keys[i];
37081
+ var lastKey = keys[i - 1];
37082
+ var segmentTime = key.time - lastKey.time;
37083
+ if (segmentTime <= 0) continue;
37084
+ if (key.time >= normalizedAge) {
37085
+ var offsetTime = normalizedAge - lastKey.time;
37086
+ var t = offsetTime / segmentTime;
37087
+ var currentValue = lastKey.value + (key.value - lastKey.value) * t;
37088
+ cumulative += (lastKey.value + currentValue) * 0.5 * offsetTime;
37089
+ return cumulative;
37090
+ }
37091
+ cumulative += (lastKey.value + key.value) * 0.5 * segmentTime;
37092
+ }
37093
+ var lastKey1 = keys[length - 1];
37094
+ return cumulative + lastKey1.value * (normalizedAge - lastKey1.time);
37095
+ };
37096
+ /**
37097
+ * @internal
36859
37098
  */ _proto._getTypeArray = function _getTypeArray() {
36860
37099
  var typeArray = this._typeArray || (this._typeArray = new Float32Array(4 * 2));
36861
37100
  if (this._typeArrayDirty) {
@@ -37504,10 +37743,20 @@ __decorate([
37504
37743
  _inherits(VelocityOverLifetimeModule, ParticleGeneratorModule);
37505
37744
  function VelocityOverLifetimeModule(generator) {
37506
37745
  var _this;
37507
- _this = ParticleGeneratorModule.call(this, generator) || this, /** @internal */ _this._velocityRand = new Rand(0, ParticleRandomSubSeeds.VelocityOverLifetime), _this._velocityMinConstant = new Vector3(), _this._velocityMaxConstant = new Vector3(), _this._space = ParticleSimulationSpace.Local;
37746
+ _this = ParticleGeneratorModule.call(this, generator) || this, /** @internal */ _this._velocityRand = new Rand(0, ParticleRandomSubSeeds.VelocityOverLifetime), _this._velocityMinConstant = new Vector3(), _this._velocityMaxConstant = new Vector3(), _this._orbitalMinConstant = new Vector3(), _this._orbitalConstant = new Vector3(), _this._offset = new Vector3(), _this._space = ParticleSimulationSpace.Local, _this._onTransformFeedbackDirty = function() {
37747
+ return _this._generator._setTransformFeedback();
37748
+ };
37508
37749
  _this.velocityX = new ParticleCompositeCurve(0);
37509
37750
  _this.velocityY = new ParticleCompositeCurve(0);
37510
37751
  _this.velocityZ = new ParticleCompositeCurve(0);
37752
+ _this.orbitalX = new ParticleCompositeCurve(0);
37753
+ _this.orbitalY = new ParticleCompositeCurve(0);
37754
+ _this.orbitalZ = new ParticleCompositeCurve(0);
37755
+ _this.radial = new ParticleCompositeCurve(0);
37756
+ // @ts-ignore
37757
+ _this._offset._onValueChanged = function() {
37758
+ return _this._generator._renderer._onGeneratorParamsChanged();
37759
+ };
37511
37760
  return _this;
37512
37761
  }
37513
37762
  var _proto = VelocityOverLifetimeModule.prototype;
@@ -37516,6 +37765,10 @@ __decorate([
37516
37765
  */ _proto._updateShaderData = function _updateShaderData(shaderData) {
37517
37766
  var velocityMacro = null;
37518
37767
  var isRandomModeMacro = null;
37768
+ var orbitalMacro = null;
37769
+ var orbitalRandomModeMacro = null;
37770
+ var radialMacro = null;
37771
+ var radialRandomModeMacro = null;
37519
37772
  if (this.enabled) {
37520
37773
  var velocityX = this.velocityX;
37521
37774
  var velocityY = this.velocityY;
@@ -37545,15 +37798,111 @@ __decorate([
37545
37798
  }
37546
37799
  }
37547
37800
  shaderData.setInt(VelocityOverLifetimeModule._spaceProperty, this.space);
37801
+ var needTransformFeedback = this._needTransformFeedback();
37802
+ var orbitalActive = needTransformFeedback && this._isOrbitalActive();
37803
+ var radialActive = needTransformFeedback && this._isRadialActive();
37804
+ if (orbitalActive) {
37805
+ var orbitalX = this._orbitalX;
37806
+ var orbitalY = this._orbitalY;
37807
+ var orbitalZ = this._orbitalZ;
37808
+ var isOrbitalRandomCurveMode = orbitalX.mode === ParticleCurveMode.TwoCurves && orbitalY.mode === ParticleCurveMode.TwoCurves && orbitalZ.mode === ParticleCurveMode.TwoCurves;
37809
+ if (isOrbitalRandomCurveMode || orbitalX.mode === ParticleCurveMode.Curve && orbitalY.mode === ParticleCurveMode.Curve && orbitalZ.mode === ParticleCurveMode.Curve) {
37810
+ shaderData.setFloatArray(VelocityOverLifetimeModule._orbitalMaxCurveXProperty, orbitalX.curveMax._getTypeArray());
37811
+ shaderData.setFloatArray(VelocityOverLifetimeModule._orbitalMaxCurveYProperty, orbitalY.curveMax._getTypeArray());
37812
+ shaderData.setFloatArray(VelocityOverLifetimeModule._orbitalMaxCurveZProperty, orbitalZ.curveMax._getTypeArray());
37813
+ orbitalMacro = VelocityOverLifetimeModule._orbitalCurveModeMacro;
37814
+ if (isOrbitalRandomCurveMode) {
37815
+ shaderData.setFloatArray(VelocityOverLifetimeModule._orbitalMinCurveXProperty, orbitalX.curveMin._getTypeArray());
37816
+ shaderData.setFloatArray(VelocityOverLifetimeModule._orbitalMinCurveYProperty, orbitalY.curveMin._getTypeArray());
37817
+ shaderData.setFloatArray(VelocityOverLifetimeModule._orbitalMinCurveZProperty, orbitalZ.curveMin._getTypeArray());
37818
+ orbitalRandomModeMacro = VelocityOverLifetimeModule._orbitalRandomModeMacro;
37819
+ }
37820
+ } else {
37821
+ this._orbitalConstant.set(orbitalX.constantMax, orbitalY.constantMax, orbitalZ.constantMax);
37822
+ shaderData.setVector3(VelocityOverLifetimeModule._orbitalMaxConstantProperty, this._orbitalConstant);
37823
+ orbitalMacro = VelocityOverLifetimeModule._orbitalConstantModeMacro;
37824
+ if (orbitalX.mode === ParticleCurveMode.TwoConstants && orbitalY.mode === ParticleCurveMode.TwoConstants && orbitalZ.mode === ParticleCurveMode.TwoConstants) {
37825
+ this._orbitalMinConstant.set(orbitalX.constantMin, orbitalY.constantMin, orbitalZ.constantMin);
37826
+ shaderData.setVector3(VelocityOverLifetimeModule._orbitalMinConstantProperty, this._orbitalMinConstant);
37827
+ orbitalRandomModeMacro = VelocityOverLifetimeModule._orbitalRandomModeMacro;
37828
+ }
37829
+ }
37830
+ }
37831
+ if (radialActive) {
37832
+ var radial = this._radial;
37833
+ var isRadialRandomMode = radial._isRandomMode();
37834
+ if (radial._isCurveMode()) {
37835
+ shaderData.setFloatArray(VelocityOverLifetimeModule._radialMaxCurveProperty, radial.curveMax._getTypeArray());
37836
+ radialMacro = VelocityOverLifetimeModule._radialCurveModeMacro;
37837
+ if (isRadialRandomMode) {
37838
+ shaderData.setFloatArray(VelocityOverLifetimeModule._radialMinCurveProperty, radial.curveMin._getTypeArray());
37839
+ radialRandomModeMacro = VelocityOverLifetimeModule._radialRandomModeMacro;
37840
+ }
37841
+ } else {
37842
+ shaderData.setFloat(VelocityOverLifetimeModule._radialMaxConstantProperty, radial.constantMax);
37843
+ radialMacro = VelocityOverLifetimeModule._radialConstantModeMacro;
37844
+ if (isRadialRandomMode) {
37845
+ shaderData.setFloat(VelocityOverLifetimeModule._radialMinConstantProperty, radial.constantMin);
37846
+ radialRandomModeMacro = VelocityOverLifetimeModule._radialRandomModeMacro;
37847
+ }
37848
+ }
37849
+ }
37850
+ if (orbitalActive || radialActive) {
37851
+ shaderData.setVector3(VelocityOverLifetimeModule._offsetProperty, this._offset);
37852
+ }
37548
37853
  }
37549
37854
  this._velocityMacro = this._enableMacro(shaderData, this._velocityMacro, velocityMacro);
37550
37855
  this._randomModeMacro = this._enableMacro(shaderData, this._randomModeMacro, isRandomModeMacro);
37856
+ this._orbitalMacro = this._enableMacro(shaderData, this._orbitalMacro, orbitalMacro);
37857
+ this._orbitalRandomModeMacro = this._enableMacro(shaderData, this._orbitalRandomModeMacro, orbitalRandomModeMacro);
37858
+ this._radialMacro = this._enableMacro(shaderData, this._radialMacro, radialMacro);
37859
+ this._radialRandomModeMacro = this._enableMacro(shaderData, this._radialRandomModeMacro, radialRandomModeMacro);
37551
37860
  };
37552
37861
  /**
37553
37862
  * @internal
37554
37863
  */ _proto._resetRandomSeed = function _resetRandomSeed(seed) {
37555
37864
  this._velocityRand.reset(seed, ParticleRandomSubSeeds.VelocityOverLifetime);
37556
37865
  };
37866
+ /**
37867
+ * @internal
37868
+ */ _proto._needTransformFeedback = function _needTransformFeedback() {
37869
+ if (!this._enabled || !this._generator._renderer.engine._hardwareRenderer.isWebGL2) {
37870
+ return false;
37871
+ }
37872
+ return this._isOrbitalActive() || this._isRadialActive();
37873
+ };
37874
+ /**
37875
+ * @internal
37876
+ */ _proto._isOrbitalActive = function _isOrbitalActive() {
37877
+ return !(this._orbitalX._isZero() && this._orbitalY._isZero() && this._orbitalZ._isZero());
37878
+ };
37879
+ /**
37880
+ * @internal
37881
+ */ _proto._isRadialActive = function _isRadialActive() {
37882
+ return !this._radial._isZero();
37883
+ };
37884
+ /**
37885
+ * @internal
37886
+ */ _proto._isRandomMode = function _isRandomMode() {
37887
+ var velocityX = this.velocityX;
37888
+ var velocityY = this.velocityY;
37889
+ var velocityZ = this.velocityZ;
37890
+ var isLinearRandomMode = velocityX.mode === ParticleCurveMode.TwoConstants && velocityY.mode === ParticleCurveMode.TwoConstants && velocityZ.mode === ParticleCurveMode.TwoConstants || velocityX.mode === ParticleCurveMode.TwoCurves && velocityY.mode === ParticleCurveMode.TwoCurves && velocityZ.mode === ParticleCurveMode.TwoCurves;
37891
+ if (!this._needTransformFeedback()) {
37892
+ return isLinearRandomMode;
37893
+ }
37894
+ var orbitalX = this._orbitalX;
37895
+ var orbitalY = this._orbitalY;
37896
+ var orbitalZ = this._orbitalZ;
37897
+ var isOrbitalRandomMode = orbitalX.mode === ParticleCurveMode.TwoConstants && orbitalY.mode === ParticleCurveMode.TwoConstants && orbitalZ.mode === ParticleCurveMode.TwoConstants || orbitalX.mode === ParticleCurveMode.TwoCurves && orbitalY.mode === ParticleCurveMode.TwoCurves && orbitalZ.mode === ParticleCurveMode.TwoCurves;
37898
+ return isLinearRandomMode || isOrbitalRandomMode || this._radial._isRandomMode();
37899
+ };
37900
+ _proto._onOrbitalRadialChange = function _onOrbitalRadialChange(lastValue, value) {
37901
+ this._onCompositeCurveChange(lastValue, value);
37902
+ lastValue == null ? void 0 : lastValue._unRegisterOnValueChanged(this._onTransformFeedbackDirty);
37903
+ value == null ? void 0 : value._registerOnValueChanged(this._onTransformFeedbackDirty);
37904
+ this._generator._setTransformFeedback();
37905
+ };
37557
37906
  _create_class(VelocityOverLifetimeModule, [
37558
37907
  {
37559
37908
  key: "velocityX",
@@ -37600,6 +37949,84 @@ __decorate([
37600
37949
  }
37601
37950
  }
37602
37951
  },
37952
+ {
37953
+ key: "orbitalX",
37954
+ get: /**
37955
+ * Orbital velocity (radians/second) around the x axis of the system.
37956
+ * @remarks Requires WebGL2.
37957
+ */ function get() {
37958
+ return this._orbitalX;
37959
+ },
37960
+ set: function set(value) {
37961
+ var lastValue = this._orbitalX;
37962
+ if (value !== lastValue) {
37963
+ this._orbitalX = value;
37964
+ this._onOrbitalRadialChange(lastValue, value);
37965
+ }
37966
+ }
37967
+ },
37968
+ {
37969
+ key: "orbitalY",
37970
+ get: /**
37971
+ * Orbital velocity (radians/second) around the y axis of the system.
37972
+ * @remarks Requires WebGL2.
37973
+ */ function get() {
37974
+ return this._orbitalY;
37975
+ },
37976
+ set: function set(value) {
37977
+ var lastValue = this._orbitalY;
37978
+ if (value !== lastValue) {
37979
+ this._orbitalY = value;
37980
+ this._onOrbitalRadialChange(lastValue, value);
37981
+ }
37982
+ }
37983
+ },
37984
+ {
37985
+ key: "orbitalZ",
37986
+ get: /**
37987
+ * Orbital velocity (radians/second) around the z axis of the system.
37988
+ * @remarks Requires WebGL2.
37989
+ */ function get() {
37990
+ return this._orbitalZ;
37991
+ },
37992
+ set: function set(value) {
37993
+ var lastValue = this._orbitalZ;
37994
+ if (value !== lastValue) {
37995
+ this._orbitalZ = value;
37996
+ this._onOrbitalRadialChange(lastValue, value);
37997
+ }
37998
+ }
37999
+ },
38000
+ {
38001
+ key: "radial",
38002
+ get: /**
38003
+ * Radial velocity moving particles away from (or towards) the center.
38004
+ * @remarks Requires WebGL2.
38005
+ */ function get() {
38006
+ return this._radial;
38007
+ },
38008
+ set: function set(value) {
38009
+ var lastValue = this._radial;
38010
+ if (value !== lastValue) {
38011
+ this._radial = value;
38012
+ this._onOrbitalRadialChange(lastValue, value);
38013
+ }
38014
+ }
38015
+ },
38016
+ {
38017
+ key: "centerOffset",
38018
+ get: /**
38019
+ * The center offset of orbital/radial motion from the particle system origin.
38020
+ */ function get() {
38021
+ return this._offset;
38022
+ },
38023
+ set: function set(value) {
38024
+ var offset = this._offset;
38025
+ if (value !== offset) {
38026
+ offset.copyFrom(value);
38027
+ }
38028
+ }
38029
+ },
37603
38030
  {
37604
38031
  key: "space",
37605
38032
  get: /**
@@ -37622,6 +38049,7 @@ __decorate([
37622
38049
  set: function set(value) {
37623
38050
  if (value !== this._enabled) {
37624
38051
  this._enabled = value;
38052
+ this._generator._setTransformFeedback();
37625
38053
  this._generator._renderer._onGeneratorParamsChanged();
37626
38054
  }
37627
38055
  }
@@ -37641,6 +38069,25 @@ VelocityOverLifetimeModule._maxGradientXProperty = ShaderProperty.getByName("ren
37641
38069
  VelocityOverLifetimeModule._maxGradientYProperty = ShaderProperty.getByName("renderer_VOLMaxGradientY");
37642
38070
  VelocityOverLifetimeModule._maxGradientZProperty = ShaderProperty.getByName("renderer_VOLMaxGradientZ");
37643
38071
  VelocityOverLifetimeModule._spaceProperty = ShaderProperty.getByName("renderer_VOLSpace");
38072
+ VelocityOverLifetimeModule._orbitalConstantModeMacro = ShaderMacro.getByName("RENDERER_VOL_ORBITAL_CONSTANT_MODE");
38073
+ VelocityOverLifetimeModule._orbitalCurveModeMacro = ShaderMacro.getByName("RENDERER_VOL_ORBITAL_CURVE_MODE");
38074
+ VelocityOverLifetimeModule._orbitalRandomModeMacro = ShaderMacro.getByName("RENDERER_VOL_ORBITAL_IS_RANDOM_TWO");
38075
+ VelocityOverLifetimeModule._radialConstantModeMacro = ShaderMacro.getByName("RENDERER_VOL_RADIAL_CONSTANT_MODE");
38076
+ VelocityOverLifetimeModule._radialCurveModeMacro = ShaderMacro.getByName("RENDERER_VOL_RADIAL_CURVE_MODE");
38077
+ VelocityOverLifetimeModule._radialRandomModeMacro = ShaderMacro.getByName("RENDERER_VOL_RADIAL_IS_RANDOM_TWO");
38078
+ VelocityOverLifetimeModule._orbitalMinConstantProperty = ShaderProperty.getByName("renderer_VOLOrbitalMinConst");
38079
+ VelocityOverLifetimeModule._orbitalMaxConstantProperty = ShaderProperty.getByName("renderer_VOLOrbitalMaxConst");
38080
+ VelocityOverLifetimeModule._orbitalMinCurveXProperty = ShaderProperty.getByName("renderer_VOLOrbitalMinCurveX");
38081
+ VelocityOverLifetimeModule._orbitalMinCurveYProperty = ShaderProperty.getByName("renderer_VOLOrbitalMinCurveY");
38082
+ VelocityOverLifetimeModule._orbitalMinCurveZProperty = ShaderProperty.getByName("renderer_VOLOrbitalMinCurveZ");
38083
+ VelocityOverLifetimeModule._orbitalMaxCurveXProperty = ShaderProperty.getByName("renderer_VOLOrbitalMaxCurveX");
38084
+ VelocityOverLifetimeModule._orbitalMaxCurveYProperty = ShaderProperty.getByName("renderer_VOLOrbitalMaxCurveY");
38085
+ VelocityOverLifetimeModule._orbitalMaxCurveZProperty = ShaderProperty.getByName("renderer_VOLOrbitalMaxCurveZ");
38086
+ VelocityOverLifetimeModule._radialMinConstantProperty = ShaderProperty.getByName("renderer_VOLRadialMinConst");
38087
+ VelocityOverLifetimeModule._radialMaxConstantProperty = ShaderProperty.getByName("renderer_VOLRadialMaxConst");
38088
+ VelocityOverLifetimeModule._radialMinCurveProperty = ShaderProperty.getByName("renderer_VOLRadialMinCurve");
38089
+ VelocityOverLifetimeModule._radialMaxCurveProperty = ShaderProperty.getByName("renderer_VOLRadialMaxCurve");
38090
+ VelocityOverLifetimeModule._offsetProperty = ShaderProperty.getByName("renderer_VOLOffset");
37644
38091
  __decorate([
37645
38092
  ignoreClone
37646
38093
  ], VelocityOverLifetimeModule.prototype, "_velocityRand", void 0);
@@ -37656,6 +38103,24 @@ __decorate([
37656
38103
  __decorate([
37657
38104
  ignoreClone
37658
38105
  ], VelocityOverLifetimeModule.prototype, "_randomModeMacro", void 0);
38106
+ __decorate([
38107
+ ignoreClone
38108
+ ], VelocityOverLifetimeModule.prototype, "_orbitalMinConstant", void 0);
38109
+ __decorate([
38110
+ ignoreClone
38111
+ ], VelocityOverLifetimeModule.prototype, "_orbitalConstant", void 0);
38112
+ __decorate([
38113
+ ignoreClone
38114
+ ], VelocityOverLifetimeModule.prototype, "_orbitalMacro", void 0);
38115
+ __decorate([
38116
+ ignoreClone
38117
+ ], VelocityOverLifetimeModule.prototype, "_orbitalRandomModeMacro", void 0);
38118
+ __decorate([
38119
+ ignoreClone
38120
+ ], VelocityOverLifetimeModule.prototype, "_radialMacro", void 0);
38121
+ __decorate([
38122
+ ignoreClone
38123
+ ], VelocityOverLifetimeModule.prototype, "_radialRandomModeMacro", void 0);
37659
38124
  __decorate([
37660
38125
  deepClone
37661
38126
  ], VelocityOverLifetimeModule.prototype, "_velocityX", void 0);
@@ -37665,6 +38130,239 @@ __decorate([
37665
38130
  __decorate([
37666
38131
  deepClone
37667
38132
  ], VelocityOverLifetimeModule.prototype, "_velocityZ", void 0);
38133
+ __decorate([
38134
+ deepClone
38135
+ ], VelocityOverLifetimeModule.prototype, "_orbitalX", void 0);
38136
+ __decorate([
38137
+ deepClone
38138
+ ], VelocityOverLifetimeModule.prototype, "_orbitalY", void 0);
38139
+ __decorate([
38140
+ deepClone
38141
+ ], VelocityOverLifetimeModule.prototype, "_orbitalZ", void 0);
38142
+ __decorate([
38143
+ deepClone
38144
+ ], VelocityOverLifetimeModule.prototype, "_radial", void 0);
38145
+ __decorate([
38146
+ deepClone
38147
+ ], VelocityOverLifetimeModule.prototype, "_offset", void 0);
38148
+ __decorate([
38149
+ ignoreClone
38150
+ ], VelocityOverLifetimeModule.prototype, "_onTransformFeedbackDirty", void 0);
38151
+
38152
+ /**
38153
+ * Optional parent properties a sub-emitter inherits
38154
+ * Sub particles are always emitted at the parent particle's position; these flags only select
38155
+ * which additional properties are inherited on top of that.
38156
+ */ var ParticleSubEmitterInheritProperty = /*#__PURE__*/ function(ParticleSubEmitterInheritProperty) {
38157
+ /** Inherit no additional properties; sub particles are still emitted at the parent's position. */ ParticleSubEmitterInheritProperty[ParticleSubEmitterInheritProperty["None"] = 0] = "None";
38158
+ /** Multiply parent's current color into the sub particle's start color. */ ParticleSubEmitterInheritProperty[ParticleSubEmitterInheritProperty["Color"] = 1] = "Color";
38159
+ /** Multiply parent's current size into the sub particle's start size. */ ParticleSubEmitterInheritProperty[ParticleSubEmitterInheritProperty["Size"] = 2] = "Size";
38160
+ /** Add parent's current rotation onto the sub particle's start rotation. */ ParticleSubEmitterInheritProperty[ParticleSubEmitterInheritProperty["Rotation"] = 4] = "Rotation";
38161
+ /** Emit the sub particle along the parent's velocity direction. */ ParticleSubEmitterInheritProperty[ParticleSubEmitterInheritProperty["Velocity"] = 8] = "Velocity";
38162
+ return ParticleSubEmitterInheritProperty;
38163
+ }({});
38164
+
38165
+ /**
38166
+ * One slot in `SubEmittersModule.subEmitters`. Configures which sub-emitter
38167
+ * fires, on which parent event, with what inheritance, probability, and count.
38168
+ */ var SubEmitter = /*#__PURE__*/ function() {
38169
+ function SubEmitter() {
38170
+ /** Bitmask of properties inherited from the parent particle. */ this.inheritProperties = ParticleSubEmitterInheritProperty.None;
38171
+ /** Probability (0..1) the sub-emitter fires for any given event. */ this.emitProbability = 1;
38172
+ /** Number of sub particles emitted per parent event. */ this.emitCount = 1;
38173
+ /** @internal */ this._module = null;
38174
+ this._emitter = null;
38175
+ this._type = ParticleSubEmitterType.Birth;
38176
+ }
38177
+ _create_class(SubEmitter, [
38178
+ {
38179
+ key: "emitter",
38180
+ get: /**
38181
+ * Target particle renderer the sub particles emit into.
38182
+ */ function get() {
38183
+ return this._emitter;
38184
+ },
38185
+ set: function set(value) {
38186
+ var _this__module;
38187
+ if (value === this._emitter) return;
38188
+ (_this__module = this._module) == null ? void 0 : _this__module._validateEmitter(value);
38189
+ this._emitter = value;
38190
+ }
38191
+ },
38192
+ {
38193
+ key: "type",
38194
+ get: /**
38195
+ * Which parent-particle event drives this slot.
38196
+ */ function get() {
38197
+ return this._type;
38198
+ },
38199
+ set: function set(value) {
38200
+ var _this__module;
38201
+ if (value === this._type) return;
38202
+ this._type = value;
38203
+ (_this__module = this._module) == null ? void 0 : _this__module._generator._setTransformFeedback();
38204
+ }
38205
+ }
38206
+ ]);
38207
+ return SubEmitter;
38208
+ }();
38209
+ __decorate([
38210
+ ignoreClone
38211
+ ], SubEmitter.prototype, "_module", void 0);
38212
+
38213
+ /**
38214
+ * Fires sub-emitters on parent particle lifecycle events (Birth / Death).
38215
+ * @remarks Requires WebGL2; the module stays inactive on WebGL1.
38216
+ */ var SubEmittersModule = /*#__PURE__*/ function(ParticleGeneratorModule) {
38217
+ _inherits(SubEmittersModule, ParticleGeneratorModule);
38218
+ function SubEmittersModule() {
38219
+ var _this;
38220
+ _this = ParticleGeneratorModule.apply(this, arguments) || this, _this._subEmitters = [], _this._probabilityRand = new Rand(0, ParticleRandomSubSeeds.SubEmitter);
38221
+ return _this;
38222
+ }
38223
+ var _proto = SubEmittersModule.prototype;
38224
+ /**
38225
+ * Add a sub-emitter slot.
38226
+ * @param emitter - Target particle renderer
38227
+ * @param type - Trigger event (`Birth` / `Death`)
38228
+ * @param inheritProperties - Bitmask of properties inherited from the parent particle
38229
+ * @param emitProbability - Per-event fire probability [0, 1]
38230
+ * @param emitCount - Number of sub particles emitted per parent event
38231
+ */ _proto.addSubEmitter = function addSubEmitter(emitter, type, inheritProperties, emitProbability, emitCount) {
38232
+ if (inheritProperties === void 0) inheritProperties = ParticleSubEmitterInheritProperty.None;
38233
+ if (emitProbability === void 0) emitProbability = 1;
38234
+ if (emitCount === void 0) emitCount = 1;
38235
+ if (SubEmittersModule._wouldCreateCycle(emitter, this._generator)) {
38236
+ throw new Error("Sub-emitter would create a cycle");
38237
+ }
38238
+ var sub = new SubEmitter();
38239
+ sub.emitter = emitter;
38240
+ sub.type = type;
38241
+ sub.inheritProperties = inheritProperties;
38242
+ sub.emitProbability = emitProbability;
38243
+ sub.emitCount = emitCount;
38244
+ sub._module = this;
38245
+ this._subEmitters.push(sub);
38246
+ this._generator._setTransformFeedback();
38247
+ };
38248
+ /**
38249
+ * Remove the sub-emitter at the given index.
38250
+ * @param index - Index of the sub-emitter to remove
38251
+ */ _proto.removeSubEmitterByIndex = function removeSubEmitterByIndex(index) {
38252
+ this._subEmitters.splice(index, 1);
38253
+ this._generator._setTransformFeedback();
38254
+ };
38255
+ /**
38256
+ * @internal
38257
+ */ _proto._dispatchEvent = function _dispatchEvent(type, worldPosition, parentColor, parentSize, parentRotation, worldDirection) {
38258
+ var subEmitters = this.subEmitters;
38259
+ for(var i = 0, n = subEmitters.length; i < n; i++){
38260
+ var sub = subEmitters[i];
38261
+ if (sub.type !== type) continue;
38262
+ var target = sub.emitter;
38263
+ if (target === null || target.destroyed) continue;
38264
+ var count = sub.emitCount;
38265
+ if (count <= 0) continue;
38266
+ if (sub.emitProbability < 1.0 && this._probabilityRand.random() >= sub.emitProbability) {
38267
+ continue;
38268
+ }
38269
+ var inherit = sub.inheritProperties;
38270
+ var colorOverride = (inherit & ParticleSubEmitterInheritProperty.Color) !== 0 ? parentColor : null;
38271
+ var sizeOverride = (inherit & ParticleSubEmitterInheritProperty.Size) !== 0 ? parentSize : null;
38272
+ var rotationOverride = (inherit & ParticleSubEmitterInheritProperty.Rotation) !== 0 ? parentRotation : null;
38273
+ var directionOverride = (inherit & ParticleSubEmitterInheritProperty.Velocity) !== 0 ? worldDirection : null;
38274
+ target.generator._emitFromSubEmitter(count, worldPosition, colorOverride, sizeOverride, rotationOverride, directionOverride);
38275
+ }
38276
+ };
38277
+ /**
38278
+ * @internal
38279
+ */ _proto._resetRandomSeed = function _resetRandomSeed(seed) {
38280
+ this._probabilityRand.reset(seed, ParticleRandomSubSeeds.SubEmitter);
38281
+ };
38282
+ /**
38283
+ * @internal
38284
+ */ _proto._hasSubEmitterOfType = function _hasSubEmitterOfType(type) {
38285
+ if (!this.enabled) return false;
38286
+ var subEmitters = this.subEmitters;
38287
+ for(var i = 0, n = subEmitters.length; i < n; i++){
38288
+ if (subEmitters[i].type === type) return true;
38289
+ }
38290
+ return false;
38291
+ };
38292
+ /**
38293
+ * @internal
38294
+ */ _proto._cloneTo = function _cloneTo(target) {
38295
+ // _module is @ignoreClone, so re-link each cloned slot back to its new module
38296
+ var subEmitters = target._subEmitters;
38297
+ for(var i = 0, n = subEmitters.length; i < n; i++){
38298
+ subEmitters[i]._module = target;
38299
+ }
38300
+ };
38301
+ /**
38302
+ * @internal
38303
+ */ _proto._validateEmitter = function _validateEmitter(emitter) {
38304
+ if (emitter && SubEmittersModule._wouldCreateCycle(emitter, this._generator)) {
38305
+ throw new Error("Sub-emitter would create a cycle");
38306
+ }
38307
+ };
38308
+ SubEmittersModule._wouldCreateCycle = function _wouldCreateCycle(target, root) {
38309
+ var visited = SubEmittersModule._cycleVisited;
38310
+ var stack = SubEmittersModule._cycleStack;
38311
+ visited.clear();
38312
+ stack.length = 0;
38313
+ stack.push(target.generator);
38314
+ var found = false;
38315
+ while(stack.length > 0){
38316
+ var cur = stack.pop();
38317
+ if (cur === root) {
38318
+ found = true;
38319
+ break;
38320
+ }
38321
+ if (visited.has(cur)) continue;
38322
+ visited.add(cur);
38323
+ var slots = cur.subEmitters.subEmitters;
38324
+ for(var i = 0, n = slots.length; i < n; i++){
38325
+ var _slots_i_emitter;
38326
+ var child = (_slots_i_emitter = slots[i].emitter) == null ? void 0 : _slots_i_emitter.generator;
38327
+ if (child && !visited.has(child)) stack.push(child);
38328
+ }
38329
+ }
38330
+ visited.clear();
38331
+ stack.length = 0;
38332
+ return found;
38333
+ };
38334
+ _create_class(SubEmittersModule, [
38335
+ {
38336
+ key: "subEmitters",
38337
+ get: /**
38338
+ * The configured sub-emitters.
38339
+ */ function get() {
38340
+ return this._subEmitters;
38341
+ }
38342
+ },
38343
+ {
38344
+ key: "enabled",
38345
+ get: function get() {
38346
+ return this._enabled && this._generator._renderer.engine._hardwareRenderer.isWebGL2;
38347
+ },
38348
+ set: function set(value) {
38349
+ if (value !== this._enabled) {
38350
+ this._enabled = value;
38351
+ this._generator._setTransformFeedback();
38352
+ }
38353
+ }
38354
+ }
38355
+ ]);
38356
+ return SubEmittersModule;
38357
+ }(ParticleGeneratorModule);
38358
+ SubEmittersModule._cycleVisited = new Set();
38359
+ SubEmittersModule._cycleStack = [];
38360
+ __decorate([
38361
+ deepClone
38362
+ ], SubEmittersModule.prototype, "_subEmitters", void 0);
38363
+ __decorate([
38364
+ ignoreClone
38365
+ ], SubEmittersModule.prototype, "_probabilityRand", void 0);
37668
38366
 
37669
38367
  /**
37670
38368
  * Particle Generator.
@@ -37685,6 +38383,7 @@ __decorate([
37685
38383
  /** @internal */ this._subPrimitive = new SubMesh(0, 0, MeshTopology.Triangles);
37686
38384
  /** @internal */ this._useTransformFeedback = false;
37687
38385
  /** @internal */ this._feedbackBindingIndex = -1;
38386
+ this._feedbackReadback = null;
37688
38387
  this._isPlaying = false;
37689
38388
  this._instanceBufferResized = false;
37690
38389
  this._waitProcessRetiredElementCount = 0;
@@ -37693,6 +38392,13 @@ __decorate([
37693
38392
  this._firstActiveTransformedBoundingBox = 0;
37694
38393
  this._firstFreeTransformedBoundingBox = 0;
37695
38394
  this._playStartDelay = 0;
38395
+ this._eventPos = new Vector3();
38396
+ this._eventColor = new Color();
38397
+ this._eventSize = new Vector3();
38398
+ this._eventRotation = new Vector3();
38399
+ this._eventDir = new Vector3();
38400
+ this._emitLocalPos = new Vector3();
38401
+ this._emitDirection = new Vector3();
37696
38402
  this._renderer = renderer;
37697
38403
  var subPrimitive = new SubPrimitive();
37698
38404
  subPrimitive.start = 0;
@@ -37705,6 +38411,7 @@ __decorate([
37705
38411
  this.sizeOverLifetime = new SizeOverLifetimeModule(this);
37706
38412
  this.limitVelocityOverLifetime = new LimitVelocityOverLifetimeModule(this);
37707
38413
  this.noise = new NoiseModule(this);
38414
+ this.subEmitters = new SubEmittersModule(this);
37708
38415
  this.customData = new CustomDataModule(this);
37709
38416
  this.emission.enabled = true;
37710
38417
  }
@@ -38036,16 +38743,15 @@ __decorate([
38036
38743
  this.rotationOverLifetime._resetRandomSeed(seed);
38037
38744
  this.colorOverLifetime._resetRandomSeed(seed);
38038
38745
  this.noise._resetRandomSeed(seed);
38746
+ this.subEmitters._resetRandomSeed(seed);
38039
38747
  };
38040
38748
  /**
38041
38749
  * @internal
38042
38750
  */ _proto._setTransformFeedback = function _setTransformFeedback() {
38043
- var needed = this.limitVelocityOverLifetime.enabled || this.noise.enabled;
38751
+ var _this_limitVelocityOverLifetime, _this_noise, _this_velocityOverLifetime, _this_subEmitters;
38752
+ var needed = !!(this._renderer.engine._hardwareRenderer.isWebGL2 && (((_this_limitVelocityOverLifetime = this.limitVelocityOverLifetime) == null ? void 0 : _this_limitVelocityOverLifetime.enabled) || ((_this_noise = this.noise) == null ? void 0 : _this_noise.enabled) || ((_this_velocityOverLifetime = this.velocityOverLifetime) == null ? void 0 : _this_velocityOverLifetime._needTransformFeedback()) || ((_this_subEmitters = this.subEmitters) == null ? void 0 : _this_subEmitters._hasSubEmitterOfType(ParticleSubEmitterType.Death))));
38044
38753
  if (needed === this._useTransformFeedback) return;
38045
38754
  this._useTransformFeedback = needed;
38046
- // Switching TF mode invalidates all active particle state: feedback buffers and instance
38047
- // buffer layout are incompatible between the two paths. Clear rather than show a one-frame
38048
- // jump; new particles will fill in naturally from the next emit cycle.
38049
38755
  this._clearActiveParticles();
38050
38756
  if (needed) {
38051
38757
  if (!this._feedbackSimulator) {
@@ -38123,7 +38829,12 @@ __decorate([
38123
38829
  this._calculateTransformedBounds(maxLifetime, generatorBounds, transformedBounds);
38124
38830
  renderer._setDirtyFlagFalse(ParticleUpdateFlags.TransformVolume);
38125
38831
  }
38126
- this._addGravityToBounds(maxLifetime, transformedBounds, bounds);
38832
+ if (this._useOrbitalBounds()) {
38833
+ bounds.min.copyFrom(transformedBounds.min);
38834
+ bounds.max.copyFrom(transformedBounds.max);
38835
+ } else {
38836
+ this._addGravityToBounds(maxLifetime, transformedBounds, bounds);
38837
+ }
38127
38838
  };
38128
38839
  /**
38129
38840
  * @internal
@@ -38149,7 +38860,9 @@ __decorate([
38149
38860
  }
38150
38861
  }
38151
38862
  var maxLifetime = this.main.startLifetime._getMax();
38152
- this._addGravityToBounds(maxLifetime, bounds, bounds);
38863
+ if (!this._useOrbitalBounds()) {
38864
+ this._addGravityToBounds(maxLifetime, bounds, bounds);
38865
+ }
38153
38866
  };
38154
38867
  /**
38155
38868
  * @internal
@@ -38201,7 +38914,7 @@ __decorate([
38201
38914
  this._transformedBoundsArray[previousFreeElement * ParticleBufferUtils.boundsFloatStride + boundsTimeOffset] = this._playTime;
38202
38915
  }
38203
38916
  };
38204
- _proto._addNewParticle = function _addNewParticle(position, direction, transform, playTime, emitWorldPositionOverride) {
38917
+ _proto._addNewParticle = function _addNewParticle(position, direction, transform, playTime, emitWorldPositionOverride, inheritColor, inheritSize, inheritRotation) {
38205
38918
  var firstFreeElement = this._firstFreeElement;
38206
38919
  var nextFreeElement = firstFreeElement + 1;
38207
38920
  if (nextFreeElement >= this._currentParticleCount) {
@@ -38239,7 +38952,7 @@ __decorate([
38239
38952
  // Time
38240
38953
  instanceVertices[offset + ParticleBufferUtils.timeOffset] = playTime;
38241
38954
  // Color
38242
- var startColor = ParticleGenerator._tempColor0;
38955
+ var startColor = ParticleGenerator._tempColor;
38243
38956
  main.startColor.evaluate(undefined, main._startColorRand.random(), startColor);
38244
38957
  startColor.copyToArray(instanceVertices, offset + 8);
38245
38958
  var duration = this.main.duration;
@@ -38298,7 +39011,7 @@ __decorate([
38298
39011
  }
38299
39012
  // Velocity random
38300
39013
  var velocityOverLifetime = this.velocityOverLifetime;
38301
- if (velocityOverLifetime.enabled && velocityOverLifetime.velocityX.mode === ParticleCurveMode.TwoConstants && velocityOverLifetime.velocityY.mode === ParticleCurveMode.TwoConstants && velocityOverLifetime.velocityZ.mode === ParticleCurveMode.TwoConstants) {
39014
+ if (velocityOverLifetime.enabled && velocityOverLifetime._isRandomMode()) {
38302
39015
  var rand = velocityOverLifetime._velocityRand;
38303
39016
  instanceVertices[offset + 24] = rand.random();
38304
39017
  instanceVertices[offset + 25] = rand.random();
@@ -38340,11 +39053,79 @@ __decorate([
38340
39053
  if (limitVelocityOverLifetime.enabled && (limitVelocityOverLifetime._isSpeedRandomMode() || limitVelocityOverLifetime._isDragRandomMode())) {
38341
39054
  instanceVertices[offset + 41] = limitVelocityOverLifetime._speedRand.random();
38342
39055
  }
39056
+ // Apply sub-emit inherit: multiply color/size, add rotation
39057
+ if (inheritColor) {
39058
+ instanceVertices[offset + 8] *= inheritColor.r;
39059
+ instanceVertices[offset + 9] *= inheritColor.g;
39060
+ instanceVertices[offset + 10] *= inheritColor.b;
39061
+ instanceVertices[offset + 11] *= inheritColor.a;
39062
+ }
39063
+ if (inheritSize) {
39064
+ instanceVertices[offset + 12] *= inheritSize.x;
39065
+ instanceVertices[offset + 13] *= inheritSize.y;
39066
+ instanceVertices[offset + 14] *= inheritSize.z;
39067
+ }
39068
+ if (inheritRotation) {
39069
+ instanceVertices[offset + 15] += inheritRotation.x;
39070
+ instanceVertices[offset + 16] += inheritRotation.y;
39071
+ instanceVertices[offset + 17] += inheritRotation.z;
39072
+ }
38343
39073
  // Initialize feedback buffer for this particle
38344
39074
  if (this._useTransformFeedback) {
38345
39075
  this._addFeedbackParticle(firstFreeElement, position, direction, startSpeed, transform, pos);
38346
39076
  }
38347
39077
  this._firstFreeElement = nextFreeElement;
39078
+ if (this.subEmitters._hasSubEmitterOfType(ParticleSubEmitterType.Birth)) {
39079
+ this._onParticleBirth(offset, position, direction, transform);
39080
+ }
39081
+ };
39082
+ _proto._onParticleBirth = function _onParticleBirth(offset, position, direction, transform) {
39083
+ var worldRotation = transform.worldRotationQuaternion;
39084
+ var birthPos = this._eventPos;
39085
+ Vector3.transformByQuat(position, worldRotation, birthPos);
39086
+ birthPos.add(transform.worldPosition);
39087
+ // Birth emission direction is known directly; Death reads it back from the feedback buffer
39088
+ var worldDirection = this._eventDir;
39089
+ Vector3.transformByQuat(direction, worldRotation, worldDirection);
39090
+ var parentColor = this._eventColor;
39091
+ var parentSize = this._eventSize;
39092
+ var parentRotation = this._eventRotation;
39093
+ this._evaluateOverLifetime(offset, 0, parentColor, parentSize, parentRotation);
39094
+ this.subEmitters._dispatchEvent(ParticleSubEmitterType.Birth, birthPos, parentColor, parentSize, parentRotation, worldDirection);
39095
+ };
39096
+ /**
39097
+ * @internal
39098
+ */ _proto._emitFromSubEmitter = function _emitFromSubEmitter(count, worldPosition, inheritColor, inheritSize, inheritRotation, worldDirection) {
39099
+ if (count <= 0) return;
39100
+ var main = this.main;
39101
+ var notRetired = this._getNotRetiredParticleCount();
39102
+ var available = main.maxParticles - notRetired;
39103
+ if (available <= 0) return;
39104
+ if (count > available) count = available;
39105
+ var transform = this._renderer.entity.transform;
39106
+ var emitterWorldPosition = transform.worldPosition, emitterWorldRotation = transform.worldRotationQuaternion;
39107
+ // Convert event world position into local emission space for a_ShapePos
39108
+ var localPos = this._emitLocalPos;
39109
+ Vector3.subtract(worldPosition, emitterWorldPosition, localPos);
39110
+ var invRot = ParticleGenerator._tempQuat0;
39111
+ Quaternion.invert(emitterWorldRotation, invRot);
39112
+ Vector3.transformByQuat(localPos, invRot, localPos);
39113
+ var direction = this._emitDirection;
39114
+ if (worldDirection) {
39115
+ Vector3.transformByQuat(worldDirection, invRot, direction);
39116
+ var len = Math.sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z);
39117
+ if (len > MathUtil.zeroTolerance) {
39118
+ direction.set(direction.x / len, direction.y / len, direction.z / len);
39119
+ } else {
39120
+ direction.set(0, 0, -1);
39121
+ }
39122
+ } else {
39123
+ direction.set(0, 0, -1);
39124
+ }
39125
+ var playTime = this._playTime;
39126
+ for(var i = 0; i < count; i++){
39127
+ this._addNewParticle(localPos, direction, transform, playTime, undefined, inheritColor, inheritSize, inheritRotation);
39128
+ }
38348
39129
  };
38349
39130
  _proto._addFeedbackParticle = function _addFeedbackParticle(index, shapePosition, direction, startSpeed, transform, emitWorldPosition) {
38350
39131
  var position;
@@ -38368,7 +39149,10 @@ __decorate([
38368
39149
  var engine = this._renderer.engine;
38369
39150
  var frameCount = engine.time.frameCount;
38370
39151
  var instanceVertices = this._instanceVertices;
38371
- while(this._firstActiveElement !== this._firstNewElement){
39152
+ var hasDeathSlot = this.subEmitters._hasSubEmitterOfType(ParticleSubEmitterType.Death);
39153
+ var firstNewElement = this._firstNewElement;
39154
+ var feedbackLoaded = false;
39155
+ while(this._firstActiveElement !== firstNewElement){
38372
39156
  var activeParticleOffset = this._firstActiveElement * ParticleBufferUtils.instanceVertexFloatStride;
38373
39157
  var activeParticleTimeOffset = activeParticleOffset + ParticleBufferUtils.timeOffset;
38374
39158
  var particleAge = this._playTime - instanceVertices[activeParticleTimeOffset];
@@ -38376,6 +39160,13 @@ __decorate([
38376
39160
  if (Math.fround(particleAge) < instanceVertices[activeParticleOffset + ParticleBufferUtils.startLifeTimeOffset]) {
38377
39161
  break;
38378
39162
  }
39163
+ if (hasDeathSlot) {
39164
+ if (this._feedbackSimulator && !feedbackLoaded) {
39165
+ this._readbackFeedback(this._firstActiveElement, firstNewElement);
39166
+ feedbackLoaded = true;
39167
+ }
39168
+ this._onParticleDeath(activeParticleOffset);
39169
+ }
38379
39170
  // Store frame count in time offset to free retired particle
38380
39171
  instanceVertices[activeParticleTimeOffset] = frameCount;
38381
39172
  if (++this._firstActiveElement >= this._currentParticleCount) {
@@ -38385,6 +39176,110 @@ __decorate([
38385
39176
  this._waitProcessRetiredElementCount++;
38386
39177
  }
38387
39178
  };
39179
+ _proto._readbackFeedback = function _readbackFeedback(firstActiveElement, firstNewElement) {
39180
+ var stride = ParticleBufferUtils.feedbackVertexStride;
39181
+ var floatStride = stride / 4;
39182
+ var totalFloatCount = this._currentParticleCount * floatStride;
39183
+ var readback = this._feedbackReadback;
39184
+ if (!readback || readback.length < totalFloatCount) {
39185
+ readback = this._feedbackReadback = new Float32Array(totalFloatCount);
39186
+ }
39187
+ var buffer = this._feedbackSimulator.readBinding.buffer;
39188
+ var wrapped = firstActiveElement >= firstNewElement;
39189
+ var firstSegmentEnd = wrapped ? this._currentParticleCount : firstNewElement;
39190
+ buffer.getData(readback, firstActiveElement * stride, firstActiveElement * floatStride, (firstSegmentEnd - firstActiveElement) * floatStride);
39191
+ if (wrapped && firstNewElement > 0) {
39192
+ buffer.getData(readback, 0, 0, firstNewElement * floatStride);
39193
+ }
39194
+ };
39195
+ _proto._onParticleDeath = function _onParticleDeath(particleOffset) {
39196
+ var instanceVertices = this._instanceVertices;
39197
+ var transform = this._renderer.entity.transform;
39198
+ var simSpaceLocal = this.main.simulationSpace === ParticleSimulationSpace.Local;
39199
+ var worldRotation = transform.worldRotationQuaternion;
39200
+ var ringIndex = particleOffset / ParticleBufferUtils.instanceVertexFloatStride;
39201
+ var feedbackData = this._feedbackReadback;
39202
+ var feedbackOffset = ringIndex * ParticleBufferUtils.feedbackVertexStride / 4;
39203
+ var local = this._eventPos;
39204
+ local.set(feedbackData[feedbackOffset], feedbackData[feedbackOffset + 1], feedbackData[feedbackOffset + 2]);
39205
+ if (simSpaceLocal) {
39206
+ Vector3.transformByQuat(local, worldRotation, local);
39207
+ local.add(transform.worldPosition);
39208
+ }
39209
+ var worldDirection = this._eventDir;
39210
+ worldDirection.set(feedbackData[feedbackOffset + 3], feedbackData[feedbackOffset + 4], feedbackData[feedbackOffset + 5]);
39211
+ if (simSpaceLocal) {
39212
+ Vector3.transformByQuat(worldDirection, worldRotation, worldDirection);
39213
+ } else {
39214
+ var spawnRotation = ParticleGenerator._tempQuat0;
39215
+ spawnRotation.set(instanceVertices[particleOffset + 30], instanceVertices[particleOffset + 31], instanceVertices[particleOffset + 32], instanceVertices[particleOffset + 33]);
39216
+ Vector3.transformByQuat(worldDirection, spawnRotation, worldDirection);
39217
+ }
39218
+ // Evaluate at the parent's normalizedAge so children inherit its visible appearance at death.
39219
+ var lifetime = instanceVertices[particleOffset + 3];
39220
+ var bornTime = instanceVertices[particleOffset + 7];
39221
+ var parentColor = this._eventColor;
39222
+ var parentSize = this._eventSize;
39223
+ var parentRotation = this._eventRotation;
39224
+ var normalizedAge = Math.min(Math.max((this._playTime - bornTime) / lifetime, 0), 1);
39225
+ this._evaluateOverLifetime(particleOffset, normalizedAge, parentColor, parentSize, parentRotation);
39226
+ this.subEmitters._dispatchEvent(ParticleSubEmitterType.Death, local, parentColor, parentSize, parentRotation, worldDirection);
39227
+ };
39228
+ _proto._evaluateOverLifetime = function _evaluateOverLifetime(particleOffset, normalizedAge, parentColor, parentSize, parentRotation) {
39229
+ var instanceVertices = this._instanceVertices;
39230
+ var r = instanceVertices[particleOffset + 8];
39231
+ var g = instanceVertices[particleOffset + 9];
39232
+ var b = instanceVertices[particleOffset + 10];
39233
+ var a = instanceVertices[particleOffset + 11];
39234
+ var col = this.colorOverLifetime;
39235
+ if (col.enabled) {
39236
+ var colorFactor = ParticleGenerator._tempColor;
39237
+ col.color.evaluate(normalizedAge, instanceVertices[particleOffset + 20], colorFactor);
39238
+ r *= colorFactor.r;
39239
+ g *= colorFactor.g;
39240
+ b *= colorFactor.b;
39241
+ a *= colorFactor.a;
39242
+ }
39243
+ parentColor.set(r, g, b, a);
39244
+ var sx = instanceVertices[particleOffset + 12];
39245
+ var sy = instanceVertices[particleOffset + 13];
39246
+ var sz = instanceVertices[particleOffset + 14];
39247
+ var sol = this.sizeOverLifetime;
39248
+ // SOL only contributes in Curve / TwoCurves modes (shader gates on RENDERER_SOL_CURVE_MODE)
39249
+ if (sol.enabled && (sol.sizeX.mode === ParticleCurveMode.Curve || sol.sizeX.mode === ParticleCurveMode.TwoCurves)) {
39250
+ var sizeRand = instanceVertices[particleOffset + 21];
39251
+ if (sol.separateAxes) {
39252
+ sx *= sol.sizeX.evaluate(normalizedAge, sizeRand);
39253
+ sy *= sol.sizeY.evaluate(normalizedAge, sizeRand);
39254
+ sz *= sol.sizeZ.evaluate(normalizedAge, sizeRand);
39255
+ } else {
39256
+ var factor = sol.sizeX.evaluate(normalizedAge, sizeRand);
39257
+ sx *= factor;
39258
+ sy *= factor;
39259
+ sz *= factor;
39260
+ }
39261
+ }
39262
+ parentSize.set(sx, sy, sz);
39263
+ var rx = instanceVertices[particleOffset + 15];
39264
+ var ry = instanceVertices[particleOffset + 16];
39265
+ var rz = instanceVertices[particleOffset + 17];
39266
+ var rol = this.rotationOverLifetime;
39267
+ if (rol.enabled) {
39268
+ var rotRand = instanceVertices[particleOffset + 22];
39269
+ var lifetime = instanceVertices[particleOffset + 3];
39270
+ var rolZ = rol.rotationZ._evaluateCumulative(normalizedAge, rotRand) * lifetime;
39271
+ if (rol.separateAxes) {
39272
+ rx += rol.rotationX._evaluateCumulative(normalizedAge, rotRand) * lifetime;
39273
+ ry += rol.rotationY._evaluateCumulative(normalizedAge, rotRand) * lifetime;
39274
+ rz += rolZ;
39275
+ } else if (this.main.startRotation3D) {
39276
+ rz += rolZ;
39277
+ } else {
39278
+ rx += rolZ; // 2D rotation: shader stores the Z angle in a_StartRotation0.x
39279
+ }
39280
+ }
39281
+ parentRotation.set(rx, ry, rz);
39282
+ };
38388
39283
  _proto._freeRetiredParticles = function _freeRetiredParticles() {
38389
39284
  var frameCount = this._renderer.engine.time.frameCount;
38390
39285
  while(this._firstRetiredElement !== this._firstActiveElement){
@@ -38528,7 +39423,7 @@ __decorate([
38528
39423
  max.set(Math.max(max.x, boundsArray[offset + 3]), Math.max(max.y, boundsArray[offset + 4]), Math.max(max.z, boundsArray[offset + 5]));
38529
39424
  };
38530
39425
  _proto._calculateTransformedBounds = function _calculateTransformedBounds(maxLifetime, origin, out) {
38531
- var velMinMaxX = ParticleGenerator._tempVector20, velMinMaxY = ParticleGenerator._tempVector21, velMinMaxZ = ParticleGenerator._tempVector22, worldOffsetMin = ParticleGenerator._tempVector30, worldOffsetMax = ParticleGenerator._tempVector31, rotateMat = ParticleGenerator._tempMat;
39426
+ var velMinMaxX = ParticleGenerator._tempVector20, velMinMaxY = ParticleGenerator._tempVector21, velMinMaxZ = ParticleGenerator._tempVector22, worldOffsetMin = ParticleGenerator._tempVector30, worldOffsetMax = ParticleGenerator._tempVector31, noiseBoundsExtents = ParticleGenerator._tempVector32, rotateMat = ParticleGenerator._tempMat;
38532
39427
  worldOffsetMin.set(0, 0, 0);
38533
39428
  worldOffsetMax.set(0, 0, 0);
38534
39429
  var transform = this._renderer.entity.transform;
@@ -38571,27 +39466,89 @@ __decorate([
38571
39466
  worldOffsetMax.set(worldOffsetMax.x + forceMinMaxX.y, worldOffsetMax.y + forceMinMaxY.y, worldOffsetMax.z + forceMinMaxZ.y);
38572
39467
  }
38573
39468
  }
38574
- out.transform(rotateMat);
38575
- min.add(worldOffsetMin);
38576
- max.add(worldOffsetMax);
38577
- // Noise module impact: noise output is normalized to [-1, 1],
38578
- // max displacement = |strength_max|
38579
39469
  var noise = this.noise;
38580
- if (noise.enabled) {
38581
- var noiseMaxX, noiseMaxY, noiseMaxZ;
38582
- if (noise.separateAxes) {
38583
- noiseMaxX = Math.abs(noise.strengthX._getMax());
38584
- noiseMaxY = Math.abs(noise.strengthY._getMax());
38585
- noiseMaxZ = Math.abs(noise.strengthZ._getMax());
38586
- } else {
38587
- noiseMaxX = noiseMaxY = noiseMaxZ = Math.abs(noise.strengthX._getMax());
39470
+ this._getNoiseBoundsExtents(maxLifetime, noiseBoundsExtents);
39471
+ var needTransformFeedback = velocityOverLifetime._needTransformFeedback();
39472
+ var orbitalActive = needTransformFeedback && velocityOverLifetime._isOrbitalActive();
39473
+ if (needTransformFeedback) {
39474
+ var centerOffset = velocityOverLifetime.centerOffset;
39475
+ var radialReach = 0;
39476
+ if (velocityOverLifetime._isRadialActive()) {
39477
+ this._getExtremeValueFromZero(velocityOverLifetime.radial, velMinMaxX);
39478
+ radialReach = Math.max(Math.abs(velMinMaxX.x), Math.abs(velMinMaxX.y)) * maxLifetime;
39479
+ }
39480
+ if (orbitalActive) {
39481
+ var dx = Math.max(Math.abs(min.x - centerOffset.x), Math.abs(max.x - centerOffset.x));
39482
+ var dy = Math.max(Math.abs(min.y - centerOffset.y), Math.abs(max.y - centerOffset.y));
39483
+ var dz = Math.max(Math.abs(min.z - centerOffset.z), Math.abs(max.z - centerOffset.z));
39484
+ var worldReach = this._getRangeReach(worldOffsetMin, worldOffsetMax);
39485
+ var noiseReach = this._getVectorReach(noiseBoundsExtents);
39486
+ var gravityReach = this._getGravityBoundsReach(maxLifetime);
39487
+ var reach = Math.sqrt(dx * dx + dy * dy + dz * dz) + worldReach + noiseReach + gravityReach + radialReach;
39488
+ min.set(Math.min(min.x, centerOffset.x - reach), Math.min(min.y, centerOffset.y - reach), Math.min(min.z, centerOffset.z - reach));
39489
+ max.set(Math.max(max.x, centerOffset.x + reach), Math.max(max.y, centerOffset.y + reach), Math.max(max.z, centerOffset.z + reach));
39490
+ } else if (radialReach > 0) {
39491
+ min.set(min.x - radialReach, min.y - radialReach, min.z - radialReach);
39492
+ max.set(max.x + radialReach, max.y + radialReach, max.z + radialReach);
39493
+ }
39494
+ }
39495
+ out.transform(rotateMat);
39496
+ if (!orbitalActive) {
39497
+ min.add(worldOffsetMin);
39498
+ max.add(worldOffsetMax);
39499
+ if (noise.enabled) {
39500
+ min.set(min.x - noiseBoundsExtents.x, min.y - noiseBoundsExtents.y, min.z - noiseBoundsExtents.z);
39501
+ max.set(max.x + noiseBoundsExtents.x, max.y + noiseBoundsExtents.y, max.z + noiseBoundsExtents.z);
38588
39502
  }
38589
- min.set(min.x - noiseMaxX, min.y - noiseMaxY, min.z - noiseMaxZ);
38590
- max.set(max.x + noiseMaxX, max.y + noiseMaxY, max.z + noiseMaxZ);
38591
39503
  }
38592
39504
  min.add(worldPosition);
38593
39505
  max.add(worldPosition);
38594
39506
  };
39507
+ _proto._useOrbitalBounds = function _useOrbitalBounds() {
39508
+ var velocityOverLifetime = this.velocityOverLifetime;
39509
+ return velocityOverLifetime._needTransformFeedback() && velocityOverLifetime._isOrbitalActive();
39510
+ };
39511
+ _proto._getNoiseBoundsExtents = function _getNoiseBoundsExtents(maxLifetime, out) {
39512
+ var noise = this.noise;
39513
+ if (!noise.enabled) {
39514
+ out.set(0, 0, 0);
39515
+ return;
39516
+ }
39517
+ var noiseMaxX, noiseMaxY, noiseMaxZ;
39518
+ if (noise.separateAxes) {
39519
+ noiseMaxX = this._getCurveMagnitudeFromZero(noise.strengthX);
39520
+ noiseMaxY = this._getCurveMagnitudeFromZero(noise.strengthY);
39521
+ noiseMaxZ = this._getCurveMagnitudeFromZero(noise.strengthZ);
39522
+ } else {
39523
+ noiseMaxX = noiseMaxY = noiseMaxZ = this._getCurveMagnitudeFromZero(noise.strengthX);
39524
+ }
39525
+ out.set(noiseMaxX * maxLifetime, noiseMaxY * maxLifetime, noiseMaxZ * maxLifetime);
39526
+ };
39527
+ _proto._getGravityBoundsReach = function _getGravityBoundsReach(maxLifetime) {
39528
+ var modifierMinMax = ParticleGenerator._tempVector20;
39529
+ this._getExtremeValueFromZero(this.main.gravityModifier, modifierMinMax);
39530
+ var coefficient = 0.5 * maxLifetime * maxLifetime;
39531
+ var minGravityEffect = modifierMinMax.x * coefficient;
39532
+ var maxGravityEffect = modifierMinMax.y * coefficient;
39533
+ var _this__renderer_scene_physics_gravity = this._renderer.scene.physics.gravity, x = _this__renderer_scene_physics_gravity.x, y = _this__renderer_scene_physics_gravity.y, z = _this__renderer_scene_physics_gravity.z;
39534
+ var gravityBoundsExtents = ParticleGenerator._tempVector33;
39535
+ gravityBoundsExtents.set(Math.max(Math.abs(x * minGravityEffect), Math.abs(x * maxGravityEffect)), Math.max(Math.abs(y * minGravityEffect), Math.abs(y * maxGravityEffect)), Math.max(Math.abs(z * minGravityEffect), Math.abs(z * maxGravityEffect)));
39536
+ return this._getVectorReach(gravityBoundsExtents);
39537
+ };
39538
+ _proto._getRangeReach = function _getRangeReach(min, max) {
39539
+ var x = Math.max(Math.abs(min.x), Math.abs(max.x));
39540
+ var y = Math.max(Math.abs(min.y), Math.abs(max.y));
39541
+ var z = Math.max(Math.abs(min.z), Math.abs(max.z));
39542
+ return Math.sqrt(x * x + y * y + z * z);
39543
+ };
39544
+ _proto._getVectorReach = function _getVectorReach(value) {
39545
+ return Math.sqrt(value.x * value.x + value.y * value.y + value.z * value.z);
39546
+ };
39547
+ _proto._getCurveMagnitudeFromZero = function _getCurveMagnitudeFromZero(curve) {
39548
+ var minMax = ParticleGenerator._tempVector20;
39549
+ this._getExtremeValueFromZero(curve, minMax);
39550
+ return Math.max(Math.abs(minMax.x), Math.abs(minMax.y));
39551
+ };
38595
39552
  _proto._addGravityToBounds = function _addGravityToBounds(maxLifetime, origin, out) {
38596
39553
  var originMin = origin.min, originMax = origin.max;
38597
39554
  var modifierMinMax = ParticleGenerator._tempVector20;
@@ -38653,8 +39610,10 @@ ParticleGenerator._tempVector22 = new Vector2();
38653
39610
  ParticleGenerator._tempVector30 = new Vector3();
38654
39611
  ParticleGenerator._tempVector31 = new Vector3();
38655
39612
  ParticleGenerator._tempVector32 = new Vector3();
39613
+ ParticleGenerator._tempVector33 = new Vector3();
38656
39614
  ParticleGenerator._tempMat = new Matrix();
38657
- ParticleGenerator._tempColor0 = new Color();
39615
+ ParticleGenerator._tempColor = new Color();
39616
+ ParticleGenerator._tempQuat0 = new Quaternion();
38658
39617
  ParticleGenerator._tempParticleRenderers = new Array();
38659
39618
  ParticleGenerator._particleIncreaseCount = 128;
38660
39619
  ParticleGenerator._transformedBoundsIncreaseCount = 16;
@@ -38689,6 +39648,9 @@ __decorate([
38689
39648
  __decorate([
38690
39649
  deepClone
38691
39650
  ], ParticleGenerator.prototype, "noise", void 0);
39651
+ __decorate([
39652
+ deepClone
39653
+ ], ParticleGenerator.prototype, "subEmitters", void 0);
38692
39654
  __decorate([
38693
39655
  deepClone
38694
39656
  ], ParticleGenerator.prototype, "customData", void 0);
@@ -38728,6 +39690,9 @@ __decorate([
38728
39690
  __decorate([
38729
39691
  ignoreClone
38730
39692
  ], ParticleGenerator.prototype, "_feedbackBindingIndex", void 0);
39693
+ __decorate([
39694
+ ignoreClone
39695
+ ], ParticleGenerator.prototype, "_feedbackReadback", void 0);
38731
39696
  __decorate([
38732
39697
  ignoreClone
38733
39698
  ], ParticleGenerator.prototype, "_isPlaying", void 0);
@@ -38758,6 +39723,27 @@ __decorate([
38758
39723
  __decorate([
38759
39724
  ignoreClone
38760
39725
  ], ParticleGenerator.prototype, "_playStartDelay", void 0);
39726
+ __decorate([
39727
+ ignoreClone
39728
+ ], ParticleGenerator.prototype, "_eventPos", void 0);
39729
+ __decorate([
39730
+ ignoreClone
39731
+ ], ParticleGenerator.prototype, "_eventColor", void 0);
39732
+ __decorate([
39733
+ ignoreClone
39734
+ ], ParticleGenerator.prototype, "_eventSize", void 0);
39735
+ __decorate([
39736
+ ignoreClone
39737
+ ], ParticleGenerator.prototype, "_eventRotation", void 0);
39738
+ __decorate([
39739
+ ignoreClone
39740
+ ], ParticleGenerator.prototype, "_eventDir", void 0);
39741
+ __decorate([
39742
+ ignoreClone
39743
+ ], ParticleGenerator.prototype, "_emitLocalPos", void 0);
39744
+ __decorate([
39745
+ ignoreClone
39746
+ ], ParticleGenerator.prototype, "_emitDirection", void 0);
38761
39747
 
38762
39748
  /**
38763
39749
  * Base material for visual effects like particles and trails.
@@ -40462,7 +41448,14 @@ var cacheDir = new Vector3();
40462
41448
  * Suspend the audio context.
40463
41449
  * @returns A promise that resolves when the audio context is suspended
40464
41450
  */ AudioManager.suspend = function suspend() {
40465
- return AudioManager.getContext().suspend();
41451
+ // No context means nothing is playing: suspending is a no-op and must NOT flag a caller-suspend
41452
+ // (a ghost flag would later block foreground recovery), and don't create a cold context just to suspend
41453
+ var context = AudioManager._context;
41454
+ if (!context) {
41455
+ return Promise.resolve();
41456
+ }
41457
+ AudioManager._suspendedByCaller = true;
41458
+ return context.suspend();
40466
41459
  };
40467
41460
  /**
40468
41461
  * Resume the audio context.
@@ -40470,6 +41463,7 @@ var cacheDir = new Vector3();
40470
41463
  * @returns A promise that resolves when the audio context is resumed
40471
41464
  */ AudioManager.resume = function resume() {
40472
41465
  var _AudioManager;
41466
+ AudioManager._suspendedByCaller = false;
40473
41467
  var __resumePromise;
40474
41468
  return (__resumePromise = (_AudioManager = AudioManager)._resumePromise) != null ? __resumePromise : _AudioManager._resumePromise = AudioManager.getContext().resume().then(function() {
40475
41469
  AudioManager._needsUserGestureResume = false;
@@ -40484,7 +41478,9 @@ var cacheDir = new Vector3();
40484
41478
  if (!context) {
40485
41479
  AudioManager._context = context = new window.AudioContext();
40486
41480
  document.addEventListener("visibilitychange", AudioManager._onVisibilityChange);
40487
- // iOS Safari requires user gesture to resume AudioContext
41481
+ // iOS Safari bfcache restore fires pageshow (persisted) but NOT visibilitychange, so recover here too
41482
+ window.addEventListener("pageshow", AudioManager._onPageShow);
41483
+ // iOS Safari requires a user gesture to resume the AudioContext
40488
41484
  document.addEventListener("touchstart", AudioManager._resumeAfterInterruption, {
40489
41485
  passive: true
40490
41486
  });
@@ -40512,27 +41508,62 @@ var cacheDir = new Vector3();
40512
41508
  return AudioManager.getContext().state === "running";
40513
41509
  };
40514
41510
  AudioManager._onVisibilityChange = function _onVisibilityChange() {
40515
- if (!document.hidden && AudioManager._playingCount > 0 && !AudioManager.isAudioContextRunning()) {
40516
- // iOS WKWebView WebKit bug(Triggered in LingGuang App): AudioContext may be in a "zombie" state where
40517
- // state reports "suspended" but resume() alone won't restart audio rendering.
40518
- // Calling suspend() first forces a clean internal state reset before user gesture triggers resume.
40519
- // Related: https://bugs.webkit.org/show_bug.cgi?id=263627
40520
- AudioManager.suspend();
40521
- AudioManager._needsUserGestureResume = true;
41511
+ if (document.hidden) {
41512
+ var // Desktop/Android don't auto-suspend a running WebAudio context when backgrounded (only iOS does),
41513
+ // so suspend here to stop audio in the background; only if a context already exists (don't create one)
41514
+ _AudioManager__context;
41515
+ (_AudioManager__context = AudioManager._context) == null ? void 0 : _AudioManager__context.suspend().catch(function() {});
41516
+ } else {
41517
+ AudioManager._recoverPlaybackContext();
41518
+ }
41519
+ };
41520
+ AudioManager._recoverPlaybackContext = function _recoverPlaybackContext() {
41521
+ // Returning to foreground with a non-running context (and not a deliberate pause): iOS leaves it
41522
+ // "interrupted", which cannot be resumed directly; suspend() first transitions it to "suspended",
41523
+ // then resume() restarts the pipeline https://bugs.webkit.org/show_bug.cgi?id=263627
41524
+ // _recovering guards re-entry: a bfcache restore fires both visibilitychange and pageshow
41525
+ if (AudioManager._recovering || document.hidden || AudioManager._suspendedByCaller || AudioManager._playingCount <= 0 || AudioManager.isAudioContextRunning()) {
41526
+ return;
41527
+ }
41528
+ AudioManager._recovering = true;
41529
+ AudioManager._needsUserGestureResume = true; // fallback if the auto-resume below is rejected
41530
+ var context = AudioManager.getContext();
41531
+ context.suspend().catch(function() {});
41532
+ // 100ms empirical delay (resume too soon after suspend is unreliable on iOS); _recovering is cleared
41533
+ // on the timer rather than off a promise because iOS may never settle suspend/resume in interrupted
41534
+ setTimeout(function() {
41535
+ AudioManager._recovering = false;
41536
+ if (document.hidden || AudioManager._suspendedByCaller) {
41537
+ return;
41538
+ }
41539
+ // Go through AudioManager.resume() so _resumePromise coalesces any gesture-resume racing us during
41540
+ // the slow iOS interrupted->running transition; a bare context.resume() here wouldn't dedupe
41541
+ AudioManager.resume().catch(function() {});
41542
+ }, 100);
41543
+ };
41544
+ AudioManager._onPageShow = function _onPageShow(event) {
41545
+ // iOS Safari bfcache restore (persisted) needs recovery; a normal load has no suspended context
41546
+ if (event.persisted) {
41547
+ AudioManager._recoverPlaybackContext();
40522
41548
  }
40523
41549
  };
40524
41550
  AudioManager._resumeAfterInterruption = function _resumeAfterInterruption() {
40525
- if (AudioManager._needsUserGestureResume) {
40526
- AudioManager.resume().catch(function(e) {
40527
- console.warn("Failed to resume AudioContext:", e);
40528
- });
41551
+ // iOS Safari gesture fallback for when auto-resume is blocked.
41552
+ // _recovering: don't bypass the 100ms delay (would resume on a still-interrupted context)
41553
+ if (AudioManager._recovering || AudioManager._suspendedByCaller || !AudioManager._needsUserGestureResume) {
41554
+ return;
40529
41555
  }
41556
+ AudioManager.resume().catch(function(e) {
41557
+ console.warn("Failed to resume AudioContext:", e);
41558
+ });
40530
41559
  };
40531
41560
  return AudioManager;
40532
41561
  }();
40533
41562
  /** @internal */ AudioManager._playingCount = 0;
40534
41563
  AudioManager._resumePromise = null;
40535
41564
  AudioManager._needsUserGestureResume = false;
41565
+ AudioManager._suspendedByCaller = false;
41566
+ AudioManager._recovering = false;
40536
41567
 
40537
41568
  /**
40538
41569
  * Audio Source Component.
@@ -40542,8 +41573,6 @@ AudioManager._needsUserGestureResume = false;
40542
41573
  var _this;
40543
41574
  _this = Component.call(this, entity) || this, /** If set to true, the audio component automatically begins to play on startup. */ _this.playOnEnabled = true, _this._isPlaying = false, _this._pendingPlay = false, _this._sourceNode = null, _this._pausedTime = -1, _this._playTime = -1, _this._volume = 1, _this._lastVolume = 1, _this._playbackRate = 1, _this._loop = false;
40544
41575
  _this._onPlayEnd = _this._onPlayEnd.bind(_this);
40545
- _this._gainNode = AudioManager.getContext().createGain();
40546
- _this._gainNode.connect(AudioManager.getGainNode());
40547
41576
  return _this;
40548
41577
  }
40549
41578
  var _proto = AudioSource.prototype;
@@ -40555,6 +41584,10 @@ AudioManager._needsUserGestureResume = false;
40555
41584
  if (!((_this__clip = this._clip) == null ? void 0 : _this__clip._getAudioSource()) || this._isPlaying || this._pendingPlay) {
40556
41585
  return;
40557
41586
  }
41587
+ // Hidden page: don't start (would leak a sound) and don't pend (would replay out of sync) -> drop
41588
+ if (document.hidden) {
41589
+ return;
41590
+ }
40558
41591
  if (AudioManager.isAudioContextRunning()) {
40559
41592
  this._startPlayback();
40560
41593
  } else {
@@ -40567,8 +41600,8 @@ AudioManager._needsUserGestureResume = false;
40567
41600
  return;
40568
41601
  }
40569
41602
  _this._pendingPlay = false;
40570
- // Check if still valid to play after async resume
40571
- if (_this._destroyed || !_this.enabled || !_this._clip) {
41603
+ // Check if still valid to play after async resume (page may have been hidden meanwhile)
41604
+ if (_this._destroyed || !_this.enabled || !_this._clip || document.hidden) {
40572
41605
  return;
40573
41606
  }
40574
41607
  _this._startPlayback();
@@ -40585,10 +41618,11 @@ AudioManager._needsUserGestureResume = false;
40585
41618
  if (this._isPlaying) {
40586
41619
  this._clearSourceNode();
40587
41620
  this._isPlaying = false;
40588
- this._pausedTime = -1;
40589
- this._playTime = -1;
40590
41621
  AudioManager._playingCount--;
40591
41622
  }
41623
+ // stop() always resets to the start, including from a paused state (where _isPlaying is already false)
41624
+ this._pausedTime = -1;
41625
+ this._playTime = -1;
40592
41626
  };
40593
41627
  /**
40594
41628
  * Pauses playing the clip.
@@ -40606,7 +41640,7 @@ AudioManager._needsUserGestureResume = false;
40606
41640
  */ _proto._cloneTo = function _cloneTo(target) {
40607
41641
  var _target__clip;
40608
41642
  (_target__clip = target._clip) == null ? void 0 : _target__clip._addReferCount(1);
40609
- target._gainNode.gain.setValueAtTime(target._volume, AudioManager.getContext().currentTime);
41643
+ // _volume is field-cloned; its gain node is applied lazily on first play
40610
41644
  };
40611
41645
  /**
40612
41646
  * @internal
@@ -40628,6 +41662,15 @@ AudioManager._needsUserGestureResume = false;
40628
41662
  _proto._onPlayEnd = function _onPlayEnd() {
40629
41663
  this.stop();
40630
41664
  };
41665
+ _proto._ensureGainNode = function _ensureGainNode() {
41666
+ var gainNode = this._gainNode;
41667
+ if (!gainNode) {
41668
+ this._gainNode = gainNode = AudioManager.getContext().createGain();
41669
+ gainNode.connect(AudioManager.getGainNode());
41670
+ gainNode.gain.setValueAtTime(this._volume, AudioManager.getContext().currentTime);
41671
+ }
41672
+ return gainNode;
41673
+ };
40631
41674
  _proto._startPlayback = function _startPlayback() {
40632
41675
  var startTime = this._pausedTime > 0 ? this._pausedTime - this._playTime : 0;
40633
41676
  this._initSourceNode(startTime);
@@ -40639,13 +41682,17 @@ AudioManager._needsUserGestureResume = false;
40639
41682
  _proto._initSourceNode = function _initSourceNode(startTime) {
40640
41683
  var context = AudioManager.getContext();
40641
41684
  var sourceNode = context.createBufferSource();
40642
- sourceNode.buffer = this._clip._getAudioSource();
41685
+ var buffer = this._clip._getAudioSource();
41686
+ sourceNode.buffer = buffer;
40643
41687
  sourceNode.playbackRate.value = this._playbackRate;
40644
41688
  sourceNode.loop = this._loop;
40645
41689
  sourceNode.onended = this._onPlayEnd;
40646
41690
  this._sourceNode = sourceNode;
40647
- sourceNode.connect(this._gainNode);
40648
- sourceNode.start(0, startTime);
41691
+ sourceNode.connect(this._ensureGainNode());
41692
+ // startTime is total elapsed time; for a looping clip wrap it into the buffer to keep the loop phase
41693
+ // (start()'s offset clamps past the end, it does not wrap)
41694
+ var offset = this._loop && buffer.duration > 0 ? startTime % buffer.duration : startTime;
41695
+ sourceNode.start(0, offset);
40649
41696
  };
40650
41697
  _proto._clearSourceNode = function _clearSourceNode() {
40651
41698
  this._sourceNode.stop();
@@ -40688,9 +41735,11 @@ AudioManager._needsUserGestureResume = false;
40688
41735
  return this._volume;
40689
41736
  },
40690
41737
  set: function set(value) {
41738
+ var // No node yet -> _ensureGainNode() applies _volume on first play
41739
+ _this__gainNode;
40691
41740
  value = Math.min(Math.max(0, value), 1.0);
40692
41741
  this._volume = value;
40693
- this._gainNode.gain.setValueAtTime(value, AudioManager.getContext().currentTime);
41742
+ (_this__gainNode = this._gainNode) == null ? void 0 : _this__gainNode.gain.setValueAtTime(value, AudioManager.getContext().currentTime);
40694
41743
  }
40695
41744
  },
40696
41745
  {
@@ -40802,6 +41851,7 @@ __decorate([
40802
41851
  Polyfill.registerPolyfill = function registerPolyfill() {
40803
41852
  Polyfill._registerMatchAll();
40804
41853
  Polyfill._registerAudioContext();
41854
+ Polyfill._registerOfflineAudioContext();
40805
41855
  Polyfill._registerTextMetrics();
40806
41856
  Polyfill._registerPromiseFinally();
40807
41857
  };
@@ -40866,20 +41916,32 @@ __decorate([
40866
41916
  if (!window.AudioContext && window.webkitAudioContext) {
40867
41917
  Logger.info("Polyfill window.AudioContext");
40868
41918
  window.AudioContext = window.webkitAudioContext;
40869
- var originalDecodeAudioData = AudioContext.prototype.decodeAudioData;
40870
- AudioContext.prototype.decodeAudioData = function(arrayBuffer, successCallback, errorCallback) {
40871
- var _this = this;
40872
- return new Promise(function(resolve, reject) {
40873
- originalDecodeAudioData.call(_this, arrayBuffer, function(buffer) {
40874
- successCallback == null ? void 0 : successCallback(buffer);
40875
- resolve(buffer);
40876
- }, function(error) {
40877
- errorCallback == null ? void 0 : errorCallback(error);
40878
- reject(error);
40879
- });
41919
+ Polyfill._promisifyDecodeAudioData(AudioContext.prototype);
41920
+ }
41921
+ };
41922
+ Polyfill._registerOfflineAudioContext = function _registerOfflineAudioContext() {
41923
+ // iOS 14.0 and earlier expose only webkitOfflineAudioContext, with callback-form decodeAudioData
41924
+ if (!window.OfflineAudioContext && window.webkitOfflineAudioContext) {
41925
+ Logger.info("Polyfill window.OfflineAudioContext");
41926
+ window.OfflineAudioContext = window.webkitOfflineAudioContext;
41927
+ Polyfill._promisifyDecodeAudioData(OfflineAudioContext.prototype);
41928
+ }
41929
+ };
41930
+ // Wrap the old callback-form decodeAudioData (on prefixed iOS contexts) into the modern Promise form
41931
+ Polyfill._promisifyDecodeAudioData = function _promisifyDecodeAudioData(proto) {
41932
+ var originalDecodeAudioData = proto.decodeAudioData;
41933
+ proto.decodeAudioData = function(arrayBuffer, successCallback, errorCallback) {
41934
+ var _this = this;
41935
+ return new Promise(function(resolve, reject) {
41936
+ originalDecodeAudioData.call(_this, arrayBuffer, function(buffer) {
41937
+ successCallback == null ? void 0 : successCallback(buffer);
41938
+ resolve(buffer);
41939
+ }, function(error) {
41940
+ errorCallback == null ? void 0 : errorCallback(error);
41941
+ reject(error);
40880
41942
  });
40881
- };
40882
- }
41943
+ });
41944
+ };
40883
41945
  };
40884
41946
  Polyfill._registerTextMetrics = function _registerTextMetrics() {
40885
41947
  // Based on the specific version of the engine implementation, when actualBoundingBoxLeft is not supported, width is used to represent the rendering width, and `textAlign` uses the default value `start` and direction is left to right.
@@ -40922,5 +41984,5 @@ __decorate([
40922
41984
  return Polyfill;
40923
41985
  }();
40924
41986
 
40925
- export { AmbientLight, AmbientOcclusion, AmbientOcclusionQuality, AnimationArrayCurve, AnimationBoolCurve, AnimationClip, AnimationClipCurveBinding, AnimationColorCurve, AnimationCurve, AnimationEvent, AnimationFloatArrayCurve, AnimationFloatCurve, AnimationQuaternionCurve, AnimationRectCurve, AnimationRefCurve, AnimationStringCurve, AnimationVector2Curve, AnimationVector3Curve, AnimationVector4Curve, Animator, AnimatorCondition, AnimatorConditionMode, AnimatorController, AnimatorControllerLayer, AnimatorControllerParameter, AnimatorCullingMode, AnimatorLayerBlendingMode, AnimatorLayerMask, AnimatorState, AnimatorStateInstance, AnimatorStateMachine, AnimatorStateTransition, AntiAliasing, AssetPromise, AssetType, AudioClip, AudioManager, AudioSource, Background, BackgroundMode, BackgroundTextureFillMode, BaseMaterial, BasicRenderPipeline, BlendFactor, BlendMode, BlendOperation, BlendShape, BlendShapeFrame, BlinnPhongMaterial, Blitter, BloomDownScaleMode, BloomEffect, BoolUpdateFlag, BoxColliderShape, BoxShape, Buffer, BufferAsset, BufferBindFlag, BufferMesh, BufferUsage, BufferUtil, Burst, Camera, CameraClearFlags, CameraModifyFlags, CameraType, Canvas, CapsuleColliderShape, CharRenderInfo, CharacterController, CircleShape, ClearableObjectPool, CloneManager, CloneUtils, Collider, ColliderShape, ColliderShapeUpAxis, Collision, CollisionDetectionMode, ColorOverLifetimeModule, ColorWriteMask, CompareFunction, Component, ConeEmitType, ConeShape, ContactPoint, ContentRestorer, ControllerCollisionFlag, ControllerNonWalkableMode, CubeProbe, CullMode, CurveKey, CustomDataModule, DataType, DependentMode, DepthTextureMode, DiffuseMode, DirectLight, DisorderedArray, Downsampling, DynamicCollider, DynamicColliderConstraints, EmissionModule, Engine, EngineEventType, EngineObject, Entity, EntityModifyFlags, EventDispatcher, FinalPass, FixedJoint, FogMode, Font, FontStyle, GLCapabilityType, GradientAlphaKey, GradientColorKey, HemisphereShape, HingeJoint, HitResult, IndexBufferBinding, IndexFormat, InputManager, InterpolationType, JSONAsset, Joint, JointLimits, JointMotor, Keyframe, Keys, Layer, LayerPathMask, Light, LimitVelocityOverLifetimeModule, Loader, Logger, MSAASamples, MainModule, Material, Mesh, MeshColliderShape, MeshColliderShapeCookingFlag, MeshRenderer, MeshShape, MeshTopology, ModelMesh, NoiseModule, OverflowMode, PBRMaterial, ParticleCompositeCurve, ParticleCompositeGradient, ParticleCurve, ParticleCurveMode, ParticleGenerator, ParticleGradient, ParticleGradientMode, ParticleMaterial, ParticleRenderMode, ParticleRenderer, ParticleScaleMode, ParticleShapeArcMode, ParticleShapeType, ParticleSimulationSpace, ParticleStopMode, PhysicsMaterial, PhysicsMaterialCombineMode, PhysicsScene, PipelineStage, PlaneColliderShape, Platform, PointLight, Pointer, PointerButton, PointerEventData, PointerEventEmitter, PointerPhase, Polyfill, PostProcess, PostProcessEffect, PostProcessEffectBoolParameter, PostProcessEffectColorParameter, PostProcessEffectEnumParameter, PostProcessEffectFloatParameter, PostProcessEffectParameter, PostProcessEffectTextureParameter, PostProcessEffectVector2Parameter, PostProcessEffectVector3Parameter, PostProcessEffectVector4Parameter, PostProcessManager, PostProcessPass, PostProcessPassEvent, PostProcessUberPass, Primitive, PrimitiveMesh, Probe, ReferResource, RefractionMode, RenderBufferDepthFormat, RenderElement, RenderFace, RenderQueue, RenderQueueFlags, RenderQueueType, RenderStateElementKey, RenderTarget, Renderer, RendererUpdateFlags, RenderingStatistics, ReplacementFailureStrategy, ResourceManager, ReturnableObjectPool, RotationOverLifetimeModule, SafeLoopArray, Scene, SceneManager, Script, SetDataOptions, Shader, ShaderData, ShaderDataGroup, ShaderFactory, ShaderLanguage, ShaderMacro, ShaderMacroCollection, ShaderPass, ShaderProperty, ShaderPropertyType, ShaderTagKey, ShadowCascadesMode, ShadowResolution, ShadowType, Signal, SimpleSpriteAssembler, SizeOverLifetimeModule, Skin, SkinnedMeshRenderer, Sky, SkyBoxMaterial, SkyProceduralMaterial, SlicedSpriteAssembler, SphereColliderShape, SphereShape, SpotLight, SpringJoint, Sprite, SpriteAtlas, SpriteDrawMode, SpriteMask, SpriteMaskInteraction, SpriteMaskLayer, SpriteModifyFlags, SpriteRenderer, SpriteTileMode, StateMachineScript, StaticCollider, StencilOperation, SubFont, SubMesh, SubPrimitive, SubShader, SunMode, SystemInfo, TextAsset, TextHorizontalAlignment, TextRenderer, TextUtils, TextVerticalAlignment, Texture, Texture2D, Texture2DArray, TextureCoordinate, TextureCube, TextureCubeFace, TextureDepthCompareFunction, TextureFilterMode, TextureFormat, TextureSheetAnimationModule, TextureUsage, TextureUtils, TextureWrapMode, TiledSpriteAssembler, Time, TonemappingEffect, TonemappingMode, TrailMaterial, TrailRenderer, TrailTextureMode, Transform, TransformModifyFlags, UnlitMaterial, Utils, VelocityOverLifetimeModule, VertexAttribute, VertexBufferBinding, VertexElement, VertexElementFormat, VertexMergeBatcher, WrapMode, XRManager, assignmentClone, deepClone, dependentComponents, ignoreClone, registerPointerEventEmitter, request, resourceLoader, shallowClone };
41987
+ export { AmbientLight, AmbientOcclusion, AmbientOcclusionQuality, AnimationArrayCurve, AnimationBoolCurve, AnimationClip, AnimationClipCurveBinding, AnimationColorCurve, AnimationCurve, AnimationEvent, AnimationFloatArrayCurve, AnimationFloatCurve, AnimationQuaternionCurve, AnimationRectCurve, AnimationRefCurve, AnimationStringCurve, AnimationVector2Curve, AnimationVector3Curve, AnimationVector4Curve, Animator, AnimatorCondition, AnimatorConditionMode, AnimatorController, AnimatorControllerLayer, AnimatorControllerParameter, AnimatorCullingMode, AnimatorLayerBlendingMode, AnimatorLayerMask, AnimatorState, AnimatorStateInstance, AnimatorStateMachine, AnimatorStateTransition, AntiAliasing, AssetPromise, AssetType, AudioClip, AudioManager, AudioSource, Background, BackgroundMode, BackgroundTextureFillMode, BaseMaterial, BasicRenderPipeline, BlendFactor, BlendMode, BlendOperation, BlendShape, BlendShapeFrame, BlinnPhongMaterial, Blitter, BloomDownScaleMode, BloomEffect, BoolUpdateFlag, BoxColliderShape, BoxShape, Buffer, BufferAsset, BufferBindFlag, BufferMesh, BufferUsage, BufferUtil, Burst, Camera, CameraClearFlags, CameraModifyFlags, CameraType, Canvas, CapsuleColliderShape, CharRenderInfo, CharacterController, CircleShape, ClearableObjectPool, CloneManager, CloneUtils, Collider, ColliderShape, ColliderShapeUpAxis, Collision, CollisionDetectionMode, ColorOverLifetimeModule, ColorWriteMask, CompareFunction, Component, ConeEmitType, ConeShape, ContactPoint, ContentRestorer, ControllerCollisionFlag, ControllerNonWalkableMode, CubeProbe, CullMode, CurveKey, CustomDataModule, DataType, DependentMode, DepthTextureMode, DiffuseMode, DirectLight, DisorderedArray, Downsampling, DynamicCollider, DynamicColliderConstraints, EmissionModule, Engine, EngineEventType, EngineObject, Entity, EntityModifyFlags, EventDispatcher, FinalPass, FixedJoint, FogMode, Font, FontStyle, GLCapabilityType, GradientAlphaKey, GradientColorKey, HemisphereShape, HingeJoint, HitResult, IndexBufferBinding, IndexFormat, InputManager, InterpolationType, JSONAsset, Joint, JointLimits, JointMotor, Keyframe, Keys, Layer, LayerPathMask, Light, LimitVelocityOverLifetimeModule, Loader, Logger, MSAASamples, MainModule, Material, Mesh, MeshColliderShape, MeshColliderShapeCookingFlag, MeshRenderer, MeshShape, MeshTopology, ModelMesh, NoiseModule, OverflowMode, PBRMaterial, ParticleCompositeCurve, ParticleCompositeGradient, ParticleCurve, ParticleCurveMode, ParticleGenerator, ParticleGradient, ParticleGradientMode, ParticleMaterial, ParticleRenderMode, ParticleRenderer, ParticleScaleMode, ParticleShapeArcMode, ParticleShapeType, ParticleSimulationSpace, ParticleStopMode, ParticleSubEmitterInheritProperty, ParticleSubEmitterType, PhysicsMaterial, PhysicsMaterialCombineMode, PhysicsScene, PipelineStage, PlaneColliderShape, Platform, PointLight, Pointer, PointerButton, PointerEventData, PointerEventEmitter, PointerPhase, Polyfill, PostProcess, PostProcessEffect, PostProcessEffectBoolParameter, PostProcessEffectColorParameter, PostProcessEffectEnumParameter, PostProcessEffectFloatParameter, PostProcessEffectParameter, PostProcessEffectTextureParameter, PostProcessEffectVector2Parameter, PostProcessEffectVector3Parameter, PostProcessEffectVector4Parameter, PostProcessManager, PostProcessPass, PostProcessPassEvent, PostProcessUberPass, Primitive, PrimitiveMesh, Probe, ReferResource, RefractionMode, RenderBufferDepthFormat, RenderElement, RenderFace, RenderQueue, RenderQueueFlags, RenderQueueType, RenderStateElementKey, RenderTarget, Renderer, RendererUpdateFlags, RenderingStatistics, ReplacementFailureStrategy, ResourceManager, ReturnableObjectPool, RotationOverLifetimeModule, SafeLoopArray, Scene, SceneManager, Script, SetDataOptions, Shader, ShaderData, ShaderDataGroup, ShaderFactory, ShaderLanguage, ShaderMacro, ShaderMacroCollection, ShaderPass, ShaderProperty, ShaderPropertyType, ShaderTagKey, ShadowCascadesMode, ShadowResolution, ShadowType, Signal, SimpleSpriteAssembler, SizeOverLifetimeModule, Skin, SkinnedMeshRenderer, Sky, SkyBoxMaterial, SkyProceduralMaterial, SlicedSpriteAssembler, SphereColliderShape, SphereShape, SpotLight, SpringJoint, Sprite, SpriteAtlas, SpriteDrawMode, SpriteMask, SpriteMaskInteraction, SpriteMaskLayer, SpriteModifyFlags, SpriteRenderer, SpriteTileMode, StateMachineScript, StaticCollider, StencilOperation, SubEmitter, SubEmittersModule, SubFont, SubMesh, SubPrimitive, SubShader, SunMode, SystemInfo, TextAsset, TextHorizontalAlignment, TextRenderer, TextUtils, TextVerticalAlignment, Texture, Texture2D, Texture2DArray, TextureCoordinate, TextureCube, TextureCubeFace, TextureDepthCompareFunction, TextureFilterMode, TextureFormat, TextureSheetAnimationModule, TextureUsage, TextureUtils, TextureWrapMode, TiledSpriteAssembler, Time, TonemappingEffect, TonemappingMode, TrailMaterial, TrailRenderer, TrailTextureMode, Transform, TransformModifyFlags, UnlitMaterial, Utils, VelocityOverLifetimeModule, VertexAttribute, VertexBufferBinding, VertexElement, VertexElementFormat, VertexMergeBatcher, WrapMode, XRManager, assignmentClone, deepClone, dependentComponents, ignoreClone, registerPointerEventEmitter, request, resourceLoader, shallowClone };
40926
41988
  //# sourceMappingURL=module.js.map