@arcgis/core 4.33.0-next.20250518 → 4.33.0-next.20250520

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 (106) hide show
  1. package/applications/Components/QuantityFormatter.js +1 -1
  2. package/assets/esri/core/workers/RemoteClient.js +1 -1
  3. package/assets/esri/core/workers/chunks/{6fa1a5b7276a037dbd6a.js → 2113da9429f6272339d7.js} +1 -1
  4. package/assets/esri/core/workers/chunks/{9c8224ca29475556e5ea.js → 26d3c9c6215c4076f943.js} +1 -1
  5. package/assets/esri/core/workers/chunks/{151d6354e7bc105b25c0.js → 585c7b485c42555ec554.js} +6 -6
  6. package/assets/esri/core/workers/chunks/62b2d3720693c93a60f2.js +1 -0
  7. package/assets/esri/core/workers/chunks/{9d5eac3bd1526e2b33e3.js → 8fda0a5b247385e68dc0.js} +1 -1
  8. package/assets/esri/core/workers/chunks/a22e5b2874647fe0d31a.js +1 -0
  9. package/assets/esri/themes/base/widgets/_FeatureFormUtilityNetworkAssociationLayers.scss +1 -1
  10. package/assets/esri/themes/base/widgets/_Legend.scss +0 -4
  11. package/assets/esri/themes/dark/main.css +1 -1
  12. package/assets/esri/themes/light/main.css +1 -1
  13. package/assets/esri/themes/light/view.css +1 -1
  14. package/assets/esri/views/magnifier/overlay.ts.svg +1 -1
  15. package/assets/esri/widgets/Directions/t9n/Directions_ar.json +1 -1
  16. package/assets/esri/widgets/Directions/t9n/Directions_bg.json +1 -1
  17. package/assets/esri/widgets/Directions/t9n/Directions_bs.json +1 -1
  18. package/assets/esri/widgets/Directions/t9n/Directions_ca.json +1 -1
  19. package/assets/esri/widgets/Directions/t9n/Directions_cs.json +1 -1
  20. package/assets/esri/widgets/Directions/t9n/Directions_da.json +1 -1
  21. package/assets/esri/widgets/Directions/t9n/Directions_de.json +1 -1
  22. package/assets/esri/widgets/Directions/t9n/Directions_el.json +1 -1
  23. package/assets/esri/widgets/Directions/t9n/Directions_es.json +1 -1
  24. package/assets/esri/widgets/Directions/t9n/Directions_et.json +1 -1
  25. package/assets/esri/widgets/Directions/t9n/Directions_fi.json +1 -1
  26. package/assets/esri/widgets/Directions/t9n/Directions_fr.json +1 -1
  27. package/assets/esri/widgets/Directions/t9n/Directions_he.json +1 -1
  28. package/assets/esri/widgets/Directions/t9n/Directions_hr.json +1 -1
  29. package/assets/esri/widgets/Directions/t9n/Directions_hu.json +1 -1
  30. package/assets/esri/widgets/Directions/t9n/Directions_id.json +1 -1
  31. package/assets/esri/widgets/Directions/t9n/Directions_it.json +1 -1
  32. package/assets/esri/widgets/Directions/t9n/Directions_ja.json +1 -1
  33. package/assets/esri/widgets/Directions/t9n/Directions_ko.json +1 -1
  34. package/assets/esri/widgets/Directions/t9n/Directions_lt.json +1 -1
  35. package/assets/esri/widgets/Directions/t9n/Directions_lv.json +1 -1
  36. package/assets/esri/widgets/Directions/t9n/Directions_nl.json +1 -1
  37. package/assets/esri/widgets/Directions/t9n/Directions_no.json +1 -1
  38. package/assets/esri/widgets/Directions/t9n/Directions_pl.json +1 -1
  39. package/assets/esri/widgets/Directions/t9n/Directions_pt-BR.json +1 -1
  40. package/assets/esri/widgets/Directions/t9n/Directions_pt-PT.json +1 -1
  41. package/assets/esri/widgets/Directions/t9n/Directions_ro.json +1 -1
  42. package/assets/esri/widgets/Directions/t9n/Directions_ru.json +1 -1
  43. package/assets/esri/widgets/Directions/t9n/Directions_sk.json +1 -1
  44. package/assets/esri/widgets/Directions/t9n/Directions_sl.json +1 -1
  45. package/assets/esri/widgets/Directions/t9n/Directions_sr.json +1 -1
  46. package/assets/esri/widgets/Directions/t9n/Directions_sv.json +1 -1
  47. package/assets/esri/widgets/Directions/t9n/Directions_th.json +1 -1
  48. package/assets/esri/widgets/Directions/t9n/Directions_tr.json +1 -1
  49. package/assets/esri/widgets/Directions/t9n/Directions_uk.json +1 -1
  50. package/assets/esri/widgets/Directions/t9n/Directions_vi.json +1 -1
  51. package/assets/esri/widgets/Directions/t9n/Directions_zh-CN.json +1 -1
  52. package/assets/esri/widgets/Directions/t9n/Directions_zh-HK.json +1 -1
  53. package/assets/esri/widgets/Directions/t9n/Directions_zh-TW.json +1 -1
  54. package/chunks/HUDMaterial.glsl.js +6 -6
  55. package/geometry/operators/densifyOperator.d.ts +1 -0
  56. package/geometry/operators/json/geodesicBufferOperator.js +1 -1
  57. package/interfaces.d.ts +28 -0
  58. package/layers/VideoLayer.js +1 -1
  59. package/layers/video/VideoController.js +1 -1
  60. package/package.json +2 -2
  61. package/rest/knowledgeGraph/GraphUpdateSearchIndexResult.js +5 -0
  62. package/rest/knowledgeGraph/wasmInterface/updateToWasmEncodedFactories.js +1 -1
  63. package/rest/knowledgeGraph/wasmInterface/wasmToDataModelChangeResponseFactories.js +1 -1
  64. package/rest/knowledgeGraphService.js +1 -1
  65. package/smartMapping/renderers/support/spikeUtils.js +1 -1
  66. package/support/revision.js +1 -1
  67. package/symbols/support/previewCIMSymbol.js +1 -1
  68. package/views/2d/engine/imagery/RasterBitmap.js +1 -1
  69. package/views/2d/layers/VideoLayerView2D.js +1 -1
  70. package/views/3d/layers/graphics/Deconflictor.js +1 -1
  71. package/views/3d/layers/graphics/Graphics3DMeshFillSymbolLayer.js +1 -1
  72. package/views/3d/layers/graphics/Graphics3DObjectSymbolLayer.js +1 -1
  73. package/views/3d/webgl-engine/effects/magnifier/Magnifier.js +1 -1
  74. package/views/3d/webgl-engine/lib/RenderingContext.js +1 -1
  75. package/views/3d/webgl-engine/parts/RenderView.js +1 -1
  76. package/views/3d/webgl-engine/shaders/HUDMaterial.glsl.js +1 -1
  77. package/views/VideoView.js +1 -1
  78. package/views/View2D.js +1 -1
  79. package/views/input/recognizers/DoubleTapDrag.js +1 -1
  80. package/views/input/recognizers/ImmediateDoubleClick.js +1 -1
  81. package/views/input/recognizers/PointerClickHoldAndDrag.js +1 -1
  82. package/views/input/recognizers/SingleAndDoubleClick.js +1 -1
  83. package/views/input/recognizers/support.js +1 -1
  84. package/views/magnifier/overlay-svg.js +1 -1
  85. package/views/ui/video/DefaultUIVideo.js +5 -0
  86. package/views/webgl/RenderingContext.js +1 -1
  87. package/views/webgl/checkWebGLError.js +1 -1
  88. package/widgets/AreaMeasurement3D/AreaMeasurement3DViewModel.js +1 -1
  89. package/widgets/AreaMeasurement3D.js +1 -1
  90. package/widgets/DirectLineMeasurement3D/DirectLineMeasurement3DViewModel.js +1 -1
  91. package/widgets/DirectLineMeasurement3D.js +1 -1
  92. package/widgets/ElevationProfile/support/geometryUtils.js +1 -1
  93. package/widgets/FeatureForm/FeatureFormUtilityNetworkAssociations/UtilityNetworkAssociationItemList.js +1 -1
  94. package/widgets/FeatureForm/UtilityNetworkAssociationAddAssociationViewModel.js +1 -1
  95. package/widgets/Legend/styles/support/sizeRampUtils.js +1 -1
  96. package/widgets/Legend/support/sizeRampUtils.js +1 -1
  97. package/widgets/LineOfSight/LineOfSightViewModel.js +1 -1
  98. package/widgets/LineOfSight.js +1 -1
  99. package/widgets/Slice/SliceViewModel.js +1 -1
  100. package/widgets/Slice.js +1 -1
  101. package/widgets/VideoPlayer.js +1 -1
  102. package/widgets/support/AnalysisViewModel.js +1 -1
  103. package/widgets/support/SelectionToolbar/SelectionToolbarViewModel.js +1 -1
  104. package/widgets/support/SelectionToolbar.js +1 -1
  105. package/assets/esri/core/workers/chunks/2873cb727c59328074db.js +0 -1
  106. package/assets/esri/core/workers/chunks/a937076d2f8c2b6a5d8a.js +0 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arcgis/core",
3
- "version": "4.33.0-next.20250518",
3
+ "version": "4.33.0-next.20250520",
4
4
  "homepage": "https://js.arcgis.com",
5
5
  "description": "ArcGIS Maps SDK for JavaScript: A complete 2D and 3D mapping and data visualization API",
6
6
  "keywords": [
@@ -28,7 +28,7 @@
28
28
  "@esri/arcgis-html-sanitizer": "~4.1.0",
29
29
  "@esri/calcite-components": "^3.2.0",
30
30
  "@vaadin/grid": "~24.7.6",
31
- "@zip.js/zip.js": "~2.7.61",
31
+ "@zip.js/zip.js": "~2.7.62",
32
32
  "luxon": "~3.6.1",
33
33
  "marked": "~15.0.11"
34
34
  },
@@ -0,0 +1,5 @@
1
+ /*
2
+ All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
+ See https://js.arcgis.com/4.33/esri/copyright.txt for details.
4
+ */
5
+ import{_ as r}from"../../chunks/tslib.es6.js";import o from"../../core/Accessor.js";import{property as e}from"../../core/accessorSupport/decorators/property.js";import"../../core/has.js";import"../../core/Logger.js";import"../../core/RandomLCG.js";import{subclass as s}from"../../core/accessorSupport/decorators/subclass.js";let t=class extends o{constructor(r){super(r),this.updatedKnowledgeGraph=null}};r([e()],t.prototype,"decoderError",void 0),r([e()],t.prototype,"updatedKnowledgeGraph",void 0),t=r([s("esri.rest.knowledgeGraph.GraphUpdateSearchIndexResult")],t);const p=t;export{p as default};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.33/esri/copyright.txt for details.
4
4
  */
5
- import e from"../../../core/Error.js";import t from"../../../geometry/Geometry.js";import{geometryToWasm as i}from"./queryToWasmEncodedFactories.js";import{EsriFieldTypes as n,EsriGeometryTypes as r,EsriGraphPropertyRole as a,NamedObjectTypes as o}from"./WasmDataModelWrapperInterfaces.js";function l(t,i){if(!t.typeName)throw new e("knowledge-graph:no-type-name","You must indicate the entity/relationship named object type to apply edits");if(!("originId"in t)){const e=new i.EntityValue;e.deleteLater(),e.type_name=t.typeName;for(const[n,r]of Object.entries(t.properties))e.set_key_value(n,g(r,i));return t.id&&e.set_id(t.id),e}if("originId"in t&&"destinationId"in t){const e=new i.RelationshipValue;e.deleteLater(),e.type_name=t.typeName;for(const[n,r]of Object.entries(t.properties))e.set_key_value(n,g(r,i));return t.id&&e.set_id(t.id),t.originId&&t.destinationId&&e.set_related_entity_ids(t.originId,t.destinationId),e}throw new e("knowledge-graph:applyEdits-encoding-failure","Could not determine the type of a named graph object passed to the encoder")}function s(e){return{xy_resolution:e.xyResolution,x_false_origin:e.xFalseOrigin,y_false_origin:e.yFalseOrigin,z_resolution:e.zResolution,z_false_origin:e.zFalseOrigin,m_resolution:e.mResolution,m_false_origin:e.mFalseOrigin}}function d(e,t){const i=new t.EntityType;return i.deleteLater(),m(e,t,i)}function u(e,t){const i=new t.RelationshipType;i.deleteLater();for(const n of e.endPoints){const e=new t.EndPoint;e.deleteLater(),e.origin_entity_type=n.originEntityType,e.dest_entity_type=n.destinationEntityType,i.add_end_point(e)}return m(e,t,i)}function y(e,t){const i=new t.EntityType;return i.deleteLater(),_(e,i)}function p(e,t){const i=new t.RelationshipType;return i.deleteLater(),_(e,i)}function f(e,t){const i=new t.GraphProperty;return i.deleteLater(),i.name=e.name,i.alias=e.alias??"",i.field_type={value:n[e.fieldType]},i.geometry_type={value:e.geometryType?r[e.geometryType]:r.esriGeometryNull},i.has_m=e.hasM??!1,i.has_z=e.hasZ??!1,i.nullable=e.nullable??!1,i.editable=e.editable,i.required=e.required,i.default_visibility=e.defaultVisibility,i.system_maintained=e.systemMaintained??!1,i.role={value:a[e.role]},i.default_value=g(e.defaultValue,t),i}function c(e,t){const i=new t.GraphProperty;return i.deleteLater(),e.hasOwnProperty("alias")&&(i.alias=e.alias),e.hasOwnProperty("editable")&&(i.editable=e.editable),e.hasOwnProperty("required")&&(i.required=e.required),e.hasOwnProperty("defaultVisibility")&&(i.default_visibility=e.defaultVisibility),e.hasOwnProperty("defaultValue")&&(i.default_value=g(e.defaultValue,t)),i}function m(e,t,i){i.name=e.name,i.alias=e.alias??"",i.role={value:o[e.role]},i.strict=e.strict;for(const n of e.properties){const e=f(n,t);i.add_property(e)}return i}function _(e,t){return e.hasOwnProperty("alias")&&(t.alias=e.alias),t}function g(e,n){return null==e?null:"object"!=typeof e||e instanceof Date?e:e instanceof t?i(e,n):null}export{d as entityTypeToWasm,f as graphPropertyToWasm,s as inputQuantizationParametersToWasmFormat,l as namedObjectToWasm,u as relationshipTypeToWasm,y as updateEntityTypeToWasm,c as updateGraphPropertyToWasm,p as updateRelationshipTypeToWasm};
5
+ import e from"../../../core/Error.js";import t from"../../../geometry/Geometry.js";import{geometryToWasm as n}from"./queryToWasmEncodedFactories.js";import{EsriFieldTypes as i,EsriGeometryTypes as r,EsriGraphPropertyRole as a,NamedObjectTypes as o}from"./WasmDataModelWrapperInterfaces.js";function s(t,n){if(!t.typeName)throw new e("knowledge-graph:no-type-name","You must indicate the entity/relationship named object type to apply edits");if(!("originId"in t)){const e=new n.EntityValue;e.deleteLater(),e.type_name=t.typeName;for(const[i,r]of Object.entries(t.properties))e.set_key_value(i,g(r,n));return t.id&&e.set_id(t.id),e}if("originId"in t&&"destinationId"in t){const e=new n.RelationshipValue;e.deleteLater(),e.type_name=t.typeName;for(const[i,r]of Object.entries(t.properties))e.set_key_value(i,g(r,n));return t.id&&e.set_id(t.id),t.originId&&t.destinationId&&e.set_related_entity_ids(t.originId,t.destinationId),e}throw new e("knowledge-graph:applyEdits-encoding-failure","Could not determine the type of a named graph object passed to the encoder")}function l(e){return{xy_resolution:e.xyResolution,x_false_origin:e.xFalseOrigin,y_false_origin:e.yFalseOrigin,z_resolution:e.zResolution,z_false_origin:e.zFalseOrigin,m_resolution:e.mResolution,m_false_origin:e.mFalseOrigin}}function d(e,t){const n=new t.EntityType;return n.deleteLater(),m(e,t,n)}function u(e,t){const n=new t.RelationshipType;n.deleteLater();for(const i of e.endPoints){const e=new t.EndPoint;e.deleteLater(),e.origin_entity_type=i.originEntityType,e.dest_entity_type=i.destinationEntityType,n.add_end_point(e)}return m(e,t,n)}function p(e,t){const n=new t.EntityType;return n.deleteLater(),h(e,n)}function y(e,t){const n=new t.RelationshipType;return n.deleteLater(),h(e,n)}function f(e,t){const n=new t.GraphProperty;return n.deleteLater(),n.name=e.name,n.alias=e.alias??"",n.field_type={value:i[e.fieldType]},n.geometry_type={value:e.geometryType?r[e.geometryType]:r.esriGeometryNull},n.has_m=e.hasM??!1,n.has_z=e.hasZ??!1,n.nullable=e.nullable??!1,n.editable=e.editable,n.required=e.required,n.default_visibility=e.defaultVisibility,n.system_maintained=e.systemMaintained??!1,n.role={value:a[e.role]},n.default_value=g(e.defaultValue,t),n}function c(e,t){const n=new t.GraphProperty;return n.deleteLater(),e.hasOwnProperty("alias")&&(n.alias=e.alias),e.hasOwnProperty("editable")&&(n.editable=e.editable),e.hasOwnProperty("required")&&(n.required=e.required),e.hasOwnProperty("defaultVisibility")&&(n.default_visibility=e.defaultVisibility),e.hasOwnProperty("defaultValue")&&(n.default_value=g(e.defaultValue,t)),n}function _(e,t){const n=new t.SearchIndexProperties;n.deleteLater();for(const i of e.propertyNames)n.add_search_property_name(i);return n}function m(e,t,n){n.name=e.name,n.alias=e.alias??"",n.role={value:o[e.role]},n.strict=e.strict;for(const i of e.properties){const e=f(i,t);n.add_property(e)}return n}function h(e,t){return e.hasOwnProperty("alias")&&(t.alias=e.alias),t}function g(e,i){return null==e?null:"object"!=typeof e||e instanceof Date?e:e instanceof t?n(e,i):null}export{d as entityTypeToWasm,f as graphPropertyToWasm,l as inputQuantizationParametersToWasmFormat,s as namedObjectToWasm,u as relationshipTypeToWasm,p as updateEntityTypeToWasm,c as updateGraphPropertyToWasm,y as updateRelationshipTypeToWasm,_ as updateSearchPropertiesToWasm};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.33/esri/copyright.txt for details.
4
4
  */
5
- import r from"../GraphAddNamedTypesResult.js";import e from"../GraphAddPropertyResult.js";import t from"../GraphDeleteNamedTypeResult.js";import o from"../GraphDeletePropertyResult.js";import s from"../GraphUpdateNamedTypesResult.js";import n from"../GraphUpdatePropertyResult.js";import{wasmErrorToEsriError as d}from"./wasmUtils.js";function p(e){const t=e.get_entity_type_add_results_count(),o=e.get_relationship_type_add_results_count(),s=new r({decoderError:d(e.error),entityAddResultsCount:t,relationshipAddResultsCount:o});for(let r=0;r<t;r++){const t=e.get_entity_type_add_results_at(r),o=t.get_name(),n=t.get_error();s.entityAddResults.push({typeName:o,error:d(n)})}for(let r=0;r<o;r++){const t=e.get_relationship_type_add_results_at(r),o=t.get_name(),n=t.get_error();s.relationshipAddResults.push({typeName:o,error:d(n)})}return s}function u(r){return new s({decoderError:d(r.error)})}function a(r){return new t({decoderError:d(r.error)})}function i(r){return new e({decoderError:d(r.error)})}function _(r){return new o({decoderError:d(r.error)})}function l(r){return new n({decoderError:d(r.error)})}export{i as decoderToAddGraphPropertiesResult,p as decoderToAddNamedTypesResult,_ as decoderToDeleteGraphPropertiesResult,a as decoderToDeleteNamedTypeResult,l as decoderToUpdateGraphPropertiesResult,u as decoderToUpdateNamedTypesResult};
5
+ import r from"../GraphAddNamedTypesResult.js";import e from"../GraphAddPropertyResult.js";import t from"../GraphDeleteNamedTypeResult.js";import o from"../GraphDeletePropertyResult.js";import n from"../GraphUpdateNamedTypesResult.js";import s from"../GraphUpdatePropertyResult.js";import{wasmErrorToEsriError as d}from"./wasmUtils.js";function p(e){const t=e.get_entity_type_add_results_count(),o=e.get_relationship_type_add_results_count(),n=new r({decoderError:d(e.error),entityAddResultsCount:t,relationshipAddResultsCount:o});for(let r=0;r<t;r++){const t=e.get_entity_type_add_results_at(r),o=t.get_name(),s=t.get_error();n.entityAddResults.push({typeName:o,error:d(s)})}for(let r=0;r<o;r++){const t=e.get_relationship_type_add_results_at(r),o=t.get_name(),s=t.get_error();n.relationshipAddResults.push({typeName:o,error:d(s)})}return n}function u(r){return new n({decoderError:d(r.error)})}function i(r){return new t({decoderError:d(r.error)})}function a(r){return new e({decoderError:d(r.error)})}function _(r){return new o({decoderError:d(r.error)})}function l(r){return new s({decoderError:d(r.error)})}function m(r){return new n({decoderError:d(r.error)})}export{a as decoderToAddGraphPropertiesResult,p as decoderToAddNamedTypesResult,_ as decoderToDeleteGraphPropertiesResult,i as decoderToDeleteNamedTypeResult,m as decoderToGraphUpdateSearchIndexResult,l as decoderToUpdateGraphPropertiesResult,u as decoderToUpdateNamedTypesResult};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.33/esri/copyright.txt for details.
4
4
  */
