import { EDITOR_CONFIG, MapAreaType, type MapPen, MapPointType } from '@api/map'; import type { RobotGroup, RobotInfo } from '@api/robot'; import type { SceneData } from '@api/scene'; import sTheme from '@core/theme.service'; import { CanvasLayer, EditType, LockState, Meta2d, s8 } from '@meta2d/core'; import { useObservable } from '@vueuse/rxjs'; import { clone, cloneDeep, get, isNil, pick, remove, some } from 'lodash-es'; import { BehaviorSubject, debounceTime, filter, map, Subject, switchMap } from 'rxjs'; import { watch } from 'vue'; export type Point = Record<'x' | 'y', number>; export class EditorService extends Meta2d { public load(map?: string, readonly = false): void { const data = map ? JSON.parse(map) : undefined; this.open(data); this.setState(readonly); } public save(): string { const data = this.data(); const map = JSON.stringify(data); return map; } public export(): string { const png = this.toPng(10); return png; } readonly #mouse$$ = new Subject<{ type: 'click' | 'mousedown' | 'mouseup'; value: Point }>(); public readonly mouseClick = useObservable( this.#mouse$$.pipe( filter(({ type }) => type === 'click'), debounceTime(100), map(({ value }) => value), ), ); public readonly mouseBrush = useObservable<[Point, Point]>( this.#mouse$$.pipe( filter(({ type }) => type === 'mousedown'), switchMap(({ value: s }) => this.#mouse$$.pipe( filter(({ type }) => type === 'mouseup'), map(({ value: e }) => <[Point, Point]>[s, e]), ), ), ), ); public override data(): SceneData { return super.data(); } public override find(target: string): MapPen[] { return super.find(target); } public setState(readonly?: boolean): void { this.lock(readonly ? LockState.Disable : LockState.None); } //#region 机器人 readonly #robotMap = new Map(); public get robots(): RobotInfo[] { return Array.from(this.#robotMap.values()); } public getRobotById(id: RobotInfo['id']): RobotInfo | undefined { return this.#robotMap.get(id); } public addRobots(gid: RobotInfo['gid'], robots: RobotInfo[]): void { const groups = clone(this.#robotGroups$$.value); const group = groups.find((v) => v.id === gid); if (isNil(group)) throw Error('未找到目标机器人组'); group.robots ??= []; robots.forEach((v) => { if (this.#robotMap.has(v.id)) return; this.#robotMap.set(v.id, { ...v, gid }); group.robots?.push(v.id); }); this.#robotGroups$$.next(groups); (this.store.data).robots = [...this.#robotMap.values()]; (this.store.data).robotGroups = this.#robotGroups$$.value; } readonly #robotGroups$$ = new BehaviorSubject([]); public readonly robotGroups = useObservable(this.#robotGroups$$.pipe(debounceTime(300))); public createRobotGroup(): void { const id = s8(); const label = `RG-${id}`; const groups = clone(this.#robotGroups$$.value); groups.push({ id, label }); this.#robotGroups$$.next(groups); (this.store.data).robotGroups = this.#robotGroups$$.value; } public deleteRobotGroup(id: RobotGroup['id']): void { const groups = clone(this.#robotGroups$$.value); const group = groups.find((v) => v.id === id); group?.robots?.forEach((v) => this.#robotMap.delete(v)); remove(groups, group); this.#robotGroups$$.next(groups); (this.store.data).robots = [...this.#robotMap.values()]; (this.store.data).robotGroups = this.#robotGroups$$.value; } public updateRobotGroupLabel(id: RobotGroup['id'], label: RobotGroup['label']): void { const groups = this.#robotGroups$$.value; const group = groups.find((v) => v.id === id); if (isNil(group)) throw Error('未找到目标机器人组'); if (some(groups, ['label', label])) throw Error('机器人组名称已经存在'); group.label = label; this.#robotGroups$$.next([...groups]); (this.store.data).robotGroups = this.#robotGroups$$.value; } //#endregion //#region 点位 public async addPoint(p: Point, type = MapPointType.普通点): Promise { const id = s8(); const pen: MapPen = { ...p, ...this.#mapPoint(type), ...this.#mapPointImage(type), id, name: 'point', tags: ['point', `point-${type}`], label: `P-${id}`, point: { type }, }; const { x, y, width, height } = this.getPenRect(pen); pen.x = x - width / 2; pen.y = y - height / 2; await this.addPen(pen, false, true, true); this.pushHistory({ type: EditType.Add, pens: [cloneDeep(pen)] }); } #mapPoint(type: MapPointType): Required> { const width = type < 10 ? 24 : 48; const height = type < 10 ? 24 : 60; const lineWidth = type < 10 ? 2 : 3; const iconSize = type < 10 ? 4 : 10; return { width, height, lineWidth, iconSize }; } #mapPointImage(type: MapPointType): Required> { const theme = this.data().theme; const image = type < 10 ? '' : `/point/${type}-${theme}.png`; return { image, canvasLayer: CanvasLayer.CanvasMain }; } //#endregion //#region 线路 //#endregion //#region 区域 public async addArea(p1: Point, p2: Point, type = MapAreaType.库区) { const scale = this.data().scale ?? 1; const w = Math.abs(p1.x - p2.x); const h = Math.abs(p1.y - p2.y); if (w * scale < 50 || h * scale < 60) return; const pen: MapPen = { name: 'area', tags: ['area', `area-${type}`], x: Math.min(p1.x, p2.x), y: Math.min(p1.y, p2.y), width: w, height: h, area: { type }, locked: LockState.DisableMoveScale, }; const area = await this.addPen(pen, false, true, true); this.bottom(area); this.pushHistory({ type: EditType.Add, pens: [cloneDeep(pen)] }); } //#endregion constructor(container: HTMLDivElement) { super(container, EDITOR_CONFIG); (container.children.item(5)).ondrop = null; this.on('*', (e, v) => this.#listen(e, v)); this.#register(); watch( () => sTheme.theme, (v) => this.#load(v), { immediate: true }, ); } #load(theme?: string): void { if (theme) { this.setTheme(theme); } const { robots, robotGroups } = this.data(); this.#robotMap.clear(); robots?.forEach((r) => this.#robotMap.set(r.id, r)); this.#robotGroups$$.next(robotGroups ?? []); this.find('point').forEach((pen) => { if (!pen.point?.type) return; if (pen.point.type < 10) return; this.canvas.updateValue(pen, this.#mapPointImage(pen.point.type)); }); this.render(); } // eslint-disable-next-line @typescript-eslint/no-explicit-any #listen(e: unknown, v: any) { switch (e) { case 'opened': this.#load(); break; case 'click': case 'mousedown': case 'mouseup': this.#mouse$$.next({ type: e, value: pick(v, 'x', 'y') }); break; default: // console.log(e, v); break; } } #register() { this.registerCanvasDraw({ point: drawPoint, line: drawLine, area: drawArea }); this.registerAnchors({ point: anchorPoint }); } } //#region 绘制函数 function drawPoint(ctx: CanvasRenderingContext2D, pen: MapPen): void { const theme = sTheme.editor; const { active, iconSize: r = 0, fontSize = 14, lineHeight = 1.5, fontFamily } = pen.calculative ?? {}; const { x = 0, y = 0, width: w = 0, height: h = 0 } = pen.calculative?.worldRect ?? {}; const { type } = pen.point ?? {}; const { label = '' } = pen ?? {}; ctx.save(); switch (type) { case MapPointType.普通点: case MapPointType.等待点: case MapPointType.避让点: case MapPointType.临时避让点: ctx.beginPath(); ctx.moveTo(x + w / 2 - r, y + r); ctx.arcTo(x + w / 2, y, x + w - r, y + h / 2 - r, r); ctx.arcTo(x + w, y + h / 2, x + w / 2 + r, y + h - r, r); ctx.arcTo(x + w / 2, y + h, x + r, y + h / 2 + r, r); ctx.arcTo(x, y + h / 2, x + r, y + h / 2 - r, r); ctx.closePath(); ctx.fillStyle = get(theme, `point-s.fill-${type}`) ?? ''; ctx.fill(); ctx.strokeStyle = get(theme, active ? 'point-s.strokeActive' : 'point-s.stroke') ?? ''; if (type === MapPointType.临时避让点) { ctx.lineCap = 'round'; ctx.beginPath(); ctx.moveTo(x + 0.66 * r, y + h / 2 - 0.66 * r); ctx.lineTo(x + r, y + h / 2 - r); ctx.moveTo(x + w / 2 - 0.66 * r, y + 0.66 * r); ctx.lineTo(x + w / 2 - r, y + r); ctx.moveTo(x + w / 2 + 0.66 * r, y + 0.66 * r); ctx.lineTo(x + w / 2 + r, y + r); ctx.moveTo(x + w - 0.66 * r, y + h / 2 - 0.66 * r); ctx.lineTo(x + w - r, y + h / 2 - r); ctx.moveTo(x + w - 0.66 * r, y + h / 2 + 0.66 * r); ctx.lineTo(x + w - r, y + h / 2 + r); ctx.moveTo(x + w / 2 + 0.66 * r, y + h - 0.66 * r); ctx.lineTo(x + w / 2 + r, y + h - r); ctx.moveTo(x + w / 2 - 0.66 * r, y + h - 0.66 * r); ctx.lineTo(x + w / 2 - r, y + h - r); ctx.moveTo(x + 0.66 * r, y + h / 2 + 0.66 * r); ctx.lineTo(x + r, y + h / 2 + r); } ctx.stroke(); break; case MapPointType.电梯点: case MapPointType.自动门点: case MapPointType.充电点: case MapPointType.停靠点: case MapPointType.动作点: ctx.roundRect(x, y, w, h, r); ctx.strokeStyle = get(theme, active ? 'point-l.strokeActive' : 'point-l.stroke') ?? ''; ctx.stroke(); break; default: break; } ctx.fillStyle = get(theme, 'color') ?? ''; ctx.font = `${fontSize}px/${lineHeight} ${fontFamily}`; ctx.textAlign = 'center'; ctx.textBaseline = 'top'; ctx.fillText(label, x + w / 2, y - fontSize * lineHeight); ctx.restore(); } function anchorPoint(pen: MapPen): void { pen.anchors = [{ x: 0.5, y: 0.5 }]; } function drawLine(ctx: CanvasRenderingContext2D, pen: MapPen): void { const [p1, p2] = pen.calculative?.worldAnchors ?? []; const { direction } = pen.route ?? {}; ctx.save(); ctx.lineWidth = 2; ctx.restore(); } function drawArea(ctx: CanvasRenderingContext2D, pen: MapPen): void { const { x = 0, y = 0, width = 0, height = 0 } = pen.calculative?.worldRect ?? {}; const { type } = pen.area ?? {}; ctx.save(); ctx.lineWidth = 1; ctx.strokeRect(x, y, width, height); ctx.fillStyle = '#fff'; ctx.fillText(String(type), x + width / 2, y); ctx.restore(); } //#endregion