@galacean/engine-loader 0.0.0-experimental-2.0-game.18 → 0.0.0-experimental-2.0-spine.1

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.
Files changed (34) hide show
  1. package/dist/main.js +1156 -1378
  2. package/dist/main.js.map +1 -1
  3. package/dist/module.js +1157 -1379
  4. package/dist/module.js.map +1 -1
  5. package/package.json +4 -4
  6. package/types/HDRDecoder.d.ts +27 -8
  7. package/types/SceneLoader.d.ts +8 -1
  8. package/types/{Texture2DLoader.d.ts → TextureLoader.d.ts} +4 -4
  9. package/types/gltf/extensions/GLTFExtensionSchema.d.ts +2 -3
  10. package/types/gltf/parser/GLTFSceneParser.d.ts +1 -0
  11. package/types/gltf/parser/GLTFSkinParser.d.ts +5 -2
  12. package/types/index.d.ts +3 -5
  13. package/types/prefab/PrefabParser.d.ts +9 -6
  14. package/types/resource-deserialize/index.d.ts +3 -2
  15. package/types/resource-deserialize/resources/parser/HierarchyParser.d.ts +22 -27
  16. package/types/resource-deserialize/resources/parser/ParserContext.d.ts +11 -11
  17. package/types/resource-deserialize/resources/parser/ReflectionParser.d.ts +45 -18
  18. package/types/resource-deserialize/resources/scene/SceneParser.d.ts +6 -7
  19. package/types/schema/BasicSchema.d.ts +21 -0
  20. package/types/schema/CommonSchema.d.ts +33 -0
  21. package/types/schema/HierarchySchema.d.ts +71 -0
  22. package/types/schema/MaterialSchema.d.ts +27 -0
  23. package/types/schema/PrefabSchema.d.ts +4 -0
  24. package/types/schema/SceneSchema.d.ts +59 -0
  25. package/types/{resource-deserialize/resources/schema → schema}/index.d.ts +4 -1
  26. package/types/schema/refs.d.ts +2 -0
  27. package/types/ShaderChunkLoader.d.ts +0 -9
  28. package/types/resource-deserialize/resources/schema/BasicSchema.d.ts +0 -105
  29. package/types/resource-deserialize/resources/schema/MaterialSchema.d.ts +0 -102
  30. package/types/resource-deserialize/resources/schema/SceneSchema.d.ts +0 -84
  31. package/types/resource-deserialize/resources/texture2D/TextureDecoder.d.ts +0 -9
  32. /package/types/{TextureCubeLoader.d.ts → resource-deserialize/resources/texture2D/Texture2DDecoder.d.ts} +0 -0
  33. /package/types/{gltf/parser/GLTFSkinParser.test.d.ts → resource-deserialize/resources/textureCube/TextureCubeDecoder.d.ts} +0 -0
  34. /package/types/{resource-deserialize/resources/schema → schema}/ProjectSchema.d.ts +0 -0
package/dist/main.js CHANGED
@@ -676,6 +676,29 @@ function _construct(Parent, args, Class) {
676
676
  return _construct.apply(null, arguments);
677
677
  }
678
678
 