5
- import{id as e}from"../kernel.js";import t from"../request.js";import r from"../core/Error.js";import a from"../core/Logger.js";import{isAbortError as n}from"../core/promiseUtils.js";import o from"../geometry/Geometry.js";import d from"../geometry/SpatialReference.js";import{submitJob as i}from"./geoprocessor/submitJob.js";import s from"./knowledgeGraph/GraphQueryResult.js";import p from"./knowledgeGraph/GraphQueryResultHeader.js";import c from"./knowledgeGraph/GraphQueryStreamingResult.js";import l from"./knowledgeGraph/KnowledgeGraph.js";import u from"./knowledgeGraph/ServiceDefinition.js";import{encodeClientDataAtKeysRequest as h}from"./knowledgeGraph/wasmInterface/clientDataToWasmEncodedFactories.js";import{getWasmInterface as w}from"./knowledgeGraph/wasmInterface/knowledgeWasmAccess.js";import{bindParamArrayToWasm as y,setInputQuantizationParametersOnEncoder as g,setOutputQuantizationParametersOnEncoder as f,setProvenanceBehaviorOnEncoder as m,geometryToWasm as _,bindParamObjectToWasm as k}from"./knowledgeGraph/wasmInterface/queryToWasmEncodedFactories.js";import{updateGraphPropertyToWasm as b,graphPropertyToWasm as G,updateEntityTypeToWasm as T,updateRelationshipTypeToWasm as v,entityTypeToWasm as A,relationshipTypeToWasm as x,inputQuantizationParametersToWasmFormat as P,namedObjectToWasm as D}from"./knowledgeGraph/wasmInterface/updateToWasmEncodedFactories.js";import{wasmClientDataAllKeysResponseToClientDataKeys as S,wasmClientDataFetchResponseToClientData as R}from"./knowledgeGraph/wasmInterface/wasmToClientDataFactories.js";import{decoderToAddNamedTypesResult as E,decoderToDeleteNamedTypeResult as C,decoderToUpdateNamedTypesResult as M,decoderToAddGraphPropertiesResult as q,decoderToDeleteGraphPropertiesResult as j,decoderToUpdateGraphPropertiesResult as N}from"./knowledgeGraph/wasmInterface/wasmToDataModelChangeResponseFactories.js";import{wasmToDataModel as F}from"./knowledgeGraph/wasmInterface/wasmToDataModelFactories.js";import{wasmToGraphQueryResponseHeader as Q,decodedWasmObjToQueryResponseObj as K}from"./knowledgeGraph/wasmInterface/wasmToQueryResponseObjFactories.js";import{decoderToApplyEditsResponse as U}from"./knowledgeGraph/wasmInterface/wasmToUpdateResponseFactories.js";import{checkWasmError as L}from"./knowledgeGraph/wasmInterface/wasmUtils.js";const W=new Map,I=()=>new Map(W.entries()),$={fetchKnowledgeGraph:async e=>{const t=new l({url:e}),r=[];return r.push(oe(t)),r.push(de(t)),await Promise.all(r),t},refreshDataModel:async e=>{e.dataModel=await Fe(e)},refreshServiceDefinition:async e=>{const r=(await t(e.url,{query:{f:"json"}})).data;return r.capabilities=r?.capabilities?.split(","),r.supportedQueryFormats=r?.supportedQueryFormats?.split(","),e.serviceDefinition=new u(r),e.serviceDefinition},executeFindPathsAsynchronous:async(e,t)=>{const a=e.inKnowledgeGraphUrl.split("/rest/services");if(a.length<2)throw new r("knowledge-graph:invalid-tool-url","The URL for the KG Service was not correctly formatted. It should contain /reset/services/");const n=a[0];return await ue(`${n}/rest/services/System/KnowledgeGraphServerToolsAsync/GPServer/ServerFilteredFindPaths`,{in_knowledge_graph_url:e.inKnowledgeGraphUrl,config_type:"STRING",config_string:e.config.toJSON(),result_type:"STRING"},{},t)},executeFindPaths:async(e,t)=>{const a=e.inKnowledgeGraphUrl.split("/rest/services");if(a.length<2)throw new r("knowledge-graph:invalid-tool-url","The URL for the KG Service was not correctly formatted. It should contain /reset/services/");const n=a[0],o=await he(`${n}/rest/services/System/KnowledgeGraphServerTools/GPServer/ServerFilteredFindPaths/execute`,{method:"post",query:{f:"pjson",in_knowledge_graph_url:e.inKnowledgeGraphUrl,config_type:"STRING",config_string:JSON.stringify(e.config),result_type:"STRING"},...t});if(o.data.results.length<1)throw new r("knowledge-graph:no-results","No results were returned from the FindPaths tool - no results returned",o);let d;for(const r of o.data.results)if("out_results_string"===r.paramName){d=r.value;break}if(!d)throw new r("knowledge-graph:no-results","No results were returned from the FindPaths tool - no results were returned on the expected paramater out_results_string",o);return d},fetchAsynchronousFindPathsResultData:async(e,t)=>(await e.fetchResultData("out_results_string",null,t)).value,executeQueryStreaming:async(e,t,a)=>{const n="include",o=`${e.url}/graph/query`;await we(e);const d=await ve(o,a);if(!e.serviceDefinition?.supportsProvenance&&t.provenanceBehavior===n)throw new r("knowledge-graph:provenance-not-supported","The Knowledge Graph Service definition indicated that provenance is not supported");d.data.body=await Ge(t,e);const i=await le(d.data.url,d.data);if(e.dataModel){const t=await Ne(i,e.dataModel);return new c({resultRowsStream:t.readableStream,resultHeader:t.resultHeader})}throw new r("knowledge-graph:undefined-data-model","The KnowledgeGraph supplied did not have a data model")},executeApplyEdits:async(e,t,a)=>{if(e.serviceDefinition?.dataEditingNotSupported)throw new r("knowledge-graph:data-editing-not-supported","The Knowledge Graph Service definition indicated that data editing is not supported");const n=`${e.url}/graph/applyEdits`;await we(e);const o=await ve(n,a);o.data.body=await ge(t,e);return xe(await le(o.data.url,o.data))},executeAddNamedTypes:async(e,t,a)=>{if(!t.newEntityTypes?.length&&!t.newRelationshipTypes?.length)throw new r("knowledge-graph:no-arguments","The operation to add types to the data model contained no values");const n=`${e.url}/dataModel/edit/namedTypes/add`;await we(e);const o=await ve(n,a);o.data.body=await fe(t);const d=await le(o.data.url,o.data),i=await Pe(d);return i.updatedKnowledgeGraph=await ne(e.url),i},executeDeleteNamedType:async(e,t,a)=>{if(!t)throw new r("knowledge-graph:no-arguments","The operation to delete a named type from the data model contained no value");const n=`${e.url}/dataModel/edit/namedTypes/${t}/delete`;await we(e);const o=await ve(n,a);o.data.body="";const d=await le(o.data.url,o.data),i=await De(d);return i.updatedKnowledgeGraph=await ne(e.url),i},executeUpdateNamedType:async(e,t,a,n)=>{if(!t&&!Object.keys(a).length)throw new r("knowledge-graph:no-arguments","The operation to update types in the data model contained missing or empty values");const o=`${e.url}/dataModel/edit/namedTypes/${t}/update`;await we(e);const d=await ve(o,n);d.data.body=await me(a,t,e.dataModel);const i=await le(d.data.url,d.data),s=await Se(i);return s.updatedKnowledgeGraph=await ne(e.url),s},executeAddGraphProperties:async(e,t,a,n)=>{if(!t&&!a.length)throw new r("knowledge-graph:no-arguments","The operation to add properties to the data model contained missing or empty values");const o=`${e.url}/dataModel/edit/namedTypes/${t}/fields/add`;await we(e);const d=await ve(o,n);d.data.body=await _e(a);const i=await le(d.data.url,d.data),s=await Re(i);return s.updatedKnowledgeGraph=await ne(e.url),s},executeDeleteGraphProperty:async(e,t,a,n)=>{if(!t&&!a)throw new r("knowledge-graph:no-arguments","The operation to delete property contained missing or empty values");const o=`${e.url}/dataModel/edit/namedTypes/${t}/fields/delete`;await we(e);const d=await ve(o,n);d.data.body=await ke(a);const i=await le(d.data.url,d.data),s=await Ee(i);return s.updatedKnowledgeGraph=await ne(e.url),s},executeUpdateGraphProperty:async(e,t,a,n,o)=>{if(!t&&!a&&!Object.keys(n).length)throw new r("knowledge-graph:no-arguments","The operation to update properties in the data model contained missing or empty values");const d=`${e.url}/dataModel/edit/namedTypes/${t}/fields/update`;await we(e);const i=await ve(d,o);i.data.body=await be(a,n);const s=await le(i.data.url,i.data),p=await Ce(s);return p.updatedKnowledgeGraph=await ne(e.url),p},executeQuery:async(e,a,n)=>{const o=`${e.url}/graph/query`,d=await t(o,{responseType:"array-buffer",query:{f:"pbf",openCypherQuery:a.openCypherQuery,...n?.query},signal:n?.signal,timeout:n?.timeout}),i=d.getHeader?.("content-type"),p=d.data;if(i?.includes("application/x-protobuf")){const t=new((await w()).GraphQueryDecoder);if(t.deleteLater(),e.dataModel){const r=je({wasmQueryDecoder:t,newArrayBufferToParse:p,dataModel:e.dataModel});return new s({resultRows:r.resultRows,resultHeader:r.resultHeader})}throw new r("knowledge-graph:undefined-data-model","The KnowledgeGraph supplied did not have a data model")}throw new r("knowledge-graph:unexpected-server-response","server returned an unexpected response",{responseType:i,data:d.data})},executeSearch:async(e,a,n)=>{const o=a.typeCategoryFilter,d=`${e.url}/graph/search`,i=await t(d,{responseType:"array-buffer",query:{f:"pbf",searchQuery:`"${a.searchQuery}"`,typeCategoryFilter:o,...n?.query},signal:n?.signal,timeout:n?.timeout}),p=i.getHeader?.("content-type"),c=i.data;if(p?.includes("application/x-protobuf")){const t=new((await w()).GraphQueryDecoder);if(t.deleteLater(),e.dataModel){const r=je({wasmQueryDecoder:t,newArrayBufferToParse:c,dataModel:e.dataModel});return new s({resultRows:r.resultRows,resultHeader:r.resultHeader})}throw new r("knowledge-graph:undefined-data-model","The KnowledgeGraph supplied did not have a data model")}throw new r("knowledge-graph:unexpected-server-response","server returned an unexpected response",{responseType:p,data:i.data})},executeSearchStreaming:async(e,t,a)=>{const n=`${e.url}/graph/search`;await we(e);const o=await ve(n,a);o.data.body=await Te(t);const d=await le(o.data.url,o.data);if(e.dataModel){const t=await Ne(d,e.dataModel);return new c({resultRowsStream:t.readableStream,resultHeader:t.resultHeader})}throw new r("knowledge-graph:undefined-data-model","The KnowledgeGraph supplied did not have a data model")},fetchClientDataAtKeys:async(e,t,a={ignoreCache:!1})=>{if(!t.length)return new Map;let n=W.get(e.url||"");n||(n=new Map,W.set(e.url||"",n));const o=new Map(n.entries()),d=`${e.url}/clientData/fetch`;t=Array.from(new Set(t));const i=await w(),s=h(t,n,i,a.ignoreCache),p=await ve(d,a.requestOptions);p.data.body=s;const c=await le(p.data.url,p.data),l=c.headers.get("content-type");if(l?.includes("application/x-protobuf")){const e=new i.ClientDataFetchResponseDecoder;e.deleteLater();const t=await c.arrayBuffer();return e.decode(new Uint8Array(t)),e.has_error()&&L(e.error,"knowledge-graph:fetchClientDataAtKeys-decoding-error","An error occurred while decoding the client data keys response"),R(e,n,o,a.ignoreCache)}throw new r("knowledge-graph:unexpected-server-response","server returned an unexpected response when fetching client data",{responseType:l,data:c})},fetchAllClientDataKeys:async(e,a)=>{const n=`${e.url}/clientData`,o=await t(n,{responseType:"array-buffer",query:{f:"pbf"},signal:a?.signal,timeout:a?.timeout}),d=o.getHeader?.("content-type"),i=o.data;if(d?.includes("application/x-protobuf")){const e=new((await w()).ClientDataKeysResponseDecoder);return e.deleteLater(),e.decode(new Uint8Array(i)),e.has_error()&&L(e.error,"knowledge-graph:fetchAllClientDataKeys-decoding-error","An error occurred while decoding the client data keys response"),S(e)}throw new r("knowledge-graph:unexpected-server-response","server returned an unexpected response",{responseType:d,data:o.data})},clearClientDataCache:()=>W.clear(),_fetchWrapper:async(e,t)=>fetch(e,t),_submitJobWrapper:async(e,t,r,a)=>i(e,t,r,a),_esriRequestWrapper:async(e,r)=>t(e,r)};async function H(e,t,r){return $.executeApplyEdits(e,t,r)}async function O(e,t,r){return $.executeAddNamedTypes(e,t,r)}async function z(e,t,r){return $.executeDeleteNamedType(e,t,r)}async function B(e,t,r,a){return $.executeUpdateNamedType(e,t,r,a)}async function J(e,t,r,a){return $.executeAddGraphProperties(e,t,r,a)}async function V(e,t,r,a){return $.executeDeleteGraphProperty(e,t,r,a)}async function Y(e,t,r,a,n){return $.executeUpdateGraphProperty(e,t,r,a,n)}async function X(e,t,r){return $.executeQuery(e,t,r)}async function Z(e,t,r){return $.executeQueryStreaming(e,t,r)}async function ee(e,t,r){return $.executeSearch(e,t,r)}async function te(e,t,r){return $.executeSearchStreaming(e,t,r)}function re(e,t){return $.fetchAllClientDataKeys(e,t)}function ae(e,t,r){return $.fetchClientDataAtKeys(e,t,r)}async function ne(e){return $.fetchKnowledgeGraph(e)}async function oe(e){return $.refreshDataModel(e)}async function de(e){return $.refreshServiceDefinition(e)}async function ie(e,t){return $.executeFindPathsAsynchronous(e,t)}async function se(e,t){return $.executeFindPaths(e,t)}async function pe(e,t){return $.fetchAsynchronousFindPathsResultData(e,t)}function ce(){return $.clearClientDataCache()}async function le(e,t){return $._fetchWrapper(e,t)}async function ue(e,t,r,a){return $._submitJobWrapper(e,t,r,a)}async function he(e,t){return $._esriRequestWrapper(e,t)}async function we(t){const r=e?.findCredential(t.url);r||(t.dataModel?await Fe(t):await oe(t))}function ye(e,t,r,a){null==t?r.set_param_key_value(e,""):"object"!=typeof t||t instanceof Date?r.set_param_key_value(e,t):t instanceof o?r.set_param_key_value(e,_(t,a)):Array.isArray(t)?r.set_param_key_value(e,y(t,a)):r.set_param_key_value(e,k(t,a))}async function ge(e,t){if(t.dataModel||await oe(t),!t.dataModel)throw new r("knowledge-graph:data-model-undefined","Encoding could not proceed because a data model was not provided and it could not be determined from the service");const a=await w(),n=!!e.options?.cascadeDelete,o=new a.GraphApplyEditsEncoder(a.SpatialReferenceUtil.WGS84(),e.options?.inputQuantizationParameters?P(e.options?.inputQuantizationParameters):a.InputQuantizationUtil.WGS84_lossless());o.deleteLater(),o.cascade_delete=n;try{let t;e.entityAdds?.forEach((e=>{t=o.add_entity(D(e,a)),L(t,"knowledge-graph:applyEdits-encoding-failed","Attempting to encode the applyEdits - an entity failed to be added to the encoder")})),e.relationshipAdds?.forEach((e=>{if(!e.originId||!e.destinationId)throw new r("knowledge-graph:relationship-origin-destination-missing","When adding a new relationship, you must provide both an origin and destination id on the appropriate class property");t=o.add_relationship(D(e,a)),L(t,"knowledge-graph:applyEdits-encoding-failed","Attempting to encode the applyEdits - a relationship failed to be added to the encoder")})),e.entityUpdates?.forEach((e=>{if(!e.id)throw new r("knowledge-graph:entity-id-missing","When updating an entity or relationship, you must specify the id on the class level property");t=o.update_entity(D(e,a)),L(t,"knowledge-graph:applyEdits-encoding-failed","Attempting to encode the applyEdits - an entity failed to be added to the encoder")})),e.relationshipUpdates?.forEach((e=>{if(!e.id)throw new r("knowledge-graph:relationship-id-missing","When updating an entity or relationship, you must specify the id on the class level property");t=o.update_relationship(D(e,a)),L(t,"knowledge-graph:applyEdits-encoding-failed","Attempting to encode the applyEdits - a relationship failed to be added to the encoder")})),e.entityDeletes?.forEach((e=>{if(!e.typeName)throw new r("knowledge-graph:no-type-name","You must indicate the entity/relationship named object type to apply edits - delete");const t=o.make_delete_helper(e.typeName,!0);t.deleteLater(),e.ids?.forEach((e=>{t.delete_by_id(e)}))})),e.relationshipDeletes?.forEach((e=>{if(!e.typeName)throw new r("knowledge-graph:no-type-name","You must indicate the entity/relationship named object type to apply edits - delete");const t=o.make_delete_helper(e.typeName,!1);e.ids?.forEach((e=>{t.delete_by_id(e)}))})),o.encode()}catch(i){throw new r("knowledge-graph:applyEdits-encoding-failed","Attempting to encode the applyEdits failed",{error:i})}const d=o.get_encoding_result();return L(d.error,"knowledge-graph:applyEdits-encoding-failed","Attempting to encode the applyEdits failed"),structuredClone(d.get_byte_buffer())}async function fe(e){const t=await w(),a=new t.GraphNamedObjectTypeAddsRequestEncoder;a.deleteLater(),e.newEntityTypes?.forEach((e=>{a.add_entity_type(A(e,t))})),e.newRelationshipTypes?.forEach((e=>{a.add_relationship_type(x(e,t))}));try{a.encode()}catch(o){throw new r("knowledge-graph:addNamedTypes-encoding-failed","Attempting to encode the addNamedTypes failed",{error:o})}const n=a.get_encoding_result();return L(n.error,"knowledge-graph:addNamedTypes-encoding-failed","Attempting to encode the addNamedTypes failed"),structuredClone(n.get_byte_buffer())}async function me(e,t,a){const n=await w(),o=new n.GraphNamedObjectTypeUpdateRequestEncoder;o.deleteLater();if(a.entityTypes.some((e=>e.name===t)))o.update_entity_type(T(e,n));else{if(!a.relationshipTypes.some((e=>e.name===t)))throw new r("knowledge-graph:updateNamedType-encoding-failed","The named type you are trying to update does not exist in the data model");o.update_relationship_type(v(e,n))}o.update_alias=e.hasOwnProperty("alias");try{o.encode()}catch(i){throw new r("knowledge-graph:updateNamedType-encoding-failed","Attempting to encode the updateNamedType failed",{error:i})}const d=o.get_encoding_result();return L(d.error,"knowledge-graph:updateNamedType-encoding-failed","Attempting to encode the updateNamedType failed"),structuredClone(d.get_byte_buffer())}async function _e(e){const t=await w(),a=new t.GraphPropertyAddsRequestEncoder;a.deleteLater(),e.forEach((e=>{a.add_graph_property(G(e,t))}));try{a.encode()}catch(o){throw new r("knowledge-graph:addGraphProperties-encoding-failed","Attempting to encode the addGraphProperties failed",{error:o})}const n=a.get_encoding_result();return L(n.error,"knowledge-graph:addGraphProperties-encoding-failed","Attempting to encode the addGraphProperties failed"),structuredClone(n.get_byte_buffer())}async function ke(e){const t=new((await w()).GraphPropertyDeleteRequestEncoder);t.deleteLater(),t.field_name=e;try{t.encode()}catch(n){throw new r("knowledge-graph:deleteGraphProperty-encoding-failed","Attempting to encode the deleteGraphProperty failed",{error:n})}const a=t.get_encoding_result();return L(a.error,"knowledge-graph:deleteGraphProperty-encoding-failed","Attempting to encode the deleteGraphProperty failed"),structuredClone(a.get_byte_buffer())}async function be(e,t){const a=await w(),n=new a.GraphPropertyUpdateRequestEncoder;n.deleteLater(),n.update_graph_property(b(t,a)),n.set_property_name(e),n.update_alias=t.hasOwnProperty("alias"),n.update_editable=t.hasOwnProperty("editable"),n.update_required=t.hasOwnProperty("required"),n.update_visible=t.hasOwnProperty("defaultVisibility"),n.update_default_value=t.hasOwnProperty("defaultValue");try{n.encode()}catch(d){throw new r("knowledge-graph:updateGraphProperty-encoding-failed","Attempting to encode the updateGraphProperty failed",{error:d})}const o=n.get_encoding_result();return L(o.error,"knowledge-graph:updateGraphProperty-encoding-failed","Attempting to encode the updateGraphProperty failed"),structuredClone(o.get_byte_buffer())}async function Ge(e,t){const a=await w(),n=new a.GraphQueryRequestEncoder;if(n.deleteLater(),e.outputSpatialReference?n.output_spatial_reference={wkid:e.outputSpatialReference.wkid,latestWkid:e.outputSpatialReference.latestWkid,vcsWkid:e.outputSpatialReference.vcsWkid,latestVcsWkid:e.outputSpatialReference.latestVcsWkid,wkt:e.outputSpatialReference.wkt??""}:n.output_spatial_reference=a.SpatialReferenceUtil.WGS84(),n.open_cypher_query=e.openCypherQuery,e.bindParameters)for(const[r,i]of Object.entries(e.bindParameters))ye(r,i,n,a);if(e.bindGeometryQuantizationParameters)g(e.bindGeometryQuantizationParameters,n);else{if(t.dataModel||await oe(t),4326!==t.dataModel?.spatialReference?.wkid)throw new r("knowledge-graph:SR-quantization-mismatch","If the DataModel indicates a coordinate system other than WGS84, inputQuantizationParameters must be provided to the query encoder");n.input_quantization_parameters=a.InputQuantizationUtil.WGS84_lossless()}e.outputQuantizationParameters&&f(e.outputQuantizationParameters,n,a),e.provenanceBehavior&&m(e.provenanceBehavior,n);try{n.encode()}catch(d){throw new r("knowledge-graph:query-encoding-failed","Attempting to encode the query failed",{error:d})}const o=n.get_encoding_result();if(0!==o.error.error_code)throw new r("knowledge-graph:query-encoding-failed","Attempting to encode the query failed",{errorCode:o.error.error_code,errorMessage:o.error.error_message});return structuredClone(o.get_byte_buffer())}async function Te(e){const t=await w(),a=new t.GraphSearchRequestEncoder;if(a.deleteLater(),a.search_query=e.searchQuery,a.type_category_filter=t.esriNamedTypeCategory[e.typeCategoryFilter],!0===e.returnSearchContext&&(a.return_search_context=e.returnSearchContext),null!=e.start&&e.start>0&&(a.start_index=e.start),null!=e.num&&(a.max_num_results=e.num),null!=e.idsFilter&&Array.isArray(e.idsFilter)&&e.idsFilter.length>0)try{a.set_ids_filter(y(e.idsFilter,t))}catch(o){throw new r("knowledge-graph:ids-format-error","Attempting to set ids filter failed. This is usually caused by an incorrectly formatted UUID string",{error:o})}e.namedTypesFilter?.forEach((e=>{a.add_named_type_filter(e)}));try{a.encode()}catch(o){throw new r("knowledge-graph:search-encoding-failed","Attempting to encode the search failed",{error:o})}const n=a.get_encoding_result();if(0!==n.error.error_code)throw new r("knowledge-graph:search-encoding-failed","Attempting to get encoding result from the query failed",{errorCode:n.error.error_code,errorMessage:n.error.error_message});return structuredClone(n.get_byte_buffer())}async function ve(e,r){return t(e,{responseType:"native-request-init",method:"post",query:{f:"pbf",...r?.query},body:"x",headers:{"Content-Type":"application/octet-stream"},signal:r?.signal,timeout:r?.timeout})}async function Ae(e,t,a){const n=e.headers.get("content-type");if(n?.includes("application/x-protobuf")){const r=await e.arrayBuffer(),n=new t;try{return n.decode(new Uint8Array(r)),a(n)}finally{n.deleteLater()}}throw new r("knowledge-graph:unexpected-server-response","server returned an unexpected response",{responseType:n,data:await e.text()})}async function xe(e){return Ae(e,(await w()).GraphApplyEditsDecoder,U)}async function Pe(e){return Ae(e,(await w()).GraphNamedObjectTypeAddsResponseDecoder,E)}async function De(e){return Ae(e,(await w()).GraphNamedObjectTypeDeleteResponseDecoder,C)}async function Se(e){return Ae(e,(await w()).GraphNamedObjectTypeUpdateResponseDecoder,M)}async function Re(e){return Ae(e,(await w()).GraphPropertyAddsResponseDecoder,q)}async function Ee(e){return Ae(e,(await w()).GraphPropertyDeleteResponseDecoder,j)}async function Ce(e){return Ae(e,(await w()).GraphPropertyUpdateResponseDecoder,N)}let Me=50;function qe(e){Me=e}function je({wasmQueryDecoder:e,newArrayBufferToParse:t,dataModel:a,decodedHeader:n,limitMaxProcessingTime:o=!1}){t&&e.push_buffer(new Uint8Array(t));const i=[];let s,p,c=0;const l=Date.now();let u=!0;for(;e.next_row();){s&&p||(s=n??Q(e),p=s.outSpatialReference??new d({wkid:4326})),c||(c=e.get_header_keys().size());const t=new Array(c);for(let r=0;r<c;r++){const n=e.get_value(r);t[r]=K(n,a,p)}if(i.push(t),o&&Date.now()-l>Me){u=!1;break}}if(e.has_error())throw new r("knowledge-graph:stream-decoding-error","One or more result rows were not successfully decoded - inner row decoding",{errorCode:e.error.error_code,errorMessage:e.error.error_message});return{resultHeader:s,resultRows:i,parsedAllResultsFromBuffer:u}}async function Ne(e,t){const o=e.headers.get("content-type");if(e.headers.get("content-length")&&a.getLogger("esri.rest.knowledgeGraph.knowledgeGraphService").warnOnce("Found `Content-Length` header when expecting a streaming HTTP response! Please investigate whether all intermediate HTTP proxies and/or load balancers are configured such that they don't forcefully buffer the entire response before returning it to the client. A valid HTTP streaming response should use Chunked Transfer Encoding and not have a Content Length defined."),o?.includes("application/x-protobuf")){const o=e.body?.getReader(),d=new((await w()).GraphQueryDecoder);let i,s,c;d.deleteLater();const l=new Promise(((e,t)=>{s=e,c=t}));let u=!1,h=null;const y=new ReadableStream({pull:async function e(l){if(!o){const e=new r("knowledge-graph:stream-decoding-error","Error reading from stream - reader is undefined");throw c(e),e}const{done:w,value:y}=h?{done:!1,value:null}:await o.read().catch((e=>{throw c(e),o.releaseLock(),e}));y&&(h=y);try{if(w){let e;if(d.has_error()?e=new r("knowledge-graph:stream-decoding-error","One or more result rows were not successfully decoded - query stream done",{errorCode:d.error.error_code,errorMessage:d.error.error_message}):u||s(new p),o.releaseLock(),e)throw l.error(e),c(e),e;return void l.close()}const{resultHeader:a,resultRows:n,parsedAllResultsFromBuffer:g}=je({wasmQueryDecoder:d,newArrayBufferToParse:y,dataModel:t,decodedHeader:i,limitMaxProcessingTime:!0});return g&&(h=null),!i&&a&&(i=a,s(a),u=!0),n.length>0?void l.enqueue(n):await e(l)}catch(g){throw a.getLogger("esri.rest.knowledgeGraph.knowledgeGraphService").error(g),c(g),o.releaseLock(),n(g)?g:new r("knowledge-graph:unexpected-server-response","Error inside streaming data return parsing",{error:g})}}});return{readableStream:y,resultHeader:await l}}throw new r("knowledge-graph:unexpected-server-response","server returned an unexpected response",{responseType:o,data:e.text()})}async function Fe(e){const a=`${e.url}/dataModel/queryDataModel`,n=await t(a,{responseType:"array-buffer",query:{f:"pbf"}}),o=n.getHeader?.("content-type"),d=n.data;if(o?.includes("application/x-protobuf")){const e=(await w()).decode_data_model_from_protocol_buffer(new Uint8Array(d));if(!e)throw new r("knowledge-graph:data-model-decode-failure","The server responded to the data model query, but the response failed to be decoded. This typically occurs when the Knowledge JS API (4.26 or later) is used with an unsupported backend (11.0 or earlier)");return F(e)}throw new r("knowledge-graph:unexpected-server-response","server returned an unexpected response",{responseType:o,data:n.data})}export{we as _checkAuthentication,he as _esriRequestWrapper,le as _fetchWrapper,I as _getClientDataCacheCopy,qe as _setMaxQueryParsingDurationForTesting,ue as _submitJobWrapper,ce as clearClientDataCache,W as clientDataCache,J as executeAddGraphProperties,O as executeAddNamedTypes,H as executeApplyEdits,V as executeDeleteGraphProperty,z as executeDeleteNamedType,se as executeFindPaths,ie as executeFindPathsAsynchronous,X as executeQuery,Z as executeQueryStreaming,ee as executeSearch,te as executeSearchStreaming,Y as executeUpdateGraphProperty,B as executeUpdateNamedType,re as fetchAllClientDataKeys,pe as fetchAsynchronousFindPathsResultData,ae as fetchClientDataAtKeys,ne as fetchKnowledgeGraph,$ as kgRestServices,oe as refreshDataModel,de as refreshServiceDefinition};
5
+ import{id as e}from"../kernel.js";import t from"../request.js";import r from"../core/Error.js";import a from"../core/Logger.js";import{isAbortError as n}from"../core/promiseUtils.js";import o from"../geometry/Geometry.js";import d from"../geometry/SpatialReference.js";import{submitJob as i}from"./geoprocessor/submitJob.js";import s from"./knowledgeGraph/GraphQueryResult.js";import p from"./knowledgeGraph/GraphQueryResultHeader.js";import c from"./knowledgeGraph/GraphQueryStreamingResult.js";import l from"./knowledgeGraph/KnowledgeGraph.js";import u from"./knowledgeGraph/ServiceDefinition.js";import{encodeClientDataAtKeysRequest as h}from"./knowledgeGraph/wasmInterface/clientDataToWasmEncodedFactories.js";import{getWasmInterface as w}from"./knowledgeGraph/wasmInterface/knowledgeWasmAccess.js";import{bindParamArrayToWasm as y,setInputQuantizationParametersOnEncoder as g,setOutputQuantizationParametersOnEncoder as f,setProvenanceBehaviorOnEncoder as m,geometryToWasm as _,bindParamObjectToWasm as k}from"./knowledgeGraph/wasmInterface/queryToWasmEncodedFactories.js";import{updateSearchPropertiesToWasm as b,updateGraphPropertyToWasm as G,graphPropertyToWasm as T,updateEntityTypeToWasm as v,updateRelationshipTypeToWasm as x,entityTypeToWasm as S,relationshipTypeToWasm as P,inputQuantizationParametersToWasmFormat as A,namedObjectToWasm as D}from"./knowledgeGraph/wasmInterface/updateToWasmEncodedFactories.js";import{wasmClientDataAllKeysResponseToClientDataKeys as R,wasmClientDataFetchResponseToClientData as E}from"./knowledgeGraph/wasmInterface/wasmToClientDataFactories.js";import{decoderToAddNamedTypesResult as C,decoderToDeleteNamedTypeResult as M,decoderToUpdateNamedTypesResult as q,decoderToAddGraphPropertiesResult as j,decoderToDeleteGraphPropertiesResult as N,decoderToUpdateGraphPropertiesResult as F,decoderToGraphUpdateSearchIndexResult as U}from"./knowledgeGraph/wasmInterface/wasmToDataModelChangeResponseFactories.js";import{wasmToDataModel as Q}from"./knowledgeGraph/wasmInterface/wasmToDataModelFactories.js";import{wasmToGraphQueryResponseHeader as I,decodedWasmObjToQueryResponseObj as K}from"./knowledgeGraph/wasmInterface/wasmToQueryResponseObjFactories.js";import{decoderToApplyEditsResponse as L}from"./knowledgeGraph/wasmInterface/wasmToUpdateResponseFactories.js";import{checkWasmError as O}from"./knowledgeGraph/wasmInterface/wasmUtils.js";const W=new Map,$=()=>new Map(W.entries()),H={fetchKnowledgeGraph:async e=>{const t=new l({url:e}),r=[];return r.push(se(t)),r.push(pe(t)),await Promise.all(r),t},refreshDataModel:async e=>{e.dataModel=await Le(e)},refreshServiceDefinition:async e=>{const r=(await t(e.url,{query:{f:"json"}})).data;return r.capabilities=r?.capabilities?.split(","),r.supportedQueryFormats=r?.supportedQueryFormats?.split(","),e.serviceDefinition=new u(r),e.serviceDefinition},executeFindPathsAsynchronous:async(e,t)=>{const a=e.inKnowledgeGraphUrl.split("/rest/services");if(a.length<2)throw new r("knowledge-graph:invalid-tool-url","The URL for the KG Service was not correctly formatted. It should contain /reset/services/");const n=a[0];return await ye(`${n}/rest/services/System/KnowledgeGraphServerToolsAsync/GPServer/ServerFilteredFindPaths`,{in_knowledge_graph_url:e.inKnowledgeGraphUrl,config_type:"STRING",config_string:e.config.toJSON(),result_type:"STRING"},{},t)},executeFindPaths:async(e,t)=>{const a=e.inKnowledgeGraphUrl.split("/rest/services");if(a.length<2)throw new r("knowledge-graph:invalid-tool-url","The URL for the KG Service was not correctly formatted. It should contain /reset/services/");const n=a[0],o=await ge(`${n}/rest/services/System/KnowledgeGraphServerTools/GPServer/ServerFilteredFindPaths/execute`,{method:"post",query:{f:"pjson",in_knowledge_graph_url:e.inKnowledgeGraphUrl,config_type:"STRING",config_string:JSON.stringify(e.config),result_type:"STRING"},...t});if(o.data.results.length<1)throw new r("knowledge-graph:no-results","No results were returned from the FindPaths tool - no results returned",o);let d;for(const r of o.data.results)if("out_results_string"===r.paramName){d=r.value;break}if(!d)throw new r("knowledge-graph:no-results","No results were returned from the FindPaths tool - no results were returned on the expected paramater out_results_string",o);return d},fetchAsynchronousFindPathsResultData:async(e,t)=>(await e.fetchResultData("out_results_string",null,t)).value,executeQueryStreaming:async(e,t,a)=>{const n="include",o=`${e.url}/graph/query`;await fe(e);const d=await Ae(o,a);if(!e.serviceDefinition?.supportsProvenance&&t.provenanceBehavior===n)throw new r("knowledge-graph:provenance-not-supported","The Knowledge Graph Service definition indicated that provenance is not supported");d.data.body=await Se(t,e);const i=await we(d.data.url,d.data);if(e.dataModel){const t=await Ke(i,e.dataModel);return new c({resultRowsStream:t.readableStream,resultHeader:t.resultHeader})}throw new r("knowledge-graph:undefined-data-model","The KnowledgeGraph supplied did not have a data model")},executeApplyEdits:async(e,t,a)=>{if(e.serviceDefinition?.dataEditingNotSupported)throw new r("knowledge-graph:data-editing-not-supported","The Knowledge Graph Service definition indicated that data editing is not supported");const n=`${e.url}/graph/applyEdits`;await fe(e);const o=await Ae(n,a);o.data.body=await _e(t,e);return Re(await we(o.data.url,o.data))},executeAddNamedTypes:async(e,t,a)=>{if(!t.newEntityTypes?.length&&!t.newRelationshipTypes?.length)throw new r("knowledge-graph:no-arguments","The operation to add types to the data model contained no values");const n=`${e.url}/dataModel/edit/namedTypes/add`;await fe(e);const o=await Ae(n,a);o.data.body=await ke(t);const d=await we(o.data.url,o.data),i=await Ee(d);return i.updatedKnowledgeGraph=await ie(e.url),i},executeDeleteNamedType:async(e,t,a)=>{if(!t)throw new r("knowledge-graph:no-arguments","The operation to delete a named type from the data model contained no value");const n=`${e.url}/dataModel/edit/namedTypes/${t}/delete`;await fe(e);const o=await Ae(n,a);o.data.body="";const d=await we(o.data.url,o.data),i=await Ce(d);return i.updatedKnowledgeGraph=await ie(e.url),i},executeUpdateNamedType:async(e,t,a,n)=>{if(!t&&!Object.keys(a).length)throw new r("knowledge-graph:no-arguments","The operation to update types in the data model contained missing or empty values");const o=`${e.url}/dataModel/edit/namedTypes/${t}/update`;await fe(e);const d=await Ae(o,n);d.data.body=await be(a,t,e.dataModel);const i=await we(d.data.url,d.data),s=await Me(i);return s.updatedKnowledgeGraph=await ie(e.url),s},executeAddGraphProperties:async(e,t,a,n)=>{if(!t&&!a.length)throw new r("knowledge-graph:no-arguments","The operation to add properties to the data model contained missing or empty values");const o=`${e.url}/dataModel/edit/namedTypes/${t}/fields/add`;await fe(e);const d=await Ae(o,n);d.data.body=await Ge(a);const i=await we(d.data.url,d.data),s=await qe(i);return s.updatedKnowledgeGraph=await ie(e.url),s},executeDeleteGraphProperty:async(e,t,a,n)=>{if(!t&&!a)throw new r("knowledge-graph:no-arguments","The operation to delete property contained missing or empty values");const o=`${e.url}/dataModel/edit/namedTypes/${t}/fields/delete`;await fe(e);const d=await Ae(o,n);d.data.body=await Te(a);const i=await we(d.data.url,d.data),s=await je(i);return s.updatedKnowledgeGraph=await ie(e.url),s},executeUpdateGraphProperty:async(e,t,a,n,o)=>{if(!t&&!a&&!Object.keys(n).length)throw new r("knowledge-graph:no-arguments","The operation to update properties in the data model contained missing or empty values");const d=`${e.url}/dataModel/edit/namedTypes/${t}/fields/update`;await fe(e);const i=await Ae(d,o);i.data.body=await ve(a,n);const s=await we(i.data.url,i.data),p=await Ne(s);return p.updatedKnowledgeGraph=await ie(e.url),p},executeUpdateSearchIndex:async(e,t,a,n)=>{if(!t)throw new r("knowledge-graph:no-arguments","The operation to update search index in the data model contained missing named type");if(!Object.keys(a.addSearchProperties??{}).length&&!Object.keys(a.removeSearchProperties??{}).length)throw new r("knowledge-graph:no-arguments","The operation to update search index in the data model contained missing or empty properties values");const o=`${e.url}/dataModel/searchIndex/update`;await fe(e);const d=await Ae(o,n);d.data.body=await xe(t,a);const i=await we(d.data.url,d.data),s=await Fe(i);return s.updatedKnowledgeGraph=await ie(e.url),s},executeQuery:async(e,a,n)=>{const o=`${e.url}/graph/query`,d=await t(o,{responseType:"array-buffer",query:{f:"pbf",openCypherQuery:a.openCypherQuery,...n?.query},signal:n?.signal,timeout:n?.timeout}),i=d.getHeader?.("content-type"),p=d.data;if(i?.includes("application/x-protobuf")){const t=new((await w()).GraphQueryDecoder);if(t.deleteLater(),e.dataModel){const r=Ie({wasmQueryDecoder:t,newArrayBufferToParse:p,dataModel:e.dataModel});return new s({resultRows:r.resultRows,resultHeader:r.resultHeader})}throw new r("knowledge-graph:undefined-data-model","The KnowledgeGraph supplied did not have a data model")}throw new r("knowledge-graph:unexpected-server-response","server returned an unexpected response",{responseType:i,data:d.data})},executeSearch:async(e,a,n)=>{const o=a.typeCategoryFilter,d=`${e.url}/graph/search`,i=await t(d,{responseType:"array-buffer",query:{f:"pbf",searchQuery:`"${a.searchQuery}"`,typeCategoryFilter:o,...n?.query},signal:n?.signal,timeout:n?.timeout}),p=i.getHeader?.("content-type"),c=i.data;if(p?.includes("application/x-protobuf")){const t=new((await w()).GraphQueryDecoder);if(t.deleteLater(),e.dataModel){const r=Ie({wasmQueryDecoder:t,newArrayBufferToParse:c,dataModel:e.dataModel});return new s({resultRows:r.resultRows,resultHeader:r.resultHeader})}throw new r("knowledge-graph:undefined-data-model","The KnowledgeGraph supplied did not have a data model")}throw new r("knowledge-graph:unexpected-server-response","server returned an unexpected response",{responseType:p,data:i.data})},executeSearchStreaming:async(e,t,a)=>{const n=`${e.url}/graph/search`;await fe(e);const o=await Ae(n,a);o.data.body=await Pe(t);const d=await we(o.data.url,o.data);if(e.dataModel){const t=await Ke(d,e.dataModel);return new c({resultRowsStream:t.readableStream,resultHeader:t.resultHeader})}throw new r("knowledge-graph:undefined-data-model","The KnowledgeGraph supplied did not have a data model")},fetchClientDataAtKeys:async(e,t,a={ignoreCache:!1})=>{if(!t.length)return new Map;let n=W.get(e.url||"");n||(n=new Map,W.set(e.url||"",n));const o=new Map(n.entries()),d=`${e.url}/clientData/fetch`;t=Array.from(new Set(t));const i=await w(),s=h(t,n,i,a.ignoreCache),p=await Ae(d,a.requestOptions);p.data.body=s;const c=await we(p.data.url,p.data),l=c.headers.get("content-type");if(l?.includes("application/x-protobuf")){const e=new i.ClientDataFetchResponseDecoder;e.deleteLater();const t=await c.arrayBuffer();return e.decode(new Uint8Array(t)),e.has_error()&&O(e.error,"knowledge-graph:fetchClientDataAtKeys-decoding-error","An error occurred while decoding the client data keys response"),E(e,n,o,a.ignoreCache)}throw new r("knowledge-graph:unexpected-server-response","server returned an unexpected response when fetching client data",{responseType:l,data:c})},fetchAllClientDataKeys:async(e,a)=>{const n=`${e.url}/clientData`,o=await t(n,{responseType:"array-buffer",query:{f:"pbf"},signal:a?.signal,timeout:a?.timeout}),d=o.getHeader?.("content-type"),i=o.data;if(d?.includes("application/x-protobuf")){const e=new((await w()).ClientDataKeysResponseDecoder);return e.deleteLater(),e.decode(new Uint8Array(i)),e.has_error()&&O(e.error,"knowledge-graph:fetchAllClientDataKeys-decoding-error","An error occurred while decoding the client data keys response"),R(e)}throw new r("knowledge-graph:unexpected-server-response","server returned an unexpected response",{responseType:d,data:o.data})},clearClientDataCache:()=>W.clear(),_fetchWrapper:async(e,t)=>fetch(e,t),_submitJobWrapper:async(e,t,r,a)=>i(e,t,r,a),_esriRequestWrapper:async(e,r)=>t(e,r)};async function z(e,t,r){return H.executeApplyEdits(e,t,r)}async function B(e,t,r){return H.executeAddNamedTypes(e,t,r)}async function J(e,t,r){return H.executeDeleteNamedType(e,t,r)}async function V(e,t,r,a){return H.executeUpdateNamedType(e,t,r,a)}async function Y(e,t,r,a){return H.executeAddGraphProperties(e,t,r,a)}async function X(e,t,r,a){return H.executeDeleteGraphProperty(e,t,r,a)}async function Z(e,t,r,a,n){return H.executeUpdateGraphProperty(e,t,r,a,n)}async function ee(e,t,r,a){return H.executeUpdateSearchIndex(e,t,r,a)}async function te(e,t,r){return H.executeQuery(e,t,r)}async function re(e,t,r){return H.executeQueryStreaming(e,t,r)}async function ae(e,t,r){return H.executeSearch(e,t,r)}async function ne(e,t,r){return H.executeSearchStreaming(e,t,r)}function oe(e,t){return H.fetchAllClientDataKeys(e,t)}function de(e,t,r){return H.fetchClientDataAtKeys(e,t,r)}async function ie(e){return H.fetchKnowledgeGraph(e)}async function se(e){return H.refreshDataModel(e)}async function pe(e){return H.refreshServiceDefinition(e)}async function ce(e,t){return H.executeFindPathsAsynchronous(e,t)}async function le(e,t){return H.executeFindPaths(e,t)}async function ue(e,t){return H.fetchAsynchronousFindPathsResultData(e,t)}function he(){return H.clearClientDataCache()}async function we(e,t){return H._fetchWrapper(e,t)}async function ye(e,t,r,a){return H._submitJobWrapper(e,t,r,a)}async function ge(e,t){return H._esriRequestWrapper(e,t)}async function fe(t){const r=e?.findCredential(t.url);r||(t.dataModel?await Le(t):await se(t))}function me(e,t,r,a){null==t?r.set_param_key_value(e,""):"object"!=typeof t||t instanceof Date?r.set_param_key_value(e,t):t instanceof o?r.set_param_key_value(e,_(t,a)):Array.isArray(t)?r.set_param_key_value(e,y(t,a)):r.set_param_key_value(e,k(t,a))}async function _e(e,t){if(t.dataModel||await se(t),!t.dataModel)throw new r("knowledge-graph:data-model-undefined","Encoding could not proceed because a data model was not provided and it could not be determined from the service");const a=await w(),n=!!e.options?.cascadeDelete,o=new a.GraphApplyEditsEncoder(a.SpatialReferenceUtil.WGS84(),e.options?.inputQuantizationParameters?A(e.options?.inputQuantizationParameters):a.InputQuantizationUtil.WGS84_lossless());o.deleteLater(),o.cascade_delete=n;try{let t;e.entityAdds?.forEach((e=>{t=o.add_entity(D(e,a)),O(t,"knowledge-graph:applyEdits-encoding-failed","Attempting to encode the applyEdits - an entity failed to be added to the encoder")})),e.relationshipAdds?.forEach((e=>{if(!e.originId||!e.destinationId)throw new r("knowledge-graph:relationship-origin-destination-missing","When adding a new relationship, you must provide both an origin and destination id on the appropriate class property");t=o.add_relationship(D(e,a)),O(t,"knowledge-graph:applyEdits-encoding-failed","Attempting to encode the applyEdits - a relationship failed to be added to the encoder")})),e.entityUpdates?.forEach((e=>{if(!e.id)throw new r("knowledge-graph:entity-id-missing","When updating an entity or relationship, you must specify the id on the class level property");t=o.update_entity(D(e,a)),O(t,"knowledge-graph:applyEdits-encoding-failed","Attempting to encode the applyEdits - an entity failed to be added to the encoder")})),e.relationshipUpdates?.forEach((e=>{if(!e.id)throw new r("knowledge-graph:relationship-id-missing","When updating an entity or relationship, you must specify the id on the class level property");t=o.update_relationship(D(e,a)),O(t,"knowledge-graph:applyEdits-encoding-failed","Attempting to encode the applyEdits - a relationship failed to be added to the encoder")})),e.entityDeletes?.forEach((e=>{if(!e.typeName)throw new r("knowledge-graph:no-type-name","You must indicate the entity/relationship named object type to apply edits - delete");const t=o.make_delete_helper(e.typeName,!0);t.deleteLater(),e.ids?.forEach((e=>{t.delete_by_id(e)}))})),e.relationshipDeletes?.forEach((e=>{if(!e.typeName)throw new r("knowledge-graph:no-type-name","You must indicate the entity/relationship named object type to apply edits - delete");const t=o.make_delete_helper(e.typeName,!1);e.ids?.forEach((e=>{t.delete_by_id(e)}))})),o.encode()}catch(i){throw new r("knowledge-graph:applyEdits-encoding-failed","Attempting to encode the applyEdits failed",{error:i})}const d=o.get_encoding_result();return O(d.error,"knowledge-graph:applyEdits-encoding-failed","Attempting to encode the applyEdits failed"),structuredClone(d.get_byte_buffer())}async function ke(e){const t=await w(),a=new t.GraphNamedObjectTypeAddsRequestEncoder;a.deleteLater(),e.newEntityTypes?.forEach((e=>{a.add_entity_type(S(e,t))})),e.newRelationshipTypes?.forEach((e=>{a.add_relationship_type(P(e,t))}));try{a.encode()}catch(o){throw new r("knowledge-graph:addNamedTypes-encoding-failed","Attempting to encode the addNamedTypes failed",{error:o})}const n=a.get_encoding_result();return O(n.error,"knowledge-graph:addNamedTypes-encoding-failed","Attempting to encode the addNamedTypes failed"),structuredClone(n.get_byte_buffer())}async function be(e,t,a){const n=await w(),o=new n.GraphNamedObjectTypeUpdateRequestEncoder;o.deleteLater();if(a.entityTypes.some((e=>e.name===t)))o.update_entity_type(v(e,n));else{if(!a.relationshipTypes.some((e=>e.name===t)))throw new r("knowledge-graph:updateNamedType-encoding-failed","The named type you are trying to update does not exist in the data model");o.update_relationship_type(x(e,n))}o.update_alias=e.hasOwnProperty("alias");try{o.encode()}catch(i){throw new r("knowledge-graph:updateNamedType-encoding-failed","Attempting to encode the updateNamedType failed",{error:i})}const d=o.get_encoding_result();return O(d.error,"knowledge-graph:updateNamedType-encoding-failed","Attempting to encode the updateNamedType failed"),structuredClone(d.get_byte_buffer())}async function Ge(e){const t=await w(),a=new t.GraphPropertyAddsRequestEncoder;a.deleteLater(),e.forEach((e=>{a.add_graph_property(T(e,t))}));try{a.encode()}catch(o){throw new r("knowledge-graph:addGraphProperties-encoding-failed","Attempting to encode the addGraphProperties failed",{error:o})}const n=a.get_encoding_result();return O(n.error,"knowledge-graph:addGraphProperties-encoding-failed","Attempting to encode the addGraphProperties failed"),structuredClone(n.get_byte_buffer())}async function Te(e){const t=new((await w()).GraphPropertyDeleteRequestEncoder);t.deleteLater(),t.field_name=e;try{t.encode()}catch(n){throw new r("knowledge-graph:deleteGraphProperty-encoding-failed","Attempting to encode the deleteGraphProperty failed",{error:n})}const a=t.get_encoding_result();return O(a.error,"knowledge-graph:deleteGraphProperty-encoding-failed","Attempting to encode the deleteGraphProperty failed"),structuredClone(a.get_byte_buffer())}async function ve(e,t){const a=await w(),n=new a.GraphPropertyUpdateRequestEncoder;n.deleteLater(),n.update_graph_property(G(t,a)),n.set_property_name(e),n.update_alias=t.hasOwnProperty("alias"),n.update_editable=t.hasOwnProperty("editable"),n.update_required=t.hasOwnProperty("required"),n.update_visible=t.hasOwnProperty("defaultVisibility"),n.update_default_value=t.hasOwnProperty("defaultValue");try{n.encode()}catch(d){throw new r("knowledge-graph:updateGraphProperty-encoding-failed","Attempting to encode the updateGraphProperty failed",{error:d})}const o=n.get_encoding_result();return O(o.error,"knowledge-graph:updateGraphProperty-encoding-failed","Attempting to encode the updateGraphProperty failed"),structuredClone(o.get_byte_buffer())}async function xe(e,t){const a=await w(),n=new a.GraphUpdateSearchIndexRequestEncoder;n.deleteLater(),t.hasOwnProperty("addSearchProperties")&&n.insert_add_search_property(e,b(t.addSearchProperties,a)),t.hasOwnProperty("removeSearchProperties")&&n.insert_delete_search_property(e,b(t.removeSearchProperties,a));try{n.encode()}catch(d){throw new r("knowledge-graph:updateSearchIndex-encoding-failed","Attempting to encode the updateSearchIndex failed",{error:d})}const o=n.get_encoding_result();return O(o.error,"knowledge-graph:updateSearchIndex-encoding-failed","Attempting to encode the updateSearchIndex failed"),structuredClone(o.get_byte_buffer())}async function Se(e,t){const a=await w(),n=new a.GraphQueryRequestEncoder;if(n.deleteLater(),e.outputSpatialReference?n.output_spatial_reference={wkid:e.outputSpatialReference.wkid,latestWkid:e.outputSpatialReference.latestWkid,vcsWkid:e.outputSpatialReference.vcsWkid,latestVcsWkid:e.outputSpatialReference.latestVcsWkid,wkt:e.outputSpatialReference.wkt??""}:n.output_spatial_reference=a.SpatialReferenceUtil.WGS84(),n.open_cypher_query=e.openCypherQuery,e.bindParameters)for(const[r,i]of Object.entries(e.bindParameters))me(r,i,n,a);if(e.bindGeometryQuantizationParameters)g(e.bindGeometryQuantizationParameters,n);else{if(t.dataModel||await se(t),4326!==t.dataModel?.spatialReference?.wkid)throw new r("knowledge-graph:SR-quantization-mismatch","If the DataModel indicates a coordinate system other than WGS84, inputQuantizationParameters must be provided to the query encoder");n.input_quantization_parameters=a.InputQuantizationUtil.WGS84_lossless()}e.outputQuantizationParameters&&f(e.outputQuantizationParameters,n,a),e.provenanceBehavior&&m(e.provenanceBehavior,n);try{n.encode()}catch(d){throw new r("knowledge-graph:query-encoding-failed","Attempting to encode the query failed",{error:d})}const o=n.get_encoding_result();if(0!==o.error.error_code)throw new r("knowledge-graph:query-encoding-failed","Attempting to encode the query failed",{errorCode:o.error.error_code,errorMessage:o.error.error_message});return structuredClone(o.get_byte_buffer())}async function Pe(e){const t=await w(),a=new t.GraphSearchRequestEncoder;if(a.deleteLater(),a.search_query=e.searchQuery,a.type_category_filter=t.esriNamedTypeCategory[e.typeCategoryFilter],!0===e.returnSearchContext&&(a.return_search_context=e.returnSearchContext),null!=e.start&&e.start>0&&(a.start_index=e.start),null!=e.num&&(a.max_num_results=e.num),null!=e.idsFilter&&Array.isArray(e.idsFilter)&&e.idsFilter.length>0)try{a.set_ids_filter(y(e.idsFilter,t))}catch(o){throw new r("knowledge-graph:ids-format-error","Attempting to set ids filter failed. This is usually caused by an incorrectly formatted UUID string",{error:o})}e.namedTypesFilter?.forEach((e=>{a.add_named_type_filter(e)}));try{a.encode()}catch(o){throw new r("knowledge-graph:search-encoding-failed","Attempting to encode the search failed",{error:o})}const n=a.get_encoding_result();if(0!==n.error.error_code)throw new r("knowledge-graph:search-encoding-failed","Attempting to get encoding result from the query failed",{errorCode:n.error.error_code,errorMessage:n.error.error_message});return structuredClone(n.get_byte_buffer())}async function Ae(e,r){return t(e,{responseType:"native-request-init",method:"post",query:{f:"pbf",...r?.query},body:"x",headers:{"Content-Type":"application/octet-stream"},signal:r?.signal,timeout:r?.timeout})}async function De(e,t,a){const n=e.headers.get("content-type");if(n?.includes("application/x-protobuf")){const r=await e.arrayBuffer(),n=new t;try{return n.decode(new Uint8Array(r)),a(n)}finally{n.deleteLater()}}throw new r("knowledge-graph:unexpected-server-response","server returned an unexpected response",{responseType:n,data:await e.text()})}async function Re(e){return De(e,(await w()).GraphApplyEditsDecoder,L)}async function Ee(e){return De(e,(await w()).GraphNamedObjectTypeAddsResponseDecoder,C)}async function Ce(e){return De(e,(await w()).GraphNamedObjectTypeDeleteResponseDecoder,M)}async function Me(e){return De(e,(await w()).GraphNamedObjectTypeUpdateResponseDecoder,q)}async function qe(e){return De(e,(await w()).GraphPropertyAddsResponseDecoder,j)}async function je(e){return De(e,(await w()).GraphPropertyDeleteResponseDecoder,N)}async function Ne(e){return De(e,(await w()).GraphPropertyUpdateResponseDecoder,F)}async function Fe(e){return De(e,(await w()).GraphUpdateSearchIndexResponseDecoder,U)}let Ue=50;function Qe(e){Ue=e}function Ie({wasmQueryDecoder:e,newArrayBufferToParse:t,dataModel:a,decodedHeader:n,limitMaxProcessingTime:o=!1}){t&&e.push_buffer(new Uint8Array(t));const i=[];let s,p,c=0;const l=Date.now();let u=!0;for(;e.next_row();){s&&p||(s=n??I(e),p=s.outSpatialReference??new d({wkid:4326})),c||(c=e.get_header_keys().size());const t=new Array(c);for(let r=0;r<c;r++){const n=e.get_value(r);t[r]=K(n,a,p)}if(i.push(t),o&&Date.now()-l>Ue){u=!1;break}}if(e.has_error())throw new r("knowledge-graph:stream-decoding-error","One or more result rows were not successfully decoded - inner row decoding",{errorCode:e.error.error_code,errorMessage:e.error.error_message});return{resultHeader:s,resultRows:i,parsedAllResultsFromBuffer:u}}async function Ke(e,t){const o=e.headers.get("content-type");if(e.headers.get("content-length")&&a.getLogger("esri.rest.knowledgeGraph.knowledgeGraphService").warnOnce("Found `Content-Length` header when expecting a streaming HTTP response! Please investigate whether all intermediate HTTP proxies and/or load balancers are configured such that they don't forcefully buffer the entire response before returning it to the client. A valid HTTP streaming response should use Chunked Transfer Encoding and not have a Content Length defined."),o?.includes("application/x-protobuf")){const o=e.body?.getReader(),d=new((await w()).GraphQueryDecoder);let i,s,c;d.deleteLater();const l=new Promise(((e,t)=>{s=e,c=t}));let u=!1,h=null;const y=new ReadableStream({pull:async function e(l){if(!o){const e=new r("knowledge-graph:stream-decoding-error","Error reading from stream - reader is undefined");throw c(e),e}const{done:w,value:y}=h?{done:!1,value:null}:await o.read().catch((e=>{throw c(e),o.releaseLock(),e}));y&&(h=y);try{if(w){let e;if(d.has_error()?e=new r("knowledge-graph:stream-decoding-error","One or more result rows were not successfully decoded - query stream done",{errorCode:d.error.error_code,errorMessage:d.error.error_message}):u||s(new p),o.releaseLock(),e)throw l.error(e),c(e),e;return void l.close()}const{resultHeader:a,resultRows:n,parsedAllResultsFromBuffer:g}=Ie({wasmQueryDecoder:d,newArrayBufferToParse:y,dataModel:t,decodedHeader:i,limitMaxProcessingTime:!0});return g&&(h=null),!i&&a&&(i=a,s(a),u=!0),n.length>0?void l.enqueue(n):await e(l)}catch(g){throw a.getLogger("esri.rest.knowledgeGraph.knowledgeGraphService").error(g),c(g),o.releaseLock(),n(g)?g:new r("knowledge-graph:unexpected-server-response","Error inside streaming data return parsing",{error:g})}}});return{readableStream:y,resultHeader:await l}}throw new r("knowledge-graph:unexpected-server-response","server returned an unexpected response",{responseType:o,data:e.text()})}async function Le(e){const a=`${e.url}/dataModel/queryDataModel`,n=await t(a,{responseType:"array-buffer",query:{f:"pbf"}}),o=n.getHeader?.("content-type"),d=n.data;if(o?.includes("application/x-protobuf")){const e=(await w()).decode_data_model_from_protocol_buffer(new Uint8Array(d));if(!e)throw new r("knowledge-graph:data-model-decode-failure","The server responded to the data model query, but the response failed to be decoded. This typically occurs when the Knowledge JS API (4.26 or later) is used with an unsupported backend (11.0 or earlier)");return Q(e)}throw new r("knowledge-graph:unexpected-server-response","server returned an unexpected response",{responseType:o,data:n.data})}export{fe as _checkAuthentication,ge as _esriRequestWrapper,we as _fetchWrapper,$ as _getClientDataCacheCopy,Qe as _setMaxQueryParsingDurationForTesting,ye as _submitJobWrapper,he as clearClientDataCache,W as clientDataCache,Y as executeAddGraphProperties,B as executeAddNamedTypes,z as executeApplyEdits,X as executeDeleteGraphProperty,J as executeDeleteNamedType,le as executeFindPaths,ce as executeFindPathsAsynchronous,te as executeQuery,re as executeQueryStreaming,ae as executeSearch,ne as executeSearchStreaming,Z as executeUpdateGraphProperty,V as executeUpdateNamedType,ee as executeUpdateSearchIndex,oe as fetchAllClientDataKeys,ue as fetchAsynchronousFindPathsResultData,de as fetchClientDataAtKeys,ie as fetchKnowledgeGraph,H as kgRestServices,se as refreshDataModel,pe as refreshServiceDefinition};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.33/esri/copyright.txt for details.
4
4
  */
