@labelbee/lb-annotation 1.23.0 → 1.24.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -197,6 +197,13 @@ declare class BasicToolOperation extends EventListener {
197
197
  x: number;
198
198
  y: number;
199
199
  };
200
+ /**
201
+ * Get the coordinates of the outer canvas by scaling the coordinates of the relative image under rotation
202
+ */
203
+ getCoordinateUnderZoomByRotateFromImgPoint(point: ICoordinate): {
204
+ x: number;
205
+ y: number;
206
+ };
200
207
  getGetCenterCoordinate(): {
201
208
  x: number;
202
209
  y: number;
@@ -250,6 +257,11 @@ declare class BasicToolOperation extends EventListener {
250
257
  */
251
258
  zoomChangeOnCenter: (newZoom: number) => void;
252
259
  renderCursorLine(lineColor?: any): void;
260
+ drawStraightLine: (points: ICoordinate[], config: {
261
+ color: string;
262
+ lineWidth: number;
263
+ globalAlpha: number;
264
+ }) => void;
253
265
  drawImg: () => void;
254
266
  drawStaticImg: () => void;
255
267
  /**
@@ -144,7 +144,6 @@ declare class CuboidOperation extends BasicToolOperation implements ITextAttribu
144
144
  */
145
145
  renderHighlightCuboidCom(cuboid: ICuboid | IDrawingCuboid): void;
146
146
  /**
147
- * TODO - Need to optimize.
148
147
  * @param cuboid
149
148
  */
150
149
  renderSingleCuboid(cuboid: ICuboid | IDrawingCuboid): void;
@@ -1,8 +1,9 @@
1
1
  /**
2
2
  * 各类的数学运算
3
3
  */
4
- import { TAnnotationViewData } from '@labelbee/lb-utils';
4
+ import { I3DSpaceCoord, IPointCloudBox, TAnnotationViewData } from '@labelbee/lb-utils';
5
5
  import { IPolygonPoint } from '@/types/tool/polygon';
6
+ import { TIndexMap } from '@/core/pointCloud/cache';
6
7
  /**
7
8
  * 基础的三角运算
8
9
  */
@@ -11,6 +12,12 @@ export declare class Trigonometric {
11
12
  static sinAPlusB(sinA: number, cosA: number, sinB: number, cosB: number): number;
12
13
  static cosAPlusB(sinA: number, cosA: number, sinB: number, cosB: number): number;
13
14
  }
15
+ interface ICalculatePointsInsideBoxParams {
16
+ indexMap: TIndexMap;
17
+ polygon: IPolygonPoint[];
18
+ zScope: [number, number];
19
+ box: IPointCloudBox;
20
+ }
14
21
  export default class MathUtils {
15
22
  /**
16
23
  * 是否在指定范围内
@@ -176,4 +183,7 @@ export default class MathUtils {
176
183
  * @param newHeight
177
184
  */
178
185
  static getModifiedRectangleCoordinates(coordinates: ICoordinate[], newWidth: number, newHeight: number): ICoordinate[];
186
+ static calculatePointsInsideBox: (params: ICalculatePointsInsideBoxParams) => number;
187
+ static isPointInsideCube(point: I3DSpaceCoord, polygon: IPolygonPoint[], zScope: [number, number]): boolean;
179
188
  }
189
+ export {};
@@ -1,2 +1,2 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var MathUtilsWorker=require("../_virtual/MathUtilsWorker.js"),tool=require("../constant/tool.js"),polygonTool=require("./tool/polygonTool.js"),PolygonUtils=require("./tool/PolygonUtils.js"),VectorUtils=require("./VectorUtils.js"),__defProp=Object.defineProperty,__defProps=Object.defineProperties,__getOwnPropDescs=Object.getOwnPropertyDescriptors,__getOwnPropSymbols=Object.getOwnPropertySymbols,__hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable,__pow=Math.pow,__defNormalProp=(e,t,o)=>t in e?__defProp(e,t,{enumerable:!0,configurable:!0,writable:!0,value:o}):e[t]=o,__spreadValues=(e,t)=>{for(var o in t||(t={}))__hasOwnProp.call(t,o)&&__defNormalProp(e,o,t[o]);if(__getOwnPropSymbols)for(var o of __getOwnPropSymbols(t))__propIsEnum.call(t,o)&&__defNormalProp(e,o,t[o]);return e},__spreadProps=(e,t)=>__defProps(e,__getOwnPropDescs(t));class Trigonometric{static tanAPlusB(t,o){return(t+o)/(1-t*o)}static sinAPlusB(t,o,s,n){return n*t+o*s}static cosAPlusB(t,o,s,n){return o*n-t*s}}const _MathUtils=class{static getRotate(e){return e+90>=360?e+90-360:e+90}static getLineLength(e,t){return Math.sqrt(Math.pow(t.y-e.y,2)+Math.pow(t.x-e.x,2))}static getTextArea(e,t,o=tool.DEFAULT_TEXT_MAX_WIDTH,s=tool.DEFAULT_FONT,n){if(typeof t!="string")return{width:0,height:0};const i=e.getContext("2d");i.font=s;let r=0;typeof n=="undefined"&&(n=e&&parseInt(window.getComputedStyle(e).lineHeight,10)||parseInt(window.getComputedStyle(document.body).lineHeight,10));const a=e&&parseInt(window.getComputedStyle(e).fontSize,10)||parseInt(window.getComputedStyle(document.body).fontSize,10)||0,c=t.split(`
2
- `);let u=0;for(let l=0;l<c.length;l++){const f=c[l].split("");let p="";for(let h=0;h<f.length;h++){const y=p+f[h],g=i.measureText(y).width;g>o&&h>0?(p=f[h],r+=n,u=o):(p=y,g>u&&(u=g))}l!==c.length-1&&(r+=n)}return{width:u,height:r+a,lineHeight:n,fontHeight:a}}static getLineCenterPoint(e){const[t,o]=e,s=VectorUtils.getVector(t,o);return{x:t.x+s.x/2,y:t.y+s.y/2}}static getPerpendicularLine(e){if(e.length!==2)return;const[t,o]=e,s={x:o.x+o.y-t.y,y:o.y-(o.x-t.x)};return[o,s]}static getPerpendicularFootOfLine(e,t){if(e.length!==2)return e;const o=this.getPerpendicularLine(e);if(!o)return e;const[s,n]=o;return this.getFootOfPerpendicular(t,s,n).footPoint}static getQuadrangleFromTriangle(e){if(e.length!==3)return e;const[t,o,s]=e,n={x:s.x+t.x-o.x,y:s.y+t.y-o.y};return[t,o,s,n]}static getRectPerpendicularOffset(e,t,o){const[s,n]=o,i=this.getFootOfPerpendicular(e,s,n).footPoint,r=this.getFootOfPerpendicular(t,s,n).footPoint,a={x:i.x-r.x,y:i.y-r.y},c=VectorUtils.add(t,a);return VectorUtils.getVector(e,c)}static getArrayIndex(e,t){return e<0?t+e:e>=t?e-t:e}static getPointListFromPointOffset(e,t,o){const s=this.getArrayIndex(t-1,e.length),n=this.getArrayIndex(t+1,e.length),i=this.getArrayIndex(t-2,e.length),r=[...e];r[t]=VectorUtils.add(r[t],o);const a=this.getFootOfPerpendicular(r[t],r[i],r[s]).footPoint,c=this.getFootOfPerpendicular(r[t],r[n],r[i]).footPoint;return r[s]=a,r[n]=c,r}static getRectCenterPoint(e){const[t,,o]=e;return{x:(t.x+o.x)/2,y:(t.y+o.y)/2}}static rotateRectPointList(e=5,t){const o=this.getRectCenterPoint(t),{PI:s}=Math,n=Math.sin(e*s/180),i=Math.cos(e*s/180);return t.map(r=>{const a=VectorUtils.getVector(o,r),c=VectorUtils.len(a),u=a.y/c,l=a.x/c;return{x:c*Trigonometric.cosAPlusB(u,l,n,i)+o.x,y:c*Trigonometric.sinAPlusB(u,l,n,i)+o.y}})}static getRectangleByRightAngle(e,t){if(t.length!==2)return t;const o=_MathUtils.getPerpendicularFootOfLine(t,e);return _MathUtils.getQuadrangleFromTriangle([...t,o])}static getRadiusFromQuadrangle(e){const[,t,o]=e,s=o.y-t.y,n=t.x-o.x,i=this.getLineLength(t,o),r=s/i,a=Math.acos(r);return n>0?Math.PI*2-a:a}static getCollectionPointByAnnotationDataPromise(e){const t=e.filter(n=>n.type==="point").map(n=>n.annotation),o=e.filter(n=>!!["polygon","line"].includes(n.type)).map(n=>n.type==="polygon"?__spreadProps(__spreadValues({},n.annotation),{pointList:PolygonUtils.concatBeginAndEnd(n.annotation.pointList)}):n.annotation),s=new MathUtilsWorker;return{promise:new Promise(function(i){s.postMessage({points:t,backgroundList:o}),s.onmessage=r=>{i(r.data),s.terminate()}}),close:()=>{s.terminate()}}}static getCollectionPointByAnnotationData(e){const t=[],o=new Set,s=e.filter(r=>r.type==="point").map(r=>r.annotation),n=e.filter(r=>!!["polygon","line"].includes(r.type)).map(r=>r.type==="polygon"?__spreadProps(__spreadValues({},r.annotation),{pointList:PolygonUtils.concatBeginAndEnd(r.annotation.pointList)}):r.annotation),i=(r,a)=>{const{dropFoot:c}=PolygonUtils.getClosestPoint(r,a,tool.ELineTypes.Line,1,{isClose:!1});if(c!==r){const u=`${c.x} + ${c.y}`;o.has(u)||t.push(r),o.add(u)}};return s.forEach(r=>{i(r,n)}),n.forEach(r=>{let a="";a=r.id,n.forEach((c,u)=>{if(c.id===a)return;const l=[...n];l.splice(u,1),c.pointList.forEach(f=>{i(f,l)})})}),{connectionPoints:t}}static getModifiedRectangleCoordinates(e,t,o){if(e.length!==4)throw new Error("Invalid number of coordinates. Four coordinates are required.");const s=e[0],n=e[1],i=e[2],r=Math.sqrt(__pow(n.x-s.x,2)+__pow(n.y-s.y,2)),a=Math.sqrt(__pow(i.x-n.x,2)+__pow(i.y-n.y,2)),c=t/r,u=o/a,l={x:s.x+(n.x-s.x)*c,y:s.y+(n.y-s.y)*c},f={x:l.x+(i.x-n.x)*u,y:l.y+(i.y-n.y)*u},p={x:s.x+(f.x-n.x),y:s.y+(f.y-n.y)};return[s,l,f,p]}};let MathUtils=_MathUtils;MathUtils.isInRange=(e,t)=>{const o=Math.min(...t),s=Math.max(...t),n=r=>r<=s&&r>=o;return(Array.isArray(e)?e:[e]).every(r=>n(r))},MathUtils.withinRange=(e,t)=>{const o=Math.min(...t),s=Math.max(...t);return e>s?s:e<o?o:e},MathUtils.calcViewportBoundaries=(e,t=!1,o=tool.SEGMENT_NUMBER,s=1)=>{if(!e)return{top:0,bottom:0,left:0,right:0};const n=20/s,i=[],r=[];let a=e;t&&(a=polygonTool.createSmoothCurvePointsFromPointList(e,o)),a.forEach(({x:y,y:x})=>{i.push(y),r.push(x)});let c=Math.min(...i),u=Math.max(...i),l=Math.min(...r),f=Math.max(...r);const p=u-c,h=f-l;if(p<n){const y=(n-p)/2;c-=y,u+=y}if(h<n){const y=(n-h)/2;l-=y,f+=y}return{top:l,bottom:f,left:c,right:u}},MathUtils.getFootOfPerpendicular=(e,t,o,s=!1,n=!1)=>{let i={x:0,y:0};const r=t.x-o.x,a=t.y-o.y;if(Math.abs(r)<1e-8&&Math.abs(a)<1e-8)return i=t,i;let c=(e.x-t.x)*(t.x-o.x)+(e.y-t.y)*(t.y-o.y);c/=r*r+a*a,i.x=t.x+c*r,i.y=t.y+c*a;const u=_MathUtils.getLineLength(e,i),l=2,f=Math.min(t.x,o.x),p=Math.max(t.x,o.x),h=Math.min(t.y,o.y),y=Math.max(t.y,o.y),x=!(_MathUtils.isInRange(e.x,[f,p])||_MathUtils.isInRange(e.y,[h,y])),g=e.x>p+l||e.x<f-l||e.y>y+l||e.y<h-l;return!n&&(s?x:g)?{footPoint:i,length:Infinity}:{footPoint:i,length:u}};var MathUtils$1=MathUtils;exports.Trigonometric=Trigonometric,exports.default=MathUtils$1;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var MathUtilsWorker=require("../_virtual/MathUtilsWorker.js"),tool=require("../constant/tool.js"),polygonTool=require("./tool/polygonTool.js"),PolygonUtils=require("./tool/PolygonUtils.js"),VectorUtils=require("./VectorUtils.js"),__defProp=Object.defineProperty,__defProps=Object.defineProperties,__getOwnPropDescs=Object.getOwnPropertyDescriptors,__getOwnPropSymbols=Object.getOwnPropertySymbols,__hasOwnProp=Object.prototype.hasOwnProperty,__propIsEnum=Object.prototype.propertyIsEnumerable,__pow=Math.pow,__defNormalProp=(e,n,t)=>n in e?__defProp(e,n,{enumerable:!0,configurable:!0,writable:!0,value:t}):e[n]=t,__spreadValues=(e,n)=>{for(var t in n||(n={}))__hasOwnProp.call(n,t)&&__defNormalProp(e,t,n[t]);if(__getOwnPropSymbols)for(var t of __getOwnPropSymbols(n))__propIsEnum.call(n,t)&&__defNormalProp(e,t,n[t]);return e},__spreadProps=(e,n)=>__defProps(e,__getOwnPropDescs(n));class Trigonometric{static tanAPlusB(n,t){return(n+t)/(1-n*t)}static sinAPlusB(n,t,i,o){return o*n+t*i}static cosAPlusB(n,t,i,o){return t*o-n*i}}var CubePosition;(function(e){e[e.Outside=0]="Outside",e[e.PartiallyInside=1]="PartiallyInside",e[e.FullyInside=2]="FullyInside"})(CubePosition||(CubePosition={}));function getCubePosition(e,n,t){const i=[{x:t.x-t.width/2,y:t.y-t.height/2,z:t.z-t.depth/2},{x:t.x+t.width/2,y:t.y-t.height/2,z:t.z-t.depth/2},{x:t.x-t.width/2,y:t.y+t.height/2,z:t.z-t.depth/2},{x:t.x+t.width/2,y:t.y+t.height/2,z:t.z-t.depth/2},{x:t.x-t.width/2,y:t.y-t.height/2,z:t.z+t.depth/2},{x:t.x+t.width/2,y:t.y-t.height/2,z:t.z+t.depth/2},{x:t.x-t.width/2,y:t.y+t.height/2,z:t.z+t.depth/2},{x:t.x+t.width/2,y:t.y+t.height/2,z:t.z+t.depth/2}];let o=0;for(let s=0;s<i.length;s++)MathUtils.isPointInsideCube(i[s],e,n)&&o++;return o===0?0:o===8?2:1}const _MathUtils=class{static getRotate(e){return e+90>=360?e+90-360:e+90}static getLineLength(e,n){return Math.sqrt(Math.pow(n.y-e.y,2)+Math.pow(n.x-e.x,2))}static getTextArea(e,n,t=tool.DEFAULT_TEXT_MAX_WIDTH,i=tool.DEFAULT_FONT,o){if(typeof n!="string")return{width:0,height:0};const s=e.getContext("2d");s.font=i;let r=0;typeof o=="undefined"&&(o=e&&parseInt(window.getComputedStyle(e).lineHeight,10)||parseInt(window.getComputedStyle(document.body).lineHeight,10));const a=e&&parseInt(window.getComputedStyle(e).fontSize,10)||parseInt(window.getComputedStyle(document.body).fontSize,10)||0,c=n.split(`
2
+ `);let y=0;for(let h=0;h<c.length;h++){const f=c[h].split("");let g="";for(let d=0;d<f.length;d++){const x=g+f[d],p=s.measureText(x).width;p>t&&d>0?(g=f[d],r+=o,y=t):(g=x,p>y&&(y=p))}h!==c.length-1&&(r+=o)}return{width:y,height:r+a,lineHeight:o,fontHeight:a}}static getLineCenterPoint(e){const[n,t]=e,i=VectorUtils.getVector(n,t);return{x:n.x+i.x/2,y:n.y+i.y/2}}static getPerpendicularLine(e){if(e.length!==2)return;const[n,t]=e,i={x:t.x+t.y-n.y,y:t.y-(t.x-n.x)};return[t,i]}static getPerpendicularFootOfLine(e,n){if(e.length!==2)return e;const t=this.getPerpendicularLine(e);if(!t)return e;const[i,o]=t;return this.getFootOfPerpendicular(n,i,o).footPoint}static getQuadrangleFromTriangle(e){if(e.length!==3)return e;const[n,t,i]=e,o={x:i.x+n.x-t.x,y:i.y+n.y-t.y};return[n,t,i,o]}static getRectPerpendicularOffset(e,n,t){const[i,o]=t,s=this.getFootOfPerpendicular(e,i,o).footPoint,r=this.getFootOfPerpendicular(n,i,o).footPoint,a={x:s.x-r.x,y:s.y-r.y},c=VectorUtils.add(n,a);return VectorUtils.getVector(e,c)}static getArrayIndex(e,n){return e<0?n+e:e>=n?e-n:e}static getPointListFromPointOffset(e,n,t){const i=this.getArrayIndex(n-1,e.length),o=this.getArrayIndex(n+1,e.length),s=this.getArrayIndex(n-2,e.length),r=[...e];r[n]=VectorUtils.add(r[n],t);const a=this.getFootOfPerpendicular(r[n],r[s],r[i]).footPoint,c=this.getFootOfPerpendicular(r[n],r[o],r[s]).footPoint;return r[i]=a,r[o]=c,r}static getRectCenterPoint(e){const[n,,t]=e;return{x:(n.x+t.x)/2,y:(n.y+t.y)/2}}static rotateRectPointList(e=5,n){const t=this.getRectCenterPoint(n),{PI:i}=Math,o=Math.sin(e*i/180),s=Math.cos(e*i/180);return n.map(r=>{const a=VectorUtils.getVector(t,r),c=VectorUtils.len(a),y=a.y/c,h=a.x/c;return{x:c*Trigonometric.cosAPlusB(y,h,o,s)+t.x,y:c*Trigonometric.sinAPlusB(y,h,o,s)+t.y}})}static getRectangleByRightAngle(e,n){if(n.length!==2)return n;const t=_MathUtils.getPerpendicularFootOfLine(n,e);return _MathUtils.getQuadrangleFromTriangle([...n,t])}static getRadiusFromQuadrangle(e){const[,n,t]=e,i=t.y-n.y,o=n.x-t.x,s=this.getLineLength(n,t),r=i/s,a=Math.acos(r);return o>0?Math.PI*2-a:a}static getCollectionPointByAnnotationDataPromise(e){const n=e.filter(o=>o.type==="point").map(o=>o.annotation),t=e.filter(o=>!!["polygon","line"].includes(o.type)).map(o=>o.type==="polygon"?__spreadProps(__spreadValues({},o.annotation),{pointList:PolygonUtils.concatBeginAndEnd(o.annotation.pointList)}):o.annotation),i=new MathUtilsWorker;return{promise:new Promise(function(s){i.postMessage({points:n,backgroundList:t}),i.onmessage=r=>{s(r.data),i.terminate()}}),close:()=>{i.terminate()}}}static getCollectionPointByAnnotationData(e){const n=[],t=new Set,i=e.filter(r=>r.type==="point").map(r=>r.annotation),o=e.filter(r=>!!["polygon","line"].includes(r.type)).map(r=>r.type==="polygon"?__spreadProps(__spreadValues({},r.annotation),{pointList:PolygonUtils.concatBeginAndEnd(r.annotation.pointList)}):r.annotation),s=(r,a)=>{const{dropFoot:c}=PolygonUtils.getClosestPoint(r,a,tool.ELineTypes.Line,1,{isClose:!1});if(c!==r){const y=`${c.x} + ${c.y}`;t.has(y)||n.push(r),t.add(y)}};return i.forEach(r=>{s(r,o)}),o.forEach(r=>{let a="";a=r.id,o.forEach((c,y)=>{if(c.id===a)return;const h=[...o];h.splice(y,1),c.pointList.forEach(f=>{s(f,h)})})}),{connectionPoints:n}}static getModifiedRectangleCoordinates(e,n,t){if(e.length!==4)throw new Error("Invalid number of coordinates. Four coordinates are required.");const i=e[0],o=e[1],s=e[2],r=Math.sqrt(__pow(o.x-i.x,2)+__pow(o.y-i.y,2)),a=Math.sqrt(__pow(s.x-o.x,2)+__pow(s.y-o.y,2)),c=n/r,y=t/a,h={x:i.x+(o.x-i.x)*c,y:i.y+(o.y-i.y)*c},f={x:h.x+(s.x-o.x)*y,y:h.y+(s.y-o.y)*y},g={x:i.x+(f.x-o.x),y:i.y+(f.y-o.y)};return[i,h,f,g]}static isPointInsideCube(e,n,t){const[i,o]=t;return!!(polygonTool.isInPolygon({x:e.x,y:e.y},n)&&e.z>=i&&e.z<=o)}};let MathUtils=_MathUtils;MathUtils.isInRange=(e,n)=>{const t=Math.min(...n),i=Math.max(...n),o=r=>r<=i&&r>=t;return(Array.isArray(e)?e:[e]).every(r=>o(r))},MathUtils.withinRange=(e,n)=>{const t=Math.min(...n),i=Math.max(...n);return e>i?i:e<t?t:e},MathUtils.calcViewportBoundaries=(e,n=!1,t=tool.SEGMENT_NUMBER,i=1)=>{if(!e)return{top:0,bottom:0,left:0,right:0};const o=20/i,s=[],r=[];let a=e;n&&(a=polygonTool.createSmoothCurvePointsFromPointList(e,t)),a.forEach(({x,y:u})=>{s.push(x),r.push(u)});let c=Math.min(...s),y=Math.max(...s),h=Math.min(...r),f=Math.max(...r);const g=y-c,d=f-h;if(g<o){const x=(o-g)/2;c-=x,y+=x}if(d<o){const x=(o-d)/2;h-=x,f+=x}return{top:h,bottom:f,left:c,right:y}},MathUtils.getFootOfPerpendicular=(e,n,t,i=!1,o=!1)=>{let s={x:0,y:0};const r=n.x-t.x,a=n.y-t.y;if(Math.abs(r)<1e-8&&Math.abs(a)<1e-8)return s=n,s;let c=(e.x-n.x)*(n.x-t.x)+(e.y-n.y)*(n.y-t.y);c/=r*r+a*a,s.x=n.x+c*r,s.y=n.y+c*a;const y=_MathUtils.getLineLength(e,s),h=2,f=Math.min(n.x,t.x),g=Math.max(n.x,t.x),d=Math.min(n.y,t.y),x=Math.max(n.y,t.y),u=!(_MathUtils.isInRange(e.x,[f,g])||_MathUtils.isInRange(e.y,[d,x])),p=e.x>g+h||e.x<f-h||e.y>x+h||e.y<d-h;return!o&&(i?u:p)?{footPoint:s,length:Infinity}:{footPoint:s,length:y}},MathUtils.calculatePointsInsideBox=e=>{const{indexMap:n,polygon:t,zScope:i,box:o}=e;let s=0;return n.forEach((r,a)=>{const c=a.split("@"),y=Number(c[0]),h=Number(c[1]),f=Number(c[2]),g={x:y-.5,y:h-.5,z:f-.5,width:1,height:1,depth:1},d=getCubePosition(t,i,g);d===2&&(s+=r.length),(d===1||d===0&&(o.width<=1||o.height<=1))&&r.forEach(x=>{_MathUtils.isPointInsideCube(x,t,i)&&s++})}),s};var MathUtils$1=MathUtils;exports.Trigonometric=Trigonometric,exports.default=MathUtils$1;
@@ -0,0 +1 @@
1
+ import{createBase64WorkerFactory as e}from"./_rollup-plugin-web-worker-loader__helper__browser__createBase64WorkerFactory.js";var l=e("Lyogcm9sbHVwLXBsdWdpbi13ZWItd29ya2VyLWxvYWRlciAqLwooZnVuY3Rpb24oKXsidXNlIHN0cmljdCI7b25tZXNzYWdlPWZ1bmN0aW9uKGkpe2NvbnN0e3BvaW50czpzfT1pLmRhdGEsZT1uZXcgTWFwO2ZvcihsZXQgdD0wO3Q8cy5sZW5ndGg7dCs9Myl7Y29uc3Qgbz1zW3RdLGM9c1t0KzFdLGE9c1t0KzJdLG49YCR7TWF0aC5jZWlsKG8pfUAke01hdGguY2VpbChjKX1AJHtNYXRoLmNlaWwoYSl9YDtlLmhhcyhuKXx8ZS5zZXQobixbXSksZS5nZXQobikucHVzaCh7eDpvLHk6Yyx6OmF9KX10aGlzLnBvc3RNZXNzYWdlKHtpbmRleE1hcDplfSl9fSkoKTsKCg==",null,!1);export{l as default};
@@ -1 +1 @@
1
- import{PCDLoader as r}from"./PCDLoader.js";class e{constructor(){this.MAX_SIZE=50,this.cacheList=[],this.loadPCDFile=t=>new Promise((s,c)=>{const o=this.pointsMap.get(t),a=this.colorMap.get(t);if(o&&a){s({points:o,color:a});return}if(this.cacheList.length>this.MAX_SIZE){const i=this.cacheList.shift();i&&this.pointsMap.delete(i.src)}this.cacheList.push({src:t}),this.pcdLoader.load(t,i=>{const h=i.geometry.attributes.position.array,n=i.geometry.attributes.color.array;this.pointsMap.set(t,h),this.colorMap.set(t,n),s({points:h,color:n})},()=>{},i=>{c(i)})}),this.pcdLoader=new r,this.pointsMap=new Map,this.colorMap=new Map,this.cache2DHighlightIndex=new Map}static getInstance(){return this.instance==null&&(this.instance=new e),this.instance}updateColor(t,s){this.colorMap.set(t,s)}clearCache2DHighlightIndex(){this.cache2DHighlightIndex.clear()}}export{e as PointCloudCache};
1
+ import l from"../../_virtual/generateIndexWorker.js";import{PCDLoader as d}from"./PCDLoader.js";var M=(p,t,i)=>new Promise((r,n)=>{var o=e=>{try{a(i.next(e))}catch(c){n(c)}},s=e=>{try{a(i.throw(e))}catch(c){n(c)}},a=e=>e.done?r(e.value):Promise.resolve(e.value).then(o,s);a((i=i.apply(p,t)).next())});class h{constructor(){this.MAX_SIZE=50,this.cacheList=[],this.loadPCDFile=t=>new Promise((i,r)=>{const n=this.pointsMap.get(t),o=this.colorMap.get(t);if(n&&o){i({points:n,color:o});return}if(this.cacheList.length>this.MAX_SIZE){const s=this.cacheList.shift();s&&this.pointsMap.delete(s.src)}this.cacheList.push({src:t}),this.pcdLoader.load(t,s=>{const a=s.geometry.attributes.position.array,e=s.geometry.attributes.color.array;this.pointsMap.set(t,a),this.colorMap.set(t,e),i({points:a,color:e})},()=>{},s=>{r(s)})}),this.loadIndexMap=(t,i)=>M(this,null,function*(){const r=this.cacheIndexMap.get(t);return new Promise(n=>{if(r)return n(r);if(window.Worker){const o=new l({type:"module"});o.postMessage({points:i}),o.onmessage=s=>{const{indexMap:a}=s.data;if(this.cacheIndexMap.set(t,a),this.cacheIndexMap.size>this.MAX_SIZE){const e=Array.from(this.cacheIndexMap.keys())[0];this.cacheIndexMap.delete(e)}n(a),o.terminate()}}})}),this.pcdLoader=new d,this.pointsMap=new Map,this.colorMap=new Map,this.cacheIndexMap=new Map,this.cache2DHighlightIndex=new Map}static getInstance(){return this.instance==null&&(this.instance=new h),this.instance}updateColor(t,i){this.colorMap.set(t,i)}clearCache2DHighlightIndex(){this.cache2DHighlightIndex.clear()}}export{h as PointCloudCache};
@@ -1,4 +1,4 @@
1
- import*as a from"three";import{toolStyleConverter as T,PerspectiveShiftUtils as v,EPerspectiveView as C,PointCloudUtils as F,DEFAULT_SPHERE_PARAMS as O}from"@labelbee/lb-utils";import E from"../../_virtual/highlightWorker.js";import V from"../../_virtual/filterBoxWorker.js";import{isInPolygon as R}from"../../utils/tool/polygonTool.js";import I from"../../utils/uuid.js";import H from"../../utils/MathUtils.js";import W from"../../utils/ImgUtils.js";import{PCDLoader as Z}from"./PCDLoader.js";import{OrbitControls as U}from"./OrbitControls.js";import{PointCloudCache as G}from"./cache.js";import{getCuboidFromPointCloudBox as A,getHighlightIndexByPoints as $,mergeHighlightList as Y}from"./matrix.js";export{createThreeMatrix4,getCuboidFromPointCloudBox,getHighlightIndexByPoints,isFisheyeCalibValid,isInImage,isMatrixValid,isMatrixValidByArr,lidar2FisheyeImage,lidar2image,mergeHighlightList,oCamFisheyeTransfer,point3DLidar2Image,pointCloudLidar2image,pointListLidar2Img,pointMappingLidar2image,rotatePoint,transferKitti2Matrix}from"./matrix.js";import{PointCloudSegmentOperation as X}from"./segmentation.js";import q from"./store/index.js";import K from"./render/index.js";import Q from"../toolOperation/eventListener.js";import"../../constant/tool.js";import"../scheduler.js";var J=Object.defineProperty,tt=Object.defineProperties,et=Object.getOwnPropertyDescriptors,j=Object.getOwnPropertySymbols,it=Object.prototype.hasOwnProperty,rt=Object.prototype.propertyIsEnumerable,L=(w,t,e)=>t in w?J(w,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):w[t]=e,b=(w,t)=>{for(var e in t||(t={}))it.call(t,e)&&L(w,e,t[e]);if(j)for(var e of j(t))rt.call(t,e)&&L(w,e,t[e]);return w},B=(w,t)=>tt(w,et(t)),z=(w,t,e)=>new Promise((i,r)=>{var s=d=>{try{o(e.next(d))}catch(n){r(n)}},h=d=>{try{o(e.throw(d))}catch(n){r(n)}},o=d=>d.done?i(d.value):Promise.resolve(d.value).then(s,h);o((e=e.apply(w,t)).next())});const nt=30,k=new E({type:"module"});class ot extends Q{constructor({container:t,noAppend:e,isOrthographicCamera:i,orthographicParams:r,backgroundColor:s="#4C4C4C",config:h,isSegment:o,checkMode:d}){super();this.zAxisLimit=10,this.initCameraPosition=this.DEFAULT_INIT_CAMERA_POSITION,this.isOrthographicCamera=!1,this.pointsUuid="",this.pointCloudObjectName="pointCloud",this.rangeObjectName="range",this.highlightGroupName="highlightBoxes",this.showDirection=!0,this.pointsMaterialSize=1,this.isSegment=!1,this.checkMode=!1,this.nextTick=()=>{!this.segmentOperation||this.segmentOperation._raycasting()},this.keydown=n=>{if(!!this.store)switch(n.key){case" ":this.controls.enablePan=!0,this.store.setForbidOperation(!0);break}},this.keyup=n=>{if(!!this.store)switch(n.key){case" ":this.controls.enablePan=!1,this.store.setForbidOperation(!1);break}},this.addSphereToSense=(n,l="blue")=>{var c;const m=(c=n.id)!=null?c:I();this.removeObjectByName(m,"sphere");const{radius:u,widthSegments:f,heightSegments:p}=O,{center:g}=n,y=new a.Group,x=new a.SphereGeometry(u,f,p),M=new a.MeshBasicMaterial({color:l}),P=new a.Mesh(x,M);P.position.set(g.x,g.y,g.z),y.add(P),y.name=`sphere${m}`,this.scene.add(y)},this.generateSphere=n=>{const{fill:l}=this.getColorFromConfig(n.attribute);this.addSphereToSense(n,l),this.render()},this.generateSpheres=n=>{n.forEach(l=>{const{fill:c}=this.getColorFromConfig(l.attribute);this.addSphereToSense(l,c)}),this.render()},this.addBoxToSense=(n,l=16777215)=>{var c;const m=(c=n.id)!=null?c:I();this.removeObjectByName(m,"box");const{center:u,width:f,height:p,depth:g,rotation:y}=n,x=new a.Group,M=new a.BoxGeometry(f,p,g),P=new a.MeshBasicMaterial({color:"blue"}),S=new a.Mesh(M,P),_=new a.BoxHelper(S,l),N=this.generateBoxArrow(n),D=this.generateBoxTrackID(n);D&&x.add(D),x.add(_),x.add(N),u&&x.position.set(u.x,u.y,u.z),y&&x.rotation.set(0,0,y),x.name=`box${m}`,this.scene.add(x)},this.applyCameraTarget=n=>{if(this.camera.type==="OrthographicCamera"&&n){const l=this.getOrthographicCameraTarget(n);this.updateCameraZoom(n.zoom),this.updateCamera(n.position,l)}},this.initShaderMaterial=()=>({vertexShader:`
1
+ import*as a from"three";import{toolStyleConverter as T,PerspectiveShiftUtils as B,EPerspectiveView as C,PointCloudUtils as E,DEFAULT_SPHERE_PARAMS as O}from"@labelbee/lb-utils";import V from"../../_virtual/highlightWorker.js";import R from"../../_virtual/filterBoxWorker.js";import{isInPolygon as H}from"../../utils/tool/polygonTool.js";import A from"../../utils/uuid.js";import L from"../../utils/MathUtils.js";import W from"../../utils/ImgUtils.js";import{PCDLoader as Z}from"./PCDLoader.js";import{OrbitControls as U}from"./OrbitControls.js";import{PointCloudCache as G}from"./cache.js";import{getCuboidFromPointCloudBox as D,getHighlightIndexByPoints as $,mergeHighlightList as Y}from"./matrix.js";export{createThreeMatrix4,getCuboidFromPointCloudBox,getHighlightIndexByPoints,isFisheyeCalibValid,isInImage,isMatrixValid,isMatrixValidByArr,lidar2FisheyeImage,lidar2image,mergeHighlightList,oCamFisheyeTransfer,point3DLidar2Image,pointCloudLidar2image,pointListLidar2Img,pointMappingLidar2image,rotatePoint,transferKitti2Matrix}from"./matrix.js";import{PointCloudSegmentOperation as X}from"./segmentation.js";import q from"./store/index.js";import K from"./render/index.js";import Q from"../toolOperation/eventListener.js";import"../../constant/tool.js";import"../scheduler.js";var J=Object.defineProperty,tt=Object.defineProperties,et=Object.getOwnPropertyDescriptors,j=Object.getOwnPropertySymbols,it=Object.prototype.hasOwnProperty,rt=Object.prototype.propertyIsEnumerable,k=(w,t,e)=>t in w?J(w,t,{enumerable:!0,configurable:!0,writable:!0,value:e}):w[t]=e,b=(w,t)=>{for(var e in t||(t={}))it.call(t,e)&&k(w,e,t[e]);if(j)for(var e of j(t))rt.call(t,e)&&k(w,e,t[e]);return w},P=(w,t)=>tt(w,et(t)),S=(w,t,e)=>new Promise((i,r)=>{var s=d=>{try{o(e.next(d))}catch(n){r(n)}},c=d=>{try{o(e.throw(d))}catch(n){r(n)}},o=d=>d.done?i(d.value):Promise.resolve(d.value).then(s,c);o((e=e.apply(w,t)).next())});const nt=30,_=new V({type:"module"});class ot extends Q{constructor({container:t,noAppend:e,isOrthographicCamera:i,orthographicParams:r,backgroundColor:s="#4C4C4C",config:c,isSegment:o,checkMode:d}){super();this.zAxisLimit=10,this.initCameraPosition=this.DEFAULT_INIT_CAMERA_POSITION,this.isOrthographicCamera=!1,this.pointsUuid="",this.pointCloudObjectName="pointCloud",this.rangeObjectName="range",this.highlightGroupName="highlightBoxes",this.showDirection=!0,this.pointsMaterialSize=1,this.isSegment=!1,this.checkMode=!1,this.nextTick=()=>{!this.segmentOperation||this.segmentOperation._raycasting()},this.keydown=n=>{if(!!this.store)switch(n.key){case" ":this.controls.enablePan=!0,this.store.setForbidOperation(!0);break}},this.keyup=n=>{if(!!this.store)switch(n.key){case" ":this.controls.enablePan=!1,this.store.setForbidOperation(!1);break}},this.addSphereToSense=(n,l="blue")=>{var h;const u=(h=n.id)!=null?h:A();this.removeObjectByName(u,"sphere");const{radius:m,widthSegments:f,heightSegments:p}=O,{center:g}=n,x=new a.Group,y=new a.SphereGeometry(m,f,p),M=new a.MeshBasicMaterial({color:l}),v=new a.Mesh(y,M);v.position.set(g.x,g.y,g.z),x.add(v),x.name=`sphere${u}`,this.scene.add(x)},this.generateSphere=n=>{const{fill:l}=this.getColorFromConfig(n.attribute);this.addSphereToSense(n,l),this.render()},this.generateSpheres=n=>{n.forEach(l=>{const{fill:h}=this.getColorFromConfig(l.attribute);this.addSphereToSense(l,h)}),this.render()},this.addBoxToSense=(n,l=16777215)=>{var h;const u=(h=n.id)!=null?h:A();this.removeObjectByName(u,"box");const{center:m,width:f,height:p,depth:g,rotation:x}=n,y=new a.Group,M=new a.BoxGeometry(f,p,g),v=new a.MeshBasicMaterial({color:"blue"}),z=new a.Mesh(M,v),N=new a.BoxHelper(z,l),F=this.generateBoxArrow(n),I=this.generateBoxTrackID(n);I&&y.add(I),y.add(N),y.add(F),m&&y.position.set(m.x,m.y,m.z),x&&y.rotation.set(0,0,x),y.name=`box${u}`,this.scene.add(y)},this.applyCameraTarget=n=>{if(this.camera.type==="OrthographicCamera"&&n){const l=this.getOrthographicCameraTarget(n);this.updateCameraZoom(n.zoom),this.updateCamera(n.position,l)}},this.initShaderMaterial=()=>({vertexShader:`
2
2
  attribute vec3 dimensions;
3
3
  varying vec3 vDimensions;
4
4
  uniform float pointSize;
@@ -28,4 +28,4 @@ import*as a from"three";import{toolStyleConverter as T,PerspectiveShiftUtils as
28
28
 
29
29
  // Output the final color
30
30
  gl_FragColor = vec4(color, 1.0);
31
- }`,uniforms:{pointSize:{value:this.pointsMaterialSize}}}),this.loadPCDFile=(...n)=>z(this,[...n],function*(l=this.currentPCDSrc,c){if(!l)return;this.clearPointCloud(),this.cacheInstance.clearCache2DHighlightIndex(),this.currentPCDSrc=l;const{points:m,color:u}=yield this.cacheInstance.loadPCDFile(l),f=new a.BufferGeometry;f.setAttribute("position",new a.BufferAttribute(m,3)),this.isSegment||f.setAttribute("dimensions",new a.BufferAttribute(u,3)),this.initCloudData(m);const p=new a.Points(f);this.renderPointCloud(p,c),this.emit("loadPCDFileEnd")}),this.getHighlightIndexByMappingImgList=n=>z(this,[n],function*({mappingImgList:l,points:c}){const m=l.length===0?[]:yield Promise.all(l.map(p=>W.load(p.url))),u=l.map((p,g)=>{var y;if(this.cacheInstance.cache2DHighlightIndex.has(p.url))return(y=this.cacheInstance.cache2DHighlightIndex.get(p.url))!=null?y:[];const x=$({points:c,calib:p.calib,width:m[g].width,height:m[g].height});return this.cacheInstance.cache2DHighlightIndex.set(p.url,x),x});return Y(u)}),this.loadPCDFileByBox=(n,l,c)=>z(this,null,function*(){const m=(p,g)=>z(this,null,function*(){const{width:y=0,height:x=0,depth:M=0}=c!=null?c:{},P=yield this.filterPointsByBox(B(b({},l),{width:l.width+y,height:l.height+x,depth:l.depth+M}),p,g);if(!P){console.error("filter Error");return}this.clearPointCloud(),this.currentPCDSrc=n;const S=new a.Points(P.geometry);S.name=this.pointCloudObjectName,this.scene.add(S),this.render()}),{points:u,color:f}=yield this.cacheInstance.loadPCDFile(n);m(u,f)}),this.generateRange=n=>{const l=this.createRange(n);this.scene.add(l)},this.generateBoxArrow=({width:n})=>{const l=new a.Vector3(1,0,0),c=new a.Vector3(n/2,0,0),m=2,u=16776960,f=new a.ArrowHelper(l,c,m,u);return f.visible=this.showDirection,f},this.generateBoxTrackID=n=>{if(!n.trackID)return;const l=new a.Texture(this.getTextCanvas(n.trackID.toString()));l.needsUpdate=!0;const c=new a.SpriteMaterial({map:l,depthWrite:!1}),m=new a.Sprite(c);return m.scale.set(5,5,5),m.position.set(-n.width/2,0,n.depth/2+.5),m},this.applyZAxisPoints=n=>{this.zAxisLimit=n,this.filterZAxisPoints(),this.render()},this.updatePointSize=({zoomIn:n,customSize:l})=>{const c=this.scene.getObjectByName(this.pointCloudObjectName);if(!c)return;const m=c.material.uniforms.pointSize.value;n?c.material.uniforms.pointSize.value=Math.min(m*1.2,10):c.material.uniforms.pointSize.value=Math.max(m/1.2,1),l&&(c.material.uniforms.pointSize.value=l,this.pointsMaterialSize=l),c.material.uniformsNeedUpdate=!0,this.render()},this.container=t,this.renderer=new a.WebGLRenderer({antialias:!0}),this.backgroundColor=s,this.config=h,this.checkMode=d!=null?d:!1,i&&r?(this.isOrthographicCamera=!0,this.camera=new a.OrthographicCamera(r.left,r.right,r.top,r.bottom,r.near,r.far)):this.camera=new a.PerspectiveCamera(30,this.containerWidth/this.containerHeight,1,1e3),this.initCamera(),this.scene=new a.Scene,this.controls=new U(this.camera,o?this.container:this.renderer.domElement),this.pcdLoader=new Z,this.axesHelper=new a.AxesHelper(1e3),this.scene.add(this.camera),e||t.appendChild(this.renderer.domElement),this.init(),this.cacheInstance=G.getInstance(),o===!0&&(this.initSegment(),this.isSegment=!0)}initSegment(){this.store=new q(this.pointCloudDelegate),this.controls.enablePan=!1,this.controls.addEventListener("start",this.orbiterStart.bind(this)),this.controls.addEventListener("change",this.orbiterChange.bind(this)),this.controls.addEventListener("end",this.orbiterEnd.bind(this)),this.segmentOperation=new X(b({dom:this.container,store:this.store},this.eventBus)),this.pointCloudRender=new K(B(b({store:this.store},this.eventBus),{nextTick:this.nextTick})),this.initMsg(),document.addEventListener("keydown",this.keydown),document.addEventListener("keyup",this.keyup)}orbiterStart(){}orbiterChange(){!this.store||(this.store.orbiting=!0)}orbiterEnd(){!this.store||(this.store.orbiting=!1)}get currentSegmentTool(){var t;return(t=this.segmentOperation)==null?void 0:t.currentToolName}get pointCloudObject(){return this.scene.getObjectByName(this.pointCloudObjectName)}initMsg(){!this.segmentOperation||(this.on("CircleSelector",this.segmentOperation.updateSelector2Circle.bind(this.segmentOperation)),this.on("LassoSelector",this.segmentOperation.updateSelector2Lasso.bind(this.segmentOperation)),this.on("RectSelector",this.segmentOperation.updateSelector2Rect.bind(this.segmentOperation)),this.on("clearPointCloud",this.clearPointCloud.bind(this)),this.on("loadPCDFile",this.loadPCDFile.bind(this)))}unbindMsg(){!this.segmentOperation||(this.unbind("CircleSelector",this.segmentOperation.updateSelector2Circle.bind(this.segmentOperation)),this.unbind("LassoSelector",this.segmentOperation.updateSelector2Lasso.bind(this.segmentOperation)),this.unbind("RectSelector",this.segmentOperation.updateSelector2Rect.bind(this.segmentOperation)),this.unbind("clearPointCloud",this.clearPointCloud.bind(this)),this.unbind("loadPCDFile",this.loadPCDFile.bind(this)))}get eventBus(){return{on:this.on.bind(this),emit:this.emit.bind(this),unbind:this.unbind.bind(this)}}get pointCloudDelegate(){return b({container:this.container,scene:this.scene,camera:this.camera,renderer:this.renderer,checkMode:this.checkMode,config:this.config},this.eventBus)}get DEFAULT_INIT_CAMERA_POSITION(){return new a.Vector3(-.01,0,1e3)}get containerWidth(){return this.container.clientWidth}get containerHeight(){return this.container.clientHeight}setInitCameraPosition(t){this.initCameraPosition=t}setConfig(t){var e;this.config=t,(e=this.store)==null||e.setConfig(t)}initOrthographicCamera(t){if(this.camera.type!=="OrthographicCamera")return;const{left:e,right:i,top:r,bottom:s,near:h,far:o}=t;this.camera.left=e,this.camera.right=i,this.camera.top=r,this.camera.bottom=s,this.camera.near=h,this.camera.far=o,this.camera.updateProjectionMatrix()}initPerspectiveCamera(){this.camera.type==="PerspectiveCamera"&&(this.camera.fov=30,this.camera.aspect=this.containerWidth/this.containerHeight,this.camera.near=1,this.camera.far=1e3,this.camera.updateProjectionMatrix())}initCamera(){const{camera:t}=this;if(this.isOrthographicCamera){const{x:e,y:i,z:r}=this.initCameraPosition;t.position.set(e,i,r)}else t.position.set(-1,0,500);t.up.set(0,0,1)}initControls(){const{controls:t}=this;t.addEventListener("change",()=>{this.render()}),this.setDefaultControls()}setDefaultControls(){const{controls:t}=this,e=[0,0,0];t.target=new a.Vector3(...e),t.addEventListener("change",()=>{this.render()}),t.maxPolarAngle=Math.PI/2,t.update()}initRenderer(){const{renderer:t}=this;t.setPixelRatio(window.devicePixelRatio),t.setSize(this.containerWidth,this.containerHeight)}init(){const{scene:t}=this;t.background=new a.Color(this.backgroundColor),this.initControls(),this.initRenderer()}removeObjectByName(t,e=""){const i=this.scene.getObjectByName(e+t);i&&i.removeFromParent()}getColorFromConfig(t){return T.getColorFromConfig({attribute:t},B(b({},this.config),{attributeConfigurable:!0}),{})}generateBox(t,e=16777215){const i=e;this.addBoxToSense(t,i),this.render()}getAllAttributeColor(t){return t.reduce((e,i)=>(e[i.attribute]=this.getColorFromConfig(i.attribute),e),{})}generateBoxes(t){t.forEach(e=>{this.addBoxToSense(e)}),this.render()}getOrthographicCamera(t){const{center:e,width:i,height:r}=t,s=10,h=e.x-i/2-s,o=e.x-i/2+s,d=e.y+r/2+s,n=e.y-r/2-s,l=100,c=-100,m=500/l;return{left:h,right:o,top:d,bottom:n,near:l,far:c,zoom:m}}updateCameraZoom(t){this.camera.zoom=t,this.camera.updateProjectionMatrix()}updateCameraByBox(t,e,i){const{center:r,width:s,height:h,depth:o,rotation:d}=t,n=this.getCameraVector(r,d,{width:s,height:h,depth:o},e);return i?(this.updateCamera(i,r),new a.Vector3(i.x,i.y,i.z)):(this.updateCamera(n,r),n)}updateCameraBySphere(t,e){const{center:i}=t,{radius:r}=O,s=this.getCameraVector(i,0,{width:r*2,height:r*2,depth:r*2},e);return this.updateCamera(s,i),s}updateOrthoCamera(t,e){const i=this.updateCameraByBox(t,e);return this.camera.zoom=1,this.camera.updateProjectionMatrix(),{cameraPositionVector:i}}updateOrthoCameraBySphere(t,e){const i=this.updateCameraBySphere(t,e);return this.camera.zoom=1,this.camera.updateProjectionMatrix(),{cameraPositionVector:i}}updateTopCamera(){this.setInitCameraPosition(this.DEFAULT_INIT_CAMERA_POSITION),this.camera.zoom=1,this.initCamera(),this.setDefaultControls(),this.camera.updateProjectionMatrix(),this.render()}updateCamera(t,e){this.camera.position.set(t.x,t.y,t.z),this.controls.target=new a.Vector3(e.x,e.y,e.z),this.controls.update()}resetCamera(){this.updateCamera(this.DEFAULT_INIT_CAMERA_POSITION,{x:0,y:0,z:0})}getOrthographicCameraTarget(t){const e=new a.Vector3(0,0,-1).applyQuaternion(t.quaternion);return t.position.clone().add(e)}createThreeMatrix4(t){return new a.Matrix4().set(...t)}filterPointsByBox(t,e,i){var r,s,h;if(!e){const o=this.scene.getObjectByName(this.pointCloudObjectName);if(!o)return console.error("There is no corresponding point cloud object"),Promise.resolve(void 0);e=(h=(s=(r=o==null?void 0:o.geometry)==null?void 0:r.attributes)==null?void 0:s.position)==null?void 0:h.array}if(window.Worker){const{zMin:o,zMax:d,polygonPointList:n}=A(t),l=e;i=i!=null?i:new Float32Array([]);const c={boxParams:t,zMin:o,zMax:d,polygonPointList:n,color:i,position:l};return new Promise(m=>{const u=new V;u.postMessage(c),u.onmessage=f=>{const{color:p,position:g,num:y}=f.data,x=new a.BufferGeometry;x.setAttribute("position",new a.Float32BufferAttribute(g,3)),x.setAttribute("color",new a.Float32BufferAttribute(p,3)),x.computeBoundingSphere(),u.terminate(),m({geometry:x,num:y})}})}return Promise.resolve(void 0)}getCameraVector(t,e,i,r=C.Front,s=nt){let h=v.frontViewMatrix4(s);switch(r){case C.Front:break;case C.Back:h=v.backViewMatrix4(s);break;case C.Left:h=v.leftViewMatrix4(s);break;case C.Right:h=v.rightViewMatrix4(s);break;case C.Top:h=v.topViewMatrix4(s);break;case C.LFT:h=v.leftFrontTopViewMatrix4(s,i);break;case C.RBT:h=v.rightBackTopViewMatrix4(s,i);break}const o=this.createThreeMatrix4(h),d=new a.Matrix4().makeTranslation(-t.x,-t.y,-t.z),n=new a.Matrix4().makeTranslation(t.x,t.y,t.z),l=new a.Matrix4().makeRotationZ(e);return new a.Vector3(t.x,t.y,t.z).clone().applyMatrix4(o).applyMatrix4(d).applyMatrix4(l).applyMatrix4(n)}createRange(t){this.removeObjectByName(this.rangeObjectName);const i=new a.EllipseCurve(0,0,t,t,0,2*Math.PI,!1,0).getPoints(50),r=new a.BufferGeometry().setFromPoints(i),s=new a.LineBasicMaterial({color:16711680}),h=new a.Line(r,s);return h.name=this.rangeObjectName,h}renderPointCloud(t,e){t.name=this.pointCloudObjectName;const i=new a.ShaderMaterial(this.initShaderMaterial());e&&this.generateRange(e),this.pointsUuid=t.uuid,t.material=i,this.filterZAxisPoints(t),this.scene.add(t),this.render()}clearAllBox(){this.clearAllGroupByPrefix("box")}clearAllSphere(){this.clearAllGroupByPrefix("sphere")}clearAllGroupByPrefix(t=""){const e=this.scene.children;for(let i=e.length-1;i>=0;i--){const r=e[i];r.type==="Group"&&r.name.startsWith(t)&&this.removeObjectByName(r.name)}}clearPointCloud(){this.removeObjectByName(this.pointCloudObjectName)}clearPointCloudAndRender(){this.clearPointCloud(),this.render()}initCloudData(t){if(!!this.store){for(let e=0;e<t.length;e+=3){const i=t[e],r=t[e+1],s=t[e+2];this.store.cloudData.set(`${i}@${r}@${s}`,{visible:!1})}this.store.setOriginPoints(t)}}highlightOriginPointCloud(t,e=[]){const i=this.scene.getObjectByName(this.pointCloudObjectName);if(!!i)return this.highlightPCDSrc=this.currentPCDSrc,new Promise((r,s)=>{if(window.Worker){const o=(t?[...t]:[]).map(l=>A(l)),d=this.getAllAttributeColor(o),n={cuboidList:o,position:i.geometry.attributes.position.array,color:i.geometry.attributes.dimensions.array,colorList:d,highlightIndex:e};k.postMessage(n),k.onmessage=l=>{const{color:c}=l.data,m=new a.BufferAttribute(c,3);if(!this.highlightPCDSrc||this.highlightPCDSrc!==this.currentPCDSrc||i.geometry.attributes.position.array.length!==c.length){s(new Error("Error Path"));return}this.cacheInstance.updateColor(this.highlightPCDSrc,c),this.highlightPCDSrc=void 0,m.needsUpdate=!0,i.geometry.setAttribute("dimensions",m),i.geometry.attributes.dimensions.needsUpdate=!0,r(c),this.render()}}})}clearHighlightBoxes(){this.removeObjectByName(this.highlightGroupName)}clearHighlightBoxesAndRender(){this.clearHighlightBoxes(),this.render()}highlightBoxes(t){const e=new a.Group;t.forEach(i=>{const{center:{x:r,y:s,z:h},width:o,height:d,depth:n,rotation:l}=i,{fill:c}=T.getColorFromConfig({attribute:i.attribute},B(b({},this.config),{attributeConfigurable:!0}),{}),m=new a.BoxGeometry(o,d,n),u=new a.MeshBasicMaterial({color:c,transparent:!0,opacity:.2,depthTest:!1});m.rotateZ(l),m.translate(r,s,h);const f=new a.Mesh(m,u);e.add(f);const p=new a.PlaneGeometry(n,d);p.rotateY(Math.PI/2),p.rotateZ(l);const g=new a.Vector3(o/2,0,0),y=new a.Matrix4().makeRotationY(Math.PI/2).makeRotationZ(l);g.applyMatrix4(y),p.translate(r+g.x,s+g.y,h+g.z);const x=new a.MeshBasicMaterial({color:c,side:a.DoubleSide,transparent:!0,opacity:.8,depthTest:!1}),M=new a.Mesh(p,x);e.add(M)}),e.name=this.highlightGroupName,this.scene.add(e),this.render()}updateColor(t){const e=this.scene.getObjectByName(this.pointCloudObjectName);if(e){const i=new a.BufferAttribute(t,3);e.geometry.setAttribute("dimensions",i),e.geometry.attributes.dimensions.needsUpdate=!0,this.render()}}setShowDirection(t){this.showDirection=t,this.scene.children.forEach(e=>{e.type==="Group"&&e.children.forEach(i=>{i.type==="ArrowHelper"&&(i.visible=t)})}),this.render()}getTextCanvas(t){const e=document.createElement("canvas"),i=e.getContext("2d");return i&&(i.font=`${50}px " bold`,i.fillStyle="white",i.textAlign="center",i.textBaseline="middle",i.fillText(t,e.width/2,e.height/2)),e}filterNoise(t){let e=[...t];e.sort((c,m)=>c.z-m.z);const i=Math.floor(e.length*.05),r=e[i];e=e.filter(({z:c})=>c>r.z+.1);const s=.005,h=Math.floor(e.length*(1-s));e=e.slice(0,h),e.sort((c,m)=>c.x-m.x);const o=Math.floor(e.length*s),d=Math.floor(e.length*(1-s));e=e.slice(o,d),e.sort((c,m)=>c.y-m.y);const n=Math.floor(e.length*s),l=Math.floor(e.length*(1-s));return e=e.slice(n,l),e.length>100?e:t}getFittedCoordinates(t,e){const i=[];let r=[...t,t[0]];e.forEach(({x:d,y:n})=>{t.forEach((l,c)=>{const m=r[c+1],u=H.getFootOfPerpendicular({x:d,y:n},l,m,!1,!0).length;(!i[c]||u<i[c].distance)&&(i[c]={distance:u,point:{x:d,y:n}})})}),r=[t[t.length-1],...t,t[0]];const s=[i[i.length-1],...i],h=t.map((d,n)=>{const l=r[n],c=r[n+1],m=r[n+2];return F.getIntersectionBySlope({p1:s[n].point,line1:[l,c],p2:s[n+1].point,line2:[c,m]})});return h.some(d=>!(Number.isFinite(d.x)&&Number.isFinite(d.y)))?t:h}getSensesPointZAxisInPolygon(t,e,i){var r,s,h;const o=this.scene.children.find(p=>p.uuid===this.pointsUuid);let d=0,n=0,l=0,c=0,m=[],u=[];const f=((h=(s=(r=o==null?void 0:o.geometry)==null?void 0:r.attributes)==null?void 0:s.position)==null?void 0:h.array)||[];for(let p=0;p<f.length;p+=3){const g=f[p],y=f[p+1],x=f[p+2];R({x:g,y},t)&&(x||x===0)&&u.push({x:g,y,z:x})}return u.length?(i&&(u=this.filterNoise(u),m=this.getFittedCoordinates(t,u)),u.sort((p,g)=>p.z-g.z),d=u[0].z-.01,n=u[u.length-1].z+.01,c=u.length,e&&(l=u.filter(({z:p})=>p>=e[0]&&p<=e[1]).length),{maxZ:n,minZ:d,count:l,zCount:c,fittedCoordinates:m}):{maxZ:n,minZ:d,count:l,zCount:c,fittedCoordinates:m}}getBasicCoordinate2Canvas(t){const e=this.containerWidth/2,i=this.containerHeight/2;return{x:t.x*e+e,y:t.y*i+i,z:t.z}}get basicCoordinate2CanvasMatrix4(){const t=this.containerWidth/2,e=this.containerHeight/2;return new a.Matrix4().set(t,0,0,t,0,e,0,e,0,0,1,0,0,0,0,1)}getCanvas2BasicCoordinate(t){const e=this.containerWidth/2,i=this.containerHeight/2;return new a.Vector3(t.x/e-e/2,-(t.y/i-i/2),1)}getPolygonSidePoints(t){const{center:{x:e,y:i,z:r},height:s,width:h,depth:o}=t,d={x:e+h/2,y:i+s/2,z:r-o/2},n={x:e+h/2,y:i+s/2,z:r+o/2},l={x:e-h/2,y:i+s/2,z:r+o/2},c={x:e-h/2,y:i+s/2,z:r-o/2};return[d,n,l,c]}getPolygonBackPoints(t){const{center:{x:e,y:i,z:r},height:s,width:h,depth:o}=t,d={x:e-h/2,y:i+s/2,z:r+o/2},n={x:e-h/2,y:i+s/2,z:r-o/2},l={x:e-h/2,y:i-s/2,z:r-o/2},c={x:e-h/2,y:i-s/2,z:r+o/2};return[d,n,l,c]}getPolygonTopPoints(t){const{center:{x:e,y:i,z:r},height:s,width:h,depth:o}=t,d={x:e+h/2,y:i+s/2,z:r+o/2},n={x:e+h/2,y:i-s/2,z:r+o/2},l={x:e-h/2,y:i-s/2,z:r+o/2},c={x:e-h/2,y:i+s/2,z:r+o/2};return[d,n,l,c]}getModelTransformationMatrix(t){const{center:{x:e,y:i,z:r},rotation:s}=t,h=new a.Matrix4().makeTranslation(-e,-i,-r),o=new a.Matrix4().makeTranslation(e,i,r),d=new a.Matrix4().makeRotationZ(s);return new a.Matrix4().multiply(o).multiply(d).multiply(h)}getBoxSidePolygon2DCoordinate(t){return this.getBoxPolygon2DCoordinate(t,C.Left)}getBoxBackPolygon2DCoordinate(t){return this.getBoxPolygon2DCoordinate(t,C.Back)}getSphereSidePoint2DCoordinate(t){return this.getSpherePoint2DCoordinate(t)}getSphereBackPoint2DCoordinate(t){return this.getSpherePoint2DCoordinate(t)}boxParams2ViewPolygon(t,e){switch(e){case C.Left:return this.getPolygonSidePoints(t);case C.Back:return this.getPolygonBackPoints(t);default:return this.getPolygonTopPoints(t)}}getBoxPolygon2DCoordinate(t,e){const i=this.boxParams2ViewPolygon(t,e),{width:r,height:s}=t,h=new a.Matrix4().premultiply(this.camera.matrixWorldInverse).premultiply(this.camera.projectionMatrix),o=new a.Matrix4().premultiply(this.getModelTransformationMatrix(t)).premultiply(h).premultiply(this.basicCoordinate2CanvasMatrix4);this.sideMatrix=o;const d=i.map(c=>new a.Vector3(c.x,c.y,c.z)).map(c=>c.applyMatrix4(this.sideMatrix)),n=this.containerWidth/r,l=this.containerHeight/s;return{polygon2d:d,zoom:Math.min(n,l)/2}}getSpherePoint2DCoordinate(t){const{center:e,attribute:i,id:r,valid:s}=t,{radius:h}=O,o={center:e,attribute:i,id:r,valid:s,width:h*2,height:h*2,depth:h*2,rotation:0},d=new a.Matrix4().premultiply(this.camera.matrixWorldInverse).premultiply(this.camera.projectionMatrix),n=new a.Matrix4().premultiply(this.getModelTransformationMatrix(o)).premultiply(d).premultiply(this.basicCoordinate2CanvasMatrix4);this.sideMatrix=n;const l=new a.Vector3(e.x,e.y,e.z).applyMatrix4(this.sideMatrix),c=this.containerWidth/(h*2),m=this.containerHeight/(h*2);return{point2d:l,zoom:Math.min(c,m)/2}}getSphereTopPoint2DCoordinate(t){const{center:e}=t,{radius:i}=O,r={x:-(e.y-this.containerWidth/2),y:-(e.x-this.containerHeight/2)},s=this.containerWidth/(i*2),h=this.containerHeight/(i*2);return{point2d:r,zoom:Math.min(s,h)/2}}getBoxTopPolygon2DCoordinate(t){const{width:e,height:i}=t,s=this.getPolygonTopPoints(t).map(d=>new a.Vector3(d.x,d.y,d.z)).map(d=>d.applyMatrix4(this.getModelTransformationMatrix(t))).map(d=>({x:d.y,y:d.x})).map(d=>({x:-(d.x-this.containerWidth/2),y:-(d.y-this.containerHeight/2)})),h=this.containerWidth/e,o=this.containerHeight/i;return{polygon2d:s,zoom:Math.min(h,o)/2}}getNewBoxBySideUpdate(t,e,i,r){const s=new a.Matrix4().makeRotationZ(r.rotation),h=new a.Vector3(-t.x,0,0).applyMatrix4(s);let o=r;return o.center={x:o.center.x+h.x,y:o.center.y+h.y,z:o.center.z-t.z},o=B(b({},o),{width:Math.abs(o.width+e),height:o.height,depth:Math.abs(o.depth+i)}),{newBoxParams:o}}getNewBoxByBackUpdate(t,e,i,r){const s=new a.Matrix4().makeRotationZ(r.rotation),h=new a.Vector3(0,-t.x,0).applyMatrix4(s);let o=r;return o.center={x:o.center.x+h.x,y:o.center.y+h.y,z:o.center.z-t.z},o=B(b({},o),{width:o.width,height:Math.abs(o.height+e),depth:Math.abs(o.depth+i)}),{newBoxParams:o}}getNewBoxBySideUpdateByPoints(t,e,i,r){var s;const h=(s=this.sideMatrix)==null?void 0:s.invert();if(!this.sideMatrix||!h){console.error("No sideMatrix");return}this.camera.zoom=1,this.camera.updateProjectionMatrix();const o=t.map(g=>new a.Vector3(g.x,g.y,g.z)).map(g=>g.applyMatrix4(h)),[d,n,l,c]=o,m=Math.max(Math.abs(d.x-l.x),Math.abs(d.x-n.x)),f=n.add(c).applyMatrix3(new a.Matrix3().set(1/2,0,0,0,1/2,0,0,0,1/2)).clone().applyMatrix3(new a.Matrix3().set(-1,0,0,0,-1,0,0,0,-1)).add(new a.Vector3(r.center.x,r.center.y,r.center.z));return{newBoxParams:B(b({},r),{center:{x:r.center.x-f.x,y:r.center.y-f.y,z:r.center.z-i},width:m,height:r.height,depth:r.depth+e,rotation:r.rotation})}}filterZAxisPoints(t){const e=t||this.scene.children.find(i=>i.uuid===this.pointsUuid);if(e){const{attributes:i}=e.geometry,{position:r}=i,s=[],{count:h}=r;for(let o=0;o<h;o++){const d=r.getZ(o);s.push(d>this.zAxisLimit?0:1)}e.geometry.setAttribute("visibility",new a.Float32BufferAttribute(s,1)),e.geometry.attributes.visibility.needsUpdate=!0}}render(){this.renderer.render(this.scene,this.camera)}}export{ot as PointCloud};
31
+ }`,uniforms:{pointSize:{value:this.pointsMaterialSize}}}),this.loadPCDFile=(...n)=>S(this,[...n],function*(l=this.currentPCDSrc,h){if(!l)return;this.clearPointCloud(),this.cacheInstance.clearCache2DHighlightIndex(),this.currentPCDSrc=l;const{points:u,color:m}=yield this.cacheInstance.loadPCDFile(l),f=new a.BufferGeometry;f.setAttribute("position",new a.BufferAttribute(u,3)),this.isSegment||f.setAttribute("dimensions",new a.BufferAttribute(m,3)),this.initCloudData(u);const p=new a.Points(f);this.renderPointCloud(p,h),this.emit("loadPCDFileEnd")}),this.getHighlightIndexByMappingImgList=n=>S(this,[n],function*({mappingImgList:l,points:h}){const u=l.length===0?[]:yield Promise.all(l.map(p=>W.load(p.url))),m=l.map((p,g)=>{var x;if(this.cacheInstance.cache2DHighlightIndex.has(p.url))return(x=this.cacheInstance.cache2DHighlightIndex.get(p.url))!=null?x:[];const y=$({points:h,calib:p.calib,width:u[g].width,height:u[g].height});return this.cacheInstance.cache2DHighlightIndex.set(p.url,y),y});return Y(m)}),this.filterPreResult=(n,l,h)=>S(this,null,function*(){const{points:u}=yield this.cacheInstance.loadPCDFile(n),m=yield this.cacheInstance.loadIndexMap(n,u);return new Promise(f=>{const p=h.map(g=>{const x=L.calculatePointsInsideBox({indexMap:m,polygon:D(g).polygonPointList,zScope:[g.center.z-g.depth/2,g.center.z+g.depth/2],box:g}),y=x>=l.lowerLimitPointsNumInBox;return P(b({},g),{valid:y,count:x})});f(p)})}),this.loadPCDFileByBox=(n,l,h)=>S(this,null,function*(){const u=(p,g)=>S(this,null,function*(){const{width:x=0,height:y=0,depth:M=0}=h!=null?h:{},v=yield this.filterPointsByBox(P(b({},l),{width:l.width+x,height:l.height+y,depth:l.depth+M}),p,g);if(!v){console.error("filter Error");return}this.clearPointCloud(),this.currentPCDSrc=n;const z=new a.Points(v.geometry);z.name=this.pointCloudObjectName,this.scene.add(z),this.render()}),{points:m,color:f}=yield this.cacheInstance.loadPCDFile(n);u(m,f)}),this.generateRange=n=>{const l=this.createRange(n);this.scene.add(l)},this.generateBoxArrow=({width:n})=>{const l=new a.Vector3(1,0,0),h=new a.Vector3(n/2,0,0),u=2,m=16776960,f=new a.ArrowHelper(l,h,u,m);return f.visible=this.showDirection,f},this.generateBoxTrackID=n=>{if(!n.trackID)return;const l=new a.Texture(this.getTextCanvas(n.trackID.toString()));l.needsUpdate=!0;const h=new a.SpriteMaterial({map:l,depthWrite:!1}),u=new a.Sprite(h);return u.scale.set(5,5,5),u.position.set(-n.width/2,0,n.depth/2+.5),u},this.applyZAxisPoints=n=>{this.zAxisLimit=n,this.filterZAxisPoints(),this.render()},this.updatePointSize=({zoomIn:n,customSize:l})=>{const h=this.scene.getObjectByName(this.pointCloudObjectName);if(!h)return;const u=h.material.uniforms.pointSize.value;n?h.material.uniforms.pointSize.value=Math.min(u*1.2,10):h.material.uniforms.pointSize.value=Math.max(u/1.2,1),l&&(h.material.uniforms.pointSize.value=l,this.pointsMaterialSize=l),h.material.uniformsNeedUpdate=!0,this.render()},this.container=t,this.renderer=new a.WebGLRenderer({antialias:!0}),this.backgroundColor=s,this.config=c,this.checkMode=d!=null?d:!1,i&&r?(this.isOrthographicCamera=!0,this.camera=new a.OrthographicCamera(r.left,r.right,r.top,r.bottom,r.near,r.far)):this.camera=new a.PerspectiveCamera(30,this.containerWidth/this.containerHeight,1,1e3),this.initCamera(),this.scene=new a.Scene,this.controls=new U(this.camera,o?this.container:this.renderer.domElement),this.pcdLoader=new Z,this.axesHelper=new a.AxesHelper(1e3),this.scene.add(this.camera),e||t.appendChild(this.renderer.domElement),this.init(),this.cacheInstance=G.getInstance(),o===!0&&(this.initSegment(),this.isSegment=!0)}initSegment(){this.store=new q(this.pointCloudDelegate),this.controls.enablePan=!1,this.controls.addEventListener("start",this.orbiterStart.bind(this)),this.controls.addEventListener("change",this.orbiterChange.bind(this)),this.controls.addEventListener("end",this.orbiterEnd.bind(this)),this.segmentOperation=new X(b({dom:this.container,store:this.store},this.eventBus)),this.pointCloudRender=new K(P(b({store:this.store},this.eventBus),{nextTick:this.nextTick})),this.initMsg(),document.addEventListener("keydown",this.keydown),document.addEventListener("keyup",this.keyup)}orbiterStart(){}orbiterChange(){!this.store||(this.store.orbiting=!0)}orbiterEnd(){!this.store||(this.store.orbiting=!1)}get currentSegmentTool(){var t;return(t=this.segmentOperation)==null?void 0:t.currentToolName}get pointCloudObject(){return this.scene.getObjectByName(this.pointCloudObjectName)}initMsg(){!this.segmentOperation||(this.on("CircleSelector",this.segmentOperation.updateSelector2Circle.bind(this.segmentOperation)),this.on("LassoSelector",this.segmentOperation.updateSelector2Lasso.bind(this.segmentOperation)),this.on("RectSelector",this.segmentOperation.updateSelector2Rect.bind(this.segmentOperation)),this.on("clearPointCloud",this.clearPointCloud.bind(this)),this.on("loadPCDFile",this.loadPCDFile.bind(this)))}unbindMsg(){!this.segmentOperation||(this.unbind("CircleSelector",this.segmentOperation.updateSelector2Circle.bind(this.segmentOperation)),this.unbind("LassoSelector",this.segmentOperation.updateSelector2Lasso.bind(this.segmentOperation)),this.unbind("RectSelector",this.segmentOperation.updateSelector2Rect.bind(this.segmentOperation)),this.unbind("clearPointCloud",this.clearPointCloud.bind(this)),this.unbind("loadPCDFile",this.loadPCDFile.bind(this)))}get eventBus(){return{on:this.on.bind(this),emit:this.emit.bind(this),unbind:this.unbind.bind(this)}}get pointCloudDelegate(){return b({container:this.container,scene:this.scene,camera:this.camera,renderer:this.renderer,checkMode:this.checkMode,config:this.config},this.eventBus)}get DEFAULT_INIT_CAMERA_POSITION(){return new a.Vector3(-.01,0,1e3)}get containerWidth(){return this.container.clientWidth}get containerHeight(){return this.container.clientHeight}setInitCameraPosition(t){this.initCameraPosition=t}setConfig(t){var e;this.config=t,(e=this.store)==null||e.setConfig(t)}initOrthographicCamera(t){if(this.camera.type!=="OrthographicCamera")return;const{left:e,right:i,top:r,bottom:s,near:c,far:o}=t;this.camera.left=e,this.camera.right=i,this.camera.top=r,this.camera.bottom=s,this.camera.near=c,this.camera.far=o,this.camera.updateProjectionMatrix()}initPerspectiveCamera(){this.camera.type==="PerspectiveCamera"&&(this.camera.fov=30,this.camera.aspect=this.containerWidth/this.containerHeight,this.camera.near=1,this.camera.far=1e3,this.camera.updateProjectionMatrix())}initCamera(){const{camera:t}=this;if(this.isOrthographicCamera){const{x:e,y:i,z:r}=this.initCameraPosition;t.position.set(e,i,r)}else t.position.set(-1,0,500);t.up.set(0,0,1)}initControls(){const{controls:t}=this;t.addEventListener("change",()=>{this.render()}),this.setDefaultControls()}setDefaultControls(){const{controls:t}=this,e=[0,0,0];t.target=new a.Vector3(...e),t.addEventListener("change",()=>{this.render()}),t.maxPolarAngle=Math.PI/2,t.update()}initRenderer(){const{renderer:t}=this;t.setPixelRatio(window.devicePixelRatio),t.setSize(this.containerWidth,this.containerHeight)}init(){const{scene:t}=this;t.background=new a.Color(this.backgroundColor),this.initControls(),this.initRenderer()}removeObjectByName(t,e=""){const i=this.scene.getObjectByName(e+t);i&&i.removeFromParent()}getColorFromConfig(t){return T.getColorFromConfig({attribute:t},P(b({},this.config),{attributeConfigurable:!0}),{})}generateBox(t,e=16777215){const i=e;this.addBoxToSense(t,i),this.render()}getAllAttributeColor(t){return t.reduce((e,i)=>(e[i.attribute]=this.getColorFromConfig(i.attribute),e),{})}generateBoxes(t){t.forEach(e=>{this.addBoxToSense(e)}),this.render()}getOrthographicCamera(t){const{center:e,width:i,height:r}=t,s=10,c=e.x-i/2-s,o=e.x-i/2+s,d=e.y+r/2+s,n=e.y-r/2-s,l=100,h=-100,u=500/l;return{left:c,right:o,top:d,bottom:n,near:l,far:h,zoom:u}}updateCameraZoom(t){this.camera.zoom=t,this.camera.updateProjectionMatrix()}updateCameraByBox(t,e,i){const{center:r,width:s,height:c,depth:o,rotation:d}=t,n=this.getCameraVector(r,d,{width:s,height:c,depth:o},e);return i?(this.updateCamera(i,r),new a.Vector3(i.x,i.y,i.z)):(this.updateCamera(n,r),n)}updateCameraBySphere(t,e){const{center:i}=t,{radius:r}=O,s=this.getCameraVector(i,0,{width:r*2,height:r*2,depth:r*2},e);return this.updateCamera(s,i),s}updateOrthoCamera(t,e){const i=this.updateCameraByBox(t,e);return this.camera.zoom=1,this.camera.updateProjectionMatrix(),{cameraPositionVector:i}}updateOrthoCameraBySphere(t,e){const i=this.updateCameraBySphere(t,e);return this.camera.zoom=1,this.camera.updateProjectionMatrix(),{cameraPositionVector:i}}updateTopCamera(){this.setInitCameraPosition(this.DEFAULT_INIT_CAMERA_POSITION),this.camera.zoom=1,this.initCamera(),this.setDefaultControls(),this.camera.updateProjectionMatrix(),this.render()}updateCamera(t,e){this.camera.position.set(t.x,t.y,t.z),this.controls.target=new a.Vector3(e.x,e.y,e.z),this.controls.update()}resetCamera(){this.updateCamera(this.DEFAULT_INIT_CAMERA_POSITION,{x:0,y:0,z:0})}getOrthographicCameraTarget(t){const e=new a.Vector3(0,0,-1).applyQuaternion(t.quaternion);return t.position.clone().add(e)}createThreeMatrix4(t){return new a.Matrix4().set(...t)}filterPointsByBox(t,e,i){var r,s,c;if(!e){const o=this.scene.getObjectByName(this.pointCloudObjectName);if(!o)return console.error("There is no corresponding point cloud object"),Promise.resolve(void 0);e=(c=(s=(r=o==null?void 0:o.geometry)==null?void 0:r.attributes)==null?void 0:s.position)==null?void 0:c.array}if(window.Worker){const{zMin:o,zMax:d,polygonPointList:n}=D(t),l=e;i=i!=null?i:new Float32Array([]);const h={boxParams:t,zMin:o,zMax:d,polygonPointList:n,color:i,position:l};return new Promise(u=>{const m=new R;m.postMessage(h),m.onmessage=f=>{const{color:p,position:g,num:x}=f.data,y=new a.BufferGeometry;y.setAttribute("position",new a.Float32BufferAttribute(g,3)),y.setAttribute("color",new a.Float32BufferAttribute(p,3)),y.computeBoundingSphere(),m.terminate(),u({geometry:y,num:x})}})}return Promise.resolve(void 0)}getCameraVector(t,e,i,r=C.Front,s=nt){let c=B.frontViewMatrix4(s);switch(r){case C.Front:break;case C.Back:c=B.backViewMatrix4(s);break;case C.Left:c=B.leftViewMatrix4(s);break;case C.Right:c=B.rightViewMatrix4(s);break;case C.Top:c=B.topViewMatrix4(s);break;case C.LFT:c=B.leftFrontTopViewMatrix4(s,i);break;case C.RBT:c=B.rightBackTopViewMatrix4(s,i);break}const o=this.createThreeMatrix4(c),d=new a.Matrix4().makeTranslation(-t.x,-t.y,-t.z),n=new a.Matrix4().makeTranslation(t.x,t.y,t.z),l=new a.Matrix4().makeRotationZ(e);return new a.Vector3(t.x,t.y,t.z).clone().applyMatrix4(o).applyMatrix4(d).applyMatrix4(l).applyMatrix4(n)}createRange(t){this.removeObjectByName(this.rangeObjectName);const i=new a.EllipseCurve(0,0,t,t,0,2*Math.PI,!1,0).getPoints(50),r=new a.BufferGeometry().setFromPoints(i),s=new a.LineBasicMaterial({color:16711680}),c=new a.Line(r,s);return c.name=this.rangeObjectName,c}renderPointCloud(t,e){t.name=this.pointCloudObjectName;const i=new a.ShaderMaterial(this.initShaderMaterial());e&&this.generateRange(e),this.pointsUuid=t.uuid,t.material=i,this.filterZAxisPoints(t),this.scene.add(t),this.render()}clearAllBox(){this.clearAllGroupByPrefix("box")}clearAllSphere(){this.clearAllGroupByPrefix("sphere")}clearAllGroupByPrefix(t=""){const e=this.scene.children;for(let i=e.length-1;i>=0;i--){const r=e[i];r.type==="Group"&&r.name.startsWith(t)&&this.removeObjectByName(r.name)}}clearPointCloud(){this.removeObjectByName(this.pointCloudObjectName)}clearPointCloudAndRender(){this.clearPointCloud(),this.render()}initCloudData(t){if(!!this.store){for(let e=0;e<t.length;e+=3){const i=t[e],r=t[e+1],s=t[e+2];this.store.cloudData.set(`${i}@${r}@${s}`,{visible:!1})}this.store.setOriginPoints(t)}}highlightOriginPointCloud(t,e=[]){const i=this.scene.getObjectByName(this.pointCloudObjectName);if(!!i)return this.highlightPCDSrc=this.currentPCDSrc,new Promise((r,s)=>{if(window.Worker){const o=(t?[...t]:[]).map(l=>D(l)),d=this.getAllAttributeColor(o),n={cuboidList:o,position:i.geometry.attributes.position.array,color:i.geometry.attributes.dimensions.array,colorList:d,highlightIndex:e};_.postMessage(n),_.onmessage=l=>{const{color:h}=l.data,u=new a.BufferAttribute(h,3);if(!this.highlightPCDSrc||this.highlightPCDSrc!==this.currentPCDSrc||i.geometry.attributes.position.array.length!==h.length){s(new Error("Error Path"));return}this.cacheInstance.updateColor(this.highlightPCDSrc,h),this.highlightPCDSrc=void 0,u.needsUpdate=!0,i.geometry.setAttribute("dimensions",u),i.geometry.attributes.dimensions.needsUpdate=!0,r(h),this.render()}}})}clearHighlightBoxes(){this.removeObjectByName(this.highlightGroupName)}clearHighlightBoxesAndRender(){this.clearHighlightBoxes(),this.render()}highlightBoxes(t){const e=new a.Group;t.forEach(i=>{const{center:{x:r,y:s,z:c},width:o,height:d,depth:n,rotation:l}=i,{fill:h}=T.getColorFromConfig({attribute:i.attribute},P(b({},this.config),{attributeConfigurable:!0}),{}),u=new a.BoxGeometry(o,d,n),m=new a.MeshBasicMaterial({color:h,transparent:!0,opacity:.2,depthTest:!1});u.rotateZ(l),u.translate(r,s,c);const f=new a.Mesh(u,m);e.add(f);const p=new a.PlaneGeometry(n,d);p.rotateY(Math.PI/2),p.rotateZ(l);const g=new a.Vector3(o/2,0,0),x=new a.Matrix4().makeRotationY(Math.PI/2).makeRotationZ(l);g.applyMatrix4(x),p.translate(r+g.x,s+g.y,c+g.z);const y=new a.MeshBasicMaterial({color:h,side:a.DoubleSide,transparent:!0,opacity:.8,depthTest:!1}),M=new a.Mesh(p,y);e.add(M)}),e.name=this.highlightGroupName,this.scene.add(e),this.render()}updateColor(t){const e=this.scene.getObjectByName(this.pointCloudObjectName);if(e){const i=new a.BufferAttribute(t,3);e.geometry.setAttribute("dimensions",i),e.geometry.attributes.dimensions.needsUpdate=!0,this.render()}}setShowDirection(t){this.showDirection=t,this.scene.children.forEach(e=>{e.type==="Group"&&e.children.forEach(i=>{i.type==="ArrowHelper"&&(i.visible=t)})}),this.render()}getTextCanvas(t){const e=document.createElement("canvas"),i=e.getContext("2d");return i&&(i.font=`${50}px " bold`,i.fillStyle="white",i.textAlign="center",i.textBaseline="middle",i.fillText(t,e.width/2,e.height/2)),e}filterNoise(t){let e=[...t];e.sort((h,u)=>h.z-u.z);const i=Math.floor(e.length*.05),r=e[i];e=e.filter(({z:h})=>h>r.z+.1);const s=.005,c=Math.floor(e.length*(1-s));e=e.slice(0,c),e.sort((h,u)=>h.x-u.x);const o=Math.floor(e.length*s),d=Math.floor(e.length*(1-s));e=e.slice(o,d),e.sort((h,u)=>h.y-u.y);const n=Math.floor(e.length*s),l=Math.floor(e.length*(1-s));return e=e.slice(n,l),e.length>100?e:t}getFittedCoordinates(t,e){const i=[];let r=[...t,t[0]];e.forEach(({x:d,y:n})=>{t.forEach((l,h)=>{const u=r[h+1],m=L.getFootOfPerpendicular({x:d,y:n},l,u,!1,!0).length;(!i[h]||m<i[h].distance)&&(i[h]={distance:m,point:{x:d,y:n}})})}),r=[t[t.length-1],...t,t[0]];const s=[i[i.length-1],...i],c=t.map((d,n)=>{const l=r[n],h=r[n+1],u=r[n+2];return E.getIntersectionBySlope({p1:s[n].point,line1:[l,h],p2:s[n+1].point,line2:[h,u]})});return c.some(d=>!(Number.isFinite(d.x)&&Number.isFinite(d.y)))?t:c}getSensesPointZAxisInPolygon(t,e,i){var r,s,c;const o=this.scene.children.find(p=>p.uuid===this.pointsUuid);let d=0,n=0,l=0,h=0,u=[],m=[];const f=((c=(s=(r=o==null?void 0:o.geometry)==null?void 0:r.attributes)==null?void 0:s.position)==null?void 0:c.array)||[];for(let p=0;p<f.length;p+=3){const g=f[p],x=f[p+1],y=f[p+2];H({x:g,y:x},t)&&(y||y===0)&&m.push({x:g,y:x,z:y})}return m.length?(i&&(m=this.filterNoise(m),u=this.getFittedCoordinates(t,m)),m.sort((p,g)=>p.z-g.z),d=m[0].z-.01,n=m[m.length-1].z+.01,h=m.length,e&&(l=m.filter(({z:p})=>p>=e[0]&&p<=e[1]).length),{maxZ:n,minZ:d,count:l,zCount:h,fittedCoordinates:u}):{maxZ:n,minZ:d,count:l,zCount:h,fittedCoordinates:u}}getBasicCoordinate2Canvas(t){const e=this.containerWidth/2,i=this.containerHeight/2;return{x:t.x*e+e,y:t.y*i+i,z:t.z}}get basicCoordinate2CanvasMatrix4(){const t=this.containerWidth/2,e=this.containerHeight/2;return new a.Matrix4().set(t,0,0,t,0,e,0,e,0,0,1,0,0,0,0,1)}getCanvas2BasicCoordinate(t){const e=this.containerWidth/2,i=this.containerHeight/2;return new a.Vector3(t.x/e-e/2,-(t.y/i-i/2),1)}getPolygonSidePoints(t){const{center:{x:e,y:i,z:r},height:s,width:c,depth:o}=t,d={x:e+c/2,y:i+s/2,z:r-o/2},n={x:e+c/2,y:i+s/2,z:r+o/2},l={x:e-c/2,y:i+s/2,z:r+o/2},h={x:e-c/2,y:i+s/2,z:r-o/2};return[d,n,l,h]}getPolygonBackPoints(t){const{center:{x:e,y:i,z:r},height:s,width:c,depth:o}=t,d={x:e-c/2,y:i+s/2,z:r+o/2},n={x:e-c/2,y:i+s/2,z:r-o/2},l={x:e-c/2,y:i-s/2,z:r-o/2},h={x:e-c/2,y:i-s/2,z:r+o/2};return[d,n,l,h]}getPolygonTopPoints(t){const{center:{x:e,y:i,z:r},height:s,width:c,depth:o}=t,d={x:e+c/2,y:i+s/2,z:r+o/2},n={x:e+c/2,y:i-s/2,z:r+o/2},l={x:e-c/2,y:i-s/2,z:r+o/2},h={x:e-c/2,y:i+s/2,z:r+o/2};return[d,n,l,h]}getModelTransformationMatrix(t){const{center:{x:e,y:i,z:r},rotation:s}=t,c=new a.Matrix4().makeTranslation(-e,-i,-r),o=new a.Matrix4().makeTranslation(e,i,r),d=new a.Matrix4().makeRotationZ(s);return new a.Matrix4().multiply(o).multiply(d).multiply(c)}getBoxSidePolygon2DCoordinate(t){return this.getBoxPolygon2DCoordinate(t,C.Left)}getBoxBackPolygon2DCoordinate(t){return this.getBoxPolygon2DCoordinate(t,C.Back)}getSphereSidePoint2DCoordinate(t){return this.getSpherePoint2DCoordinate(t)}getSphereBackPoint2DCoordinate(t){return this.getSpherePoint2DCoordinate(t)}boxParams2ViewPolygon(t,e){switch(e){case C.Left:return this.getPolygonSidePoints(t);case C.Back:return this.getPolygonBackPoints(t);default:return this.getPolygonTopPoints(t)}}getBoxPolygon2DCoordinate(t,e){const i=this.boxParams2ViewPolygon(t,e),{width:r,height:s}=t,c=new a.Matrix4().premultiply(this.camera.matrixWorldInverse).premultiply(this.camera.projectionMatrix),o=new a.Matrix4().premultiply(this.getModelTransformationMatrix(t)).premultiply(c).premultiply(this.basicCoordinate2CanvasMatrix4);this.sideMatrix=o;const d=i.map(h=>new a.Vector3(h.x,h.y,h.z)).map(h=>h.applyMatrix4(this.sideMatrix)),n=this.containerWidth/r,l=this.containerHeight/s;return{polygon2d:d,zoom:Math.min(n,l)/2}}getSpherePoint2DCoordinate(t){const{center:e,attribute:i,id:r,valid:s}=t,{radius:c}=O,o={center:e,attribute:i,id:r,valid:s,width:c*2,height:c*2,depth:c*2,rotation:0},d=new a.Matrix4().premultiply(this.camera.matrixWorldInverse).premultiply(this.camera.projectionMatrix),n=new a.Matrix4().premultiply(this.getModelTransformationMatrix(o)).premultiply(d).premultiply(this.basicCoordinate2CanvasMatrix4);this.sideMatrix=n;const l=new a.Vector3(e.x,e.y,e.z).applyMatrix4(this.sideMatrix),h=this.containerWidth/(c*2),u=this.containerHeight/(c*2);return{point2d:l,zoom:Math.min(h,u)/2}}getSphereTopPoint2DCoordinate(t){const{center:e}=t,{radius:i}=O,r={x:-(e.y-this.containerWidth/2),y:-(e.x-this.containerHeight/2)},s=this.containerWidth/(i*2),c=this.containerHeight/(i*2);return{point2d:r,zoom:Math.min(s,c)/2}}getBoxTopPolygon2DCoordinate(t){const{width:e,height:i}=t,s=this.getPolygonTopPoints(t).map(d=>new a.Vector3(d.x,d.y,d.z)).map(d=>d.applyMatrix4(this.getModelTransformationMatrix(t))).map(d=>({x:d.y,y:d.x})).map(d=>({x:-(d.x-this.containerWidth/2),y:-(d.y-this.containerHeight/2)})),c=this.containerWidth/e,o=this.containerHeight/i;return{polygon2d:s,zoom:Math.min(c,o)/2}}getNewBoxBySideUpdate(t,e,i,r){const s=new a.Matrix4().makeRotationZ(r.rotation),c=new a.Vector3(-t.x,0,0).applyMatrix4(s);let o=r;return o.center={x:o.center.x+c.x,y:o.center.y+c.y,z:o.center.z-t.z},o=P(b({},o),{width:Math.abs(o.width+e),height:o.height,depth:Math.abs(o.depth+i)}),{newBoxParams:o}}getNewBoxByBackUpdate(t,e,i,r){const s=new a.Matrix4().makeRotationZ(r.rotation),c=new a.Vector3(0,-t.x,0).applyMatrix4(s);let o=r;return o.center={x:o.center.x+c.x,y:o.center.y+c.y,z:o.center.z-t.z},o=P(b({},o),{width:o.width,height:Math.abs(o.height+e),depth:Math.abs(o.depth+i)}),{newBoxParams:o}}getNewBoxBySideUpdateByPoints(t,e,i,r){var s;const c=(s=this.sideMatrix)==null?void 0:s.invert();if(!this.sideMatrix||!c){console.error("No sideMatrix");return}this.camera.zoom=1,this.camera.updateProjectionMatrix();const o=t.map(g=>new a.Vector3(g.x,g.y,g.z)).map(g=>g.applyMatrix4(c)),[d,n,l,h]=o,u=Math.max(Math.abs(d.x-l.x),Math.abs(d.x-n.x)),f=n.add(h).applyMatrix3(new a.Matrix3().set(1/2,0,0,0,1/2,0,0,0,1/2)).clone().applyMatrix3(new a.Matrix3().set(-1,0,0,0,-1,0,0,0,-1)).add(new a.Vector3(r.center.x,r.center.y,r.center.z));return{newBoxParams:P(b({},r),{center:{x:r.center.x-f.x,y:r.center.y-f.y,z:r.center.z-i},width:u,height:r.height,depth:r.depth+e,rotation:r.rotation})}}filterZAxisPoints(t){const e=t||this.scene.children.find(i=>i.uuid===this.pointsUuid);if(e){const{attributes:i}=e.geometry,{position:r}=i,s=[],{count:c}=r;for(let o=0;o<c;o++){const d=r.getZ(o);s.push(d>this.zAxisLimit?0:1)}e.geometry.setAttribute("visibility",new a.Float32BufferAttribute(s,1)),e.geometry.attributes.visibility.needsUpdate=!0}}render(){this.renderer.render(this.scene,this.camera)}}export{ot as PointCloud};
@@ -1 +1 @@
1
- import g from"lodash";import{ELineTypes as P,ELineColor as U,EToolName as _,ETextType as M}from"../../constant/tool.js";import B from"../../utils/ActionsHistory.js";import S from"../../utils/uuid.js";import v from"../../constant/keyCode.js";import L from"../../utils/MathUtils.js";import{BasicToolOperation as j}from"./basicToolOperation.js";import u from"../../utils/tool/LineToolUtils.js";import{createSmoothCurvePointsFromPointList as R,isInPolygon as V,createSmoothCurvePoints as W}from"../../utils/tool/polygonTool.js";import K from"../../utils/tool/CommonToolUtils.js";import N from"../../utils/tool/CanvasUtils.js";import F from"../../utils/tool/DrawUtils.js";import z from"../../utils/tool/StyleUtils.js";import y from"../../utils/tool/AttributeUtils.js";import $ from"./textAttributeClass.js";import J from"./Selection.js";import Y from"../../locales/index.js";import{EMessage as X}from"../../locales/constants.js";var q=Object.defineProperty,G=Object.defineProperties,Z=Object.getOwnPropertyDescriptors,O=Object.getOwnPropertySymbols,Q=Object.prototype.hasOwnProperty,tt=Object.prototype.propertyIsEnumerable,E=(d,e,t)=>e in d?q(d,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):d[e]=t,T=(d,e)=>{for(var t in e||(e={}))Q.call(e,t)&&E(d,t,e[t]);if(O)for(var t of O(e))tt.call(e,t)&&E(d,t,e[t]);return d},w=(d,e)=>G(d,Z(e)),k;(function(d){d[d.Create=0]="Create",d[d.Active=1]="Active",d[d.None=2]="None"})(k||(k={}));const p=16,C={x:0,y:20},x=3,m=5,H=2;class et extends j{constructor(e){super(e);this.drawActivatedLine=(t,i,s)=>{const n=this.isCreate?g.cloneDeep([{pointList:this.activeLine,order:this.nextOrder(),attribute:this.defaultAttribute,valid:this.isLineValid}]):g.cloneDeep(this.selectedLines),o=this.isActiveLineValid();n.forEach(r=>{if((r==null?void 0:r.pointList)&&(r.pointList=r.pointList.map(l=>Object.assign(l,{actual:{x:l.x,y:l.y}},this.coordUtils.getRenderCoord(l)))),!r.pointList)return;const h=this.getLineColorByAttribute({attribute:r.attribute,valid:r.valid});return this.selectedLines.length>0&&(this.drawLineLength(r.pointList,h),this.renderActiveArea(L.calcViewportBoundaries(r.pointList,this.isCurve,p))),this.drawLine(r.pointList,t,h,!0,!0),r.pointList[0]&&this.drawLineNumber(r.pointList[0],r.order,h,"",this.defaultAttribute,o),t&&this.isCreate&&this.arc(t,x,h),this.cursor&&!this.selectedPoint&&!s&&!this.isShift&&this.arc(this.cursor,m,h),r})},this.drawHoverPoint=t=>{if(!this.isMousedown&&t&&this.selectedID){const i=this.getPointList(this.activeLine),s=this.activeLine.find(o=>u.calcDistance(this.coordUtils.getRenderCoord(o),t)<=m);let n;!s&&this.activeLine&&(n=this.findNearestPoint(i,t)),this.hoverPointID=s?s.id:void 0,this.cursor=s||n==null?void 0:n.point}},this.updatedLine={id:"",valid:!1,order:0},this.toolName="lineTool",this.lineList=[],this.activeLine=[],this.coordsInsideActiveArea=!1,this.hoverLineSegmentIndex=-1,this.isShift=!1,this.isReference=!1,this.drawCurveLine=(t,i,s,n=!0,o=!1,r)=>{const h=R(i,p);t.save(),t.lineCap="round",t.lineJoin="round",t.strokeStyle=s.color,n&&(t.lineWidth=s.lineWidth),o&&u.setReferenceCtx(t),i.forEach(({specialEdge:l},a)=>{const c=h.splice(0,p+1);t.save(),t.beginPath(),r===a&&(t.lineWidth=4),c.forEach(({x:f,y:b},I)=>{const D=I>0?"lineTo":"moveTo";l&&u.setSpecialEdgeStyle(t),t[D](f,b)}),t.stroke(),t.restore()}),t.restore()},this.drawLine=(t,i,s,n=!1,o=!1)=>{const r=i?t.concat(i):t,h={color:s,lineWidth:o?1:this.lineStyle.lineWidth};this.isCurve?u.drawCurveLine(this.ctx,r,h,!n,this.isReference,o?this.hoverLineSegmentIndex:-1):this.drawStraightLine(r,h,o),n&&t.forEach(l=>{var a,c;const f=l.id,b=f&&[this.hoverPointID,(a=this.selectedPoint)==null?void 0:a.id].includes(f)?m:x;this.arc(l,b,s),[this.hoverPointID,(c=this.selectedPoint)==null?void 0:c.id].includes(f)||this.arc(l,H,"white")})},this.drawStraightLine=(t,i,s=!1)=>{const{ctx:n}=this;n&&(n.save(),n.lineCap="round",n.lineJoin="round",n.strokeStyle=i.color,n.lineWidth=i.lineWidth,this.isReference&&u.setReferenceCtx(n),t.forEach((o,r)=>{if(n.beginPath(),r>0){const h=t[r-1];n.save(),(h==null?void 0:h.specialEdge)&&u.setSpecialEdgeStyle(n),s&&this.hoverLineSegmentIndex+1===r&&(n.lineWidth=4),n.moveTo(h.x,h.y),n.lineTo(o.x,o.y),n.stroke(),n.restore()}}),n.restore())},this.drawLines=()=>{try{const t=g.cloneDeep(this.attributeFilteredLines);if(this.isHidden)return;t.forEach(i=>{if(!this.selection.isIdSelected(i.id)&&i.pointList){i.pointList.map(h=>Object.assign(h,{actual:{x:h.x,y:h.y}},this.coordUtils.getRenderCoord(h)));const{order:s,label:n}=i,o=s,r=i&&this.getLineColorByAttribute(i);this.drawLine(i.pointList,void 0,r,!1),this.drawLineNumber(i.pointList[0],o,r,n,i.attribute,i.valid),i.id!==this.textEditingID&&(this.drawLineTextAttribute(i.pointList[1],r,i==null?void 0:i.textAttribute),this.drawLineLength(i.pointList,r))}})}catch(t){console.error(t,"\u7EBF\u6761\u5DE5\u5177\u6570\u636E\u89E3\u6790\u9519\u8BEF"),this.lineList=[],this.clearCanvas()}},this.render=t=>{super.render(),this.drawLines(),this.drawActivatedLine(t,void 0,!1),this.renderTextAttribute(),this.renderCursorLine(this.getLineColor(this.defaultAttribute))},this.moveLineInPolygon=(t,i)=>{var s;if(!Array.isArray(this.activeLine))return!1;((s=this.activeLine)==null?void 0:s.every(o=>this.isInBasicPolygon({x:o.x+t,y:o.y+i})))&&(this.lineDragging=!0,this.moveActiveArea(t,i))},this.getSelectedLinesArea=()=>L.calcViewportBoundaries(this.selectedLines.reduce((t,i)=>(i==null?void 0:i.pointList)?t.concat(...i==null?void 0:i.pointList):t,[])),this.moveLineInRectRange=(t,i,s,n)=>{if(this.selectedLines.length===0)return;const{top:o,left:r,right:h,bottom:l}=this.getSelectedLinesArea(),a=[r,h].map(A=>g.isNumber(A)?A+t:0),c=[o,l].map(A=>g.isNumber(A)?A+i:0),f=r>=0&&h&&L.isInRange(a,s),b=o>=0&&l&&L.isInRange(c,n),I=f?t:0,D=b?i:0;this.lineDragging=!0,this.moveActiveArea(I,D)},this.onRightClick=t=>{if(this.cursor=void 0,this.isCreate){if(this.isLinePointsNotEnough())return;if(u.lineLengthSum(this.activeLine||[])<this.minLength)return this.emit("messageInfo",`${Y.getMessagesByLocale(X.MinLengthLimitErrorNotice,this.lang)}${this.minLength}`),!0;this.stopLineCreating(!0);return}const i=this.findHoverLine(this.getCoordinate(t));this.setSelectedLineID(i==null?void 0:i.id,t.ctrlKey),this.emit("contextmenu")},this.updateSelectedAttributeAfterHistoryChanged=()=>{if(this.selectedIDs.length>0){const t=this.lineList.find(s=>s.id===this.selectedIDs[0]),i=t==null?void 0:t.attribute;typeof i=="string"&&(this.defaultAttribute=i,this.updateAttribute(i),this.render())}},this.onLeftClick=t=>{const i=this.getCoordinate(t),{lineDragging:s}=this;if(this.lineDragging=!1,this.isSpaceKey)return;if(this.isNone&&t.ctrlKey){const o=this.findHoverLine(i);o&&this.setInvalidLine(o.id);return}if(this.isLinePointsExceed())return;const n=this.getNextPoint(t,i);if(this.isCreate||this.isNone){this.setCreateStatusAndAddPoint(n);return}if(this.isActive){if(s)return;if(this.isMouseCoordOutsideActiveArea()){this.setNoneStatus(!1),this.setCreateStatusAndAddPoint(n);return}if(t.shiftKey){this.updateLineSegmentSpecial(i);return}this.coordsInsideActiveArea&&t.ctrlKey&&this.setInvalidLine(this.selectedID),this.addLinePointToActiveLine()}},this.onDblclick=()=>{},this.onKeyUp=t=>{if(super.onKeyUp(t),this.isShift=!1,this.hoverLineSegmentIndex=-1,!this.selection.triggerKeyboardEvent(t,this.setLineList)){if(t.keyCode===v.Esc){this.stopLineCreating(!1);return}if(this.selectedLine){if(t.key==="Delete"){this.deleteLine();return}if(t.key==="f"){this.setInvalidLine(this.selectedID);return}if(t.key===" "){this.continueToEdit();return}}this.keyboardEventWhileLineCreating(t)}},this.onRightDblClick=t=>{super.onRightDblClick(t);const i=this.getCoordinate(t);if(this.isActive){const s=this.findHoveredPoint(i);if(s){this.deleteSelectedLinePoint(s.id);return}this.deleteSelectedLine(i)}},this.setReference=t=>{this.isReference=t},this.pointsWithinRange=t=>!(this.lowerLimitPointNum&&t<this.lowerLimitPointNum||this.upperLimitPointNum&&t>this.upperLimitPointNum),this.setLineList=t=>{const i=t.length!==this.lineListLen;this.lineList=t,i&&this.emit("updatePageNumber")},this.textChange=t=>{this.config.textConfigurable===!1||!this.selectedID||(this.updateSelectedTextAttribute(t),this.emit("selectedChange"))},this.status=2,this.isMousedown=!1,this.lineDragging=!1,this.isLineValid=!0,this.setConfig(e.config),this.prevAxis={x:0,y:0},this.textEditingID="",this.updateSelectedTextAttribute=this.updateSelectedTextAttribute.bind(this),this.getCurrentSelectedData=this.getCurrentSelectedData.bind(this),this.actionsHistory=new B,this.selection=new J(this),this.dependToolConfig={lineType:P.Line},this.historyDisabled=!1}get selectedLines(){return this.lineList.filter(e=>this.selection.isIdSelected(e.id))}get isLineSelected(){return this.selectedID&&this.activeLine}get selectedLine(){return this.lineList.find(e=>e.id===this.selectedID)}get isCreate(){return this.status===0}get isActive(){return this.selectedLines.length>0}get isNone(){return!this.isCreate&&this.selectedIDs.length===0}get isCurve(){return this.config.lineType===P.Curve}get isMultipleColor(){return this.config.lineColor===U.MultiColor}get imageSize(){return this.rotate%180==0?this.basicImgInfo:{width:this.basicImgInfo.height,height:this.basicImgInfo.width}}get lineListLen(){return this.lineList.length}get edgeAdsorptionEnabled(){return this.edgeAdsorption&&!this.isCurve&&this.lineListLen>0}get attributeConfigurable(){return this.config.attributeConfigurable}get isTextConfigurable(){return this.config.textConfigurable}get isDependPolygon(){return this.dependToolName===_.Polygon}get isDependRect(){return this.dependToolName===_.Rect}get isCurrentAttributeLocked(){return this.attributeLockList.includes(this.defaultAttribute)}get attributeFilteredLines(){return this.attributeLockList.length>0?this.lineList.filter(e=>this.attributeLockList.includes((e==null?void 0:e.attribute)||"")):this.lineList}get selectedIDs(){return this.selection.selectedIDs}get selectedID(){return this.selection.selectedID}get enableOutOfTarget(){return this.config.enableOutOfTarget||this.config.outOfTarget||this.config.drawOutsideTarget}get showOrder(){var e;return(e=this.config.showOrder)!=null?e:this.config.isShowOrder}get edgeAdsorption(){return this.config.edgeAdsorption}get attributeList(){return this.config.attributeList}get lowerLimitPointNum(){return this.config.lowerLimitPointNum}get minLength(){var e;return((e=this.config)==null?void 0:e.minLength)||0}get upperLimitPointNum(){return this.config.upperLimitPointNum}get textCheckType(){return this.config.textCheckType}get customFormat(){return this.config.customFormat}get dataList(){return this.lineList}get hasActiveLine(){return this.activeLine&&this.activeLine.length>0}get viewPortLines(){const e=N.getViewPort(this.canvas,this.currentPos,this.zoom);return this.isHidden?[]:this.attributeFilteredLines.filter(t=>{var i;return(i=t==null?void 0:t.pointList)==null?void 0:i.some(s=>N.inViewPort(s,e))})}get lineStyle(){return{lineWidth:this.style.width,color:this.getLineColor(this.defaultAttribute),opacity:this.style.opacity}}get selectedText(){var e,t;return(t=(e=this.lineList.find(i=>i.id===this.selectedID))==null?void 0:e.textAttribute)!=null?t:""}get currentPageResult(){return this.lineList}updateStatus(e,t=!1){if(e!==this.status){if(t){let i="";this.textCheckType===M.Order&&this.isTextConfigurable&&(i=y.getTextAttribute(this.lineList,this.textCheckType)),this.emit("updateText",i)}this.status=e,this.lineStatusChanged()}}isInBasicPolygon(e){var t,i;return V(e,((t=this.basicResult)==null?void 0:t.pointList)||[],(i=this.dependToolConfig)==null?void 0:i.lineType)}getPolygonPointList(){if(!this.basicResult)return[];const{pointList:e}=this.basicResult,{lineType:t}=this.dependToolConfig;return t===P.Curve?W(e.reduce((i,s)=>[...i,s.x,s.y],[]),.5,!0,20):e}getNextCoordByRenderCoord(e){return this.getNextCoordByAbsCoord(this.coordUtils.getAbsCoord(e))}getNextCoordByAbsCoord(e){var t;const i=(t=this.activeLine)==null?void 0:t.slice(-1)[0];return i?this.coordUtils.getNextCoordByDependTool(e,i):e}pointInLine(e,t,i){return e.filter(s=>s).length<2?!1:e.some((s,n)=>{if(n===0)return!1;const o=this.coordUtils.getRenderCoord(e[n-1]),r=this.coordUtils.getRenderCoord(s);return u.isInLine(t,o,r,i)})}arc(e,t=x,i){var s,n,o,r,h,l;if(this.ctx){const{x:a,y:c}=e;(s=this.ctx)==null||s.save(),(n=this.ctx)==null||n.beginPath(),this.ctx.fillStyle=i||this.lineStyle.color,(o=this.ctx)==null||o.arc(a,c,t,0,360),(r=this.ctx)==null||r.closePath(),(h=this.ctx)==null||h.fill(),(l=this.ctx)==null||l.restore()}}renderActiveArea({top:e,left:t,right:i,bottom:s}){this.ctx&&(this.ctx.save(),this.ctx.beginPath(),this.ctx.strokeStyle="#B3B8FF",this.ctx.rect(t,e,i-t,s-e),this.ctx.stroke(),this.ctx.restore())}addLinePoint(e){var t,i,s,n;this.arc(e),(t=this.activeLine)==null||t.push(w(T({},e),{id:S()})),((i=this.activeLine)==null?void 0:i.length)===1?(s=this.actionsHistory)==null||s.initRecord(this.activeLine):(n=this.actionsHistory)==null||n.pushHistory(this.activeLine),this.render()}setCreateStatusAndAddPoint(e,t=!1){this.updateStatus(0,t),this.addLinePoint(e)}isActiveLineValid(){var e;return this.selectedID?(e=this.lineList.find(t=>t.id===this.selectedID))==null?void 0:e.valid:this.isLineValid}nextOrder(){return this.lineListLen===0?1:this.lineList.slice(-1)[0].order+1}getLineColorByAttribute(e,t=!1){return z.getStrokeAndFill(this.getColor(e.attribute),e.valid,{isSelected:t}).stroke}drawLineNumber(e,t=1,i,s="",n,o=!0){var r,h,l;if((this.showOrder||this.attributeConfigurable)&&this.ctx){let a=this.showOrder?t.toString():`${s}`;if(this.attributeConfigurable){const c=n?(l=(h=(r=this.attributeList)==null?void 0:r.find(f=>f.value===n))==null?void 0:h.key)!=null?l:n:"";a=[a,`${!o&&c?"\u65E0\u6548":""}${c}`].filter(f=>f).join("_")}this.drawText(e,a,i)}}drawLineTextAttribute(e,t,i){if(e&&i)return this.drawText(e,i,t,200)}drawLineLength(e,t){var i;if(((i=this.config)==null?void 0:i.showLineLength)&&e){const s=e.reduce((o,r,h)=>h<=0||!e[h-1].actual||!r.actual?o:o+u.calcDistance(e[h-1].actual,r.actual),0),n=e[e.length-1];this.drawText(n,`l = ${s.toFixed(2)}`,t)}}drawText(e,t,i,s){var n,o;this.ctx&&((n=this.ctx)==null||n.save(),this.ctx.font="italic bold 14px SourceHanSansCN-Regular",this.ctx.fillStyle=i,this.ctx.strokeStyle=i,this.ctx.shadowColor="rgba(0, 0, 0, 0.6)",this.ctx.shadowOffsetY=2,this.ctx.shadowBlur=4,s?F.wrapText(this.canvas,t,e.x-C.x,e.y-C.y,s):this.ctx.fillText(t,e.x-C.x,e.y-C.y),(o=this.ctx)==null||o.restore())}moveActiveArea(e,t){this.selectedLines.length>0&&(this.selectedLines.forEach(i=>{var s;(s=i.pointList)==null||s.forEach(n=>Object.assign(n,{x:n.x+e,y:n.y+t}))}),this.render()),this.emit("dataUpdated",this.lineList,this.selectedIDs)}findHoveredPoint(e){if(!!this.activeLine)return this.activeLine.find(t=>{const i=this.coordUtils.getRenderCoord(t);return u.calcDistance(i,e)<=m})}findHoverLine(e){return g.cloneDeep(this.lineList).reverse().find(({pointList:i})=>{const s=i?this.getPointList(i):[],n=this.getLineWidthScope();return s.some((o,r)=>{if(r===0)return!1;const h=this.coordUtils.getRenderCoord(o),l=this.coordUtils.getRenderCoord(s[r-1]);return u.isInLine(e,h,l,n)})})}getAdsorptionPoint(e){let t,i,s;return g.cloneDeep(this.lineList).reverse().forEach(({pointList:n,id:o})=>{if(o===this.selectedID||!n||(n==null?void 0:n.length)<2)return;const r=this.findNearestPoint(n,e);if(r){if(r.minDistance===0){t=r.point;return}(i===void 0||r.minDistance<i)&&(t=r.point,i=r.minDistance)}}),s||t}findNearestPoint(e,t,i=7){let s;const n=i;for(let o=1;o<=e.length-1;o++){const r=this.coordUtils.getRenderCoord(e[o]),h=this.coordUtils.getRenderCoord(e[o-1]),{length:l,footPoint:a}=L.getFootOfPerpendicular(t,r,h),c=u.calcTwoPointDistance(r,t),f=u.calcTwoPointDistance(h,t);if(c<=i*2){s=r,i=0;break}if(f<=i*2){s=h,i=0;break}l<i&&(s=a,i=l)}return s?{point:s,minDistance:n}:void 0}getPointList(e){return this.isCurve?R(e,p):e}moveSelectedLine(e){const t=(e.x-this.prevAxis.x)/this.zoom,i=(e.y-this.prevAxis.y)/this.zoom;if(this.enableOutOfTarget){this.lineDragging=!0,this.moveActiveArea(t,i);return}if(this.isDependPolygon){this.moveLineInPolygon(t,i);return}let s=[0,this.imageSize.width],n=[0,this.imageSize.height];if(this.isDependRect){const{x:o,y:r,width:h,height:l}=this.basicResult;s=[o,o+h],n=[r,r+l]}this.moveLineInRectRange(t,i,s,n)}moveSelectPoint(e){if(!this.selectedPoint)return;const t=e.x-this.prevAxis.x,i=e.y-this.prevAxis.y,s=(this.selectedPoint?this.selectedPoint.x:0)+t/this.zoom,n=(this.selectedPoint?this.selectedPoint.y:0)+i/this.zoom,o={x:s,y:n};Object.assign(this.selectedPoint,this.getNextCoordByAbsCoord(o)),this.updateLines(),this.render()}getCoordByConfig(e,t){var i;const s=!!e.shiftKey,n=e.altKey;if(((i=this.activeLine)==null?void 0:i.length)>0&&s){const o=this.activeLine.slice(-1)[0];return u.getVHPoint(o,t,this.coordUtils.getAbsCoord(t),this.coordUtils.getRenderCoord(o))}return this.edgeAdsorptionEnabled&&!n?this.getAdsorptionPoint(t):t}getNextPoint(e,t){const i=this.getCoordByConfig(e,t)||t;return this.enableOutOfTarget?this.coordUtils.getAbsCoord(i):this.getNextCoordByRenderCoord(i)}lineHover(){this.render()}mouseMoveHandler(e){const t=this.getCoordinate(e),i=e.which===1;if(this.isCreate){this.hasActiveLine&&this.renderNextPoint(e,t);return}if(this.isNone&&(this.lineHover(),this.edgeAdsorptionEnabled&&!e.altKey)){const s=this.getAdsorptionPoint(t);s&&this.arc(s)}if(this.isActive){if(this.isMousedown&&i){if(this.selectedPoint){this.moveSelectPoint(t);return}if(this.coordsInsideActiveArea){this.moveSelectedLine(t),this.drawActivatedLine(void 0,void 0,!0);return}}this.drawHoverPoint(t),this.render()}}onMouseMove(e){if(super.onMouseMove(e)||this.forbidMouseOperation||!this.imgInfo)return;const t=this.getCoordinate(e);this.mouseMoveHandler(e),this.prevAxis=t}setActiveLine(e){this.activeLine=e?g.cloneDeep(e):void 0}historyChanged(e){if(this.historyDisabled)return;const t=`${e}Enabled`;if(this.isCreate){if(this.actionsHistory&&this.actionsHistory[t]){const i=this.actionsHistory&&this.actionsHistory[e]();this.setActiveLine(i),this.render()}return}if(this.history&&this.history[t]){const i=this.history[e](),s=i==null?void 0:i.find(n=>n.id===this.selectedID);this.lineList=i,this.selectedID&&s?this.setActiveLine(s==null?void 0:s.pointList):this.setNoneStatus(),this.render()}this.emit("dataUpdated",this.lineList)}undo(){this.historyChanged("undo"),this.updateSelectedAttributeAfterHistoryChanged()}redo(){this.historyChanged("redo"),this.updateSelectedAttributeAfterHistoryChanged()}isCoordInsideTarget(e){if(this.isDependPolygon)return this.isInBasicPolygon(e);if(this.isDependRect){const{x:t,y:i,width:s,height:n}=this.basicResult,o=[t,t+s],r=[i,i+n];return L.isInRange(e.x,o)&&L.isInRange(e.y,r)}return L.isInRange(e.x,[0,this.imageSize.width])&&L.isInRange(e.y,[0,this.imageSize.height])}getPointInsertIndex(e,t){if(e&&this.activeLine){const i=this.getPointList(this.activeLine);return this.activeLine.length===2?1:this.activeLine.findIndex((s,n)=>{if(n>0){const o=this.activeLine?this.activeLine[n-1]:void 0,r=this.isCurve?i.slice((n-1)*(p+1),n*(p+1)):[o,s];return this.pointInLine(r,e,t||this.getLineWidthScope())}return!1})}return-1}getLineWidthScope(){return this.lineStyle.lineWidth}isMouseCoordOutsideActiveArea(){return!this.coordsInsideActiveArea&&!this.selectedPoint}isLinePointsExceed(){return this.isCreate&&this.activeLine&&this.upperLimitPointNum&&~~this.upperLimitPointNum<=this.activeLine.length}isLinePointsNotEnough(){var e;return this.activeLine&&((e=this.activeLine)==null?void 0:e.length)<this.lowerLimitPointNum}updateLineSegmentSpecial(e){const t=this.getPointInsertIndex(e,2)-1;if(t>-1){const i=this.activeLine[t];i.specialEdge=!i.specialEdge,this.hoverLineSegmentIndex=-1,this.render()}}addLinePointToActiveLine(){var e;const t=this.getPointInsertIndex(this.cursor),i=this.pointsWithinRange(this.activeLine.length+1);this.cursor&&t>-1&&i&&(this.activeLine.splice(t,0,w(T({},this.coordUtils.getAbsCoord(this.cursor)),{id:S()})),this.updateLines(),(e=this.history)==null||e.pushHistory(this.lineList),this.render(),this.cursor=void 0)}isCoordOnSelectedArea(e){return this.selectedLines.some(t=>u.inArea(L.calcViewportBoundaries(t.pointList),this.coordUtils.getAbsCoord(e)))}onMouseDown(e){if(super.onMouseDown(e)||this.forbidMouseOperation||!this.imgInfo)return;const t=this.getCoordinate(e);if(this.isMousedown=!0,this.prevAxis=t,e.which===3){this.cursor=void 0;return}this.selectedPoint=this.findHoveredPoint(t),this.coordsInsideActiveArea=this.selectedLines.length>0?this.isCoordOnSelectedArea(t):!1,this.lineDragging=!1}lineHasChanged(){const e=this.lineList.find(t=>t.id===this.selectedID);return e?JSON.stringify(e.pointList)!==JSON.stringify(this.activeLine):!1}updateLines(){const e=this.lineList.find(t=>t.id===this.selectedID);e&&(e.pointList=g.cloneDeep(this.activeLine),this.updatedLine=e,this.emit("dataUpdated",this.lineList))}onMouseUp(e){const t=()=>{this.isMousedown=!1,this.hoverPointID=void 0,this.cursor=void 0,this.selectedPoint=void 0};if(this.hoverPointID=void 0,super.onMouseUp(e)||this.forbidMouseOperation||!this.imgInfo){t();return}e.which===1&&this.onLeftClick(e),e.which===3&&this.onRightClick(e),t()}isTextValid(e){return y.textAttributeValidate(this.textCheckType,this.customFormat,e)}createLineData(){const e=S(),t={pointList:g.cloneDeep(this.activeLine),id:e,valid:this.isLineValid,order:this.nextOrder()};return t.attribute=this.defaultAttribute,t}stopLineCreating(e=!0){var t,i,s,n;const o=this.selectedID?!0:!!this.isTextConfigurable;let r;if(e){if(this.selectedID){const h=this.lineList.find(l=>l.id===this.selectedID);r=this.selectedID,h&&(h.pointList=g.cloneWith(this.activeLine),g.isEqual(h.pointList,(t=this.history)==null?void 0:t.pushHistory(this.lineList))||(i=this.history)==null||i.pushHistory(this.lineList))}else if(this.isCreate&&this.activeLine&&this.activeLine.length>1){const h=this.createLineData();r=h.id,this.setLineList([...this.lineList,h]),(s=this.history)==null||s.pushHistory(this.lineList)}}o?(this.activeLine=[],this.setSelectedLineID(r,!1,!1)):this.setNoneStatus(),(n=this.actionsHistory)==null||n.empty(),this.render()}setNoneStatus(e=!0){e&&this.updateStatus(2),this.activeLine=[],this.setSelectedLineID(void 0),this.isLineValid=!0,this.cursor=void 0}setKeyDownStatus(e,t){this.isShift=t!=null?t:e.keyCode===v.Shift}continueToEdit(){var e,t;((e=this.selectedLine)==null?void 0:e.pointList)&&(this.updateStatus(0),this.cursor=void 0,this.setActiveLine(this.selectedLine.pointList),(t=this.actionsHistory)==null||t.pushHistory(this.activeLine),this.render())}setInvalidLineOnCreating(e){if(this.selectedID&&e.keyCode!==v.Ctrl||!this.isCreate)return;const t=!e.ctrlKey;this.selectedID?this.setInvalidLine(this.selectedID,t,!1):this.isLineValid=t}onKeyDown(e){if(super.onKeyDown(e),this.setKeyDownStatus(e),e.keyCode===v.Z&&!e.ctrlKey&&this.toggleIsHide(),e.keyCode===v.Shift&&this.render(),e.keyCode===v.Tab){e.preventDefault(),this.selectToNextLine(e);return}if(this.isCreate&&this.keyboardEventWhileLineCreating(e),this.config.attributeConfigurable){const t=y.getAttributeByKeycode(e.keyCode,this.config.attributeList);t!==void 0&&this.setDefaultAttribute(t)}}selectToNextLine(e){const t=K.getNextSelectedRectIDByEvent(this.viewPortLines.map(i=>{var s,n,o,r;return w(T({},i),{x:(n=(s=i.pointList[0])==null?void 0:s.x)!=null?n:0,y:(r=(o=i.pointList[0])==null?void 0:o.y)!=null?r:0})}),e,this.selectedID);t&&this.selection.setSelectedIDs(t.id)}keyboardEventWhileLineCreating(e){!this.isCreate||(e.keyCode===v.Ctrl&&this.setInvalidLineOnCreating(e),[v.Shift,v.Alt].includes(e.keyCode)&&this.renderNextPoint(e,this.prevAxis))}renderNextPoint(e,t){const i=this.coordUtils.getRenderCoord(this.getNextPoint(e,t));this.render(i)}deleteSelectedLine(e){var t;if(this.selectedLine){const i=L.calcViewportBoundaries((t=this.selectedLine)==null?void 0:t.pointList,this.isCurve,p,this.zoom);u.inArea(i,this.coordUtils.getAbsCoord(e))&&this.deleteLine()}}deleteSelectedLinePoint(e){var t;this.pointsWithinRange(this.activeLine.length-1)&&e&&(this.setActiveLine(this.activeLine.filter(s=>s.id!==e)),this.updateLines(),(t=this.history)==null||t.pushHistory(this.lineList)),this.cursor=void 0,this.render()}deleteLine(){var e;this.lineList=this.lineList.filter(t=>!this.selection.isIdSelected(t.id)),(e=this.history)==null||e.pushHistory(this.lineList),this.setNoneStatus(),this.emit("dataUpdated",this.lineList),this.render()}setInvalidLine(e,t,i=!0){var s;const n=this.lineList.find(o=>o.id===e);n&&(n.valid=t!==void 0?t:!n.valid,(s=this.history)==null||s.pushHistory(this.lineList),this.emit("dataUpdated",this.lineList),i&&this.render())}empty(){var e,t;this.lineList=[],this.setNoneStatus(),this.selectedPoint=void 0,(e=this.actionsHistory)==null||e.empty(),(t=this.history)==null||t.init(),this.emit("dataUpdated",this.lineList),this.render()}setAttribute(e){var t;this.attributeConfigurable&&(this.defaultAttribute=e,this.setLineAttribute("attribute",e),this.selectedIDs.length>0&&((t=this.history)==null||t.pushHistory(this.lineList)))}setTextAttribute(e){var t;this.isTextConfigurable&&(this.setLineAttribute("textAttribute",e),(t=this.history)==null||t.applyAttribute(this.selectedID,"textAttribute",e))}setLineAttribute(e,t){this.selectedIDs.length>0&&(this.lineList.forEach(i=>{this.selection.isIdSelected(i.id)&&(i[e]=t)}),this.render())}updateAttribute(e){this.emit("updateAttribute",e)}updateLineAttributes(e){var t;if(this.attributeConfigurable&&e){const i=(e==null?void 0:e.attribute)||"";this.defaultAttribute=i,this.updateAttribute(i)}if(this.isTextConfigurable&&e){const i=(e==null?void 0:e.textAttribute)||"";this.updateTextAttribute(i)}(t=this.history)==null||t.updateHistory(this.lineList)}lineStatusChanged(){this.emit("lineStatusChanged",{status:this.status,selectedLineID:this.selectedID})}updateTextAttribute(e){if(this.selectedID){const t=this.lineList.find(i=>i.id===this.selectedID);t&&(t.textAttribute=e)}this.emit("updateText",e)}saveData(){this.stopLineCreating(),this.setNoneStatus(),this.render()}setTextEditingID(e){this.textEditingID=e,this.render()}updateAttrWhileIDChanged(e){if(e){const t=this.lineList.find(i=>i.id===e);t&&this.setDefaultAttribute(t.attribute)}}setSelectedLineID(e,t=!1,i=!0){this.selection.setSelectedIDs(e,t),this.status=1,i&&e&&this.updateAttrWhileIDChanged(this.selectedID),this.selectedLine&&this.setActiveLine(this.selectedLine.pointList),this.selectedIDs.length===0&&this.setActiveLine([]),this.emit("dataUpdated",this.lineList,this.selectedIDs)}attributeLockListChange(e){this.attributeLockList=e,this.render()}setResult(e){this.setLineList(e),this.render()}setConfig(e){super.setConfig(e)}toggleIsHide(){this.setIsHidden(!this.isHidden),this.render()}clearCanvas(){super.clearCanvas()}clearResult(){this.setResult([]),this.setSelectedLineID(void 0),this.render()}exportData(){return[this.lineList,this.basicImgInfo]}setDefaultAttribute(e=""){var t;this.attributeConfigurable&&(this.defaultAttribute=e,this.changeStyle(this.defaultAttribute),this.setLineAttribute("attribute",e),this.selectedIDs.length>0&&((t=this.history)==null||t.pushHistory(this.lineList)),this.emit("changeAttributeSidebar"))}getCurrentSelectedData(){var e,t;const i=this.isActiveLineValid(),s=this.defaultAttribute,n=this.getColor(s),o=i?n==null?void 0:n.valid.stroke:n==null?void 0:n.invalid.stroke,r=(t=(e=this.lineList.find(h=>h.id===this.selectedID))==null?void 0:e.textAttribute)!=null?t:"";return{color:o,textAttribute:r}}renderTextAttribute(){var e,t,i,s;if(!this.ctx||!this.selectedLine||this.activeLine&&((e=this.activeLine)==null?void 0:e.length)<2)return;const n=this.isActiveLineValid(),o=this.defaultAttribute,{x:r,y:h}=this.selectedLine.pointList[1],l=this.coordUtils.getRenderCoord({x:r,y:h}),a=this.getColor(o),c=n?a==null?void 0:a.valid.stroke:a==null?void 0:a.invalid.stroke,f=(i=(t=this.lineList.find(b=>b.id===this.selectedID))==null?void 0:t.textAttribute)!=null?i:"";this._textAttributeInstance||(this._textAttributeInstance=new $({container:this.container,icon:this.getTextIconSvg(o),color:c,getCurrentSelectedData:this.getCurrentSelectedData,updateSelectedTextAttribute:this.updateSelectedTextAttribute})),this._textAttributeInstance&&!((s=this._textAttributeInstance)==null?void 0:s.isExit)&&this._textAttributeInstance.appendToContainer(),this._textAttributeInstance.update(`${f}`,{left:l.x,top:l.y,color:c}),this._textAttributeInstance.updateIcon(this.getTextIconSvg(o))}getTextIconSvg(e=""){return y.getTextIconSvg(e,this.config.attributeList,this.config.attributeConfigurable,this.baseIcon)}updateSelectedTextAttribute(e){if(this._textAttributeInstance&&e&&this.selectedID){let t=e;!y.textAttributeValidate(this.config.textCheckType,"",t)&&(this.emit("messageError",y.getErrorNotice(this.config.textCheckType,this.lang)),t=""),this.setTextAttribute(t),this.emit("updateTextAttribute"),this.render()}}}export{H as INNER_POINT_RADIUS,C as LINE_ORDER_OFFSET,m as POINT_ACTIVE_RADIUS,x as POINT_RADIUS,p as SEGMENT_NUMBER,et as default};
1
+ import g from"lodash";import{ELineTypes as P,ELineColor as U,EToolName as _,ETextType as M}from"../../constant/tool.js";import B from"../../utils/ActionsHistory.js";import S from"../../utils/uuid.js";import L from"../../constant/keyCode.js";import v from"../../utils/MathUtils.js";import{BasicToolOperation as j}from"./basicToolOperation.js";import u from"../../utils/tool/LineToolUtils.js";import{createSmoothCurvePointsFromPointList as R,isInPolygon as V,createSmoothCurvePoints as W}from"../../utils/tool/polygonTool.js";import K from"../../utils/tool/CommonToolUtils.js";import N from"../../utils/tool/CanvasUtils.js";import F from"../../utils/tool/DrawUtils.js";import z from"../../utils/tool/StyleUtils.js";import y from"../../utils/tool/AttributeUtils.js";import $ from"./textAttributeClass.js";import J from"./Selection.js";import Y from"../../locales/index.js";import{EMessage as X}from"../../locales/constants.js";var q=Object.defineProperty,G=Object.defineProperties,Z=Object.getOwnPropertyDescriptors,O=Object.getOwnPropertySymbols,Q=Object.prototype.hasOwnProperty,tt=Object.prototype.propertyIsEnumerable,E=(d,e,t)=>e in d?q(d,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):d[e]=t,T=(d,e)=>{for(var t in e||(e={}))Q.call(e,t)&&E(d,t,e[t]);if(O)for(var t of O(e))tt.call(e,t)&&E(d,t,e[t]);return d},w=(d,e)=>G(d,Z(e)),k;(function(d){d[d.Create=0]="Create",d[d.Active=1]="Active",d[d.None=2]="None"})(k||(k={}));const p=16,C={x:0,y:20},x=3,m=5,H=2;class et extends j{constructor(e){super(e);this.drawActivatedLine=(t,i,s)=>{const n=this.isCreate?g.cloneDeep([{pointList:this.activeLine,order:this.nextOrder(),attribute:this.defaultAttribute,valid:this.isLineValid}]):g.cloneDeep(this.selectedLines),o=this.isActiveLineValid();n.forEach(r=>{if((r==null?void 0:r.pointList)&&(r.pointList=r.pointList.map(l=>Object.assign(l,{actual:{x:l.x,y:l.y}},this.coordUtils.getRenderCoord(l)))),!r.pointList)return;const h=this.getLineColorByAttribute({attribute:r.attribute,valid:r.valid});return this.selectedLines.length>0&&(this.drawLineLength(r.pointList,h),this.renderActiveArea(v.calcViewportBoundaries(r.pointList,this.isCurve,p))),this.drawLine(r.pointList,t,h,!0,!0),r.pointList[0]&&this.drawLineNumber(r.pointList[0],r.order,h,"",this.defaultAttribute,o),t&&this.isCreate&&this.arc(t,x,h),this.cursor&&!this.selectedPoint&&!s&&!this.isShift&&this.arc(this.cursor,m,h),r})},this.drawHoverPoint=t=>{if(!this.isMousedown&&t&&this.selectedID){const i=this.getPointList(this.activeLine),s=this.activeLine.find(o=>u.calcDistance(this.coordUtils.getRenderCoord(o),t)<=m);let n;!s&&this.activeLine&&(n=this.findNearestPoint(i,t)),this.hoverPointID=s?s.id:void 0,this.cursor=s||n==null?void 0:n.point}},this.updatedLine={id:"",valid:!1,order:0},this.toolName="lineTool",this.lineList=[],this.activeLine=[],this.coordsInsideActiveArea=!1,this.hoverLineSegmentIndex=-1,this.isShift=!1,this.isReference=!1,this.drawCurveLine=(t,i,s,n=!0,o=!1,r)=>{const h=R(i,p);t.save(),t.lineCap="round",t.lineJoin="round",t.strokeStyle=s.color,n&&(t.lineWidth=s.lineWidth),o&&u.setReferenceCtx(t),i.forEach(({specialEdge:l},a)=>{const c=h.splice(0,p+1);t.save(),t.beginPath(),r===a&&(t.lineWidth=4),c.forEach(({x:f,y:b},I)=>{const D=I>0?"lineTo":"moveTo";l&&u.setSpecialEdgeStyle(t),t[D](f,b)}),t.stroke(),t.restore()}),t.restore()},this.drawLine=(t,i,s,n=!1,o=!1)=>{const r=i?t.concat(i):t,h={color:s,lineWidth:o?1:this.lineStyle.lineWidth};this.isCurve?u.drawCurveLine(this.ctx,r,h,!n,this.isReference,o?this.hoverLineSegmentIndex:-1):this.drawStraightLine(r,h,o),n&&t.forEach(l=>{var a,c;const f=l.id,b=f&&[this.hoverPointID,(a=this.selectedPoint)==null?void 0:a.id].includes(f)?m:x;this.arc(l,b,s),[this.hoverPointID,(c=this.selectedPoint)==null?void 0:c.id].includes(f)||this.arc(l,H,"white")})},this.drawStraightLine=(t,i,s=!1)=>{const{ctx:n}=this;n&&(n.save(),n.lineCap="round",n.lineJoin="round",n.strokeStyle=i.color,n.lineWidth=i.lineWidth,this.isReference&&u.setReferenceCtx(n),t.forEach((o,r)=>{if(n.beginPath(),r>0){const h=t[r-1];n.save(),(h==null?void 0:h.specialEdge)&&u.setSpecialEdgeStyle(n),s&&this.hoverLineSegmentIndex+1===r&&(n.lineWidth=4),n.moveTo(h.x,h.y),n.lineTo(o.x,o.y),n.stroke(),n.restore()}}),n.restore())},this.drawLines=()=>{try{const t=g.cloneDeep(this.attributeFilteredLines);if(this.isHidden)return;t.forEach(i=>{if(!this.selection.isIdSelected(i.id)&&i.pointList){i.pointList.map(h=>Object.assign(h,{actual:{x:h.x,y:h.y}},this.coordUtils.getRenderCoord(h)));const{order:s,label:n}=i,o=s,r=i&&this.getLineColorByAttribute(i);this.drawLine(i.pointList,void 0,r,!1),this.drawLineNumber(i.pointList[0],o,r,n,i.attribute,i.valid),i.id!==this.textEditingID&&(this.drawLineTextAttribute(i.pointList[1],r,i==null?void 0:i.textAttribute),this.drawLineLength(i.pointList,r))}})}catch(t){console.error(t,"\u7EBF\u6761\u5DE5\u5177\u6570\u636E\u89E3\u6790\u9519\u8BEF"),this.lineList=[],this.clearCanvas()}},this.render=t=>{super.render(),this.drawLines(),this.drawActivatedLine(t,void 0,!1),this.renderTextAttribute(),this.renderCursorLine(this.getLineColor(this.defaultAttribute))},this.moveLineInPolygon=(t,i)=>{var s;if(!Array.isArray(this.activeLine))return!1;((s=this.activeLine)==null?void 0:s.every(o=>this.isInBasicPolygon({x:o.x+t,y:o.y+i})))&&(this.lineDragging=!0,this.moveActiveArea(t,i))},this.getSelectedLinesArea=()=>v.calcViewportBoundaries(this.selectedLines.reduce((t,i)=>(i==null?void 0:i.pointList)?t.concat(...i==null?void 0:i.pointList):t,[])),this.moveLineInRectRange=(t,i,s,n)=>{if(this.selectedLines.length===0)return;const{top:o,left:r,right:h,bottom:l}=this.getSelectedLinesArea(),a=[r,h].map(A=>g.isNumber(A)?A+t:0),c=[o,l].map(A=>g.isNumber(A)?A+i:0),f=r>=0&&h&&v.isInRange(a,s),b=o>=0&&l&&v.isInRange(c,n),I=f?t:0,D=b?i:0;this.lineDragging=!0,this.moveActiveArea(I,D)},this.onRightClick=t=>{if(this.cursor=void 0,this.isCreate){if(this.isLinePointsNotEnough())return;if(u.lineLengthSum(this.activeLine||[])<this.minLength)return this.emit("messageInfo",`${Y.getMessagesByLocale(X.MinLengthLimitErrorNotice,this.lang)}${this.minLength}`),!0;this.stopLineCreating(!0);return}const i=this.findHoverLine(this.getCoordinate(t));this.setSelectedLineID(i==null?void 0:i.id,t.ctrlKey),this.emit("contextmenu")},this.updateSelectedAttributeAfterHistoryChanged=()=>{if(this.selectedIDs.length>0){const t=this.lineList.find(s=>s.id===this.selectedIDs[0]),i=t==null?void 0:t.attribute;typeof i=="string"&&(this.defaultAttribute=i,this.updateAttribute(i),this.render())}},this.onLeftClick=t=>{const i=this.getCoordinate(t),{lineDragging:s}=this;if(this.lineDragging=!1,this.isSpaceKey)return;if(this.isNone&&t.ctrlKey){const o=this.findHoverLine(i);o&&this.setInvalidLine(o.id);return}if(this.isLinePointsExceed())return;const n=this.getNextPoint(t,i);if(this.isCreate||this.isNone){this.setCreateStatusAndAddPoint(n);return}if(this.isActive){if(s)return;if(this.isMouseCoordOutsideActiveArea()){this.setNoneStatus(!1),this.setCreateStatusAndAddPoint(n);return}if(t.shiftKey){this.updateLineSegmentSpecial(i);return}this.coordsInsideActiveArea&&t.ctrlKey&&this.setInvalidLine(this.selectedID),this.addLinePointToActiveLine()}},this.onDblclick=()=>{},this.onKeyUp=t=>{if(super.onKeyUp(t),this.isShift=!1,this.hoverLineSegmentIndex=-1,!this.selection.triggerKeyboardEvent(t,this.setLineList)){if(t.keyCode===L.Esc){this.stopLineCreating(!1);return}if(this.selectedLine){if(t.key==="Delete"){this.deleteLine();return}if(t.key==="f"){this.setInvalidLine(this.selectedID);return}if(t.key===" "){this.continueToEdit();return}}this.keyboardEventWhileLineCreating(t)}},this.onRightDblClick=t=>{super.onRightDblClick(t);const i=this.getCoordinate(t);if(this.isActive){const s=this.findHoveredPoint(i);if(s){this.deleteSelectedLinePoint(s.id);return}this.deleteSelectedLine(i)}},this.setReference=t=>{this.isReference=t},this.pointsWithinRange=t=>!(this.lowerLimitPointNum&&t<this.lowerLimitPointNum||this.upperLimitPointNum&&t>this.upperLimitPointNum),this.setLineList=t=>{const i=t.length!==this.lineListLen;this.lineList=t,i&&this.emit("updatePageNumber")},this.textChange=t=>{this.config.textConfigurable===!1||!this.selectedID||(this.updateSelectedTextAttribute(t),this.emit("selectedChange"))},this.status=2,this.isMousedown=!1,this.lineDragging=!1,this.isLineValid=!0,this.setConfig(e.config),this.prevAxis={x:0,y:0},this.textEditingID="",this.updateSelectedTextAttribute=this.updateSelectedTextAttribute.bind(this),this.getCurrentSelectedData=this.getCurrentSelectedData.bind(this),this.actionsHistory=new B,this.selection=new J(this),this.dependToolConfig={lineType:P.Line},this.historyDisabled=!1}get selectedLines(){return this.lineList.filter(e=>this.selection.isIdSelected(e.id))}get isLineSelected(){return this.selectedID&&this.activeLine}get selectedLine(){return this.lineList.find(e=>e.id===this.selectedID)}get isCreate(){return this.status===0}get isActive(){return this.selectedLines.length>0}get isNone(){return!this.isCreate&&this.selectedIDs.length===0}get isCurve(){return this.config.lineType===P.Curve}get isMultipleColor(){return this.config.lineColor===U.MultiColor}get imageSize(){return this.rotate%180==0?this.basicImgInfo:{width:this.basicImgInfo.height,height:this.basicImgInfo.width}}get lineListLen(){return this.lineList.length}get edgeAdsorptionEnabled(){return this.edgeAdsorption&&!this.isCurve&&this.lineListLen>0}get attributeConfigurable(){return this.config.attributeConfigurable}get isTextConfigurable(){return this.config.textConfigurable}get isDependPolygon(){return this.dependToolName===_.Polygon}get isDependRect(){return this.dependToolName===_.Rect}get isCurrentAttributeLocked(){return this.attributeLockList.includes(this.defaultAttribute)}get attributeFilteredLines(){return this.attributeLockList.length>0?this.lineList.filter(e=>this.attributeLockList.includes((e==null?void 0:e.attribute)||"")):this.lineList}get selectedIDs(){return this.selection.selectedIDs}get selectedID(){return this.selection.selectedID}get enableOutOfTarget(){return this.config.enableOutOfTarget||this.config.outOfTarget||this.config.drawOutsideTarget}get showOrder(){var e;return(e=this.config.showOrder)!=null?e:this.config.isShowOrder}get edgeAdsorption(){return this.config.edgeAdsorption}get attributeList(){return this.config.attributeList}get lowerLimitPointNum(){return this.config.lowerLimitPointNum}get minLength(){var e;return((e=this.config)==null?void 0:e.minLength)||0}get upperLimitPointNum(){return this.config.upperLimitPointNum}get textCheckType(){return this.config.textCheckType}get customFormat(){return this.config.customFormat}get dataList(){return this.lineList}get hasActiveLine(){return this.activeLine&&this.activeLine.length>0}get viewPortLines(){const e=N.getViewPort(this.canvas,this.currentPos,this.zoom);return this.isHidden?[]:this.attributeFilteredLines.filter(t=>{var i;return(i=t==null?void 0:t.pointList)==null?void 0:i.some(s=>N.inViewPort(s,e))})}get lineStyle(){return{lineWidth:this.style.width,color:this.getLineColor(this.defaultAttribute),opacity:this.style.opacity}}get selectedText(){var e,t;return(t=(e=this.lineList.find(i=>i.id===this.selectedID))==null?void 0:e.textAttribute)!=null?t:""}get currentPageResult(){return this.lineList}updateStatus(e,t=!1){if(e!==this.status){if(t){let i="";this.textCheckType===M.Order&&this.isTextConfigurable&&(i=y.getTextAttribute(this.lineList,this.textCheckType)),this.emit("updateText",i)}this.status=e,this.lineStatusChanged()}}isInBasicPolygon(e){var t,i;return V(e,((t=this.basicResult)==null?void 0:t.pointList)||[],(i=this.dependToolConfig)==null?void 0:i.lineType)}getPolygonPointList(){if(!this.basicResult)return[];const{pointList:e}=this.basicResult,{lineType:t}=this.dependToolConfig;return t===P.Curve?W(e.reduce((i,s)=>[...i,s.x,s.y],[]),.5,!0,20):e}getNextCoordByRenderCoord(e){return this.getNextCoordByAbsCoord(this.coordUtils.getAbsCoord(e))}getNextCoordByAbsCoord(e){var t;const i=(t=this.activeLine)==null?void 0:t.slice(-1)[0];return i?this.coordUtils.getNextCoordByDependTool(e,i):e}pointInLine(e,t,i){return e.filter(s=>s).length<2?!1:e.some((s,n)=>{if(n===0)return!1;const o=this.coordUtils.getRenderCoord(e[n-1]),r=this.coordUtils.getRenderCoord(s);return u.isInLine(t,o,r,i)})}arc(e,t=x,i){var s,n,o,r,h,l;if(this.ctx){const{x:a,y:c}=e;(s=this.ctx)==null||s.save(),(n=this.ctx)==null||n.beginPath(),this.ctx.fillStyle=i||this.lineStyle.color,(o=this.ctx)==null||o.arc(a,c,t,0,360),(r=this.ctx)==null||r.closePath(),(h=this.ctx)==null||h.fill(),(l=this.ctx)==null||l.restore()}}renderActiveArea({top:e,left:t,right:i,bottom:s}){this.ctx&&(this.ctx.save(),this.ctx.beginPath(),this.ctx.strokeStyle="#B3B8FF",this.ctx.rect(t,e,i-t,s-e),this.ctx.stroke(),this.ctx.restore())}addLinePoint(e){var t,i,s,n;this.arc(e),(t=this.activeLine)==null||t.push(w(T({},e),{id:S()})),((i=this.activeLine)==null?void 0:i.length)===1?(s=this.actionsHistory)==null||s.initRecord(this.activeLine):(n=this.actionsHistory)==null||n.pushHistory(this.activeLine),this.render()}setCreateStatusAndAddPoint(e,t=!1){this.updateStatus(0,t),this.addLinePoint(e)}isActiveLineValid(){var e;return this.selectedID?(e=this.lineList.find(t=>t.id===this.selectedID))==null?void 0:e.valid:this.isLineValid}nextOrder(){return this.lineListLen===0?1:this.lineList.slice(-1)[0].order+1}getLineColorByAttribute(e,t=!1){return z.getStrokeAndFill(this.getColor(e.attribute),e.valid,{isSelected:t}).stroke}drawLineNumber(e,t=1,i,s="",n,o=!0){var r,h,l;if((this.showOrder||this.attributeConfigurable)&&this.ctx){let a=this.showOrder?t.toString():`${s}`;if(this.attributeConfigurable){const c=n?(l=(h=(r=this.attributeList)==null?void 0:r.find(f=>f.value===n))==null?void 0:h.key)!=null?l:n:"";a=[a,`${!o&&c?"\u65E0\u6548":""}${c}`].filter(f=>f).join("_")}this.drawText(e,a,i)}}drawLineTextAttribute(e,t,i){if(e&&i)return this.drawText(e,i,t,200)}drawLineLength(e,t){var i;if(((i=this.config)==null?void 0:i.showLineLength)&&e){const s=e.reduce((o,r,h)=>h<=0||!e[h-1].actual||!r.actual?o:o+u.calcDistance(e[h-1].actual,r.actual),0),n=e[e.length-1];this.drawText(n,`l = ${s.toFixed(2)}`,t)}}drawText(e,t,i,s){var n,o;this.ctx&&((n=this.ctx)==null||n.save(),this.ctx.font="italic bold 14px SourceHanSansCN-Regular",this.ctx.fillStyle=i,this.ctx.strokeStyle=i,this.ctx.shadowColor="rgba(0, 0, 0, 0.6)",this.ctx.shadowOffsetY=2,this.ctx.shadowBlur=4,s?F.wrapText(this.canvas,t,e.x-C.x,e.y-C.y,s):this.ctx.fillText(t,e.x-C.x,e.y-C.y),(o=this.ctx)==null||o.restore())}moveActiveArea(e,t){this.selectedLines.length>0&&(this.selectedLines.forEach(i=>{var s;(s=i.pointList)==null||s.forEach(n=>Object.assign(n,{x:n.x+e,y:n.y+t}))}),this.render()),this.emit("dataUpdated",this.lineList,this.selectedIDs)}findHoveredPoint(e){if(!!this.activeLine)return this.activeLine.find(t=>{const i=this.coordUtils.getRenderCoord(t);return u.calcDistance(i,e)<=m})}findHoverLine(e){return g.cloneDeep(this.lineList).reverse().find(({pointList:i})=>{const s=i?this.getPointList(i):[],n=this.getLineWidthScope();return s.some((o,r)=>{if(r===0)return!1;const h=this.coordUtils.getRenderCoord(o),l=this.coordUtils.getRenderCoord(s[r-1]);return u.isInLine(e,h,l,n)})})}getAdsorptionPoint(e){let t,i,s;return g.cloneDeep(this.lineList).reverse().forEach(({pointList:n,id:o})=>{if(o===this.selectedID||!n||(n==null?void 0:n.length)<2)return;const r=this.findNearestPoint(n,e);if(r){if(r.minDistance===0){t=r.point;return}(i===void 0||r.minDistance<i)&&(t=r.point,i=r.minDistance)}}),s||t}findNearestPoint(e,t,i=7){let s;const n=i;for(let o=1;o<=e.length-1;o++){const r=this.coordUtils.getRenderCoord(e[o]),h=this.coordUtils.getRenderCoord(e[o-1]),{length:l,footPoint:a}=v.getFootOfPerpendicular(t,r,h),c=u.calcTwoPointDistance(r,t),f=u.calcTwoPointDistance(h,t);if(c<=i*2){s=r,i=0;break}if(f<=i*2){s=h,i=0;break}l<i&&(s=a,i=l)}return s?{point:s,minDistance:n}:void 0}getPointList(e){return this.isCurve?R(e,p):e}moveSelectedLine(e){const t=(e.x-this.prevAxis.x)/this.zoom,i=(e.y-this.prevAxis.y)/this.zoom;if(this.enableOutOfTarget){this.lineDragging=!0,this.moveActiveArea(t,i);return}if(this.isDependPolygon){this.moveLineInPolygon(t,i);return}let s=[0,this.imageSize.width],n=[0,this.imageSize.height];if(this.isDependRect){const{x:o,y:r,width:h,height:l}=this.basicResult;s=[o,o+h],n=[r,r+l]}this.moveLineInRectRange(t,i,s,n)}moveSelectPoint(e){if(!this.selectedPoint)return;const t=e.x-this.prevAxis.x,i=e.y-this.prevAxis.y,s=(this.selectedPoint?this.selectedPoint.x:0)+t/this.zoom,n=(this.selectedPoint?this.selectedPoint.y:0)+i/this.zoom,o={x:s,y:n};Object.assign(this.selectedPoint,this.getNextCoordByAbsCoord(o)),this.updateLines(),this.render()}getCoordByConfig(e,t){var i;const s=!!e.shiftKey,n=e.altKey;if(((i=this.activeLine)==null?void 0:i.length)>0&&s){const o=this.activeLine.slice(-1)[0];return u.getVHPoint(o,t,this.coordUtils.getAbsCoord(t),this.coordUtils.getRenderCoord(o))}return this.edgeAdsorptionEnabled&&!n?this.getAdsorptionPoint(t):t}getNextPoint(e,t){const i=this.getCoordByConfig(e,t)||t;return this.enableOutOfTarget?this.coordUtils.getAbsCoord(i):this.getNextCoordByRenderCoord(i)}lineHover(){this.render()}mouseMoveHandler(e){const t=this.getCoordinate(e),i=e.which===1;if(this.isCreate){this.hasActiveLine&&this.renderNextPoint(e,t);return}if(this.isNone&&(this.lineHover(),this.edgeAdsorptionEnabled&&!e.altKey)){const s=this.getAdsorptionPoint(t);s&&this.arc(s)}if(this.isActive){if(this.isMousedown&&i){if(this.selectedPoint){this.moveSelectPoint(t);return}if(this.coordsInsideActiveArea){this.moveSelectedLine(t),this.drawActivatedLine(void 0,void 0,!0);return}}this.drawHoverPoint(t),this.render()}}onMouseMove(e){if(super.onMouseMove(e)||this.forbidMouseOperation||!this.imgInfo)return;const t=this.getCoordinate(e);this.mouseMoveHandler(e),this.prevAxis=t}setActiveLine(e){this.activeLine=e?g.cloneDeep(e):void 0}historyChanged(e){if(this.historyDisabled)return;const t=`${e}Enabled`;if(this.isCreate){if(this.actionsHistory&&this.actionsHistory[t]){const i=this.actionsHistory&&this.actionsHistory[e]();this.setActiveLine(i),this.render()}return}if(this.history&&this.history[t]){const i=this.history[e](),s=i==null?void 0:i.find(n=>n.id===this.selectedID);this.lineList=i,this.selectedID&&s?this.setActiveLine(s==null?void 0:s.pointList):this.setNoneStatus(),this.render()}this.emit("dataUpdated",this.lineList)}undo(){this.historyChanged("undo"),this.updateSelectedAttributeAfterHistoryChanged()}redo(){this.historyChanged("redo"),this.updateSelectedAttributeAfterHistoryChanged()}isCoordInsideTarget(e){if(this.isDependPolygon)return this.isInBasicPolygon(e);if(this.isDependRect){const{x:t,y:i,width:s,height:n}=this.basicResult,o=[t,t+s],r=[i,i+n];return v.isInRange(e.x,o)&&v.isInRange(e.y,r)}return v.isInRange(e.x,[0,this.imageSize.width])&&v.isInRange(e.y,[0,this.imageSize.height])}getPointInsertIndex(e,t){if(e&&this.activeLine){const i=this.getPointList(this.activeLine);return this.activeLine.length===2?1:this.activeLine.findIndex((s,n)=>{if(n>0){const o=this.activeLine?this.activeLine[n-1]:void 0,r=this.isCurve?i.slice((n-1)*(p+1),n*(p+1)):[o,s];return this.pointInLine(r,e,t||this.getLineWidthScope())}return!1})}return-1}getLineWidthScope(){return this.lineStyle.lineWidth}isMouseCoordOutsideActiveArea(){return!this.coordsInsideActiveArea&&!this.selectedPoint}isLinePointsExceed(){return this.isCreate&&this.activeLine&&this.upperLimitPointNum&&~~this.upperLimitPointNum<=this.activeLine.length}isLinePointsNotEnough(){var e;return this.activeLine&&((e=this.activeLine)==null?void 0:e.length)<this.lowerLimitPointNum}updateLineSegmentSpecial(e){const t=this.getPointInsertIndex(e,2)-1;if(t>-1){const i=this.activeLine[t];i.specialEdge=!i.specialEdge,this.hoverLineSegmentIndex=-1,this.render()}}addLinePointToActiveLine(){var e;const t=this.getPointInsertIndex(this.cursor),i=this.pointsWithinRange(this.activeLine.length+1);this.cursor&&t>-1&&i&&(this.activeLine.splice(t,0,w(T({},this.coordUtils.getAbsCoord(this.cursor)),{id:S()})),this.updateLines(),(e=this.history)==null||e.pushHistory(this.lineList),this.render(),this.cursor=void 0)}isCoordOnSelectedArea(e){return this.selectedLines.some(t=>u.inArea(v.calcViewportBoundaries(t.pointList),this.coordUtils.getAbsCoord(e)))}onMouseDown(e){if(super.onMouseDown(e)||this.forbidMouseOperation||!this.imgInfo)return;const t=this.getCoordinate(e);if(this.isMousedown=!0,this.prevAxis=t,e.which===3){this.cursor=void 0;return}this.selectedPoint=this.findHoveredPoint(t),this.coordsInsideActiveArea=this.selectedLines.length>0?this.isCoordOnSelectedArea(t):!1,this.lineDragging=!1}lineHasChanged(){const e=this.lineList.find(t=>t.id===this.selectedID);return e?JSON.stringify(e.pointList)!==JSON.stringify(this.activeLine):!1}updateLines(){const e=this.lineList.find(t=>t.id===this.selectedID);e&&(e.pointList=g.cloneDeep(this.activeLine),this.updatedLine=e,this.emit("dataUpdated",this.lineList))}onMouseUp(e){const t=()=>{this.isMousedown=!1,this.hoverPointID=void 0,this.cursor=void 0,this.selectedPoint=void 0};if(this.hoverPointID=void 0,super.onMouseUp(e)||this.forbidMouseOperation||!this.imgInfo){t();return}e.which===1&&this.onLeftClick(e),e.which===3&&this.onRightClick(e),t()}isTextValid(e){return y.textAttributeValidate(this.textCheckType,this.customFormat,e)}createLineData(){const e=S(),t={pointList:g.cloneDeep(this.activeLine),id:e,valid:this.isLineValid,order:this.nextOrder()};return t.attribute=this.defaultAttribute,t}stopLineCreating(e=!0){var t,i,s,n;const o=this.selectedID?!0:!!this.isTextConfigurable;let r;if(e){if(this.selectedID){const h=this.lineList.find(l=>l.id===this.selectedID);r=this.selectedID,h&&(h.pointList=g.cloneWith(this.activeLine),g.isEqual(h.pointList,(t=this.history)==null?void 0:t.pushHistory(this.lineList))||(i=this.history)==null||i.pushHistory(this.lineList))}else if(this.isCreate&&this.activeLine&&this.activeLine.length>1){const h=this.createLineData();r=h.id,this.setLineList([...this.lineList,h]),(s=this.history)==null||s.pushHistory(this.lineList)}}o?(this.activeLine=[],this.setSelectedLineID(r,!1,!1)):this.setNoneStatus(),(n=this.actionsHistory)==null||n.empty(),this.render()}setNoneStatus(e=!0){e&&this.updateStatus(2),this.activeLine=[],this.setSelectedLineID(void 0),this.isLineValid=!0,this.cursor=void 0}setKeyDownStatus(e,t){this.isShift=t!=null?t:e.keyCode===L.Shift}continueToEdit(){var e,t;((e=this.selectedLine)==null?void 0:e.pointList)&&(this.updateStatus(0),this.cursor=void 0,this.setActiveLine(this.selectedLine.pointList),(t=this.actionsHistory)==null||t.pushHistory(this.activeLine),this.render())}setInvalidLineOnCreating(e){if(this.selectedID&&e.keyCode!==L.Ctrl||!this.isCreate)return;const t=!e.ctrlKey;this.selectedID?this.setInvalidLine(this.selectedID,t,!1):this.isLineValid=t}onKeyDown(e){if(super.onKeyDown(e),this.setKeyDownStatus(e),e.keyCode===L.Z&&!e.ctrlKey&&this.toggleIsHide(),e.keyCode===L.Shift&&this.render(),e.keyCode===L.Tab){e.preventDefault(),this.selectToNextLine(e);return}if(this.isCreate&&this.keyboardEventWhileLineCreating(e),this.config.attributeConfigurable){const t=y.getAttributeByKeycode(e.keyCode,this.config.attributeList);t!==void 0&&this.setDefaultAttribute(t)}}selectToNextLine(e){const t=K.getNextSelectedRectIDByEvent(this.viewPortLines.map(i=>{var s,n,o,r;return w(T({},i),{x:(n=(s=i.pointList[0])==null?void 0:s.x)!=null?n:0,y:(r=(o=i.pointList[0])==null?void 0:o.y)!=null?r:0})}),e,this.selectedID);t&&this.selection.setSelectedIDs(t.id)}keyboardEventWhileLineCreating(e){!this.isCreate||(e.keyCode===L.Ctrl&&this.setInvalidLineOnCreating(e),[L.Shift,L.Alt].includes(e.keyCode)&&this.renderNextPoint(e,this.prevAxis))}renderNextPoint(e,t){const i=this.coordUtils.getRenderCoord(this.getNextPoint(e,t));this.render(i)}deleteSelectedLine(e){var t;if(this.selectedLine){const i=v.calcViewportBoundaries((t=this.selectedLine)==null?void 0:t.pointList,this.isCurve,p,this.zoom);u.inArea(i,this.coordUtils.getAbsCoord(e))&&this.deleteLine()}}deleteSelectedLinePoint(e){var t;this.pointsWithinRange(this.activeLine.length-1)&&e&&(this.setActiveLine(this.activeLine.filter(s=>s.id!==e)),this.updateLines(),(t=this.history)==null||t.pushHistory(this.lineList)),this.cursor=void 0,this.render()}deleteLine(){var e;this.lineList=this.lineList.filter(t=>!this.selection.isIdSelected(t.id)),(e=this.history)==null||e.pushHistory(this.lineList),this.setNoneStatus(),this.emit("dataUpdated",this.lineList),this.render()}setInvalidLine(e,t,i=!0){var s;const n=this.lineList.find(o=>o.id===e);n&&(n.valid=t!==void 0?t:!n.valid,(s=this.history)==null||s.pushHistory(this.lineList),this.emit("dataUpdated",this.lineList),i&&this.render())}empty(){var e,t;this.lineList=[],this.setNoneStatus(),this.selectedPoint=void 0,(e=this.actionsHistory)==null||e.empty(),(t=this.history)==null||t.init(),this.emit("dataUpdated",this.lineList),this.render()}setAttribute(e){var t;this.attributeConfigurable&&(this.defaultAttribute=e,this.setLineAttribute("attribute",e),this.selectedIDs.length>0&&((t=this.history)==null||t.pushHistory(this.lineList)))}setTextAttribute(e){var t;this.isTextConfigurable&&(this.setLineAttribute("textAttribute",e),(t=this.history)==null||t.applyAttribute(this.selectedID,"textAttribute",e))}setLineAttribute(e,t){this.selectedIDs.length>0&&(this.lineList.forEach(i=>{this.selection.isIdSelected(i.id)&&(i[e]=t)}),this.render())}updateAttribute(e){this.emit("updateAttribute",e)}updateLineAttributes(e){var t;if(this.attributeConfigurable&&e){const i=(e==null?void 0:e.attribute)||"";this.defaultAttribute=i,this.updateAttribute(i)}if(this.isTextConfigurable&&e){const i=(e==null?void 0:e.textAttribute)||"";this.updateTextAttribute(i)}(t=this.history)==null||t.updateHistory(this.lineList)}lineStatusChanged(){this.emit("lineStatusChanged",{status:this.status,selectedLineID:this.selectedID})}updateTextAttribute(e){if(this.selectedID){const t=this.lineList.find(i=>i.id===this.selectedID);t&&(t.textAttribute=e)}this.emit("updateText",e)}saveData(){this.stopLineCreating(),this.setNoneStatus(),this.render()}setTextEditingID(e){this.textEditingID=e,this.render()}updateAttrWhileIDChanged(e){if(e){const t=this.lineList.find(i=>i.id===e);t&&this.setDefaultAttribute(t.attribute)}}setSelectedLineID(e,t=!1,i=!0){this.selection.setSelectedIDs(e,t),this.status=1,i&&e&&this.updateAttrWhileIDChanged(this.selectedID),this.selectedLine&&this.setActiveLine(this.selectedLine.pointList),this.selectedIDs.length===0&&this.setActiveLine([]),this.emit("dataUpdated",this.lineList,this.selectedIDs)}attributeLockListChange(e){this.attributeLockList=e,this.render()}setResult(e){this.setLineList(e),this.render()}setConfig(e){super.setConfig(e)}toggleIsHide(){this.setIsHidden(!this.isHidden),this.render()}clearCanvas(){super.clearCanvas()}clearResult(){this.setResult([]),this.setSelectedLineID(void 0),this.render()}exportData(){return[this.lineList,this.basicImgInfo]}setDefaultAttribute(e=""){var t;this.attributeConfigurable&&(this.defaultAttribute=e,this.changeStyle(this.defaultAttribute),this.setLineAttribute("attribute",e),this.selectedIDs.length>0&&((t=this.history)==null||t.pushHistory(this.lineList)),this.emit("changeAttributeSidebar"))}getCurrentSelectedData(){var e,t;const i=this.isActiveLineValid(),s=this.defaultAttribute,n=this.getColor(s),o=i?n==null?void 0:n.valid.stroke:n==null?void 0:n.invalid.stroke,r=(t=(e=this.lineList.find(h=>h.id===this.selectedID))==null?void 0:e.textAttribute)!=null?t:"";return{color:o,textAttribute:r}}renderTextAttribute(){var e,t,i,s;if(!this.ctx||!this.selectedLine||this.activeLine&&((e=this.activeLine)==null?void 0:e.length)<2)return;const n=this.isActiveLineValid(),o=this.defaultAttribute,{x:r,y:h}=this.selectedLine.pointList[1],l=this.coordUtils.getRenderCoord({x:r,y:h}),a=this.getColor(o),c=n?a==null?void 0:a.valid.stroke:a==null?void 0:a.invalid.stroke,f=(i=(t=this.lineList.find(b=>b.id===this.selectedID))==null?void 0:t.textAttribute)!=null?i:"";this._textAttributeInstance||(this._textAttributeInstance=new $({container:this.container,icon:this.getTextIconSvg(o),color:c,getCurrentSelectedData:this.getCurrentSelectedData,updateSelectedTextAttribute:this.updateSelectedTextAttribute})),this._textAttributeInstance&&!((s=this._textAttributeInstance)==null?void 0:s.isExit)&&this._textAttributeInstance.appendToContainer(),this._textAttributeInstance.update(`${f}`,{left:l.x,top:l.y,color:c}),this._textAttributeInstance.updateIcon(this.getTextIconSvg(o))}getTextIconSvg(e=""){return y.getTextIconSvg(e,this.config.attributeList,this.config.attributeConfigurable,this.baseIcon)}updateSelectedTextAttribute(e){if(this._textAttributeInstance&&e!==void 0&&this.selectedID){let t=e;!y.textAttributeValidate(this.config.textCheckType,"",t)&&t!==""&&(this.emit("messageError",y.getErrorNotice(this.config.textCheckType,this.lang)),t=""),this.setTextAttribute(t),this.emit("updateTextAttribute"),this.render()}}}export{H as INNER_POINT_RADIUS,C as LINE_ORDER_OFFSET,m as POINT_ACTIVE_RADIUS,x as POINT_RADIUS,p as SEGMENT_NUMBER,et as default};
@@ -1 +1 @@
1
- import{ImgConversionUtils as n}from"@labelbee/lb-utils";import r from"../../utils/tool/AxisUtils.js";import a from"../../utils/tool/DrawUtils.js";import{EToolName as h,EScribblePattern as o}from"../../constant/tool.js";import c from"../../utils/tool/CommonToolUtils.js";import l from"../../utils/tool/AttributeUtils.js";import{BasicToolOperation as u}from"./basicToolOperation.js";const d=20,C="white";class v extends u{constructor(t){super(t);this.toolName=h.ScribbleTool,this.action=o.Scribble,this.getOriginCoordinate=i=>r.changePointByZoom(this.getCoordinateUnderZoomByRotate(i),1/this.zoom),this.onMouseDown=i=>{super.onMouseDown(i)||this.forbidMouseOperation||!this.imgInfo||(this.initCacheCanvas(this.imgNode),this.mouseEvents("onMouseDown").call(this,i))},this.onMouseMove=i=>{super.onMouseMove(i)||this.forbidMouseOperation||!this.imgInfo||this.mouseEvents("onMouseMove").call(this,i)},this.onMouseUp=i=>{super.onMouseUp(i)||this.forbidMouseOperation||!this.imgInfo||this.mouseEvents("onMouseUp").call(this,i)},this.mouseEvents=i=>({[o.Scribble]:{onMouseMove:this.onScribbleMove,onMouseUp:this.onScribbleEnd,onMouseDown:this.onScribbleStart},[o.Erase]:{onMouseMove:this.onEraseMove,onMouseUp:this.onEraseEnd,onMouseDown:this.onEraseStart}})[this.action][i],this.setPattern=i=>{switch(this.action=i,i){case o.Erase:{this.setCustomCursor(this.cursorErase);break}default:{this.setCustomCursor("none");break}}};var e;if(this.penSize=d,((e=this.config.attributeList)==null?void 0:e.length)>0){const i=this.config.attributeList[0];this.setDefaultAttribute(i.value)}}get cursorErase(){const t='<?xml version="1.0" encoding="UTF-8"?><svg width="24" heighst="24" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg"><g clip-path="url(#icon-65e7e1747c11bad3)"><path d="M44.7818 24.1702L31.918 7.09935L14.1348 20.5L27.5 37L30.8556 34.6643L44.7818 24.1702Z" fill="#141414" stroke="#000000" stroke-width="4" stroke-linejoin="miter"/><path d="M27.4998 37L23.6613 40.0748L13.0978 40.074L10.4973 36.6231L4.06543 28.0876L14.4998 20.2248" stroke="#000000" stroke-width="4" stroke-linejoin="miter"/><path d="M13.2056 40.072L44.5653 40.072" stroke="#000000" stroke-width="4" stroke-linecap="round"/></g><defs><clipPath id="icon-65e7e1747c11bad3"><rect width="48" height="48" fill="#df4c4c"/></clipPath></defs></svg>';return`url(${`data:image/svg+xml;base64,${window.btoa(unescape(encodeURIComponent(t)))}`}) 0 0, auto`}get defaultCursor(){return this.action===o.Erase?this.cursorErase:this.isShowDefaultCursor?"default":"none"}get color(){var t,e;return(e=(t=this==null?void 0:this.defaultAttributeInfo)==null?void 0:t.color)!=null?e:C}get penSizeWithZoom(){return this.penSize/this.zoom}get cacheCanvasToDataUrl(){var t;return(t=this.cacheCanvas)==null?void 0:t.toDataURL("image/png",0)}setPenSize(t){this.penSize=t}initCacheCanvas(t){if(this.cacheCanvas||!t)return;const{canvas:e,ctx:i}=n.createCanvas(t);this.cacheCanvas=e,this.cacheContext=i}updateCacheCanvasSize(t){this.cacheCanvas&&(this.cacheCanvas.width=t.width,this.cacheCanvas.height=t.height)}updateUrl2CacheContext(t){n.createImgDom(t).then(e=>{this.cacheContext||this.initCacheCanvas(e),this.cacheContext&&(this.cacheContext.save(),this.clearCacheCanvas(),this.cacheContext.drawImage(e,0,0,e.width,e.height),this.cacheContext.restore(),this.render())})}setImgNode(t,e){super.setImgNode(t,e),this.cacheCanvas?this.updateCacheCanvasSize(t):this.initCacheCanvas(t)}setResult(t){var e,i;let{url:s}=(e=t==null?void 0:t[0])!=null?e:{};if(this.clearCacheCanvas(),s||(s=(i=this.cacheCanvasToDataUrl)!=null?i:""),this.history.initRecord([s],!0),!s){this.render();return}this.updateUrl2CacheContext(s)}onKeyDown(t){if(!c.hotkeyFilter(t)||super.onKeyDown(t)===!1)return;const{keyCode:e}=t,i=l.getAttributeByKeycode(e,this.config.attributeList);i!==void 0&&this.setDefaultAttribute(i)}eventBinding(){super.eventBinding()}setDefaultAttribute(t){const e=this.config.attributeList.find(i=>i.value===t);e&&(this.defaultAttribute=e.value,this.defaultAttributeInfo=e,this.emit("changeAttributeSidebar"),this.render())}clearStatusAfterLeave(){this.onScribbleEnd(),this.startPoint=void 0}onMouseLeave(){super.onMouseLeave(),this.clearStatusAfterLeave()}onScribbleStart(t){if(!this.cacheContext)return;this.cacheContext.save(),this.cacheContext.beginPath(),this.cacheContext.strokeStyle=this.color,this.cacheContext.lineWidth=this.penSizeWithZoom,this.cacheContext.lineCap="round",this.cacheContext.lineJoin="round";const e=this.getOriginCoordinate(t);this.cacheContext.moveTo(e.x,e.y),this.startPoint=e}onScribbleMove(t){if(t.buttons===1&&this.cacheContext&&this.startPoint){const e=this.getOriginCoordinate(t);this.cacheContext.lineTo(e.x,e.y),this.cacheContext.stroke()}}onScribbleEnd(){var t,e;this.startPoint&&((t=this.cacheContext)==null||t.closePath(),(e=this.cacheContext)==null||e.restore(),this.startPoint=void 0,this.history.pushHistory(this.cacheCanvasToDataUrl))}eraseArc(t){var e;if(this.cacheContext){const i=this.getOriginCoordinate(t);this.cacheContext.save(),this.cacheContext.beginPath(),this.cacheContext.arc(i.x,i.y,this.penSizeWithZoom/2,0,Math.PI*2,!1),this.cacheContext.clip(),this.cacheContext.clearRect(0,0,this.cacheContext.canvas.width,this.cacheContext.canvas.height),(e=this.cacheContext)==null||e.restore()}}onEraseStart(t){!this.cacheContext||t.buttons!==1||this.eraseArc(t)}onEraseMove(t){!this.cacheContext||t.buttons!==1||this.eraseArc(t)}onEraseEnd(){}exportData(){const t=this.cacheCanvasToDataUrl;return[[],this.basicImgInfo,{imgBase64:t}]}clearCacheCanvas(){var t;(t=this.cacheContext)==null||t.clearRect(0,0,this.cacheContext.canvas.width,this.cacheContext.canvas.height),this.render()}clearResult(){this.clearCacheCanvas(),this.history.pushHistory(this.cacheCanvasToDataUrl)}renderPoint(t){a.drawCircleWithFill(this.canvas,this.coord,t,{color:this.color})}renderBorderPoint(t){a.drawCircle(this.canvas,this.coord,t,{color:"black"})}render(){if(super.render(),!this.ctx||!this.cacheCanvas||(this.ctx.save(),this.ctx.globalAlpha=.5,a.drawImg(this.canvas,this.cacheCanvas,{zoom:this.zoom,currentPos:this.currentPos,rotate:this.rotate}),this.ctx.restore(),this.forbidOperation||this.forbidCursorLine))return;const t=this.penSize/2;this.action===o.Erase?this.renderBorderPoint(t):this.renderPoint(t)}undo(){const t=this.history.undo();t&&this.cacheCanvas&&this.updateUrl2CacheContext(t)}redo(){const t=this.history.redo();t&&this.cacheCanvas&&this.updateUrl2CacheContext(t)}}export{v as default};
1
+ import{ImgConversionUtils as a}from"@labelbee/lb-utils";import c from"../../utils/tool/AxisUtils.js";import n from"../../utils/tool/DrawUtils.js";import{EToolName as l,EScribblePattern as o}from"../../constant/tool.js";import u from"../../utils/tool/CommonToolUtils.js";import d from"../../utils/tool/AttributeUtils.js";import h from"../../constant/keyCode.js";import{BasicToolOperation as C}from"./basicToolOperation.js";const v=20,f="white";class p extends C{constructor(t){super(t);this.toolName=l.ScribbleTool,this.action=o.Scribble,this.getOriginCoordinate=i=>c.changePointByZoom(this.getCoordinateUnderZoomByRotate(i),1/this.zoom),this.onMouseDown=i=>{super.onMouseDown(i)||this.forbidMouseOperation||!this.imgInfo||(this.initCacheCanvas(this.imgNode),this.mouseEvents("onMouseDown").call(this,i))},this.onMouseMove=i=>{super.onMouseMove(i)||this.forbidMouseOperation||!this.imgInfo||this.mouseEvents("onMouseMove").call(this,i)},this.onMouseUp=i=>{super.onMouseUp(i)||this.forbidMouseOperation||!this.imgInfo||this.mouseEvents("onMouseUp").call(this,i)},this.mouseEvents=i=>({[o.Scribble]:{onMouseMove:this.onScribbleMove,onMouseUp:this.onScribbleEnd,onMouseDown:this.onScribbleStart},[o.Erase]:{onMouseMove:this.onEraseMove,onMouseUp:this.onEraseEnd,onMouseDown:this.onEraseStart}})[this.action][i],this.setPattern=i=>{switch(this.action=i,i){case o.Erase:{this.setCustomCursor(this.cursorErase);break}default:{this.setCustomCursor("none");break}}};var e;if(this.penSize=v,this.isHidden=!1,this.pointList=[],((e=this.config.attributeList)==null?void 0:e.length)>0){const i=this.config.attributeList[0];this.setDefaultAttribute(i.value)}}get cursorErase(){const t='<?xml version="1.0" encoding="UTF-8"?><svg width="24" heighst="24" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg"><g clip-path="url(#icon-65e7e1747c11bad3)"><path d="M44.7818 24.1702L31.918 7.09935L14.1348 20.5L27.5 37L30.8556 34.6643L44.7818 24.1702Z" fill="#141414" stroke="#000000" stroke-width="4" stroke-linejoin="miter"/><path d="M27.4998 37L23.6613 40.0748L13.0978 40.074L10.4973 36.6231L4.06543 28.0876L14.4998 20.2248" stroke="#000000" stroke-width="4" stroke-linejoin="miter"/><path d="M13.2056 40.072L44.5653 40.072" stroke="#000000" stroke-width="4" stroke-linecap="round"/></g><defs><clipPath id="icon-65e7e1747c11bad3"><rect width="48" height="48" fill="#df4c4c"/></clipPath></defs></svg>';return`url(${`data:image/svg+xml;base64,${window.btoa(unescape(encodeURIComponent(t)))}`}) 0 0, auto`}get defaultCursor(){return this.action===o.Erase?this.cursorErase:this.isShowDefaultCursor?"default":"none"}get color(){var t,e;return(e=(t=this==null?void 0:this.defaultAttributeInfo)==null?void 0:t.color)!=null?e:f}get penSizeWithZoom(){return this.penSize/this.zoom}get cacheCanvasToDataUrl(){var t;return(t=this.cacheCanvas)==null?void 0:t.toDataURL("image/png",0)}setPenSize(t){this.penSize=t,this.render()}initCacheCanvas(t){if(this.cacheCanvas||!t)return;const{canvas:e,ctx:i}=a.createCanvas(t);this.cacheCanvas=e,this.cacheContext=i}updateCacheCanvasSize(t){this.cacheCanvas&&(this.cacheCanvas.width=t.width,this.cacheCanvas.height=t.height)}updateUrl2CacheContext(t){a.createImgDom(t).then(e=>{this.cacheContext||this.initCacheCanvas(e),this.cacheContext&&(this.cacheContext.save(),this.clearCacheCanvas(),this.cacheContext.drawImage(e,0,0,e.width,e.height),this.cacheContext.restore(),this.render())})}setImgNode(t,e){super.setImgNode(t,e),this.cacheCanvas?this.updateCacheCanvasSize(t):this.initCacheCanvas(t)}setResult(t){var e,i;let{url:s}=(e=t==null?void 0:t[0])!=null?e:{};if(this.clearCacheCanvas(),s||(s=(i=this.cacheCanvasToDataUrl)!=null?i:""),this.history.initRecord([s],!0),!s){this.render();return}this.updateUrl2CacheContext(s)}onKeyDown(t){if(!u.hotkeyFilter(t)||super.onKeyDown(t)===!1)return;const{keyCode:e}=t,i=d.getAttributeByKeycode(e,this.config.attributeList);i!==void 0&&this.setDefaultAttribute(i),e===h.Z&&!t.ctrlKey&&this.toggleIsHide(),t.ctrlKey&&this.action===o.Scribble&&(this.lineActive=!0,this.render())}onKeyUp(t){super.onKeyUp(t),t.keyCode===h.Ctrl&&(this.lineActive=!1,this.pointList=[],this.render())}toggleIsHide(){this.setIsHidden(!this.isHidden),this.render()}eventBinding(){super.eventBinding()}setDefaultAttribute(t){const e=this.config.attributeList.find(i=>i.value===t);e&&(this.defaultAttribute=e.value,this.defaultAttributeInfo=e,this.emit("changeAttributeSidebar"),this.render())}clearStatusAfterLeave(){this.onScribbleEnd(),this.startPoint=void 0}onMouseLeave(){super.onMouseLeave(),this.clearStatusAfterLeave()}onScribbleStart(t){if(!this.cacheContext)return;this.cacheContext.save(),this.cacheContext.beginPath(),this.cacheContext.strokeStyle=this.color,this.cacheContext.lineWidth=this.penSizeWithZoom,this.cacheContext.lineCap="round",this.cacheContext.lineJoin="round";const e=this.getOriginCoordinate(t);this.cacheContext.moveTo(e.x,e.y),this.startPoint=e,this.lineActive&&this.scribbleOnImgByLine(e)}scribbleOnImgByLine(t){const e=this.cacheContext;!e||(this.pointList.push(t),this.pointList.length>1&&this.pointList.forEach((i,s)=>{if(e.beginPath(),s>0){const r=this.pointList[s-1];e.save(),e.moveTo(r.x,r.y),e.lineTo(i.x,i.y),e.stroke(),e.restore()}}))}onScribbleMove(t){const e=this.getOriginCoordinate(t);if(this.lineActive){this.prePoint=e;return}t.buttons===1&&this.cacheContext&&this.startPoint&&(this.cacheContext.lineTo(e.x,e.y),this.cacheContext.stroke())}onScribbleEnd(){var t,e;this.startPoint&&((t=this.cacheContext)==null||t.closePath(),(e=this.cacheContext)==null||e.restore(),this.startPoint=void 0,this.history.pushHistory(this.cacheCanvasToDataUrl))}eraseArc(t){var e;if(this.cacheContext){const i=this.getOriginCoordinate(t);this.cacheContext.save(),this.cacheContext.beginPath(),this.cacheContext.arc(i.x,i.y,this.penSizeWithZoom/2,0,Math.PI*2,!1),this.cacheContext.clip(),this.cacheContext.clearRect(0,0,this.cacheContext.canvas.width,this.cacheContext.canvas.height),(e=this.cacheContext)==null||e.restore()}}onEraseStart(t){!this.cacheContext||t.buttons!==1||this.eraseArc(t)}onEraseMove(t){!this.cacheContext||t.buttons!==1||this.eraseArc(t)}onEraseEnd(){}exportData(){const t=this.cacheCanvasToDataUrl;return[[],this.basicImgInfo,{imgBase64:t}]}clearCacheCanvas(){var t;(t=this.cacheContext)==null||t.clearRect(0,0,this.cacheContext.canvas.width,this.cacheContext.canvas.height),this.render()}clearResult(){this.clearCacheCanvas(),this.history.pushHistory(this.cacheCanvasToDataUrl)}renderPoint(t){n.drawCircleWithFill(this.canvas,this.coord,t,{color:this.color})}renderBorderPoint(t){n.drawCircle(this.canvas,this.coord,t,{color:"black"})}drawLineSegment(){if(this.prePoint&&this.pointList.length>0){const i=[this.pointList[this.pointList.length-1]].concat(this.prePoint).map(s=>this.getCoordinateUnderZoomByRotateFromImgPoint(s));this.drawStraightLine(i,{color:this.color,lineWidth:this.penSize,globalAlpha:.5})}}render(){if(super.render(),!this.ctx||!this.cacheCanvas||this.isHidden||(this.lineActive&&(this.renderCursorLine(this.color),this.drawLineSegment()),this.ctx.save(),this.ctx.globalAlpha=.5,n.drawImg(this.canvas,this.cacheCanvas,{zoom:this.zoom,currentPos:this.currentPos,rotate:this.rotate}),this.ctx.restore(),this.forbidOperation||this.forbidCursorLine))return;const t=this.penSize/2;this.action===o.Erase?this.renderBorderPoint(t):this.renderPoint(t)}undo(){const t=this.history.undo();t&&this.cacheCanvas&&this.updateUrl2CacheContext(t)}redo(){const t=this.history.redo();t&&this.cacheCanvas&&this.updateUrl2CacheContext(t)}}export{p as default};
@@ -1 +1 @@
1
- import{i18n as R,ImgPosUtils as L,toolStyleConverter as k}from"@labelbee/lb-utils";import{isNumber as E}from"lodash";import{EOperationMode as w,EToolName as y}from"../../constant/tool.js";import B from"../../utils/MathUtils.js";import _,{CoordinateUtils as G}from"../../utils/tool/AxisUtils.js";import F from"../../utils/tool/CanvasUtils.js";import D from"../../utils/tool/CommonToolUtils.js";import H from"../../utils/tool/LineToolUtils.js";import{ELang as x,EGrowthMode as V,EDragStatus as Y}from"../../constant/annotation.js";import P from"../../constant/keyCode.js";import{styleString as X,BASE_ICON as $}from"../../constant/style.js";import U from"../../locales/index.js";import{EMessage as Z}from"../../locales/constants.js";import q from"../../utils/ActionsHistory.js";import O from"../../utils/tool/AttributeUtils.js";import J from"../../utils/tool/DblClickEventListener.js";import g from"../../utils/tool/DrawUtils.js";import Q from"../../utils/tool/RenderDomUtils.js";import A from"../../utils/tool/ZoomUtils.js";import tt from"./eventListener.js";var it=Object.defineProperty,et=Object.defineProperties,st=Object.getOwnPropertyDescriptors,N=Object.getOwnPropertySymbols,ot=Object.prototype.hasOwnProperty,nt=Object.prototype.propertyIsEnumerable,j=(c,t,i)=>t in c?it(c,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):c[t]=i,z=(c,t)=>{for(var i in t||(t={}))ot.call(t,i)&&j(c,i,t[i]);if(N)for(var i of N(t))nt.call(t,i)&&j(c,i,t[i]);return c},T=(c,t)=>et(c,st(t)),rt=(c,t,i)=>new Promise((e,s)=>{var o=n=>{try{r(i.next(n))}catch(a){s(a)}},h=n=>{try{r(i.throw(n))}catch(a){s(a)}},r=n=>n.done?e(n.value):Promise.resolve(n.value).then(o,h);r((i=i.apply(c,t)).next())});const K={[x.Zh]:"cn",[x.US]:"en"},at={min:.2,max:1e3,ratio:.4};class ht extends tt{constructor(t){super();this.isDrag=!1,this.isSpaceKey=!1,this.staticMode=!1,this.operationMode=w.General,this.innerZoom=1,this.basicZoom=.01,this.isSpaceClick=!1,this.isDragStart=!1,this.startTime=0,this.zoomInfo=at,this.initImgPos=()=>rt(this,null,function*(){var d,l;if(!this.imgNode)return;const u=(d=this._imgAttribute)==null?void 0:d.zoomRatio,m=(l=this._imgAttribute)==null?void 0:l.isOriginalSize,{currentPos:f,imgInfo:I,zoom:v}=L.getInitImgPos(this.size,{width:this.imgNode.width,height:this.imgNode.height},this.rotate,u,m);this.setCurrentPos(f),this.currentPosStorage=f,this.setImgInfo(I),this.setZoom(v),this.render(),this.renderBasicCanvas(),this.emit("dependRender"),this.emit("renderZoom",v,f,I)}),this.getCurrentPos=d=>{const{_firstClickCoordinate:l,currentPosStorage:u}=this;try{let m;return l&&u?m={y:u.y+d.y-l.y,x:u.x+d.x-l.x}:m={x:0,y:0},m}catch(m){return console.error(m),{x:0,y:0}}},this.wheelChangePos=(d,l,u)=>{const{currentPos:m,imgNode:f}=this;if(!f){console.error("unable to load image");return}if(this.zoom===this.basicZoom&&l===-1)return;const I=A.wheelChangePos(f,d,l,m,{zoom:u||this.zoom,innerZoom:this.innerZoom,basicZoom:this.basicZoom,zoomMax:this.zoomInfo.max,rotate:this.rotate});if(!I)return;const{currentPos:v,ratio:W,zoom:S,imgInfo:M}=I;this.setZoom(S),this.setCurrentPos(v),this.currentPosStorage=v,this.setImgInfo(M),this.zoomInfo.ratio=W,this.emit("renderZoom",S,v,M)},this.zoomChanged=(d,l=V.Linear)=>{const u=A.zoomChanged(this.zoom,d,l);this.wheelChangePos(this.getGetCenterCoordinate(),u>this.zoom?1:-1,u),this.render(),this.renderBasicCanvas()},this.zoomChangeOnCenter=d=>{this.wheelChangePos(this.getGetCenterCoordinate(),0,d),this.render(),this.renderBasicCanvas()},this.drawImg=()=>{!this.imgNode||this.hiddenImg===!0||(g.drawImg(this.basicCanvas,this.imgNode,{zoom:this.zoom,currentPos:this.currentPos,rotate:this.rotate,imgAttribute:this._imgAttribute}),this.drawStaticImg())},this.drawStaticImg=()=>{!this.staticImgNode||!this.staticMode||(this.clearCanvas(),g.drawImg(this.canvas,this.staticImgNode,{zoom:this.zoom,currentPos:this.currentPos,rotate:this.rotate,imgAttribute:this._imgAttribute}))};var i,e,s,o,h,r,n,a,C,b,p;this.container=t.container,this.config=D.jsonParser(t.config),this.showDefaultCursor=t.showDefaultCursor||!1,this.destroyCanvas(),this.createCanvas(t.size,t.isAppend),this.imgNode=t.imgNode,this.staticMode=(i=t.staticMode)!=null?i:!1,this.isImgError=!t.imgNode,this.basicImgInfo={width:(s=(e=t.imgNode)==null?void 0:e.width)!=null?s:0,height:(h=(o=t.imgNode)==null?void 0:o.height)!=null?h:0,valid:!0,rotate:0},this.forbidOperation=(r=t.forbidOperation)!=null?r:!1,this.forbidBasicResultRender=(n=t.forbidBasicResultRender)!=null?n:!1,this.size=t.size,this.currentPos={x:0,y:0},this.zoom=1,this.coord={x:-1,y:-1},this.currentPosStorage={x:0,y:0},this.isShowCursor=!1,this.attributeLockList=[],this.history=new q,this.style=(a=t.style)!=null?a:D.jsonParser(X),this._imgAttribute=(C=t.imgAttribute)!=null?C:{},this.isHidden=!1,this.dragStatus=Y.Wait,this.defaultAttribute=(b=t==null?void 0:t.defaultAttribute)!=null?b:"",this.forbidCursorLine=!!t.forbidCursorLine,this.lang=(p=t==null?void 0:t.language)!=null?p:x.Zh,R.changeLanguage(K[this.lang]),this.onMouseDown=this.onMouseDown.bind(this),this.onMouseMove=this.onMouseMove.bind(this),this.onMouseLeave=this.onMouseLeave.bind(this),this.onMouseUp=this.onMouseUp.bind(this),this.onKeyDown=this.onKeyDown.bind(this),this.onKeyUp=this.onKeyUp.bind(this),this.onWheel=this.onWheel.bind(this),this.onLeftDblClick=this.onLeftDblClick.bind(this),this.onRightDblClick=this.onRightDblClick.bind(this),this.onClick=this.onClick.bind(this),this.clearImgDrag=this.clearImgDrag.bind(this),this.dblClickListener=new J(this.container,200),this.coordUtils=new G(this),this.coordUtils.setBasicImgInfo(this.basicImgInfo),this.hiddenImg=t.hiddenImg||!1,t.zoomInfo&&(this.zoomInfo=t.zoomInfo)}onContextmenu(t){t.preventDefault()}get ctx(){var t;return this._ctx||((t=this.canvas)==null?void 0:t.getContext("2d"))}get basicCtx(){var t;return(t=this.basicCanvas)==null?void 0:t.getContext("2d")}get rotate(){var t,i;return(i=(t=this.basicImgInfo)==null?void 0:t.rotate)!=null?i:0}get valid(){var t,i;return(i=(t=this.basicImgInfo)==null?void 0:t.valid)!=null?i:!0}get baseIcon(){return $[this.style.color]}get defaultCursor(){return this.showDefaultCursor?"default":"none"}get dataList(){return[]}get innerPosAndZoom(){return{innerZoom:this.innerZoom,currentPosStorage:this.currentPosStorage}}get isShowDefaultCursor(){return this.showDefaultCursor}get isMultiMoveMode(){return this.operationMode===w.MultiMove}get hasMarkerConfig(){return this.config.markerConfigurable===!0&&this.config.markerList&&this.config.markerList.length>0}setZoom(t){this.zoom=t,this.innerZoom=t,this.coordUtils.setZoomAndCurrentPos(this.zoom,this.currentPos)}setCurrentPos(t){this.currentPos=t,this.coordUtils.setZoomAndCurrentPos(this.zoom,this.currentPos)}setReferenceData(t){this.referenceData=t}setImgInfo(t){this.imgInfo=t}setCurrentPosStorage(t){this.currentPosStorage=t}setOperationMode(t){this.operationMode=t}recoverOperationMode(){this.operationMode===w.MultiMove&&this.setOperationMode(w.General)}updatePosition(t){const{zoom:i,currentPos:e}=t;this.setZoom(i),this.setCurrentPos(e),this.currentPosStorage=e,this.renderBasicCanvas(),this.render()}setLang(t){this.lang=t;const i=K[t];R.changeLanguage(i)}setShowDefaultCursor(t){this.showDefaultCursor=t,this.container.style.cursor=this.defaultCursor}setCustomCursor(t){this.container.style.cursor=t}get forbidMouseOperation(){return this.forbidOperation||this.valid===!1}get pixelRatio(){var t;return F.getPixelRatio((t=this.canvas)==null?void 0:t.getContext("2d"))}init(){this.eventUnbinding(),this.initPosition(),this.eventBinding(),this.render(),this.renderBasicCanvas()}destroy(){this.destroyCanvas(),this.eventUnbinding()}updateCanvasBasicStyle(t,i,e){const s=this.pixelRatio;t.style.position="absolute",t.width=i.width*s,t.height=i.height*s,t.style.width=`${i.width}px`,t.style.height=`${i.height}px`,t.style.left="0",t.style.top="0",t.style.zIndex=`${e} `}createCanvas(t,i=!0){var e,s;const o=this.pixelRatio,h=document.createElement("canvas");this.updateCanvasBasicStyle(h,t,0),this.basicCanvas=h;const r=document.createElement("canvas");this.updateCanvasBasicStyle(r,t,10),i&&(this.container.hasChildNodes()?(this.container.insertBefore(r,this.container.childNodes[0]),this.container.insertBefore(h,this.container.childNodes[0])):(this.container.appendChild(h),this.container.appendChild(r))),this.canvas=r,this.container.style.cursor=this.defaultCursor,(e=this.ctx)==null||e.scale(o,o),(s=this.basicCtx)==null||s.scale(o,o),this.ctx&&(this.ctx.imageSmoothingEnabled=!1)}destroyCanvas(){this.canvas&&this.container.contains(this.canvas)&&this.container.removeChild(this.canvas),this.basicCanvas&&this.container.contains(this.basicCanvas)&&this.container.removeChild(this.basicCanvas),this.clearInvalidPage(),this.clearImgDrag()}setStyle(t){this.style=t,this.render()}setImgNode(t,i={}){this.imgNode=t,this.setBasicImgInfo(z({width:t.width,height:t.height,valid:!0,rotate:0},i)),this.updateZoomInfo(),this.isImgError===!0&&(this.isImgError=!1,this.emit("changeAnnotationShow")),typeof i.valid=="boolean"&&this.setValid(i.valid),this.initImgPos(),this.render(),this.renderBasicCanvas()}updateZoomInfo(t=this.imgNode,i=this.size){var e;if(!t||!i)return;const{min:s}=L.getMinZoomByImgAndSize({canvasSize:i,imgSize:{width:t.width,height:t.height},rotate:this.rotate,zoomRatio:(e=this._imgAttribute)==null?void 0:e.zoomRatio});this.zoomInfo=T(z({},this.zoomInfo),{min:s})}setErrorImg(){const t=this.isImgError;this.isImgError=!0,this.imgNode=void 0,this.setBasicImgInfo({width:0,height:0,valid:!0,rotate:0}),t===!1&&this.emit("changeAnnotationShow")}setBasicImgInfo(t){this.basicImgInfo=t,this.coordUtils.setBasicImgInfo(t)}setForbidOperation(t){this.forbidOperation=t,this.setShowDefaultCursor(t),this.render()}setForbidCursorLine(t){this.forbidCursorLine=t,this.render()}setIsHidden(t){this.isHidden=t,this.emit("hiddenChange")}setDefaultAttribute(t){this.defaultAttribute=t}getCoordinateInOrigin(t){const i=this.canvas.getBoundingClientRect();return{x:(t.clientX-i.left-this.currentPos.x)/this.zoom,y:(t.clientY-i.top-this.currentPos.y)/this.zoom}}getTextIconSvg(t=""){var i;return O.getTextIconSvg(t,(i=this.config)==null?void 0:i.attributeList,this.config.attributeConfigurable,this.baseIcon)}setIsShowOrder(t){this.config.isShowOrder=t,this.render()}getCoordinate(t){const i=this.canvas.getBoundingClientRect();return{x:t.clientX-i.left,y:t.clientY-i.top}}getCoordinateUnderZoom(t){const i=this.canvas.getBoundingClientRect();return{x:t.clientX-i.left-this.currentPos.x,y:t.clientY-i.top-this.currentPos.y}}getCoordinateUnderZoomByRotate(t){const{x:i,y:e}=this.getCoordinateUnderZoom(t);return this.basicImgInfo.rotate===90?{x:e,y:this.basicImgInfo.height*this.zoom-i}:this.basicImgInfo.rotate===180?{x:this.basicImgInfo.width*this.zoom-i,y:this.basicImgInfo.height*this.zoom-e}:this.basicImgInfo.rotate===270?{x:this.basicImgInfo.width*this.zoom-e,y:i}:{x:i,y:e}}getGetCenterCoordinate(){return{x:this.size.width/2,y:this.size.height/2}}initPosition(){if(this.basicResult&&this.imgInfo){const{basicResult:t,size:i,imgNode:e,_imgAttribute:s,imgInfo:o,dependToolName:h}=this;if(t&&e&&h){let r=t;switch(h){case y.Polygon:case y.Line:{if(t.pointList){const a=B.calcViewportBoundaries(t.pointList);r={x:a.left,y:a.top,width:a.right-a.left,height:a.bottom-a.top}}break}}const n=L.getBasicRecPos(e,r,i,void 0,s==null?void 0:s.zoomRatio,s==null?void 0:s.isOriginalSize);n&&(this.setCurrentPos(n.currentPos),this.currentPosStorage=this.currentPos,this.setImgInfo(T(z({},o),{width:o.width/this.innerZoom*n.innerZoom,height:o.height/this.innerZoom*n.innerZoom})),this.setZoom(n.innerZoom),this.render(),this.renderBasicCanvas())}}else this.initImgPos()}undo(){this.history.undo()}redo(){this.history.redo()}clearCanvas(){var t;(t=this.ctx)==null||t.clearRect(0,0,this.size.width,this.size.height)}clearBasicCanvas(){var t;(t=this.basicCtx)==null||t.clearRect(0,0,this.size.width,this.size.height)}eventBinding(){this.dblClickListener.addEvent(()=>{},this.onLeftDblClick,this.onRightDblClick),this.container.addEventListener("mousedown",this.onMouseDown),this.container.addEventListener("mousemove",this.onMouseMove),this.container.addEventListener("mouseup",this.onMouseUp),this.container.addEventListener("mouseleave",this.onMouseLeave),this.container.addEventListener("click",this.onClick),this.container.addEventListener("wheel",this.onWheel),document.addEventListener("keydown",this.onKeyDown),document.addEventListener("keyup",this.onKeyUp),window.parent.document.addEventListener("contextmenu",this.onContextmenu,!1)}eventUnbinding(){this.container.removeEventListener("mousedown",this.onMouseDown),this.container.removeEventListener("mousemove",this.onMouseMove),this.container.removeEventListener("mouseup",this.onMouseUp),this.container.removeEventListener("mouseleave",this.onMouseLeave),this.container.removeEventListener("wheel",this.onWheel),this.container.removeEventListener("click",this.onClick),document.removeEventListener("keydown",this.onKeyDown),document.removeEventListener("keyup",this.onKeyUp),window.parent.document.removeEventListener("contextmenu",this.onContextmenu,!1),this.dblClickListener.removeEvent()}clearImgDrag(){this.isDrag=!1,this.isDragStart=!1,this.isSpaceClick=!1,this.startTime=0,this.container.style.cursor=this.defaultCursor,this.forbidCursorLine=!1}clearCursorLine(){this.coord={x:-1,y:-1}}onMouseDown(t){if(!this.canvas||this.isImgError)return!0;const i=this.getCoordinate(t);(this.isSpaceKey&&t.button===0||t.button===2)&&(t.stopPropagation(),this._firstClickCoordinate=i,this.currentPosStorage=this.currentPos,this.isSpaceClick=!0,this.isDragStart=!0,this.startTime=new Date().getTime())}onMouseMove(t){if(!this.canvas||this.isImgError)return!0;const i=this.getCoordinate(t);this.isShowCursor&&(this.coord=i);try{if(!i||!E(i==null?void 0:i.x)||!E(i==null?void 0:i.y))throw new Error("coord error");if(this.coord=i,(this.isSpaceClick||this.isDragStart)&&this._firstClickCoordinate){const e=this.getCurrentPos(i);this.setCurrentPos(e),this.isDrag=!0,this.container.style.cursor="grabbing",this.forbidCursorLine=!0,this.renderBasicCanvas(),this.emit("dependRender"),this.emit("dragMove",{currentPos:e,zoom:this.zoom,imgInfo:this.imgInfo})}this.render()}catch(e){console.error(e)}}onMouseUp(t){if(!this.canvas||this.isImgError)return!0;if(this.container.style.cursor=this.defaultCursor,this.forbidCursorLine=!1,this.isDrag=!1,this.isDragStart=!1,this.isSpaceClick=!1,this.startTime!==0&&this._firstClickCoordinate){const i=new Date().getTime(),e=this.getCoordinate(t);if(i-this.startTime>1e3||this.isSpaceKey===!0||H.calcTwoPointDistance(e,this._firstClickCoordinate)>10)return t.stopPropagation(),this.startTime=0,this.render(),!0}this.startTime=0,this.render()}onMouseLeave(){this.clearImgDrag()}onClick(t){}onLeftDblClick(t){}onRightDblClick(t){this.clearImgDrag()}onKeyDown(t){switch(t.keyCode===P.Alt&&t.preventDefault(),t.keyCode){case P.Space:this.isSpaceKey=!0,t.preventDefault();break;case P.Z:if(t.ctrlKey)return t.shiftKey?this.redo():this.undo(),!1;break}return!0}onKeyUp(t){switch(t.keyCode){case P.Space:this.isSpaceKey=!1;break}}exportCustomData(){return{}}onWheel(t,i=!0){if(!this.imgNode||!this.coord)return;t.preventDefault(),t.stopPropagation();const e=this.getCoordinate(t),s=t.deltaY||t.wheelDelta;let o=0;s>0&&this.zoom>this.zoomInfo.min&&(o=-1),s<0&&this.zoom<this.zoomInfo.max&&(o=1),this.wheelChangePos(e,o),this.emit("dependRender"),i&&this.render(),this.renderBasicCanvas()}renderCursorLine(t=(i=>(i=this.style.lineColor[0])!=null?i:"")()){if(!this.ctx||this.forbidCursorLine||this.forbidOperation)return;const{x:i,y:e}=this.coord;g.drawLine(this.canvas,{x:0,y:e},{x:1e4,y:e},{color:t}),g.drawLine(this.canvas,{x:i,y:0},{x:i,y:1e4},{color:t}),g.drawCircleWithFill(this.canvas,{x:i,y:e},1,{color:"white"})}setSize(t){var i;this.size=t,this.updateZoomInfo(),this.container.contains(this.canvas)&&(this.destroyCanvas(),this.createCanvas(t),this.eventUnbinding(),this.init(),((i=this.basicImgInfo)==null?void 0:i.valid)===!1&&this.renderInvalidPage())}setImgAttribute(t){const i=this._imgAttribute;if(this._imgAttribute=t,(i==null?void 0:i.zoomRatio)!==t.zoomRatio||i.isOriginalSize!==t.isOriginalSize){this.initImgPos();return}this.renderBasicCanvas(),this.render()}clearResult(t){}setValid(t){this.basicImgInfo.valid=t,t===!1?(this.renderInvalidPage(),this.clearResult(!1)):this.clearInvalidPage()}setRotate(t){this.basicImgInfo.rotate=t}setBasicResult(t){this.basicResult=t,this.coordUtils.setBasicResult(t),this.initPosition(),this.emit("dependRender")}setDependName(t,i){this.dependToolName=t,this.coordUtils.setDependInfo(t,i)}setAttributeLockList(t){this.attributeLockList=t,this.render()}setConfig(t){this.config=D.jsonParser(t)}setDataInjectionAtCreation(t){this.dataInjectionAtCreation=t}setRenderEnhance(t){this.renderEnhance=t}setCustomRenderStyle(t){this.customRenderStyle=t}updateRotate(){if(this.dependToolName)return this.emit("messageInfo",U.getMessagesByLocale(Z.NoRotateInDependence,this.lang)),!1;if(this.dataList.length>0)return this.emit("messageInfo",U.getMessagesByLocale(Z.NoRotateNotice,this.lang)),!1;const t=B.getRotate(this.basicImgInfo.rotate);this.basicImgInfo.rotate=t,this.initImgPos(),this.emit("updateResult")}getColor(t="",i=this.config){return k.getColorByConfig({attribute:t,config:i,style:this.style})}getLineColor(t=""){var i,e,s,o,h,r,n,a;if(((i=this.config)==null?void 0:i.attributeConfigurable)===!0){const p=O.getAttributeIndex(t,(s=(e=this.config)==null?void 0:e.attributeList)!=null?s:[])+1;return((r=(h=(o=this.config)==null?void 0:o.attributeList)==null?void 0:h.find(l=>l.value===t))==null?void 0:r.color)?(a=(n=k.getColorByConfig({attribute:t,config:this.config}))==null?void 0:n.valid)==null?void 0:a.stroke:this.style.attributeLineColor?this.style.attributeLineColor[p]:""}const{color:C,lineColor:b}=this.style;return C&&b?b[C]:""}clearInvalidPage(){this._invalidDOM&&this.container&&this.container.contains(this._invalidDOM)&&(this.container.removeChild(this._invalidDOM),this._invalidDOM=void 0)}renderInvalidPage(){!this.container||this._invalidDOM||(this._invalidDOM=Q.renderInvalidPage(this.container,this.size,this.lang))}renderBasicCanvas(){if(!this.basicCanvas)return;this.clearBasicCanvas(),this.drawImg();const t=3;if(!this.forbidBasicResultRender&&this.basicResult&&this.dependToolName)switch(this.dependToolName){case y.Rect:{g.drawRect(this.basicCanvas,_.changeRectByZoom(this.basicResult,this.zoom,this.currentPos),{color:"rgba(204,204,204,1.00)",thickness:t});break}case y.Polygon:{g.drawPolygonWithFillAndLine(this.basicCanvas,_.changePointListByZoom(this.basicResult.pointList,this.zoom,this.currentPos),{fillColor:"transparent",strokeColor:"rgba(204,204,204,1.00)",isClose:!0,thickness:t});break}case y.Line:{g.drawLineWithPointList(this.basicCanvas,_.changePointListByZoom(this.basicResult.pointList,this.zoom,this.currentPos),{color:"rgba(204,204,204,1.00)",thickness:t});break}}}render(){!this.canvas||!this.ctx||!this.imgNode||this.clearCanvas()}changeStyle(t=this.defaultAttribute){this.emit("changeStyle",{attribute:t})}}export{ht as BasicToolOperation};
1
+ import{i18n as R,ImgPosUtils as L,toolStyleConverter as k}from"@labelbee/lb-utils";import{isNumber as E}from"lodash";import{EOperationMode as p,EToolName as y}from"../../constant/tool.js";import B from"../../utils/MathUtils.js";import _,{CoordinateUtils as G}from"../../utils/tool/AxisUtils.js";import F from"../../utils/tool/CanvasUtils.js";import x from"../../utils/tool/CommonToolUtils.js";import H from"../../utils/tool/LineToolUtils.js";import{ELang as z,EGrowthMode as V,EDragStatus as Y}from"../../constant/annotation.js";import w from"../../constant/keyCode.js";import{styleString as X,BASE_ICON as $}from"../../constant/style.js";import U from"../../locales/index.js";import{EMessage as Z}from"../../locales/constants.js";import J from"../../utils/ActionsHistory.js";import A from"../../utils/tool/AttributeUtils.js";import q from"../../utils/tool/DblClickEventListener.js";import v from"../../utils/tool/DrawUtils.js";import Q from"../../utils/tool/RenderDomUtils.js";import O from"../../utils/tool/ZoomUtils.js";import tt from"./eventListener.js";var it=Object.defineProperty,et=Object.defineProperties,st=Object.getOwnPropertyDescriptors,N=Object.getOwnPropertySymbols,ot=Object.prototype.hasOwnProperty,nt=Object.prototype.propertyIsEnumerable,j=(u,t,i)=>t in u?it(u,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):u[t]=i,D=(u,t)=>{for(var i in t||(t={}))ot.call(t,i)&&j(u,i,t[i]);if(N)for(var i of N(t))nt.call(t,i)&&j(u,i,t[i]);return u},T=(u,t)=>et(u,st(t)),rt=(u,t,i)=>new Promise((e,o)=>{var n=r=>{try{a(i.next(r))}catch(l){o(l)}},c=r=>{try{a(i.throw(r))}catch(l){o(l)}},a=r=>r.done?e(r.value):Promise.resolve(r.value).then(n,c);a((i=i.apply(u,t)).next())});const K={[z.Zh]:"cn",[z.US]:"en"},at={min:.2,max:1e3,ratio:.4};class ht extends tt{constructor(t){super();this.isDrag=!1,this.isSpaceKey=!1,this.staticMode=!1,this.operationMode=p.General,this.innerZoom=1,this.basicZoom=.01,this.isSpaceClick=!1,this.isDragStart=!1,this.startTime=0,this.zoomInfo=at,this.initImgPos=()=>rt(this,null,function*(){var d,h;if(!this.imgNode)return;const s=(d=this._imgAttribute)==null?void 0:d.zoomRatio,m=(h=this._imgAttribute)==null?void 0:h.isOriginalSize,{currentPos:g,imgInfo:f,zoom:C}=L.getInitImgPos(this.size,{width:this.imgNode.width,height:this.imgNode.height},this.rotate,s,m);this.setCurrentPos(g),this.currentPosStorage=g,this.setImgInfo(f),this.setZoom(C),this.render(),this.renderBasicCanvas(),this.emit("dependRender"),this.emit("renderZoom",C,g,f)}),this.getCurrentPos=d=>{const{_firstClickCoordinate:h,currentPosStorage:s}=this;try{let m;return h&&s?m={y:s.y+d.y-h.y,x:s.x+d.x-h.x}:m={x:0,y:0},m}catch(m){return console.error(m),{x:0,y:0}}},this.wheelChangePos=(d,h,s)=>{const{currentPos:m,imgNode:g}=this;if(!g){console.error("unable to load image");return}if(this.zoom===this.basicZoom&&h===-1)return;const f=O.wheelChangePos(g,d,h,m,{zoom:s||this.zoom,innerZoom:this.innerZoom,basicZoom:this.basicZoom,zoomMax:this.zoomInfo.max,rotate:this.rotate});if(!f)return;const{currentPos:C,ratio:W,zoom:S,imgInfo:M}=f;this.setZoom(S),this.setCurrentPos(C),this.currentPosStorage=C,this.setImgInfo(M),this.zoomInfo.ratio=W,this.emit("renderZoom",S,C,M)},this.zoomChanged=(d,h=V.Linear)=>{const s=O.zoomChanged(this.zoom,d,h);this.wheelChangePos(this.getGetCenterCoordinate(),s>this.zoom?1:-1,s),this.render(),this.renderBasicCanvas()},this.zoomChangeOnCenter=d=>{this.wheelChangePos(this.getGetCenterCoordinate(),0,d),this.render(),this.renderBasicCanvas()},this.drawStraightLine=(d,h)=>{const{ctx:s}=this;s&&(s.save(),s.lineCap="round",s.lineJoin="round",s.strokeStyle=h.color,s.lineWidth=h.lineWidth,s.globalAlpha=h.globalAlpha,d.forEach((m,g)=>{if(s.beginPath(),g>0){const f=d[g-1];s.save(),s.moveTo(f.x,f.y),s.lineTo(m.x,m.y),s.stroke(),s.restore()}}),s.restore())},this.drawImg=()=>{!this.imgNode||this.hiddenImg===!0||(v.drawImg(this.basicCanvas,this.imgNode,{zoom:this.zoom,currentPos:this.currentPos,rotate:this.rotate,imgAttribute:this._imgAttribute}),this.drawStaticImg())},this.drawStaticImg=()=>{!this.staticImgNode||!this.staticMode||(this.clearCanvas(),v.drawImg(this.canvas,this.staticImgNode,{zoom:this.zoom,currentPos:this.currentPos,rotate:this.rotate,imgAttribute:this._imgAttribute}))};var i,e,o,n,c,a,r,l,b,I,P;this.container=t.container,this.config=x.jsonParser(t.config),this.showDefaultCursor=t.showDefaultCursor||!1,this.destroyCanvas(),this.createCanvas(t.size,t.isAppend),this.imgNode=t.imgNode,this.staticMode=(i=t.staticMode)!=null?i:!1,this.isImgError=!t.imgNode,this.basicImgInfo={width:(o=(e=t.imgNode)==null?void 0:e.width)!=null?o:0,height:(c=(n=t.imgNode)==null?void 0:n.height)!=null?c:0,valid:!0,rotate:0},this.forbidOperation=(a=t.forbidOperation)!=null?a:!1,this.forbidBasicResultRender=(r=t.forbidBasicResultRender)!=null?r:!1,this.size=t.size,this.currentPos={x:0,y:0},this.zoom=1,this.coord={x:-1,y:-1},this.currentPosStorage={x:0,y:0},this.isShowCursor=!1,this.attributeLockList=[],this.history=new J,this.style=(l=t.style)!=null?l:x.jsonParser(X),this._imgAttribute=(b=t.imgAttribute)!=null?b:{},this.isHidden=!1,this.dragStatus=Y.Wait,this.defaultAttribute=(I=t==null?void 0:t.defaultAttribute)!=null?I:"",this.forbidCursorLine=!!t.forbidCursorLine,this.lang=(P=t==null?void 0:t.language)!=null?P:z.Zh,R.changeLanguage(K[this.lang]),this.onMouseDown=this.onMouseDown.bind(this),this.onMouseMove=this.onMouseMove.bind(this),this.onMouseLeave=this.onMouseLeave.bind(this),this.onMouseUp=this.onMouseUp.bind(this),this.onKeyDown=this.onKeyDown.bind(this),this.onKeyUp=this.onKeyUp.bind(this),this.onWheel=this.onWheel.bind(this),this.onLeftDblClick=this.onLeftDblClick.bind(this),this.onRightDblClick=this.onRightDblClick.bind(this),this.onClick=this.onClick.bind(this),this.clearImgDrag=this.clearImgDrag.bind(this),this.dblClickListener=new q(this.container,200),this.coordUtils=new G(this),this.coordUtils.setBasicImgInfo(this.basicImgInfo),this.hiddenImg=t.hiddenImg||!1,t.zoomInfo&&(this.zoomInfo=t.zoomInfo)}onContextmenu(t){t.preventDefault()}get ctx(){var t;return this._ctx||((t=this.canvas)==null?void 0:t.getContext("2d"))}get basicCtx(){var t;return(t=this.basicCanvas)==null?void 0:t.getContext("2d")}get rotate(){var t,i;return(i=(t=this.basicImgInfo)==null?void 0:t.rotate)!=null?i:0}get valid(){var t,i;return(i=(t=this.basicImgInfo)==null?void 0:t.valid)!=null?i:!0}get baseIcon(){return $[this.style.color]}get defaultCursor(){return this.showDefaultCursor?"default":"none"}get dataList(){return[]}get innerPosAndZoom(){return{innerZoom:this.innerZoom,currentPosStorage:this.currentPosStorage}}get isShowDefaultCursor(){return this.showDefaultCursor}get isMultiMoveMode(){return this.operationMode===p.MultiMove}get hasMarkerConfig(){return this.config.markerConfigurable===!0&&this.config.markerList&&this.config.markerList.length>0}setZoom(t){this.zoom=t,this.innerZoom=t,this.coordUtils.setZoomAndCurrentPos(this.zoom,this.currentPos)}setCurrentPos(t){this.currentPos=t,this.coordUtils.setZoomAndCurrentPos(this.zoom,this.currentPos)}setReferenceData(t){this.referenceData=t}setImgInfo(t){this.imgInfo=t}setCurrentPosStorage(t){this.currentPosStorage=t}setOperationMode(t){this.operationMode=t}recoverOperationMode(){this.operationMode===p.MultiMove&&this.setOperationMode(p.General)}updatePosition(t){const{zoom:i,currentPos:e}=t;this.setZoom(i),this.setCurrentPos(e),this.currentPosStorage=e,this.renderBasicCanvas(),this.render()}setLang(t){this.lang=t;const i=K[t];R.changeLanguage(i)}setShowDefaultCursor(t){this.showDefaultCursor=t,this.container.style.cursor=this.defaultCursor}setCustomCursor(t){this.container.style.cursor=t}get forbidMouseOperation(){return this.forbidOperation||this.valid===!1}get pixelRatio(){var t;return F.getPixelRatio((t=this.canvas)==null?void 0:t.getContext("2d"))}init(){this.eventUnbinding(),this.initPosition(),this.eventBinding(),this.render(),this.renderBasicCanvas()}destroy(){this.destroyCanvas(),this.eventUnbinding()}updateCanvasBasicStyle(t,i,e){const o=this.pixelRatio;t.style.position="absolute",t.width=i.width*o,t.height=i.height*o,t.style.width=`${i.width}px`,t.style.height=`${i.height}px`,t.style.left="0",t.style.top="0",t.style.zIndex=`${e} `}createCanvas(t,i=!0){var e,o;const n=this.pixelRatio,c=document.createElement("canvas");this.updateCanvasBasicStyle(c,t,0),this.basicCanvas=c;const a=document.createElement("canvas");this.updateCanvasBasicStyle(a,t,10),i&&(this.container.hasChildNodes()?(this.container.insertBefore(a,this.container.childNodes[0]),this.container.insertBefore(c,this.container.childNodes[0])):(this.container.appendChild(c),this.container.appendChild(a))),this.canvas=a,this.container.style.cursor=this.defaultCursor,(e=this.ctx)==null||e.scale(n,n),(o=this.basicCtx)==null||o.scale(n,n),this.ctx&&(this.ctx.imageSmoothingEnabled=!1)}destroyCanvas(){this.canvas&&this.container.contains(this.canvas)&&this.container.removeChild(this.canvas),this.basicCanvas&&this.container.contains(this.basicCanvas)&&this.container.removeChild(this.basicCanvas),this.clearInvalidPage(),this.clearImgDrag()}setStyle(t){this.style=t,this.render()}setImgNode(t,i={}){this.imgNode=t,this.setBasicImgInfo(D({width:t.width,height:t.height,valid:!0,rotate:0},i)),this.updateZoomInfo(),this.isImgError===!0&&(this.isImgError=!1,this.emit("changeAnnotationShow")),typeof i.valid=="boolean"&&this.setValid(i.valid),this.initImgPos(),this.render(),this.renderBasicCanvas()}updateZoomInfo(t=this.imgNode,i=this.size){var e;if(!t||!i)return;const{min:o}=L.getMinZoomByImgAndSize({canvasSize:i,imgSize:{width:t.width,height:t.height},rotate:this.rotate,zoomRatio:(e=this._imgAttribute)==null?void 0:e.zoomRatio});this.zoomInfo=T(D({},this.zoomInfo),{min:o})}setErrorImg(){const t=this.isImgError;this.isImgError=!0,this.imgNode=void 0,this.setBasicImgInfo({width:0,height:0,valid:!0,rotate:0}),t===!1&&this.emit("changeAnnotationShow")}setBasicImgInfo(t){this.basicImgInfo=t,this.coordUtils.setBasicImgInfo(t)}setForbidOperation(t){this.forbidOperation=t,this.setShowDefaultCursor(t),this.render()}setForbidCursorLine(t){this.forbidCursorLine=t,this.render()}setIsHidden(t){this.isHidden=t,this.emit("hiddenChange")}setDefaultAttribute(t){this.defaultAttribute=t}getCoordinateInOrigin(t){const i=this.canvas.getBoundingClientRect();return{x:(t.clientX-i.left-this.currentPos.x)/this.zoom,y:(t.clientY-i.top-this.currentPos.y)/this.zoom}}getTextIconSvg(t=""){var i;return A.getTextIconSvg(t,(i=this.config)==null?void 0:i.attributeList,this.config.attributeConfigurable,this.baseIcon)}setIsShowOrder(t){this.config.isShowOrder=t,this.render()}getCoordinate(t){const i=this.canvas.getBoundingClientRect();return{x:t.clientX-i.left,y:t.clientY-i.top}}getCoordinateUnderZoom(t){const i=this.canvas.getBoundingClientRect();return{x:t.clientX-i.left-this.currentPos.x,y:t.clientY-i.top-this.currentPos.y}}getCoordinateUnderZoomByRotate(t){const{x:i,y:e}=this.getCoordinateUnderZoom(t);return this.basicImgInfo.rotate===90?{x:e,y:this.basicImgInfo.height*this.zoom-i}:this.basicImgInfo.rotate===180?{x:this.basicImgInfo.width*this.zoom-i,y:this.basicImgInfo.height*this.zoom-e}:this.basicImgInfo.rotate===270?{x:this.basicImgInfo.width*this.zoom-e,y:i}:{x:i,y:e}}getCoordinateUnderZoomByRotateFromImgPoint(t){const{x:i,y:e}=t;return this.basicImgInfo.rotate===90?{x:(this.basicImgInfo.height-e)*this.zoom+this.currentPos.x,y:i*this.zoom+this.currentPos.y}:this.basicImgInfo.rotate===180?{x:(this.basicImgInfo.width-i)*this.zoom+this.currentPos.x,y:(this.basicImgInfo.height-e)*this.zoom+this.currentPos.y}:this.basicImgInfo.rotate===270?{x:e*this.zoom+this.currentPos.x,y:(this.basicImgInfo.width-i)*this.zoom+this.currentPos.y}:{x:i*this.zoom+this.currentPos.x,y:e*this.zoom+this.currentPos.y}}getGetCenterCoordinate(){return{x:this.size.width/2,y:this.size.height/2}}initPosition(){if(this.basicResult&&this.imgInfo){const{basicResult:t,size:i,imgNode:e,_imgAttribute:o,imgInfo:n,dependToolName:c}=this;if(t&&e&&c){let a=t;switch(c){case y.Polygon:case y.Line:{if(t.pointList){const l=B.calcViewportBoundaries(t.pointList);a={x:l.left,y:l.top,width:l.right-l.left,height:l.bottom-l.top}}break}}const r=L.getBasicRecPos(e,a,i,void 0,o==null?void 0:o.zoomRatio,o==null?void 0:o.isOriginalSize);r&&(this.setCurrentPos(r.currentPos),this.currentPosStorage=this.currentPos,this.setImgInfo(T(D({},n),{width:n.width/this.innerZoom*r.innerZoom,height:n.height/this.innerZoom*r.innerZoom})),this.setZoom(r.innerZoom),this.render(),this.renderBasicCanvas())}}else this.initImgPos()}undo(){this.history.undo()}redo(){this.history.redo()}clearCanvas(){var t;(t=this.ctx)==null||t.clearRect(0,0,this.size.width,this.size.height)}clearBasicCanvas(){var t;(t=this.basicCtx)==null||t.clearRect(0,0,this.size.width,this.size.height)}eventBinding(){this.dblClickListener.addEvent(()=>{},this.onLeftDblClick,this.onRightDblClick),this.container.addEventListener("mousedown",this.onMouseDown),this.container.addEventListener("mousemove",this.onMouseMove),this.container.addEventListener("mouseup",this.onMouseUp),this.container.addEventListener("mouseleave",this.onMouseLeave),this.container.addEventListener("click",this.onClick),this.container.addEventListener("wheel",this.onWheel),document.addEventListener("keydown",this.onKeyDown),document.addEventListener("keyup",this.onKeyUp),window.parent.document.addEventListener("contextmenu",this.onContextmenu,!1)}eventUnbinding(){this.container.removeEventListener("mousedown",this.onMouseDown),this.container.removeEventListener("mousemove",this.onMouseMove),this.container.removeEventListener("mouseup",this.onMouseUp),this.container.removeEventListener("mouseleave",this.onMouseLeave),this.container.removeEventListener("wheel",this.onWheel),this.container.removeEventListener("click",this.onClick),document.removeEventListener("keydown",this.onKeyDown),document.removeEventListener("keyup",this.onKeyUp),window.parent.document.removeEventListener("contextmenu",this.onContextmenu,!1),this.dblClickListener.removeEvent()}clearImgDrag(){this.isDrag=!1,this.isDragStart=!1,this.isSpaceClick=!1,this.startTime=0,this.container.style.cursor=this.defaultCursor,this.forbidCursorLine=!1}clearCursorLine(){this.coord={x:-1,y:-1}}onMouseDown(t){if(!this.canvas||this.isImgError)return!0;const i=this.getCoordinate(t);(this.isSpaceKey&&t.button===0||t.button===2)&&(t.stopPropagation(),this._firstClickCoordinate=i,this.currentPosStorage=this.currentPos,this.isSpaceClick=!0,this.isDragStart=!0,this.startTime=new Date().getTime())}onMouseMove(t){if(!this.canvas||this.isImgError)return!0;const i=this.getCoordinate(t);this.isShowCursor&&(this.coord=i);try{if(!i||!E(i==null?void 0:i.x)||!E(i==null?void 0:i.y))throw new Error("coord error");if(this.coord=i,(this.isSpaceClick||this.isDragStart)&&this._firstClickCoordinate){const e=this.getCurrentPos(i);this.setCurrentPos(e),this.isDrag=!0,this.container.style.cursor="grabbing",this.forbidCursorLine=!0,this.renderBasicCanvas(),this.emit("dependRender"),this.emit("dragMove",{currentPos:e,zoom:this.zoom,imgInfo:this.imgInfo})}this.render()}catch(e){console.error(e)}}onMouseUp(t){if(!this.canvas||this.isImgError)return!0;if(this.container.style.cursor=this.defaultCursor,this.forbidCursorLine=!1,this.isDrag=!1,this.isDragStart=!1,this.isSpaceClick=!1,this.startTime!==0&&this._firstClickCoordinate){const i=new Date().getTime(),e=this.getCoordinate(t);if(i-this.startTime>1e3||this.isSpaceKey===!0||H.calcTwoPointDistance(e,this._firstClickCoordinate)>10)return t.stopPropagation(),this.startTime=0,this.render(),!0}this.startTime=0,this.render()}onMouseLeave(){this.clearImgDrag()}onClick(t){}onLeftDblClick(t){}onRightDblClick(t){this.clearImgDrag()}onKeyDown(t){switch(t.keyCode===w.Alt&&t.preventDefault(),t.keyCode){case w.Space:this.isSpaceKey=!0,t.preventDefault();break;case w.Z:if(t.ctrlKey)return t.shiftKey?this.redo():this.undo(),!1;break}return!0}onKeyUp(t){switch(t.keyCode){case w.Space:this.isSpaceKey=!1;break}}exportCustomData(){return{}}onWheel(t,i=!0){if(!this.imgNode||!this.coord)return;t.preventDefault(),t.stopPropagation();const e=this.getCoordinate(t),o=t.deltaY||t.wheelDelta;let n=0;o>0&&this.zoom>this.zoomInfo.min&&(n=-1),o<0&&this.zoom<this.zoomInfo.max&&(n=1),this.wheelChangePos(e,n),this.emit("dependRender"),i&&this.render(),this.renderBasicCanvas()}renderCursorLine(t=(i=>(i=this.style.lineColor[0])!=null?i:"")()){if(!this.ctx||this.forbidCursorLine||this.forbidOperation)return;const{x:i,y:e}=this.coord;v.drawLine(this.canvas,{x:0,y:e},{x:1e4,y:e},{color:t}),v.drawLine(this.canvas,{x:i,y:0},{x:i,y:1e4},{color:t}),v.drawCircleWithFill(this.canvas,{x:i,y:e},1,{color:"white"})}setSize(t){var i;this.size=t,this.updateZoomInfo(),this.container.contains(this.canvas)&&(this.destroyCanvas(),this.createCanvas(t),this.eventUnbinding(),this.init(),((i=this.basicImgInfo)==null?void 0:i.valid)===!1&&this.renderInvalidPage())}setImgAttribute(t){const i=this._imgAttribute;if(this._imgAttribute=t,(i==null?void 0:i.zoomRatio)!==t.zoomRatio||i.isOriginalSize!==t.isOriginalSize){this.initImgPos();return}this.renderBasicCanvas(),this.render()}clearResult(t){}setValid(t){this.basicImgInfo.valid=t,t===!1?(this.renderInvalidPage(),this.clearResult(!1)):this.clearInvalidPage()}setRotate(t){this.basicImgInfo.rotate=t}setBasicResult(t){this.basicResult=t,this.coordUtils.setBasicResult(t),this.initPosition(),this.emit("dependRender")}setDependName(t,i){this.dependToolName=t,this.coordUtils.setDependInfo(t,i)}setAttributeLockList(t){this.attributeLockList=t,this.render()}setConfig(t){this.config=x.jsonParser(t)}setDataInjectionAtCreation(t){this.dataInjectionAtCreation=t}setRenderEnhance(t){this.renderEnhance=t}setCustomRenderStyle(t){this.customRenderStyle=t}updateRotate(){if(this.dependToolName)return this.emit("messageInfo",U.getMessagesByLocale(Z.NoRotateInDependence,this.lang)),!1;if(this.dataList.length>0)return this.emit("messageInfo",U.getMessagesByLocale(Z.NoRotateNotice,this.lang)),!1;const t=B.getRotate(this.basicImgInfo.rotate);this.basicImgInfo.rotate=t,this.initImgPos(),this.emit("updateResult")}getColor(t="",i=this.config){return k.getColorByConfig({attribute:t,config:i,style:this.style})}getLineColor(t=""){var i,e,o,n,c,a,r,l;if(((i=this.config)==null?void 0:i.attributeConfigurable)===!0){const P=A.getAttributeIndex(t,(o=(e=this.config)==null?void 0:e.attributeList)!=null?o:[])+1;return((a=(c=(n=this.config)==null?void 0:n.attributeList)==null?void 0:c.find(h=>h.value===t))==null?void 0:a.color)?(l=(r=k.getColorByConfig({attribute:t,config:this.config}))==null?void 0:r.valid)==null?void 0:l.stroke:this.style.attributeLineColor?this.style.attributeLineColor[P]:""}const{color:b,lineColor:I}=this.style;return b&&I?I[b]:""}clearInvalidPage(){this._invalidDOM&&this.container&&this.container.contains(this._invalidDOM)&&(this.container.removeChild(this._invalidDOM),this._invalidDOM=void 0)}renderInvalidPage(){!this.container||this._invalidDOM||(this._invalidDOM=Q.renderInvalidPage(this.container,this.size,this.lang))}renderBasicCanvas(){if(!this.basicCanvas)return;this.clearBasicCanvas(),this.drawImg();const t=3;if(!this.forbidBasicResultRender&&this.basicResult&&this.dependToolName)switch(this.dependToolName){case y.Rect:{v.drawRect(this.basicCanvas,_.changeRectByZoom(this.basicResult,this.zoom,this.currentPos),{color:"rgba(204,204,204,1.00)",thickness:t});break}case y.Polygon:{v.drawPolygonWithFillAndLine(this.basicCanvas,_.changePointListByZoom(this.basicResult.pointList,this.zoom,this.currentPos),{fillColor:"transparent",strokeColor:"rgba(204,204,204,1.00)",isClose:!0,thickness:t});break}case y.Line:{v.drawLineWithPointList(this.basicCanvas,_.changePointListByZoom(this.basicResult.pointList,this.zoom,this.currentPos),{color:"rgba(204,204,204,1.00)",thickness:t});break}}}render(){!this.canvas||!this.ctx||!this.imgNode||this.clearCanvas()}changeStyle(t=this.defaultAttribute){this.emit("changeStyle",{attribute:t})}}export{ht as BasicToolOperation};