679
+ function _object_without_properties_loose(source, excluded) {
680
+ if (source == null) return {};
681
+
682
+ var target = {};
683
+ var sourceKeys = Object.keys(source);
684
+ var key, i;
685
+
686
+ for (i = 0; i < sourceKeys.length; i++) {
687
+ key = sourceKeys[i];
688
+ if (excluded.indexOf(key) >= 0) continue;
689
+ target[key] = source[key];
690
+ }
691
+
692
+ return target;
693
+ }
694
+
695
+ function resolveRefItem(refs, index, owner, label) {
696
+ if (!Number.isInteger(index) || index < 0 || index >= refs.length) {
697
+ throw new Error(owner + ": invalid ref index " + index + " for " + label);
698
+ }
699
+ return refs[index];
700
+ }
701
+
679
702
  var ParserType = /*#__PURE__*/ function(ParserType) {
680
703
  ParserType[ParserType["Prefab"] = 0] = "Prefab";
681
704
  ParserType[ParserType["Scene"] = 1] = "Scene";
@@ -689,32 +712,20 @@ var ParserType = /*#__PURE__*/ function(ParserType) {
689
712
  this.engine = engine;
690
713
  this.type = type;
691
714
  this.resource = resource;
692
- this.entityMap = new Map();
693
- this.entityConfigMap = new Map();
694
- this.components = new Map();
695
- this.componentConfigMap = new Map();
696
- this.rootIds = [];
697
- this.strippedIds = [];
698
- this._tasks = new Set();
715
+ this./** Runtime Entity instances, indexed by the flat entities[] position. */ entityInstances = [];
716
+ this./** Components waiting for props/calls application (Stage 4). */ pendingComponents = [];
699
717
  this._loaded = 0;
700
718
  this._total = 0;
701
719
  this.resourceManager = engine.resourceManager;
702
720
  }
703
721
  var _proto = ParserContext.prototype;
704
722
  _proto.clear = function clear() {
705
- this.entityMap.clear();
706
- this.components.clear();
707
- this.componentConfigMap.clear();
708
- this.entityConfigMap.clear();
709
- this.rootIds.length = 0;
710
- this.strippedIds.length = 0;
711
- };
712
- /** @internal */ _proto._addDependentAsset = function _addDependentAsset(url, promise) {
723
+ this.entityInstances.length = 0;
724
+ this.pendingComponents.length = 0;
725
+ };
726
+ /** @internal */ _proto._addDependentAsset = function _addDependentAsset(promise) {
713
727
  var _this = this;
714
- var tasks = this._tasks;
715
- if (tasks.has(url)) return;
716
728
  ++this._total;
717
- tasks.add(url);
718
729
  promise.finally(function() {
719
730
  ++_this._loaded;
720
731
  _this._setTaskCompleteProgress(_this._loaded, _this._total);
@@ -724,243 +735,446 @@ var ParserType = /*#__PURE__*/ function(ParserType) {
724
735
  }();
725
736
 
726
737
  var ReflectionParser = /*#__PURE__*/ function() {
727
- function ReflectionParser(_context) {
738
+ function ReflectionParser(_context, _refs) {
728
739
  this._context = _context;
740
+ this._refs = _refs;
729
741
  }
730
742
  var _proto = ReflectionParser.prototype;
731
- _proto.parseEntity = function parseEntity(entityConfig) {
732
- var _this = this;
733
- return this._getEntityByConfig(entityConfig).then(function(entity) {
734
- var _entityConfig_isActive;
735
- entity.isActive = (_entityConfig_isActive = entityConfig.isActive) != null ? _entityConfig_isActive : true;
736
- var transform = entity.transform;
737
- var transformConfig = entityConfig.transform;
738
- if (transformConfig) {
739
- _this.parsePropsAndMethods(transform, transformConfig);
740
- } else {
741
- var position = entityConfig.position, rotation = entityConfig.rotation, scale = entityConfig.scale;
742
- if (position) transform.position.copyFrom(position);
743
- if (rotation) transform.rotation.copyFrom(rotation);
744
- if (scale) transform.scale.copyFrom(scale);
745
- }
746
- var _entityConfig_layer;
747
- entity.layer = (_entityConfig_layer = entityConfig.layer) != null ? _entityConfig_layer : entity.layer;
748
- // @ts-ignore
749
- _this._context.type === ParserType.Prefab && entity._markAsTemplate(_this._context.resource);
750
- return entity;
751
- });
752
- };
753
- _proto.parseClassObject = function parseClassObject(item) {
754
- var _this = this;
755
- var Class = engineCore.Loader.getClass(item.class);
756
- var _item_constructParams;
757
- var params = (_item_constructParams = item.constructParams) != null ? _item_constructParams : [];
758
- return Promise.all(params.map(function(param) {
759
- return _this.parseBasicType(param);
760
- })).then(function(resultParams) {
761
- return _construct(Class, [].concat(resultParams));
762
- }).then(function(instance) {
763
- return _this.parsePropsAndMethods(instance, item);
764
- });
765
- };
766
- _proto.parsePropsAndMethods = function parsePropsAndMethods(instance, item) {
743
+ /**
744
+ * Apply v2 props to a component/object instance.
745
+ * Each prop value is resolved recursively (handling $ref, $type, $class, $entity, $component, $signal).
746
+ */ _proto.parseProps = function parseProps(instance, props) {
767
747
  var promises = [];
768
- if (item.methods) {
769
- for(var methodName in item.methods){
770
- var methodParams = item.methods[methodName];
771
- for(var i = 0, count = methodParams.length; i < count; i++){
772
- promises.push(this.parseMethod(instance, methodName, methodParams[i]));
773
- }
774
- }
775
- }
776
- if (item.props) {
748
+ if (props) {
777
749
  var _this, _loop = function(key) {
778
- var value = item.props[key];
779
- var promise = _this.parseBasicType(value, instance[key]).then(function(v) {
780
- return instance[key] = v;
750
+ var promise = _this._resolveValue(props[key], instance[key]).then(function(v) {
751
+ instance[key] = v;
781
752
  });
782
753
  promises.push(promise);
783
754
  };
784
- for(var key in item.props)_this = this, _loop(key);
755
+ for(var key in props)_this = this, _loop(key);
785
756
  }
786
757
  return Promise.all(promises).then(function() {
787
758
  return instance;
788
759
  });
789
760
  };
790
- _proto.parseMethod = function parseMethod(instance, methodName, methodParams) {
761
+ /**
762
+ * Execute calls sequentially on a target instance.
763
+ * Call args are resolved with the same v2 value rules as props.
764
+ */ _proto.parseCalls = function parseCalls(instance, calls) {
765
+ var _loop = function(i, n) {
766
+ var call = calls[i];
767
+ chain = chain.then(function() {
768
+ var method = instance == null ? void 0 : instance[call.method];
769
+ if (typeof method !== "function") {
770
+ return Promise.reject(new Error('Call target does not have method "' + call.method + '"'));
771
+ }
772
+ var _call_args;
773
+ return Promise.all(((_call_args = call.args) != null ? _call_args : []).map(function(arg) {
774
+ return _this._resolveValue(arg);
775
+ })).then(function(resolvedArgs) {
776
+ return Promise.resolve(method.apply(instance, resolvedArgs));
777
+ }).then(function(result) {
778
+ if (!call.result) return result;
779
+ if (result == null || (typeof result === "undefined" ? "undefined" : _type_of(result)) !== "object" && typeof result !== "function") {
780
+ return Promise.reject(new Error('Call "' + call.method + '" returned ' + result + " and cannot be mutated by result"));
781
+ }
782
+ return _this.parseMutationBlock(result, call.result);
783
+ });
784
+ });
785
+ };
791
786
  var _this = this;
792
- var isMethodObject = ReflectionParser._isMethodObject(methodParams);
793
- var params = isMethodObject ? methodParams.params : methodParams;
794
- return Promise.all(params.map(function(param) {
795
- return _this.parseBasicType(param);
796
- })).then(function(result) {
797
- var _instance;
798
- var methodResult = (_instance = instance)[methodName].apply(_instance, [].concat(result));
799
- if (isMethodObject && methodParams.result) {
800
- return _this.parsePropsAndMethods(methodResult, methodParams.result);
801
- } else {
802
- return methodResult;
803
- }
787
+ if (!(calls == null ? void 0 : calls.length)) return Promise.resolve(instance);
788
+ var chain = Promise.resolve();
789
+ for(var i = 0, n = calls.length; i < n; i++)_loop(i);
790
+ return chain.then(function() {
791
+ return instance;
804
792
  });
805
793
  };
806
- _proto.parseSignal = function parseSignal(signalRef) {
807
- var _this = this;
808
- var signal = new engineCore.Signal();
809
- return Promise.all(signalRef.listeners.map(function(listener) {
810
- return Promise.all([
811
- _this.parseBasicType(listener.target),
812
- listener.arguments ? Promise.all(listener.arguments.map(function(a) {
813
- return _this.parseBasicType(a);
814
- })) : Promise.resolve([])
815
- ]).then(function(param) {
816
- var target = param[0], resolvedArgs = param[1];
817
- if (target) {
818
- var _signal;
819
- (_signal = signal).on.apply(_signal, [].concat([
820
- target,
821
- listener.methodName
822
- ], resolvedArgs));
823
- }
824
- });
825
- })).then(function() {
826
- return signal;
794
+ /**
795
+ * Apply props and calls from the same mutation block without imposing ordering between them.
796
+ */ _proto.parseMutationBlock = function parseMutationBlock(target, block) {
797
+ if (!block) return Promise.resolve(target);
798
+ return Promise.all([
799
+ this.parseProps(target, block.props),
800
+ this.parseCalls(target, block.calls)
801
+ ]).then(function() {
802
+ return target;
827
803
  });
828
804
  };
829
- _proto.parseBasicType = function parseBasicType(value, originValue) {
830
- var _this = this;
831
- if (Array.isArray(value)) {
832
- return Promise.all(value.map(function(item) {
833
- return _this.parseBasicType(item);
805
+ /**
806
+ * Resolve a v2 value with $ prefix detection.
807
+ *
808
+ * Priority:
809
+ * 1. null/undefined/primitive → passthrough
810
+ * 2. Array → recurse each element
811
+ * 3. { $ref } → asset reference
812
+ * 4. { $type } → polymorphic type construct; optional $args are constructor args
813
+ * 5. { $class } → registered class constructor
814
+ * 6. { $entity } → entity reference by path (flat index + optional children descent)
815
+ * 7. { $component } → component reference
816
+ * 8. { $signal } → signal binding
817
+ * 9. { $props/$calls } → mutate the existing target object
818
+ * 10. plain object → recurse values (modify originValue in place if exists)
819
+ */ _proto._resolveValue = function _resolveValue(value, originValue) {
820
+ var _this, _loop = function(key) {
821
+ promises.push(_this._resolveValue(obj[key], target1[key]).then(function(v) {
822
+ return target1[key] = v;
834
823
  }));
835
- } else if ((typeof value === "undefined" ? "undefined" : _type_of(value)) === "object" && value != null) {
836
- if (ReflectionParser._isClassType(value)) {
837
- return Promise.resolve(engineCore.Loader.getClass(value["classType"]));
838
- } else if (ReflectionParser._isClass(value)) {
839
- // class object
840
- return this.parseClassObject(value);
841
- } else if (ReflectionParser._isAssetRef(value)) {
842
- var _this1 = this, context = _this1._context;
843
- // reference object
844
- // @ts-ignore
845
- return context.resourceManager.getResourceByRef(value).then(function(resource) {
846
- if (resource && context.type === ParserType.Prefab) {
847
- // @ts-ignore
848
- context.resource._addDependenceAsset(resource);
849
- }
850
- return resource;
851
- });
852
- } else if (ReflectionParser._isComponentRef(value)) {
853
- var entity = this._resolveEntityByPath(value.entityPath);
854
- if (!entity) return Promise.resolve(null);
855
- var type = engineCore.Loader.getClass(value.componentType);
856
- if (!type) return Promise.resolve(null);
857
- // Try direct components first, fallback to children search (for GLB clone entities
858
- // where the component lives on a child entity inside the clone)
859
- var direct = entity.getComponents(type, []);
860
- var result = direct[value.componentIndex];
861
- if (result) return Promise.resolve(result);
862
- var includeChildren = [];
863
- entity.getComponentsIncludeChildren(type, includeChildren);
864
- var _includeChildren_value_componentIndex;
865
- return Promise.resolve((_includeChildren_value_componentIndex = includeChildren[value.componentIndex]) != null ? _includeChildren_value_componentIndex : null);
866
- } else if (ReflectionParser._isEntityRef(value)) {
867
- return Promise.resolve(this._resolveEntityByPath(value.entityPath));
868
- } else if (ReflectionParser._isSignalRef(value)) {
869
- return this.parseSignal(value);
870
- } else if (originValue) {
871
- var _this2, _loop = function(key) {
872
- if (key === "methods") {
873
- var methods = value[key];
874
- for(var methodName in methods){
875
- var methodParams = methods[methodName];
876
- for(var i = 0, count = methodParams.length; i < count; i++){
877
- var params = methodParams[i];
878
- var promise = _this2.parseMethod(originValue, methodName, params);
879
- promises.push(promise);
880
- }
881
- }
882
- } else {
883
- promises.push(_this2.parseBasicType(value[key], originValue[key]).then(function(v) {
884
- return originValue[key] = v;
885
- }));
886
- }
887
- };
888
- var promises = [];
889
- for(var key in value)_this2 = this, _loop(key);
890
- return Promise.all(promises).then(function() {
891
- return originValue;
892
- });
824
+ };
825
+ var _this1 = this;
826
+ if (value == null || (typeof value === "undefined" ? "undefined" : _type_of(value)) !== "object") return Promise.resolve(value);
827
+ if (Array.isArray(value)) return Promise.all(value.map(function(v) {
828
+ return _this1._resolveValue(v);
829
+ }));
830
+ var obj = value;
831
+ // $ref asset reference (index into refs array)
832
+ if ("$ref" in obj) {
833
+ var _this2 = this, context = _this2._context;
834
+ var refItem;
835
+ try {
836
+ refItem = resolveRefItem(this._refs, obj.$ref, "ReflectionParser", "$ref");
837
+ } catch (error) {
838
+ return Promise.reject(error);
893
839
  }
894
- }
895
- // primitive type
896
- return Promise.resolve(value);
897
- };
898
- _proto._getEntityByConfig = function _getEntityByConfig(entityConfig) {
899
- var _this = this;
900
- // @ts-ignore
901
- var assetUrl = entityConfig.assetUrl;
902
- var engine = this._context.engine;
903
- if (assetUrl) {
904
- return engine.resourceManager// @ts-ignore
905
- .getResourceByRef({
906
- url: assetUrl,
907
- key: entityConfig.key,
908
- isClone: entityConfig.isClone
909
- }).then(function(entity) {
910
- // @ts-ignore
911
- var resource = engine.resourceManager._objectPool[assetUrl];
912
- if (resource && _this._context.type === ParserType.Prefab) {
840
+ // @ts-ignore
841
+ return context.resourceManager.getResourceByRef(refItem).then(function(resource) {
842
+ if (resource && context.type === ParserType.Prefab) {
913
843
  // @ts-ignore
914
- _this._context.resource._addDependenceAsset(resource);
844
+ context.resource._addDependenceAsset(resource);
915
845
  }
916
- entity.name = entityConfig.name;
917
- return entity;
846
+ return resource;
918
847
  });
919
- } else {
920
- var transform = entityConfig.transform;
921
- var entity = new engineCore.Entity(engine, entityConfig.name, transform ? engineCore.Loader.getClass(transform.class) : engineCore.Transform);
922
- return Promise.resolve(entity);
923
848
  }
849
+ // $type — polymorphic type: construct instance and apply remaining props
850
+ if ("$type" in obj) {
851
+ var $type = obj.$type, $args = obj.$args, $props = obj.$props, $calls = obj.$calls, rest = _object_without_properties_loose(obj, [
852
+ "$type",
853
+ "$args",
854
+ "$props",
855
+ "$calls"
856
+ ]);
857
+ return this._resolveRegisteredClass($type, "$type").then(function(Class) {
858
+ if ($args !== undefined && !Array.isArray($args)) {
859
+ return Promise.reject(new Error("$type.$args must be an array"));
860
+ }
861
+ return Promise.all(($args != null ? $args : []).map(function(arg) {
862
+ return _this1._resolveValue(arg);
863
+ })).then(function(resolvedArgs) {
864
+ var instance = _construct(Class, [].concat(resolvedArgs));
865
+ return _this1._applyRuntimeMutation(instance, Object.keys(rest).length > 0 ? rest : undefined, $props, $calls);
866
+ });
867
+ });
868
+ }
869
+ // $class — registered class constructor for factory-style methods.
870
+ if ("$class" in obj) {
871
+ return this._resolveRegisteredClass(obj.$class, "$class");
872
+ }
873
+ // $entity — entity reference by path (first element = flat index, subsequent = children indices)
874
+ if ("$entity" in obj) {
875
+ return Promise.resolve(this._resolveEntityRef(obj.$entity));
876
+ }
877
+ // $component — component reference: { entity, type, index }
878
+ if ("$component" in obj) {
879
+ return Promise.resolve(this._resolveComponent(obj.$component));
880
+ }
881
+ // $signal — signal binding: register listeners on the existing Signal instance
882
+ if ("$signal" in obj) {
883
+ return this._resolveSignal(originValue, obj.$signal);
884
+ }
885
+ // Runtime mutation block for existing nested objects.
886
+ if ("$props" in obj || "$calls" in obj) {
887
+ var target = originValue && (typeof originValue === "undefined" ? "undefined" : _type_of(originValue)) === "object" && !Array.isArray(originValue) ? originValue : {};
888
+ return this._applyRuntimeMutation(target, undefined, obj.$props, obj.$calls);
889
+ }
890
+ // Plain object — recurse each value, modifying originValue in place or building a new object
891
+ var target1 = originValue && (typeof originValue === "undefined" ? "undefined" : _type_of(originValue)) === "object" && !Array.isArray(originValue) ? originValue : {};
892
+ var promises = [];
893
+ for(var key in obj)_this = this, _loop(key);
894
+ return Promise.all(promises).then(function() {
895
+ return target1;
896
+ });
924
897
  };
925
- _proto._resolveEntityByPath = function _resolveEntityByPath(entityPath) {
926
- var _this__context = this._context, rootIds = _this__context.rootIds, entityMap = _this__context.entityMap;
927
- if (!entityPath.length || entityPath[0] >= rootIds.length) return null;
928
- var entity = entityMap.get(rootIds[entityPath[0]]);
929
- for(var i = 1; i < entityPath.length; i++){
930
- if (!entity || entityPath[i] >= entity.children.length) return null;
931
- entity = entity.children[entityPath[i]];
898
+ _proto._applyRuntimeMutation = function _applyRuntimeMutation(target, directProps, runtimeProps, runtimeCalls) {
899
+ var props = directProps ? _extends({}, directProps) : undefined;
900
+ var calls;
901
+ try {
902
+ var normalizedProps = this._normalizeRuntimeProps(runtimeProps);
903
+ if (normalizedProps) {
904
+ props = Object.assign(props != null ? props : {}, normalizedProps);
905
+ }
906
+ calls = this._normalizeRuntimeCalls(runtimeCalls);
907
+ } catch (error) {
908
+ return Promise.reject(error);
932
909
  }
933
- return entity;
910
+ return this.parseMutationBlock(target, {
911
+ props: props,
912
+ calls: calls
913
+ });
934
914
  };
935
- ReflectionParser._isClass = function _isClass(value) {
936
- return value["class"] !== undefined;
915
+ _proto._normalizeRuntimeProps = function _normalizeRuntimeProps(props) {
916
+ if (props === undefined) return undefined;
917
+ if (props == null || (typeof props === "undefined" ? "undefined" : _type_of(props)) !== "object" || Array.isArray(props)) {
918
+ throw new Error("$props must be an object");
919
+ }
920
+ return props;
937
921
  };
938
- ReflectionParser._isClassType = function _isClassType(value) {
939
- return value["classType"] !== undefined;
922
+ _proto._normalizeRuntimeCalls = function _normalizeRuntimeCalls(calls) {
923
+ if (calls === undefined) return undefined;
924
+ if (!Array.isArray(calls)) {
925
+ throw new Error("$calls must be an array");
926
+ }
927
+ return calls;
940
928
  };
941
- ReflectionParser._isAssetRef = function _isAssetRef(value) {
942
- return value["url"] !== undefined;
929
+ _proto._getRegisteredClass = function _getRegisteredClass(value, sentinel) {
930
+ if (typeof value !== "string" || value.length === 0) {
931
+ throw new Error("" + sentinel + " must be a non-empty registered class name string");
932
+ }
933
+ var Class = engineCore.Loader.getClass(value);
934
+ if (!Class) throw new Error('Loader.getClass: class "' + value + '" is not registered');
935
+ return Class;
943
936
  };
944
- ReflectionParser._isEntityRef = function _isEntityRef(value) {
945
- return Array.isArray(value["entityPath"]) && value["componentType"] === undefined;
937
+ /** Promise-adapt {@link _getRegisteredClass} so $type/$class branches can fold into the resolver chain. */ _proto._resolveRegisteredClass = function _resolveRegisteredClass(value, sentinel) {
938
+ try {
939
+ return Promise.resolve(this._getRegisteredClass(value, sentinel));
940
+ } catch (error) {
941
+ return Promise.reject(error);
942
+ }
946
943
  };
947
- ReflectionParser._isComponentRef = function _isComponentRef(value) {
948
- return Array.isArray(value["entityPath"]) && value["componentType"] !== undefined;
944
+ _proto._resolveSignal = function _resolveSignal(signal, listeners) {
945
+ var _this = this;
946
+ if (!signal || typeof signal.on !== "function") {
947
+ return Promise.reject(new Error("$signal requires a pre-initialized Signal instance on the target property"));
948
+ }
949
+ var promises = listeners.map(function(listener) {
950
+ var targetComponent = _this._resolveComponent(listener.target.$component);
951
+ if (!targetComponent) return Promise.resolve();
952
+ var _listener_args;
953
+ return Promise.all(((_listener_args = listener.args) != null ? _listener_args : []).map(function(a) {
954
+ return _this._resolveValue(a);
955
+ })).then(function(resolvedArgs) {
956
+ var _signal;
957
+ (_signal = signal).on.apply(_signal, [].concat([
958
+ targetComponent,
959
+ listener.methodName
960
+ ], resolvedArgs));
961
+ });
962
+ });
963
+ return Promise.all(promises).then(function() {
964
+ return signal;
965
+ });
949
966
  };
950
- ReflectionParser._isSignalRef = function _isSignalRef(value) {
951
- return value["listeners"] !== undefined;
967
+ _proto._resolveComponent = function _resolveComponent(comp) {
968
+ var entity = this._resolveEntityRef(comp.entity);
969
+ if (!entity) return null;
970
+ var type = engineCore.Loader.getClass(comp.type);
971
+ if (!type) return null;
972
+ var buffer = ReflectionParser._componentBuffer;
973
+ buffer.length = 0;
974
+ entity.getComponents(type, buffer);
975
+ var _buffer_comp_index;
976
+ var result = (_buffer_comp_index = buffer[comp.index]) != null ? _buffer_comp_index : null;
977
+ buffer.length = 0;
978
+ return result;
952
979
  };
953
- ReflectionParser._isMethodObject = function _isMethodObject(value) {
954
- return Array.isArray(value == null ? void 0 : value.params);
980
+ _proto._resolveEntityRef = function _resolveEntityRef(path) {
981
+ if (!path || path.length === 0) return null;
982
+ var _this__context_entityInstances_path_;
983
+ var entity = (_this__context_entityInstances_path_ = this._context.entityInstances[path[0]]) != null ? _this__context_entityInstances_path_ : null;
984
+ for(var i = 1, n = path.length; entity && i < n; i++){
985
+ var _entity_children_path_i;
986
+ entity = (_entity_children_path_i = entity.children[path[i]]) != null ? _entity_children_path_i : null;
987
+ }
988
+ return entity;
955
989
  };
956
990
  return ReflectionParser;
957
991
  }();
992
+ /** @internal shared with HierarchyParser; each use must length=0 -> getComponents -> read -> length=0 synchronously. */ ReflectionParser._componentBuffer = [];
993
+
994
+ /**
995
+ * HDR (Radiance RGBE) image decoder.
996
+ *
997
+ * Decodes .hdr files into pixel data. Supports parsing the header
998
+ * and decoding RLE-compressed RGBE scanlines into R16G16B16A16 half-float pixels.
999
+ */ var HDRDecoder = /*#__PURE__*/ function() {
1000
+ function HDRDecoder() {}
1001
+ /**
1002
+ * Parse the header of an HDR file.
1003
+ * @returns Header info including width, height, and data start position.
1004
+ */ HDRDecoder.parseHeader = function parseHeader(uint8array) {
1005
+ var line = this._readStringLine(uint8array, 0);
1006
+ if (line[0] !== "#" || line[1] !== "?") {
1007
+ throw "HDRDecoder: invalid file header";
1008
+ }
1009
+ var endOfHeader = false;
1010
+ var findFormat = false;
1011
+ var lineIndex = 0;
1012
+ do {
1013
+ lineIndex += line.length + 1;
1014
+ line = this._readStringLine(uint8array, lineIndex);
1015
+ if (line === "FORMAT=32-bit_rle_rgbe") findFormat = true;
1016
+ else if (line.length === 0) endOfHeader = true;
1017
+ }while (!endOfHeader);
1018
+ if (!findFormat) {
1019
+ throw "HDRDecoder: unsupported format, expected 32-bit_rle_rgbe";
1020
+ }
1021
+ lineIndex += line.length + 1;
1022
+ line = this._readStringLine(uint8array, lineIndex);
1023
+ var match = /^\-Y (.*) \+X (.*)$/g.exec(line);
1024
+ if (!match || match.length < 3) {
1025
+ throw "HDRDecoder: missing image size, only -Y +X layout is supported";
1026
+ }
1027
+ var width = parseInt(match[2]);
1028
+ var height = parseInt(match[1]);
1029
+ if (width < 8 || width > 0x7fff) {
1030
+ throw "HDRDecoder: unsupported image width, must be between 8 and 32767";
1031
+ }
1032
+ return {
1033
+ height: height,
1034
+ width: width,
1035
+ dataPosition: lineIndex + line.length + 1
1036
+ };
1037
+ };
1038
+ /**
1039
+ * Decode an HDR file buffer into R16G16B16A16 half-float pixel data.
1040
+ * @param buffer - The full HDR file as Uint8Array.
1041
+ * @returns Object with width, height, and half-float pixel data.
1042
+ */ HDRDecoder.decode = function decode(buffer) {
1043
+ var header = this.parseHeader(buffer);
1044
+ var width = header.width, height = header.height, dataPosition = header.dataPosition;
1045
+ var rgbe = this._readPixels(buffer.subarray(dataPosition), width, height);
1046
+ var pixels = this._rgbeToHalfFloat(rgbe, width, height);
1047
+ return {
1048
+ width: width,
1049
+ height: height,
1050
+ pixels: pixels
1051
+ };
1052
+ };
1053
+ /**
1054
+ * Convert RGBE pixel data to R16G16B16A16 half-float.
1055
+ */ HDRDecoder._rgbeToHalfFloat = function _rgbeToHalfFloat(rgbe, width, height) {
1056
+ var floatView = this._floatView;
1057
+ var uint32View = this._uint32View;
1058
+ var _this__float2HalfTables = this._float2HalfTables, baseTable = _this__float2HalfTables.baseTable, shiftTable = _this__float2HalfTables.shiftTable;
1059
+ var one = 0x3c00; // Half float 1.0
1060
+ var pixelCount = width * height;
1061
+ var result = new Uint16Array(pixelCount * 4);
1062
+ for(var i = 0; i < pixelCount; i++){
1063
+ var srcIdx = i * 4;
1064
+ var dstIdx = i * 4;
1065
+ var scaleFactor = Math.pow(2, rgbe[srcIdx + 3] - 128 - 8);
1066
+ for(var c = 0; c < 3; c++){
1067
+ floatView[0] = Math.min(rgbe[srcIdx + c] * scaleFactor, 65504);
1068
+ var f = uint32View[0];
1069
+ var e = f >> 23 & 0x1ff;
1070
+ result[dstIdx + c] = baseTable[e] + ((f & 0x007fffff) >> shiftTable[e]);
1071
+ }
1072
+ result[dstIdx + 3] = one;
1073
+ }
1074
+ return result;
1075
+ };
1076
+ /**
1077
+ * Decode RLE-compressed RGBE scanlines into raw RGBE pixel data.
1078
+ */ HDRDecoder._readPixels = function _readPixels(buffer, width, height) {
1079
+ var byteLength = buffer.byteLength;
1080
+ var dataRGBA = new Uint8Array(4 * width * height);
1081
+ var offset = 0;
1082
+ var pos = 0;
1083
+ var ptrEnd = 4 * width;
1084
+ var scanLineBuffer = new Uint8Array(ptrEnd);
1085
+ var numScanLines = height;
1086
+ while(numScanLines > 0 && pos < byteLength){
1087
+ var a = buffer[pos++];
1088
+ var b = buffer[pos++];
1089
+ var c = buffer[pos++];
1090
+ var d = buffer[pos++];
1091
+ if (a !== 2 || b !== 2 || c & 0x80 || width < 8 || width > 32767) return buffer;
1092
+ if ((c << 8 | d) !== width) throw "HDRDecoder: wrong scanline width";
1093
+ var ptr = 0;
1094
+ while(ptr < ptrEnd && pos < byteLength){
1095
+ var count = buffer[pos++];
1096
+ var isEncodedRun = count > 128;
1097
+ if (isEncodedRun) count -= 128;
1098
+ if (count === 0 || ptr + count > ptrEnd) throw "HDRDecoder: bad scanline data";
1099
+ if (isEncodedRun) {
1100
+ var byteValue = buffer[pos++];
1101
+ for(var i = 0; i < count; i++)scanLineBuffer[ptr++] = byteValue;
1102
+ } else {
1103
+ scanLineBuffer.set(buffer.subarray(pos, pos + count), ptr);
1104
+ ptr += count;
1105
+ pos += count;
1106
+ }
1107
+ }
1108
+ for(var i1 = 0; i1 < width; i1++, offset += 4){
1109
+ dataRGBA[offset] = scanLineBuffer[i1];
1110
+ dataRGBA[offset + 1] = scanLineBuffer[i1 + width];
1111
+ dataRGBA[offset + 2] = scanLineBuffer[i1 + width * 2];
1112
+ dataRGBA[offset + 3] = scanLineBuffer[i1 + width * 3];
1113
+ }
1114
+ numScanLines--;
1115
+ }
1116
+ return dataRGBA;
1117
+ };
1118
+ HDRDecoder._generateFloat2HalfTables = function _generateFloat2HalfTables() {
1119
+ var baseTable = new Uint32Array(512);
1120
+ var shiftTable = new Uint32Array(512);
1121
+ for(var i = 0; i < 256; ++i){
1122
+ var e = i - 127;
1123
+ if (e < -27) {
1124
+ baseTable[i] = 0x0000;
1125
+ baseTable[i | 0x100] = 0x8000;
1126
+ shiftTable[i] = 24;
1127
+ shiftTable[i | 0x100] = 24;
1128
+ } else if (e < -14) {
1129
+ baseTable[i] = 0x0400 >> -e - 14;
1130
+ baseTable[i | 0x100] = 0x0400 >> -e - 14 | 0x8000;
1131
+ shiftTable[i] = -e - 1;
1132
+ shiftTable[i | 0x100] = -e - 1;
1133
+ } else if (e <= 15) {
1134
+ baseTable[i] = e + 15 << 10;
1135
+ baseTable[i | 0x100] = e + 15 << 10 | 0x8000;
1136
+ shiftTable[i] = 13;
1137
+ shiftTable[i | 0x100] = 13;
1138
+ } else if (e < 128) {
1139
+ baseTable[i] = 0x7c00;
1140
+ baseTable[i | 0x100] = 0xfc00;
1141
+ shiftTable[i] = 24;
1142
+ shiftTable[i | 0x100] = 24;
1143
+ } else {
1144
+ baseTable[i] = 0x7c00;
1145
+ baseTable[i | 0x100] = 0xfc00;
1146
+ shiftTable[i] = 13;
1147
+ shiftTable[i | 0x100] = 13;
1148
+ }
1149
+ }
1150
+ return {
1151
+ baseTable: baseTable,
1152
+ shiftTable: shiftTable
1153
+ };
1154
+ };
1155
+ HDRDecoder._readStringLine = function _readStringLine(uint8array, startIndex) {
1156
+ var line = "";
1157
+ for(var i = startIndex, n = uint8array.length; i < n; i++){
1158
+ var character = String.fromCharCode(uint8array[i]);
1159
+ if (character === "\n") break;
1160
+ line += character;
1161
+ }
1162
+ return line;
1163
+ };
1164
+ return HDRDecoder;
1165
+ }();
1166
+ HDRDecoder._float2HalfTables = HDRDecoder._generateFloat2HalfTables();
1167
+ HDRDecoder._floatView = new Float32Array(1);
1168
+ HDRDecoder._uint32View = new Uint32Array(HDRDecoder._floatView.buffer);
958
1169
 
959
- exports.Texture2DDecoder = /*#__PURE__*/ function() {
1170
+ /**
1171
+ * Data format: [url] [mipmap(1B)] [filterMode(1B)] [anisoLevel(1B)] [wrapModeU(1B)] [wrapModeV(1B)]
1172
+ * [format(1B)] [width(2B)] [height(2B)] [isSRGBColorSpace(1B)] [Uint32(imageSize) + imageBytes]
1173
+ */ var Texture2DDecoder = /*#__PURE__*/ function() {
960
1174
  function Texture2DDecoder() {}
961
1175
  Texture2DDecoder.decode = function decode(engine, bufferReader, restoredTexture) {
962
1176
  return new engineCore.AssetPromise(function(resolve, reject) {
963
- var url = bufferReader.nextStr();
1177
+ bufferReader.nextStr();
964
1178
  var mipmap = !!bufferReader.nextUint8();
965
1179
  var filterMode = bufferReader.nextUint8();
966
1180
  var anisoLevel = bufferReader.nextUint8();
@@ -969,58 +1183,34 @@ exports.Texture2DDecoder = /*#__PURE__*/ function() {
969
1183
  var format = bufferReader.nextUint8();
970
1184
  var width = bufferReader.nextUint16();
971
1185
  var height = bufferReader.nextUint16();
972
- var isPixelBuffer = bufferReader.nextUint8();
973
1186
  var isSRGBColorSpace = !!bufferReader.nextUint8();
974
- var mipCount = bufferReader.nextUint8();
975
- var imagesData = bufferReader.nextImagesData(mipCount);
976
- var texture2D = restoredTexture || new engineCore.Texture2D(engine, width, height, format, mipmap, isSRGBColorSpace);
977
- texture2D.filterMode = filterMode;
978
- texture2D.anisoLevel = anisoLevel;
979
- texture2D.wrapModeU = wrapModeU;
980
- texture2D.wrapModeV = wrapModeV;
981
- if (isPixelBuffer) {
982
- var pixelBuffer = imagesData[0];
983
- texture2D.setPixelBuffer(pixelBuffer);
984
- if (mipmap) {
985
- texture2D.generateMipmaps();
986
- for(var i = 1; i < mipCount; i++){
987
- var pixelBuffer1 = imagesData[i];
988
- texture2D.setPixelBuffer(pixelBuffer1, i);
989
- }
990
- }
991
- // @ts-ignore
992
- engine.resourceManager._objectPool[url] = texture2D;
993
- resolve(texture2D);
1187
+ var imageData = bufferReader.nextImagesData(1)[0];
1188
+ var isHDR = imageData[0] === 0x23 && imageData[1] === 0x3f;
1189
+ var textureFormat = isHDR ? engineCore.TextureFormat.R16G16B16A16 : format;
1190
+ var texture = restoredTexture || new engineCore.Texture2D(engine, width, height, textureFormat, mipmap, isHDR ? false : isSRGBColorSpace);
1191
+ texture.filterMode = filterMode;
1192
+ texture.anisoLevel = anisoLevel;
1193
+ texture.wrapModeU = wrapModeU;
1194
+ texture.wrapModeV = wrapModeV;
1195
+ if (isHDR) {
1196
+ var pixels = HDRDecoder.decode(imageData).pixels;
1197
+ texture.setPixelBuffer(pixels);
1198
+ mipmap && texture.generateMipmaps();
1199
+ resolve(texture);
994
1200
  } else {
995
- var blob = new window.Blob([
996
- imagesData[0]
1201
+ var blob = new Blob([
1202
+ imageData
997
1203
  ]);
998
1204
  var img = new Image();
999
1205
  img.onload = function() {
1000
- texture2D.setImageSource(img);
1001
- var completedCount = 0;
1002
- var onComplete = function() {
1003
- completedCount++;
1004
- if (completedCount >= mipCount) {
1005
- resolve(texture2D);
1006
- }
1007
- };
1008
- onComplete();
1009
- if (mipmap) {
1010
- var _loop = function(i) {
1011
- var blob = new window.Blob([
1012
- imagesData[i]
1013
- ]);
1014
- var img = new Image();
1015
- img.onload = function() {
1016
- texture2D.setImageSource(img, i);
1017
- onComplete();
1018
- };
1019
- img.src = URL.createObjectURL(blob);
1020
- };
1021
- texture2D.generateMipmaps();
1022
- for(var i = 1; i < mipCount; i++)_loop(i);
1023
- }
1206
+ URL.revokeObjectURL(img.src);
1207
+ texture.setImageSource(img);
1208
+ mipmap && texture.generateMipmaps();
1209
+ resolve(texture);
1210
+ };
1211
+ img.onerror = function(e) {
1212
+ URL.revokeObjectURL(img.src);
1213
+ reject(e);
1024
1214
  };
1025
1215
  img.src = URL.createObjectURL(blob);
1026
1216
  }
@@ -1028,9 +1218,72 @@ exports.Texture2DDecoder = /*#__PURE__*/ function() {
1028
1218
  };
1029
1219
  return Texture2DDecoder;
1030
1220
  }();
1031
- exports.Texture2DDecoder = __decorate([
1221
+ Texture2DDecoder = __decorate([
1032
1222
  decoder("Texture2D")
1033
- ], exports.Texture2DDecoder);
1223
+ ], Texture2DDecoder);
1224
+
1225
+ /**
1226
+ * Data format: [url] [mipmap(1B)] [filterMode(1B)] [anisoLevel(1B)] [wrapModeU(1B)] [wrapModeV(1B)]
1227
+ * [format(1B)] [faceSize(2B)] [isSRGBColorSpace(1B)] [Uint32(size) + faceBytes] × 6
1228
+ */ var TextureCubeDecoder = /*#__PURE__*/ function() {
1229
+ function TextureCubeDecoder() {}
1230
+ TextureCubeDecoder.decode = function decode(engine, bufferReader, restoredTexture) {
1231
+ return new engineCore.AssetPromise(function(resolve, reject) {
1232
+ bufferReader.nextStr();
1233
+ var mipmap = !!bufferReader.nextUint8();
1234
+ var filterMode = bufferReader.nextUint8();
1235
+ var anisoLevel = bufferReader.nextUint8();
1236
+ var wrapModeU = bufferReader.nextUint8();
1237
+ var wrapModeV = bufferReader.nextUint8();
1238
+ var format = bufferReader.nextUint8();
1239
+ var faceSize = bufferReader.nextUint16();
1240
+ var isSRGBColorSpace = !!bufferReader.nextUint8();
1241
+ var facesData = bufferReader.nextImagesData(6);
1242
+ // Detect format by first face's magic bytes
1243
+ var isHDR = facesData[0][0] === 0x23 && facesData[0][1] === 0x3f;
1244
+ var textureFormat = isHDR ? engineCore.TextureFormat.R16G16B16A16 : format;
1245
+ var texture = restoredTexture || new engineCore.TextureCube(engine, faceSize, textureFormat, mipmap, isSRGBColorSpace);
1246
+ texture.filterMode = filterMode;
1247
+ texture.anisoLevel = anisoLevel;
1248
+ texture.wrapModeU = wrapModeU;
1249
+ texture.wrapModeV = wrapModeV;
1250
+ if (isHDR) {
1251
+ for(var i = 0; i < 6; i++){
1252
+ var pixels = HDRDecoder.decode(facesData[i]).pixels;
1253
+ texture.setPixelBuffer(engineCore.TextureCubeFace.PositiveX + i, pixels, 0);
1254
+ }
1255
+ mipmap && texture.generateMipmaps();
1256
+ resolve(texture);
1257
+ } else {
1258
+ var _loop = function(i1) {
1259
+ var blob = new Blob([
1260
+ facesData[i1]
1261
+ ]);
1262
+ var img = new Image();
1263
+ img.onload = function() {
1264
+ URL.revokeObjectURL(img.src);
1265
+ texture.setImageSource(engineCore.TextureCubeFace.PositiveX + i1, img);
1266
+ if (++loadedCount === 6) {
1267
+ mipmap && texture.generateMipmaps();
1268
+ resolve(texture);
1269
+ }
1270
+ };
1271
+ img.onerror = function(e) {
1272
+ URL.revokeObjectURL(img.src);
1273
+ reject(e);
1274
+ };
1275
+ img.src = URL.createObjectURL(blob);
1276
+ };
1277
+ var loadedCount = 0;
1278
+ for(var i1 = 0; i1 < 6; i1++)_loop(i1);
1279
+ }
1280
+ });
1281
+ };
1282
+ return TextureCubeDecoder;
1283
+ }();
1284
+ TextureCubeDecoder = __decorate([
1285
+ decoder("TextureCube")
1286
+ ], TextureCubeDecoder);
1034
1287
 
1035
1288
  function _instanceof(left, right) {
1036
1289
  if (right != null && typeof Symbol !== "undefined" && right[Symbol.hasInstance]) {
@@ -1038,45 +1291,6 @@ function _instanceof(left, right) {
1038
1291
  } else return left instanceof right;
1039
1292
  }
1040
1293
 
1041
- function _array_like_to_array(arr, len) {
1042
- if (len == null || len > arr.length) len = arr.length;
1043
-
1044
- for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
1045
-
1046
- return arr2;
1047
- }
1048
-
1049
- function _unsupported_iterable_to_array(o, minLen) {
1050
- if (!o) return;
1051
- if (typeof o === "string") return _array_like_to_array(o, minLen);
1052
-
1053
- var n = Object.prototype.toString.call(o).slice(8, -1);
1054
-
1055
- if (n === "Object" && o.constructor) n = o.constructor.name;
1056
- if (n === "Map" || n === "Set") return Array.from(n);
1057
- if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
1058
- }
1059
-
1060
- function _create_for_of_iterator_helper_loose(o, allowArrayLike) {
1061
- var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
1062
-
1063
- if (it) return (it = it.call(o)).next.bind(it);
1064
- // Fallback for engines without symbol support
1065
- if (Array.isArray(o) || (it = _unsupported_iterable_to_array(o)) || allowArrayLike && o && typeof o.length === "number") {
1066
- if (it) o = it;
1067
-
1068
- var i = 0;
1069
-
1070
- return function() {
1071
- if (i >= o.length) return { done: true };
1072
-
1073
- return { done: false, value: o[i++] };
1074
- };
1075
- }
1076
-
1077
- throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
1078
- }
1079
-
1080
1294
  /**
1081
1295
  * The Prefab resource.
1082
1296
  */ var PrefabResource = /*#__PURE__*/ function(ReferResource1) {
@@ -1108,8 +1322,9 @@ function _create_for_of_iterator_helper_loose(o, allowArrayLike) {
1108
1322
  };
1109
1323
  _proto._onDestroy = function _onDestroy() {
1110
1324
  var _this = this;
1325
+ var _this__root;
1111
1326
  ReferResource1.prototype._onDestroy.call(this);
1112
- this._root.destroy();
1327
+ (_this__root = this._root) == null ? void 0 : _this__root.destroy();
1113
1328
  this._dependenceAssets.forEach(function(asset) {
1114
1329
  if (_instanceof(asset, engineCore.ReferResource)) {
1115
1330
  // @ts-ignore
@@ -1125,319 +1340,260 @@ function _create_for_of_iterator_helper_loose(o, allowArrayLike) {
1125
1340
  var _this = this;
1126
1341
  this.data = data;
1127
1342
  this.context = context;
1128
- this._prefabContextMap = new WeakMap();
1129
- this._prefabPromiseMap = new Map();
1343
+ if (data.version !== "2.0") {
1344
+ var resourceType = context.type === ParserType.Scene ? "scene" : "prefab";
1345
+ throw new Error("Unsupported " + resourceType + ' format version "' + data.version + '". Expected "2.0".');
1346
+ }
1130
1347
  this._engine = this.context.engine;
1131
- this._organizeEntities = this._organizeEntities.bind(this);
1132
- this._parseComponents = this._parseComponents.bind(this);
1133
- this._parsePrefabModification = this._parsePrefabModification.bind(this);
1134
- this._parseAddedComponents = this._parseAddedComponents.bind(this);
1135
- this._parseComponentsPropsAndMethods = this._parseComponentsPropsAndMethods.bind(this);
1136
- this._parsePrefabRemovedEntities = this._parsePrefabRemovedEntities.bind(this);
1137
- this._parsePrefabRemovedComponents = this._parsePrefabRemovedComponents.bind(this);
1138
- this._clearAndResolve = this._clearAndResolve.bind(this);
1139
1348
  this.promise = new Promise(function(resolve, reject) {
1140
1349
  _this._reject = reject;
1141
1350
  _this._resolve = resolve;
1142
1351
  });
1143
- this._reflectionParser = new ReflectionParser(context);
1352
+ this._reflectionParser = new ReflectionParser(context, data.refs);
1144
1353
  }
1145
1354
  var _proto = HierarchyParser.prototype;
1146
- /** start parse the scene or prefab or others */ _proto.start = function start() {
1147
- this._parseEntities().then(this._organizeEntities).then(this._parseComponents).then(this._parseAddedComponents).then(this._parseComponentsPropsAndMethods).then(this._parsePrefabModification).then(this._parsePrefabRemovedEntities).then(this._parsePrefabRemovedComponents).then(this._clearAndResolve).then(this._resolve).catch(this._reject);
1148
- };
1149
- _proto._applyEntityData = function _applyEntityData(entity, entityConfig) {
1150
- if (entityConfig === void 0) entityConfig = {};
1151
- var _entityConfig_isActive;
1152
- entity.isActive = (_entityConfig_isActive = entityConfig.isActive) != null ? _entityConfig_isActive : entity.isActive;
1153
- var _entityConfig_name;
1154
- entity.name = (_entityConfig_name = entityConfig.name) != null ? _entityConfig_name : entity.name;
1155
- var transform = entity.transform;
1156
- var transformConfig = entityConfig.transform;
1157
- if (transformConfig) {
1158
- this._reflectionParser.parsePropsAndMethods(transform, transformConfig);
1159
- } else {
1160
- var position = entityConfig.position, rotation = entityConfig.rotation, scale = entityConfig.scale;
1161
- if (position) transform.position.copyFrom(position);
1162
- if (rotation) transform.rotation.copyFrom(rotation);
1163
- if (scale) transform.scale.copyFrom(scale);
1164
- }
1165
- if (entityConfig.layer) entity.layer = entityConfig.layer;
1166
- return entity;
1167
- };
1168
- _proto._parseEntities = function _parseEntities() {
1355
+ _proto.start = function start() {
1169
1356
  var _this = this;
1170
- var entitiesConfig = this.data.entities;
1171
- var entityConfigMap = this.context.entityConfigMap;
1172
- var entityMap = this.context.entityMap;
1173
- var engine = this._engine;
1174
- var promises = entitiesConfig.map(function(entityConfig) {
1175
- var _entityConfig_strippedId;
1176
- var id = (_entityConfig_strippedId = entityConfig.strippedId) != null ? _entityConfig_strippedId : entityConfig.id;
1177
- entityConfig.id = id;
1178
- entityConfigMap.set(id, entityConfig);
1179
- return _this._getEntityByConfig(entityConfig, engine);
1180
- });
1181
- return Promise.all(promises).then(function(entities) {
1182
- for(var i = 0, l = entities.length; i < l; i++){
1183
- entityMap.set(entitiesConfig[i].id, entities[i]);
1184
- }
1185
- // Build rootIds in serialization order (not async completion order)
1186
- var rootIds = _this.context.rootIds;
1187
- for(var i1 = 0, l1 = entitiesConfig.length; i1 < l1; i1++){
1188
- if (!entitiesConfig[i1].parent && !entitiesConfig[i1].strippedId) {
1189
- rootIds.push(entitiesConfig[i1].id);
1190
- }
1191
- }
1192
- return entities;
1193
- });
1194
- };
1195
- _proto._parseComponents = function _parseComponents() {
1196
- var entitiesConfig = this.data.entities;
1197
- var entityMap = this.context.entityMap;
1198
- for(var i = 0, l = entitiesConfig.length; i < l; i++){
1199
- var entityConfig = entitiesConfig[i];
1200
- if (entityConfig.strippedId) {
1201
- continue;
1202
- }
1203
- var entity = entityMap.get(entityConfig.id);
1204
- this._addComponents(entity, entityConfig.components);
1205
- }
1206
- };
1207
- _proto._parsePrefabModification = function _parsePrefabModification() {
1208
- var _loop = function(i, l) {
1209
- var entityConfig = entitiesConfig[i];
1210
- var id = entityConfig.id, modifications = entityConfig.modifications;
1211
- if (modifications == null ? void 0 : modifications.length) {
1212
- var _promises;
1213
- var rootEntity = entityMap.get(id);
1214
- (_promises = promises).push.apply(_promises, [].concat(modifications.map(function(modification) {
1215
- var target = modification.target, props = modification.props, methods = modification.methods;
1216
- var entityId = target.entityId, componentId = target.componentId;
1217
- var context = _this._prefabContextMap.get(rootEntity);
1218
- var targetEntity = context.entityMap.get(entityId);
1219
- var targetComponent = context.components.get(componentId);
1220
- if (targetComponent) {
1221
- return _this._reflectionParser.parsePropsAndMethods(targetComponent, {
1222
- props: props,
1223
- methods: methods
1224
- });
1225
- } else if (targetEntity) {
1226
- return Promise.resolve(_this._applyEntityData(targetEntity, props));
1227
- }
1228
- })));
1357
+ this._parseEntities().then(function() {
1358
+ return _this._organizeEntities();
1359
+ }).then(function() {
1360
+ return _this._parseComponents();
1361
+ }).then(function() {
1362
+ return _this._parseComponentsPropsAndCalls();
1363
+ }).then(function() {
1364
+ return _this._parsePrefabOverrides();
1365
+ }).then(function() {
1366
+ return _this._clearAndResolve();
1367
+ }).then(this._resolve).catch(this._reject);
1368
+ };
1369
+ _proto._onEntityCreated = function _onEntityCreated(_entity) {};
1370
+ // ---------------------------------------------------------------------------
1371
+ // Stage 1: Create entity instances
1372
+ // ---------------------------------------------------------------------------
1373
+ _proto._parseEntities = function _parseEntities() {
1374
+ var _this, _loop = function(i, n) {
1375
+ var entityConfig = entities[i];
1376
+ if (HierarchyParser._isPrefabInstanceEntity(entityConfig)) {
1377
+ promises.push(_this._loadPrefabInstance(entityConfig, engine).then(function(entity) {
1378
+ entityInstances[i] = entity;
1379
+ }));
1380
+ } else {
1381
+ var entity = new engineCore.Entity(engine, entityConfig.name);
1382
+ HierarchyParser._applyEntityProps(entity, entityConfig);
1383
+ _this._onEntityCreated(entity);
1384
+ entityInstances[i] = entity;
1229
1385
  }
1230
1386
  };
1231
- var _this = this;
1232
- var entitiesConfig = this.data.entities;
1233
- var entityMap = this.context.entityMap;
1387
+ var entities = this.data.entities;
1388
+ var entityInstances = this.context.entityInstances;
1389
+ var engine = this._engine;
1234
1390
  var promises = [];
1235
- for(var i = 0, l = entitiesConfig.length; i < l; i++)_loop(i);
1391
+ for(var i = 0, n = entities.length; i < n; i++)_this = this, _loop(i);
1236
1392
  return Promise.all(promises);
1237
1393
  };
1238
- _proto._parseAddedComponents = function _parseAddedComponents() {
1239
- var entityMap = this.context.entityMap;
1240
- var entityConfigMap = this.context.entityConfigMap;
1241
- var strippedIds = this.context.strippedIds;
1242
- for(var i = 0, n = strippedIds.length; i < n; i++){
1243
- var entityConfig = entityConfigMap.get(strippedIds[i]);
1244
- var prefabContext = this._prefabContextMap.get(entityMap.get(entityConfig.prefabInstanceId));
1245
- var entity = prefabContext.entityMap.get(entityConfig.prefabSource.entityId);
1246
- this._addComponents(entity, entityConfig.components);
1247
- }
1248
- };
1249
- _proto._parsePrefabRemovedEntities = function _parsePrefabRemovedEntities() {
1250
- var entitiesConfig = this.data.entities;
1251
- var entityMap = this.context.entityMap;
1252
- for(var i = 0, l = entitiesConfig.length; i < l; i++){
1253
- var entityConfig = entitiesConfig[i];
1254
- var id = entityConfig.id, removedEntities = entityConfig.removedEntities;
1255
- if (removedEntities == null ? void 0 : removedEntities.length) {
1256
- var rootEntity = entityMap.get(id);
1257
- for(var j = 0, m = removedEntities.length; j < m; j++){
1258
- var target = removedEntities[j];
1259
- var entityId = target.entityId;
1260
- var context = this._prefabContextMap.get(rootEntity);
1261
- var targetEntity = context.entityMap.get(entityId);
1262
- if (targetEntity) {
1263
- targetEntity.destroy();
1264
- }
1265
- }
1394
+ // ---------------------------------------------------------------------------
1395
+ // Stage 2: Build parent-child hierarchy
1396
+ // ---------------------------------------------------------------------------
1397
+ _proto._organizeEntities = function _organizeEntities() {
1398
+ var entities = this.data.entities;
1399
+ var entityInstances = this.context.entityInstances;
1400
+ for(var i = 0, n = entities.length; i < n; i++){
1401
+ var entityConfig = entities[i];
1402
+ // Prefab instance entities manage their own children.
1403
+ if (HierarchyParser._isPrefabInstanceEntity(entityConfig)) continue;
1404
+ var children = entityConfig.children;
1405
+ if (!children) continue;
1406
+ var parent = entityInstances[i];
1407
+ for(var j = 0, m = children.length; j < m; j++){
1408
+ parent.addChild(entityInstances[children[j]]);
1266
1409
  }
1267
1410
  }
1411
+ var rootIndices = this._getRootIndices();
1412
+ for(var i1 = 0, n1 = rootIndices.length; i1 < n1; i1++){
1413
+ this._handleRootEntity(rootIndices[i1]);
1414
+ }
1268
1415
  };
1269
- _proto._parsePrefabRemovedComponents = function _parsePrefabRemovedComponents() {
1270
- var entitiesConfig = this.data.entities;
1271
- var entityMap = this.context.entityMap;
1272
- var prefabContextMap = this._prefabContextMap;
1273
- for(var i = 0, l = entitiesConfig.length; i < l; i++){
1274
- var entityConfig = entitiesConfig[i];
1275
- var id = entityConfig.id, removedComponents = entityConfig.removedComponents;
1276
- if (removedComponents == null ? void 0 : removedComponents.length) {
1277
- var rootEntity = entityMap.get(id);
1278
- for(var j = 0, m = removedComponents.length; j < m; j++){
1279
- var target = removedComponents[j];
1280
- var componentId = target.componentId;
1281
- var context = prefabContextMap.get(rootEntity);
1282
- var targetComponent = context.components.get(componentId);
1283
- if (targetComponent) {
1284
- targetComponent.destroy();
1285
- }
1286
- }
1416
+ // ---------------------------------------------------------------------------
1417
+ // Stage 3: Add components to entities
1418
+ // ---------------------------------------------------------------------------
1419
+ _proto._parseComponents = function _parseComponents() {
1420
+ var entities = this.data.entities;
1421
+ var allComponents = this.data.components;
1422
+ var entityInstances = this.context.entityInstances;
1423
+ var pendingComponents = this.context.pendingComponents;
1424
+ var refs = this.data.refs;
1425
+ for(var i = 0, n = entities.length; i < n; i++){
1426
+ var entityConfig = entities[i];
1427
+ if (HierarchyParser._isPrefabInstanceEntity(entityConfig)) continue;
1428
+ var entity = entityInstances[i];
1429
+ var componentIndices = entityConfig.components;
1430
+ if (!componentIndices) continue;
1431
+ for(var j = 0, m = componentIndices.length; j < m; j++){
1432
+ var config = allComponents[componentIndices[j]];
1433
+ var instance = HierarchyParser._addComponentFromConfig(entity, config, refs);
1434
+ pendingComponents.push({
1435
+ instance: instance,
1436
+ config: config
1437
+ });
1287
1438
  }
1288
1439
  }
1289
1440
  };
1290
- _proto._organizeEntities = function _organizeEntities() {
1291
- var _this_context = this.context, rootIds = _this_context.rootIds, strippedIds = _this_context.strippedIds;
1292
- var parentIds = rootIds.concat(strippedIds);
1293
- for(var i = 0, l = parentIds.length; i < l; i++){
1294
- this._parseChildren(parentIds[i]);
1295
- }
1296
- for(var i1 = 0; i1 < rootIds.length; i1++){
1297
- this._handleRootEntity(rootIds[i1]);
1441
+ // ---------------------------------------------------------------------------
1442
+ // Stage 4: Apply props and execute calls on components
1443
+ // ---------------------------------------------------------------------------
1444
+ _proto._parseComponentsPropsAndCalls = function _parseComponentsPropsAndCalls() {
1445
+ var pendingComponents = this.context.pendingComponents;
1446
+ var reflectionParser = this._reflectionParser;
1447
+ var promises = [];
1448
+ for(var i = 0, n = pendingComponents.length; i < n; i++){
1449
+ var _pendingComponents_i = pendingComponents[i], instance = _pendingComponents_i.instance, config = _pendingComponents_i.config;
1450
+ promises.push(reflectionParser.parseMutationBlock(instance, config));
1298
1451
  }
1452
+ return Promise.all(promises);
1299
1453
  };
1300
- _proto._getEntityByConfig = function _getEntityByConfig(entityConfig, engine) {
1301
- var _this = this;
1302
- var entityPromise;
1303
- if (entityConfig.assetUrl) {
1304
- entityPromise = this._parsePrefab(entityConfig, engine);
1305
- } else if (entityConfig.strippedId) {
1306
- entityPromise = this._parseStrippedEntity(entityConfig);
1307
- } else {
1308
- entityPromise = this._parseEntity(entityConfig, engine);
1454
+ // ---------------------------------------------------------------------------
1455
+ // Stage 5: Apply prefab instance overrides
1456
+ // ---------------------------------------------------------------------------
1457
+ _proto._parsePrefabOverrides = function _parsePrefabOverrides() {
1458
+ var entities = this.data.entities;
1459
+ var entityInstances = this.context.entityInstances;
1460
+ var promises = [];
1461
+ for(var i = 0, n = entities.length; i < n; i++){
1462
+ var entityConfig = entities[i];
1463
+ if (!HierarchyParser._isPrefabInstanceEntity(entityConfig)) continue;
1464
+ var overrides = entityConfig.instance.overrides;
1465
+ if (!overrides) continue;
1466
+ this._applyOverrides(entityInstances[i], overrides, promises);
1309
1467
  }
1310
- return entityPromise.then(function(entity) {
1311
- return _this._applyEntityData(entity, entityConfig);
1312
- });
1468
+ return Promise.all(promises);
1313
1469
  };
1314
- _proto._parseEntity = function _parseEntity(entityConfig, engine) {
1315
- var transform = entityConfig.transform;
1316
- var entity = new engineCore.Entity(engine, entityConfig.name, transform ? engineCore.Loader.getClass(transform.class) : engineCore.Transform);
1317
- this._addEntityPlugin(entityConfig.id, entity);
1318
- return Promise.resolve(entity);
1470
+ _proto._applyOverrides = function _applyOverrides(rootEntity, overrides, promises) {
1471
+ var refs = this.data.refs;
1472
+ var reflectionParser = this._reflectionParser;
1473
+ // entityProps — entity-level property overrides
1474
+ if (overrides.entityProps) {
1475
+ for(var j = 0, m = overrides.entityProps.length; j < m; j++){
1476
+ var override = overrides.entityProps[j];
1477
+ HierarchyParser._applyEntityProps(HierarchyParser._resolveEntity(rootEntity, override.path), override);
1478
+ }
1479
+ }
1480
+ // componentProps — component-level property overrides
1481
+ if (overrides.componentProps) {
1482
+ for(var j1 = 0, m1 = overrides.componentProps.length; j1 < m1; j1++){
1483
+ var override1 = overrides.componentProps[j1];
1484
+ var entity = HierarchyParser._resolveEntity(rootEntity, override1.path);
1485
+ var target = HierarchyParser._resolveComponent(entity, override1.selector);
1486
+ promises.push(reflectionParser.parseMutationBlock(target, override1));
1487
+ }
1488
+ }
1489
+ // addedComponents — attach top-level components[index] to a prefab entity and parse props
1490
+ if (overrides.addedComponents) {
1491
+ var allComponents = this.data.components;
1492
+ for(var j2 = 0, m2 = overrides.addedComponents.length; j2 < m2; j2++){
1493
+ var added = overrides.addedComponents[j2];
1494
+ var entity1 = HierarchyParser._resolveEntity(rootEntity, added.target);
1495
+ var config = allComponents[added.component];
1496
+ var component = HierarchyParser._addComponentFromConfig(entity1, config, refs);
1497
+ promises.push(reflectionParser.parseMutationBlock(component, config));
1498
+ }
1499
+ }
1500
+ // addedEntities — attach already-created top-level entityInstances[index] as a child
1501
+ if (overrides.addedEntities) {
1502
+ var entityInstances = this.context.entityInstances;
1503
+ for(var j3 = 0, m3 = overrides.addedEntities.length; j3 < m3; j3++){
1504
+ var added1 = overrides.addedEntities[j3];
1505
+ var parent = HierarchyParser._resolveEntity(rootEntity, added1.parent);
1506
+ parent.addChild(entityInstances[added1.entity]);
1507
+ }
1508
+ }
1509
+ // removedEntities — pre-resolve all targets then destroy (destroy shifts sibling indices)
1510
+ if (overrides.removedEntities) {
1511
+ var removed = overrides.removedEntities;
1512
+ var targets = new Array(removed.length);
1513
+ for(var j4 = 0, m4 = removed.length; j4 < m4; j4++){
1514
+ targets[j4] = HierarchyParser._resolveEntity(rootEntity, removed[j4]);
1515
+ }
1516
+ for(var j5 = 0, m5 = targets.length; j5 < m5; j5++){
1517
+ targets[j5].destroy();
1518
+ }
1519
+ }
1520
+ // removedComponents — pre-resolve all targets then destroy (destroy shifts component indices)
1521
+ if (overrides.removedComponents) {
1522
+ var targets1 = [];
1523
+ for(var j6 = 0, m6 = overrides.removedComponents.length; j6 < m6; j6++){
1524
+ var override2 = overrides.removedComponents[j6];
1525
+ var entity2 = HierarchyParser._resolveEntity(rootEntity, override2.path);
1526
+ var selectors = override2.selectors;
1527
+ for(var k = 0, p = selectors.length; k < p; k++){
1528
+ targets1.push(HierarchyParser._resolveComponent(entity2, selectors[k]));
1529
+ }
1530
+ }
1531
+ for(var j7 = 0, m7 = targets1.length; j7 < m7; j7++){
1532
+ targets1[j7].destroy();
1533
+ }
1534
+ }
1319
1535
  };
1320
- _proto._parsePrefab = function _parsePrefab(entityConfig, engine) {
1536
+ // ---------------------------------------------------------------------------
1537
+ // Prefab instance loading
1538
+ // ---------------------------------------------------------------------------
1539
+ _proto._loadPrefabInstance = function _loadPrefabInstance(entityConfig, engine) {
1321
1540
  var _this = this;
1322
- var assetUrl = entityConfig.assetUrl;
1541
+ var instance = entityConfig.instance;
1542
+ var refItem;
1543
+ try {
1544
+ refItem = resolveRefItem(this.data.refs, instance.asset, "HierarchyParser", "instance.asset");
1545
+ } catch (error) {
1546
+ return Promise.reject(error);
1547
+ }
1323
1548
  return engine.resourceManager// @ts-ignore
1324
- .getResourceByRef({
1325
- url: assetUrl
1326
- }).then(function(prefabResource) {
1549
+ .getResourceByRef(refItem).then(function(prefabResource) {
1327
1550
  var entity = _instanceof(prefabResource, PrefabResource) ? prefabResource.instantiate() : prefabResource.instantiateSceneRoot();
1328
- var instanceContext = new ParserContext(engine, ParserType.Prefab, null);
1329
- _this._generateInstanceContext(entity, instanceContext, "");
1330
- _this._prefabContextMap.set(entity, instanceContext);
1331
- var cbArray = _this._prefabPromiseMap.get(entityConfig.id);
1332
- if (cbArray) {
1333
- for(var i = 0, n = cbArray.length; i < n; i++){
1334
- cbArray[i].resolve(instanceContext);
1335
- }
1336
- }
1551
+ _this._onEntityCreated(entity);
1337
1552
  return entity;
1338
1553
  });
1339
1554
  };
1340
- _proto._parseStrippedEntity = function _parseStrippedEntity(entityConfig) {
1341
- var _this = this;
1342
- this.context.strippedIds.push(entityConfig.id);
1343
- return new Promise(function(resolve, reject) {
1344
- var _this__prefabPromiseMap_get;
1345
- var cbArray = (_this__prefabPromiseMap_get = _this._prefabPromiseMap.get(entityConfig.prefabInstanceId)) != null ? _this__prefabPromiseMap_get : [];
1346
- cbArray.push({
1347
- resolve: resolve,
1348
- reject: reject
1349
- });
1350
- _this._prefabPromiseMap.set(entityConfig.prefabInstanceId, cbArray);
1351
- }).then(function(context) {
1352
- var entityId = entityConfig.prefabSource.entityId;
1353
- return context.entityMap.get(entityId);
1354
- });
1355
- };
1356
- _proto._parseChildren = function _parseChildren(parentId) {
1357
- var _this_context = this.context, entityConfigMap = _this_context.entityConfigMap, entityMap = _this_context.entityMap;
1358
- var children = entityConfigMap.get(parentId).children;
1359
- if (children && children.length > 0) {
1360
- var parent = entityMap.get(parentId);
1361
- for(var i = 0; i < children.length; i++){
1362
- var childId = children[i];
1363
- var entity = entityMap.get(childId);
1364
- parent.addChild(entity);
1365
- this._parseChildren(childId);
1366
- }
1555
+ // ---------------------------------------------------------------------------
1556
+ // Utilities
1557
+ // ---------------------------------------------------------------------------
1558
+ /** Resolve an entity inside a prefab instance by walking the child-index path from root */ HierarchyParser._resolveEntity = function _resolveEntity(root, path) {
1559
+ var entity = root;
1560
+ for(var i = 0, n = path.length; i < n; i++){
1561
+ entity = entity.children[path[i]];
1562
+ if (!entity) throw new Error("HierarchyParser: override target entity not found at path [" + path + "], failed at depth " + i);
1367
1563
  }
1564
+ return entity;
1368
1565
  };
1369
- _proto._addComponents = function _addComponents(entity, components) {
1370
- var context = this.context;
1371
- var componentMap = context.components;
1372
- var componentConfigMap = context.componentConfigMap;
1373
- for(var i = 0, n = components.length; i < n; i++){
1374
- var componentConfig = components[i];
1375
- var key = !componentConfig.url ? componentConfig.class : componentConfig.url;
1376
- var componentId = componentConfig.id;
1377
- var component = entity.addComponent(engineCore.Loader.getClass(key));
1378
- componentMap.set(componentId, component);
1379
- componentConfigMap.set(componentId, componentConfig);
1380
- this._addComponentPlugin(componentId, component);
1381
- }
1382
- };
1383
- _proto._generateInstanceContext = function _generateInstanceContext(entity, context, path) {
1384
- var entityMap = context.entityMap, components = context.components;
1385
- var componentsMap = {};
1386
- var componentIndexMap = {};
1387
- entityMap.set(path, entity);
1388
- // @ts-ignore
1389
- entity._components.forEach(function(component) {
1390
- // @ts-ignore
1391
- var name = engineCore.Loader.getClassName(component.constructor);
1392
- if (!componentsMap[name]) {
1393
- componentsMap[name] = entity.getComponents(component.constructor, []);
1394
- componentIndexMap[name] = 0;
1395
- }
1396
- components.set(path + ":" + name + "/" + componentIndexMap[name]++, component);
1397
- });
1398
- for(var i = 0, n = entity.children.length; i < n; i++){
1399
- var child = entity.children[i];
1400
- var childPath = path ? path + "/" + i : "" + i;
1401
- this._generateInstanceContext(child, context, childPath);
1402
- }
1566
+ /** Resolve a component on an entity by type name + per-type index */ HierarchyParser._resolveComponent = function _resolveComponent(entity, selector) {
1567
+ var type = engineCore.Loader.getClass(selector.type);
1568
+ if (!type) throw new Error('HierarchyParser: override target component type "' + selector.type + '" is not registered');
1569
+ var buffer = ReflectionParser._componentBuffer;
1570
+ buffer.length = 0;
1571
+ entity.getComponents(type, buffer);
1572
+ var result = buffer[selector.index];
1573
+ buffer.length = 0;
1574
+ if (!result) throw new Error("HierarchyParser: override target component not found: " + selector.type + "/" + selector.index);
1575
+ return result;
1403
1576
  };
1404
- _proto._parseComponentsPropsAndMethods = function _parseComponentsPropsAndMethods() {
1405
- var context = this.context;
1406
- var componentConfigMap = context.componentConfigMap;
1407
- var reflectionParser = this._reflectionParser;
1408
- var promises = [];
1409
- for(var _iterator = _create_for_of_iterator_helper_loose(context.components), _step; !(_step = _iterator()).done;){
1410
- var _step_value = _step.value, componentId = _step_value[0], component = _step_value[1];
1411
- var componentConfig = componentConfigMap.get(componentId);
1412
- if (componentConfig) {
1413
- promises.push(reflectionParser.parsePropsAndMethods(component, componentConfig));
1414
- }
1415
- }
1416
- return Promise.all(promises);
1577
+ /** Resolve component class from config and add to entity. Throws if class is not registered. */ HierarchyParser._addComponentFromConfig = function _addComponentFromConfig(entity, config, refs) {
1578
+ var key = config.script != null ? resolveRefItem(refs, config.script, "HierarchyParser", "component.script").url : config.type;
1579
+ var Class = engineCore.Loader.getClass(key);
1580
+ if (!Class) throw new Error('Loader.getClass: class "' + key + '" is not registered');
1581
+ return entity.addComponent(Class);
1582
+ };
1583
+ HierarchyParser._isPrefabInstanceEntity = function _isPrefabInstanceEntity(entityConfig) {
1584
+ return "instance" in entityConfig;
1585
+ };
1586
+ /** Apply entity-level props (name, isActive, layer, transform) to an entity. */ HierarchyParser._applyEntityProps = function _applyEntityProps(entity, props) {
1587
+ if (props.name != null) entity.name = props.name;
1588
+ if (props.isActive != null) entity.isActive = props.isActive;
1589
+ if (props.layer != null) entity.layer = props.layer;
1590
+ if (props.position) entity.transform.position.set(props.position[0], props.position[1], props.position[2]);
1591
+ if (props.rotation) entity.transform.rotation.set(props.rotation[0], props.rotation[1], props.rotation[2]);
1592
+ if (props.scale) entity.transform.scale.set(props.scale[0], props.scale[1], props.scale[2]);
1417
1593
  };
1418
- _proto._addComponentPlugin = function _addComponentPlugin(componentId, component) {};
1419
- _proto._addEntityPlugin = function _addEntityPlugin(entityId, entity) {};
1420
1594
  return HierarchyParser;
1421
1595
  }();
1422
1596
 
1423
- var MaterialLoaderType = /*#__PURE__*/ function(MaterialLoaderType) {
1424
- MaterialLoaderType["Vector2"] = "Vector2";
1425
- MaterialLoaderType["Vector3"] = "Vector3";
1426
- MaterialLoaderType["Vector4"] = "Vector4";
1427
- MaterialLoaderType["Color"] = "Color";
1428
- MaterialLoaderType["Float"] = "Float";
1429
- MaterialLoaderType["Texture"] = "Texture";
1430
- MaterialLoaderType["Boolean"] = "Boolean";
1431
- MaterialLoaderType["Integer"] = "Integer";
1432
- return MaterialLoaderType;
1433
- }({});
1434
-
1435
- var SpecularMode = /*#__PURE__*/ function(SpecularMode) {
1436
- SpecularMode["Sky"] = "Sky";
1437
- SpecularMode["Custom"] = "Custom";
1438
- return SpecularMode;
1439
- }({});
1440
-
1441
1597
  /** @Internal */ var SceneParser = /*#__PURE__*/ function(HierarchyParser) {
1442
1598
  _inherits(SceneParser, HierarchyParser);
1443
1599
  function SceneParser(data, context, scene) {
@@ -1451,91 +1607,43 @@ var SpecularMode = /*#__PURE__*/ function(SpecularMode) {
1451
1607
  */ _proto._collectDependentAssets = function _collectDependentAssets(data) {
1452
1608
  var context = this.context;
1453
1609
  var resourceManager = context.resourceManager;
1454
- this._parseDependentAssets(data);
1455
- var scene = data.scene;
1456
- var ambient = scene.ambient;
1457
- if (ambient) {
1458
- var useCustomAmbient = ambient.specularMode === SpecularMode.Custom;
1459
- var useSH = ambient.diffuseMode === engineCore.DiffuseMode.SphericalHarmonics;
1460
- var customAmbientLight = ambient.customAmbientLight, ambientLight = ambient.ambientLight;
1461
- if (useCustomAmbient && customAmbientLight) {
1462
- // @ts-ignore
1463
- context._addDependentAsset(customAmbientLight.url, resourceManager.getResourceByRef(customAmbientLight));
1464
- }
1465
- if (ambientLight && (!useCustomAmbient || useSH)) {
1466
- // @ts-ignore
1467
- context._addDependentAsset(ambientLight.url, resourceManager.getResourceByRef(ambientLight));
1468
- }
1469
- }
1470
- var background = scene.background;
1471
- var backgroundMode = background.mode;
1472
- if (backgroundMode === engineCore.BackgroundMode.Texture) {
1473
- var texture = background.texture;
1610
+ var refs = data.refs;
1611
+ for(var i = 0, n = refs.length; i < n; i++){
1474
1612
  // @ts-ignore
1475
- texture && context._addDependentAsset(texture.url, resourceManager.getResourceByRef(texture));
1476
- } else if (backgroundMode === engineCore.BackgroundMode.Sky) {
1477
- var skyMesh = background.skyMesh, skyMaterial = background.skyMaterial;
1478
- if (skyMesh && skyMaterial) {
1479
- // @ts-ignore
1480
- context._addDependentAsset(skyMesh.url, resourceManager.getResourceByRef(skyMesh));
1481
- // @ts-ignore
1482
- context._addDependentAsset(skyMaterial.url, resourceManager.getResourceByRef(skyMaterial));
1483
- }
1613
+ context._addDependentAsset(resourceManager.getResourceByRef(refs[i]));
1484
1614
  }
1485
1615
  };
1486
- _proto._handleRootEntity = function _handleRootEntity(id) {
1487
- var entityMap = this.context.entityMap;
1488
- this.scene.addRootEntity(entityMap.get(id));
1616
+ _proto._getRootIndices = function _getRootIndices() {
1617
+ return this.data.scene.rootEntities;
1618
+ };
1619
+ _proto._handleRootEntity = function _handleRootEntity(index) {
1620
+ this.scene.addRootEntity(this.context.entityInstances[index]);
1489
1621
  };
1490
1622
  _proto._clearAndResolve = function _clearAndResolve() {
1491
1623
  this.context.clear();
1492
1624
  return this.scene;
1493
1625
  };
1494
- _proto._parseDependentAssets = function _parseDependentAssets(file) {
1495
- var entities = file.entities;
1496
- for(var i = 0, n = entities.length; i < n; i++){
1497
- var entity = entities[i];
1498
- if (!!entity.assetUrl) {
1499
- var context = this.context;
1500
- var url = entity.assetUrl, key = entity.key;
1501
- // @ts-ignore
1502
- context._addDependentAsset(url, context.resourceManager.getResourceByRef({
1503
- url: url,
1504
- key: key
1505
- }));
1506
- } else if (entity.strippedId) {
1507
- continue;
1508
- } else {
1509
- var components = entity.components;
1510
- for(var j = 0, m = components.length; j < m; j++){
1511
- var component = components[j];
1512
- this._searchDependentAssets(component.methods);
1513
- this._searchDependentAssets(component.props);
1514
- }
1515
- }
1516
- }
1517
- };
1518
- _proto._searchDependentAssets = function _searchDependentAssets(value) {
1519
- if (Array.isArray(value)) {
1520
- for(var i = 0, n = value.length; i < n; i++){
1521
- this._searchDependentAssets(value[i]);
1522
- }
1523
- } else if (!!value && (typeof value === "undefined" ? "undefined" : _type_of(value)) === "object") {
1524
- // @ts-ignore
1525
- if (ReflectionParser._isAssetRef(value)) {
1526
- var context = this.context;
1527
- // @ts-ignore
1528
- context._addDependentAsset(value.url, context.resourceManager.getResourceByRef(value));
1529
- } else {
1530
- for(var key in value){
1531
- this._searchDependentAssets(value[key]);
1532
- }
1533
- }
1534
- }
1535
- };
1536
1626
  return SceneParser;
1537
1627
  }(HierarchyParser);
1538
1628
 
1629
+ var SpecularMode = /*#__PURE__*/ function(SpecularMode) {
1630
+ SpecularMode[SpecularMode["Sky"] = 0] = "Sky";
1631
+ SpecularMode[SpecularMode["Custom"] = 1] = "Custom";
1632
+ return SpecularMode;
1633
+ }({});
1634
+
1635
+ var MaterialLoaderType = /*#__PURE__*/ function(MaterialLoaderType) {
1636
+ MaterialLoaderType["Vector2"] = "Vector2";
1637
+ MaterialLoaderType["Vector3"] = "Vector3";
1638
+ MaterialLoaderType["Vector4"] = "Vector4";
1639
+ MaterialLoaderType["Color"] = "Color";
1640
+ MaterialLoaderType["Float"] = "Float";
1641
+ MaterialLoaderType["Texture"] = "Texture";
1642
+ MaterialLoaderType["Boolean"] = "Boolean";
1643
+ MaterialLoaderType["Integer"] = "Integer";
1644
+ return MaterialLoaderType;
1645
+ }({});
1646
+
1539
1647
  /**
1540
1648
  * Decode engine binary resource.
1541
1649
  * @param arrayBuffer - array buffer of decode binary file
@@ -3017,6 +3125,45 @@ function getMeshoptDecoder() {
3017
3125
  return GLTFResource;
3018
3126
  }(engineCore.ReferResource);
3019
3127
 
3128
+ function _array_like_to_array(arr, len) {
3129
+ if (len == null || len > arr.length) len = arr.length;
3130
+
3131
+ for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i];
3132
+
3133
+ return arr2;
3134
+ }
3135
+
3136
+ function _unsupported_iterable_to_array(o, minLen) {
3137
+ if (!o) return;
3138
+ if (typeof o === "string") return _array_like_to_array(o, minLen);
3139
+
3140
+ var n = Object.prototype.toString.call(o).slice(8, -1);
3141
+
3142
+ if (n === "Object" && o.constructor) n = o.constructor.name;
3143
+ if (n === "Map" || n === "Set") return Array.from(n);
3144
+ if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _array_like_to_array(o, minLen);
3145
+ }
3146
+
3147
+ function _create_for_of_iterator_helper_loose(o, allowArrayLike) {
3148
+ var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"];
3149
+
3150
+ if (it) return (it = it.call(o)).next.bind(it);
3151
+ // Fallback for engines without symbol support
3152
+ if (Array.isArray(o) || (it = _unsupported_iterable_to_array(o)) || allowArrayLike && o && typeof o.length === "number") {
3153
+ if (it) o = it;
3154
+
3155
+ var i = 0;
3156
+
3157
+ return function() {
3158
+ if (i >= o.length) return { done: true };
3159
+
3160
+ return { done: false, value: o[i++] };
3161
+ };
3162
+ }
3163
+
3164
+ throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
3165
+ }
3166
+
3020
3167
  /**
3021
3168
  * Module for glTF 2.0 Interface
3022
3169
  */ /**
@@ -3638,11 +3785,13 @@ function registerGLTFParser(pipeline) {
3638
3785
  });
3639
3786
  var img = new Image();
3640
3787
  img.onerror = function() {
3788
+ URL.revokeObjectURL(img.src);
3641
3789
  reject(new Error("Failed to load image buffer"));
3642
3790
  };
3643
3791
  img.onload = function() {
3644
3792
  // Call requestAnimationFrame to avoid iOS's bug.
3645
3793
  requestAnimationFrame(function() {
3794
+ URL.revokeObjectURL(img.src);
3646
3795
  resolve(img);
3647
3796
  img.onload = null;
3648
3797
  img.onerror = null;
@@ -4763,7 +4912,6 @@ exports.GLTFSceneParser = /*#__PURE__*/ function(GLTFParser1) {
4763
4912
  }
4764
4913
  var _proto = GLTFSceneParser.prototype;
4765
4914
  _proto.parse = function parse(context, index) {
4766
- var _glTFResource;
4767
4915
  var _context_glTF = context.glTF, scenes = _context_glTF.scenes, _context_glTF_scene = _context_glTF.scene, scene = _context_glTF_scene === void 0 ? 0 : _context_glTF_scene, glTFResource = context.glTFResource;
4768
4916
  var sceneInfo = scenes[index];
4769
4917
  var sceneExtensions = sceneInfo.extensions;
@@ -4777,7 +4925,6 @@ exports.GLTFSceneParser = /*#__PURE__*/ function(GLTFParser1) {
4777
4925
  for(var i = 0; i < sceneNodes.length; i++){
4778
4926
  sceneRoot.addChild(context.get(GLTFParserType.Entity, sceneNodes[i]));
4779
4927
  }
4780
- ((_glTFResource = glTFResource)._sceneRoots || (_glTFResource._sceneRoots = []))[index] = sceneRoot;
4781
4928
  if (isDefaultScene) {
4782
4929
  glTFResource._defaultSceneRoot = sceneRoot;
4783
4930
  }
@@ -4907,13 +5054,15 @@ exports.GLTFSceneParser = /*#__PURE__*/ function(GLTFParser1) {
4907
5054
  if (rootBoneIndex !== -1) {
4908
5055
  engineMath.BoundingBox.transform(mesh.bounds, inverseBindMatrices[rootBoneIndex], skinnedMeshRenderer.localBounds);
4909
5056
  } else {
4910
- var inverseRootBoneWorld = new engineMath.Matrix();
5057
+ // rootBone can be outside skin.joints, so it has no inverse bind matrix
5058
+ var inverseRootBoneWorld = GLTFSceneParser._tempMatrix;
4911
5059
  engineMath.Matrix.invert(rootBone.transform.worldMatrix, inverseRootBoneWorld);
4912
5060
  engineMath.BoundingBox.transform(mesh.bounds, inverseRootBoneWorld, skinnedMeshRenderer.localBounds);
4913
5061
  }
4914
5062
  };
4915
5063
  return GLTFSceneParser;
4916
5064
  }(GLTFParser);
5065
+ exports.GLTFSceneParser._tempMatrix = new engineMath.Matrix();
4917
5066
  exports.GLTFSceneParser = __decorate([
4918
5067
  registerGLTFParser(GLTFParserType.Scene)
4919
5068
  ], exports.GLTFSceneParser);
@@ -4948,36 +5097,31 @@ exports.GLTFSkinParser = /*#__PURE__*/ function(GLTFParser) {
4948
5097
  skin.joints[i] = bone.name;
4949
5098
  }
4950
5099
  skin.bones = bones;
4951
- // Get skeleton
5100
+ // Get skeleton — when `skin.skeleton` is absent, resolve via joints' LCA
5101
+ // LCA falls back to the GLTF_ROOT wrapper only when joints span multiple top-level scene nodes
4952
5102
  if (skeleton !== undefined) {
4953
5103
  var rootBone = entities[skeleton];
5104
+ if (!rootBone) {
5105
+ throw "Skin skeleton index " + skeleton + " is out of range.";
5106
+ }
4954
5107
  skin.rootBone = rootBone;
4955
5108
  } else {
4956
- var rootBone1 = _this._findSkinRootBoneByLCA(index, joints, entities, glTF.nodes);
4957
- if (rootBone1) {
4958
- skin.rootBone = rootBone1;
4959
- } else {
5109
+ var rootBone1 = _this._findSkeletonRootBone(joints, entities);
5110
+ if (!rootBone1) {
4960
5111
  throw "Failed to find skeleton root bone.";
4961
5112
  }
5113
+ skin.rootBone = rootBone1;
4962
5114
  }
4963
5115
  return skin;
4964
5116
  });
4965
5117
  return engineCore.AssetPromise.resolve(skinPromise);
4966
5118
  };
4967
- _proto._findSkinRootBoneByLCA = function _findSkinRootBoneByLCA(skinIndex, joints, entities, nodes) {
4968
- if (nodes === void 0) nodes = [];
4969
- var nodeIndices = joints.slice();
4970
- for(var i = 0, n = nodes.length; i < n; i++){
4971
- var _nodes_i;
4972
- if (((_nodes_i = nodes[i]) == null ? void 0 : _nodes_i.skin) === skinIndex) {
4973
- nodeIndices.push(i);
4974
- }
4975
- }
4976
- return this._findRootBoneByLCA(nodeIndices, entities);
4977
- };
4978
- _proto._findRootBoneByLCA = function _findRootBoneByLCA(nodeIndices, entities) {
4979
- var paths = [];
4980
- for(var _iterator = _create_for_of_iterator_helper_loose(nodeIndices), _step; !(_step = _iterator()).done;){
5119
+ /**
5120
+ * Resolve the skeleton rootBone as the lowest common ancestor of the joints' parent chains.
5121
+ * Returns null when joints share no common ancestor.
5122
+ */ _proto._findSkeletonRootBone = function _findSkeletonRootBone(joints, entities) {
5123
+ var paths = {};
5124
+ for(var _iterator = _create_for_of_iterator_helper_loose(joints), _step; !(_step = _iterator()).done;){
4981
5125
  var index = _step.value;
4982
5126
  var path = new Array();
4983
5127
  var entity = entities[index];
@@ -4985,22 +5129,17 @@ exports.GLTFSkinParser = /*#__PURE__*/ function(GLTFParser) {
4985
5129
  path.unshift(entity);
4986
5130
  entity = entity.parent;
4987
5131
  }
4988
- if (path.length) {
4989
- paths.push(path);
4990
- }
4991
- }
4992
- if (!paths.length) {
4993
- return null;
5132
+ paths[index] = path;
4994
5133
  }
4995
5134
  var rootNode = null;
4996
5135
  for(var i = 0;; i++){
4997
- var path1 = paths[0];
5136
+ var path1 = paths[joints[0]];
4998
5137
  if (i >= path1.length) {
4999
5138
  return rootNode;
5000
5139
  }
5001
5140
  var entity1 = path1[i];
5002
- for(var j = 1, m = paths.length; j < m; j++){
5003
- path1 = paths[j];
5141
+ for(var j = 1, m = joints.length; j < m; j++){
5142
+ path1 = paths[joints[j]];
5004
5143
  if (i >= path1.length || entity1 !== path1[i]) {
5005
5144
  return rootNode;
5006
5145
  }
@@ -5063,7 +5202,7 @@ exports.GLTFTextureParser = /*#__PURE__*/ function(GLTFParser1) {
5063
5202
  if (uri) {
5064
5203
  var extIndex = uri.lastIndexOf(".");
5065
5204
  var ext = uri.substring(extIndex + 1);
5066
- var type = ext.startsWith("ktx") ? engineCore.AssetType.KTX : engineCore.AssetType.Texture2D;
5205
+ var type = ext.startsWith("ktx") ? engineCore.AssetType.KTX : engineCore.AssetType.Texture;
5067
5206
  texture = engine.resourceManager.load({
5068
5207
  url: engineCore.Utils.resolveAbsoluteUrl(url, uri),
5069
5208
  type: type,
@@ -5280,15 +5419,17 @@ var PrefabParser = /*#__PURE__*/ function(HierarchyParser) {
5280
5419
  return _this;
5281
5420
  }
5282
5421
  var _proto = PrefabParser.prototype;
5283
- _proto._applyEntityData = function _applyEntityData(entity, entityConfig) {
5284
- if (entityConfig === void 0) entityConfig = {};
5285
- HierarchyParser.prototype._applyEntityData.call(this, entity, entityConfig);
5422
+ _proto._onEntityCreated = function _onEntityCreated(entity) {
5286
5423
  // @ts-ignore
5287
5424
  entity._markAsTemplate(this.context.resource);
5288
- return entity;
5289
5425
  };
5290
- _proto._handleRootEntity = function _handleRootEntity(id) {
5291
- this.prefabResource._root = this.context.entityMap.get(id);
5426
+ _proto._getRootIndices = function _getRootIndices() {
5427
+ return [
5428
+ this.data.root
5429
+ ];
5430
+ };
5431
+ _proto._handleRootEntity = function _handleRootEntity(index) {
5432
+ this.prefabResource._root = this.context.entityInstances[index];
5292
5433
  };
5293
5434
  _proto._clearAndResolve = function _clearAndResolve() {
5294
5435
  this.context.clear();
@@ -5299,9 +5440,7 @@ var PrefabParser = /*#__PURE__*/ function(HierarchyParser) {
5299
5440
  var context = new ParserContext(engine, ParserType.Prefab, prefabResource);
5300
5441
  var parser = new PrefabParser(data, context, prefabResource);
5301
5442
  parser.start();
5302
- return parser.promise.then(function() {
5303
- return prefabResource;
5304
- });
5443
+ return parser.promise;
5305
5444
  };
5306
5445
  return PrefabParser;
5307
5446
  }(HierarchyParser);
@@ -5641,15 +5780,6 @@ var KTXContentRestorer = /*#__PURE__*/ function(ContentRestorer) {
5641
5780
  return KTXContentRestorer;
5642
5781
  }(engineCore.ContentRestorer);
5643
5782
 
5644
- function parseProperty(object, key, value) {
5645
- if ((typeof value === "undefined" ? "undefined" : _type_of(value)) === "object") {
5646
- for(var subKey in value){
5647
- parseProperty(object[key], subKey, value[subKey]);
5648
- }
5649
- } else {
5650
- object[key] = value;
5651
- }
5652
- }
5653
5783
  var MaterialLoader = /*#__PURE__*/ function(Loader) {
5654
5784
  _inherits(MaterialLoader, Loader);
5655
5785
  function MaterialLoader() {
@@ -5710,7 +5840,7 @@ var MaterialLoader = /*#__PURE__*/ function(Loader) {
5710
5840
  break;
5711
5841
  }
5712
5842
  };
5713
- var name = materialSchema.name, shaderData = materialSchema.shaderData, macros = materialSchema.macros, renderState = materialSchema.renderState;
5843
+ var name = materialSchema.name, shaderData = materialSchema.shaderData, macros = materialSchema.macros;
5714
5844
  var material = new engineCore.Material(engine, shader);
5715
5845
  material.name = name;
5716
5846
  var texturePromises = new Array();
@@ -5724,7 +5854,6 @@ var MaterialLoader = /*#__PURE__*/ function(Loader) {
5724
5854
  materialShaderData.enableMacro(name1, value);
5725
5855
  }
5726
5856
  }
5727
- parseProperty(material, "renderState", renderState);
5728
5857
  return Promise.all(texturePromises).then(function() {
5729
5858
  return material;
5730
5859
  });
@@ -5939,7 +6068,7 @@ var SpriteAtlasLoader = /*#__PURE__*/ function(Loader) {
5939
6068
  var _atlasItem_type;
5940
6069
  chainPromises.push(resourceManager.load({
5941
6070
  url: engineCore.Utils.resolveAbsoluteUrl(item.url, atlasItem.img),
5942
- type: (_atlasItem_type = atlasItem.type) != null ? _atlasItem_type : engineCore.AssetType.Texture2D,
6071
+ type: (_atlasItem_type = atlasItem.type) != null ? _atlasItem_type : engineCore.AssetType.Texture,
5943
6072
  params: {
5944
6073
  format: format,
5945
6074
  mipmap: mipmap
@@ -5989,8 +6118,7 @@ var SpriteAtlasLoader = /*#__PURE__*/ function(Loader) {
5989
6118
  var offsetLeft = atlasRegionOffset.x, offsetTop = atlasRegionOffset.y, offsetRight = atlasRegionOffset.z, offsetBottom = atlasRegionOffset.w;
5990
6119
  sprite.atlasRegionOffset.set(offsetLeft * invW, offsetTop * invH, offsetRight * invW, offsetBottom * invH);
5991
6120
  }
5992
- var _config_atlasRotated;
5993
- sprite.atlasRotated = (_config_atlasRotated = config.atlasRotated) != null ? _config_atlasRotated : false;
6121
+ config.atlasRotated && (sprite.atlasRotated = true);
5994
6122
  }
5995
6123
  width === undefined || (sprite.width = width);
5996
6124
  height === undefined || (sprite.height = height);
@@ -6019,517 +6147,210 @@ var SpriteLoader = /*#__PURE__*/ function(Loader) {
6019
6147
  return data.belongToAtlas ? _this._loadFromAtlas(resourceManager, data) : _this._loadFromTexture(resourceManager, data);
6020
6148
  });
6021
6149
  };
6022
- _proto._loadFromAtlas = function _loadFromAtlas(resourceManager, data) {
6023
- var _this = this;
6024
- return resourceManager// @ts-ignore
6025
- .getResourceByRef(data.belongToAtlas).then(function(atlas) {
6026
- return atlas.getSprite(data.fullPath) || _this._loadFromTexture(resourceManager, data);
6027
- });
6028
- };
6029
- _proto._loadFromTexture = function _loadFromTexture(resourceManager, data) {
6030
- if (data.texture) {
6031
- return resourceManager// @ts-ignore
6032
- .getResourceByRef(data.texture).then(function(texture) {
6033
- var sprite = new engineCore.Sprite(resourceManager.engine, texture, data.region, data.pivot, data.border);
6034
- var width = data.width, height = data.height;
6035
- width === undefined || (sprite.width = width);
6036
- height === undefined || (sprite.height = height);
6037
- return sprite;
6038
- });
6039
- } else {
6040
- return new engineCore.AssetPromise(function(resolve) {
6041
- var sprite = new engineCore.Sprite(resourceManager.engine, null, data.region, data.pivot, data.border);
6042
- var width = data.width, height = data.height;
6043
- width === undefined || (sprite.width = width);
6044
- height === undefined || (sprite.height = height);
6045
- resolve(sprite);
6046
- });
6047
- }
6048
- };
6049
- return SpriteLoader;
6050
- }(engineCore.Loader);
6051
- SpriteLoader = __decorate([
6052
- engineCore.resourceLoader(engineCore.AssetType.Sprite, [
6053
- "sprite"
6054
- ])
6055
- ], SpriteLoader);
6056
-
6057
- var TextLoader = /*#__PURE__*/ function(Loader) {
6058
- _inherits(TextLoader, Loader);
6059
- function TextLoader() {
6060
- return Loader.apply(this, arguments) || this;
6061
- }
6062
- var _proto = TextLoader.prototype;
6063
- _proto.load = function load(item, resourceManager) {
6064
- // @ts-ignore
6065
- return resourceManager._request(item.url, _extends({}, item, {
6066
- type: "text"
6067
- })).then(function(text) {
6068
- var asset = new engineCore.TextAsset(resourceManager.engine);
6069
- asset.text = text;
6070
- return asset;
6071
- });
6072
- };
6073
- return TextLoader;
6074
- }(engineCore.Loader);
6075
- TextLoader = __decorate([
6076
- engineCore.resourceLoader(engineCore.AssetType.Text, [
6077
- "txt"
6078
- ])
6079
- ], TextLoader);
6080
-
6081
- function loadImageFromBuffer(buffer) {
6082
- return new engineCore.AssetPromise(function(resolve, reject) {
6083
- var blob = new Blob([
6084
- buffer
6085
- ]);
6086
- var img = new Image();
6087
- img.onload = function() {
6088
- URL.revokeObjectURL(img.src);
6089
- resolve(img);
6090
- };
6091
- img.onerror = reject;
6092
- img.src = URL.createObjectURL(blob);
6093
- });
6094
- }
6095
- var Texture2DLoader = /*#__PURE__*/ function(Loader) {
6096
- _inherits(Texture2DLoader, Loader);
6097
- function Texture2DLoader() {
6098
- return Loader.apply(this, arguments) || this;
6099
- }
6100
- var _proto = Texture2DLoader.prototype;
6101
- _proto.load = function load(item, resourceManager) {
6102
- var _this = this;
6103
- var url = item.url;
6104
- var requestConfig = _extends({}, item, {
6105
- type: "arraybuffer"
6106
- });
6107
- return new engineCore.AssetPromise(function(resolve, reject, setTaskCompleteProgress, setTaskDetailProgress) {
6108
- resourceManager// @ts-ignore
6109
- ._request(url, requestConfig).onProgress(setTaskCompleteProgress, setTaskDetailProgress).then(function(buffer) {
6110
- if (FileHeader.checkMagic(buffer)) {
6111
- decode(buffer, resourceManager.engine).then(function(texture) {
6112
- resourceManager.addContentRestorer(new Texture2DContentRestorer(texture, url, requestConfig));
6113
- resolve(texture);
6114
- }, reject);
6115
- } else {
6116
- loadImageFromBuffer(buffer).then(function(img) {
6117
- var texture = _this._createTexture(img, item, resourceManager);
6118
- resourceManager.addContentRestorer(new Texture2DContentRestorer(texture, url, requestConfig));
6119
- resolve(texture);
6120
- }, reject);
6121
- }
6122
- }).catch(reject);
6123
- });
6124
- };
6125
- _proto._createTexture = function _createTexture(img, item, resourceManager) {
6126
- var _item_params;
6127
- var _ref = (_item_params = item.params) != null ? _item_params : {}, _ref_format = _ref.format, format = _ref_format === void 0 ? engineCore.TextureFormat.R8G8B8A8 : _ref_format, anisoLevel = _ref.anisoLevel, wrapModeU = _ref.wrapModeU, wrapModeV = _ref.wrapModeV, filterMode = _ref.filterMode, _ref_isSRGBColorSpace = _ref.isSRGBColorSpace, isSRGBColorSpace = _ref_isSRGBColorSpace === void 0 ? true : _ref_isSRGBColorSpace, _ref_mipmap = _ref.mipmap, mipmap = _ref_mipmap === void 0 ? true : _ref_mipmap;
6128
- var width = img.width, height = img.height;
6129
- var engine = resourceManager.engine;
6130
- var generateMipmap = engineCore.TextureUtils.supportGenerateMipmapsWithCorrection(engine, width, height, format, mipmap, isSRGBColorSpace);
6131
- var texture = new engineCore.Texture2D(engine, width, height, format, generateMipmap, isSRGBColorSpace);
6132
- texture.anisoLevel = anisoLevel != null ? anisoLevel : texture.anisoLevel;
6133
- texture.filterMode = filterMode != null ? filterMode : texture.filterMode;
6134
- texture.wrapModeU = wrapModeU != null ? wrapModeU : texture.wrapModeU;
6135
- texture.wrapModeV = wrapModeV != null ? wrapModeV : texture.wrapModeV;
6136
- texture.setImageSource(img);
6137
- generateMipmap && texture.generateMipmaps();
6138
- var url = item.url;
6139
- if (url.indexOf("data:") !== 0) {
6140
- texture.name = url.substring(url.lastIndexOf("/") + 1);
6141
- }
6142
- return texture;
6143
- };
6144
- return Texture2DLoader;
6145
- }(engineCore.Loader);
6146
- Texture2DLoader = __decorate([
6147
- engineCore.resourceLoader(engineCore.AssetType.Texture2D, [
6148
- "png",
6149
- "jpg",
6150
- "webp",
6151
- "jpeg",
6152
- "tex"
6153
- ])
6154
- ], Texture2DLoader);
6155
- var Texture2DContentRestorer = /*#__PURE__*/ function(ContentRestorer) {
6156
- _inherits(Texture2DContentRestorer, ContentRestorer);
6157
- function Texture2DContentRestorer(resource, url, requestConfig) {
6158
- var _this;
6159
- _this = ContentRestorer.call(this, resource) || this, _this.url = url, _this.requestConfig = requestConfig;
6160
- return _this;
6161
- }
6162
- var _proto = Texture2DContentRestorer.prototype;
6163
- _proto.restoreContent = function restoreContent() {
6164
- var texture = this.resource;
6165
- var engine = texture.engine;
6166
- return engine.resourceManager// @ts-ignore
6167
- ._request(this.url, this.requestConfig).then(function(buffer) {
6168
- if (FileHeader.checkMagic(buffer)) {
6169
- return decode(buffer, engine, texture);
6170
- } else {
6171
- return loadImageFromBuffer(buffer).then(function(img) {
6172
- texture.setImageSource(img);
6173
- texture.generateMipmaps();
6174
- return texture;
6175
- });
6176
- }
6177
- });
6178
- };
6179
- return Texture2DContentRestorer;
6180
- }(engineCore.ContentRestorer);
6181
-
6182
- /**
6183
- * HDR panorama to cubemap decoder.
6184
- */ var HDRDecoder = /*#__PURE__*/ function() {
6185
- function HDRDecoder() {}
6186
- HDRDecoder.parseHeader = function parseHeader(uint8array) {
6187
- var line = this._readStringLine(uint8array, 0);
6188
- if (line[0] !== "#" || line[1] !== "?") {
6189
- throw "HDRDecoder: invalid file header";
6190
- }
6191
- var endOfHeader = false;
6192
- var findFormat = false;
6193
- var lineIndex = 0;
6194
- do {
6195
- lineIndex += line.length + 1;
6196
- line = this._readStringLine(uint8array, lineIndex);
6197
- if (line === "FORMAT=32-bit_rle_rgbe") findFormat = true;
6198
- else if (line.length === 0) endOfHeader = true;
6199
- }while (!endOfHeader);
6200
- if (!findFormat) {
6201
- throw "HDRDecoder: unsupported format, expected 32-bit_rle_rgbe";
6202
- }
6203
- lineIndex += line.length + 1;
6204
- line = this._readStringLine(uint8array, lineIndex);
6205
- var match = /^\-Y (.*) \+X (.*)$/g.exec(line);
6206
- if (!match || match.length < 3) {
6207
- throw "HDRDecoder: missing image size, only -Y +X layout is supported";
6208
- }
6209
- var width = parseInt(match[2]);
6210
- var height = parseInt(match[1]);
6211
- if (width < 8 || width > 0x7fff) {
6212
- throw "HDRDecoder: unsupported image width, must be between 8 and 32767";
6213
- }
6214
- return {
6215
- height: height,
6216
- width: width,
6217
- dataPosition: lineIndex + line.length + 1
6218
- };
6219
- };
6220
- HDRDecoder.decodeFaces = function decodeFaces(bufferArray, header, onFace) {
6221
- var width = header.width, height = header.height, dataPosition = header.dataPosition;
6222
- var cubeSize = height >> 1;
6223
- var pixels = HDRDecoder._readPixels(bufferArray.subarray(dataPosition), width, height);
6224
- var faces = HDRDecoder._faces;
6225
- var faceBuffer = new Uint16Array(cubeSize * cubeSize * 4);
6226
- for(var faceIndex = 0; faceIndex < 6; faceIndex++){
6227
- HDRDecoder._createCubemapData(cubeSize, faces[faceIndex], pixels, width, height, faceBuffer);
6228
- onFace(faceIndex, faceBuffer);
6229
- }
6230
- };
6231
- HDRDecoder._generateFloat2HalfTables = function _generateFloat2HalfTables() {
6232
- var baseTable = new Uint32Array(512);
6233
- var shiftTable = new Uint32Array(512);
6234
- for(var i = 0; i < 256; ++i){
6235
- var e = i - 127;
6236
- if (e < -27) {
6237
- baseTable[i] = 0x0000;
6238
- baseTable[i | 0x100] = 0x8000;
6239
- shiftTable[i] = 24;
6240
- shiftTable[i | 0x100] = 24;
6241
- } else if (e < -14) {
6242
- baseTable[i] = 0x0400 >> -e - 14;
6243
- baseTable[i | 0x100] = 0x0400 >> -e - 14 | 0x8000;
6244
- shiftTable[i] = -e - 1;
6245
- shiftTable[i | 0x100] = -e - 1;
6246
- } else if (e <= 15) {
6247
- baseTable[i] = e + 15 << 10;
6248
- baseTable[i | 0x100] = e + 15 << 10 | 0x8000;
6249
- shiftTable[i] = 13;
6250
- shiftTable[i | 0x100] = 13;
6251
- } else if (e < 128) {
6252
- baseTable[i] = 0x7c00;
6253
- baseTable[i | 0x100] = 0xfc00;
6254
- shiftTable[i] = 24;
6255
- shiftTable[i | 0x100] = 24;
6256
- } else {
6257
- baseTable[i] = 0x7c00;
6258
- baseTable[i | 0x100] = 0xfc00;
6259
- shiftTable[i] = 13;
6260
- shiftTable[i | 0x100] = 13;
6261
- }
6262
- }
6263
- return {
6264
- baseTable: baseTable,
6265
- shiftTable: shiftTable
6266
- };
6267
- };
6268
- HDRDecoder._createCubemapData = function _createCubemapData(texSize, face, pixels, inputWidth, inputHeight, facePixels) {
6269
- var invSize = 1 / texSize;
6270
- var rotDX1X = (face[3] - face[0]) * invSize;
6271
- var rotDX1Y = (face[4] - face[1]) * invSize;
6272
- var rotDX1Z = (face[5] - face[2]) * invSize;
6273
- var rotDX2X = (face[9] - face[6]) * invSize;
6274
- var rotDX2Y = (face[10] - face[7]) * invSize;
6275
- var rotDX2Z = (face[11] - face[8]) * invSize;
6276
- var floatView = HDRDecoder._floatView;
6277
- var uint32View = HDRDecoder._uint32View;
6278
- var _HDRDecoder__float2HalfTables = HDRDecoder._float2HalfTables, baseTable = _HDRDecoder__float2HalfTables.baseTable, shiftTable = _HDRDecoder__float2HalfTables.shiftTable;
6279
- var one = HDRDecoder._one;
6280
- var fy = 0;
6281
- for(var y = 0; y < texSize; y++){
6282
- var xv1X = face[0], xv1Y = face[1], xv1Z = face[2];
6283
- var xv2X = face[6], xv2Y = face[7], xv2Z = face[8];
6284
- for(var x = 0; x < texSize; x++){
6285
- var dirX = xv1X + (xv2X - xv1X) * fy;
6286
- var dirY = xv1Y + (xv2Y - xv1Y) * fy;
6287
- var dirZ = xv1Z + (xv2Z - xv1Z) * fy;
6288
- var invLen = 1 / Math.sqrt(dirX * dirX + dirY * dirY + dirZ * dirZ);
6289
- dirX *= invLen;
6290
- dirY *= invLen;
6291
- dirZ *= invLen;
6292
- var px = Math.round((Math.atan2(dirZ, dirX) / Math.PI * 0.5 + 0.5) * inputWidth);
6293
- if (px < 0) px = 0;
6294
- else if (px >= inputWidth) px = inputWidth - 1;
6295
- var py = Math.round(Math.acos(dirY) / Math.PI * inputHeight);
6296
- if (py < 0) py = 0;
6297
- else if (py >= inputHeight) py = inputHeight - 1;
6298
- var srcIndex = (inputHeight - py - 1) * inputWidth * 4 + px * 4;
6299
- var scaleFactor = Math.pow(2, pixels[srcIndex + 3] - 128) / 255;
6300
- var dstIndex = y * texSize * 4 + x * 4;
6301
- for(var c = 0; c < 3; c++){
6302
- // Clamp to half-float max (65504) to prevent Infinity in R16G16B16A16
6303
- floatView[0] = Math.min(pixels[srcIndex + c] * scaleFactor, 65504);
6304
- var f = uint32View[0];
6305
- var e = f >> 23 & 0x1ff;
6306
- facePixels[dstIndex + c] = baseTable[e] + ((f & 0x007fffff) >> shiftTable[e]);
6307
- }
6308
- facePixels[dstIndex + 3] = one;
6309
- xv1X += rotDX1X;
6310
- xv1Y += rotDX1Y;
6311
- xv1Z += rotDX1Z;
6312
- xv2X += rotDX2X;
6313
- xv2Y += rotDX2Y;
6314
- xv2Z += rotDX2Z;
6315
- }
6316
- fy += invSize;
6317
- }
6318
- };
6319
- HDRDecoder._readStringLine = function _readStringLine(uint8array, startIndex) {
6320
- var line = "";
6321
- for(var i = startIndex, n = uint8array.length; i < n; i++){
6322
- var character = String.fromCharCode(uint8array[i]);
6323
- if (character === "\n") break;
6324
- line += character;
6325
- }
6326
- return line;
6327
- };
6328
- HDRDecoder._readPixels = function _readPixels(buffer, width, height) {
6329
- var byteLength = buffer.byteLength;
6330
- var dataRGBA = new Uint8Array(4 * width * height);
6331
- var offset = 0;
6332
- var pos = 0;
6333
- var ptrEnd = 4 * width;
6334
- var scanLineBuffer = new Uint8Array(ptrEnd);
6335
- var numScanLines = height;
6336
- while(numScanLines > 0 && pos < byteLength){
6337
- var a = buffer[pos++];
6338
- var b = buffer[pos++];
6339
- var c = buffer[pos++];
6340
- var d = buffer[pos++];
6341
- if (a !== 2 || b !== 2 || c & 0x80 || width < 8 || width > 32767) return buffer;
6342
- if ((c << 8 | d) !== width) throw "HDRDecoder: wrong scanline width";
6343
- var ptr = 0;
6344
- while(ptr < ptrEnd && pos < byteLength){
6345
- var count = buffer[pos++];
6346
- var isEncodedRun = count > 128;
6347
- if (isEncodedRun) count -= 128;
6348
- if (count === 0 || ptr + count > ptrEnd) throw "HDRDecoder: bad scanline data";
6349
- if (isEncodedRun) {
6350
- var byteValue = buffer[pos++];
6351
- for(var i = 0; i < count; i++)scanLineBuffer[ptr++] = byteValue;
6352
- } else {
6353
- scanLineBuffer.set(buffer.subarray(pos, pos + count), ptr);
6354
- ptr += count;
6355
- pos += count;
6356
- }
6357
- }
6358
- for(var i1 = 0; i1 < width; i1++, offset += 4){
6359
- dataRGBA[offset] = scanLineBuffer[i1];
6360
- dataRGBA[offset + 1] = scanLineBuffer[i1 + width];
6361
- dataRGBA[offset + 2] = scanLineBuffer[i1 + width * 2];
6362
- dataRGBA[offset + 3] = scanLineBuffer[i1 + width * 3];
6363
- }
6364
- numScanLines--;
6150
+ _proto._loadFromAtlas = function _loadFromAtlas(resourceManager, data) {
6151
+ var _this = this;
6152
+ return resourceManager// @ts-ignore
6153
+ .getResourceByRef(data.belongToAtlas).then(function(atlas) {
6154
+ return atlas.getSprite(data.fullPath) || _this._loadFromTexture(resourceManager, data);
6155
+ });
6156
+ };
6157
+ _proto._loadFromTexture = function _loadFromTexture(resourceManager, data) {
6158
+ if (data.texture) {
6159
+ return resourceManager// @ts-ignore
6160
+ .getResourceByRef(data.texture).then(function(texture) {
6161
+ var sprite = new engineCore.Sprite(resourceManager.engine, texture, data.region, data.pivot, data.border);
6162
+ var width = data.width, height = data.height;
6163
+ width === undefined || (sprite.width = width);
6164
+ height === undefined || (sprite.height = height);
6165
+ return sprite;
6166
+ });
6167
+ } else {
6168
+ return new engineCore.AssetPromise(function(resolve) {
6169
+ var sprite = new engineCore.Sprite(resourceManager.engine, null, data.region, data.pivot, data.border);
6170
+ var width = data.width, height = data.height;
6171
+ width === undefined || (sprite.width = width);
6172
+ height === undefined || (sprite.height = height);
6173
+ resolve(sprite);
6174
+ });
6365
6175
  }
6366
- return dataRGBA;
6367
6176
  };
6368
- return HDRDecoder;
6369
- }();
6370
- // Float32 to Float16 lookup tables (http://www.fox-toolkit.org/ftp/fasthalffloatconversion.pdf)
6371
- HDRDecoder._float2HalfTables = HDRDecoder._generateFloat2HalfTables();
6372
- HDRDecoder._floatView = new Float32Array(1);
6373
- HDRDecoder._uint32View = new Uint32Array(HDRDecoder._floatView.buffer);
6374
- HDRDecoder._one = 0x3c00 // Half float for 1.0
6375
- ;
6376
- // prettier-ignore
6377
- HDRDecoder._faces = [
6378
- /* +X */ [
6379
- 1,
6380
- -1,
6381
- -1,
6382
- 1,
6383
- -1,
6384
- 1,
6385
- 1,
6386
- 1,
6387
- -1,
6388
- 1,
6389
- 1,
6390
- 1
6391
- ],
6392
- /* -X */ [
6393
- -1,
6394
- -1,
6395
- 1,
6396
- -1,
6397
- -1,
6398
- -1,
6399
- -1,
6400
- 1,
6401
- 1,
6402
- -1,
6403
- 1,
6404
- -1
6405
- ],
6406
- /* +Y */ [
6407
- -1,
6408
- -1,
6409
- 1,
6410
- 1,
6411
- -1,
6412
- 1,
6413
- -1,
6414
- -1,
6415
- -1,
6416
- 1,
6417
- -1,
6418
- -1
6419
- ],
6420
- /* -Y */ [
6421
- -1,
6422
- 1,
6423
- -1,
6424
- 1,
6425
- 1,
6426
- -1,
6427
- -1,
6428
- 1,
6429
- 1,
6430
- 1,
6431
- 1,
6432
- 1
6433
- ],
6434
- /* +Z */ [
6435
- -1,
6436
- -1,
6437
- -1,
6438
- 1,
6439
- -1,
6440
- -1,
6441
- -1,
6442
- 1,
6443
- -1,
6444
- 1,
6445
- 1,
6446
- -1
6447
- ],
6448
- /* -Z */ [
6449
- 1,
6450
- -1,
6451
- 1,
6452
- -1,
6453
- -1,
6454
- 1,
6455
- 1,
6456
- 1,
6457
- 1,
6458
- -1,
6459
- 1,
6460
- 1
6461
- ]
6462
- ];
6177
+ return SpriteLoader;
6178
+ }(engineCore.Loader);
6179
+ SpriteLoader = __decorate([
6180
+ engineCore.resourceLoader(engineCore.AssetType.Sprite, [
6181
+ "sprite"
6182
+ ])
6183
+ ], SpriteLoader);
6184
+
6185
+ var TextLoader = /*#__PURE__*/ function(Loader) {
6186
+ _inherits(TextLoader, Loader);
6187
+ function TextLoader() {
6188
+ return Loader.apply(this, arguments) || this;
6189
+ }
6190
+ var _proto = TextLoader.prototype;
6191
+ _proto.load = function load(item, resourceManager) {
6192
+ // @ts-ignore
6193
+ return resourceManager._request(item.url, _extends({}, item, {
6194
+ type: "text"
6195
+ })).then(function(text) {
6196
+ var asset = new engineCore.TextAsset(resourceManager.engine);
6197
+ asset.text = text;
6198
+ return asset;
6199
+ });
6200
+ };
6201
+ return TextLoader;
6202
+ }(engineCore.Loader);
6203
+ TextLoader = __decorate([
6204
+ engineCore.resourceLoader(engineCore.AssetType.Text, [
6205
+ "txt"
6206
+ ])
6207
+ ], TextLoader);
6463
6208
 
6464
- var TextureCubeLoader = /*#__PURE__*/ function(Loader) {
6465
- _inherits(TextureCubeLoader, Loader);
6466
- function TextureCubeLoader() {
6209
+ var TextureLoader = /*#__PURE__*/ function(Loader) {
6210
+ _inherits(TextureLoader, Loader);
6211
+ function TextureLoader() {
6467
6212
  return Loader.apply(this, arguments) || this;
6468
6213
  }
6469
- var _proto = TextureCubeLoader.prototype;
6214
+ var _proto = TextureLoader.prototype;
6470
6215
  _proto.load = function load(item, resourceManager) {
6216
+ var _this = this;
6217
+ var url = item.url;
6218
+ var requestConfig = _extends({}, item, {
6219
+ type: "arraybuffer"
6220
+ });
6221
+ return new engineCore.AssetPromise(function(resolve, reject, setTaskCompleteProgress, setTaskDetailProgress) {
6222
+ resourceManager// @ts-ignore
6223
+ ._request(url, requestConfig).onProgress(setTaskCompleteProgress, setTaskDetailProgress).then(function(buffer) {
6224
+ _this._decode(buffer, item, resourceManager).then(function(texture) {
6225
+ resourceManager.addContentRestorer(new TextureContentRestorer(texture, url, requestConfig));
6226
+ resolve(texture);
6227
+ }, reject);
6228
+ }).catch(reject);
6229
+ });
6230
+ };
6231
+ _proto._decode = function _decode(buffer, item, resourceManager) {
6232
+ if (FileHeader.checkMagic(buffer)) {
6233
+ return decode(buffer, resourceManager.engine);
6234
+ }
6235
+ var bufferView = new Uint8Array(buffer);
6236
+ var isHDR = bufferView[0] === 0x23 && bufferView[1] === 0x3f;
6237
+ if (isHDR) {
6238
+ return this._decodeHDR(bufferView, item, resourceManager);
6239
+ }
6240
+ return this._decodeImage(buffer, item, resourceManager);
6241
+ };
6242
+ _proto._decodeHDR = function _decodeHDR(buffer, item, resourceManager) {
6243
+ var _this = this;
6471
6244
  return new engineCore.AssetPromise(function(resolve, reject) {
6472
6245
  var engine = resourceManager.engine;
6473
- var url = item.url;
6474
- var requestConfig = _extends({}, item, {
6475
- type: "arraybuffer"
6476
- });
6477
- resourceManager// @ts-ignore
6478
- ._request(url, requestConfig).then(function(buffer) {
6479
- if (!engineCore.SystemInfo.supportsTextureFormat(engine, engineCore.TextureFormat.R16G16B16A16)) {
6480
- reject(new Error("TextureCubeLoader: HDR texture requires half float support."));
6481
- return;
6482
- }
6246
+ if (!engineCore.SystemInfo.supportsTextureFormat(engine, engineCore.TextureFormat.R16G16B16A16)) {
6247
+ reject(new Error("TextureLoader: HDR texture requires half float support."));
6248
+ return;
6249
+ }
6250
+ var _HDRDecoder_decode = HDRDecoder.decode(buffer), width = _HDRDecoder_decode.width, height = _HDRDecoder_decode.height, pixels = _HDRDecoder_decode.pixels;
6251
+ var _item_params;
6252
+ var _ref = (_item_params = item.params) != null ? _item_params : {}, _ref_mipmap = _ref.mipmap, mipmap = _ref_mipmap === void 0 ? true : _ref_mipmap;
6253
+ var texture = new engineCore.Texture2D(engine, width, height, engineCore.TextureFormat.R16G16B16A16, mipmap, false);
6254
+ texture.setPixelBuffer(pixels);
6255
+ mipmap && texture.generateMipmaps();
6256
+ _this._applyParams(texture, item);
6257
+ resolve(texture);
6258
+ });
6259
+ };
6260
+ _proto._decodeImage = function _decodeImage(buffer, item, resourceManager) {
6261
+ var _this = this;
6262
+ return new engineCore.AssetPromise(function(resolve, reject) {
6263
+ var blob = new Blob([
6264
+ buffer
6265
+ ]);
6266
+ var img = new Image();
6267
+ img.onload = function() {
6268
+ URL.revokeObjectURL(img.src);
6483
6269
  var _item_params;
6484
- var _ref = (_item_params = item.params) != null ? _item_params : {}, _ref_mipmap = _ref.mipmap, mipmap = _ref_mipmap === void 0 ? true : _ref_mipmap, anisoLevel = _ref.anisoLevel, wrapModeU = _ref.wrapModeU, wrapModeV = _ref.wrapModeV, filterMode = _ref.filterMode;
6485
- var bufferArray = new Uint8Array(buffer);
6486
- var header = HDRDecoder.parseHeader(bufferArray);
6487
- var texture = new engineCore.TextureCube(engine, header.height >> 1, engineCore.TextureFormat.R16G16B16A16, mipmap, false);
6488
- HDRDecoder.decodeFaces(bufferArray, header, function(faceIndex, data) {
6489
- texture.setPixelBuffer(engineCore.TextureCubeFace.PositiveX + faceIndex, data, 0);
6490
- });
6491
- texture.generateMipmaps();
6492
- texture.anisoLevel = anisoLevel != null ? anisoLevel : texture.anisoLevel;
6493
- texture.filterMode = filterMode != null ? filterMode : texture.filterMode;
6494
- texture.wrapModeU = wrapModeU != null ? wrapModeU : texture.wrapModeU;
6495
- texture.wrapModeV = wrapModeV != null ? wrapModeV : texture.wrapModeV;
6496
- resourceManager.addContentRestorer(new HDRContentRestorer(texture, url, requestConfig));
6270
+ var _ref = (_item_params = item.params) != null ? _item_params : {}, _ref_format = _ref.format, format = _ref_format === void 0 ? engineCore.TextureFormat.R8G8B8A8 : _ref_format, _ref_isSRGBColorSpace = _ref.isSRGBColorSpace, isSRGBColorSpace = _ref_isSRGBColorSpace === void 0 ? true : _ref_isSRGBColorSpace, _ref_mipmap = _ref.mipmap, mipmap = _ref_mipmap === void 0 ? true : _ref_mipmap;
6271
+ var engine = resourceManager.engine;
6272
+ var width = img.width, height = img.height;
6273
+ var generateMipmap = engineCore.TextureUtils.supportGenerateMipmapsWithCorrection(engine, width, height, format, mipmap, isSRGBColorSpace);
6274
+ var texture = new engineCore.Texture2D(engine, width, height, format, generateMipmap, isSRGBColorSpace);
6275
+ texture.setImageSource(img);
6276
+ generateMipmap && texture.generateMipmaps();
6277
+ _this._applyParams(texture, item);
6497
6278
  resolve(texture);
6498
- }).catch(reject);
6279
+ };
6280
+ img.onerror = function(e) {
6281
+ URL.revokeObjectURL(img.src);
6282
+ reject(e);
6283
+ };
6284
+ img.src = URL.createObjectURL(blob);
6499
6285
  });
6500
6286
  };
6501
- return TextureCubeLoader;
6287
+ _proto._applyParams = function _applyParams(texture, item) {
6288
+ var _item_params;
6289
+ var _ref = (_item_params = item.params) != null ? _item_params : {}, anisoLevel = _ref.anisoLevel, wrapModeU = _ref.wrapModeU, wrapModeV = _ref.wrapModeV, filterMode = _ref.filterMode;
6290
+ texture.anisoLevel = anisoLevel != null ? anisoLevel : texture.anisoLevel;
6291
+ texture.filterMode = filterMode != null ? filterMode : texture.filterMode;
6292
+ texture.wrapModeU = wrapModeU != null ? wrapModeU : texture.wrapModeU;
6293
+ texture.wrapModeV = wrapModeV != null ? wrapModeV : texture.wrapModeV;
6294
+ var url = item.url;
6295
+ if (url.indexOf("data:") !== 0) {
6296
+ texture.name = url.substring(url.lastIndexOf("/") + 1);
6297
+ }
6298
+ };
6299
+ return TextureLoader;
6502
6300
  }(engineCore.Loader);
6503
- TextureCubeLoader = __decorate([
6504
- engineCore.resourceLoader(engineCore.AssetType.TextureCube, [
6505
- "texCube",
6301
+ TextureLoader = __decorate([
6302
+ engineCore.resourceLoader(engineCore.AssetType.Texture, [
6303
+ "tex",
6304
+ "png",
6305
+ "jpg",
6306
+ "webp",
6307
+ "jpeg",
6506
6308
  "hdr"
6507
6309
  ])
6508
- ], TextureCubeLoader);
6509
- var HDRContentRestorer = /*#__PURE__*/ function(ContentRestorer) {
6510
- _inherits(HDRContentRestorer, ContentRestorer);
6511
- function HDRContentRestorer(resource, url, requestConfig) {
6310
+ ], TextureLoader);
6311
+ var TextureContentRestorer = /*#__PURE__*/ function(ContentRestorer) {
6312
+ _inherits(TextureContentRestorer, ContentRestorer);
6313
+ function TextureContentRestorer(resource, url, requestConfig) {
6512
6314
  var _this;
6513
6315
  _this = ContentRestorer.call(this, resource) || this, _this.url = url, _this.requestConfig = requestConfig;
6514
6316
  return _this;
6515
6317
  }
6516
- var _proto = HDRContentRestorer.prototype;
6318
+ var _proto = TextureContentRestorer.prototype;
6517
6319
  _proto.restoreContent = function restoreContent() {
6518
6320
  var _this = this;
6519
- return new engineCore.AssetPromise(function(resolve, reject) {
6520
- var resource = _this.resource;
6521
- resource.engine.resourceManager// @ts-ignore
6522
- ._request(_this.url, _this.requestConfig).then(function(buffer) {
6523
- var bufferArray = new Uint8Array(buffer);
6524
- HDRDecoder.decodeFaces(bufferArray, HDRDecoder.parseHeader(bufferArray), function(faceIndex, data) {
6525
- resource.setPixelBuffer(engineCore.TextureCubeFace.PositiveX + faceIndex, data, 0);
6526
- });
6527
- resource.generateMipmaps();
6528
- resolve(resource);
6529
- }).catch(reject);
6321
+ return this.resource.engine.resourceManager// @ts-ignore
6322
+ ._request(this.url, this.requestConfig).then(function(buffer) {
6323
+ if (FileHeader.checkMagic(buffer)) {
6324
+ return decode(buffer, _this.resource.engine, _this.resource);
6325
+ }
6326
+ var bufferView = new Uint8Array(buffer);
6327
+ var texture = _this.resource;
6328
+ if (bufferView[0] === 0x23 && bufferView[1] === 0x3f) {
6329
+ var pixels = HDRDecoder.decode(bufferView).pixels;
6330
+ texture.setPixelBuffer(pixels);
6331
+ texture.mipmapCount > 1 && texture.generateMipmaps();
6332
+ return texture;
6333
+ }
6334
+ return new engineCore.AssetPromise(function(resolve, reject) {
6335
+ var blob = new Blob([
6336
+ buffer
6337
+ ]);
6338
+ var img = new Image();
6339
+ img.onload = function() {
6340
+ URL.revokeObjectURL(img.src);
6341
+ texture.setImageSource(img);
6342
+ texture.mipmapCount > 1 && texture.generateMipmaps();
6343
+ resolve(texture);
6344
+ };
6345
+ img.onerror = function(e) {
6346
+ URL.revokeObjectURL(img.src);
6347
+ reject(e);
6348
+ };
6349
+ img.src = URL.createObjectURL(blob);
6350
+ });
6530
6351
  });
6531
6352
  };
6532
- return HDRContentRestorer;
6353
+ return TextureContentRestorer;
6533
6354
  }(engineCore.ContentRestorer);
6534
6355
 
6535
6356
  var AudioLoader = /*#__PURE__*/ function(Loader) {
@@ -6547,8 +6368,7 @@ var AudioLoader = /*#__PURE__*/ function(Loader) {
6547
6368
  resourceManager// @ts-ignore
6548
6369
  ._request(url, requestConfig).then(function(arrayBuffer) {
6549
6370
  var audioClip = new engineCore.AudioClip(resourceManager.engine);
6550
- // @ts-ignore
6551
- engineCore.AudioManager.getContext().decodeAudioData(arrayBuffer).then(function(result) {
6371
+ AudioLoader._getDecodeContext().decodeAudioData(arrayBuffer).then(function(result) {
6552
6372
  // @ts-ignore
6553
6373
  audioClip._setAudioSource(result);
6554
6374
  if (url.indexOf("data:") !== 0) {
@@ -6564,6 +6384,12 @@ var AudioLoader = /*#__PURE__*/ function(Loader) {
6564
6384
  });
6565
6385
  });
6566
6386
  };
6387
+ AudioLoader._getDecodeContext = function _getDecodeContext() {
6388
+ var _AudioLoader;
6389
+ // length/channels are decode-only placeholders; 44100 is the safest cross-browser rate.
6390
+ // decodeAudioData resamples once to this rate then again to the playback rate, so pitch/duration are unaffected
6391
+ return (_AudioLoader = AudioLoader)._decodeContext || (_AudioLoader._decodeContext = new OfflineAudioContext(1, 1, 44100));
6392
+ };
6567
6393
  return AudioLoader;
6568
6394
  }(engineCore.Loader);
6569
6395
  AudioLoader = __decorate([
@@ -6571,58 +6397,12 @@ AudioLoader = __decorate([
6571
6397
  "mp3",
6572
6398
  "ogg",
6573
6399
  "wav",
6574
- "audio",
6575
6400
  "m4a",
6576
6401
  "aac",
6577
6402
  "flac"
6578
6403
  ])
6579
6404
  ], AudioLoader);
6580
6405
 
6581
- var ShaderChunkLoader = /*#__PURE__*/ function(Loader) {
6582
- _inherits(ShaderChunkLoader, Loader);
6583
- function ShaderChunkLoader() {
6584
- return Loader.apply(this, arguments) || this;
6585
- }
6586
- var _proto = ShaderChunkLoader.prototype;
6587
- _proto.load = function load(item, resourceManager) {
6588
- var url = item.url;
6589
- // @ts-ignore
6590
- return resourceManager._request(url, _extends({}, item, {
6591
- type: "text"
6592
- })).then(function(code) {
6593
- engineCore.ShaderFactory.registerInclude(url.substring(1), code);
6594
- return ShaderChunkLoader._loadChunksInCode(code, url, resourceManager);
6595
- });
6596
- };
6597
- /**
6598
- * @internal
6599
- */ ShaderChunkLoader._loadChunksInCode = function _loadChunksInCode(code, basePath, resourceManager) {
6600
- var shaderChunkPaths = new Array();
6601
- var matches = code.matchAll(ShaderChunkLoader._shaderIncludeRegex);
6602
- for(var _iterator = _create_for_of_iterator_helper_loose(matches), _step; !(_step = _iterator()).done;){
6603
- var match = _step.value;
6604
- var chunkPath = engineCore.Utils.resolveAbsoluteUrl(basePath, match[1]);
6605
- if (!engineCore.ShaderLib[chunkPath.substring(1)]) {
6606
- shaderChunkPaths.push(chunkPath);
6607
- }
6608
- }
6609
- return Promise.all(shaderChunkPaths.map(function(chunkPath) {
6610
- // @ts-ignore
6611
- return resourceManager.load({
6612
- type: "ShaderChunk",
6613
- url: chunkPath
6614
- });
6615
- }));
6616
- };
6617
- return ShaderChunkLoader;
6618
- }(engineCore.Loader);
6619
- ShaderChunkLoader._shaderIncludeRegex = /#include\s+"([./][^\\"]+)"/gm;
6620
- ShaderChunkLoader = __decorate([
6621
- engineCore.resourceLoader("ShaderChunk", [
6622
- "glsl"
6623
- ])
6624
- ], ShaderChunkLoader);
6625
-
6626
6406
  var ShaderLoader = /*#__PURE__*/ function(Loader) {
6627
6407
  _inherits(ShaderLoader, Loader);
6628
6408
  function ShaderLoader() {
@@ -6630,32 +6410,29 @@ var ShaderLoader = /*#__PURE__*/ function(Loader) {
6630
6410
  }
6631
6411
  var _proto = ShaderLoader.prototype;
6632
6412
  _proto.load = function load(item, resourceManager) {
6633
- var _this = this;
6634
6413
  var url = item.url;
6414
+ if (url.endsWith(".shaderc")) {
6415
+ // @ts-ignore
6416
+ return resourceManager._request(url, _extends({}, item, {
6417
+ type: "json"
6418
+ })).then(function(data) {
6419
+ // @ts-ignore - _createFromPrecompiled is @internal
6420
+ return engineCore.Shader._createFromPrecompiled(data);
6421
+ });
6422
+ }
6635
6423
  // @ts-ignore
6636
6424
  return resourceManager._request(url, _extends({}, item, {
6637
6425
  type: "text"
6638
6426
  })).then(function(code) {
6639
- var builtinShader = _this._getBuiltinShader(code);
6640
- if (builtinShader) {
6641
- return engineCore.Shader.find(builtinShader);
6642
- }
6643
- return ShaderChunkLoader._loadChunksInCode(code, url, resourceManager).then(function() {
6644
- var shader = engineCore.Shader.create(code, undefined, url);
6645
- return shader;
6646
- });
6427
+ return engineCore.Shader.create(code, undefined, url);
6647
6428
  });
6648
6429
  };
6649
- _proto._getBuiltinShader = function _getBuiltinShader(code) {
6650
- var match = code.match(ShaderLoader._builtinRegex);
6651
- if (match && match[1]) return match[1];
6652
- };
6653
6430
  return ShaderLoader;
6654
6431
  }(engineCore.Loader);
6655
- ShaderLoader._builtinRegex = /^\s*\/\/\s*@builtin\s+(\w+)/;
6656
6432
  ShaderLoader = __decorate([
6657
6433
  engineCore.resourceLoader(engineCore.AssetType.Shader, [
6658
- "shader"
6434
+ "shader",
6435
+ "shaderc"
6659
6436
  ])
6660
6437
  ], ShaderLoader);
6661
6438
 
@@ -6735,6 +6512,122 @@ RenderTargetLoader = __decorate([
6735
6512
  ])
6736
6513
  ], RenderTargetLoader);
6737
6514
 
6515
+ function loadRef(refs, index, resourceManager, label) {
6516
+ var ref = resolveRefItem(refs, index, "SceneLoader", label);
6517
+ // @ts-ignore
6518
+ return resourceManager.getResourceByRef(ref);
6519
+ }
6520
+ /**
6521
+ * Apply scene-level data (ambient, background, shadow, fog, AO) to a Scene.
6522
+ * @internal
6523
+ */ function applySceneData(scene, sceneData, resourceManager, refs) {
6524
+ var promises = [];
6525
+ try {
6526
+ // parse ambient light
6527
+ var ambient = sceneData.ambient;
6528
+ if (ambient) {
6529
+ var useCustomAmbient = ambient.specularMode === SpecularMode.Custom;
6530
+ var useSH = ambient.diffuseMode === engineCore.DiffuseMode.SphericalHarmonics;
6531
+ scene.ambientLight.diffuseIntensity = ambient.diffuseIntensity;
6532
+ scene.ambientLight.specularIntensity = ambient.specularIntensity;
6533
+ scene.ambientLight.diffuseMode = ambient.diffuseMode;
6534
+ var solidColor = ambient.diffuseSolidColor;
6535
+ if (solidColor) {
6536
+ scene.ambientLight.diffuseSolidColor.set(solidColor[0], solidColor[1], solidColor[2], solidColor[3]);
6537
+ }
6538
+ if (useCustomAmbient && ambient.customAmbientLight != null) {
6539
+ promises.push(loadRef(refs, ambient.customAmbientLight, resourceManager, "scene.ambient.customAmbientLight").then(function(ambientLight) {
6540
+ scene.ambientLight.specularTexture = ambientLight == null ? void 0 : ambientLight.specularTexture;
6541
+ }));
6542
+ }
6543
+ if (ambient.ambientLight != null && (!useCustomAmbient || useSH)) {
6544
+ promises.push(loadRef(refs, ambient.ambientLight, resourceManager, "scene.ambient.ambientLight").then(function(ambientLight) {
6545
+ if (!useCustomAmbient) {
6546
+ scene.ambientLight.specularTexture = ambientLight == null ? void 0 : ambientLight.specularTexture;
6547
+ }
6548
+ if (useSH) {
6549
+ scene.ambientLight.diffuseSphericalHarmonics = ambientLight == null ? void 0 : ambientLight.diffuseSphericalHarmonics;
6550
+ }
6551
+ }));
6552
+ }
6553
+ }
6554
+ // parse background
6555
+ var background = sceneData.background;
6556
+ scene.background.mode = background.mode;
6557
+ switch(scene.background.mode){
6558
+ case engineCore.BackgroundMode.SolidColor:
6559
+ {
6560
+ var color = background.color;
6561
+ scene.background.solidColor.set(color[0], color[1], color[2], color[3]);
6562
+ break;
6563
+ }
6564
+ case engineCore.BackgroundMode.Sky:
6565
+ if (background.skyMesh != null && background.skyMaterial != null) {
6566
+ promises.push(loadRef(refs, background.skyMesh, resourceManager, "scene.background.skyMesh").then(function(mesh) {
6567
+ scene.background.sky.mesh = mesh;
6568
+ }), loadRef(refs, background.skyMaterial, resourceManager, "scene.background.skyMaterial").then(function(material) {
6569
+ scene.background.sky.material = material;
6570
+ }));
6571
+ } else {
6572
+ engineCore.Logger.warn("Sky background mode requires skyMesh and skyMaterial");
6573
+ }
6574
+ break;
6575
+ case engineCore.BackgroundMode.Texture:
6576
+ if (background.texture != null) {
6577
+ promises.push(loadRef(refs, background.texture, resourceManager, "scene.background.texture").then(function(texture) {
6578
+ scene.background.texture = texture;
6579
+ }));
6580
+ var _background_textureFillMode;
6581
+ scene.background.textureFillMode = (_background_textureFillMode = background.textureFillMode) != null ? _background_textureFillMode : scene.background.textureFillMode;
6582
+ }
6583
+ break;
6584
+ }
6585
+ } catch (error) {
6586
+ return Promise.reject(error);
6587
+ }
6588
+ // parse shadow
6589
+ var shadow = sceneData.shadow;
6590
+ if (shadow) {
6591
+ if (shadow.castShadows != undefined) scene.castShadows = shadow.castShadows;
6592
+ if (shadow.shadowResolution != undefined) scene.shadowResolution = shadow.shadowResolution;
6593
+ if (shadow.shadowDistance != undefined) scene.shadowDistance = shadow.shadowDistance;
6594
+ if (shadow.shadowCascades != undefined) scene.shadowCascades = shadow.shadowCascades;
6595
+ if (shadow.enableTransparentShadow != undefined) scene.enableTransparentShadow = shadow.enableTransparentShadow;
6596
+ if (shadow.shadowTwoCascadeSplits != undefined) scene.shadowTwoCascadeSplits = shadow.shadowTwoCascadeSplits;
6597
+ if (shadow.shadowFourCascadeSplits) {
6598
+ var splits = shadow.shadowFourCascadeSplits;
6599
+ scene.shadowFourCascadeSplits.set(splits[0], splits[1], splits[2]);
6600
+ }
6601
+ if (shadow.shadowFadeBorder != undefined) scene.shadowFadeBorder = shadow.shadowFadeBorder;
6602
+ }
6603
+ // parse fog
6604
+ var fog = sceneData.fog;
6605
+ if (fog) {
6606
+ if (fog.fogMode != undefined) scene.fogMode = fog.fogMode;
6607
+ if (fog.fogStart != undefined) scene.fogStart = fog.fogStart;
6608
+ if (fog.fogEnd != undefined) scene.fogEnd = fog.fogEnd;
6609
+ if (fog.fogDensity != undefined) scene.fogDensity = fog.fogDensity;
6610
+ if (fog.fogColor) scene.fogColor.set(fog.fogColor[0], fog.fogColor[1], fog.fogColor[2], fog.fogColor[3]);
6611
+ }
6612
+ // Post Process
6613
+ if (sceneData.postProcess) {
6614
+ engineCore.Logger.warn("Post Process is not supported in scene yet, please add PostProcess component in entity instead.");
6615
+ }
6616
+ // Ambient Occlusion
6617
+ var ambientOcclusion = sceneData.ambientOcclusion;
6618
+ if (ambientOcclusion) {
6619
+ var sceneAO = scene.ambientOcclusion;
6620
+ if (ambientOcclusion.enabledAmbientOcclusion != undefined) sceneAO.enabled = ambientOcclusion.enabledAmbientOcclusion;
6621
+ if (ambientOcclusion.quality != undefined) sceneAO.quality = ambientOcclusion.quality;
6622
+ if (ambientOcclusion.intensity != undefined) sceneAO.intensity = ambientOcclusion.intensity;
6623
+ if (ambientOcclusion.radius != undefined) sceneAO.radius = ambientOcclusion.radius;
6624
+ if (ambientOcclusion.bias != undefined) sceneAO.bias = ambientOcclusion.bias;
6625
+ if (ambientOcclusion.power != undefined) sceneAO.power = ambientOcclusion.power;
6626
+ if (ambientOcclusion.bilateralThreshold != undefined) sceneAO.bilateralThreshold = ambientOcclusion.bilateralThreshold;
6627
+ if (ambientOcclusion.minHorizonAngle != undefined) sceneAO.minHorizonAngle = ambientOcclusion.minHorizonAngle;
6628
+ }
6629
+ return Promise.all(promises).then(function() {});
6630
+ }
6738
6631
  var SceneLoader = /*#__PURE__*/ function(Loader) {
6739
6632
  _inherits(SceneLoader, Loader);
6740
6633
  function SceneLoader() {
@@ -6748,130 +6641,15 @@ var SceneLoader = /*#__PURE__*/ function(Loader) {
6748
6641
  ._request(item.url, _extends({}, item, {
6749
6642
  type: "json"
6750
6643
  })).then(function(data) {
6751
- var _data_name;
6752
- var scene = new engineCore.Scene(engine, (_data_name = data.name) != null ? _data_name : "");
6644
+ var _data_scene_name;
6645
+ var scene = new engineCore.Scene(engine, (_data_scene_name = data.scene.name) != null ? _data_scene_name : "");
6753
6646
  var context = new ParserContext(engine, ParserType.Scene, scene);
6754
6647
  var parser = new SceneParser(data, context, scene);
6755
6648
  parser._collectDependentAssets(data);
6756
6649
  context._setTaskCompleteProgress = setTaskCompleteProgress;
6757
6650
  parser.start();
6758
6651
  return parser.promise.then(function() {
6759
- var promises = [];
6760
- // parse ambient light
6761
- var ambient = data.scene.ambient;
6762
- if (ambient) {
6763
- var useCustomAmbient = ambient.specularMode === SpecularMode.Custom;
6764
- var useSH = ambient.diffuseMode === engineCore.DiffuseMode.SphericalHarmonics;
6765
- scene.ambientLight.diffuseIntensity = ambient.diffuseIntensity;
6766
- scene.ambientLight.specularIntensity = ambient.specularIntensity;
6767
- scene.ambientLight.diffuseMode = ambient.diffuseMode;
6768
- scene.ambientLight.diffuseSolidColor.copyFrom(ambient.diffuseSolidColor);
6769
- if (useCustomAmbient && ambient.customAmbientLight) {
6770
- promises.push(// @ts-ignore
6771
- resourceManager.getResourceByRef(ambient.customAmbientLight).then(function(ambientLight) {
6772
- scene.ambientLight.specularTexture = ambientLight == null ? void 0 : ambientLight.specularTexture;
6773
- }));
6774
- }
6775
- if (ambient.ambientLight && (!useCustomAmbient || useSH)) {
6776
- promises.push(// @ts-ignore
6777
- resourceManager.getResourceByRef(ambient.ambientLight).then(function(ambientLight) {
6778
- if (!useCustomAmbient) {
6779
- scene.ambientLight.specularTexture = ambientLight == null ? void 0 : ambientLight.specularTexture;
6780
- }
6781
- if (useSH) {
6782
- scene.ambientLight.diffuseSphericalHarmonics = ambientLight == null ? void 0 : ambientLight.diffuseSphericalHarmonics;
6783
- }
6784
- }));
6785
- }
6786
- }
6787
- // parse background
6788
- var background = data.scene.background;
6789
- scene.background.mode = background.mode;
6790
- switch(scene.background.mode){
6791
- case engineCore.BackgroundMode.SolidColor:
6792
- scene.background.solidColor.copyFrom(background.color);
6793
- break;
6794
- case engineCore.BackgroundMode.Sky:
6795
- if (background.skyMesh && background.skyMaterial) {
6796
- // @ts-ignore
6797
- var skyMeshPromise = resourceManager.getResourceByRef(background.skyMesh).then(function(mesh) {
6798
- scene.background.sky.mesh = mesh;
6799
- });
6800
- // @ts-ignore
6801
- // prettier-ignore
6802
- var skyMaterialPromise = resourceManager.getResourceByRef(background.skyMaterial).then(function(material) {
6803
- scene.background.sky.material = material;
6804
- });
6805
- promises.push(skyMeshPromise, skyMaterialPromise);
6806
- } else {
6807
- engineCore.Logger.warn("Sky background mode requires skyMesh and skyMaterial");
6808
- }
6809
- break;
6810
- case engineCore.BackgroundMode.Texture:
6811
- if (background.texture) {
6812
- // @ts-ignore
6813
- // prettier-ignore
6814
- var backgroundPromise = resourceManager.getResourceByRef(background.texture).then(function(texture) {
6815
- scene.background.texture = texture;
6816
- });
6817
- promises.push(backgroundPromise);
6818
- var _background_textureFillMode;
6819
- scene.background.textureFillMode = (_background_textureFillMode = background.textureFillMode) != null ? _background_textureFillMode : scene.background.textureFillMode;
6820
- }
6821
- break;
6822
- }
6823
- // parse shadow
6824
- var shadow = data.scene.shadow;
6825
- if (shadow) {
6826
- if (shadow.castShadows != undefined) scene.castShadows = shadow.castShadows;
6827
- if (shadow.shadowResolution != undefined) scene.shadowResolution = shadow.shadowResolution;
6828
- if (shadow.shadowDistance != undefined) scene.shadowDistance = shadow.shadowDistance;
6829
- if (shadow.shadowCascades != undefined) scene.shadowCascades = shadow.shadowCascades;
6830
- if (shadow.enableTransparentShadow != undefined) {
6831
- scene.enableTransparentShadow = shadow.enableTransparentShadow;
6832
- }
6833
- var _shadow_shadowTwoCascadeSplits;
6834
- scene.shadowTwoCascadeSplits = (_shadow_shadowTwoCascadeSplits = shadow.shadowTwoCascadeSplits) != null ? _shadow_shadowTwoCascadeSplits : scene.shadowTwoCascadeSplits;
6835
- shadow.shadowFourCascadeSplits && scene.shadowFourCascadeSplits.copyFrom(shadow.shadowFourCascadeSplits);
6836
- var _shadow_shadowFadeBorder;
6837
- scene.shadowFadeBorder = (_shadow_shadowFadeBorder = shadow.shadowFadeBorder) != null ? _shadow_shadowFadeBorder : scene.shadowFadeBorder;
6838
- }
6839
- // parse fog
6840
- var fog = data.scene.fog;
6841
- if (fog) {
6842
- if (fog.fogMode != undefined) scene.fogMode = fog.fogMode;
6843
- if (fog.fogStart != undefined) scene.fogStart = fog.fogStart;
6844
- if (fog.fogEnd != undefined) scene.fogEnd = fog.fogEnd;
6845
- if (fog.fogDensity != undefined) scene.fogDensity = fog.fogDensity;
6846
- if (fog.fogColor != undefined) scene.fogColor.copyFrom(fog.fogColor);
6847
- }
6848
- // parse physics
6849
- var physics = data.scene.physics;
6850
- // PhysicsScene has a native backing only when the engine was created with a physics backend.
6851
- // Keep scene files loadable for render-only engines by ignoring serialized physics settings there.
6852
- if (physics && engine._physicsInitialized) {
6853
- if (physics.gravity != undefined) scene.physics.gravity.copyFrom(physics.gravity);
6854
- if (physics.fixedTimeStep != undefined) scene.physics.fixedTimeStep = physics.fixedTimeStep;
6855
- }
6856
- // Post Process
6857
- var postProcessData = data.scene.postProcess;
6858
- if (postProcessData) {
6859
- engineCore.Logger.warn("Post Process is not supported in scene yet, please add PostProcess component in entity instead.");
6860
- }
6861
- // Ambient Occlusion
6862
- var ambientOcclusion = data.scene.ambientOcclusion;
6863
- if (ambientOcclusion) {
6864
- var sceneAmbientOcclusion = scene.ambientOcclusion;
6865
- sceneAmbientOcclusion.enabled = ambientOcclusion.enabledAmbientOcclusion;
6866
- sceneAmbientOcclusion.intensity = ambientOcclusion.intensity;
6867
- sceneAmbientOcclusion.radius = ambientOcclusion.radius;
6868
- sceneAmbientOcclusion.bias = ambientOcclusion.bias;
6869
- sceneAmbientOcclusion.power = ambientOcclusion.power;
6870
- sceneAmbientOcclusion.quality = ambientOcclusion.quality;
6871
- sceneAmbientOcclusion.bilateralThreshold = ambientOcclusion.bilateralThreshold;
6872
- sceneAmbientOcclusion.minHorizonAngle = ambientOcclusion.minHorizonAngle;
6873
- }
6874
- return Promise.all(promises).then(function() {
6652
+ return applySceneData(scene, data.scene, resourceManager, data.refs).then(function() {
6875
6653
  resolve(scene);
6876
6654
  });
6877
6655
  });