5
- import e from"../../../Color.js";import{clone as t}from"../../../core/lang.js";import{px2pt as o}from"../../../core/screenUtils.js";import i from"../../../symbols/CIMSymbol.js";import{Simple3DLineStyle as r,LineJoinStyle as n,LineCapStyle as l}from"../../../symbols/cim/enums.js";const a="spike-height-override",s=o(8),m=o(20);function f(e){const{field:t,normalizationField:o,sizeStops:i}=e,{value:r,size:n}=i[0],{value:l,size:s}=i[1];let m,f=0;t&&(f=`$feature["${t}"]`,m=`\n if(!HasValue($feature, "${t}")){\n return 0;\n }\n $feature["${t}"];\n `),o&&(f=`$feature["${t}"] / $feature["${o}"]`,m=`if(!HasValue($feature, "${t}") || !HasValue($feature, "${o}") || $feature["${o}"] <= 0){\n return 0;\n }\n $feature["${t}"];\n $feature["${o}"];`);return[{type:"CIMPrimitiveOverride",primitiveName:a,propertyName:"Length",valueExpressionInfo:{type:"CIMExpressionInfo",title:"Custom",expression:`\n ${m}\n var value = ${f};\n\n var maxSize = ${s};\n var minSize = ${n};\n\n var minDataValue = ${r};\n var maxDataValue = ${l};\n\n var ratio = Constrain(( value - minDataValue ) / ( maxDataValue - minDataValue ), 0, 1);\n\n var size = Constrain(maxSize * ratio, minSize, maxSize);\n return size;\n `,returnType:"Default"}}]}function u(e){const{primitiveOverrides:t,baseWidth:o,defaultHeight:r}=e,n=c(e);return new i({data:{type:"CIMSymbolReference",symbol:{type:"CIMPointSymbol",effects:[{type:"CIMGeometricEffectRadial",primitiveName:a,angle:90,length:r??m},{type:"CIMGeometricEffectTaperedPolygon",fromWidth:o??s,toWidth:1,length:5}],symbolLayers:n,haloSize:1,scaleX:1,angleAlignment:"Display"},primitiveOverrides:t}})}function c(e){const t=[p(e)],o=y(e);return o&&t.push(o),t}function p(e){const{strokeColor:t,strokeWidth:i,symbolStyle:a}=e;let s=t?.toArray(),m=!1;return"triangle-open-fill-outline"===a||"triangle-enclosed-fill-outline"===a?m=!0:"triangle-open-outline"!==a&&"triangle-enclosed-outline"!==a&&"triangle-open-fill"!==a&&"triangle-enclosed-fill"!==a||(s=e.color?.toArray()),{type:"CIMSolidStroke",effects:d(a),enable:!0,colorLocked:m,capStyle:l.Round,joinStyle:n.Round,lineStyle3D:r.Strip,miterLimit:4,width:i??o(1),color:s}}function d(e){if("triangle-enclosed-fill"!==e&&"triangle-enclosed-fill-outline"!==e&&"triangle-enclosed-outline"!==e)return[{type:"CIMGeometricEffectAddControlPoints",angleTolerance:90,primitiveName:"spike-control-points"},{type:"CIMGeometricEffectSuppress",suppress:!0,invert:!0,primitiveName:"spike-stroke-suppress"}]}function y(e){const{color:t,symbolStyle:o}=e;if("triangle-open-outline"!==o&&"triangle-enclosed-outline"!==o)return{type:"CIMSolidFill",enable:!0,colorLocked:!1,color:t?.toArray()}}function v(o,i){const{defaultHeight:r,baseWidth:n,color:l,strokeColor:s,primitiveOverrides:m,symbolStyle:f,strokeWidth:u}=i,p="CIMPointSymbol"===o.data.symbol?.type?o.data.symbol:null;if(!p)return o;const d=p.effects,y=d?.find((e=>"CIMGeometricEffectTaperedPolygon"===e.type)),v=d?.find((e=>"CIMGeometricEffectRadial"===e.type&&e.primitiveName===a));null!=n&&y&&(y.fromWidth=n),null!=r&&v&&(v.length=r);const g=p.symbolLayers,S=g?.find((e=>"CIMSolidStroke"===e.type)),C=g?.find((e=>"CIMSolidFill"===e.type));return f?p.symbolLayers=c({color:l??(C?.color?new e(C.color):void 0),strokeColor:s??(S?.color?new e(S.color):void 0),strokeWidth:u??S?.width,symbolStyle:f}):S&&null!=s?S.color=s.toArray():C&&null!=l&&(C.color=l.toArray()),void 0!==m&&(o.data.primitiveOverrides=t(m)),o}function g(e){const t="CIMPointSymbol"===e.data.symbol?.type?e.data.symbol?.effects:null;return 2!==t?.length?null:t.find((e=>"CIMGeometricEffectTaperedPolygon"===e.type))?.fromWidth??null}export{f as createPrimitiveOverrides,u as createSpikeSymbol,g as getSpikeSymbolBaseWidth,v as updateSpikeSymbol};
5
+ import e from"../../../Color.js";import{clone as t}from"../../../core/lang.js";import{px2pt as o}from"../../../core/screenUtils.js";import i from"../../../symbols/CIMSymbol.js";import{Simple3DLineStyle as r,LineJoinStyle as n,LineCapStyle as l}from"../../../symbols/cim/enums.js";const a="spike-height-override",s=o(8),m=o(20);function u(e){const{field:t,normalizationField:o,sizeStops:i}=e,{value:r,size:n}=i[0],{value:l,size:s}=i[1];let m,u=0;t&&(u=`$feature["${t}"]`,m=`\n if(!HasValue($feature, "${t}")){\n return 0;\n }\n $feature["${t}"];\n `),o&&(u=`$feature["${t}"] / $feature["${o}"]`,m=`if(!HasValue($feature, "${t}") || !HasValue($feature, "${o}") || $feature["${o}"] <= 0){\n return 0;\n }\n $feature["${t}"];\n $feature["${o}"];`);return[{type:"CIMPrimitiveOverride",primitiveName:a,propertyName:"Length",valueExpressionInfo:{type:"CIMExpressionInfo",title:"Custom",expression:`\n ${m}\n var value = ${u};\n\n var maxSize = ${s};\n var minSize = ${n};\n\n var minDataValue = ${r};\n var maxDataValue = ${l};\n\n var ratio = Constrain(( value - minDataValue ) / ( maxDataValue - minDataValue ), 0, 1);\n\n var size = Constrain(maxSize * ratio, minSize, maxSize);\n return size;\n `,returnType:"Default"}}]}function f(e){const{primitiveOverrides:t,baseWidth:o,defaultHeight:r}=e,n=c(e);return new i({data:{type:"CIMSymbolReference",symbol:{type:"CIMPointSymbol",effects:[{type:"CIMGeometricEffectRadial",primitiveName:a,angle:90,length:r??m},{type:"CIMGeometricEffectTaperedPolygon",fromWidth:o??s,toWidth:1,length:5}],symbolLayers:n,haloSize:1,scaleX:1,angleAlignment:"Display"},primitiveOverrides:t}})}function c(e){const t=[p(e)],o=y(e);return o&&t.push(o),t}function p(e){const{strokeColor:t,strokeWidth:i,symbolStyle:a}=e;let s=t?.toArray(),m=!1;return"triangle-open-fill-outline"===a||"triangle-enclosed-fill-outline"===a?m=!0:"triangle-open-outline"!==a&&"triangle-enclosed-outline"!==a&&"triangle-open-fill"!==a&&"triangle-enclosed-fill"!==a||(s=e.color?.toArray()),{type:"CIMSolidStroke",effects:d(a),enable:!0,colorLocked:m,capStyle:l.Round,joinStyle:n.Round,lineStyle3D:r.Strip,miterLimit:4,width:i??o(1),color:s}}function d(e){if("triangle-enclosed-fill"!==e&&"triangle-enclosed-fill-outline"!==e&&"triangle-enclosed-outline"!==e)return[{type:"CIMGeometricEffectAddControlPoints",angleTolerance:90,primitiveName:"spike-control-points"},{type:"CIMGeometricEffectSuppress",suppress:!0,invert:!0,primitiveName:"spike-stroke-suppress"}]}function y(e){const{color:t,symbolStyle:o}=e;if("triangle-open-outline"!==o&&"triangle-enclosed-outline"!==o)return{type:"CIMSolidFill",enable:!0,colorLocked:!1,color:t?.toArray()}}function v(o,i){const{defaultHeight:r,baseWidth:n,color:l,strokeColor:s,primitiveOverrides:m,symbolStyle:u,strokeWidth:f}=i,p="CIMPointSymbol"===o.data.symbol?.type?o.data.symbol:null;if(!p)return o;const d=p.effects,y=d?.find((e=>"CIMGeometricEffectTaperedPolygon"===e.type)),v=d?.find((e=>"CIMGeometricEffectRadial"===e.type&&e.primitiveName===a));null!=n&&y&&(y.fromWidth=n),null!=r&&v&&(v.length=r);const S=p.symbolLayers,$=S?.find((e=>"CIMSolidStroke"===e.type)),g=S?.find((e=>"CIMSolidFill"===e.type));return u?p.symbolLayers=c({color:l??(g?.color?new e(g.color):void 0),strokeColor:s??($?.color?new e($.color):void 0),strokeWidth:f??$?.width,symbolStyle:u}):$&&null!=s?$.color=s.toArray():g&&null!=l&&(g.color=l.toArray()),void 0!==m&&(o.data.primitiveOverrides=t(m)),o}export{u as createPrimitiveOverrides,f as createSpikeSymbol,v as updateSpikeSymbol};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.33/esri/copyright.txt for details.
4
4
  */
5
- const c="20250518",f="c5fd0a2e7cce4f2054834f1d089cacc9d3f8ab6c";export{c as buildDate,f as commitHash};
5
+ const b="20250520",d="678852de9ad4fcf4db9b290654f6d0915609bb99";export{b as buildDate,d as commitHash};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.33/esri/copyright.txt for details.
4
4
  */
5
- import{pt2px as e,px2pt as t}from"../../core/screenUtils.js";import{CIMSymbolHelper as i}from"../cim/CIMSymbolHelper.js";import{CIMSymbolRasterizer as l}from"../cim/CIMSymbolRasterizer.js";import{OverrideHelper as r}from"../cim/OverrideHelper.js";import{mapCIMSymbolToGeometryType as o}from"../cim/utils.js";import{SymbolSizeDefaults as n}from"./previewUtils.js";import{renderSymbol as a}from"./renderUtils.js";const s=new l(null),m=t(n.size),h=t(n.maxSize),c=t(n.lineWidth),y=1;async function u(e,t,i){const l=t?.size;let r=null!=l&&"object"==typeof l&&"width"in l?l.width:l,o=null!=l&&"object"==typeof l&&"height"in l?l.height:l;if(null==r||null==o)if("esriGeometryPolygon"===i)r=o=t.maxSize?Math.min(t.maxSize,m):m;else{const l=await f(e,t,i);l&&(r=l.width,o=l.height),"esriGeometryPolyline"===i&&(r=t.maxSize?Math.min(t.maxSize,c):c),r=null!=r&&isFinite(r)?Math.min(r,h):m,o=null!=o&&isFinite(o)?Math.max(Math.min(o,h),y):m}return"legend"===t.style&&"esriGeometryPolyline"===i&&(r=c),{width:r,height:o}}async function f(e,t,l){const{feature:o,fieldMap:n,viewParams:a}=t.cimOptions||t,m=await r.resolveSymbolOverrides(e.data,o,null,n,l,null,a);if(!m)return null;(e=e.clone()).data={type:"CIMSymbolReference",symbol:m},e.data.primitiveOverrides=void 0;const h=[];return i.fetchResources(m,s.resourceManager,h),i.fetchFonts(m,s.resourceManager,h),h.length>0&&await Promise.all(h),i.getEnvelope(m,null,s.resourceManager)}async function g(i,l={}){const{node:r,opacity:n,symbolConfig:m}=l,h=null!=m&&"object"==typeof m&&"isSquareFill"in m&&m.isSquareFill,c=l.cimOptions||l,y=c.geometryType||o(i?.data?.symbol),f=await u(i,l,y),{feature:g,fieldMap:d}=c,p=l?.geometry||h||"esriGeometryPolygon"!==y?"preview":"legend";let w=f;const b=f;if(l?.geometry&&("esriGeometryPolygon"===y||"esriGeometryPolyline"===y)){const i=200;if(e(f.width)<i||e(f.height)<i){const e=f.width>f.height?t(i)*f.height/f.width:t(i);w={width:f.width>f.height?t(i):t(i)*f.width/f.height,height:e}}}const M=await s.rasterizeCIMSymbolAsync(i,g,w,p,d,y,null,c.viewParams,c.allowScalingUp,l?.geometry?.toJSON());if(!M)return null;const{width:S,height:v}=M,j=document.createElement("canvas");j.width=S,j.height=v;j.getContext("2d").putImageData(M,0,0);const x=e(b.width),z=e(b.height),P=new Image(x,z);P.src=j.toDataURL(),P.ariaLabel=l.ariaLabel??null,P.alt=l.ariaLabel??"",null!=n&&(P.style.opacity=`${n}`);let C=P;if(null!=l.effectView){const e={shape:{type:"image",x:0,y:0,width:x,height:z,src:P.src},fill:null,stroke:null,offset:[0,0]};C=a([[e]],[x,z],{effectView:l.effectView,ariaLabel:l.ariaLabel})}return r&&C&&r.appendChild(C),C}export{g as previewCIMSymbol};
5
+ import{pt2px as e,px2pt as t}from"../../core/screenUtils.js";import{CIMSymbolHelper as i}from"../cim/CIMSymbolHelper.js";import{CIMSymbolRasterizer as l}from"../cim/CIMSymbolRasterizer.js";import{OverrideHelper as o}from"../cim/OverrideHelper.js";import{mapCIMSymbolToGeometryType as r}from"../cim/utils.js";import{SymbolSizeDefaults as n}from"./previewUtils.js";import{renderSymbol as a}from"./renderUtils.js";const s=new l(null),m=t(n.size),h=t(n.maxSize),c=t(n.lineWidth),y=1;async function u(e,t,i){const l=t?.size;let o=null!=l&&"object"==typeof l&&"width"in l?l.width:l,r=null!=l&&"object"==typeof l&&"height"in l?l.height:l;if(null==o||null==r)if("esriGeometryPolygon"===i)o=r=t.maxSize?Math.min(t.maxSize,m):m;else{const l=await f(e,t,i);l&&(o=l.width,r=l.height),"esriGeometryPolyline"===i&&(o=t.maxSize?Math.min(t.maxSize,c):c),o=null!=o&&isFinite(o)?Math.min(o,h):m,r=null!=r&&isFinite(r)?Math.max(Math.min(r,h),y):m}return"legend"===t.style&&"esriGeometryPolyline"===i&&(o=c),{width:o,height:r}}async function f(e,t={},l){const n=t.cimOptions||t;l??=n.geometryType||r(e?.data?.symbol);const{feature:a,fieldMap:m,viewParams:h}=n,c=await o.resolveSymbolOverrides(e.data,a,null,m,l,null,h);if(!c)return null;(e=e.clone()).data={type:"CIMSymbolReference",symbol:c},e.data.primitiveOverrides=void 0;const y=[];return i.fetchResources(c,s.resourceManager,y),i.fetchFonts(c,s.resourceManager,y),y.length>0&&await Promise.all(y),i.getEnvelope(c,null,s.resourceManager)}async function g(i,l={}){const{node:o,opacity:n,symbolConfig:m}=l,h=null!=m&&"object"==typeof m&&"isSquareFill"in m&&m.isSquareFill,c=l.cimOptions||l,y=c.geometryType||r(i?.data?.symbol),f=await u(i,l,y),{feature:g,fieldMap:d}=c,p=l?.geometry||h||"esriGeometryPolygon"!==y?"preview":"legend";let w=f;const b=f;if(l?.geometry&&("esriGeometryPolygon"===y||"esriGeometryPolyline"===y)){const i=200;if(e(f.width)<i||e(f.height)<i){const e=f.width>f.height?t(i)*f.height/f.width:t(i);w={width:f.width>f.height?t(i):t(i)*f.width/f.height,height:e}}}const M=await s.rasterizeCIMSymbolAsync(i,g,w,p,d,y,null,c.viewParams,c.allowScalingUp,l?.geometry?.toJSON());if(!M)return null;const{width:S,height:v}=M,j=document.createElement("canvas");j.width=S,j.height=v;j.getContext("2d").putImageData(M,0,0);const x=e(b.width),z=e(b.height),P=new Image(x,z);P.src=j.toDataURL(),P.ariaLabel=l.ariaLabel??null,P.alt=l.ariaLabel??"",null!=n&&(P.style.opacity=`${n}`);let C=P;if(null!=l.effectView){const e={shape:{type:"image",x:0,y:0,width:x,height:z,src:P.src},fill:null,stroke:null,offset:[0,0]};C=a([[e]],[x,z],{effectView:l.effectView,ariaLabel:l.ariaLabel})}return o&&C&&o.appendChild(C),C}export{f as getCIMSymbolPreviewSize,g as previewCIMSymbol};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.33/esri/copyright.txt for details.
4
4
  */
5
- import{disposeMaybe as e}from"../../../../core/maybe.js";import{identity as t,translate as s,rotate as r,scaleByVec2 as i,multiply as o}from"../../../../core/libs/gl-matrix-2/math/mat3.js";import{create as a}from"../../../../core/libs/gl-matrix-2/factories/mat3f32.js";import{fromValues as u}from"../../../../core/libs/gl-matrix-2/factories/vec2f32.js";import{DisplayObject as h}from"../DisplayObject.js";import{TextureSamplingMode as n}from"../../../webgl/enums.js";import{createTransformTexture as l,createRasterTexture as d,createColormapTexture as p}from"../../../webgl/rasterUtils.js";const c={bandCount:3,minOutput:0,maxOutput:1,minCutOff:[0,0,0],maxCutOff:[255,255,255],factor:[1/255,1/255,1/255],useGamma:!1,gamma:[1,1,1],gammaCorrection:[1,1,1],colormap:null,colormapOffset:null,stretchType:"none",type:"stretch"};class _ extends h{constructor(e=null,t=null,s=null){super(),this._textureInvalidated=!0,this._colormapTextureInvalidated=!0,this._rasterTexture=null,this._rasterTextureBandIds=null,this._transformGridTexture=null,this._colormapTexture=null,this._colormap=null,this._supportsBilinearTexture=!0,this._processedTexture=null,this.functionTextures=[],this.projected=!1,this.stencilRef=0,this.coordScale=[1,1],this._processed=!1,this._symbolizerParameters=null,this.height=null,this.isRendereredSource=!1,this.pixelRatio=1,this.resolution=0,this.rotation=0,this._source=null,this.rawPixelData=null,this._suspended=!1,this._bandIds=null,this._interpolation=null,this._transformGrid=null,this.width=null,this.x=0,this.y=0,this.source=e,this.transformGrid=t,this.interpolation=s}destroy(){this._disposeTextures()}get processedTexture(){return this._processedTexture}set processedTexture(e){this._processedTexture!==e&&(this._disposeTextures(!0),this._processedTexture=e)}get rasterTexture(){return this._rasterTexture}set rasterTexture(e){this._rasterTexture!==e&&(this._rasterTexture?.dispose(),this._rasterTexture=e),null==e&&(this.projected=!1)}get processed(){return this._processed}set processed(t){this._processed=t,t||(e(this.processedTexture),this.invalidateTexture())}get symbolizerParameters(){return this._symbolizerParameters||c}set symbolizerParameters(e){this._symbolizerParameters!==e&&(this._symbolizerParameters=e,this._colormapTextureInvalidated=!0,this.commonUniforms=null)}get source(){return this._source}set source(e){this._source!==e&&(this._source=e,this._rasterTexture&&(this._rasterTexture.dispose(),this._rasterTexture=null,this._rasterTextureBandIds=null),this.commonUniforms=null,this.projected=!1,this.invalidateTexture())}get suspended(){return this._suspended}set suspended(e){this._suspended&&!e&&this.stage&&(this.ready(),this.requestRender()),this._suspended=e}get bandIds(){return this._bandIds}set bandIds(e){this._bandIds=e,this._isBandIdsChanged(e)&&(this.projected=!1,this.invalidateTexture())}get interpolation(){return this._interpolation||"nearest"}set interpolation(e){this._interpolation=e,this._rasterTexture&&this._rasterTexture.setSamplingMode("bilinear"===this._getTextureSamplingMethod(e||"nearest")?n.LINEAR:n.NEAREST)}get transformGrid(){return this._transformGrid}set transformGrid(t){this._transformGrid!==t&&(this._transformGrid=t,this._transformGridTexture=e(this._transformGridTexture))}invalidateTexture(){this._textureInvalidated||(this._textureInvalidated=!0,this.requestRender())}getRasterTextureSize(e=!1){const t=e||this.projected;return[t?this.width:this.source?.width||this.width,t?this.height:this.source?.height||this.height]}getRasterCellSize(){const e=this.rawPixelData?.srcPixelSize,{projected:t,resolution:s}=this;return e&&!t?[e.x,e.y]:[s,s]}_createTransforms(){return{displayViewScreenMat3:a()}}setTransform(e){const a=t(this.transforms.displayViewScreenMat3),[h,n]=e.toScreenNoRotation([0,0],[this.x,this.y]),l=this.resolution/this.pixelRatio/e.resolution,d=l*this.width,p=l*this.height,c=Math.PI*this.rotation/180;s(a,a,u(h,n)),s(a,a,u(d/2,p/2)),r(a,a,-c),s(a,a,u(-d/2,-p/2)),i(a,a,u(d,p)),o(this.transforms.displayViewScreenMat3,e.displayViewMat3,a)}getTextures({forProcessing:e=!1,useProcessedTexture:t=!1}={}){const s=t?this._processedTexture??this._rasterTexture:this._rasterTexture,r=[],i=[];return s?(this._transformGridTexture&&!this.projected&&(i.push(this._transformGridTexture),r.push("u_transformGrid")),t?(i.push(s),r.push("u_image"),this._colormapTexture&&(i.push(this._colormapTexture),r.push("u_colormap")),{names:r,textures:i}):(i.push(s),r.push("u_image"),this._colormapTexture&&!e&&(i.push(this._colormapTexture),r.push("u_colormap")),{names:r,textures:i})):{names:r,textures:i}}onAttach(){this.invalidateTexture()}onDetach(){this.invalidateTexture()}updateTexture({context:e}){if(!this.stage)return void this._disposeTextures();const t=this._isValidSource(this.source);t&&this._colormapTextureInvalidated&&(this._colormapTextureInvalidated=!1,this._updateColormapTexture(e)),this._textureInvalidated&&(this._textureInvalidated=!1,this._createOrDestroyRasterTexture(e),this._rasterTexture&&(t?this.transformGrid&&!this._transformGridTexture&&(this._transformGridTexture=l(e,this.transformGrid)):this._rasterTexture.setData(null)),this.suspended||(this.ready(),this.requestRender()))}updateProcessedTexture(){const{functionTextures:e}=this;0!==e.length&&(this.processedTexture=e.shift(),e.forEach((e=>e?.dispose())),e.length=0,this.processed=!!this.processedTexture)}_createOrDestroyRasterTexture(e){const t=this.source?.extractBands(this.bandIds);if(!this._isValidSource(t))return void(this._rasterTexture&&(this._rasterTexture.dispose(),this._rasterTextureBandIds=null,this._rasterTexture=null));const s=!this._isBandIdsChanged(this.bandIds);if(this._rasterTexture){if(s)return;this._rasterTexture.dispose(),this._rasterTextureBandIds=null,this._rasterTexture=null}this._supportsBilinearTexture=!!e.capabilities.textureFloatLinear;const r=this._getTextureSamplingMethod(this.interpolation),i=this.isRendereredSource;this._rasterTexture=d(e,t,r,i),this.projected=!1,this._processed=!1,this._rasterTextureBandIds=this.bandIds?[...this.bandIds]:null}_isBandIdsChanged(e){const t=this._rasterTextureBandIds;return!(null==t&&null==e||t&&e&&t.join("")===e.join(""))}_isValidSource(e){return null!=e&&e.pixels?.length>0}_getTextureSamplingMethod(e){const{type:t}=this.symbolizerParameters,s="lut"===t&&!this.symbolizerParameters.isClassBreaks||"hillshade"===t||"stretch"===t&&1===this.symbolizerParameters.bandCount;return!this._supportsBilinearTexture||s||"bilinear"!==e&&"cubic"!==e?"nearest":"bilinear"}_updateColormapTexture(e){const t=this._colormap,s=this.symbolizerParameters.colormap;return s?t?s.length!==t.length||s.some(((e,s)=>e!==t[s]))?(this._colormapTexture&&(this._colormapTexture.dispose(),this._colormapTexture=null),this._colormapTexture=p(e,s),void(this._colormap=s)):void 0:(this._colormapTexture=p(e,s),void(this._colormap=s)):(this._colormapTexture&&(this._colormapTexture.dispose(),this._colormapTexture=null),void(this._colormap=null))}_disposeTextures(e=!1){!this._transformGridTexture||e&&!this.projected||(this._transformGridTexture.dispose(),this._transformGridTexture=null),!e&&this._colormapTexture&&(this._colormapTexture.dispose(),this._colormapTexture=null,this._colormap=null,this._colormapTextureInvalidated=!0),!e&&this._rasterTexture&&(this._rasterTexture.dispose(),this._rasterTexture=null,this._rasterTextureBandIds=null),this._processedTexture&&(this._processedTexture.dispose(),this._processedTexture=null)}}class x extends _{get source(){return this._source}}function m(e){return null!=e.source}export{_ as RasterBitmap,x as RasterBitmapWithSource,m as hasSource};
5
+ import{disposeMaybe as e}from"../../../../core/maybe.js";import{identity as t,translate as s,rotate as r,scaleByVec2 as i,multiply as o}from"../../../../core/libs/gl-matrix-2/math/mat3.js";import{create as a}from"../../../../core/libs/gl-matrix-2/factories/mat3f32.js";import{fromValues as u}from"../../../../core/libs/gl-matrix-2/factories/vec2f32.js";import{DisplayObject as h}from"../DisplayObject.js";import{TextureSamplingMode as n}from"../../../webgl/enums.js";import{createTransformTexture as l,createRasterTexture as d,createColormapTexture as c}from"../../../webgl/rasterUtils.js";const p={bandCount:3,minOutput:0,maxOutput:1,minCutOff:[0,0,0],maxCutOff:[255,255,255],factor:[1/255,1/255,1/255],useGamma:!1,gamma:[1,1,1],gammaCorrection:[1,1,1],colormap:null,colormapOffset:null,stretchType:"none",type:"stretch"};class _ extends h{constructor(e=null,t=null,s=null){super(),this._textureInvalidated=!0,this._colormapTextureInvalidated=!0,this._rasterTexture=null,this._rasterTextureBandIds=null,this._transformGridTexture=null,this._colormapTexture=null,this._colormap=null,this._supportsBilinearTexture=!0,this._processedTexture=null,this.functionTextures=[],this.projected=!1,this.stencilRef=0,this.coordScale=[1,1],this._processed=!1,this._symbolizerParameters=null,this.height=null,this.isRendereredSource=!1,this.pixelRatio=1,this.resolution=0,this.rotation=0,this._source=null,this.rawPixelData=null,this._suspended=!1,this._bandIds=null,this._interpolation=null,this._transformGrid=null,this.width=null,this.x=0,this.y=0,this.source=e,this.transformGrid=t,this.interpolation=s}destroy(){this._disposeTextures()}get processedTexture(){return this._processedTexture}set processedTexture(e){this._processedTexture!==e&&(this._disposeTextures(!0),this._processedTexture=e)}get rasterTexture(){return this._rasterTexture}set rasterTexture(e){this._rasterTexture!==e&&(this._rasterTexture?.dispose(),this._rasterTexture=e),null==e&&(this.projected=!1)}get processed(){return this._processed}set processed(t){this._processed=t,t||(e(this.processedTexture),this.invalidateTexture())}get symbolizerParameters(){return this._symbolizerParameters||p}set symbolizerParameters(e){this._symbolizerParameters!==e&&(this._symbolizerParameters=e,this._colormapTextureInvalidated=!0,this.commonUniforms=null)}get source(){return this._source}set source(e){this._source!==e&&(this._source=e,this._rasterTexture&&(this._rasterTexture.dispose(),this._rasterTexture=null,this._rasterTextureBandIds=null),this.commonUniforms=null,this.projected=!1,this.invalidateTexture())}get suspended(){return this._suspended}set suspended(e){this._suspended&&!e&&this.stage&&(this.ready(),this.requestRender()),this._suspended=e}get bandIds(){return this._bandIds}set bandIds(e){this._bandIds=e,this._isBandIdsChanged(e)&&(this.projected=!1,this.invalidateTexture())}get interpolation(){return this._interpolation||"nearest"}set interpolation(e){this._interpolation=e,this._rasterTexture&&this._rasterTexture.setSamplingMode("bilinear"===this._getTextureSamplingMethod(e||"nearest")?n.LINEAR:n.NEAREST)}get transformGrid(){return this._transformGrid}set transformGrid(t){this._transformGrid!==t&&(this._transformGrid=t,this._transformGridTexture=e(this._transformGridTexture))}invalidateTexture(){this._textureInvalidated||(this._textureInvalidated=!0,this.requestRender())}getRasterTextureSize(e=!1){const t=e||this.projected;return[t?this.width:this.source?.width||this.width,t?this.height:this.source?.height||this.height]}getRasterCellSize(){const e=this.rawPixelData?.srcPixelSize,{projected:t,resolution:s}=this;return e&&!t?[e.x,e.y]:[s,s]}_createTransforms(){return{displayViewScreenMat3:a()}}setTransform(e){const a=t(this.transforms.displayViewScreenMat3),[h,n]=e.toScreenNoRotation([0,0],[this.x,this.y]),l=this.resolution/this.pixelRatio/e.resolution,d=l*this.width,c=l*this.height,p=Math.PI*this.rotation/180;s(a,a,u(h,n)),s(a,a,u(d/2,c/2)),r(a,a,-p),s(a,a,u(-d/2,-c/2)),i(a,a,u(d,c)),o(this.transforms.displayViewScreenMat3,e.displayViewMat3,a)}getTextures({forProcessing:e=!1,useProcessedTexture:t=!1}={}){const s=t?this._processedTexture??this._rasterTexture:this._rasterTexture,r=[],i=[];return s?(this._transformGridTexture&&!this.projected&&(i.push(this._transformGridTexture),r.push("u_transformGrid")),i.push(s),r.push("u_image"),!this._colormapTexture||!t&&e||(i.push(this._colormapTexture),r.push("u_colormap")),{names:r,textures:i}):{names:r,textures:i}}onAttach(){this.invalidateTexture()}onDetach(){this.invalidateTexture()}updateTexture({context:e}){if(!this.stage)return void this._disposeTextures();const t=this._isValidSource(this.source);t&&this._colormapTextureInvalidated&&(this._colormapTextureInvalidated=!1,this._updateColormapTexture(e)),this._textureInvalidated&&(this._textureInvalidated=!1,this._createOrDestroyRasterTexture(e),this._rasterTexture&&(t?this.transformGrid&&!this._transformGridTexture&&(this._transformGridTexture=l(e,this.transformGrid)):this._rasterTexture.setData(null)),this.suspended||(this.ready(),this.requestRender()))}updateProcessedTexture(){const{functionTextures:e}=this;0!==e.length&&(this.processedTexture=e.shift(),e.forEach((e=>e?.dispose())),e.length=0,this.processed=!!this.processedTexture)}_createOrDestroyRasterTexture(e){const t=this.source?.extractBands(this.bandIds);if(!this._isValidSource(t))return void(this._rasterTexture&&(this._rasterTexture.dispose(),this._rasterTextureBandIds=null,this._rasterTexture=null));const s=!this._isBandIdsChanged(this.bandIds);if(this._rasterTexture){if(s)return;this._rasterTexture.dispose(),this._rasterTextureBandIds=null,this._rasterTexture=null}this._supportsBilinearTexture=!!e.capabilities.textureFloatLinear;const r=this._getTextureSamplingMethod(this.interpolation),i=this.isRendereredSource;this._rasterTexture=d(e,t,r,i),this.projected=!1,this._processed=!1,this._rasterTextureBandIds=this.bandIds?[...this.bandIds]:null}_isBandIdsChanged(e){const t=this._rasterTextureBandIds;return!(null==t&&null==e||t&&e&&t.join("")===e.join(""))}_isValidSource(e){return null!=e&&e.pixels?.length>0}_getTextureSamplingMethod(e){const{type:t}=this.symbolizerParameters,s="lut"===t&&!this.symbolizerParameters.isClassBreaks||"hillshade"===t||"stretch"===t&&1===this.symbolizerParameters.bandCount;return!this._supportsBilinearTexture||s||"bilinear"!==e&&"cubic"!==e?"nearest":"bilinear"}_updateColormapTexture(e){const t=this._colormap,s=this.symbolizerParameters.colormap;return s?t?s.length!==t.length||s.some(((e,s)=>e!==t[s]))?(this._colormapTexture&&(this._colormapTexture.dispose(),this._colormapTexture=null),this._colormapTexture=c(e,s),void(this._colormap=s)):void 0:(this._colormapTexture=c(e,s),void(this._colormap=s)):(this._colormapTexture&&(this._colormapTexture.dispose(),this._colormapTexture=null),void(this._colormap=null))}_disposeTextures(e=!1){!this._transformGridTexture||e&&!this.projected||(this._transformGridTexture.dispose(),this._transformGridTexture=null),!e&&this._colormapTexture&&(this._colormapTexture.dispose(),this._colormapTexture=null,this._colormap=null,this._colormapTextureInvalidated=!0),!e&&this._rasterTexture&&(this._rasterTexture.dispose(),this._rasterTexture=null,this._rasterTextureBandIds=null),this._processedTexture&&(this._processedTexture.dispose(),this._processedTexture=null)}}class x extends _{get source(){return this._source}}function m(e){return null!=e.source}export{_ as RasterBitmap,x as RasterBitmapWithSource,m as hasSource};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.33/esri/copyright.txt for details.
4
4
  */
5
- import{_ as e}from"../../../chunks/tslib.es6.js";import t from"../../../Color.js";import r from"../../../Graphic.js";import{destroyMaybe as i}from"../../../core/maybe.js";import{watch as s,initial as l}from"../../../core/reactiveUtils.js";import{property as o}from"../../../core/accessorSupport/decorators/property.js";import"../../../core/has.js";import"../../../core/Logger.js";import"../../../core/RandomLCG.js";import{subclass as a}from"../../../core/accessorSupport/decorators/subclass.js";import n from"../../../layers/GraphicsLayer.js";import m from"../../../layers/support/TelemetryDisplay.js";import y from"../../../symbols/SimpleFillSymbol.js";import h from"../../../symbols/SimpleLineSymbol.js";import p from"../../../symbols/SimpleMarkerSymbol.js";import{applyCIMSymbolRotation as c,applyCIMSymbolColor as b}from"../../../symbols/support/cimSymbolUtils.js";import{symbolTypes as u}from"../../../symbols/support/typeUtils.js";import f from"../engine/webgl/OverlayContainer.js";import d from"../engine/webgl/OverlayMultipoint.js";import{LayerView2DMixin as g}from"./LayerView2D.js";import S from"./graphics/GraphicContainer.js";import _ from"./graphics/GraphicsView2D.js";import C from"../../layers/LayerView.js";const L=new t([255,127,0]),v=10005;let T=class extends(g(C)){constructor(){super(...arguments),this._graphicsLayer=new n,this._frameOutlineGraphic=new r({symbol:new y({outline:{type:"simple-line",color:L}})}),this._frameCenterGraphic=new r({symbol:new p({color:L,style:"cross"})}),this._sensorTrailGraphic=new r({symbol:new h({color:L})}),this._sensorSightlineGraphic=new r({symbol:new h({color:L})}),this._sensorLocationGraphic=new r({symbol:new p({color:L})}),this._overlayContainer=null,this._sensorLocationSymbolType=null,this.layer=null,this.sensorLocationSymbol=null,this.symbolAngle=0,this.visibleTelemetryElements=null}destroy(){this._graphicsLayer=i(this._graphicsLayer)}initialize(){this._sensorLocationSymbolType=this.layer?.sensorSymbol.type,this._graphicsLayer.graphics.addMany([this._frameCenterGraphic,this._frameOutlineGraphic,this._sensorLocationGraphic,this._sensorSightlineGraphic,this._sensorTrailGraphic]),this.visibleTelemetryElements=new m({frame:this.layer.telemetryDisplay?.frame??!1,frameCenter:this.layer.telemetryDisplay?.frameCenter??!0,frameOutline:this.layer.telemetryDisplay?.frameOutline??!0,lineOfSight:this.layer.telemetryDisplay?.lineOfSight??!0,sensorLocation:this.layer.telemetryDisplay?.sensorLocation??!0,sensorTrail:this.layer.telemetryDisplay?.sensorTrail??!0})}attach(){this._overlayContainer=new f,this.container.addChild(this._overlayContainer),this._addOverlayMultipoint(),this.graphicsView=new _({requestUpdateCallback:()=>this.requestUpdate(),view:this.view,graphics:this._graphicsLayer.graphics,container:new S(this.view.featuresTilingScheme)}),this.container.addChild(this.graphicsView.container),this.addAttachHandles(this._graphicsLayer.on("graphic-update",this.graphicsView.graphicUpdateHandler)),this.addAttachHandles([s((()=>[this.layer.telemetryDisplay?.frame,this.layer.telemetryDisplay?.frameCenter,this.layer.telemetryDisplay?.frameOutline,this.layer.telemetryDisplay?.sensorLocation,this.layer.telemetryDisplay?.sensorTrail,this.layer.telemetryDisplay?.lineOfSight]),(()=>this._updateVisibleTelemetryElements()),l),s((()=>[this.layer.telemetry,this.visibleTelemetryElements?.frameCenter,this.visibleTelemetryElements?.frameOutline,this.visibleTelemetryElements?.sensorLocation,this.visibleTelemetryElements?.sensorTrail,this.visibleTelemetryElements?.lineOfSight]),(()=>this._updateGraphicGeometries()),l),s((()=>this.layer.metadata),(()=>this._updateSensorLocationSymbolAngle()),l),s((()=>this.layer?.frameCenterSymbol),(()=>this._updateFrameCenterSymbol()),l),s((()=>this.layer?.frameOutlineSymbol),(()=>this._updateFrameOutlineSymbol()),l),s((()=>this.layer?.sensorSightLineSymbol),(()=>this._updateSensorSightlineSymbol()),l),s((()=>this.layer?.sensorSymbol),(()=>this._updateSensorLocationSymbol()),l),s((()=>this.layer?.sensorTrailSymbol),(()=>this._updateSensorTrailSymbol()),l),s((()=>this.layer?.telemetryColor),(()=>this._updateTelemetryColor()),l)])}detach(){this._overlayContainer.removeAllChildren(),this.container.removeAllChildren(),this.graphicsView=i(this.graphicsView)}supportsSpatialReference(e){return!0}moveEnd(){}viewChange(){this.graphicsView.viewChange()}update(e){this.graphicsView.processUpdate(e)}isUpdating(){return!this.graphicsView||this.graphicsView.updating}_updateVisibleTelemetryElements(){this.visibleTelemetryElements&&this.layer.telemetryDisplay&&(this.visibleTelemetryElements.frame=this.layer.telemetryDisplay.frame,this.visibleTelemetryElements.frameCenter=this.layer.telemetryDisplay.frameCenter,this.visibleTelemetryElements.frameOutline=this.layer.telemetryDisplay.frameOutline,this.visibleTelemetryElements.lineOfSight=this.layer.telemetryDisplay.lineOfSight,this.visibleTelemetryElements.sensorLocation=this.layer.telemetryDisplay.sensorLocation,this.visibleTelemetryElements.sensorTrail=this.layer.telemetryDisplay.sensorTrail)}_updateGraphicGeometries(){const{telemetry:e}=this.layer,{visibleTelemetryElements:t}=this;e&&t&&(t.frameOutline&&e.frameOutline?this._frameOutlineGraphic.geometry=this.layer.telemetry.frameOutline:this._frameOutlineGraphic.geometry=null,t.sensorTrail&&e.sensorTrail?this._sensorTrailGraphic.geometry=this.layer.telemetry.sensorTrail:this._sensorTrailGraphic.geometry=null,t.lineOfSight&&e.lineOfSight?this._sensorSightlineGraphic.geometry=this.layer.telemetry.lineOfSight:this._sensorSightlineGraphic.geometry=null,t.sensorLocation&&e.sensorLocation?this._sensorLocationGraphic.geometry=this.layer.telemetry.sensorLocation:this._sensorLocationGraphic.geometry=null,t.frameCenter&&e.frameCenter?this._frameCenterGraphic.geometry=this.layer.telemetry.frameCenter:this._frameCenterGraphic.geometry=null)}_updateSensorLocationSymbolAngle(){if(!this.layer?.metadata?.size||!this._sensorLocationGraphic.symbol)return;const e=this.layer?.metadata?.get(v);if(!e?.value||"number"!=typeof e?.value)return;this.symbolAngle=Math.round(e?.value);const t=this._sensorLocationGraphic.symbol.clone();"simple-marker"===t.type||"picture-marker"===t.type?t.angle=this.symbolAngle:"cim"===t.type&&c(t,this.symbolAngle,!0),this._sensorLocationGraphic.symbol=t}_updateSensorLocationSymbolColor(){if(!this._sensorLocationGraphic?.symbol)return;const e=this._sensorLocationGraphic.symbol.clone();"simple-marker"===e.type?(e.color=this.layer?.telemetryColor||L,e.outline.color=this.layer.telemetryColor):"picture-marker"===e.type?e.color=this.layer?.telemetryColor||L:"cim"===e.type&&(e.color=this.layer?.telemetryColor||L,e?.color&&b(e,e.color||L)),this._sensorLocationGraphic.symbol=e.clone()}_updateTelemetryColor(){this._frameOutlineGraphic.symbol.outline.color=this.layer?.telemetryColor||L,this._sensorTrailGraphic.symbol.color=this.layer?.telemetryColor||L,this._sensorSightlineGraphic.symbol.color=this.layer?.telemetryColor||L,this._frameCenterGraphic.symbol.color=this.layer?.telemetryColor||L,this._updateSensorLocationSymbolColor()}_updateSensorLocationSymbol(){switch(this._sensorLocationSymbolType){case"simple-marker":case"picture-marker":case"cim":this.sensorLocationSymbol=this.layer.sensorSymbol,this._sensorLocationGraphic.symbol=this.sensorLocationSymbol}}_updateFrameCenterSymbol(){this.layer?.frameCenterSymbol&&(this._frameCenterGraphic.symbol=this.layer.frameCenterSymbol.clone())}_updateFrameOutlineSymbol(){this.layer?.frameOutlineSymbol&&(this._frameOutlineGraphic.symbol=this.layer.frameOutlineSymbol.clone())}_updateSensorSightlineSymbol(){this.layer?.sensorSightLineSymbol&&(this._sensorSightlineGraphic.symbol=this.layer.sensorSightLineSymbol.clone())}_updateSensorTrailSymbol(){this.layer?.sensorTrailSymbol&&(this._sensorTrailGraphic.symbol=this.layer.sensorTrailSymbol.clone())}async _addOverlayMultipoint(){if(!this.layer.videoElement)return;const e=new d(this.layer.videoElement);this.addAttachHandles([s((()=>[this.layer.frameHorizonPoints,this.layer.groundControlPoints]),(()=>{const{visibleTelemetryElements:t}=this;t?.frame?(e.frameHorizonPoints=this.layer.frameHorizonPoints,e.groundControlPoints=this.layer.groundControlPoints,e.opacity=1):e.opacity=0}),l)]),this._overlayContainer.addChild(e),this.view.stage.requestRender()}};e([o()],T.prototype,"graphicsView",void 0),e([o()],T.prototype,"layer",void 0),e([o({types:u})],T.prototype,"sensorLocationSymbol",void 0),e([o()],T.prototype,"symbolAngle",void 0),e([o({type:m})],T.prototype,"visibleTelemetryElements",void 0),T=e([a("esri.views.2d.layers.VideoLayerView2D")],T);const G=T;export{G as default};
5
+ import{_ as e}from"../../../chunks/tslib.es6.js";import t from"../../../Color.js";import r from"../../../Graphic.js";import{destroyMaybe as i}from"../../../core/maybe.js";import{watch as s,initial as l}from"../../../core/reactiveUtils.js";import{property as o}from"../../../core/accessorSupport/decorators/property.js";import"../../../core/has.js";import"../../../core/Logger.js";import"../../../core/RandomLCG.js";import{subclass as a}from"../../../core/accessorSupport/decorators/subclass.js";import n from"../../../layers/GraphicsLayer.js";import m from"../../../layers/support/TelemetryDisplay.js";import y from"../../../symbols/SimpleFillSymbol.js";import h from"../../../symbols/SimpleLineSymbol.js";import p from"../../../symbols/SimpleMarkerSymbol.js";import{applyCIMSymbolRotation as c,applyCIMSymbolColor as b}from"../../../symbols/support/cimSymbolUtils.js";import{symbolTypes as u}from"../../../symbols/support/typeUtils.js";import f from"../engine/webgl/OverlayContainer.js";import d from"../engine/webgl/OverlayMultipoint.js";import{LayerView2DMixin as g}from"./LayerView2D.js";import S from"./graphics/GraphicContainer.js";import _ from"./graphics/GraphicsView2D.js";import C from"../../layers/LayerView.js";const L=new t([255,127,0]),v=10005;let T=class extends(g(C)){constructor(){super(...arguments),this._graphicsLayer=new n,this._frameOutlineGraphic=new r({symbol:new y({outline:{type:"simple-line",color:L}})}),this._frameCenterGraphic=new r({symbol:new p({color:L,style:"cross"})}),this._sensorTrailGraphic=new r({symbol:new h({color:L})}),this._sensorSightlineGraphic=new r({symbol:new h({color:L})}),this._sensorLocationGraphic=new r({symbol:new p({color:L})}),this._overlayContainer=null,this._sensorLocationSymbolType=null,this.layer=null,this.sensorLocationSymbol=null,this.symbolAngle=0,this.visibleTelemetryElements=null}destroy(){this._graphicsLayer=i(this._graphicsLayer)}initialize(){this._sensorLocationSymbolType=this.layer?.sensorSymbol.type,this._graphicsLayer.graphics.addMany([this._frameCenterGraphic,this._frameOutlineGraphic,this._sensorLocationGraphic,this._sensorSightlineGraphic,this._sensorTrailGraphic]),this.visibleTelemetryElements=new m({frame:this.layer.telemetryDisplay?.frame??!1,frameCenter:this.layer.telemetryDisplay?.frameCenter??!0,frameOutline:this.layer.telemetryDisplay?.frameOutline??!0,lineOfSight:this.layer.telemetryDisplay?.lineOfSight??!0,sensorLocation:this.layer.telemetryDisplay?.sensorLocation??!0,sensorTrail:this.layer.telemetryDisplay?.sensorTrail??!0})}attach(){this._overlayContainer=new f,this.container.addChild(this._overlayContainer),this._addOverlayMultipoint(),this.graphicsView=new _({requestUpdateCallback:()=>this.requestUpdate(),view:this.view,graphics:this._graphicsLayer.graphics,container:new S(this.view.featuresTilingScheme)}),this.container.addChild(this.graphicsView.container),this.addAttachHandles(this._graphicsLayer.on("graphic-update",this.graphicsView.graphicUpdateHandler)),this.addAttachHandles([s((()=>[this.layer.telemetryDisplay?.frame,this.layer.telemetryDisplay?.frameCenter,this.layer.telemetryDisplay?.frameOutline,this.layer.telemetryDisplay?.sensorLocation,this.layer.telemetryDisplay?.sensorTrail,this.layer.telemetryDisplay?.lineOfSight]),(()=>this._updateVisibleTelemetryElements()),l),s((()=>[this.layer.telemetry,this.visibleTelemetryElements?.frameCenter,this.visibleTelemetryElements?.frameOutline,this.visibleTelemetryElements?.sensorLocation,this.visibleTelemetryElements?.sensorTrail,this.visibleTelemetryElements?.lineOfSight]),(()=>this._updateGraphicGeometries()),l),s((()=>this.layer.metadata),(()=>this._updateSensorLocationSymbolAngle()),l),s((()=>this.layer?.frameCenterSymbol),(()=>this._updateFrameCenterSymbol()),l),s((()=>this.layer?.frameOutlineSymbol),(()=>this._updateFrameOutlineSymbol()),l),s((()=>this.layer?.sensorSightLineSymbol),(()=>this._updateSensorSightlineSymbol()),l),s((()=>this.layer?.sensorSymbol),(()=>this._updateSensorLocationSymbol()),l),s((()=>this.layer?.sensorTrailSymbol),(()=>this._updateSensorTrailSymbol()),l),s((()=>this.layer?.telemetryColor),(()=>this._updateTelemetryColor()),l)])}detach(){this._overlayContainer.removeAllChildren(),this.container.removeAllChildren(),this.graphicsView=i(this.graphicsView)}supportsSpatialReference(e){return!0}moveEnd(){}viewChange(){this.graphicsView.viewChange()}update(e){this.graphicsView.processUpdate(e)}isUpdating(){return!this.graphicsView||this.graphicsView.updating}_updateVisibleTelemetryElements(){this.visibleTelemetryElements&&this.layer.telemetryDisplay&&(this.visibleTelemetryElements.frame=this.layer.telemetryDisplay.frame,this.visibleTelemetryElements.frameCenter=this.layer.telemetryDisplay.frameCenter,this.visibleTelemetryElements.frameOutline=this.layer.telemetryDisplay.frameOutline,this.visibleTelemetryElements.lineOfSight=this.layer.telemetryDisplay.lineOfSight,this.visibleTelemetryElements.sensorLocation=this.layer.telemetryDisplay.sensorLocation,this.visibleTelemetryElements.sensorTrail=this.layer.telemetryDisplay.sensorTrail)}_updateGraphicGeometries(){const{telemetry:e}=this.layer,{visibleTelemetryElements:t}=this;e&&t&&(t.frameOutline&&e.frameOutline?this._frameOutlineGraphic.geometry=this.layer.telemetry.frameOutline:this._frameOutlineGraphic.geometry=null,t.sensorTrail&&e.sensorTrail?this._sensorTrailGraphic.geometry=this.layer.telemetry.sensorTrail:this._sensorTrailGraphic.geometry=null,t.lineOfSight&&e.lineOfSight?this._sensorSightlineGraphic.geometry=this.layer.telemetry.lineOfSight:this._sensorSightlineGraphic.geometry=null,t.sensorLocation&&e.sensorLocation?this._sensorLocationGraphic.geometry=this.layer.telemetry.sensorLocation:this._sensorLocationGraphic.geometry=null,t.frameCenter&&e.frameCenter?this._frameCenterGraphic.geometry=this.layer.telemetry.frameCenter:this._frameCenterGraphic.geometry=null)}_updateSensorLocationSymbolAngle(){if(!this.layer?.metadata?.size||!this._sensorLocationGraphic.symbol)return;const e=this.layer?.metadata?.get(v);if(!e?.value||"number"!=typeof e?.value)return;this.symbolAngle=Math.round(e?.value);const t=this._sensorLocationGraphic.symbol.clone();"simple-marker"===t.type||"picture-marker"===t.type?t.angle=this.symbolAngle:"cim"===t.type&&c(t,this.symbolAngle,!0),this._sensorLocationGraphic.symbol=t}_updateSensorLocationSymbolColor(){if(!this._sensorLocationGraphic?.symbol)return;const e=this._sensorLocationGraphic.symbol.clone();"simple-marker"===e.type?(e.color=this.layer?.telemetryColor||L,e.outline.color=this.layer.telemetryColor):"picture-marker"===e.type?e.color=this.layer?.telemetryColor||L:"cim"===e.type&&(e.color=this.layer?.telemetryColor||L,e?.color&&b(e,e.color||L)),this._sensorLocationGraphic.symbol=e.clone()}_updateTelemetryColor(){this._frameOutlineGraphic.symbol.outline.color=this.layer?.telemetryColor||L,this._sensorTrailGraphic.symbol.color=this.layer?.telemetryColor||L,this._sensorSightlineGraphic.symbol.color=this.layer?.telemetryColor||L,this._frameCenterGraphic.symbol.color=this.layer?.telemetryColor||L,this._updateSensorLocationSymbolColor()}_updateSensorLocationSymbol(){switch(this._sensorLocationSymbolType){case"simple-marker":case"picture-marker":case"cim":this.sensorLocationSymbol=this.layer.sensorSymbol,this._sensorLocationGraphic.symbol=this.sensorLocationSymbol}}_updateFrameCenterSymbol(){this.layer?.frameCenterSymbol&&(this._frameCenterGraphic.symbol=this.layer.frameCenterSymbol.clone())}_updateFrameOutlineSymbol(){this.layer?.frameOutlineSymbol&&(this._frameOutlineGraphic.symbol=this.layer.frameOutlineSymbol.clone())}_updateSensorSightlineSymbol(){this.layer?.sensorSightLineSymbol&&(this._sensorSightlineGraphic.symbol=this.layer.sensorSightLineSymbol.clone())}_updateSensorTrailSymbol(){this.layer?.sensorTrailSymbol&&(this._sensorTrailGraphic.symbol=this.layer.sensorTrailSymbol.clone())}async _addOverlayMultipoint(){if(!this.layer.videoElement)return;const e=new d(this.layer.videoElement);this.addAttachHandles([s((()=>[this.layer.frameHorizonPoints,this.layer.groundControlPoints,this.layer.frameOpacity]),(()=>{const{visibleTelemetryElements:t}=this;e.frameHorizonPoints=this.layer.frameHorizonPoints,e.groundControlPoints=this.layer.groundControlPoints,e.opacity=this.layer.frameOpacity,e.visible=t?.frame??!1}),l)]),this._overlayContainer.addChild(e),this.view.stage.requestRender()}};e([o()],T.prototype,"graphicsView",void 0),e([o()],T.prototype,"layer",void 0),e([o({types:u})],T.prototype,"sensorLocationSymbol",void 0),e([o()],T.prototype,"symbolAngle",void 0),e([o({type:m})],T.prototype,"visibleTelemetryElements",void 0),T=e([a("esri.views.2d.layers.VideoLayerView2D")],T);const G=T;export{G as default};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.33/esri/copyright.txt for details.
4
4
  */
5
- import{_ as i}from"../../../../chunks/tslib.es6.js";import t from"../../../../core/Accessor.js";import{lerp as e}from"../../../../core/mathUtils.js";import{destroyMaybe as s}from"../../../../core/maybe.js";import{property as r}from"../../../../core/accessorSupport/decorators/property.js";import"../../../../core/has.js";import"../../../../core/Logger.js";import"../../../../core/RandomLCG.js";import{subclass as c}from"../../../../core/accessorSupport/decorators/subclass.js";import{transpose as o}from"../../../../core/libs/gl-matrix-2/math/mat4.js";import{create as n}from"../../../../core/libs/gl-matrix-2/factories/mat4f64.js";import{create as a}from"../../../../core/libs/gl-matrix-2/factories/vec2f64.js";import{t as l,g as h,i as u,c as d}from"../../../../chunks/vec32.js";import{ZEROS as p,create as f}from"../../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{s as _,t as m,b as g}from"../../../../chunks/vec42.js";import{create as y}from"../../../../core/libs/gl-matrix-2/factories/vec4f64.js";import{UpdatingHandles as v}from"../../../../core/support/UpdatingHandles.js";import{getReferenceEllipsoid as b}from"../../../../geometry/ellipsoidUtils.js";import{create as O,empty as w,copy as I,offset as D,width as C,height as j,expand as G}from"../../../../geometry/support/aaBoundingRect.js";import{e as k,d as S,a as A}from"../../../../chunks/boundedPlane.js";import{create as N}from"../../../../geometry/support/ray.js";import{a as P,c as T,j as x,h as E}from"../../../../chunks/sphere.js";import{DeconflictAABR as Q}from"./DeconflictAABR.js";import{prepare as V,drawPoly as L}from"./deconflictorDebug.js";import{VisibilityGroup as F,VisibilityFlag as R}from"./enums.js";import H from"../../webgl/RenderCamera.js";import{GPUPointOcclusionQuery as U}from"../../webgl-engine/lib/GPUPointOcclusionQuery.js";import{applyPrecomputedScaleFactor as B}from"../../webgl-engine/lib/screenSizePerspectiveUtils.js";import{VertexAttribute as M}from"../../webgl-engine/lib/VertexAttribute.js";import{HUDMaterial as W}from"../../webgl-engine/materials/HUDMaterial.js";import{ScaleInfo as z}from"../../webgl-engine/materials/ScaleInfo.js";import{Yield as Y}from"../../../support/Yield.js";const q=f(),J=f(),K=y(),X=y(),Z=f(),$=n(),ii=T(),ti=N(),ei=f(),si=O();class ri{constructor(i){this.id=i,this.aabr=O(),this.altitude=0,this.distance=0,this.distanceToOccluder=0,this.culled=!1,this.visible=!1,this.priority=0}}function ci(i,t){const e=0!==i.distanceToOccluder&&i.distance>i.distanceToOccluder,s=0!==t.distanceToOccluder&&t.distance>t.distanceToOccluder;return e!==s?+e-+s:i.priority!==t.priority?t.priority-i.priority:i.distance!==t.distance?i.distance-t.distance:i.visible!==t.visible?+t.visible-+i.visible:i.id-t.id}class oi{constructor(i,t){this.graphics3DGraphic=i,this.slicePlaneEnabled=t,this._info=null,this._labelInfo=null}ensureInfo(i){let t=this.getInfo(i);return t||(t=new ri(this.graphics3DGraphic.graphic.uid),this._setInfo(i,t)),t}getInfo(i){return i===F.LABEL?this._labelInfo:this._info}removeInfo(i){this._setInfo(i,null)}_setInfo(i,t){i===F.LABEL?this._labelInfo=t:this._info=t}}var ni;!function(i){i[i.Idle=0]="Idle",i[i.CheckOcclusion=1]="CheckOcclusion",i[i.WaitOcclusion=2]="WaitOcclusion",i[i.Collect=3]="Collect",i[i.Deconflict=4]="Deconflict",i[i.NumStates=5]="NumStates"}(ni||(ni={}));class ai{constructor(){this.camera=new H,this.slicePlane=S(),this.slicePlaneEnabled=!1}copyFrom(i){this.camera.copyFrom(i.camera),A(i.slicePlane,this.slicePlane),this.slicePlaneEnabled=i.slicePlaneEnabled}}let li=class extends t{get dirty(){return this._dirty}get state(){return this._state}constructor(i){super(i),this._dirty=!1,this._viewState=new ai,this._state=ni.Idle,this._checkOcclusion=new Map,this._active=new Map,this._checkOcclusionIterator=null,this._activeIterator=null,this._occlusionQueryUids=new Array,this._updatingHandles=new v,this._deconflictor=new Q(((i,t)=>{i.visible=t,this._setGraphicVisibility(this._active.get(i.id),t)}),((i,t)=>i.id!==t.id),ci),this._baseOccludedVisibility=10,this._altitudeFactor=2,this._minAltitudeDifference=100}initialize(){this._updatingHandles.add((()=>(this.view?.map?.ground?.opacity??0)>0),(()=>this.setDirty())),this._updatingHandles.add((()=>this.view.ready),(()=>this._occlusionQuery=null))}destroy(){this._occlusionQuery=null,this._updatingHandles.destroy(),this._deconflictor.destroy(),this._checkOcclusion.clear(),this._active.clear()}setDirty(){!this._dirty&&(this._active.size>0||this._checkOcclusion.size>0)&&(this._dirty=!0,this.notifyChange("updating"))}setPriority(i,t){const e=this._active.get(i.graphic.uid)?.getInfo(this.visibilityGroup);e&&(e.priority=t)}get updating(){return this._state!==ni.Idle||this._dirty||this._updatingHandles.updating}get updatingProgress(){if(!this.updating)return 1;const i=this._state/ni.NumStates;return this._dirty?.5*i:i}get running(){return this.view.ready&&null!=this.view.state&&this.updating}runTask(i){switch(this._state){case ni.Idle:this._startUpdate(),i.madeProgress();case ni.CheckOcclusion:if(this._state=ni.CheckOcclusion,!this._processCheckOcclusion(i))return;case ni.WaitOcclusion:if(this._state=ni.WaitOcclusion,this._occlusionQuery&&!this._occlusionQuery.done)return Y;this._readOcclusionQueryResult(),i.madeProgress();case ni.Collect:if(this._state=ni.Collect,!this._collectActiveGraphics(i))return;case ni.Deconflict:if(this._state=ni.Deconflict,this._deconflictor.run(i),!this._deconflictor.done)return;default:this._state=ni.Idle,this.notifyChange("updating")}}setGraphicsActive(i,t){t?i.forEach((i=>this.addToActiveGraphics(i))):i.forEach((i=>this.removeFromActiveGraphics(i)))}layerSupportsDeconfliction(i){if(null==i||"object3d"!==i.type)return!1;const t=i.stageObject;if(1!==(t?.geometries.length??0))return!1;const e=t?.geometries[0],s=e?.material;return s instanceof W}_startUpdate(){V(this.view),this._dirty=!1,this._viewState.copyFrom(this.viewState);const{fullWidth:i,fullHeight:t}=this._viewState.camera;this._deconflictor.reset(i,t),this._resetIterators(),this._checkOcclusion.size?(this._occlusionQuery??=new U({view:this.view}),this._occlusionQuery.init(this._checkOcclusion.size,this._viewState.camera.eye),this._occlusionQueryUids.length=0):this._occlusionQuery=s(this._occlusionQuery)}addToActiveGraphics(i){i.ensureInfo(this.visibilityGroup),this._active.set(i.graphics3DGraphic.graphic.uid,i),this.setDirty()}removeFromActiveGraphics(i){hi(i,this.visibilityGroup),i.removeInfo(this.visibilityGroup),this._active.delete(i.graphics3DGraphic.graphic.uid),this.setDirty()}addToCheckOcclusion(i){this._checkOcclusion.set(i.graphics3DGraphic.graphic.uid,i),this.setDirty()}removeFromCheckOcclusion(i){this._checkOcclusion.delete(i.graphics3DGraphic.graphic.uid)}_processCheckOcclusion(i){if(0===this._checkOcclusion.size||!this._occlusionQuery)return!0;const t=this._ensureCheckOcclusionIterator(),e=this._viewState.camera,s=o($,e.viewInverseTransposeMatrix),r=this.view.map.ground.opacity>0,c="global"===this.view.viewingMode&&r&&e.relativeElevation>0?ii:null;let n=0;null!=c&&(l(P(c),p,e.viewMatrix),c[3]=b(this.view.spatialReference).radius,n=x(c,p));const a=O();for(;;){if(i.done)return!1;i.madeProgress();const r=t.next();if(!0===r.done)break;const o=r.value,h=o.graphics3DGraphic;if(h.destroyed)continue;if(!h.isVisible(F.GRAPHIC,R.DECONFLICTION))continue;const u=fi(h,this.visibilityGroup);let d=null,p=!0;for(const i of u){if(!this.layerSupportsDeconfliction(i))continue;d=_i,this._projectHudLayer(i,e,d),w(a);const t=i.stageObject.geometries[0].material;if(this._expandBoundingRect(a,e,i,t,d),d.isOutsideScreen){p=!1;break}if(this._isCulledBySlice(o,d.positionView)){p=!1;break}if(null!=c&&pi(d,c,n)){p=!1;break}l(J,d.positionView,s),d.altitude=this.view.renderCoordsHelper.getAltitude(J);this._occlusionQuery.addPosition(J)===this._occlusionQueryUids.length&&this._occlusionQueryUids.push(h.graphic.uid);const r=o.ensureInfo(this.visibilityGroup);r.altitude=d.altitude,r.distance=d.distance,r.distanceToOccluder=d.distanceToOccluder,r.culled=!1,I(r.aabr,a);break}if(this._active.has(h.graphic.uid)&&(!p||!d)){const i=o.ensureInfo(this.visibilityGroup);i.visible=!d,i.culled=!0}}return this._checkOcclusionIterator=null,this._occlusionQuery?.start(),!0}_readOcclusionQueryResult(){const i=this._viewState.camera,t=this.view.renderCoordsHelper.getAltitude(i.eye);for(let e=0;e<this._occlusionQueryUids.length;e++){const i=this._occlusionQueryUids[e],s=this._checkOcclusion.get(i);if(!s)continue;const r=this._occlusionQuery?.getOcclusion(e)??-1,c=s.getInfo(this.visibilityGroup);c&&(c.distanceToOccluder=r>0?c.distance-r:0);const o=r<=0||this._occludedVisibility(c?.distanceToOccluder??0,c?.distance??r,c?.altitude??0,t);this._active.has(i)?c&&(c.culled=!o,c.visible=o):this._setGraphicVisibility(s,o)}}_collectActiveGraphics(i){const t=this._ensureActiveGraphicsIterator(),e=this.visibilityGroup===F.LABEL;for(;!i.done;){i.madeProgress();const s=t.next();if(!0===s.done)return this._activeIterator=null,!0;const r=s.value,c=r.getInfo(this.visibilityGroup);if(!c)continue;!(!e||r.graphics3DGraphic.isVisible())||c.culled?(L(c.aabr,!1,!0),this._setGraphicVisibility(r,c.visible)):this._deconflictor.add(c)}return!1}_occludedVisibility(i,t,e,s){const r=Math.max(this._minAltitudeDifference,Math.abs(e-s))-this._minAltitudeDifference;return 0===i||t-i<=this._baseOccludedVisibility+this._altitudeFactor*r}_resetIterators(){this._checkOcclusionIterator=null,this._activeIterator=null}_ensureCheckOcclusionIterator(){return this._checkOcclusionIterator??=this._checkOcclusion.values(),this._checkOcclusionIterator}_ensureActiveGraphicsIterator(){return this._activeIterator??=this._active.values(),this._activeIterator}_projectHudLayer(i,t,e){const s=i.stageObject,r=s.geometries[0],c=r.material,o=P(s.boundingVolumeWorldSpace.bounds);l(q,o,t.viewMatrix);const n=r.attributes,a=n.get(M.NORMAL).data,d=n.get(M.CENTEROFFSETANDDISTANCE).data;c.applyShaderOffsetsView(q,a,s.transformation,d,t,e.scaleInfo,q),_(K,q[0],q[1],q[2],1),m(X,K,t.projectionMatrix),h(e.positionNDC,X,1/X[3]),c.applyShaderOffsetsNDC(e.positionNDC,d,t,e.positionNDC,Z),e.distanceWithoutPolygonOffset=t.depthNDCToWorld(Z[2]),e.distance=Z[2]===e.positionNDC[2]?e.distanceWithoutPolygonOffset:t.depthNDCToWorld(e.positionNDC[2]),_(X,e.positionNDC[0],e.positionNDC[1],e.positionNDC[2],1),m(K,X,t.inverseProjectionMatrix),g(K,K,1/K[3]),u(e.positionView,q[0],q[1],q[2])}_isCulledBySlice(i,t){return i.slicePlaneEnabled&&this._viewState.slicePlaneEnabled&&k(this._viewState.slicePlane,t)}_expandBoundingRect(i,t,s,r,{positionNDC:c,scaleInfo:o}){const n=s.getScreenSize(ui);B(n,o.factor,n),n[0]*=t.pixelRatio,n[1]*=t.pixelRatio;const a=D(r.calculateRelativeScreenBounds(n,o.factorAlignment.scale*t.pixelRatio,si),e(0,t.fullWidth,.5+.5*c[0]),e(0,t.fullHeight,.5+.5*c[1])),l=this.marginFactor;if(0!==l){const i=l*Math.min(C(a),j(a));a[0]-=i,a[1]-=i,a[2]+=i,a[3]+=i}G(i,a,i)}_setGraphicVisibility(i,t){const e=i?.graphics3DGraphic;e&&!e.destroyed&&(e.setVisibilityFlag(this.visibilityGroup,R.DECONFLICTION,t),this.visibilityGroup===F.LABEL&&this.view.labeler.setLabelGraphicVisibility(e,t))}};function hi(i,t){const e=i.graphics3DGraphic;e.destroyed||e.setVisibilityFlag(t,R.DECONFLICTION,!0)}i([r({constructOnly:!0})],li.prototype,"view",void 0),i([r({type:Boolean,readOnly:!0})],li.prototype,"updating",null),i([r({readOnly:!0})],li.prototype,"_updatingHandles",void 0),li=i([c("esri.views.3d.layers.graphics.Deconflictor")],li);const ui=a();class di{constructor(){this.positionView=f(),this.positionNDC=f(),this.altitude=0,this.distance=0,this.distanceToOccluder=0,this.distanceWithoutPolygonOffset=0,this.scaleInfo=new z}get isOutsideScreen(){const i=this.positionNDC;return i[0]<-1||i[1]<-1||i[2]<-1||i[0]>=1||i[1]>=1||i[2]>=1}}function pi(i,t,e){return d(ti.direction,i.positionView),u(ti.origin,0,0,0),!!E(t,ti,ei)&&i.distanceWithoutPolygonOffset>e}function fi(i,t){return t===F.LABEL?i.labelLayers:i.layers}const _i=new di;export{li as Deconflictor,oi as DeconflictorGraphic,ai as DeconflictorViewState,ni as State};
5
+ import{_ as i}from"../../../../chunks/tslib.es6.js";import t from"../../../../core/Accessor.js";import{lerp as e}from"../../../../core/mathUtils.js";import{destroyMaybe as s}from"../../../../core/maybe.js";import{property as r}from"../../../../core/accessorSupport/decorators/property.js";import"../../../../core/has.js";import"../../../../core/Logger.js";import"../../../../core/RandomLCG.js";import{subclass as c}from"../../../../core/accessorSupport/decorators/subclass.js";import{transpose as o}from"../../../../core/libs/gl-matrix-2/math/mat4.js";import{create as n}from"../../../../core/libs/gl-matrix-2/factories/mat4f64.js";import{create as a}from"../../../../core/libs/gl-matrix-2/factories/vec2f64.js";import{t as l,g as h,i as u,c as d}from"../../../../chunks/vec32.js";import{ZEROS as p,create as f}from"../../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{s as _,t as m,b as g}from"../../../../chunks/vec42.js";import{create as y}from"../../../../core/libs/gl-matrix-2/factories/vec4f64.js";import{UpdatingHandles as v}from"../../../../core/support/UpdatingHandles.js";import{getReferenceEllipsoid as b}from"../../../../geometry/ellipsoidUtils.js";import{create as O,empty as w,copy as I,offset as D,width as C,height as j,expand as G}from"../../../../geometry/support/aaBoundingRect.js";import{e as k,d as S,a as A}from"../../../../chunks/boundedPlane.js";import{create as Q}from"../../../../geometry/support/ray.js";import{a as N,c as P,j as T,h as x}from"../../../../chunks/sphere.js";import{DeconflictAABR as E}from"./DeconflictAABR.js";import{prepare as V,drawPoly as L}from"./deconflictorDebug.js";import{VisibilityGroup as U,VisibilityFlag as F}from"./enums.js";import R from"../../webgl/RenderCamera.js";import{GPUPointOcclusionQuery as H}from"../../webgl-engine/lib/GPUPointOcclusionQuery.js";import{applyPrecomputedScaleFactor as B}from"../../webgl-engine/lib/screenSizePerspectiveUtils.js";import{VertexAttribute as M}from"../../webgl-engine/lib/VertexAttribute.js";import{HUDMaterial as W}from"../../webgl-engine/materials/HUDMaterial.js";import{ScaleInfo as z}from"../../webgl-engine/materials/ScaleInfo.js";import{Yield as Y}from"../../../support/Yield.js";const q=f(),J=f(),K=y(),X=y(),Z=f(),$=n(),ii=P(),ti=Q(),ei=f(),si=O();class ri{constructor(i){this.id=i,this.aabr=O(),this.altitude=0,this.distance=0,this.distanceToOccluder=0,this.culled=!1,this.visible=!1,this.priority=0}}function ci(i,t){const e=0!==i.distanceToOccluder&&i.distance>i.distanceToOccluder,s=0!==t.distanceToOccluder&&t.distance>t.distanceToOccluder;return e!==s?+e-+s:i.priority!==t.priority?t.priority-i.priority:i.distance!==t.distance?i.distance-t.distance:i.visible!==t.visible?+t.visible-+i.visible:i.id-t.id}class oi{constructor(i,t){this.graphics3DGraphic=i,this.slicePlaneEnabled=t,this._info=null,this._labelInfo=null}ensureInfo(i){let t=this.getInfo(i);return t||(t=new ri(this.graphics3DGraphic.graphic.uid),this._setInfo(i,t)),t}getInfo(i){return i===U.LABEL?this._labelInfo:this._info}removeInfo(i){this._setInfo(i,null)}_setInfo(i,t){i===U.LABEL?this._labelInfo=t:this._info=t}}var ni;!function(i){i[i.Idle=0]="Idle",i[i.CheckOcclusion=1]="CheckOcclusion",i[i.WaitOcclusion=2]="WaitOcclusion",i[i.Collect=3]="Collect",i[i.Deconflict=4]="Deconflict",i[i.NumStates=5]="NumStates"}(ni||(ni={}));class ai{constructor(){this.camera=new R,this.slicePlane=S(),this.slicePlaneEnabled=!1}copyFrom(i){this.camera.copyFrom(i.camera),A(i.slicePlane,this.slicePlane),this.slicePlaneEnabled=i.slicePlaneEnabled}}let li=class extends t{get dirty(){return this._dirty}get state(){return this._state}constructor(i){super(i),this._dirty=!1,this._viewState=new ai,this._state=ni.Idle,this._checkOcclusion=new Map,this._active=new Map,this._checkOcclusionIterator=null,this._activeIterator=null,this._occlusionQueryUids=new Array,this._updatingHandles=new v,this._deconflictor=new E(((i,t)=>{i.visible=t,this._setGraphicVisibility(this._active.get(i.id),t)}),((i,t)=>i.id!==t.id),ci),this._baseOccludedVisibility=10,this._altitudeFactor=2,this._minAltitudeDifference=100}initialize(){this._updatingHandles.add((()=>(this.view?.map?.ground?.opacity??0)>0),(()=>this.setDirty())),this._updatingHandles.add((()=>this.view.ready),(()=>this._occlusionQuery=null))}destroy(){this._occlusionQuery=null,this._updatingHandles.destroy(),this._deconflictor.destroy(),this._checkOcclusion.clear(),this._active.clear()}setDirty(){!this._dirty&&(this._active.size>0||this._checkOcclusion.size>0)&&(this._dirty=!0,this.notifyChange("updating"))}setPriority(i,t){const e=this._active.get(i.graphic.uid)?.getInfo(this.visibilityGroup);e&&(e.priority=t)}get updating(){return this._state!==ni.Idle||this._dirty||this._updatingHandles.updating}get updatingProgress(){if(!this.updating)return 1;const i=this._state/ni.NumStates;return this._dirty?.5*i:i}get running(){return this.view.ready&&null!=this.view.state&&this.updating}runTask(i){switch(this._state){case ni.Idle:this._startUpdate(),i.madeProgress();case ni.CheckOcclusion:if(this._state=ni.CheckOcclusion,!this._processCheckOcclusion(i))return;case ni.WaitOcclusion:if(this._state=ni.WaitOcclusion,this._occlusionQuery&&!this._occlusionQuery.done)return Y;this._readOcclusionQueryResult(),i.madeProgress();case ni.Collect:if(this._state=ni.Collect,!this._collectActiveGraphics(i))return;case ni.Deconflict:if(this._state=ni.Deconflict,this._deconflictor.run(i),!this._deconflictor.done)return;default:this._state=ni.Idle,this.notifyChange("updating")}}setGraphicsActive(i,t){t?i.forEach((i=>this.addToActiveGraphics(i))):i.forEach((i=>this.removeFromActiveGraphics(i)))}layerSupportsDeconfliction(i){if(null==i||"object3d"!==i.type)return!1;const t=i.stageObject;if(1!==(t?.geometries.length??0))return!1;const e=t?.geometries[0],s=e?.material;return s instanceof W}_startUpdate(){V(this.view),this._dirty=!1,this._viewState.copyFrom(this.viewState);const{fullWidth:i,fullHeight:t}=this._viewState.camera;this._deconflictor.reset(i,t),this._resetIterators(),this._occlusionQueryUids.length=0,this._checkOcclusion.size||(this._occlusionQuery=s(this._occlusionQuery))}addToActiveGraphics(i){i.ensureInfo(this.visibilityGroup),this._active.set(i.graphics3DGraphic.graphic.uid,i),this.setDirty()}removeFromActiveGraphics(i){hi(i,this.visibilityGroup),i.removeInfo(this.visibilityGroup),this._active.delete(i.graphics3DGraphic.graphic.uid),this.setDirty()}addToCheckOcclusion(i){this._checkOcclusion.set(i.graphics3DGraphic.graphic.uid,i),this.setDirty()}removeFromCheckOcclusion(i){this._checkOcclusion.delete(i.graphics3DGraphic.graphic.uid)}_processCheckOcclusion(i){if(0===this._checkOcclusion.size)return!0;const t=this._ensureCheckOcclusionIterator(),e=this._viewState.camera,r=o($,e.viewInverseTransposeMatrix),c=this.view.map.ground.opacity>0,n="global"===this.view.viewingMode&&c&&e.relativeElevation>0?ii:null;let a=0;null!=n&&(l(N(n),p,e.viewMatrix),n[3]=b(this.view.spatialReference).radius,a=T(n,p));const h=O();for(;;){if(i.done)return!1;i.madeProgress();const s=t.next();if(!0===s.done)break;const c=s.value,o=c.graphics3DGraphic;if(o.destroyed)continue;if(!o.isVisible(U.GRAPHIC,F.DECONFLICTION))continue;const u=fi(o,this.visibilityGroup);let d=null,p=!0;for(const i of u){if(!this.layerSupportsDeconfliction(i))continue;d=_i,this._projectHudLayer(i,e,d),w(h);const t=i.stageObject.geometries[0].material;if(this._expandBoundingRect(h,e,i,t,d),d.isOutsideScreen){p=!1;break}if(this._isCulledBySlice(c,d.positionView)){p=!1;break}if(null!=n&&pi(d,n,a)){p=!1;break}l(J,d.positionView,r),d.altitude=this.view.renderCoordsHelper.getAltitude(J);const s=c.ensureInfo(this.visibilityGroup);if(s.altitude=d.altitude,s.distance=d.distance,s.distanceToOccluder=d.distanceToOccluder,s.culled=!1,I(s.aabr,h),t.parameters.occlusionTest)break;this._ensureOcclusionQuery().addPosition(J)===this._occlusionQueryUids.length&&this._occlusionQueryUids.push(o.graphic.uid);break}if(this._active.has(o.graphic.uid)&&(!p||!d)){const i=c.ensureInfo(this.visibilityGroup);i.visible=!d,i.culled=!0}}return this._checkOcclusionIterator=null,this._occlusionQueryUids.length||(this._occlusionQuery=s(this._occlusionQuery)),this._occlusionQuery?.start(),!0}_readOcclusionQueryResult(){if(!this._occlusionQuery||!this._occlusionQueryUids.length)return;const i=this._viewState.camera,t=this.view.renderCoordsHelper.getAltitude(i.eye);for(let e=0;e<this._occlusionQueryUids.length;e++){const i=this._occlusionQueryUids[e],s=this._checkOcclusion.get(i);if(!s)continue;const r=this._occlusionQuery.getOcclusion(e)??-1,c=s.getInfo(this.visibilityGroup);c&&(c.distanceToOccluder=r>0?c.distance-r:0);const o=r<=0||this._occludedVisibility(c?.distanceToOccluder??0,c?.distance??r,c?.altitude??0,t);this._active.has(i)?c&&(c.culled=!o,c.visible=o):this._setGraphicVisibility(s,o)}this._occlusionQueryUids.length=0}_collectActiveGraphics(i){const t=this._ensureActiveGraphicsIterator(),e=this.visibilityGroup===U.LABEL;for(;!i.done;){i.madeProgress();const s=t.next();if(!0===s.done)return this._activeIterator=null,!0;const r=s.value,c=r.getInfo(this.visibilityGroup);if(!c)continue;!(!e||r.graphics3DGraphic.isVisible())||c.culled?(L(c.aabr,!1,!0),this._setGraphicVisibility(r,c.visible)):this._deconflictor.add(c)}return!1}_occludedVisibility(i,t,e,s){const r=Math.max(this._minAltitudeDifference,Math.abs(e-s))-this._minAltitudeDifference;return 0===i||t-i<=this._baseOccludedVisibility+this._altitudeFactor*r}_resetIterators(){this._checkOcclusionIterator=null,this._activeIterator=null}_ensureCheckOcclusionIterator(){return this._checkOcclusionIterator??=this._checkOcclusion.values(),this._checkOcclusionIterator}_ensureActiveGraphicsIterator(){return this._activeIterator??=this._active.values(),this._activeIterator}_ensureOcclusionQuery(){return this._occlusionQuery??=new H({view:this.view}),this._occlusionQueryUids.length||this._occlusionQuery.init(this._checkOcclusion.size,this._viewState.camera.eye),this._occlusionQuery}_projectHudLayer(i,t,e){const s=i.stageObject,r=s.geometries[0],c=r.material,o=N(s.boundingVolumeWorldSpace.bounds);l(q,o,t.viewMatrix);const n=r.attributes,a=n.get(M.NORMAL).data,d=n.get(M.CENTEROFFSETANDDISTANCE).data;c.applyShaderOffsetsView(q,a,s.transformation,d,t,e.scaleInfo,q),_(K,q[0],q[1],q[2],1),m(X,K,t.projectionMatrix),h(e.positionNDC,X,1/X[3]),c.applyShaderOffsetsNDC(e.positionNDC,d,t,e.positionNDC,Z),e.distanceWithoutPolygonOffset=t.depthNDCToWorld(Z[2]),e.distance=Z[2]===e.positionNDC[2]?e.distanceWithoutPolygonOffset:t.depthNDCToWorld(e.positionNDC[2]),_(X,e.positionNDC[0],e.positionNDC[1],e.positionNDC[2],1),m(K,X,t.inverseProjectionMatrix),g(K,K,1/K[3]),u(e.positionView,q[0],q[1],q[2])}_isCulledBySlice(i,t){return i.slicePlaneEnabled&&this._viewState.slicePlaneEnabled&&k(this._viewState.slicePlane,t)}_expandBoundingRect(i,t,s,r,{positionNDC:c,scaleInfo:o}){const n=s.getScreenSize(ui);B(n,o.factor,n),n[0]*=t.pixelRatio,n[1]*=t.pixelRatio;const a=D(r.calculateRelativeScreenBounds(n,o.factorAlignment.scale*t.pixelRatio,si),e(0,t.fullWidth,.5+.5*c[0]),e(0,t.fullHeight,.5+.5*c[1])),l=this.marginFactor;if(0!==l){const i=l*Math.min(C(a),j(a));a[0]-=i,a[1]-=i,a[2]+=i,a[3]+=i}G(i,a,i)}_setGraphicVisibility(i,t){const e=i?.graphics3DGraphic;e&&!e.destroyed&&(e.setVisibilityFlag(this.visibilityGroup,F.DECONFLICTION,t),this.visibilityGroup===U.LABEL&&this.view.labeler.setLabelGraphicVisibility(e,t))}};function hi(i,t){const e=i.graphics3DGraphic;e.destroyed||e.setVisibilityFlag(t,F.DECONFLICTION,!0)}i([r({constructOnly:!0})],li.prototype,"view",void 0),i([r({type:Boolean,readOnly:!0})],li.prototype,"updating",null),i([r({readOnly:!0})],li.prototype,"_updatingHandles",void 0),li=i([c("esri.views.3d.layers.graphics.Deconflictor")],li);const ui=a();class di{constructor(){this.positionView=f(),this.positionNDC=f(),this.altitude=0,this.distance=0,this.distanceToOccluder=0,this.distanceWithoutPolygonOffset=0,this.scaleInfo=new z}get isOutsideScreen(){const i=this.positionNDC;return i[0]<-1||i[1]<-1||i[2]<-1||i[0]>=1||i[1]>=1||i[2]>=1}}function pi(i,t,e){return d(ti.direction,i.positionView),u(ti.origin,0,0,0),!!x(t,ti,ei)&&i.distanceWithoutPolygonOffset>e}function fi(i,t){return t===U.LABEL?i.labelLayers:i.layers}const _i=new di;export{li as Deconflictor,oi as DeconflictorGraphic,ai as DeconflictorViewState,ni as State};
@@ -2,4 +2,4 @@
2
2
  All material copyright ESRI, All Rights Reserved, unless otherwise specified.
3
3
  See https://js.arcgis.com/4.33/esri/copyright.txt for details.
4
4
  */
5
- import e from"../../../../Color.js";import"../../../../core/has.js";import{deg2rad as t}from"../../../../core/mathUtils.js";import{releaseMaybe as r}from"../../../../core/maybe.js";import{isPromiseLike as o}from"../../../../core/promiseUtils.js";import{normalFromMat4 as a,fromMat4 as n}from"../../../../core/libs/gl-matrix-2/math/mat3.js";import{create as s}from"../../../../core/libs/gl-matrix-2/factories/mat3f64.js";import{fromTranslation as i,multiply as l,invert as c,getTranslation as u}from"../../../../core/libs/gl-matrix-2/math/mat4.js";import{create as m,IDENTITY as f,clone as p}from"../../../../core/libs/gl-matrix-2/factories/mat4f64.js";import{ONES as h}from"../../../../core/libs/gl-matrix-2/factories/vec2f64.js";import{i as d,f as g,g as x,t as _,o as y,n as b,b as T,d as v,h as w,e as M}from"../../../../chunks/vec32.js";import{create as R,ONES as C,ZEROS as j}from"../../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{ONES as A,ZEROS as P}from"../../../../core/libs/gl-matrix-2/factories/vec4f64.js";import{canProjectWithoutEngine as O}from"../../../../geometry/projection.js";import{computeTranslationToOriginAndRotation as E}from"../../../../geometry/projection/computeTranslationToOriginAndRotation.js";import{projectBuffer as N}from"../../../../geometry/projection/projectBuffer.js";import{projectVectorToPoint as I}from"../../../../geometry/projection/projectVectorToPoint.js";import{fromBuffer as S,create as U,intersectsClippingArea as B}from"../../../../geometry/support/aaBoundingBox.js";import{newFloatArray as F}from"../../../../geometry/support/FloatArray.js";import{getZeroIndexArray as V,getContinuousIndexArray as L}from"../../../../geometry/support/Indices.js";import D from"../../../../geometry/support/MeshComponent.js";import G from"../../../../geometry/support/MeshMaterialMetallicRoughness.js";import $ from"../../../../geometry/support/MeshTextureTransform.js";import{isRelativeVertexSpace as H,isAbsoluteVertexSpace as k}from"../../../../geometry/support/meshVertexSpaceUtils.js";import{equals as q,isPlateCarree as z}from"../../../../geometry/support/spatialReferenceUtils.js";import{t as W}from"../../../../chunks/vec3.js";import{transformNormal as Y,transformVectorENUPlateCarree as Z,VectorType as J,transformVectorWMPlateCarree as K,projectNormalToPCPF as Q,transformTangent as X,projectTangentToPCPF as ee}from"../../../../geometry/support/meshUtils/projection.js";import{projectMeshVertexPositions as te}from"../../../../geometry/support/meshUtils/projectMeshVertexPositions.js";import{makeDehydratedPoint as re}from"../../../../layers/graphics/dehydratedPoint.js";import{MeshTransformUpdateAction as oe}from"../../../../layers/graphics/sources/interfaces.js";import{getEmissiveMode as ae}from"../../../../symbols/support/materialUtils.js";import{ViewingMode as ne}from"../../../ViewingMode.js";import{isEncodedMeshTexture as se}from"../../glTF/internal/resourceUtils.js";import{getTransformMatrix as ie}from"../../glTF/internal/TextureTransformUtils.js";import{defaultSymbolLayerMemoryComplexity as le}from"./defaultSymbolComplexity.js";import{perObjectElevationAligner as ce}from"./ElevationAligners.js";import{needsElevationUpdates3D as ue,evaluateElevationInfoAtPoint as me}from"./elevationAlignmentUtils.js";import{Graphics3DMeshObject3DGraphicLayer as fe}from"./Graphics3DMeshObject3DGraphicLayer.js";import{Object3DEdgeState as pe}from"./Graphics3DObject3DGraphicLayer.js";import{Graphics3DSymbolLayer as he}from"./Graphics3DSymbolLayer.js";import{MaterialInfoCache as de,MeshFastUpdateProcessor as ge}from"./MeshFastUpdateProcessor.js";import{SymbolComplexity as xe}from"./SymbolComplexity.js";import{hasEdges as _e,createMaterial as ye}from"../support/edgeUtils.js";import{parseColorMixMode as be,encodeSymbolColor as Te}from"../support/symbolColorUtils.js";import{debugFlags as ve}from"../../support/debugFlags.js";import{Attribute as we}from"../../webgl-engine/lib/Attribute.js";import{AlphaDiscardMode as Me,CullFaceOptions as Re}from"../../webgl-engine/lib/basicInterfaces.js";import{Geometry as Ce}from"../../webgl-engine/lib/Geometry.js";import{Object3D as je}from"../../webgl-engine/lib/Object3D.js";import{Texture as Ae}from"../../webgl-engine/lib/Texture.js";import{VertexAttribute as Pe}from"../../webgl-engine/lib/VertexAttribute.js";import{DefaultMaterial as Oe}from"../../webgl-engine/materials/DefaultMaterial.js";import{NativeLineMaterial as Ee}from"../../webgl-engine/materials/NativeLineMaterial.js";import{useSchematicPBR as Ne,advancedMRRFactors as Ie,schematicMRRFactors as Se}from"../../webgl-engine/materials/pbrUtils.js";import{TextureWrapMode as Ue}from"../../../webgl/enums.js";import{GeometryType as Be}from"../../webgl-engine/lib/IntersectableGeometry.js";const Fe=["mesh"];class Ve extends he{constructor(e,t,r,o){super(e,t,r,o,rt(t)),this._materialInfoCache=new de,this._fastUpdateProcessor=new ge,this._textures=new Map,this.ensureDrapedStatus(!1)}async doLoad(){ve.DRAW_MESH_GEOMETRY_NORMALS&&(this._debugVertexNormalMaterial=new Ee({color:[1,0,1,1]}),this._debugTangentNormalMaterial=new Ee({color:[1,.5,0,1]}),this._debugFaceNormalMaterial=new Ee({color:[0,1,1,1]})),this.updateComplexity()}destroy(){super.destroy(),this._textures.forEach((e=>e.unload())),this._context.stage.removeTextures(Array.from(this._textures.values())),this._materialInfoCache.clear(),this._textures.clear(),this._fastUpdateProcessor.destroy()}get materials(){return this._materialInfoCache.materials}createGraphics3DGraphic(e){const t=e.graphic;if(!this._validateGeometry(t.geometry,Fe,"fill on mesh-3d"))return null;const r=this.setGraphicElevationContext(t),o=e.renderingInfo;return this._createAs3DShape(t,o,r,t.uid)}onRemoveGraphic(e){this._fastUpdateProcessor.onRemoveGraphic(e,this._materialInfoCache)}layerOpacityChanged(e,t){const r=this._getLayerOpacity();this._updateMaterialParameters((e=>{e.material.setParameters({layerOpacity:r});const t=e.material.parameters;this._setMaterialTextureAlphaMode(t,e)})),e?.forEach((e=>t(e)?.layerOpacityChanged(r,this._context.isAsync)))}layerElevationInfoChanged(e,t){return this.updateGraphics3DGraphicElevationInfo(e,t,ue)}slicePlaneEnabledChanged(e,t){return this._updateMaterialParameters((({material:e})=>{e.setParameters({hasSlicePlane:this._context.slicePlaneEnabled})})),e?.forEach((e=>t(e)?.slicePlaneEnabledChanged(this._context.slicePlaneEnabled,this._context.isAsync))),!0}physicalBasedRenderingChanged(){const e=this._usePBR();return this._updateMaterialParameters((({material:t})=>t.setParameters({usePBR:e}))),!0}updateTransform(e,t,r,o){if(!e.fastTransformUpdatesAllowed)return!1;const a=e.fastTransformUpdatesEnabled;switch(o){case oe.EnableFastUpdates:if(a)return!0;break;case oe.DisableFastUpdates:if(!a)return!0;break;default:if(!a)return!!this.updateTransform(e,t,r,oe.EnableFastUpdates)&&(e.autoDisableFastTransformUpdates((()=>this.updateTransform(e,t,r,oe.DisableFastUpdates))),!0)}const n=this._context.renderCoordsHelper.spatialReference,s=ut,{origin:i,transform:l}=r;if(!E(t,d(nt,i.x,i.y,i.z??0),s,n))return!1;switch(o){case oe.EnableFastUpdates:this._fastUpdateProcessor.enable(e,this._materialInfoCache,this._context);break;case oe.DisableFastUpdates:this._fastUpdateProcessor.disable(e,this._materialInfoCache);break;case oe.UpdateFastLocalOrigin:e.updateFastLocalOrigin(s,l,this._context.localOriginFactory)}const{elevationContext:c}=e;c.centerPointInElevationSR=this._getCenterPointInElevationSR(s);const{elevationProvider:u,renderCoordsHelper:m}=this._context,f=(e,t)=>me(e,u,c,m,t);return e.alignedSampledElevation=ce(e,c,u.spatialReference,f,m,s),e.updateTransform(s,l,this._context.isAsync),e.updateAutoDisableFastTransformUpdates((()=>this.updateTransform(e,t,r,oe.DisableFastUpdates))),!0}computeComplexity(){if(!this._textures||0===this._textures.size)return super.computeComplexity();let e=0;for(const o of this._textures.values())e+=o.usedMemory;const t={...le(this.symbol,this.symbolLayer),resourceBytes:e},r=_e(this.symbolLayer)?2:0;return new xe({drawCallsPerFeature:r,memory:t})}_requiresSymbolVertexColors(){return this._drivenProperties.color||this._drivenProperties.opacity}_materialPropertiesDefault(e,t){const r=this._requiresSymbolVertexColors(),o=!!e.vertexAttributes.color,a=!!e.vertexAttributes.tangent;return{hasSymbolVertexColors:r,hasVertexColors:o,hasVertexTangents:a,uid:`vc:${o},vt:${a},vct${t},svc:${r}`}}_materialProperties(e,t,r){const o=this._materialPropertiesDefault(e,r);if(!t.material)return o;const{color:a,colorTexture:n,colorTextureTransform:s,normalTexture:i,normalTextureTransform:l,doubleSided:c,alphaCutoff:u,alphaMode:m}=t.material,f=Xe(a),p=Xe(n),h=et(s),d=Xe(i),g=et(l);if(o.color=a,o.colorTexture=n,o.normalTexture=i,o.uid=`${o.uid},cmuid:${f},ctmuid:${p},cttuid:${h},ntmuid:${d},nttuid:${g},ds:${c},ac:${u},am:${m}`,t.material instanceof G){const{metallic:e,roughness:r,metallicRoughnessTexture:a,metallicRoughnessTextureTransform:n,emissiveColor:i,emissiveTexture:c,emissiveTextureTransform:u,occlusionTexture:m,occlusionTextureTransform:f}=t.material,p=Xe(a),h=et(n),d=Xe(i),g=Xe(c),x=et(u),_=Xe(m),y=et(f);o.metallic=e,o.roughness=r,o.metallicRoughnessTexture=a,o.emissiveColor=i,o.emissiveTexture=c,o.occlusionTexture=m,o.colorTextureTransform=We(s),o.normalTextureTransform=We(l),o.emissiveTextureTransform=We(u),o.occlusionTextureTransform=We(f),o.metallicRoughnessTextureTransform=We(n),o.uid=`${o.uid},mrm:${e},mrr:${r},mrt:${p},mrtt:${h},emuid:${d},etmuid:${g},ett:${x},otmuid:${_},ott:${y}`}return o}_getInternalTexture(e,t=!1,a=Me.Opaque){const n=Qe(e);if(!n)return null;const s=`${e.contentHash}/${a}`;let i=this._textures.get(s);if(i){const e=this._context.stage.renderView.textures;let t=null;const a=e.acquire(i.id);return null==a||o(a)||(i.events.on("unloaded",(()=>t=r(t))),t=a),i}let l=null;const c=this._context.stage.renderView.renderingContext.parameters.maxMaxAnisotropy,u={wrap:Ye(e.wrap),noUnpackFlip:!0,maxAnisotropy:c,mipmap:c>1};return se(n)?(l=n.data,u.preMultiplyAlpha=!1,u.encoding=n.encoding):(l=n,u.preMultiplyAlpha=a!==Me.Opaque,u.compressionHandle=t?this._context.compressionHandle:void 0,u.compressionCallback=t?()=>this.updateComplexity():void 0),i=new Ae(l,u),this._textures.set(s,i),i.events.on("loaded",(()=>this.updateComplexity())),i.load(this._context.stage.renderView.renderingContext),this._context.stage.addTexture(i),i.events.on("unloaded",(()=>{this._textures.delete(s)})),i}_setInternalMaterialTextureParameters(t,r){if(null!=t.colorTexture){const e=r.textureAlphaMode!==Me.Opaque,o=this._getInternalTexture(t.colorTexture,e,r.textureAlphaMode);o?(r.textureId=o.id,r.textureAlphaPremultiplied=!!o.parameters.preMultiplyAlpha):r.textureId=void 0}t.normalTexture&&(r.normalTextureId=this._getInternalTexture(t.normalTexture)?.id),t.emissiveColor&&(r.emissiveBaseColor=e.toUnitRGB(t.emissiveColor)),t.emissiveTexture&&(r.emissiveTextureId=this._getInternalTexture(t.emissiveTexture)?.id),t.occlusionTexture&&(r.occlusionTextureId=this._getInternalTexture(t.occlusionTexture,!0)?.id),t.metallicRoughnessTexture&&(r.metallicRoughnessTextureId=this._getInternalTexture(t.metallicRoughnessTexture,!0)?.id)}_setInternalMaterialParameters(e,t,r){null!=e.color&&Ke(e.color,t,r),this._setInternalMaterialTextureParameters(e,t),t.colorTextureTransformMatrix=ie(e.colorTextureTransform),t.normalTextureTransformMatrix=ie(e.normalTextureTransform);const o=null!=e.normalTextureTransform?.scale?e.normalTextureTransform?.scale:h;t.scale=[o[0],o[1]],t.occlusionTextureTransformMatrix=ie(e.occlusionTextureTransform),t.emissiveTextureTransformMatrix=ie(e.emissiveTextureTransform),t.metallicRoughnessTextureTransformMatrix=ie(e.metallicRoughnessTextureTransform)}_setExternalMaterialParameters(t,r=this.symbolLayer?.material?.color){const o=this._drivenProperties.color;let a=this.symbolLayer.material?.colorMixMode??null;if(o)t.externalColor=A;else{const o=r??null;o?t.externalColor=e.toUnitRGBA(o):(a=null,t.externalColor=A)}a&&(t.colorMixMode=a),t.castShadows=!!this.symbolLayer.castShadows,t.emissiveStrength=this.symbolLayer?.material?.emissive?.strength??1,t.emissiveSource=ae(this.symbolLayer?.material?.emissive?.source??"emissive")}_getOrCreateMaterial(t,r){const o=r.material?.color,a=r.material?.colorTexture,n=r.material?.alphaMode,s="blend"===n,i=!("opaque"===n)&&(Je(t)||null!=o&&o.a<1||a?.transparent||s),l=this._materialProperties(t,r,i),c=this._materialInfoCache.byUid(l.uid);if(c)return this._setInternalMaterialTextureParameters(l,c.material.parameters),c.material;const u={uid:l.uid,material:null,isComponentTransparent:i,alphaMode:r.material?r.material.alphaMode:"opaque"},m=Ne({normalTexture:l.normalTexture,metallicRoughnessTexture:l.metallicRoughnessTexture,metallicFactor:l.metallic,roughnessFactor:l.roughness,emissiveTexture:l.emissiveTexture,emissiveFactor:e.toUnitRGB(l.emissiveColor),occlusionTexture:l.occlusionTexture}),f={usePBR:this._usePBR(),isSchematic:m,hasVertexColors:l.hasVertexColors,hasSymbolColors:l.hasSymbolVertexColors,hasVertexTangents:l.hasVertexTangents,ambient:j,diffuse:C,opacity:1,doubleSided:!0,doubleSidedType:"winding-order",cullFace:Re.None,layerOpacity:this._getLayerOpacity(),hasSlicePlane:this._context.slicePlaneEnabled,drivenOpacity:this.needsDrivenTransparentPass||u.isComponentTransparent};f.mrrFactors=m?Se:[l.metallic,l.roughness,Ie[2]],r.material&&(f.doubleSided=r.material.doubleSided,f.cullFace=r.material.doubleSided?Re.None:Re.Back,f.textureAlphaCutoff=r.material.alphaCutoff),this._setExternalMaterialParameters(f),this._setMaterialTextureAlphaMode(f,u),this._setInternalMaterialParameters(l,f,u);const p=new Oe(f,this._context);return u.material=p,this._materialInfoCache.set(l.uid,u),p}prepareSymbolLayerPatch(e){if("partial"!==e.diff.type)return;const t=e.diff.diff;this._preparePatchColor(e,t)}_preparePatchColor(e,t){if(!t.material||"partial"!==t.material.type)return;const r=t.material.diff;if(!r.color||"complete"!==r.color.type||null==r.color.newValue||null==r.color.oldValue)return;const o=r.color.newValue;delete r.color,e.symbolLayerStatePatches.push((()=>{this._updateMaterialParameters((e=>{const t=e.material.parameters;this._setExternalMaterialParameters(t,o),this._setMaterialTextureAlphaMode(t,e),e.material.setParameters({externalColor:t.externalColor})}))}))}_usePBR(){return this._context.physicalBasedRenderingEnabled}_setMaterialTextureAlphaMode(e,t){if("auto"===t.alphaMode){const r=this.needsDrivenTransparentPass||t.isComponentTransparent||(e.layerOpacity??1)<1||(e.opacity??1)<1||(e.externalColor?.[3]??1)<1;e.textureAlphaMode=r?Me.MaskBlend:Me.Opaque}else e.textureAlphaMode="opaque"===t.alphaMode?Me.Opaque:"mask"===t.alphaMode?Me.Mask:Me.Blend}_createFaceDebugNormals(e,t){const r=t.length,o=e.spatialReference.isGeographic?20015077/180:1,n=.1*Math.max(e.extent.width*o,e.extent.height*o,e.extent.zmax-e.extent.zmin),i=[],l=[],c=t[0].transformation,u=a(s(),c);for(let a=0;a<r;a++){const e=t[a].attributes.get(Pe.POSITION);if(!e)continue;const r=e.data,o=e.indices;for(let t=0;t<o.length;t+=3)ze(r,o,t,lt),qe(r,o,t,nt,st,it),g(nt,nt,st),g(nt,nt,it),x(nt,nt,1/3),_(nt,nt,c),i.push(...nt),y(lt,lt,u),b(lt,lt),T(nt,nt,lt,n),i.push(...nt),l.push(l.length),l.push(l.length)}return i.length?new Ce(this._debugFaceNormalMaterial,[[Pe.POSITION,new we(i,l,3,!0)]],null,Be.Line):null}_createPerVertexDebugVectors(e,t,r,o,i){const l=t.length,c=e.spatialReference.isGeographic?20015077/180:1,u=.1*i*Math.max(e.extent.width*c,e.extent.height*c,e.extent.zmax-e.extent.zmin),m=[],f=[],p=t[0].transformation,h=a(s(),p);r===Pe.TANGENT&&n(h,p);for(let a=0;a<l;a++){const e=t[a],o=e.attributes.get(Pe.POSITION),n=e.attributes.get(r);if(!o||!n)continue;const s=o.data,i=o.indices,l=n.data,c=n.indices;for(let t=0;t<i.length;t++){const e=3*i[t],r=c[t]*n.stride;d(nt,s[e+0],s[e+1],s[e+2]),_(nt,nt,p),m.push(...nt),d(st,l[r+0],l[r+1],l[r+2]),y(st,st,h),b(st,st),T(nt,nt,st,u),m.push(...nt),f.push(f.length),f.push(f.length)}}return m.length?new Ce(o,[[Pe.POSITION,new we(m,f,3,!0)]],null,Be.Line):null}_createAs3DShape(e,t,r,o){const a=e.geometry;if("mesh"!==a.type)return null;const n=this._createGeometryInfo(a,t,o);if(null==n)return null;const{geometries:s,objectTransformation:i}=n;if(ve.DRAW_MESH_GEOMETRY_NORMALS){const e=this._createPerVertexDebugVectors(a,s,Pe.NORMAL,this._debugVertexNormalMaterial,1),t=this._createPerVertexDebugVectors(a,s,Pe.TANGENT,this._debugTangentNormalMaterial,.5),r=this._createFaceDebugNormals(a,s);e&&s.push(e),t&&s.push(t),r&&s.push(r)}const l=this._context.layerViewUid,c=new je({geometries:s,layerViewUid:l,graphicUid:o,isElevationSource:!0});c.transformation=i;const u=ye(this.symbolLayer,{opacity:this._getLayerOpacity()}),m=u?new pe(s[0].material,u,this._context.slicePlaneEnabled):null,f=new fe(this,c,null,ce,r,m);this._fastUpdateProcessor.onAddGraphic(),f.needsElevationUpdates=ue(r.mode),f.useObjectOriginAsAttachmentOrigin=!0,f.fastTransformUpdatesAllowed=this._fastTransformUpdatesAllowed(a),r.centerPointInElevationSR=this._getCenterPointInElevationSR(c.transformation);const{elevationProvider:p,renderCoordsHelper:h}=this._context,d=(e,t)=>me(e,p,r,h,t);return f.alignedSampledElevation=ce(f,r,p.spatialReference,d,h),f}_fastTransformUpdatesAllowed(e){const{vertexSpace:t,spatialReference:r}=e;if(!H(t))return!1;const{type:o}=t,{view:a}=this._context.graphicsCoreOwner,{viewingMode:n}=a.state,s=a.spatialReference;return n===ne.Global&&"local"===o||n===ne.Local&&q(s,r)&&"georeferenced"===o&&!r.isGeographic}_getCenterPointInElevationSR(e){const t=re(0,0,0,this._context.elevationProvider.spatialReference??null);return I([e[12],e[13],e[14]],this._context.renderCoordsHelper.spatialReference,t),t}_passthroughReprojectionInfo(e){return e.reprojection===pt.NONE&&!!e.objectTransformation}_createPositionBuffer(e,t){const r=e.vertexAttributes.position;let o,a=r;if(t.reprojection===pt.NONE)return{position:a,georeferencedPositionBuffer:o};const n=t.reprojection===pt.RENDER?t.transformBeforeProject:null;n&&(a=W(new Float64Array(a.length),a,n));const{normal:s,tangent:i}=e.vertexAttributes;this._passthroughReprojectionInfo(t)||!s&&!i||(o=a);const l=a===r||a===o?new Float64Array(a.length):a;return N(a,e.spatialReference,0,l,this._context.renderCoordsHelper.spatialReference,0),{position:l,georeferencedPositionBuffer:o}}_createNormalBuffer(e,t,r,o){const a=e.vertexAttributes.normal;if(null==a)return null;let n=a;const s=o.reprojection===pt.RENDER?o.transformBeforeProject:null;s&&(n=Y(n,new Float32Array(n.length),s));const i=this._context.graphicsCoreOwner.view.viewingMode;if(o.reprojection===pt.NONE)return n;if("local"===i){if(!z(this._context.renderCoordsHelper.spatialReference))return n;if(null==r)return null;if(e.spatialReference.isGeographic){const e=n===a?new Float32Array(n.length):n;return Z(n,J.NORMAL,r,e)}if(e.spatialReference.isWebMercator){const e=n===a?new Float32Array(n.length):n;return K(n,J.NORMAL,r,e)}return n}if(null==r)return null;const l=n===a?new Float32Array(n.length):n,c=this._context.renderCoordsHelper.spatialReference;return Q(n,r,e.spatialReference,t,c,l)}_createTangentBuffer(e,t,r,o){const a=e.vertexAttributes.tangent;if(null==a)return null;let n=a;const s=o.reprojection===pt.RENDER?o.transformBeforeProject:null;s&&(n=X(n,new Float32Array(n.length),s));const i=this._context.graphicsCoreOwner.view.viewingMode;if(o.reprojection===pt.NONE)return n;if("local"===i){if(!z(this._context.renderCoordsHelper.spatialReference))return n;if(null==r)return null;if(e.spatialReference.isGeographic){const e=n===a?new Float32Array(n.length):n;return Z(n,J.TANGENT,r,e)}if(e.spatialReference.isWebMercator){const e=n===a?new Float32Array(n.length):n;return K(n,J.TANGENT,r,e)}return n}if(null==r)return null;const l=n===a?new Float32Array(n.length):n,c=this._context.renderCoordsHelper.spatialReference;return ee(n,r,e.spatialReference,t,c,l)}_createSymbolColorBuffer(e){if(this._requiresSymbolVertexColors()){const t=this._getVertexOpacityAndColor(e,this._getFallbackOpacityAndColor()),r=be(this.symbolLayer?.material?.colorMixMode),o=new Uint8Array(4);return Te(t,r,o),o}return null}_createBuffers(e,t){const r=e.vertexAttributes&&e.vertexAttributes.position;if(!r)return this.logger.warn("Mesh geometry must contain position vertex attributes"),null;const o=e.vertexAttributes.normal,a=e.vertexAttributes.uv,n=e.vertexAttributes.tangent;if(o&&o.length!==r.length)return this.logger.warn("Mesh normal vertex buffer must contain the same number of elements as the position buffer"),null;if(n&&n.length/4!=r.length/3)return this.logger.warn("Mesh tangent vertex buffer must contain the same number of elements as the position buffer"),null;if(a&&a.length/2!=r.length/3)return this.logger.warn("Mesh uv vertex buffer must contain the same number of elements as the position buffer"),null;const s=this._computeReprojectionInfo(e),{position:i,georeferencedPositionBuffer:l}=this._createPositionBuffer(e,s),c=tt(e),u=this._createSymbolColorBuffer(t),f=this._createNormalBuffer(e,i,l,s),p=this._createTangentBuffer(e,i,l,s),h=a,{transformation:d,position:g,normal:x,tangent:_}=this._passthroughReprojectionInfo(s)?{transformation:s.objectTransformation,position:i,normal:f,tangent:p}:this._transformOriginLocal(e,i,f,p);return{positionBuffer:g,normalBuffer:x,tangentBuffer:_,uvBuffer:h,colorBuffer:c,symbolColorBuffer:u,objectTransformation:d,geometryTransformation:s.reprojection===pt.NONE&&s.geometryTransformation?s.geometryTransformation:m()}}_computeReprojectionInfo(e){const{vertexSpace:t}=e,r="georeferenced"===t.type?q(this._context.renderCoordsHelper.spatialReference,e.spatialReference)?pt.NONE:pt.RENDER:pt.NONE;if(k(t))return{reprojection:r};const o=t.origin,a=m(),n=e.transform?.localMatrix??f;if(r===pt.NONE){E(e.spatialReference,o,a,this._context.renderCoordsHelper.spatialReference);return{reprojection:r,objectTransformation:a,geometryTransformation:p(n)}}const s=i(m(),o);return l(s,s,n),{reprojection:r,transformBeforeProject:s}}_transformOriginLocal(e,t,r,o){const a=this._context.renderCoordsHelper.spatialReference,n=e.origin;at[0]=n.x,at[1]=n.y,at[2]=n.z??0;const s=m();E(e.spatialReference,at,s,a),c(ct,s);const{position:i,normal:l,tangent:u}=e.vertexAttributes,f=t===i?new Float64Array(t.length):t;W(f,t,ct);const p=r?r===l?new Float32Array(r.length):r:null,h=o?o===u?new Float32Array(o.length):o:null;return r&&p&&Y(r,p,ct),o&&h&&X(o,h,ct),{transformation:s,position:f,normal:p,tangent:h}}_validateFaces(e,t){const r=e.vertexAttributes.position.length/3,o=t.faces;if(o){let e=-1;for(let t=0;t<o.length;t++){const r=o[t];r>e&&(e=r)}if(r<=e)return this.logger.warn(`Vertex index ${e} is out of bounds of the mesh position buffer`),!1}else if(r%3!=0)return this.logger.warn("Mesh position buffer length must be a multiple of 9 if no component faces are defined (3 values per vertex * 3 vertices per triangle)"),!1;return!0}_isOutsideClippingArea(e){if(!this._context.clippingExtent)return!1;const t=e.vertexAttributes?.position;if(!t)return!1;const r=this._context.elevationProvider.spatialReference,o=te(e,r??e.spatialReference);return!!o&&(S(o,mt),!B(mt,this._context.clippingExtent))}_createGeometryInfo(e,t,r){if(!O(e.spatialReference,this._context.renderCoordsHelper.spatialReference))return this.logger.warn("Geometry spatial reference is not compatible with the view"),null;if(!this._validateVertexSpace(e))return null;if(this._isOutsideClippingArea(e))return null;const o=this._createBuffers(e,t);if(null==o)return null;const{positionBuffer:a,uvBuffer:n,colorBuffer:s,symbolColorBuffer:i,normalBuffer:l,tangentBuffer:c,objectTransformation:m,geometryTransformation:f}=o,p=e.components??ft,h=new Array;let d=!1;const g=u(nt,m),x=this._context.localOriginFactory.getOrigin(g);for(const u of p){if(!this._validateFaces(e,u))return null;const t=De(e,u);if(0===t.length)continue;const o=Ge(a,l,u,t);o.didFlipNormals&&(d=!0);const m=[[Pe.POSITION,new we(a,t,3,!0)],[Pe.NORMAL,new we(o.normals,o.indices,3,!0)]];s&&m.push([Pe.COLOR,new we(s,t,4,!0)]),i&&m.push([Pe.SYMBOLCOLOR,new we(i,V(t.length),4,!0)]),n&&m.push([Pe.UV0,new we(n,t,2,!0)]),c&&m.push([Pe.TANGENT,new we(c,t,4,!0)]);const p=this._context.stage.renderView.getObjectAndLayerIdColor({graphicUid:r,layerViewUid:this._context.layerViewUid}),g=this._getOrCreateMaterial(e,u),_=new Ce(g,m,null,Be.Mesh,p);_.transformation=f,_.localOrigin=x,h.push(_)}return d&&this.logger.warn("Normals have been automatically flipped to be consistent with the counter clock wise face winding order. It is better to generate mesh geometries that have consistent normals."),{geometries:h,objectTransformation:m}}_updateMaterialParameters(e){this._materialInfoCache.forEachMaterialInfo(e),this._fastUpdateProcessor.forEachMaterialInfo(e),this._fastUpdateProcessor.forEachClonedMaterial(((e,t)=>{t.setParameters(e.parameters)}))}_validateVertexSpace(e){const{_context:{graphicsCoreOwner:{view:{state:{viewingMode:t}}}}}=this,{vertexSpace:r}=e;return t!==ne.Local||"local"!==r.type||(this.logger.warn("Displaying a mesh with a local vertex space in a view in local viewing mode is not supported."),!1)}test(){return{...super.test(),materials:this._materialInfoCache.materials}}_getFallbackOpacityAndColor(){const t=this.symbolLayer?.material?.color;return e.toUnitRGBA(t)??P}}class Le{constructor(e,t,r){this.normals=e,this.indices=t,this.didFlipNormals=r}}function De(e,t){return t.faces??L(e.vertexAttributes.position.length/3)}function Ge(e,t,r,o){switch(r.shading||"flat"){default:case"source":return He(e,t,r,o);case"flat":return $e(e,o);case"smooth":return ke(e,o)}}function $e(e,t){const r=F(t.length),o=new Array(3*t.length);for(let a=0;a<t.length;a+=3){const n=ze(e,t,a,lt);for(let e=0;e<3;e++)r[a+e]=n[e],o[a+e]=a/3}return new Le(r,o,!1)}function He(e,t,r,o){if(null==t)return $e(e,o);let a=!1;if(!r.trustSourceNormals)for(let n=0;n<o.length;n+=3){ze(e,o,n,lt);for(let e=0;e<3;e++){const r=3*o[n+e];nt[0]=t[r],nt[1]=t[r+1],nt[2]=t[r+2],M(lt,nt)<0&&(t[r]=-t[r],t[r+1]=-t[r+1],t[r+2]=-t[r+2],a=!0)}}return new Le(t,o,a)}function ke(e,t){const r={};for(let n=0;n<t.length;n+=3){const o=ze(e,t,n,lt);for(let e=0;e<3;e++){const a=t[n+e];let s=r[a];s||(s={normal:R(),count:0},r[a]=s),g(s.normal,s.normal,o),s.count++}}const o=F(3*t.length),a=new Array(3*t.length);for(let n=0;n<t.length;n++){const e=r[t[n]];1!==e.count&&(b(e.normal,e.normal),e.count=1);for(let t=0;t<3;t++)o[3*n+t]=e.normal[t];a[n]=n}return new Le(o,a,!1)}function qe(e,t,r,o,a,n){const s=3*t[r],i=3*t[r+1],l=3*t[r+2];o[0]=e[s],o[1]=e[s+1],o[2]=e[s+2],a[0]=e[i],a[1]=e[i+1],a[2]=e[i+2],n[0]=e[l],n[1]=e[l+1],n[2]=e[l+2]}function ze(e,t,r,o){return qe(e,t,r,nt,st,it),v(st,st,nt),v(it,it,nt),w(nt,st,it),b(o,nt),o}function We(e){if(!e)return null;const{scale:r,offset:o,rotation:a}=e;return{scale:r,offset:o,rotation:t(a)}}function Ye(e="repeat"){if("string"==typeof e){const t=Ze(e);return{s:t,t}}return{s:Ze(e.horizontal),t:Ze(e.vertical)}}function Ze(e){switch(e){case"clamp":return Ue.CLAMP_TO_EDGE;case"mirror":return Ue.MIRRORED_REPEAT;default:return Ue.REPEAT}}function Je(e){const t=e.vertexAttributes.color;if(null==t)return!1;for(let r=3;r<t.length;r+=4)if(255!==t[r])return!0;return!1}function Ke(t,r,o){r.diffuse=e.toUnitRGB(t),r.opacity="opaque"===o.alphaMode?1:t.a}function Qe(e){return e.data??e.url}function Xe(t){return null==t?"-":t instanceof e?t.toHex():t.contentHash}function et(e){const{offset:t,scale:r,rotation:o}=e??ot;return`${t[0]},${t[1]},${o},${r[0]},${r[1]}`}function tt(e){return e.vertexAttributes.color}function rt(e){return 1===(e.material?.color?.a??1)}const ot=new $,at=R(),nt=R(),st=R(),it=R(),lt=R(),ct=m(),ut=m(),mt=U(),ft=[new D];var pt;!function(e){e[e.NONE=0]="NONE",e[e.RENDER=1]="RENDER"}(pt||(pt={}));export{Ve as Graphics3DMeshFillSymbolLayer};
5
+ import e from"../../../../Color.js";import"../../../../core/has.js";import{deg2rad as t}from"../../../../core/mathUtils.js";import{releaseMaybe as r}from"../../../../core/maybe.js";import{isPromiseLike as o}from"../../../../core/promiseUtils.js";import{normalFromMat4 as a,fromMat4 as n}from"../../../../core/libs/gl-matrix-2/math/mat3.js";import{create as s}from"../../../../core/libs/gl-matrix-2/factories/mat3f64.js";import{fromTranslation as i,multiply as l,invert as c,getTranslation as u}from"../../../../core/libs/gl-matrix-2/math/mat4.js";import{create as m,IDENTITY as f,clone as p}from"../../../../core/libs/gl-matrix-2/factories/mat4f64.js";import{ONES as h}from"../../../../core/libs/gl-matrix-2/factories/vec2f64.js";import{i as d,f as g,g as x,t as _,o as y,n as b,b as T,d as v,h as w,e as M}from"../../../../chunks/vec32.js";import{create as R,ONES as C,ZEROS as j}from"../../../../core/libs/gl-matrix-2/factories/vec3f64.js";import{ONES as A,ZEROS as P}from"../../../../core/libs/gl-matrix-2/factories/vec4f64.js";import{canProjectWithoutEngine as O}from"../../../../geometry/projection.js";import{computeTranslationToOriginAndRotation as E}from"../../../../geometry/projection/computeTranslationToOriginAndRotation.js";import{projectBuffer as N}from"../../../../geometry/projection/projectBuffer.js";import{projectVectorToPoint as I}from"../../../../geometry/projection/projectVectorToPoint.js";import{fromBuffer as S,create as U,intersectsClippingArea as B}from"../../../../geometry/support/aaBoundingBox.js";import{newFloatArray as F}from"../../../../geometry/support/FloatArray.js";import{getZeroIndexArray as V,getContinuousIndexArray as L}from"../../../../geometry/support/Indices.js";import D from"../../../../geometry/support/MeshComponent.js";import G from"../../../../geometry/support/MeshMaterialMetallicRoughness.js";import $ from"../../../../geometry/support/MeshTextureTransform.js";import{isRelativeVertexSpace as H,isAbsoluteVertexSpace as k}from"../../../../geometry/support/meshVertexSpaceUtils.js";import{equals as q,isPlateCarree as z}from"../../../../geometry/support/spatialReferenceUtils.js";import{t as W}from"../../../../chunks/vec3.js";import{transformNormal as Y,transformVectorENUPlateCarree as Z,VectorType as J,transformVectorWMPlateCarree as K,projectNormalToPCPF as Q,transformTangent as X,projectTangentToPCPF as ee}from"../../../../geometry/support/meshUtils/projection.js";import{projectMeshVertexPositions as te}from"../../../../geometry/support/meshUtils/projectMeshVertexPositions.js";import{makeDehydratedPoint as re}from"../../../../layers/graphics/dehydratedPoint.js";import{MeshTransformUpdateAction as oe}from"../../../../layers/graphics/sources/interfaces.js";import{getEmissiveMode as ae}from"../../../../symbols/support/materialUtils.js";import{ViewingMode as ne}from"../../../ViewingMode.js";import{isEncodedMeshTexture as se}from"../../glTF/internal/resourceUtils.js";import{getTransformMatrix as ie}from"../../glTF/internal/TextureTransformUtils.js";import{defaultSymbolLayerMemoryComplexity as le}from"./defaultSymbolComplexity.js";import{perObjectElevationAligner as ce}from"./ElevationAligners.js";import{needsElevationUpdates3D as ue,evaluateElevationInfoAtPoint as me}from"./elevationAlignmentUtils.js";import{Graphics3DMeshObject3DGraphicLayer as fe}from"./Graphics3DMeshObject3DGraphicLayer.js";import{Object3DEdgeState as pe}from"./Graphics3DObject3DGraphicLayer.js";import{Graphics3DSymbolLayer as he}from"./Graphics3DSymbolLayer.js";import{MaterialInfoCache as de,MeshFastUpdateProcessor as ge}from"./MeshFastUpdateProcessor.js";import{SymbolComplexity as xe}from"./SymbolComplexity.js";import{hasEdges as _e,createMaterial as ye}from"../support/edgeUtils.js";import{parseColorMixMode as be,encodeSymbolColor as Te}from"../support/symbolColorUtils.js";import{debugFlags as ve}from"../../support/debugFlags.js";import{Attribute as we}from"../../webgl-engine/lib/Attribute.js";import{AlphaDiscardMode as Me,CullFaceOptions as Re}from"../../webgl-engine/lib/basicInterfaces.js";import{Geometry as Ce}from"../../webgl-engine/lib/Geometry.js";import{Object3D as je}from"../../webgl-engine/lib/Object3D.js";import{Texture as Ae}from"../../webgl-engine/lib/Texture.js";import{VertexAttribute as Pe}from"../../webgl-engine/lib/VertexAttribute.js";import{DefaultMaterial as Oe}from"../../webgl-engine/materials/DefaultMaterial.js";import{NativeLineMaterial as Ee}from"../../webgl-engine/materials/NativeLineMaterial.js";import{useSchematicPBR as Ne,advancedMRRFactors as Ie,schematicMRRFactors as Se}from"../../webgl-engine/materials/pbrUtils.js";import{TextureWrapMode as Ue}from"../../../webgl/enums.js";import{GeometryType as Be}from"../../webgl-engine/lib/IntersectableGeometry.js";const Fe=["mesh"];class Ve extends he{constructor(e,t,r,o){super(e,t,r,o,rt(t)),this._materialInfoCache=new de,this._fastUpdateProcessor=new ge,this._textures=new Map,this.ensureDrapedStatus(!1)}async doLoad(){ve.DRAW_MESH_GEOMETRY_NORMALS&&(this._debugVertexNormalMaterial=new Ee({color:[1,0,1,1]}),this._debugTangentNormalMaterial=new Ee({color:[1,.5,0,1]}),this._debugFaceNormalMaterial=new Ee({color:[0,1,1,1]})),this.updateComplexity()}destroy(){super.destroy(),this._textures.forEach((e=>e.unload())),this._context.stage.removeTextures(Array.from(this._textures.values())),this._materialInfoCache.clear(),this._textures.clear(),this._fastUpdateProcessor.destroy()}get materials(){return this._materialInfoCache.materials}createGraphics3DGraphic(e){const t=e.graphic;if(!this._validateGeometry(t.geometry,Fe,"fill on mesh-3d"))return null;const r=this.setGraphicElevationContext(t),o=e.renderingInfo;return this._createAs3DShape(t,o,r,t.uid)}onRemoveGraphic(e){this._fastUpdateProcessor.onRemoveGraphic(e,this._materialInfoCache)}layerOpacityChanged(e,t){const r=this._getLayerOpacity();this._updateMaterialParameters((e=>{e.material.setParameters({layerOpacity:r});const t=e.material.parameters;this._setMaterialTextureAlphaMode(t,e)})),e?.forEach((e=>t(e)?.layerOpacityChanged(r,this._context.isAsync)))}layerElevationInfoChanged(e,t){return this.updateGraphics3DGraphicElevationInfo(e,t,ue)}slicePlaneEnabledChanged(e,t){return this._updateMaterialParameters((({material:e})=>{e.setParameters({hasSlicePlane:this._context.slicePlaneEnabled})})),e?.forEach((e=>t(e)?.slicePlaneEnabledChanged(this._context.slicePlaneEnabled,this._context.isAsync))),!0}physicalBasedRenderingChanged(){const e=this._usePBR();return this._updateMaterialParameters((({material:t})=>t.setParameters({usePBR:e}))),!0}updateTransform(e,t,r,o){if(!e.fastTransformUpdatesAllowed)return!1;const a=e.fastTransformUpdatesEnabled;switch(o){case oe.EnableFastUpdates:if(a)return!0;break;case oe.DisableFastUpdates:if(!a)return!0;break;default:if(!a)return!!this.updateTransform(e,t,r,oe.EnableFastUpdates)&&(e.autoDisableFastTransformUpdates((()=>this.updateTransform(e,t,r,oe.DisableFastUpdates))),!0)}const n=this._context.renderCoordsHelper.spatialReference,s=ut,{origin:i,transform:l}=r;if(!E(t,d(nt,i.x,i.y,i.z??0),s,n))return!1;switch(o){case oe.EnableFastUpdates:this._fastUpdateProcessor.enable(e,this._materialInfoCache,this._context);break;case oe.DisableFastUpdates:this._fastUpdateProcessor.disable(e,this._materialInfoCache);break;case oe.UpdateFastLocalOrigin:e.updateFastLocalOrigin(s,l,this._context.localOriginFactory)}const{elevationContext:c}=e;c.centerPointInElevationSR=this._getCenterPointInElevationSR(s);const{elevationProvider:u,renderCoordsHelper:m}=this._context,f=(e,t)=>me(e,u,c,m,t);return e.alignedSampledElevation=ce(e,c,u.spatialReference,f,m,s),e.updateTransform(s,l,this._context.isAsync),e.updateAutoDisableFastTransformUpdates((()=>this.updateTransform(e,t,r,oe.DisableFastUpdates))),!0}computeComplexity(){if(!this._textures||0===this._textures.size)return super.computeComplexity();let e=0;for(const o of this._textures.values())e+=o.usedMemory;const t={...le(this.symbol,this.symbolLayer),resourceBytes:e},r=_e(this.symbolLayer)?2:0;return new xe({drawCallsPerFeature:r,memory:t})}_requiresSymbolVertexColors(){return this._drivenProperties.color||this._drivenProperties.opacity}_materialPropertiesDefault(e,t){const r=this._requiresSymbolVertexColors(),o=!!e.vertexAttributes.color,a=!!e.vertexAttributes.tangent;return{hasSymbolVertexColors:r,hasVertexColors:o,hasVertexTangents:a,uid:`vc:${o},vt:${a},vct${t},svc:${r}`}}_materialProperties(e,t,r){const o=this._materialPropertiesDefault(e,r);if(!t.material)return o;const{color:a,colorTexture:n,colorTextureTransform:s,normalTexture:i,normalTextureTransform:l,doubleSided:c,alphaCutoff:u,alphaMode:m}=t.material,f=Xe(a),p=Xe(n),h=et(s),d=Xe(i),g=et(l);if(o.color=a,o.colorTexture=n,o.normalTexture=i,o.uid=`${o.uid},cmuid:${f},ctmuid:${p},cttuid:${h},ntmuid:${d},nttuid:${g},ds:${c},ac:${u},am:${m}`,t.material instanceof G){const{metallic:e,roughness:r,metallicRoughnessTexture:a,metallicRoughnessTextureTransform:n,emissiveColor:i,emissiveTexture:c,emissiveTextureTransform:u,occlusionTexture:m,occlusionTextureTransform:f}=t.material,p=Xe(a),h=et(n),d=Xe(i),g=Xe(c),x=et(u),_=Xe(m),y=et(f);o.metallic=e,o.roughness=r,o.metallicRoughnessTexture=a,o.emissiveColor=i,o.emissiveTexture=c,o.occlusionTexture=m,o.colorTextureTransform=We(s),o.normalTextureTransform=We(l),o.emissiveTextureTransform=We(u),o.occlusionTextureTransform=We(f),o.metallicRoughnessTextureTransform=We(n),o.uid=`${o.uid},mrm:${e},mrr:${r},mrt:${p},mrtt:${h},emuid:${d},etmuid:${g},ett:${x},otmuid:${_},ott:${y}`}return o}_getInternalTexture(e,t=!1,a=Me.Opaque){const n=Qe(e);if(!n)return null;const s=`${e.contentHash}/${a}`;let i=this._textures.get(s);if(i){const e=this._context.stage.renderView.textures;let t=null;const a=e.acquire(i.id);return null==a||o(a)||(i.events.on("unloaded",(()=>t=r(t))),t=a),i}let l=null;const c=this._context.stage.renderView.renderingContext.parameters.maxMaxAnisotropy,u={wrap:Ye(e.wrap),noUnpackFlip:!0,maxAnisotropy:c,mipmap:c>1};return se(n)?(l=n.data,u.preMultiplyAlpha=!1,u.encoding=n.encoding):(l=n,u.preMultiplyAlpha=a!==Me.Opaque,u.compressionHandle=t?this._context.compressionHandle:void 0,u.compressionCallback=t?()=>this.updateComplexity():void 0),i=new Ae(l,u),this._textures.set(s,i),i.events.on("loaded",(()=>this.updateComplexity())),i.load(this._context.stage.renderView.renderingContext),this._context.stage.addTexture(i),i.events.on("unloaded",(()=>{this._textures.delete(s)})),i}_setInternalMaterialTextureParameters(t,r){if(null!=t.colorTexture){const e=r.textureAlphaMode!==Me.Opaque,o=this._getInternalTexture(t.colorTexture,e,r.textureAlphaMode);o?(r.textureId=o.id,r.textureAlphaPremultiplied=!!o.parameters.preMultiplyAlpha):r.textureId=void 0}t.normalTexture&&(r.normalTextureId=this._getInternalTexture(t.normalTexture)?.id),t.emissiveColor&&(r.emissiveBaseColor=e.toUnitRGB(t.emissiveColor)),t.emissiveTexture&&(r.emissiveTextureId=this._getInternalTexture(t.emissiveTexture)?.id),t.occlusionTexture&&(r.occlusionTextureId=this._getInternalTexture(t.occlusionTexture,!0)?.id),t.metallicRoughnessTexture&&(r.metallicRoughnessTextureId=this._getInternalTexture(t.metallicRoughnessTexture,!0)?.id)}_setInternalMaterialParameters(e,t,r){null!=e.color&&Ke(e.color,t,r),this._setInternalMaterialTextureParameters(e,t),t.colorTextureTransformMatrix=ie(e.colorTextureTransform),t.normalTextureTransformMatrix=ie(e.normalTextureTransform);const o=null!=e.normalTextureTransform?.scale?e.normalTextureTransform?.scale:h;t.scale=[o[0],o[1]],t.occlusionTextureTransformMatrix=ie(e.occlusionTextureTransform),t.emissiveTextureTransformMatrix=ie(e.emissiveTextureTransform),t.metallicRoughnessTextureTransformMatrix=ie(e.metallicRoughnessTextureTransform)}_setExternalMaterialParameters(t,r=this.symbolLayer?.material?.color){const o=this._drivenProperties.color,a=this._drivenProperties.opacity;let n=this.symbolLayer.material?.colorMixMode??null;if(o)t.externalColor=A;else{const o=r??null;if(o){const r=e.toUnitRGBA(o);a&&(r[3]=1),t.externalColor=r}else n=null,t.externalColor=A}n&&(t.colorMixMode=n),t.castShadows=!!this.symbolLayer.castShadows,t.emissiveStrength=this.symbolLayer?.material?.emissive?.strength??1,t.emissiveSource=ae(this.symbolLayer?.material?.emissive?.source??"emissive")}_getOrCreateMaterial(t,r){const o=r.material?.color,a=r.material?.colorTexture,n=r.material?.alphaMode,s="blend"===n,i=!("opaque"===n)&&(Je(t)||null!=o&&o.a<1||a?.transparent||s),l=this._materialProperties(t,r,i),c=this._materialInfoCache.byUid(l.uid);if(c)return this._setInternalMaterialTextureParameters(l,c.material.parameters),c.material;const u={uid:l.uid,material:null,isComponentTransparent:i,alphaMode:r.material?r.material.alphaMode:"opaque"},m=Ne({normalTexture:l.normalTexture,metallicRoughnessTexture:l.metallicRoughnessTexture,metallicFactor:l.metallic,roughnessFactor:l.roughness,emissiveTexture:l.emissiveTexture,emissiveFactor:e.toUnitRGB(l.emissiveColor),occlusionTexture:l.occlusionTexture}),f={usePBR:this._usePBR(),isSchematic:m,hasVertexColors:l.hasVertexColors,hasSymbolColors:l.hasSymbolVertexColors,hasVertexTangents:l.hasVertexTangents,ambient:j,diffuse:C,opacity:1,doubleSided:!0,doubleSidedType:"winding-order",cullFace:Re.None,layerOpacity:this._getLayerOpacity(),hasSlicePlane:this._context.slicePlaneEnabled,drivenOpacity:this.needsDrivenTransparentPass||u.isComponentTransparent};f.mrrFactors=m?Se:[l.metallic,l.roughness,Ie[2]],r.material&&(f.doubleSided=r.material.doubleSided,f.cullFace=r.material.doubleSided?Re.None:Re.Back,f.textureAlphaCutoff=r.material.alphaCutoff),this._setExternalMaterialParameters(f),this._setMaterialTextureAlphaMode(f,u),this._setInternalMaterialParameters(l,f,u);const p=new Oe(f,this._context);return u.material=p,this._materialInfoCache.set(l.uid,u),p}prepareSymbolLayerPatch(e){if("partial"!==e.diff.type)return;const t=e.diff.diff;this._preparePatchColor(e,t)}_preparePatchColor(e,t){if(!t.material||"partial"!==t.material.type)return;const r=t.material.diff;if(!r.color||"complete"!==r.color.type||null==r.color.newValue||null==r.color.oldValue)return;const o=r.color.newValue;delete r.color,e.symbolLayerStatePatches.push((()=>{this._updateMaterialParameters((e=>{const t=e.material.parameters;this._setExternalMaterialParameters(t,o),this._setMaterialTextureAlphaMode(t,e),e.material.setParameters({externalColor:t.externalColor})}))}))}_usePBR(){return this._context.physicalBasedRenderingEnabled}_setMaterialTextureAlphaMode(e,t){if("auto"===t.alphaMode){const r=this.needsDrivenTransparentPass||t.isComponentTransparent||(e.layerOpacity??1)<1||(e.opacity??1)<1||(e.externalColor?.[3]??1)<1;e.textureAlphaMode=r?Me.MaskBlend:Me.Opaque}else e.textureAlphaMode="opaque"===t.alphaMode?Me.Opaque:"mask"===t.alphaMode?Me.Mask:Me.Blend}_createFaceDebugNormals(e,t){const r=t.length,o=e.spatialReference.isGeographic?20015077/180:1,n=.1*Math.max(e.extent.width*o,e.extent.height*o,e.extent.zmax-e.extent.zmin),i=[],l=[],c=t[0].transformation,u=a(s(),c);for(let a=0;a<r;a++){const e=t[a].attributes.get(Pe.POSITION);if(!e)continue;const r=e.data,o=e.indices;for(let t=0;t<o.length;t+=3)ze(r,o,t,lt),qe(r,o,t,nt,st,it),g(nt,nt,st),g(nt,nt,it),x(nt,nt,1/3),_(nt,nt,c),i.push(...nt),y(lt,lt,u),b(lt,lt),T(nt,nt,lt,n),i.push(...nt),l.push(l.length),l.push(l.length)}return i.length?new Ce(this._debugFaceNormalMaterial,[[Pe.POSITION,new we(i,l,3,!0)]],null,Be.Line):null}_createPerVertexDebugVectors(e,t,r,o,i){const l=t.length,c=e.spatialReference.isGeographic?20015077/180:1,u=.1*i*Math.max(e.extent.width*c,e.extent.height*c,e.extent.zmax-e.extent.zmin),m=[],f=[],p=t[0].transformation,h=a(s(),p);r===Pe.TANGENT&&n(h,p);for(let a=0;a<l;a++){const e=t[a],o=e.attributes.get(Pe.POSITION),n=e.attributes.get(r);if(!o||!n)continue;const s=o.data,i=o.indices,l=n.data,c=n.indices;for(let t=0;t<i.length;t++){const e=3*i[t],r=c[t]*n.stride;d(nt,s[e+0],s[e+1],s[e+2]),_(nt,nt,p),m.push(...nt),d(st,l[r+0],l[r+1],l[r+2]),y(st,st,h),b(st,st),T(nt,nt,st,u),m.push(...nt),f.push(f.length),f.push(f.length)}}return m.length?new Ce(o,[[Pe.POSITION,new we(m,f,3,!0)]],null,Be.Line):null}_createAs3DShape(e,t,r,o){const a=e.geometry;if("mesh"!==a.type)return null;const n=this._createGeometryInfo(a,t,o);if(null==n)return null;const{geometries:s,objectTransformation:i}=n;if(ve.DRAW_MESH_GEOMETRY_NORMALS){const e=this._createPerVertexDebugVectors(a,s,Pe.NORMAL,this._debugVertexNormalMaterial,1),t=this._createPerVertexDebugVectors(a,s,Pe.TANGENT,this._debugTangentNormalMaterial,.5),r=this._createFaceDebugNormals(a,s);e&&s.push(e),t&&s.push(t),r&&s.push(r)}const l=this._context.layerViewUid,c=new je({geometries:s,layerViewUid:l,graphicUid:o,isElevationSource:!0});c.transformation=i;const u=ye(this.symbolLayer,{opacity:this._getLayerOpacity()}),m=u?new pe(s[0].material,u,this._context.slicePlaneEnabled):null,f=new fe(this,c,null,ce,r,m);this._fastUpdateProcessor.onAddGraphic(),f.needsElevationUpdates=ue(r.mode),f.useObjectOriginAsAttachmentOrigin=!0,f.fastTransformUpdatesAllowed=this._fastTransformUpdatesAllowed(a),r.centerPointInElevationSR=this._getCenterPointInElevationSR(c.transformation);const{elevationProvider:p,renderCoordsHelper:h}=this._context,d=(e,t)=>me(e,p,r,h,t);return f.alignedSampledElevation=ce(f,r,p.spatialReference,d,h),f}_fastTransformUpdatesAllowed(e){const{vertexSpace:t,spatialReference:r}=e;if(!H(t))return!1;const{type:o}=t,{view:a}=this._context.graphicsCoreOwner,{viewingMode:n}=a.state,s=a.spatialReference;return n===ne.Global&&"local"===o||n===ne.Local&&q(s,r)&&"georeferenced"===o&&!r.isGeographic}_getCenterPointInElevationSR(e){const t=re(0,0,0,this._context.elevationProvider.spatialReference??null);return I([e[12],e[13],e[14]],this._context.renderCoordsHelper.spatialReference,t),t}_passthroughReprojectionInfo(e){return e.reprojection===pt.NONE&&!!e.objectTransformation}_createPositionBuffer(e,t){const r=e.vertexAttributes.position;let o,a=r;if(t.reprojection===pt.NONE)return{position:a,georeferencedPositionBuffer:o};const n=t.reprojection===pt.RENDER?t.transformBeforeProject:null;n&&(a=W(new Float64Array(a.length),a,n));const{normal:s,tangent:i}=e.vertexAttributes;this._passthroughReprojectionInfo(t)||!s&&!i||(o=a);const l=a===r||a===o?new Float64Array(a.length):a;return N(a,e.spatialReference,0,l,this._context.renderCoordsHelper.spatialReference,0),{position:l,georeferencedPositionBuffer:o}}_createNormalBuffer(e,t,r,o){const a=e.vertexAttributes.normal;if(null==a)return null;let n=a;const s=o.reprojection===pt.RENDER?o.transformBeforeProject:null;s&&(n=Y(n,new Float32Array(n.length),s));const i=this._context.graphicsCoreOwner.view.viewingMode;if(o.reprojection===pt.NONE)return n;if("local"===i){if(!z(this._context.renderCoordsHelper.spatialReference))return n;if(null==r)return null;if(e.spatialReference.isGeographic){const e=n===a?new Float32Array(n.length):n;return Z(n,J.NORMAL,r,e)}if(e.spatialReference.isWebMercator){const e=n===a?new Float32Array(n.length):n;return K(n,J.NORMAL,r,e)}return n}if(null==r)return null;const l=n===a?new Float32Array(n.length):n,c=this._context.renderCoordsHelper.spatialReference;return Q(n,r,e.spatialReference,t,c,l)}_createTangentBuffer(e,t,r,o){const a=e.vertexAttributes.tangent;if(null==a)return null;let n=a;const s=o.reprojection===pt.RENDER?o.transformBeforeProject:null;s&&(n=X(n,new Float32Array(n.length),s));const i=this._context.graphicsCoreOwner.view.viewingMode;if(o.reprojection===pt.NONE)return n;if("local"===i){if(!z(this._context.renderCoordsHelper.spatialReference))return n;if(null==r)return null;if(e.spatialReference.isGeographic){const e=n===a?new Float32Array(n.length):n;return Z(n,J.TANGENT,r,e)}if(e.spatialReference.isWebMercator){const e=n===a?new Float32Array(n.length):n;return K(n,J.TANGENT,r,e)}return n}if(null==r)return null;const l=n===a?new Float32Array(n.length):n,c=this._context.renderCoordsHelper.spatialReference;return ee(n,r,e.spatialReference,t,c,l)}_createSymbolColorBuffer(e){if(this._requiresSymbolVertexColors()){const t=this._getVertexOpacityAndColor(e,this._getFallbackOpacityAndColor()),r=be(this.symbolLayer?.material?.colorMixMode),o=new Uint8Array(4);return Te(t,r,o),o}return null}_createBuffers(e,t){const r=e.vertexAttributes&&e.vertexAttributes.position;if(!r)return this.logger.warn("Mesh geometry must contain position vertex attributes"),null;const o=e.vertexAttributes.normal,a=e.vertexAttributes.uv,n=e.vertexAttributes.tangent;if(o&&o.length!==r.length)return this.logger.warn("Mesh normal vertex buffer must contain the same number of elements as the position buffer"),null;if(n&&n.length/4!=r.length/3)return this.logger.warn("Mesh tangent vertex buffer must contain the same number of elements as the position buffer"),null;if(a&&a.length/2!=r.length/3)return this.logger.warn("Mesh uv vertex buffer must contain the same number of elements as the position buffer"),null;const s=this._computeReprojectionInfo(e),{position:i,georeferencedPositionBuffer:l}=this._createPositionBuffer(e,s),c=tt(e),u=this._createSymbolColorBuffer(t),f=this._createNormalBuffer(e,i,l,s),p=this._createTangentBuffer(e,i,l,s),h=a,{transformation:d,position:g,normal:x,tangent:_}=this._passthroughReprojectionInfo(s)?{transformation:s.objectTransformation,position:i,normal:f,tangent:p}:this._transformOriginLocal(e,i,f,p);return{positionBuffer:g,normalBuffer:x,tangentBuffer:_,uvBuffer:h,colorBuffer:c,symbolColorBuffer:u,objectTransformation:d,geometryTransformation:s.reprojection===pt.NONE&&s.geometryTransformation?s.geometryTransformation:m()}}_computeReprojectionInfo(e){const{vertexSpace:t}=e,r="georeferenced"===t.type?q(this._context.renderCoordsHelper.spatialReference,e.spatialReference)?pt.NONE:pt.RENDER:pt.NONE;if(k(t))return{reprojection:r};const o=t.origin,a=m(),n=e.transform?.localMatrix??f;if(r===pt.NONE){E(e.spatialReference,o,a,this._context.renderCoordsHelper.spatialReference);return{reprojection:r,objectTransformation:a,geometryTransformation:p(n)}}const s=i(m(),o);return l(s,s,n),{reprojection:r,transformBeforeProject:s}}_transformOriginLocal(e,t,r,o){const a=this._context.renderCoordsHelper.spatialReference,n=e.origin;at[0]=n.x,at[1]=n.y,at[2]=n.z??0;const s=m();E(e.spatialReference,at,s,a),c(ct,s);const{position:i,normal:l,tangent:u}=e.vertexAttributes,f=t===i?new Float64Array(t.length):t;W(f,t,ct);const p=r?r===l?new Float32Array(r.length):r:null,h=o?o===u?new Float32Array(o.length):o:null;return r&&p&&Y(r,p,ct),o&&h&&X(o,h,ct),{transformation:s,position:f,normal:p,tangent:h}}_validateFaces(e,t){const r=e.vertexAttributes.position.length/3,o=t.faces;if(o){let e=-1;for(let t=0;t<o.length;t++){const r=o[t];r>e&&(e=r)}if(r<=e)return this.logger.warn(`Vertex index ${e} is out of bounds of the mesh position buffer`),!1}else if(r%3!=0)return this.logger.warn("Mesh position buffer length must be a multiple of 9 if no component faces are defined (3 values per vertex * 3 vertices per triangle)"),!1;return!0}_isOutsideClippingArea(e){if(!this._context.clippingExtent)return!1;const t=e.vertexAttributes?.position;if(!t)return!1;const r=this._context.elevationProvider.spatialReference,o=te(e,r??e.spatialReference);return!!o&&(S(o,mt),!B(mt,this._context.clippingExtent))}_createGeometryInfo(e,t,r){if(!O(e.spatialReference,this._context.renderCoordsHelper.spatialReference))return this.logger.warn("Geometry spatial reference is not compatible with the view"),null;if(!this._validateVertexSpace(e))return null;if(this._isOutsideClippingArea(e))return null;const o=this._createBuffers(e,t);if(null==o)return null;const{positionBuffer:a,uvBuffer:n,colorBuffer:s,symbolColorBuffer:i,normalBuffer:l,tangentBuffer:c,objectTransformation:m,geometryTransformation:f}=o,p=e.components??ft,h=new Array;let d=!1;const g=u(nt,m),x=this._context.localOriginFactory.getOrigin(g);for(const u of p){if(!this._validateFaces(e,u))return null;const t=De(e,u);if(0===t.length)continue;const o=Ge(a,l,u,t);o.didFlipNormals&&(d=!0);const m=[[Pe.POSITION,new we(a,t,3,!0)],[Pe.NORMAL,new we(o.normals,o.indices,3,!0)]];s&&m.push([Pe.COLOR,new we(s,t,4,!0)]),i&&m.push([Pe.SYMBOLCOLOR,new we(i,V(t.length),4,!0)]),n&&m.push([Pe.UV0,new we(n,t,2,!0)]),c&&m.push([Pe.TANGENT,new we(c,t,4,!0)]);const p=this._context.stage.renderView.getObjectAndLayerIdColor({graphicUid:r,layerViewUid:this._context.layerViewUid}),g=this._getOrCreateMaterial(e,u),_=new Ce(g,m,null,Be.Mesh,p);_.transformation=f,_.localOrigin=x,h.push(_)}return d&&this.logger.warn("Normals have been automatically flipped to be consistent with the counter clock wise face winding order. It is better to generate mesh geometries that have consistent normals."),{geometries:h,objectTransformation:m}}_updateMaterialParameters(e){this._materialInfoCache.forEachMaterialInfo(e),this._fastUpdateProcessor.forEachMaterialInfo(e),this._fastUpdateProcessor.forEachClonedMaterial(((e,t)=>{t.setParameters(e.parameters)}))}_validateVertexSpace(e){const{_context:{graphicsCoreOwner:{view:{state:{viewingMode:t}}}}}=this,{vertexSpace:r}=e;return t!==ne.Local||"local"!==r.type||(this.logger.warn("Displaying a mesh with a local vertex space in a view in local viewing mode is not supported."),!1)}test(){return{...super.test(),materials:this._materialInfoCache.materials}}_getFallbackOpacityAndColor(){const t=this.symbolLayer?.material?.color;return e.toUnitRGBA(t)??P}}class Le{constructor(e,t,r){this.normals=e,this.indices=t,this.didFlipNormals=r}}function De(e,t){return t.faces??L(e.vertexAttributes.position.length/3)}function Ge(e,t,r,o){switch(r.shading||"flat"){default:case"source":return He(e,t,r,o);case"flat":return $e(e,o);case"smooth":return ke(e,o)}}function $e(e,t){const r=F(t.length),o=new Array(3*t.length);for(let a=0;a<t.length;a+=3){const n=ze(e,t,a,lt);for(let e=0;e<3;e++)r[a+e]=n[e],o[a+e]=a/3}return new Le(r,o,!1)}function He(e,t,r,o){if(null==t)return $e(e,o);let a=!1;if(!r.trustSourceNormals)for(let n=0;n<o.length;n+=3){ze(e,o,n,lt);for(let e=0;e<3;e++){const r=3*o[n+e];nt[0]=t[r],nt[1]=t[r+1],nt[2]=t[r+2],M(lt,nt)<0&&(t[r]=-t[r],t[r+1]=-t[r+1],t[r+2]=-t[r+2],a=!0)}}return new Le(t,o,a)}function ke(e,t){const r={};for(let n=0;n<t.length;n+=3){const o=ze(e,t,n,lt);for(let e=0;e<3;e++){const a=t[n+e];let s=r[a];s||(s={normal:R(),count:0},r[a]=s),g(s.normal,s.normal,o),s.count++}}const o=F(3*t.length),a=new Array(3*t.length);for(let n=0;n<t.length;n++){const e=r[t[n]];1!==e.count&&(b(e.normal,e.normal),e.count=1);for(let t=0;t<3;t++)o[3*n+t]=e.normal[t];a[n]=n}return new Le(o,a,!1)}function qe(e,t,r,o,a,n){const s=3*t[r],i=3*t[r+1],l=3*t[r+2];o[0]=e[s],o[1]=e[s+1],o[2]=e[s+2],a[0]=e[i],a[1]=e[i+1],a[2]=e[i+2],n[0]=e[l],n[1]=e[l+1],n[2]=e[l+2]}function ze(e,t,r,o){return qe(e,t,r,nt,st,it),v(st,st,nt),v(it,it,nt),w(nt,st,it),b(o,nt),o}function We(e){if(!e)return null;const{scale:r,offset:o,rotation:a}=e;return{scale:r,offset:o,rotation:t(a)}}function Ye(e="repeat"){if("string"==typeof e){const t=Ze(e);return{s:t,t}}return{s:Ze(e.horizontal),t:Ze(e.vertical)}}function Ze(e){switch(e){case"clamp":return Ue.CLAMP_TO_EDGE;case"mirror":return Ue.MIRRORED_REPEAT;default:return Ue.REPEAT}}function Je(e){const t=e.vertexAttributes.color;if(null==t)return!1;for(let r=3;r<t.length;r+=4)if(255!==t[r])return!0;return!1}function Ke(t,r,o){r.diffuse=e.toUnitRGB(t),r.opacity="opaque"===o.alphaMode?1:t.a}function Qe(e){return e.data??e.url}function Xe(t){return null==t?"-":t instanceof e?t.toHex():t.contentHash}function et(e){const{offset:t,scale:r,rotation:o}=e??ot;return`${t[0]},${t[1]},${o},${r[0]},${r[1]}`}function tt(e){return e.vertexAttributes.color}function rt(e){return 1===(e.material?.color?.a??1)}const ot=new $,at=R(),nt=R(),st=R(),it=R(),lt=R(),ct=m(),ut=m(),mt=U(),ft=[new D];var pt;!function(e){e[e.NONE=0]="NONE",e[e.RENDER=1]="RENDER"}(pt||(pt={}));export{Ve as Graphics3DMeshFillSymbolLayer};